edge-currency-accountbased 2.2.2 → 2.2.4

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.
@@ -1 +1 @@
1
- "use strict";(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[518],{58355:function(B,x,c){var d=c(35717),C=c(51031),T=c(71027),E=c(89509).Buffer,t=c(78028),A=c(79785),w=c(89072),g=E.alloc(128);function O(P,l){T.call(this,"digest"),typeof l=="string"&&(l=E.from(l));var _=P==="sha512"||P==="sha384"?128:64;if(this._alg=P,this._key=l,l.length>_){var U=P==="rmd160"?new A:w(P);l=U.update(l).digest()}else l.length<_&&(l=E.concat([l,g],_));for(var D=this._ipad=E.allocUnsafe(_),h=this._opad=E.allocUnsafe(_),p=0;p<_;p++)D[p]=l[p]^54,h[p]=l[p]^92;this._hash=P==="rmd160"?new A:w(P),this._hash.update(D)}d(O,T),O.prototype._update=function(P){this._hash.update(P)},O.prototype._final=function(){var P=this._hash.digest(),l=this._alg==="rmd160"?new A:w(this._alg);return l.update(this._opad).update(P).digest()},B.exports=function(l,_){return l=l.toLowerCase(),l==="rmd160"||l==="ripemd160"?new O("rmd160",_):l==="md5"?new C(t,_):new O(l,_)}},51031:function(B,x,c){var d=c(35717),C=c(89509).Buffer,T=c(71027),E=C.alloc(128),t=64;function A(w,g){T.call(this,"digest"),typeof g=="string"&&(g=C.from(g)),this._alg=w,this._key=g,g.length>t?g=w(g):g.length<t&&(g=C.concat([g,E],t));for(var O=this._ipad=C.allocUnsafe(t),P=this._opad=C.allocUnsafe(t),l=0;l<t;l++)O[l]=g[l]^54,P[l]=g[l]^92;this._hash=[O]}d(A,T),A.prototype._update=function(w){this._hash.push(w)},A.prototype._final=function(){var w=this._alg(C.concat(this._hash));return this._alg(C.concat([this._opad,w]))},B.exports=A},79014:function(B,x,c){c.d(x,{Q:function(){return D},k:function(){return U}});var d=c(77591),C=c.n(d),T=c(24350),E=c(84564),t=c.n(E),A=c(76714),w=Object.defineProperty,g=Object.getOwnPropertySymbols,O=Object.prototype.hasOwnProperty,P=Object.prototype.propertyIsEnumerable,l=(h,p,v)=>p in h?w(h,p,{enumerable:!0,configurable:!0,writable:!0,value:v}):h[p]=v,_=(h,p)=>{for(var v in p||(p={}))O.call(p,v)&&l(h,v,p[v]);if(g)for(var v of g(p))P.call(p,v)&&l(h,v,p[v]);return h};function U(h,p,v,b,k=[]){const y=_({},t()(p,{},!0)),K=p.startsWith(`${h.pluginId}://`);if(y.protocol!=null&&(y.protocol=y.protocol.replace(":","")),y.protocol!=null&&y.protocol!==""&&!v[y.protocol])throw new Error(`Uri protocol '${y.protocol}' is not supported for ${h.pluginId}.`);if(y.host===""&&y.pathname==="")throw new Error("Path and host not found in uri.");const S={publicAddress:y.host!==""?y.host:y.pathname.split("/")[0]},F=y.query.label,N=y.query.message,W=y.query.category;(F!=null||N!=null||W!=null||K)&&(S.metadata={},S.metadata.name=F,S.metadata.notes=N,S.metadata.category=W,S.metadata.gateway=K!=null?K:!1);const R=y.query.amount;if(R!=null&&typeof R=="string"){b==null&&(b=h.currencyCode);const J=(0,A.Qs)(b!=null?b:"",h,k);if(J==null)throw new Error("InternalErrorInvalidCurrencyCode");let $=(0,d.mul)(R,J.multiplier);$=(0,d.toFixed)($,0,0),S.nativeAmount=$,S.currencyCode=b}return{edgeParsedUri:S,parsedUri:y}}function D(h,p,v){if(h.publicAddress==null)throw new Error("InvalidPublicAddressError");if(v==null&&h.label==null&&h.message==null)return h.publicAddress;{let b="";v!=null&&(b+="amount="+v+"&"),(h.label!=null||h.message!=null)&&(typeof h.label=="string"&&(b+="label="+h.label+"&"),typeof h.message=="string"&&(b+="message="+h.message+"&")),b=b.substr(0,b.length-1);const k={scheme:p,path:h.publicAddress,query:b};return(0,T.qC)(k)}}},59677:function(B,x,c){c.r(x),c.d(x,{FilecoinTools:function(){return z},makeCurrencyEngine:function(){return ht},makeCurrencyTools:function(){return ft}});var d=c(23145),C=c(77591),T=c(37786),E=c(2153),t=c(82448),A=c(35620),w=c(79014),g=c(76714),O=c(62177);const P=(0,t.su)({}),l=(0,t.su)({sigJson:(0,t.Zz)((0,t.su)({Data:t.XC,Type:(0,t.Wf)(1,3)})),txJson:(0,t.su)({To:t.XC,From:t.XC,Nonce:t.mH,Value:t.XC,GasLimit:t.mH,GasFeeCap:t.XC,GasPremium:t.XC,Method:t.mH,Params:t.XC})}),_=(0,t.su)({address:t.XC,publicKey:t.XC}),U=(0,O.jd)(_),D=o=>{const e=(0,t.su)({[`${o}Mnemonic`]:t.XC,[`${o}Key`]:t.XC});return(0,t.W1)(n=>{const r=e(n);return{mnemonic:r[`${o}Mnemonic`],privateKey:r[`${o}Key`]}},n=>({[`${o}Mnemonic`]:n.mnemonic,[`${o}Key`]:n.privateKey}))};var h=c(94935),p=c(84650),v=(o,e,n)=>new Promise((r,s)=>{var a=i=>{try{f(n.next(i))}catch(m){s(m)}},u=i=>{try{f(n.throw(i))}catch(m){s(m)}},f=i=>i.done?r(i.value):Promise.resolve(i.value).then(a,u);f((n=n.apply(o,e)).next())});const b=o=>(0,t.su)({result:o}),k=(0,t.$e)((0,t.su)({code:t.mH,message:t.XC})),y=o=>(0,t.$e)((0,t._C)(k,b(o))),K=(0,t.su)({height:t.mH,block_time:t.mH,cid:t.XC,from:t.XC,to:t.XC,value:t.XC,exit_code:t.XC,method_name:t.XC}),V=(0,t.su)({account_type:t.XC,account_info:(0,t.su)({account_basic:(0,t.su)({account_id:t.XC,account_address:t.XC,account_type:t.XC,account_balance:t.XC,nonce:t.mH,code_cid:t.XC,create_time:t.XC,latest_transfer_time:t.XC})})}),S=(0,t.su)({messages_by_account_id_list:(0,t.Vk)((0,t._2)(K),()=>[]),total_count:t.mH}),F=(0,t.su)({MessageDetails:(0,t.su)({message_basic:(0,t.su)({height:t.mH,block_time:t.mH,cid:t.XC,from:t.XC,to:t.XC,value:t.XC,exit_code:t.XC,method_name:t.XC}),blk_cids:(0,t._2)(t.XC),consume_list:(0,t._2)((0,t.su)({from:t.XC,to:t.XC,value:t.XC,consume_type:t.XC})),version:t.mH,nonce:t.mH,gas_fee_cap:t.XC,gas_premium:t.XC,gas_limit:t.mH,gas_used:t.XC,base_fee:t.XC,all_gas_fee:t.XC,eth_message:t.XC})});class N{constructor(e,n){this.baseUrl=e,this.fetch=n}getAccountInfo(e){return v(this,null,function*(){const r=yield(yield this.fetch(`${this.baseUrl}/AccountInfoByID`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({account_id:e})})).text(),s=y(V)(r);if(!("result"in s))throw new Error(`Error response code ${s.code}: ${s.message}`);return s})}getAccountMessages(e,n,r=20){return v(this,null,function*(){const a=yield(yield this.fetch(`${this.baseUrl}/MessagesByAccountID`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({account_id:e,address:"",filters:{index:n,page:0,limit:r,method_name:""}})})).text(),u=y(S)(a);if(!("result"in u))throw new Error(`Error response code ${u.code}: ${u.message}`);return u})}getMessageDetails(e){return v(this,null,function*(){const r=yield(yield this.fetch(`${this.baseUrl}/MessageDetails`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({message_cid:e})})).text(),s=y(F)(r);if(!("result"in s))throw new Error(`Error response code ${s.code}: ${s.message}`);return s})}}var W=Math.pow,R=(o,e,n)=>new Promise((r,s)=>{var a=i=>{try{f(n.next(i))}catch(m){s(m)}},u=i=>{try{f(n.throw(i))}catch(m){s(m)}},f=i=>i.done?r(i.value):Promise.resolve(i.value).then(a,u);f((n=n.apply(o,e)).next())});const J=o=>(0,t.su)({id:t.mH,jsonrpc:t.XC,result:o}),$=(0,t.su)({id:t.mH,jsonrpc:t.XC,error:(0,t.su)({code:t.mH,message:t.XC})}),Q=o=>(0,t.$e)((0,t._C)($,J(o))),Z=(0,t.su)({Height:t.mH});class q{constructor(e,n){this.baseUrl=e,this.fetch=n}getChainHead(){return R(this,null,function*(){const e=Math.floor(Math.random()*W(10,8)),r=yield(yield this.fetch(this.baseUrl,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({id:e,jsonrpc:"2.0",method:"Filecoin.ChainHead",params:null})})).text(),s=Q(Z)(r);if("error"in s)throw new Error(`Error response code ${s.error.code}: ${s.error.message}`);return s})}}var tt=Object.defineProperty,et=Object.defineProperties,nt=Object.getOwnPropertyDescriptors,j=Object.getOwnPropertySymbols,st=Object.getPrototypeOf,rt=Object.prototype.hasOwnProperty,ot=Object.prototype.propertyIsEnumerable,it=Reflect.get,Y=(o,e,n)=>e in o?tt(o,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):o[e]=n,at=(o,e)=>{for(var n in e||(e={}))rt.call(e,n)&&Y(o,n,e[n]);if(j)for(var n of j(e))ot.call(e,n)&&Y(o,n,e[n]);return o},ct=(o,e)=>et(o,nt(e)),L=(o,e,n)=>it(st(o),n,e),I=(o,e,n)=>new Promise((r,s)=>{var a=i=>{try{f(n.next(i))}catch(m){s(m)}},u=i=>{try{f(n.throw(i))}catch(m){s(m)}},f=i=>i.done?r(i.value):Promise.resolve(i.value).then(a,u);f((n=n.apply(o,e)).next())});const lt=15e3,ut=3e4,dt=15e3;class X extends p.P{constructor(e,n,r,s){super(e,n,r,s);const{networkInfo:a}=e;this.address=d.kL.fromString(r.keys.address),this.availableAttoFil="0",this.filRpc=new d.rP(e.networkInfo.rpcNode.networkName,{url:e.networkInfo.rpcNode.url,token:e.currencyInfo.currencyCode}),this.filscanApi=new N(e.networkInfo.filscanUrl,e.io.fetchCors),this.rpcExtra=new q(e.networkInfo.rpcNode.url,e.io.fetchCors),this.networkInfo=a,this.pluginId=this.currencyInfo.pluginId}setOtherData(e){this.otherData=P(e)}initData(){this.availableAttoFil="0"}initSubscriptions(){this.addToLoop("checkBalance",lt).catch(e=>this.log(e)),this.addToLoop("checkBlockHeight",ut).catch(e=>this.log(e)),this.addToLoop("checkTransactions",dt).catch(e=>this.log(e))}onUpdateBlockHeight(e){this.walletLocalData.blockHeight!==e&&(this.walletLocalData.blockHeight=e,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight))}onUpdateTransactions(){this.transactionsChangedArray.length>0&&(this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[])}startEngine(){return I(this,null,function*(){this.initData(),this.initSubscriptions(),yield L(X.prototype,this,"startEngine").call(this)})}killEngine(){return I(this,null,function*(){yield L(X.prototype,this,"killEngine").call(this)})}clearBlockchainCache(){return I(this,null,function*(){yield L(X.prototype,this,"clearBlockchainCache").call(this)})}resyncBlockchain(){return I(this,null,function*(){yield L(X.prototype,this,"killEngine").call(this),yield this.clearBlockchainCache(),yield this.startEngine()})}getFreshAddress(){return I(this,null,function*(){const{address:e}=this.walletInfo.keys;return{publicAddress:e}})}getMaxSpendable(e){return I(this,null,function*(){const r=(yield this.makeSpend(e)).networkFee,s=(0,C.sub)(this.availableAttoFil,r);if((0,C.lte)(s,"0"))throw new h.C_;return s})}makeSpend(e){return I(this,null,function*(){const{edgeSpendInfo:n,currencyCode:r}=this.makeSpendCheck(e),s=n.spendTargets[0],{publicAddress:a,nativeAmount:u}=s;if(a==null)throw new Error("Missing publicAddress in EdgeSpendInfo");if(u==null)throw new h.$D;const f=d.kL.fromString(a),i=d.YW.getNew(f,this.address,d.WU.fromAtto(u),0);yield i.prepareToSend(this.filRpc);const m=i.toJSON(),M={sigJson:void 0,txJson:m},G=(0,C.mul)(m.GasLimit.toString(),m.GasPremium),pt=(0,C.add)(u,G);return{txid:"",date:0,currencyCode:r,blockHeight:0,nativeAmount:`-${pt}`,isSend:u.startsWith("-"),networkFee:G,ourReceiveAddresses:[],otherParams:M,signedTx:"",walletId:this.walletId}})}signTx(e,n){return I(this,null,function*(){const r=l(e.otherParams),s=d.YW.fromJSON(r.txJson),a=D(this.pluginId)(n),u=d.w5.deriveAccount(a.mnemonic,d.BG.SECP256K1,this.tools.derivationPath),f=yield d.w5.signTransaction(u,s);return e.otherParams=ct(at({},e.otherParams),{sigJson:f.toJSON()}),e})}broadcastTx(e,n){return I(this,null,function*(){const r=l(e.otherParams);if(r.sigJson==null)throw new Error("Cannot broadcast unsigned transaction");const s=d.Pc.fromJSON(r.sigJson),a=d.YW.fromJSON(r.txJson),u=yield this.filRpc.broadcastTransaction(a,s);if("error"in u)throw new Error(u.error.message);return e.txid=u.result["/"],e})}getDisplayPrivateSeed(e){return D(this.pluginId)(e).mnemonic}getDisplayPublicSeed(){return this.walletInfo.keys.publicKey}loadEngine(){return I(this,null,function*(){yield L(X.prototype,this,"loadEngine").call(this),this.engineOn=!0})}checkBalance(){return I(this,null,function*(){const e=yield this.filRpc.walletBalance(this.address);if("error"in e)throw new Error(e.error.message);const{result:n}=e;this.availableAttoFil=n,this.updateBalance(this.currencyInfo.currencyCode,n),this.tokenCheckBalanceStatus[this.currencyInfo.currencyCode]=1,this.updateOnAddressesChecked(),this.walletLocalDataDirty=!0})}checkBlockHeight(){return I(this,null,function*(){const n=(yield this.rpcExtra.getChainHead()).result.Height;this.onUpdateBlockHeight(n)})}checkTransactions(){return I(this,null,function*(){const e=this.address.toString(),n=20;let r=0,s=0,a=0;do{const u=yield this.filscanApi.getAccountMessages(e,r++,n),f=u.result.messages_by_account_id_list;for(const i of f){const m=i.cid;if(this.findTransaction(this.currencyInfo.currencyCode,m)>=0)return;this.processMessage(i)}a=u.result.total_count,s+=f.length,this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=a===0?1:s/a,this.updateOnAddressesChecked()}while(s<a)})}processMessage(e){const n=this.address.toString();let r=e.value;const s=[],a="0";e.to!==n?r=`-${(0,C.add)(r,a)}`:s.push(n);const u={txid:e.cid,date:e.block_time,currencyCode:this.currencyInfo.currencyCode,blockHeight:e.height,nativeAmount:r,isSend:r.startsWith("-"),networkFee:a,ourReceiveAddresses:s,signedTx:"",otherParams:{},walletId:this.walletId};this.addTransaction(this.currencyInfo.currencyCode,u),this.onUpdateTransactions(),this.walletLocalData.blockHeight<e.height&&this.onUpdateBlockHeight(e.height)}}function ht(o,e,n,r){return I(this,null,function*(){const s=U(n),a=new X(o,e,s,r);return yield a.loadEngine(),a})}var H=(o,e,n)=>new Promise((r,s)=>{var a=i=>{try{f(n.next(i))}catch(m){s(m)}},u=i=>{try{f(n.throw(i))}catch(m){s(m)}},f=i=>i.done?r(i.value):Promise.resolve(i.value).then(a,u);f((n=n.apply(o,e)).next())});class z{constructor(e){const{builtinTokens:n,currencyInfo:r,io:s,networkInfo:a}=e;this.builtinTokens=n,this.currencyInfo=r,this.io=s,this.networkInfo=a,this.derivationPath=`m/44'/${this.networkInfo.hdPathCoinType}'/0'/0/0`}isValidAddress(e){return H(this,null,function*(){try{return d.kL.fromString(e),!0}catch{return!1}})}importPrivateKey(e){return H(this,arguments,function*(n,r={}){const{pluginId:s}=this.currencyInfo;if(!(0,E.validateMnemonic)(n))throw new Error("Invalid mnemonic");const a=(yield(0,E.mnemonicToSeed)(n)).toString("hex");return{[`${s}Key`]:a,[`${s}Mnemonic`]:n}})}createPrivateKey(e){return H(this,null,function*(){const{pluginId:n}=this.currencyInfo;if(e!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const r=A.YU.stringify(this.io.random(32)),s=(0,E.entropyToMnemonic)(r);return{[`${n}Key`]:r,[`${n}Mnemonic`]:s}})}checkPublicKey(e){return H(this,null,function*(){return(0,t.Vk)(_)(e)!=null})}derivePublicKey(e){return H(this,null,function*(){if(e.type!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const{pluginId:n}=this.currencyInfo,{hdPathCoinType:r}=this.networkInfo,s=D(n)(e.keys),a=yield(0,E.mnemonicToSeed)(s.mnemonic),m=(0,T.fromSeed)(a).deriveHardened(44).deriveHardened(r).deriveHardened(0).neutered().toBase58(),G=d.w5.deriveAccount(s.mnemonic,d.BG.SECP256K1,this.derivationPath).address.toString();return{publicKey:m,address:G}})}parseUri(e,n,r){return H(this,null,function*(){const{pluginId:s}=this.currencyInfo,a={[s]:!0},{edgeParsedUri:u,edgeParsedUri:{publicAddress:f}}=(0,w.k)(this.currencyInfo,e,a,n!=null?n:this.currencyInfo.currencyCode,r);if(f==null||!(yield this.isValidAddress(f)))throw new Error("InvalidPublicAddressError");return u})}encodeUri(e){return H(this,arguments,function*(n,r=[]){const{pluginId:s}=this.currencyInfo,{nativeAmount:a,currencyCode:u,publicAddress:f}=n;if(!(yield this.isValidAddress(f)))throw new Error("InvalidPublicAddressError");let i;if(a!=null){const M=(0,g.Qs)(u!=null?u:this.currencyInfo.currencyCode,this.currencyInfo,r);if(M==null)throw new Error("InternalErrorInvalidCurrencyCode");i=(0,C.div)(a,M.multiplier,18)}return(0,w.Q)(n,`${s}`,i)})}}function ft(o){return H(this,null,function*(){return new z(o)})}},35620:function(B,x,c){c.d(x,{US:function(){return t},YU:function(){return C}});var d=c(79911);const C=d.base16,T=d.base32,E=d.base32hex,t=d.base64,A=d.base64url,w=d.codec;var g=null}}]);
1
+ "use strict";(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[518],{58355:function(F,O,u){var f=u(35717),g=u(51031),X=u(71027),_=u(89509).Buffer,e=u(78028),x=u(79785),P=u(89072),y=_.alloc(128);function A(w,h){X.call(this,"digest"),typeof h=="string"&&(h=_.from(h));var T=w==="sha512"||w==="sha384"?128:64;if(this._alg=w,this._key=h,h.length>T){var L=w==="rmd160"?new x:P(w);h=L.update(h).digest()}else h.length<T&&(h=_.concat([h,y],T));for(var D=this._ipad=_.allocUnsafe(T),p=this._opad=_.allocUnsafe(T),m=0;m<T;m++)D[m]=h[m]^54,p[m]=h[m]^92;this._hash=w==="rmd160"?new x:P(w),this._hash.update(D)}f(A,X),A.prototype._update=function(w){this._hash.update(w)},A.prototype._final=function(){var w=this._hash.digest(),h=this._alg==="rmd160"?new x:P(this._alg);return h.update(this._opad).update(w).digest()},F.exports=function(h,T){return h=h.toLowerCase(),h==="rmd160"||h==="ripemd160"?new A("rmd160",T):h==="md5"?new g(e,T):new A(h,T)}},51031:function(F,O,u){var f=u(35717),g=u(89509).Buffer,X=u(71027),_=g.alloc(128),e=64;function x(P,y){X.call(this,"digest"),typeof y=="string"&&(y=g.from(y)),this._alg=P,this._key=y,y.length>e?y=P(y):y.length<e&&(y=g.concat([y,_],e));for(var A=this._ipad=g.allocUnsafe(e),w=this._opad=g.allocUnsafe(e),h=0;h<e;h++)A[h]=y[h]^54,w[h]=y[h]^92;this._hash=[A]}f(x,X),x.prototype._update=function(P){this._hash.push(P)},x.prototype._final=function(){var P=this._alg(g.concat(this._hash));return this._alg(g.concat([this._opad,P]))},F.exports=x},79014:function(F,O,u){u.d(O,{Q:function(){return D},k:function(){return L}});var f=u(77591),g=u.n(f),X=u(24350),_=u(84564),e=u.n(_),x=u(76714),P=Object.defineProperty,y=Object.getOwnPropertySymbols,A=Object.prototype.hasOwnProperty,w=Object.prototype.propertyIsEnumerable,h=(p,m,v)=>m in p?P(p,m,{enumerable:!0,configurable:!0,writable:!0,value:v}):p[m]=v,T=(p,m)=>{for(var v in m||(m={}))A.call(m,v)&&h(p,v,m[v]);if(y)for(var v of y(m))w.call(m,v)&&h(p,v,m[v]);return p};function L(p,m,v,I,B=[]){const C=T({},e()(m,{},!0)),K=m.startsWith(`${p.pluginId}://`);if(C.protocol!=null&&(C.protocol=C.protocol.replace(":","")),C.protocol!=null&&C.protocol!==""&&!v[C.protocol])throw new Error(`Uri protocol '${C.protocol}' is not supported for ${p.pluginId}.`);if(C.host===""&&C.pathname==="")throw new Error("Path and host not found in uri.");const S={publicAddress:C.host!==""?C.host:C.pathname.split("/")[0]},G=C.query.label,$=C.query.message,j=C.query.category;(G!=null||$!=null||j!=null||K)&&(S.metadata={},S.metadata.name=G,S.metadata.notes=$,S.metadata.category=j,S.metadata.gateway=K!=null?K:!1);const N=C.query.amount;if(N!=null&&typeof N=="string"){I==null&&(I=p.currencyCode);const R=(0,x.Qs)(I!=null?I:"",p,B);if(R==null)throw new Error("InternalErrorInvalidCurrencyCode");let W=(0,f.mul)(N,R.multiplier);W=(0,f.toFixed)(W,0,0),S.nativeAmount=W,S.currencyCode=I}return{edgeParsedUri:S,parsedUri:C}}function D(p,m,v){if(p.publicAddress==null)throw new Error("InvalidPublicAddressError");if(v==null&&p.label==null&&p.message==null)return p.publicAddress;{let I="";v!=null&&(I+="amount="+v+"&"),(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 B={scheme:m,path:p.publicAddress,query:I};return(0,X.qC)(B)}}},12636:function(F,O,u){u.r(O),u.d(O,{FilecoinTools:function(){return Y},makeCurrencyEngine:function(){return Ee},makeCurrencyTools:function(){return be}});var f=u(23145),g=u(77591),X=u(37786),_=u(2153),e=u(82448),x=u(35620),P=u(79014),y=u(76714),A=u(62177);const w=(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}),L=(0,A.jd)(T),D=c=>{const t=(0,e.su)({[`${c}Mnemonic`]:e.XC,[`${c}Key`]:e.XC});return(0,e.W1)(s=>{const i=t(s);return{mnemonic:i[`${c}Mnemonic`],privateKey:i[`${c}Key`]}},s=>({[`${c}Mnemonic`]:s.mnemonic,[`${c}Key`]:s.privateKey}))};var p=u(94935),m=u(84650),v=(c,t,s)=>new Promise((i,n)=>{var a=r=>{try{l(s.next(r))}catch(d){n(d)}},o=r=>{try{l(s.throw(r))}catch(d){n(d)}},l=r=>r.done?i(r.value):Promise.resolve(r.value).then(a,o);l((s=s.apply(c,t)).next())});const I=(0,e.su)({statusCode:e.mH,message:e.XC,error:e.XC}),B=c=>(0,e.$e)((0,e._C)(I,c)),C=(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}),K=(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}))}),V=(0,e.su)({messages:(0,e._2)(C),totalCount:e.mH}),S=K;class G{constructor(t,s){this.baseUrl=t,this.fetch=s}getAccountMessages(t,s,i=20){return v(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 l=yield(yield this.fetch(n.toString(),{method:"GET",headers:{"content-type":"application/json"}})).text(),r=B(V)(l);if("error"in r)throw new Error(`Error response code ${r.statusCode}: ${r.message} ${r.error}`);return r})}getMessageDetails(t){return v(this,null,function*(){const i=yield(yield this.fetch(`${this.baseUrl}/message/${t}`,{method:"GET",headers:{"content-type":"application/json"}})).text(),n=B(S)(i);if("error"in n)throw new Error(`Error response code ${n.statusCode}: ${n.message} ${n.error}`);return n})}}var $=(c,t,s)=>new Promise((i,n)=>{var a=r=>{try{l(s.next(r))}catch(d){n(d)}},o=r=>{try{l(s.throw(r))}catch(d){n(d)}},l=r=>r.done?i(r.value):Promise.resolve(r.value).then(a,o);l((s=s.apply(c,t)).next())});const j=c=>(0,e.su)({result:c}),N=(0,e.su)({code:e.mH,message:e.XC}),R=c=>(0,e.$e)((0,e._C)(N,j(c))),W=(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}),q=(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})})}),ee=(0,e.su)({messages_by_account_id_list:(0,e.Vk)((0,e._2)(W),()=>[]),total_count:e.mH}),te=(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 se{constructor(t,s){this.baseUrl=t,this.fetch=s}getAccountInfo(t){return $(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=R(q)(i);if(!("result"in n))throw new Error(`Error response code ${n.code}: ${n.message}`);return n.result})}getAccountMessages(t,s,i=20){return $(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=R(ee)(a);if(!("result"in o))throw new Error(`Error response code ${o.code}: ${o.message}`);return o.result})}getMessageDetails(t){return $(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=R(te)(i);if(!("result"in n))throw new Error(`Error response code ${n.code}: ${n.message}`);return n.result})}}var ne=Math.pow,re=(c,t,s)=>new Promise((i,n)=>{var a=r=>{try{l(s.next(r))}catch(d){n(d)}},o=r=>{try{l(s.throw(r))}catch(d){n(d)}},l=r=>r.done?i(r.value):Promise.resolve(r.value).then(a,o);l((s=s.apply(c,t)).next())});const oe=c=>(0,e.su)({id:e.mH,jsonrpc:e.XC,result:c}),ie=(0,e.su)({id:e.mH,jsonrpc:e.XC,error:(0,e.su)({code:e.mH,message:e.XC})}),ae=c=>(0,e.$e)((0,e._C)(ie,oe(c))),ce=(0,e.su)({Height:e.mH});class le{constructor(t,s){this.baseUrl=t,this.fetch=s}getChainHead(){return re(this,null,function*(){const t=Math.floor(Math.random()*ne(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=ae(ce)(i);if("error"in n)throw new Error(`Error response code ${n.error.code}: ${n.error.message}`);return n})}}var ue=Object.defineProperty,de=Object.defineProperties,he=Object.getOwnPropertyDescriptors,Q=Object.getOwnPropertySymbols,fe=Object.getPrototypeOf,pe=Object.prototype.hasOwnProperty,me=Object.prototype.propertyIsEnumerable,ge=Reflect.get,z=(c,t,s)=>t in c?ue(c,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):c[t]=s,ye=(c,t)=>{for(var s in t||(t={}))pe.call(t,s)&&z(c,s,t[s]);if(Q)for(var s of Q(t))me.call(t,s)&&z(c,s,t[s]);return c},Ce=(c,t)=>de(c,he(t)),J=(c,t,s)=>ge(fe(c),s,t),E=(c,t,s)=>new Promise((i,n)=>{var a=r=>{try{l(s.next(r))}catch(d){n(d)}},o=r=>{try{l(s.throw(r))}catch(d){n(d)}},l=r=>r.done?i(r.value):Promise.resolve(r.value).then(a,o);l((s=s.apply(c,t)).next())});const ve=15e3,we=3e4,Pe=15e3;class U extends m.P{constructor(t,s,i,n){super(t,s,i,n),this.filfoxMessageToEdgeTransaction=o=>{const l=this.address.toString(),r=[],d=o.transfers.filter(k=>k.type==="miner-fee"||k.type==="burner-fee").reduce((k,Z)=>(0,g.add)(k,Z.value),"0");let b;return o.from===l?(b=`-${d}`,o.to!==l&&(b=(0,g.sub)(b,o.value))):(b=o.value,r.push(l)),{txid:o.cid,date:o.timestamp,currencyCode:this.currencyInfo.currencyCode,blockHeight:o.height,nativeAmount:b,isSend:b.startsWith("-"),networkFee:d,ourReceiveAddresses:r,signedTx:"",otherParams:{},walletId:this.walletId}};const{networkInfo:a}=t;this.address=f.kL.fromString(i.keys.address),this.availableAttoFil="0",this.isScanning=!1,this.networkInfo=a,this.pluginId=this.currencyInfo.pluginId,this.filRpc=new f.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 se(t.networkInfo.filscanUrl,t.io.fetchCors),this.rpcExtra=new le(t.networkInfo.rpcNode.url,t.io.fetchCors)}setOtherData(t){this.otherData=w(t)}initData(){this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=0,this.availableAttoFil="0"}initSubscriptions(){this.addToLoop("checkBalance",ve).catch(t=>this.log(t)),this.addToLoop("checkBlockHeight",we).catch(t=>this.log(t)),this.addToLoop("checkTransactions",Pe).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 J(U.prototype,this,"startEngine").call(this)})}killEngine(){return E(this,null,function*(){yield J(U.prototype,this,"killEngine").call(this)})}clearBlockchainCache(){return E(this,null,function*(){yield J(U.prototype,this,"clearBlockchainCache").call(this)})}resyncBlockchain(){return E(this,null,function*(){yield J(U.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 i=(yield this.makeSpend(t)).networkFee,n=(0,g.sub)(this.availableAttoFil,i);if((0,g.lte)(n,"0"))throw new p.C_;return n})}makeSpend(t){return E(this,null,function*(){const{edgeSpendInfo:s,currencyCode:i}=this.makeSpendCheck(t),n=s.spendTargets[0],{publicAddress:a,nativeAmount:o}=n;if(a==null)throw new Error("Missing publicAddress in EdgeSpendInfo");if(o==null)throw new p.$D;const l=f.kL.fromString(a),r=f.YW.getNew(l,this.address,f.WU.fromAtto(o),0);yield r.prepareToSend(this.filRpc);const d=r.toJSON(),b={sigJson:void 0,txJson:d},H=(0,g.mul)(d.GasLimit.toString(),d.GasPremium),k=(0,g.mul)((0,g.add)(o,H),"-1");return{txid:"",date:0,currencyCode:i,blockHeight:0,nativeAmount:k,isSend:!0,networkFee:H,ourReceiveAddresses:[],otherParams:b,signedTx:"",walletId:this.walletId}})}signTx(t,s){return E(this,null,function*(){const i=h(t.otherParams),n=f.YW.fromJSON(i.txJson),a=D(this.pluginId)(s),o=f.w5.deriveAccount(a.mnemonic,f.BG.SECP256K1,this.tools.derivationPath),l=yield f.w5.signTransaction(o,n);return t.otherParams=Ce(ye({},t.otherParams),{sigJson:l.toJSON()}),t.date=Date.now()/1e3,t})}broadcastTx(t,s){return E(this,null,function*(){const i=h(t.otherParams);if(i.sigJson==null)throw new Error("Cannot broadcast unsigned transaction");const n=f.Pc.fromJSON(i.sigJson),a=f.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 D(this.pluginId)(t).mnemonic}getDisplayPublicSeed(){return this.walletInfo.keys.publicKey}loadEngine(){return E(this,null,function*(){yield J(U.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*(){if(!this.isScanning)try{this.isScanning=!0;const t=this.address.toString(),s=o=>{const l=this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode],r=o;l<1&&(r>=1||r>l*1.1)&&(this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=r,this.updateOnAddressesChecked())},i=({tx:o,progress:l})=>{this.addTransaction(this.currencyInfo.currencyCode,o),this.onUpdateTransactions(),this.walletLocalData.blockHeight<o.blockHeight&&this.onUpdateBlockHeight(o.blockHeight),s(l)},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 E(this,null,function*(){let n=0,a=0,o=-1;do{const l=yield this.filfoxApi.getAccountMessages(t,n++,20);o=o===-1?l.totalCount:o;const r=l.messages;for(const d of r){if(d.height<this.walletLocalData.lastAddressQueryHeight)return;const b=yield this.filfoxApi.getMessageDetails(d.cid),H=this.filfoxMessageToEdgeTransaction(b),k=o===0?1:++a/o;s({tx:H,progress:k})}}while(a<o)})}scanTransactionsFromFilscan(t,s){return E(this,null,function*(){let n=0,a=0,o=-1;do{const l=yield this.filscanApi.getAccountMessages(t,n++,20);o=o===-1?l.total_count:o;const r=l.messages_by_account_id_list;for(const d of r){if(d.height<this.walletLocalData.lastAddressQueryHeight)return;const b=this.filscanMessageToEdgeTransaction(d),H=o===0?1:++a/o;s({tx:b,progress:H})}}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,g.sub)(a,t.value))):(a=t.value,i.push(s)),{txid:t.cid,date:t.block_time,currencyCode:this.currencyInfo.currencyCode,blockHeight:t.height,nativeAmount:a,isSend:a.startsWith("-"),networkFee:n,ourReceiveAddresses:i,signedTx:"",otherParams:{},walletId:this.walletId}}}function Ee(c,t,s,i){return E(this,null,function*(){const n=L(s),a=new U(c,t,n,i);return yield a.loadEngine(),a})}var M=(c,t,s)=>new Promise((i,n)=>{var a=r=>{try{l(s.next(r))}catch(d){n(d)}},o=r=>{try{l(s.throw(r))}catch(d){n(d)}},l=r=>r.done?i(r.value):Promise.resolve(r.value).then(a,o);l((s=s.apply(c,t)).next())});class Y{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 M(this,null,function*(){try{return f.kL.fromString(t),!0}catch{return!1}})}importPrivateKey(t){return M(this,arguments,function*(s,i={}){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 M(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,_.entropyToMnemonic)(i);return{[`${s}Key`]:i,[`${s}Mnemonic`]:n}})}checkPublicKey(t){return M(this,null,function*(){return(0,e.Vk)(T)(t)!=null})}derivePublicKey(t){return M(this,null,function*(){if(t.type!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const{pluginId:s}=this.currencyInfo,{hdPathCoinType:i}=this.networkInfo,n=D(s)(t.keys),a=yield(0,_.mnemonicToSeed)(n.mnemonic),d=(0,X.fromSeed)(a).deriveHardened(44).deriveHardened(i).deriveHardened(0).neutered().toBase58(),H=f.w5.deriveAccount(n.mnemonic,f.BG.SECP256K1,this.derivationPath).address.toString();return{publicKey:d,address:H}})}parseUri(t,s,i){return M(this,null,function*(){const{pluginId:n}=this.currencyInfo,a={[n]:!0},{edgeParsedUri:o,edgeParsedUri:{publicAddress:l}}=(0,P.k)(this.currencyInfo,t,a,s!=null?s:this.currencyInfo.currencyCode,i);if(l==null||!(yield this.isValidAddress(l)))throw new Error("InvalidPublicAddressError");return o})}encodeUri(t){return M(this,arguments,function*(s,i=[]){const{pluginId:n}=this.currencyInfo,{nativeAmount:a,currencyCode:o,publicAddress:l}=s;if(!(yield this.isValidAddress(l)))throw new Error("InvalidPublicAddressError");let r;if(a!=null){const b=(0,y.Qs)(o!=null?o:this.currencyInfo.currencyCode,this.currencyInfo,i);if(b==null)throw new Error("InternalErrorInvalidCurrencyCode");r=(0,g.div)(a,b.multiplier,18)}return(0,P.Q)(s,`${n}`,r)})}}function be(c){return M(this,null,function*(){return new Y(c)})}},35620:function(F,O,u){u.d(O,{US:function(){return e},YU:function(){return g}});var f=u(79911);const g=f.base16,X=f.base32,_=f.base32hex,e=f.base64,x=f.base64url,P=f.codec;var y=null}}]);
@@ -1,2 +1,2 @@
1
- "use strict";(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[159],{79014:function(_,O,d){d.d(O,{Q:function(){return V},k:function(){return b}});var w=d(77591),A=d.n(w),R=d(24350),x=d(84564),N=d.n(x),M=d(76714),h=Object.defineProperty,U=Object.getOwnPropertySymbols,L=Object.prototype.hasOwnProperty,$=Object.prototype.propertyIsEnumerable,P=(a,y,f)=>y in a?h(a,y,{enumerable:!0,configurable:!0,writable:!0,value:f}):a[y]=f,S=(a,y)=>{for(var f in y||(y={}))L.call(y,f)&&P(a,f,y[f]);if(U)for(var f of U(y))$.call(y,f)&&P(a,f,y[f]);return a};function b(a,y,f,g,D=[]){const u=S({},N()(y,{},!0)),T=y.startsWith(`${a.pluginId}://`);if(u.protocol!=null&&(u.protocol=u.protocol.replace(":","")),u.protocol!=null&&u.protocol!==""&&!f[u.protocol])throw new Error(`Uri protocol '${u.protocol}' is not supported for ${a.pluginId}.`);if(u.host===""&&u.pathname==="")throw new Error("Path and host not found in uri.");const k={publicAddress:u.host!==""?u.host:u.pathname.split("/")[0]},p=u.query.label,I=u.query.message,z=u.query.category;(p!=null||I!=null||z!=null||T)&&(k.metadata={},k.metadata.name=p,k.metadata.notes=I,k.metadata.category=z,k.metadata.gateway=T!=null?T:!1);const m=u.query.amount;if(m!=null&&typeof m=="string"){g==null&&(g=a.currencyCode);const B=(0,M.Qs)(g!=null?g:"",a,D);if(B==null)throw new Error("InternalErrorInvalidCurrencyCode");let K=(0,w.mul)(m,B.multiplier);K=(0,w.toFixed)(K,0,0),k.nativeAmount=K,k.currencyCode=g}return{edgeParsedUri:k,parsedUri:u}}function V(a,y,f){if(a.publicAddress==null)throw new Error("InvalidPublicAddressError");if(f==null&&a.label==null&&a.message==null)return a.publicAddress;{let g="";f!=null&&(g+="amount="+f+"&"),(a.label!=null||a.message!=null)&&(typeof a.label=="string"&&(g+="label="+a.label+"&"),typeof a.message=="string"&&(g+="message="+a.message+"&")),g=g.substr(0,g.length-1);const D={scheme:y,path:a.publicAddress,query:g};return(0,R.qC)(D)}}},62560:function(_,O,d){d.r(O),d.d(O,{ZcashTools:function(){return B},makeCurrencyEngine:function(){return z},makeCurrencyTools:function(){return K}});var w=d(77591),A=d(2153),R=d(48764),x=d(62177),N=d(79014),M=d(76714),h=d(82448);const U=(0,h.su)({first:h.mH,last:h.mH}),L=(0,h.su)({alias:(0,h.Vk)(h.XC),blockRange:(0,h.Vk)(U,()=>({first:0,last:0}))}),$=(0,h.su)({birthdayHeight:h.mH,publicKey:h.XC,unifiedViewingKeys:(0,h.su)({extfvk:h.XC,extpub:h.XC})}),P=(0,x.jd)($),S=s=>{const t=(0,h.su)({[`${s}Mnemonic`]:h.XC,[`${s}SpendKey`]:h.XC,[`${s}BirthdayHeight`]:h.mH});return(0,h.W1)(e=>{const n=t(e);return{mnemonic:n[`${s}Mnemonic`],spendKey:n[`${s}SpendKey`],birthdayHeight:n[`${s}BirthdayHeight`]}},e=>({[`${s}Mnemonic`]:e.mnemonic,[`${s}SpendKey`]:e.spendKey,[`${s}BirthdayHeight`]:e.birthdayHeight}))};var b=d(94935),V=d(84650),a=Object.defineProperty,y=Object.getOwnPropertySymbols,f=Object.getPrototypeOf,g=Object.prototype.hasOwnProperty,D=Object.prototype.propertyIsEnumerable,u=Reflect.get,T=(s,t,e)=>t in s?a(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,W=(s,t)=>{for(var e in t||(t={}))g.call(t,e)&&T(s,e,t[e]);if(y)for(var e of y(t))D.call(t,e)&&T(s,e,t[e]);return s},k=(s,t,e)=>u(f(s),e,t),p=(s,t,e)=>new Promise((n,r)=>{var c=i=>{try{l(e.next(i))}catch(v){r(v)}},o=i=>{try{l(e.throw(i))}catch(v){r(v)}},l=i=>i.done?n(i.value):Promise.resolve(i.value).then(c,o);l((e=e.apply(s,t)).next())});class I extends V.P{constructor(t,e,n,r,c){super(t,e,n,r);const{networkInfo:o}=t;this.pluginId=this.currencyInfo.pluginId,this.networkInfo=o,this.makeSynchronizer=c,this.queryMutex=!1}setOtherData(t){this.otherData=L(t)}initData(){const{birthdayHeight:t,alias:e}=this.initializer;this.otherData.blockRange.first===0&&(this.otherData.blockRange={first:t,last:t}),this.alias=e,this.initialNumBlocksToDownload=-1,this.synchronizerStatus="DISCONNECTED",this.availableZatoshi="0",this.progressRatio=0}initSubscriptions(){this.synchronizer.on("update",t=>p(this,null,function*(){const{lastDownloadedHeight:e,scanProgress:n,networkBlockHeight:r}=t;this.onUpdateBlockHeight(r),this.onUpdateProgress(e,n,r),yield this.queryAll()})),this.synchronizer.on("statusChanged",t=>p(this,null,function*(){this.synchronizerStatus=t.name,yield this.queryAll()}))}queryAll(){return p(this,null,function*(){if(!this.queryMutex){this.queryMutex=!0;try{yield this.queryBalance(),yield this.queryTransactions(),this.onUpdateTransactions()}catch{}this.queryMutex=!1}})}onUpdateBlockHeight(t){this.walletLocalData.blockHeight!==t&&(this.walletLocalData.blockHeight=t,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight))}onUpdateTransactions(){this.transactionsChangedArray.length>0&&(this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[])}onUpdateProgress(t,e,n){if(!this.addressesChecked&&!this.isSynced()){this.tokenCheckBalanceStatus[this.currencyInfo.currencyCode]=e*.99/100;let r=0;if(t>0){const o=n-t;this.initialNumBlocksToDownload<0&&(this.initialNumBlocksToDownload=o),r=o===0||this.initialNumBlocksToDownload===0?1:1-o/this.initialNumBlocksToDownload}this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=r*.8;const c=(this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]+this.tokenCheckBalanceStatus[this.currencyInfo.currencyCode])/2;c!==this.progressRatio&&(Math.abs(c-this.progressRatio)>.1||c===1)&&(this.progressRatio=c,this.updateOnAddressesChecked())}}startEngine(){return p(this,null,function*(){this.initData(),this.synchronizer=yield this.makeSynchronizer(this.initializer),yield this.synchronizer.start(),this.initSubscriptions(),yield k(I.prototype,this,"startEngine").call(this)})}isSynced(){return this.synchronizerStatus==="SYNCED"}queryBalance(){return p(this,null,function*(){if(!!this.isSynced())try{const t=yield this.synchronizer.getShieldedBalance();if(t.totalZatoshi==="-1")return;this.availableZatoshi=t.availableZatoshi,this.updateBalance(this.currencyInfo.currencyCode,t.totalZatoshi)}catch(t){this.warn("Failed to update balances",t),this.updateBalance(this.currencyInfo.currencyCode,"0")}})}queryTransactions(){return p(this,null,function*(){try{let t=this.otherData.blockRange.first,e=this.otherData.blockRange.last;for(;this.isSynced()&&e<=this.walletLocalData.blockHeight;){if((yield this.synchronizer.getTransactions({first:t,last:e})).forEach(r=>this.processTransaction(r)),e===this.walletLocalData.blockHeight){t=this.walletLocalData.blockHeight,this.walletLocalDataDirty=!0,this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=1,this.updateOnAddressesChecked();break}t=e+1,e=e+this.networkInfo.transactionQueryLimit<this.walletLocalData.blockHeight?e+this.networkInfo.transactionQueryLimit:this.walletLocalData.blockHeight,this.otherData.blockRange={first:t,last:e},this.walletLocalDataDirty=!0}}catch(t){this.error(`Error querying ${this.currencyInfo.currencyCode} transactions `,t)}})}processTransaction(t){let e=t.value;const n=[];t.toAddress!=null?e=`-${(0,w.add)(e,this.networkInfo.defaultNetworkFee)}`:n.push(this.walletInfo.keys.publicKey);const r={txid:t.rawTransactionId,date:t.blockTimeInSeconds,currencyCode:this.currencyInfo.currencyCode,blockHeight:t.minedHeight,nativeAmount:e,isSend:e.startsWith("-"),networkFee:this.networkInfo.defaultNetworkFee,ourReceiveAddresses:n,signedTx:"",otherParams:{},walletId:this.walletId};this.addTransaction(this.currencyInfo.currencyCode,r)}killEngine(){return p(this,null,function*(){yield this.synchronizer.stop(),yield k(I.prototype,this,"killEngine").call(this)})}clearBlockchainCache(){return p(this,null,function*(){yield k(I.prototype,this,"clearBlockchainCache").call(this)})}resyncBlockchain(){return p(this,null,function*(){yield k(I.prototype,this,"killEngine").call(this),yield this.clearBlockchainCache(),yield this.startEngine(),this.synchronizer.rescan(this.walletInfo.keys.birthdayHeight).catch(t=>this.warn("resyncBlockchain failed: ",t))})}getMaxSpendable(){return p(this,null,function*(){const t=(0,w.sub)(this.availableZatoshi,this.networkInfo.defaultNetworkFee);if((0,w.lte)(t,"0"))throw new b.C_;return t})}makeSpend(t){return p(this,null,function*(){var e;if(!this.isSynced())throw new Error("Cannot spend until wallet is synced");const{edgeSpendInfo:n,currencyCode:r}=this.makeSpendCheck(t),c=n.spendTargets[0],{publicAddress:o,nativeAmount:l}=c;if(o==null)throw new Error("makeSpend Missing publicAddress");if(l==null)throw new b.$D;if((0,w.eq)(l,"0"))throw new b.$D;const i=(0,w.add)(l,this.networkInfo.defaultNetworkFee);if((0,w.gt)(i,(e=this.walletLocalData.totalBalances[this.currencyInfo.currencyCode])!=null?e:"0"))throw new b.C_;if((0,w.gt)(i,this.availableZatoshi))throw new b.C_("Amount exceeds available balance");const v=n.spendTargets.map(C=>{var H;return{uniqueIdentifier:C.uniqueIdentifier,memo:C.memo,nativeAmount:(H=C.nativeAmount)!=null?H:"0",currencyCode:r,publicAddress:o}});return{txid:"",date:0,currencyCode:r,blockHeight:0,nativeAmount:`-${i}`,isSend:l.startsWith("-"),networkFee:this.networkInfo.defaultNetworkFee,ourReceiveAddresses:[],signedTx:"",spendTargets:v,walletId:this.walletId}})}signTx(t){return p(this,null,function*(){return t})}broadcastTx(t,e){return p(this,null,function*(){var n,r;const c=S(this.pluginId)(e==null?void 0:e.privateKeys);if(t.spendTargets==null||t.spendTargets.length!==1)throw new Error("Invalid spend targets");const o=t.spendTargets[0],l={zatoshi:(0,w.sub)((0,w.abs)(t.nativeAmount),t.networkFee),toAddress:o.publicAddress,memo:(r=(n=o.memo)!=null?n:o.uniqueIdentifier)!=null?r:"",fromAccountIndex:0,spendingKey:c.spendKey};try{const i=yield this.synchronizer.sendToAddress(l);t.txid=i.txId,t.signedTx=i.raw,t.date=Date.now()/1e3,this.warn(`SUCCESS broadcastTx
2
- ${(0,M.oX)(t)}`)}catch(i){throw this.warn("FAILURE broadcastTx failed: ",i),i}return t})}loadEngine(){return p(this,null,function*(){const{walletInfo:t}=this;yield k(I.prototype,this,"loadEngine").call(this),this.engineOn=!0;const{rpcNode:e}=this.networkInfo;this.initializer=W({fullViewingKey:t.keys.unifiedViewingKeys,birthdayHeight:t.keys.birthdayHeight,alias:t.keys.publicKey},e)})}}function z(s,t,e,n){return p(this,null,function*(){const r=P(e),{makeSynchronizer:c}=s.nativeIo["edge-currency-accountbased"][s.networkInfo.nativeSdk],o=new I(s,t,r,n,c);return yield o.loadEngine(),o})}var m=(s,t,e)=>new Promise((n,r)=>{var c=i=>{try{l(e.next(i))}catch(v){r(v)}},o=i=>{try{l(e.throw(i))}catch(v){r(v)}},l=i=>i.done?n(i.value):Promise.resolve(i.value).then(c,o);l((e=e.apply(s,t)).next())});class B{constructor(t){const{builtinTokens:e,currencyInfo:n,io:r,networkInfo:c}=t;this.builtinTokens=e,this.currencyInfo=n,this.io=r,this.networkInfo=c;const o=t.nativeIo["edge-currency-accountbased"];if(o==null)throw new Error("Need opts");const{KeyTool:l,AddressTool:i}=o[this.networkInfo.nativeSdk];this.KeyTool=l,this.AddressTool=i}getDisplayPrivateKey(t){return m(this,null,function*(){const{pluginId:e}=this.currencyInfo;return S(e)(t.keys).mnemonic})}getDisplayPublicKey(t){return m(this,null,function*(){var e;const{keys:n}=P(t);return(e=n.unifiedViewingKeys)==null?void 0:e.extfvk})}getNewWalletBirthdayBlockheight(){return m(this,null,function*(){try{return yield this.KeyTool.getBirthdayHeight(this.networkInfo.rpcNode.defaultHost,this.networkInfo.rpcNode.defaultPort)}catch{return this.networkInfo.defaultBirthday}})}isValidAddress(t){return m(this,null,function*(){return(yield this.AddressTool.isValidShieldedAddress(t))||(yield this.AddressTool.isValidTransparentAddress(t))})}importPrivateKey(t){return m(this,arguments,function*(e,n={}){const{pluginId:r}=this.currencyInfo;if(!(0,A.validateMnemonic)(e))throw new Error(`Invalid ${this.currencyInfo.currencyCode} mnemonic`);const l=(yield(0,A.mnemonicToSeed)(e)).toString("hex"),i=yield this.KeyTool.deriveSpendingKey(l,this.networkInfo.rpcNode.networkName);if(typeof i!="string")throw new Error("Invalid spendKey type");const v=yield this.getNewWalletBirthdayBlockheight();let E=v;const{birthdayHeight:C}=n;if(C!=null){(0,x.jD)(C);const H=parseInt(C);if(H>v)throw new Error("InvalidBirthdayHeight");E=H}return{[`${r}Mnemonic`]:e,[`${r}SpendKey`]:i,[`${r}BirthdayHeight`]:E}})}createPrivateKey(t){return m(this,null,function*(){if(t!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const e=R.Buffer.from(this.io.random(32)).toString("hex"),n=(0,A.entropyToMnemonic)(e);return yield this.importPrivateKey(n)})}checkPublicKey(t){return m(this,null,function*(){try{return $(t),!0}catch{return!1}})}derivePublicKey(t){return m(this,null,function*(){const{pluginId:e}=this.currencyInfo,n=S(e)(t.keys);if(t.type!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const r=n.mnemonic;if(typeof r!="string")throw new Error("InvalidMnemonic");const o=(yield(0,A.mnemonicToSeed)(r)).toString("hex"),l=yield this.KeyTool.deriveViewingKey(o,this.networkInfo.rpcNode.networkName),i=yield this.AddressTool.deriveShieldedAddress(l.extfvk,this.networkInfo.rpcNode.networkName);return{birthdayHeight:n.birthdayHeight,publicKey:i,unifiedViewingKeys:l}})}parseUri(t,e,n){return m(this,null,function*(){const{pluginId:r}=this.currencyInfo,c={[r]:!0},{edgeParsedUri:o,edgeParsedUri:{publicAddress:l}}=(0,N.k)(this.currencyInfo,t,c,e!=null?e:this.currencyInfo.currencyCode,n);if(l==null||!(yield this.isValidAddress(l)))throw new Error("InvalidPublicAddressError");return o})}encodeUri(t){return m(this,arguments,function*(e,n=[]){const{pluginId:r}=this.currencyInfo,{nativeAmount:c,currencyCode:o,publicAddress:l}=e;if(!(yield this.isValidAddress(l)))throw new Error("InvalidPublicAddressError");let i;if(c!=null){const E=(0,M.Qs)(o!=null?o:this.currencyInfo.currencyCode,this.currencyInfo,n);if(E==null)throw new Error("InternalErrorInvalidCurrencyCode");i=(0,w.div)(c,E.multiplier,18)}return(0,N.Q)(e,`${r}`,i)})}}function K(s){return m(this,null,function*(){return new B(s)})}}}]);
1
+ "use strict";(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[159],{79014:function(F,H,d){d.d(H,{Q:function(){return V},k:function(){return b}});var g=d(77591),A=d.n(g),$=d(24350),O=d(84564),x=d.n(O),N=d(76714),h=Object.defineProperty,M=Object.getOwnPropertySymbols,L=Object.prototype.hasOwnProperty,U=Object.prototype.propertyIsEnumerable,P=(a,y,f)=>y in a?h(a,y,{enumerable:!0,configurable:!0,writable:!0,value:f}):a[y]=f,S=(a,y)=>{for(var f in y||(y={}))L.call(y,f)&&P(a,f,y[f]);if(M)for(var f of M(y))U.call(y,f)&&P(a,f,y[f]);return a};function b(a,y,f,m,D=[]){const u=S({},x()(y,{},!0)),T=y.startsWith(`${a.pluginId}://`);if(u.protocol!=null&&(u.protocol=u.protocol.replace(":","")),u.protocol!=null&&u.protocol!==""&&!f[u.protocol])throw new Error(`Uri protocol '${u.protocol}' is not supported for ${a.pluginId}.`);if(u.host===""&&u.pathname==="")throw new Error("Path and host not found in uri.");const k={publicAddress:u.host!==""?u.host:u.pathname.split("/")[0]},p=u.query.label,I=u.query.message,z=u.query.category;(p!=null||I!=null||z!=null||T)&&(k.metadata={},k.metadata.name=p,k.metadata.notes=I,k.metadata.category=z,k.metadata.gateway=T!=null?T:!1);const w=u.query.amount;if(w!=null&&typeof w=="string"){m==null&&(m=a.currencyCode);const B=(0,N.Qs)(m!=null?m:"",a,D);if(B==null)throw new Error("InternalErrorInvalidCurrencyCode");let K=(0,g.mul)(w,B.multiplier);K=(0,g.toFixed)(K,0,0),k.nativeAmount=K,k.currencyCode=m}return{edgeParsedUri:k,parsedUri:u}}function V(a,y,f){if(a.publicAddress==null)throw new Error("InvalidPublicAddressError");if(f==null&&a.label==null&&a.message==null)return a.publicAddress;{let m="";f!=null&&(m+="amount="+f+"&"),(a.label!=null||a.message!=null)&&(typeof a.label=="string"&&(m+="label="+a.label+"&"),typeof a.message=="string"&&(m+="message="+a.message+"&")),m=m.substr(0,m.length-1);const D={scheme:y,path:a.publicAddress,query:m};return(0,$.qC)(D)}}},62560:function(F,H,d){d.r(H),d.d(H,{ZcashTools:function(){return B},makeCurrencyEngine:function(){return z},makeCurrencyTools:function(){return K}});var g=d(77591),A=d(2153),$=d(48764),O=d(62177),x=d(79014),N=d(76714),h=d(82448);const M=(0,h.su)({first:h.mH,last:h.mH}),L=(0,h.su)({alias:(0,h.Vk)(h.XC),blockRange:(0,h.Vk)(M,()=>({first:0,last:0}))}),U=(0,h.su)({birthdayHeight:h.mH,publicKey:h.XC,unifiedViewingKeys:(0,h.su)({extfvk:h.XC,extpub:h.XC})}),P=(0,O.jd)(U),S=s=>{const t=(0,h.su)({[`${s}Mnemonic`]:h.XC,[`${s}SpendKey`]:h.XC,[`${s}BirthdayHeight`]:h.mH});return(0,h.W1)(e=>{const n=t(e);return{mnemonic:n[`${s}Mnemonic`],spendKey:n[`${s}SpendKey`],birthdayHeight:n[`${s}BirthdayHeight`]}},e=>({[`${s}Mnemonic`]:e.mnemonic,[`${s}SpendKey`]:e.spendKey,[`${s}BirthdayHeight`]:e.birthdayHeight}))};var b=d(94935),V=d(84650),a=Object.defineProperty,y=Object.getOwnPropertySymbols,f=Object.getPrototypeOf,m=Object.prototype.hasOwnProperty,D=Object.prototype.propertyIsEnumerable,u=Reflect.get,T=(s,t,e)=>t in s?a(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,_=(s,t)=>{for(var e in t||(t={}))m.call(t,e)&&T(s,e,t[e]);if(y)for(var e of y(t))D.call(t,e)&&T(s,e,t[e]);return s},k=(s,t,e)=>u(f(s),e,t),p=(s,t,e)=>new Promise((n,r)=>{var l=i=>{try{c(e.next(i))}catch(v){r(v)}},o=i=>{try{c(e.throw(i))}catch(v){r(v)}},c=i=>i.done?n(i.value):Promise.resolve(i.value).then(l,o);c((e=e.apply(s,t)).next())});class I extends V.P{constructor(t,e,n,r,l){super(t,e,n,r);const{networkInfo:o}=t;this.pluginId=this.currencyInfo.pluginId,this.networkInfo=o,this.makeSynchronizer=l,this.queryMutex=!1}setOtherData(t){this.otherData=L(t)}initData(){const{birthdayHeight:t,alias:e}=this.initializer;this.otherData.blockRange.first===0&&(this.otherData.blockRange={first:t,last:t}),this.alias=e,this.initialNumBlocksToDownload=-1,this.synchronizerStatus="DISCONNECTED",this.availableZatoshi="0",this.progressRatio=0}initSubscriptions(){this.synchronizer.on("update",t=>p(this,null,function*(){const{lastDownloadedHeight:e,scanProgress:n,networkBlockHeight:r}=t;this.onUpdateBlockHeight(r),this.onUpdateProgress(e,n,r),yield this.queryAll()})),this.synchronizer.on("statusChanged",t=>p(this,null,function*(){this.synchronizerStatus=t.name,yield this.queryAll()}))}queryAll(){return p(this,null,function*(){if(!this.queryMutex){this.queryMutex=!0;try{yield this.queryBalance(),yield this.queryTransactions(),this.onUpdateTransactions()}catch{}this.queryMutex=!1}})}onUpdateBlockHeight(t){this.walletLocalData.blockHeight!==t&&(this.walletLocalData.blockHeight=t,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight))}onUpdateTransactions(){this.transactionsChangedArray.length>0&&(this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[])}onUpdateProgress(t,e,n){if(!this.addressesChecked&&!this.isSynced()){this.tokenCheckBalanceStatus[this.currencyInfo.currencyCode]=e*.99/100;let r=0;if(t>0){const o=n-t;this.initialNumBlocksToDownload<0&&(this.initialNumBlocksToDownload=o),r=o===0||this.initialNumBlocksToDownload===0?1:1-o/this.initialNumBlocksToDownload}this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=r*.8;const l=(this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]+this.tokenCheckBalanceStatus[this.currencyInfo.currencyCode])/2;l!==this.progressRatio&&(Math.abs(l-this.progressRatio)>.1||l===1)&&(this.progressRatio=l,this.updateOnAddressesChecked())}}startEngine(){return p(this,null,function*(){this.initData(),this.synchronizer=yield this.makeSynchronizer(this.initializer),yield this.synchronizer.start(),this.initSubscriptions(),yield k(I.prototype,this,"startEngine").call(this)})}isSynced(){return this.synchronizerStatus==="SYNCED"}queryBalance(){return p(this,null,function*(){if(!!this.isSynced())try{const t=yield this.synchronizer.getShieldedBalance();if(t.totalZatoshi==="-1")return;this.availableZatoshi=t.availableZatoshi,this.updateBalance(this.currencyInfo.currencyCode,t.totalZatoshi)}catch(t){this.warn("Failed to update balances",t),this.updateBalance(this.currencyInfo.currencyCode,"0")}})}queryTransactions(){return p(this,null,function*(){try{let t=this.otherData.blockRange.first,e=this.otherData.blockRange.last;for(;this.isSynced()&&e<=this.walletLocalData.blockHeight;){if((yield this.synchronizer.getTransactions({first:t,last:e})).forEach(r=>this.processTransaction(r)),e===this.walletLocalData.blockHeight){t=this.walletLocalData.blockHeight,this.walletLocalDataDirty=!0,this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=1,this.updateOnAddressesChecked();break}t=e+1,e=e+this.networkInfo.transactionQueryLimit<this.walletLocalData.blockHeight?e+this.networkInfo.transactionQueryLimit:this.walletLocalData.blockHeight,this.otherData.blockRange={first:t,last:e},this.walletLocalDataDirty=!0}}catch(t){this.error(`Error querying ${this.currencyInfo.currencyCode} transactions `,t)}})}processTransaction(t){let e=t.value;const n=[];t.toAddress!=null?e=`-${(0,g.add)(e,this.networkInfo.defaultNetworkFee)}`:n.push(this.walletInfo.keys.publicKey);const r={txid:t.rawTransactionId,date:t.blockTimeInSeconds,currencyCode:this.currencyInfo.currencyCode,blockHeight:t.minedHeight,nativeAmount:e,isSend:e.startsWith("-"),networkFee:this.networkInfo.defaultNetworkFee,ourReceiveAddresses:n,signedTx:"",otherParams:{},walletId:this.walletId};this.addTransaction(this.currencyInfo.currencyCode,r)}killEngine(){return p(this,null,function*(){yield this.synchronizer.stop(),yield k(I.prototype,this,"killEngine").call(this)})}clearBlockchainCache(){return p(this,null,function*(){yield k(I.prototype,this,"clearBlockchainCache").call(this)})}resyncBlockchain(){return p(this,null,function*(){yield k(I.prototype,this,"killEngine").call(this),yield this.clearBlockchainCache(),yield this.startEngine(),this.synchronizer.rescan(this.walletInfo.keys.birthdayHeight).catch(t=>this.warn("resyncBlockchain failed: ",t))})}getMaxSpendable(){return p(this,null,function*(){const t=(0,g.sub)(this.availableZatoshi,this.networkInfo.defaultNetworkFee);if((0,g.lte)(t,"0"))throw new b.C_;return t})}makeSpend(t){return p(this,null,function*(){var e;if(!this.isSynced())throw new Error("Cannot spend until wallet is synced");const{edgeSpendInfo:n,currencyCode:r}=this.makeSpendCheck(t),l=n.spendTargets[0],{publicAddress:o,nativeAmount:c}=l;if(o==null)throw new Error("makeSpend Missing publicAddress");if(c==null)throw new b.$D;if((0,g.eq)(c,"0"))throw new b.$D;const i=(0,g.add)(c,this.networkInfo.defaultNetworkFee);if((0,g.gt)(i,(e=this.walletLocalData.totalBalances[this.currencyInfo.currencyCode])!=null?e:"0"))throw new b.C_;if((0,g.gt)(i,this.availableZatoshi))throw new b.C_("Amount exceeds available balance");const v=n.spendTargets.map(E=>{var W;return{uniqueIdentifier:E.uniqueIdentifier,memo:E.memo,nativeAmount:(W=E.nativeAmount)!=null?W:"0",currencyCode:r,publicAddress:o}}),C=(0,g.mul)(i,"-1");return{txid:"",date:0,currencyCode:r,blockHeight:0,nativeAmount:C,isSend:!0,networkFee:this.networkInfo.defaultNetworkFee,ourReceiveAddresses:[],signedTx:"",spendTargets:v,walletId:this.walletId}})}signTx(t){return p(this,null,function*(){return t})}broadcastTx(t,e){return p(this,null,function*(){var n,r;const l=S(this.pluginId)(e==null?void 0:e.privateKeys);if(t.spendTargets==null||t.spendTargets.length!==1)throw new Error("Invalid spend targets");const o=t.spendTargets[0],c={zatoshi:(0,g.sub)((0,g.abs)(t.nativeAmount),t.networkFee),toAddress:o.publicAddress,memo:(r=(n=o.memo)!=null?n:o.uniqueIdentifier)!=null?r:"",fromAccountIndex:0,spendingKey:l.spendKey};try{const i=yield this.synchronizer.sendToAddress(c);t.txid=i.txId,t.signedTx=i.raw,t.date=Date.now()/1e3,this.warn(`SUCCESS broadcastTx
2
+ ${(0,N.oX)(t)}`)}catch(i){throw this.warn("FAILURE broadcastTx failed: ",i),i}return t})}loadEngine(){return p(this,null,function*(){const{walletInfo:t}=this;yield k(I.prototype,this,"loadEngine").call(this),this.engineOn=!0;const{rpcNode:e}=this.networkInfo;this.initializer=_({fullViewingKey:t.keys.unifiedViewingKeys,birthdayHeight:t.keys.birthdayHeight,alias:t.keys.publicKey},e)})}}function z(s,t,e,n){return p(this,null,function*(){const r=P(e),{makeSynchronizer:l}=s.nativeIo["edge-currency-accountbased"][s.networkInfo.nativeSdk],o=new I(s,t,r,n,l);return yield o.loadEngine(),o})}var w=(s,t,e)=>new Promise((n,r)=>{var l=i=>{try{c(e.next(i))}catch(v){r(v)}},o=i=>{try{c(e.throw(i))}catch(v){r(v)}},c=i=>i.done?n(i.value):Promise.resolve(i.value).then(l,o);c((e=e.apply(s,t)).next())});class B{constructor(t){const{builtinTokens:e,currencyInfo:n,io:r,networkInfo:l}=t;this.builtinTokens=e,this.currencyInfo=n,this.io=r,this.networkInfo=l;const o=t.nativeIo["edge-currency-accountbased"];if(o==null)throw new Error("Need opts");const{KeyTool:c,AddressTool:i}=o[this.networkInfo.nativeSdk];this.KeyTool=c,this.AddressTool=i}getDisplayPrivateKey(t){return w(this,null,function*(){const{pluginId:e}=this.currencyInfo;return S(e)(t.keys).mnemonic})}getDisplayPublicKey(t){return w(this,null,function*(){var e;const{keys:n}=P(t);return(e=n.unifiedViewingKeys)==null?void 0:e.extfvk})}getNewWalletBirthdayBlockheight(){return w(this,null,function*(){try{return yield this.KeyTool.getBirthdayHeight(this.networkInfo.rpcNode.defaultHost,this.networkInfo.rpcNode.defaultPort)}catch{return this.networkInfo.defaultBirthday}})}isValidAddress(t){return w(this,null,function*(){return(yield this.AddressTool.isValidShieldedAddress(t))||(yield this.AddressTool.isValidTransparentAddress(t))})}importPrivateKey(t){return w(this,arguments,function*(e,n={}){const{pluginId:r}=this.currencyInfo;if(!(0,A.validateMnemonic)(e))throw new Error(`Invalid ${this.currencyInfo.currencyCode} mnemonic`);const c=(yield(0,A.mnemonicToSeed)(e)).toString("hex"),i=yield this.KeyTool.deriveSpendingKey(c,this.networkInfo.rpcNode.networkName);if(typeof i!="string")throw new Error("Invalid spendKey type");const v=yield this.getNewWalletBirthdayBlockheight();let C=v;const{birthdayHeight:R}=n;if(R!=null){(0,O.jD)(R);const E=parseInt(R);if(E>v)throw new Error("InvalidBirthdayHeight");C=E}return{[`${r}Mnemonic`]:e,[`${r}SpendKey`]:i,[`${r}BirthdayHeight`]:C}})}createPrivateKey(t){return w(this,null,function*(){if(t!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const e=$.Buffer.from(this.io.random(32)).toString("hex"),n=(0,A.entropyToMnemonic)(e);return yield this.importPrivateKey(n)})}checkPublicKey(t){return w(this,null,function*(){try{return U(t),!0}catch{return!1}})}derivePublicKey(t){return w(this,null,function*(){const{pluginId:e}=this.currencyInfo,n=S(e)(t.keys);if(t.type!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const r=n.mnemonic;if(typeof r!="string")throw new Error("InvalidMnemonic");const o=(yield(0,A.mnemonicToSeed)(r)).toString("hex"),c=yield this.KeyTool.deriveViewingKey(o,this.networkInfo.rpcNode.networkName),i=yield this.AddressTool.deriveShieldedAddress(c.extfvk,this.networkInfo.rpcNode.networkName);return{birthdayHeight:n.birthdayHeight,publicKey:i,unifiedViewingKeys:c}})}parseUri(t,e,n){return w(this,null,function*(){const{pluginId:r}=this.currencyInfo,l={[r]:!0},{edgeParsedUri:o,edgeParsedUri:{publicAddress:c}}=(0,x.k)(this.currencyInfo,t,l,e!=null?e:this.currencyInfo.currencyCode,n);if(c==null||!(yield this.isValidAddress(c)))throw new Error("InvalidPublicAddressError");return o})}encodeUri(t){return w(this,arguments,function*(e,n=[]){const{pluginId:r}=this.currencyInfo,{nativeAmount:l,currencyCode:o,publicAddress:c}=e;if(!(yield this.isValidAddress(c)))throw new Error("InvalidPublicAddressError");let i;if(l!=null){const C=(0,N.Qs)(o!=null?o:this.currencyInfo.currencyCode,this.currencyInfo,n);if(C==null)throw new Error("InternalErrorInvalidCurrencyCode");i=(0,g.div)(l,C.multiplier,18)}return(0,x.Q)(e,`${r}`,i)})}}function K(s){return w(this,null,function*(){return new B(s)})}}}]);
@@ -118,6 +118,14 @@ const builtinTokens = {
118
118
  contractAddress: '0xA7D7079b0FEaD91F3e65f86E8915Cb59c1a4C664'
119
119
  }
120
120
  },
121
+ '9702230a8ea53601f5cd2dc00fdbc13d4df4a8c7': {
122
+ currencyCode: 'USDT',
123
+ displayName: 'Tether USD',
124
+ denominations: [{ name: 'USDT', multiplier: '1000000' }],
125
+ networkLocation: {
126
+ contractAddress: '0x9702230A8Ea53601f5cD2dc00fDBc13d4dF4A8c7'
127
+ }
128
+ },
121
129
  c7198437980c041c805a1edcba50c1ce5db95118: {
122
130
  currencyCode: 'USDT.e',
123
131
  displayName: 'Tether USD',
@@ -934,6 +934,14 @@ const builtinTokens = {
934
934
  contractAddress: '0x3a4f40631a4f906c2BaD353Ed06De7A5D3fCb430'
935
935
  }
936
936
  },
937
+ e17b8adf8e46b15f3f9ab4bb9e3b6e31db09126e: {
938
+ currencyCode: 'PYUSD',
939
+ displayName: 'PayPal USD',
940
+ denominations: [{ name: 'PYUSD', multiplier: '1000000' }],
941
+ networkLocation: {
942
+ contractAddress: '0xe17b8aDF8E46b15f3F9aB4Bb9E3b6e31Db09126E'
943
+ }
944
+ },
937
945
  '4a220e6096b25eadb88358cb44068a3248254675': {
938
946
  currencyCode: 'QNT',
939
947
  displayName: 'Quant',
@@ -34,6 +34,7 @@ var _CurrencyEngine = require('../common/CurrencyEngine');
34
34
 
35
35
 
36
36
  var _filecoinTypes = require('./filecoinTypes');
37
+ var _Filfox = require('./Filfox');
37
38
  var _Filscan = require('./Filscan');
38
39
  var _RpcExtra = require('./RpcExtra');
39
40
 
@@ -50,11 +51,13 @@ const CHECK_TRANSACTION_INTERVAL = 15000
50
51
 
51
52
 
52
53
 
54
+
53
55
 
54
56
  // Backends:
55
57
 
56
58
 
57
59
 
60
+
58
61
 
59
62
  constructor(
60
63
  env,
@@ -62,19 +65,21 @@ const CHECK_TRANSACTION_INTERVAL = 15000
62
65
  walletInfo,
63
66
  opts
64
67
  ) {
65
- super(env, tools, walletInfo, opts)
68
+ super(env, tools, walletInfo, opts);FilecoinEngine.prototype.__init.call(this);
66
69
  const { networkInfo } = env
67
70
  this.address = _izarifilecoin.Address.fromString(walletInfo.keys.address)
68
71
  this.availableAttoFil = '0'
72
+ this.isScanning = false
73
+ this.networkInfo = networkInfo
74
+ this.pluginId = this.currencyInfo.pluginId
75
+
69
76
  this.filRpc = new (0, _izarifilecoin.RPC)(env.networkInfo.rpcNode.networkName, {
70
77
  url: env.networkInfo.rpcNode.url,
71
78
  token: env.currencyInfo.currencyCode
72
79
  })
80
+ this.filfoxApi = new (0, _Filfox.Filfox)(env.networkInfo.filfoxUrl, env.io.fetchCors)
73
81
  this.filscanApi = new (0, _Filscan.Filscan)(env.networkInfo.filscanUrl, env.io.fetchCors)
74
82
  this.rpcExtra = new (0, _RpcExtra.RpcExtra)(env.networkInfo.rpcNode.url, env.io.fetchCors)
75
-
76
- this.networkInfo = networkInfo
77
- this.pluginId = this.currencyInfo.pluginId
78
83
  }
79
84
 
80
85
  setOtherData(raw) {
@@ -82,9 +87,7 @@ const CHECK_TRANSACTION_INTERVAL = 15000
82
87
  }
83
88
 
84
89
  initData() {
85
- // Initialize walletLocalData:
86
- // ...
87
-
90
+ this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode] = 0
88
91
  // Engine variables
89
92
  this.availableAttoFil = '0'
90
93
  }
@@ -186,15 +189,15 @@ const CHECK_TRANSACTION_INTERVAL = 15000
186
189
  }
