edge-currency-accountbased 2.2.3 → 2.3.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.
Files changed (88) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/android/src/main/assets/edge-currency-accountbased/234.chunk.js +35 -0
  3. package/android/src/main/assets/edge-currency-accountbased/248.chunk.js +35 -0
  4. package/android/src/main/assets/edge-currency-accountbased/336.chunk.js +9 -0
  5. package/android/src/main/assets/edge-currency-accountbased/612.chunk.js +1 -0
  6. package/android/src/main/assets/edge-currency-accountbased/{945.chunk.js → 814.chunk.js} +8 -8
  7. package/android/src/main/assets/edge-currency-accountbased/935.chunk.js +1 -1
  8. package/android/src/main/assets/edge-currency-accountbased/94.chunk.js +8 -0
  9. package/android/src/main/assets/edge-currency-accountbased/algorand.chunk.js +2 -2
  10. package/android/src/main/assets/edge-currency-accountbased/bnb.chunk.js +4 -4
  11. package/android/src/main/assets/edge-currency-accountbased/edge-currency-accountbased.js +10 -10
  12. package/android/src/main/assets/edge-currency-accountbased/eos.chunk.js +12 -12
  13. package/android/src/main/assets/edge-currency-accountbased/ethereum.chunk.js +5 -5
  14. package/android/src/main/assets/edge-currency-accountbased/filecoin.chunk.js +1 -1
  15. package/android/src/main/assets/edge-currency-accountbased/fio.chunk.js +2 -2
  16. package/android/src/main/assets/edge-currency-accountbased/hedera.chunk.js +2 -2
  17. package/android/src/main/assets/edge-currency-accountbased/polkadot.chunk.js +2 -2
  18. package/android/src/main/assets/edge-currency-accountbased/ripple.chunk.js +5 -5
  19. package/android/src/main/assets/edge-currency-accountbased/solana.chunk.js +3 -3
  20. package/android/src/main/assets/edge-currency-accountbased/stellar.chunk.js +4 -4
  21. package/android/src/main/assets/edge-currency-accountbased/tezos.chunk.js +3 -3
  22. package/android/src/main/assets/edge-currency-accountbased/tron.chunk.js +1 -1
  23. package/android/src/main/assets/edge-currency-accountbased/zcash.chunk.js +2 -2
  24. package/lib/algorand/AlgorandEngine.js +46 -24
  25. package/lib/algorand/algorandInfo.js +8 -7
  26. package/lib/algorand/algorandTestnetInfo.js +8 -7
  27. package/lib/binance/BinanceEngine.js +19 -17
  28. package/lib/binance/binanceInfo.js +10 -7
  29. package/lib/common/types.js +10 -0
  30. package/lib/common/upgradeMemos.js +52 -0
  31. package/lib/common/utf8.js +32 -0
  32. package/lib/common/validateMemos.js +107 -0
  33. package/lib/eos/EosEngine.js +42 -41
  34. package/lib/eos/info/eosCommonInfo.js +10 -0
  35. package/lib/eos/info/eosInfo.js +15 -17
  36. package/lib/eos/info/telosInfo.js +15 -15
  37. package/lib/eos/info/waxInfo.js +15 -16
  38. package/lib/ethereum/EthereumEngine.js +13 -12
  39. package/lib/ethereum/EthereumNetwork.js +16 -14
  40. package/lib/ethereum/info/avalancheInfo.js +17 -7
  41. package/lib/ethereum/info/binancesmartchainInfo.js +9 -7
  42. package/lib/ethereum/info/celoInfo.js +9 -7
  43. package/lib/ethereum/info/ethDevInfo.js +9 -7
  44. package/lib/ethereum/info/ethereumCommonInfo.js +10 -0
  45. package/lib/ethereum/info/ethereumInfo.js +17 -7
  46. package/lib/ethereum/info/ethereumclassicInfo.js +9 -7
  47. package/lib/ethereum/info/ethereumpowInfo.js +9 -7
  48. package/lib/ethereum/info/fantomInfo.js +9 -7
  49. package/lib/ethereum/info/goerliInfo.js +9 -7
  50. package/lib/ethereum/info/kovanInfo.js +9 -7
  51. package/lib/ethereum/info/optimismInfo.js +9 -7
  52. package/lib/ethereum/info/polygonInfo.js +9 -7
  53. package/lib/ethereum/info/pulsechainInfo.js +9 -7
  54. package/lib/ethereum/info/rinkebyInfo.js +9 -7
  55. package/lib/ethereum/info/ropstenInfo.js +9 -7
  56. package/lib/ethereum/info/rskInfo.js +9 -7
  57. package/lib/ethereum/info/zksyncInfo.js +9 -7
  58. package/lib/filecoin/FilecoinEngine.js +125 -87
  59. package/lib/filecoin/Filfox.js +68 -1
  60. package/lib/filecoin/filecoinInfo.js +5 -7
  61. package/lib/fio/FioEngine.js +25 -17
  62. package/lib/fio/fioInfo.js +8 -6
  63. package/lib/hedera/HederaEngine.js +22 -18
  64. package/lib/hedera/hederaInfo.js +11 -8
  65. package/lib/hedera/hederaTestnetInfo.js +6 -6
  66. package/lib/polkadot/PolkadotEngine.js +15 -9
  67. package/lib/polkadot/info/liberlandInfo.js +3 -2
  68. package/lib/polkadot/info/liberlandTestnetInfo.js +3 -2
  69. package/lib/polkadot/info/polkadotInfo.js +8 -5
  70. package/lib/ripple/RippleEngine.js +53 -75
  71. package/lib/ripple/rippleInfo.js +16 -8
  72. package/lib/solana/SolanaEngine.js +17 -12
  73. package/lib/solana/solanaInfo.js +9 -5
  74. package/lib/stellar/StellarEngine.js +31 -22
  75. package/lib/stellar/stellarInfo.js +16 -7
  76. package/lib/tezos/TezosEngine.js +17 -11
  77. package/lib/tezos/tezosInfo.js +8 -5
  78. package/lib/tron/TronEngine.js +85 -68
  79. package/lib/tron/tronInfo.js +8 -7
  80. package/lib/zcash/ZcashEngine.js +23 -23
  81. package/lib/zcash/piratechainInfo.js +8 -6
  82. package/lib/zcash/zcashInfo.js +7 -6
  83. package/package.json +2 -2
  84. package/android/src/main/assets/edge-currency-accountbased/124.chunk.js +0 -35
  85. package/android/src/main/assets/edge-currency-accountbased/223.chunk.js +0 -9
  86. package/android/src/main/assets/edge-currency-accountbased/650.chunk.js +0 -1
  87. package/android/src/main/assets/edge-currency-accountbased/689.chunk.js +0 -8
  88. package/android/src/main/assets/edge-currency-accountbased/826.chunk.js +0 -35
