edge-currency-accountbased 2.2.1 → 2.2.3

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(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,2 +1,2 @@
1
- "use strict";(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[591],{79014:function(et,M,f){f.d(M,{Q:function(){return _},k:function(){return Q}});var E=f(77591),j=f.n(E),W=f(24350),X=f(84564),a=f.n(X),L=f(76714),U=Object.defineProperty,S=Object.getOwnPropertySymbols,F=Object.prototype.hasOwnProperty,I=Object.prototype.propertyIsEnumerable,i=(h,m,g)=>m in h?U(h,m,{enumerable:!0,configurable:!0,writable:!0,value:g}):h[m]=g,V=(h,m)=>{for(var g in m||(m={}))F.call(m,g)&&i(h,g,m[g]);if(S)for(var g of S(m))I.call(m,g)&&i(h,g,m[g]);return h};function Q(h,m,g,k,T=[]){const p=V({},a()(m,{},!0)),O=m.startsWith(`${h.pluginId}://`);if(p.protocol!=null&&(p.protocol=p.protocol.replace(":","")),p.protocol!=null&&p.protocol!==""&&!g[p.protocol])throw new Error(`Uri protocol '${p.protocol}' is not supported for ${h.pluginId}.`);if(p.host===""&&p.pathname==="")throw new Error("Path and host not found in uri.");const C={publicAddress:p.host!==""?p.host:p.pathname.split("/")[0]},H=p.query.label,$=p.query.message,B=p.query.category;(H!=null||$!=null||B!=null||O)&&(C.metadata={},C.metadata.name=H,C.metadata.notes=$,C.metadata.category=B,C.metadata.gateway=O!=null?O:!1);const x=p.query.amount;if(x!=null&&typeof x=="string"){k==null&&(k=h.currencyCode);const R=(0,L.Qs)(k!=null?k:"",h,T);if(R==null)throw new Error("InternalErrorInvalidCurrencyCode");let D=(0,E.mul)(x,R.multiplier);D=(0,E.toFixed)(D,0,0),C.nativeAmount=D,C.currencyCode=k}return{edgeParsedUri:C,parsedUri:p}}function _(h,m,g){if(h.publicAddress==null)throw new Error("InvalidPublicAddressError");if(g==null&&h.label==null&&h.message==null)return h.publicAddress;{let k="";g!=null&&(k+="amount="+g+"&"),(h.label!=null||h.message!=null)&&(typeof h.label=="string"&&(k+="label="+h.label+"&"),typeof h.message=="string"&&(k+="message="+h.message+"&")),k=k.substr(0,k.length-1);const T={scheme:m,path:h.publicAddress,query:k};return(0,W.qC)(T)}}},34765:function(et,M,f){f.r(M),f.d(M,{PolkadotTools:function(){return tt},makeCurrencyEngine:function(){return at},makeCurrencyTools:function(){return ut}});var E=f(58170),j=f(21293),W=f(18534),X=f(23670),a=f(77591),L=f(2153),U=f(48764),S=f(20918),F=f(79014),I=f(76714),i=f(82448),V=f(62177);const Q=(0,i.Vk)((0,i.su)({balance:i.mH})),_=(0,i.su)({txCount:(0,i.Vk)(i.mH,0)}),h=(0,i.su)({code:i.mH,message:i.XC,data:(0,i.Zz)((0,i.su)(i.JC))}),m=(0,i.su)({from:i.XC,to:i.XC,success:i.jK,hash:i.XC,block_num:i.mH,block_timestamp:i.mH,module:i.XC,amount:i.XC,fee:i.XC}),g=(0,i.su)({count:i.mH,transfers:(0,i.Vk)((0,i._2)(m),()=>[])}),k=V.BQ,T=u=>{const t=(0,i.su)({[`${u}Mnemonic`]:(0,i.Zz)(i.XC),[`${u}Key`]:i.XC});return(0,i.W1)(e=>{const s=t(e);return{mnemonic:s[`${u}Mnemonic`],privateKey:s[`${u}Key`]}},e=>({[`${u}Mnemonic`]:e.mnemonic,[`${u}Key`]:e.privateKey}))};var p=f(94935),O=f(35620),z=f(84650),C=Object.defineProperty,H=Object.defineProperties,$=Object.getOwnPropertyDescriptors,B=Object.getOwnPropertySymbols,x=Object.getPrototypeOf,R=Object.prototype.hasOwnProperty,D=Object.prototype.propertyIsEnumerable,nt=Reflect.get,G=(u,t,e)=>t in u?C(u,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):u[t]=e,q=(u,t)=>{for(var e in t||(t={}))R.call(t,e)&&G(u,e,t[e]);if(B)for(var e of B(t))D.call(t,e)&&G(u,e,t[e]);return u},Y=(u,t)=>H(u,$(t)),J=(u,t,e)=>nt(x(u),e,t),w=(u,t,e)=>new Promise((s,n)=>{var r=o=>{try{d(e.next(o))}catch(l){n(l)}},c=o=>{try{d(e.throw(o))}catch(l){n(l)}},d=o=>o.done?s(o.value):Promise.resolve(o.value).then(r,c);d((e=e.apply(u,t)).next())});const rt=5e3,st=2e4,ot=3e3,it=(0,I.jT)();class N extends z.P{constructor(t,e,s,n){super(t,e,s,n),this.getRecipientBalance=r=>w(this,null,function*(){try{return(yield this.api.query.system.account(r)).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=_(t)}fetchSubscan(t,e){return w(this,null,function*(){if(this.networkInfo.subscanBaseUrl==null)throw new Error("Missing subscan url");const s={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(e)},n=yield this.fetchCors(this.networkInfo.subscanBaseUrl+t,s);if(!n.ok||n.status===429)throw new Error(`Subscan ${t} failed with ${n.status}`);const r=yield n.json();return h(r)})}queryBalance(){return w(this,null,function*(){const t=[[this.api.query.system.account,this.walletInfo.keys.publicKey]],e=[];for(const n of this.enabledTokenIds){const r=this.allTokensMap[n];if(r==null)continue;const c=(0,S.Oj)(r.networkLocation);c!=null&&(t.push([this.api.query.assets.account,[c.contractAddress,this.walletInfo.keys.publicKey]]),e.push(r))}(yield this.api.queryMulti(t,n=>{if(n.length===0)throw new Error("No balances returned");const r=n.shift();this.nonce=r.nonce.toNumber(),this.updateBalance(this.currencyInfo.currencyCode,r.data.free.toString());for(const[c,d]of n.entries()){const o=e[c],l=Q(d.toPrimitive());if(l==null){this.updateBalance(o.currencyCode,"0");return}this.updateBalance(o.currencyCode,l.balance.toString())}}))()})}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:s,success:n,hash:r,block_num:c,block_timestamp:d,module:o,amount:l,fee:y}=t;if(!n||o!=="balances")return;const P=(0,I.aL)(this.currencyInfo.currencyCode,this.currencyInfo,this.allTokensMap);if(P==null)return;const A=[];let v=(0,a.mul)(l,P.multiplier);e===this.walletInfo.keys.publicKey?v=`-${(0,a.add)(v,y)}`:A.push(s);const K={txid:r,date:d,currencyCode:this.currencyInfo.currencyCode,blockHeight:c,nativeAmount:v,isSend:v.startsWith("-"),networkFee:y,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 it(()=>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 s=0,n=[];try{const r=yield this.fetchSubscan("/scan/transfers",e),c=g(r.data);s=c.count,n=c.transfers}catch(r){if(r instanceof Error&&r.message.includes("Subscan /scan/transfers failed with 429")){this.log(r.message);continue}else throw r}if(s===this.otherData.txCount||(n.forEach(r=>{try{this.processPolkadotTransaction(m(r))}catch{const d=r!=null&&typeof r.hash=="string"?r.hash:"";this.warn(`Ignoring invalid transfer ${d}`)}}),this.otherData.txCount=t*this.networkInfo.subscanQueryLimit+n.length,this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=Math.min(1,s===0?1:this.otherData.txCount/s),this.updateOnAddressesChecked(),s===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",st).catch(()=>{}),this.addToLoop("queryBalance",rt).catch(()=>{}),this.addToLoop("queryTransactions",ot).catch(()=>{}),yield J(N.prototype,this,"startEngine").call(this)})}killEngine(){return w(this,null,function*(){yield J(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 l=[{publicAddress:t.spendTargets[0].publicAddress,nativeAmount:e}],y=Y(q({},t),{spendTargets:l});return yield this.makeSpend(y),e}const s=(0,a.sub)(e,this.api.consts.balances.existentialDeposit.toString()),n=[{publicAddress:t.spendTargets[0].publicAddress,nativeAmount:"0"}],r=Y(q({},t),{spendTargets:n}),d=(yield this.makeSpend(r)).networkFee,o=(l,y)=>{const P=(0,a.sub)(y,l);if((0,a.lte)(P,"1"))return l;const A=(0,a.add)(l,(0,a.div)(P,"2")),v=(0,I.X0)(A).replace("0x",""),K=v.length%2===1?`0${v}`:v,dt=(0,a.mul)((0,a.div)(K.length.toString(),"2"),this.networkInfo.lengthFeePerByte),ht=(0,a.add)((0,a.add)(dt,d),A);return(0,a.gt)(ht,s)?o(l,A):o(A,y)};return o("0",(0,a.add)(s,"1"))})}makeSpend(t){return w(this,null,function*(){const{edgeSpendInfo:e,currencyCode:s}=this.makeSpendCheck(t);if(e.spendTargets.length!==1)throw new Error("Error: only one output allowed");const{nativeAmount:n,publicAddress:r}=e.spendTargets[0];if(r==null)throw new Error("makeSpend Missing publicAddress");if(n==null)throw new p.$D;const c=this.getBalance({currencyCode:s});let d,o;if(e.tokenId==null){const P=(0,a.sub)(c,this.api.consts.balances.existentialDeposit.toString());if((0,a.gt)(n,P))throw new p.C_;const v=yield(yield this.api.tx.balances.transferKeepAlive(r,n)).paymentInfo(this.walletInfo.keys.publicKey);if(o=(0,a.sub)(v.partialFee.toString(),(0,a.mul)(this.networkInfo.lengthFeePerByte,this.networkInfo.partialFeeOffsetMultiplier)),d=(0,a.add)(n,o),(0,a.gt)(d,P))throw new p.C_}else{if((0,a.gt)(n,c))throw new p.C_;d=n;const A=yield(yield this.api.tx.assets.transfer(parseInt(e.tokenId),r,n)).paymentInfo(this.walletInfo.keys.publicKey);o=(0,a.sub)(A.partialFee.toString(),(0,a.mul)(this.networkInfo.lengthFeePerByte,this.networkInfo.partialFeeOffsetMultiplier));const v=this.getBalance({currencyCode:this.currencyInfo.currencyCode}),K=(0,a.sub)(v,this.api.consts.balances.existentialDeposit.toString());if((0,a.gt)(o,K))throw new p.C_({currencyCode:this.currencyInfo.currencyCode,networkFee:o})}const l={publicAddress:r};return{txid:"",date:0,currencyCode:s,blockHeight:0,nativeAmount:(0,a.mul)(d,"-1"),isSend:!0,networkFee:o,ourReceiveAddresses:[],signedTx:"",otherParams:l,walletId:this.walletId}})}signTx(t,e){return w(this,null,function*(){const s=T(this.currencyInfo.pluginId)(e),{publicAddress:n}=(0,I.Xp)(t);if(n==null)throw new Error("Missing publicAddress from makeSpend");const r=this.allTokens.find(y=>y.currencyCode===t.currencyCode);let c;if(r==null){const y=(0,a.abs)((0,a.add)(t.nativeAmount,t.networkFee));yield this.checkRecipientMinimumBalance(this.getRecipientBalance,y,n),c=yield this.api.tx.balances.transferKeepAlive(n,y)}else if(r.contractAddress!=null){const y=(0,a.abs)(t.nativeAmount);c=yield this.api.tx.assets.transfer(parseInt(r.contractAddress),n,y)}else throw new Error("Unrecognized asset");const d=this.api.createType("SignerPayload",{method:c,nonce:this.nonce,genesisHash:this.api.genesisHash,blockHash:this.api.genesisHash,runtimeVersion:this.api.runtimeVersion,version:this.api.extrinsicVersion}),o=this.api.createType("ExtrinsicPayload",d.toPayload(),{version:this.api.extrinsicVersion});if(this.keypair==null)if(this.keypair=new E.Y({ss58Format:0}),s.mnemonic!=null)this.keypair.addFromUri(s.mnemonic);else{const y=O.YU.parse(s.privateKey);this.keypair.addFromSeed(y)}const l=o.sign(this.keypair.getPair(this.walletInfo.keys.publicKey));return c.addSignature(this.walletInfo.keys.publicKey,l.signature,d.toPayload()),t.signedTx=c.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 at(u,t,e,s){return w(this,null,function*(){const n=k(e),r=new N(u,t,n,s);return yield r.loadEngine(),r})}var b=(u,t,e)=>new Promise((s,n)=>{var r=o=>{try{d(e.next(o))}catch(l){n(l)}},c=o=>{try{d(e.throw(o))}catch(l){n(l)}},d=o=>o.done?s(o.value):Promise.resolve(o.value).then(r,c);d((e=e.apply(u,t)).next())});const{ed25519PairFromSeed:ct,isAddress:Z,mnemonicToMiniSecret:lt}=X;class tt{constructor(t){const{builtinTokens:e,currencyInfo:s,io:n,networkInfo:r}=t;this.builtinTokens=e,this.currencyInfo=s,this.io=n,this.networkInfo=r,this.polkadotApiSubscribers=new Set}getDisplayPrivateKey(t){return b(this,null,function*(){var e;const{pluginId:s}=this.currencyInfo,n=T(s)(t.keys);return(e=n.mnemonic)!=null?e:n.privateKey})}getDisplayPublicKey(t){return b(this,null,function*(){const{keys:e}=k(t);return e.publicKey})}importPrivateKey(t){return b(this,null,function*(){const{pluginId:e}=this.currencyInfo;if((0,L.validateMnemonic)(t)){const s=lt(t),{secretKey:n}=ct(s);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)),s=(0,L.entropyToMnemonic)(e);return yield this.importPrivateKey(s)})}derivePublicKey(t){return b(this,null,function*(){const{pluginId:e}=this.currencyInfo;return{publicKey:new E.Y({ss58Format:0}).addFromUri(t.keys[`${e}Mnemonic`]).address}})}parseUri(t,e,s){return b(this,null,function*(){var n,r;const{pluginId:c}=this.currencyInfo,d={[c]:!0},{parsedUri:o,edgeParsedUri:l}=(0,F.k)(this.currencyInfo,t,d,e!=null?e:this.currencyInfo.currencyCode,s),y=(n=l.publicAddress)!=null?n:"";if(!Z(y))throw new Error("InvalidPublicAddressError");return l.uniqueIdentifier=(r=o.query.memo)!=null?r:void 0,l})}encodeUri(t){return b(this,arguments,function*(e,s=[]){const{pluginId:n}=this.currencyInfo,{nativeAmount:r,currencyCode:c,publicAddress:d}=e;if(!Z(d))throw new Error("InvalidPublicAddressError");let o;if(typeof r=="string"){const y=(0,I.Qs)(c!=null?c:this.currencyInfo.currencyCode,this.currencyInfo,s);if(y==null)throw new Error("InternalErrorInvalidCurrencyCode");o=(0,a.div)(r,y.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,S.Rp)(t);const e=(0,S.Oj)(t.networkLocation);if(e==null)throw new Error("ErrorInvalidContractAddress");return e.contractAddress})}}function ut(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(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)})}}}]);
@@ -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
 
@@ -55,6 +56,7 @@ const CHECK_TRANSACTION_INTERVAL = 15000
55
56
 
56
57
 
57
58
 
59
+
58
60
 
59
61
  constructor(
60
62
  env,
@@ -62,7 +64,7 @@ const CHECK_TRANSACTION_INTERVAL = 15000
62
64
  walletInfo,
63
65
  opts
64
66
  ) {
65
- super(env, tools, walletInfo, opts)
67
+ super(env, tools, walletInfo, opts);FilecoinEngine.prototype.__init.call(this);
66
68
  const { networkInfo } = env
67
69
  this.address = _izarifilecoin.Address.fromString(walletInfo.keys.address)
68
70
  this.availableAttoFil = '0'
@@ -70,6 +72,7 @@ const CHECK_TRANSACTION_INTERVAL = 15000
70
72
  url: env.networkInfo.rpcNode.url,
71
73
  token: env.currencyInfo.currencyCode
72
74
  })
75
+ this.filfoxApi = new (0, _Filfox.Filfox)(env.networkInfo.filfoxUrl, env.io.fetchCors)
73
76
  this.filscanApi = new (0, _Filscan.Filscan)(env.networkInfo.filscanUrl, env.io.fetchCors)
74
77
  this.rpcExtra = new (0, _RpcExtra.RpcExtra)(env.networkInfo.rpcNode.url, env.io.fetchCors)
75
78
 
@@ -296,18 +299,73 @@ const CHECK_TRANSACTION_INTERVAL = 15000
296
299
  async checkTransactions() {
297
300
  const addressString = this.address.toString()
298
301
 
302
+ const handleScanProgress = (progress) => {
303
+ const currentProgress =
304
+ this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]
305
+ const newProgress = progress
306
+
307
+ if (
308
+ // Only send event if we haven't completed sync
309
+ currentProgress < 1 &&
310
+ // Avoid thrashing
311
+ (newProgress >= 1 || newProgress > currentProgress * 1.1)
312
+ ) {
313
+ this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode] =
314
+ newProgress
315
+ this.updateOnAddressesChecked()
316
+ }
317
+ }
318
+
319
+ const handleScan = ({
320
+ tx,
321
+ progress
322
+ }
323
+
324
+
325
+ ) => {
326
+ this.addTransaction(this.currencyInfo.currencyCode, tx)
327
+ this.onUpdateTransactions()
328
+
329
+ // Progress the block-height if the message's height is greater than
330
+ // last poll for block-height.
331
+ if (this.walletLocalData.blockHeight < tx.blockHeight) {
332
+ this.onUpdateBlockHeight(tx.blockHeight)
333
+ }
334
+
335
+ handleScanProgress(progress)
336
+ }
337
+
338
+ const scanners = [
339
+ this.scanTransactionsFromFilscan(addressString, handleScan),
340
+ this.scanTransactionsFromFilfox(addressString, handleScan)
341
+ ]
342
+
343
+ await Promise.all(scanners)
344
+
345
+ handleScanProgress(1)
346
+ }
347
+
348
+ async scanTransactionsFromFilfox(
349
+ address,
350
+ onScan
351
+ ) {
299
352
  const messagesPerPage = 20
300
353
  let index = 0
301
354
  let messagesChecked = 0
302
- let messageCount = 0
355
+ let messageCount = -1
303
356
  do {
304
- const messagesResponse = await this.filscanApi.getAccountMessages(
305
- addressString,
357
+ const messagesResponse = await this.filfoxApi.getAccountMessages(
358
+ address,
306
359
  index++,
307
360
  messagesPerPage
308
361
  )
309
- const messages = messagesResponse.result.messages_by_account_id_list
310
362
 
363
+ // Only update the message count on the first query because mutating this
364
+ // in-between pagination may cause infinite loops.
365
+ messageCount =
366
+ messageCount === -1 ? messagesResponse.totalCount : messageCount
367
+
368
+ const messages = messagesResponse.messages
311
369
  for (const message of messages) {
312
370
  const txid = message.cid
313
371
  const idx = this.findTransaction(this.currencyInfo.currencyCode, txid)
@@ -319,18 +377,63 @@ const CHECK_TRANSACTION_INTERVAL = 15000
319
377
  }
320
378
 
321
379
  // Process message into a transaction
322
- this.processMessage(message)
380
+ const tx = this.filfoxMessageToEdgeTransaction(message)
381
+
382
+ // Calculate the progress
383
+ const progress =
384
+ messageCount === 0 ? 1 : ++messagesChecked / messageCount
385
+
386
+ onScan({ tx, progress })
323
387
  }
388
+ } while (messagesChecked < messageCount)
389
+ }
324
390
 
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()
391
+ async scanTransactionsFromFilscan(
392
+ address,
393
+ onScan
394
+ ) {
395
+ const messagesPerPage = 20
396
+ let index = 0
397
+ let messagesChecked = 0
398
+ let messageCount = -1
399
+ do {
400
+ const messagesResponse = await this.filscanApi.getAccountMessages(
401
+ address,
402
+ index++,
403
+ messagesPerPage
404
+ )
405
+
406
+ // Only update the message count on the first query because mutating this
407
+ // in-between pagination may cause infinite loops.
408
+ messageCount =
409
+ messageCount === -1 ? messagesResponse.total_count : messageCount
410
+
411
+ const messages = messagesResponse.messages_by_account_id_list
412
+ for (const message of messages) {
413
+ const txid = message.cid
414
+ const idx = this.findTransaction(this.currencyInfo.currencyCode, txid)
415
+
416
+ if (idx >= 0) {
417
+ // Exit early because we reached transaction history from previous
418
+ // check
419
+ return
420
+ }
421
+
422
+ // Process message into a transaction
423
+ const tx = this.filscanMessageToEdgeTransaction(message)
424
+
425
+ // Calculate the progress
426
+ const progress =
427
+ messageCount === 0 ? 1 : ++messagesChecked / messageCount
428
+
429
+ onScan({ tx, progress })
430
+ }
330
431
  } while (messagesChecked < messageCount)
331
432
  }
332
433
 
333
- processMessage(message) {
434
+ __init() {this.filfoxMessageToEdgeTransaction = (
435
+ message
436
+ ) => {
334
437
  const addressString = this.address.toString()
335
438
  let netNativeAmount = message.value
336
439
  const ourReceiveAddresses = []
@@ -345,7 +448,7 @@ const CHECK_TRANSACTION_INTERVAL = 15000
345
448
 
346
449
  const edgeTransaction = {
347
450
  txid: message.cid,
348
- date: message.block_time,
451
+ date: message.timestamp,
349
452
  currencyCode: this.currencyInfo.currencyCode,
350
453
  blockHeight: message.height,
351
454
  nativeAmount: netNativeAmount,
@@ -356,14 +459,38 @@ const CHECK_TRANSACTION_INTERVAL = 15000
356
459
  otherParams: {},
357
460
  walletId: this.walletId
358
461
  }
359
- this.addTransaction(this.currencyInfo.currencyCode, edgeTransaction)
360
- this.onUpdateTransactions()
361
462
 
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)
463
+ return edgeTransaction
464
+ }}
465
+
466
+ filscanMessageToEdgeTransaction(message) {
467
+ const addressString = this.address.toString()
468
+ let netNativeAmount = message.value
469
+ const ourReceiveAddresses = []
470
+
471
+ const networkFee = '0' // TODO: calculate transaction fee from onchain gas fields
472
+ if (message.to !== addressString) {
473
+ // check if tx is a spend
474
+ netNativeAmount = `-${_biggystring.add.call(void 0, netNativeAmount, networkFee)}`
475
+ } else {
476
+ ourReceiveAddresses.push(addressString)
477
+ }
478
+
479
+ const edgeTransaction = {
480
+ txid: message.cid,
481
+ date: message.block_time,
482
+ currencyCode: this.currencyInfo.currencyCode,
483
+ blockHeight: message.height,
484
+ nativeAmount: netNativeAmount,
485
+ isSend: netNativeAmount.startsWith('-'),
486
+ networkFee,
487
+ ourReceiveAddresses, // blank if you sent money otherwise array of addresses that are yours in this transaction
488
+ signedTx: '',
489
+ otherParams: {},
490
+ walletId: this.walletId
366
491
  }
492
+
493
+ return edgeTransaction
367
494
  }
368
495
  } exports.FilecoinEngine = FilecoinEngine;
369
496
  async function makeCurrencyEngine(
@@ -0,0 +1,101 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+ var _cleaners = require('cleaners');
10
+
11
+
12
+ // -----------------------------------------------------------------------------
13
+ // Types
14
+ // -----------------------------------------------------------------------------
15
+
16
+ //
17
+ // Response Templates
18
+ //
19
+
20
+
21
+ const asFilfoxError = _cleaners.asObject.call(void 0, {
22
+ statusCode: _cleaners.asNumber,
23
+ message: _cleaners.asString,
24
+ error: _cleaners.asString
25
+ }); exports.asFilfoxError = asFilfoxError
26
+
27
+
28
+ const asFilfoxEnvelope = (
29
+ asResult
30
+ ) => _cleaners.asJSON.call(void 0, _cleaners.asEither.call(void 0, exports.asFilfoxError, asResult)); exports.asFilfoxEnvelope = asFilfoxEnvelope
31
+
32
+ //
33
+ // Nominal Types
34
+ //
35
+
36
+
37
+ const asFilfoxMessage = _cleaners.asObject.call(void 0, {
38
+ cid: _cleaners.asString,
39
+ from: _cleaners.asString,
40
+ height: _cleaners.asNumber,
41
+ method: _cleaners.asString,
42
+ nonce: _cleaners.asNumber,
43
+ reciept: _cleaners.asObject.call(void 0, {
44
+ exitCode: _cleaners.asNumber
45
+ }),
46
+ timestamp: _cleaners.asNumber,
47
+ to: _cleaners.asString,
48
+ value: _cleaners.asString
49
+ }); exports.asFilfoxMessage = asFilfoxMessage
50
+
51
+ //
52
+ // Messages
53
+ //
54
+
55
+
56
+ const asFilfoxMessagesResult = _cleaners.asObject.call(void 0, {
57
+ messages: _cleaners.asArray.call(void 0, exports.asFilfoxMessage),
58
+ totalCount: _cleaners.asNumber
59
+ }); exports.asFilfoxMessagesResult = asFilfoxMessagesResult
60
+
61
+ // -----------------------------------------------------------------------------
62
+ // Implementation
63
+ // -----------------------------------------------------------------------------
64
+
65
+ class Filfox {
66
+
67
+
68
+
69
+ constructor(baseUrl, fetchFn) {
70
+ this.baseUrl = baseUrl
71
+ this.fetch = fetchFn
72
+ }
73
+
74
+ async getAccountMessages(
75
+ address,
76
+ page,
77
+ pageSize = 20
78
+ ) {
79
+ const url = new URL(`${this.baseUrl}/address/${address}/messages`)
80
+ const searchParams = new URLSearchParams({
81
+ page: page.toString(),
82
+ pageSize: pageSize.toString()
83
+ })
84
+ url.search = searchParams.toString()
85
+ const response = await this.fetch(url.toString(), {
86
+ method: 'GET',
87
+ headers: {
88
+ 'content-type': 'application/json'
89
+ }
90
+ })
91
+ const responseText = await response.text()
92
+ const responseBody = exports.asFilfoxEnvelope.call(void 0, (0, exports.asFilfoxMessagesResult))(responseText)
93
+
94
+ if ('error' in responseBody)
95
+ throw new Error(
96
+ `Error response code ${responseBody.statusCode}: ${responseBody.message} ${responseBody.error}`
97
+ )
98
+
99
+ return responseBody
100
+ }
101
+ } exports.Filfox = Filfox;
@@ -29,12 +29,10 @@ var _cleaners = require('cleaners');
29
29
  }); exports.asFilscanOkResponse = asFilscanOkResponse
30
30
 
31
31
 
32
- const asFilscanError = _cleaners.asJSON.call(void 0,
33
- _cleaners.asObject.call(void 0, {
34
- code: _cleaners.asNumber,
35
- message: _cleaners.asString
36
- })
37
- ); exports.asFilscanError = asFilscanError
32
+ const asFilscanError = _cleaners.asObject.call(void 0, {
33
+ code: _cleaners.asNumber,
34
+ message: _cleaners.asString
35
+ }); exports.asFilscanError = asFilscanError
38
36
 
39
37
 
40
38
  const asFilscanEnvelope = (
@@ -146,9 +144,7 @@ var _cleaners = require('cleaners');
146
144
  this.fetch = fetchFn
147
145
  }
148
146
 
149
- async getAccountInfo(
150
- accountId
151
- ) {
147
+ async getAccountInfo(accountId) {
152
148
  const response = await this.fetch(`${this.baseUrl}/AccountInfoByID`, {
153
149
  method: 'POST',
154
150
  headers: {
@@ -168,7 +164,7 @@ var _cleaners = require('cleaners');
168
164
  `Error response code ${responseBody.code}: ${responseBody.message}`
169
165
  )
170
166
 
171
- return responseBody
167
+ return responseBody.result
172
168
  }
173
169
 
174
170
  async getAccountMessages(
@@ -202,7 +198,7 @@ var _cleaners = require('cleaners');
202
198
  `Error response code ${responseBody.code}: ${responseBody.message}`
203
199
  )
204
200
 
205
- return responseBody
201
+ return responseBody.result
206
202
  }
207
203
 
208
204
  async getMessageDetails(
@@ -227,6 +223,6 @@ var _cleaners = require('cleaners');
227
223
  `Error response code ${responseBody.code}: ${responseBody.message}`
228
224
  )
229
225
 
230
- return responseBody
226
+ return responseBody.result
231
227
  }
232
228
  } exports.Filscan = Filscan;
@@ -6,6 +6,7 @@ var _innerPlugin = require('../common/innerPlugin');
6
6
 
7
7
 
8
8
  const networkInfo = {
9
+ filfoxUrl: 'https://filfox.info/api/v1',
9
10
  filscanUrl: 'https://api-v2.filscan.io/api/v1',
10
11
  hdPathCoinType: 461,
11
12
  rpcNode: {
@@ -28,6 +28,7 @@ var _types = require('../common/types');
28
28
 
29
29
 
30
30
 
31
+
31
32
  const asFilecoinWalletOtherData = _cleaners.asObject.call(void 0, {}); exports.asFilecoinWalletOtherData = asFilecoinWalletOtherData
32
33
 
33
34