187
190
 
188
191
  const networkFee = _biggystring.mul.call(void 0, txJson.GasLimit.toString(), txJson.GasPremium) // TODO: Include base fee and burn fee somehow?
189
- const totalTxAmount = _biggystring.add.call(void 0, nativeAmount, networkFee)
192
+ const txNativeAmount = _biggystring.mul.call(void 0, _biggystring.add.call(void 0, nativeAmount, networkFee), '-1')
190
193
 
191
194
  const edgeTransaction = {
192
195
  txid: '',
193
196
  date: 0,
194
197
  currencyCode,
195
198
  blockHeight: 0,
196
- nativeAmount: `-${totalTxAmount}`,
197
- isSend: nativeAmount.startsWith('-'),
199
+ nativeAmount: txNativeAmount,
200
+ isSend: true,
198
201
  networkFee,
199
202
  ourReceiveAddresses: [],
200
203
  otherParams,
@@ -227,6 +230,8 @@ const CHECK_TRANSACTION_INTERVAL = 15000
227
230
  sigJson: signature.toJSON()
228
231
  }
229
232
 
233
+ edgeTransaction.date = Date.now() / 1000
234
+
230
235
  return edgeTransaction
231
236
  }
232
237
 
@@ -294,52 +299,212 @@ const CHECK_TRANSACTION_INTERVAL = 15000
294
299
  }