@@ -1 +1 @@
1
- "use strict";(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[518],{58355:function(U,H,u){var f=u(35717),g=u(51031),O=u(71027),_=u(89509).Buffer,e=u(78028),b=u(79785),w=u(89072),y=_.alloc(128);function x(C,h){O.call(this,"digest"),typeof h=="string"&&(h=_.from(h));var T=C==="sha512"||C==="sha384"?128:64;if(this._alg=C,this._key=h,h.length>T){var B=C==="rmd160"?new b:w(C);h=B.update(h).digest()}else h.length<T&&(h=_.concat([h,y],T));for(var X=this._ipad=_.allocUnsafe(T),p=this._opad=_.allocUnsafe(T),m=0;m<T;m++)X[m]=h[m]^54,p[m]=h[m]^92;this._hash=C==="rmd160"?new b:w(C),this._hash.update(X)}f(x,O),x.prototype._update=function(C){this._hash.update(C)},x.prototype._final=function(){var C=this._hash.digest(),h=this._alg==="rmd160"?new b:w(this._alg);return h.update(this._opad).update(C).digest()},U.exports=function(h,T){return h=h.toLowerCase(),h==="rmd160"||h==="ripemd160"?new x("rmd160",T):h==="md5"?new g(e,T):new x(h,T)}},51031:function(U,H,u){var f=u(35717),g=u(89509).Buffer,O=u(71027),_=g.alloc(128),e=64;function b(w,y){O.call(this,"digest"),typeof y=="string"&&(y=g.from(y)),this._alg=w,this._key=y,y.length>e?y=w(y):y.length<e&&(y=g.concat([y,_],e));for(var x=this._ipad=g.allocUnsafe(e),C=this._opad=g.allocUnsafe(e),h=0;h<e;h++)x[h]=y[h]^54,C[h]=y[h]^92;this._hash=[x]}f(b,O),b.prototype._update=function(w){this._hash.push(w)},b.prototype._final=function(){var w=this._alg(g.concat(this._hash));return this._alg(g.concat([this._opad,w]))},U.exports=b},79014:function(U,H,u){u.d(H,{Q:function(){return X},k:function(){return B}});var f=u(77591),g=u.n(f),O=u(24350),_=u(84564),e=u.n(_),b=u(76714),w=Object.defineProperty,y=Object.getOwnPropertySymbols,x=Object.prototype.hasOwnProperty,C=Object.prototype.propertyIsEnumerable,h=(p,m,P)=>m in p?w(p,m,{enumerable:!0,configurable:!0,writable:!0,value:P}):p[m]=P,T=(p,m)=>{for(var P in m||(m={}))x.call(m,P)&&h(p,P,m[P]);if(y)for(var P of y(m))C.call(m,P)&&h(p,P,m[P]);return p};function B(p,m,P,I,R=[]){const v=T({},e()(m,{},!0)),$=m.startsWith(`${p.pluginId}://`);if(v.protocol!=null&&(v.protocol=v.protocol.replace(":","")),v.protocol!=null&&v.protocol!==""&&!P[v.protocol])throw new Error(`Uri protocol '${v.protocol}' is not supported for ${p.pluginId}.`);if(v.host===""&&v.pathname==="")throw new Error("Path and host not found in uri.");const A={publicAddress:v.host!==""?v.host:v.pathname.split("/")[0]},J=v.query.label,G=v.query.message,F=v.query.category;(J!=null||G!=null||F!=null||$)&&(A.metadata={},A.metadata.name=J,A.metadata.notes=G,A.metadata.category=F,A.metadata.gateway=$!=null?$:!1);const K=v.query.amount;if(K!=null&&typeof K=="string"){I==null&&(I=p.currencyCode);const j=(0,b.Qs)(I!=null?I:"",p,R);if(j==null)throw new Error("InternalErrorInvalidCurrencyCode");let L=(0,f.mul)(K,j.multiplier);L=(0,f.toFixed)(L,0,0),A.nativeAmount=L,A.currencyCode=I}return{edgeParsedUri:A,parsedUri:v}}function X(p,m,P){if(p.publicAddress==null)throw new Error("InvalidPublicAddressError");if(P==null&&p.label==null&&p.message==null)return p.publicAddress;{let I="";P!=null&&(I+="amount="+P+"&"),(p.label!=null||p.message!=null)&&(typeof p.label=="string"&&(I+="label="+p.label+"&"),typeof p.message=="string"&&(I+="message="+p.message+"&")),I=I.substr(0,I.length-1);const R={scheme:m,path:p.publicAddress,query:I};return(0,O.qC)(R)}}},12636:function(U,H,u){u.r(H),u.d(H,{FilecoinTools:function(){return Z},makeCurrencyEngine:function(){return Pe},makeCurrencyTools:function(){return we}});var f=u(23145),g=u(77591),O=u(37786),_=u(2153),e=u(82448),b=u(35620),w=u(79014),y=u(76714),x=u(62177);const C=(0,e.su)({}),h=(0,e.su)({sigJson:(0,e.Zz)((0,e.su)({Data:e.XC,Type:(0,e.Wf)(1,3)})),txJson:(0,e.su)({To:e.XC,From:e.XC,Nonce:e.mH,Value:e.XC,GasLimit:e.mH,GasFeeCap:e.XC,GasPremium:e.XC,Method:e.mH,Params:e.XC})}),T=(0,e.su)({address:e.XC,publicKey:e.XC}),B=(0,x.jd)(T),X=c=>{const t=(0,e.su)({[`${c}Mnemonic`]:e.XC,[`${c}Key`]:e.XC});return(0,e.W1)(s=>{const o=t(s);return{mnemonic:o[`${c}Mnemonic`],privateKey:o[`${c}Key`]}},s=>({[`${c}Mnemonic`]:s.mnemonic,[`${c}Key`]:s.privateKey}))};var p=u(94935),m=u(84650),P=(c,t,s)=>new Promise((o,n)=>{var a=r=>{try{l(s.next(r))}catch(d){n(d)}},i=r=>{try{l(s.throw(r))}catch(d){n(d)}},l=r=>r.done?o(r.value):Promise.resolve(r.value).then(a,i);l((s=s.apply(c,t)).next())});const I=(0,e.su)({statusCode:e.mH,message:e.XC,error:e.XC}),R=c=>(0,e.$e)((0,e._C)(I,c)),v=(0,e.su)({cid:e.XC,from:e.XC,height:e.mH,method:e.XC,nonce:e.mH,reciept:(0,e.su)({exitCode:e.mH}),timestamp:e.mH,to:e.XC,value:e.XC}),$=(0,e.su)({messages:(0,e._2)(v),totalCount:e.mH});class z{constructor(t,s){this.baseUrl=t,this.fetch=s}getAccountMessages(t,s,o=20){return P(this,null,function*(){const n=new URL(`${this.baseUrl}/address/${t}/messages`),a=new URLSearchParams({page:s.toString(),pageSize:o.toString()});n.search=a.toString();const l=yield(yield this.fetch(n.toString(),{method:"GET",headers:{"content-type":"application/json"}})).text(),r=R($)(l);if("error"in r)throw new Error(`Error response code ${r.statusCode}: ${r.message} ${r.error}`);return r})}}var A=(c,t,s)=>new Promise((o,n)=>{var a=r=>{try{l(s.next(r))}catch(d){n(d)}},i=r=>{try{l(s.throw(r))}catch(d){n(d)}},l=r=>r.done?o(r.value):Promise.resolve(r.value).then(a,i);l((s=s.apply(c,t)).next())});const J=c=>(0,e.su)({result:c}),G=(0,e.su)({code:e.mH,message:e.XC}),F=c=>(0,e.$e)((0,e._C)(G,J(c))),K=(0,e.su)({height:e.mH,block_time:e.mH,cid:e.XC,from:e.XC,to:e.XC,value:e.XC,exit_code:e.XC,method_name:e.XC}),j=(0,e.su)({account_type:e.XC,account_info:(0,e.su)({account_basic:(0,e.su)({account_id:e.XC,account_address:e.XC,account_type:e.XC,account_balance:e.XC,nonce:e.mH,code_cid:e.XC,create_time:e.XC,latest_transfer_time:e.XC})})}),L=(0,e.su)({messages_by_account_id_list:(0,e.Vk)((0,e._2)(K),()=>[]),total_count:e.mH}),q=(0,e.su)({MessageDetails:(0,e.su)({message_basic:(0,e.su)({height:e.mH,block_time:e.mH,cid:e.XC,from:e.XC,to:e.XC,value:e.XC,exit_code:e.XC,method_name:e.XC}),blk_cids:(0,e._2)(e.XC),consume_list:(0,e._2)((0,e.su)({from:e.XC,to:e.XC,value:e.XC,consume_type:e.XC})),version:e.mH,nonce:e.mH,gas_fee_cap:e.XC,gas_premium:e.XC,gas_limit:e.mH,gas_used:e.XC,base_fee:e.XC,all_gas_fee:e.XC,eth_message:e.XC})});class ee{constructor(t,s){this.baseUrl=t,this.fetch=s}getAccountInfo(t){return A(this,null,function*(){const o=yield(yield this.fetch(`${this.baseUrl}/AccountInfoByID`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({account_id:t})})).text(),n=F(j)(o);if(!("result"in n))throw new Error(`Error response code ${n.code}: ${n.message}`);return n.result})}getAccountMessages(t,s,o=20){return A(this,null,function*(){const a=yield(yield this.fetch(`${this.baseUrl}/MessagesByAccountID`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({account_id:t,address:"",filters:{index:s,page:0,limit:o,method_name:""}})})).text(),i=F(L)(a);if(!("result"in i))throw new Error(`Error response code ${i.code}: ${i.message}`);return i.result})}getMessageDetails(t){return A(this,null,function*(){const o=yield(yield this.fetch(`${this.baseUrl}/MessageDetails`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({message_cid:t})})).text(),n=F(q)(o);if(!("result"in n))throw new Error(`Error response code ${n.code}: ${n.message}`);return n.result})}}var te=Math.pow,se=(c,t,s)=>new Promise((o,n)=>{var a=r=>{try{l(s.next(r))}catch(d){n(d)}},i=r=>{try{l(s.throw(r))}catch(d){n(d)}},l=r=>r.done?o(r.value):Promise.resolve(r.value).then(a,i);l((s=s.apply(c,t)).next())});const ne=c=>(0,e.su)({id:e.mH,jsonrpc:e.XC,result:c}),re=(0,e.su)({id:e.mH,jsonrpc:e.XC,error:(0,e.su)({code:e.mH,message:e.XC})}),oe=c=>(0,e.$e)((0,e._C)(re,ne(c))),ie=(0,e.su)({Height:e.mH});class ae{constructor(t,s){this.baseUrl=t,this.fetch=s}getChainHead(){return se(this,null,function*(){const t=Math.floor(Math.random()*te(10,8)),o=yield(yield this.fetch(this.baseUrl,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({id:t,jsonrpc:"2.0",method:"Filecoin.ChainHead",params:null})})).text(),n=oe(ie)(o);if("error"in n)throw new Error(`Error response code ${n.error.code}: ${n.error.message}`);return n})}}var ce=Object.defineProperty,le=Object.defineProperties,ue=Object.getOwnPropertyDescriptors,Y=Object.getOwnPropertySymbols,de=Object.getPrototypeOf,he=Object.prototype.hasOwnProperty,fe=Object.prototype.propertyIsEnumerable,pe=Reflect.get,Q=(c,t,s)=>t in c?ce(c,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):c[t]=s,me=(c,t)=>{for(var s in t||(t={}))he.call(t,s)&&Q(c,s,t[s]);if(Y)for(var s of Y(t))fe.call(t,s)&&Q(c,s,t[s]);return c},ge=(c,t)=>le(c,ue(t)),N=(c,t,s)=>pe(de(c),s,t),E=(c,t,s)=>new Promise((o,n)=>{var a=r=>{try{l(s.next(r))}catch(d){n(d)}},i=r=>{try{l(s.throw(r))}catch(d){n(d)}},l=r=>r.done?o(r.value):Promise.resolve(r.value).then(a,i);l((s=s.apply(c,t)).next())});const ye=15e3,ve=3e4,Ce=15e3;class M extends m.P{constructor(t,s,o,n){super(t,s,o,n),this.filfoxMessageToEdgeTransaction=i=>{const l=this.address.toString();let r=i.value;const d=[],S="0";return i.to!==l?r=`-${(0,g.add)(r,S)}`:d.push(l),{txid:i.cid,date:i.timestamp,currencyCode:this.currencyInfo.currencyCode,blockHeight:i.height,nativeAmount:r,isSend:r.startsWith("-"),networkFee:S,ourReceiveAddresses:d,signedTx:"",otherParams:{},walletId:this.walletId}};const{networkInfo:a}=t;this.address=f.kL.fromString(o.keys.address),this.availableAttoFil="0",this.filRpc=new f.rP(t.networkInfo.rpcNode.networkName,{url:t.networkInfo.rpcNode.url,token:t.currencyInfo.currencyCode}),this.filfoxApi=new z(t.networkInfo.filfoxUrl,t.io.fetchCors),this.filscanApi=new ee(t.networkInfo.filscanUrl,t.io.fetchCors),this.rpcExtra=new ae(t.networkInfo.rpcNode.url,t.io.fetchCors),this.networkInfo=a,this.pluginId=this.currencyInfo.pluginId}setOtherData(t){this.otherData=C(t)}initData(){this.availableAttoFil="0"}initSubscriptions(){this.addToLoop("checkBalance",ye).catch(t=>this.log(t)),this.addToLoop("checkBlockHeight",ve).catch(t=>this.log(t)),this.addToLoop("checkTransactions",Ce).catch(t=>this.log(t))}onUpdateBlockHeight(t){this.walletLocalData.blockHeight!==t&&(this.walletLocalData.blockHeight=t,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight))}onUpdateTransactions(){this.transactionsChangedArray.length>0&&(this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[])}startEngine(){return E(this,null,function*(){this.initData(),this.initSubscriptions(),yield N(M.prototype,this,"startEngine").call(this)})}killEngine(){return E(this,null,function*(){yield N(M.prototype,this,"killEngine").call(this)})}clearBlockchainCache(){return E(this,null,function*(){yield N(M.prototype,this,"clearBlockchainCache").call(this)})}resyncBlockchain(){return E(this,null,function*(){yield N(M.prototype,this,"killEngine").call(this),yield this.clearBlockchainCache(),yield this.startEngine()})}getFreshAddress(){return E(this,null,function*(){const{address:t}=this.walletInfo.keys;return{publicAddress:t}})}getMaxSpendable(t){return E(this,null,function*(){const o=(yield this.makeSpend(t)).networkFee,n=(0,g.sub)(this.availableAttoFil,o);if((0,g.lte)(n,"0"))throw new p.C_;return n})}makeSpend(t){return E(this,null,function*(){const{edgeSpendInfo:s,currencyCode:o}=this.makeSpendCheck(t),n=s.spendTargets[0],{publicAddress:a,nativeAmount:i}=n;if(a==null)throw new Error("Missing publicAddress in EdgeSpendInfo");if(i==null)throw new p.$D;const l=f.kL.fromString(a),r=f.YW.getNew(l,this.address,f.WU.fromAtto(i),0);yield r.prepareToSend(this.filRpc);const d=r.toJSON(),S={sigJson:void 0,txJson:d},k=(0,g.mul)(d.GasLimit.toString(),d.GasPremium),W=(0,g.add)(i,k);return{txid:"",date:0,currencyCode:o,blockHeight:0,nativeAmount:`-${W}`,isSend:i.startsWith("-"),networkFee:k,ourReceiveAddresses:[],otherParams:S,signedTx:"",walletId:this.walletId}})}signTx(t,s){return E(this,null,function*(){const o=h(t.otherParams),n=f.YW.fromJSON(o.txJson),a=X(this.pluginId)(s),i=f.w5.deriveAccount(a.mnemonic,f.BG.SECP256K1,this.tools.derivationPath),l=yield f.w5.signTransaction(i,n);return t.otherParams=ge(me({},t.otherParams),{sigJson:l.toJSON()}),t})}broadcastTx(t,s){return E(this,null,function*(){const o=h(t.otherParams);if(o.sigJson==null)throw new Error("Cannot broadcast unsigned transaction");const n=f.Pc.fromJSON(o.sigJson),a=f.YW.fromJSON(o.txJson),i=yield this.filRpc.broadcastTransaction(a,n);if("error"in i)throw new Error(i.error.message);return t.txid=i.result["/"],t})}getDisplayPrivateSeed(t){return X(this.pluginId)(t).mnemonic}getDisplayPublicSeed(){return this.walletInfo.keys.publicKey}loadEngine(){return E(this,null,function*(){yield N(M.prototype,this,"loadEngine").call(this),this.engineOn=!0})}checkBalance(){return E(this,null,function*(){const t=yield this.filRpc.walletBalance(this.address);if("error"in t)throw new Error(t.error.message);const{result:s}=t;this.availableAttoFil=s,this.updateBalance(this.currencyInfo.currencyCode,s),this.tokenCheckBalanceStatus[this.currencyInfo.currencyCode]=1,this.updateOnAddressesChecked(),this.walletLocalDataDirty=!0})}checkBlockHeight(){return E(this,null,function*(){const s=(yield this.rpcExtra.getChainHead()).result.Height;this.onUpdateBlockHeight(s)})}checkTransactions(){return E(this,null,function*(){const t=this.address.toString(),s=a=>{const i=this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode],l=a;i<1&&(l>=1||l>i*1.1)&&(this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=l,this.updateOnAddressesChecked())},o=({tx:a,progress:i})=>{this.addTransaction(this.currencyInfo.currencyCode,a),this.onUpdateTransactions(),this.walletLocalData.blockHeight<a.blockHeight&&this.onUpdateBlockHeight(a.blockHeight),s(i)},n=[this.scanTransactionsFromFilscan(t,o),this.scanTransactionsFromFilfox(t,o)];yield Promise.all(n),s(1)})}scanTransactionsFromFilfox(t,s){return E(this,null,function*(){let n=0,a=0,i=-1;do{const l=yield this.filfoxApi.getAccountMessages(t,n++,20);i=i===-1?l.totalCount:i;const r=l.messages;for(const d of r){const S=d.cid;if(this.findTransaction(this.currencyInfo.currencyCode,S)>=0)return;const W=this.filfoxMessageToEdgeTransaction(d),V=i===0?1:++a/i;s({tx:W,progress:V})}}while(a<i)})}scanTransactionsFromFilscan(t,s){return E(this,null,function*(){let n=0,a=0,i=-1;do{const l=yield this.filscanApi.getAccountMessages(t,n++,20);i=i===-1?l.total_count:i;const r=l.messages_by_account_id_list;for(const d of r){const S=d.cid;if(this.findTransaction(this.currencyInfo.currencyCode,S)>=0)return;const W=this.filscanMessageToEdgeTransaction(d),V=i===0?1:++a/i;s({tx:W,progress:V})}}while(a<i)})}filscanMessageToEdgeTransaction(t){const s=this.address.toString();let o=t.value;const n=[],a="0";return t.to!==s?o=`-${(0,g.add)(o,a)}`:n.push(s),{txid:t.cid,date:t.block_time,currencyCode:this.currencyInfo.currencyCode,blockHeight:t.height,nativeAmount:o,isSend:o.startsWith("-"),networkFee:a,ourReceiveAddresses:n,signedTx:"",otherParams:{},walletId:this.walletId}}}function Pe(c,t,s,o){return E(this,null,function*(){const n=B(s),a=new M(c,t,n,o);return yield a.loadEngine(),a})}var D=(c,t,s)=>new Promise((o,n)=>{var a=r=>{try{l(s.next(r))}catch(d){n(d)}},i=r=>{try{l(s.throw(r))}catch(d){n(d)}},l=r=>r.done?o(r.value):Promise.resolve(r.value).then(a,i);l((s=s.apply(c,t)).next())});class Z{constructor(t){const{builtinTokens:s,currencyInfo:o,io:n,networkInfo:a}=t;this.builtinTokens=s,this.currencyInfo=o,this.io=n,this.networkInfo=a,this.derivationPath=`m/44'/${this.networkInfo.hdPathCoinType}'/0'/0/0`}isValidAddress(t){return D(this,null,function*(){try{return f.kL.fromString(t),!0}catch{return!1}})}importPrivateKey(t){return D(this,arguments,function*(s,o={}){const{pluginId:n}=this.currencyInfo;if(!(0,_.validateMnemonic)(s))throw new Error("Invalid mnemonic");const a=(yield(0,_.mnemonicToSeed)(s)).toString("hex");return{[`${n}Key`]:a,[`${n}Mnemonic`]:s}})}createPrivateKey(t){return D(this,null,function*(){const{pluginId:s}=this.currencyInfo;if(t!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const o=b.YU.stringify(this.io.random(32)),n=(0,_.entropyToMnemonic)(o);return{[`${s}Key`]:o,[`${s}Mnemonic`]:n}})}checkPublicKey(t){return D(this,null,function*(){return(0,e.Vk)(T)(t)!=null})}derivePublicKey(t){return D(this,null,function*(){if(t.type!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const{pluginId:s}=this.currencyInfo,{hdPathCoinType:o}=this.networkInfo,n=X(s)(t.keys),a=yield(0,_.mnemonicToSeed)(n.mnemonic),d=(0,O.fromSeed)(a).deriveHardened(44).deriveHardened(o).deriveHardened(0).neutered().toBase58(),k=f.w5.deriveAccount(n.mnemonic,f.BG.SECP256K1,this.derivationPath).address.toString();return{publicKey:d,address:k}})}parseUri(t,s,o){return D(this,null,function*(){const{pluginId:n}=this.currencyInfo,a={[n]:!0},{edgeParsedUri:i,edgeParsedUri:{publicAddress:l}}=(0,w.k)(this.currencyInfo,t,a,s!=null?s:this.currencyInfo.currencyCode,o);if(l==null||!(yield this.isValidAddress(l)))throw new Error("InvalidPublicAddressError");return i})}encodeUri(t){return D(this,arguments,function*(s,o=[]){const{pluginId:n}=this.currencyInfo,{nativeAmount:a,currencyCode:i,publicAddress:l}=s;if(!(yield this.isValidAddress(l)))throw new Error("InvalidPublicAddressError");let r;if(a!=null){const S=(0,y.Qs)(i!=null?i:this.currencyInfo.currencyCode,this.currencyInfo,o);if(S==null)throw new Error("InternalErrorInvalidCurrencyCode");r=(0,g.div)(a,S.multiplier,18)}return(0,w.Q)(s,`${n}`,r)})}}function we(c){return D(this,null,function*(){return new Z(c)})}},35620:function(U,H,u){u.d(H,{US:function(){return e},YU:function(){return g}});var f=u(79911);const g=f.base16,O=f.base32,_=f.base32hex,e=f.base64,b=f.base64url,w=f.codec;var y=null}}]);
1
+ "use strict";(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[518],{58355:function($,B,u){var m=u(35717),y=u(51031),H=u(71027),X=u(89509).Buffer,e=u(78028),x=u(79785),I=u(89072),C=X.alloc(128);function A(v,d){H.call(this,"digest"),typeof d=="string"&&(d=X.from(d));var b=v==="sha512"||v==="sha384"?128:64;if(this._alg=v,this._key=d,d.length>b){var R=v==="rmd160"?new x:I(v);d=R.update(d).digest()}else d.length<b&&(d=X.concat([d,C],b));for(var _=this._ipad=X.allocUnsafe(b),f=this._opad=X.allocUnsafe(b),p=0;p<b;p++)_[p]=d[p]^54,f[p]=d[p]^92;this._hash=v==="rmd160"?new x:I(v),this._hash.update(_)}m(A,H),A.prototype._update=function(v){this._hash.update(v)},A.prototype._final=function(){var v=this._hash.digest(),d=this._alg==="rmd160"?new x:I(this._alg);return d.update(this._opad).update(v).digest()},$.exports=function(d,b){return d=d.toLowerCase(),d==="rmd160"||d==="ripemd160"?new A("rmd160",b):d==="md5"?new y(e,b):new A(d,b)}},51031:function($,B,u){var m=u(35717),y=u(89509).Buffer,H=u(71027),X=y.alloc(128),e=64;function x(I,C){H.call(this,"digest"),typeof C=="string"&&(C=y.from(C)),this._alg=I,this._key=C,C.length>e?C=I(C):C.length<e&&(C=y.concat([C,X],e));for(var A=this._ipad=y.allocUnsafe(e),v=this._opad=y.allocUnsafe(e),d=0;d<e;d++)A[d]=C[d]^54,v[d]=C[d]^92;this._hash=[A]}m(x,H),x.prototype._update=function(I){this._hash.push(I)},x.prototype._final=function(){var I=this._alg(y.concat(this._hash));return this._alg(y.concat([this._opad,I]))},$.exports=x},79014:function($,B,u){u.d(B,{Q:function(){return _},k:function(){return R}});var m=u(77591),y=u.n(m),H=u(24350),X=u(84564),e=u.n(X),x=u(76714),I=Object.defineProperty,C=Object.getOwnPropertySymbols,A=Object.prototype.hasOwnProperty,v=Object.prototype.propertyIsEnumerable,d=(f,p,w)=>p in f?I(f,p,{enumerable:!0,configurable:!0,writable:!0,value:w}):f[p]=w,b=(f,p)=>{for(var w in p||(p={}))A.call(p,w)&&d(f,w,p[w]);if(C)for(var w of C(p))v.call(p,w)&&d(f,w,p[w]);return f};function R(f,p,w,E,L=[]){const g=b({},e()(p,{},!0)),K=p.startsWith(`${f.pluginId}://`);if(g.protocol!=null&&(g.protocol=g.protocol.replace(":","")),g.protocol!=null&&g.protocol!==""&&!w[g.protocol])throw new Error(`Uri protocol '${g.protocol}' is not supported for ${f.pluginId}.`);if(g.host===""&&g.pathname==="")throw new Error("Path and host not found in uri.");const S={publicAddress:g.host!==""?g.host:g.pathname.split("/")[0]},J=g.query.label,G=g.query.message,U=g.query.category;(J!=null||G!=null||U!=null||K)&&(S.metadata={},S.metadata.name=J,S.metadata.notes=G,S.metadata.category=U,S.metadata.gateway=K!=null?K:!1);const N=g.query.amount;if(N!=null&&typeof N=="string"){E==null&&(E=f.currencyCode);const V=(0,x.Qs)(E!=null?E:"",f,L);if(V==null)throw new Error("InternalErrorInvalidCurrencyCode");let k=(0,m.mul)(N,V.multiplier);k=(0,m.toFixed)(k,0,0),S.nativeAmount=k,S.currencyCode=E}return{edgeParsedUri:S,parsedUri:g}}function _(f,p,w){if(f.publicAddress==null)throw new Error("InvalidPublicAddressError");if(w==null&&f.label==null&&f.message==null)return f.publicAddress;{let E="";w!=null&&(E+="amount="+w+"&"),(f.label!=null||f.message!=null)&&(typeof f.label=="string"&&(E+="label="+f.label+"&"),typeof f.message=="string"&&(E+="message="+f.message+"&")),E=E.substr(0,E.length-1);const L={scheme:p,path:f.publicAddress,query:E};return(0,H.qC)(L)}}},12636:function($,B,u){u.r(B),u.d(B,{FilecoinTools:function(){return Z},makeCurrencyEngine:function(){return Te},makeCurrencyTools:function(){return Ie}});var m=u(23145),y=u(77591),H=u(37786),X=u(2153),e=u(82448),x=u(35620),I=u(79014),C=u(76714),A=u(62177);const v=(0,e.su)({}),d=(0,e.su)({sigJson:(0,e.Zz)((0,e.su)({Data:e.XC,Type:(0,e.Wf)(1,3)})),txJson:(0,e.su)({To:e.XC,From:e.XC,Nonce:e.mH,Value:e.XC,GasLimit:e.mH,GasFeeCap:e.XC,GasPremium:e.XC,Method:e.mH,Params:e.XC})}),b=(0,e.su)({address:e.XC,publicKey:e.XC}),R=(0,A.jd)(b),_=l=>{const t=(0,e.su)({[`${l}Mnemonic`]:e.XC,[`${l}Key`]:e.XC});return(0,e.W1)(s=>{const i=t(s);return{mnemonic:i[`${l}Mnemonic`],privateKey:i[`${l}Key`]}},s=>({[`${l}Mnemonic`]:s.mnemonic,[`${l}Key`]:s.privateKey}))};var f=u(94935),p=u(84650),w=u(72681),E=(l,t,s)=>new Promise((i,n)=>{var a=r=>{try{c(s.next(r))}catch(h){n(h)}},o=r=>{try{c(s.throw(r))}catch(h){n(h)}},c=r=>r.done?i(r.value):Promise.resolve(r.value).then(a,o);c((s=s.apply(l,t)).next())});const L=(0,e.su)({statusCode:e.mH,message:e.XC,error:e.XC}),g=l=>(0,e.$e)((0,e._C)(L,l)),K=(0,e.su)({cid:e.XC,from:e.XC,height:e.mH,method:e.XC,nonce:e.mH,receipt:(0,e.su)({exitCode:e.mH}),timestamp:e.mH,to:e.XC,value:e.XC}),Q=(0,e.su)({cid:e.XC,height:e.mH,timestamp:e.mH,from:e.XC,to:e.XC,value:e.XC,gasLimit:e.mH,gasFeeCap:e.XC,gasPremium:e.XC,receipt:(0,e.su)({exitCode:e.mH,return:e.XC,gasUsed:e.mH}),baseFee:e.XC,fee:(0,e.su)({baseFeeBurn:e.XC,overEstimationBurn:e.XC,minerPenalty:e.XC,minerTip:e.XC,refund:e.XC}),transfers:(0,e._2)((0,e.su)({from:e.XC,fromId:e.XC,to:e.XC,toId:e.XC,value:e.XC,type:e.XC}))}),S=(0,e.su)({messages:(0,e._2)(K),totalCount:e.mH}),J=Q;class G{constructor(t,s){this.baseUrl=t,this.fetch=s}getAccountMessages(t,s,i=20){return E(this,null,function*(){const n=new URL(`${this.baseUrl}/address/${t}/messages`),a=new URLSearchParams({page:s.toString(),pageSize:i.toString()});n.search=a.toString();const c=yield(yield this.fetch(n.toString(),{method:"GET",headers:{"content-type":"application/json"}})).text(),r=g(S)(c);if("error"in r)throw new Error(`Error response code ${r.statusCode}: ${r.message} ${r.error}`);return r})}getMessageDetails(t){return E(this,null,function*(){const i=yield(yield this.fetch(`${this.baseUrl}/message/${t}`,{method:"GET",headers:{"content-type":"application/json"}})).text(),n=g(J)(i);if("error"in n)throw new Error(`Error response code ${n.statusCode}: ${n.message} ${n.error}`);return n})}}var U=(l,t,s)=>new Promise((i,n)=>{var a=r=>{try{c(s.next(r))}catch(h){n(h)}},o=r=>{try{c(s.throw(r))}catch(h){n(h)}},c=r=>r.done?i(r.value):Promise.resolve(r.value).then(a,o);c((s=s.apply(l,t)).next())});const N=l=>(0,e.su)({result:l}),V=(0,e.su)({code:e.mH,message:e.XC}),k=l=>(0,e.$e)((0,e._C)(V,N(l))),q=(0,e.su)({height:e.mH,block_time:e.mH,cid:e.XC,from:e.XC,to:e.XC,value:e.XC,exit_code:e.XC,method_name:e.XC}),ee=(0,e.su)({account_type:e.XC,account_info:(0,e.su)({account_basic:(0,e.su)({account_id:e.XC,account_address:e.XC,account_type:e.XC,account_balance:e.XC,nonce:e.mH,code_cid:e.XC,create_time:e.XC,latest_transfer_time:e.XC})})}),te=(0,e.su)({messages_by_account_id_list:(0,e.Vk)((0,e._2)(q),()=>[]),total_count:e.mH}),se=(0,e.su)({MessageDetails:(0,e.su)({message_basic:(0,e.su)({height:e.mH,block_time:e.mH,cid:e.XC,from:e.XC,to:e.XC,value:e.XC,exit_code:e.XC,method_name:e.XC}),blk_cids:(0,e._2)(e.XC),consume_list:(0,e._2)((0,e.su)({from:e.XC,to:e.XC,value:e.XC,consume_type:e.XC})),version:e.mH,nonce:e.mH,gas_fee_cap:e.XC,gas_premium:e.XC,gas_limit:e.mH,gas_used:e.XC,base_fee:e.XC,all_gas_fee:e.XC,eth_message:e.XC})});class ne{constructor(t,s){this.baseUrl=t,this.fetch=s}getAccountInfo(t){return U(this,null,function*(){const i=yield(yield this.fetch(`${this.baseUrl}/AccountInfoByID`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({account_id:t})})).text(),n=k(ee)(i);if(!("result"in n))throw new Error(`Error response code ${n.code}: ${n.message}`);return n.result})}getAccountMessages(t,s,i=20){return U(this,null,function*(){const a=yield(yield this.fetch(`${this.baseUrl}/MessagesByAccountID`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({account_id:t,address:"",filters:{index:s,page:0,limit:i,method_name:""}})})).text(),o=k(te)(a);if(!("result"in o))throw new Error(`Error response code ${o.code}: ${o.message}`);return o.result})}getMessageDetails(t){return U(this,null,function*(){const i=yield(yield this.fetch(`${this.baseUrl}/MessageDetails`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({message_cid:t})})).text(),n=k(se)(i);if(!("result"in n))throw new Error(`Error response code ${n.code}: ${n.message}`);return n.result})}}var re=Math.pow,oe=(l,t,s)=>new Promise((i,n)=>{var a=r=>{try{c(s.next(r))}catch(h){n(h)}},o=r=>{try{c(s.throw(r))}catch(h){n(h)}},c=r=>r.done?i(r.value):Promise.resolve(r.value).then(a,o);c((s=s.apply(l,t)).next())});const ie=l=>(0,e.su)({id:e.mH,jsonrpc:e.XC,result:l}),ae=(0,e.su)({id:e.mH,jsonrpc:e.XC,error:(0,e.su)({code:e.mH,message:e.XC})}),ce=l=>(0,e.$e)((0,e._C)(ae,ie(l))),le=(0,e.su)({Height:e.mH});class ue{constructor(t,s){this.baseUrl=t,this.fetch=s}getChainHead(){return oe(this,null,function*(){const t=Math.floor(Math.random()*re(10,8)),i=yield(yield this.fetch(this.baseUrl,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({id:t,jsonrpc:"2.0",method:"Filecoin.ChainHead",params:null})})).text(),n=ce(le)(i);if("error"in n)throw new Error(`Error response code ${n.error.code}: ${n.error.message}`);return n})}}var de=Object.defineProperty,he=Object.defineProperties,fe=Object.getOwnPropertyDescriptors,z=Object.getOwnPropertySymbols,pe=Object.getPrototypeOf,me=Object.prototype.hasOwnProperty,ge=Object.prototype.propertyIsEnumerable,ye=Reflect.get,Y=(l,t,s)=>t in l?de(l,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):l[t]=s,Ce=(l,t)=>{for(var s in t||(t={}))me.call(t,s)&&Y(l,s,t[s]);if(z)for(var s of z(t))ge.call(t,s)&&Y(l,s,t[s]);return l},ve=(l,t)=>he(l,fe(t)),W=(l,t,s)=>ye(pe(l),s,t),T=(l,t,s)=>new Promise((i,n)=>{var a=r=>{try{c(s.next(r))}catch(h){n(h)}},o=r=>{try{c(s.throw(r))}catch(h){n(h)}},c=r=>r.done?i(r.value):Promise.resolve(r.value).then(a,o);c((s=s.apply(l,t)).next())});const we=15e3,Pe=3e4,Ee=15e3;class F extends p.P{constructor(t,s,i,n){super(t,s,i,n),this.filfoxMessageToEdgeTransaction=o=>{const c=this.address.toString(),r=[],h=o.transfers.filter(O=>O.type==="miner-fee"||O.type==="burner-fee").reduce((O,j)=>(0,y.add)(O,j.value),"0");let P;return o.from===c?(P=`-${h}`,o.to!==c&&(P=(0,y.sub)(P,o.value))):(P=o.value,r.push(c)),{blockHeight:o.height,currencyCode:this.currencyInfo.currencyCode,date:o.timestamp,isSend:P.startsWith("-"),memos:[],nativeAmount:P,networkFee:h,otherParams:{},ourReceiveAddresses:r,signedTx:"",txid:o.cid,walletId:this.walletId}};const{networkInfo:a}=t;this.address=m.kL.fromString(i.keys.address),this.availableAttoFil="0",this.isScanning=!1,this.networkInfo=a,this.pluginId=this.currencyInfo.pluginId,this.filRpc=new m.rP(t.networkInfo.rpcNode.networkName,{url:t.networkInfo.rpcNode.url,token:t.currencyInfo.currencyCode}),this.filfoxApi=new G(t.networkInfo.filfoxUrl,t.io.fetchCors),this.filscanApi=new ne(t.networkInfo.filscanUrl,t.io.fetchCors),this.rpcExtra=new ue(t.networkInfo.rpcNode.url,t.io.fetchCors)}setOtherData(t){this.otherData=v(t)}initData(){this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=0,this.availableAttoFil="0"}initSubscriptions(){this.addToLoop("checkBalance",we).catch(t=>this.log(t)),this.addToLoop("checkBlockHeight",Pe).catch(t=>this.log(t)),this.addToLoop("checkTransactions",Ee).catch(t=>this.log(t))}onUpdateBlockHeight(t){this.walletLocalData.blockHeight!==t&&(this.walletLocalData.blockHeight=t,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight))}onUpdateTransactions(){this.transactionsChangedArray.length>0&&(this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[])}startEngine(){return T(this,null,function*(){this.initData(),this.initSubscriptions(),yield W(F.prototype,this,"startEngine").call(this)})}killEngine(){return T(this,null,function*(){yield W(F.prototype,this,"killEngine").call(this)})}clearBlockchainCache(){return T(this,null,function*(){yield W(F.prototype,this,"clearBlockchainCache").call(this)})}resyncBlockchain(){return T(this,null,function*(){yield W(F.prototype,this,"killEngine").call(this),yield this.clearBlockchainCache(),yield this.startEngine()})}getFreshAddress(){return T(this,null,function*(){const{address:t}=this.walletInfo.keys;return{publicAddress:t}})}getMaxSpendable(t){return T(this,null,function*(){const i=(yield this.makeSpend(t)).networkFee,n=(0,y.sub)(this.availableAttoFil,i);if((0,y.lte)(n,"0"))throw new f.C_;return n})}makeSpend(t){return T(this,null,function*(){t=(0,w.s)(t,this.currencyInfo);const{edgeSpendInfo:s,currencyCode:i}=this.makeSpendCheck(t),{memos:n=[]}=s,a=s.spendTargets[0],{publicAddress:o,nativeAmount:c}=a;if(o==null)throw new Error("Missing publicAddress in EdgeSpendInfo");if(c==null)throw new f.$D;const r=m.kL.fromString(o),h=m.YW.getNew(r,this.address,m.WU.fromAtto(c),0);yield h.prepareToSend(this.filRpc);const P=h.toJSON(),M={sigJson:void 0,txJson:P},O=(0,y.mul)(P.GasLimit.toString(),P.GasPremium),j=(0,y.mul)((0,y.add)(c,O),"-1");return{blockHeight:0,currencyCode:i,date:0,isSend:!0,memos:n,nativeAmount:j,networkFee:O,otherParams:M,ourReceiveAddresses:[],signedTx:"",txid:"",walletId:this.walletId}})}signTx(t,s){return T(this,null,function*(){const i=d(t.otherParams),n=m.YW.fromJSON(i.txJson),a=_(this.pluginId)(s),o=m.w5.deriveAccount(a.mnemonic,m.BG.SECP256K1,this.tools.derivationPath),c=yield m.w5.signTransaction(o,n);return t.otherParams=ve(Ce({},t.otherParams),{sigJson:c.toJSON()}),t.date=Date.now()/1e3,t})}broadcastTx(t,s){return T(this,null,function*(){const i=d(t.otherParams);if(i.sigJson==null)throw new Error("Cannot broadcast unsigned transaction");const n=m.Pc.fromJSON(i.sigJson),a=m.YW.fromJSON(i.txJson),o=yield this.filRpc.broadcastTransaction(a,n);if("error"in o)throw new Error(o.error.message);return t.txid=o.result["/"],t})}getDisplayPrivateSeed(t){return _(this.pluginId)(t).mnemonic}getDisplayPublicSeed(){return this.walletInfo.keys.publicKey}loadEngine(){return T(this,null,function*(){yield W(F.prototype,this,"loadEngine").call(this),this.engineOn=!0})}checkBalance(){return T(this,null,function*(){const t=yield this.filRpc.walletBalance(this.address);if("error"in t)throw new Error(t.error.message);const{result:s}=t;this.availableAttoFil=s,this.updateBalance(this.currencyInfo.currencyCode,s),this.tokenCheckBalanceStatus[this.currencyInfo.currencyCode]=1,this.updateOnAddressesChecked(),this.walletLocalDataDirty=!0})}checkBlockHeight(){return T(this,null,function*(){const s=(yield this.rpcExtra.getChainHead()).result.Height;this.onUpdateBlockHeight(s)})}checkTransactions(){return T(this,null,function*(){if(!this.isScanning)try{this.isScanning=!0;const t=this.address.toString(),s=o=>{const c=this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode],r=o;c<1&&(r>=1||r>c*1.1)&&(this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=r,this.updateOnAddressesChecked())},i=({tx:o,progress:c})=>{this.addTransaction(this.currencyInfo.currencyCode,o),this.onUpdateTransactions(),this.walletLocalData.blockHeight<o.blockHeight&&this.onUpdateBlockHeight(o.blockHeight),s(c)},n=[this.scanTransactionsFromFilfox(t,i)],a=this.walletLocalData.blockHeight;yield Promise.all(n),this.walletLocalData.lastAddressQueryHeight=a,this.walletLocalDataDirty=!0,s(1)}catch(t){throw console.error(t),t}finally{this.isScanning=!1}})}scanTransactionsFromFilfox(t,s){return T(this,null,function*(){let n=0,a=0,o=-1;do{const c=yield this.filfoxApi.getAccountMessages(t,n++,20);o=o===-1?c.totalCount:o;const r=c.messages;for(const h of r){if(h.height<this.walletLocalData.lastAddressQueryHeight)return;const P=yield this.filfoxApi.getMessageDetails(h.cid),M=this.filfoxMessageToEdgeTransaction(P),O=o===0?1:++a/o;s({tx:M,progress:O})}}while(a<o)})}scanTransactionsFromFilscan(t,s){return T(this,null,function*(){let n=0,a=0,o=-1;do{const c=yield this.filscanApi.getAccountMessages(t,n++,20);o=o===-1?c.total_count:o;const r=c.messages_by_account_id_list;for(const h of r){if(h.height<this.walletLocalData.lastAddressQueryHeight)return;const P=this.filscanMessageToEdgeTransaction(h),M=o===0?1:++a/o;s({tx:P,progress:M})}}while(a<o)})}filscanMessageToEdgeTransaction(t){const s=this.address.toString(),i=[],n="0";let a;return t.from===s?(a=`-${n}`,t.to!==s&&(a=(0,y.sub)(a,t.value))):(a=t.value,i.push(s)),{blockHeight:t.height,currencyCode:this.currencyInfo.currencyCode,date:t.block_time,isSend:a.startsWith("-"),memos:[],nativeAmount:a,networkFee:n,otherParams:{},ourReceiveAddresses:i,signedTx:"",txid:t.cid,walletId:this.walletId}}}function Te(l,t,s,i){return T(this,null,function*(){const n=R(s),a=new F(l,t,n,i);return yield a.loadEngine(),a})}var D=(l,t,s)=>new Promise((i,n)=>{var a=r=>{try{c(s.next(r))}catch(h){n(h)}},o=r=>{try{c(s.throw(r))}catch(h){n(h)}},c=r=>r.done?i(r.value):Promise.resolve(r.value).then(a,o);c((s=s.apply(l,t)).next())});class Z{constructor(t){const{builtinTokens:s,currencyInfo:i,io:n,networkInfo:a}=t;this.builtinTokens=s,this.currencyInfo=i,this.io=n,this.networkInfo=a,this.derivationPath=`m/44'/${this.networkInfo.hdPathCoinType}'/0'/0/0`}isValidAddress(t){return D(this,null,function*(){try{return m.kL.fromString(t),!0}catch{return!1}})}importPrivateKey(t){return D(this,arguments,function*(s,i={}){const{pluginId:n}=this.currencyInfo;if(!(0,X.validateMnemonic)(s))throw new Error("Invalid mnemonic");const a=(yield(0,X.mnemonicToSeed)(s)).toString("hex");return{[`${n}Key`]:a,[`${n}Mnemonic`]:s}})}createPrivateKey(t){return D(this,null,function*(){const{pluginId:s}=this.currencyInfo;if(t!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const i=x.YU.stringify(this.io.random(32)),n=(0,X.entropyToMnemonic)(i);return{[`${s}Key`]:i,[`${s}Mnemonic`]:n}})}checkPublicKey(t){return D(this,null,function*(){return(0,e.Vk)(b)(t)!=null})}derivePublicKey(t){return D(this,null,function*(){if(t.type!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const{pluginId:s}=this.currencyInfo,{hdPathCoinType:i}=this.networkInfo,n=_(s)(t.keys),a=yield(0,X.mnemonicToSeed)(n.mnemonic),h=(0,H.fromSeed)(a).deriveHardened(44).deriveHardened(i).deriveHardened(0).neutered().toBase58(),M=m.w5.deriveAccount(n.mnemonic,m.BG.SECP256K1,this.derivationPath).address.toString();return{publicKey:h,address:M}})}parseUri(t,s,i){return D(this,null,function*(){const{pluginId:n}=this.currencyInfo,a={[n]:!0},{edgeParsedUri:o,edgeParsedUri:{publicAddress:c}}=(0,I.k)(this.currencyInfo,t,a,s!=null?s:this.currencyInfo.currencyCode,i);if(c==null||!(yield this.isValidAddress(c)))throw new Error("InvalidPublicAddressError");return o})}encodeUri(t){return D(this,arguments,function*(s,i=[]){const{pluginId:n}=this.currencyInfo,{nativeAmount:a,currencyCode:o,publicAddress:c}=s;if(!(yield this.isValidAddress(c)))throw new Error("InvalidPublicAddressError");let r;if(a!=null){const P=(0,C.Qs)(o!=null?o:this.currencyInfo.currencyCode,this.currencyInfo,i);if(P==null)throw new Error("InternalErrorInvalidCurrencyCode");r=(0,y.div)(a,P.multiplier,18)}return(0,I.Q)(s,`${n}`,r)})}}function Ie(l){return D(this,null,function*(){return new Z(l)})}}}]);
@@ -1,2 +1,2 @@
1
- "use strict";(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[805],{79014:function(ye,Z,w){w.d(Z,{Q:function(){return u},k:function(){return ae}});var F=w(77591),ue=w.n(F),O=w(24350),ie=w(84564),Q=w.n(ie),D=w(76714),c=Object.defineProperty,P=Object.getOwnPropertySymbols,ee=Object.prototype.hasOwnProperty,f=Object.prototype.propertyIsEnumerable,S=(b,T,q)=>T in b?c(b,T,{enumerable:!0,configurable:!0,writable:!0,value:q}):b[T]=q,W=(b,T)=>{for(var q in T||(T={}))ee.call(T,q)&&S(b,q,T[q]);if(P)for(var q of P(T))f.call(T,q)&&S(b,q,T[q]);return b};function ae(b,T,q,K,z=[]){const R=W({},Q()(T,{},!0)),J=T.startsWith(`${b.pluginId}://`);if(R.protocol!=null&&(R.protocol=R.protocol.replace(":","")),R.protocol!=null&&R.protocol!==""&&!q[R.protocol])throw new Error(`Uri protocol '${R.protocol}' is not supported for ${b.pluginId}.`);if(R.host===""&&R.pathname==="")throw new Error("Path and host not found in uri.");const L={publicAddress:R.host!==""?R.host:R.pathname.split("/")[0]},j=R.query.label,te=R.query.message,Y=R.query.category;(j!=null||te!=null||Y!=null||J)&&(L.metadata={},L.metadata.name=j,L.metadata.notes=te,L.metadata.category=Y,L.metadata.gateway=J!=null?J:!1);const G=R.query.amount;if(G!=null&&typeof G=="string"){K==null&&(K=b.currencyCode);const se=(0,D.Qs)(K!=null?K:"",b,z);if(se==null)throw new Error("InternalErrorInvalidCurrencyCode");let V=(0,F.mul)(G,se.multiplier);V=(0,F.toFixed)(V,0,0),L.nativeAmount=V,L.currencyCode=K}return{edgeParsedUri:L,parsedUri:R}}function u(b,T,q){if(b.publicAddress==null)throw new Error("InvalidPublicAddressError");if(q==null&&b.label==null&&b.message==null)return b.publicAddress;{let K="";q!=null&&(K+="amount="+q+"&"),(b.label!=null||b.message!=null)&&(typeof b.label=="string"&&(K+="label="+b.label+"&"),typeof b.message=="string"&&(K+="message="+b.message+"&")),K=K.substr(0,K.length-1);const z={scheme:T,path:b.publicAddress,query:K};return(0,O.qC)(z)}}},44285:function(ye,Z,w){w.r(Z),w.d(Z,{FioTools:function(){return me},checkAddress:function(){return de},makeCurrencyEngine:function(){return De},makeCurrencyTools:function(){return Ae}});var F=w(93491),ue=w(15179),O=w(77591),ie=w(2153),Q=w(79014),D=w(76714),c=w(5607),P=w(24827),ee=w(50857),f=w(3559),S=w(37858),W=w(82626),ae=w(37297),u=w(82448),b=w(94935),T=w(84650);const q=(0,u.su)({fio_domains:(0,u._2)((0,u.su)({fio_domain:u.XC,expiration:u.XC,is_public:u.mH})),fio_addresses:(0,u._2)((0,u.su)({fio_address:u.XC,remaining_bundled_tx:u.mH}))}),K=(0,u.su)({account_action_seq:u.mH,block_num:u.mH,block_time:u.XC,action_trace:(0,u.su)({receiver:u.XC,act:(0,u.su)({account:u.XC,name:u.XC,authorization:(0,u._2)((0,u.su)({actor:u.XC,permission:u.XC})),data:(0,u.su)({payee_public_key:(0,u.Zz)(u.XC),amount:(0,u.Zz)(u.mH),max_fee:(0,u.Zz)(u.mH),actor:(0,u.Zz)(u.XC),tpid:(0,u.Zz)(u.XC),quantity:(0,u.Zz)(u.XC),memo:(0,u.Zz)(u.XC),to:(0,u.Zz)(u.XC),from:(0,u.Zz)(u.XC)}),hex_data:u.XC}),trx_id:u.XC,block_num:u.mH,block_time:u.XC,producer_block_id:u.XC})}),z=(0,u.su)({actions:(0,u._2)(K)}),R=(0,u.su)({balance:u.mH,available:u.mH,staked:u.mH,srps:u.mH,roe:u.XC});var J=Object.defineProperty,he=Object.defineProperties,L=Object.getOwnPropertyDescriptors,j=Object.getOwnPropertySymbols,te=Object.getPrototypeOf,Y=Object.prototype.hasOwnProperty,G=Object.prototype.propertyIsEnumerable,se=Reflect.get,V=(g,e,s)=>e in g?J(g,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):g[e]=s,x=(g,e)=>{for(var s in e||(e={}))Y.call(e,s)&&V(g,s,e[s]);if(j)for(var s of j(e))G.call(e,s)&&V(g,s,e[s]);return g},H=(g,e)=>he(g,L(e)),pe=(g,e)=>{var s={};for(var t in g)Y.call(g,t)&&e.indexOf(t)<0&&(s[t]=g[t]);if(g!=null&&j)for(var t of j(g))e.indexOf(t)<0&&G.call(g,t)&&(s[t]=g[t]);return s},fe=(g,e,s)=>se(te(g),s,e),p=(g,e,s)=>new Promise((t,r)=>{var o=n=>{try{a(s.next(n))}catch(i){r(i)}},l=n=>{try{a(s.throw(n))}catch(i){r(i)}},a=n=>n.done?t(n.value):Promise.resolve(n.value).then(o,l);a((s=s.apply(g,e)).next())});const ge=1e4,_e=15e3,ke=1e4,be=[c.BP[c.aO.transferTokens],c.BP[c.aO.unStakeFioTokens],"regaddress"],we=1e4;class ne extends T.P{constructor(e,s,t,r,o){super(e,s,t,r),this.fioRequestsListChanged=(l,a)=>{function n(i,d){for(const h of i)if(d.findIndex(v=>v.fio_request_id===h.fio_request_id)<0)return!0;return!1}return!!(n(l,a)||n(a,l))},this.removeFioRequest=(l,a)=>{const n=this.otherData.fioRequests[a].findIndex(i=>i.fio_request_id===`${l}`);n>-1&&this.otherData.fioRequests[a].splice(n,1)},this.fetchCors=(0,D.zR)(e.io),this.tpid=o,this.networkInfo=e.networkInfo,this.refBlock={expiration:"",ref_block_num:0,ref_block_prefix:0},this.fees=new Map,this.actor=F.rn.accountHash(this.walletInfo.keys.publicKey).accountnm,this.obtData=[],this.otherMethods={fioAction:(l,a)=>p(this,null,function*(){return yield this.multicastServers(l,a)}),getFioAddresses:()=>p(this,null,function*(){return this.otherData.fioAddresses}),getFioAddressNames:()=>p(this,null,function*(){return this.otherData.fioAddresses.map(l=>l.name)}),getFioDomains:()=>p(this,null,function*(){return this.otherData.fioDomains}),getFioRequests:(l,a,n=50)=>p(this,null,function*(){const i=n*(a-1),d=n*a;return this.otherData.fioRequests[l].sort((h,v)=>h.time_stamp<v.time_stamp?1:-1).slice(i,d)}),getObtData:()=>p(this,null,function*(){return this.obtData})}}localDataDirty(){this.walletLocalDataDirty=!0}setOtherData(e){this.otherData=(0,c.CL)(e)}getUTCDate(e){const s=new Date(e);return Date.UTC(s.getFullYear(),s.getMonth(),s.getDate(),s.getHours(),s.getMinutes(),s.getSeconds())}getUnlockDate(e){const s=Math.floor(e.getTime()/c.qj)*c.qj;return new Date(s+c.dm)}checkBlockchainInnerLoop(){return p(this,null,function*(){try{const e=yield this.multicastServers("getChainInfo"),s=e.head_block_num;this.walletLocalData.blockHeight!==s&&(this.checkDroppedTransactionsThrottled(),this.walletLocalData.blockHeight=s,this.localDataDirty(),this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight));const t=yield this.multicastServers("getBlock",e),r=new Date(`${e.head_block_time}Z`);r.setSeconds(r.getSeconds()+180);const o=r.toISOString();this.refBlock={expiration:o.substring(0,o.length-1),ref_block_num:t.block_num&65535,ref_block_prefix:t.ref_block_prefix}}catch(e){this.error("checkBlockchainInnerLoop Error fetching height: ",e)}})}getBalance(e){return super.getBalance(e)}doInitialBalanceCallback(){var e;super.doInitialBalanceCallback();const s=this.networkInfo.balanceCurrencyCodes;for(const t of Object.values(s))try{this.currencyEngineCallbacks.onBalanceChanged(t,(e=this.walletLocalData.totalBalances[t])!=null?e:"0")}catch(r){this.log.error("doInitialBalanceCallback Error for currencyCode",t,r)}try{this.currencyEngineCallbacks.onStakingStatusChanged(x({},this.otherData.stakingStatus))}catch(t){this.error("doInitialBalanceCallback onStakingStatusChanged",t)}}checkUnStakeTx(e){return e.name===c.BP[c.aO.unStakeFioTokens]||e.data!=null&&e.data.memo===c.Nd}updateStakingStatus(e,s,t,r){const o=this.getUnlockDate(new Date(this.getUTCDate(s))),l=this.otherData.stakingStatus.stakedAmounts.findIndex(a=>{var n;return((n=a.unlockDate)==null?void 0:n.getTime())===o.getTime()});if(l<0){const a=this.otherData.stakingStatus.stakedAmounts.findIndex(i=>{var d,h;return o.getTime()>=((h=(d=i.unlockDate)==null?void 0:d.getTime())!=null?h:0)}),n=a<0?this.otherData.stakingStatus.stakedAmounts.length:a;this.otherData.stakingStatus.stakedAmounts.splice(n,0,{nativeAmount:e,unlockDate:o,otherParams:{date:new Date(s),txs:[{txId:t,nativeAmount:e,blockTime:s,txName:r}]}})}else{const a=H(x({},this.otherData.stakingStatus.stakedAmounts[l]),{nativeAmount:"0"}),n=a.otherParams.txs.findIndex(({txId:i,txName:d})=>i===t&&d===r);n<0?a.otherParams.txs.push({txId:t,nativeAmount:e,blockTime:s,txName:r}):a.otherParams.txs[n]={txId:t,nativeAmount:e,blockTime:s,txName:r};for(const i of a.otherParams.txs)a.nativeAmount=(0,O.add)(a.nativeAmount,i.nativeAmount);this.otherData.stakingStatus.stakedAmounts[l]=a}this.localDataDirty();try{this.currencyEngineCallbacks.onStakingStatusChanged(x({},this.otherData.stakingStatus))}catch{this.error("onStakingStatusChanged error")}}getStakingStatus(){return p(this,null,function*(){return x({},this.otherData.stakingStatus)})}processTransaction(e,s,t=this.currencyInfo.currencyCode){var r,o,l,a,n,i,d,h,v;const{act:{name:I,data:_,account:y,authorization:E}}=e.action_trace;let C,m,k="0",A={account:y,name:I,authorization:E,data:_,meta:{}};const $=[];if(e.block_num<=this.otherData.highestTxHeight)return e.block_num;if(be.includes(I)){C="0",I==="regaddress"&&e.action_trace.act.authorization.some(U=>U.actor===this.actor)&&(k=String((r=e.action_trace.act.data.max_fee)!=null?r:0),C=`-${k}`),I===c.BP[c.aO.transferTokens]&&_.amount!=null&&(C=_.amount.toString(),m=_.actor,_.payee_public_key===this.walletInfo.keys.publicKey?($.push(this.walletInfo.keys.publicKey),m===s&&(C="0")):C=`-${C}`);const N=this.findTransaction(t,e.action_trace.trx_id);if(N>-1){const U=this.transactionList[t][N];if(A=H(x(x({},U.otherParams),A),{data:x(x({},(l=(o=U.otherParams)==null?void 0:o.data)!=null?l:{}),A.data),meta:x(x({},(n=(a=U.otherParams)==null?void 0:a.meta)!=null?n:{}),A.meta)}),A.meta.isTransferProcessed!=null)return e.block_num;A.meta.isFeeProcessed!=null?I===c.BP[c.aO.transferTokens]?(C=(0,O.sub)(C,U.networkFee),k=U.networkFee):(C=U.nativeAmount,k="0"):this.error("processTransaction error - existing spend transaction should have isTransferProcessed or isFeeProcessed set")}this.checkUnStakeTx(A)&&this.updateStakingStatus(_.amount!=null?_.amount.toString():"0",e.block_time,e.action_trace.trx_id,I),A.meta.isTransferProcessed=!0;const M={txid:e.action_trace.trx_id,date:this.getUTCDate(e.block_time)/1e3,currencyCode:t,blockHeight:e.block_num>0?e.block_num:0,nativeAmount:C,isSend:C.startsWith("-"),networkFee:k,ourReceiveAddresses:$,signedTx:"",otherParams:A,walletId:this.walletId};this.addTransaction(t,M)}if(I===c.BP.transfer&&_.quantity!=null){const[N]=_.quantity.split(" "),M=N.toString(),U=(0,D.aL)(t,this.currencyInfo,this.allTokensMap);if(U==null)return this.error(`Received unsupported currencyCode: ${t}`),0;const X=(0,O.mul)(M,U.multiplier);_.to===s?(C=`${X}`,k=`-${X}`):(C=`-${X}`,k=X);const re=this.findTransaction(t,e.action_trace.trx_id);if(re>-1){const oe=this.transactionList[t][re];if(A=H(x(x({},A),oe.otherParams),{data:x(x({},A.data),(d=(i=oe.otherParams)==null?void 0:i.data)!=null?d:{}),meta:x(x({},A.meta),(v=(h=oe.otherParams)==null?void 0:h.meta)!=null?v:{})}),A.meta.isFeeProcessed!=null)return e.block_num;A.meta.isTransferProcessed!=null?_.to!==s?C=(0,O.sub)(oe.nativeAmount,k):k="0":this.error("processTransaction error - existing spend transaction should have isTransferProcessed or isFeeProcessed set")}this.checkUnStakeTx(A)&&this.updateStakingStatus(X,e.block_time,e.action_trace.trx_id,I),A.meta.isFeeProcessed=!0;const Pe={txid:e.action_trace.trx_id,date:this.getUTCDate(e.block_time)/1e3,currencyCode:t,blockHeight:e.block_num>0?e.block_num:0,nativeAmount:C,isSend:C.startsWith("-"),networkFee:k,signedTx:"",ourReceiveAddresses:[],otherParams:A,walletId:this.walletId};this.addTransaction(t,Pe)}return e.block_num}getSortedHistoryNodesLastActionSeqNumbers(){return p(this,null,function*(){const e=this.networkInfo.historyNodeUrls.map((t,r)=>p(this,null,function*(){var o;try{const l=yield this.requestHistory(r,{account_name:this.actor,pos:-1},c.pg.getActions);return((o=l==null?void 0:l.error)==null?void 0:o.noNodeForIndex)!=null?{nodeIndex:r,seqNumber:-1}:(z(l),l.actions.length===0?{nodeIndex:r,seqNumber:-1}:{nodeIndex:r,seqNumber:l.actions[l.actions.length-1].account_action_seq})}catch{return{nodeIndex:r,seqNumber:-1}}})),s=yield Promise.all(e);return s.sort((t,r)=>r.seqNumber-t.seqNumber),s})}checkTransactions(e){return p(this,null,function*(){var s,t;if((e==null?void 0:e.length)===0)return!1;if(e=e!=null?e:yield this.getSortedHistoryNodesLastActionSeqNumbers(),e.reduce((i,d)=>i+d.seqNumber,0)===-e.length)return!0;let r=this.otherData.highestTxHeight;const o=e[0].seqNumber,l=e[0].nodeIndex;let a=Math.max(0,o-c.WX+1),n=!1;for(;!n;){let i;try{if(i=yield this.requestHistory(l,{account_name:this.actor,pos:a,offset:c.WX-1},c.pg.getActions),((s=i.error)==null?void 0:s.noNodeForIndex)!=null)return!1;let d=[];if(((t=i.actions)==null?void 0:t.length)>0)d=i.actions;else break;for(let h=d.length-1;h>-1;h--){const v=d[h];K(v);const I=this.processTransaction(v,this.actor);if(I>r)r=I;else if(I===r&&h===c.WX-1||I<this.otherData.highestTxHeight){n=!0;break}}if(a===0)break;a=Math.max(0,a-c.WX);continue}catch{return yield this.checkTransactions(e.slice(1))}}return r>this.otherData.highestTxHeight&&(this.otherData.highestTxHeight=r,this.localDataDirty()),!0})}checkTransactionsInnerLoop(){return p(this,null,function*(){let e;try{e=yield this.checkTransactions()}catch(s){this.error("checkTransactionsInnerLoop fetches failed with error: ",s);return}e&&(this.tokenCheckTransactionsStatus.FIO=1,this.updateOnAddressesChecked()),this.transactionsChangedArray.length>0&&(this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[])})}requestHistory(e,s,t){return p(this,null,function*(){if(this.networkInfo.historyNodeUrls[e]==null)return{error:{noNodeForIndex:!0}};const r=this.networkInfo.historyNodeUrls[e],o=JSON.stringify(s);return yield(yield fetch(`${r}history/${t}`,{method:"POST",headers:{"Content-Length":(o.length*2).toString(),Accept:"application/json","Content-Type":"application/json"},body:o})).json()})}fioApiRequest(e,s,t,r=!1){return p(this,null,function*(){var o,l,a,n;const i=new F.rn("",this.walletInfo.keys.publicKey,e,this.fetchCors,void 0,this.tpid,r);let d;try{switch(s){case"getChainInfo":d=yield i.transactions.getChainInfo();break;case"getBlock":d=yield i.transactions.getBlock(t);break;case"getObtData":case"getPendingFioRequests":case"getSentFioRequests":{const{endpoint:h,body:v}=t;d=yield i.transactions.executeCall(h,JSON.stringify(v));break}default:d=yield i.genericAction(s,t)}}catch(h){if(h.errorCode!=null&&P.lI.includes(h.errorCode))((a=(l=(o=h.json)==null?void 0:o.fields)==null?void 0:l[0])==null?void 0:a.error)!=null&&(h.message=h.json.fields[0].error),d={isError:!0,data:{code:h.errorCode,message:(n=h.message)!=null?n:(0,D.HY)(h),json:h.json,list:h.list}},h.errorCode!==404&&this.log(`fioApiRequest error. actionName: ${s} - apiUrl: ${e} - message: ${JSON.stringify(h.json)}`);else throw this.log(`fioApiRequest error. actionName: ${s} - apiUrl: ${e} - message: `,h),h}return d})}executePreparedTrx(e,s,t){return p(this,null,function*(){var r,o,l;const a=new F.rn("",this.walletInfo.keys.publicKey,e,this.fetchCors,void 0,this.tpid,!0);let n;this.warn(`executePreparedTrx. preparedTrx: ${JSON.stringify(t)} - apiUrl: ${e}`);try{n=yield a.executePreparedTrx(s,t),this.warn(`executePreparedTrx. res: ${JSON.stringify(n)} - apiUrl: ${e} - endpoint: ${s}`)}catch(i){throw i.errorCode!=null&&P.lI.includes(i.errorCode)?(this.log(`executePreparedTrx error. requestParams: ${JSON.stringify(t)} - apiUrl: ${e} - endpoint: ${s} - message: ${JSON.stringify(i.json)}`),((l=(o=(r=i.json)==null?void 0:r.fields)==null?void 0:o[0])==null?void 0:l.error)!=null&&(i.message=i.json.fields[0].error),i):(this.log(`executePreparedTrx error. requestParams: ${JSON.stringify(t)} - apiUrl: ${e} - endpoint: ${s} - message: `,i),i)}return n})}multicastServers(e,s){return p(this,null,function*(){var t,r,o,l,a;let n;if(c.K1[e]){const i=(0,f.h0)(s);if(this.warn(`multicastServers executePreparedTrx. actionName: ${e} - res: ${JSON.stringify(i)}`),n=yield(0,D.Wp)((0,D.Sy)(this.networkInfo.apiUrls.map(d=>p(this,null,function*(){return yield(0,D.Vs)(this.executePreparedTrx(d,S.EndPoint[c.VW[e]],i),1e4)})))),this.warn(`multicastServers res. actionName: ${e} - res: ${JSON.stringify(n)}`),n==null)throw new Error("Service is unavailable")}else e==="getFioNames"?(n=yield(0,D.ml)(this.networkInfo.apiUrls.map(i=>p(this,null,function*(){return yield(0,D.Vs)(this.fioApiRequest(i,e,s),1e4)})),i=>{const d=(0,f.$K)(c.Mi)(i);return d!=null?d.data.json.message:(0,f.e1)(i)},2),((r=(t=n==null?void 0:n.data)==null?void 0:t.json)==null?void 0:r.message)===c.Mi&&(n={fio_domains:[],fio_addresses:[]})):e==="getFioBalance"?(n=yield(0,D.ml)(this.networkInfo.apiUrls.map(i=>p(this,null,function*(){return yield(0,D.Vs)(this.fioApiRequest(i,e,s),1e4)})),i=>{const d=(0,f.$K)(c.d9)(i);return d!=null?d.data.json.message:(0,f.sq)(i)},2),((l=(o=n==null?void 0:n.data)==null?void 0:o.json)==null?void 0:l.message)===c.d9&&(n={balance:0,available:0,staked:0,srps:0,roe:""})):e==="getFees"?n=yield(0,D.QJ)((0,D.Sy)(this.networkInfo.apiUrls.map(i=>()=>p(this,null,function*(){const d=new F.rn("",this.walletInfo.keys.publicKey,i,this.fetchCors,void 0,this.tpid),{endpoint:h,param:v}=s,I=yield d.getFee(h,v);return(0,f.lZ)(I).fee.toString()})))):n=yield(0,D.QJ)((0,D.Sy)(this.networkInfo.apiUrls.map(i=>()=>p(this,null,function*(){return yield this.fioApiRequest(i,e,s)}))));if(n.isError!=null){const i=new P.OU((a=n.errorMessage)!=null?a:n.data.message);throw i.json=n.data.json,i.list=n.data.list,i.errorCode=n.data.code,i}return n})}checkAccountInnerLoop(){return p(this,null,function*(){const e=this.currencyInfo.currencyCode,s=this.networkInfo.balanceCurrencyCodes;typeof this.walletLocalData.totalBalances[e]>"u"&&this.updateBalance(e,"0");try{const t={staked:"0",locked:"0"},{balance:r,available:o,staked:l,srps:a,roe:n}=R(yield this.multicastServers("getFioBalance")),i=String(r);t.staked=String(l),t.locked=(0,O.sub)(i,String(o)),this.otherData.srps=a,this.otherData.stakingRoe=n,this.updateBalance(e,i),this.updateBalance(s.staked,t.staked),this.updateBalance(s.locked,t.locked)}catch(t){this.log.warn("checkAccountInnerLoop getFioBalance error: ",t)}try{const t=q(yield this.multicastServers("getFioNames",{fioPublicKey:this.walletInfo.keys.publicKey}));let r=!1,o=!1,l=!1;if(t.fio_addresses.length!==this.otherData.fioAddresses.length)o=!0;else{for(const a of t.fio_addresses){const n=this.otherData.fioAddresses.find(i=>i.name===a.fio_address);if(n!=null){if(n.bundledTxs!==a.remaining_bundled_tx){o=!0;break}}else{o=!0;break}}if(!o){for(const a of this.otherData.fioAddresses)if(t.fio_addresses.findIndex(n=>n.fio_address===a.name)<0){o=!0;break}}}if(t.fio_domains.length!==this.otherData.fioDomains.length)l=!0;else{for(const a of t.fio_domains){const n=this.otherData.fioDomains.find(i=>i.name===a.fio_domain);if(n!=null){if(n.expiration!==a.expiration){l=!0;break}if(n.isPublic!==(a.is_public===1)){l=!0;break}}else{l=!0;break}}if(!l){for(const a of this.otherData.fioDomains)if(t.fio_domains.findIndex(n=>n.fio_domain===a.name)<0){l=!0;break}}}o&&(r=!0,this.otherData.fioAddresses=t.fio_addresses.map(a=>({name:a.fio_address,bundledTxs:a.remaining_bundled_tx}))),l&&(r=!0,this.otherData.fioDomains=t.fio_domains.map(a=>({name:a.fio_domain,expiration:a.expiration,isPublic:a.is_public===1}))),r&&this.localDataDirty()}catch(t){this.warn("checkAccountInnerLoop getFioNames error: ",t)}})}fetchEncryptedFioRequests(e,s){return p(this,null,function*(){const r=e==="PENDING"?"getPendingFioRequests":"getSentFioRequests";let o=100,l=1;const a=[];for(;o===100;)try{const n=yield this.multicastServers(r,{endpoint:s.getEndPoint(),body:{fio_public_key:this.walletInfo.keys.publicKey,limit:100,offset:(l-1)*100}}),i=(0,f.S_)(n),{requests:d,more:h}=i;if(a.push(...d),h===0)break;l++,o=d.length}catch(n){const i=(0,u.Vk)(f.Pq)(n.json);(i==null?void 0:i.message)!=="No FIO Requests"&&this.error("fetchEncryptedFioRequests error: ",n);break}return a})}fetchEncryptedObtData(e,s){return p(this,null,function*(){let r=100,o=1;const l=[];for(;r===100;){let a;try{a=yield this.multicastServers(e,{endpoint:s.getEndPoint(),body:{fio_public_key:this.walletInfo.keys.publicKey,limit:100,offset:(o-1)*100}});const n=(0,f._v)(a),{obt_data_records:i,more:d}=n;if(l.push(...i),d===0)break;o++,r=i.length}catch(n){const i=(0,u.Vk)(f.Pq)(n.json);(i==null?void 0:i.message)!=="No FIO Requests"&&this.error("fetchEncryptedObtData error: ",n);break}}return l})}syncNetwork(e){return p(this,null,function*(){var s;const t=(0,f.UW)(e==null?void 0:e.privateKeys);let r=!1;const o=(i,d)=>p(this,null,function*(){var h;const v=yield this.fetchEncryptedFioRequests(i,d);d.privateKey=t.fioKey,d.publicKey=this.walletInfo.keys.publicKey;const I=(h=d.decrypt({requests:v}))!=null?h:{requests:[]};this.fioRequestsListChanged(this.otherData.fioRequests[i],I.requests)&&(this.otherData.fioRequests[i]=[...I.requests],r=!0)});yield o("PENDING",new W.PendingFioRequests(this.walletInfo.keys.publicKey)),yield o("SENT",new W.SentFioRequests(this.walletInfo.keys.publicKey)),r&&this.localDataDirty();const l=new W.GetObtData(this.walletInfo.keys.publicKey),a=yield this.fetchEncryptedObtData("getObtData",l);l.privateKey=t.fioKey,l.publicKey=this.walletInfo.keys.publicKey;const n=(s=l.decrypt({obt_data_records:a}))!=null?s:{obt_data_records:[]};return this.obtData=n.obt_data_records,we})}getFee(e,s){return p(this,null,function*(){let t=this.fees.get(e);if(t==null||t.expiration+30*1e3<Date.now()){const o={fee:yield this.multicastServers("getFees",{endpoint:e,param:s}),expiration:Date.now()};this.fees.set(e,o),t=o}return t.fee})}startEngine(){return p(this,null,function*(){this.engineOn=!0,this.addToLoop("checkBlockchainInnerLoop",_e).catch(()=>{}),this.addToLoop("checkAccountInnerLoop",ge).catch(()=>{}),this.addToLoop("checkTransactionsInnerLoop",ke).catch(()=>{}),yield fe(ne.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return p(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getMaxSpendable(e){return p(this,null,function*(){var s;const t=this.getBalance({currencyCode:e.currencyCode}),r=(s=this.walletLocalData.totalBalances[this.networkInfo.balanceCurrencyCodes.locked])!=null?s:"0";e.spendTargets[0].nativeAmount="1";const o=yield this.makeSpend(e),l=(0,O.sub)((0,O.sub)(t,o.networkFee),r);if((0,O.lt)(l,"0"))throw new b.C_({networkFee:o.networkFee});return l})}makeSpend(e){return p(this,null,function*(){var s,t;const{edgeSpendInfo:r,nativeBalance:o,currencyCode:l}=this.makeSpendCheck(e),a=(s=this.walletLocalData.totalBalances[this.networkInfo.balanceCurrencyCodes.locked])!=null?s:"0",n=(0,O.sub)(o,a),i=r.spendTargets[0],{publicAddress:d}=i,{nativeAmount:h}=i;if(d==null)throw new Error("makeSpend Missing publicAddress");if(h==null)throw new b.$D;let{otherParams:v}=r;(v==null||Object.keys(v).length===0)&&(v={action:{name:c.aO.transferTokens,params:{payeeFioPublicKey:d,amount:h,maxFee:0}}});const{name:I,params:_}=(0,f.iR)(v.action);let y,E;switch(I){case c.aO.transferTokens:{y=yield this.getFee(S.EndPoint.transferTokens),E={account:"fio.token",action:c.BP[c.aO.transferTokens],data:{payee_public_key:d,amount:h,max_fee:y}};break}case c.aO.stakeFioTokens:{const{fioAddress:m}=(0,f.NB)(_);y=yield this.getFee(S.EndPoint.stakeFioTokens,m),E={account:"fio.staking",action:c.BP[I],data:{amount:h,fio_address:m,actor:this.actor,max_fee:y}};break}case c.aO.unStakeFioTokens:{const{fioAddress:m}=(0,f.NB)(_);y=yield this.getFee(S.EndPoint.unStakeFioTokens,m),E={account:"fio.staking",action:c.BP[I],data:{amount:h,fio_address:m,actor:this.actor,max_fee:y}};const k=this.getUnlockDate(new Date),A=(t=this.walletLocalData.totalBalances[this.networkInfo.balanceCurrencyCodes.staked])!=null?t:"0";if((0,O.gt)(h,A)||(0,O.gt)(`${y}`,n))throw new b.C_;const $=(0,O.mul)((0,O.mul)((0,O.div)(h,A,18),`${this.otherData.srps}`),this.otherData.stakingRoe),N=(0,O.max)((0,O.sub)($,h),"0");v.ui={accrued:$,estReward:N,unlockDate:k};break}case c.aO.transferFioAddress:{const{fioAddress:m}=(0,f.NB)(_);y=yield this.getFee(S.EndPoint.transferFioAddress,m),E={account:"fio.address",action:"xferaddress",data:{fio_address:m,new_owner_fio_public_key:d,actor:this.actor,max_fee:y}};break}case c.aO.transferFioDomain:{const{fioDomain:m}=(0,f.L2)(_);y=yield this.getFee(S.EndPoint.transferFioDomain),E={account:"fio.address",action:"xferdomain",data:{fio_domain:m,new_owner_fio_public_key:d,actor:this.actor,max_fee:y}};break}case c.aO.addPublicAddresses:{const{fioAddress:m,publicAddresses:k}=(0,f.PH)(_);y=yield this.getFee(S.EndPoint.addPubAddress,m),E={account:"fio.address",action:"addaddress",data:{fio_address:m,public_addresses:k,actor:this.actor,max_fee:y}};break}case c.aO.removePublicAddresses:{const{fioAddress:m,publicAddresses:k}=(0,f.PH)(_);y=yield this.getFee(S.EndPoint.removePubAddress,m),E={account:"fio.address",action:"remaddress",data:{fio_address:m,public_addresses:k,actor:this.actor,max_fee:y}};break}case c.aO.registerFioAddress:{const{fioAddress:m}=(0,f.NB)(_);y=yield this.getFee(S.EndPoint.registerFioAddress),E={account:"fio.address",action:"regaddress",data:{fio_address:m,owner_fio_public_key:this.walletInfo.keys.publicKey,max_fee:y,actor:this.actor}};break}case c.aO.registerFioDomain:{const{fioDomain:m}=(0,f.AJ)(_);y=yield this.getFee(S.EndPoint.registerFioDomain),E={account:"fio.address",action:"regdomain",data:{fio_domain:m,owner_fio_public_key:this.walletInfo.keys.publicKey,max_fee:y,actor:this.actor}};break}case c.aO.renewFioDomain:{const{fioDomain:m}=(0,f.AJ)(_);y=yield this.getFee(S.EndPoint.renewFioDomain),E={account:"fio.address",action:"renewdomain",data:{fio_domain:m,max_fee:y,actor:this.actor}};break}case c.aO.addBundledTransactions:{const{bundleSets:m,fioAddress:k}=(0,f.Ej)(_);y=yield this.getFee(S.EndPoint.addBundledTransactions,k),E={account:"fio.address",action:"addbundles",data:{fio_address:k,bundle_sets:m,actor:this.actor,max_fee:y}};break}case c.aO.setFioDomainPublic:{const{fioDomain:m,isPublic:k}=(0,f.oY)(_);y=yield this.getFee(S.EndPoint.setFioDomainPublic),E={account:"fio.address",action:"setdomainpub",data:{fio_domain:m,is_public:k?1:0,max_fee:y,actor:this.actor}};break}case c.aO.rejectFundsRequest:{const{fioRequestId:m,payerFioAddress:k}=(0,f.OR)(_);y=yield this.getFee(S.EndPoint.rejectFundsRequest,k),E={account:"fio.reqobt",action:"rejectfndreq",data:{fio_request_id:m,max_fee:y,actor:this.actor}};break}case c.aO.cancelFundsRequest:{const{fioAddress:m,fioRequestId:k}=(0,f.mO)(_);y=yield this.getFee(S.EndPoint.cancelFundsRequest,m),E={account:"fio.reqobt",action:"cancelfndreq",data:{fio_request_id:k,max_fee:y,actor:this.actor}};break}case c.aO.recordObtData:{const{payerFioAddress:m}=(0,f.XB)(_);y=yield this.getFee(S.EndPoint.recordObtData,m);break}case c.aO.requestFunds:{const{payeeFioAddress:m}=(0,f.Vd)(_);y=yield this.getFee(S.EndPoint.newFundsRequest,m);break}default:throw new Error("Unrecognized FIO action")}return{txid:"",date:0,currencyCode:l,blockHeight:0,nativeAmount:(0,O.sub)(`-${h}`,`${y}`),isSend:!0,networkFee:`${y}`,ourReceiveAddresses:[],signedTx:"",otherParams:H(x({},v),{txParams:E}),walletId:this.walletId}})}signTx(e,s){return p(this,null,function*(){const t=(0,f.UW)(s),r=(0,D.Xp)(e);let o=(0,u.Vk)(f.B3)(r.txParams);const l=new ae.Transactions;if(o==null){const{name:h,params:v}=(0,f.iR)(r.action),{networkFee:I}=e;switch(h){case c.aO.recordObtData:{const{payerFioAddress:_,payeeFioAddress:y,payerPublicAddress:E,payeePublicAddress:C,amount:m,tokenCode:k,chainCode:A,obtId:$,memo:N,status:M,fioRequestId:U}=(0,f.XB)(v),X={payer_public_address:E,payee_public_address:C,amount:m,chain_code:A,token_code:k,status:M,obt_id:$,memo:N,hash:void 0,offline_url:void 0},re=l.getCipherContent("record_obt_data_content",X,t.fioKey,E);o={account:"fio.reqobt",action:"recordobt",data:{payer_fio_address:_,payee_fio_address:y,content:re,fio_request_id:U,max_fee:I,actor:this.actor}};break}case c.aO.requestFunds:{const{payerFioAddress:_,payerFioPublicKey:y,payeeFioAddress:E,payeeTokenPublicAddress:C,amount:m,chainCode:k,tokenCode:A,memo:$}=(0,f.Vd)(v),N={payee_public_address:C,amount:m,chain_code:k,token_code:A,memo:$,hash:void 0,offline_url:void 0},M=l.getCipherContent("new_funds_content",N,t.fioKey,y);o={account:"fio.reqobt",action:"newfundsreq",data:{payer_fio_address:_,payee_fio_address:E,content:M,max_fee:I,actor:this.actor}};break}default:throw new Error("Unknown FIO action")}}const a=yield l.createRawTransaction({action:o.action,account:o.account,data:H(x({},o.data),{tpid:this.tpid}),publicKey:this.walletInfo.keys.publicKey,chainData:this.refBlock}),{serializedContextFreeData:n,serializedTransaction:i}=yield l.serialize({chainId:this.networkInfo.chainId,transaction:a}),d=yield l.sign({chainId:this.networkInfo.chainId,privateKeys:[t.fioKey],transaction:a,serializedTransaction:i,serializedContextFreeData:n});return e.otherParams=H(x({},e.otherParams),{signedTx:d}),e})}broadcastTx(e){return p(this,null,function*(){var s;const t=(0,D.Xp)(e);if(((s=t.action)==null?void 0:s.name)==null)throw new Error('Action is not set, "action" prop of otherParams is required for FIO actions');const r=(0,f.h0)(t.signedTx),o=(0,f.Yd)(yield this.multicastServers(t.action.name,r));e.metadata={notes:o.transaction_id},e.txid=o.transaction_id,e.date=Date.now()/1e3,e.blockHeight=o.block_num,this.warn(`SUCCESS broadcastTx
2
- ${(0,D.oX)(e)}`);const l=o,{block_num:a,block_time:n,transaction_id:i}=l,d=pe(l,["block_num","block_time","transaction_id"]);return e.otherParams=H(x({},t),{broadcastResult:d}),e})}saveTx(e){return p(this,null,function*(){var s;const t=(0,D.Xp)(e),{broadcastResult:r={},action:o}=t,{name:l,params:a}=(0,f.iR)(o);try{switch(l){case c.aO.transferFioDomain:{const n=this.otherData.fioDomains.findIndex(({name:i})=>i===a.fioDomain);n>=0&&(this.otherData.fioDomains.splice(n,1),this.localDataDirty());break}case c.aO.transferFioAddress:{const n=this.otherData.fioAddresses.findIndex(({name:i})=>i===a.fioAddress);n>=0&&(this.otherData.fioAddresses.splice(n,1),this.localDataDirty());break}case c.aO.registerFioAddress:{const{fioAddress:n}=(0,f.NB)(a);this.otherData.fioAddresses.find(({name:d})=>d===n)==null&&(this.otherData.fioAddresses.push({name:n,bundledTxs:void 0}),this.localDataDirty());break}case c.aO.registerFioDomain:{const{fioDomain:n}=(0,f.AJ)(a);if(r.expiration==null)throw new Error("expiration not present");const i=this.otherData.fioDomains.find(({name:d})=>d===n);i!=null&&(i.expiration=r.expiration,this.localDataDirty());break}case c.aO.renewFioDomain:{const{fioDomain:n}=(0,f.AJ)(a);if(r.expiration==null)throw new Error("expiration not present");const i=this.otherData.fioDomains.find(({name:d})=>d===n);i!=null&&(i.expiration=r.expiration,this.localDataDirty());break}case c.aO.addBundledTransactions:{const{fioAddress:n}=(0,f.Ej)(a),i=this.otherData.fioAddresses.find(({name:d})=>d===n);if(i==null)throw new P.OU("Fio Address is not found in engine");i.bundledTxs=((s=i.bundledTxs)!=null?s:0)+c.BB,this.localDataDirty();break}case c.aO.rejectFundsRequest:{const{fioRequestId:n}=(0,f.OR)(a);typeof n=="string"&&(this.removeFioRequest(n,"PENDING"),this.localDataDirty());break}case c.aO.cancelFundsRequest:{const{fioRequestId:n}=(0,f.mO)(a);typeof n=="string"&&(this.removeFioRequest(n,"SENT"),this.localDataDirty());break}case c.aO.recordObtData:{const{fioRequestId:n}=(0,f.XB)(a);n!=null&&r.status==="sent_to_blockchain"&&(this.removeFioRequest(n,"PENDING"),this.localDataDirty());break}}}catch(n){this.log.warn(`Error attempting post-broadcast action ${l}:`,n)}yield fe(ne.prototype,this,"saveTx").call(this,e)})}getFreshAddress(e){return p(this,null,function*(){return{publicAddress:this.walletInfo.keys.publicKey}})}}function De(g,e,s,t){return p(this,null,function*(){const{tpid:r="finance@edge"}=g.initOptions,o=(0,f.RB)(s),l=new ne(g,e,o,t,r);return yield l.loadEngine(),l})}var ve=w(48764).Buffer,B=(g,e,s)=>new Promise((t,r)=>{var o=n=>{try{a(s.next(n))}catch(i){r(i)}},l=n=>{try{a(s.throw(n))}catch(i){r(i)}},a=n=>n.done?t(n.value):Promise.resolve(n.value).then(o,l);a((s=s.apply(g,e)).next())});const le="FIO",ce="fio",Ie="";function de(g){const e=g.startsWith(le),s=g.length===53;return e&&s}class me{constructor(e){const{builtinTokens:s,currencyInfo:t,initOptions:r,io:o,networkInfo:l}=e;this.builtinTokens=s,this.currencyInfo=t,this.io=o,this.networkInfo=l;const{tpid:a="finance@edge",fioRegApiToken:n=Ie}=r;this.fetchCors=(0,D.zR)(e.io),this.fioRegApiToken=n,this.tpid=a;for(const i of this.networkInfo.apiUrls)new F.rn("","",i,this.fetchCors,void 0,a)}getDisplayPrivateKey(e){return B(this,null,function*(){return(0,f.UW)(e.keys).fioKey})}getDisplayPublicKey(e){return B(this,null,function*(){const{keys:s}=(0,f.RB)(e);return s.publicKey})}importPrivateKey(e){return B(this,null,function*(){const{pluginId:s}=this.currencyInfo,t={};if(/[0-9a-zA-Z]{51}$/.test(e))ue._q.fromString(e),t.fioKey=e;else{if(!(0,ie.validateMnemonic)(e))throw new Error("Invalid input");const o=yield F.rn.createPrivateKeyMnemonic(e);t.fioKey=o.fioKey,t.mnemonic=o.mnemonic}const r=yield this.derivePublicKey({type:`wallet:${s}`,id:"fake",keys:t});return t.publicKey=r.publicKey,t})}createPrivateKey(e){return B(this,null,function*(){if(e.replace("wallet:","")===ce){const t=ve.from(this.io.random(32));return yield F.rn.createPrivateKey(t)}else throw new Error("InvalidWalletType")})}derivePublicKey(e){return B(this,null,function*(){if(e.type.replace("wallet:","")===ce)return F.rn.derivedPublicKey(e.keys.fioKey);throw new Error("InvalidWalletType")})}parseUri(e){return B(this,null,function*(){var s;const{edgeParsedUri:t}=(0,Q.k)(ee.j,e,{fio:!0},le);if(!de((s=t.publicAddress)!=null?s:""))throw new Error("InvalidPublicAddressError");return t})}encodeUri(e){return B(this,arguments,function*(s,t=[]){if(!de(s.publicAddress))throw new Error("InvalidPublicAddressError");let o;if(typeof s.nativeAmount=="string"){const a=le,n=s.nativeAmount,i=(0,D.Qs)(a,ee.j,t);if(i==null)throw new Error("InternalErrorInvalidCurrencyCode");o=(0,O.div)(n,i.multiplier,16)}return(0,Q.Q)(s,ce,o)})}getConnectedPublicAddress(e,s,t){return B(this,null,function*(){var r;try{F.rn.isFioAddressValid(e)}catch{throw new P.OU("",400,this.networkInfo.errorCodes.INVALID_FIO_ADDRESS)}try{if((yield this.multicastServers("isAvailable",{fioName:e})).is_registered===0)throw new P.OU("",404,this.networkInfo.errorCodes.FIO_ADDRESS_IS_NOT_EXIST)}catch(o){throw o.name==="FioError"&&((r=o.json)==null?void 0:r.fields)!=null&&o.errorCode===400&&(o.labelCode=this.networkInfo.errorCodes.INVALID_FIO_ADDRESS),o}try{const o=yield this.multicastServers("getPublicAddress",{fioAddress:e,chainCode:s,tokenCode:t});if(o.public_address==null||o.public_address==="0")throw new P.OU("",404,this.networkInfo.errorCodes.FIO_ADDRESS_IS_NOT_LINKED);return o}catch(o){throw o.name==="FioError"&&o.labelCode===this.networkInfo.errorCodes.FIO_ADDRESS_IS_NOT_LINKED||o.errorCode===404?new P.OU("",404,this.networkInfo.errorCodes.FIO_ADDRESS_IS_NOT_LINKED):o}})}isFioAddressValid(e){return B(this,null,function*(){try{return F.rn.isFioAddressValid(e)}catch{return!1}})}validateAccount(e,s=!1){return B(this,null,function*(){var t;try{if(s){if(!F.rn.isFioDomainValid(e))return!1}else if(!F.rn.isFioAddressValid(e))return!1}catch{throw new P.OU("",400,this.networkInfo.errorCodes.INVALID_FIO_ADDRESS)}try{return(yield this.multicastServers("isAvailable",{fioName:e})).is_registered===0}catch(r){throw r.name==="FioError"&&((t=r.json)==null?void 0:t.fields)!=null&&r.errorCode===400&&(r.labelCode=this.networkInfo.errorCodes.INVALID_FIO_ADDRESS),r}})}isDomainPublic(e){return B(this,null,function*(){if((yield this.multicastServers("isAvailable",{fioName:e})).is_registered===0)throw new P.OU("",400,this.networkInfo.errorCodes.FIO_DOMAIN_IS_NOT_EXIST);const t=yield this.fetchCors(`${this.networkInfo.fioRegApiUrl}${c.n3.isDomainPublic}/${e}`,{method:"GET"});if(!t.ok){const o=yield t.json();throw new P.OU("",t.status,this.networkInfo.errorCodes.IS_DOMAIN_PUBLIC_ERROR,o)}const{isPublic:r}=yield t.json();return r})}doesAccountExist(e){return B(this,null,function*(){try{if(!F.rn.isFioAddressValid(e))return!1}catch{return!1}try{return(yield this.multicastServers("isAvailable",{fioName:e})).is_registered===1}catch(s){return this.error("doesAccountExist error: ",s),!1}})}buyAddressRequest(e,s=!1){return B(this,null,function*(){const t={Accept:"application/json","Content-Type":"application/json"};s&&(e.apiToken=this.fioRegApiToken);try{const r=yield this.fetchCors(`${this.networkInfo.fioRegApiUrl}${c.n3.buyAddress}`,{method:"POST",headers:t,body:JSON.stringify(e)});if(!r.ok){const o=yield r.json();throw this.networkInfo.errorCodes[o.errorCode]!=null?new P.OU(o.error,r.status,this.networkInfo.errorCodes[o.errorCode],o):o.error==="Already registered"?new P.OU(o.error,r.status,this.networkInfo.errorCodes.ALREADY_REGISTERED,o):new Error(o.error)}return yield r.json()}catch(r){throw r.labelCode!=null?r:new P.OU((0,D.HY)(r),500,this.networkInfo.errorCodes.SERVER_ERROR)}})}getDomains(e=""){return B(this,null,function*(){e==null&&(e=this.networkInfo.defaultRef);try{const s=yield this.fetchCors(`${this.networkInfo.fioRegApiUrl}${c.n3.getDomains}/${e}`,{method:"GET"}),t=yield s.json();if(!s.ok)throw this.networkInfo.errorCodes[t.errorCode]!=null?new P.OU(t.error,s.status,this.networkInfo.errorCodes[t.errorCode],t):new Error(t.error);return t.domains}catch(s){throw s.labelCode!=null?s:new P.OU((0,D.HY)(s),500,this.networkInfo.errorCodes.SERVER_ERROR)}})}getStakeEstReturn(){return B(this,null,function*(){try{const e=yield this.fetchCors(`${this.networkInfo.fioStakingApyUrl}`,{method:"GET"}),s=yield e.json();if(!e.ok)throw new Error(this.networkInfo.errorCodes.SERVER_ERROR);const t=s.historical_apr["7day"];return t!=null&&t>c.OT||t==null?c.OT:t}catch(e){throw e.labelCode!=null?e:new P.OU(e.message,500,this.networkInfo.errorCodes.SERVER_ERROR)}})}multicastServers(e,s){return B(this,null,function*(){const t=yield(0,D.QJ)((0,D.Sy)(this.networkInfo.apiUrls.map(r=>()=>B(this,null,function*(){let o;const l=new F.rn("","",r,this.fetchCors,void 0,this.tpid);try{o=yield l.genericAction(e,s)}catch(a){if(a.errorCode!=null&&P.lI.includes(a.errorCode))o={isError:!0,data:{code:a.errorCode,message:(0,D.HY)(a),json:a.json,list:a.list}};else throw a}return o}))));if(t.isError!=null){const r=new P.OU(t.errorMessage);throw r.json=t.data.json,r.list=t.data.list,r.errorCode=t.data.code,r}return t})}}function Ae(g){return B(this,null,function*(){return new me(g)})}}}]);
1
+ "use strict";(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[805],{79014:function(pe,Z,b){b.d(Z,{Q:function(){return d},k:function(){return ae}});var F=b(77591),ue=b.n(F),E=b(24350),ie=b(84564),Q=b.n(ie),A=b(76714),c=Object.defineProperty,I=Object.getOwnPropertySymbols,ee=Object.prototype.hasOwnProperty,f=Object.prototype.propertyIsEnumerable,C=(w,T,x)=>T in w?c(w,T,{enumerable:!0,configurable:!0,writable:!0,value:x}):w[T]=x,W=(w,T)=>{for(var x in T||(T={}))ee.call(T,x)&&C(w,x,T[x]);if(I)for(var x of I(T))f.call(T,x)&&C(w,x,T[x]);return w};function ae(w,T,x,B,G=[]){const O=W({},Q()(T,{},!0)),z=T.startsWith(`${w.pluginId}://`);if(O.protocol!=null&&(O.protocol=O.protocol.replace(":","")),O.protocol!=null&&O.protocol!==""&&!x[O.protocol])throw new Error(`Uri protocol '${O.protocol}' is not supported for ${w.pluginId}.`);if(O.host===""&&O.pathname==="")throw new Error("Path and host not found in uri.");const L={publicAddress:O.host!==""?O.host:O.pathname.split("/")[0]},te=O.query.label,j=O.query.message,se=O.query.category;(te!=null||j!=null||se!=null||z)&&(L.metadata={},L.metadata.name=te,L.metadata.notes=j,L.metadata.category=se,L.metadata.gateway=z!=null?z:!1);const V=O.query.amount;if(V!=null&&typeof V=="string"){B==null&&(B=w.currencyCode);const J=(0,A.Qs)(B!=null?B:"",w,G);if(J==null)throw new Error("InternalErrorInvalidCurrencyCode");let Y=(0,F.mul)(V,J.multiplier);Y=(0,F.toFixed)(Y,0,0),L.nativeAmount=Y,L.currencyCode=B}return{edgeParsedUri:L,parsedUri:O}}function d(w,T,x){if(w.publicAddress==null)throw new Error("InvalidPublicAddressError");if(x==null&&w.label==null&&w.message==null)return w.publicAddress;{let B="";x!=null&&(B+="amount="+x+"&"),(w.label!=null||w.message!=null)&&(typeof w.label=="string"&&(B+="label="+w.label+"&"),typeof w.message=="string"&&(B+="message="+w.message+"&")),B=B.substr(0,B.length-1);const G={scheme:T,path:w.publicAddress,query:B};return(0,E.qC)(G)}}},44285:function(pe,Z,b){b.r(Z),b.d(Z,{FioTools:function(){return ye},checkAddress:function(){return de},makeCurrencyEngine:function(){return ve},makeCurrencyTools:function(){return Pe}});var F=b(93491),ue=b(45234),E=b(77591),ie=b(2153),Q=b(79014),A=b(76714),c=b(5607),I=b(24827),ee=b(50857),f=b(3559),C=b(37858),W=b(82626),ae=b(37297),d=b(82448),w=b(94935),T=b(84650),x=b(72681);const B=(0,d.su)({fio_domains:(0,d._2)((0,d.su)({fio_domain:d.XC,expiration:d.XC,is_public:d.mH})),fio_addresses:(0,d._2)((0,d.su)({fio_address:d.XC,remaining_bundled_tx:d.mH}))}),G=(0,d.su)({account_action_seq:d.mH,block_num:d.mH,block_time:d.XC,action_trace:(0,d.su)({receiver:d.XC,act:(0,d.su)({account:d.XC,name:d.XC,authorization:(0,d._2)((0,d.su)({actor:d.XC,permission:d.XC})),data:(0,d.su)({payee_public_key:(0,d.Zz)(d.XC),amount:(0,d.Zz)(d.mH),max_fee:(0,d.Zz)(d.mH),actor:(0,d.Zz)(d.XC),tpid:(0,d.Zz)(d.XC),quantity:(0,d.Zz)(d.XC),memo:(0,d.Zz)(d.XC),to:(0,d.Zz)(d.XC),from:(0,d.Zz)(d.XC)}),hex_data:d.XC}),trx_id:d.XC,block_num:d.mH,block_time:d.XC,producer_block_id:d.XC})}),O=(0,d.su)({actions:(0,d._2)(G)}),z=(0,d.su)({balance:d.mH,available:d.mH,staked:d.mH,srps:d.mH,roe:d.XC});var he=Object.defineProperty,L=Object.defineProperties,te=Object.getOwnPropertyDescriptors,j=Object.getOwnPropertySymbols,se=Object.getPrototypeOf,V=Object.prototype.hasOwnProperty,J=Object.prototype.propertyIsEnumerable,Y=Reflect.get,fe=(_,e,s)=>e in _?he(_,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):_[e]=s,S=(_,e)=>{for(var s in e||(e={}))V.call(e,s)&&fe(_,s,e[s]);if(j)for(var s of j(e))J.call(e,s)&&fe(_,s,e[s]);return _},M=(_,e)=>L(_,te(e)),ge=(_,e)=>{var s={};for(var t in _)V.call(_,t)&&e.indexOf(t)<0&&(s[t]=_[t]);if(_!=null&&j)for(var t of j(_))e.indexOf(t)<0&&J.call(_,t)&&(s[t]=_[t]);return s},me=(_,e,s)=>Y(se(_),s,e),g=(_,e,s)=>new Promise((t,n)=>{var o=r=>{try{a(s.next(r))}catch(i){n(i)}},l=r=>{try{a(s.throw(r))}catch(i){n(i)}},a=r=>r.done?t(r.value):Promise.resolve(r.value).then(o,l);a((s=s.apply(_,e)).next())});const ke=1e4,_e=15e3,be=1e4,we=[c.BP[c.aO.transferTokens],c.BP[c.aO.unStakeFioTokens],"regaddress"],De=1e4;class re extends T.P{constructor(e,s,t,n,o){super(e,s,t,n),this.fioRequestsListChanged=(l,a)=>{function r(i,u){for(const m of i)if(u.findIndex(D=>D.fio_request_id===m.fio_request_id)<0)return!0;return!1}return!!(r(l,a)||r(a,l))},this.removeFioRequest=(l,a)=>{const r=this.otherData.fioRequests[a].findIndex(i=>i.fio_request_id===`${l}`);r>-1&&this.otherData.fioRequests[a].splice(r,1)},this.fetchCors=(0,A.zR)(e.io),this.tpid=o,this.networkInfo=e.networkInfo,this.refBlock={expiration:"",ref_block_num:0,ref_block_prefix:0},this.fees=new Map,this.actor=F.rn.accountHash(this.walletInfo.keys.publicKey).accountnm,this.obtData=[],this.otherMethods={fioAction:(l,a)=>g(this,null,function*(){return yield this.multicastServers(l,a)}),getFioAddresses:()=>g(this,null,function*(){return this.otherData.fioAddresses}),getFioAddressNames:()=>g(this,null,function*(){return this.otherData.fioAddresses.map(l=>l.name)}),getFioDomains:()=>g(this,null,function*(){return this.otherData.fioDomains}),getFioRequests:(l,a,r=50)=>g(this,null,function*(){const i=r*(a-1),u=r*a;return this.otherData.fioRequests[l].sort((m,D)=>m.time_stamp<D.time_stamp?1:-1).slice(i,u)}),getObtData:()=>g(this,null,function*(){return this.obtData})}}localDataDirty(){this.walletLocalDataDirty=!0}setOtherData(e){this.otherData=(0,c.CL)(e)}getUTCDate(e){const s=new Date(e);return Date.UTC(s.getFullYear(),s.getMonth(),s.getDate(),s.getHours(),s.getMinutes(),s.getSeconds())}getUnlockDate(e){const s=Math.floor(e.getTime()/c.qj)*c.qj;return new Date(s+c.dm)}checkBlockchainInnerLoop(){return g(this,null,function*(){try{const e=yield this.multicastServers("getChainInfo"),s=e.head_block_num;this.walletLocalData.blockHeight!==s&&(this.checkDroppedTransactionsThrottled(),this.walletLocalData.blockHeight=s,this.localDataDirty(),this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight));const t=yield this.multicastServers("getBlock",e),n=new Date(`${e.head_block_time}Z`);n.setSeconds(n.getSeconds()+180);const o=n.toISOString();this.refBlock={expiration:o.substring(0,o.length-1),ref_block_num:t.block_num&65535,ref_block_prefix:t.ref_block_prefix}}catch(e){this.error("checkBlockchainInnerLoop Error fetching height: ",e)}})}getBalance(e){return super.getBalance(e)}doInitialBalanceCallback(){var e;super.doInitialBalanceCallback();const s=this.networkInfo.balanceCurrencyCodes;for(const t of Object.values(s))try{this.currencyEngineCallbacks.onBalanceChanged(t,(e=this.walletLocalData.totalBalances[t])!=null?e:"0")}catch(n){this.log.error("doInitialBalanceCallback Error for currencyCode",t,n)}try{this.currencyEngineCallbacks.onStakingStatusChanged(S({},this.otherData.stakingStatus))}catch(t){this.error("doInitialBalanceCallback onStakingStatusChanged",t)}}checkUnStakeTx(e){return e.name===c.BP[c.aO.unStakeFioTokens]||e.data!=null&&e.data.memo===c.Nd}updateStakingStatus(e,s,t,n){const o=this.getUnlockDate(new Date(this.getUTCDate(s))),l=this.otherData.stakingStatus.stakedAmounts.findIndex(a=>{var r;return((r=a.unlockDate)==null?void 0:r.getTime())===o.getTime()});if(l<0){const a=this.otherData.stakingStatus.stakedAmounts.findIndex(i=>{var u,m;return o.getTime()>=((m=(u=i.unlockDate)==null?void 0:u.getTime())!=null?m:0)}),r=a<0?this.otherData.stakingStatus.stakedAmounts.length:a;this.otherData.stakingStatus.stakedAmounts.splice(r,0,{nativeAmount:e,unlockDate:o,otherParams:{date:new Date(s),txs:[{txId:t,nativeAmount:e,blockTime:s,txName:n}]}})}else{const a=M(S({},this.otherData.stakingStatus.stakedAmounts[l]),{nativeAmount:"0"}),r=a.otherParams.txs.findIndex(({txId:i,txName:u})=>i===t&&u===n);r<0?a.otherParams.txs.push({txId:t,nativeAmount:e,blockTime:s,txName:n}):a.otherParams.txs[r]={txId:t,nativeAmount:e,blockTime:s,txName:n};for(const i of a.otherParams.txs)a.nativeAmount=(0,E.add)(a.nativeAmount,i.nativeAmount);this.otherData.stakingStatus.stakedAmounts[l]=a}this.localDataDirty();try{this.currencyEngineCallbacks.onStakingStatusChanged(S({},this.otherData.stakingStatus))}catch{this.error("onStakingStatusChanged error")}}getStakingStatus(){return g(this,null,function*(){return S({},this.otherData.stakingStatus)})}processTransaction(e,s,t=this.currencyInfo.currencyCode){var n,o,l,a,r,i,u,m,D;const{act:{name:v,data:R,account:P,authorization:y}}=e.action_trace;let k,H,h="0",p={account:P,name:v,authorization:y,data:R,meta:{}};const N=[];if(e.block_num<=this.otherData.highestTxHeight)return e.block_num;if(we.includes(v)){k="0",v==="regaddress"&&e.action_trace.act.authorization.some(K=>K.actor===this.actor)&&(h=String((n=e.action_trace.act.data.max_fee)!=null?n:0),k=`-${h}`),v===c.BP[c.aO.transferTokens]&&R.amount!=null&&(k=R.amount.toString(),H=R.actor,R.payee_public_key===this.walletInfo.keys.publicKey?(N.push(this.walletInfo.keys.publicKey),H===s&&(k="0")):k=`-${k}`);const U=this.findTransaction(t,e.action_trace.trx_id);if(U>-1){const K=this.transactionList[t][U];if(p=M(S(S({},K.otherParams),p),{data:S(S({},(l=(o=K.otherParams)==null?void 0:o.data)!=null?l:{}),p.data),meta:S(S({},(r=(a=K.otherParams)==null?void 0:a.meta)!=null?r:{}),p.meta)}),p.meta.isTransferProcessed!=null)return e.block_num;p.meta.isFeeProcessed!=null?v===c.BP[c.aO.transferTokens]?(k=(0,E.sub)(k,K.networkFee),h=K.networkFee):(k=K.nativeAmount,h="0"):this.error("processTransaction error - existing spend transaction should have isTransferProcessed or isFeeProcessed set")}this.checkUnStakeTx(p)&&this.updateStakingStatus(R.amount!=null?R.amount.toString():"0",e.block_time,e.action_trace.trx_id,v),p.meta.isTransferProcessed=!0;const $={blockHeight:e.block_num>0?e.block_num:0,currencyCode:t,date:this.getUTCDate(e.block_time)/1e3,isSend:k.startsWith("-"),memos:[],nativeAmount:k,networkFee:h,otherParams:p,ourReceiveAddresses:N,signedTx:"",txid:e.action_trace.trx_id,walletId:this.walletId};this.addTransaction(t,$)}if(v===c.BP.transfer&&R.quantity!=null){const[U]=R.quantity.split(" "),$=U.toString(),K=(0,A.aL)(t,this.currencyInfo,this.allTokensMap);if(K==null)return this.error(`Received unsupported currencyCode: ${t}`),0;const X=(0,E.mul)($,K.multiplier);R.to===s?(k=`${X}`,h=`-${X}`):(k=`-${X}`,h=X);const ne=this.findTransaction(t,e.action_trace.trx_id);if(ne>-1){const oe=this.transactionList[t][ne];if(p=M(S(S({},p),oe.otherParams),{data:S(S({},p.data),(u=(i=oe.otherParams)==null?void 0:i.data)!=null?u:{}),meta:S(S({},p.meta),(D=(m=oe.otherParams)==null?void 0:m.meta)!=null?D:{})}),p.meta.isFeeProcessed!=null)return e.block_num;p.meta.isTransferProcessed!=null?R.to!==s?k=(0,E.sub)(oe.nativeAmount,h):h="0":this.error("processTransaction error - existing spend transaction should have isTransferProcessed or isFeeProcessed set")}this.checkUnStakeTx(p)&&this.updateStakingStatus(X,e.block_time,e.action_trace.trx_id,v),p.meta.isFeeProcessed=!0;const Ee={blockHeight:e.block_num>0?e.block_num:0,currencyCode:t,date:this.getUTCDate(e.block_time)/1e3,isSend:k.startsWith("-"),memos:[],nativeAmount:k,networkFee:h,otherParams:p,ourReceiveAddresses:[],signedTx:"",txid:e.action_trace.trx_id,walletId:this.walletId};this.addTransaction(t,Ee)}return e.block_num}getSortedHistoryNodesLastActionSeqNumbers(){return g(this,null,function*(){const e=this.networkInfo.historyNodeUrls.map((t,n)=>g(this,null,function*(){var o;try{const l=yield this.requestHistory(n,{account_name:this.actor,pos:-1},c.pg.getActions);return((o=l==null?void 0:l.error)==null?void 0:o.noNodeForIndex)!=null?{nodeIndex:n,seqNumber:-1}:(O(l),l.actions.length===0?{nodeIndex:n,seqNumber:-1}:{nodeIndex:n,seqNumber:l.actions[l.actions.length-1].account_action_seq})}catch{return{nodeIndex:n,seqNumber:-1}}})),s=yield Promise.all(e);return s.sort((t,n)=>n.seqNumber-t.seqNumber),s})}checkTransactions(e){return g(this,null,function*(){var s,t;if((e==null?void 0:e.length)===0)return!1;if(e=e!=null?e:yield this.getSortedHistoryNodesLastActionSeqNumbers(),e.reduce((i,u)=>i+u.seqNumber,0)===-e.length)return!0;let n=this.otherData.highestTxHeight;const o=e[0].seqNumber,l=e[0].nodeIndex;let a=Math.max(0,o-c.WX+1),r=!1;for(;!r;){let i;try{if(i=yield this.requestHistory(l,{account_name:this.actor,pos:a,offset:c.WX-1},c.pg.getActions),((s=i.error)==null?void 0:s.noNodeForIndex)!=null)return!1;let u=[];if(((t=i.actions)==null?void 0:t.length)>0)u=i.actions;else break;for(let m=u.length-1;m>-1;m--){const D=u[m];G(D);const v=this.processTransaction(D,this.actor);if(v>n)n=v;else if(v===n&&m===c.WX-1||v<this.otherData.highestTxHeight){r=!0;break}}if(a===0)break;a=Math.max(0,a-c.WX);continue}catch{return yield this.checkTransactions(e.slice(1))}}return n>this.otherData.highestTxHeight&&(this.otherData.highestTxHeight=n,this.localDataDirty()),!0})}checkTransactionsInnerLoop(){return g(this,null,function*(){let e;try{e=yield this.checkTransactions()}catch(s){this.error("checkTransactionsInnerLoop fetches failed with error: ",s);return}e&&(this.tokenCheckTransactionsStatus.FIO=1,this.updateOnAddressesChecked()),this.transactionsChangedArray.length>0&&(this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[])})}requestHistory(e,s,t){return g(this,null,function*(){if(this.networkInfo.historyNodeUrls[e]==null)return{error:{noNodeForIndex:!0}};const n=this.networkInfo.historyNodeUrls[e],o=JSON.stringify(s);return yield(yield fetch(`${n}history/${t}`,{method:"POST",headers:{"Content-Length":(o.length*2).toString(),Accept:"application/json","Content-Type":"application/json"},body:o})).json()})}fioApiRequest(e,s,t,n=!1){return g(this,null,function*(){var o,l,a,r;const i=new F.rn("",this.walletInfo.keys.publicKey,e,this.fetchCors,void 0,this.tpid,n);let u;try{switch(s){case"getChainInfo":u=yield i.transactions.getChainInfo();break;case"getBlock":u=yield i.transactions.getBlock(t);break;case"getObtData":case"getPendingFioRequests":case"getSentFioRequests":{const{endpoint:m,body:D}=t;u=yield i.transactions.executeCall(m,JSON.stringify(D));break}default:u=yield i.genericAction(s,t)}}catch(m){if(m.errorCode!=null&&I.lI.includes(m.errorCode))((a=(l=(o=m.json)==null?void 0:o.fields)==null?void 0:l[0])==null?void 0:a.error)!=null&&(m.message=m.json.fields[0].error),u={isError:!0,data:{code:m.errorCode,message:(r=m.message)!=null?r:(0,A.HY)(m),json:m.json,list:m.list}},m.errorCode!==404&&this.log(`fioApiRequest error. actionName: ${s} - apiUrl: ${e} - message: ${JSON.stringify(m.json)}`);else throw this.log(`fioApiRequest error. actionName: ${s} - apiUrl: ${e} - message: `,m),m}return u})}executePreparedTrx(e,s,t){return g(this,null,function*(){var n,o,l;const a=new F.rn("",this.walletInfo.keys.publicKey,e,this.fetchCors,void 0,this.tpid,!0);let r;this.warn(`executePreparedTrx. preparedTrx: ${JSON.stringify(t)} - apiUrl: ${e}`);try{r=yield a.executePreparedTrx(s,t),this.warn(`executePreparedTrx. res: ${JSON.stringify(r)} - apiUrl: ${e} - endpoint: ${s}`)}catch(i){throw i.errorCode!=null&&I.lI.includes(i.errorCode)?(this.log(`executePreparedTrx error. requestParams: ${JSON.stringify(t)} - apiUrl: ${e} - endpoint: ${s} - message: ${JSON.stringify(i.json)}`),((l=(o=(n=i.json)==null?void 0:n.fields)==null?void 0:o[0])==null?void 0:l.error)!=null&&(i.message=i.json.fields[0].error),i):(this.log(`executePreparedTrx error. requestParams: ${JSON.stringify(t)} - apiUrl: ${e} - endpoint: ${s} - message: `,i),i)}return r})}multicastServers(e,s){return g(this,null,function*(){var t,n,o,l,a;let r;if(c.K1[e]){const i=(0,f.h0)(s);if(this.warn(`multicastServers executePreparedTrx. actionName: ${e} - res: ${JSON.stringify(i)}`),r=yield(0,A.Wp)((0,A.Sy)(this.networkInfo.apiUrls.map(u=>g(this,null,function*(){return yield(0,A.Vs)(this.executePreparedTrx(u,C.EndPoint[c.VW[e]],i),1e4)})))),this.warn(`multicastServers res. actionName: ${e} - res: ${JSON.stringify(r)}`),r==null)throw new Error("Service is unavailable")}else e==="getFioNames"?(r=yield(0,A.ml)(this.networkInfo.apiUrls.map(i=>g(this,null,function*(){return yield(0,A.Vs)(this.fioApiRequest(i,e,s),1e4)})),i=>{const u=(0,f.$K)(c.Mi)(i);return u!=null?u.data.json.message:(0,f.e1)(i)},2),((n=(t=r==null?void 0:r.data)==null?void 0:t.json)==null?void 0:n.message)===c.Mi&&(r={fio_domains:[],fio_addresses:[]})):e==="getFioBalance"?(r=yield(0,A.ml)(this.networkInfo.apiUrls.map(i=>g(this,null,function*(){return yield(0,A.Vs)(this.fioApiRequest(i,e,s),1e4)})),i=>{const u=(0,f.$K)(c.d9)(i);return u!=null?u.data.json.message:(0,f.sq)(i)},2),((l=(o=r==null?void 0:r.data)==null?void 0:o.json)==null?void 0:l.message)===c.d9&&(r={balance:0,available:0,staked:0,srps:0,roe:""})):e==="getFees"?r=yield(0,A.QJ)((0,A.Sy)(this.networkInfo.apiUrls.map(i=>()=>g(this,null,function*(){const u=new F.rn("",this.walletInfo.keys.publicKey,i,this.fetchCors,void 0,this.tpid),{endpoint:m,param:D}=s,v=yield u.getFee(m,D);return(0,f.lZ)(v).fee.toString()})))):r=yield(0,A.QJ)((0,A.Sy)(this.networkInfo.apiUrls.map(i=>()=>g(this,null,function*(){return yield this.fioApiRequest(i,e,s)}))));if(r.isError!=null){const i=new I.OU((a=r.errorMessage)!=null?a:r.data.message);throw i.json=r.data.json,i.list=r.data.list,i.errorCode=r.data.code,i}return r})}checkAccountInnerLoop(){return g(this,null,function*(){const e=this.currencyInfo.currencyCode,s=this.networkInfo.balanceCurrencyCodes;typeof this.walletLocalData.totalBalances[e]>"u"&&this.updateBalance(e,"0");try{const t={staked:"0",locked:"0"},{balance:n,available:o,staked:l,srps:a,roe:r}=z(yield this.multicastServers("getFioBalance")),i=String(n);t.staked=String(l),t.locked=(0,E.sub)(i,String(o)),this.otherData.srps=a,this.otherData.stakingRoe=r,this.updateBalance(e,i),this.updateBalance(s.staked,t.staked),this.updateBalance(s.locked,t.locked)}catch(t){this.log.warn("checkAccountInnerLoop getFioBalance error: ",t)}try{const t=B(yield this.multicastServers("getFioNames",{fioPublicKey:this.walletInfo.keys.publicKey}));let n=!1,o=!1,l=!1;if(t.fio_addresses.length!==this.otherData.fioAddresses.length)o=!0;else{for(const a of t.fio_addresses){const r=this.otherData.fioAddresses.find(i=>i.name===a.fio_address);if(r!=null){if(r.bundledTxs!==a.remaining_bundled_tx){o=!0;break}}else{o=!0;break}}if(!o){for(const a of this.otherData.fioAddresses)if(t.fio_addresses.findIndex(r=>r.fio_address===a.name)<0){o=!0;break}}}if(t.fio_domains.length!==this.otherData.fioDomains.length)l=!0;else{for(const a of t.fio_domains){const r=this.otherData.fioDomains.find(i=>i.name===a.fio_domain);if(r!=null){if(r.expiration!==a.expiration){l=!0;break}if(r.isPublic!==(a.is_public===1)){l=!0;break}}else{l=!0;break}}if(!l){for(const a of this.otherData.fioDomains)if(t.fio_domains.findIndex(r=>r.fio_domain===a.name)<0){l=!0;break}}}o&&(n=!0,this.otherData.fioAddresses=t.fio_addresses.map(a=>({name:a.fio_address,bundledTxs:a.remaining_bundled_tx}))),l&&(n=!0,this.otherData.fioDomains=t.fio_domains.map(a=>({name:a.fio_domain,expiration:a.expiration,isPublic:a.is_public===1}))),n&&this.localDataDirty()}catch(t){this.warn("checkAccountInnerLoop getFioNames error: ",t)}})}fetchEncryptedFioRequests(e,s){return g(this,null,function*(){const n=e==="PENDING"?"getPendingFioRequests":"getSentFioRequests";let o=100,l=1;const a=[];for(;o===100;)try{const r=yield this.multicastServers(n,{endpoint:s.getEndPoint(),body:{fio_public_key:this.walletInfo.keys.publicKey,limit:100,offset:(l-1)*100}}),i=(0,f.S_)(r),{requests:u,more:m}=i;if(a.push(...u),m===0)break;l++,o=u.length}catch(r){const i=(0,d.Vk)(f.Pq)(r.json);(i==null?void 0:i.message)!=="No FIO Requests"&&this.error("fetchEncryptedFioRequests error: ",r);break}return a})}fetchEncryptedObtData(e,s){return g(this,null,function*(){let n=100,o=1;const l=[];for(;n===100;){let a;try{a=yield this.multicastServers(e,{endpoint:s.getEndPoint(),body:{fio_public_key:this.walletInfo.keys.publicKey,limit:100,offset:(o-1)*100}});const r=(0,f._v)(a),{obt_data_records:i,more:u}=r;if(l.push(...i),u===0)break;o++,n=i.length}catch(r){const i=(0,d.Vk)(f.Pq)(r.json);(i==null?void 0:i.message)!=="No FIO Requests"&&this.error("fetchEncryptedObtData error: ",r);break}}return l})}syncNetwork(e){return g(this,null,function*(){var s;const t=(0,f.UW)(e==null?void 0:e.privateKeys);let n=!1;const o=(i,u)=>g(this,null,function*(){var m;const D=yield this.fetchEncryptedFioRequests(i,u);u.privateKey=t.fioKey,u.publicKey=this.walletInfo.keys.publicKey;const v=(m=u.decrypt({requests:D}))!=null?m:{requests:[]};this.fioRequestsListChanged(this.otherData.fioRequests[i],v.requests)&&(this.otherData.fioRequests[i]=[...v.requests],n=!0)});yield o("PENDING",new W.PendingFioRequests(this.walletInfo.keys.publicKey)),yield o("SENT",new W.SentFioRequests(this.walletInfo.keys.publicKey)),n&&this.localDataDirty();const l=new W.GetObtData(this.walletInfo.keys.publicKey),a=yield this.fetchEncryptedObtData("getObtData",l);l.privateKey=t.fioKey,l.publicKey=this.walletInfo.keys.publicKey;const r=(s=l.decrypt({obt_data_records:a}))!=null?s:{obt_data_records:[]};return this.obtData=r.obt_data_records,De})}getFee(e,s){return g(this,null,function*(){let t=this.fees.get(e);if(t==null||t.expiration+30*1e3<Date.now()){const o={fee:yield this.multicastServers("getFees",{endpoint:e,param:s}),expiration:Date.now()};this.fees.set(e,o),t=o}return t.fee})}startEngine(){return g(this,null,function*(){this.engineOn=!0,this.addToLoop("checkBlockchainInnerLoop",_e).catch(()=>{}),this.addToLoop("checkAccountInnerLoop",ke).catch(()=>{}),this.addToLoop("checkTransactionsInnerLoop",be).catch(()=>{}),yield me(re.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return g(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getMaxSpendable(e){return g(this,null,function*(){var s;e=(0,x.s)(e,this.currencyInfo);const t=this.getBalance({currencyCode:e.currencyCode}),n=(s=this.walletLocalData.totalBalances[this.networkInfo.balanceCurrencyCodes.locked])!=null?s:"0";e.spendTargets[0].nativeAmount="1";const o=yield this.makeSpend(e),l=(0,E.sub)((0,E.sub)(t,o.networkFee),n);if((0,E.lt)(l,"0"))throw new w.C_({networkFee:o.networkFee});return l})}makeSpend(e){return g(this,null,function*(){var s,t;e=(0,x.s)(e,this.currencyInfo);const{edgeSpendInfo:n,nativeBalance:o,currencyCode:l}=this.makeSpendCheck(e),{memos:a=[]}=n,r=(s=this.walletLocalData.totalBalances[this.networkInfo.balanceCurrencyCodes.locked])!=null?s:"0",i=(0,E.sub)(o,r),u=n.spendTargets[0],{publicAddress:m}=u,{nativeAmount:D}=u;if(m==null)throw new Error("makeSpend Missing publicAddress");if(D==null)throw new w.$D;let{otherParams:v}=n;(v==null||Object.keys(v).length===0)&&(v={action:{name:c.aO.transferTokens,params:{payeeFioPublicKey:m,amount:D,maxFee:0}}});const{name:R,params:P}=(0,f.iR)(v.action);let y,k;switch(R){case c.aO.transferTokens:{y=yield this.getFee(C.EndPoint.transferTokens),k={account:"fio.token",action:c.BP[c.aO.transferTokens],data:{payee_public_key:m,amount:D,max_fee:y}};break}case c.aO.stakeFioTokens:{const{fioAddress:h}=(0,f.NB)(P);y=yield this.getFee(C.EndPoint.stakeFioTokens,h),k={account:"fio.staking",action:c.BP[R],data:{amount:D,fio_address:h,actor:this.actor,max_fee:y}};break}case c.aO.unStakeFioTokens:{const{fioAddress:h}=(0,f.NB)(P);y=yield this.getFee(C.EndPoint.unStakeFioTokens,h),k={account:"fio.staking",action:c.BP[R],data:{amount:D,fio_address:h,actor:this.actor,max_fee:y}};const p=this.getUnlockDate(new Date),N=(t=this.walletLocalData.totalBalances[this.networkInfo.balanceCurrencyCodes.staked])!=null?t:"0";if((0,E.gt)(D,N)||(0,E.gt)(`${y}`,i))throw new w.C_;const U=(0,E.mul)((0,E.mul)((0,E.div)(D,N,18),`${this.otherData.srps}`),this.otherData.stakingRoe),$=(0,E.max)((0,E.sub)(U,D),"0");v.ui={accrued:U,estReward:$,unlockDate:p};break}case c.aO.transferFioAddress:{const{fioAddress:h}=(0,f.NB)(P);y=yield this.getFee(C.EndPoint.transferFioAddress,h),k={account:"fio.address",action:"xferaddress",data:{fio_address:h,new_owner_fio_public_key:m,actor:this.actor,max_fee:y}};break}case c.aO.transferFioDomain:{const{fioDomain:h}=(0,f.L2)(P);y=yield this.getFee(C.EndPoint.transferFioDomain),k={account:"fio.address",action:"xferdomain",data:{fio_domain:h,new_owner_fio_public_key:m,actor:this.actor,max_fee:y}};break}case c.aO.addPublicAddresses:{const{fioAddress:h,publicAddresses:p}=(0,f.PH)(P);y=yield this.getFee(C.EndPoint.addPubAddress,h),k={account:"fio.address",action:"addaddress",data:{fio_address:h,public_addresses:p,actor:this.actor,max_fee:y}};break}case c.aO.removePublicAddresses:{const{fioAddress:h,publicAddresses:p}=(0,f.PH)(P);y=yield this.getFee(C.EndPoint.removePubAddress,h),k={account:"fio.address",action:"remaddress",data:{fio_address:h,public_addresses:p,actor:this.actor,max_fee:y}};break}case c.aO.registerFioAddress:{const{fioAddress:h}=(0,f.NB)(P);y=yield this.getFee(C.EndPoint.registerFioAddress),k={account:"fio.address",action:"regaddress",data:{fio_address:h,owner_fio_public_key:this.walletInfo.keys.publicKey,max_fee:y,actor:this.actor}};break}case c.aO.registerFioDomain:{const{fioDomain:h}=(0,f.AJ)(P);y=yield this.getFee(C.EndPoint.registerFioDomain),k={account:"fio.address",action:"regdomain",data:{fio_domain:h,owner_fio_public_key:this.walletInfo.keys.publicKey,max_fee:y,actor:this.actor}};break}case c.aO.renewFioDomain:{const{fioDomain:h}=(0,f.AJ)(P);y=yield this.getFee(C.EndPoint.renewFioDomain),k={account:"fio.address",action:"renewdomain",data:{fio_domain:h,max_fee:y,actor:this.actor}};break}case c.aO.addBundledTransactions:{const{bundleSets:h,fioAddress:p}=(0,f.Ej)(P);y=yield this.getFee(C.EndPoint.addBundledTransactions,p),k={account:"fio.address",action:"addbundles",data:{fio_address:p,bundle_sets:h,actor:this.actor,max_fee:y}};break}case c.aO.setFioDomainPublic:{const{fioDomain:h,isPublic:p}=(0,f.oY)(P);y=yield this.getFee(C.EndPoint.setFioDomainPublic),k={account:"fio.address",action:"setdomainpub",data:{fio_domain:h,is_public:p?1:0,max_fee:y,actor:this.actor}};break}case c.aO.rejectFundsRequest:{const{fioRequestId:h,payerFioAddress:p}=(0,f.OR)(P);y=yield this.getFee(C.EndPoint.rejectFundsRequest,p),k={account:"fio.reqobt",action:"rejectfndreq",data:{fio_request_id:h,max_fee:y,actor:this.actor}};break}case c.aO.cancelFundsRequest:{const{fioAddress:h,fioRequestId:p}=(0,f.mO)(P);y=yield this.getFee(C.EndPoint.cancelFundsRequest,h),k={account:"fio.reqobt",action:"cancelfndreq",data:{fio_request_id:p,max_fee:y,actor:this.actor}};break}case c.aO.recordObtData:{const{payerFioAddress:h}=(0,f.XB)(P);y=yield this.getFee(C.EndPoint.recordObtData,h);break}case c.aO.requestFunds:{const{payeeFioAddress:h}=(0,f.Vd)(P);y=yield this.getFee(C.EndPoint.newFundsRequest,h);break}default:throw new Error("Unrecognized FIO action")}return{blockHeight:0,currencyCode:l,date:0,isSend:!0,memos:a,nativeAmount:(0,E.sub)(`-${D}`,`${y}`),networkFee:`${y}`,otherParams:M(S({},v),{txParams:k}),ourReceiveAddresses:[],signedTx:"",txid:"",walletId:this.walletId}})}signTx(e,s){return g(this,null,function*(){const t=(0,f.UW)(s),n=(0,A.Xp)(e);let o=(0,d.Vk)(f.B3)(n.txParams);const l=new ae.Transactions;if(o==null){const{name:m,params:D}=(0,f.iR)(n.action),{networkFee:v}=e;switch(m){case c.aO.recordObtData:{const{payerFioAddress:R,payeeFioAddress:P,payerPublicAddress:y,payeePublicAddress:k,amount:H,tokenCode:h,chainCode:p,obtId:N,memo:U,status:$,fioRequestId:K}=(0,f.XB)(D),X={payer_public_address:y,payee_public_address:k,amount:H,chain_code:p,token_code:h,status:$,obt_id:N,memo:U,hash:void 0,offline_url:void 0},ne=l.getCipherContent("record_obt_data_content",X,t.fioKey,y);o={account:"fio.reqobt",action:"recordobt",data:{payer_fio_address:R,payee_fio_address:P,content:ne,fio_request_id:K,max_fee:v,actor:this.actor}};break}case c.aO.requestFunds:{const{payerFioAddress:R,payerFioPublicKey:P,payeeFioAddress:y,payeeTokenPublicAddress:k,amount:H,chainCode:h,tokenCode:p,memo:N}=(0,f.Vd)(D),U={payee_public_address:k,amount:H,chain_code:h,token_code:p,memo:N,hash:void 0,offline_url:void 0},$=l.getCipherContent("new_funds_content",U,t.fioKey,P);o={account:"fio.reqobt",action:"newfundsreq",data:{payer_fio_address:R,payee_fio_address:y,content:$,max_fee:v,actor:this.actor}};break}default:throw new Error("Unknown FIO action")}}const a=yield l.createRawTransaction({action:o.action,account:o.account,data:M(S({},o.data),{tpid:this.tpid}),publicKey:this.walletInfo.keys.publicKey,chainData:this.refBlock}),{serializedContextFreeData:r,serializedTransaction:i}=yield l.serialize({chainId:this.networkInfo.chainId,transaction:a}),u=yield l.sign({chainId:this.networkInfo.chainId,privateKeys:[t.fioKey],transaction:a,serializedTransaction:i,serializedContextFreeData:r});return e.otherParams=M(S({},e.otherParams),{signedTx:u}),e})}broadcastTx(e){return g(this,null,function*(){var s;const t=(0,A.Xp)(e);if(((s=t.action)==null?void 0:s.name)==null)throw new Error('Action is not set, "action" prop of otherParams is required for FIO actions');const n=(0,f.h0)(t.signedTx),o=(0,f.Yd)(yield this.multicastServers(t.action.name,n));e.metadata={notes:o.transaction_id},e.txid=o.transaction_id,e.date=Date.now()/1e3,e.blockHeight=o.block_num,this.warn(`SUCCESS broadcastTx
2
+ ${(0,A.oX)(e)}`);const l=o,{block_num:a,block_time:r,transaction_id:i}=l,u=ge(l,["block_num","block_time","transaction_id"]);return e.otherParams=M(S({},t),{broadcastResult:u}),e})}saveTx(e){return g(this,null,function*(){var s;const t=(0,A.Xp)(e),{broadcastResult:n={},action:o}=t,{name:l,params:a}=(0,f.iR)(o);try{switch(l){case c.aO.transferFioDomain:{const r=this.otherData.fioDomains.findIndex(({name:i})=>i===a.fioDomain);r>=0&&(this.otherData.fioDomains.splice(r,1),this.localDataDirty());break}case c.aO.transferFioAddress:{const r=this.otherData.fioAddresses.findIndex(({name:i})=>i===a.fioAddress);r>=0&&(this.otherData.fioAddresses.splice(r,1),this.localDataDirty());break}case c.aO.registerFioAddress:{const{fioAddress:r}=(0,f.NB)(a);this.otherData.fioAddresses.find(({name:u})=>u===r)==null&&(this.otherData.fioAddresses.push({name:r,bundledTxs:void 0}),this.localDataDirty());break}case c.aO.registerFioDomain:{const{fioDomain:r}=(0,f.AJ)(a);if(n.expiration==null)throw new Error("expiration not present");const i=this.otherData.fioDomains.find(({name:u})=>u===r);i!=null&&(i.expiration=n.expiration,this.localDataDirty());break}case c.aO.renewFioDomain:{const{fioDomain:r}=(0,f.AJ)(a);if(n.expiration==null)throw new Error("expiration not present");const i=this.otherData.fioDomains.find(({name:u})=>u===r);i!=null&&(i.expiration=n.expiration,this.localDataDirty());break}case c.aO.addBundledTransactions:{const{fioAddress:r}=(0,f.Ej)(a),i=this.otherData.fioAddresses.find(({name:u})=>u===r);if(i==null)throw new I.OU("Fio Address is not found in engine");i.bundledTxs=((s=i.bundledTxs)!=null?s:0)+c.BB,this.localDataDirty();break}case c.aO.rejectFundsRequest:{const{fioRequestId:r}=(0,f.OR)(a);typeof r=="string"&&(this.removeFioRequest(r,"PENDING"),this.localDataDirty());break}case c.aO.cancelFundsRequest:{const{fioRequestId:r}=(0,f.mO)(a);typeof r=="string"&&(this.removeFioRequest(r,"SENT"),this.localDataDirty());break}case c.aO.recordObtData:{const{fioRequestId:r}=(0,f.XB)(a);r!=null&&n.status==="sent_to_blockchain"&&(this.removeFioRequest(r,"PENDING"),this.localDataDirty());break}}}catch(r){this.log.warn(`Error attempting post-broadcast action ${l}:`,r)}yield me(re.prototype,this,"saveTx").call(this,e)})}getFreshAddress(e){return g(this,null,function*(){return{publicAddress:this.walletInfo.keys.publicKey}})}}function ve(_,e,s,t){return g(this,null,function*(){const{tpid:n="finance@edge"}=_.initOptions,o=(0,f.RB)(s),l=new re(_,e,o,t,n);return yield l.loadEngine(),l})}var Ae=b(48764).Buffer,q=(_,e,s)=>new Promise((t,n)=>{var o=r=>{try{a(s.next(r))}catch(i){n(i)}},l=r=>{try{a(s.throw(r))}catch(i){n(i)}},a=r=>r.done?t(r.value):Promise.resolve(r.value).then(o,l);a((s=s.apply(_,e)).next())});const le="FIO",ce="fio",Ie="";function de(_){const e=_.startsWith(le),s=_.length===53;return e&&s}class ye{constructor(e){const{builtinTokens:s,currencyInfo:t,initOptions:n,io:o,networkInfo:l}=e;this.builtinTokens=s,this.currencyInfo=t,this.io=o,this.networkInfo=l;const{tpid:a="finance@edge",fioRegApiToken:r=Ie}=n;this.fetchCors=(0,A.zR)(e.io),this.fioRegApiToken=r,this.tpid=a;for(const i of this.networkInfo.apiUrls)new F.rn("","",i,this.fetchCors,void 0,a)}getDisplayPrivateKey(e){return q(this,null,function*(){return(0,f.UW)(e.keys).fioKey})}getDisplayPublicKey(e){return q(this,null,function*(){const{keys:s}=(0,f.RB)(e);return s.publicKey})}importPrivateKey(e){return q(this,null,function*(){const{pluginId:s}=this.currencyInfo,t={};if(/[0-9a-zA-Z]{51}$/.test(e))ue._q.fromString(e),t.fioKey=e;else{if(!(0,ie.validateMnemonic)(e))throw new Error("Invalid input");const o=yield F.rn.createPrivateKeyMnemonic(e);t.fioKey=o.fioKey,t.mnemonic=o.mnemonic}const n=yield this.derivePublicKey({type:`wallet:${s}`,id:"fake",keys:t});return t.publicKey=n.publicKey,t})}createPrivateKey(e){return q(this,null,function*(){if(e.replace("wallet:","")===ce){const t=Ae.from(this.io.random(32));return yield F.rn.createPrivateKey(t)}else throw new Error("InvalidWalletType")})}derivePublicKey(e){return q(this,null,function*(){if(e.type.replace("wallet:","")===ce)return F.rn.derivedPublicKey(e.keys.fioKey);throw new Error("InvalidWalletType")})}parseUri(e){return q(this,null,function*(){var s;const{edgeParsedUri:t}=(0,Q.k)(ee.j,e,{fio:!0},le);if(!de((s=t.publicAddress)!=null?s:""))throw new Error("InvalidPublicAddressError");return t})}encodeUri(e){return q(this,arguments,function*(s,t=[]){if(!de(s.publicAddress))throw new Error("InvalidPublicAddressError");let o;if(typeof s.nativeAmount=="string"){const a=le,r=s.nativeAmount,i=(0,A.Qs)(a,ee.j,t);if(i==null)throw new Error("InternalErrorInvalidCurrencyCode");o=(0,E.div)(r,i.multiplier,16)}return(0,Q.Q)(s,ce,o)})}getConnectedPublicAddress(e,s,t){return q(this,null,function*(){var n;try{F.rn.isFioAddressValid(e)}catch{throw new I.OU("",400,this.networkInfo.errorCodes.INVALID_FIO_ADDRESS)}try{if((yield this.multicastServers("isAvailable",{fioName:e})).is_registered===0)throw new I.OU("",404,this.networkInfo.errorCodes.FIO_ADDRESS_IS_NOT_EXIST)}catch(o){throw o.name==="FioError"&&((n=o.json)==null?void 0:n.fields)!=null&&o.errorCode===400&&(o.labelCode=this.networkInfo.errorCodes.INVALID_FIO_ADDRESS),o}try{const o=yield this.multicastServers("getPublicAddress",{fioAddress:e,chainCode:s,tokenCode:t});if(o.public_address==null||o.public_address==="0")throw new I.OU("",404,this.networkInfo.errorCodes.FIO_ADDRESS_IS_NOT_LINKED);return o}catch(o){throw o.name==="FioError"&&o.labelCode===this.networkInfo.errorCodes.FIO_ADDRESS_IS_NOT_LINKED||o.errorCode===404?new I.OU("",404,this.networkInfo.errorCodes.FIO_ADDRESS_IS_NOT_LINKED):o}})}isFioAddressValid(e){return q(this,null,function*(){try{return F.rn.isFioAddressValid(e)}catch{return!1}})}validateAccount(e,s=!1){return q(this,null,function*(){var t;try{if(s){if(!F.rn.isFioDomainValid(e))return!1}else if(!F.rn.isFioAddressValid(e))return!1}catch{throw new I.OU("",400,this.networkInfo.errorCodes.INVALID_FIO_ADDRESS)}try{return(yield this.multicastServers("isAvailable",{fioName:e})).is_registered===0}catch(n){throw n.name==="FioError"&&((t=n.json)==null?void 0:t.fields)!=null&&n.errorCode===400&&(n.labelCode=this.networkInfo.errorCodes.INVALID_FIO_ADDRESS),n}})}isDomainPublic(e){return q(this,null,function*(){if((yield this.multicastServers("isAvailable",{fioName:e})).is_registered===0)throw new I.OU("",400,this.networkInfo.errorCodes.FIO_DOMAIN_IS_NOT_EXIST);const t=yield this.fetchCors(`${this.networkInfo.fioRegApiUrl}${c.n3.isDomainPublic}/${e}`,{method:"GET"});if(!t.ok){const o=yield t.json();throw new I.OU("",t.status,this.networkInfo.errorCodes.IS_DOMAIN_PUBLIC_ERROR,o)}const{isPublic:n}=yield t.json();return n})}doesAccountExist(e){return q(this,null,function*(){try{if(!F.rn.isFioAddressValid(e))return!1}catch{return!1}try{return(yield this.multicastServers("isAvailable",{fioName:e})).is_registered===1}catch(s){return this.error("doesAccountExist error: ",s),!1}})}buyAddressRequest(e,s=!1){return q(this,null,function*(){const t={Accept:"application/json","Content-Type":"application/json"};s&&(e.apiToken=this.fioRegApiToken);try{const n=yield this.fetchCors(`${this.networkInfo.fioRegApiUrl}${c.n3.buyAddress}`,{method:"POST",headers:t,body:JSON.stringify(e)});if(!n.ok){const o=yield n.json();throw this.networkInfo.errorCodes[o.errorCode]!=null?new I.OU(o.error,n.status,this.networkInfo.errorCodes[o.errorCode],o):o.error==="Already registered"?new I.OU(o.error,n.status,this.networkInfo.errorCodes.ALREADY_REGISTERED,o):new Error(o.error)}return yield n.json()}catch(n){throw n.labelCode!=null?n:new I.OU((0,A.HY)(n),500,this.networkInfo.errorCodes.SERVER_ERROR)}})}getDomains(e=""){return q(this,null,function*(){e==null&&(e=this.networkInfo.defaultRef);try{const s=yield this.fetchCors(`${this.networkInfo.fioRegApiUrl}${c.n3.getDomains}/${e}`,{method:"GET"}),t=yield s.json();if(!s.ok)throw this.networkInfo.errorCodes[t.errorCode]!=null?new I.OU(t.error,s.status,this.networkInfo.errorCodes[t.errorCode],t):new Error(t.error);return t.domains}catch(s){throw s.labelCode!=null?s:new I.OU((0,A.HY)(s),500,this.networkInfo.errorCodes.SERVER_ERROR)}})}getStakeEstReturn(){return q(this,null,function*(){try{const e=yield this.fetchCors(`${this.networkInfo.fioStakingApyUrl}`,{method:"GET"}),s=yield e.json();if(!e.ok)throw new Error(this.networkInfo.errorCodes.SERVER_ERROR);const t=s.historical_apr["7day"];return t!=null&&t>c.OT||t==null?c.OT:t}catch(e){throw e.labelCode!=null?e:new I.OU(e.message,500,this.networkInfo.errorCodes.SERVER_ERROR)}})}multicastServers(e,s){return q(this,null,function*(){const t=yield(0,A.QJ)((0,A.Sy)(this.networkInfo.apiUrls.map(n=>()=>q(this,null,function*(){let o;const l=new F.rn("","",n,this.fetchCors,void 0,this.tpid);try{o=yield l.genericAction(e,s)}catch(a){if(a.errorCode!=null&&I.lI.includes(a.errorCode))o={isError:!0,data:{code:a.errorCode,message:(0,A.HY)(a),json:a.json,list:a.list}};else throw a}return o}))));if(t.isError!=null){const n=new I.OU(t.errorMessage);throw n.json=t.data.json,n.list=t.data.list,n.errorCode=t.data.code,n}return t})}}function Pe(_){return q(this,null,function*(){return new ye(_)})}}}]);
@@ -1,2 +1,2 @@
1
- (self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[894],{79014:function(X,R,f){"use strict";f.d(R,{Q:function(){return G},k:function(){return q}});var g=f(77591),b=f.n(g),B=f(24350),L=f(84564),S=f.n(L),E=f(76714),H=Object.defineProperty,j=Object.getOwnPropertySymbols,K=Object.prototype.hasOwnProperty,D=Object.prototype.propertyIsEnumerable,F=(l,y,p)=>y in l?H(l,y,{enumerable:!0,configurable:!0,writable:!0,value:p}):l[y]=p,W=(l,y)=>{for(var p in y||(y={}))K.call(y,p)&&F(l,p,y[p]);if(j)for(var p of j(y))D.call(y,p)&&F(l,p,y[p]);return l};function q(l,y,p,w,_=[]){const d=W({},S()(y,{},!0)),O=y.startsWith(`${l.pluginId}://`);if(d.protocol!=null&&(d.protocol=d.protocol.replace(":","")),d.protocol!=null&&d.protocol!==""&&!p[d.protocol])throw new Error(`Uri protocol '${d.protocol}' is not supported for ${l.pluginId}.`);if(d.host===""&&d.pathname==="")throw new Error("Path and host not found in uri.");const I={publicAddress:d.host!==""?d.host:d.pathname.split("/")[0]},v=d.query.label,x=d.query.message,$=d.query.category;(v!=null||x!=null||$!=null||O)&&(I.metadata={},I.metadata.name=v,I.metadata.notes=x,I.metadata.category=$,I.metadata.gateway=O!=null?O:!1);const N=d.query.amount;if(N!=null&&typeof N=="string"){w==null&&(w=l.currencyCode);const A=(0,E.Qs)(w!=null?w:"",l,_);if(A==null)throw new Error("InternalErrorInvalidCurrencyCode");let M=(0,g.mul)(N,A.multiplier);M=(0,g.toFixed)(M,0,0),I.nativeAmount=M,I.currencyCode=w}return{edgeParsedUri:I,parsedUri:d}}function G(l,y,p){if(l.publicAddress==null)throw new Error("InvalidPublicAddressError");if(p==null&&l.label==null&&l.message==null)return l.publicAddress;{let w="";p!=null&&(w+="amount="+p+"&"),(l.label!=null||l.message!=null)&&(typeof l.label=="string"&&(w+="label="+l.label+"&"),typeof l.message=="string"&&(w+="message="+l.message+"&")),w=w.substr(0,w.length-1);const _={scheme:y,path:l.publicAddress,query:w};return(0,B.qC)(_)}}},20212:function(X,R,f){"use strict";f.r(R),f.d(R,{HederaTools:function(){return J},makeCurrencyEngine:function(){return N},makeCurrencyTools:function(){return tt}});var g=f(17481),b=f(77591),B=f(2153),L=f(79014),S=f(76714),E=f(825);const H=(c="")=>/^(0|(?:[1-9]\d*))\.(0|(?:[1-9]\d*))\.(0|(?:[1-9]\d*))(?:-([a-z]{5}))?$/.test(c),j=(c,t)=>{let e="";const r=[];let n=0,o=0,i=0,a=0,s=0,h=0;const m=26*26*26,P=26*26*26*26*26,C=97,T=1000003,Q=31,k=`${t}000000000000`,U=[];for(let u=0;u<k.length;u+=2)U.push(parseInt(k.substr(u,2),16));for(let u=0;u<c.length;u++)r.push(c[u]==="."?10:parseInt(c[u],10));for(let u=0;u<r.length;u++)i=(Q*i+r[u])%m,u%2===0?n=(n+r[u])%11:o=(o+r[u])%11;for(let u=0;u<U.length;u++)a=(Q*a+U[u])%P;s=(((c.length%5*11+n)*11+o)*m+i+a)%P,h=s*T%P;for(let u=0;u<5;u++)e=String.fromCharCode(C+h%26)+e,h/=26;return e};var K=f(94935),D=f(35620),F=f(84650),W=Object.defineProperty,q=Object.defineProperties,G=Object.getOwnPropertyDescriptors,l=Object.getOwnPropertySymbols,y=Object.getPrototypeOf,p=Object.prototype.hasOwnProperty,w=Object.prototype.propertyIsEnumerable,_=Reflect.get,d=(c,t,e)=>t in c?W(c,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):c[t]=e,O=(c,t)=>{for(var e in t||(t={}))p.call(t,e)&&d(c,e,t[e]);if(l)for(var e of l(t))w.call(t,e)&&d(c,e,t[e]);return c},z=(c,t)=>q(c,G(t)),I=(c,t,e)=>_(y(c),e,t),v=(c,t,e)=>new Promise((r,n)=>{var o=s=>{try{a(e.next(s))}catch(h){n(h)}},i=s=>{try{a(e.throw(s))}catch(h){n(h)}},a=s=>s.done?r(s.value):Promise.resolve(s.value).then(o,i);a((e=e.apply(c,t)).next())});class x extends F.P{constructor(t,e,r,n){super(t,e,r,n);const{client:o,creatorApiServers:i,mirrorNodes:a,maxFee:s}=t.networkInfo;this.client=g.Client[`for${o}`](),this.fetchCors=(0,S.zR)(t.io),this.accountNameChecked=!1,this.creatorApiServers=i,this.mirrorNodes=a,this.maxFee=s,this.otherMethods={getAccountActivationQuote:h=>v(this,null,function*(){const{currencyCode:m,activePublicKey:P}=h;if(m==null||P==null)throw new Error("ErrorInvalidParams");const{accountActivationQuoteAmount:C,accountActivationQuoteAddress:T}=this.otherData;if(C!=null&&T!=null)return{paymentAddress:T,currencyCode:m,amount:(0,b.toFixed)(C,3,9),exchangeAmount:"0"};const Q={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({currency:m,public_key:P})};try{const k=yield this.fetchCors(`${this.creatorApiServers[0]}/account`,Q);if(!k.ok)throw new Error(yield k.text());const U=(0,E.LZ)(yield k.json()),{request_id:u,address:Y,amount:Z}=U;return this.warn(`activationRequestId: ${u}`),this.otherData.activationRequestId=u,this.otherData.accountActivationQuoteAddress=Y,this.otherData.accountActivationQuoteAmount=Z,this.walletLocalDataDirty=!0,{paymentAddress:Y,currencyCode:m,amount:(0,b.toFixed)(Z,3,18),exchangeAmount:"0"}}catch(k){throw this.warn("getAccountActivationQuote: error submitting account activation request",k),new Error("ErrorActivationRequest")}}),submitActivationPayment:h=>v(this,null,function*(){const m=this.otherData.activationRequestId;if(m==null)throw new Error({message:"ErrorNoActivationPending"});const P={method:"PUT",headers:{Accept:"application/octet-stream","Content-Type":"application/octet-stream"},body:(0,S.ah)(h.signedTx)},C=`${this.creatorApiServers[0]}/request/${m}/payment`;try{const T=yield this.fetchCors(C,P);if(!T.ok)throw this.warn(`submitActivationPayment failed to submit payment
2
- ${yield T.text()}`),new Error("ErrorActivationPayment")}catch(T){throw this.warn("submitActivationPayment error: ",T),T}return this.otherData.paymentSubmitted=!0,this.walletLocalDataDirty=!0,h})}}checkAccountCreationStatus(){return v(this,null,function*(){if(this.accountNameChecked)return;const{activationRequestId:t,paymentSubmitted:e}=this.otherData;let r;try{const n=yield this.fetchCors(`${this.mirrorNodes[0]}/api/v1/accounts?account.publickey=${this.walletInfo.keys.publicKey}`),{accounts:o}=(0,E.DP)(yield n.json());for(const i of o)this.walletInfo.keys.publicKey.includes(i.key.key)&&(r=i.account);this.accountNameChecked=!0}catch(n){this.warn(`checkAccountCreationStatus ${this.mirrorNodes[0]} error`,n)}if(r==null&&e&&t!=null)try{const n=yield this.fetchCors(`${this.creatorApiServers[0]}/request/${t}/status`),o=(0,E.qv)(yield n.json());if(o.status==="transaction_error")throw this.otherData.activationRequestId=void 0,this.otherData.accountActivationQuoteAddress=void 0,this.otherData.accountActivationQuoteAmount=void 0,this.walletLocalDataDirty=!0,this.warn(`hederaEngine error from account activation status ${JSON.stringify(o)}`),new Error("ErrorAccountActivation");o.status==="success"&&o.account_id!=null&&(r=o.account_id)}catch(n){if(this.warn(`error checking Hedera account creation status, ID: ${t} error `,n),(n==null?void 0:n.message)==="ErrorAccountActivation")throw n}r!=null&&(this.otherData.hederaAccount=r,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onAddressChanged(),this.accountNameChecked=!0)})}setOtherData(t){this.otherData=(0,E.nG)(t)}queryBalance(){return v(this,null,function*(){const t=this.otherData.hederaAccount;if(t==null){this.accountNameChecked&&this.updateBalance(this.currencyInfo.currencyCode,"0");return}const e=`${this.mirrorNodes[0]}/api/v1/balances?account.id=${t}`;try{const r=yield this.fetchCors(e);if(!r.ok){const i=yield r.text();throw new Error(i)}const o=(0,E.sd)(yield r.json()).balances.find(i=>i.account===t);if(o==null)throw new Error("Unable to find matching balanceObj");this.updateBalance(this.currencyInfo.currencyCode,o.balance.toString())}catch(r){this.warn("queryBalance error checking balance:",r)}})}getNewTransactions(){return v(this,null,function*(){if(this.otherData.hederaAccount==null){this.accountNameChecked&&(this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=1,this.updateOnAddressesChecked());return}try{for(;;){const t=yield this.getTransactionsMirrorNode(this.otherData.latestTimestamp);if(t.length>0)this.processTxs(t);else break}this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=1,this.updateOnAddressesChecked()}catch(t){this.warn("getNewTransactions error getting transactions:",t)}})}processTxs(t){if(t.length>0){const e=t[t.length-1];if(e.otherParams==null)throw new Error("hederaEngine: EdgeTransaction must have otherParams");this.otherData.latestTimestamp!==e.otherParams.consensusAt&&(this.otherData.latestTimestamp=e.otherParams.consensusAt,this.walletLocalDataDirty=!0),t.forEach(r=>this.addTransaction(this.currencyInfo.currencyCode,r)),this.currencyEngineCallbacks.onTransactionsChanged(t)}}getTransactionsMirrorNode(t){return v(this,null,function*(){var e;if(this.otherData.hederaAccount==null)throw new Error("no Hedera account ID");const r=(e=this.otherData.hederaAccount)!=null?e:"",n=`${this.mirrorNodes[0]}/api/v1/transactions?transactionType=CRYPTOTRANSFER&account.id=${r}&order=asc&timestamp=gt:${t}`,o=yield this.fetchCors(n);if(!o.ok)return this.warn(`getTransactionsMirrorNode error fetching MirrorNode transactions: ${n}`),[];const i=(0,E.Vf)(yield o.json()),a=[];for(const s of i.transactions){const h=s.transfers.find(C=>C.account===r);if(h==null)continue;const m=h.amount.toString(),P=[];(0,b.gt)(m,"0")&&P.push(r),a.push({txid:$(D.US.parse(s.transaction_hash)),date:parseInt(s.valid_start_timestamp),currencyCode:this.currencyInfo.currencyCode,blockHeight:1,nativeAmount:m,isSend:m.startsWith("-"),networkFee:s.charged_tx_fee.toString(),ourReceiveAddresses:P,signedTx:"",otherParams:{consensusAt:s.consensus_timestamp},walletId:this.walletId})}return a})}startEngine(){return v(this,null,function*(){this.engineOn=!0,this.accountNameChecked=this.otherData.hederaAccount!=null,this.addToLoop("getNewTransactions",1e3),this.addToLoop("queryBalance",5e3),this.addToLoop("checkAccountCreationStatus",5e3),yield I(x.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return v(this,null,function*(){this.accountNameChecked=!1,yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}makeSpend(t){return v(this,null,function*(){var e;if(this.otherData.hederaAccount==null)throw Error("ErrorAccountNotActivated");const{edgeSpendInfo:r,currencyCode:n}=this.makeSpendCheck(t);if(r.spendTargets.length!==1)throw new Error("Error: only one output allowed");const{publicAddress:o,uniqueIdentifier:i=""}=r.spendTargets[0];let{nativeAmount:a}=r.spendTargets[0];if(o==null)throw new Error("makeSpend Missing publicAddress");if(a==null)throw new K.$D;if((0,b.eq)(a,"0"))throw new K.$D;const s=g.Hbar.fromTinybar(a),h=g.Hbar.fromTinybar(this.maxFee),m=h.asTinybar().toString();if(a=(0,b.add)(a,m),(0,b.gt)(a,(e=this.walletLocalData.totalBalances[n])!=null?e:"0"))throw new K.C_;if(this.otherData.hederaAccount==null)throw new Error("creating a transfer without an account ID");const P=new g.TransactionId(this.otherData.hederaAccount),C=new g.TransferTransaction().setTransactionId(P).addHbarTransfer(this.otherData.hederaAccount,s.negated()).addHbarTransfer(o,s).setMaxTransactionFee(h).setTransactionMemo(i).build(this.client);return{txid:"",date:0,currencyCode:n,blockHeight:0,nativeAmount:`-${a}`,isSend:!0,networkFee:m,ourReceiveAddresses:[],signedTx:"",otherParams:{fromAddress:this.walletLocalData.publicKey,toAddress:o,transferTx:D.US.stringify(C.toBytes())},walletId:this.walletId}})}signTx(t,e){return v(this,null,function*(){const r=(0,E.cG)(this.currencyInfo.pluginId)(e);if(t.otherParams==null||t.otherParams.transferTx==null)throw new Error("missing otherParam transferTx");const n=r.privateKey;if(n==null)throw new Error("missing privateKey in walletInfo");const o=g.Transaction.fromBytes(D.US.parse(t.otherParams.transferTx));return yield o.sign(g.Ed25519PrivateKey.fromString(n)),z(O({},t),{signedTx:D.US.stringify(o.toBytes()),txid:$(o.hash()),date:Date.now()/1e3,otherParams:O({},t.otherParams)})})}broadcastTx(t){return v(this,null,function*(){if(t.signedTx==null)throw new Error("InvalidTransactionParams");try{yield g.Transaction.fromBytes(D.US.parse(t.signedTx)).execute(this.client)}catch(e){throw this.warn("broadcastTx error",e),e}return t.blockHeight=1,t})}getFreshAddress(t){return v(this,null,function*(){var e;return{publicAddress:(e=this.otherData.hederaAccount)!=null?e:""}})}getBlockHeight(){return Math.floor(Date.now()/1e3)}}function $(c){return D.YU.stringify(c).toLowerCase()}function N(c,t,e,r){return v(this,null,function*(){const n=(0,E.y_)(e),o=new x(c,t,n,r);return yield o.loadEngine(),o})}var A=(c,t,e)=>new Promise((r,n)=>{var o=s=>{try{a(e.next(s))}catch(h){n(h)}},i=s=>{try{a(e.throw(s))}catch(h){n(h)}},a=s=>s.done?r(s.value):Promise.resolve(s.value).then(o,i);a((e=e.apply(c,t)).next())});const M="",V="302e020100300506032b657004220420";class J{constructor(t){const{builtinTokens:e,currencyInfo:r,io:n,log:o,networkInfo:i}=t;this.builtinTokens=e,this.currencyInfo=r,this.fetchCors=(0,S.zR)(n),this.io=n,this.log=o,this.networkInfo=i}getDisplayPrivateKey(t){return A(this,null,function*(){var e;const{pluginId:r}=this.currencyInfo,n=(0,E.cG)(r)(t.keys);return(e=n.mnemonic)!=null?e:n.privateKey})}getDisplayPublicKey(t){return A(this,null,function*(){const{keys:e}=(0,E.y_)(t);return e.publicKey})}createPrivateKey(t){return A(this,null,function*(){if(t!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const e=this.io.random(32),r=(0,B.entropyToMnemonic)(e);return yield this.importPrivateKey(r)})}importPrivateKey(t){return A(this,null,function*(){const{pluginId:e}=this.currencyInfo;try{let r,n;if(/^(0x)?[0-9a-fA-F]{64}$/.test(t.replace(V,""))){const o=t.replace(/^0x/,"").replace(V,"");n=g.Ed25519PrivateKey.fromString(o).toString()}else if((0,B.validateMnemonic)(t)){const i=yield g.Mnemonic.fromString(t).toPrivateKey(M);r=t,n=i.toString()}else throw new Error("InvalidPrivateKey");return{[`${e}Mnemonic`]:r,[`${e}Key`]:n}}catch{throw new Error("InvalidPrivateKey")}})}derivePublicKey(t){return A(this,null,function*(){var e;const{pluginId:r}=this.currencyInfo;if(t.type!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");if(t.keys==null||((e=t.keys)==null?void 0:e[`${r}Key`])==null)throw new Error("Invalid private key");return{publicKey:g.Ed25519PrivateKey.fromString(t.keys[`${r}Key`]).publicKey.toString()}})}parseUri(t){return A(this,null,function*(){const{pluginId:e}=this.currencyInfo,{edgeParsedUri:r,edgeParsedUri:{publicAddress:n}}=(0,L.k)(this.currencyInfo,t,{[`${e}`]:!0},this.currencyInfo.currencyCode);if(n!=null){const{checksumNetworkID:o}=this.networkInfo,[i,a]=n.split("-");if(!H(n)||a!=null&&a!==j(i,o))throw new Error("InvalidPublicAddressError")}return r})}encodeUri(t){return A(this,arguments,function*(e,r=[]){const{pluginId:n}=this.currencyInfo,{publicAddress:o,nativeAmount:i}=e;if(!H(o))throw new Error("InvalidPublicAddressError");if(i==null||typeof i!="string")return o;const a=(0,S.Qs)(this.currencyInfo.currencyCode,this.currencyInfo,r);if(a==null)throw new Error("InternalErrorInvalidCurrencyCode");const s=(0,b.div)(i,a.multiplier,8);return(0,L.Q)(e,n,s)})}getActivationSupportedCurrencies(){return A(this,null,function*(){return{result:{ETH:!0}}})}getActivationCost(){return A(this,null,function*(){const t=this.networkInfo.creatorApiServers[0];try{const e=yield this.fetchCors(`${t}/account/cost`);return(0,E.NV)(yield e.json()).hbar}catch(e){throw this.log.warn("getActivationCost error unable to get account activation cost",e),new Error("ErrorUnableToGetCost")}})}validateAccount(){return A(this,null,function*(){return{result:"AccountAvailable"}})}}function tt(c){return A(this,null,function*(){return new J(c)})}},55024:function(){}}]);
1
+ (self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[894],{79014:function(X,U,d){"use strict";d.d(U,{Q:function(){return G},k:function(){return q}});var g=d(77591),D=d.n(g),R=d(24350),B=d(84564),S=d.n(B),P=d(76714),L=Object.defineProperty,H=Object.getOwnPropertySymbols,_=Object.prototype.hasOwnProperty,k=Object.prototype.propertyIsEnumerable,j=(l,y,p)=>y in l?L(l,y,{enumerable:!0,configurable:!0,writable:!0,value:p}):l[y]=p,W=(l,y)=>{for(var p in y||(y={}))_.call(y,p)&&j(l,p,y[p]);if(H)for(var p of H(y))k.call(y,p)&&j(l,p,y[p]);return l};function q(l,y,p,w,N=[]){const f=W({},S()(y,{},!0)),O=y.startsWith(`${l.pluginId}://`);if(f.protocol!=null&&(f.protocol=f.protocol.replace(":","")),f.protocol!=null&&f.protocol!==""&&!p[f.protocol])throw new Error(`Uri protocol '${f.protocol}' is not supported for ${l.pluginId}.`);if(f.host===""&&f.pathname==="")throw new Error("Path and host not found in uri.");const C={publicAddress:f.host!==""?f.host:f.pathname.split("/")[0]},F=f.query.label,v=f.query.message,x=f.query.category;(F!=null||v!=null||x!=null||O)&&(C.metadata={},C.metadata.name=F,C.metadata.notes=v,C.metadata.category=x,C.metadata.gateway=O!=null?O:!1);const K=f.query.amount;if(K!=null&&typeof K=="string"){w==null&&(w=l.currencyCode);const Q=(0,P.Qs)(w!=null?w:"",l,N);if(Q==null)throw new Error("InternalErrorInvalidCurrencyCode");let A=(0,g.mul)(K,Q.multiplier);A=(0,g.toFixed)(A,0,0),C.nativeAmount=A,C.currencyCode=w}return{edgeParsedUri:C,parsedUri:f}}function G(l,y,p){if(l.publicAddress==null)throw new Error("InvalidPublicAddressError");if(p==null&&l.label==null&&l.message==null)return l.publicAddress;{let w="";p!=null&&(w+="amount="+p+"&"),(l.label!=null||l.message!=null)&&(typeof l.label=="string"&&(w+="label="+l.label+"&"),typeof l.message=="string"&&(w+="message="+l.message+"&")),w=w.substr(0,w.length-1);const N={scheme:y,path:l.publicAddress,query:w};return(0,R.qC)(N)}}},20212:function(X,U,d){"use strict";d.r(U),d.d(U,{HederaTools:function(){return J},makeCurrencyEngine:function(){return Q},makeCurrencyTools:function(){return et}});var g=d(17481),D=d(77591),R=d(2153),B=d(79014),S=d(76714),P=d(825);const L=(i="")=>/^(0|(?:[1-9]\d*))\.(0|(?:[1-9]\d*))\.(0|(?:[1-9]\d*))(?:-([a-z]{5}))?$/.test(i),H=(i,t)=>{let e="";const r=[];let n=0,o=0,s=0,h=0,a=0,c=0;const m=26*26*26,E=26*26*26*26*26,I=97,T=1000003,$=31,b=`${t}000000000000`,M=[];for(let u=0;u<b.length;u+=2)M.push(parseInt(b.substr(u,2),16));for(let u=0;u<i.length;u++)r.push(i[u]==="."?10:parseInt(i[u],10));for(let u=0;u<r.length;u++)s=($*s+r[u])%m,u%2===0?n=(n+r[u])%11:o=(o+r[u])%11;for(let u=0;u<M.length;u++)h=($*h+M[u])%E;a=(((i.length%5*11+n)*11+o)*m+s+h)%E,c=a*T%E;for(let u=0;u<5;u++)e=String.fromCharCode(I+c%26)+e,c/=26;return e};var _=d(94935),k=d(35620),j=d(84650),W=d(72681),q=Object.defineProperty,G=Object.defineProperties,l=Object.getOwnPropertyDescriptors,y=Object.getOwnPropertySymbols,p=Object.getPrototypeOf,w=Object.prototype.hasOwnProperty,N=Object.prototype.propertyIsEnumerable,f=Reflect.get,O=(i,t,e)=>t in i?q(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,z=(i,t)=>{for(var e in t||(t={}))w.call(t,e)&&O(i,e,t[e]);if(y)for(var e of y(t))N.call(t,e)&&O(i,e,t[e]);return i},C=(i,t)=>G(i,l(t)),F=(i,t,e)=>f(p(i),e,t),v=(i,t,e)=>new Promise((r,n)=>{var o=a=>{try{h(e.next(a))}catch(c){n(c)}},s=a=>{try{h(e.throw(a))}catch(c){n(c)}},h=a=>a.done?r(a.value):Promise.resolve(a.value).then(o,s);h((e=e.apply(i,t)).next())});class x extends j.P{constructor(t,e,r,n){super(t,e,r,n);const{client:o,creatorApiServers:s,mirrorNodes:h,maxFee:a}=t.networkInfo;this.client=g.Client[`for${o}`](),this.fetchCors=(0,S.zR)(t.io),this.accountNameChecked=!1,this.creatorApiServers=s,this.mirrorNodes=h,this.maxFee=a,this.otherMethods={getAccountActivationQuote:c=>v(this,null,function*(){const{currencyCode:m,activePublicKey:E}=c;if(m==null||E==null)throw new Error("ErrorInvalidParams");const{accountActivationQuoteAmount:I,accountActivationQuoteAddress:T}=this.otherData;if(I!=null&&T!=null)return{paymentAddress:T,currencyCode:m,amount:(0,D.toFixed)(I,3,9),exchangeAmount:"0"};const $={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({currency:m,public_key:E})};try{const b=yield this.fetchCors(`${this.creatorApiServers[0]}/account`,$);if(!b.ok)throw new Error(yield b.text());const M=(0,P.LZ)(yield b.json()),{request_id:u,address:Y,amount:Z}=M;return this.warn(`activationRequestId: ${u}`),this.otherData.activationRequestId=u,this.otherData.accountActivationQuoteAddress=Y,this.otherData.accountActivationQuoteAmount=Z,this.walletLocalDataDirty=!0,{paymentAddress:Y,currencyCode:m,amount:(0,D.toFixed)(Z,3,18),exchangeAmount:"0"}}catch(b){throw this.warn("getAccountActivationQuote: error submitting account activation request",b),new Error("ErrorActivationRequest")}}),submitActivationPayment:c=>v(this,null,function*(){const m=this.otherData.activationRequestId;if(m==null)throw new Error({message:"ErrorNoActivationPending"});const E={method:"PUT",headers:{Accept:"application/octet-stream","Content-Type":"application/octet-stream"},body:(0,S.ah)(c.signedTx)},I=`${this.creatorApiServers[0]}/request/${m}/payment`;try{const T=yield this.fetchCors(I,E);if(!T.ok)throw this.warn(`submitActivationPayment failed to submit payment
2
+ ${yield T.text()}`),new Error("ErrorActivationPayment")}catch(T){throw this.warn("submitActivationPayment error: ",T),T}return this.otherData.paymentSubmitted=!0,this.walletLocalDataDirty=!0,c})}}checkAccountCreationStatus(){return v(this,null,function*(){if(this.accountNameChecked)return;const{activationRequestId:t,paymentSubmitted:e}=this.otherData;let r;try{const n=yield this.fetchCors(`${this.mirrorNodes[0]}/api/v1/accounts?account.publickey=${this.walletInfo.keys.publicKey}`),{accounts:o}=(0,P.DP)(yield n.json());for(const s of o)this.walletInfo.keys.publicKey.includes(s.key.key)&&(r=s.account);this.accountNameChecked=!0}catch(n){this.warn(`checkAccountCreationStatus ${this.mirrorNodes[0]} error`,n)}if(r==null&&e&&t!=null)try{const n=yield this.fetchCors(`${this.creatorApiServers[0]}/request/${t}/status`),o=(0,P.qv)(yield n.json());if(o.status==="transaction_error")throw this.otherData.activationRequestId=void 0,this.otherData.accountActivationQuoteAddress=void 0,this.otherData.accountActivationQuoteAmount=void 0,this.walletLocalDataDirty=!0,this.warn(`hederaEngine error from account activation status ${JSON.stringify(o)}`),new Error("ErrorAccountActivation");o.status==="success"&&o.account_id!=null&&(r=o.account_id)}catch(n){if(this.warn(`error checking Hedera account creation status, ID: ${t} error `,n),(n==null?void 0:n.message)==="ErrorAccountActivation")throw n}r!=null&&(this.otherData.hederaAccount=r,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onAddressChanged(),this.accountNameChecked=!0)})}setOtherData(t){this.otherData=(0,P.nG)(t)}queryBalance(){return v(this,null,function*(){const t=this.otherData.hederaAccount;if(t==null){this.accountNameChecked&&this.updateBalance(this.currencyInfo.currencyCode,"0");return}const e=`${this.mirrorNodes[0]}/api/v1/balances?account.id=${t}`;try{const r=yield this.fetchCors(e);if(!r.ok){const s=yield r.text();throw new Error(s)}const o=(0,P.sd)(yield r.json()).balances.find(s=>s.account===t);if(o==null)throw new Error("Unable to find matching balanceObj");this.updateBalance(this.currencyInfo.currencyCode,o.balance.toString())}catch(r){this.warn("queryBalance error checking balance:",r)}})}getNewTransactions(){return v(this,null,function*(){if(this.otherData.hederaAccount==null){this.accountNameChecked&&(this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=1,this.updateOnAddressesChecked());return}try{for(;;){const t=yield this.getTransactionsMirrorNode(this.otherData.latestTimestamp);if(t.length>0)this.processTxs(t);else break}this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=1,this.updateOnAddressesChecked()}catch(t){this.warn("getNewTransactions error getting transactions:",t)}})}processTxs(t){if(t.length>0){const e=t[t.length-1];if(e.otherParams==null)throw new Error("hederaEngine: EdgeTransaction must have otherParams");this.otherData.latestTimestamp!==e.otherParams.consensusAt&&(this.otherData.latestTimestamp=e.otherParams.consensusAt,this.walletLocalDataDirty=!0),t.forEach(r=>this.addTransaction(this.currencyInfo.currencyCode,r)),this.currencyEngineCallbacks.onTransactionsChanged(t)}}getTransactionsMirrorNode(t){return v(this,null,function*(){var e;if(this.otherData.hederaAccount==null)throw new Error("no Hedera account ID");const r=(e=this.otherData.hederaAccount)!=null?e:"",n=`${this.mirrorNodes[0]}/api/v1/transactions?transactionType=CRYPTOTRANSFER&account.id=${r}&order=asc&timestamp=gt:${t}`,o=yield this.fetchCors(n);if(!o.ok)return this.warn(`getTransactionsMirrorNode error fetching MirrorNode transactions: ${n}`),[];const s=(0,P.Vf)(yield o.json()),h=[];for(const a of s.transactions){const c=a.transfers.find(I=>I.account===r);if(c==null)continue;const m=c.amount.toString(),E=[];(0,D.gt)(m,"0")&&E.push(r),h.push({blockHeight:1,currencyCode:this.currencyInfo.currencyCode,date:parseInt(a.valid_start_timestamp),isSend:m.startsWith("-"),memos:[],nativeAmount:m,networkFee:a.charged_tx_fee.toString(),otherParams:{consensusAt:a.consensus_timestamp},ourReceiveAddresses:E,signedTx:"",txid:K(k.US.parse(a.transaction_hash)),walletId:this.walletId})}return h})}startEngine(){return v(this,null,function*(){this.engineOn=!0,this.accountNameChecked=this.otherData.hederaAccount!=null,this.addToLoop("getNewTransactions",1e3),this.addToLoop("queryBalance",5e3),this.addToLoop("checkAccountCreationStatus",5e3),yield F(x.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return v(this,null,function*(){this.accountNameChecked=!1,yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}makeSpend(t){return v(this,null,function*(){var e,r;t=(0,W.s)(t,this.currencyInfo);const{edgeSpendInfo:n,currencyCode:o}=this.makeSpendCheck(t),{memos:s=[]}=n;if(this.otherData.hederaAccount==null)throw Error("ErrorAccountNotActivated");if(n.spendTargets.length!==1)throw new Error("Error: only one output allowed");const h=((e=s[0])==null?void 0:e.type)==="text"?s[0].value:"",{publicAddress:a}=n.spendTargets[0];let{nativeAmount:c}=n.spendTargets[0];if(a==null)throw new Error("makeSpend Missing publicAddress");if(c==null)throw new _.$D;if((0,D.eq)(c,"0"))throw new _.$D;const m=g.Hbar.fromTinybar(c),E=g.Hbar.fromTinybar(this.maxFee),I=E.asTinybar().toString();if(c=(0,D.add)(c,I),(0,D.gt)(c,(r=this.walletLocalData.totalBalances[o])!=null?r:"0"))throw new _.C_;if(this.otherData.hederaAccount==null)throw new Error("creating a transfer without an account ID");const T=new g.TransactionId(this.otherData.hederaAccount),$=new g.TransferTransaction().setTransactionId(T).addHbarTransfer(this.otherData.hederaAccount,m.negated()).addHbarTransfer(a,m).setMaxTransactionFee(E).setTransactionMemo(h).build(this.client);return{blockHeight:0,currencyCode:o,date:0,isSend:!0,memos:s,nativeAmount:`-${c}`,networkFee:I,otherParams:{fromAddress:this.walletLocalData.publicKey,toAddress:a,transferTx:k.US.stringify($.toBytes())},ourReceiveAddresses:[],signedTx:"",txid:"",walletId:this.walletId}})}signTx(t,e){return v(this,null,function*(){const r=(0,P.cG)(this.currencyInfo.pluginId)(e);if(t.otherParams==null||t.otherParams.transferTx==null)throw new Error("missing otherParam transferTx");const n=r.privateKey;if(n==null)throw new Error("missing privateKey in walletInfo");const o=g.Transaction.fromBytes(k.US.parse(t.otherParams.transferTx));return yield o.sign(g.Ed25519PrivateKey.fromString(n)),C(z({},t),{signedTx:k.US.stringify(o.toBytes()),txid:K(o.hash()),date:Date.now()/1e3,otherParams:z({},t.otherParams)})})}broadcastTx(t){return v(this,null,function*(){if(t.signedTx==null)throw new Error("InvalidTransactionParams");try{yield g.Transaction.fromBytes(k.US.parse(t.signedTx)).execute(this.client)}catch(e){throw this.warn("broadcastTx error",e),e}return t.blockHeight=1,t})}getFreshAddress(t){return v(this,null,function*(){var e;return{publicAddress:(e=this.otherData.hederaAccount)!=null?e:""}})}getBlockHeight(){return Math.floor(Date.now()/1e3)}}function K(i){return k.YU.stringify(i).toLowerCase()}function Q(i,t,e,r){return v(this,null,function*(){const n=(0,P.y_)(e),o=new x(i,t,n,r);return yield o.loadEngine(),o})}var A=(i,t,e)=>new Promise((r,n)=>{var o=a=>{try{h(e.next(a))}catch(c){n(c)}},s=a=>{try{h(e.throw(a))}catch(c){n(c)}},h=a=>a.done?r(a.value):Promise.resolve(a.value).then(o,s);h((e=e.apply(i,t)).next())});const tt="",V="302e020100300506032b657004220420";class J{constructor(t){const{builtinTokens:e,currencyInfo:r,io:n,log:o,networkInfo:s}=t;this.builtinTokens=e,this.currencyInfo=r,this.fetchCors=(0,S.zR)(n),this.io=n,this.log=o,this.networkInfo=s}getDisplayPrivateKey(t){return A(this,null,function*(){var e;const{pluginId:r}=this.currencyInfo,n=(0,P.cG)(r)(t.keys);return(e=n.mnemonic)!=null?e:n.privateKey})}getDisplayPublicKey(t){return A(this,null,function*(){const{keys:e}=(0,P.y_)(t);return e.publicKey})}createPrivateKey(t){return A(this,null,function*(){if(t!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const e=this.io.random(32),r=(0,R.entropyToMnemonic)(e);return yield this.importPrivateKey(r)})}importPrivateKey(t){return A(this,null,function*(){const{pluginId:e}=this.currencyInfo;try{let r,n;if(/^(0x)?[0-9a-fA-F]{64}$/.test(t.replace(V,""))){const o=t.replace(/^0x/,"").replace(V,"");n=g.Ed25519PrivateKey.fromString(o).toString()}else if((0,R.validateMnemonic)(t)){const s=yield g.Mnemonic.fromString(t).toPrivateKey(tt);r=t,n=s.toString()}else throw new Error("InvalidPrivateKey");return{[`${e}Mnemonic`]:r,[`${e}Key`]:n}}catch{throw new Error("InvalidPrivateKey")}})}derivePublicKey(t){return A(this,null,function*(){var e;const{pluginId:r}=this.currencyInfo;if(t.type!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");if(t.keys==null||((e=t.keys)==null?void 0:e[`${r}Key`])==null)throw new Error("Invalid private key");return{publicKey:g.Ed25519PrivateKey.fromString(t.keys[`${r}Key`]).publicKey.toString()}})}parseUri(t){return A(this,null,function*(){const{pluginId:e}=this.currencyInfo,{edgeParsedUri:r,edgeParsedUri:{publicAddress:n}}=(0,B.k)(this.currencyInfo,t,{[`${e}`]:!0},this.currencyInfo.currencyCode);if(n!=null){const{checksumNetworkID:o}=this.networkInfo,[s,h]=n.split("-");if(!L(n)||h!=null&&h!==H(s,o))throw new Error("InvalidPublicAddressError")}return r})}encodeUri(t){return A(this,arguments,function*(e,r=[]){const{pluginId:n}=this.currencyInfo,{publicAddress:o,nativeAmount:s}=e;if(!L(o))throw new Error("InvalidPublicAddressError");if(s==null||typeof s!="string")return o;const h=(0,S.Qs)(this.currencyInfo.currencyCode,this.currencyInfo,r);if(h==null)throw new Error("InternalErrorInvalidCurrencyCode");const a=(0,D.div)(s,h.multiplier,8);return(0,B.Q)(e,n,a)})}getActivationSupportedCurrencies(){return A(this,null,function*(){return{result:{ETH:!0}}})}getActivationCost(){return A(this,null,function*(){const t=this.networkInfo.creatorApiServers[0];try{const e=yield this.fetchCors(`${t}/account/cost`);return(0,P.NV)(yield e.json()).hbar}catch(e){throw this.log.warn("getActivationCost error unable to get account activation cost",e),new Error("ErrorUnableToGetCost")}})}validateAccount(){return A(this,null,function*(){return{result:"AccountAvailable"}})}}function et(i){return A(this,null,function*(){return new J(i)})}},55024:function(){}}]);
@@ -1,2 +1,2 @@
1
- "use strict";(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[591],{79014:function(et,M,d){d.d(M,{Q:function(){return _},k:function(){return V}});var S=d(77591),j=d.n(S),W=d(24350),X=d(84564),i=d.n(X),L=d(76714),U=Object.defineProperty,T=Object.getOwnPropertySymbols,F=Object.prototype.hasOwnProperty,I=Object.prototype.propertyIsEnumerable,a=(c,g,m)=>g in c?U(c,g,{enumerable:!0,configurable:!0,writable:!0,value:m}):c[g]=m,Q=(c,g)=>{for(var m in g||(g={}))F.call(g,m)&&a(c,m,g[m]);if(T)for(var m of T(g))I.call(g,m)&&a(c,m,g[m]);return c};function V(c,g,m,k,P=[]){const y=Q({},i()(g,{},!0)),O=g.startsWith(`${c.pluginId}://`);if(y.protocol!=null&&(y.protocol=y.protocol.replace(":","")),y.protocol!=null&&y.protocol!==""&&!m[y.protocol])throw new Error(`Uri protocol '${y.protocol}' is not supported for ${c.pluginId}.`);if(y.host===""&&y.pathname==="")throw new Error("Path and host not found in uri.");const C={publicAddress:y.host!==""?y.host:y.pathname.split("/")[0]},H=y.query.label,x=y.query.message,R=y.query.category;(H!=null||x!=null||R!=null||O)&&(C.metadata={},C.metadata.name=H,C.metadata.notes=x,C.metadata.category=R,C.metadata.gateway=O!=null?O:!1);const B=y.query.amount;if(B!=null&&typeof B=="string"){k==null&&(k=c.currencyCode);const $=(0,L.Qs)(k!=null?k:"",c,P);if($==null)throw new Error("InternalErrorInvalidCurrencyCode");let D=(0,S.mul)(B,$.multiplier);D=(0,S.toFixed)(D,0,0),C.nativeAmount=D,C.currencyCode=k}return{edgeParsedUri:C,parsedUri:y}}function _(c,g,m){if(c.publicAddress==null)throw new Error("InvalidPublicAddressError");if(m==null&&c.label==null&&c.message==null)return c.publicAddress;{let k="";m!=null&&(k+="amount="+m+"&"),(c.label!=null||c.message!=null)&&(typeof c.label=="string"&&(k+="label="+c.label+"&"),typeof c.message=="string"&&(k+="message="+c.message+"&")),k=k.substr(0,k.length-1);const P={scheme:g,path:c.publicAddress,query:k};return(0,W.qC)(P)}}},34765:function(et,M,d){d.r(M),d.d(M,{PolkadotTools:function(){return tt},makeCurrencyEngine:function(){return it},makeCurrencyTools:function(){return ct}});var S=d(58170),j=d(21293),W=d(18534),X=d(23670),i=d(77591),L=d(2153),U=d(48764),T=d(20918),F=d(79014),I=d(76714),a=d(82448),Q=d(62177);const V=(0,a.su)({txCount:(0,a.Vk)(a.mH,0)}),_=(0,a.su)({code:a.mH,message:a.XC,data:(0,a.Zz)((0,a.su)(a.JC))}),c=(0,a.su)({from:a.XC,to:a.XC,success:a.jK,hash:a.XC,block_num:a.mH,block_timestamp:a.mH,module:a.XC,amount:a.XC,fee:a.XC}),g=(0,a.su)({count:a.mH,transfers:(0,a.Vk)((0,a._2)(c),()=>[])}),m=Q.BQ,k=u=>{const t=(0,a.su)({[`${u}Mnemonic`]:(0,a.Zz)(a.XC),[`${u}Key`]:a.XC});return(0,a.W1)(e=>{const r=t(e);return{mnemonic:r[`${u}Mnemonic`],privateKey:r[`${u}Key`]}},e=>({[`${u}Mnemonic`]:e.mnemonic,[`${u}Key`]:e.privateKey}))};var P=d(94935),y=d(35620),O=d(84650),z=Object.defineProperty,C=Object.defineProperties,H=Object.getOwnPropertyDescriptors,x=Object.getOwnPropertySymbols,R=Object.getPrototypeOf,B=Object.prototype.hasOwnProperty,$=Object.prototype.propertyIsEnumerable,D=Reflect.get,G=(u,t,e)=>t in u?z(u,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):u[t]=e,Y=(u,t)=>{for(var e in t||(t={}))B.call(t,e)&&G(u,e,t[e]);if(x)for(var e of x(t))$.call(t,e)&&G(u,e,t[e]);return u},J=(u,t)=>C(u,H(t)),Z=(u,t,e)=>D(R(u),e,t),w=(u,t,e)=>new Promise((r,n)=>{var s=o=>{try{h(e.next(o))}catch(f){n(f)}},l=o=>{try{h(e.throw(o))}catch(f){n(f)}},h=o=>o.done?r(o.value):Promise.resolve(o.value).then(s,l);h((e=e.apply(u,t)).next())});const nt=5e3,rt=2e4,st=3e3,ot=(0,I.jT)();class N extends O.P{constructor(t,e,r,n){super(t,e,r,n),this.getRecipientBalance=s=>w(this,null,function*(){try{return(yield this.api.query.system.account(s)).data.free.toString()}catch{return this.minimumAddressBalance}}),this.fetchCors=(0,I.zR)(t.io),this.networkInfo=t.networkInfo,this.nonce=0}setOtherData(t){this.otherData=V(t)}fetchSubscan(t,e){return w(this,null,function*(){if(this.networkInfo.subscanBaseUrl==null)throw new Error("Missing subscan url");const r={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(e)},n=yield this.fetchCors(this.networkInfo.subscanBaseUrl+t,r);if(!n.ok||n.status===429)throw new Error(`Subscan ${t} failed with ${n.status}`);const s=yield n.json();return _(s)})}queryBalance(){return w(this,null,function*(){const t=yield this.api.query.system.account(this.walletInfo.keys.publicKey);this.nonce=t.nonce.toNumber(),this.updateBalance(this.currencyInfo.currencyCode,t.data.free.toString());for(const e of this.enabledTokenIds){const r=this.allTokensMap[e];if(r==null)continue;const n=(0,T.Oj)(r.networkLocation);if(n==null)continue;const s=yield this.api.query.assets.account(n.contractAddress,this.walletInfo.keys.publicKey);let l="0";s.isSome&&(l=s.unwrap().balance.toString()),this.updateBalance(r.currencyCode,l)}})}queryBlockheight(){return w(this,null,function*(){try{const e=(yield this.api.rpc.chain.getBlock()).block.header.number.toNumber();e>this.walletLocalData.blockHeight&&(this.walletLocalData.blockHeight=e,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight))}catch(t){this.warn("queryBlockheight failed with error: ",t)}})}processPolkadotTransaction(t){const{from:e,to:r,success:n,hash:s,block_num:l,block_timestamp:h,module:o,amount:f,fee:p}=t;if(!n||o!=="balances")return;const E=(0,I.aL)(this.currencyInfo.currencyCode,this.currencyInfo,this.allTokensMap);if(E==null)return;const A=[];let v=(0,i.mul)(f,E.multiplier);e===this.walletInfo.keys.publicKey?v=`-${(0,i.add)(v,p)}`:A.push(r);const K={txid:s,date:h,currencyCode:this.currencyInfo.currencyCode,blockHeight:l,nativeAmount:v,isSend:v.startsWith("-"),networkFee:p,ourReceiveAddresses:A,signedTx:"",walletId:this.walletId};this.addTransaction(this.currencyInfo.currencyCode,K)}queryTransactions(){return w(this,null,function*(){if(this.networkInfo.subscanBaseUrl==null){for(const t of this.enabledTokens)this.tokenCheckTransactionsStatus[t]=1;this.updateOnAddressesChecked();return}return yield ot(()=>w(this,null,function*(){return yield this.queryTransactionsInner()}))})}queryTransactionsInner(){return w(this,null,function*(){let t=Math.floor(this.otherData.txCount/this.networkInfo.subscanQueryLimit);for(;;){const e={row:this.networkInfo.subscanQueryLimit,page:t,address:this.walletInfo.keys.publicKey};let r=0,n=[];try{const s=yield this.fetchSubscan("/scan/transfers",e),l=g(s.data);r=l.count,n=l.transfers}catch(s){if(s instanceof Error&&s.message.includes("Subscan /scan/transfers failed with 429")){this.log(s.message);continue}else throw s}if(r===this.otherData.txCount||(n.forEach(s=>{try{this.processPolkadotTransaction(c(s))}catch{const h=s!=null&&typeof s.hash=="string"?s.hash:"";this.warn(`Ignoring invalid transfer ${h}`)}}),this.otherData.txCount=t*this.networkInfo.subscanQueryLimit+n.length,this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=Math.min(1,r===0?1:this.otherData.txCount/r),this.updateOnAddressesChecked(),r===this.otherData.txCount))break;t++}this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=1,this.updateOnAddressesChecked(),this.transactionsChangedArray.length>0&&(this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[])})}startEngine(){return w(this,null,function*(){this.engineOn=!0,yield this.tools.connectApi(this.walletId),this.api=this.tools.polkadotApi,this.minimumAddressBalance=this.api.consts.balances.existentialDeposit.toString(),this.addToLoop("queryBlockheight",rt).catch(()=>{}),this.addToLoop("queryBalance",nt).catch(()=>{}),this.addToLoop("queryTransactions",st).catch(()=>{}),yield Z(N.prototype,this,"startEngine").call(this)})}killEngine(){return w(this,null,function*(){yield Z(N.prototype,this,"killEngine").call(this),yield this.tools.disconnectApi(this.walletId)})}resyncBlockchain(){return w(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getMaxSpendable(t){return w(this,null,function*(){if(t.spendTargets.length===0||t.spendTargets[0].publicAddress==null)throw new Error("Missing public address");const e=this.getBalance({currencyCode:t.currencyCode});if(t.currencyCode!==this.currencyInfo.currencyCode){const f=[{publicAddress:t.spendTargets[0].publicAddress,nativeAmount:e}],p=J(Y({},t),{spendTargets:f});return yield this.makeSpend(p),e}const r=(0,i.sub)(e,this.api.consts.balances.existentialDeposit.toString()),n=[{publicAddress:t.spendTargets[0].publicAddress,nativeAmount:"0"}],s=J(Y({},t),{spendTargets:n}),h=(yield this.makeSpend(s)).networkFee,o=(f,p)=>{const E=(0,i.sub)(p,f);if((0,i.lte)(E,"1"))return f;const A=(0,i.add)(f,(0,i.div)(E,"2")),v=(0,I.X0)(A).replace("0x",""),K=v.length%2===1?`0${v}`:v,ut=(0,i.mul)((0,i.div)(K.length.toString(),"2"),this.networkInfo.lengthFeePerByte),dt=(0,i.add)((0,i.add)(ut,h),A);return(0,i.gt)(dt,r)?o(f,A):o(A,p)};return o("0",(0,i.add)(r,"1"))})}makeSpend(t){return w(this,null,function*(){const{edgeSpendInfo:e,currencyCode:r}=this.makeSpendCheck(t);if(e.spendTargets.length!==1)throw new Error("Error: only one output allowed");const{nativeAmount:n,publicAddress:s}=e.spendTargets[0];if(s==null)throw new Error("makeSpend Missing publicAddress");if(n==null)throw new P.$D;const l=this.getBalance({currencyCode:r});let h,o;if(e.tokenId==null){const E=(0,i.sub)(l,this.api.consts.balances.existentialDeposit.toString());if((0,i.gt)(n,E))throw new P.C_;const v=yield(yield this.api.tx.balances.transferKeepAlive(s,n)).paymentInfo(this.walletInfo.keys.publicKey);if(o=(0,i.sub)(v.partialFee.toString(),(0,i.mul)(this.networkInfo.lengthFeePerByte,this.networkInfo.partialFeeOffsetMultiplier)),h=(0,i.add)(n,o),(0,i.gt)(h,E))throw new P.C_}else{if((0,i.gt)(n,l))throw new P.C_;h=n;const A=yield(yield this.api.tx.assets.transfer(parseInt(e.tokenId),s,n)).paymentInfo(this.walletInfo.keys.publicKey);o=(0,i.sub)(A.partialFee.toString(),(0,i.mul)(this.networkInfo.lengthFeePerByte,this.networkInfo.partialFeeOffsetMultiplier));const v=this.getBalance({currencyCode:this.currencyInfo.currencyCode}),K=(0,i.sub)(v,this.api.consts.balances.existentialDeposit.toString());if((0,i.gt)(o,K))throw new P.C_({currencyCode:this.currencyInfo.currencyCode,networkFee:o})}const f={publicAddress:s};return{txid:"",date:0,currencyCode:r,blockHeight:0,nativeAmount:(0,i.mul)(h,"-1"),isSend:!0,networkFee:o,ourReceiveAddresses:[],signedTx:"",otherParams:f,walletId:this.walletId}})}signTx(t,e){return w(this,null,function*(){const r=k(this.currencyInfo.pluginId)(e),{publicAddress:n}=(0,I.Xp)(t);if(n==null)throw new Error("Missing publicAddress from makeSpend");const s=this.allTokens.find(p=>p.currencyCode===t.currencyCode);let l;if(s==null){const p=(0,i.abs)((0,i.add)(t.nativeAmount,t.networkFee));yield this.checkRecipientMinimumBalance(this.getRecipientBalance,p,n),l=yield this.api.tx.balances.transferKeepAlive(n,p)}else if(s.contractAddress!=null){const p=(0,i.abs)(t.nativeAmount);l=yield this.api.tx.assets.transfer(parseInt(s.contractAddress),n,p)}else throw new Error("Unrecognized asset");const h=this.api.createType("SignerPayload",{method:l,nonce:this.nonce,genesisHash:this.api.genesisHash,blockHash:this.api.genesisHash,runtimeVersion:this.api.runtimeVersion,version:this.api.extrinsicVersion}),o=this.api.createType("ExtrinsicPayload",h.toPayload(),{version:this.api.extrinsicVersion});if(this.keypair==null)if(this.keypair=new S.Y({ss58Format:0}),r.mnemonic!=null)this.keypair.addFromUri(r.mnemonic);else{const p=y.YU.parse(r.privateKey);this.keypair.addFromSeed(p)}const f=o.sign(this.keypair.getPair(this.walletInfo.keys.publicKey));return l.addSignature(this.walletInfo.keys.publicKey,f.signature,h.toPayload()),t.signedTx=l.toHex(),t})}broadcastTx(t){return w(this,null,function*(){try{const e=yield this.api.rpc.author.submitExtrinsic(t.signedTx);t.txid=e.toHex(),t.date=Date.now()/1e3,this.warn(`SUCCESS broadcastTx
2
- ${(0,I.oX)(t)}`)}catch(e){throw this.warn("FAILURE broadcastTx failed: ",e),e}return t})}}function it(u,t,e,r){return w(this,null,function*(){const n=m(e),s=new N(u,t,n,r);return yield s.loadEngine(),s})}var b=(u,t,e)=>new Promise((r,n)=>{var s=o=>{try{h(e.next(o))}catch(f){n(f)}},l=o=>{try{h(e.throw(o))}catch(f){n(f)}},h=o=>o.done?r(o.value):Promise.resolve(o.value).then(s,l);h((e=e.apply(u,t)).next())});const{ed25519PairFromSeed:at,isAddress:q,mnemonicToMiniSecret:lt}=X;class tt{constructor(t){const{builtinTokens:e,currencyInfo:r,io:n,networkInfo:s}=t;this.builtinTokens=e,this.currencyInfo=r,this.io=n,this.networkInfo=s,this.polkadotApiSubscribers=new Set}getDisplayPrivateKey(t){return b(this,null,function*(){var e;const{pluginId:r}=this.currencyInfo,n=k(r)(t.keys);return(e=n.mnemonic)!=null?e:n.privateKey})}getDisplayPublicKey(t){return b(this,null,function*(){const{keys:e}=m(t);return e.publicKey})}importPrivateKey(t){return b(this,null,function*(){const{pluginId:e}=this.currencyInfo;if((0,L.validateMnemonic)(t)){const r=lt(t),{secretKey:n}=at(r);return{[`${e}Mnemonic`]:t,[`${e}Key`]:U.Buffer.from(n).toString("hex")}}else{if((0,I.vq)(t))return{[`${e}Key`]:t};throw new Error("InvalidPrivateKey")}})}createPrivateKey(t){return b(this,null,function*(){if(t!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const e=U.Buffer.from(this.io.random(32)),r=(0,L.entropyToMnemonic)(e);return yield this.importPrivateKey(r)})}derivePublicKey(t){return b(this,null,function*(){const{pluginId:e}=this.currencyInfo;return{publicKey:new S.Y({ss58Format:0}).addFromUri(t.keys[`${e}Mnemonic`]).address}})}parseUri(t,e,r){return b(this,null,function*(){var n,s;const{pluginId:l}=this.currencyInfo,h={[l]:!0},{parsedUri:o,edgeParsedUri:f}=(0,F.k)(this.currencyInfo,t,h,e!=null?e:this.currencyInfo.currencyCode,r),p=(n=f.publicAddress)!=null?n:"";if(!q(p))throw new Error("InvalidPublicAddressError");return f.uniqueIdentifier=(s=o.query.memo)!=null?s:void 0,f})}encodeUri(t){return b(this,arguments,function*(e,r=[]){const{pluginId:n}=this.currencyInfo,{nativeAmount:s,currencyCode:l,publicAddress:h}=e;if(!q(h))throw new Error("InvalidPublicAddressError");let o;if(typeof s=="string"){const p=(0,I.Qs)(l!=null?l:this.currencyInfo.currencyCode,this.currencyInfo,r);if(p==null)throw new Error("InternalErrorInvalidCurrencyCode");o=(0,i.div)(s,p.multiplier,10)}return(0,F.Q)(e,n,o)})}connectApi(t){return b(this,null,function*(){return this.polkadotApi==null&&(this.polkadotApi=yield j.G.create({initWasm:!1,provider:new W.U(this.networkInfo.rpcNodes[0])})),this.polkadotApiSubscribers.add(t),this.polkadotApi})}disconnectApi(t){return b(this,null,function*(){this.polkadotApiSubscribers.delete(t),this.polkadotApiSubscribers.size===0&&(yield this.polkadotApi.disconnect(),this.polkadotApi=void 0)})}getTokenId(t){return b(this,null,function*(){(0,T.Rp)(t);const e=(0,T.Oj)(t.networkLocation);if(e==null)throw new Error("ErrorInvalidContractAddress");return e.contractAddress})}}function ct(u){return b(this,null,function*(){return new tt(u)})}}}]);
1
+ "use strict";(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[591],{79014:function(nt,M,h){h.d(M,{Q:function(){return j},k:function(){return V}});var S=h(77591),Y=h.n(S),W=h(24350),X=h(84564),i=h.n(X),L=h(76714),U=Object.defineProperty,T=Object.getOwnPropertySymbols,F=Object.prototype.hasOwnProperty,I=Object.prototype.propertyIsEnumerable,a=(u,g,m)=>g in u?U(u,g,{enumerable:!0,configurable:!0,writable:!0,value:m}):u[g]=m,Q=(u,g)=>{for(var m in g||(g={}))F.call(g,m)&&a(u,m,g[m]);if(T)for(var m of T(g))I.call(g,m)&&a(u,m,g[m]);return u};function V(u,g,m,k,P=[]){const p=Q({},i()(g,{},!0)),x=g.startsWith(`${u.pluginId}://`);if(p.protocol!=null&&(p.protocol=p.protocol.replace(":","")),p.protocol!=null&&p.protocol!==""&&!m[p.protocol])throw new Error(`Uri protocol '${p.protocol}' is not supported for ${u.pluginId}.`);if(p.host===""&&p.pathname==="")throw new Error("Path and host not found in uri.");const A={publicAddress:p.host!==""?p.host:p.pathname.split("/")[0]},H=p.query.label,R=p.query.message,B=p.query.category;(H!=null||R!=null||B!=null||x)&&(A.metadata={},A.metadata.name=H,A.metadata.notes=R,A.metadata.category=B,A.metadata.gateway=x!=null?x:!1);const D=p.query.amount;if(D!=null&&typeof D=="string"){k==null&&(k=u.currencyCode);const $=(0,L.Qs)(k!=null?k:"",u,P);if($==null)throw new Error("InternalErrorInvalidCurrencyCode");let K=(0,S.mul)(D,$.multiplier);K=(0,S.toFixed)(K,0,0),A.nativeAmount=K,A.currencyCode=k}return{edgeParsedUri:A,parsedUri:p}}function j(u,g,m){if(u.publicAddress==null)throw new Error("InvalidPublicAddressError");if(m==null&&u.label==null&&u.message==null)return u.publicAddress;{let k="";m!=null&&(k+="amount="+m+"&"),(u.label!=null||u.message!=null)&&(typeof u.label=="string"&&(k+="label="+u.label+"&"),typeof u.message=="string"&&(k+="message="+u.message+"&")),k=k.substr(0,k.length-1);const P={scheme:g,path:u.publicAddress,query:k};return(0,W.qC)(P)}}},34765:function(nt,M,h){h.r(M),h.d(M,{PolkadotTools:function(){return et},makeCurrencyEngine:function(){return lt},makeCurrencyTools:function(){return dt}});var S=h(58170),Y=h(36010),W=h(18534),X=h(23670),i=h(77591),L=h(2153),U=h(48764),T=h(20918),F=h(79014),I=h(76714),a=h(82448),Q=h(62177);const V=(0,a.su)({txCount:(0,a.Vk)(a.mH,0)}),j=(0,a.su)({code:a.mH,message:a.XC,data:(0,a.Zz)((0,a.su)(a.JC))}),u=(0,a.su)({from:a.XC,to:a.XC,success:a.jK,hash:a.XC,block_num:a.mH,block_timestamp:a.mH,module:a.XC,amount:a.XC,fee:a.XC}),g=(0,a.su)({count:a.mH,transfers:(0,a.Vk)((0,a._2)(u),()=>[])}),m=Q.BQ,k=d=>{const t=(0,a.su)({[`${d}Mnemonic`]:(0,a.Zz)(a.XC),[`${d}Key`]:a.XC});return(0,a.W1)(e=>{const r=t(e);return{mnemonic:r[`${d}Mnemonic`],privateKey:r[`${d}Key`]}},e=>({[`${d}Mnemonic`]:e.mnemonic,[`${d}Key`]:e.privateKey}))};var P=h(94935),p=h(35620),x=h(84650),z=h(72681),A=Object.defineProperty,H=Object.defineProperties,R=Object.getOwnPropertyDescriptors,B=Object.getOwnPropertySymbols,D=Object.getPrototypeOf,$=Object.prototype.hasOwnProperty,K=Object.prototype.propertyIsEnumerable,rt=Reflect.get,_=(d,t,e)=>t in d?A(d,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):d[t]=e,J=(d,t)=>{for(var e in t||(t={}))$.call(t,e)&&_(d,e,t[e]);if(B)for(var e of B(t))K.call(t,e)&&_(d,e,t[e]);return d},Z=(d,t)=>H(d,R(t)),q=(d,t,e)=>rt(D(d),e,t),w=(d,t,e)=>new Promise((r,s)=>{var n=o=>{try{f(e.next(o))}catch(c){s(c)}},l=o=>{try{f(e.throw(o))}catch(c){s(c)}},f=o=>o.done?r(o.value):Promise.resolve(o.value).then(n,l);f((e=e.apply(d,t)).next())});const st=5e3,ot=2e4,it=3e3,at=(0,I.jT)();class N extends x.P{constructor(t,e,r,s){super(t,e,r,s),this.getRecipientBalance=n=>w(this,null,function*(){try{return(yield this.api.query.system.account(n)).data.free.toString()}catch{return this.minimumAddressBalance}}),this.fetchCors=(0,I.zR)(t.io),this.networkInfo=t.networkInfo,this.nonce=0}setOtherData(t){this.otherData=V(t)}fetchSubscan(t,e){return w(this,null,function*(){if(this.networkInfo.subscanBaseUrl==null)throw new Error("Missing subscan url");const r={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(e)},s=yield this.fetchCors(this.networkInfo.subscanBaseUrl+t,r);if(!s.ok||s.status===429)throw new Error(`Subscan ${t} failed with ${s.status}`);const n=yield s.json();return j(n)})}queryBalance(){return w(this,null,function*(){const t=yield this.api.query.system.account(this.walletInfo.keys.publicKey);this.nonce=t.nonce.toNumber(),this.updateBalance(this.currencyInfo.currencyCode,t.data.free.toString());for(const e of this.enabledTokenIds){const r=this.allTokensMap[e];if(r==null)continue;const s=(0,T.Oj)(r.networkLocation);if(s==null)continue;const n=yield this.api.query.assets.account(s.contractAddress,this.walletInfo.keys.publicKey);let l="0";n.isSome&&(l=n.unwrap().balance.toString()),this.updateBalance(r.currencyCode,l)}})}queryBlockheight(){return w(this,null,function*(){try{const e=(yield this.api.rpc.chain.getBlock()).block.header.number.toNumber();e>this.walletLocalData.blockHeight&&(this.walletLocalData.blockHeight=e,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight))}catch(t){this.warn("queryBlockheight failed with error: ",t)}})}processPolkadotTransaction(t){const{from:e,to:r,success:s,hash:n,block_num:l,block_timestamp:f,module:o,amount:c,fee:y}=t;if(!s||o!=="balances")return;const O=(0,I.aL)(this.currencyInfo.currencyCode,this.currencyInfo,this.allTokensMap);if(O==null)return;const b=[];let C=(0,i.mul)(c,O.multiplier);e===this.walletInfo.keys.publicKey?C=`-${(0,i.add)(C,y)}`:b.push(r);const E={blockHeight:l,currencyCode:this.currencyInfo.currencyCode,date:f,isSend:C.startsWith("-"),memos:[],nativeAmount:C,networkFee:y,ourReceiveAddresses:b,signedTx:"",txid:n,walletId:this.walletId};this.addTransaction(this.currencyInfo.currencyCode,E)}queryTransactions(){return w(this,null,function*(){if(this.networkInfo.subscanBaseUrl==null){for(const t of this.enabledTokens)this.tokenCheckTransactionsStatus[t]=1;this.updateOnAddressesChecked();return}return yield at(()=>w(this,null,function*(){return yield this.queryTransactionsInner()}))})}queryTransactionsInner(){return w(this,null,function*(){let t=Math.floor(this.otherData.txCount/this.networkInfo.subscanQueryLimit);for(;;){const e={row:this.networkInfo.subscanQueryLimit,page:t,address:this.walletInfo.keys.publicKey};let r=0,s=[];try{const n=yield this.fetchSubscan("/scan/transfers",e),l=g(n.data);r=l.count,s=l.transfers}catch(n){if(n instanceof Error&&n.message.includes("Subscan /scan/transfers failed with 429")){this.log(n.message);continue}else throw n}if(r===this.otherData.txCount||(s.forEach(n=>{try{this.processPolkadotTransaction(u(n))}catch{const f=n!=null&&typeof n.hash=="string"?n.hash:"";this.warn(`Ignoring invalid transfer ${f}`)}}),this.otherData.txCount=t*this.networkInfo.subscanQueryLimit+s.length,this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=Math.min(1,r===0?1:this.otherData.txCount/r),this.updateOnAddressesChecked(),r===this.otherData.txCount))break;t++}this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=1,this.updateOnAddressesChecked(),this.transactionsChangedArray.length>0&&(this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[])})}startEngine(){return w(this,null,function*(){this.engineOn=!0,yield this.tools.connectApi(this.walletId),this.api=this.tools.polkadotApi,this.minimumAddressBalance=this.api.consts.balances.existentialDeposit.toString(),this.addToLoop("queryBlockheight",ot).catch(()=>{}),this.addToLoop("queryBalance",st).catch(()=>{}),this.addToLoop("queryTransactions",it).catch(()=>{}),yield q(N.prototype,this,"startEngine").call(this)})}killEngine(){return w(this,null,function*(){yield q(N.prototype,this,"killEngine").call(this),yield this.tools.disconnectApi(this.walletId)})}resyncBlockchain(){return w(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getMaxSpendable(t){return w(this,null,function*(){if(t=(0,z.s)(t,this.currencyInfo),t.spendTargets.length===0||t.spendTargets[0].publicAddress==null)throw new Error("Missing public address");const e=this.getBalance({currencyCode:t.currencyCode});if(t.currencyCode!==this.currencyInfo.currencyCode){const c=[{publicAddress:t.spendTargets[0].publicAddress,nativeAmount:e}],y=Z(J({},t),{spendTargets:c});return yield this.makeSpend(y),e}const r=(0,i.sub)(e,this.api.consts.balances.existentialDeposit.toString()),s=[{publicAddress:t.spendTargets[0].publicAddress,nativeAmount:"0"}],n=Z(J({},t),{spendTargets:s}),f=(yield this.makeSpend(n)).networkFee,o=(c,y)=>{const O=(0,i.sub)(y,c);if((0,i.lte)(O,"1"))return c;const b=(0,i.add)(c,(0,i.div)(O,"2")),C=(0,I.X0)(b).replace("0x",""),E=C.length%2===1?`0${C}`:C,G=(0,i.mul)((0,i.div)(E.length.toString(),"2"),this.networkInfo.lengthFeePerByte),ht=(0,i.add)((0,i.add)(G,f),b);return(0,i.gt)(ht,r)?o(c,b):o(b,y)};return o("0",(0,i.add)(r,"1"))})}makeSpend(t){return w(this,null,function*(){t=(0,z.s)(t,this.currencyInfo);const{edgeSpendInfo:e,currencyCode:r}=this.makeSpendCheck(t),{memos:s=[]}=e;if(e.spendTargets.length!==1)throw new Error("Error: only one output allowed");const{nativeAmount:n,publicAddress:l}=e.spendTargets[0];if(l==null)throw new Error("makeSpend Missing publicAddress");if(n==null)throw new P.$D;const f=this.getBalance({currencyCode:r});let o,c;if(e.tokenId==null){const b=(0,i.sub)(f,this.api.consts.balances.existentialDeposit.toString());if((0,i.gt)(n,b))throw new P.C_;const E=yield(yield this.api.tx.balances.transferKeepAlive(l,n)).paymentInfo(this.walletInfo.keys.publicKey);if(c=(0,i.sub)(E.partialFee.toString(),(0,i.mul)(this.networkInfo.lengthFeePerByte,this.networkInfo.partialFeeOffsetMultiplier)),o=(0,i.add)(n,c),(0,i.gt)(o,b))throw new P.C_}else{if((0,i.gt)(n,f))throw new P.C_;o=n;const C=yield(yield this.api.tx.assets.transfer(parseInt(e.tokenId),l,n)).paymentInfo(this.walletInfo.keys.publicKey);c=(0,i.sub)(C.partialFee.toString(),(0,i.mul)(this.networkInfo.lengthFeePerByte,this.networkInfo.partialFeeOffsetMultiplier));const E=this.getBalance({currencyCode:this.currencyInfo.currencyCode}),G=(0,i.sub)(E,this.api.consts.balances.existentialDeposit.toString());if((0,i.gt)(c,G))throw new P.C_({currencyCode:this.currencyInfo.currencyCode,networkFee:c})}const y={publicAddress:l};return{blockHeight:0,currencyCode:r,date:0,isSend:!0,memos:s,nativeAmount:(0,i.mul)(o,"-1"),networkFee:c,otherParams:y,ourReceiveAddresses:[],signedTx:"",txid:"",walletId:this.walletId}})}signTx(t,e){return w(this,null,function*(){const r=k(this.currencyInfo.pluginId)(e),{publicAddress:s}=(0,I.Xp)(t);if(s==null)throw new Error("Missing publicAddress from makeSpend");const n=this.allTokens.find(y=>y.currencyCode===t.currencyCode);let l;if(n==null){const y=(0,i.abs)((0,i.add)(t.nativeAmount,t.networkFee));yield this.checkRecipientMinimumBalance(this.getRecipientBalance,y,s),l=yield this.api.tx.balances.transferKeepAlive(s,y)}else if(n.contractAddress!=null){const y=(0,i.abs)(t.nativeAmount);l=yield this.api.tx.assets.transfer(parseInt(n.contractAddress),s,y)}else throw new Error("Unrecognized asset");const f=this.api.createType("SignerPayload",{method:l,nonce:this.nonce,genesisHash:this.api.genesisHash,blockHash:this.api.genesisHash,runtimeVersion:this.api.runtimeVersion,version:this.api.extrinsicVersion}),o=this.api.createType("ExtrinsicPayload",f.toPayload(),{version:this.api.extrinsicVersion});if(this.keypair==null)if(this.keypair=new S.Y({ss58Format:0}),r.mnemonic!=null)this.keypair.addFromUri(r.mnemonic);else{const y=p.YU.parse(r.privateKey);this.keypair.addFromSeed(y)}const c=o.sign(this.keypair.getPair(this.walletInfo.keys.publicKey));return l.addSignature(this.walletInfo.keys.publicKey,c.signature,f.toPayload()),t.signedTx=l.toHex(),t})}broadcastTx(t){return w(this,null,function*(){try{const e=yield this.api.rpc.author.submitExtrinsic(t.signedTx);t.txid=e.toHex(),t.date=Date.now()/1e3,this.warn(`SUCCESS broadcastTx
2
+ ${(0,I.oX)(t)}`)}catch(e){throw this.warn("FAILURE broadcastTx failed: ",e),e}return t})}}function lt(d,t,e,r){return w(this,null,function*(){const s=m(e),n=new N(d,t,s,r);return yield n.loadEngine(),n})}var v=(d,t,e)=>new Promise((r,s)=>{var n=o=>{try{f(e.next(o))}catch(c){s(c)}},l=o=>{try{f(e.throw(o))}catch(c){s(c)}},f=o=>o.done?r(o.value):Promise.resolve(o.value).then(n,l);f((e=e.apply(d,t)).next())});const{ed25519PairFromSeed:ct,isAddress:tt,mnemonicToMiniSecret:ut}=X;class et{constructor(t){const{builtinTokens:e,currencyInfo:r,io:s,networkInfo:n}=t;this.builtinTokens=e,this.currencyInfo=r,this.io=s,this.networkInfo=n,this.polkadotApiSubscribers=new Set}getDisplayPrivateKey(t){return v(this,null,function*(){var e;const{pluginId:r}=this.currencyInfo,s=k(r)(t.keys);return(e=s.mnemonic)!=null?e:s.privateKey})}getDisplayPublicKey(t){return v(this,null,function*(){const{keys:e}=m(t);return e.publicKey})}importPrivateKey(t){return v(this,null,function*(){const{pluginId:e}=this.currencyInfo;if((0,L.validateMnemonic)(t)){const r=ut(t),{secretKey:s}=ct(r);return{[`${e}Mnemonic`]:t,[`${e}Key`]:U.Buffer.from(s).toString("hex")}}else{if((0,I.vq)(t))return{[`${e}Key`]:t};throw new Error("InvalidPrivateKey")}})}createPrivateKey(t){return v(this,null,function*(){if(t!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const e=U.Buffer.from(this.io.random(32)),r=(0,L.entropyToMnemonic)(e);return yield this.importPrivateKey(r)})}derivePublicKey(t){return v(this,null,function*(){const{pluginId:e}=this.currencyInfo;return{publicKey:new S.Y({ss58Format:0}).addFromUri(t.keys[`${e}Mnemonic`]).address}})}parseUri(t,e,r){return v(this,null,function*(){var s,n;const{pluginId:l}=this.currencyInfo,f={[l]:!0},{parsedUri:o,edgeParsedUri:c}=(0,F.k)(this.currencyInfo,t,f,e!=null?e:this.currencyInfo.currencyCode,r),y=(s=c.publicAddress)!=null?s:"";if(!tt(y))throw new Error("InvalidPublicAddressError");return c.uniqueIdentifier=(n=o.query.memo)!=null?n:void 0,c})}encodeUri(t){return v(this,arguments,function*(e,r=[]){const{pluginId:s}=this.currencyInfo,{nativeAmount:n,currencyCode:l,publicAddress:f}=e;if(!tt(f))throw new Error("InvalidPublicAddressError");let o;if(typeof n=="string"){const y=(0,I.Qs)(l!=null?l:this.currencyInfo.currencyCode,this.currencyInfo,r);if(y==null)throw new Error("InternalErrorInvalidCurrencyCode");o=(0,i.div)(n,y.multiplier,10)}return(0,F.Q)(e,s,o)})}connectApi(t){return v(this,null,function*(){return this.polkadotApi==null&&(this.polkadotApi=yield Y.G.create({initWasm:!1,provider:new W.U(this.networkInfo.rpcNodes[0])})),this.polkadotApiSubscribers.add(t),this.polkadotApi})}disconnectApi(t){return v(this,null,function*(){this.polkadotApiSubscribers.delete(t),this.polkadotApiSubscribers.size===0&&(yield this.polkadotApi.disconnect(),this.polkadotApi=void 0)})}getTokenId(t){return v(this,null,function*(){(0,T.Rp)(t);const e=(0,T.Oj)(t.networkLocation);if(e==null)throw new Error("ErrorInvalidContractAddress");return e.contractAddress})}}function dt(d){return v(this,null,function*(){return new et(d)})}}}]);