edge-currency-accountbased 0.22.21 → 0.23.0
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 +7 -0
- package/android/src/main/assets/edge-currency-accountbased/{645.chunk.js → 216.chunk.js} +6 -6
- package/android/src/main/assets/edge-currency-accountbased/244.chunk.js +1 -1
- package/android/src/main/assets/edge-currency-accountbased/387.chunk.js +9 -0
- package/android/src/main/assets/edge-currency-accountbased/491.chunk.js +1 -1
- package/android/src/main/assets/edge-currency-accountbased/549.chunk.js +1 -1
- package/android/src/main/assets/edge-currency-accountbased/94.chunk.js +8 -9
- package/android/src/main/assets/edge-currency-accountbased/bnb.chunk.js +3 -3
- package/android/src/main/assets/edge-currency-accountbased/edge-currency-accountbased.js +2 -2
- package/android/src/main/assets/edge-currency-accountbased/eos.chunk.js +11 -11
- package/android/src/main/assets/edge-currency-accountbased/ethereum.chunk.js +9 -9
- package/android/src/main/assets/edge-currency-accountbased/fio.chunk.js +2 -2
- package/android/src/main/assets/edge-currency-accountbased/hedera.chunk.js +2 -2
- package/android/src/main/assets/edge-currency-accountbased/polkadot.chunk.js +2 -2
- package/android/src/main/assets/edge-currency-accountbased/ripple.chunk.js +5 -4
- package/android/src/main/assets/edge-currency-accountbased/solana.chunk.js +3 -3
- package/android/src/main/assets/edge-currency-accountbased/stellar.chunk.js +6 -6
- package/android/src/main/assets/edge-currency-accountbased/tezos.chunk.js +3 -3
- package/android/src/main/assets/edge-currency-accountbased/tron.chunk.js +1 -1
- package/android/src/main/assets/edge-currency-accountbased/zcash.chunk.js +2 -2
- package/lib/binance/bnbEngine.js +28 -16
- package/lib/binance/bnbTypes.js +11 -0
- package/lib/common/engine.js +47 -3
- package/lib/common/types.js +20 -0
- package/lib/declare-modules.d.js +0 -22
- package/lib/eos/eosEngine.js +32 -21
- package/lib/eos/eosTypes.js +16 -0
- package/lib/eos/info/eosInfo.js +3 -1
- package/lib/ethereum/ethEngine.js +90 -140
- package/lib/ethereum/ethTypes.js +64 -0
- package/lib/fio/fioConst.js +26 -55
- package/lib/fio/fioEngine.js +830 -609
- package/lib/fio/fioError.js +15 -22
- package/lib/fio/fioInfo.js +13 -23
- package/lib/fio/fioPlugin.js +85 -94
- package/lib/fio/fioTypes.js +180 -1
- package/lib/hedera/hederaEngine.js +24 -12
- package/lib/hedera/hederaTypes.js +37 -0
- package/lib/polkadot/polkadotEngine.js +30 -10
- package/lib/polkadot/polkadotTypes.js +37 -0
- package/lib/solana/solanaEngine.js +25 -27
- package/lib/solana/solanaTypes.js +37 -0
- package/lib/stellar/stellarEngine.js +21 -19
- package/lib/stellar/stellarTypes.js +10 -0
- package/lib/tezos/tezosEngine.js +23 -18
- package/lib/tezos/tezosTypes.js +16 -0
- package/lib/tron/tronEngine.js +14 -7
- package/lib/tron/tronPlugin.js +1 -1
- package/lib/tron/tronTypes.js +15 -11
- package/lib/xrp/xrpEngine.js +86 -59
- package/lib/xrp/xrpTypes.js +16 -0
- package/lib/zcash/zecEngine.js +33 -27
- package/lib/zcash/zecInfo.js +4 -1
- package/lib/zcash/zecPlugin.js +20 -6
- package/lib/zcash/zecTypes.js +57 -1
- package/package.json +3 -3
- package/android/src/main/assets/edge-currency-accountbased/206.chunk.js +0 -8
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[679],{79014:function(ht,R,v){"use strict";v.d(R,{Q:function(){return Y},k:function(){return Z}});var C=v(77591),D=v.n(C),H=v(24350),U=v(84564),m=v.n(U),n=v(76714),z=Object.defineProperty,X=Object.getOwnPropertySymbols,B=Object.prototype.hasOwnProperty,Q=Object.prototype.propertyIsEnumerable,M=(p,A,S)=>A in p?z(p,A,{enumerable:!0,configurable:!0,writable:!0,value:S}):p[A]=S,V=(p,A)=>{for(var S in A||(A={}))B.call(A,S)&&M(p,S,A[S]);if(X)for(var S of X(A))Q.call(A,S)&&M(p,S,A[S]);return p};function Z(p,A,S,_,F){const b=V({},m()(A,{},!0))
|
|
1
|
+
(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[679],{79014:function(ht,R,v){"use strict";v.d(R,{Q:function(){return Y},k:function(){return Z}});var C=v(77591),D=v.n(C),H=v(24350),U=v(84564),m=v.n(U),n=v(76714),z=Object.defineProperty,X=Object.getOwnPropertySymbols,B=Object.prototype.hasOwnProperty,Q=Object.prototype.propertyIsEnumerable,M=(p,A,S)=>A in p?z(p,A,{enumerable:!0,configurable:!0,writable:!0,value:S}):p[A]=S,V=(p,A)=>{for(var S in A||(A={}))B.call(A,S)&&M(p,S,A[S]);if(X)for(var S of X(A))Q.call(A,S)&&M(p,S,A[S]);return p};function Z(p,A,S,_,F){const b=V({},m()(A,{},!0)),$=A.startsWith(`${p.pluginId}://`);if(b.protocol!=null&&(b.protocol=b.protocol.replace(":","")),b.protocol!=null&&b.protocol!==""&&!S[b.protocol])throw new Error(`Uri protocol '${b.protocol}' is not supported for ${p.pluginId}.`);if(b.host===""&&b.pathname==="")throw new Error("Path and host not found in uri.");const P={publicAddress:b.host!==""?b.host:b.pathname.split("/")[0]},j=b.query.label,J=b.query.message,q=b.query.category;(j!=null||J!=null||q!=null||$)&&(P.metadata={},P.metadata.name=j,P.metadata.notes=J,P.metadata.category=q,P.metadata.gateway=$!=null?$:!1);const O=b.query.amount;if(O!=null&&typeof O=="string"){_==null&&(_=p.currencyCode);const G=(0,n.cp)(p,_!=null?_:"",F);if(G==null)throw new Error("InternalErrorInvalidCurrencyCode");let K=(0,C.mul)(O,G.multiplier);K=(0,C.toFixed)(K,0,0),P.nativeAmount=K,P.currencyCode=_}return{edgeParsedUri:P,parsedUri:b}}function Y(p,A,S){if(p.publicAddress==null)throw new Error("InvalidPublicAddressError");if(S==null&&p.label==null&&p.message==null)return p.publicAddress;{let _="";S!=null&&(_+="amount="+S+"&"),(p.label!=null||p.message!=null)&&(typeof p.label=="string"&&(_+="label="+p.label+"&"),typeof p.message=="string"&&(_+="message="+p.message+"&")),_=_.substr(0,_.length-1);const F={scheme:A,path:p.publicAddress,query:_};return(0,H.qC)(F)}}},58030:function(ht,R,v){"use strict";v.r(R),v.d(R,{EosTools:function(){return lt},checkAddress:function(){return x},getClient:function(){return N},makeCurrencyEngine:function(){return bt},makeCurrencyTools:function(){return It}});var C=v(45234),D=v(77591),H=v(20918),U=v(79014),m=v(76714),n=v(82448);const z=(0,n.su)({amount:n.XC,currencyCode:n.XC,expireTime:n.mH,paymentAddress:n.XC}),X=(0,n.su)({result:(0,n.su)(n.jK)}),B=(0,n.su)({cpu:n.mH,net:n.mH,ram:n.mH}),Q=(0,n.su)({trx_id:n.XC,"@timestamp":n.XC,block_num:n.mH,act:(0,n.su)({data:(0,n.su)({from:n.XC,to:n.XC,amount:n.mH,symbol:n.XC,memo:n.XC})})}),M=(0,n.su)({actions:(0,n._2)(Q)}),V=(0,n.su)({account_names:(0,n._2)(n.XC)}),Z=(0,n.su)({trace:(0,n.su)({block:(0,n.su)({num:n.mH,timestamp:n.XC}),id:n.XC,matchingActions:(0,n._2)((0,n.su)({json:(0,n.su)({from:n.XC,memo:n.XC,quantity:n.XC,to:n.XC})}))})}),Y=(0,n.su)({data:(0,n.su)({searchTransactionsBackward:(0,n.su)({results:(0,n._2)(Z)})})}),p=(0,n.su)({errors:(0,n._2)((0,n.su)({message:n.XC,extensions:(0,n.su)({code:n.XC,terminal:n.jK})}))}),A=`
|
|
2
2
|
query ($query: String!, $limit: Int64, $low: Int64, $high: Int64) {
|
|
3
3
|
searchTransactionsBackward(query: $query, lowBlockNum: $low, highBlockNum: $high, limit: $limit) {
|
|
4
4
|
results {
|
|
@@ -15,19 +15,19 @@ query ($query: String!, $limit: Int64, $low: Int64, $high: Int64) {
|
|
|
15
15
|
}
|
|
16
16
|
}
|
|
17
17
|
}
|
|
18
|
-
`,S=(0,n.su)({act:(0,n.su)({data:(0,n.su)({from:n.XC,to:n.XC,amount:n.mH,symbol:n.XC,memo:(0,n.Zz)(n.XC)})}),trx_id:n.XC,"@timestamp":n.XC,block_num:n.mH}),_=(0,n.su)({account:n.XC,name:(0,n.Wf)("transfer"),authorization:(0,n.vq)((0,n.su)({actor:n.XC,permission:(0,n.Wf)("active")})),data:(0,n.su)({from:n.XC,to:n.XC,quantity:n.XC,memo:(0,n.Zz)(n.XC)})}),F=(0,n.su)({actions:(0,n._2)(_),signatures:(0,n._2)(n.XC)}),b={structs:[{base:"",name:"transfer",fields:[{name:"from",type:"name"},{name:"to",type:"name"},{name:"quantity",type:"asset"},{name:"memo",type:"string"}]}],actions:[{name:"transfer",type:"transfer",ricardian_contract:""}]},x={structs:[{base:"",name:"powerup",fields:[{name:"payer",type:"name"},{name:"receiver",type:"name"},{name:"days",type:"int32"},{name:"net_frac",type:"int64"},{name:"cpu_frac",type:"int64"},{name:"max_payment",type:"asset"}]}],actions:[{name:"powerup",type:"powerup",ricardian_contract:""}]};var tt=v(84248),P=v(94935),j=v(84564),J=v.n(j),q=v(50244),$=v(83718),G=Object.defineProperty,K=Object.defineProperties,dt=Object.getOwnPropertyDescriptors,st=Object.getOwnPropertySymbols,ft=Object.getPrototypeOf,mt=Object.prototype.hasOwnProperty,pt=Object.prototype.propertyIsEnumerable,yt=Reflect.get,it=(g,t,e)=>t in g?G(g,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):g[t]=e,et=(g,t)=>{for(var e in t||(t={}))mt.call(t,e)&&it(g,e,t[e]);if(st)for(var e of st(t))pt.call(t,e)&&it(g,e,t[e]);return g},nt=(g,t)=>K(g,dt(t)),rt=(g,t,e)=>yt(ft(g),e,t),d=(g,t,e)=>new Promise((r,o)=>{var i=s=>{try{l(e.next(s))}catch(c){o(c)}},a=s=>{try{l(e.throw(s))}catch(c){o(c)}},l=s=>s.done?r(s.value):Promise.resolve(s.value).then(i,a);l((e=e.apply(g,t)).next())});const gt=1e4,wt=15e3,vt=1e4,kt=!0,Ct=!0,ct={ramdeathtest:!0,krpj4avazggi:!0,fobleos13125:!0};class L extends q.P{constructor(t,e,r,o){const i=(0,m.zR)(t);super(t,e,r,o);const{networkInfo:a}=t;this.fetchCors=i,this.networkInfo=a,this.activatedAccountsCache={};const{currencyCode:l,denominations:s}=this.currencyInfo;this.referenceBlock={ref_block_num:0,ref_block_prefix:0},this.accountResources={cpu:0,net:0},this.getResourcesMutex=!1,this.allTokens.push(nt(et({},s[0]),{currencyCode:l,currencyName:l,contractAddress:"eosio.token",denominations:s})),this.otherMethods={getAccountActivationQuote:c=>d(this,null,function*(){const{requestedAccountName:u,currencyCode:h,ownerPublicKey:f,activePublicKey:y,requestedAccountCurrencyCode:w}=c;if(h==null||u==null)throw new Error("ErrorInvalidParams");if(f==null&&y==null)throw new Error("ErrorInvalidParams");if(!N(u)){const k=new Error("ErrorInvalidAccountName");throw k.name="ErrorInvalidAccountName",k}const I={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({requestedAccountName:u,currencyCode:h,ownerPublicKey:f,activePublicKey:y,requestedAccountCurrencyCode:w})};try{const k=yield(0,m.QJ)(this.networkInfo.eosActivationServers.map(E=>()=>d(this,null,function*(){const ot=`${E}/api/v1/activateAccount`;return yield(yield i(ot,I)).json()})),15e3);return z(k)}catch(k){throw this.error("getAccountActivationQuoteError: ",k),new Error("getAccountActivationQuoteError")}})}}setOtherData(t){this.otherData=(0,$.s)(t)}loadEngine(t,e,r){return d(this,null,function*(){if(yield rt(L.prototype,this,"loadEngine").call(this,t,e,r),typeof this.walletInfo.keys.ownerPublicKey!="string")if(e.keys.ownerPublicKey!=null)this.walletInfo.keys.ownerPublicKey=e.keys.ownerPublicKey;else{const o=yield t.derivePublicKey(this.walletInfo);this.walletInfo.keys.ownerPublicKey=o.ownerPublicKey}})}checkBlockchainInnerLoop(){return d(this,null,function*(){try{const t=yield this.multicastServers("getInfo"),e=t.head_block_num.toNumber();this.walletLocalData.blockHeight!==e&&(this.checkDroppedTransactionsThrottled(),this.walletLocalData.blockHeight=e,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight));const r=t.getTransactionHeader();this.referenceBlock={ref_block_num:r.ref_block_num.toNumber(),ref_block_prefix:r.ref_block_prefix.toNumber()}}catch(t){this.error("Error fetching height: ",t)}})}processIncomingTransaction(t){const e=(0,n.Vk)(S)(t);if(e==null)return this.error("Invalid supernode tx"),0;const{act:r,trx_id:o,block_num:i}=e,a=e["@timestamp"],{from:l,to:s,memo:c,symbol:u}=r.data,h=r.data.amount.toString(),f=u,y=[],w=(0,m.cp)(this.currencyInfo,f,this.allTokens);if(w==null)return this.error(`processIncomingTransaction Received unsupported currencyCode: ${f}`),0;let I=(0,D.mul)(h,w.multiplier),k="";s===this.otherData.accountName?(k=l,y.push(s),l===this.otherData.accountName&&(I="0")):(k=s,I=`-${I}`);const E={txid:o,date:Date.parse(a)/1e3,currencyCode:f,blockHeight:i>0?i:0,nativeAmount:I,networkFee:"0",parentNetworkFee:"0",ourReceiveAddresses:y,signedTx:"",otherParams:{},metadata:{name:k,notes:c},walletId:this.walletId};return this.addTransaction(f,E),E.blockHeight}processOutgoingTransaction(t){const e=[],r=t["@timestamp"].includes("Z")?t["@timestamp"]:t["@timestamp"]+"Z",o=Date.parse(r)/1e3,i=t.block_num>0?t.block_num:0;if(t.block_num==null)return this.error(`Invalid ${this.currencyInfo.currencyCode} transaction data. No tx block_num`),0;const a=t.trx_id;if(t.act==null)return this.error(`Invalid ${this.currencyInfo.currencyCode} transaction data. No action.act`),0;if(t.act.name==="transfer"){if(t.act.data==null)return this.error(`Invalid ${this.currencyInfo.currencyCode} transaction data. No action.act.data`),0;const{from:s,to:c,memo:u,amount:h,symbol:f}=t.act.data,y=h.toString(),w=f,I=(0,m.cp)(this.currencyInfo,w,this.allTokens);if(I==null)return this.error(`processOutgoingTransaction Received unsupported currencyCode: ${w}`),0;let k=(0,D.mul)(y,I.multiplier);c===this.otherData.accountName?(e.push(c),s===this.otherData.accountName&&(k="0")):k=`-${k}`;const E={txid:a,date:o,currencyCode:w,blockHeight:i,nativeAmount:k,networkFee:"0",parentNetworkFee:"0",ourReceiveAddresses:e,signedTx:"",metadata:{notes:u},otherParams:{fromAddress:s,toAddress:c},walletId:this.walletId};this.addTransaction(w,E)}return i}checkOutgoingTransactions(t,e){return d(this,null,function*(){var r,o;if(!Ct)throw new Error("Dont use full node API");const i=10;let a=0,l=!1,s=(r=this.otherData.lastQueryActionSeq[e])!=null?r:0;for(;!l;){const c={direction:"outgoing",acct:t,currencyCode:e,skip:a,limit:i,low:s+1},u=yield this.multicastServers("getOutgoingTransactions",c);let h=[];if(u.actions!=null&&u.actions.length>0)h=u.actions;else break;for(let f=0;f<h.length;f++){const y=h[f],w=this.processOutgoingTransaction(y);if(w>s)s=w;else if(w===s&&f===0&&a===0){l=!0;break}}if(h==null||h.length<i)break;a+=10}return s>((o=this.otherData.lastQueryActionSeq[e])!=null?o:0)&&(this.otherData.lastQueryActionSeq[e]=s,this.walletLocalDataDirty=!0),!0})}checkIncomingTransactions(t,e){return d(this,null,function*(){var r,o;if(!kt)throw new Error("Dont use Hyperion API");let i=(r=this.otherData.highestTxHeight[e])!=null?r:0;const a=10;let l=0,s=!1;for(;!s;){this.log("looping through checkIncomingTransactions, newHighestTxHeight: ",i);const c={direction:"incoming",acct:t,currencyCode:e,skip:l,limit:a,low:i+1},u=yield this.multicastServers("getIncomingTransactions",c);let h=[];if(u.actions.sort((f,y)=>y.block_num-f.block_num),u.actions.length>0)h=u.actions;else break;for(let f=0;f<h.length;f++){const y=h[f],w=this.processIncomingTransaction(y);if(w>i)i=w;else if(w===i&&f===0&&l===0){s=!0;break}}if(h.length===0||h.length<a)break;l+=10}return i>((o=this.otherData.highestTxHeight[e])!=null?o:0)&&(this.otherData.highestTxHeight[e]=i,this.walletLocalDataDirty=!0),!0})}checkTransactionsInnerLoop(){return d(this,null,function*(){if(this.otherData==null||this.otherData.accountName==="")return;const t=this.otherData.accountName;for(const e of this.enabledTokens){let r,o;try{r=yield this.checkIncomingTransactions(t,e),o=yield this.checkOutgoingTransactions(t,e)}catch(i){this.error("checkTransactionsInnerLoop fetches failed with error: ",i);return}r&&o&&(this.tokenCheckTransactionsStatus[e]=1,this.updateOnAddressesChecked()),this.transactionsChangedArray.length>0&&(this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[])}})}multicastServers(t,...e){return d(this,null,function*(){const{currencyCode:r}=this.currencyInfo;let o={result:"",server:"no server"};switch(t){case"getAccount":{o=yield(0,m.QJ)(this.networkInfo.eosNodes.map(i=>()=>d(this,null,function*(){const l=yield O(this.fetchCors,i).v1.chain.get_account(this.otherData.accountName);return{server:i,result:l}})));break}case"getIncomingTransactions":case"getOutgoingTransactions":{const{direction:i,acct:a,currencyCode:l,skip:s,limit:c,low:u}=e[0],h=this.networkInfo.eosHyperionNodes.map(y=>()=>d(this,null,function*(){const w=y+`/v2/history/get_actions?transfer.${i==="outgoing"?"from":"to"}=${a}&transfer.symbol=${l}&skip=${s}&limit=${c}&sort=desc`,I=yield this.fetchCors(w),k=J()(w,{},!0);if(!I.ok)throw this.error(`multicast in / out tx server error: ${y}`),new Error(`The server returned error code ${I.status} for ${k.hostname}`);const E=M(yield I.json());return{server:y,result:E}})),f=this.networkInfo.eosDfuseServers.map(y=>()=>d(this,null,function*(){if(this.currencyInfo.currencyCode!=="EOS")throw new Error("dfuse only supports EOS");const w=yield this.fetchCors(`${y}/graphql`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:A,variables:{query:`${i==="outgoing"?"auth":"receiver"}:${a} action:transfer`,limit:c,low:u}})}),I=(0,n._C)(Y,p)(yield w.json());if("errors"in I)throw this.warn(`dfuse ${y} get transactions failed: ${JSON.stringify(I.errors[0])}`),new Error(I.errors[0].message);const k=I.data.searchTransactionsBackward.results.map(E=>Q({trx_id:E.trace.id,"@timestamp":E.trace.block.timestamp,block_num:E.trace.block.num,act:{data:{from:E.trace.matchingActions[0].json.from,to:E.trace.matchingActions[0].json.to,amount:Number(E.trace.matchingActions[0].json.quantity.split(" ")[0]),symbol:E.trace.matchingActions[0].json.quantity.split(" ")[1],memo:E.trace.matchingActions[0].json.memo}}}));return{server:y,result:{actions:k}}}));o=yield(0,m.QJ)([...h,...f]);break}case"getKeyAccounts":{const i=e[0],a=this.networkInfo.eosHyperionNodes.map(s=>()=>d(this,null,function*(){const u=yield O(this.fetchCors,s).v1.history.get_key_accounts(i);if(u.account_names.length===0)throw new Error(`${s} could not find account with public key: ${i}`);return{server:s,result:u.account_names[0].toString()}})),l=this.networkInfo.eosDfuseServers.map(s=>()=>d(this,null,function*(){if(this.currencyInfo.currencyCode!=="EOS")throw new Error("dfuse only supports EOS");const c=yield this.fetchCors(`${s}/v0/state/key_accounts?public_key=${i}`);if(!c.ok)throw new Error(`${s} get_account failed with ${c.status}`);const u=V(yield c.json());if(u.account_names.length===0)throw new Error("dfuse returned empty array");return{server:s,result:u.account_names[0]}}));o=yield(0,m.QJ)([...a,...l]);break}case"getCurrencyBalance":{const i=e[0];o=yield(0,m.QJ)(this.networkInfo.eosNodes.map(a=>()=>d(this,null,function*(){const s=yield O(this.fetchCors,a).v1.chain.get_currency_balance(i,this.otherData.accountName);return{server:a,result:s}})));break}case"getInfo":{const{eosNodes:i}=this.networkInfo,a=(0,m.sD)(i,3);o=yield(0,m.QJ)(a.map(l=>()=>d(this,null,function*(){const c=yield O(this.fetchCors,l).v1.chain.get_info();return{server:l,result:c}})));break}case"getPowerUpState":{o=yield(0,m.QJ)(this.networkInfo.eosNodes.map(i=>()=>d(this,null,function*(){const a=O(this.fetchCors,i),s=yield new tt._B({api:a}).v1.powerup.get_state();return{server:i,result:s}})));break}case"getResourceUsage":{o=yield(0,m.QJ)(this.networkInfo.eosNodes.map(i=>()=>d(this,null,function*(){const a=O(this.fetchCors,i),s=yield new tt._B({api:a}).getSampledUsage();return{server:i,result:s}})));break}case"transact":{const{eosNodes:i}=this.networkInfo,a=(0,m.sD)(i,30);o=yield(0,m.QJ)(a.map(l=>()=>d(this,null,function*(){const s=e[0],u=yield O(this.fetchCors,l).v1.chain.send_transaction(s);return{server:l,result:u}})));break}}return this.log(`${r} multicastServers ${t} ${o.server} won`),o.result})}checkAccountInnerLoop(){return d(this,null,function*(){var t,e,r,o;const i=this.walletLocalData.publicKey;try{if(ct[(t=this.otherData.accountName)!=null?t:""]&&(this.otherData.accountName="",this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onAddressChanged()),this.otherData.accountName===""){const c=yield this.multicastServers("getKeyAccounts",i);c!=null&&ct[c]==null&&(this.otherData.accountName=c,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onAddressChanged())}for(const c of this.allTokens)if(this.enabledTokens.includes(c.currencyCode)){const h=(o=(r=(e=(yield this.multicastServers("getCurrencyBalance",c.contractAddress))[0])==null?void 0:e.units)==null?void 0:r.toString())!=null?o:"0";this.updateBalance(c.currencyCode,h)}this.updateOnAddressesChecked();const a=yield this.multicastServers("getAccount"),{cpu_limit:l,net_limit:s}=a;this.accountResources={cpu:l.available.toNumber(),net:s.available.toNumber()}}catch(a){this.error("Error fetching account: ",a)}})}getResources(){return d(this,null,function*(){if(this.getResourcesMutex)return;const{cpu:t,net:e}=this.accountResources;if(!(t>500&&e>500)){if(this.otherData.lastFreePowerUp>Date.now()-1e3*60*60*12){const r=(0,m.sD)(this.networkInfo.powerUpServers,1);try{const o=yield this.fetchCors(`${r}/${this.otherData.accountName}`);if(!o.ok)throw new Error(`getResources error ${o.status}`);this.otherData.lastFreePowerUp=Date.now(),this.walletLocalDataDirty=!0,this.log.warn("getResources freePowerUp SUCCESS");return}catch(o){this.log.warn("getResources lastFreePowerUp error",o)}}try{const r=yield this.multicastServers("getPowerUpState"),o=yield this.multicastServers("getResourceUsage"),i=r.cpu.frac(o,1e3),a=r.net.frac(o,1e3),l=[{account:"eosio",name:"powerup",authorization:[{actor:this.otherData.accountName,permission:"active"}],data:{payer:this.otherData.accountName,receiver:this.otherData.accountName,days:1,cpu_frac:i,net_frac:a,max_payment:"0.0003 EOS"}}],s={txid:"",date:0,currencyCode:this.currencyInfo.currencyCode,blockHeight:0,nativeAmount:"-3",networkFee:"0",ourReceiveAddresses:[],signedTx:"",otherParams:{actions:l,signatures:[]},walletId:this.walletId},c=yield this.signTx(s);this.getResourcesMutex=!0,yield this.broadcastTx(c),this.log.warn("getResources purchase SUCCESS")}catch(r){this.log.warn(`getResources purchase FAILURE
|
|
19
|
-
`,
|
|
20
|
-
${(0,m.oX)(t)}`),t}catch(
|
|
21
|
-
Caught exception: `,
|
|
22
|
-
`+String(
|
|
18
|
+
`,S=(0,n.su)({act:(0,n.su)({data:(0,n.su)({from:n.XC,to:n.XC,amount:n.mH,symbol:n.XC,memo:(0,n.Zz)(n.XC)})}),trx_id:n.XC,"@timestamp":n.XC,block_num:n.mH}),_=(0,n.su)({account:n.XC,name:(0,n.Wf)("transfer"),authorization:(0,n.vq)((0,n.su)({actor:n.XC,permission:(0,n.Wf)("active")})),data:(0,n.su)({from:n.XC,to:n.XC,quantity:n.XC,memo:(0,n.Zz)(n.XC)})}),F=(0,n.su)({actions:(0,n._2)(_),signatures:(0,n._2)(n.XC)}),b={structs:[{base:"",name:"transfer",fields:[{name:"from",type:"name"},{name:"to",type:"name"},{name:"quantity",type:"asset"},{name:"memo",type:"string"}]}],actions:[{name:"transfer",type:"transfer",ricardian_contract:""}]},$={structs:[{base:"",name:"powerup",fields:[{name:"payer",type:"name"},{name:"receiver",type:"name"},{name:"days",type:"int32"},{name:"net_frac",type:"int64"},{name:"cpu_frac",type:"int64"},{name:"max_payment",type:"asset"}]}],actions:[{name:"powerup",type:"powerup",ricardian_contract:""}]};var tt=v(84248),P=v(94935),j=v(84564),J=v.n(j),q=v(50244),O=v(83718),G=Object.defineProperty,K=Object.defineProperties,dt=Object.getOwnPropertyDescriptors,st=Object.getOwnPropertySymbols,ft=Object.getPrototypeOf,mt=Object.prototype.hasOwnProperty,pt=Object.prototype.propertyIsEnumerable,yt=Reflect.get,it=(g,t,e)=>t in g?G(g,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):g[t]=e,et=(g,t)=>{for(var e in t||(t={}))mt.call(t,e)&&it(g,e,t[e]);if(st)for(var e of st(t))pt.call(t,e)&&it(g,e,t[e]);return g},nt=(g,t)=>K(g,dt(t)),rt=(g,t,e)=>yt(ft(g),e,t),f=(g,t,e)=>new Promise((s,o)=>{var r=i=>{try{l(e.next(i))}catch(a){o(a)}},c=i=>{try{l(e.throw(i))}catch(a){o(a)}},l=i=>i.done?s(i.value):Promise.resolve(i.value).then(r,c);l((e=e.apply(g,t)).next())});const gt=1e4,wt=15e3,vt=1e4,kt=!0,Ct=!0,ct={ramdeathtest:!0,krpj4avazggi:!0,fobleos13125:!0};class L extends q.P{constructor(t,e,s,o){const r=(0,m.zR)(t);super(t,e,s,o);const{networkInfo:c}=t;this.fetchCors=r,this.networkInfo=c,this.activatedAccountsCache={};const{currencyCode:l,denominations:i}=this.currencyInfo;this.referenceBlock={ref_block_num:0,ref_block_prefix:0},this.accountResources={cpu:0,net:0},this.getResourcesMutex=!1,this.allTokens.push(nt(et({},i[0]),{currencyCode:l,currencyName:l,contractAddress:"eosio.token",denominations:i})),this.otherMethods={getAccountActivationQuote:a=>f(this,null,function*(){const{requestedAccountName:h,currencyCode:u,ownerPublicKey:d,activePublicKey:y,requestedAccountCurrencyCode:w}=a;if(u==null||h==null)throw new Error("ErrorInvalidParams");if(d==null&&y==null)throw new Error("ErrorInvalidParams");if(!x(h)){const k=new Error("ErrorInvalidAccountName");throw k.name="ErrorInvalidAccountName",k}const I={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({requestedAccountName:h,currencyCode:u,ownerPublicKey:d,activePublicKey:y,requestedAccountCurrencyCode:w})};try{const k=yield(0,m.QJ)(this.networkInfo.eosActivationServers.map(E=>()=>f(this,null,function*(){const ot=`${E}/api/v1/activateAccount`;return yield(yield r(ot,I)).json()})),15e3);return z(k)}catch(k){throw this.error("getAccountActivationQuoteError: ",k),new Error("getAccountActivationQuoteError")}})}}setOtherData(t){this.otherData=(0,O.sr)(t)}loadEngine(t,e,s){return f(this,null,function*(){if(yield rt(L.prototype,this,"loadEngine").call(this,t,e,s),typeof this.walletInfo.keys.ownerPublicKey!="string")if(e.keys.ownerPublicKey!=null)this.walletInfo.keys.ownerPublicKey=e.keys.ownerPublicKey;else{const o=yield t.derivePublicKey(this.walletInfo);this.walletInfo.keys.ownerPublicKey=o.ownerPublicKey}})}checkBlockchainInnerLoop(){return f(this,null,function*(){try{const t=yield this.multicastServers("getInfo"),e=t.head_block_num.toNumber();this.walletLocalData.blockHeight!==e&&(this.checkDroppedTransactionsThrottled(),this.walletLocalData.blockHeight=e,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight));const s=t.getTransactionHeader();this.referenceBlock={ref_block_num:s.ref_block_num.toNumber(),ref_block_prefix:s.ref_block_prefix.toNumber()}}catch(t){this.error("Error fetching height: ",t)}})}processIncomingTransaction(t){const e=(0,n.Vk)(S)(t);if(e==null)return this.error("Invalid supernode tx"),0;const{act:s,trx_id:o,block_num:r}=e,c=e["@timestamp"],{from:l,to:i,memo:a,symbol:h}=s.data,u=s.data.amount.toString(),d=h,y=[],w=(0,m.cp)(this.currencyInfo,d,this.allTokens);if(w==null)return this.error(`processIncomingTransaction Received unsupported currencyCode: ${d}`),0;let I=(0,D.mul)(u,w.multiplier),k="";i===this.otherData.accountName?(k=l,y.push(i),l===this.otherData.accountName&&(I="0")):(k=i,I=`-${I}`);const E={txid:o,date:Date.parse(c)/1e3,currencyCode:d,blockHeight:r>0?r:0,nativeAmount:I,networkFee:"0",parentNetworkFee:"0",ourReceiveAddresses:y,signedTx:"",otherParams:{},metadata:{name:k,notes:a},walletId:this.walletId};return this.addTransaction(d,E),E.blockHeight}processOutgoingTransaction(t){const e=[],s=t["@timestamp"].includes("Z")?t["@timestamp"]:t["@timestamp"]+"Z",o=Date.parse(s)/1e3,r=t.block_num>0?t.block_num:0;if(t.block_num==null)return this.error(`Invalid ${this.currencyInfo.currencyCode} transaction data. No tx block_num`),0;const c=t.trx_id;if(t.act==null)return this.error(`Invalid ${this.currencyInfo.currencyCode} transaction data. No action.act`),0;if(t.act.name==="transfer"){if(t.act.data==null)return this.error(`Invalid ${this.currencyInfo.currencyCode} transaction data. No action.act.data`),0;const{from:i,to:a,memo:h,amount:u,symbol:d}=t.act.data,y=u.toString(),w=d,I=(0,m.cp)(this.currencyInfo,w,this.allTokens);if(I==null)return this.error(`processOutgoingTransaction Received unsupported currencyCode: ${w}`),0;let k=(0,D.mul)(y,I.multiplier);a===this.otherData.accountName?(e.push(a),i===this.otherData.accountName&&(k="0")):k=`-${k}`;const E={txid:c,date:o,currencyCode:w,blockHeight:r,nativeAmount:k,networkFee:"0",parentNetworkFee:"0",ourReceiveAddresses:e,signedTx:"",metadata:{notes:h},otherParams:{fromAddress:i,toAddress:a},walletId:this.walletId};this.addTransaction(w,E)}return r}checkOutgoingTransactions(t,e){return f(this,null,function*(){var s,o;if(!Ct)throw new Error("Dont use full node API");const r=10;let c=0,l=!1,i=(s=this.otherData.lastQueryActionSeq[e])!=null?s:0;for(;!l;){const a={direction:"outgoing",acct:t,currencyCode:e,skip:c,limit:r,low:i+1},h=yield this.multicastServers("getOutgoingTransactions",a);let u=[];if(h.actions!=null&&h.actions.length>0)u=h.actions;else break;for(let d=0;d<u.length;d++){const y=u[d],w=this.processOutgoingTransaction(y);if(w>i)i=w;else if(w===i&&d===0&&c===0){l=!0;break}}if(u==null||u.length<r)break;c+=10}return i>((o=this.otherData.lastQueryActionSeq[e])!=null?o:0)&&(this.otherData.lastQueryActionSeq[e]=i,this.walletLocalDataDirty=!0),!0})}checkIncomingTransactions(t,e){return f(this,null,function*(){var s,o;if(!kt)throw new Error("Dont use Hyperion API");let r=(s=this.otherData.highestTxHeight[e])!=null?s:0;const c=10;let l=0,i=!1;for(;!i;){this.log("looping through checkIncomingTransactions, newHighestTxHeight: ",r);const a={direction:"incoming",acct:t,currencyCode:e,skip:l,limit:c,low:r+1},h=yield this.multicastServers("getIncomingTransactions",a);let u=[];if(h.actions.sort((d,y)=>y.block_num-d.block_num),h.actions.length>0)u=h.actions;else break;for(let d=0;d<u.length;d++){const y=u[d],w=this.processIncomingTransaction(y);if(w>r)r=w;else if(w===r&&d===0&&l===0){i=!0;break}}if(u.length===0||u.length<c)break;l+=10}return r>((o=this.otherData.highestTxHeight[e])!=null?o:0)&&(this.otherData.highestTxHeight[e]=r,this.walletLocalDataDirty=!0),!0})}checkTransactionsInnerLoop(){return f(this,null,function*(){if(this.otherData==null||this.otherData.accountName==="")return;const t=this.otherData.accountName;for(const e of this.enabledTokens){let s,o;try{s=yield this.checkIncomingTransactions(t,e),o=yield this.checkOutgoingTransactions(t,e)}catch(r){this.error("checkTransactionsInnerLoop fetches failed with error: ",r);return}s&&o&&(this.tokenCheckTransactionsStatus[e]=1,this.updateOnAddressesChecked()),this.transactionsChangedArray.length>0&&(this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[])}})}multicastServers(t,...e){return f(this,null,function*(){const{currencyCode:s}=this.currencyInfo;let o={result:"",server:"no server"};switch(t){case"getAccount":{o=yield(0,m.QJ)(this.networkInfo.eosNodes.map(r=>()=>f(this,null,function*(){const l=yield N(this.fetchCors,r).v1.chain.get_account(this.otherData.accountName);return{server:r,result:l}})));break}case"getIncomingTransactions":case"getOutgoingTransactions":{const{direction:r,acct:c,currencyCode:l,skip:i,limit:a,low:h}=e[0],u=this.networkInfo.eosHyperionNodes.map(y=>()=>f(this,null,function*(){const w=y+`/v2/history/get_actions?transfer.${r==="outgoing"?"from":"to"}=${c}&transfer.symbol=${l}&skip=${i}&limit=${a}&sort=desc`,I=yield this.fetchCors(w),k=J()(w,{},!0);if(!I.ok)throw this.error(`multicast in / out tx server error: ${y}`),new Error(`The server returned error code ${I.status} for ${k.hostname}`);const E=M(yield I.json());return{server:y,result:E}})),d=this.networkInfo.eosDfuseServers.map(y=>()=>f(this,null,function*(){if(this.currencyInfo.currencyCode!=="EOS")throw new Error("dfuse only supports EOS");const w=yield this.fetchCors(`${y}/graphql`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:A,variables:{query:`${r==="outgoing"?"auth":"receiver"}:${c} action:transfer`,limit:a,low:h}})}),I=(0,n._C)(Y,p)(yield w.json());if("errors"in I)throw this.warn(`dfuse ${y} get transactions failed: ${JSON.stringify(I.errors[0])}`),new Error(I.errors[0].message);const k=I.data.searchTransactionsBackward.results.map(E=>Q({trx_id:E.trace.id,"@timestamp":E.trace.block.timestamp,block_num:E.trace.block.num,act:{data:{from:E.trace.matchingActions[0].json.from,to:E.trace.matchingActions[0].json.to,amount:Number(E.trace.matchingActions[0].json.quantity.split(" ")[0]),symbol:E.trace.matchingActions[0].json.quantity.split(" ")[1],memo:E.trace.matchingActions[0].json.memo}}}));return{server:y,result:{actions:k}}}));o=yield(0,m.QJ)([...u,...d]);break}case"getKeyAccounts":{const r=e[0],c=this.networkInfo.eosHyperionNodes.map(i=>()=>f(this,null,function*(){const h=yield N(this.fetchCors,i).v1.history.get_key_accounts(r);if(h.account_names.length===0)throw new Error(`${i} could not find account with public key: ${r}`);return{server:i,result:h.account_names[0].toString()}})),l=this.networkInfo.eosDfuseServers.map(i=>()=>f(this,null,function*(){if(this.currencyInfo.currencyCode!=="EOS")throw new Error("dfuse only supports EOS");const a=yield this.fetchCors(`${i}/v0/state/key_accounts?public_key=${r}`);if(!a.ok)throw new Error(`${i} get_account failed with ${a.status}`);const h=V(yield a.json());if(h.account_names.length===0)throw new Error("dfuse returned empty array");return{server:i,result:h.account_names[0]}}));o=yield(0,m.QJ)([...c,...l]);break}case"getCurrencyBalance":{const r=e[0];o=yield(0,m.QJ)(this.networkInfo.eosNodes.map(c=>()=>f(this,null,function*(){const i=yield N(this.fetchCors,c).v1.chain.get_currency_balance(r,this.otherData.accountName);return{server:c,result:i}})));break}case"getInfo":{const{eosNodes:r}=this.networkInfo,c=(0,m.sD)(r,3);o=yield(0,m.QJ)(c.map(l=>()=>f(this,null,function*(){const a=yield N(this.fetchCors,l).v1.chain.get_info();return{server:l,result:a}})));break}case"getPowerUpState":{o=yield(0,m.QJ)(this.networkInfo.eosNodes.map(r=>()=>f(this,null,function*(){const c=N(this.fetchCors,r),i=yield new tt._B({api:c}).v1.powerup.get_state();return{server:r,result:i}})));break}case"getResourceUsage":{o=yield(0,m.QJ)(this.networkInfo.eosNodes.map(r=>()=>f(this,null,function*(){const c=N(this.fetchCors,r),i=yield new tt._B({api:c}).getSampledUsage();return{server:r,result:i}})));break}case"transact":{const{eosNodes:r}=this.networkInfo,c=(0,m.sD)(r,30);o=yield(0,m.QJ)(c.map(l=>()=>f(this,null,function*(){const i=e[0],h=yield N(this.fetchCors,l).v1.chain.send_transaction(i);return{server:l,result:h}})));break}}return this.log(`${s} multicastServers ${t} ${o.server} won`),o.result})}checkAccountInnerLoop(){return f(this,null,function*(){var t,e,s,o;const r=this.walletLocalData.publicKey;try{if(ct[(t=this.otherData.accountName)!=null?t:""]&&(this.otherData.accountName="",this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onAddressChanged()),this.otherData.accountName===""){const a=yield this.multicastServers("getKeyAccounts",r);a!=null&&ct[a]==null&&(this.otherData.accountName=a,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onAddressChanged())}for(const a of this.allTokens)if(this.enabledTokens.includes(a.currencyCode)){const u=(o=(s=(e=(yield this.multicastServers("getCurrencyBalance",a.contractAddress))[0])==null?void 0:e.units)==null?void 0:s.toString())!=null?o:"0";this.updateBalance(a.currencyCode,u)}this.updateOnAddressesChecked();const c=yield this.multicastServers("getAccount"),{cpu_limit:l,net_limit:i}=c;this.accountResources={cpu:l.available.toNumber(),net:i.available.toNumber()}}catch(c){this.error("Error fetching account: ",c)}})}getResources(t){return f(this,null,function*(){if(this.getResourcesMutex)return;const{cpu:e,net:s}=this.accountResources;if(!(e>500&&s>500)){if(this.otherData.lastFreePowerUp>Date.now()-1e3*60*60*12){const o=(0,m.sD)(this.networkInfo.powerUpServers,1);try{const r=yield this.fetchCors(`${o}/${this.otherData.accountName}`);if(!r.ok)throw new Error(`getResources error ${r.status}`);this.otherData.lastFreePowerUp=Date.now(),this.walletLocalDataDirty=!0,this.log.warn("getResources freePowerUp SUCCESS");return}catch(r){this.log.warn("getResources lastFreePowerUp error",r)}}try{const o=yield this.multicastServers("getPowerUpState"),r=yield this.multicastServers("getResourceUsage"),c=o.cpu.frac(r,1e3),l=o.net.frac(r,1e3),i=[{account:"eosio",name:"powerup",authorization:[{actor:this.otherData.accountName,permission:"active"}],data:{payer:this.otherData.accountName,receiver:this.otherData.accountName,days:1,cpu_frac:c,net_frac:l,max_payment:"0.0003 EOS"}}],a={txid:"",date:0,currencyCode:this.currencyInfo.currencyCode,blockHeight:0,nativeAmount:"-3",networkFee:"0",ourReceiveAddresses:[],signedTx:"",otherParams:{actions:i,signatures:[]},walletId:this.walletId},h=yield this.signTx(a,t);this.getResourcesMutex=!0,yield this.broadcastTx(h,{privateKeys:t}),this.log.warn("getResources purchase SUCCESS")}catch(o){this.log.warn(`getResources purchase FAILURE
|
|
19
|
+
`,o)}finally{this.getResourcesMutex=!1}}})}clearBlockchainCache(){return f(this,null,function*(){this.activatedAccountsCache={},yield rt(L.prototype,this,"clearBlockchainCache").call(this),this.otherData.lastQueryActionSeq={},this.otherData.highestTxHeight={},this.otherData.accountName=""})}startEngine(){return f(this,null,function*(){this.engineOn=!0,this.addToLoop("checkBlockchainInnerLoop",wt).catch(()=>{}),this.addToLoop("checkAccountInnerLoop",gt).catch(()=>{}),this.addToLoop("checkTransactionsInnerLoop",vt).catch(()=>{}),yield rt(L.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return f(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getFreshAddress(){return f(this,null,function*(){return this.otherData.accountName!=null?{publicAddress:this.otherData.accountName}:{publicAddress:"",publicKey:this.walletInfo.keys.publicKey,ownerPublicKey:this.walletInfo.keys.ownerPublicKey}})}makeSpend(t){return f(this,null,function*(){const{edgeSpendInfo:e,currencyCode:s,nativeBalance:o,denom:r}=this.makeSpendCheck(t),c=this.getTokenInfo(s);if(c==null)throw new Error("Unable to find token info");const{contractAddress:l="eosio.token"}=c,i=(0,m.cp)(this.currencyInfo,s,this.allTokens);if(i==null)throw new Error(`Error: no native denomination found for ${s}`);const a=i.multiplier.length-1;if(e.spendTargets.length!==1)throw new Error("Error: only one output allowed");const{publicAddress:h}=e.spendTargets[0];let{nativeAmount:u}=e.spendTargets[0];if(h==null)throw new Error("makeSpend Missing publicAddress");if(u==null)throw new P.$D;let d=!1;const y=this.activatedAccountsCache[h];if(y!==void 0&&!y)d=!0;else if(y===void 0)try{yield this.tools.getAccSystemStats(h),this.activatedAccountsCache[h]=!0}catch(W){if(W instanceof C.Hx&&W.details[0].message.includes("unknown key"))this.activatedAccountsCache[h]=!1,d=!0;else throw this.error("makeSpend eosPlugin.getAccSystemStats Error ",W),W}if(d)throw new Error("ErrorAccountNotActivated");if((0,D.eq)(u,"0"))throw new P.$D;const w=(0,D.div)(u,r.multiplier,a),I="0";if((0,D.gt)(u,o))throw new P.C_;const k=(0,D.toFixed)(w,a)+` ${s}`;let E="";e.spendTargets[0].otherParams!=null&&typeof e.spendTargets[0].otherParams.uniqueIdentifier=="string"&&(E=e.spendTargets[0].otherParams.uniqueIdentifier);const ot=[{account:l,name:"transfer",authorization:[{actor:this.otherData.accountName,permission:"active"}],data:{from:this.otherData.accountName,to:h,quantity:k,memo:E}}];u=`-${u}`;const ut={txid:"",date:0,currencyCode:s,blockHeight:0,nativeAmount:u,networkFee:I,ourReceiveAddresses:[],signedTx:"",otherParams:{actions:ot,signatures:[]},walletId:this.walletId};return this.warn(`${this.currencyInfo.currencyCode} tx prepared: ${u} ${this.walletLocalData.publicKey} -> ${h}`),ut})}signTx(t,e){return f(this,null,function*(){const s=(0,O.Vo)(e),o=(0,m.Xp)(t),r=o.actions[0].name==="transfer"?b:$,c=C.YW.from(nt(et({},this.referenceBlock),{expiration:new Date(new Date().getTime()+3e4),actions:o.actions}),r),l=c.signingDigest(this.networkInfo.chainId),a=C._q.from(s.eosKey).signDigest(l),h=C.uQ.from(nt(et({},c),{signatures:[a]}));o.signatures.push(a.toString());const d=C.f1.fromSigned(h).packed_trx.hexString;return t.signedTx=d,t.otherParams=o,t})}broadcastTx(t,e){return f(this,null,function*(){var s,o,r;const c=(0,O.Vo)(e==null?void 0:e.privateKeys);yield this.getResources(c);const l=(0,m.Xp)(t),{signatures:i}=l,a=C.f1.from({signatures:i,packed_trx:t.signedTx});try{const h=yield this.multicastServers("transact",a);return t.date=Date.now()/1e3,t.txid=h.transaction_id,this.warn(`SUCCESS broadcastTx
|
|
20
|
+
${(0,m.oX)(t)}`),t}catch(h){this.error(`
|
|
21
|
+
Caught exception: `,h),h instanceof C.Hx&&this.error(JSON.stringify(h.error,null,2));let u=h;u.error!=null&&(this.error(`err.error= ${u.error}`),this.error(`err.error.name= ${u.error.name}`));try{u=JSON.parse(h)}catch{throw h}throw((s=u.error)==null?void 0:s.name)==="tx_net_usage_exceeded"?(u=new Error("Insufficient NET available to send EOS transaction"),u.name="ErrorEosInsufficientNet"):((o=u.error)==null?void 0:o.name)==="tx_cpu_usage_exceeded"?(u=new Error("Insufficient CPU available to send EOS transaction"),u.name="ErrorEosInsufficientCpu"):((r=u.error)==null?void 0:r.name)==="ram_usage_exceeded"&&(u=new Error("Insufficient RAM available to send EOS transaction"),u.name="ErrorEosInsufficientRam"),u}})}getDisplayPrivateSeed(t){const e=(0,O.Vo)(t);let s="";return s+=`owner key
|
|
22
|
+
`+String(e.eosOwnerKey)+`
|
|
23
23
|
|
|
24
|
-
|
|
25
|
-
`+String(
|
|
24
|
+
`,s+=`active key
|
|
25
|
+
`+String(e.eosKey)+`
|
|
26
26
|
|
|
27
|
-
|
|
27
|
+
`,s}getDisplayPublicSeed(){var t,e;let s="";return((t=this.walletInfo.keys)==null?void 0:t.ownerPublicKey)!=null&&(s+=`owner publicKey
|
|
28
28
|
`+String(this.walletInfo.keys.ownerPublicKey)+`
|
|
29
29
|
|
|
30
|
-
`),((e=this.walletInfo.keys)==null?void 0:e.publicKey)!=null&&(
|
|
30
|
+
`),((e=this.walletInfo.keys)==null?void 0:e.publicKey)!=null&&(s+=`active publicKey
|
|
31
31
|
`+String(this.walletInfo.keys.publicKey)+`
|
|
32
32
|
|
|
33
|
-
`),
|
|
33
|
+
`),s}}function bt(g,t,e,s){return f(this,null,function*(){const o=(0,O.fz)(e),r=new L(g,t,o,s);return yield r.loadEngine(t,o,s),r})}var at=v(48764).Buffer,T=(g,t,e)=>new Promise((s,o)=>{var r=i=>{try{l(e.next(i))}catch(a){o(a)}},c=i=>{try{l(e.throw(i))}catch(a){o(a)}},l=i=>i.done?s(i.value):Promise.resolve(i.value).then(r,c);l((e=e.apply(g,t)).next())});function x(g){return C.VG.pattern.test(g)}function N(g,t){const e=new C.c6(t,{fetch:g});return new C.lP({provider:e})}class lt{constructor(t){const{builtinTokens:e,currencyInfo:s,io:o,log:r,networkInfo:c}=t;this.builtinTokens=e,this.currencyInfo=s,this.io=o,this.log=r,this.networkInfo=c,this.fetchCors=(0,m.zR)(t)}importPrivateKey(t){return T(this,null,function*(){const e=t.replace(/ /g,"");if(e.length!==51)throw new Error("Private key wrong length");return C._q.fromString(e),{eosKey:e}})}createPrivateKey(t){return T(this,null,function*(){const e=t.replace("wallet:",""),s=this.currencyInfo.walletType.replace("wallet:","");if(e===s){let o=at.from(this.io.random(32)).toString("hex");const r=C._q.from(o).toWif();o=at.from(this.io.random(32)).toString("hex");const c=C._q.from(o).toWif();return{eosOwnerKey:r,eosKey:c}}else throw new Error("InvalidWalletType")})}derivePublicKey(t){return T(this,null,function*(){const e=t.type.replace("wallet:",""),s=this.currencyInfo.walletType.replace("wallet:","");if(e===s){const o=C._q.from(t.keys.eosKey).toPublic().toLegacyString();let r;return t.keys.eosOwnerKey!=null&&(r=C._q.from(t.keys.eosOwnerKey).toPublic().toLegacyString()),{publicKey:o,ownerPublicKey:r}}else throw new Error("InvalidWalletType")})}parseUri(t){return T(this,null,function*(){var e;const{edgeParsedUri:s}=(0,U.k)(this.currencyInfo,t,{[this.networkInfo.uriProtocol]:!0});if(!x((e=s.publicAddress)!=null?e:""))throw new Error("InvalidPublicAddressError");return s})}encodeUri(t){return T(this,null,function*(){if(!x(t.publicAddress))throw new Error("InvalidPublicAddressError");let s;if(typeof t.nativeAmount=="string"){const r=this.currencyInfo.currencyCode,c=t.nativeAmount,l=(0,m.cp)(this.currencyInfo,r);if(l==null)throw new Error("InternalErrorInvalidCurrencyCode");s=(0,D.div)(c,l.multiplier,4)}return(0,U.Q)(t,this.networkInfo.uriProtocol,s)})}getTokenId(t){return T(this,null,function*(){(0,H.Rp)(t);const e=(0,H.Oj)(t.networkLocation);if(e==null||!x(e.contractAddress))throw new Error("ErrorInvalidContractAddress");return e.contractAddress.toLowerCase()})}getAccSystemStats(t){return T(this,null,function*(){return yield(0,m.QJ)(this.networkInfo.eosNodes.map(e=>()=>T(this,null,function*(){return yield N(this.fetchCors,e).v1.chain.get_account(t)})))})}getActivationSupportedCurrencies(){return T(this,null,function*(){try{const t=yield(0,m.QJ)(this.networkInfo.eosActivationServers.map(e=>()=>T(this,null,function*(){const s=`${e}/api/v1/getSupportedCurrencies`;return{result:yield(yield this.fetchCors(s)).json()}})));return X(t)}catch(t){throw this.log.error("UnableToGetSupportedCurrencies error: ",t),new Error("UnableToGetSupportedCurrencies")}})}getActivationCost(t){return T(this,null,function*(){try{return yield(0,m.QJ)(this.networkInfo.eosActivationServers.map(s=>()=>T(this,null,function*(){const o=`${s}/api/v1/eosPrices/${t}`,r=yield this.fetchCors(o),c=B(yield r.json()),l=`${s}/api/v1/startingResources/${t}`,i=yield this.fetchCors(l),a=B(yield i.json()),u=(Number(c.ram)*a.ram+Number(c.net)*a.net+Number(c.cpu)*a.cpu).toString();return(0,D.toFixed)(u,0,4)})))}catch(e){throw this.log.error("ErrorUnableToGetCost: ",e),new Error("ErrorUnableToGetCost")}})}validateAccount(t){return T(this,null,function*(){const e=x(t)&&t.length===12,s={result:""};if(!e){const o=new Error("ErrorInvalidAccountName");throw o.name="ErrorInvalidAccountName",o}try{if((yield this.getAccSystemStats(t))!=null){const r=new Error("ErrorAccountUnavailable");throw r.name="ErrorAccountUnavailable",r}throw new Error("ErrorUnknownError")}catch(o){if(o instanceof C.Hx&&o.details[0].message.includes("unknown key"))s.result="AccountAvailable";else throw o}return this.log(`validateAccount: result=${s.result}`),s})}}function It(g){return T(this,null,function*(){return new lt(g)})}},89214:function(){}}]);
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[513],{86352:function(Pe,le,C){"use strict";C.d(le,{Vn:function(){return ge},lF:function(){return fe},sp:function(){return oe}});var z=C(76714),p=(j,H,g)=>new Promise((M,U)=>{var W=n=>{try{F(g.next(n))}catch(A){U(A)}},T=n=>{try{F(g.throw(n))}catch(A){U(A)}},F=n=>n.done?M(n.value):Promise.resolve(n.value).then(W,T);F((g=g.apply(j,H)).next())});const q=["https://info1.edge.app","https://info2.edge.app"];function ee(j,H,g){return p(this,arguments,function*(M,U,W,T=5e3,F=fetch){const n=M.map(A=>()=>p(this,null,function*(){const te=yield F(A+"/"+U,W);if(typeof te!="object"){const B=`Invalid return value ${U} in ${A}`;throw console.log(B),new Error(B)}return te}));return yield(0,z.QJ)(n,T)})}function fe(j,H,g,M,U=5e3,W){return p(this,null,function*(){const T=yield ee((0,z.Sy)(H),g,M,U,W);if(!T.ok){const A=yield T.text();throw console.error(A),new Error(`Error fetching ${g}: ${A}`)}const F=yield T.json();return j(F)})}function I(j,H,g,M=5e3,U){return p(this,null,function*(){return yield ee((0,z.Sy)(j),H,g,M,U)})}const ge=(j,H,g,M)=>p(void 0,null,function*(){return yield I(q,j,H,g,M)}),oe=j=>Object.keys(j).map(H=>{const g=j[H];return g==null?H:`${H}=${encodeURIComponent(g)}`}).join("&")},79014:function(Pe,le,C){"use strict";C.d(le,{Q:function(){return W},k:function(){return U}});var z=C(77591),p=C.n(z),q=C(24350),ee=C(84564),fe=C.n(ee),I=C(76714),ge=Object.defineProperty,oe=Object.getOwnPropertySymbols,j=Object.prototype.hasOwnProperty,H=Object.prototype.propertyIsEnumerable,g=(T,F,n)=>F in T?ge(T,F,{enumerable:!0,configurable:!0,writable:!0,value:n}):T[F]=n,M=(T,F)=>{for(var n in F||(F={}))j.call(F,n)&&g(T,n,F[n]);if(oe)for(var n of oe(F))H.call(F,n)&&g(T,n,F[n]);return T};function U(T,F,n,A,te){const B=M({},fe()(F,{},!0)),ie=F.startsWith(`${T.pluginId}://`);if(B.protocol!=null&&(B.protocol=B.protocol.replace(":","")),B.protocol!=null&&B.protocol!==""&&!n[B.protocol])throw new Error(`Uri protocol '${B.protocol}' is not supported for ${T.pluginId}.`);if(B.host===""&&B.pathname==="")throw new Error("Path and host not found in uri.");const V={publicAddress:B.host!==""?B.host:B.pathname.split("/")[0]},me=B.query.label,Q=B.query.message,ae=B.query.category;(me!=null||Q!=null||ae!=null||ie)&&(V.metadata={},V.metadata.name=me,V.metadata.notes=Q,V.metadata.category=ae,V.metadata.gateway=ie!=null?ie:!1);const ne=B.query.amount;if(ne!=null&&typeof ne=="string"){A==null&&(A=T.currencyCode);const ye=(0,I.cp)(T,A!=null?A:"",te);if(ye==null)throw new Error("InternalErrorInvalidCurrencyCode");let pe=(0,z.mul)(ne,ye.multiplier);pe=(0,z.toFixed)(pe,0,0),V.nativeAmount=pe,V.currencyCode=A}return{edgeParsedUri:V,parsedUri:B}}function W(T,F,n){if(T.publicAddress==null)throw new Error("InvalidPublicAddressError");if(n==null&&T.label==null&&T.message==null)return T.publicAddress;{let A="";n!=null&&(A+="amount="+n+"&"),(T.label!=null||T.message!=null)&&(typeof T.label=="string"&&(A+="label="+T.label+"&"),typeof T.message=="string"&&(A+="message="+T.message+"&")),A=A.substr(0,A.length-1);const te={scheme:F,path:T.publicAddress,query:A};return(0,q.qC)(te)}}},6094:function(Pe,le,C){"use strict";C.r(le),C.d(le,{EthereumTools:function(){return Je},makeCurrencyEngine:function(){return Zt},makeCurrencyTools:function(){return nn}});var z=C(46286),p=C(77591),q=C(2153),ee=C(48764),fe=C(21964),I=C.n(fe),ge=C(48367),oe=C.n(ge),j=C(20918),H=C(79014),g=C(76714),M=C(49889),U=C(2832),W=C.n(U),T=C(66052),F=C(12614),n=C(82448),A=C(94935),te=C(50144),B=C(68142),ie=C.n(B),Te=C(37217),V=C.n(Te),me=C(50244);const Q=1e9,ae=1e8,ne=3e4,ye=.75,pe=60*10*1e3,Qe=5*60*1e3;var Ze=C(84564),J=C.n(Ze);const ze=m=>{const e=(0,n.XC)(m);if(/0[xX][0-9a-fA-F]+/.test(e))return parseInt(e,16);throw new TypeError("Expected a hex number")},Ye=m=>{const e=(0,n.XC)(m);if(/0[xX][0-9a-fA-F]+/.test(e))return(0,p.add)(m,"0");throw new TypeError("Expected a hex number")},qe=(0,n.su)({result:ze}),et=(0,n.su)({result:Ye}),tt=(0,n.su)({safeLow:n.mH,average:n.mH,fast:n.mH,fastest:n.mH}),nt=(0,n.su)({types:(0,n.su)((0,n._2)((0,n.su)({name:n.XC,type:n.XC}))),primaryType:n.XC,domain:n.JC,message:n.JC}),st=(0,n.su)({minGasLimit:(0,n.Zz)(n.XC),regularTransaction:n.XC,tokenTransaction:n.XC}),rt=(0,n.su)({highFee:n.XC,lowFee:n.XC,minGasPrice:(0,n.Zz)(n.XC),standardFeeLow:n.XC,standardFeeHigh:n.XC,standardFeeLowAmount:n.XC,standardFeeHighAmount:n.XC}),ot=(0,n.su)({lowFee:n.XC,standardFeeLow:n.XC,standardFeeHigh:n.XC,highFee:n.XC}),it=(0,n.su)({baseFeeMultiplier:(0,n.Zz)(ot),gasLimit:st,gasPrice:(0,n.Zz)(rt),minPriorityFee:(0,n.Zz)(n.XC)}),at={baseFeeMultiplier:void 0,gasLimit:{minGasLimit:"",regularTransaction:"",tokenTransaction:""},gasPrice:void 0,minPriorityFee:void 0},Ae=(0,n.su)(it),ct=(0,n.su)({blockNumber:n.XC,timeStamp:n.XC,hash:(0,n.Zz)(n.XC),transactionHash:(0,n.Zz)(n.XC),to:n.XC,from:n.XC,value:n.XC,nonce:n.XC,gasPrice:n.XC,gas:n.XC,gasUsed:n.XC,confirmations:n.XC,contractAddress:n.XC,tokenName:n.XC,tokenSymbol:n.XC,tokenDecimal:n.XC}),lt=(0,n.su)({hash:(0,n.Zz)(n.XC),transactionHash:(0,n.Zz)(n.XC),blockNumber:n.XC,timeStamp:n.XC,gasPrice:n.XC,gasUsed:n.XC,value:n.XC,nonce:n.XC,from:n.XC,to:n.XC,gas:n.XC,isError:n.XC,confirmations:(0,n.Zz)(n.XC)}),ht=(0,n.su)({hash:(0,n.Zz)(n.XC),transactionHash:(0,n.Zz)(n.XC),blockNumber:n.XC,timeStamp:n.XC,gasUsed:n.XC,value:n.XC,from:n.XC,to:n.XC,gas:n.XC,isError:n.XC,contractAddress:(0,n.Zz)(n.XC)}),Ie=(0,n.su)({LastBlock:n.XC,SafeGasPrice:n.XC,ProposeGasPrice:n.XC,FastGasPrice:n.XC,suggestBaseFee:(0,n.Vk)(n.XC),gasUsedRatio:(0,n.Vk)((0,n._2)(n.XC))}),sn=(0,n.su)({status:n.XC,message:n.XC,result:(0,n._C)(n.XC,(0,n.su)(Ie))}),be=(0,n.su)({from:(0,n._2)(n.XC),to:(0,n._2)(n.XC),gas:n.XC,gasPrice:n.XC,gasUsed:n.XC,tokenRecipientAddress:(0,n.Zz)(n.XC),nonceUsed:(0,n.Zz)(n.XC),replacedTxid:(0,n.Zz)(n.XC),data:(0,n.Zz)((0,n._C)(n.XC,n.gu))}),ut=(0,n.su)({nextNonce:(0,n.Vk)(n.XC,"0"),unconfirmedNextNonce:(0,n.Vk)(n.XC,"0"),networkFees:(0,n.Vk)(Ae,{default:at})}),dt=(0,n.su)({blockbook:(0,n.su)({bestHeight:n.mH})}),Se=(0,n.su)({symbol:n.XC,contract:n.XC,balance:n.XC}),ft=(0,n.su)({balance:n.XC,unconfirmedBalance:n.XC,unconfirmedTxs:n.mH,nonce:n.XC,tokens:(0,n.Vk)((0,n._2)(Se),[])}),gt=(0,n.su)({balance:n.XC,token_address:n.XC,token_symbol:n.XC}),pt=(0,n.su)({data:(0,n.su)((0,n.su)({address:(0,n.su)({balance:n.XC}),layer_2:(0,n.su)({erc_20:(0,n._2)((0,n.Zz)(n.XC))})}))}),mt=(0,n.su)({data:(0,n.su)({blocks:n.mH})}),rn=(0,n.su)({hash:n.XC,timestamp:n.XC,blockNumber:n.XC,value:n.XC,fee:n.XC,gasLimit:n.XC,gasPrice:n.XC,gasUsed:n.XC,from:(0,n._2)((0,n.su)({address:n.XC})),to:(0,n._2)((0,n.su)({address:n.XC}))}),ce=(0,n.su)({result:n.XC}),yt=(0,n.su)({l1Fee:n.XC}),kt=(0,n.su)({l1GasPrice:n.XC}),on=(0,n.su)({uri:n.XC,language:(0,n.Vk)(n.XC),token:(0,n.Vk)(n.XC)}),an=(0,n.su)({id:(0,n._C)(n.XC,n.mH),method:(0,n.Wf)("personal_sign","eth_sign","eth_signTypedData","eth_signTypedData_v4","eth_sendTransaction","eth_signTransaction","eth_sendRawTransaction"),params:(0,n._2)(n.JC)}),wt=(0,n.su)({peerId:n.XC,peerMeta:(0,n.su)({description:n.XC,url:n.XC,icons:(0,n._2)(n.XC),name:n.XC}),chainId:(0,n.Zz)(n.mH,1)}),Et=(0,n.su)({params:(0,n._2)(wt)});var vt=C(86352),he=(m,e,t)=>new Promise((s,r)=>{var i=d=>{try{l(t.next(d))}catch(c){r(c)}},u=d=>{try{l(t.throw(d))}catch(c){r(c)}},l=d=>d.done?s(d.value):Promise.resolve(d.value).then(i,u);l((t=t.apply(m,e)).next())});const ke=(m,e)=>{const t=Object.keys(e);for(const s of t){const r=e[s];typeof r=="string"&&m(` ${s}: ${(0,p.div)(r,"1000000000",18)} gwei`)}},bt=(m,e,t,s,r)=>({infoFeeProvider:()=>he(void 0,null,function*(){return yield At(m,e)}),externalFeeProviders:[Pt,Tt,Ct].map(u=>()=>he(void 0,null,function*(){return yield u(m,e,t,s,r)}))}),Ct=(m,e,t,s,r)=>he(void 0,null,function*(){const{rpcServers:i,supportsEIP1559:u=!1}=r;if(u)return;const l=(0,g.sD)(i,1)[0],d={headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST",body:JSON.stringify({method:"eth_gasPrice",params:[],id:1,jsonrpc:"2.0"})},c=yield m(l,d);if(!c.ok){const y=yield c.text();throw new Error(`fetchFeesFromRpc fetch error: ${y}`)}const o=yield c.json(),a=(0,n.Vk)(ce)(o);if(a==null)throw new Error(`fetchFeesFromRpc ${l} returned invalid json: ${o}`);const{result:h}=a,f=(0,g.Z8)(h),k={lowFee:(0,p.mul)(f,"1"),standardFeeLow:(0,p.mul)(f,"1.06"),standardFeeHigh:(0,p.mul)(f,"1.12"),highFee:(0,p.mul)(f,"1.25")};return s(`fetchFeesFromRpc: ${e.currencyCode}`),ke(s,k),k}),Pt=(m,e,t,s,r)=>he(void 0,null,function*(){const i=r.evmScanApiServers,u=Le(t,e,s);if(i==null||u==null)return;const l=`&apikey=${Array.isArray(u)?(0,g.sD)(u,1)[0]:u!=null?u:""}`,d=`${(0,g.sD)(i,1)[0]}/api?module=gastracker&action=gasoracle${l}`,c=yield m(d);if(!c.ok)throw new Error(`EvmScan fetch error: ${JSON.stringify(c)}`);const o=yield c.json(),a=o.message.includes("NOTOK");if(!(o!=null&&!a))throw new Error(`fetchFeesFromEvmScan unrecognized response message: ${o.message}`);const{SafeGasPrice:f,ProposeGasPrice:k,FastGasPrice:y}=Ie(o.result),E=parseInt(f);let b=parseInt(k),w=parseInt(y);b<=E&&(b=E+1),w<=b&&(w=b+1);const S=`${E*Q}`,R=`${(E+b)/2*Q}`,x=`${w*Q}`,_=`${w*Q/ye}`,N={lowFee:S,standardFeeLow:R,standardFeeHigh:x,highFee:_};return s(`fetchFeesFromEvmScan: ${e.currencyCode}`),ke(s,N),N}),Tt=(m,e,t,s,r)=>he(void 0,null,function*(){const{ethGasStationUrl:i}=r,u=It(t,e,s);if(i==null||u==null)return;const l=u?`?api-key=${u||""}`:"",c=yield(yield m(`${i}${l}`)).json(),o=tt(c);if(e.currencyCode==="MATIC"&&(o.safeLow*=10,o.average=(c.fast+c.safeLow)/2*10,o.fast=c.standard*10,o.fastest*=10),o.safeLow<=0||o.safeLow>ne)throw new Error("Invalid safeLow value from Gas Station");if(o.average<1||o.average>ne)throw new Error("Invalid average value from Gas Station");if(o.fast<1||o.fast>ne)throw new Error("Invalid fastest value from Gas Station");if(o.fastest<1||o.fastest>ne)throw new Error("Invalid fastest value from Gas Station");o.average<=o.safeLow&&(o.average=o.safeLow+1),o.fast<=o.average&&(o.fast=o.average+1),o.fastest<=o.fast&&(o.fastest=o.fast+1);let a=o.safeLow,h=o.fast,f=((o.fast+o.fastest)*.5+o.fastest)*.5,k=f>o.fastest?f:o.fastest;a=Math.round(a)*ae,h=Math.round(h)*ae,f=Math.round(f)*ae,k=Math.round(k)*ae;const y={lowFee:a.toString(),standardFeeLow:h.toString(),standardFeeHigh:f.toString(),highFee:k.toString()};return s(`fetchFeesFromEvmGasStation: ${e.currencyCode}`),ke(s,y),y}),At=(m,e)=>he(void 0,[m,e],function*(t,{currencyCode:s}){const i=yield(yield(0,vt.Vn)(`v1/networkFees/${s}`,void 0,void 0,t)).json();return Ae(i)}),Le=(m,e,t)=>{const{evmScanApiKey:s,etherscanApiKey:r,ftmscanApiKey:i,bscscanApiKey:u,polygonscanApiKey:l}=m;if(s!=null)return s;const{currencyCode:d}=e;if(d==="ETH"&&r!=null)return t.warn("INIT OPTION 'etherscanApiKey' IS DEPRECATED. USE 'evmScanApiKey' INSTEAD"),r;if(d==="FTM"&&i!=null)return t.warn("INIT OPTION 'ftmscanApiKey' IS DEPRECATED. USE 'evmScanApiKey' INSTEAD"),i;if(d==="BNB"&&u!=null)return t.warn("INIT OPTION 'bscscanApiKey' IS DEPRECATED. USE 'evmScanApiKey' INSTEAD"),u;if(d==="MATIC"&&l!=null)return t.warn("INIT OPTION 'polygonscanApiKey' IS DEPRECATED. USE 'evmScanApiKey' INSTEAD"),l},It=(m,e,t)=>{const{gasStationApiKey:s,ethGasStationApiKey:r}=m;if(s!=null)return s;const{currencyCode:i}=e;if(i==="ETH"&&r!=null)return t.warn("INIT OPTION 'ethGasStationApiKey' IS DEPRECATED. USE 'gasStationApiKey' INSTEAD"),r};var St=Object.defineProperty,Lt=Object.defineProperties,Ft=Object.getOwnPropertyDescriptors,Fe=Object.getOwnPropertySymbols,Ot=Object.prototype.hasOwnProperty,xt=Object.prototype.propertyIsEnumerable,Oe=(m,e,t)=>e in m?St(m,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):m[e]=t,xe=(m,e)=>{for(var t in e||(e={}))Ot.call(e,t)&&Oe(m,t,e[t]);if(Fe)for(var t of Fe(e))xt.call(e,t)&&Oe(m,t,e[t]);return m},Be=(m,e)=>Lt(m,Ft(e)),v=(m,e,t)=>new Promise((s,r)=>{var i=d=>{try{l(t.next(d))}catch(c){r(c)}},u=d=>{try{l(t.throw(d))}catch(c){r(c)}},l=d=>d.done?s(d.value):Promise.resolve(d.value).then(i,u);l((t=t.apply(m,e)).next())});const Bt=2e4,Nt=2e4,Dt=2e4,$t=2e4,Ne=4*2,De=2*60,Rt=50;function we(m,e){return v(this,null,function*(){return{result:yield m,server:e}})}const Ce=(m,e,t)=>{let s={};try{s=Be(xe({gasPrice:(0,p.div)(m,Q.toString(),Q.toString().length-1)},t!==void 0?{gasUsed:t}:{}),{gasLimit:e})}catch(r){console.log(`Failed to construct feeRateUssed: ${r}`)}return s};class _t{constructor(e){this.ethEngine=e,this.ethNeeds={blockHeightLastChecked:0,nonceLastChecked:0,tokenBalLastChecked:{},tokenTxsLastChecked:{}},this.fetchGetEtherscan=this.fetchGetEtherscan.bind(this),this.multicastServers=this.multicastServers.bind(this),this.checkAddressBlockbook=this.checkAddressBlockbook.bind(this),this.checkBlockHeightEthscan=this.checkBlockHeightEthscan.bind(this),this.checkBlockHeightBlockchair=this.checkBlockHeightBlockchair.bind(this),this.checkBlockHeightAmberdata=this.checkBlockHeightAmberdata.bind(this),this.checkBlockHeightBlockbook=this.checkBlockHeightBlockbook.bind(this),this.checkNonceRpc=this.checkNonceRpc.bind(this),this.checkNonceEthscan=this.checkNonceEthscan.bind(this),this.checkNonceAmberdata=this.checkNonceAmberdata.bind(this),this.checkTokenBalEthscan=this.checkTokenBalEthscan.bind(this),this.checkTokenBalBlockchair=this.checkTokenBalBlockchair.bind(this),this.checkTokenBalRpc=this.checkTokenBalRpc.bind(this),this.checkTxsEthscan=this.checkTxsEthscan.bind(this),this.processEthereumNetworkUpdate=this.processEthereumNetworkUpdate.bind(this),this.queryFuncs=this.buildQueryFuncs(this.ethEngine.networkInfo),this.walletId=e.walletInfo.id}processEvmScanTransaction(e,t){return v(this,null,function*(){var s;const r=[],i=(s=e.hash)!=null?s:e.transactionHash;if(i==null)throw new Error("Invalid transaction result format");const u=e.from.toLowerCase()===this.ethEngine.walletLocalData.publicKey.toLowerCase(),l=t!==this.ethEngine.currencyInfo.currencyCode,d="gasPrice"in e?e.gasPrice:void 0,c=d!=null?(0,p.mul)(d,e.gasUsed):"0";let o="0";if(u&&this.ethEngine.networkInfo.l1RollupParams!=null){const b=yield this.multicastServers("eth_getTransactionReceipt",[i]),w=yt(b.result.result);o=(0,p.add)(o,(0,g.X0)(w.l1Fee))}let a,h,f;u?l?(a=(0,p.sub)("0",e.value),h="0",f=(0,p.add)(c,o)):e.from.toLowerCase()===e.to.toLowerCase()?(a=(0,p.sub)((0,p.sub)("0",c),o),h=(0,p.add)(c,o)):(a=(0,p.sub)((0,p.sub)((0,p.sub)("0",e.value),c),o),h=(0,p.add)(c,o)):(a=e.value,h="0",r.push(this.ethEngine.walletLocalData.publicKey));const k={from:[e.from],to:[e.to],gas:e.gas,gasPrice:d!=null?d:"",gasUsed:e.gasUsed};let y=parseInt(e.blockNumber);return y<0&&(y=0),{txid:i,date:parseInt(e.timeStamp),currencyCode:t,blockHeight:y,nativeAmount:a,networkFee:h,feeRateUsed:d!=null?Ce(d,e.gas,e.gasUsed):void 0,parentNetworkFee:f,ourReceiveAddresses:r,signedTx:"",otherParams:k,walletId:this.walletId}})}processAlethioTransaction(e,t){let s;const r=[];let i;const u=t!==this.ethEngine.currencyInfo.currencyCode,l=e.attributes.value,d=e.attributes.fee?e.attributes.fee:"0",c=e.relationships.from.data.id,o=e.relationships.to.data.id;t===this.ethEngine.currencyInfo.currencyCode?i=d:i="0";const a=c.toLowerCase()===this.ethEngine.walletLocalData.publicKey.toLowerCase();if(a)c.toLowerCase()===o.toLowerCase()?s=(0,p.mul)(i,"-1"):(s=(0,p.sub)("0",l),u||(s=(0,p.sub)(s,i)));else if(o.toLowerCase()===this.ethEngine.walletLocalData.publicKey.toLowerCase())s=l,r.push(this.ethEngine.walletLocalData.publicKey.toLowerCase());else return null;const h={from:[c],to:[o],gas:"0",gasPrice:"0",gasUsed:"0"};let f=e.attributes.globalRank[0];f<0&&(f=0);let k,y="0";return u&&a?k=i:y=i,{txid:e.relationships.transaction.data.id,date:e.attributes.blockCreationTime,currencyCode:t,blockHeight:f,nativeAmount:s,networkFee:y,ourReceiveAddresses:r,signedTx:"",parentNetworkFee:k,otherParams:h,walletId:this.walletId}}fetchGetEtherscan(e,t){return v(this,null,function*(){const s=Le(this.ethEngine.initOptions,this.ethEngine.currencyInfo,this.ethEngine.log),r=`&apikey=${Array.isArray(s)?(0,g.sD)(s,1)[0]:s!=null?s:""}`,i=`${e}/api${t}`,u=yield this.ethEngine.io.fetch(`${i}${r}`);return u.ok||this.throwError(u,"fetchGetEtherscan",i),yield u.json()})}fetchGetBlockbook(e,t){return v(this,null,function*(){const s=e+t;return yield(e.includes("trezor")?yield this.ethEngine.fetchCors(s,{headers:{"User-Agent":"http.agent"}}):yield this.ethEngine.io.fetch(s)).json()})}fetchPostRPC(e,t,s,r){return v(this,null,function*(){const i={id:s,jsonrpc:"2.0",method:e,params:t};let u="";if(r.includes("infura")){const{infuraProjectId:c}=this.ethEngine.initOptions;if(!c||c.length<6)throw new Error("Need Infura Project ID");u=`/${c}`}else if(r.includes("alchemyapi")){const{alchemyApiKey:c}=this.ethEngine.initOptions;if(!c||c.length<6)throw new Error("Need Alchemy API key");u=`/v2/-${c}`}else if(r.includes("quiknode")){const{quiknodeApiKey:c}=this.ethEngine.initOptions;if(!c||c.length<6)throw new Error("Need Quiknode API key");u=`/${c}/`}r+=u;const l=yield this.ethEngine.io.fetch(r,{headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST",body:JSON.stringify(i)}),d=J()(r,{},!0);return l.ok||this.throwError(l,"fetchPostRPC",d.hostname),yield l.json()})}fetchPostBlockcypher(e,t,s){return v(this,null,function*(){const{blockcypherApiKey:r}=this.ethEngine.initOptions;let i="";r&&r.length>5&&(i="&token="+r);const u=`${s}/${e}${i}`,l=yield this.ethEngine.io.fetch(u,{headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST",body:JSON.stringify(t)}),d=J()(u,{},!0);return l.ok||this.throwError(l,"fetchPostBlockcypher",d.hostname),yield l.json()})}fetchGetBlockchair(e,t=!1){return v(this,null,function*(){const{blockchairApiKey:s}=this.ethEngine.initOptions,{blockchairApiServers:r}=this.ethEngine.networkInfo,i=t&&s?`&key=${s}`:"",u=`${r[0]}${e}`,l=yield this.ethEngine.io.fetch(`${u}${i}`);return l.ok||this.throwError(l,"fetchGetBlockchair",u),yield l.json()})}fetchPostAmberdataRpc(e){return v(this,arguments,function*(t,s=[]){const{amberdataApiKey:r=""}=this.ethEngine.initOptions,{amberdataRpcServers:i}=this.ethEngine.networkInfo,u=`${i[0]}`,l={jsonrpc:"2.0",method:t,params:s,id:1},d=yield this.ethEngine.fetchCors(u,{headers:{"x-amberdata-blockchain-id":this.ethEngine.networkInfo.amberDataBlockchainId,"x-api-key":r,"Content-Type":"application/json"},method:"POST",body:JSON.stringify(l)}),c=J()(u,{},!0);return d.ok||this.throwError(d,"fetchPostAmberdataRpc",c),yield d.json()})}fetchGetAmberdataApi(e){return v(this,null,function*(){const{amberdataApiKey:t=""}=this.ethEngine.initOptions,{amberdataApiServers:s}=this.ethEngine.networkInfo,r=`${s[0]}${e}`,i=yield this.ethEngine.fetchCors(r,{headers:{"x-amberdata-blockchain-id":this.ethEngine.networkInfo.amberDataBlockchainId,"x-api-key":t}});return i.ok||this.throwError(i,"fetchGetAmberdata",r),yield i.json()})}fetchGetAlethio(e,t=!0,s){return v(this,null,function*(){const{alethioApiKey:r=""}=this.ethEngine.initOptions,{alethioApiServers:i}=this.ethEngine.networkInfo,u=t?`${i[0]}${e}`:e,l=yield this.ethEngine.io.fetch(u,r?{headers:{Authorization:`Bearer ${r}`}}:void 0);return l.ok||this.throwError(l,"fetchGetAlethio",u),yield l.json()})}broadcastEtherscan(e,t){return v(this,null,function*(){const s=`?module=proxy&action=eth_sendRawTransaction&hex=${e.signedTx}`,r=yield this.fetchGetEtherscan(t,s);return this.broadcastResponseHandler(r,t,e)})}broadcastRPC(e,t,s){return v(this,null,function*(){const r="eth_sendRawTransaction",i=[e.signedTx],u=yield this.fetchPostRPC(r,i,t,s),l=J()(s,{},!0);return this.broadcastResponseHandler(u,l,e)})}broadcastBlockCypher(e,t){return v(this,null,function*(){const s=`v1/${this.ethEngine.currencyInfo.currencyCode.toLowerCase()}/main/txs/push`,r=e.signedTx.replace("0x",""),i=yield this.fetchPostBlockcypher(s,{tx:r},t);return this.broadcastResponseHandler(i,t,e)})}broadcastBlockbook(e,t){return v(this,null,function*(){const s=yield this.fetchGetBlockbook(t,`/api/v2/sendtx/${e.signedTx}`);return this.broadcastResponseHandler(s,t,e)})}broadcastResponseHandler(e,t,s){if(typeof e.error<"u")throw this.ethEngine.error(`FAILURE ${t}
|
|
1
|
+
(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[513],{86352:function(Te,le,C){"use strict";C.d(le,{Vn:function(){return ge},lF:function(){return fe},sp:function(){return oe}});var z=C(76714),p=(K,H,f)=>new Promise((j,M)=>{var J=n=>{try{F(f.next(n))}catch(A){M(A)}},T=n=>{try{F(f.throw(n))}catch(A){M(A)}},F=n=>n.done?j(n.value):Promise.resolve(n.value).then(J,T);F((f=f.apply(K,H)).next())});const q=["https://info1.edge.app","https://info2.edge.app"];function ee(K,H,f){return p(this,arguments,function*(j,M,J,T=5e3,F=fetch){const n=j.map(A=>()=>p(this,null,function*(){const te=yield F(A+"/"+M,J);if(typeof te!="object"){const B=`Invalid return value ${M} in ${A}`;throw console.log(B),new Error(B)}return te}));return yield(0,z.QJ)(n,T)})}function fe(K,H,f,j,M=5e3,J){return p(this,null,function*(){const T=yield ee((0,z.Sy)(H),f,j,M,J);if(!T.ok){const A=yield T.text();throw console.error(A),new Error(`Error fetching ${f}: ${A}`)}const F=yield T.json();return K(F)})}function S(K,H,f,j=5e3,M){return p(this,null,function*(){return yield ee((0,z.Sy)(K),H,f,j,M)})}const ge=(K,H,f,j)=>p(void 0,null,function*(){return yield S(q,K,H,f,j)}),oe=K=>Object.keys(K).map(H=>{const f=K[H];return f==null?H:`${H}=${encodeURIComponent(f)}`}).join("&")},79014:function(Te,le,C){"use strict";C.d(le,{Q:function(){return J},k:function(){return M}});var z=C(77591),p=C.n(z),q=C(24350),ee=C(84564),fe=C.n(ee),S=C(76714),ge=Object.defineProperty,oe=Object.getOwnPropertySymbols,K=Object.prototype.hasOwnProperty,H=Object.prototype.propertyIsEnumerable,f=(T,F,n)=>F in T?ge(T,F,{enumerable:!0,configurable:!0,writable:!0,value:n}):T[F]=n,j=(T,F)=>{for(var n in F||(F={}))K.call(F,n)&&f(T,n,F[n]);if(oe)for(var n of oe(F))H.call(F,n)&&f(T,n,F[n]);return T};function M(T,F,n,A,te){const B=j({},fe()(F,{},!0)),ie=F.startsWith(`${T.pluginId}://`);if(B.protocol!=null&&(B.protocol=B.protocol.replace(":","")),B.protocol!=null&&B.protocol!==""&&!n[B.protocol])throw new Error(`Uri protocol '${B.protocol}' is not supported for ${T.pluginId}.`);if(B.host===""&&B.pathname==="")throw new Error("Path and host not found in uri.");const V={publicAddress:B.host!==""?B.host:B.pathname.split("/")[0]},me=B.query.label,Z=B.query.message,ae=B.query.category;(me!=null||Z!=null||ae!=null||ie)&&(V.metadata={},V.metadata.name=me,V.metadata.notes=Z,V.metadata.category=ae,V.metadata.gateway=ie!=null?ie:!1);const ne=B.query.amount;if(ne!=null&&typeof ne=="string"){A==null&&(A=T.currencyCode);const ye=(0,S.cp)(T,A!=null?A:"",te);if(ye==null)throw new Error("InternalErrorInvalidCurrencyCode");let pe=(0,z.mul)(ne,ye.multiplier);pe=(0,z.toFixed)(pe,0,0),V.nativeAmount=pe,V.currencyCode=A}return{edgeParsedUri:V,parsedUri:B}}function J(T,F,n){if(T.publicAddress==null)throw new Error("InvalidPublicAddressError");if(n==null&&T.label==null&&T.message==null)return T.publicAddress;{let A="";n!=null&&(A+="amount="+n+"&"),(T.label!=null||T.message!=null)&&(typeof T.label=="string"&&(A+="label="+T.label+"&"),typeof T.message=="string"&&(A+="message="+T.message+"&")),A=A.substr(0,A.length-1);const te={scheme:F,path:T.publicAddress,query:A};return(0,q.qC)(te)}}},6094:function(Te,le,C){"use strict";C.r(le),C.d(le,{EthereumTools:function(){return Je},makeCurrencyEngine:function(){return en},makeCurrencyTools:function(){return an}});var z=C(46286),p=C(77591),q=C(2153),ee=C(48764),fe=C(21964),S=C.n(fe),ge=C(48367),oe=C.n(ge),K=C(20918),H=C(79014),f=C(76714),j=C(49889),M=C(2832),J=C.n(M),T=C(66052),F=C(12614),n=C(82448),A=C(94935),te=C(50144),B=C(68142),ie=C.n(B),Ae=C(37217),V=C.n(Ae),me=C(50244);const Z=1e9,ae=1e8,ne=3e4,ye=.75,pe=60*10*1e3,Qe=5*60*1e3;var ze=C(84564),W=C.n(ze);const Ye=m=>{const e=(0,n.XC)(m);if(/0[xX][0-9a-fA-F]+/.test(e))return parseInt(e,16);throw new TypeError("Expected a hex number")},qe=m=>{const e=(0,n.XC)(m);if(/0[xX][0-9a-fA-F]+/.test(e))return(0,p.add)(m,"0");throw new TypeError("Expected a hex number")},et=(0,n.su)({result:Ye}),tt=(0,n.su)({result:qe}),nt=(0,n.su)({safeLow:n.mH,average:n.mH,fast:n.mH,fastest:n.mH}),st=(0,n.su)({types:(0,n.su)((0,n._2)((0,n.su)({name:n.XC,type:n.XC}))),primaryType:n.XC,domain:n.JC,message:n.JC});var rt=C(62177);const ot=(0,n.su)({minGasLimit:(0,n.Zz)(n.XC),regularTransaction:n.XC,tokenTransaction:n.XC}),it=(0,n.su)({highFee:n.XC,lowFee:n.XC,minGasPrice:(0,n.Zz)(n.XC),standardFeeLow:n.XC,standardFeeHigh:n.XC,standardFeeLowAmount:n.XC,standardFeeHighAmount:n.XC}),at=(0,n.su)({lowFee:n.XC,standardFeeLow:n.XC,standardFeeHigh:n.XC,highFee:n.XC}),ct=(0,n.su)({baseFeeMultiplier:(0,n.Zz)(at),gasLimit:ot,gasPrice:(0,n.Zz)(it),minPriorityFee:(0,n.Zz)(n.XC)}),lt={baseFeeMultiplier:void 0,gasLimit:{minGasLimit:"",regularTransaction:"",tokenTransaction:""},gasPrice:void 0,minPriorityFee:void 0},Ie=(0,n.su)(ct),ht=(0,n.su)({blockNumber:n.XC,timeStamp:n.XC,hash:(0,n.Zz)(n.XC),transactionHash:(0,n.Zz)(n.XC),to:n.XC,from:n.XC,value:n.XC,nonce:n.XC,gasPrice:n.XC,gas:n.XC,gasUsed:n.XC,confirmations:n.XC,contractAddress:n.XC,tokenName:n.XC,tokenSymbol:n.XC,tokenDecimal:n.XC}),ut=(0,n.su)({hash:(0,n.Zz)(n.XC),transactionHash:(0,n.Zz)(n.XC),blockNumber:n.XC,timeStamp:n.XC,gasPrice:n.XC,gasUsed:n.XC,value:n.XC,nonce:n.XC,from:n.XC,to:n.XC,gas:n.XC,isError:n.XC,confirmations:(0,n.Zz)(n.XC)}),dt=(0,n.su)({hash:(0,n.Zz)(n.XC),transactionHash:(0,n.Zz)(n.XC),blockNumber:n.XC,timeStamp:n.XC,gasUsed:n.XC,value:n.XC,from:n.XC,to:n.XC,gas:n.XC,isError:n.XC,contractAddress:(0,n.Zz)(n.XC)}),Se=(0,n.su)({LastBlock:n.XC,SafeGasPrice:n.XC,ProposeGasPrice:n.XC,FastGasPrice:n.XC,suggestBaseFee:(0,n.Vk)(n.XC),gasUsedRatio:(0,n.Vk)((0,n._2)(n.XC))}),cn=(0,n.su)({status:n.XC,message:n.XC,result:(0,n._C)(n.XC,(0,n.su)(Se))}),be=(0,n.su)({from:(0,n._2)(n.XC),to:(0,n._2)(n.XC),gas:n.XC,gasPrice:n.XC,gasUsed:n.XC,tokenRecipientAddress:(0,n.Zz)(n.XC),nonceUsed:(0,n.Zz)(n.XC),replacedTxid:(0,n.Zz)(n.XC),data:(0,n.Zz)((0,n._C)(n.XC,n.gu))}),ft=(0,n.su)({nextNonce:(0,n.Vk)(n.XC,"0"),unconfirmedNextNonce:(0,n.Vk)(n.XC,"0"),networkFees:(0,n.Vk)(Ie,{default:lt})}),gt=(0,n.su)({blockbook:(0,n.su)({bestHeight:n.mH})}),Le=(0,n.su)({symbol:n.XC,contract:n.XC,balance:n.XC}),pt=(0,n.su)({balance:n.XC,unconfirmedBalance:n.XC,unconfirmedTxs:n.mH,nonce:n.XC,tokens:(0,n.Vk)((0,n._2)(Le),[])}),mt=(0,n.su)({balance:n.XC,token_address:n.XC,token_symbol:n.XC}),yt=(0,n.su)({data:(0,n.su)((0,n.su)({address:(0,n.su)({balance:n.XC}),layer_2:(0,n.su)({erc_20:(0,n._2)((0,n.Zz)(n.XC))})}))}),kt=(0,n.su)({data:(0,n.su)({blocks:n.mH})}),ln=(0,n.su)({hash:n.XC,timestamp:n.XC,blockNumber:n.XC,value:n.XC,fee:n.XC,gasLimit:n.XC,gasPrice:n.XC,gasUsed:n.XC,from:(0,n._2)((0,n.su)({address:n.XC})),to:(0,n._2)((0,n.su)({address:n.XC}))}),ce=(0,n.su)({result:n.XC}),wt=(0,n.su)({l1Fee:n.XC}),Et=(0,n.su)({l1GasPrice:n.XC}),hn=(0,n.su)({uri:n.XC,language:(0,n.Vk)(n.XC),token:(0,n.Vk)(n.XC)}),un=(0,n.su)({id:(0,n._C)(n.XC,n.mH),method:(0,n.Wf)("personal_sign","eth_sign","eth_signTypedData","eth_signTypedData_v4","eth_sendTransaction","eth_signTransaction","eth_sendRawTransaction"),params:(0,n._2)(n.JC)}),vt=(0,n.su)({peerId:n.XC,peerMeta:(0,n.su)({description:n.XC,url:n.XC,icons:(0,n._2)(n.XC),name:n.XC}),chainId:(0,n.Zz)(n.mH,1)}),bt=(0,n.su)({params:(0,n._2)(vt)}),Ct=(0,n.Zz)((0,n.su)({typedData:(0,n.Zz)(n.jK,!1)}),{typedData:!1}),Pt=rt.BQ,Ce=m=>{const e=m,t=(0,n.su)({[`${e}Mnemonic`]:(0,n.Zz)(n.XC),[`${e}Key`]:n.XC}),s=(0,n.su)({keys:t});return(0,n.W1)(o=>{const i=(0,n.Vk)(s)(o);if(i!=null)return{mnemonic:i.keys[`${e}Mnemonic`],privateKey:i.keys[`${e}Key`]};const l=t(o);return{mnemonic:l[`${e}Mnemonic`],privateKey:l[`${e}Key`]}},o=>({[`${e}Mnemonic`]:o.mnemonic,[`${e}Key`]:o.privateKey}))};var Tt=C(86352),he=(m,e,t)=>new Promise((s,o)=>{var i=h=>{try{a(t.next(h))}catch(r){o(r)}},l=h=>{try{a(t.throw(h))}catch(r){o(r)}},a=h=>h.done?s(h.value):Promise.resolve(h.value).then(i,l);a((t=t.apply(m,e)).next())});const ke=(m,e)=>{const t=Object.keys(e);for(const s of t){const o=e[s];typeof o=="string"&&m(` ${s}: ${(0,p.div)(o,"1000000000",18)} gwei`)}},At=(m,e,t,s,o)=>({infoFeeProvider:()=>he(void 0,null,function*(){return yield Ft(m,e)}),externalFeeProviders:[St,Lt,It].map(l=>()=>he(void 0,null,function*(){return yield l(m,e,t,s,o)}))}),It=(m,e,t,s,o)=>he(void 0,null,function*(){const{rpcServers:i,supportsEIP1559:l=!1}=o;if(l)return;const a=(0,f.sD)(i,1)[0],h={headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST",body:JSON.stringify({method:"eth_gasPrice",params:[],id:1,jsonrpc:"2.0"})},r=yield m(a,h);if(!r.ok){const y=yield r.text();throw new Error(`fetchFeesFromRpc fetch error: ${y}`)}const u=yield r.json(),c=(0,n.Vk)(ce)(u);if(c==null)throw new Error(`fetchFeesFromRpc ${a} returned invalid json: ${u}`);const{result:d}=c,g=(0,f.Z8)(d),k={lowFee:(0,p.mul)(g,"1"),standardFeeLow:(0,p.mul)(g,"1.06"),standardFeeHigh:(0,p.mul)(g,"1.12"),highFee:(0,p.mul)(g,"1.25")};return s(`fetchFeesFromRpc: ${e.currencyCode}`),ke(s,k),k}),St=(m,e,t,s,o)=>he(void 0,null,function*(){const i=o.evmScanApiServers,l=Fe(t,e,s);if(i==null||l==null)return;const a=`&apikey=${Array.isArray(l)?(0,f.sD)(l,1)[0]:l!=null?l:""}`,h=`${(0,f.sD)(i,1)[0]}/api?module=gastracker&action=gasoracle${a}`,r=yield m(h);if(!r.ok)throw new Error(`EvmScan fetch error: ${JSON.stringify(r)}`);const u=yield r.json(),c=u.message.includes("NOTOK");if(!(u!=null&&!c))throw new Error(`fetchFeesFromEvmScan unrecognized response message: ${u.message}`);const{SafeGasPrice:g,ProposeGasPrice:k,FastGasPrice:y}=Se(u.result),v=parseInt(g);let b=parseInt(k),w=parseInt(y);b<=v&&(b=v+1),w<=b&&(w=b+1);const I=`${v*Z}`,R=`${(v+b)/2*Z}`,x=`${w*Z}`,_=`${w*Z/ye}`,N={lowFee:I,standardFeeLow:R,standardFeeHigh:x,highFee:_};return s(`fetchFeesFromEvmScan: ${e.currencyCode}`),ke(s,N),N}),Lt=(m,e,t,s,o)=>he(void 0,null,function*(){const{ethGasStationUrl:i}=o,l=Ot(t,e,s);if(i==null||l==null)return;const a=l?`?api-key=${l||""}`:"",r=yield(yield m(`${i}${a}`)).json(),u=nt(r);if(e.currencyCode==="MATIC"&&(u.safeLow*=10,u.average=(r.fast+r.safeLow)/2*10,u.fast=r.standard*10,u.fastest*=10),u.safeLow<=0||u.safeLow>ne)throw new Error("Invalid safeLow value from Gas Station");if(u.average<1||u.average>ne)throw new Error("Invalid average value from Gas Station");if(u.fast<1||u.fast>ne)throw new Error("Invalid fastest value from Gas Station");if(u.fastest<1||u.fastest>ne)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 c=u.safeLow,d=u.fast,g=((u.fast+u.fastest)*.5+u.fastest)*.5,k=g>u.fastest?g:u.fastest;c=Math.round(c)*ae,d=Math.round(d)*ae,g=Math.round(g)*ae,k=Math.round(k)*ae;const y={lowFee:c.toString(),standardFeeLow:d.toString(),standardFeeHigh:g.toString(),highFee:k.toString()};return s(`fetchFeesFromEvmGasStation: ${e.currencyCode}`),ke(s,y),y}),Ft=(m,e)=>he(void 0,[m,e],function*(t,{currencyCode:s}){const i=yield(yield(0,Tt.Vn)(`v1/networkFees/${s}`,void 0,void 0,t)).json();return Ie(i)}),Fe=(m,e,t)=>{const{evmScanApiKey:s,etherscanApiKey:o,ftmscanApiKey:i,bscscanApiKey:l,polygonscanApiKey:a}=m;if(s!=null)return s;const{currencyCode:h}=e;if(h==="ETH"&&o!=null)return t.warn("INIT OPTION 'etherscanApiKey' IS DEPRECATED. USE 'evmScanApiKey' INSTEAD"),o;if(h==="FTM"&&i!=null)return t.warn("INIT OPTION 'ftmscanApiKey' IS DEPRECATED. USE 'evmScanApiKey' INSTEAD"),i;if(h==="BNB"&&l!=null)return t.warn("INIT OPTION 'bscscanApiKey' IS DEPRECATED. USE 'evmScanApiKey' INSTEAD"),l;if(h==="MATIC"&&a!=null)return t.warn("INIT OPTION 'polygonscanApiKey' IS DEPRECATED. USE 'evmScanApiKey' INSTEAD"),a},Ot=(m,e,t)=>{const{gasStationApiKey:s,ethGasStationApiKey:o}=m;if(s!=null)return s;const{currencyCode:i}=e;if(i==="ETH"&&o!=null)return t.warn("INIT OPTION 'ethGasStationApiKey' IS DEPRECATED. USE 'gasStationApiKey' INSTEAD"),o};var Bt=Object.defineProperty,xt=Object.defineProperties,Nt=Object.getOwnPropertyDescriptors,Oe=Object.getOwnPropertySymbols,$t=Object.prototype.hasOwnProperty,Dt=Object.prototype.propertyIsEnumerable,Be=(m,e,t)=>e in m?Bt(m,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):m[e]=t,xe=(m,e)=>{for(var t in e||(e={}))$t.call(e,t)&&Be(m,t,e[t]);if(Oe)for(var t of Oe(e))Dt.call(e,t)&&Be(m,t,e[t]);return m},Ne=(m,e)=>xt(m,Nt(e)),E=(m,e,t)=>new Promise((s,o)=>{var i=h=>{try{a(t.next(h))}catch(r){o(r)}},l=h=>{try{a(t.throw(h))}catch(r){o(r)}},a=h=>h.done?s(h.value):Promise.resolve(h.value).then(i,l);a((t=t.apply(m,e)).next())});const Rt=2e4,_t=2e4,Xt=2e4,Ht=2e4,$e=4*2,De=2*60,Gt=50;function we(m,e){return E(this,null,function*(){return{result:yield m,server:e}})}const Pe=(m,e,t)=>{let s={};try{s=Ne(xe({gasPrice:(0,p.div)(m,Z.toString(),Z.toString().length-1)},t!==void 0?{gasUsed:t}:{}),{gasLimit:e})}catch(o){console.log(`Failed to construct feeRateUssed: ${o}`)}return s};class Kt{constructor(e){this.ethEngine=e,this.ethNeeds={blockHeightLastChecked:0,nonceLastChecked:0,tokenBalLastChecked:{},tokenTxsLastChecked:{}},this.fetchGetEtherscan=this.fetchGetEtherscan.bind(this),this.multicastServers=this.multicastServers.bind(this),this.checkAddressBlockbook=this.checkAddressBlockbook.bind(this),this.checkBlockHeightEthscan=this.checkBlockHeightEthscan.bind(this),this.checkBlockHeightBlockchair=this.checkBlockHeightBlockchair.bind(this),this.checkBlockHeightAmberdata=this.checkBlockHeightAmberdata.bind(this),this.checkBlockHeightBlockbook=this.checkBlockHeightBlockbook.bind(this),this.checkNonceRpc=this.checkNonceRpc.bind(this),this.checkNonceEthscan=this.checkNonceEthscan.bind(this),this.checkNonceAmberdata=this.checkNonceAmberdata.bind(this),this.checkTokenBalEthscan=this.checkTokenBalEthscan.bind(this),this.checkTokenBalBlockchair=this.checkTokenBalBlockchair.bind(this),this.checkTokenBalRpc=this.checkTokenBalRpc.bind(this),this.checkTxsEthscan=this.checkTxsEthscan.bind(this),this.processEthereumNetworkUpdate=this.processEthereumNetworkUpdate.bind(this),this.queryFuncs=this.buildQueryFuncs(this.ethEngine.networkInfo),this.walletId=e.walletInfo.id}processEvmScanTransaction(e,t){return E(this,null,function*(){var s;const o=[],i=(s=e.hash)!=null?s:e.transactionHash;if(i==null)throw new Error("Invalid transaction result format");const l=e.from.toLowerCase()===this.ethEngine.walletLocalData.publicKey.toLowerCase(),a=t!==this.ethEngine.currencyInfo.currencyCode,h="gasPrice"in e?e.gasPrice:void 0,r=h!=null?(0,p.mul)(h,e.gasUsed):"0";let u="0";if(l&&this.ethEngine.networkInfo.l1RollupParams!=null){const b=yield this.multicastServers("eth_getTransactionReceipt",[i]),w=wt(b.result.result);u=(0,p.add)(u,(0,f.X0)(w.l1Fee))}let c,d,g;l?a?(c=(0,p.sub)("0",e.value),d="0",g=(0,p.add)(r,u)):e.from.toLowerCase()===e.to.toLowerCase()?(c=(0,p.sub)((0,p.sub)("0",r),u),d=(0,p.add)(r,u)):(c=(0,p.sub)((0,p.sub)((0,p.sub)("0",e.value),r),u),d=(0,p.add)(r,u)):(c=e.value,d="0",o.push(this.ethEngine.walletLocalData.publicKey));const k={from:[e.from],to:[e.to],gas:e.gas,gasPrice:h!=null?h:"",gasUsed:e.gasUsed};let y=parseInt(e.blockNumber);return y<0&&(y=0),{txid:i,date:parseInt(e.timeStamp),currencyCode:t,blockHeight:y,nativeAmount:c,networkFee:d,feeRateUsed:h!=null?Pe(h,e.gas,e.gasUsed):void 0,parentNetworkFee:g,ourReceiveAddresses:o,signedTx:"",otherParams:k,walletId:this.walletId}})}processAlethioTransaction(e,t){let s;const o=[];let i;const l=t!==this.ethEngine.currencyInfo.currencyCode,a=e.attributes.value,h=e.attributes.fee?e.attributes.fee:"0",r=e.relationships.from.data.id,u=e.relationships.to.data.id;t===this.ethEngine.currencyInfo.currencyCode?i=h:i="0";const c=r.toLowerCase()===this.ethEngine.walletLocalData.publicKey.toLowerCase();if(c)r.toLowerCase()===u.toLowerCase()?s=(0,p.mul)(i,"-1"):(s=(0,p.sub)("0",a),l||(s=(0,p.sub)(s,i)));else if(u.toLowerCase()===this.ethEngine.walletLocalData.publicKey.toLowerCase())s=a,o.push(this.ethEngine.walletLocalData.publicKey.toLowerCase());else return null;const d={from:[r],to:[u],gas:"0",gasPrice:"0",gasUsed:"0"};let g=e.attributes.globalRank[0];g<0&&(g=0);let k,y="0";return l&&c?k=i:y=i,{txid:e.relationships.transaction.data.id,date:e.attributes.blockCreationTime,currencyCode:t,blockHeight:g,nativeAmount:s,networkFee:y,ourReceiveAddresses:o,signedTx:"",parentNetworkFee:k,otherParams:d,walletId:this.walletId}}fetchGetEtherscan(e,t){return E(this,null,function*(){const s=Fe(this.ethEngine.initOptions,this.ethEngine.currencyInfo,this.ethEngine.log),o=`&apikey=${Array.isArray(s)?(0,f.sD)(s,1)[0]:s!=null?s:""}`,i=`${e}/api${t}`,l=yield this.ethEngine.io.fetch(`${i}${o}`);return l.ok||this.throwError(l,"fetchGetEtherscan",i),yield l.json()})}fetchGetBlockbook(e,t){return E(this,null,function*(){const s=e+t;return yield(e.includes("trezor")?yield this.ethEngine.fetchCors(s,{headers:{"User-Agent":"http.agent"}}):yield this.ethEngine.io.fetch(s)).json()})}fetchPostRPC(e,t,s,o){return E(this,null,function*(){const i={id:s,jsonrpc:"2.0",method:e,params:t};let l="";if(o.includes("infura")){const{infuraProjectId:r}=this.ethEngine.initOptions;if(!r||r.length<6)throw new Error("Need Infura Project ID");l=`/${r}`}else if(o.includes("alchemyapi")){const{alchemyApiKey:r}=this.ethEngine.initOptions;if(!r||r.length<6)throw new Error("Need Alchemy API key");l=`/v2/-${r}`}else if(o.includes("quiknode")){const{quiknodeApiKey:r}=this.ethEngine.initOptions;if(!r||r.length<6)throw new Error("Need Quiknode API key");l=`/${r}/`}o+=l;const a=yield this.ethEngine.io.fetch(o,{headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST",body:JSON.stringify(i)}),h=W()(o,{},!0);return a.ok||this.throwError(a,"fetchPostRPC",h.hostname),yield a.json()})}fetchPostBlockcypher(e,t,s){return E(this,null,function*(){const{blockcypherApiKey:o}=this.ethEngine.initOptions;let i="";o&&o.length>5&&(i="&token="+o);const l=`${s}/${e}${i}`,a=yield this.ethEngine.io.fetch(l,{headers:{Accept:"application/json","Content-Type":"application/json"},method:"POST",body:JSON.stringify(t)}),h=W()(l,{},!0);return a.ok||this.throwError(a,"fetchPostBlockcypher",h.hostname),yield a.json()})}fetchGetBlockchair(e,t=!1){return E(this,null,function*(){const{blockchairApiKey:s}=this.ethEngine.initOptions,{blockchairApiServers:o}=this.ethEngine.networkInfo,i=t&&s?`&key=${s}`:"",l=`${o[0]}${e}`,a=yield this.ethEngine.io.fetch(`${l}${i}`);return a.ok||this.throwError(a,"fetchGetBlockchair",l),yield a.json()})}fetchPostAmberdataRpc(e){return E(this,arguments,function*(t,s=[]){const{amberdataApiKey:o=""}=this.ethEngine.initOptions,{amberdataRpcServers:i}=this.ethEngine.networkInfo,l=`${i[0]}`,a={jsonrpc:"2.0",method:t,params:s,id:1},h=yield this.ethEngine.fetchCors(l,{headers:{"x-amberdata-blockchain-id":this.ethEngine.networkInfo.amberDataBlockchainId,"x-api-key":o,"Content-Type":"application/json"},method:"POST",body:JSON.stringify(a)}),r=W()(l,{},!0);return h.ok||this.throwError(h,"fetchPostAmberdataRpc",r),yield h.json()})}fetchGetAmberdataApi(e){return E(this,null,function*(){const{amberdataApiKey:t=""}=this.ethEngine.initOptions,{amberdataApiServers:s}=this.ethEngine.networkInfo,o=`${s[0]}${e}`,i=yield this.ethEngine.fetchCors(o,{headers:{"x-amberdata-blockchain-id":this.ethEngine.networkInfo.amberDataBlockchainId,"x-api-key":t}});return i.ok||this.throwError(i,"fetchGetAmberdata",o),yield i.json()})}fetchGetAlethio(e,t=!0,s){return E(this,null,function*(){const{alethioApiKey:o=""}=this.ethEngine.initOptions,{alethioApiServers:i}=this.ethEngine.networkInfo,l=t?`${i[0]}${e}`:e,a=yield this.ethEngine.io.fetch(l,o?{headers:{Authorization:`Bearer ${o}`}}:void 0);return a.ok||this.throwError(a,"fetchGetAlethio",l),yield a.json()})}broadcastEtherscan(e,t){return E(this,null,function*(){const s=`?module=proxy&action=eth_sendRawTransaction&hex=${e.signedTx}`,o=yield this.fetchGetEtherscan(t,s);return this.broadcastResponseHandler(o,t,e)})}broadcastRPC(e,t,s){return E(this,null,function*(){const o="eth_sendRawTransaction",i=[e.signedTx],l=yield this.fetchPostRPC(o,i,t,s),a=W()(s,{},!0);return this.broadcastResponseHandler(l,a,e)})}broadcastBlockCypher(e,t){return E(this,null,function*(){const s=`v1/${this.ethEngine.currencyInfo.currencyCode.toLowerCase()}/main/txs/push`,o=e.signedTx.replace("0x",""),i=yield this.fetchPostBlockcypher(s,{tx:o},t);return this.broadcastResponseHandler(i,t,e)})}broadcastBlockbook(e,t){return E(this,null,function*(){const s=yield this.fetchGetBlockbook(t,`/api/v2/sendtx/${e.signedTx}`);return this.broadcastResponseHandler(s,t,e)})}broadcastResponseHandler(e,t,s){if(typeof e.error<"u")throw this.ethEngine.error(`FAILURE ${t}
|
|
2
2
|
${JSON.stringify(e.error)}
|
|
3
|
-
${(0,
|
|
4
|
-
${(0,
|
|
3
|
+
${(0,f.oX)(s)}`),e.error;if(typeof e.result=="string")return this.ethEngine.warn(`SUCCESS ${t}
|
|
4
|
+
${(0,f.oX)(s)}`),e;throw this.ethEngine.error(`FAILURE ${t}
|
|
5
5
|
Invalid return value ${JSON.stringify(e)}
|
|
6
|
-
${(0,
|
|
7
|
-
${(0,
|
|
8
|
-
${JSON.stringify(
|
|
9
|
-
${JSON.stringify(i)}`),new Error("checkTokenBalBlockchair tokenData is invalid")}return{tokenBal:r,server:"blockchair"}})}checkTokenBalRpc(e){return v(this,null,function*(){let t,s,r,i;const u=this.ethEngine.walletLocalData.publicKey;try{if(e===this.ethEngine.currencyInfo.currencyCode)s=yield this.multicastServers("eth_getBalance",u),r=s.result,i=s.server;else{const l=this.ethEngine.getTokenInfo(e);if(l!=null&&typeof l.contractAddress=="string"){const d={data:`0x70a08231${(0,g.gc)((0,g.KT)(u),32)}`,to:l.contractAddress},c=yield this.multicastServers("eth_call",d),o=c.result.result;if(!o.startsWith("0x"))throw new Error("Invalid return value. Result not hex");c.result.result=(0,g.Z8)(o),r=c.result,i=c.server}}t=ce(r)}catch(l){throw this.ethEngine.error(`checkTokenBalRpc token ${e} response ${s||""} `,l),new Error(`checkTokenBalRpc invalid ${e} response ${JSON.stringify(r)}`)}return{tokenBal:{[e]:t.result},server:i}})}checkAndUpdate(e=0,t,s,r){return v(this,null,function*(){const i=Date.now();if(i-e>t)try{const u=yield r();this.processEthereumNetworkUpdate(i,u,s)}catch(u){this.ethEngine.error("checkAndUpdate ",u)}})}getQueryHeightWithLookback(e){return e>Ne?e-Ne:0}getQueryDateWithLookback(e){return e>De?e-De:0}needsLoop(){return v(this,null,function*(){for(;this.ethEngine.engineOn;){const e=this.ethEngine.walletLocalData.blockHeight;yield this.checkAndUpdate(this.ethNeeds.blockHeightLastChecked,Bt,e,()=>v(this,null,function*(){return yield this.check("blockheight")})),yield this.checkAndUpdate(this.ethNeeds.nonceLastChecked,Nt,e,()=>v(this,null,function*(){return yield this.check("nonce")}));const{currencyCode:t}=this.ethEngine.currencyInfo,s=this.ethEngine.enabledTokens;s.includes(t)||s.push(t);for(const r of s)yield this.checkAndUpdate(this.ethNeeds.tokenBalLastChecked[r],Dt,e,()=>v(this,null,function*(){return yield this.check("tokenBal",r)})),yield this.checkAndUpdate(this.ethNeeds.tokenTxsLastChecked[r],$t,e,()=>v(this,null,function*(){return yield this.check("txs",{startBlock:this.getQueryHeightWithLookback(this.ethEngine.walletLocalData.lastTransactionQueryHeight[r]),startDate:this.getQueryDateWithLookback(this.ethEngine.walletLocalData.lastTransactionDate[r]),currencyCode:r})}));yield(0,g.HB)(1e3)}})}processEthereumNetworkUpdate(e,t,s){if(!!t){if(t.blockHeight){this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} processEthereumNetworkUpdate blockHeight ${t.server||"no server"} won`);const r=t.blockHeight;this.ethEngine.log(`Got block height ${r||"no blockheight"}`),typeof r=="number"&&this.ethEngine.walletLocalData.blockHeight!==r&&(this.ethNeeds.blockHeightLastChecked=e,this.ethEngine.checkDroppedTransactionsThrottled(),this.ethEngine.walletLocalData.blockHeight=r,this.ethEngine.walletLocalDataDirty=!0,this.ethEngine.currencyEngineCallbacks.onBlockHeightChanged(this.ethEngine.walletLocalData.blockHeight))}if(t.newNonce&&(this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} processEthereumNetworkUpdate nonce ${t.server||"no server"} won`),this.ethNeeds.nonceLastChecked=e,this.ethEngine.otherData.nextNonce=t.newNonce,this.ethEngine.walletLocalDataDirty=!0),t.tokenBal!=null){const r=t.tokenBal;this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} processEthereumNetworkUpdate tokenBal ${t.server||"no server"} won`);for(const i of Object.keys(r))this.ethNeeds.tokenBalLastChecked[i]=e,this.ethEngine.updateBalance(i,r[i])}if(t.tokenTxs!=null){const r=t.tokenTxs;this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} processEthereumNetworkUpdate tokenTxs ${t.server||"no server"} won`);for(const i of Object.keys(r)){this.ethNeeds.tokenTxsLastChecked[i]=e,this.ethEngine.tokenCheckTransactionsStatus[i]=1;const u=r[i];if(u.edgeTransactions){for(const l of u.edgeTransactions)this.ethEngine.addTransaction(i,l);this.ethEngine.walletLocalData.lastTransactionQueryHeight[i]=s,this.ethEngine.walletLocalData.lastTransactionDate[i]=e}}this.ethEngine.updateOnAddressesChecked()}this.ethEngine.transactionsChangedArray.length>0&&(this.ethEngine.currencyEngineCallbacks.onTransactionsChanged(this.ethEngine.transactionsChangedArray),this.ethEngine.transactionsChangedArray=[])}}buildQueryFuncs(e){const{rpcServers:t,evmScanApiServers:s,blockbookServers:r,blockchairApiServers:i,amberdataRpcServers:u,amberdataApiServers:l}=e,d=[],c=[],o=[],a=[];return s.length>0&&(d.push(this.checkBlockHeightEthscan),c.push(this.checkNonceEthscan),a.push(this.checkTokenBalEthscan)),o.push(this.checkTxsEthscan),r.length>0&&(d.push(this.checkBlockHeightBlockbook),a.push(this.checkAddressBlockbook),c.push(this.checkAddressBlockbook)),i.length>0&&(d.push(this.checkBlockHeightBlockchair),a.push(this.checkTokenBalBlockchair)),u.length>0&&(d.push(this.checkBlockHeightAmberdata),c.push(this.checkNonceAmberdata)),l.length>0,t.length>0&&(c.push(this.checkNonceRpc),a.push(this.checkTokenBalRpc)),{blockheight:d,nonce:c,txs:o,tokenBal:a}}throwError(e,t,s){switch(e.status){case 402:case 429:case 432:throw new Error("rateLimited");default:throw new Error(`${t} The server returned error code ${e.status} for ${s}`)}}logError(e,t){(0,g.HY)(t).includes("rateLimited")?this.ethEngine.log(e,t):this.ethEngine.error(e,t)}}const Xt="low",Ht="standard",Gt="high",$e="custom",Re="1000000000";function _e(m,e,t,s){var r,i,u,l,d,c,o;let a=!0,h,f;if(m.spendTargets&&m.spendTargets.length>0&&m.spendTargets[0].publicAddress){const{customNetworkFee:k}=m||{};if(m.networkFeeOption===$e&&k!=null){const{gasLimit:P,gasPrice:O}=k;if((isNaN(P)||P==="")&&(isNaN(O)||O==="")){const L=new Error("Custom Fee must have at least gasLimit or gasPrice specified");throw L.name="ErrorBelowMinimumFee",L}if(O!=null&&O!==""){const L=(l=(i=(r=e.default)==null?void 0:r.gasPrice)==null?void 0:i.minGasPrice)!=null?l:(u=s.defaultNetworkFees.default.gasPrice)==null?void 0:u.minGasPrice;if(L!=null){const D=(0,p.div)(L,Re);if((0,p.lt)(O,D)||/^\s*$/.test(O)){const G=new Error(`Gas Limit: ${P} Gas Price (Gwei): ${O}`);throw G.name="ErrorBelowMinimumFee",G}}f=(0,p.mul)(O,Re)}if(P!=null&&P!==""){const L=(o=(c=(d=e.default)==null?void 0:d.gasLimit)==null?void 0:c.minGasLimit)!=null?o:s.defaultNetworkFees.default.gasLimit.minGasLimit;if(L!=null&&(0,p.lt)(P,L)||/^\s*$/.test(P)){const D=new Error(`Gas Limit: ${P} Gas Price (Gwei): ${O}`);throw D.name="ErrorBelowMinimumFee",D}h=P,a=!1}}if(h!=null&&f!=null)return{gasLimit:h,gasPrice:f,useDefaults:!1};const y=(0,g.f0)(m.spendTargets[0].publicAddress);let E=e.default,b=e.default;typeof e[y]<"u"&&(b=e[y],a=!1,typeof b.gasPrice<"u"&&(E=b));let w="regularTransaction";m.currencyCode&&m.currencyCode!==t.currencyCode&&(w="tokenTransaction");let S="standard";typeof m.networkFeeOption=="string"&&m.networkFeeOption!==$e&&(S=m.networkFeeOption);const R=b.gasLimit[w];let x="";if(!m.spendTargets[0].nativeAmount)throw new Error("ErrorInvalidNativeAmount");let _=m.spendTargets[0].nativeAmount;if(w==="tokenTransaction"&&(_=(0,p.div)(_,"10")),E.gasPrice==null)throw new Error("ErrorInvalidGasPrice");const N=E.gasPrice;switch(S){case Xt:x=N.lowFee;break;case Ht:{if((0,p.gte)(_,E.gasPrice.standardFeeHighAmount)){x=N.standardFeeHigh;break}if((0,p.lte)(_,N.standardFeeLowAmount)){if(!E.gasPrice)throw new Error("ErrorInvalidGasPrice");x=E.gasPrice.standardFeeLow;break}const P=(0,p.sub)(N.standardFeeHighAmount,N.standardFeeLowAmount),O=(0,p.sub)(N.standardFeeHigh,N.standardFeeLow),L=(0,p.sub)(_,N.standardFeeLowAmount),D=(0,p.mul)(L,O),G=(0,p.div)(D,P);x=(0,p.add)(N.standardFeeLow,G);break}case Gt:x=E.gasPrice.highFee;break;default:throw new Error("Invalid networkFeeOption")}return{gasLimit:h!=null?h:R,gasPrice:f!=null?f:x,useDefaults:a}}else throw new Error("ErrorInvalidSpendInfo")}const jt="1040",Xe=m=>{const{chainParams:e,data:t,dynamicOverhead:s,fixedOverhead:r,gasPriceL1Wei:i,gasLimit:u,nonce:l,to:d,value:c="0x0"}=m,o=W().custom(e),f=T.Transaction.fromTxData({nonce:l!=null?(0,g.X0)(l):void 0,gasPrice:(0,g.X0)(i),gasLimit:(0,g.X0)(u),to:d,value:c,data:t},{common:o}).raw().map(w=>w.toString("hex")).join().match(/(.{1,2})/g);if(f==null)throw new Error("Invalid rawTx string");let k=0;for(let w=0;w<f.length;w++)f[w]==="00"?k+=4:k+=16;const y=(0,p.add)((0,p.add)(k.toString(),r),jt),E=(0,p.div)(s,"1000000",18);return(0,p.mul)((0,p.mul)(i,y),E)};var Y=C(48764).Buffer,Kt=Object.defineProperty,Mt=Object.defineProperties,Ut=Object.getOwnPropertyDescriptors,He=Object.getOwnPropertySymbols,Jt=Object.getPrototypeOf,Wt=Object.prototype.hasOwnProperty,Vt=Object.prototype.propertyIsEnumerable,Qt=Reflect.get,Ge=(m,e,t)=>e in m?Kt(m,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):m[e]=t,K=(m,e)=>{for(var t in e||(e={}))Wt.call(e,t)&&Ge(m,t,e[t]);if(He)for(var t of He(e))Vt.call(e,t)&&Ge(m,t,e[t]);return m},ue=(m,e)=>Mt(m,Ut(e)),Ee=(m,e,t)=>Qt(Jt(m),t,e),$=(m,e,t)=>new Promise((s,r)=>{var i=d=>{try{l(t.next(d))}catch(c){r(c)}},u=d=>{try{l(t.throw(d))}catch(c){r(c)}},l=d=>d.done?s(d.value):Promise.resolve(d.value).then(i,u);l((t=t.apply(m,e)).next())});class de extends me.P{constructor(e,t,s,r,i,u){super(e,t,s,i),this.updateNetworkFeesFromBaseFeePerGas=()=>$(this,null,function*(){var o;const{supportsEIP1559:a=!1}=this.networkInfo;if(!a)return;const{baseFeePerGas:h}=yield this.ethNetwork.getBaseFeePerGas();if(h==null)return;const f=(0,g.Z8)(h),k=this.otherData.networkFees;if(k.default==null||k.default.gasPrice==null)return;const y=this.networkInfo.defaultNetworkFees.default,E=k.default.minPriorityFee||y.minPriorityFee,b=(o=k.default.baseFeeMultiplier)!=null?o:y.baseFeeMultiplier;if(E==null||b==null)return;const w={lowFee:"",standardFeeLow:"",standardFeeHigh:"",highFee:""};for(const S of Object.keys(b)){const R=(0,p.mul)(b[S],f),x=(0,p.add)(R,E);w[S]=(0,p.div)(x,"1")}return this.log(`updateNetworkFeesFromBaseFeePerGas ${this.currencyInfo.currencyCode}`),ke(this.log,w),w});const{pluginId:l}=this.currencyInfo;typeof this.walletInfo.keys[`${l}Key`]!="string"&&s.keys.keys&&s.keys.keys[`${l}Key`]&&(this.walletInfo.keys[`${l}Key`]=s.keys.keys[`${l}Key`]),this.initOptions=r,this.networkInfo=e.networkInfo,this.ethNetwork=new _t(this),this.lastEstimatedGasLimit={publicAddress:"",contractAddress:"",gasLimit:""},this.networkInfo.l1RollupParams!=null&&(this.l1RollupParams=this.networkInfo.l1RollupParams),this.fetchCors=(0,g.zR)(e);const{infoFeeProvider:d,externalFeeProviders:c}=bt(this.io.fetch,this.currencyInfo,this.initOptions,this.log,this.networkInfo);this.infoFeeProvider=d,this.externalFeeProviders=[...c,this.updateNetworkFeesFromBaseFeePerGas],this.utils={signMessage:o=>{if(!(0,g.vq)(o))throw new Error("ErrorInvalidMessage");const a=Y.from(this.getDisplayPrivateSeed(),"hex"),h=(0,g.ah)(o),f=I().hashPersonalMessage(h),{v:k,r:y,s:E}=I().ecsign(f,a);return I().toRpcSig(k,y,E)},signTypedData:o=>{const a=nt(o),h=Y.from(this.getDisplayPrivateSeed(),"hex"),{types:f}=a;function k(X,P=[]){if(P.includes(X)||f[X]===void 0)return P;P.push(X);for(const O of f[X])for(const L of k(O.type,P))P.includes(L)||P.push(L);return P}function y(X){let P=k(X);P=P.filter(L=>L!==X),P=[X].concat(P.sort());let O="";for(const L of P)O+=`${L}(${f[L].map(({name:D,type:G})=>`${G} ${D}`).join(",")})`;return O}function E(X){return I().keccak256(y(X))}function b(X,P){const O=[],L=[];O.push("bytes32"),L.push(E(X));for(const D of f[X]){let G=P[D.name];if(D.type==="string"||D.type==="bytes")O.push("bytes32"),G=I().keccak256(G),L.push(G);else if(f[D.type]!==void 0)O.push("bytes32"),G=I().keccak256(b(D.type,G)),L.push(G);else{if(D.type.lastIndexOf("]")===D.type.length-1)throw new Error("Arrays currently unimplemented in encodeData");O.push(D.type),L.push(G)}}return ie().rawEncode(O,L)}function w(X,P){return I().keccak256(b(X,P))}function S(){return I().keccak256(Y.concat([Y.from("1901","hex"),w("EIP712Domain",a.domain),w(a.primaryType,a.message)]))}const R=I().ecsign(S(),h),{v:x,r:_,s:N}=R;return I().bufferToHex(Y.concat([I().setLengthLeft(_,32),I().setLengthLeft(N,32),I().toBuffer(x)]))},txRpcParamsToSpendInfo:(o,a)=>{const h={otherParams:o};return o.to!=null&&(h.publicAddress=o.to),o.value!=null?h.nativeAmount=(0,g.Z8)(o.value):h.nativeAmount="0",{currencyCode:a,spendTargets:[h],networkFeeOption:"custom",customNetworkFee:{gasLimit:(0,g.Z8)(o.gas),gasPrice:(0,p.div)((0,g.Z8)(o.gasPrice),Q.toString(),18)},otherParams:o}}},this.otherMethods={personal_sign:o=>this.utils.signMessage(o[0]),eth_sign:o=>this.utils.signMessage(o[1]),eth_signTypedData:o=>{try{return this.utils.signTypedData(JSON.parse(o[1]))}catch{return this.otherMethods.eth_signTypedData_v4(o)}},eth_signTypedData_v4:o=>(0,te.signTypedData_v4)(Y.from(this.getDisplayPrivateSeed(),"hex"),{data:JSON.parse(o[1])}),eth_sendTransaction:(o,a)=>$(this,null,function*(){const h=this.utils.txRpcParamsToSpendInfo(o[0],a),f=yield this.makeSpend(h),k=yield this.signTx(f);return yield this.broadcastTx(k)}),eth_signTransaction:(o,a)=>$(this,null,function*(){const h=this.utils.txRpcParamsToSpendInfo(o[0],a),f=yield this.makeSpend(h);return yield this.signTx(f)}),eth_sendRawTransaction:o=>$(this,null,function*(){const a={currencyCode:"",nativeAmount:"",networkFee:"",blockHeight:0,date:Date.now(),txid:"",signedTx:o[0],ourReceiveAddresses:[],walletId:this.walletId};return yield this.broadcastTx(a)}),wcInit:(o,a="Edge")=>$(this,null,function*(){return yield(0,g.Vs)(new Promise((h,f)=>{const k=new F.Z({uri:o.uri,storageId:o.uri,clientMeta:{description:"Edge Wallet",url:"https://www.edge.app",icons:["https://content.edge.app/Edge_logo_Icon.png"],name:a}});k.on("session_request",(y,E)=>{if(y)throw this.error("Wallet connect session_request",y),y;const b=Et(E).params[0],w=ue(K({},b),{timeConnected:Date.now()/1e3});this.tools.walletConnectors[o.uri]={connector:k,wcProps:o,dApp:w},h(w)}),k.on("call_request",(y,E)=>{try{if(y)throw y;const b={uri:o.uri,dApp:this.tools.walletConnectors[o.uri].dApp,payload:E,walletId:this.tools.walletConnectors[o.uri].walletId};(E.method==="eth_sendTransaction"||E.method==="eth_signTransaction")&&(E.params=[K(K({},{gas:(0,g.X0)(this.otherData.networkFees.default.gasLimit.tokenTransaction),gasPrice:(0,g.X0)(this.otherData.networkFees.default.gasPrice.standardFeeHigh)}),E.params[0])]),this.currencyEngineCallbacks.onWcNewContractCall(b)}catch(b){throw this.warn("Wallet connect call_request ",b),b}}),k.on("disconnect",(y,E)=>{if(y!=null)throw y;delete this.tools.walletConnectors[o.uri]})}),5e3)}),wcConnect:(o,a,h)=>{this.tools.walletConnectors[o].connector.approveSession({accounts:[a],chainId:this.networkInfo.chainParams.chainId}),this.tools.walletConnectors[o].walletId=h},wcDisconnect:o=>{this.tools.walletConnectors[o].connector.killSession(),delete this.tools.walletConnectors[o]},wcRequestResponse:(o,a,h)=>$(this,null,function*(){const f=k=>K({id:h.id,jsonrpc:"2.0"},k);if(a)try{const k=yield this.otherMethods[`${h.method}`](h.params);switch(h.method){case"personal_sign":case"eth_sign":case"eth_signTypedData":case"eth_signTypedData_v4":this.tools.walletConnectors[o].connector.approveRequest(f({result:k}));break;case"eth_signTransaction":this.tools.walletConnectors[o].connector.approveRequest(f({result:k.signedTx}));break;case"eth_sendTransaction":case"eth_sendRawTransaction":this.tools.walletConnectors[o].connector.approveRequest(f({result:k.txid}))}}catch(k){throw this.tools.walletConnectors[o].connector.rejectRequest(f({error:{message:"rejected"}})),k}else this.tools.walletConnectors[o].connector.rejectRequest(f({error:{message:"rejected"}}))}),wcGetConnections:()=>Object.keys(this.tools.walletConnectors).filter(o=>this.tools.walletConnectors[o].walletId===this.walletInfo.id).map(o=>K(K({},this.tools.walletConnectors[o].dApp),this.tools.walletConnectors[o].wcProps))}}setOtherData(e){this.otherData=ut(e),this.otherData.networkFees.default.gasPrice==null&&(this.otherData.networkFees=K({},this.networkInfo.defaultNetworkFees))}updateNetworkFees(){return $(this,null,function*(){for(const e of this.externalFeeProviders)try{const t=yield e();if(t==null)continue;const s={};Object.keys(t).forEach(r=>{const i=r;s[i]=(0,g.Y7)(t[i])}),this.otherData.networkFees.default.gasPrice!=null&&(this.otherData.networkFees.default.gasPrice=K(K({},this.otherData.networkFees.default.gasPrice),s)),this.walletLocalDataDirty=!0;break}catch(t){this.error(`Error fetching fees from ${e.name}. ${JSON.stringify(t)}`)}})}updateL1RollupParams(){return $(this,null,function*(){if(this.l1RollupParams!=null){try{const e=yield this.ethNetwork.multicastServers("rollup_gasPrices"),t=kt(e.result.result),{l1GasPrice:s}=t;this.l1RollupParams=ue(K({},this.l1RollupParams),{gasPriceL1Wei:(0,p.ceil)((0,p.mul)((0,g.Z8)(s),this.l1RollupParams.maxGasPriceL1Multiplier),0)})}catch(e){this.log.warn("Failed to update l1GasPrice",e)}try{const e={to:this.l1RollupParams.oracleContractAddress,data:this.l1RollupParams.dynamicOverheadMethod},t=yield this.ethNetwork.multicastServers("eth_call",e),s=ce(t.result);this.l1RollupParams=ue(K({},this.l1RollupParams),{dynamicOverhead:(0,g.Z8)(s.result)})}catch(e){this.log.warn("Failed to update dynamicOverhead",e)}}})}clearBlockchainCache(){return $(this,null,function*(){yield Ee(de.prototype,this,"clearBlockchainCache").call(this),this.otherData.nextNonce="0",this.otherData.unconfirmedNextNonce="0",this.otherData.networkFees=this.networkInfo.defaultNetworkFees})}startEngine(){return $(this,null,function*(){var e;this.engineOn=!0;const t=(e=this.networkInfo.feeUpdateFrequencyMs)!=null?e:pe;this.infoFeeProvider().then(s=>{this.log.warn("infoFeeProvider:",JSON.stringify(s,null,2)),this.otherData.networkFees=(0,g.nu)(this.otherData.networkFees,s),this.walletLocalDataDirty=!0}).catch(()=>this.warn("Error fetching fees from Info Server")).finally(()=>$(this,null,function*(){return yield this.addToLoop("updateNetworkFees",t)})),this.addToLoop("updateL1RollupParams",Qe).catch(()=>{}),this.ethNetwork.needsLoop(),Ee(de.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return $(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getMaxSpendable(e){return $(this,null,function*(){const t=this.getBalance({currencyCode:e.currencyCode}),s=e.spendTargets[0].publicAddress;if(s==null)throw new Error("makeSpend Missing publicAddress");if(e.currencyCode===this.currencyInfo.currencyCode){const r=(i,u)=>{const l=(0,p.sub)(u,i);if((0,p.lte)(l,"1"))return i;const d=(0,p.add)(i,(0,p.div)(l,"2"));e.spendTargets[0].nativeAmount=d;const{gasPrice:c,gasLimit:o}=_e(e,this.otherData.networkFees,this.currencyInfo,this.networkInfo),a=(0,p.mul)(c,o);let h="0";if(this.l1RollupParams!=null){const k={nonce:this.otherData.unconfirmedNextNonce,gasPriceL1Wei:this.l1RollupParams.gasPriceL1Wei,gasLimit:o,to:s,value:(0,g.X0)(d),chainParams:this.networkInfo.chainParams,dynamicOverhead:this.l1RollupParams.dynamicOverhead,fixedOverhead:this.l1RollupParams.fixedOverhead};h=Xe(k)}const f=(0,p.add)((0,p.add)(d,a),h);return(0,p.gt)(f,t)?r(i,d):r(d,u)};return r("0",(0,p.add)(t,"1"))}else return e.spendTargets[0].nativeAmount=t,yield this.makeSpend(e),this.getBalance({currencyCode:e.currencyCode})})}makeSpend(e){return $(this,null,function*(){var t,s,r,i;const{edgeSpendInfo:u,currencyCode:l,skipChecks:d}=this.makeSpendCheck(e),{pendingTxs:c=[]}=u;if(u.spendTargets.length!==1)throw new Error("Error: only one output allowed");const o=u.spendTargets[0],{publicAddress:a}=o;let{nativeAmount:h}=o;if(a==null)throw new Error("makeSpend Missing publicAddress");if(h==null)throw new A.$D;if(!I().isValidAddress(a))throw new TypeError(`Invalid ${this.currencyInfo.pluginId} address`);let f=(s=o.memo)!=null?s:(t=o.otherParams)==null?void 0:t.data;if(f!=null&&f.length>0&&!(0,g.vq)(f))throw new Error("Memo/data field must be of type 'hex'");f===""&&(f=void 0);const k=f!=null;let y;const E=_e(u,this.otherData.networkFees,this.currencyInfo,this.networkInfo),b=E.gasPrice;let w=E.gasLimit;const S=E.useDefaults,R=w;let x;if(c.length>0){const Z=this.walletLocalData.otherData,re=this.walletLocalData.numUnconfirmedSpendTxs>0?Z.unconfirmedNextNonce:Z.nextNonce;x=(0,p.add)(re,c.length.toString())}let _,N;if(l===this.currencyInfo.currencyCode)y={from:[this.walletLocalData.publicKey],to:[a],gas:w,gasPrice:b,gasUsed:"0",nonceUsed:x,data:f},N=(0,g.X0)(h);else{if(f)_=a;else{const re=this.getTokenInfo(l);if(re==null||typeof re.contractAddress!="string")throw new Error("Error: Token not supported or invalid contract address");_=re.contractAddress,N=(0,g.X0)(h);const ve=ie().simpleEncode("transfer(address,uint256):(uint256)",a,N);N="0x0",f="0x"+Y.from(ve).toString("hex")}y={from:[this.walletLocalData.publicKey],to:[_],gas:w,gasPrice:b,gasUsed:"0",tokenRecipientAddress:a,nonceUsed:x,data:f}}if(S&&(this.lastEstimatedGasLimit.publicAddress!==a||this.lastEstimatedGasLimit.contractAddress!==_||this.lastEstimatedGasLimit.gasLimit==="")){const Z=[{to:_||a,from:this.walletLocalData.publicKey,gas:"0xffffff",value:N,data:f},"latest"];let re=!1;try{const We=(yield this.ethNetwork.multicastServers("eth_getCode",[_||a,"latest"])).result.result!=="0x";try{if(!We&&!k)w="21000";else{const Ve=yield this.ethNetwork.multicastServers("eth_estimateGas",Z);w=(0,p.add)(parseInt(Ve.result.result,16).toString(),"0"),We&&(w=(0,p.mul)(w,"2"))}re=!0}catch{if(k)throw new Error("Unable to estimate gas limit. Please try again later");this.networkInfo.defaultNetworkFees.default.gasLimit.tokenTransaction!=null&&(w=this.networkInfo.defaultNetworkFees.default.gasLimit.tokenTransaction)}if((0,p.lt)(w,"21000"))throw w=R,this.lastEstimatedGasLimit.gasLimit="",new Error("Calculated gasLimit less than minimum");re&&(this.lastEstimatedGasLimit={publicAddress:a,contractAddress:_,gasLimit:w})}catch(ve){this.error("makeSpend Error determining gas limit ",ve)}}else S&&(w=this.lastEstimatedGasLimit.gasLimit);y.gas=w;const X=(r=this.walletLocalData.totalBalances[this.currencyInfo.currencyCode])!=null?r:"0";let P=(0,p.mul)(b,w),O="0",L=null,D="0";if(this.l1RollupParams!=null){const Z={nonce:y.nonceUsed,gasPriceL1Wei:this.l1RollupParams.gasPriceL1Wei,gasLimit:y.gas,to:y.to[0],value:N,data:y.data,chainParams:this.networkInfo.chainParams,dynamicOverhead:this.l1RollupParams.dynamicOverhead,fixedOverhead:this.l1RollupParams.fixedOverhead};D=Xe(Z)}if(l===this.currencyInfo.currencyCode){if(P=(0,p.add)(P,D),O=(0,p.add)(P,h),!d&&(0,p.gt)(O,X))throw new A.C_;h=(0,p.mul)(O,"-1")}else{if(L=(0,p.add)(P,D),!d&&(0,p.gt)(P,X))throw new A.C_({currencyCode:this.currencyInfo.currencyCode,networkFee:P});const Z=(i=this.walletLocalData.totalBalances[l])!=null?i:"0";if(!d&&(0,p.gt)(h,Z))throw new A.C_;P="0",h=(0,p.mul)(h,"-1")}const G={txid:"",date:0,currencyCode:l,blockHeight:0,nativeAmount:h,networkFee:P,feeRateUsed:Ce(b,w),ourReceiveAddresses:[],signedTx:"",otherParams:y,walletId:this.walletId};return L&&(G.parentNetworkFee=L),G})}signTx(e){return $(this,null,function*(){const t=(0,g.Xp)(e),s=(0,g.NC)(t.gas),r=(0,g.NC)(t.gasPrice);let i;if(e.currencyCode===this.currencyInfo.currencyCode){const E=(0,p.add)(e.nativeAmount,e.networkFee);i=(0,p.mul)("-1",E,16)}else i=(0,p.mul)("-1",e.nativeAmount,16);(0,p.lt)(i,"0")&&(i="0x00");let u=t.nonceUsed;if(!u)if(this.walletLocalData.numUnconfirmedSpendTxs&&(0,p.gt)(this.otherData.unconfirmedNextNonce,this.otherData.nextNonce)){const E=(0,p.sub)(this.otherData.unconfirmedNextNonce,this.otherData.nextNonce);if((0,p.lte)(E,"5"))u=this.otherData.unconfirmedNextNonce,this.walletLocalDataDirty=!0;else{const b=new Error("Excessive pending spend transactions");throw b.name="ErrorExcessivePendingSpends",b}}else u=this.otherData.nextNonce;const l=(0,g.NC)(u);let d;if(t.data!=null)d=t.data,e.currencyCode!==this.currencyInfo.currencyCode&&(i="0x00");else if(e.currencyCode===this.currencyInfo.currencyCode)d="";else{const E=ie().simpleEncode("transfer(address,uint256):(uint256)",t.tokenRecipientAddress,i);d="0x"+Y.from(E).toString("hex"),i="0x00"}const{chainParams:c}=this.networkInfo,o=W().custom(c),a={nonce:l,gasPrice:r,gasLimit:s,to:t.to[0],value:i,data:d},h=Y.from(this.walletInfo.keys[`${this.currencyInfo.pluginId}Key`],"hex"),f=V().fromPrivateKey(h);this.warn(`signTx getAddressString ${f.getAddressString()}`);const y=T.Transaction.fromTxData(a,{common:o}).sign(h);return e.signedTx=(0,g.$9)(y.serialize()),e.txid=(0,g.$9)(y.hash()),e.date=Date.now()/1e3,e.otherParams!=null&&(e.otherParams.nonceUsed=u),this.warn(`signTx
|
|
10
|
-
${(0,
|
|
11
|
-
${(0,
|
|
6
|
+
${(0,f.oX)(s)}`),new Error("Invalid return value on transaction send")}multicastServers(e,...t){return E(this,null,function*(){const{rpcServers:s,blockcypherApiServers:o,evmScanApiServers:i,blockbookServers:l,chainParams:{chainId:a}}=this.ethEngine.networkInfo;let h={result:"",server:"no server"},r,u;switch(e){case"broadcastTx":{const c=[];s.forEach(d=>{const g=W()(d,{},!0);c.push(we(this.broadcastRPC(t[0],a,d),g.hostname))}),i.forEach(d=>{c.push(we(this.broadcastEtherscan(t[0],d),"etherscan"))}),l.forEach(d=>{c.push(we(this.broadcastBlockbook(t[0],d),"blockbook"))}),o.forEach(d=>{c.push(we(this.broadcastBlockCypher(t[0],d),"blockcypher"))}),h=yield(0,f.Wp)(c),this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} multicastServers ${e} ${h.server} won`);break}case"eth_blockNumber":r=i.map(c=>()=>E(this,null,function*(){if(!c.includes("etherscan")&&!c.includes("blockscout"))throw new Error(`Unsupported command eth_blockNumber in ${c}`);let d="?module=proxy&action=eth_blockNumber";c.includes("blockscout")&&(d="?module=block&action=eth_block_number");const g=yield this.fetchGetEtherscan(c,d);if(typeof g.result!="string"){const k=`Invalid return value eth_blockNumber in ${c}`;throw this.ethEngine.error(k),new Error(k)}return{server:c,result:g}})),r.push(...s.map(c=>()=>E(this,null,function*(){const d=yield this.fetchPostRPC("eth_blockNumber",[],a,c);if(d.error!=null)throw this.ethEngine.error(`Successful eth_blockNumber response object from ${c} included an error ${d.error}`),new Error("Successful eth_blockNumber response object included an error");return{server:W()(c).hostname,result:d}}))),r=(0,f.Sy)(r),h=yield(0,f.QJ)(r);break;case"eth_estimateGas":r=s.map(c=>()=>E(this,null,function*(){const d=yield this.fetchPostRPC("eth_estimateGas",t[0],a,c);if(d.error!=null)throw this.ethEngine.error(`Successful eth_estimateGas response object from ${c} included an error ${d.error}`),new Error("Successful eth_estimateGas response object included an error");return{server:W()(c).hostname,result:d}})),h=yield(0,f.QJ)(r);break;case"eth_getTransactionReceipt":case"rollup_gasPrices":case"eth_getCode":r=s.map(c=>()=>E(this,null,function*(){const d=yield this.fetchPostRPC(e,t[0],a,c);if(d.error!=null)throw this.ethEngine.error(`Successful ${e} response object from ${c} included an error ${d.error}`),new Error(`Successful ${e} response object included an error`);return{server:W()(c).hostname,result:d}})),h=yield(0,f.QJ)(r);break;case"eth_getTransactionCount":u=`?module=proxy&action=eth_getTransactionCount&address=${t[0]}&tag=latest`,r=i.map(c=>()=>E(this,null,function*(){if(!c.includes("etherscan")&&!c.includes("blockscout"))throw new Error(`Unsupported command eth_getTransactionCount in ${c}`);const d=yield this.fetchGetEtherscan(c,u);if(typeof d.result!="string"){const g=`Invalid return value eth_getTransactionCount in ${c}`;throw this.ethEngine.error(g),new Error(g)}return{server:c,result:d}})),r=(0,f.Sy)(r),h=yield(0,f.QJ)(r);break;case"eth_getTransactionCount_RPC":r=s.map(c=>()=>E(this,null,function*(){const d=yield this.fetchPostRPC("eth_getTransactionCount",[t[0],"latest"],a,c);if(d.error!=null)throw this.ethEngine.error(`Successful eth_getTransactionCount_RPC response object from ${c} included an error ${d.error}`),new Error("Successful eth_getTransactionCount_RPC response object included an error");return{server:W()(c).hostname,result:d}})),r=(0,f.Sy)(r),h=yield(0,f.QJ)(r);break;case"eth_getBalance":u=`?module=account&action=balance&address=${t[0]}&tag=latest`,r=i.map(c=>()=>E(this,null,function*(){const d=yield this.fetchGetEtherscan(c,u);if(!d.result||typeof d.result!="string"){const g=`Invalid return value eth_getBalance in ${c}`;throw this.ethEngine.error(g),new Error(g)}return{server:c,result:d}})),r.push(...s.map(c=>()=>E(this,null,function*(){const d=yield this.fetchPostRPC("eth_getBalance",[t[0],"latest"],a,c);if(d.error!=null)throw this.ethEngine.error(`Successful eth_getBalance response object from ${c} included an error ${d.error}`),new Error("Successful eth_getBalance response object included an error");if(!(0,f.vq)(d.result))throw new Error(`eth_getBalance not hex for ${W()(c).hostname}`);return d.result=(0,f.Z8)(d.result),{server:W()(c).hostname,result:d}}))),r=(0,f.Sy)(r),h=yield(0,f.QJ)(r);break;case"getTokenBalance":u=`?module=account&action=tokenbalance&contractaddress=${t[1]}&address=${t[0]}&tag=latest`,r=i.map(c=>()=>E(this,null,function*(){const d=yield this.fetchGetEtherscan(c,u);if(!d.result||typeof d.result!="string"){const g=`Invalid return value getTokenBalance in ${c}`;throw this.ethEngine.error(g),new Error(g)}return{server:c,result:d}})),r=(0,f.Sy)(r),h=yield(0,f.QJ)(r);break;case"getTransactions":{const{currencyCode:c,address:d,startBlock:g,page:k,offset:y,contractAddress:v,searchRegularTxs:b}=t[0];let w;c===this.ethEngine.currencyInfo.currencyCode?w=`?action=${b?"txlist":"txlistinternal"}&module=account`:w=`?action=tokentx&contractaddress=${v}&module=account`,u=`${w}&address=${d}&startblock=${g}&endblock=999999999&sort=asc&page=${k}&offset=${y}`,r=i.map(I=>()=>E(this,null,function*(){const R=yield this.fetchGetEtherscan(I,u);if(typeof R.result!="object"||typeof R.result.length!="number"){const x=`Invalid return value getTransactions in ${I}`;throw R.result!=="Max rate limit reached"&&this.ethEngine.error(x),new Error(x)}return{server:I,result:R}})),r=(0,f.Sy)(r),r.length>0?h=yield(0,f.QJ)(r):h=Ne(xe({},h),{result:{result:[]}});break}case"blockbookBlockHeight":r=l.map(c=>()=>E(this,null,function*(){const d=yield this.fetchGetBlockbook(c,t[0]);return{server:c,result:d}})),r=(0,f.Sy)(r),h=yield(0,f.QJ)(r);break;case"blockbookAddress":r=l.map(c=>()=>E(this,null,function*(){const d=yield this.fetchGetBlockbook(c,t[0]);return{server:c,result:d}})),r=(0,f.Sy)(r),h=yield(0,f.QJ)(r);break;case"eth_call":r=s.map(c=>()=>E(this,null,function*(){const d=yield this.fetchPostRPC("eth_call",[t[0],"latest"],a,c);if(d.error!=null)throw this.ethEngine.error(`Successful eth_call response object from ${c} included an error ${d.error}`),new Error("Successful eth_call response object included an error");return{server:W()(c).hostname,result:d}})),h=yield(0,f.QJ)(r);break}return h})}getBaseFeePerGas(){return E(this,null,function*(){const{rpcServers:e,chainParams:{chainId:t}}=this.ethEngine.networkInfo,s=e.map(o=>()=>E(this,null,function*(){return yield this.fetchPostRPC("eth_getBlockByNumber",["latest",!1],t,o).then(i=>{if(i.error!=null){const a=`multicast get_baseFeePerGas error response from ${o}: ${JSON.stringify(i.error)}`;throw this.ethEngine.warn(a),new Error(a)}return{baseFeePerGas:i.result.baseFeePerGas}})}));return yield(0,f.QJ)(s)})}checkBlockHeightEthscan(){return E(this,null,function*(){const{result:e,server:t}=yield this.multicastServers("eth_blockNumber");return{blockHeight:et(e).result,server:t}})}checkBlockHeightBlockbook(){return E(this,null,function*(){try{const{result:e,server:t}=yield this.multicastServers("blockbookBlockHeight","/api/v2");return{blockHeight:gt(e).blockbook.bestHeight,server:t}}catch(e){throw this.ethEngine.log("checkBlockHeightBlockbook blockHeight ",e),new Error("checkBlockHeightBlockbook returned invalid JSON")}})}checkBlockHeightBlockchair(){return E(this,null,function*(){try{const e=yield this.fetchGetBlockchair(`/${this.ethEngine.currencyInfo.pluginId}/stats`,!1);return{blockHeight:parseInt(kt(e).data.blocks,10),server:"blockchair"}}catch(e){throw this.logError(e),new Error("checkBlockHeightBlockchair returned invalid JSON")}})}checkBlockHeightAmberdata(){return E(this,null,function*(){try{const e=yield this.fetchPostAmberdataRpc("eth_blockNumber",[]);return{blockHeight:parseInt(ce(e).result,16),server:"amberdata"}}catch(e){throw this.logError("checkBlockHeightAmberdata",e),new Error("checkTxsAmberdata (regular tx) response is invalid")}})}checkNonceRpc(){return E(this,null,function*(){const e=this.ethEngine.walletLocalData.publicKey,{result:t,server:s}=yield this.multicastServers("eth_getTransactionCount_RPC",e),o=ce(t);if(/0[xX][0-9a-fA-F]+/.test(o.result))return{newNonce:(0,p.add)("0",o.result),server:s};throw new Error("checkNonceRpc returned invalid JSON")})}checkNonceEthscan(){return E(this,null,function*(){const e=this.ethEngine.walletLocalData.publicKey,{result:t,server:s}=yield this.multicastServers("eth_getTransactionCount",e);return{newNonce:tt(t).result,server:s}})}checkNonceAmberdata(){return E(this,null,function*(){const e=this.ethEngine.walletLocalData.publicKey;try{const t=yield this.fetchPostAmberdataRpc("eth_getTransactionCount",[e,"latest"]);return{newNonce:`${parseInt(ce(t).result,16)}`,server:"amberdata"}}catch(t){throw this.logError("checkNonceAmberdata",t),new Error("Amberdata returned invalid JSON")}})}check(e,...t){return E(this,null,function*(){return yield(0,f.QJ)(this.queryFuncs[e].map(s=>()=>E(this,null,function*(){return yield s(...t)}))).catch(s=>({}))})}getAllTxsEthscan(e,t,s,o){return E(this,null,function*(){const i=this.ethEngine.walletLocalData.publicKey;let l=1;const a=[];let h="";const r=o.contractAddress,u=o.searchRegularTxs;for(;;){const c=Gt,d=yield this.multicastServers("getTransactions",{currencyCode:t,address:i,startBlock:e,page:l,offset:c,contractAddress:r,searchRegularTxs:u});h=d.server;const g=d.result.result;for(let k=0;k<g.length;k++)try{const y=s(g[k]),v=yield this.processEvmScanTransaction(y,t);a.push(v)}catch(y){throw this.ethEngine.error(`getAllTxsEthscan ${s.name}
|
|
7
|
+
${(0,f.HY)(y)}
|
|
8
|
+
${JSON.stringify(g[k])}`),new Error(`getAllTxsEthscan ${s.name} is invalid`)}if(g.length===0)break;l++}return{allTransactions:a,server:h}})}checkTxsEthscan(e){return E(this,null,function*(){const{startBlock:t,currencyCode:s}=e;let o,i;if(s===this.ethEngine.currencyInfo.currencyCode){const a=yield this.getAllTxsEthscan(t,s,ut,{searchRegularTxs:!0}),h=yield this.getAllTxsEthscan(t,s,dt,{searchRegularTxs:!1});o=a.server||h.server,i=[...a.allTransactions,...h.allTransactions]}else{const a=this.ethEngine.getTokenInfo(s);if(a!=null&&typeof a.contractAddress=="string"){const h=a.contractAddress,r=yield this.getAllTxsEthscan(t,s,ht,{contractAddress:h});o=r.server,i=r.allTransactions}else return{}}const l={blockHeight:t,edgeTransactions:i};return{tokenTxs:{[s]:l},server:o}})}getTokenCurrencyCode(e){const t=this.ethEngine.walletLocalData.publicKey;if(e.toLowerCase()===t.toLowerCase())return this.ethEngine.currencyInfo.currencyCode;for(const s of this.ethEngine.enabledTokens){const o=this.ethEngine.getTokenInfo(s);if(o!=null){const i=o.contractAddress;if(e&&typeof i=="string"&&i.toLowerCase()===e.toLowerCase())return s}}}checkAddressBlockbook(e){return E(this,null,function*(){const t=this.ethEngine.walletLocalData.publicKey.toLowerCase(),s={newNonce:"0",tokenBal:{},server:""},o="/api/v2/address/"+t+"?&details=tokenBalances",{result:i,server:l}=yield this.multicastServers("blockbookAddress",o);let a;try{a=pt(i)}catch{throw this.ethEngine.error(`checkTxsBlockbook ${l} error BlockbookAddress ${JSON.stringify(i)}`),new Error(`checkTxsBlockbook ${l} returned invalid JSON for BlockbookAddress`)}const{nonce:h,tokens:r,balance:u}=a;s.newNonce=h,s.tokenBal!=null&&(s.tokenBal[this.ethEngine.currencyInfo.currencyCode]=u),s.server=l;for(const c of r)try{const{symbol:d,balance:g}=Le(c);s.tokenBal[d]=g}catch{throw this.ethEngine.error(`checkTxsBlockbook ${l} BlockbookTokenBalance ${JSON.stringify(c)}`),new Error(`checkTxsBlockbook ${l} returned invalid JSON for BlockbookTokenBalance`)}return s})}checkTokenBalEthscan(e){return E(this,null,function*(){const t=this.ethEngine.walletLocalData.publicKey;let s,o,i,l;try{if(e===this.ethEngine.currencyInfo.currencyCode)s=yield this.multicastServers("eth_getBalance",t),o=s.result,i=s.server;else{const a=this.ethEngine.getTokenInfo(e);if(a!=null&&typeof a.contractAddress=="string"){const h=a.contractAddress,r=yield this.multicastServers("getTokenBalance",t,h);o=r.result,i=r.server}}l=ce(o)}catch(a){throw this.ethEngine.error(`checkTokenBalEthscan token ${e} response ${s||""} `,a),new Error(`checkTokenBalEthscan invalid ${e} response ${JSON.stringify(o)}`)}if(/^\d+$/.test(l.result)){const a=l.result;return{tokenBal:{[e]:a},server:i}}else throw new Error(`checkTokenBalEthscan returned invalid JSON for ${e}`)})}checkTokenBalBlockchair(){return E(this,null,function*(){let e;const t=this.ethEngine.walletLocalData.publicKey,s=`/${this.ethEngine.currencyInfo.pluginId}/dashboards/address/${t}?erc_20=true`;try{const i=yield this.fetchGetBlockchair(s,!1);e=yt(i)}catch(i){throw this.logError("checkTokenBalBlockchair",i),new Error("checkTokenBalBlockchair response is invalid")}const o={[this.ethEngine.currencyInfo.currencyCode]:e.data[t].address.balance};for(const i of e.data[t].layer_2.erc_20)try{const l=mt(i),a=l.balance,h=l.token_address,r=l.token_symbol,u=this.ethEngine.getTokenInfo(r);u!=null&&u.contractAddress===h&&(o[r]=a)}catch(l){throw this.ethEngine.error(`checkTokenBalBlockchair tokenData ${(0,f.HY)(l)}
|
|
9
|
+
${JSON.stringify(i)}`),new Error("checkTokenBalBlockchair tokenData is invalid")}return{tokenBal:o,server:"blockchair"}})}checkTokenBalRpc(e){return E(this,null,function*(){let t,s,o,i;const l=this.ethEngine.walletLocalData.publicKey;try{if(e===this.ethEngine.currencyInfo.currencyCode)s=yield this.multicastServers("eth_getBalance",l),o=s.result,i=s.server;else{const a=this.ethEngine.getTokenInfo(e);if(a!=null&&typeof a.contractAddress=="string"){const h={data:`0x70a08231${(0,f.gc)((0,f.KT)(l),32)}`,to:a.contractAddress},r=yield this.multicastServers("eth_call",h),u=r.result.result;if(!u.startsWith("0x"))throw new Error("Invalid return value. Result not hex");r.result.result=(0,f.Z8)(u),o=r.result,i=r.server}}t=ce(o)}catch(a){throw this.ethEngine.error(`checkTokenBalRpc token ${e} response ${s||""} `,a),new Error(`checkTokenBalRpc invalid ${e} response ${JSON.stringify(o)}`)}return{tokenBal:{[e]:t.result},server:i}})}checkAndUpdate(e=0,t,s,o){return E(this,null,function*(){const i=Date.now();if(i-e>t)try{const l=yield o();this.processEthereumNetworkUpdate(i,l,s)}catch(l){this.ethEngine.error("checkAndUpdate ",l)}})}getQueryHeightWithLookback(e){return e>$e?e-$e:0}getQueryDateWithLookback(e){return e>De?e-De:0}needsLoop(){return E(this,null,function*(){for(;this.ethEngine.engineOn;){const e=this.ethEngine.walletLocalData.blockHeight;yield this.checkAndUpdate(this.ethNeeds.blockHeightLastChecked,Rt,e,()=>E(this,null,function*(){return yield this.check("blockheight")})),yield this.checkAndUpdate(this.ethNeeds.nonceLastChecked,_t,e,()=>E(this,null,function*(){return yield this.check("nonce")}));const{currencyCode:t}=this.ethEngine.currencyInfo,s=this.ethEngine.enabledTokens;s.includes(t)||s.push(t);for(const o of s)yield this.checkAndUpdate(this.ethNeeds.tokenBalLastChecked[o],Xt,e,()=>E(this,null,function*(){return yield this.check("tokenBal",o)})),yield this.checkAndUpdate(this.ethNeeds.tokenTxsLastChecked[o],Ht,e,()=>E(this,null,function*(){return yield this.check("txs",{startBlock:this.getQueryHeightWithLookback(this.ethEngine.walletLocalData.lastTransactionQueryHeight[o]),startDate:this.getQueryDateWithLookback(this.ethEngine.walletLocalData.lastTransactionDate[o]),currencyCode:o})}));yield(0,f.HB)(1e3)}})}processEthereumNetworkUpdate(e,t,s){if(!!t){if(t.blockHeight){this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} processEthereumNetworkUpdate blockHeight ${t.server||"no server"} won`);const o=t.blockHeight;this.ethEngine.log(`Got block height ${o||"no blockheight"}`),typeof o=="number"&&this.ethEngine.walletLocalData.blockHeight!==o&&(this.ethNeeds.blockHeightLastChecked=e,this.ethEngine.checkDroppedTransactionsThrottled(),this.ethEngine.walletLocalData.blockHeight=o,this.ethEngine.walletLocalDataDirty=!0,this.ethEngine.currencyEngineCallbacks.onBlockHeightChanged(this.ethEngine.walletLocalData.blockHeight))}if(t.newNonce&&(this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} processEthereumNetworkUpdate nonce ${t.server||"no server"} won`),this.ethNeeds.nonceLastChecked=e,this.ethEngine.otherData.nextNonce=t.newNonce,this.ethEngine.walletLocalDataDirty=!0),t.tokenBal!=null){const o=t.tokenBal;this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} processEthereumNetworkUpdate tokenBal ${t.server||"no server"} won`);for(const i of Object.keys(o))this.ethNeeds.tokenBalLastChecked[i]=e,this.ethEngine.updateBalance(i,o[i])}if(t.tokenTxs!=null){const o=t.tokenTxs;this.ethEngine.log(`${this.ethEngine.currencyInfo.currencyCode} processEthereumNetworkUpdate tokenTxs ${t.server||"no server"} won`);for(const i of Object.keys(o)){this.ethNeeds.tokenTxsLastChecked[i]=e,this.ethEngine.tokenCheckTransactionsStatus[i]=1;const l=o[i];if(l.edgeTransactions){for(const a of l.edgeTransactions)this.ethEngine.addTransaction(i,a);this.ethEngine.walletLocalData.lastTransactionQueryHeight[i]=s,this.ethEngine.walletLocalData.lastTransactionDate[i]=e}}this.ethEngine.updateOnAddressesChecked()}this.ethEngine.transactionsChangedArray.length>0&&(this.ethEngine.currencyEngineCallbacks.onTransactionsChanged(this.ethEngine.transactionsChangedArray),this.ethEngine.transactionsChangedArray=[])}}buildQueryFuncs(e){const{rpcServers:t,evmScanApiServers:s,blockbookServers:o,blockchairApiServers:i,amberdataRpcServers:l,amberdataApiServers:a}=e,h=[],r=[],u=[],c=[];return s.length>0&&(h.push(this.checkBlockHeightEthscan),r.push(this.checkNonceEthscan),c.push(this.checkTokenBalEthscan)),u.push(this.checkTxsEthscan),o.length>0&&(h.push(this.checkBlockHeightBlockbook),c.push(this.checkAddressBlockbook),r.push(this.checkAddressBlockbook)),i.length>0&&(h.push(this.checkBlockHeightBlockchair),c.push(this.checkTokenBalBlockchair)),l.length>0&&(h.push(this.checkBlockHeightAmberdata),r.push(this.checkNonceAmberdata)),a.length>0,t.length>0&&(r.push(this.checkNonceRpc),c.push(this.checkTokenBalRpc)),{blockheight:h,nonce:r,txs:u,tokenBal:c}}throwError(e,t,s){switch(e.status){case 402:case 429:case 432:throw new Error("rateLimited");default:throw new Error(`${t} The server returned error code ${e.status} for ${s}`)}}logError(e,t){(0,f.HY)(t).includes("rateLimited")?this.ethEngine.log(e,t):this.ethEngine.error(e,t)}}const jt="low",Mt="standard",Ut="high",Re="custom",_e="1000000000";function Xe(m,e,t,s){var o,i,l,a,h,r,u;let c=!0,d,g;if(m.spendTargets&&m.spendTargets.length>0&&m.spendTargets[0].publicAddress){const{customNetworkFee:k}=m||{};if(m.networkFeeOption===Re&&k!=null){const{gasLimit:P,gasPrice:O}=k;if((isNaN(P)||P==="")&&(isNaN(O)||O==="")){const L=new Error("Custom Fee must have at least gasLimit or gasPrice specified");throw L.name="ErrorBelowMinimumFee",L}if(O!=null&&O!==""){const L=(a=(i=(o=e.default)==null?void 0:o.gasPrice)==null?void 0:i.minGasPrice)!=null?a:(l=s.defaultNetworkFees.default.gasPrice)==null?void 0:l.minGasPrice;if(L!=null){const $=(0,p.div)(L,_e);if((0,p.lt)(O,$)||/^\s*$/.test(O)){const G=new Error(`Gas Limit: ${P} Gas Price (Gwei): ${O}`);throw G.name="ErrorBelowMinimumFee",G}}g=(0,p.mul)(O,_e)}if(P!=null&&P!==""){const L=(u=(r=(h=e.default)==null?void 0:h.gasLimit)==null?void 0:r.minGasLimit)!=null?u:s.defaultNetworkFees.default.gasLimit.minGasLimit;if(L!=null&&(0,p.lt)(P,L)||/^\s*$/.test(P)){const $=new Error(`Gas Limit: ${P} Gas Price (Gwei): ${O}`);throw $.name="ErrorBelowMinimumFee",$}d=P,c=!1}}if(d!=null&&g!=null)return{gasLimit:d,gasPrice:g,useDefaults:!1};const y=(0,f.f0)(m.spendTargets[0].publicAddress);let v=e.default,b=e.default;typeof e[y]<"u"&&(b=e[y],c=!1,typeof b.gasPrice<"u"&&(v=b));let w="regularTransaction";m.currencyCode&&m.currencyCode!==t.currencyCode&&(w="tokenTransaction");let I="standard";typeof m.networkFeeOption=="string"&&m.networkFeeOption!==Re&&(I=m.networkFeeOption);const R=b.gasLimit[w];let x="";if(!m.spendTargets[0].nativeAmount)throw new Error("ErrorInvalidNativeAmount");let _=m.spendTargets[0].nativeAmount;if(w==="tokenTransaction"&&(_=(0,p.div)(_,"10")),v.gasPrice==null)throw new Error("ErrorInvalidGasPrice");const N=v.gasPrice;switch(I){case jt:x=N.lowFee;break;case Mt:{if((0,p.gte)(_,v.gasPrice.standardFeeHighAmount)){x=N.standardFeeHigh;break}if((0,p.lte)(_,N.standardFeeLowAmount)){if(!v.gasPrice)throw new Error("ErrorInvalidGasPrice");x=v.gasPrice.standardFeeLow;break}const P=(0,p.sub)(N.standardFeeHighAmount,N.standardFeeLowAmount),O=(0,p.sub)(N.standardFeeHigh,N.standardFeeLow),L=(0,p.sub)(_,N.standardFeeLowAmount),$=(0,p.mul)(L,O),G=(0,p.div)($,P);x=(0,p.add)(N.standardFeeLow,G);break}case Ut:x=v.gasPrice.highFee;break;default:throw new Error("Invalid networkFeeOption")}return{gasLimit:d!=null?d:R,gasPrice:g!=null?g:x,useDefaults:c}}else throw new Error("ErrorInvalidSpendInfo")}const Wt="1040",He=m=>{const{chainParams:e,data:t,dynamicOverhead:s,fixedOverhead:o,gasPriceL1Wei:i,gasLimit:l,nonce:a,to:h,value:r="0x0"}=m,u=J().custom(e),g=T.Transaction.fromTxData({nonce:a!=null?(0,f.X0)(a):void 0,gasPrice:(0,f.X0)(i),gasLimit:(0,f.X0)(l),to:h,value:r,data:t},{common:u}).raw().map(w=>w.toString("hex")).join().match(/(.{1,2})/g);if(g==null)throw new Error("Invalid rawTx string");let k=0;for(let w=0;w<g.length;w++)g[w]==="00"?k+=4:k+=16;const y=(0,p.add)((0,p.add)(k.toString(),o),Wt),v=(0,p.div)(s,"1000000",18);return(0,p.mul)((0,p.mul)(i,y),v)};var Y=C(48764).Buffer,Jt=Object.defineProperty,Vt=Object.defineProperties,Zt=Object.getOwnPropertyDescriptors,Ge=Object.getOwnPropertySymbols,Qt=Object.getPrototypeOf,zt=Object.prototype.hasOwnProperty,Yt=Object.prototype.propertyIsEnumerable,qt=Reflect.get,Ke=(m,e,t)=>e in m?Jt(m,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):m[e]=t,U=(m,e)=>{for(var t in e||(e={}))zt.call(e,t)&&Ke(m,t,e[t]);if(Ge)for(var t of Ge(e))Yt.call(e,t)&&Ke(m,t,e[t]);return m},ue=(m,e)=>Vt(m,Zt(e)),Ee=(m,e,t)=>qt(Qt(m),t,e),D=(m,e,t)=>new Promise((s,o)=>{var i=h=>{try{a(t.next(h))}catch(r){o(r)}},l=h=>{try{a(t.throw(h))}catch(r){o(r)}},a=h=>h.done?s(h.value):Promise.resolve(h.value).then(i,l);a((t=t.apply(m,e)).next())});class de extends me.P{constructor(e,t,s,o,i,l){super(e,t,s,i),this.updateNetworkFeesFromBaseFeePerGas=()=>D(this,null,function*(){var r;const{supportsEIP1559:u=!1}=this.networkInfo;if(!u)return;const{baseFeePerGas:c}=yield this.ethNetwork.getBaseFeePerGas();if(c==null)return;const d=(0,f.Z8)(c),g=this.otherData.networkFees;if(g.default==null||g.default.gasPrice==null)return;const k=this.networkInfo.defaultNetworkFees.default,y=g.default.minPriorityFee||k.minPriorityFee,v=(r=g.default.baseFeeMultiplier)!=null?r:k.baseFeeMultiplier;if(y==null||v==null)return;const b={lowFee:"",standardFeeLow:"",standardFeeHigh:"",highFee:""};for(const w of Object.keys(v)){const I=(0,p.mul)(v[w],d),R=(0,p.add)(I,y);b[w]=(0,p.div)(R,"1")}return this.log(`updateNetworkFeesFromBaseFeePerGas ${this.currencyInfo.currencyCode}`),ke(this.log,b),b}),this.initOptions=o,this.networkInfo=e.networkInfo,this.ethNetwork=new Kt(this),this.lastEstimatedGasLimit={publicAddress:"",contractAddress:"",gasLimit:""},this.networkInfo.l1RollupParams!=null&&(this.l1RollupParams=this.networkInfo.l1RollupParams),this.fetchCors=(0,f.zR)(e);const{infoFeeProvider:a,externalFeeProviders:h}=At(this.io.fetch,this.currencyInfo,this.initOptions,this.log,this.networkInfo);this.infoFeeProvider=a,this.externalFeeProviders=[...h,this.updateNetworkFeesFromBaseFeePerGas],this.utils={signMessage:(r,u)=>{if(!(0,f.vq)(r))throw new Error("ErrorInvalidMessage");const c=Y.from(u.privateKey,"hex"),d=(0,f.ah)(r),g=S().hashPersonalMessage(d),{v:k,r:y,s:v}=S().ecsign(g,c);return S().toRpcSig(k,y,v)},signTypedData:(r,u)=>{const c=st(r),d=Y.from(u.privateKey,"hex"),{types:g}=c;function k(X,P=[]){if(P.includes(X)||g[X]===void 0)return P;P.push(X);for(const O of g[X])for(const L of k(O.type,P))P.includes(L)||P.push(L);return P}function y(X){let P=k(X);P=P.filter(L=>L!==X),P=[X].concat(P.sort());let O="";for(const L of P)O+=`${L}(${g[L].map(({name:$,type:G})=>`${G} ${$}`).join(",")})`;return O}function v(X){return S().keccak256(y(X))}function b(X,P){const O=[],L=[];O.push("bytes32"),L.push(v(X));for(const $ of g[X]){let G=P[$.name];if($.type==="string"||$.type==="bytes")O.push("bytes32"),G=S().keccak256(G),L.push(G);else if(g[$.type]!==void 0)O.push("bytes32"),G=S().keccak256(b($.type,G)),L.push(G);else{if($.type.lastIndexOf("]")===$.type.length-1)throw new Error("Arrays currently unimplemented in encodeData");O.push($.type),L.push(G)}}return ie().rawEncode(O,L)}function w(X,P){return S().keccak256(b(X,P))}function I(){return S().keccak256(Y.concat([Y.from("1901","hex"),w("EIP712Domain",c.domain),w(c.primaryType,c.message)]))}const R=S().ecsign(I(),d),{v:x,r:_,s:N}=R;return S().bufferToHex(Y.concat([S().setLengthLeft(_,32),S().setLengthLeft(N,32),S().toBuffer(x)]))},txRpcParamsToSpendInfo:r=>{const u={otherParams:r};return r.to!=null&&(u.publicAddress=r.to),r.value!=null?u.nativeAmount=(0,f.Z8)(r.value):u.nativeAmount="0",{currencyCode:this.currencyInfo.currencyCode,spendTargets:[u],networkFeeOption:"custom",customNetworkFee:{gasLimit:(0,f.Z8)(r.gas),gasPrice:(0,p.div)((0,f.Z8)(r.gasPrice),Z.toString(),18)},otherParams:r}}},this.otherMethods={txRpcParamsToSpendInfo:r=>D(this,null,function*(){return this.utils.txRpcParamsToSpendInfo(r)}),wcInit:(r,u="Edge")=>D(this,null,function*(){return yield(0,f.Vs)(new Promise((c,d)=>{const g=new F.Z({uri:r.uri,storageId:r.uri,clientMeta:{description:"Edge Wallet",url:"https://www.edge.app",icons:["https://content.edge.app/Edge_logo_Icon.png"],name:u}});g.on("session_request",(k,y)=>{if(k)throw this.error("Wallet connect session_request",k),k;const v=bt(y).params[0],b=ue(U({},v),{timeConnected:Date.now()/1e3});this.tools.walletConnectors[r.uri]={connector:g,wcProps:r,dApp:b},c(b)}),g.on("call_request",(k,y)=>{try{if(k)throw k;const v={uri:r.uri,dApp:this.tools.walletConnectors[r.uri].dApp,payload:y,walletId:this.tools.walletConnectors[r.uri].walletId};(y.method==="eth_sendTransaction"||y.method==="eth_signTransaction")&&(y.params=[U(U({},{gas:(0,f.X0)(this.otherData.networkFees.default.gasLimit.tokenTransaction),gasPrice:(0,f.X0)(this.otherData.networkFees.default.gasPrice.standardFeeHigh)}),y.params[0])]),this.currencyEngineCallbacks.onWcNewContractCall(v)}catch(v){throw this.warn("Wallet connect call_request ",v),v}}),g.on("disconnect",(k,y)=>{if(k!=null)throw k;delete this.tools.walletConnectors[r.uri]})}),5e3)}),wcConnect:(r,u,c)=>{this.tools.walletConnectors[r].connector.approveSession({accounts:[u],chainId:this.networkInfo.chainParams.chainId}),this.tools.walletConnectors[r].walletId=c},wcDisconnect:r=>{this.tools.walletConnectors[r].connector.killSession(),delete this.tools.walletConnectors[r]},wcApproveRequest:(r,u,c)=>D(this,null,function*(){this.tools.walletConnectors[r].connector.approveRequest({id:parseInt(u.id.toString()),jsonrpc:"2.0",result:c})}),wcRejectRequest:(r,u)=>D(this,null,function*(){this.tools.walletConnectors[r].connector.rejectRequest({id:parseInt(u.id.toString()),jsonrpc:"2.0",error:{message:"rejected"}})}),wcGetConnections:()=>Object.keys(this.tools.walletConnectors).filter(r=>this.tools.walletConnectors[r].walletId===this.walletInfo.id).map(r=>U(U({},this.tools.walletConnectors[r].dApp),this.tools.walletConnectors[r].wcProps))}}setOtherData(e){this.otherData=ft(e),this.otherData.networkFees.default.gasPrice==null&&(this.otherData.networkFees=U({},this.networkInfo.defaultNetworkFees))}updateNetworkFees(){return D(this,null,function*(){for(const e of this.externalFeeProviders)try{const t=yield e();if(t==null)continue;const s={};Object.keys(t).forEach(o=>{const i=o;s[i]=(0,f.Y7)(t[i])}),this.otherData.networkFees.default.gasPrice!=null&&(this.otherData.networkFees.default.gasPrice=U(U({},this.otherData.networkFees.default.gasPrice),s)),this.walletLocalDataDirty=!0;break}catch(t){this.error(`Error fetching fees from ${e.name}. ${JSON.stringify(t)}`)}})}updateL1RollupParams(){return D(this,null,function*(){if(this.l1RollupParams!=null){try{const e=yield this.ethNetwork.multicastServers("rollup_gasPrices"),t=Et(e.result.result),{l1GasPrice:s}=t;this.l1RollupParams=ue(U({},this.l1RollupParams),{gasPriceL1Wei:(0,p.ceil)((0,p.mul)((0,f.Z8)(s),this.l1RollupParams.maxGasPriceL1Multiplier),0)})}catch(e){this.log.warn("Failed to update l1GasPrice",e)}try{const e={to:this.l1RollupParams.oracleContractAddress,data:this.l1RollupParams.dynamicOverheadMethod},t=yield this.ethNetwork.multicastServers("eth_call",e),s=ce(t.result);this.l1RollupParams=ue(U({},this.l1RollupParams),{dynamicOverhead:(0,f.Z8)(s.result)})}catch(e){this.log.warn("Failed to update dynamicOverhead",e)}}})}clearBlockchainCache(){return D(this,null,function*(){yield Ee(de.prototype,this,"clearBlockchainCache").call(this),this.otherData.nextNonce="0",this.otherData.unconfirmedNextNonce="0",this.otherData.networkFees=this.networkInfo.defaultNetworkFees})}startEngine(){return D(this,null,function*(){var e;this.engineOn=!0;const t=(e=this.networkInfo.feeUpdateFrequencyMs)!=null?e:pe;this.infoFeeProvider().then(s=>{this.log.warn("infoFeeProvider:",JSON.stringify(s,null,2)),this.otherData.networkFees=(0,f.nu)(this.otherData.networkFees,s),this.walletLocalDataDirty=!0}).catch(()=>this.warn("Error fetching fees from Info Server")).finally(()=>D(this,null,function*(){return yield this.addToLoop("updateNetworkFees",t)})),this.addToLoop("updateL1RollupParams",Qe).catch(()=>{}),this.ethNetwork.needsLoop(),Ee(de.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return D(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getMaxSpendable(e){return D(this,null,function*(){const t=this.getBalance({currencyCode:e.currencyCode}),s=e.spendTargets[0].publicAddress;if(s==null)throw new Error("makeSpend Missing publicAddress");if(e.currencyCode===this.currencyInfo.currencyCode){const o=(i,l)=>{const a=(0,p.sub)(l,i);if((0,p.lte)(a,"1"))return i;const h=(0,p.add)(i,(0,p.div)(a,"2"));e.spendTargets[0].nativeAmount=h;const{gasPrice:r,gasLimit:u}=Xe(e,this.otherData.networkFees,this.currencyInfo,this.networkInfo),c=(0,p.mul)(r,u);let d="0";if(this.l1RollupParams!=null){const k={nonce:this.otherData.unconfirmedNextNonce,gasPriceL1Wei:this.l1RollupParams.gasPriceL1Wei,gasLimit:u,to:s,value:(0,f.X0)(h),chainParams:this.networkInfo.chainParams,dynamicOverhead:this.l1RollupParams.dynamicOverhead,fixedOverhead:this.l1RollupParams.fixedOverhead};d=He(k)}const g=(0,p.add)((0,p.add)(h,c),d);return(0,p.gt)(g,t)?o(i,h):o(h,l)};return o("0",(0,p.add)(t,"1"))}else return e.spendTargets[0].nativeAmount=t,yield this.makeSpend(e),this.getBalance({currencyCode:e.currencyCode})})}makeSpend(e){return D(this,null,function*(){var t,s,o,i;const{edgeSpendInfo:l,currencyCode:a,skipChecks:h}=this.makeSpendCheck(e),{pendingTxs:r=[]}=l;if(l.spendTargets.length!==1)throw new Error("Error: only one output allowed");const u=l.spendTargets[0],{publicAddress:c}=u;let{nativeAmount:d}=u;if(c==null)throw new Error("makeSpend Missing publicAddress");if(d==null)throw new A.$D;if(!S().isValidAddress(c))throw new TypeError(`Invalid ${this.currencyInfo.pluginId} address`);let g=(s=u.memo)!=null?s:(t=u.otherParams)==null?void 0:t.data;if(g!=null&&g.length>0&&!(0,f.vq)(g))throw new Error("Memo/data field must be of type 'hex'");g===""&&(g=void 0);const k=g!=null;let y;const v=Xe(l,this.otherData.networkFees,this.currencyInfo,this.networkInfo),b=v.gasPrice;let w=v.gasLimit;const I=v.useDefaults,R=w;let x;if(r.length>0){const Q=this.walletLocalData.otherData,re=this.walletLocalData.numUnconfirmedSpendTxs>0?Q.unconfirmedNextNonce:Q.nextNonce;x=(0,p.add)(re,r.length.toString())}let _,N;if(a===this.currencyInfo.currencyCode)y={from:[this.walletLocalData.publicKey],to:[c],gas:w,gasPrice:b,gasUsed:"0",nonceUsed:x,data:g},N=(0,f.X0)(d);else{if(g)_=c;else{const re=this.getTokenInfo(a);if(re==null||typeof re.contractAddress!="string")throw new Error("Error: Token not supported or invalid contract address");_=re.contractAddress,N=(0,f.X0)(d);const ve=ie().simpleEncode("transfer(address,uint256):(uint256)",c,N);N="0x0",g="0x"+Y.from(ve).toString("hex")}y={from:[this.walletLocalData.publicKey],to:[_],gas:w,gasPrice:b,gasUsed:"0",tokenRecipientAddress:c,nonceUsed:x,data:g}}if(I&&(this.lastEstimatedGasLimit.publicAddress!==c||this.lastEstimatedGasLimit.contractAddress!==_||this.lastEstimatedGasLimit.gasLimit==="")){const Q=[{to:_||c,from:this.walletLocalData.publicKey,gas:"0xffffff",value:N,data:g},"latest"];let re=!1;try{const Ve=(yield this.ethNetwork.multicastServers("eth_getCode",[_||c,"latest"])).result.result!=="0x";try{if(!Ve&&!k)w="21000";else{const Ze=yield this.ethNetwork.multicastServers("eth_estimateGas",Q);w=(0,p.add)(parseInt(Ze.result.result,16).toString(),"0"),Ve&&(w=(0,p.mul)(w,"2"))}re=!0}catch{if(k)throw new Error("Unable to estimate gas limit. Please try again later");this.networkInfo.defaultNetworkFees.default.gasLimit.tokenTransaction!=null&&(w=this.networkInfo.defaultNetworkFees.default.gasLimit.tokenTransaction)}if((0,p.lt)(w,"21000"))throw w=R,this.lastEstimatedGasLimit.gasLimit="",new Error("Calculated gasLimit less than minimum");re&&(this.lastEstimatedGasLimit={publicAddress:c,contractAddress:_,gasLimit:w})}catch(ve){this.error("makeSpend Error determining gas limit ",ve)}}else I&&(w=this.lastEstimatedGasLimit.gasLimit);y.gas=w;const X=(o=this.walletLocalData.totalBalances[this.currencyInfo.currencyCode])!=null?o:"0";let P=(0,p.mul)(b,w),O="0",L=null,$="0";if(this.l1RollupParams!=null){const Q={nonce:y.nonceUsed,gasPriceL1Wei:this.l1RollupParams.gasPriceL1Wei,gasLimit:y.gas,to:y.to[0],value:N,data:y.data,chainParams:this.networkInfo.chainParams,dynamicOverhead:this.l1RollupParams.dynamicOverhead,fixedOverhead:this.l1RollupParams.fixedOverhead};$=He(Q)}if(a===this.currencyInfo.currencyCode){if(P=(0,p.add)(P,$),O=(0,p.add)(P,d),!h&&(0,p.gt)(O,X))throw new A.C_;d=(0,p.mul)(O,"-1")}else{if(L=(0,p.add)(P,$),!h&&(0,p.gt)(P,X))throw new A.C_({currencyCode:this.currencyInfo.currencyCode,networkFee:P});const Q=(i=this.walletLocalData.totalBalances[a])!=null?i:"0";if(!h&&(0,p.gt)(d,Q))throw new A.C_;P="0",d=(0,p.mul)(d,"-1")}const G={txid:"",date:0,currencyCode:a,blockHeight:0,nativeAmount:d,networkFee:P,feeRateUsed:Pe(b,w),ourReceiveAddresses:[],signedTx:"",otherParams:y,walletId:this.walletId};return L&&(G.parentNetworkFee=L),G})}signMessage(e,t,s){return D(this,null,function*(){const o=Ce(this.currencyInfo.pluginId)(t);if(Ct(s.otherParams).typedData){const l=JSON.parse(e);try{return this.utils.signTypedData(l,o)}catch{return(0,te.signTypedData_v4)(Y.from(o.privateKey,"hex"),{data:l})}}return this.utils.signMessage(e,o)})}signTx(e,t){return D(this,null,function*(){const s=Ce(this.currencyInfo.pluginId)(t),o=(0,f.Xp)(e),i=(0,f.NC)(o.gas),l=(0,f.NC)(o.gasPrice);let a;if(e.currencyCode===this.currencyInfo.currencyCode){const w=(0,p.add)(e.nativeAmount,e.networkFee);a=(0,p.mul)("-1",w,16)}else a=(0,p.mul)("-1",e.nativeAmount,16);(0,p.lt)(a,"0")&&(a="0x00");let h=o.nonceUsed;if(!h)if(this.walletLocalData.numUnconfirmedSpendTxs&&(0,p.gt)(this.otherData.unconfirmedNextNonce,this.otherData.nextNonce)){const w=(0,p.sub)(this.otherData.unconfirmedNextNonce,this.otherData.nextNonce);if((0,p.lte)(w,"5"))h=this.otherData.unconfirmedNextNonce,this.walletLocalDataDirty=!0;else{const I=new Error("Excessive pending spend transactions");throw I.name="ErrorExcessivePendingSpends",I}}else h=this.otherData.nextNonce;const r=(0,f.NC)(h);let u;if(o.data!=null)u=o.data,e.currencyCode!==this.currencyInfo.currencyCode&&(a="0x00");else if(e.currencyCode===this.currencyInfo.currencyCode)u="";else{const w=ie().simpleEncode("transfer(address,uint256):(uint256)",o.tokenRecipientAddress,a);u="0x"+Y.from(w).toString("hex"),a="0x00"}const{chainParams:c}=this.networkInfo,d=J().custom(c),g={nonce:r,gasPrice:l,gasLimit:i,to:o.to[0],value:a,data:u},k=Y.from(s.privateKey,"hex"),y=V().fromPrivateKey(k);this.warn(`signTx getAddressString ${y.getAddressString()}`);const b=T.Transaction.fromTxData(g,{common:d}).sign(k);return e.signedTx=(0,f.$9)(b.serialize()),e.txid=(0,f.$9)(b.hash()),e.date=Date.now()/1e3,e.otherParams!=null&&(e.otherParams.nonceUsed=h),this.warn(`signTx
|
|
10
|
+
${(0,f.oX)(e)}`),e})}broadcastTx(e){return D(this,null,function*(){return yield this.ethNetwork.multicastServers("broadcastTx",e),this.warn(`SUCCESS broadcastTx
|
|
11
|
+
${(0,f.oX)(e)}`),e})}accelerate(e){return D(this,null,function*(){var t,s,o;const{currencyCode:i}=e,l=(0,n.Vk)(be)(e.otherParams);let a=e.txid,h=yield this.findTransaction(i,(0,f.f0)(a));if(h===-1&&((l==null?void 0:l.replacedTxid)!=null&&l.replacedTxid!==""&&(a=l.replacedTxid,h=yield this.findTransaction(i,(0,f.f0)(a))),h===-1))return null;const r=this.transactionList[i][h],u=(0,n.Vk)(be)(r.otherParams);if(r==null||r.blockHeight>0||u==null||u.nonceUsed==null||u.data!=null)return null;const c=((t=r.spendTargets)!=null?t:[])[0];if(c==null)return null;const d=(0,p.mul)(u.gasPrice,"2"),g=u.gas,k=ue(U({},u),{gas:g,gasPrice:d,replacedTxid:a});let{nativeAmount:y}=c,v=(0,p.mul)(d,g),b="0",w;const I=(s=this.walletLocalData.totalBalances[this.currencyInfo.currencyCode])!=null?s:"0";if(i===this.currencyInfo.currencyCode){if(b=(0,p.add)(v,y),(0,p.gt)(b,I))throw new A.C_;y=(0,p.mul)(b,"-1")}else{if(w=v,(0,p.gt)(v,I))throw new A.C_({currencyCode:this.currencyInfo.currencyCode,networkFee:v});const R=(o=this.walletLocalData.totalBalances[i])!=null?o:"0";if((0,p.gt)(y,R))throw new A.C_;v="0",y=(0,p.mul)(y,"-1")}return ue(U({},e),{txid:"",feeRateUsed:Pe(d,g),nativeAmount:y,networkFee:v,otherParams:k,parentNetworkFee:w})})}getDisplayPrivateSeed(e){return Ce(this.currencyInfo.pluginId)(e).privateKey}getDisplayPublicSeed(){return this.walletInfo.keys.publicKey}saveTx(e){return D(this,null,function*(){var t;const s=(0,n.Vk)(be)(e.otherParams);if((s==null?void 0:s.replacedTxid)!=null){const{currencyCode:o}=e,i=(0,f.f0)(s.replacedTxid),l=this.findTransaction(o,i);if(l!==-1){const a=this.transactionList[o][l],h=e.metadata,r=ue(U({},a),{metadata:h,blockHeight:-1});this.addTransaction(o,r)}}if(e.blockHeight===0){const o=(t=e.otherParams)==null?void 0:t.nonceUsed;o!=null&&(this.otherData.unconfirmedNextNonce=(0,p.add)(o,"1"))}Ee(de.prototype,this,"saveTx").call(this,e)})}addCustomToken(e){return D(this,null,function*(){const{contractAddress:t}=e;if(!(0,f.vq)(t)||(0,f.KT)(t).length!==40)throw new Error("ErrorInvalidContractAddress");yield Ee(de.prototype,this,"addCustomToken").call(this,e,t.toLowerCase())})}}function en(m,e,t,s){return D(this,null,function*(){const{currencyInfo:o,initOptions:i}=m,l=Pt(t),a=new de(m,e,l,i,s,o);return yield a.loadEngine(e,l,s),a})}var tn=Object.defineProperty,nn=Object.defineProperties,sn=Object.getOwnPropertyDescriptors,je=Object.getOwnPropertySymbols,rn=Object.prototype.hasOwnProperty,on=Object.prototype.propertyIsEnumerable,Me=(m,e,t)=>e in m?tn(m,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):m[e]=t,Ue=(m,e)=>{for(var t in e||(e={}))rn.call(e,t)&&Me(m,t,e[t]);if(je)for(var t of je(e))on.call(e,t)&&Me(m,t,e[t]);return m},We=(m,e)=>nn(m,sn(e)),se=(m,e,t)=>new Promise((s,o)=>{var i=h=>{try{a(t.next(h))}catch(r){o(r)}},l=h=>{try{a(t.throw(h))}catch(r){o(r)}},a=h=>h.done?s(h.value):Promise.resolve(h.value).then(i,l);a((t=t.apply(m,e)).next())});class Je{constructor(e){const{builtinTokens:t,currencyInfo:s,io:o,networkInfo:i}=e;this.builtinTokens=t,this.currencyInfo=s,this.io=o,this.networkInfo=i,this.walletConnectors={}}importPrivateKey(e){return se(this,null,function*(){const{pluginId:t}=this.currencyInfo,{pluginMnemonicKeyName:s,pluginRegularKeyName:o}=this.networkInfo;if(/^(0x)?[0-9a-fA-F]{64}$/.test(e)){const i=ee.Buffer.from(e.replace(/^0x/,""),"hex");if(!S().isValidPrivate(i))throw new Error("Invalid private key");const l=i.toString("hex"),a={[o]:l};return this.derivePublicKey({type:`wallet:${t}`,id:"fake",keys:a}),a}else{if(!(0,q.validateMnemonic)(e))throw new Error("Invalid input");const i=yield this._mnemonicToHex(e);return{[s]:e,[o]:i}}})}createPrivateKey(e){return se(this,null,function*(){const{pluginMnemonicKeyName:t,pluginRegularKeyName:s}=this.networkInfo;if(e.replace("wallet:","")!==this.currencyInfo.pluginId)throw new Error("InvalidWalletType");const i=ee.Buffer.from(this.io.random(32)),l=(0,q.entropyToMnemonic)(i),a=yield this._mnemonicToHex(l);return{[t]:l,[s]:a}})}derivePublicKey(e){return se(this,null,function*(){const{pluginId:t}=this.currencyInfo,{hdPathCoinType:s,pluginMnemonicKeyName:o,pluginRegularKeyName:i}=this.networkInfo;if(e.type!==`wallet:${t}`)throw new Error("Invalid wallet type");let l;if(e.keys[o]!=null){const a=(0,q.mnemonicToSeedSync)(e.keys[o]),h=oe().fromMasterSeed(a),r=`m/44'/${s}'/0'/0/`,d=h.derivePath(r+0).getWallet().getPublicKey();l=`0x${S().pubToAddress(d).toString("hex")}`}else{const a=ee.Buffer.from(e.keys[i].replace(/^0x/,""),"hex");if(!S().isValidPrivate(a))throw new Error("Invalid private key");l=`0x${S().privateToAddress(a).toString("hex")}`}if(!S().isValidAddress(l))throw new Error("Invalid address");return{publicKey:l}})}_mnemonicToHex(e){return se(this,null,function*(){const{hdPathCoinType:t}=this.networkInfo,s=oe().fromMasterSeed((0,q.mnemonicToSeedSync)(e)),o=`m/44'/${t}'/0'/0/`;return s.derivePath(o+0).getWallet().getPrivateKeyString().replace(/^0x/,"")})}parseUri(e,t,s){return se(this,null,function*(){var o,i,l,a,h;const r={wc:!0};this.networkInfo.uriNetworks.forEach(y=>{r[y]=!0});const{parsedUri:u,edgeParsedUri:c}=(0,H.k)(this.currencyInfo,e,r,t||this.currencyInfo.currencyCode,s);if(u.protocol==="wc"){if(u.query.bridge!=null&&u.query.key!=null)return c.walletConnect={uri:e,topic:u.pathname.split("@")[0],version:u.pathname.split("@")[1],bridge:u.query.bridge,key:u.query.key},c;throw new Error("MissingWcBridgeKey")}let d="";c.publicAddress&&(d=c.publicAddress,c.publicAddress=c.publicAddress.toLowerCase());let[g,k]=d.split("-");if(k||(k=g,g="pay"),d=k,/[A-F]/.test(d)&&!S().isValidChecksumAddress(d))throw new Error("InvalidPublicAddressError");if(d=d.toLowerCase(),!S().isValidAddress(d||""))throw new Error("InvalidPublicAddressError");if(g==="token"||g==="token_info"){if(!u.query)throw new Error("InvalidUriError");const y=(o=u.query.symbol)!=null?o:"SYM";if(y.length<2||y.length>5)throw new Error("Wrong Token symbol");const v=(i=u.query.name)!=null?i:y,b=(l=u.query.decimals)!=null?l:"18";let w="1000000000000000000";const I=parseInt(b);if(I<0||I>18)throw new Error("Wrong number of decimals");w="1"+"0".repeat(I);const R=(a=u.query.type)!=null?a:this.networkInfo.ercTokenStandard;return{token:{currencyCode:y,contractAddress:k.toLowerCase(),currencyName:v,multiplier:w,denominations:[{name:y,multiplier:w}],type:R.toUpperCase()}}}if(g==="pay"){const y=d,v=u.pathname.split("/")[1],b=u.query;switch(v){case"transfer":{const w=(h=b.address)!=null?h:"",I=y!=null?y:"",R=b.uint256!=null?(0,f.EE)(b.uint256):c.nativeAmount,x=this.currencyInfo.metaTokens.find(_=>_.contractAddress===I);if(t!=null&&(x==null||x.currencyCode!==t))throw new Error("InternalErrorInvalidCurrencyCode");if(!S().isValidAddress(w))throw new Error("InvalidPublicAddressError");if(!S().isValidAddress(I))throw new Error("InvalidContractAddressError");return We(Ue({},c),{currencyCode:x==null?void 0:x.currencyCode,nativeAmount:R,publicAddress:w})}case void 0:{const w=y,I=b.value!=null?(0,f.EE)(b.value):c.nativeAmount;return We(Ue({},c),{publicAddress:w,nativeAmount:I})}default:throw new Error("UnsupportedContractFunction")}}throw new Error("InvalidUriError")})}encodeUri(e,t){return se(this,null,function*(){const{publicAddress:s,nativeAmount:o,currencyCode:i}=e;if(!S().isValidAddress(s))throw new Error("InvalidPublicAddressError");let a;if(typeof o=="string"){const r=(0,f.cp)(this.currencyInfo,i||this.currencyInfo.currencyCode,t);if(r==null)throw new Error("InternalErrorInvalidCurrencyCode");a=(0,p.div)(o,r.multiplier,18)}return(0,H.Q)(e,this.currencyInfo.pluginId,a)})}getSplittableTypes(e){return Object.keys(j.j).map(t=>`wallet:${t}`)}getTokenId(e){return se(this,null,function*(){(0,K.Rp)(e);const t=(0,K.Oj)(e.networkLocation);if(t==null||!S().isValidAddress(t.contractAddress))throw new Error("ErrorInvalidContractAddress");return t.contractAddress.toLowerCase().replace(/^0x/,"")})}}function an(m){return se(this,null,function*(){const e=new Je(m),t=(0,z.$o)();return t!=null&&t.clear(),e})}},89214:function(){},52361:function(){},94616:function(){},88924:function(){},55024:function(){}}]);
|