295
300
 
296
301
  async checkTransactions() {
297
- const addressString = this.address.toString()
302
+ // We shouldn't start scanning if scanning is already happening:
303
+ if (this.isScanning) return
304
+ try {
305
+ this.isScanning = true
306
+
307
+ const addressString = this.address.toString()
308
+
309
+ const handleScanProgress = (progress) => {
310
+ const currentProgress =
311
+ this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]
312
+ const newProgress = progress
313
+
314
+ if (
315
+ // Only send event if we haven't completed sync
316
+ currentProgress < 1 &&
317
+ // Avoid thrashing
318
+ (newProgress >= 1 || newProgress > currentProgress * 1.1)
319
+ ) {
320
+ this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode] =
321
+ newProgress
322
+ this.updateOnAddressesChecked()
323
+ }
324
+ }
325
+
326
+ const handleScan = ({
327
+ tx,
328
+ progress
329
+ }
298
330
 
331
+
332
+ ) => {
333
+ this.addTransaction(this.currencyInfo.currencyCode, tx)
334
+ this.onUpdateTransactions()
335
+
336
+ // Progress the block-height if the message's height is greater than
337
+ // last poll for block-height.
338
+ if (this.walletLocalData.blockHeight < tx.blockHeight) {
339
+ this.onUpdateBlockHeight(tx.blockHeight)
340
+ }
341
+
342
+ handleScanProgress(progress)
343
+ }
344
+
345
+ const scanners = [
346
+ // this.scanTransactionsFromFilscan(addressString, handleScan),
347
+ this.scanTransactionsFromFilfox(addressString, handleScan)
348
+ ]
349
+
350
+ const startingNetworkHeight = this.walletLocalData.blockHeight
351
+
352
+ // Run scanners:
353
+ await Promise.all(scanners)
354
+
355
+ // Save the network height at the start of the scanning
356
+ this.walletLocalData.lastAddressQueryHeight = startingNetworkHeight
357
+ this.walletLocalDataDirty = true
358
+
359
+ // Make sure the sync progress is 100%
360
+ handleScanProgress(1)
361
+ } catch (error) {
362
+ console.error(error)
363
+ throw error
364
+ } finally {
365
+ this.isScanning = false
366
+ }
367
+ }
368
+
369
+ async scanTransactionsFromFilfox(
370
+ address,
371
+ onScan
372
+ ) {
299
373
  const messagesPerPage = 20
300
374
  let index = 0
301
375
  let messagesChecked = 0
302
- let messageCount = 0
376
+ let messageCount = -1
303
377
  do {
304
- const messagesResponse = await this.filscanApi.getAccountMessages(
305
- addressString,
378
+ const messagesResponse = await this.filfoxApi.getAccountMessages(
379
+ address,
306
380
  index++,
307
381
  messagesPerPage
308
382
  )
309
- const messages = messagesResponse.result.messages_by_account_id_list
310
383
 
311
- for (const message of messages) {
312
- const txid = message.cid
313
- const idx = this.findTransaction(this.currencyInfo.currencyCode, txid)
384
+ // Only update the message count on the first query because mutating this
385
+ // in-between pagination may cause infinite loops.
386
+ messageCount =
387
+ messageCount === -1 ? messagesResponse.totalCount : messageCount
314
388
 
315
- if (idx >= 0) {
316
- // Exit early because we reached transaction history from previous
317
- // check
318
- return
319
- }
389
+ const messages = messagesResponse.messages
390
+ for (const message of messages) {
391
+ // Exit when we reach a transaction we may already have saved
392
+ if (message.height < this.walletLocalData.lastAddressQueryHeight) return
320
393
 
321
394
  // Process message into a transaction
322
- this.processMessage(message)
395
+ const messageDetails = await this.filfoxApi.getMessageDetails(
396
+ message.cid
397
+ )
398
+ const tx = this.filfoxMessageToEdgeTransaction(messageDetails)
399
+
400
+ // Calculate the progress
401
+ const progress =
402
+ messageCount === 0 ? 1 : ++messagesChecked / messageCount
403
+
404
+ onScan({ tx, progress })
323
405
  }
406
+ } while (messagesChecked < messageCount)
407
+ }
324
408
 
325
- messageCount = messagesResponse.result.total_count
326
- messagesChecked += messages.length
327
- this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode] =
328
- messageCount === 0 ? 1 : messagesChecked / messageCount
329
- this.updateOnAddressesChecked()
409
+ async scanTransactionsFromFilscan(
410
+ address,
411
+ onScan
412
+ ) {
413
+ const messagesPerPage = 20
414
+ let index = 0
415
+ let messagesChecked = 0
416
+ let messageCount = -1
417
+ do {
418
+ const messagesResponse = await this.filscanApi.getAccountMessages(
419
+ address,
420
+ index++,
421
+ messagesPerPage
422
+ )
423
+
424
+ // Only update the message count on the first query because mutating this
425
+ // in-between pagination may cause infinite loops.
426
+ messageCount =
427
+ messageCount === -1 ? messagesResponse.total_count : messageCount
428
+
429
+ const messages = messagesResponse.messages_by_account_id_list
430
+ for (const message of messages) {
431
+ // Exit when we reach a transaction we may already have saved
432
+ if (message.height < this.walletLocalData.lastAddressQueryHeight) return
433
+
434
+ // Process message into a transaction
435
+ const tx = this.filscanMessageToEdgeTransaction(message)
436
+
437
+ // Calculate the progress
438
+ const progress =
439
+ messageCount === 0 ? 1 : ++messagesChecked / messageCount
440
+
441
+ onScan({ tx, progress })
442
+ }
330
443
  } while (messagesChecked < messageCount)
331
444
  }
332
445
 
333
- processMessage(message) {
446
+ __init() {this.filfoxMessageToEdgeTransaction = (
447
+ messageDetails
448
+ ) => {
449
+ const addressString = this.address.toString()
450
+ const ourReceiveAddresses = []
451
+
452
+ // Handle network fees:
453
+ const networkFee = messageDetails.transfers
454
+ .filter(
455
+ transfer =>
456
+ transfer.type === 'miner-fee' || transfer.type === 'burner-fee'
457
+ )
458
+ .reduce((sum, transfer) => _biggystring.add.call(void 0, sum, transfer.value), '0')
459
+
460
+ // Handle native amount:
461
+ let nativeAmount
462
+ if (messageDetails.from === addressString) {
463
+ // For spends, always include network fee
464
+ nativeAmount = `-${networkFee}`
465
+ if (messageDetails.to !== addressString) {
466
+ // For spends not to self, subtract tx value
467
+ nativeAmount = _biggystring.sub.call(void 0, nativeAmount, messageDetails.value)
468
+ }
469
+ } else {
470
+ // For receives nativeAMount is always positively the value
471
+ nativeAmount = messageDetails.value
472
+ ourReceiveAddresses.push(addressString)
473
+ }
474
+
475
+ const edgeTransaction = {
476
+ txid: messageDetails.cid,
477
+ date: messageDetails.timestamp,
478
+ currencyCode: this.currencyInfo.currencyCode,
479
+ blockHeight: messageDetails.height,
480
+ nativeAmount,
481
+ isSend: nativeAmount.startsWith('-'),
482
+ networkFee,
483
+ ourReceiveAddresses, // blank if you sent money otherwise array of addresses that are yours in this transaction
484
+ signedTx: '',
485
+ otherParams: {},
486
+ walletId: this.walletId
487
+ }
488
+
489
+ return edgeTransaction
490
+ }}
491
+
492
+ filscanMessageToEdgeTransaction(message) {
334
493
  const addressString = this.address.toString()
335
- let netNativeAmount = message.value
336
494
  const ourReceiveAddresses = []
337
495
 
338
496
  const networkFee = '0' // TODO: calculate transaction fee from onchain gas fields
339
- if (message.to !== addressString) {
340
- // check if tx is a spend
341
- netNativeAmount = `-${_biggystring.add.call(void 0, netNativeAmount, networkFee)}`
497
+ let nativeAmount
498
+ if (message.from === addressString) {
499
+ // For spends, always include network fee
500
+ nativeAmount = `-${networkFee}`
501
+ if (message.to !== addressString) {
502
+ // For spends not to self, subtract tx value
503
+ nativeAmount = _biggystring.sub.call(void 0, nativeAmount, message.value)
504
+ }
342
505
  } else {
506
+ // For receives nativeAMount is always positively the value
507
+ nativeAmount = message.value
343
508
  ourReceiveAddresses.push(addressString)
344
509
  }
345
510
 
@@ -348,22 +513,16 @@ const CHECK_TRANSACTION_INTERVAL = 15000
348
513
  date: message.block_time,
349
514
  currencyCode: this.currencyInfo.currencyCode,
350
515
  blockHeight: message.height,
351
- nativeAmount: netNativeAmount,
352
- isSend: netNativeAmount.startsWith('-'),
516
+ nativeAmount,
517
+ isSend: nativeAmount.startsWith('-'),
353
518
  networkFee,
354
519
  ourReceiveAddresses, // blank if you sent money otherwise array of addresses that are yours in this transaction
355
520
  signedTx: '',
356
521
  otherParams: {},
357
522
  walletId: this.walletId
358
523
  }
359
- this.addTransaction(this.currencyInfo.currencyCode, edgeTransaction)
360
- this.onUpdateTransactions()
361
524
 
362
- // Progress the block-height if the message's height is greater than
363
- // last poll for block-height.
364
- if (this.walletLocalData.blockHeight < message.height) {
365
- this.onUpdateBlockHeight(message.height)
366
- }
525
+ return edgeTransaction
367
526
  }
368
527
  } exports.FilecoinEngine = FilecoinEngine;
369
528
  async function makeCurrencyEngine(