edge-currency-accountbased 3.2.2 → 3.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,2 +1,2 @@
1
- (self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[2805],{79014:function(pe,Q,D){"use strict";D.d(Q,{Q:function(){return z},k:function(){return u}});var R=D(77591),ue=D.n(R),P=D(24350),ie=D(84564),ee=D.n(ie),b=D(76714),h=Object.defineProperty,I=Object.getOwnPropertySymbols,y=Object.prototype.hasOwnProperty,C=Object.prototype.propertyIsEnumerable,V=(w,x,T)=>x in w?h(w,x,{enumerable:!0,configurable:!0,writable:!0,value:T}):w[x]=T,ae=(w,x)=>{for(var T in x||(x={}))y.call(x,T)&&V(w,T,x[T]);if(I)for(var T of I(x))C.call(x,T)&&V(w,T,x[T]);return w};function u(w,x,T,B,G=[]){const O=ae({},ee()(x,{},!0)),W=x.startsWith(`${w.pluginId}://`);if(O.protocol!=null&&(O.protocol=O.protocol.replace(":","")),O.protocol!=null&&O.protocol!==""&&!T[O.protocol])throw new Error(`Uri protocol '${O.protocol}' is not supported for ${w.pluginId}.`);if(O.host===""&&O.pathname==="")throw new Error("Path and host not found in uri.");const U={publicAddress:O.host!==""?O.host:O.pathname.split("/")[0]},te=O.query.label,j=O.query.message,se=O.query.category;(te!=null||j!=null||se!=null||W)&&(U.metadata={},U.metadata.name=te,U.metadata.notes=j,U.metadata.category=se,U.metadata.gateway=W!=null?W:!1);const J=O.query.amount;if(J!=null&&typeof J=="string"){B==null&&(B=w.currencyCode);const Y=(0,b.Qs)(B!=null?B:"",w,G);if(Y==null)throw new Error("InternalErrorInvalidCurrencyCode");let Z=(0,R.mul)(J,Y.multiplier);Z=(0,R.toFixed)(Z,0,0),U.nativeAmount=Z,U.currencyCode=B}return{edgeParsedUri:U,parsedUri:O}}function z(w,x,T){if(w.publicAddress==null)throw new Error("InvalidPublicAddressError");if(T==null&&w.label==null&&w.message==null)return w.publicAddress;{let B="";T!=null&&(B+="amount="+T+"&"),(w.label!=null||w.message!=null)&&(typeof w.label=="string"&&(B+="label="+w.label+"&"),typeof w.message=="string"&&(B+="message="+w.message+"&")),B=B.substr(0,B.length-1);const G={scheme:x,path:w.publicAddress,query:B};return(0,P.qC)(G)}}},44285:function(pe,Q,D){"use strict";D.r(Q),D.d(Q,{FioTools:function(){return ye},checkAddress:function(){return de},makeCurrencyEngine:function(){return ve},makeCurrencyTools:function(){return Ie}});var R=D(93491),ue=D(45234),P=D(77591),ie=D(2153),ee=D(79014),b=D(76714),h=D(5607),I=D(24827),y=D(3559),C=D(37858),V=D(82626),ae=D(37297),u=D(82448),z=D(94935),w=D(84650),x=D(72681);const T=(0,u.su)({fio_domains:(0,u._2)((0,u.su)({fio_domain:u.XC,expiration:u.XC,is_public:u.mH})),fio_addresses:(0,u._2)((0,u.su)({fio_address:u.XC,remaining_bundled_tx:u.mH}))}),B=(0,u.Vk)((0,u.Wf)("unstakefio","transfer","regaddress"),null),G=(0,u.su)({account_action_seq:u.mH,block_num:u.mH,block_time:u.XC,action_trace:(0,u.su)({receiver:u.XC,act:(0,u.su)({account:u.XC,name:B,authorization:(0,u._2)((0,u.su)({actor:u.XC,permission:u.XC})),data:(0,u.su)({payee_public_key:(0,u.Zz)(u.XC),amount:(0,u.Zz)(u.mH),max_fee:(0,u.Zz)(u.mH),actor:(0,u.Zz)(u.XC),tpid:(0,u.Zz)(u.XC),quantity:(0,u.Zz)(u.XC),memo:(0,u.Zz)(u.XC),to:(0,u.Zz)(u.XC),from:(0,u.Zz)(u.XC)}),hex_data:u.XC}),trx_id:u.XC,block_num:u.mH,block_time:u.XC,producer_block_id:u.XC})}),O=(0,u.su)({actions:(0,u._2)(G)}),W=(0,u.su)({balance:u.mH,available:u.mH,staked:u.mH,srps:u.mH,roe:u.XC});var he=Object.defineProperty,U=Object.defineProperties,te=Object.getOwnPropertyDescriptors,j=Object.getOwnPropertySymbols,se=Object.getPrototypeOf,J=Object.prototype.hasOwnProperty,Y=Object.prototype.propertyIsEnumerable,Z=Reflect.get,fe=(_,e,s)=>e in _?he(_,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):_[e]=s,S=(_,e)=>{for(var s in e||(e={}))J.call(e,s)&&fe(_,s,e[s]);if(j)for(var s of j(e))Y.call(e,s)&&fe(_,s,e[s]);return _},H=(_,e)=>U(_,te(e)),ge=(_,e)=>{var s={};for(var t in _)J.call(_,t)&&e.indexOf(t)<0&&(s[t]=_[t]);if(_!=null&&j)for(var t of j(_))e.indexOf(t)<0&&Y.call(_,t)&&(s[t]=_[t]);return s},me=(_,e,s)=>Z(se(_),s,e),k=(_,e,s)=>new Promise((t,n)=>{var r=o=>{try{a(s.next(o))}catch(i){n(i)}},l=o=>{try{a(s.throw(o))}catch(i){n(i)}},a=o=>o.done?t(o.value):Promise.resolve(o.value).then(r,l);a((s=s.apply(_,e)).next())});const ke=1e4,_e=15e3,be=1e4,De=1e4;class ne extends w.P{constructor(e,s,t,n,r){super(e,s,t,n),this.fioRequestsListChanged=(l,a)=>{function o(i,d){for(const c of i)if(d.findIndex(g=>g.fio_request_id===c.fio_request_id)<0)return!0;return!1}return!!(o(l,a)||o(a,l))},this.removeFioRequest=(l,a)=>{const o=this.otherData.fioRequests[a].findIndex(i=>i.fio_request_id===`${l}`);o>-1&&this.otherData.fioRequests[a].splice(o,1)},this.fetchCors=(0,b.zR)(e.io),this.tpid=r,this.networkInfo=e.networkInfo,this.refBlock={expiration:"",ref_block_num:0,ref_block_prefix:0},this.fees=new Map,this.actor=R.rn.accountHash(this.walletInfo.keys.publicKey).accountnm,this.obtData=[],this.otherMethods={fioAction:(l,a)=>k(this,null,function*(){return yield this.multicastServers(l,a)}),getFioAddresses:()=>k(this,null,function*(){return this.otherData.fioAddresses}),getFioAddressNames:()=>k(this,null,function*(){return this.otherData.fioAddresses.map(l=>l.name)}),getFioDomains:()=>k(this,null,function*(){return this.otherData.fioDomains}),getFioRequests:(l,a,o=50)=>k(this,null,function*(){const i=o*(a-1),d=o*a;return this.otherData.fioRequests[l].sort((c,g)=>c.time_stamp<g.time_stamp?1:-1).slice(i,d)}),getObtData:()=>k(this,null,function*(){return this.obtData})}}localDataDirty(){this.walletLocalDataDirty=!0}setOtherData(e){this.otherData=(0,h.CL)(e)}getUTCDate(e){const s=new Date(e);return Date.UTC(s.getFullYear(),s.getMonth(),s.getDate(),s.getHours(),s.getMinutes(),s.getSeconds())}getUnlockDate(e){const s=Math.floor(e.getTime()/h.qj)*h.qj;return new Date(s+h.dm)}checkBlockchainInnerLoop(){return k(this,null,function*(){try{const e=yield this.multicastServers("getChainInfo"),s=e.head_block_num;this.walletLocalData.blockHeight!==s&&(this.checkDroppedTransactionsThrottled(),this.walletLocalData.blockHeight=s,this.localDataDirty(),this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight));const t=yield this.multicastServers("getBlock",e),n=new Date(`${e.head_block_time}Z`);n.setSeconds(n.getSeconds()+180);const r=n.toISOString();this.refBlock={expiration:r.substring(0,r.length-1),ref_block_num:t.block_num&65535,ref_block_prefix:t.ref_block_prefix}}catch(e){this.error("checkBlockchainInnerLoop Error fetching height: ",e)}})}getBalance(e){return super.getBalance(e)}doInitialBalanceCallback(){super.doInitialBalanceCallback();try{this.currencyEngineCallbacks.onStakingStatusChanged(S({},this.otherData.stakingStatus))}catch(e){this.error("doInitialBalanceCallback onStakingStatusChanged",e)}}checkUnStakeTx(e){return e.name==="unstakefio"||e.data!=null&&e.data.memo===h.Nd}updateStakingStatus(e){if(this.otherData.stakingStatus.stakedAmounts[0]={nativeAmount:this.otherData.lockedBalances.locked,unlockDate:void 0,otherParams:{type:"LOCKED"}},this.otherData.stakingStatus.stakedAmounts[1]={nativeAmount:this.otherData.lockedBalances.staked,unlockDate:void 0,otherParams:{type:"STAKED"}},e!=null){const{nativeAmount:s,blockTime:t,txId:n,txName:r}=e,l=this.getUnlockDate(new Date(this.getUTCDate(t))),a=this.otherData.stakingStatus.stakedAmounts.findIndex(o=>{var i;return((i=o.unlockDate)==null?void 0:i.getTime())===l.getTime()});if(a<0){const o=this.otherData.stakingStatus.stakedAmounts.findIndex(d=>{var c,g;return l.getTime()>=((g=(c=d.unlockDate)==null?void 0:c.getTime())!=null?g:1/0)}),i=o<0?this.otherData.stakingStatus.stakedAmounts.length:o;this.otherData.stakingStatus.stakedAmounts.splice(i,0,{nativeAmount:s,unlockDate:l,otherParams:{date:new Date(t),txs:[{txId:n,nativeAmount:s,blockTime:t,txName:r}]}})}else{const o=H(S({},this.otherData.stakingStatus.stakedAmounts[a]),{nativeAmount:"0"}),i=o.otherParams.txs.findIndex(({txId:d,txName:c})=>d===n&&c===r);i<0?o.otherParams.txs.push({txId:n,nativeAmount:s,blockTime:t,txName:r}):o.otherParams.txs[i]={txId:n,nativeAmount:s,blockTime:t,txName:r};for(const d of o.otherParams.txs)o.nativeAmount=(0,P.add)(o.nativeAmount,d.nativeAmount);this.otherData.stakingStatus.stakedAmounts[a]=o}}this.localDataDirty();try{this.currencyEngineCallbacks.onStakingStatusChanged(S({},this.otherData.stakingStatus))}catch{this.error("onStakingStatusChanged error")}}getStakingStatus(){return k(this,null,function*(){return S({},this.otherData.stakingStatus)})}processTransaction(e,s,t=this.currencyInfo.currencyCode){var n,r,l,a,o,i,d,c,g;const{act:{name:p,data:m,account:v,authorization:N}}=e.action_trace;let f,E,q="0",A={account:v,name:p,authorization:N,data:m,meta:{}};const L=[];if(e.block_num<=this.otherData.highestTxHeight)return e.block_num;if(p!=null){f="0",p==="regaddress"&&e.action_trace.act.authorization.some(K=>K.actor===this.actor)&&(q=String((n=e.action_trace.act.data.max_fee)!=null?n:0),f=`-${q}`),p==="transfer"&&m.amount!=null&&(f=m.amount.toString(),E=m.actor,m.payee_public_key===this.walletInfo.keys.publicKey?(L.push(this.walletInfo.keys.publicKey),E===s&&(f="0")):f=`-${f}`);const $=this.findTransaction(t,e.action_trace.trx_id);if($>-1){const K=this.transactionList[t][$];if(A=H(S(S({},K.otherParams),A),{data:S(S({},(l=(r=K.otherParams)==null?void 0:r.data)!=null?l:{}),A.data),meta:S(S({},(o=(a=K.otherParams)==null?void 0:a.meta)!=null?o:{}),A.meta)}),A.meta.isTransferProcessed!=null)return e.block_num;A.meta.isFeeProcessed!=null?p===h.BP[h.aO.transferTokens]?(f=(0,P.sub)(f,K.networkFee),q=K.networkFee):(f=K.nativeAmount,q="0"):this.error("processTransaction error - existing spend transaction should have isTransferProcessed or isFeeProcessed set")}this.checkUnStakeTx(A)&&this.updateStakingStatus({nativeAmount:m.amount!=null?m.amount.toString():"0",blockTime:e.block_time,txId:e.action_trace.trx_id,txName:p}),A.meta.isTransferProcessed=!0;const M={blockHeight:e.block_num>0?e.block_num:0,currencyCode:t,date:this.getUTCDate(e.block_time)/1e3,isSend:f.startsWith("-"),memos:[],nativeAmount:f,networkFee:q,otherParams:A,ourReceiveAddresses:L,signedTx:"",txid:e.action_trace.trx_id,walletId:this.walletId};this.addTransaction(t,M)}if(p==="transfer"&&m.quantity!=null){const[$]=m.quantity.split(" "),M=$.toString(),K=(0,b.aL)(t,this.currencyInfo,this.allTokensMap);if(K==null)return this.error(`Received unsupported currencyCode: ${t}`),0;const X=(0,P.mul)(M,K.multiplier);m.to===s?(f=`${X}`,q=`-${X}`):(f=`-${X}`,q=X);const re=this.findTransaction(t,e.action_trace.trx_id);if(re>-1){const oe=this.transactionList[t][re];if(A=H(S(S({},A),oe.otherParams),{data:S(S({},A.data),(d=(i=oe.otherParams)==null?void 0:i.data)!=null?d:{}),meta:S(S({},A.meta),(g=(c=oe.otherParams)==null?void 0:c.meta)!=null?g:{})}),A.meta.isFeeProcessed!=null)return e.block_num;A.meta.isTransferProcessed!=null?m.to!==s?f=(0,P.sub)(oe.nativeAmount,q):q="0":this.error("processTransaction error - existing spend transaction should have isTransferProcessed or isFeeProcessed set")}this.checkUnStakeTx(A)&&this.updateStakingStatus({nativeAmount:X,blockTime:e.block_time,txId:e.action_trace.trx_id,txName:p}),A.meta.isFeeProcessed=!0;const Pe={blockHeight:e.block_num>0?e.block_num:0,currencyCode:t,date:this.getUTCDate(e.block_time)/1e3,isSend:f.startsWith("-"),memos:[],nativeAmount:f,networkFee:q,otherParams:A,ourReceiveAddresses:[],signedTx:"",txid:e.action_trace.trx_id,walletId:this.walletId};this.addTransaction(t,Pe)}return e.block_num}getSortedHistoryNodesLastActionSeqNumbers(){return k(this,null,function*(){const e=this.networkInfo.historyNodeUrls.map((t,n)=>k(this,null,function*(){var r;try{const l=yield this.requestHistory(n,{account_name:this.actor,pos:-1},h.pg.getActions);return((r=l==null?void 0:l.error)==null?void 0:r.noNodeForIndex)!=null?{nodeIndex:n,seqNumber:-1}:(O(l),l.actions.length===0?{nodeIndex:n,seqNumber:-1}:{nodeIndex:n,seqNumber:l.actions[l.actions.length-1].account_action_seq})}catch{return{nodeIndex:n,seqNumber:-1}}})),s=yield Promise.all(e);return s.sort((t,n)=>n.seqNumber-t.seqNumber),s})}checkTransactions(e){return k(this,null,function*(){var s,t;if((e==null?void 0:e.length)===0)return!1;if(e=e!=null?e:yield this.getSortedHistoryNodesLastActionSeqNumbers(),e.reduce((i,d)=>i+d.seqNumber,0)===-e.length)return!0;let n=this.otherData.highestTxHeight;const r=e[0].seqNumber,l=e[0].nodeIndex;let a=Math.max(0,r-h.WX+1),o=!1;for(;!o;){let i;try{if(i=yield this.requestHistory(l,{account_name:this.actor,pos:a,offset:h.WX-1},h.pg.getActions),((s=i.error)==null?void 0:s.noNodeForIndex)!=null)return!1;let d=[];if(((t=i.actions)==null?void 0:t.length)>0)d=i.actions;else break;for(let c=d.length-1;c>-1;c--){const g=G(d[c]),p=this.processTransaction(g,this.actor);if(p>n)n=p;else if(p===n&&c===h.WX-1||p<this.otherData.highestTxHeight){o=!0;break}}if(a===0)break;a=Math.max(0,a-h.WX);continue}catch{return yield this.checkTransactions(e.slice(1))}}return n>this.otherData.highestTxHeight&&(this.otherData.highestTxHeight=n,this.localDataDirty()),!0})}checkTransactionsInnerLoop(){return k(this,null,function*(){let e;try{e=yield this.checkTransactions()}catch(s){this.error("checkTransactionsInnerLoop fetches failed with error: ",s);return}e&&(this.tokenCheckTransactionsStatus.FIO=1,this.updateOnAddressesChecked()),this.transactionsChangedArray.length>0&&(this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[])})}requestHistory(e,s,t){return k(this,null,function*(){if(this.networkInfo.historyNodeUrls[e]==null)return{error:{noNodeForIndex:!0}};const n=this.networkInfo.historyNodeUrls[e],r=JSON.stringify(s);return yield(yield fetch(`${n}history/${t}`,{method:"POST",headers:{"Content-Length":(r.length*2).toString(),Accept:"application/json","Content-Type":"application/json"},body:r})).json()})}fioApiRequest(e,s,t,n=!1){return k(this,null,function*(){var r,l,a,o;const i=new R.rn("",this.walletInfo.keys.publicKey,e,this.fetchCors,void 0,this.tpid,n);let d;try{switch(s){case"getChainInfo":d=yield i.transactions.getChainInfo();break;case"getBlock":d=yield i.transactions.getBlock(t);break;case"getObtData":case"getPendingFioRequests":case"getSentFioRequests":{const{endpoint:c,body:g}=t;d=yield i.transactions.executeCall(c,JSON.stringify(g));break}case"getCurrencyBalance":{d=yield(yield this.fetchCors(`${e}chain/get_currency_balance`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(t)})).json();break}default:d=yield i.genericAction(s,t)}}catch(c){if(c.errorCode!=null&&I.lI.includes(c.errorCode))((a=(l=(r=c.json)==null?void 0:r.fields)==null?void 0:l[0])==null?void 0:a.error)!=null&&(c.message=c.json.fields[0].error),d={isError:!0,data:{code:c.errorCode,message:(o=c.message)!=null?o:(0,b.HY)(c),json:c.json,list:c.list}},c.errorCode!==404&&this.log(`fioApiRequest error. actionName: ${s} - apiUrl: ${e} - message: ${JSON.stringify(c.json)}`);else throw this.log(`fioApiRequest error. actionName: ${s} - apiUrl: ${e} - message: `,c),c}return d})}executePreparedTrx(e,s,t){return k(this,null,function*(){var n,r,l;const a=new R.rn("",this.walletInfo.keys.publicKey,e,this.fetchCors,void 0,this.tpid,!0);let o;this.warn(`executePreparedTrx. preparedTrx: ${JSON.stringify(t)} - apiUrl: ${e}`);try{o=yield a.executePreparedTrx(s,t),this.warn(`executePreparedTrx. res: ${JSON.stringify(o)} - apiUrl: ${e} - endpoint: ${s}`)}catch(i){throw i.errorCode!=null&&I.lI.includes(i.errorCode)?(this.log(`executePreparedTrx error. requestParams: ${JSON.stringify(t)} - apiUrl: ${e} - endpoint: ${s} - message: ${JSON.stringify(i.json)}`),((l=(r=(n=i.json)==null?void 0:n.fields)==null?void 0:r[0])==null?void 0:l.error)!=null&&(i.message=i.json.fields[0].error),i):(this.log(`executePreparedTrx error. requestParams: ${JSON.stringify(t)} - apiUrl: ${e} - endpoint: ${s} - message: `,i),i)}return o})}multicastServers(e,s){return k(this,null,function*(){var t,n,r,l,a,o,i,d;let c;if(h.K1[e]){const g=(0,y.h0)(s);if(this.warn(`multicastServers executePreparedTrx. actionName: ${e} - res: ${JSON.stringify(g)}`),c=yield(0,b.Wp)((0,b.Sy)(this.networkInfo.apiUrls.map(p=>k(this,null,function*(){return yield(0,b.Vs)(this.executePreparedTrx(p,C.EndPoint[h.VW[e]],g),1e4)})))),this.warn(`multicastServers res. actionName: ${e} - res: ${JSON.stringify(c)}`),c==null)throw new Error("Service is unavailable")}else if(e==="getFioNames")c=yield(0,b.ml)(this.networkInfo.apiUrls.map(g=>k(this,null,function*(){return yield(0,b.Vs)(this.fioApiRequest(g,e,s),1e4)})),g=>{const p=(0,y.$K)(h.Mi)(g);return p!=null?p.data.json.message:(0,y.e1)(g)},2),((n=(t=c==null?void 0:c.data)==null?void 0:t.json)==null?void 0:n.message)===h.Mi&&(c={fio_domains:[],fio_addresses:[]});else if(e==="getCurrencyBalance"){c=yield(0,b.ml)(this.networkInfo.apiUrls.map(v=>k(this,null,function*(){return yield(0,b.Vs)(this.fioApiRequest(v,"getCurrencyBalance",{code:"fio.token",account:this.actor,symbol:"FIO"}),1e4)})),v=>JSON.stringify(v),2),((l=(r=c==null?void 0:c.data)==null?void 0:r.json)==null?void 0:l.message)===h.d9&&(c={balance:0,available:0,staked:0,srps:0,roe:""});const p=(0,u.vq)(u.XC)(c)[0].split(" ")[0],m=(0,P.mul)(p,(a=this.currencyInfo.denominations[0].multiplier)!=null?a:"1000000000");c={balance:parseInt(m),available:0,staked:0,srps:0,roe:"0"}}else e==="getFioBalance"?(c=yield(0,b.ml)(this.networkInfo.apiUrls.map(g=>k(this,null,function*(){return yield(0,b.Vs)(this.fioApiRequest(g,e,s),1e4)})),g=>{const p=(0,y.$K)(h.d9)(g);return p!=null?p.data.json.message:(0,y.sq)(g)},2),((i=(o=c==null?void 0:c.data)==null?void 0:o.json)==null?void 0:i.message)===h.d9&&(c={balance:0,available:0,staked:0,srps:0,roe:""})):e==="getFees"?c=yield(0,b.QJ)((0,b.Sy)(this.networkInfo.apiUrls.map(g=>()=>k(this,null,function*(){const p=new R.rn("",this.walletInfo.keys.publicKey,g,this.fetchCors,void 0,this.tpid),{endpoint:m,param:v}=s,N=yield p.getFee(m,v);return(0,y.lZ)(N).fee.toString()})))):c=yield(0,b.QJ)((0,b.Sy)(this.networkInfo.apiUrls.map(g=>()=>k(this,null,function*(){return yield this.fioApiRequest(g,e,s)}))));if(c.isError!=null){const g=new I.OU((d=c.errorMessage)!=null?d:c.data.message);throw g.json=c.data.json,g.list=c.data.list,g.errorCode=c.data.code,g}return c})}checkAccountInnerLoop(){return k(this,null,function*(){var e;const s=this.currencyInfo.currencyCode;typeof this.walletLocalData.totalBalances[s]>"u"&&this.updateBalance(s,"0");try{const t={staked:"0",locked:"0"};let n;try{n=W(yield this.multicastServers("getFioBalance"))}catch(c){if(((e=c==null?void 0:c.json)==null?void 0:e.message)===h.kE)n=W(yield this.multicastServers("getCurrencyBalance")),this.log.warn("Returning FIO balance only due to chain bug");else throw c}const{balance:r,available:l,staked:a,srps:o,roe:i}=n,d=String(r);t.staked=String(a),t.locked=(0,P.sub)(d,String(l)),this.otherData.srps=o,this.otherData.stakingRoe=i,this.updateBalance(s,d),(t.staked!==this.otherData.lockedBalances.staked||t.locked!==this.otherData.lockedBalances.locked)&&(this.otherData.lockedBalances=t,this.localDataDirty(),this.updateStakingStatus())}catch(t){this.log.warn("checkAccountInnerLoop getFioBalance error: ",t)}try{const t=T(yield this.multicastServers("getFioNames",{fioPublicKey:this.walletInfo.keys.publicKey}));let n=!1,r=!1,l=!1;if(t.fio_addresses.length!==this.otherData.fioAddresses.length)r=!0;else{for(const a of t.fio_addresses){const o=this.otherData.fioAddresses.find(i=>i.name===a.fio_address);if(o!=null){if(o.bundledTxs!==a.remaining_bundled_tx){r=!0;break}}else{r=!0;break}}if(!r){for(const a of this.otherData.fioAddresses)if(t.fio_addresses.findIndex(o=>o.fio_address===a.name)<0){r=!0;break}}}if(t.fio_domains.length!==this.otherData.fioDomains.length)l=!0;else{for(const a of t.fio_domains){const o=this.otherData.fioDomains.find(i=>i.name===a.fio_domain);if(o!=null){if(o.expiration!==a.expiration){l=!0;break}if(o.isPublic!==(a.is_public===1)){l=!0;break}}else{l=!0;break}}if(!l){for(const a of this.otherData.fioDomains)if(t.fio_domains.findIndex(o=>o.fio_domain===a.name)<0){l=!0;break}}}r&&(n=!0,this.otherData.fioAddresses=t.fio_addresses.map(a=>({name:a.fio_address,bundledTxs:a.remaining_bundled_tx}))),l&&(n=!0,this.otherData.fioDomains=t.fio_domains.map(a=>({name:a.fio_domain,expiration:a.expiration,isPublic:a.is_public===1}))),n&&this.localDataDirty()}catch(t){this.warn("checkAccountInnerLoop getFioNames error: ",t)}})}fetchEncryptedFioRequests(e,s){return k(this,null,function*(){const n=e==="PENDING"?"getPendingFioRequests":"getSentFioRequests";let r=100,l=1;const a=[];for(;r===100;)try{const o=yield this.multicastServers(n,{endpoint:s.getEndPoint(),body:{fio_public_key:this.walletInfo.keys.publicKey,limit:100,offset:(l-1)*100}}),i=(0,y.S_)(o),{requests:d,more:c}=i;if(a.push(...d),c===0)break;l++,r=d.length}catch(o){const i=(0,u.Vk)(y.Pq)(o.json);(i==null?void 0:i.message)!=="No FIO Requests"&&this.error("fetchEncryptedFioRequests error: ",o);break}return a})}fetchEncryptedObtData(e,s){return k(this,null,function*(){let n=100,r=1;const l=[];for(;n===100;){let a;try{a=yield this.multicastServers(e,{endpoint:s.getEndPoint(),body:{fio_public_key:this.walletInfo.keys.publicKey,limit:100,offset:(r-1)*100}});const o=(0,y._v)(a),{obt_data_records:i,more:d}=o;if(l.push(...i),d===0)break;r++,n=i.length}catch(o){const i=(0,u.Vk)(y.Pq)(o.json);(i==null?void 0:i.message)!=="No FIO Requests"&&this.error("fetchEncryptedObtData error: ",o);break}}return l})}syncNetwork(e){return k(this,null,function*(){var s;const t=(0,y.UW)(e==null?void 0:e.privateKeys);let n=!1;const r=(i,d)=>k(this,null,function*(){var c;const g=yield this.fetchEncryptedFioRequests(i,d);d.privateKey=t.fioKey,d.publicKey=this.walletInfo.keys.publicKey;const p=(c=d.decrypt({requests:g}))!=null?c:{requests:[]};this.fioRequestsListChanged(this.otherData.fioRequests[i],p.requests)&&(this.otherData.fioRequests[i]=[...p.requests],n=!0)});yield r("PENDING",new V.PendingFioRequests(this.walletInfo.keys.publicKey)),yield r("SENT",new V.SentFioRequests(this.walletInfo.keys.publicKey)),n&&this.localDataDirty();const l=new V.GetObtData(this.walletInfo.keys.publicKey),a=yield this.fetchEncryptedObtData("getObtData",l);l.privateKey=t.fioKey,l.publicKey=this.walletInfo.keys.publicKey;const o=(s=l.decrypt({obt_data_records:a}))!=null?s:{obt_data_records:[]};return this.obtData=o.obt_data_records,De})}getFee(e,s){return k(this,null,function*(){let t=this.fees.get(e);if(t==null||t.expiration+30*1e3<Date.now()){const r={fee:yield this.multicastServers("getFees",{endpoint:e,param:s}),expiration:Date.now()};this.fees.set(e,r),t=r}return t.fee})}startEngine(){return k(this,null,function*(){this.engineOn=!0,this.addToLoop("checkBlockchainInnerLoop",_e).catch(()=>{}),this.addToLoop("checkAccountInnerLoop",ke).catch(()=>{}),this.addToLoop("checkTransactionsInnerLoop",be).catch(()=>{}),yield me(ne.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return k(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getMaxSpendable(e){return k(this,null,function*(){e=(0,x.s)(e,this.currencyInfo);const s=this.getBalance({currencyCode:e.currencyCode}),t=this.otherData.lockedBalances.locked;e.spendTargets[0].nativeAmount="1";const n=yield this.makeSpend(e),r=(0,P.sub)((0,P.sub)(s,n.networkFee),t);if((0,P.lt)(r,"0"))throw new z.C_({networkFee:n.networkFee});return r})}makeSpend(e){return k(this,null,function*(){e=(0,x.s)(e,this.currencyInfo);const{edgeSpendInfo:s,nativeBalance:t,currencyCode:n}=this.makeSpendCheck(e),{memos:r=[]}=s,l=this.otherData.lockedBalances.locked,a=(0,P.sub)(t,l),o=s.spendTargets[0],{publicAddress:i}=o,{nativeAmount:d}=o;if(i==null)throw new Error("makeSpend Missing publicAddress");if(d==null)throw new z.$D;let{otherParams:c}=s;(c==null||Object.keys(c).length===0)&&(c={action:{name:h.aO.transferTokens,params:{payeeFioPublicKey:i,amount:d,maxFee:0}}});const{name:g,params:p}=(0,y.iR)(c.action);let m,v;switch(g){case h.aO.transferTokens:{m=yield this.getFee(C.EndPoint.transferTokens),v={account:"fio.token",action:h.BP[h.aO.transferTokens],data:{payee_public_key:i,amount:d,max_fee:m}};break}case h.aO.stakeFioTokens:{const{fioAddress:f}=(0,y.NB)(p);m=yield this.getFee(C.EndPoint.stakeFioTokens,f),v={account:"fio.staking",action:h.BP[g],data:{amount:d,fio_address:f,actor:this.actor,max_fee:m}};break}case h.aO.unStakeFioTokens:{const{fioAddress:f}=(0,y.NB)(p);m=yield this.getFee(C.EndPoint.unStakeFioTokens,f),v={account:"fio.staking",action:h.BP[g],data:{amount:d,fio_address:f,actor:this.actor,max_fee:m}};const E=this.getUnlockDate(new Date),q=this.otherData.lockedBalances.staked;if((0,P.gt)(d,q)||(0,P.gt)(`${m}`,a))throw new z.C_;const A=(0,P.mul)((0,P.mul)((0,P.div)(d,q,18),`${this.otherData.srps}`),this.otherData.stakingRoe),L=(0,P.max)((0,P.sub)(A,d),"0");c.ui={accrued:A,estReward:L,unlockDate:E};break}case h.aO.transferFioAddress:{const{fioAddress:f}=(0,y.NB)(p);m=yield this.getFee(C.EndPoint.transferFioAddress,f),v={account:"fio.address",action:"xferaddress",data:{fio_address:f,new_owner_fio_public_key:i,actor:this.actor,max_fee:m}};break}case h.aO.transferFioDomain:{const{fioDomain:f}=(0,y.L2)(p);m=yield this.getFee(C.EndPoint.transferFioDomain),v={account:"fio.address",action:"xferdomain",data:{fio_domain:f,new_owner_fio_public_key:i,actor:this.actor,max_fee:m}};break}case h.aO.addPublicAddresses:{const{fioAddress:f,publicAddresses:E}=(0,y.PH)(p);m=yield this.getFee(C.EndPoint.addPubAddress,f),v={account:"fio.address",action:"addaddress",data:{fio_address:f,public_addresses:E,actor:this.actor,max_fee:m}};break}case h.aO.removePublicAddresses:{const{fioAddress:f,publicAddresses:E}=(0,y.PH)(p);m=yield this.getFee(C.EndPoint.removePubAddress,f),v={account:"fio.address",action:"remaddress",data:{fio_address:f,public_addresses:E,actor:this.actor,max_fee:m}};break}case h.aO.registerFioAddress:{const{fioAddress:f}=(0,y.NB)(p);m=yield this.getFee(C.EndPoint.registerFioAddress),v={account:"fio.address",action:"regaddress",data:{fio_address:f,owner_fio_public_key:this.walletInfo.keys.publicKey,max_fee:m,actor:this.actor}};break}case h.aO.registerFioDomain:{const{fioDomain:f}=(0,y.AJ)(p);m=yield this.getFee(C.EndPoint.registerFioDomain),v={account:"fio.address",action:"regdomain",data:{fio_domain:f,owner_fio_public_key:this.walletInfo.keys.publicKey,max_fee:m,actor:this.actor}};break}case h.aO.renewFioDomain:{const{fioDomain:f}=(0,y.AJ)(p);m=yield this.getFee(C.EndPoint.renewFioDomain),v={account:"fio.address",action:"renewdomain",data:{fio_domain:f,max_fee:m,actor:this.actor}};break}case h.aO.addBundledTransactions:{const{bundleSets:f,fioAddress:E}=(0,y.Ej)(p);m=yield this.getFee(C.EndPoint.addBundledTransactions,E),v={account:"fio.address",action:"addbundles",data:{fio_address:E,bundle_sets:f,actor:this.actor,max_fee:m}};break}case h.aO.setFioDomainPublic:{const{fioDomain:f,isPublic:E}=(0,y.oY)(p);m=yield this.getFee(C.EndPoint.setFioDomainPublic),v={account:"fio.address",action:"setdomainpub",data:{fio_domain:f,is_public:E?1:0,max_fee:m,actor:this.actor}};break}case h.aO.rejectFundsRequest:{const{fioRequestId:f,payerFioAddress:E}=(0,y.OR)(p);m=yield this.getFee(C.EndPoint.rejectFundsRequest,E),v={account:"fio.reqobt",action:"rejectfndreq",data:{fio_request_id:f,max_fee:m,actor:this.actor}};break}case h.aO.cancelFundsRequest:{const{fioAddress:f,fioRequestId:E}=(0,y.mO)(p);m=yield this.getFee(C.EndPoint.cancelFundsRequest,f),v={account:"fio.reqobt",action:"cancelfndreq",data:{fio_request_id:E,max_fee:m,actor:this.actor}};break}case h.aO.recordObtData:{const{payerFioAddress:f}=(0,y.XB)(p);m=yield this.getFee(C.EndPoint.recordObtData,f);break}case h.aO.requestFunds:{const{payeeFioAddress:f}=(0,y.Vd)(p);m=yield this.getFee(C.EndPoint.newFundsRequest,f);break}default:throw new Error("Unrecognized FIO action")}return{blockHeight:0,currencyCode:n,date:0,isSend:!0,memos:r,nativeAmount:(0,P.sub)(`-${d}`,`${m}`),networkFee:`${m}`,otherParams:H(S({},c),{txParams:v}),ourReceiveAddresses:[],signedTx:"",txid:"",walletId:this.walletId}})}signTx(e,s){return k(this,null,function*(){const t=(0,y.UW)(s),n=(0,b.Xp)(e);let r=(0,u.Vk)(y.B3)(n.txParams);const l=new ae.Transactions;if(r==null){const{name:c,params:g}=(0,y.iR)(n.action),{networkFee:p}=e;switch(c){case h.aO.recordObtData:{const{payerFioAddress:m,payeeFioAddress:v,payerPublicAddress:N,payeePublicAddress:f,amount:E,tokenCode:q,chainCode:A,obtId:L,memo:$,status:M,fioRequestId:K}=(0,y.XB)(g),X={payer_public_address:N,payee_public_address:f,amount:E,chain_code:A,token_code:q,status:M,obt_id:L,memo:$,hash:void 0,offline_url:void 0},re=l.getCipherContent("record_obt_data_content",X,t.fioKey,N);r={account:"fio.reqobt",action:"recordobt",data:{payer_fio_address:m,payee_fio_address:v,content:re,fio_request_id:K,max_fee:p,actor:this.actor}};break}case h.aO.requestFunds:{const{payerFioAddress:m,payerFioPublicKey:v,payeeFioAddress:N,payeeTokenPublicAddress:f,amount:E,chainCode:q,tokenCode:A,memo:L}=(0,y.Vd)(g),$={payee_public_address:f,amount:E,chain_code:q,token_code:A,memo:L,hash:void 0,offline_url:void 0},M=l.getCipherContent("new_funds_content",$,t.fioKey,v);r={account:"fio.reqobt",action:"newfundsreq",data:{payer_fio_address:m,payee_fio_address:N,content:M,max_fee:p,actor:this.actor}};break}default:throw new Error("Unknown FIO action")}}const a=yield l.createRawTransaction({action:r.action,account:r.account,data:H(S({},r.data),{tpid:this.tpid}),publicKey:this.walletInfo.keys.publicKey,chainData:this.refBlock}),{serializedContextFreeData:o,serializedTransaction:i}=yield l.serialize({chainId:this.networkInfo.chainId,transaction:a}),d=yield l.sign({chainId:this.networkInfo.chainId,privateKeys:[t.fioKey],transaction:a,serializedTransaction:i,serializedContextFreeData:o});return e.otherParams=H(S({},e.otherParams),{signedTx:d}),e})}broadcastTx(e){return k(this,null,function*(){var s;const t=(0,b.Xp)(e);if(((s=t.action)==null?void 0:s.name)==null)throw new Error('Action is not set, "action" prop of otherParams is required for FIO actions');const n=(0,y.h0)(t.signedTx),r=(0,y.Yd)(yield this.multicastServers(t.action.name,n));e.metadata={notes:r.transaction_id},e.txid=r.transaction_id,e.date=Date.now()/1e3,e.blockHeight=r.block_num,this.warn(`SUCCESS broadcastTx
2
- ${(0,b.oX)(e)}`);const l=r,{block_num:a,block_time:o,transaction_id:i}=l,d=ge(l,["block_num","block_time","transaction_id"]);return e.otherParams=H(S({},t),{broadcastResult:d}),e})}saveTx(e){return k(this,null,function*(){var s;const t=(0,b.Xp)(e),{broadcastResult:n={},action:r}=t,{name:l,params:a}=(0,y.iR)(r);try{switch(l){case h.aO.transferFioDomain:{const o=this.otherData.fioDomains.findIndex(({name:i})=>i===a.fioDomain);o>=0&&(this.otherData.fioDomains.splice(o,1),this.localDataDirty());break}case h.aO.transferFioAddress:{const o=this.otherData.fioAddresses.findIndex(({name:i})=>i===a.fioAddress);o>=0&&(this.otherData.fioAddresses.splice(o,1),this.localDataDirty());break}case h.aO.registerFioAddress:{const{fioAddress:o}=(0,y.NB)(a);this.otherData.fioAddresses.find(({name:d})=>d===o)==null&&(this.otherData.fioAddresses.push({name:o,bundledTxs:void 0}),this.localDataDirty());break}case h.aO.registerFioDomain:{const{fioDomain:o}=(0,y.AJ)(a);if(n.expiration==null)throw new Error("expiration not present");const i=this.otherData.fioDomains.find(({name:d})=>d===o);i!=null&&(i.expiration=n.expiration,this.localDataDirty());break}case h.aO.renewFioDomain:{const{fioDomain:o}=(0,y.AJ)(a);if(n.expiration==null)throw new Error("expiration not present");const i=this.otherData.fioDomains.find(({name:d})=>d===o);i!=null&&(i.expiration=n.expiration,this.localDataDirty());break}case h.aO.addBundledTransactions:{const{fioAddress:o}=(0,y.Ej)(a),i=this.otherData.fioAddresses.find(({name:d})=>d===o);if(i==null)throw new I.OU("Fio Address is not found in engine");i.bundledTxs=((s=i.bundledTxs)!=null?s:0)+h.BB,this.localDataDirty();break}case h.aO.rejectFundsRequest:{const{fioRequestId:o}=(0,y.OR)(a);typeof o=="string"&&(this.removeFioRequest(o,"PENDING"),this.localDataDirty());break}case h.aO.cancelFundsRequest:{const{fioRequestId:o}=(0,y.mO)(a);typeof o=="string"&&(this.removeFioRequest(o,"SENT"),this.localDataDirty());break}case h.aO.recordObtData:{const{fioRequestId:o}=(0,y.XB)(a);o!=null&&n.status==="sent_to_blockchain"&&(this.removeFioRequest(o,"PENDING"),this.localDataDirty());break}}}catch(o){this.log.warn(`Error attempting post-broadcast action ${l}:`,o)}yield me(ne.prototype,this,"saveTx").call(this,e)})}getFreshAddress(e){return k(this,null,function*(){return{publicAddress:this.walletInfo.keys.publicKey}})}}function ve(_,e,s,t){return k(this,null,function*(){const{tpid:n="finance@edge"}=_.initOptions,r=(0,y.RB)(s),l=new ne(_,e,r,t,n);return yield l.loadEngine(),l})}var we=D(48764).Buffer,F=(_,e,s)=>new Promise((t,n)=>{var r=o=>{try{a(s.next(o))}catch(i){n(i)}},l=o=>{try{a(s.throw(o))}catch(i){n(i)}},a=o=>o.done?t(o.value):Promise.resolve(o.value).then(r,l);a((s=s.apply(_,e)).next())});const le="FIO",ce="fio",Ae="";function de(_){const e=_.startsWith(le),s=_.length===53;return e&&s}class ye{constructor(e){const{builtinTokens:s,currencyInfo:t,initOptions:n,io:r,networkInfo:l}=e;this.builtinTokens=s,this.currencyInfo=t,this.io=r,this.networkInfo=l;const{tpid:a="finance@edge",fioRegApiToken:o=Ae}=n;this.fetchCors=(0,b.zR)(e.io),this.fioRegApiToken=o,this.tpid=a;for(const i of this.networkInfo.apiUrls)new R.rn("","",i,this.fetchCors,void 0,a)}getDisplayPrivateKey(e){return F(this,null,function*(){return(0,y.UW)(e.keys).fioKey})}getDisplayPublicKey(e){return F(this,null,function*(){const{keys:s}=(0,y.RB)(e);return s.publicKey})}importPrivateKey(e){return F(this,null,function*(){const{pluginId:s}=this.currencyInfo,t={};if(/[0-9a-zA-Z]{51}$/.test(e))ue._q.fromString(e),t.fioKey=e;else{if(!(0,ie.validateMnemonic)(e))throw new Error("Invalid input");const r=yield R.rn.createPrivateKeyMnemonic(e);t.fioKey=r.fioKey,t.mnemonic=r.mnemonic}const n=yield this.derivePublicKey({type:`wallet:${s}`,id:"fake",keys:t});return t.publicKey=n.publicKey,t})}createPrivateKey(e){return F(this,null,function*(){if(e.replace("wallet:","")===ce){const t=we.from(this.io.random(32));return yield R.rn.createPrivateKey(t)}else throw new Error("InvalidWalletType")})}derivePublicKey(e){return F(this,null,function*(){if(e.type.replace("wallet:","")===ce)return R.rn.derivedPublicKey(e.keys.fioKey);throw new Error("InvalidWalletType")})}parseUri(e){return F(this,null,function*(){var s;const{edgeParsedUri:t}=(0,ee.k)(this.currencyInfo,e,{fio:!0},le);if(!de((s=t.publicAddress)!=null?s:""))throw new Error("InvalidPublicAddressError");return t})}encodeUri(e){return F(this,arguments,function*(s,t=[]){if(!de(s.publicAddress))throw new Error("InvalidPublicAddressError");let r;if(typeof s.nativeAmount=="string"){const a=le,o=s.nativeAmount,i=(0,b.Qs)(a,this.currencyInfo,t);if(i==null)throw new Error("InternalErrorInvalidCurrencyCode");r=(0,P.div)(o,i.multiplier,16)}return(0,ee.Q)(s,ce,r)})}getConnectedPublicAddress(e,s,t){return F(this,null,function*(){var n;try{R.rn.isFioAddressValid(e)}catch{throw new I.OU("",400,this.networkInfo.errorCodes.INVALID_FIO_ADDRESS)}try{if((yield this.multicastServers("isAvailable",{fioName:e})).is_registered===0)throw new I.OU("",404,this.networkInfo.errorCodes.FIO_ADDRESS_IS_NOT_EXIST)}catch(r){throw r.name==="FioError"&&((n=r.json)==null?void 0:n.fields)!=null&&r.errorCode===400&&(r.labelCode=this.networkInfo.errorCodes.INVALID_FIO_ADDRESS),r}try{const r=yield this.multicastServers("getPublicAddress",{fioAddress:e,chainCode:s,tokenCode:t});if(r.public_address==null||r.public_address==="0")throw new I.OU("",404,this.networkInfo.errorCodes.FIO_ADDRESS_IS_NOT_LINKED);return r}catch(r){throw r.name==="FioError"&&r.labelCode===this.networkInfo.errorCodes.FIO_ADDRESS_IS_NOT_LINKED||r.errorCode===404?new I.OU("",404,this.networkInfo.errorCodes.FIO_ADDRESS_IS_NOT_LINKED):r}})}isFioAddressValid(e){return F(this,null,function*(){try{return R.rn.isFioAddressValid(e)}catch{return!1}})}validateAccount(e,s=!1){return F(this,null,function*(){var t;try{if(s){if(!R.rn.isFioDomainValid(e))return!1}else if(!R.rn.isFioAddressValid(e))return!1}catch{throw new I.OU("",400,this.networkInfo.errorCodes.INVALID_FIO_ADDRESS)}try{return(yield this.multicastServers("isAvailable",{fioName:e})).is_registered===0}catch(n){throw n.name==="FioError"&&((t=n.json)==null?void 0:t.fields)!=null&&n.errorCode===400&&(n.labelCode=this.networkInfo.errorCodes.INVALID_FIO_ADDRESS),n}})}isDomainPublic(e){return F(this,null,function*(){if((yield this.multicastServers("isAvailable",{fioName:e})).is_registered===0)throw new I.OU("",400,this.networkInfo.errorCodes.FIO_DOMAIN_IS_NOT_EXIST);const t=yield this.fetchCors(`${this.networkInfo.fioRegApiUrl}${h.n3.isDomainPublic}/${e}`,{method:"GET"});if(!t.ok){const r=yield t.json();throw new I.OU("",t.status,this.networkInfo.errorCodes.IS_DOMAIN_PUBLIC_ERROR,r)}const{isPublic:n}=yield t.json();return n})}doesAccountExist(e){return F(this,null,function*(){try{if(!R.rn.isFioAddressValid(e))return!1}catch{return!1}try{return(yield this.multicastServers("isAvailable",{fioName:e})).is_registered===1}catch(s){return this.error("doesAccountExist error: ",s),!1}})}buyAddressRequest(e,s=!1){return F(this,null,function*(){const t={Accept:"application/json","Content-Type":"application/json"};s&&(e.apiToken=this.fioRegApiToken);try{const n=yield this.fetchCors(`${this.networkInfo.fioRegApiUrl}${h.n3.buyAddress}`,{method:"POST",headers:t,body:JSON.stringify(e)});if(!n.ok){const r=yield n.json();throw this.networkInfo.errorCodes[r.errorCode]!=null?new I.OU(r.error,n.status,this.networkInfo.errorCodes[r.errorCode],r):r.error==="Already registered"?new I.OU(r.error,n.status,this.networkInfo.errorCodes.ALREADY_REGISTERED,r):new Error(r.error)}return yield n.json()}catch(n){throw n.labelCode!=null?n:new I.OU((0,b.HY)(n),500,this.networkInfo.errorCodes.SERVER_ERROR)}})}getDomains(e=""){return F(this,null,function*(){e==null&&(e=this.networkInfo.defaultRef);try{const s=yield this.fetchCors(`${this.networkInfo.fioRegApiUrl}${h.n3.getDomains}/${e}`,{method:"GET"}),t=yield s.json();if(!s.ok)throw this.networkInfo.errorCodes[t.errorCode]!=null?new I.OU(t.error,s.status,this.networkInfo.errorCodes[t.errorCode],t):new Error(t.error);return t.domains}catch(s){throw s.labelCode!=null?s:new I.OU((0,b.HY)(s),500,this.networkInfo.errorCodes.SERVER_ERROR)}})}getStakeEstReturn(){return F(this,null,function*(){try{const e=yield this.fetchCors(`${this.networkInfo.fioStakingApyUrl}`,{method:"GET"}),s=yield e.json();if(!e.ok)throw new Error(this.networkInfo.errorCodes.SERVER_ERROR);const t=s.historical_apr["7day"];return t!=null&&t>h.OT||t==null?h.OT:t}catch(e){throw e.labelCode!=null?e:new I.OU(e.message,500,this.networkInfo.errorCodes.SERVER_ERROR)}})}multicastServers(e,s){return F(this,null,function*(){const t=yield(0,b.QJ)((0,b.Sy)(this.networkInfo.apiUrls.map(n=>()=>F(this,null,function*(){let r;const l=new R.rn("","",n,this.fetchCors,void 0,this.tpid);try{r=yield l.genericAction(e,s)}catch(a){if(a.errorCode!=null&&I.lI.includes(a.errorCode))r={isError:!0,data:{code:a.errorCode,message:(0,b.HY)(a),json:a.json,list:a.list}};else throw a}return r}))));if(t.isError!=null){const n=new I.OU(t.errorMessage);throw n.json=t.data.json,n.list=t.data.list,n.errorCode=t.data.code,n}return t})}}function Ie(_){return F(this,null,function*(){return new ye(_)})}},89214:function(){},52361:function(){},94616:function(){}}]);
1
+ (self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[2805],{79014:function(pe,Q,D){"use strict";D.d(Q,{Q:function(){return z},k:function(){return u}});var R=D(77591),ue=D.n(R),P=D(24350),ie=D(84564),ee=D.n(ie),b=D(76714),h=Object.defineProperty,I=Object.getOwnPropertySymbols,p=Object.prototype.hasOwnProperty,C=Object.prototype.propertyIsEnumerable,V=(w,x,T)=>x in w?h(w,x,{enumerable:!0,configurable:!0,writable:!0,value:T}):w[x]=T,ae=(w,x)=>{for(var T in x||(x={}))p.call(x,T)&&V(w,T,x[T]);if(I)for(var T of I(x))C.call(x,T)&&V(w,T,x[T]);return w};function u(w,x,T,B,G=[]){const O=ae({},ee()(x,{},!0)),W=x.startsWith(`${w.pluginId}://`);if(O.protocol!=null&&(O.protocol=O.protocol.replace(":","")),O.protocol!=null&&O.protocol!==""&&!T[O.protocol])throw new Error(`Uri protocol '${O.protocol}' is not supported for ${w.pluginId}.`);if(O.host===""&&O.pathname==="")throw new Error("Path and host not found in uri.");const U={publicAddress:O.host!==""?O.host:O.pathname.split("/")[0]},te=O.query.label,j=O.query.message,se=O.query.category;(te!=null||j!=null||se!=null||W)&&(U.metadata={},U.metadata.name=te,U.metadata.notes=j,U.metadata.category=se,U.metadata.gateway=W!=null?W:!1);const J=O.query.amount;if(J!=null&&typeof J=="string"){B==null&&(B=w.currencyCode);const Y=(0,b.Qs)(B!=null?B:"",w,G);if(Y==null)throw new Error("InternalErrorInvalidCurrencyCode");let Z=(0,R.mul)(J,Y.multiplier);Z=(0,R.toFixed)(Z,0,0),U.nativeAmount=Z,U.currencyCode=B}return{edgeParsedUri:U,parsedUri:O}}function z(w,x,T){if(w.publicAddress==null)throw new Error("InvalidPublicAddressError");if(T==null&&w.label==null&&w.message==null)return w.publicAddress;{let B="";T!=null&&(B+="amount="+T+"&"),(w.label!=null||w.message!=null)&&(typeof w.label=="string"&&(B+="label="+w.label+"&"),typeof w.message=="string"&&(B+="message="+w.message+"&")),B=B.substr(0,B.length-1);const G={scheme:x,path:w.publicAddress,query:B};return(0,P.qC)(G)}}},44285:function(pe,Q,D){"use strict";D.r(Q),D.d(Q,{FioTools:function(){return ye},checkAddress:function(){return de},makeCurrencyEngine:function(){return ve},makeCurrencyTools:function(){return Ie}});var R=D(93491),ue=D(45234),P=D(77591),ie=D(2153),ee=D(79014),b=D(76714),h=D(5607),I=D(24827),p=D(3559),C=D(37858),V=D(82626),ae=D(37297),u=D(82448),z=D(94935),w=D(84650),x=D(72681);const T=(0,u.su)({fio_domains:(0,u._2)((0,u.su)({fio_domain:u.XC,expiration:u.XC,is_public:u.mH})),fio_addresses:(0,u._2)((0,u.su)({fio_address:u.XC,remaining_bundled_tx:u.mH}))}),B=(0,u.Vk)((0,u.Wf)("unstakefio","transfer","regaddress","trnsfiopubky"),null),G=(0,u.su)({account_action_seq:u.mH,block_num:u.mH,block_time:u.XC,action_trace:(0,u.su)({receiver:u.XC,act:(0,u.su)({account:u.XC,name:B,authorization:(0,u._2)((0,u.su)({actor:u.XC,permission:u.XC})),data:(0,u.su)({payee_public_key:(0,u.Zz)(u.XC),amount:(0,u.Zz)(u.mH),max_fee:(0,u.Zz)(u.mH),actor:(0,u.Zz)(u.XC),tpid:(0,u.Zz)(u.XC),quantity:(0,u.Zz)(u.XC),memo:(0,u.Zz)(u.XC),to:(0,u.Zz)(u.XC),from:(0,u.Zz)(u.XC)}),hex_data:u.XC}),trx_id:u.XC,block_num:u.mH,block_time:u.XC,producer_block_id:u.XC})}),O=(0,u.su)({actions:(0,u._2)(G)}),W=(0,u.su)({balance:u.mH,available:u.mH,staked:u.mH,srps:u.mH,roe:u.XC});var he=Object.defineProperty,U=Object.defineProperties,te=Object.getOwnPropertyDescriptors,j=Object.getOwnPropertySymbols,se=Object.getPrototypeOf,J=Object.prototype.hasOwnProperty,Y=Object.prototype.propertyIsEnumerable,Z=Reflect.get,fe=(_,e,s)=>e in _?he(_,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):_[e]=s,S=(_,e)=>{for(var s in e||(e={}))J.call(e,s)&&fe(_,s,e[s]);if(j)for(var s of j(e))Y.call(e,s)&&fe(_,s,e[s]);return _},H=(_,e)=>U(_,te(e)),ge=(_,e)=>{var s={};for(var t in _)J.call(_,t)&&e.indexOf(t)<0&&(s[t]=_[t]);if(_!=null&&j)for(var t of j(_))e.indexOf(t)<0&&Y.call(_,t)&&(s[t]=_[t]);return s},me=(_,e,s)=>Z(se(_),s,e),k=(_,e,s)=>new Promise((t,n)=>{var r=o=>{try{a(s.next(o))}catch(i){n(i)}},l=o=>{try{a(s.throw(o))}catch(i){n(i)}},a=o=>o.done?t(o.value):Promise.resolve(o.value).then(r,l);a((s=s.apply(_,e)).next())});const ke=1e4,_e=15e3,be=1e4,De=1e4;class ne extends w.P{constructor(e,s,t,n,r){super(e,s,t,n),this.fioRequestsListChanged=(l,a)=>{function o(i,d){for(const c of i)if(d.findIndex(g=>g.fio_request_id===c.fio_request_id)<0)return!0;return!1}return!!(o(l,a)||o(a,l))},this.removeFioRequest=(l,a)=>{const o=this.otherData.fioRequests[a].findIndex(i=>i.fio_request_id===`${l}`);o>-1&&this.otherData.fioRequests[a].splice(o,1)},this.fetchCors=(0,b.zR)(e.io),this.tpid=r,this.networkInfo=e.networkInfo,this.refBlock={expiration:"",ref_block_num:0,ref_block_prefix:0},this.fees=new Map,this.actor=R.rn.accountHash(this.walletInfo.keys.publicKey).accountnm,this.obtData=[],this.otherMethods={fioAction:(l,a)=>k(this,null,function*(){return yield this.multicastServers(l,a)}),getFioAddresses:()=>k(this,null,function*(){return this.otherData.fioAddresses}),getFioAddressNames:()=>k(this,null,function*(){return this.otherData.fioAddresses.map(l=>l.name)}),getFioDomains:()=>k(this,null,function*(){return this.otherData.fioDomains}),getFioRequests:(l,a,o=50)=>k(this,null,function*(){const i=o*(a-1),d=o*a;return this.otherData.fioRequests[l].sort((c,g)=>c.time_stamp<g.time_stamp?1:-1).slice(i,d)}),getObtData:()=>k(this,null,function*(){return this.obtData})}}localDataDirty(){this.walletLocalDataDirty=!0}setOtherData(e){this.otherData=(0,h.CL)(e)}getUTCDate(e){const s=new Date(e);return Date.UTC(s.getFullYear(),s.getMonth(),s.getDate(),s.getHours(),s.getMinutes(),s.getSeconds())}getUnlockDate(e){const s=Math.floor(e.getTime()/h.qj)*h.qj;return new Date(s+h.dm)}checkBlockchainInnerLoop(){return k(this,null,function*(){try{const e=yield this.multicastServers("getChainInfo"),s=e.head_block_num;this.walletLocalData.blockHeight!==s&&(this.checkDroppedTransactionsThrottled(),this.walletLocalData.blockHeight=s,this.localDataDirty(),this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight));const t=yield this.multicastServers("getBlock",e),n=new Date(`${e.head_block_time}Z`);n.setSeconds(n.getSeconds()+180);const r=n.toISOString();this.refBlock={expiration:r.substring(0,r.length-1),ref_block_num:t.block_num&65535,ref_block_prefix:t.ref_block_prefix}}catch(e){this.error("checkBlockchainInnerLoop Error fetching height: ",e)}})}getBalance(e){return super.getBalance(e)}doInitialBalanceCallback(){super.doInitialBalanceCallback();try{this.currencyEngineCallbacks.onStakingStatusChanged(S({},this.otherData.stakingStatus))}catch(e){this.error("doInitialBalanceCallback onStakingStatusChanged",e)}}checkUnStakeTx(e){return e.name==="unstakefio"||e.data!=null&&e.data.memo===h.Nd}updateStakingStatus(e){if(this.otherData.stakingStatus.stakedAmounts[0]={nativeAmount:this.otherData.lockedBalances.locked,unlockDate:void 0,otherParams:{type:"LOCKED"}},this.otherData.stakingStatus.stakedAmounts[1]={nativeAmount:this.otherData.lockedBalances.staked,unlockDate:void 0,otherParams:{type:"STAKED"}},e!=null){const{nativeAmount:s,blockTime:t,txId:n,txName:r}=e,l=this.getUnlockDate(new Date(this.getUTCDate(t))),a=this.otherData.stakingStatus.stakedAmounts.findIndex(o=>{var i;return((i=o.unlockDate)==null?void 0:i.getTime())===l.getTime()});if(a<0){const o=this.otherData.stakingStatus.stakedAmounts.findIndex(d=>{var c,g;return l.getTime()>=((g=(c=d.unlockDate)==null?void 0:c.getTime())!=null?g:1/0)}),i=o<0?this.otherData.stakingStatus.stakedAmounts.length:o;this.otherData.stakingStatus.stakedAmounts.splice(i,0,{nativeAmount:s,unlockDate:l,otherParams:{date:new Date(t),txs:[{txId:n,nativeAmount:s,blockTime:t,txName:r}]}})}else{const o=H(S({},this.otherData.stakingStatus.stakedAmounts[a]),{nativeAmount:"0"}),i=o.otherParams.txs.findIndex(({txId:d,txName:c})=>d===n&&c===r);i<0?o.otherParams.txs.push({txId:n,nativeAmount:s,blockTime:t,txName:r}):o.otherParams.txs[i]={txId:n,nativeAmount:s,blockTime:t,txName:r};for(const d of o.otherParams.txs)o.nativeAmount=(0,P.add)(o.nativeAmount,d.nativeAmount);this.otherData.stakingStatus.stakedAmounts[a]=o}}this.localDataDirty();try{this.currencyEngineCallbacks.onStakingStatusChanged(S({},this.otherData.stakingStatus))}catch{this.error("onStakingStatusChanged error")}}getStakingStatus(){return k(this,null,function*(){return S({},this.otherData.stakingStatus)})}processTransaction(e,s,t=this.currencyInfo.currencyCode){var n,r,l,a,o,i,d,c,g;const{act:{name:y,data:m,account:v,authorization:N}}=e.action_trace;let f,E,q="0",A={account:v,name:y,authorization:N,data:m,meta:{}};const L=[];if(e.block_num<=this.otherData.highestTxHeight)return e.block_num;if(y==="trnsfiopubky"||y==="unstakefio"||y==="regaddress"){f="0",y==="regaddress"&&e.action_trace.act.authorization.some(K=>K.actor===this.actor)&&(q=String((n=e.action_trace.act.data.max_fee)!=null?n:0),f=`-${q}`),y==="trnsfiopubky"&&m.amount!=null&&(f=m.amount.toString(),E=m.actor,m.payee_public_key===this.walletInfo.keys.publicKey?(L.push(this.walletInfo.keys.publicKey),E===s&&(f="0")):f=`-${f}`);const $=this.findTransaction(t,e.action_trace.trx_id);if($>-1){const K=this.transactionList[t][$];if(A=H(S(S({},K.otherParams),A),{data:S(S({},(l=(r=K.otherParams)==null?void 0:r.data)!=null?l:{}),A.data),meta:S(S({},(o=(a=K.otherParams)==null?void 0:a.meta)!=null?o:{}),A.meta)}),A.meta.isTransferProcessed!=null)return e.block_num;A.meta.isFeeProcessed!=null?y===h.BP[h.aO.transferTokens]?(f=(0,P.sub)(f,K.networkFee),q=K.networkFee):(f=K.nativeAmount,q="0"):this.error("processTransaction error - existing spend transaction should have isTransferProcessed or isFeeProcessed set")}this.checkUnStakeTx(A)&&this.updateStakingStatus({nativeAmount:m.amount!=null?m.amount.toString():"0",blockTime:e.block_time,txId:e.action_trace.trx_id,txName:y}),A.meta.isTransferProcessed=!0;const M={blockHeight:e.block_num>0?e.block_num:0,currencyCode:t,date:this.getUTCDate(e.block_time)/1e3,isSend:f.startsWith("-"),memos:[],nativeAmount:f,networkFee:q,otherParams:A,ourReceiveAddresses:L,signedTx:"",txid:e.action_trace.trx_id,walletId:this.walletId};this.addTransaction(t,M)}if(y==="transfer"&&m.quantity!=null){const[$]=m.quantity.split(" "),M=$.toString(),K=(0,b.aL)(t,this.currencyInfo,this.allTokensMap);if(K==null)return this.error(`Received unsupported currencyCode: ${t}`),0;const X=(0,P.mul)(M,K.multiplier);m.to===s?(f=`${X}`,q=`-${X}`):(f=`-${X}`,q=X);const re=this.findTransaction(t,e.action_trace.trx_id);if(re>-1){const oe=this.transactionList[t][re];if(A=H(S(S({},A),oe.otherParams),{data:S(S({},A.data),(d=(i=oe.otherParams)==null?void 0:i.data)!=null?d:{}),meta:S(S({},A.meta),(g=(c=oe.otherParams)==null?void 0:c.meta)!=null?g:{})}),A.meta.isFeeProcessed!=null)return e.block_num;A.meta.isTransferProcessed!=null?m.to!==s?f=(0,P.sub)(oe.nativeAmount,q):q="0":this.error("processTransaction error - existing spend transaction should have isTransferProcessed or isFeeProcessed set")}this.checkUnStakeTx(A)&&this.updateStakingStatus({nativeAmount:X,blockTime:e.block_time,txId:e.action_trace.trx_id,txName:y}),A.meta.isFeeProcessed=!0;const Pe={blockHeight:e.block_num>0?e.block_num:0,currencyCode:t,date:this.getUTCDate(e.block_time)/1e3,isSend:f.startsWith("-"),memos:[],nativeAmount:f,networkFee:q,otherParams:A,ourReceiveAddresses:[],signedTx:"",txid:e.action_trace.trx_id,walletId:this.walletId};this.addTransaction(t,Pe)}return e.block_num}getSortedHistoryNodesLastActionSeqNumbers(){return k(this,null,function*(){const e=this.networkInfo.historyNodeUrls.map((t,n)=>k(this,null,function*(){var r;try{const l=yield this.requestHistory(n,{account_name:this.actor,pos:-1},h.pg.getActions);return((r=l==null?void 0:l.error)==null?void 0:r.noNodeForIndex)!=null?{nodeIndex:n,seqNumber:-1}:(O(l),l.actions.length===0?{nodeIndex:n,seqNumber:-1}:{nodeIndex:n,seqNumber:l.actions[l.actions.length-1].account_action_seq})}catch{return{nodeIndex:n,seqNumber:-1}}})),s=yield Promise.all(e);return s.sort((t,n)=>n.seqNumber-t.seqNumber),s})}checkTransactions(e){return k(this,null,function*(){var s,t;if((e==null?void 0:e.length)===0)return!1;if(e=e!=null?e:yield this.getSortedHistoryNodesLastActionSeqNumbers(),e.reduce((i,d)=>i+d.seqNumber,0)===-e.length)return!0;let n=this.otherData.highestTxHeight;const r=e[0].seqNumber,l=e[0].nodeIndex;let a=Math.max(0,r-h.WX+1),o=!1;for(;!o;){let i;try{if(i=yield this.requestHistory(l,{account_name:this.actor,pos:a,offset:h.WX-1},h.pg.getActions),((s=i.error)==null?void 0:s.noNodeForIndex)!=null)return!1;let d=[];if(((t=i.actions)==null?void 0:t.length)>0)d=i.actions;else break;for(let c=d.length-1;c>-1;c--){const g=G(d[c]),y=this.processTransaction(g,this.actor);if(y>n)n=y;else if(y===n&&c===h.WX-1||y<this.otherData.highestTxHeight){o=!0;break}}if(a===0)break;a=Math.max(0,a-h.WX);continue}catch{return yield this.checkTransactions(e.slice(1))}}return n>this.otherData.highestTxHeight&&(this.otherData.highestTxHeight=n,this.localDataDirty()),!0})}checkTransactionsInnerLoop(){return k(this,null,function*(){let e;try{e=yield this.checkTransactions()}catch(s){this.error("checkTransactionsInnerLoop fetches failed with error: ",s);return}e&&(this.tokenCheckTransactionsStatus.FIO=1,this.updateOnAddressesChecked()),this.transactionsChangedArray.length>0&&(this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[])})}requestHistory(e,s,t){return k(this,null,function*(){if(this.networkInfo.historyNodeUrls[e]==null)return{error:{noNodeForIndex:!0}};const n=this.networkInfo.historyNodeUrls[e],r=JSON.stringify(s);return yield(yield fetch(`${n}history/${t}`,{method:"POST",headers:{"Content-Length":(r.length*2).toString(),Accept:"application/json","Content-Type":"application/json"},body:r})).json()})}fioApiRequest(e,s,t,n=!1){return k(this,null,function*(){var r,l,a,o;const i=new R.rn("",this.walletInfo.keys.publicKey,e,this.fetchCors,void 0,this.tpid,n);let d;try{switch(s){case"getChainInfo":d=yield i.transactions.getChainInfo();break;case"getBlock":d=yield i.transactions.getBlock(t);break;case"getObtData":case"getPendingFioRequests":case"getSentFioRequests":{const{endpoint:c,body:g}=t;d=yield i.transactions.executeCall(c,JSON.stringify(g));break}case"getCurrencyBalance":{d=yield(yield this.fetchCors(`${e}chain/get_currency_balance`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(t)})).json();break}default:d=yield i.genericAction(s,t)}}catch(c){if(c.errorCode!=null&&I.lI.includes(c.errorCode))((a=(l=(r=c.json)==null?void 0:r.fields)==null?void 0:l[0])==null?void 0:a.error)!=null&&(c.message=c.json.fields[0].error),d={isError:!0,data:{code:c.errorCode,message:(o=c.message)!=null?o:(0,b.HY)(c),json:c.json,list:c.list}},c.errorCode!==404&&this.log(`fioApiRequest error. actionName: ${s} - apiUrl: ${e} - message: ${JSON.stringify(c.json)}`);else throw this.log(`fioApiRequest error. actionName: ${s} - apiUrl: ${e} - message: `,c),c}return d})}executePreparedTrx(e,s,t){return k(this,null,function*(){var n,r,l;const a=new R.rn("",this.walletInfo.keys.publicKey,e,this.fetchCors,void 0,this.tpid,!0);let o;this.warn(`executePreparedTrx. preparedTrx: ${JSON.stringify(t)} - apiUrl: ${e}`);try{o=yield a.executePreparedTrx(s,t),this.warn(`executePreparedTrx. res: ${JSON.stringify(o)} - apiUrl: ${e} - endpoint: ${s}`)}catch(i){throw i.errorCode!=null&&I.lI.includes(i.errorCode)?(this.log(`executePreparedTrx error. requestParams: ${JSON.stringify(t)} - apiUrl: ${e} - endpoint: ${s} - message: ${JSON.stringify(i.json)}`),((l=(r=(n=i.json)==null?void 0:n.fields)==null?void 0:r[0])==null?void 0:l.error)!=null&&(i.message=i.json.fields[0].error),i):(this.log(`executePreparedTrx error. requestParams: ${JSON.stringify(t)} - apiUrl: ${e} - endpoint: ${s} - message: `,i),i)}return o})}multicastServers(e,s){return k(this,null,function*(){var t,n,r,l,a,o,i,d;let c;if(h.K1[e]){const g=(0,p.h0)(s);if(this.warn(`multicastServers executePreparedTrx. actionName: ${e} - res: ${JSON.stringify(g)}`),c=yield(0,b.Wp)((0,b.Sy)(this.networkInfo.apiUrls.map(y=>k(this,null,function*(){return yield(0,b.Vs)(this.executePreparedTrx(y,C.EndPoint[h.VW[e]],g),1e4)})))),this.warn(`multicastServers res. actionName: ${e} - res: ${JSON.stringify(c)}`),c==null)throw new Error("Service is unavailable")}else if(e==="getFioNames")c=yield(0,b.ml)(this.networkInfo.apiUrls.map(g=>k(this,null,function*(){return yield(0,b.Vs)(this.fioApiRequest(g,e,s),1e4)})),g=>{const y=(0,p.$K)(h.Mi)(g);return y!=null?y.data.json.message:(0,p.e1)(g)},2),((n=(t=c==null?void 0:c.data)==null?void 0:t.json)==null?void 0:n.message)===h.Mi&&(c={fio_domains:[],fio_addresses:[]});else if(e==="getCurrencyBalance"){c=yield(0,b.ml)(this.networkInfo.apiUrls.map(v=>k(this,null,function*(){return yield(0,b.Vs)(this.fioApiRequest(v,"getCurrencyBalance",{code:"fio.token",account:this.actor,symbol:"FIO"}),1e4)})),v=>JSON.stringify(v),2),((l=(r=c==null?void 0:c.data)==null?void 0:r.json)==null?void 0:l.message)===h.d9&&(c={balance:0,available:0,staked:0,srps:0,roe:""});const y=(0,u.vq)(u.XC)(c)[0].split(" ")[0],m=(0,P.mul)(y,(a=this.currencyInfo.denominations[0].multiplier)!=null?a:"1000000000");c={balance:parseInt(m),available:0,staked:0,srps:0,roe:"0"}}else e==="getFioBalance"?(c=yield(0,b.ml)(this.networkInfo.apiUrls.map(g=>k(this,null,function*(){return yield(0,b.Vs)(this.fioApiRequest(g,e,s),1e4)})),g=>{const y=(0,p.$K)(h.d9)(g);return y!=null?y.data.json.message:(0,p.sq)(g)},2),((i=(o=c==null?void 0:c.data)==null?void 0:o.json)==null?void 0:i.message)===h.d9&&(c={balance:0,available:0,staked:0,srps:0,roe:""})):e==="getFees"?c=yield(0,b.QJ)((0,b.Sy)(this.networkInfo.apiUrls.map(g=>()=>k(this,null,function*(){const y=new R.rn("",this.walletInfo.keys.publicKey,g,this.fetchCors,void 0,this.tpid),{endpoint:m,param:v}=s,N=yield y.getFee(m,v);return(0,p.lZ)(N).fee.toString()})))):c=yield(0,b.QJ)((0,b.Sy)(this.networkInfo.apiUrls.map(g=>()=>k(this,null,function*(){return yield this.fioApiRequest(g,e,s)}))));if(c.isError!=null){const g=new I.OU((d=c.errorMessage)!=null?d:c.data.message);throw g.json=c.data.json,g.list=c.data.list,g.errorCode=c.data.code,g}return c})}checkAccountInnerLoop(){return k(this,null,function*(){var e;const s=this.currencyInfo.currencyCode;typeof this.walletLocalData.totalBalances[s]>"u"&&this.updateBalance(s,"0");try{const t={staked:"0",locked:"0"};let n;try{n=W(yield this.multicastServers("getFioBalance"))}catch(c){if(((e=c==null?void 0:c.json)==null?void 0:e.message)===h.kE)n=W(yield this.multicastServers("getCurrencyBalance")),this.log.warn("Returning FIO balance only due to chain bug");else throw c}const{balance:r,available:l,staked:a,srps:o,roe:i}=n,d=String(r);t.staked=String(a),t.locked=(0,P.sub)(d,String(l)),this.otherData.srps=o,this.otherData.stakingRoe=i,this.updateBalance(s,d),(t.staked!==this.otherData.lockedBalances.staked||t.locked!==this.otherData.lockedBalances.locked)&&(this.otherData.lockedBalances=t,this.localDataDirty(),this.updateStakingStatus())}catch(t){this.log.warn("checkAccountInnerLoop getFioBalance error: ",t)}try{const t=T(yield this.multicastServers("getFioNames",{fioPublicKey:this.walletInfo.keys.publicKey}));let n=!1,r=!1,l=!1;if(t.fio_addresses.length!==this.otherData.fioAddresses.length)r=!0;else{for(const a of t.fio_addresses){const o=this.otherData.fioAddresses.find(i=>i.name===a.fio_address);if(o!=null){if(o.bundledTxs!==a.remaining_bundled_tx){r=!0;break}}else{r=!0;break}}if(!r){for(const a of this.otherData.fioAddresses)if(t.fio_addresses.findIndex(o=>o.fio_address===a.name)<0){r=!0;break}}}if(t.fio_domains.length!==this.otherData.fioDomains.length)l=!0;else{for(const a of t.fio_domains){const o=this.otherData.fioDomains.find(i=>i.name===a.fio_domain);if(o!=null){if(o.expiration!==a.expiration){l=!0;break}if(o.isPublic!==(a.is_public===1)){l=!0;break}}else{l=!0;break}}if(!l){for(const a of this.otherData.fioDomains)if(t.fio_domains.findIndex(o=>o.fio_domain===a.name)<0){l=!0;break}}}r&&(n=!0,this.otherData.fioAddresses=t.fio_addresses.map(a=>({name:a.fio_address,bundledTxs:a.remaining_bundled_tx}))),l&&(n=!0,this.otherData.fioDomains=t.fio_domains.map(a=>({name:a.fio_domain,expiration:a.expiration,isPublic:a.is_public===1}))),n&&this.localDataDirty()}catch(t){this.warn("checkAccountInnerLoop getFioNames error: ",t)}})}fetchEncryptedFioRequests(e,s){return k(this,null,function*(){const n=e==="PENDING"?"getPendingFioRequests":"getSentFioRequests";let r=100,l=1;const a=[];for(;r===100;)try{const o=yield this.multicastServers(n,{endpoint:s.getEndPoint(),body:{fio_public_key:this.walletInfo.keys.publicKey,limit:100,offset:(l-1)*100}}),i=(0,p.S_)(o),{requests:d,more:c}=i;if(a.push(...d),c===0)break;l++,r=d.length}catch(o){const i=(0,u.Vk)(p.Pq)(o.json);(i==null?void 0:i.message)!=="No FIO Requests"&&this.error("fetchEncryptedFioRequests error: ",o);break}return a})}fetchEncryptedObtData(e,s){return k(this,null,function*(){let n=100,r=1;const l=[];for(;n===100;){let a;try{a=yield this.multicastServers(e,{endpoint:s.getEndPoint(),body:{fio_public_key:this.walletInfo.keys.publicKey,limit:100,offset:(r-1)*100}});const o=(0,p._v)(a),{obt_data_records:i,more:d}=o;if(l.push(...i),d===0)break;r++,n=i.length}catch(o){const i=(0,u.Vk)(p.Pq)(o.json);(i==null?void 0:i.message)!=="No FIO Requests"&&this.error("fetchEncryptedObtData error: ",o);break}}return l})}syncNetwork(e){return k(this,null,function*(){var s;const t=(0,p.UW)(e==null?void 0:e.privateKeys);let n=!1;const r=(i,d)=>k(this,null,function*(){var c;const g=yield this.fetchEncryptedFioRequests(i,d);d.privateKey=t.fioKey,d.publicKey=this.walletInfo.keys.publicKey;const y=(c=d.decrypt({requests:g}))!=null?c:{requests:[]};this.fioRequestsListChanged(this.otherData.fioRequests[i],y.requests)&&(this.otherData.fioRequests[i]=[...y.requests],n=!0)});yield r("PENDING",new V.PendingFioRequests(this.walletInfo.keys.publicKey)),yield r("SENT",new V.SentFioRequests(this.walletInfo.keys.publicKey)),n&&this.localDataDirty();const l=new V.GetObtData(this.walletInfo.keys.publicKey),a=yield this.fetchEncryptedObtData("getObtData",l);l.privateKey=t.fioKey,l.publicKey=this.walletInfo.keys.publicKey;const o=(s=l.decrypt({obt_data_records:a}))!=null?s:{obt_data_records:[]};return this.obtData=o.obt_data_records,De})}getFee(e,s){return k(this,null,function*(){let t=this.fees.get(e);if(t==null||t.expiration+30*1e3<Date.now()){const r={fee:yield this.multicastServers("getFees",{endpoint:e,param:s}),expiration:Date.now()};this.fees.set(e,r),t=r}return t.fee})}startEngine(){return k(this,null,function*(){this.engineOn=!0,this.addToLoop("checkBlockchainInnerLoop",_e).catch(()=>{}),this.addToLoop("checkAccountInnerLoop",ke).catch(()=>{}),this.addToLoop("checkTransactionsInnerLoop",be).catch(()=>{}),yield me(ne.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return k(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getMaxSpendable(e){return k(this,null,function*(){e=(0,x.s)(e,this.currencyInfo);const s=this.getBalance({currencyCode:e.currencyCode}),t=this.otherData.lockedBalances.locked;e.spendTargets[0].nativeAmount="1";const n=yield this.makeSpend(e),r=(0,P.sub)((0,P.sub)(s,n.networkFee),t);if((0,P.lt)(r,"0"))throw new z.C_({networkFee:n.networkFee});return r})}makeSpend(e){return k(this,null,function*(){e=(0,x.s)(e,this.currencyInfo);const{edgeSpendInfo:s,nativeBalance:t,currencyCode:n}=this.makeSpendCheck(e),{memos:r=[]}=s,l=this.otherData.lockedBalances.locked,a=(0,P.sub)(t,l),o=s.spendTargets[0],{publicAddress:i}=o,{nativeAmount:d}=o;if(i==null)throw new Error("makeSpend Missing publicAddress");if(d==null)throw new z.$D;let{otherParams:c}=s;(c==null||Object.keys(c).length===0)&&(c={action:{name:h.aO.transferTokens,params:{payeeFioPublicKey:i,amount:d,maxFee:0}}});const{name:g,params:y}=(0,p.iR)(c.action);let m,v;switch(g){case h.aO.transferTokens:{m=yield this.getFee(C.EndPoint.transferTokens),v={account:"fio.token",action:h.BP[h.aO.transferTokens],data:{payee_public_key:i,amount:d,max_fee:m}};break}case h.aO.stakeFioTokens:{const{fioAddress:f}=(0,p.NB)(y);m=yield this.getFee(C.EndPoint.stakeFioTokens,f),v={account:"fio.staking",action:h.BP[g],data:{amount:d,fio_address:f,actor:this.actor,max_fee:m}};break}case h.aO.unStakeFioTokens:{const{fioAddress:f}=(0,p.NB)(y);m=yield this.getFee(C.EndPoint.unStakeFioTokens,f),v={account:"fio.staking",action:h.BP[g],data:{amount:d,fio_address:f,actor:this.actor,max_fee:m}};const E=this.getUnlockDate(new Date),q=this.otherData.lockedBalances.staked;if((0,P.gt)(d,q)||(0,P.gt)(`${m}`,a))throw new z.C_;const A=(0,P.mul)((0,P.mul)((0,P.div)(d,q,18),`${this.otherData.srps}`),this.otherData.stakingRoe),L=(0,P.max)((0,P.sub)(A,d),"0");c.ui={accrued:A,estReward:L,unlockDate:E};break}case h.aO.transferFioAddress:{const{fioAddress:f}=(0,p.NB)(y);m=yield this.getFee(C.EndPoint.transferFioAddress,f),v={account:"fio.address",action:"xferaddress",data:{fio_address:f,new_owner_fio_public_key:i,actor:this.actor,max_fee:m}};break}case h.aO.transferFioDomain:{const{fioDomain:f}=(0,p.L2)(y);m=yield this.getFee(C.EndPoint.transferFioDomain),v={account:"fio.address",action:"xferdomain",data:{fio_domain:f,new_owner_fio_public_key:i,actor:this.actor,max_fee:m}};break}case h.aO.addPublicAddresses:{const{fioAddress:f,publicAddresses:E}=(0,p.PH)(y);m=yield this.getFee(C.EndPoint.addPubAddress,f),v={account:"fio.address",action:"addaddress",data:{fio_address:f,public_addresses:E,actor:this.actor,max_fee:m}};break}case h.aO.removePublicAddresses:{const{fioAddress:f,publicAddresses:E}=(0,p.PH)(y);m=yield this.getFee(C.EndPoint.removePubAddress,f),v={account:"fio.address",action:"remaddress",data:{fio_address:f,public_addresses:E,actor:this.actor,max_fee:m}};break}case h.aO.registerFioAddress:{const{fioAddress:f}=(0,p.NB)(y);m=yield this.getFee(C.EndPoint.registerFioAddress),v={account:"fio.address",action:"regaddress",data:{fio_address:f,owner_fio_public_key:this.walletInfo.keys.publicKey,max_fee:m,actor:this.actor}};break}case h.aO.registerFioDomain:{const{fioDomain:f}=(0,p.AJ)(y);m=yield this.getFee(C.EndPoint.registerFioDomain),v={account:"fio.address",action:"regdomain",data:{fio_domain:f,owner_fio_public_key:this.walletInfo.keys.publicKey,max_fee:m,actor:this.actor}};break}case h.aO.renewFioDomain:{const{fioDomain:f}=(0,p.AJ)(y);m=yield this.getFee(C.EndPoint.renewFioDomain),v={account:"fio.address",action:"renewdomain",data:{fio_domain:f,max_fee:m,actor:this.actor}};break}case h.aO.addBundledTransactions:{const{bundleSets:f,fioAddress:E}=(0,p.Ej)(y);m=yield this.getFee(C.EndPoint.addBundledTransactions,E),v={account:"fio.address",action:"addbundles",data:{fio_address:E,bundle_sets:f,actor:this.actor,max_fee:m}};break}case h.aO.setFioDomainPublic:{const{fioDomain:f,isPublic:E}=(0,p.oY)(y);m=yield this.getFee(C.EndPoint.setFioDomainPublic),v={account:"fio.address",action:"setdomainpub",data:{fio_domain:f,is_public:E?1:0,max_fee:m,actor:this.actor}};break}case h.aO.rejectFundsRequest:{const{fioRequestId:f,payerFioAddress:E}=(0,p.OR)(y);m=yield this.getFee(C.EndPoint.rejectFundsRequest,E),v={account:"fio.reqobt",action:"rejectfndreq",data:{fio_request_id:f,max_fee:m,actor:this.actor}};break}case h.aO.cancelFundsRequest:{const{fioAddress:f,fioRequestId:E}=(0,p.mO)(y);m=yield this.getFee(C.EndPoint.cancelFundsRequest,f),v={account:"fio.reqobt",action:"cancelfndreq",data:{fio_request_id:E,max_fee:m,actor:this.actor}};break}case h.aO.recordObtData:{const{payerFioAddress:f}=(0,p.XB)(y);m=yield this.getFee(C.EndPoint.recordObtData,f);break}case h.aO.requestFunds:{const{payeeFioAddress:f}=(0,p.Vd)(y);m=yield this.getFee(C.EndPoint.newFundsRequest,f);break}default:throw new Error("Unrecognized FIO action")}return{blockHeight:0,currencyCode:n,date:0,isSend:!0,memos:r,nativeAmount:(0,P.sub)(`-${d}`,`${m}`),networkFee:`${m}`,otherParams:H(S({},c),{txParams:v}),ourReceiveAddresses:[],signedTx:"",txid:"",walletId:this.walletId}})}signTx(e,s){return k(this,null,function*(){const t=(0,p.UW)(s),n=(0,b.Xp)(e);let r=(0,u.Vk)(p.B3)(n.txParams);const l=new ae.Transactions;if(r==null){const{name:c,params:g}=(0,p.iR)(n.action),{networkFee:y}=e;switch(c){case h.aO.recordObtData:{const{payerFioAddress:m,payeeFioAddress:v,payerPublicAddress:N,payeePublicAddress:f,amount:E,tokenCode:q,chainCode:A,obtId:L,memo:$,status:M,fioRequestId:K}=(0,p.XB)(g),X={payer_public_address:N,payee_public_address:f,amount:E,chain_code:A,token_code:q,status:M,obt_id:L,memo:$,hash:void 0,offline_url:void 0},re=l.getCipherContent("record_obt_data_content",X,t.fioKey,N);r={account:"fio.reqobt",action:"recordobt",data:{payer_fio_address:m,payee_fio_address:v,content:re,fio_request_id:K,max_fee:y,actor:this.actor}};break}case h.aO.requestFunds:{const{payerFioAddress:m,payerFioPublicKey:v,payeeFioAddress:N,payeeTokenPublicAddress:f,amount:E,chainCode:q,tokenCode:A,memo:L}=(0,p.Vd)(g),$={payee_public_address:f,amount:E,chain_code:q,token_code:A,memo:L,hash:void 0,offline_url:void 0},M=l.getCipherContent("new_funds_content",$,t.fioKey,v);r={account:"fio.reqobt",action:"newfundsreq",data:{payer_fio_address:m,payee_fio_address:N,content:M,max_fee:y,actor:this.actor}};break}default:throw new Error("Unknown FIO action")}}const a=yield l.createRawTransaction({action:r.action,account:r.account,data:H(S({},r.data),{tpid:this.tpid}),publicKey:this.walletInfo.keys.publicKey,chainData:this.refBlock}),{serializedContextFreeData:o,serializedTransaction:i}=yield l.serialize({chainId:this.networkInfo.chainId,transaction:a}),d=yield l.sign({chainId:this.networkInfo.chainId,privateKeys:[t.fioKey],transaction:a,serializedTransaction:i,serializedContextFreeData:o});return e.otherParams=H(S({},e.otherParams),{signedTx:d}),e})}broadcastTx(e){return k(this,null,function*(){var s;const t=(0,b.Xp)(e);if(((s=t.action)==null?void 0:s.name)==null)throw new Error('Action is not set, "action" prop of otherParams is required for FIO actions');const n=(0,p.h0)(t.signedTx),r=(0,p.Yd)(yield this.multicastServers(t.action.name,n));e.metadata={notes:r.transaction_id},e.txid=r.transaction_id,e.date=Date.now()/1e3,e.blockHeight=r.block_num,this.warn(`SUCCESS broadcastTx
2
+ ${(0,b.oX)(e)}`);const l=r,{block_num:a,block_time:o,transaction_id:i}=l,d=ge(l,["block_num","block_time","transaction_id"]);return e.otherParams=H(S({},t),{broadcastResult:d}),e})}saveTx(e){return k(this,null,function*(){var s;const t=(0,b.Xp)(e),{broadcastResult:n={},action:r}=t,{name:l,params:a}=(0,p.iR)(r);try{switch(l){case h.aO.transferFioDomain:{const o=this.otherData.fioDomains.findIndex(({name:i})=>i===a.fioDomain);o>=0&&(this.otherData.fioDomains.splice(o,1),this.localDataDirty());break}case h.aO.transferFioAddress:{const o=this.otherData.fioAddresses.findIndex(({name:i})=>i===a.fioAddress);o>=0&&(this.otherData.fioAddresses.splice(o,1),this.localDataDirty());break}case h.aO.registerFioAddress:{const{fioAddress:o}=(0,p.NB)(a);this.otherData.fioAddresses.find(({name:d})=>d===o)==null&&(this.otherData.fioAddresses.push({name:o,bundledTxs:void 0}),this.localDataDirty());break}case h.aO.registerFioDomain:{const{fioDomain:o}=(0,p.AJ)(a);if(n.expiration==null)throw new Error("expiration not present");const i=this.otherData.fioDomains.find(({name:d})=>d===o);i!=null&&(i.expiration=n.expiration,this.localDataDirty());break}case h.aO.renewFioDomain:{const{fioDomain:o}=(0,p.AJ)(a);if(n.expiration==null)throw new Error("expiration not present");const i=this.otherData.fioDomains.find(({name:d})=>d===o);i!=null&&(i.expiration=n.expiration,this.localDataDirty());break}case h.aO.addBundledTransactions:{const{fioAddress:o}=(0,p.Ej)(a),i=this.otherData.fioAddresses.find(({name:d})=>d===o);if(i==null)throw new I.OU("Fio Address is not found in engine");i.bundledTxs=((s=i.bundledTxs)!=null?s:0)+h.BB,this.localDataDirty();break}case h.aO.rejectFundsRequest:{const{fioRequestId:o}=(0,p.OR)(a);typeof o=="string"&&(this.removeFioRequest(o,"PENDING"),this.localDataDirty());break}case h.aO.cancelFundsRequest:{const{fioRequestId:o}=(0,p.mO)(a);typeof o=="string"&&(this.removeFioRequest(o,"SENT"),this.localDataDirty());break}case h.aO.recordObtData:{const{fioRequestId:o}=(0,p.XB)(a);o!=null&&n.status==="sent_to_blockchain"&&(this.removeFioRequest(o,"PENDING"),this.localDataDirty());break}}}catch(o){this.log.warn(`Error attempting post-broadcast action ${l}:`,o)}yield me(ne.prototype,this,"saveTx").call(this,e)})}getFreshAddress(e){return k(this,null,function*(){return{publicAddress:this.walletInfo.keys.publicKey}})}}function ve(_,e,s,t){return k(this,null,function*(){const{tpid:n="finance@edge"}=_.initOptions,r=(0,p.RB)(s),l=new ne(_,e,r,t,n);return yield l.loadEngine(),l})}var we=D(48764).Buffer,F=(_,e,s)=>new Promise((t,n)=>{var r=o=>{try{a(s.next(o))}catch(i){n(i)}},l=o=>{try{a(s.throw(o))}catch(i){n(i)}},a=o=>o.done?t(o.value):Promise.resolve(o.value).then(r,l);a((s=s.apply(_,e)).next())});const le="FIO",ce="fio",Ae="";function de(_){const e=_.startsWith(le),s=_.length===53;return e&&s}class ye{constructor(e){const{builtinTokens:s,currencyInfo:t,initOptions:n,io:r,networkInfo:l}=e;this.builtinTokens=s,this.currencyInfo=t,this.io=r,this.networkInfo=l;const{tpid:a="finance@edge",fioRegApiToken:o=Ae}=n;this.fetchCors=(0,b.zR)(e.io),this.fioRegApiToken=o,this.tpid=a;for(const i of this.networkInfo.apiUrls)new R.rn("","",i,this.fetchCors,void 0,a)}getDisplayPrivateKey(e){return F(this,null,function*(){return(0,p.UW)(e.keys).fioKey})}getDisplayPublicKey(e){return F(this,null,function*(){const{keys:s}=(0,p.RB)(e);return s.publicKey})}importPrivateKey(e){return F(this,null,function*(){const{pluginId:s}=this.currencyInfo,t={};if(/[0-9a-zA-Z]{51}$/.test(e))ue._q.fromString(e),t.fioKey=e;else{if(!(0,ie.validateMnemonic)(e))throw new Error("Invalid input");const r=yield R.rn.createPrivateKeyMnemonic(e);t.fioKey=r.fioKey,t.mnemonic=r.mnemonic}const n=yield this.derivePublicKey({type:`wallet:${s}`,id:"fake",keys:t});return t.publicKey=n.publicKey,t})}createPrivateKey(e){return F(this,null,function*(){if(e.replace("wallet:","")===ce){const t=we.from(this.io.random(32));return yield R.rn.createPrivateKey(t)}else throw new Error("InvalidWalletType")})}derivePublicKey(e){return F(this,null,function*(){if(e.type.replace("wallet:","")===ce)return R.rn.derivedPublicKey(e.keys.fioKey);throw new Error("InvalidWalletType")})}parseUri(e){return F(this,null,function*(){var s;const{edgeParsedUri:t}=(0,ee.k)(this.currencyInfo,e,{fio:!0},le);if(!de((s=t.publicAddress)!=null?s:""))throw new Error("InvalidPublicAddressError");return t})}encodeUri(e){return F(this,arguments,function*(s,t=[]){if(!de(s.publicAddress))throw new Error("InvalidPublicAddressError");let r;if(typeof s.nativeAmount=="string"){const a=le,o=s.nativeAmount,i=(0,b.Qs)(a,this.currencyInfo,t);if(i==null)throw new Error("InternalErrorInvalidCurrencyCode");r=(0,P.div)(o,i.multiplier,16)}return(0,ee.Q)(s,ce,r)})}getConnectedPublicAddress(e,s,t){return F(this,null,function*(){var n;try{R.rn.isFioAddressValid(e)}catch{throw new I.OU("",400,this.networkInfo.errorCodes.INVALID_FIO_ADDRESS)}try{if((yield this.multicastServers("isAvailable",{fioName:e})).is_registered===0)throw new I.OU("",404,this.networkInfo.errorCodes.FIO_ADDRESS_IS_NOT_EXIST)}catch(r){throw r.name==="FioError"&&((n=r.json)==null?void 0:n.fields)!=null&&r.errorCode===400&&(r.labelCode=this.networkInfo.errorCodes.INVALID_FIO_ADDRESS),r}try{const r=yield this.multicastServers("getPublicAddress",{fioAddress:e,chainCode:s,tokenCode:t});if(r.public_address==null||r.public_address==="0")throw new I.OU("",404,this.networkInfo.errorCodes.FIO_ADDRESS_IS_NOT_LINKED);return r}catch(r){throw r.name==="FioError"&&r.labelCode===this.networkInfo.errorCodes.FIO_ADDRESS_IS_NOT_LINKED||r.errorCode===404?new I.OU("",404,this.networkInfo.errorCodes.FIO_ADDRESS_IS_NOT_LINKED):r}})}isFioAddressValid(e){return F(this,null,function*(){try{return R.rn.isFioAddressValid(e)}catch{return!1}})}validateAccount(e,s=!1){return F(this,null,function*(){var t;try{if(s){if(!R.rn.isFioDomainValid(e))return!1}else if(!R.rn.isFioAddressValid(e))return!1}catch{throw new I.OU("",400,this.networkInfo.errorCodes.INVALID_FIO_ADDRESS)}try{return(yield this.multicastServers("isAvailable",{fioName:e})).is_registered===0}catch(n){throw n.name==="FioError"&&((t=n.json)==null?void 0:t.fields)!=null&&n.errorCode===400&&(n.labelCode=this.networkInfo.errorCodes.INVALID_FIO_ADDRESS),n}})}isDomainPublic(e){return F(this,null,function*(){if((yield this.multicastServers("isAvailable",{fioName:e})).is_registered===0)throw new I.OU("",400,this.networkInfo.errorCodes.FIO_DOMAIN_IS_NOT_EXIST);const t=yield this.fetchCors(`${this.networkInfo.fioRegApiUrl}${h.n3.isDomainPublic}/${e}`,{method:"GET"});if(!t.ok){const r=yield t.json();throw new I.OU("",t.status,this.networkInfo.errorCodes.IS_DOMAIN_PUBLIC_ERROR,r)}const{isPublic:n}=yield t.json();return n})}doesAccountExist(e){return F(this,null,function*(){try{if(!R.rn.isFioAddressValid(e))return!1}catch{return!1}try{return(yield this.multicastServers("isAvailable",{fioName:e})).is_registered===1}catch(s){return this.error("doesAccountExist error: ",s),!1}})}buyAddressRequest(e,s=!1){return F(this,null,function*(){const t={Accept:"application/json","Content-Type":"application/json"};s&&(e.apiToken=this.fioRegApiToken);try{const n=yield this.fetchCors(`${this.networkInfo.fioRegApiUrl}${h.n3.buyAddress}`,{method:"POST",headers:t,body:JSON.stringify(e)});if(!n.ok){const r=yield n.json();throw this.networkInfo.errorCodes[r.errorCode]!=null?new I.OU(r.error,n.status,this.networkInfo.errorCodes[r.errorCode],r):r.error==="Already registered"?new I.OU(r.error,n.status,this.networkInfo.errorCodes.ALREADY_REGISTERED,r):new Error(r.error)}return yield n.json()}catch(n){throw n.labelCode!=null?n:new I.OU((0,b.HY)(n),500,this.networkInfo.errorCodes.SERVER_ERROR)}})}getDomains(e=""){return F(this,null,function*(){e==null&&(e=this.networkInfo.defaultRef);try{const s=yield this.fetchCors(`${this.networkInfo.fioRegApiUrl}${h.n3.getDomains}/${e}`,{method:"GET"}),t=yield s.json();if(!s.ok)throw this.networkInfo.errorCodes[t.errorCode]!=null?new I.OU(t.error,s.status,this.networkInfo.errorCodes[t.errorCode],t):new Error(t.error);return t.domains}catch(s){throw s.labelCode!=null?s:new I.OU((0,b.HY)(s),500,this.networkInfo.errorCodes.SERVER_ERROR)}})}getStakeEstReturn(){return F(this,null,function*(){try{const e=yield this.fetchCors(`${this.networkInfo.fioStakingApyUrl}`,{method:"GET"}),s=yield e.json();if(!e.ok)throw new Error(this.networkInfo.errorCodes.SERVER_ERROR);const t=s.historical_apr["7day"];return t!=null&&t>h.OT||t==null?h.OT:t}catch(e){throw e.labelCode!=null?e:new I.OU(e.message,500,this.networkInfo.errorCodes.SERVER_ERROR)}})}multicastServers(e,s){return F(this,null,function*(){const t=yield(0,b.QJ)((0,b.Sy)(this.networkInfo.apiUrls.map(n=>()=>F(this,null,function*(){let r;const l=new R.rn("","",n,this.fetchCors,void 0,this.tpid);try{r=yield l.genericAction(e,s)}catch(a){if(a.errorCode!=null&&I.lI.includes(a.errorCode))r={isError:!0,data:{code:a.errorCode,message:(0,b.HY)(a),json:a.json,list:a.list}};else throw a}return r}))));if(t.isError!=null){const n=new I.OU(t.errorMessage);throw n.json=t.data.json,n.list=t.data.list,n.errorCode=t.data.code,n}return t})}}function Ie(_){return F(this,null,function*(){return new ye(_)})}},89214:function(){},52361:function(){},94616:function(){}}]);
@@ -1,2 +1,2 @@
1
- (self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[3591],{79014:function(nt,M,h){"use strict";h.d(M,{Q:function(){return j},k:function(){return V}});var S=h(77591),Y=h.n(S),W=h(24350),X=h(84564),i=h.n(X),L=h(76714),U=Object.defineProperty,T=Object.getOwnPropertySymbols,F=Object.prototype.hasOwnProperty,I=Object.prototype.propertyIsEnumerable,a=(u,g,m)=>g in u?U(u,g,{enumerable:!0,configurable:!0,writable:!0,value:m}):u[g]=m,Q=(u,g)=>{for(var m in g||(g={}))F.call(g,m)&&a(u,m,g[m]);if(T)for(var m of T(g))I.call(g,m)&&a(u,m,g[m]);return u};function V(u,g,m,k,P=[]){const p=Q({},i()(g,{},!0)),x=g.startsWith(`${u.pluginId}://`);if(p.protocol!=null&&(p.protocol=p.protocol.replace(":","")),p.protocol!=null&&p.protocol!==""&&!m[p.protocol])throw new Error(`Uri protocol '${p.protocol}' is not supported for ${u.pluginId}.`);if(p.host===""&&p.pathname==="")throw new Error("Path and host not found in uri.");const A={publicAddress:p.host!==""?p.host:p.pathname.split("/")[0]},H=p.query.label,R=p.query.message,B=p.query.category;(H!=null||R!=null||B!=null||x)&&(A.metadata={},A.metadata.name=H,A.metadata.notes=R,A.metadata.category=B,A.metadata.gateway=x!=null?x:!1);const D=p.query.amount;if(D!=null&&typeof D=="string"){k==null&&(k=u.currencyCode);const $=(0,L.Qs)(k!=null?k:"",u,P);if($==null)throw new Error("InternalErrorInvalidCurrencyCode");let K=(0,S.mul)(D,$.multiplier);K=(0,S.toFixed)(K,0,0),A.nativeAmount=K,A.currencyCode=k}return{edgeParsedUri:A,parsedUri:p}}function j(u,g,m){if(u.publicAddress==null)throw new Error("InvalidPublicAddressError");if(m==null&&u.label==null&&u.message==null)return u.publicAddress;{let k="";m!=null&&(k+="amount="+m+"&"),(u.label!=null||u.message!=null)&&(typeof u.label=="string"&&(k+="label="+u.label+"&"),typeof u.message=="string"&&(k+="message="+u.message+"&")),k=k.substr(0,k.length-1);const P={scheme:g,path:u.publicAddress,query:k};return(0,W.qC)(P)}}},34765:function(nt,M,h){"use strict";h.r(M),h.d(M,{PolkadotTools:function(){return et},makeCurrencyEngine:function(){return ct},makeCurrencyTools:function(){return dt}});var S=h(58170),Y=h(36010),W=h(18534),X=h(23670),i=h(77591),L=h(2153),U=h(48764),T=h(20918),F=h(79014),I=h(76714),a=h(82448),Q=h(62177);const V=(0,a.su)({txCount:(0,a.Vk)(a.mH,0)}),j=(0,a.su)({code:a.mH,message:a.XC,data:(0,a.Zz)((0,a.su)(a.JC))}),u=(0,a.su)({from:a.XC,to:a.XC,success:a.jK,hash:a.XC,block_num:a.mH,block_timestamp:a.mH,module:a.XC,amount:a.XC,fee:a.XC}),g=(0,a.su)({count:a.mH,transfers:(0,a.Vk)((0,a._2)(u),()=>[])}),m=Q.BQ,k=d=>{const t=(0,a.su)({[`${d}Mnemonic`]:(0,a.Zz)(a.XC),[`${d}Key`]:a.XC});return(0,a.W1)(e=>{const r=t(e);return{mnemonic:r[`${d}Mnemonic`],privateKey:r[`${d}Key`]}},e=>({[`${d}Mnemonic`]:e.mnemonic,[`${d}Key`]:e.privateKey}))};var P=h(94935),p=h(79325),x=h(84650),z=h(72681),A=Object.defineProperty,H=Object.defineProperties,R=Object.getOwnPropertyDescriptors,B=Object.getOwnPropertySymbols,D=Object.getPrototypeOf,$=Object.prototype.hasOwnProperty,K=Object.prototype.propertyIsEnumerable,rt=Reflect.get,J=(d,t,e)=>t in d?A(d,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):d[t]=e,Z=(d,t)=>{for(var e in t||(t={}))$.call(t,e)&&J(d,e,t[e]);if(B)for(var e of B(t))K.call(t,e)&&J(d,e,t[e]);return d},_=(d,t)=>H(d,R(t)),q=(d,t,e)=>rt(D(d),e,t),w=(d,t,e)=>new Promise((r,s)=>{var n=o=>{try{f(e.next(o))}catch(l){s(l)}},c=o=>{try{f(e.throw(o))}catch(l){s(l)}},f=o=>o.done?r(o.value):Promise.resolve(o.value).then(n,c);f((e=e.apply(d,t)).next())});const st=5e3,ot=2e4,it=3e3,at=(0,I.jT)();class N extends x.P{constructor(t,e,r,s){super(t,e,r,s),this.getRecipientBalance=n=>w(this,null,function*(){try{return(yield this.api.query.system.account(n)).data.free.toString()}catch{return this.minimumAddressBalance}}),this.fetchCors=(0,I.zR)(t.io),this.networkInfo=t.networkInfo,this.nonce=0}setOtherData(t){this.otherData=V(t)}fetchSubscan(t,e){return w(this,null,function*(){if(this.networkInfo.subscanBaseUrl==null)throw new Error("Missing subscan url");const r={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(e)},s=yield this.fetchCors(this.networkInfo.subscanBaseUrl+t,r);if(!s.ok||s.status===429)throw new Error(`Subscan ${t} failed with ${s.status}`);const n=yield s.json();return j(n)})}queryBalance(){return w(this,null,function*(){const t=yield this.api.query.system.account(this.walletInfo.keys.publicKey);this.nonce=t.nonce.toNumber(),this.updateBalance(this.currencyInfo.currencyCode,t.data.free.toString());for(const e of this.enabledTokenIds){const r=this.allTokensMap[e];if(r==null)continue;const s=(0,T.Oj)(r.networkLocation);if(s==null)continue;const n=yield this.api.query.assets.account(s.contractAddress,this.walletInfo.keys.publicKey);let c="0";n.isSome&&(c=n.unwrap().balance.toString()),this.updateBalance(r.currencyCode,c)}})}queryBlockheight(){return w(this,null,function*(){try{const e=(yield this.api.rpc.chain.getBlock()).block.header.number.toNumber();e>this.walletLocalData.blockHeight&&(this.walletLocalData.blockHeight=e,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight))}catch(t){this.warn("queryBlockheight failed with error: ",t)}})}processPolkadotTransaction(t){const{from:e,to:r,success:s,hash:n,block_num:c,block_timestamp:f,module:o,amount:l,fee:y}=t;if(!s||o!=="balances")return;const O=(0,I.aL)(this.currencyInfo.currencyCode,this.currencyInfo,this.allTokensMap);if(O==null)return;const b=[];let C=(0,i.mul)(l,O.multiplier);e===this.walletInfo.keys.publicKey?C=`-${(0,i.add)(C,y)}`:b.push(r);const E={blockHeight:c,currencyCode:this.currencyInfo.currencyCode,date:f,isSend:C.startsWith("-"),memos:[],nativeAmount:C,networkFee:y,ourReceiveAddresses:b,signedTx:"",txid:n,walletId:this.walletId};this.addTransaction(this.currencyInfo.currencyCode,E)}queryTransactions(){return w(this,null,function*(){if(this.networkInfo.subscanBaseUrl==null){for(const t of this.enabledTokens)this.tokenCheckTransactionsStatus[t]=1;this.updateOnAddressesChecked();return}return yield at(()=>w(this,null,function*(){return yield this.queryTransactionsInner()}))})}queryTransactionsInner(){return w(this,null,function*(){let t=Math.floor(this.otherData.txCount/this.networkInfo.subscanQueryLimit);for(;;){const e={row:this.networkInfo.subscanQueryLimit,page:t,address:this.walletInfo.keys.publicKey};let r=0,s=[];try{const n=yield this.fetchSubscan("/scan/transfers",e),c=g(n.data);r=c.count,s=c.transfers}catch(n){if(n instanceof Error&&n.message.includes("Subscan /scan/transfers failed with 429")){this.log(n.message);continue}else throw n}if(r===this.otherData.txCount||(s.forEach(n=>{try{this.processPolkadotTransaction(u(n))}catch{const f=n!=null&&typeof n.hash=="string"?n.hash:"";this.warn(`Ignoring invalid transfer ${f}`)}}),this.otherData.txCount=t*this.networkInfo.subscanQueryLimit+s.length,this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=Math.min(1,r===0?1:this.otherData.txCount/r),this.updateOnAddressesChecked(),r===this.otherData.txCount))break;t++}this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=1,this.updateOnAddressesChecked(),this.transactionsChangedArray.length>0&&(this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[])})}startEngine(){return w(this,null,function*(){this.engineOn=!0,yield this.tools.connectApi(this.walletId),this.api=this.tools.polkadotApi,this.minimumAddressBalance=this.api.consts.balances.existentialDeposit.toString(),this.addToLoop("queryBlockheight",ot).catch(()=>{}),this.addToLoop("queryBalance",st).catch(()=>{}),this.addToLoop("queryTransactions",it).catch(()=>{}),yield q(N.prototype,this,"startEngine").call(this)})}killEngine(){return w(this,null,function*(){yield q(N.prototype,this,"killEngine").call(this),yield this.tools.disconnectApi(this.walletId)})}resyncBlockchain(){return w(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getMaxSpendable(t){return w(this,null,function*(){if(t=(0,z.s)(t,this.currencyInfo),t.spendTargets.length===0||t.spendTargets[0].publicAddress==null)throw new Error("Missing public address");const e=this.getBalance({currencyCode:t.currencyCode});if(t.currencyCode!==this.currencyInfo.currencyCode){const l=[{publicAddress:t.spendTargets[0].publicAddress,nativeAmount:e}],y=_(Z({},t),{spendTargets:l});return yield this.makeSpend(y),e}const r=(0,i.sub)(e,this.api.consts.balances.existentialDeposit.toString()),s=[{publicAddress:t.spendTargets[0].publicAddress,nativeAmount:"0"}],n=_(Z({},t),{spendTargets:s}),f=(yield this.makeSpend(n)).networkFee,o=(l,y)=>{const O=(0,i.sub)(y,l);if((0,i.lte)(O,"1"))return l;const b=(0,i.add)(l,(0,i.div)(O,"2")),C=(0,I.X0)(b).replace("0x",""),E=C.length%2===1?`0${C}`:C,G=(0,i.mul)((0,i.div)(E.length.toString(),"2"),this.networkInfo.lengthFeePerByte),ht=(0,i.add)((0,i.add)(G,f),b);return(0,i.gt)(ht,r)?o(l,b):o(b,y)};return o("0",(0,i.add)(r,"1"))})}makeSpend(t){return w(this,null,function*(){t=(0,z.s)(t,this.currencyInfo);const{edgeSpendInfo:e,currencyCode:r}=this.makeSpendCheck(t),{memos:s=[]}=e;if(e.spendTargets.length!==1)throw new Error("Error: only one output allowed");const{nativeAmount:n,publicAddress:c}=e.spendTargets[0];if(c==null)throw new Error("makeSpend Missing publicAddress");if(n==null)throw new P.$D;const f=this.getBalance({currencyCode:r});let o,l;if(e.tokenId==null){const b=(0,i.sub)(f,this.api.consts.balances.existentialDeposit.toString());if((0,i.gt)(n,b))throw new P.C_;const E=yield(yield this.api.tx.balances.transferKeepAlive(c,n)).paymentInfo(this.walletInfo.keys.publicKey);if(l=(0,i.sub)(E.partialFee.toString(),(0,i.mul)(this.networkInfo.lengthFeePerByte,this.networkInfo.partialFeeOffsetMultiplier)),o=(0,i.add)(n,l),(0,i.gt)(o,b))throw new P.C_}else{if((0,i.gt)(n,f))throw new P.C_;o=n;const C=yield(yield this.api.tx.assets.transfer(parseInt(e.tokenId),c,n)).paymentInfo(this.walletInfo.keys.publicKey);l=(0,i.sub)(C.partialFee.toString(),(0,i.mul)(this.networkInfo.lengthFeePerByte,this.networkInfo.partialFeeOffsetMultiplier));const E=this.getBalance({currencyCode:this.currencyInfo.currencyCode}),G=(0,i.sub)(E,this.api.consts.balances.existentialDeposit.toString());if((0,i.gt)(l,G))throw new P.C_({currencyCode:this.currencyInfo.currencyCode,networkFee:l})}const y={publicAddress:c};return{blockHeight:0,currencyCode:r,date:0,isSend:!0,memos:s,nativeAmount:(0,i.mul)(o,"-1"),networkFee:l,otherParams:y,ourReceiveAddresses:[],signedTx:"",txid:"",walletId:this.walletId}})}signTx(t,e){return w(this,null,function*(){const r=k(this.currencyInfo.pluginId)(e),{publicAddress:s}=(0,I.Xp)(t);if(s==null)throw new Error("Missing publicAddress from makeSpend");const n=this.allTokens.find(y=>y.currencyCode===t.currencyCode);let c;if(n==null){const y=(0,i.abs)((0,i.add)(t.nativeAmount,t.networkFee));yield this.checkRecipientMinimumBalance(this.getRecipientBalance,y,s),c=yield this.api.tx.balances.transferKeepAlive(s,y)}else if(n.contractAddress!=null){const y=(0,i.abs)(t.nativeAmount);c=yield this.api.tx.assets.transfer(parseInt(n.contractAddress),s,y)}else throw new Error("Unrecognized asset");const f=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",f.toPayload(),{version:this.api.extrinsicVersion});if(this.keypair==null)if(this.keypair=new S.Y({ss58Format:0}),r.mnemonic!=null)this.keypair.addFromUri(r.mnemonic);else{const y=p.YU.parse(r.privateKey);this.keypair.addFromSeed(y)}const l=o.sign(this.keypair.getPair(this.walletInfo.keys.publicKey));return c.addSignature(this.walletInfo.keys.publicKey,l.signature,f.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 ct(d,t,e,r){return w(this,null,function*(){const s=m(e),n=new N(d,t,s,r);return yield n.loadEngine(),n})}var v=(d,t,e)=>new Promise((r,s)=>{var n=o=>{try{f(e.next(o))}catch(l){s(l)}},c=o=>{try{f(e.throw(o))}catch(l){s(l)}},f=o=>o.done?r(o.value):Promise.resolve(o.value).then(n,c);f((e=e.apply(d,t)).next())});const{ed25519PairFromSeed:lt,isAddress:tt,mnemonicToMiniSecret:ut}=X;class et{constructor(t){const{builtinTokens:e,currencyInfo:r,io:s,networkInfo:n}=t;this.builtinTokens=e,this.currencyInfo=r,this.io=s,this.networkInfo=n,this.polkadotApiSubscribers=new Set}getDisplayPrivateKey(t){return v(this,null,function*(){var e;const{pluginId:r}=this.currencyInfo,s=k(r)(t.keys);return(e=s.mnemonic)!=null?e:s.privateKey})}getDisplayPublicKey(t){return v(this,null,function*(){const{keys:e}=m(t);return e.publicKey})}importPrivateKey(t){return v(this,null,function*(){const{pluginId:e}=this.currencyInfo;if((0,L.validateMnemonic)(t)){const r=ut(t),{secretKey:s}=lt(r);return{[`${e}Mnemonic`]:t,[`${e}Key`]:U.Buffer.from(s).toString("hex")}}else{if((0,I.vq)(t))return{[`${e}Key`]:t};throw new Error("InvalidPrivateKey")}})}createPrivateKey(t){return v(this,null,function*(){if(t!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const e=U.Buffer.from(this.io.random(32)),r=(0,L.entropyToMnemonic)(e);return yield this.importPrivateKey(r)})}derivePublicKey(t){return v(this,null,function*(){const{pluginId:e}=this.currencyInfo;return{publicKey:new S.Y({ss58Format:0}).addFromUri(t.keys[`${e}Mnemonic`]).address}})}parseUri(t,e,r){return v(this,null,function*(){var s,n;const{pluginId:c}=this.currencyInfo,f={[c]:!0},{parsedUri:o,edgeParsedUri:l}=(0,F.k)(this.currencyInfo,t,f,e!=null?e:this.currencyInfo.currencyCode,r),y=(s=l.publicAddress)!=null?s:"";if(!tt(y))throw new Error("InvalidPublicAddressError");return l.uniqueIdentifier=(n=o.query.memo)!=null?n:void 0,l})}encodeUri(t){return v(this,arguments,function*(e,r=[]){const{pluginId:s}=this.currencyInfo,{nativeAmount:n,currencyCode:c,publicAddress:f}=e;if(!tt(f))throw new Error("InvalidPublicAddressError");let o;if(typeof n=="string"){const y=(0,I.Qs)(c!=null?c:this.currencyInfo.currencyCode,this.currencyInfo,r);if(y==null)throw new Error("InternalErrorInvalidCurrencyCode");o=(0,i.div)(n,y.multiplier,10)}return(0,F.Q)(e,s,o)})}connectApi(t){return v(this,null,function*(){return this.polkadotApi==null&&(this.polkadotApi=yield Y.G.create({initWasm:!1,provider:new W.U(this.networkInfo.rpcNodes[0])})),this.polkadotApiSubscribers.add(t),this.polkadotApi})}disconnectApi(t){return v(this,null,function*(){this.polkadotApiSubscribers.delete(t),this.polkadotApiSubscribers.size===0&&(yield this.polkadotApi.disconnect(),this.polkadotApi=void 0)})}getTokenId(t){return v(this,null,function*(){(0,T.Rp)(t);const e=(0,T.Oj)(t.networkLocation);if(e==null)throw new Error("ErrorInvalidContractAddress");return e.contractAddress})}}function dt(d){return v(this,null,function*(){return new et(d)})}},52361:function(){},94616:function(){}}]);
1
+ (self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[3591],{79014:function(nt,M,h){"use strict";h.d(M,{Q:function(){return j},k:function(){return V}});var E=h(77591),Y=h.n(E),W=h(24350),X=h(84564),i=h.n(X),L=h(76714),U=Object.defineProperty,T=Object.getOwnPropertySymbols,F=Object.prototype.hasOwnProperty,C=Object.prototype.propertyIsEnumerable,a=(u,g,m)=>g in u?U(u,g,{enumerable:!0,configurable:!0,writable:!0,value:m}):u[g]=m,Q=(u,g)=>{for(var m in g||(g={}))F.call(g,m)&&a(u,m,g[m]);if(T)for(var m of T(g))C.call(g,m)&&a(u,m,g[m]);return u};function V(u,g,m,k,P=[]){const p=Q({},i()(g,{},!0)),x=g.startsWith(`${u.pluginId}://`);if(p.protocol!=null&&(p.protocol=p.protocol.replace(":","")),p.protocol!=null&&p.protocol!==""&&!m[p.protocol])throw new Error(`Uri protocol '${p.protocol}' is not supported for ${u.pluginId}.`);if(p.host===""&&p.pathname==="")throw new Error("Path and host not found in uri.");const A={publicAddress:p.host!==""?p.host:p.pathname.split("/")[0]},H=p.query.label,R=p.query.message,B=p.query.category;(H!=null||R!=null||B!=null||x)&&(A.metadata={},A.metadata.name=H,A.metadata.notes=R,A.metadata.category=B,A.metadata.gateway=x!=null?x:!1);const K=p.query.amount;if(K!=null&&typeof K=="string"){k==null&&(k=u.currencyCode);const $=(0,L.Qs)(k!=null?k:"",u,P);if($==null)throw new Error("InternalErrorInvalidCurrencyCode");let D=(0,E.mul)(K,$.multiplier);D=(0,E.toFixed)(D,0,0),A.nativeAmount=D,A.currencyCode=k}return{edgeParsedUri:A,parsedUri:p}}function j(u,g,m){if(u.publicAddress==null)throw new Error("InvalidPublicAddressError");if(m==null&&u.label==null&&u.message==null)return u.publicAddress;{let k="";m!=null&&(k+="amount="+m+"&"),(u.label!=null||u.message!=null)&&(typeof u.label=="string"&&(k+="label="+u.label+"&"),typeof u.message=="string"&&(k+="message="+u.message+"&")),k=k.substr(0,k.length-1);const P={scheme:g,path:u.publicAddress,query:k};return(0,W.qC)(P)}}},34765:function(nt,M,h){"use strict";h.r(M),h.d(M,{PolkadotTools:function(){return et},makeCurrencyEngine:function(){return ct},makeCurrencyTools:function(){return dt}});var E=h(58170),Y=h(36010),W=h(18534),X=h(23670),i=h(77591),L=h(2153),U=h(48764),T=h(20918),F=h(79014),C=h(76714),a=h(82448),Q=h(62177);const V=(0,a.su)({txCount:(0,a.Vk)(a.mH,0)}),j=(0,a.su)({code:a.mH,message:a.XC,data:(0,a.Zz)((0,a.su)(a.JC))}),u=(0,a.su)({from:a.XC,to:a.XC,success:a.jK,hash:a.XC,block_num:a.mH,block_timestamp:a.mH,module:a.XC,amount:a.XC,fee:a.XC}),g=(0,a.su)({count:a.mH,transfers:(0,a.Vk)((0,a._2)(u),()=>[])}),m=Q.BQ,k=d=>{const t=(0,a.su)({[`${d}Mnemonic`]:(0,a.Zz)(a.XC),[`${d}Key`]:a.XC});return(0,a.W1)(e=>{const n=t(e);return{mnemonic:n[`${d}Mnemonic`],privateKey:n[`${d}Key`]}},e=>({[`${d}Mnemonic`]:e.mnemonic,[`${d}Key`]:e.privateKey}))};var P=h(94935),p=h(79325),x=h(84650),z=h(72681),A=Object.defineProperty,H=Object.defineProperties,R=Object.getOwnPropertyDescriptors,B=Object.getOwnPropertySymbols,K=Object.getPrototypeOf,$=Object.prototype.hasOwnProperty,D=Object.prototype.propertyIsEnumerable,rt=Reflect.get,J=(d,t,e)=>t in d?A(d,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):d[t]=e,Z=(d,t)=>{for(var e in t||(t={}))$.call(t,e)&&J(d,e,t[e]);if(B)for(var e of B(t))D.call(t,e)&&J(d,e,t[e]);return d},_=(d,t)=>H(d,R(t)),q=(d,t,e)=>rt(K(d),e,t),w=(d,t,e)=>new Promise((n,s)=>{var r=o=>{try{f(e.next(o))}catch(l){s(l)}},c=o=>{try{f(e.throw(o))}catch(l){s(l)}},f=o=>o.done?n(o.value):Promise.resolve(o.value).then(r,c);f((e=e.apply(d,t)).next())});const st=5e3,ot=2e4,it=3e3,at=(0,C.jT)();class N extends x.P{constructor(t,e,n,s){super(t,e,n,s),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,C.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 n={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(e)},s=yield this.fetchCors(this.networkInfo.subscanBaseUrl+t,n);if(!s.ok||s.status===429)throw new Error(`Subscan ${t} failed with ${s.status}`);const r=yield s.json();return j(r)})}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 n=this.allTokensMap[e];if(n==null)continue;const s=(0,T.Oj)(n.networkLocation);if(s==null)continue;const r=yield this.api.query.assets.account(s.contractAddress,this.walletInfo.keys.publicKey);let c="0";r.isSome&&(c=r.unwrap().balance.toString()),this.updateBalance(n.currencyCode,c)}})}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:n,success:s,hash:r,block_num:c,block_timestamp:f,module:o,amount:l,fee:y}=t;if(!s||o!=="balances")return;const O=(0,C.aL)(this.currencyInfo.currencyCode,this.currencyInfo,this.allTokensMap);if(O==null)return;const b=[];let I=(0,i.mul)(l,O.multiplier);e===this.walletInfo.keys.publicKey?I=`-${(0,i.add)(I,y)}`:b.push(n);const S={blockHeight:c,currencyCode:this.currencyInfo.currencyCode,date:f,isSend:I.startsWith("-"),memos:[],nativeAmount:I,networkFee:y,ourReceiveAddresses:b,signedTx:"",txid:r,walletId:this.walletId};this.addTransaction(this.currencyInfo.currencyCode,S)}queryTransactions(){return w(this,null,function*(){if(this.networkInfo.subscanBaseUrl==null){for(const t of this.enabledTokens)this.tokenCheckTransactionsStatus[t]=1;this.updateOnAddressesChecked();return}return yield at(()=>w(this,null,function*(){return yield this.queryTransactionsInner()}))})}queryTransactionsInner(){return w(this,null,function*(){let t=Math.floor(this.otherData.txCount/this.networkInfo.subscanQueryLimit);for(;;){const e={row:this.networkInfo.subscanQueryLimit,page:t,address:this.walletInfo.keys.publicKey};let n=0,s=[];try{const r=yield this.fetchSubscan("/scan/transfers",e),c=g(r.data);n=c.count,s=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(n===this.otherData.txCount||(s.forEach(r=>{try{this.processPolkadotTransaction(u(r))}catch{const f=r!=null&&typeof r.hash=="string"?r.hash:"";this.warn(`Ignoring invalid transfer ${f}`)}}),this.otherData.txCount=t*this.networkInfo.subscanQueryLimit+s.length,this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=Math.min(1,n===0?1:this.otherData.txCount/n),this.updateOnAddressesChecked(),n===this.otherData.txCount))break;t++}this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=1,this.updateOnAddressesChecked(),this.transactionsChangedArray.length>0&&(this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[])})}startEngine(){return w(this,null,function*(){this.engineOn=!0,yield this.tools.connectApi(this.walletId),this.api=this.tools.polkadotApi,this.minimumAddressBalance=this.api.consts.balances.existentialDeposit.toString(),this.addToLoop("queryBlockheight",ot).catch(()=>{}),this.addToLoop("queryBalance",st).catch(()=>{}),this.addToLoop("queryTransactions",it).catch(()=>{}),yield q(N.prototype,this,"startEngine").call(this)})}killEngine(){return w(this,null,function*(){yield q(N.prototype,this,"killEngine").call(this),yield this.tools.disconnectApi(this.walletId)})}resyncBlockchain(){return w(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getMaxSpendable(t){return w(this,null,function*(){if(t=(0,z.s)(t,this.currencyInfo),t.spendTargets.length===0||t.spendTargets[0].publicAddress==null)throw new Error("Missing public address");const e=this.getBalance({currencyCode:t.currencyCode});if(t.currencyCode!==this.currencyInfo.currencyCode){const l=[{publicAddress:t.spendTargets[0].publicAddress,nativeAmount:e}],y=_(Z({},t),{spendTargets:l});return yield this.makeSpend(y),e}const n=(0,i.sub)(e,this.api.consts.balances.existentialDeposit.toString()),s=[{publicAddress:t.spendTargets[0].publicAddress,nativeAmount:"0"}],r=_(Z({},t),{spendTargets:s}),f=(yield this.makeSpend(r)).networkFee,o=(l,y)=>{const O=(0,i.sub)(y,l);if((0,i.lte)(O,"1"))return l;const b=(0,i.add)(l,(0,i.div)(O,"2")),I=(0,C.X0)(b).replace("0x",""),S=I.length%2===1?`0${I}`:I,G=(0,i.mul)((0,i.div)(S.length.toString(),"2"),this.networkInfo.lengthFeePerByte),ht=(0,i.add)((0,i.add)(G,f),b);return(0,i.gt)(ht,n)?o(l,b):o(b,y)};return o("0",(0,i.add)(n,"1"))})}makeSpend(t){return w(this,null,function*(){t=(0,z.s)(t,this.currencyInfo);const{edgeSpendInfo:e,currencyCode:n}=this.makeSpendCheck(t),{memos:s=[]}=e;if(e.spendTargets.length!==1)throw new Error("Error: only one output allowed");const{nativeAmount:r,publicAddress:c}=e.spendTargets[0];if(c==null)throw new Error("makeSpend Missing publicAddress");if(r==null)throw new P.$D;const f=this.getBalance({currencyCode:n});let o,l;if(e.tokenId==null){const b=(0,i.sub)(f,this.api.consts.balances.existentialDeposit.toString());if((0,i.gt)(r,b))throw new P.C_;const S=yield(yield this.api.tx.balances.transferKeepAlive(c,r)).paymentInfo(this.walletInfo.keys.publicKey);if(l=(0,i.sub)(S.partialFee.toString(),(0,i.mul)(this.networkInfo.lengthFeePerByte,this.networkInfo.partialFeeOffsetMultiplier)),o=(0,i.add)(r,l),(0,i.gt)(o,b))throw new P.C_}else{if((0,i.gt)(r,f))throw new P.C_;o=r;const I=yield(yield this.api.tx.assets.transfer(parseInt(e.tokenId),c,r)).paymentInfo(this.walletInfo.keys.publicKey);l=(0,i.sub)(I.partialFee.toString(),(0,i.mul)(this.networkInfo.lengthFeePerByte,this.networkInfo.partialFeeOffsetMultiplier));const S=this.getBalance({currencyCode:this.currencyInfo.currencyCode}),G=(0,i.sub)(S,this.api.consts.balances.existentialDeposit.toString());if((0,i.gt)(l,G))throw new P.C_({currencyCode:this.currencyInfo.currencyCode,networkFee:l})}const y={publicAddress:c};return{blockHeight:0,currencyCode:n,date:0,isSend:!0,memos:s,nativeAmount:(0,i.mul)(o,"-1"),networkFee:l,otherParams:y,ourReceiveAddresses:[],signedTx:"",txid:"",walletId:this.walletId}})}signTx(t,e){return w(this,null,function*(){const n=k(this.currencyInfo.pluginId)(e),{publicAddress:s}=(0,C.Xp)(t);if(s==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,i.abs)((0,i.add)(t.nativeAmount,t.networkFee));yield this.checkRecipientMinimumBalance(this.getRecipientBalance,y,s),c=yield this.api.tx.balances.transferKeepAlive(s,y)}else if(r.contractAddress!=null){const y=(0,i.abs)(t.nativeAmount);c=yield this.api.tx.assets.transfer(parseInt(r.contractAddress),s,y)}else throw new Error("Unrecognized asset");const f=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",f.toPayload(),{version:this.api.extrinsicVersion});if(this.keypair==null)if(this.keypair=new E.Y({ss58Format:this.networkInfo.ss58Format}),n.mnemonic!=null)this.keypair.addFromUri(n.mnemonic);else{const y=p.YU.parse(n.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,f.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,C.oX)(t)}`)}catch(e){throw this.warn("FAILURE broadcastTx failed: ",e),e}return t})}getFreshAddress(){return w(this,null,function*(){const t=new E.Y,{publicKey:e}=this.walletInfo.keys,n=t.decodeAddress(e);return{publicAddress:t.encodeAddress(n,this.networkInfo.ss58Format)}})}}function ct(d,t,e,n){return w(this,null,function*(){const s=m(e),r=new N(d,t,s,n);return yield r.loadEngine(),r})}var v=(d,t,e)=>new Promise((n,s)=>{var r=o=>{try{f(e.next(o))}catch(l){s(l)}},c=o=>{try{f(e.throw(o))}catch(l){s(l)}},f=o=>o.done?n(o.value):Promise.resolve(o.value).then(r,c);f((e=e.apply(d,t)).next())});const{ed25519PairFromSeed:lt,isAddress:tt,mnemonicToMiniSecret:ut}=X;class et{constructor(t){const{builtinTokens:e,currencyInfo:n,io:s,networkInfo:r}=t;this.builtinTokens=e,this.currencyInfo=n,this.io=s,this.networkInfo=r,this.polkadotApiSubscribers=new Set}getDisplayPrivateKey(t){return v(this,null,function*(){var e;const{pluginId:n}=this.currencyInfo,s=k(n)(t.keys);return(e=s.mnemonic)!=null?e:s.privateKey})}getDisplayPublicKey(t){return v(this,null,function*(){const{keys:e}=m(t);return e.publicKey})}importPrivateKey(t){return v(this,null,function*(){const{pluginId:e}=this.currencyInfo;if((0,L.validateMnemonic)(t)){const n=ut(t),{secretKey:s}=lt(n);return{[`${e}Mnemonic`]:t,[`${e}Key`]:U.Buffer.from(s).toString("hex")}}else{if((0,C.vq)(t))return{[`${e}Key`]:t};throw new Error("InvalidPrivateKey")}})}createPrivateKey(t){return v(this,null,function*(){if(t!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const e=U.Buffer.from(this.io.random(32)),n=(0,L.entropyToMnemonic)(e);return yield this.importPrivateKey(n)})}derivePublicKey(t){return v(this,null,function*(){const{pluginId:e}=this.currencyInfo;return{publicKey:new E.Y({ss58Format:this.networkInfo.ss58Format}).addFromUri(t.keys[`${e}Mnemonic`]).address}})}parseUri(t,e,n){return v(this,null,function*(){var s,r;const{pluginId:c}=this.currencyInfo,f={[c]:!0},{parsedUri:o,edgeParsedUri:l}=(0,F.k)(this.currencyInfo,t,f,e!=null?e:this.currencyInfo.currencyCode,n),y=(s=l.publicAddress)!=null?s:"";if(!tt(y))throw new Error("InvalidPublicAddressError");return l.uniqueIdentifier=(r=o.query.memo)!=null?r:void 0,l})}encodeUri(t){return v(this,arguments,function*(e,n=[]){const{pluginId:s}=this.currencyInfo,{nativeAmount:r,currencyCode:c,publicAddress:f}=e;if(!tt(f))throw new Error("InvalidPublicAddressError");let o;if(typeof r=="string"){const y=(0,C.Qs)(c!=null?c:this.currencyInfo.currencyCode,this.currencyInfo,n);if(y==null)throw new Error("InternalErrorInvalidCurrencyCode");o=(0,i.div)(r,y.multiplier,10)}return(0,F.Q)(e,s,o)})}connectApi(t){return v(this,null,function*(){return this.polkadotApi==null&&(this.polkadotApi=yield Y.G.create({initWasm:!1,provider:new W.U(this.networkInfo.rpcNodes[0])})),this.polkadotApiSubscribers.add(t),this.polkadotApi})}disconnectApi(t){return v(this,null,function*(){this.polkadotApiSubscribers.delete(t),this.polkadotApiSubscribers.size===0&&(yield this.polkadotApi.disconnect(),this.polkadotApi=void 0)})}getTokenId(t){return v(this,null,function*(){(0,T.Rp)(t);const e=(0,T.Oj)(t.networkLocation);if(e==null)throw new Error("ErrorInvalidContractAddress");return e.contractAddress})}}function dt(d){return v(this,null,function*(){return new et(d)})}},52361:function(){},94616:function(){}}]);
@@ -403,7 +403,11 @@ const SYNC_NETWORK_INTERVAL = 10000
403
403
  }
404
404
 
405
405
  // Transfer funds transaction
406
- if (trxName != null) {
406
+ if (
407
+ trxName === 'trnsfiopubky' ||
408
+ trxName === 'unstakefio' ||
409
+ trxName === 'regaddress'
410
+ ) {
407
411
  nativeAmount = '0'
408
412
 
409
413
  if (trxName === 'regaddress') {
@@ -421,7 +425,7 @@ const SYNC_NETWORK_INTERVAL = 10000
421
425
  }
422
426
  }
423
427
 
424
- if (trxName === 'transfer' && data.amount != null) {
428
+ if (trxName === 'trnsfiopubky' && data.amount != null) {
425
429
  nativeAmount = data.amount.toString()
426
430
  actorSender = data.actor
427
431
  if (data.payee_public_key === this.walletInfo.keys.publicKey) {
@@ -25,7 +25,7 @@ var _cleaners = require('cleaners');
25
25
  }); exports.asGetFioName = asGetFioName
26
26
 
27
27
  const asFioTxName = _cleaners.asMaybe.call(void 0,
28
- _cleaners.asValue.call(void 0, 'unstakefio', 'transfer', 'regaddress'),
28
+ _cleaners.asValue.call(void 0, 'unstakefio', 'transfer', 'regaddress', 'trnsfiopubky'),
29
29
  null
30
30
  ); exports.asFioTxName = asFioTxName
31
31
 
@@ -14,6 +14,7 @@ var _biggystring = require('biggystring');
14
14
 
15
15
 
16
16
 
17
+
17
18
  var _types = require('edge-core-js/types');
18
19
  var _rfc4648 = require('rfc4648');
19
20
 
@@ -560,7 +561,7 @@ const queryTxMutex = _utils.makeMutex.call(void 0, )
560
561
  )
561
562
 
562
563
  if (this.keypair == null) {
563
- this.keypair = new (0, _api.Keyring)({ ss58Format: 0 })
564
+ this.keypair = new (0, _api.Keyring)({ ss58Format: this.networkInfo.ss58Format })
564
565
  if (polkadotPrivateKeys.mnemonic != null) {
565
566
  this.keypair.addFromUri(polkadotPrivateKeys.mnemonic)
566
567
  } else {
@@ -601,6 +602,20 @@ const queryTxMutex = _utils.makeMutex.call(void 0, )
601
602
 
602
603
  return edgeTransaction
603
604
  }
605
+
606
+ // This ensures that local wallets originally created with incorrect ss58 encoding can still get the correct address
607
+ async getFreshAddress() {
608
+ const keyring = new (0, _api.Keyring)()
609
+ const { publicKey } = this.walletInfo.keys
610
+ const decodedAddress = keyring.decodeAddress(publicKey)
611
+ const encodedAddress = keyring.encodeAddress(
612
+ decodedAddress,
613
+ this.networkInfo.ss58Format
614
+ )
615
+ return {
616
+ publicAddress: encodedAddress
617
+ }
618
+ }
604
619
  } exports.PolkadotEngine = PolkadotEngine;
605
620
 
606
621
  async function makeCurrencyEngine(
@@ -91,7 +91,7 @@ const { ed25519PairFromSeed, isAddress, mnemonicToMiniSecret } = utilCrypto
91
91
 
92
92
  async derivePublicKey(walletInfo) {
93
93
  const { pluginId } = this.currencyInfo
94
- const keyring = new (0, _api.Keyring)({ ss58Format: 0 })
94
+ const keyring = new (0, _api.Keyring)({ ss58Format: this.networkInfo.ss58Format })
95
95
  const pair = keyring.addFromUri(walletInfo.keys[`${pluginId}Mnemonic`])
96
96
  return {
97
97
  publicKey: pair.address
@@ -18,6 +18,7 @@ const builtinTokens = {
18
18
 
19
19
  const networkInfo = {
20
20
  rpcNodes: ['wss://mainnet.liberland.org/'],
21
+ ss58Format: 42,
21
22
  subscanBaseUrl: undefined,
22
23
  subscanQueryLimit: 100,
23
24
  partialFeeOffsetMultiplier: '2',
@@ -18,6 +18,7 @@ const builtinTokens = {
18
18
 
19
19
  const networkInfo = {
20
20
  rpcNodes: ['wss://testchain.liberland.org/'],
21
+ ss58Format: 42,
21
22
  subscanBaseUrl: undefined,
22
23
  subscanQueryLimit: 100,
23
24
  partialFeeOffsetMultiplier: '2',
@@ -6,6 +6,7 @@ var _innerPlugin = require('../../common/innerPlugin');
6
6
 
7
7
  const networkInfo = {
8
8
  rpcNodes: ['wss://rpc.polkadot.io'],
9
+ ss58Format: 0,
9
10
  subscanBaseUrl: 'https://polkadot.api.subscan.io/api',
10
11
  subscanQueryLimit: 100,
11
12
  partialFeeOffsetMultiplier: '1',
@@ -21,6 +21,7 @@ var _types = require('../common/types');
21
21
 
22
22
 
23
23
 
24
+
24
25
  const asPolkadotWalletOtherData = _cleaners.asObject.call(void 0, {
25
26
  txCount: _cleaners.asMaybe.call(void 0, _cleaners.asNumber, 0)
26
27
  }); exports.asPolkadotWalletOtherData = asPolkadotWalletOtherData
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "edge-currency-accountbased",
3
- "version": "3.2.2",
3
+ "version": "3.2.3",
4
4
  "description": "Edge currency plugin for account based currencies",
5
5
  "homepage": "https://edge.app/",
6
6
  "repository": {