edge-currency-accountbased 2.2.3 → 2.2.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/android/src/main/assets/edge-currency-accountbased/1944.chunk.js +4 -0
- package/android/src/main/assets/edge-currency-accountbased/2153.chunk.js +2 -0
- package/android/src/main/assets/edge-currency-accountbased/2821.chunk.js +2 -0
- package/android/src/main/assets/edge-currency-accountbased/2896.chunk.js +35 -0
- package/android/src/main/assets/edge-currency-accountbased/2945.chunk.js +25 -0
- package/android/src/main/assets/edge-currency-accountbased/3491.chunk.js +1 -0
- package/android/src/main/assets/edge-currency-accountbased/{620.chunk.js → 3620.chunk.js} +1 -1
- package/android/src/main/assets/edge-currency-accountbased/{666.chunk.js → 3666.chunk.js} +1 -1
- package/android/src/main/assets/edge-currency-accountbased/3720.chunk.js +1 -0
- package/android/src/main/assets/edge-currency-accountbased/{978.chunk.js → 3978.chunk.js} +1 -1
- package/android/src/main/assets/edge-currency-accountbased/4251.chunk.js +4 -0
- package/android/src/main/assets/edge-currency-accountbased/4431.chunk.js +1 -0
- package/android/src/main/assets/edge-currency-accountbased/4618.chunk.js +20 -0
- package/android/src/main/assets/edge-currency-accountbased/{627.chunk.js → 4627.chunk.js} +1 -1
- package/android/src/main/assets/edge-currency-accountbased/4650.chunk.js +1 -0
- package/android/src/main/assets/edge-currency-accountbased/{826.chunk.js → 5179.chunk.js} +1 -1
- package/android/src/main/assets/edge-currency-accountbased/{835.chunk.js → 5835.chunk.js} +1 -1
- package/android/src/main/assets/edge-currency-accountbased/5836.chunk.js +1 -0
- package/android/src/main/assets/edge-currency-accountbased/6266.chunk.js +1 -0
- package/android/src/main/assets/edge-currency-accountbased/6291.chunk.js +58 -0
- package/android/src/main/assets/edge-currency-accountbased/6341.chunk.js +44 -0
- package/android/src/main/assets/edge-currency-accountbased/7221.chunk.js +1 -0
- package/android/src/main/assets/edge-currency-accountbased/7428.chunk.js +6 -0
- package/android/src/main/assets/edge-currency-accountbased/{481.chunk.js → 7481.chunk.js} +1 -1
- package/android/src/main/assets/edge-currency-accountbased/7542.chunk.js +1 -0
- package/android/src/main/assets/edge-currency-accountbased/7786.chunk.js +2 -0
- package/android/src/main/assets/edge-currency-accountbased/8190.chunk.js +1 -0
- package/android/src/main/assets/edge-currency-accountbased/{689.chunk.js → 8689.chunk.js} +1 -1
- package/android/src/main/assets/edge-currency-accountbased/{726.chunk.js → 8726.chunk.js} +1 -1
- package/android/src/main/assets/edge-currency-accountbased/9068.chunk.js +1 -0
- package/android/src/main/assets/edge-currency-accountbased/{223.chunk.js → 9223.chunk.js} +2 -2
- package/android/src/main/assets/edge-currency-accountbased/9539.chunk.js +10 -0
- package/android/src/main/assets/edge-currency-accountbased/{645.chunk.js → 9645.chunk.js} +6 -6
- package/android/src/main/assets/edge-currency-accountbased/9669.chunk.js +7 -0
- package/android/src/main/assets/edge-currency-accountbased/algorand.chunk.js +1 -1
- package/android/src/main/assets/edge-currency-accountbased/bnb.chunk.js +2 -2
- package/android/src/main/assets/edge-currency-accountbased/edge-currency-accountbased.js +2 -18
- package/android/src/main/assets/edge-currency-accountbased/eos.chunk.js +5 -5
- package/android/src/main/assets/edge-currency-accountbased/ethereum.chunk.js +2 -2
- package/android/src/main/assets/edge-currency-accountbased/filecoin.chunk.js +1 -1
- package/android/src/main/assets/edge-currency-accountbased/fio.chunk.js +2 -2
- package/android/src/main/assets/edge-currency-accountbased/hedera.chunk.js +2 -2
- package/android/src/main/assets/edge-currency-accountbased/polkadot.chunk.js +2 -2
- package/android/src/main/assets/edge-currency-accountbased/ripple.chunk.js +2 -2
- package/android/src/main/assets/edge-currency-accountbased/solana.chunk.js +2 -2
- package/android/src/main/assets/edge-currency-accountbased/stellar.chunk.js +2 -2
- package/android/src/main/assets/edge-currency-accountbased/tezos.chunk.js +2 -2
- package/android/src/main/assets/edge-currency-accountbased/tron.chunk.js +1 -1
- package/android/src/main/assets/edge-currency-accountbased/zcash.chunk.js +2 -2
- package/lib/ethereum/info/avalancheInfo.js +8 -0
- package/lib/ethereum/info/ethereumInfo.js +8 -0
- package/lib/filecoin/FilecoinEngine.js +112 -79
- package/lib/filecoin/Filfox.js +68 -1
- package/lib/filecoin/filecoinInfo.js +8 -3
- package/lib/filecoin/filecoinTypes.js +1 -6
- package/lib/zcash/ZcashEngine.js +11 -9
- package/package.json +1 -1
- package/android/src/main/assets/edge-currency-accountbased/124.chunk.js +0 -35
- package/android/src/main/assets/edge-currency-accountbased/17.chunk.js +0 -58
- package/android/src/main/assets/edge-currency-accountbased/190.chunk.js +0 -1
- package/android/src/main/assets/edge-currency-accountbased/221.chunk.js +0 -1
- package/android/src/main/assets/edge-currency-accountbased/298.chunk.js +0 -44
- package/android/src/main/assets/edge-currency-accountbased/431.chunk.js +0 -1
- package/android/src/main/assets/edge-currency-accountbased/491.chunk.js +0 -1
- package/android/src/main/assets/edge-currency-accountbased/539.chunk.js +0 -10
- package/android/src/main/assets/edge-currency-accountbased/542.chunk.js +0 -1
- package/android/src/main/assets/edge-currency-accountbased/618.chunk.js +0 -20
- package/android/src/main/assets/edge-currency-accountbased/650.chunk.js +0 -1
- package/android/src/main/assets/edge-currency-accountbased/68.chunk.js +0 -1
- package/android/src/main/assets/edge-currency-accountbased/720.chunk.js +0 -1
- package/android/src/main/assets/edge-currency-accountbased/786.chunk.js +0 -2
- package/android/src/main/assets/edge-currency-accountbased/836.chunk.js +0 -1
- package/android/src/main/assets/edge-currency-accountbased/935.chunk.js +0 -1
- package/android/src/main/assets/edge-currency-accountbased/944.chunk.js +0 -4
- package/android/src/main/assets/edge-currency-accountbased/945.chunk.js +0 -25
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[805],{79014:function(ye,Z,w){w.d(Z,{Q:function(){return u},k:function(){return ae}});var F=w(77591),ue=w.n(F),O=w(24350),ie=w(84564),Q=w.n(ie),D=w(76714),c=Object.defineProperty,P=Object.getOwnPropertySymbols,ee=Object.prototype.hasOwnProperty,f=Object.prototype.propertyIsEnumerable,S=(b,T,q)=>T in b?c(b,T,{enumerable:!0,configurable:!0,writable:!0,value:q}):b[T]=q,W=(b,T)=>{for(var q in T||(T={}))ee.call(T,q)&&S(b,q,T[q]);if(P)for(var q of P(T))f.call(T,q)&&S(b,q,T[q]);return b};function ae(b,T,q,K,z=[]){const R=W({},Q()(T,{},!0)),J=T.startsWith(`${b.pluginId}://`);if(R.protocol!=null&&(R.protocol=R.protocol.replace(":","")),R.protocol!=null&&R.protocol!==""&&!q[R.protocol])throw new Error(`Uri protocol '${R.protocol}' is not supported for ${b.pluginId}.`);if(R.host===""&&R.pathname==="")throw new Error("Path and host not found in uri.");const L={publicAddress:R.host!==""?R.host:R.pathname.split("/")[0]},j=R.query.label,te=R.query.message,Y=R.query.category;(j!=null||te!=null||Y!=null||J)&&(L.metadata={},L.metadata.name=j,L.metadata.notes=te,L.metadata.category=Y,L.metadata.gateway=J!=null?J:!1);const G=R.query.amount;if(G!=null&&typeof G=="string"){K==null&&(K=b.currencyCode);const se=(0,D.Qs)(K!=null?K:"",b,z);if(se==null)throw new Error("InternalErrorInvalidCurrencyCode");let V=(0,F.mul)(G,se.multiplier);V=(0,F.toFixed)(V,0,0),L.nativeAmount=V,L.currencyCode=K}return{edgeParsedUri:L,parsedUri:R}}function u(b,T,q){if(b.publicAddress==null)throw new Error("InvalidPublicAddressError");if(q==null&&b.label==null&&b.message==null)return b.publicAddress;{let K="";q!=null&&(K+="amount="+q+"&"),(b.label!=null||b.message!=null)&&(typeof b.label=="string"&&(K+="label="+b.label+"&"),typeof b.message=="string"&&(K+="message="+b.message+"&")),K=K.substr(0,K.length-1);const z={scheme:T,path:b.publicAddress,query:K};return(0,O.qC)(z)}}},44285:function(ye,Z,w){w.r(Z),w.d(Z,{FioTools:function(){return me},checkAddress:function(){return de},makeCurrencyEngine:function(){return De},makeCurrencyTools:function(){return Ae}});var F=w(93491),ue=w(15179),O=w(77591),ie=w(2153),Q=w(79014),D=w(76714),c=w(5607),P=w(24827),ee=w(50857),f=w(3559),S=w(37858),W=w(82626),ae=w(37297),u=w(82448),b=w(94935),T=w(84650);const q=(0,u.su)({fio_domains:(0,u._2)((0,u.su)({fio_domain:u.XC,expiration:u.XC,is_public:u.mH})),fio_addresses:(0,u._2)((0,u.su)({fio_address:u.XC,remaining_bundled_tx:u.mH}))}),K=(0,u.su)({account_action_seq:u.mH,block_num:u.mH,block_time:u.XC,action_trace:(0,u.su)({receiver:u.XC,act:(0,u.su)({account:u.XC,name:u.XC,authorization:(0,u._2)((0,u.su)({actor:u.XC,permission:u.XC})),data:(0,u.su)({payee_public_key:(0,u.Zz)(u.XC),amount:(0,u.Zz)(u.mH),max_fee:(0,u.Zz)(u.mH),actor:(0,u.Zz)(u.XC),tpid:(0,u.Zz)(u.XC),quantity:(0,u.Zz)(u.XC),memo:(0,u.Zz)(u.XC),to:(0,u.Zz)(u.XC),from:(0,u.Zz)(u.XC)}),hex_data:u.XC}),trx_id:u.XC,block_num:u.mH,block_time:u.XC,producer_block_id:u.XC})}),z=(0,u.su)({actions:(0,u._2)(K)}),R=(0,u.su)({balance:u.mH,available:u.mH,staked:u.mH,srps:u.mH,roe:u.XC});var J=Object.defineProperty,he=Object.defineProperties,L=Object.getOwnPropertyDescriptors,j=Object.getOwnPropertySymbols,te=Object.getPrototypeOf,Y=Object.prototype.hasOwnProperty,G=Object.prototype.propertyIsEnumerable,se=Reflect.get,V=(g,e,s)=>e in g?J(g,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):g[e]=s,x=(g,e)=>{for(var s in e||(e={}))Y.call(e,s)&&V(g,s,e[s]);if(j)for(var s of j(e))G.call(e,s)&&V(g,s,e[s]);return g},H=(g,e)=>he(g,L(e)),pe=(g,e)=>{var s={};for(var t in g)Y.call(g,t)&&e.indexOf(t)<0&&(s[t]=g[t]);if(g!=null&&j)for(var t of j(g))e.indexOf(t)<0&&G.call(g,t)&&(s[t]=g[t]);return s},fe=(g,e,s)=>se(te(g),s,e),p=(g,e,s)=>new Promise((t,r)=>{var o=n=>{try{a(s.next(n))}catch(i){r(i)}},l=n=>{try{a(s.throw(n))}catch(i){r(i)}},a=n=>n.done?t(n.value):Promise.resolve(n.value).then(o,l);a((s=s.apply(g,e)).next())});const ge=1e4,_e=15e3,ke=1e4,be=[c.BP[c.aO.transferTokens],c.BP[c.aO.unStakeFioTokens],"regaddress"],we=1e4;class ne extends T.P{constructor(e,s,t,r,o){super(e,s,t,r),this.fioRequestsListChanged=(l,a)=>{function n(i,d){for(const h of i)if(d.findIndex(v=>v.fio_request_id===h.fio_request_id)<0)return!0;return!1}return!!(n(l,a)||n(a,l))},this.removeFioRequest=(l,a)=>{const n=this.otherData.fioRequests[a].findIndex(i=>i.fio_request_id===`${l}`);n>-1&&this.otherData.fioRequests[a].splice(n,1)},this.fetchCors=(0,D.zR)(e.io),this.tpid=o,this.networkInfo=e.networkInfo,this.refBlock={expiration:"",ref_block_num:0,ref_block_prefix:0},this.fees=new Map,this.actor=F.rn.accountHash(this.walletInfo.keys.publicKey).accountnm,this.obtData=[],this.otherMethods={fioAction:(l,a)=>p(this,null,function*(){return yield this.multicastServers(l,a)}),getFioAddresses:()=>p(this,null,function*(){return this.otherData.fioAddresses}),getFioAddressNames:()=>p(this,null,function*(){return this.otherData.fioAddresses.map(l=>l.name)}),getFioDomains:()=>p(this,null,function*(){return this.otherData.fioDomains}),getFioRequests:(l,a,n=50)=>p(this,null,function*(){const i=n*(a-1),d=n*a;return this.otherData.fioRequests[l].sort((h,v)=>h.time_stamp<v.time_stamp?1:-1).slice(i,d)}),getObtData:()=>p(this,null,function*(){return this.obtData})}}localDataDirty(){this.walletLocalDataDirty=!0}setOtherData(e){this.otherData=(0,c.CL)(e)}getUTCDate(e){const s=new Date(e);return Date.UTC(s.getFullYear(),s.getMonth(),s.getDate(),s.getHours(),s.getMinutes(),s.getSeconds())}getUnlockDate(e){const s=Math.floor(e.getTime()/c.qj)*c.qj;return new Date(s+c.dm)}checkBlockchainInnerLoop(){return p(this,null,function*(){try{const e=yield this.multicastServers("getChainInfo"),s=e.head_block_num;this.walletLocalData.blockHeight!==s&&(this.checkDroppedTransactionsThrottled(),this.walletLocalData.blockHeight=s,this.localDataDirty(),this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight));const t=yield this.multicastServers("getBlock",e),r=new Date(`${e.head_block_time}Z`);r.setSeconds(r.getSeconds()+180);const o=r.toISOString();this.refBlock={expiration:o.substring(0,o.length-1),ref_block_num:t.block_num&65535,ref_block_prefix:t.ref_block_prefix}}catch(e){this.error("checkBlockchainInnerLoop Error fetching height: ",e)}})}getBalance(e){return super.getBalance(e)}doInitialBalanceCallback(){var e;super.doInitialBalanceCallback();const s=this.networkInfo.balanceCurrencyCodes;for(const t of Object.values(s))try{this.currencyEngineCallbacks.onBalanceChanged(t,(e=this.walletLocalData.totalBalances[t])!=null?e:"0")}catch(r){this.log.error("doInitialBalanceCallback Error for currencyCode",t,r)}try{this.currencyEngineCallbacks.onStakingStatusChanged(x({},this.otherData.stakingStatus))}catch(t){this.error("doInitialBalanceCallback onStakingStatusChanged",t)}}checkUnStakeTx(e){return e.name===c.BP[c.aO.unStakeFioTokens]||e.data!=null&&e.data.memo===c.Nd}updateStakingStatus(e,s,t,r){const o=this.getUnlockDate(new Date(this.getUTCDate(s))),l=this.otherData.stakingStatus.stakedAmounts.findIndex(a=>{var n;return((n=a.unlockDate)==null?void 0:n.getTime())===o.getTime()});if(l<0){const a=this.otherData.stakingStatus.stakedAmounts.findIndex(i=>{var d,h;return o.getTime()>=((h=(d=i.unlockDate)==null?void 0:d.getTime())!=null?h:0)}),n=a<0?this.otherData.stakingStatus.stakedAmounts.length:a;this.otherData.stakingStatus.stakedAmounts.splice(n,0,{nativeAmount:e,unlockDate:o,otherParams:{date:new Date(s),txs:[{txId:t,nativeAmount:e,blockTime:s,txName:r}]}})}else{const a=H(x({},this.otherData.stakingStatus.stakedAmounts[l]),{nativeAmount:"0"}),n=a.otherParams.txs.findIndex(({txId:i,txName:d})=>i===t&&d===r);n<0?a.otherParams.txs.push({txId:t,nativeAmount:e,blockTime:s,txName:r}):a.otherParams.txs[n]={txId:t,nativeAmount:e,blockTime:s,txName:r};for(const i of a.otherParams.txs)a.nativeAmount=(0,O.add)(a.nativeAmount,i.nativeAmount);this.otherData.stakingStatus.stakedAmounts[l]=a}this.localDataDirty();try{this.currencyEngineCallbacks.onStakingStatusChanged(x({},this.otherData.stakingStatus))}catch{this.error("onStakingStatusChanged error")}}getStakingStatus(){return p(this,null,function*(){return x({},this.otherData.stakingStatus)})}processTransaction(e,s,t=this.currencyInfo.currencyCode){var r,o,l,a,n,i,d,h,v;const{act:{name:I,data:_,account:y,authorization:E}}=e.action_trace;let C,m,k="0",A={account:y,name:I,authorization:E,data:_,meta:{}};const $=[];if(e.block_num<=this.otherData.highestTxHeight)return e.block_num;if(be.includes(I)){C="0",I==="regaddress"&&e.action_trace.act.authorization.some(U=>U.actor===this.actor)&&(k=String((r=e.action_trace.act.data.max_fee)!=null?r:0),C=`-${k}`),I===c.BP[c.aO.transferTokens]&&_.amount!=null&&(C=_.amount.toString(),m=_.actor,_.payee_public_key===this.walletInfo.keys.publicKey?($.push(this.walletInfo.keys.publicKey),m===s&&(C="0")):C=`-${C}`);const N=this.findTransaction(t,e.action_trace.trx_id);if(N>-1){const U=this.transactionList[t][N];if(A=H(x(x({},U.otherParams),A),{data:x(x({},(l=(o=U.otherParams)==null?void 0:o.data)!=null?l:{}),A.data),meta:x(x({},(n=(a=U.otherParams)==null?void 0:a.meta)!=null?n:{}),A.meta)}),A.meta.isTransferProcessed!=null)return e.block_num;A.meta.isFeeProcessed!=null?I===c.BP[c.aO.transferTokens]?(C=(0,O.sub)(C,U.networkFee),k=U.networkFee):(C=U.nativeAmount,k="0"):this.error("processTransaction error - existing spend transaction should have isTransferProcessed or isFeeProcessed set")}this.checkUnStakeTx(A)&&this.updateStakingStatus(_.amount!=null?_.amount.toString():"0",e.block_time,e.action_trace.trx_id,I),A.meta.isTransferProcessed=!0;const M={txid:e.action_trace.trx_id,date:this.getUTCDate(e.block_time)/1e3,currencyCode:t,blockHeight:e.block_num>0?e.block_num:0,nativeAmount:C,isSend:C.startsWith("-"),networkFee:k,ourReceiveAddresses:$,signedTx:"",otherParams:A,walletId:this.walletId};this.addTransaction(t,M)}if(I===c.BP.transfer&&_.quantity!=null){const[N]=_.quantity.split(" "),M=N.toString(),U=(0,D.aL)(t,this.currencyInfo,this.allTokensMap);if(U==null)return this.error(`Received unsupported currencyCode: ${t}`),0;const X=(0,O.mul)(M,U.multiplier);_.to===s?(C=`${X}`,k=`-${X}`):(C=`-${X}`,k=X);const re=this.findTransaction(t,e.action_trace.trx_id);if(re>-1){const oe=this.transactionList[t][re];if(A=H(x(x({},A),oe.otherParams),{data:x(x({},A.data),(d=(i=oe.otherParams)==null?void 0:i.data)!=null?d:{}),meta:x(x({},A.meta),(v=(h=oe.otherParams)==null?void 0:h.meta)!=null?v:{})}),A.meta.isFeeProcessed!=null)return e.block_num;A.meta.isTransferProcessed!=null?_.to!==s?C=(0,O.sub)(oe.nativeAmount,k):k="0":this.error("processTransaction error - existing spend transaction should have isTransferProcessed or isFeeProcessed set")}this.checkUnStakeTx(A)&&this.updateStakingStatus(X,e.block_time,e.action_trace.trx_id,I),A.meta.isFeeProcessed=!0;const Pe={txid:e.action_trace.trx_id,date:this.getUTCDate(e.block_time)/1e3,currencyCode:t,blockHeight:e.block_num>0?e.block_num:0,nativeAmount:C,isSend:C.startsWith("-"),networkFee:k,signedTx:"",ourReceiveAddresses:[],otherParams:A,walletId:this.walletId};this.addTransaction(t,Pe)}return e.block_num}getSortedHistoryNodesLastActionSeqNumbers(){return p(this,null,function*(){const e=this.networkInfo.historyNodeUrls.map((t,r)=>p(this,null,function*(){var o;try{const l=yield this.requestHistory(r,{account_name:this.actor,pos:-1},c.pg.getActions);return((o=l==null?void 0:l.error)==null?void 0:o.noNodeForIndex)!=null?{nodeIndex:r,seqNumber:-1}:(z(l),l.actions.length===0?{nodeIndex:r,seqNumber:-1}:{nodeIndex:r,seqNumber:l.actions[l.actions.length-1].account_action_seq})}catch{return{nodeIndex:r,seqNumber:-1}}})),s=yield Promise.all(e);return s.sort((t,r)=>r.seqNumber-t.seqNumber),s})}checkTransactions(e){return p(this,null,function*(){var s,t;if((e==null?void 0:e.length)===0)return!1;if(e=e!=null?e:yield this.getSortedHistoryNodesLastActionSeqNumbers(),e.reduce((i,d)=>i+d.seqNumber,0)===-e.length)return!0;let r=this.otherData.highestTxHeight;const o=e[0].seqNumber,l=e[0].nodeIndex;let a=Math.max(0,o-c.WX+1),n=!1;for(;!n;){let i;try{if(i=yield this.requestHistory(l,{account_name:this.actor,pos:a,offset:c.WX-1},c.pg.getActions),((s=i.error)==null?void 0:s.noNodeForIndex)!=null)return!1;let d=[];if(((t=i.actions)==null?void 0:t.length)>0)d=i.actions;else break;for(let h=d.length-1;h>-1;h--){const v=d[h];K(v);const I=this.processTransaction(v,this.actor);if(I>r)r=I;else if(I===r&&h===c.WX-1||I<this.otherData.highestTxHeight){n=!0;break}}if(a===0)break;a=Math.max(0,a-c.WX);continue}catch{return yield this.checkTransactions(e.slice(1))}}return r>this.otherData.highestTxHeight&&(this.otherData.highestTxHeight=r,this.localDataDirty()),!0})}checkTransactionsInnerLoop(){return p(this,null,function*(){let e;try{e=yield this.checkTransactions()}catch(s){this.error("checkTransactionsInnerLoop fetches failed with error: ",s);return}e&&(this.tokenCheckTransactionsStatus.FIO=1,this.updateOnAddressesChecked()),this.transactionsChangedArray.length>0&&(this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[])})}requestHistory(e,s,t){return p(this,null,function*(){if(this.networkInfo.historyNodeUrls[e]==null)return{error:{noNodeForIndex:!0}};const r=this.networkInfo.historyNodeUrls[e],o=JSON.stringify(s);return yield(yield fetch(`${r}history/${t}`,{method:"POST",headers:{"Content-Length":(o.length*2).toString(),Accept:"application/json","Content-Type":"application/json"},body:o})).json()})}fioApiRequest(e,s,t,r=!1){return p(this,null,function*(){var o,l,a,n;const i=new F.rn("",this.walletInfo.keys.publicKey,e,this.fetchCors,void 0,this.tpid,r);let d;try{switch(s){case"getChainInfo":d=yield i.transactions.getChainInfo();break;case"getBlock":d=yield i.transactions.getBlock(t);break;case"getObtData":case"getPendingFioRequests":case"getSentFioRequests":{const{endpoint:h,body:v}=t;d=yield i.transactions.executeCall(h,JSON.stringify(v));break}default:d=yield i.genericAction(s,t)}}catch(h){if(h.errorCode!=null&&P.lI.includes(h.errorCode))((a=(l=(o=h.json)==null?void 0:o.fields)==null?void 0:l[0])==null?void 0:a.error)!=null&&(h.message=h.json.fields[0].error),d={isError:!0,data:{code:h.errorCode,message:(n=h.message)!=null?n:(0,D.HY)(h),json:h.json,list:h.list}},h.errorCode!==404&&this.log(`fioApiRequest error. actionName: ${s} - apiUrl: ${e} - message: ${JSON.stringify(h.json)}`);else throw this.log(`fioApiRequest error. actionName: ${s} - apiUrl: ${e} - message: `,h),h}return d})}executePreparedTrx(e,s,t){return p(this,null,function*(){var r,o,l;const a=new F.rn("",this.walletInfo.keys.publicKey,e,this.fetchCors,void 0,this.tpid,!0);let n;this.warn(`executePreparedTrx. preparedTrx: ${JSON.stringify(t)} - apiUrl: ${e}`);try{n=yield a.executePreparedTrx(s,t),this.warn(`executePreparedTrx. res: ${JSON.stringify(n)} - apiUrl: ${e} - endpoint: ${s}`)}catch(i){throw i.errorCode!=null&&P.lI.includes(i.errorCode)?(this.log(`executePreparedTrx error. requestParams: ${JSON.stringify(t)} - apiUrl: ${e} - endpoint: ${s} - message: ${JSON.stringify(i.json)}`),((l=(o=(r=i.json)==null?void 0:r.fields)==null?void 0:o[0])==null?void 0:l.error)!=null&&(i.message=i.json.fields[0].error),i):(this.log(`executePreparedTrx error. requestParams: ${JSON.stringify(t)} - apiUrl: ${e} - endpoint: ${s} - message: `,i),i)}return n})}multicastServers(e,s){return p(this,null,function*(){var t,r,o,l,a;let n;if(c.K1[e]){const i=(0,f.h0)(s);if(this.warn(`multicastServers executePreparedTrx. actionName: ${e} - res: ${JSON.stringify(i)}`),n=yield(0,D.Wp)((0,D.Sy)(this.networkInfo.apiUrls.map(d=>p(this,null,function*(){return yield(0,D.Vs)(this.executePreparedTrx(d,S.EndPoint[c.VW[e]],i),1e4)})))),this.warn(`multicastServers res. actionName: ${e} - res: ${JSON.stringify(n)}`),n==null)throw new Error("Service is unavailable")}else e==="getFioNames"?(n=yield(0,D.ml)(this.networkInfo.apiUrls.map(i=>p(this,null,function*(){return yield(0,D.Vs)(this.fioApiRequest(i,e,s),1e4)})),i=>{const d=(0,f.$K)(c.Mi)(i);return d!=null?d.data.json.message:(0,f.e1)(i)},2),((r=(t=n==null?void 0:n.data)==null?void 0:t.json)==null?void 0:r.message)===c.Mi&&(n={fio_domains:[],fio_addresses:[]})):e==="getFioBalance"?(n=yield(0,D.ml)(this.networkInfo.apiUrls.map(i=>p(this,null,function*(){return yield(0,D.Vs)(this.fioApiRequest(i,e,s),1e4)})),i=>{const d=(0,f.$K)(c.d9)(i);return d!=null?d.data.json.message:(0,f.sq)(i)},2),((l=(o=n==null?void 0:n.data)==null?void 0:o.json)==null?void 0:l.message)===c.d9&&(n={balance:0,available:0,staked:0,srps:0,roe:""})):e==="getFees"?n=yield(0,D.QJ)((0,D.Sy)(this.networkInfo.apiUrls.map(i=>()=>p(this,null,function*(){const d=new F.rn("",this.walletInfo.keys.publicKey,i,this.fetchCors,void 0,this.tpid),{endpoint:h,param:v}=s,I=yield d.getFee(h,v);return(0,f.lZ)(I).fee.toString()})))):n=yield(0,D.QJ)((0,D.Sy)(this.networkInfo.apiUrls.map(i=>()=>p(this,null,function*(){return yield this.fioApiRequest(i,e,s)}))));if(n.isError!=null){const i=new P.OU((a=n.errorMessage)!=null?a:n.data.message);throw i.json=n.data.json,i.list=n.data.list,i.errorCode=n.data.code,i}return n})}checkAccountInnerLoop(){return p(this,null,function*(){const e=this.currencyInfo.currencyCode,s=this.networkInfo.balanceCurrencyCodes;typeof this.walletLocalData.totalBalances[e]>"u"&&this.updateBalance(e,"0");try{const t={staked:"0",locked:"0"},{balance:r,available:o,staked:l,srps:a,roe:n}=R(yield this.multicastServers("getFioBalance")),i=String(r);t.staked=String(l),t.locked=(0,O.sub)(i,String(o)),this.otherData.srps=a,this.otherData.stakingRoe=n,this.updateBalance(e,i),this.updateBalance(s.staked,t.staked),this.updateBalance(s.locked,t.locked)}catch(t){this.log.warn("checkAccountInnerLoop getFioBalance error: ",t)}try{const t=q(yield this.multicastServers("getFioNames",{fioPublicKey:this.walletInfo.keys.publicKey}));let r=!1,o=!1,l=!1;if(t.fio_addresses.length!==this.otherData.fioAddresses.length)o=!0;else{for(const a of t.fio_addresses){const n=this.otherData.fioAddresses.find(i=>i.name===a.fio_address);if(n!=null){if(n.bundledTxs!==a.remaining_bundled_tx){o=!0;break}}else{o=!0;break}}if(!o){for(const a of this.otherData.fioAddresses)if(t.fio_addresses.findIndex(n=>n.fio_address===a.name)<0){o=!0;break}}}if(t.fio_domains.length!==this.otherData.fioDomains.length)l=!0;else{for(const a of t.fio_domains){const n=this.otherData.fioDomains.find(i=>i.name===a.fio_domain);if(n!=null){if(n.expiration!==a.expiration){l=!0;break}if(n.isPublic!==(a.is_public===1)){l=!0;break}}else{l=!0;break}}if(!l){for(const a of this.otherData.fioDomains)if(t.fio_domains.findIndex(n=>n.fio_domain===a.name)<0){l=!0;break}}}o&&(r=!0,this.otherData.fioAddresses=t.fio_addresses.map(a=>({name:a.fio_address,bundledTxs:a.remaining_bundled_tx}))),l&&(r=!0,this.otherData.fioDomains=t.fio_domains.map(a=>({name:a.fio_domain,expiration:a.expiration,isPublic:a.is_public===1}))),r&&this.localDataDirty()}catch(t){this.warn("checkAccountInnerLoop getFioNames error: ",t)}})}fetchEncryptedFioRequests(e,s){return p(this,null,function*(){const r=e==="PENDING"?"getPendingFioRequests":"getSentFioRequests";let o=100,l=1;const a=[];for(;o===100;)try{const n=yield this.multicastServers(r,{endpoint:s.getEndPoint(),body:{fio_public_key:this.walletInfo.keys.publicKey,limit:100,offset:(l-1)*100}}),i=(0,f.S_)(n),{requests:d,more:h}=i;if(a.push(...d),h===0)break;l++,o=d.length}catch(n){const i=(0,u.Vk)(f.Pq)(n.json);(i==null?void 0:i.message)!=="No FIO Requests"&&this.error("fetchEncryptedFioRequests error: ",n);break}return a})}fetchEncryptedObtData(e,s){return p(this,null,function*(){let r=100,o=1;const l=[];for(;r===100;){let a;try{a=yield this.multicastServers(e,{endpoint:s.getEndPoint(),body:{fio_public_key:this.walletInfo.keys.publicKey,limit:100,offset:(o-1)*100}});const n=(0,f._v)(a),{obt_data_records:i,more:d}=n;if(l.push(...i),d===0)break;o++,r=i.length}catch(n){const i=(0,u.Vk)(f.Pq)(n.json);(i==null?void 0:i.message)!=="No FIO Requests"&&this.error("fetchEncryptedObtData error: ",n);break}}return l})}syncNetwork(e){return p(this,null,function*(){var s;const t=(0,f.UW)(e==null?void 0:e.privateKeys);let r=!1;const o=(i,d)=>p(this,null,function*(){var h;const v=yield this.fetchEncryptedFioRequests(i,d);d.privateKey=t.fioKey,d.publicKey=this.walletInfo.keys.publicKey;const I=(h=d.decrypt({requests:v}))!=null?h:{requests:[]};this.fioRequestsListChanged(this.otherData.fioRequests[i],I.requests)&&(this.otherData.fioRequests[i]=[...I.requests],r=!0)});yield o("PENDING",new W.PendingFioRequests(this.walletInfo.keys.publicKey)),yield o("SENT",new W.SentFioRequests(this.walletInfo.keys.publicKey)),r&&this.localDataDirty();const l=new W.GetObtData(this.walletInfo.keys.publicKey),a=yield this.fetchEncryptedObtData("getObtData",l);l.privateKey=t.fioKey,l.publicKey=this.walletInfo.keys.publicKey;const n=(s=l.decrypt({obt_data_records:a}))!=null?s:{obt_data_records:[]};return this.obtData=n.obt_data_records,we})}getFee(e,s){return p(this,null,function*(){let t=this.fees.get(e);if(t==null||t.expiration+30*1e3<Date.now()){const o={fee:yield this.multicastServers("getFees",{endpoint:e,param:s}),expiration:Date.now()};this.fees.set(e,o),t=o}return t.fee})}startEngine(){return p(this,null,function*(){this.engineOn=!0,this.addToLoop("checkBlockchainInnerLoop",_e).catch(()=>{}),this.addToLoop("checkAccountInnerLoop",ge).catch(()=>{}),this.addToLoop("checkTransactionsInnerLoop",ke).catch(()=>{}),yield fe(ne.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return p(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getMaxSpendable(e){return p(this,null,function*(){var s;const t=this.getBalance({currencyCode:e.currencyCode}),r=(s=this.walletLocalData.totalBalances[this.networkInfo.balanceCurrencyCodes.locked])!=null?s:"0";e.spendTargets[0].nativeAmount="1";const o=yield this.makeSpend(e),l=(0,O.sub)((0,O.sub)(t,o.networkFee),r);if((0,O.lt)(l,"0"))throw new b.C_({networkFee:o.networkFee});return l})}makeSpend(e){return p(this,null,function*(){var s,t;const{edgeSpendInfo:r,nativeBalance:o,currencyCode:l}=this.makeSpendCheck(e),a=(s=this.walletLocalData.totalBalances[this.networkInfo.balanceCurrencyCodes.locked])!=null?s:"0",n=(0,O.sub)(o,a),i=r.spendTargets[0],{publicAddress:d}=i,{nativeAmount:h}=i;if(d==null)throw new Error("makeSpend Missing publicAddress");if(h==null)throw new b.$D;let{otherParams:v}=r;(v==null||Object.keys(v).length===0)&&(v={action:{name:c.aO.transferTokens,params:{payeeFioPublicKey:d,amount:h,maxFee:0}}});const{name:I,params:_}=(0,f.iR)(v.action);let y,E;switch(I){case c.aO.transferTokens:{y=yield this.getFee(S.EndPoint.transferTokens),E={account:"fio.token",action:c.BP[c.aO.transferTokens],data:{payee_public_key:d,amount:h,max_fee:y}};break}case c.aO.stakeFioTokens:{const{fioAddress:m}=(0,f.NB)(_);y=yield this.getFee(S.EndPoint.stakeFioTokens,m),E={account:"fio.staking",action:c.BP[I],data:{amount:h,fio_address:m,actor:this.actor,max_fee:y}};break}case c.aO.unStakeFioTokens:{const{fioAddress:m}=(0,f.NB)(_);y=yield this.getFee(S.EndPoint.unStakeFioTokens,m),E={account:"fio.staking",action:c.BP[I],data:{amount:h,fio_address:m,actor:this.actor,max_fee:y}};const k=this.getUnlockDate(new Date),A=(t=this.walletLocalData.totalBalances[this.networkInfo.balanceCurrencyCodes.staked])!=null?t:"0";if((0,O.gt)(h,A)||(0,O.gt)(`${y}`,n))throw new b.C_;const $=(0,O.mul)((0,O.mul)((0,O.div)(h,A,18),`${this.otherData.srps}`),this.otherData.stakingRoe),N=(0,O.max)((0,O.sub)($,h),"0");v.ui={accrued:$,estReward:N,unlockDate:k};break}case c.aO.transferFioAddress:{const{fioAddress:m}=(0,f.NB)(_);y=yield this.getFee(S.EndPoint.transferFioAddress,m),E={account:"fio.address",action:"xferaddress",data:{fio_address:m,new_owner_fio_public_key:d,actor:this.actor,max_fee:y}};break}case c.aO.transferFioDomain:{const{fioDomain:m}=(0,f.L2)(_);y=yield this.getFee(S.EndPoint.transferFioDomain),E={account:"fio.address",action:"xferdomain",data:{fio_domain:m,new_owner_fio_public_key:d,actor:this.actor,max_fee:y}};break}case c.aO.addPublicAddresses:{const{fioAddress:m,publicAddresses:k}=(0,f.PH)(_);y=yield this.getFee(S.EndPoint.addPubAddress,m),E={account:"fio.address",action:"addaddress",data:{fio_address:m,public_addresses:k,actor:this.actor,max_fee:y}};break}case c.aO.removePublicAddresses:{const{fioAddress:m,publicAddresses:k}=(0,f.PH)(_);y=yield this.getFee(S.EndPoint.removePubAddress,m),E={account:"fio.address",action:"remaddress",data:{fio_address:m,public_addresses:k,actor:this.actor,max_fee:y}};break}case c.aO.registerFioAddress:{const{fioAddress:m}=(0,f.NB)(_);y=yield this.getFee(S.EndPoint.registerFioAddress),E={account:"fio.address",action:"regaddress",data:{fio_address:m,owner_fio_public_key:this.walletInfo.keys.publicKey,max_fee:y,actor:this.actor}};break}case c.aO.registerFioDomain:{const{fioDomain:m}=(0,f.AJ)(_);y=yield this.getFee(S.EndPoint.registerFioDomain),E={account:"fio.address",action:"regdomain",data:{fio_domain:m,owner_fio_public_key:this.walletInfo.keys.publicKey,max_fee:y,actor:this.actor}};break}case c.aO.renewFioDomain:{const{fioDomain:m}=(0,f.AJ)(_);y=yield this.getFee(S.EndPoint.renewFioDomain),E={account:"fio.address",action:"renewdomain",data:{fio_domain:m,max_fee:y,actor:this.actor}};break}case c.aO.addBundledTransactions:{const{bundleSets:m,fioAddress:k}=(0,f.Ej)(_);y=yield this.getFee(S.EndPoint.addBundledTransactions,k),E={account:"fio.address",action:"addbundles",data:{fio_address:k,bundle_sets:m,actor:this.actor,max_fee:y}};break}case c.aO.setFioDomainPublic:{const{fioDomain:m,isPublic:k}=(0,f.oY)(_);y=yield this.getFee(S.EndPoint.setFioDomainPublic),E={account:"fio.address",action:"setdomainpub",data:{fio_domain:m,is_public:k?1:0,max_fee:y,actor:this.actor}};break}case c.aO.rejectFundsRequest:{const{fioRequestId:m,payerFioAddress:k}=(0,f.OR)(_);y=yield this.getFee(S.EndPoint.rejectFundsRequest,k),E={account:"fio.reqobt",action:"rejectfndreq",data:{fio_request_id:m,max_fee:y,actor:this.actor}};break}case c.aO.cancelFundsRequest:{const{fioAddress:m,fioRequestId:k}=(0,f.mO)(_);y=yield this.getFee(S.EndPoint.cancelFundsRequest,m),E={account:"fio.reqobt",action:"cancelfndreq",data:{fio_request_id:k,max_fee:y,actor:this.actor}};break}case c.aO.recordObtData:{const{payerFioAddress:m}=(0,f.XB)(_);y=yield this.getFee(S.EndPoint.recordObtData,m);break}case c.aO.requestFunds:{const{payeeFioAddress:m}=(0,f.Vd)(_);y=yield this.getFee(S.EndPoint.newFundsRequest,m);break}default:throw new Error("Unrecognized FIO action")}return{txid:"",date:0,currencyCode:l,blockHeight:0,nativeAmount:(0,O.sub)(`-${h}`,`${y}`),isSend:!0,networkFee:`${y}`,ourReceiveAddresses:[],signedTx:"",otherParams:H(x({},v),{txParams:E}),walletId:this.walletId}})}signTx(e,s){return p(this,null,function*(){const t=(0,f.UW)(s),r=(0,D.Xp)(e);let o=(0,u.Vk)(f.B3)(r.txParams);const l=new ae.Transactions;if(o==null){const{name:h,params:v}=(0,f.iR)(r.action),{networkFee:I}=e;switch(h){case c.aO.recordObtData:{const{payerFioAddress:_,payeeFioAddress:y,payerPublicAddress:E,payeePublicAddress:C,amount:m,tokenCode:k,chainCode:A,obtId:$,memo:N,status:M,fioRequestId:U}=(0,f.XB)(v),X={payer_public_address:E,payee_public_address:C,amount:m,chain_code:A,token_code:k,status:M,obt_id:$,memo:N,hash:void 0,offline_url:void 0},re=l.getCipherContent("record_obt_data_content",X,t.fioKey,E);o={account:"fio.reqobt",action:"recordobt",data:{payer_fio_address:_,payee_fio_address:y,content:re,fio_request_id:U,max_fee:I,actor:this.actor}};break}case c.aO.requestFunds:{const{payerFioAddress:_,payerFioPublicKey:y,payeeFioAddress:E,payeeTokenPublicAddress:C,amount:m,chainCode:k,tokenCode:A,memo:$}=(0,f.Vd)(v),N={payee_public_address:C,amount:m,chain_code:k,token_code:A,memo:$,hash:void 0,offline_url:void 0},M=l.getCipherContent("new_funds_content",N,t.fioKey,y);o={account:"fio.reqobt",action:"newfundsreq",data:{payer_fio_address:_,payee_fio_address:E,content:M,max_fee:I,actor:this.actor}};break}default:throw new Error("Unknown FIO action")}}const a=yield l.createRawTransaction({action:o.action,account:o.account,data:H(x({},o.data),{tpid:this.tpid}),publicKey:this.walletInfo.keys.publicKey,chainData:this.refBlock}),{serializedContextFreeData:n,serializedTransaction:i}=yield l.serialize({chainId:this.networkInfo.chainId,transaction:a}),d=yield l.sign({chainId:this.networkInfo.chainId,privateKeys:[t.fioKey],transaction:a,serializedTransaction:i,serializedContextFreeData:n});return e.otherParams=H(x({},e.otherParams),{signedTx:d}),e})}broadcastTx(e){return p(this,null,function*(){var s;const t=(0,D.Xp)(e);if(((s=t.action)==null?void 0:s.name)==null)throw new Error('Action is not set, "action" prop of otherParams is required for FIO actions');const r=(0,f.h0)(t.signedTx),o=(0,f.Yd)(yield this.multicastServers(t.action.name,r));e.metadata={notes:o.transaction_id},e.txid=o.transaction_id,e.date=Date.now()/1e3,e.blockHeight=o.block_num,this.warn(`SUCCESS broadcastTx
|
|
2
|
-
${(0,D.oX)(e)}`);const l=o,{block_num:a,block_time:n,transaction_id:i}=l,d=pe(l,["block_num","block_time","transaction_id"]);return e.otherParams=H(x({},t),{broadcastResult:d}),e})}saveTx(e){return p(this,null,function*(){var s;const t=(0,D.Xp)(e),{broadcastResult:r={},action:o}=t,{name:l,params:a}=(0,f.iR)(o);try{switch(l){case c.aO.transferFioDomain:{const n=this.otherData.fioDomains.findIndex(({name:i})=>i===a.fioDomain);n>=0&&(this.otherData.fioDomains.splice(n,1),this.localDataDirty());break}case c.aO.transferFioAddress:{const n=this.otherData.fioAddresses.findIndex(({name:i})=>i===a.fioAddress);n>=0&&(this.otherData.fioAddresses.splice(n,1),this.localDataDirty());break}case c.aO.registerFioAddress:{const{fioAddress:n}=(0,f.NB)(a);this.otherData.fioAddresses.find(({name:d})=>d===n)==null&&(this.otherData.fioAddresses.push({name:n,bundledTxs:void 0}),this.localDataDirty());break}case c.aO.registerFioDomain:{const{fioDomain:n}=(0,f.AJ)(a);if(r.expiration==null)throw new Error("expiration not present");const i=this.otherData.fioDomains.find(({name:d})=>d===n);i!=null&&(i.expiration=r.expiration,this.localDataDirty());break}case c.aO.renewFioDomain:{const{fioDomain:n}=(0,f.AJ)(a);if(r.expiration==null)throw new Error("expiration not present");const i=this.otherData.fioDomains.find(({name:d})=>d===n);i!=null&&(i.expiration=r.expiration,this.localDataDirty());break}case c.aO.addBundledTransactions:{const{fioAddress:n}=(0,f.Ej)(a),i=this.otherData.fioAddresses.find(({name:d})=>d===n);if(i==null)throw new P.OU("Fio Address is not found in engine");i.bundledTxs=((s=i.bundledTxs)!=null?s:0)+c.BB,this.localDataDirty();break}case c.aO.rejectFundsRequest:{const{fioRequestId:n}=(0,f.OR)(a);typeof n=="string"&&(this.removeFioRequest(n,"PENDING"),this.localDataDirty());break}case c.aO.cancelFundsRequest:{const{fioRequestId:n}=(0,f.mO)(a);typeof n=="string"&&(this.removeFioRequest(n,"SENT"),this.localDataDirty());break}case c.aO.recordObtData:{const{fioRequestId:n}=(0,f.XB)(a);n!=null&&r.status==="sent_to_blockchain"&&(this.removeFioRequest(n,"PENDING"),this.localDataDirty());break}}}catch(n){this.log.warn(`Error attempting post-broadcast action ${l}:`,n)}yield fe(ne.prototype,this,"saveTx").call(this,e)})}getFreshAddress(e){return p(this,null,function*(){return{publicAddress:this.walletInfo.keys.publicKey}})}}function De(g,e,s,t){return p(this,null,function*(){const{tpid:r="finance@edge"}=g.initOptions,o=(0,f.RB)(s),l=new ne(g,e,o,t,r);return yield l.loadEngine(),l})}var ve=w(48764).Buffer,B=(g,e,s)=>new Promise((t,r)=>{var o=n=>{try{a(s.next(n))}catch(i){r(i)}},l=n=>{try{a(s.throw(n))}catch(i){r(i)}},a=n=>n.done?t(n.value):Promise.resolve(n.value).then(o,l);a((s=s.apply(g,e)).next())});const le="FIO",ce="fio",Ie="";function de(g){const e=g.startsWith(le),s=g.length===53;return e&&s}class me{constructor(e){const{builtinTokens:s,currencyInfo:t,initOptions:r,io:o,networkInfo:l}=e;this.builtinTokens=s,this.currencyInfo=t,this.io=o,this.networkInfo=l;const{tpid:a="finance@edge",fioRegApiToken:n=Ie}=r;this.fetchCors=(0,D.zR)(e.io),this.fioRegApiToken=n,this.tpid=a;for(const i of this.networkInfo.apiUrls)new F.rn("","",i,this.fetchCors,void 0,a)}getDisplayPrivateKey(e){return B(this,null,function*(){return(0,f.UW)(e.keys).fioKey})}getDisplayPublicKey(e){return B(this,null,function*(){const{keys:s}=(0,f.RB)(e);return s.publicKey})}importPrivateKey(e){return B(this,null,function*(){const{pluginId:s}=this.currencyInfo,t={};if(/[0-9a-zA-Z]{51}$/.test(e))ue._q.fromString(e),t.fioKey=e;else{if(!(0,ie.validateMnemonic)(e))throw new Error("Invalid input");const o=yield F.rn.createPrivateKeyMnemonic(e);t.fioKey=o.fioKey,t.mnemonic=o.mnemonic}const r=yield this.derivePublicKey({type:`wallet:${s}`,id:"fake",keys:t});return t.publicKey=r.publicKey,t})}createPrivateKey(e){return B(this,null,function*(){if(e.replace("wallet:","")===ce){const t=ve.from(this.io.random(32));return yield F.rn.createPrivateKey(t)}else throw new Error("InvalidWalletType")})}derivePublicKey(e){return B(this,null,function*(){if(e.type.replace("wallet:","")===ce)return F.rn.derivedPublicKey(e.keys.fioKey);throw new Error("InvalidWalletType")})}parseUri(e){return B(this,null,function*(){var s;const{edgeParsedUri:t}=(0,Q.k)(ee.j,e,{fio:!0},le);if(!de((s=t.publicAddress)!=null?s:""))throw new Error("InvalidPublicAddressError");return t})}encodeUri(e){return B(this,arguments,function*(s,t=[]){if(!de(s.publicAddress))throw new Error("InvalidPublicAddressError");let o;if(typeof s.nativeAmount=="string"){const a=le,n=s.nativeAmount,i=(0,D.Qs)(a,ee.j,t);if(i==null)throw new Error("InternalErrorInvalidCurrencyCode");o=(0,O.div)(n,i.multiplier,16)}return(0,Q.Q)(s,ce,o)})}getConnectedPublicAddress(e,s,t){return B(this,null,function*(){var r;try{F.rn.isFioAddressValid(e)}catch{throw new P.OU("",400,this.networkInfo.errorCodes.INVALID_FIO_ADDRESS)}try{if((yield this.multicastServers("isAvailable",{fioName:e})).is_registered===0)throw new P.OU("",404,this.networkInfo.errorCodes.FIO_ADDRESS_IS_NOT_EXIST)}catch(o){throw o.name==="FioError"&&((r=o.json)==null?void 0:r.fields)!=null&&o.errorCode===400&&(o.labelCode=this.networkInfo.errorCodes.INVALID_FIO_ADDRESS),o}try{const o=yield this.multicastServers("getPublicAddress",{fioAddress:e,chainCode:s,tokenCode:t});if(o.public_address==null||o.public_address==="0")throw new P.OU("",404,this.networkInfo.errorCodes.FIO_ADDRESS_IS_NOT_LINKED);return o}catch(o){throw o.name==="FioError"&&o.labelCode===this.networkInfo.errorCodes.FIO_ADDRESS_IS_NOT_LINKED||o.errorCode===404?new P.OU("",404,this.networkInfo.errorCodes.FIO_ADDRESS_IS_NOT_LINKED):o}})}isFioAddressValid(e){return B(this,null,function*(){try{return F.rn.isFioAddressValid(e)}catch{return!1}})}validateAccount(e,s=!1){return B(this,null,function*(){var t;try{if(s){if(!F.rn.isFioDomainValid(e))return!1}else if(!F.rn.isFioAddressValid(e))return!1}catch{throw new P.OU("",400,this.networkInfo.errorCodes.INVALID_FIO_ADDRESS)}try{return(yield this.multicastServers("isAvailable",{fioName:e})).is_registered===0}catch(r){throw r.name==="FioError"&&((t=r.json)==null?void 0:t.fields)!=null&&r.errorCode===400&&(r.labelCode=this.networkInfo.errorCodes.INVALID_FIO_ADDRESS),r}})}isDomainPublic(e){return B(this,null,function*(){if((yield this.multicastServers("isAvailable",{fioName:e})).is_registered===0)throw new P.OU("",400,this.networkInfo.errorCodes.FIO_DOMAIN_IS_NOT_EXIST);const t=yield this.fetchCors(`${this.networkInfo.fioRegApiUrl}${c.n3.isDomainPublic}/${e}`,{method:"GET"});if(!t.ok){const o=yield t.json();throw new P.OU("",t.status,this.networkInfo.errorCodes.IS_DOMAIN_PUBLIC_ERROR,o)}const{isPublic:r}=yield t.json();return r})}doesAccountExist(e){return B(this,null,function*(){try{if(!F.rn.isFioAddressValid(e))return!1}catch{return!1}try{return(yield this.multicastServers("isAvailable",{fioName:e})).is_registered===1}catch(s){return this.error("doesAccountExist error: ",s),!1}})}buyAddressRequest(e,s=!1){return B(this,null,function*(){const t={Accept:"application/json","Content-Type":"application/json"};s&&(e.apiToken=this.fioRegApiToken);try{const r=yield this.fetchCors(`${this.networkInfo.fioRegApiUrl}${c.n3.buyAddress}`,{method:"POST",headers:t,body:JSON.stringify(e)});if(!r.ok){const o=yield r.json();throw this.networkInfo.errorCodes[o.errorCode]!=null?new P.OU(o.error,r.status,this.networkInfo.errorCodes[o.errorCode],o):o.error==="Already registered"?new P.OU(o.error,r.status,this.networkInfo.errorCodes.ALREADY_REGISTERED,o):new Error(o.error)}return yield r.json()}catch(r){throw r.labelCode!=null?r:new P.OU((0,D.HY)(r),500,this.networkInfo.errorCodes.SERVER_ERROR)}})}getDomains(e=""){return B(this,null,function*(){e==null&&(e=this.networkInfo.defaultRef);try{const s=yield this.fetchCors(`${this.networkInfo.fioRegApiUrl}${c.n3.getDomains}/${e}`,{method:"GET"}),t=yield s.json();if(!s.ok)throw this.networkInfo.errorCodes[t.errorCode]!=null?new P.OU(t.error,s.status,this.networkInfo.errorCodes[t.errorCode],t):new Error(t.error);return t.domains}catch(s){throw s.labelCode!=null?s:new P.OU((0,D.HY)(s),500,this.networkInfo.errorCodes.SERVER_ERROR)}})}getStakeEstReturn(){return B(this,null,function*(){try{const e=yield this.fetchCors(`${this.networkInfo.fioStakingApyUrl}`,{method:"GET"}),s=yield e.json();if(!e.ok)throw new Error(this.networkInfo.errorCodes.SERVER_ERROR);const t=s.historical_apr["7day"];return t!=null&&t>c.OT||t==null?c.OT:t}catch(e){throw e.labelCode!=null?e:new P.OU(e.message,500,this.networkInfo.errorCodes.SERVER_ERROR)}})}multicastServers(e,s){return B(this,null,function*(){const t=yield(0,D.QJ)((0,D.Sy)(this.networkInfo.apiUrls.map(r=>()=>B(this,null,function*(){let o;const l=new F.rn("","",r,this.fetchCors,void 0,this.tpid);try{o=yield l.genericAction(e,s)}catch(a){if(a.errorCode!=null&&P.lI.includes(a.errorCode))o={isError:!0,data:{code:a.errorCode,message:(0,D.HY)(a),json:a.json,list:a.list}};else throw a}return o}))));if(t.isError!=null){const r=new P.OU(t.errorMessage);throw r.json=t.data.json,r.list=t.data.list,r.errorCode=t.data.code,r}return t})}}function Ae(g){return B(this,null,function*(){return new me(g)})}}}]);
|
|
1
|
+
(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[2805],{79014:function(ye,Z,w){"use strict";w.d(Z,{Q:function(){return u},k:function(){return ae}});var F=w(77591),ue=w.n(F),O=w(24350),ie=w(84564),Q=w.n(ie),D=w(76714),c=Object.defineProperty,P=Object.getOwnPropertySymbols,ee=Object.prototype.hasOwnProperty,f=Object.prototype.propertyIsEnumerable,S=(b,T,q)=>T in b?c(b,T,{enumerable:!0,configurable:!0,writable:!0,value:q}):b[T]=q,W=(b,T)=>{for(var q in T||(T={}))ee.call(T,q)&&S(b,q,T[q]);if(P)for(var q of P(T))f.call(T,q)&&S(b,q,T[q]);return b};function ae(b,T,q,K,z=[]){const R=W({},Q()(T,{},!0)),J=T.startsWith(`${b.pluginId}://`);if(R.protocol!=null&&(R.protocol=R.protocol.replace(":","")),R.protocol!=null&&R.protocol!==""&&!q[R.protocol])throw new Error(`Uri protocol '${R.protocol}' is not supported for ${b.pluginId}.`);if(R.host===""&&R.pathname==="")throw new Error("Path and host not found in uri.");const L={publicAddress:R.host!==""?R.host:R.pathname.split("/")[0]},j=R.query.label,te=R.query.message,Y=R.query.category;(j!=null||te!=null||Y!=null||J)&&(L.metadata={},L.metadata.name=j,L.metadata.notes=te,L.metadata.category=Y,L.metadata.gateway=J!=null?J:!1);const G=R.query.amount;if(G!=null&&typeof G=="string"){K==null&&(K=b.currencyCode);const se=(0,D.Qs)(K!=null?K:"",b,z);if(se==null)throw new Error("InternalErrorInvalidCurrencyCode");let V=(0,F.mul)(G,se.multiplier);V=(0,F.toFixed)(V,0,0),L.nativeAmount=V,L.currencyCode=K}return{edgeParsedUri:L,parsedUri:R}}function u(b,T,q){if(b.publicAddress==null)throw new Error("InvalidPublicAddressError");if(q==null&&b.label==null&&b.message==null)return b.publicAddress;{let K="";q!=null&&(K+="amount="+q+"&"),(b.label!=null||b.message!=null)&&(typeof b.label=="string"&&(K+="label="+b.label+"&"),typeof b.message=="string"&&(K+="message="+b.message+"&")),K=K.substr(0,K.length-1);const z={scheme:T,path:b.publicAddress,query:K};return(0,O.qC)(z)}}},44285:function(ye,Z,w){"use strict";w.r(Z),w.d(Z,{FioTools:function(){return me},checkAddress:function(){return de},makeCurrencyEngine:function(){return De},makeCurrencyTools:function(){return Ae}});var F=w(93491),ue=w(15179),O=w(77591),ie=w(2153),Q=w(79014),D=w(76714),c=w(5607),P=w(24827),ee=w(50857),f=w(3559),S=w(37858),W=w(82626),ae=w(37297),u=w(82448),b=w(94935),T=w(84650);const q=(0,u.su)({fio_domains:(0,u._2)((0,u.su)({fio_domain:u.XC,expiration:u.XC,is_public:u.mH})),fio_addresses:(0,u._2)((0,u.su)({fio_address:u.XC,remaining_bundled_tx:u.mH}))}),K=(0,u.su)({account_action_seq:u.mH,block_num:u.mH,block_time:u.XC,action_trace:(0,u.su)({receiver:u.XC,act:(0,u.su)({account:u.XC,name:u.XC,authorization:(0,u._2)((0,u.su)({actor:u.XC,permission:u.XC})),data:(0,u.su)({payee_public_key:(0,u.Zz)(u.XC),amount:(0,u.Zz)(u.mH),max_fee:(0,u.Zz)(u.mH),actor:(0,u.Zz)(u.XC),tpid:(0,u.Zz)(u.XC),quantity:(0,u.Zz)(u.XC),memo:(0,u.Zz)(u.XC),to:(0,u.Zz)(u.XC),from:(0,u.Zz)(u.XC)}),hex_data:u.XC}),trx_id:u.XC,block_num:u.mH,block_time:u.XC,producer_block_id:u.XC})}),z=(0,u.su)({actions:(0,u._2)(K)}),R=(0,u.su)({balance:u.mH,available:u.mH,staked:u.mH,srps:u.mH,roe:u.XC});var J=Object.defineProperty,he=Object.defineProperties,L=Object.getOwnPropertyDescriptors,j=Object.getOwnPropertySymbols,te=Object.getPrototypeOf,Y=Object.prototype.hasOwnProperty,G=Object.prototype.propertyIsEnumerable,se=Reflect.get,V=(g,e,s)=>e in g?J(g,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):g[e]=s,x=(g,e)=>{for(var s in e||(e={}))Y.call(e,s)&&V(g,s,e[s]);if(j)for(var s of j(e))G.call(e,s)&&V(g,s,e[s]);return g},H=(g,e)=>he(g,L(e)),pe=(g,e)=>{var s={};for(var t in g)Y.call(g,t)&&e.indexOf(t)<0&&(s[t]=g[t]);if(g!=null&&j)for(var t of j(g))e.indexOf(t)<0&&G.call(g,t)&&(s[t]=g[t]);return s},fe=(g,e,s)=>se(te(g),s,e),p=(g,e,s)=>new Promise((t,r)=>{var o=n=>{try{a(s.next(n))}catch(i){r(i)}},l=n=>{try{a(s.throw(n))}catch(i){r(i)}},a=n=>n.done?t(n.value):Promise.resolve(n.value).then(o,l);a((s=s.apply(g,e)).next())});const ge=1e4,_e=15e3,ke=1e4,be=[c.BP[c.aO.transferTokens],c.BP[c.aO.unStakeFioTokens],"regaddress"],we=1e4;class ne extends T.P{constructor(e,s,t,r,o){super(e,s,t,r),this.fioRequestsListChanged=(l,a)=>{function n(i,d){for(const h of i)if(d.findIndex(v=>v.fio_request_id===h.fio_request_id)<0)return!0;return!1}return!!(n(l,a)||n(a,l))},this.removeFioRequest=(l,a)=>{const n=this.otherData.fioRequests[a].findIndex(i=>i.fio_request_id===`${l}`);n>-1&&this.otherData.fioRequests[a].splice(n,1)},this.fetchCors=(0,D.zR)(e.io),this.tpid=o,this.networkInfo=e.networkInfo,this.refBlock={expiration:"",ref_block_num:0,ref_block_prefix:0},this.fees=new Map,this.actor=F.rn.accountHash(this.walletInfo.keys.publicKey).accountnm,this.obtData=[],this.otherMethods={fioAction:(l,a)=>p(this,null,function*(){return yield this.multicastServers(l,a)}),getFioAddresses:()=>p(this,null,function*(){return this.otherData.fioAddresses}),getFioAddressNames:()=>p(this,null,function*(){return this.otherData.fioAddresses.map(l=>l.name)}),getFioDomains:()=>p(this,null,function*(){return this.otherData.fioDomains}),getFioRequests:(l,a,n=50)=>p(this,null,function*(){const i=n*(a-1),d=n*a;return this.otherData.fioRequests[l].sort((h,v)=>h.time_stamp<v.time_stamp?1:-1).slice(i,d)}),getObtData:()=>p(this,null,function*(){return this.obtData})}}localDataDirty(){this.walletLocalDataDirty=!0}setOtherData(e){this.otherData=(0,c.CL)(e)}getUTCDate(e){const s=new Date(e);return Date.UTC(s.getFullYear(),s.getMonth(),s.getDate(),s.getHours(),s.getMinutes(),s.getSeconds())}getUnlockDate(e){const s=Math.floor(e.getTime()/c.qj)*c.qj;return new Date(s+c.dm)}checkBlockchainInnerLoop(){return p(this,null,function*(){try{const e=yield this.multicastServers("getChainInfo"),s=e.head_block_num;this.walletLocalData.blockHeight!==s&&(this.checkDroppedTransactionsThrottled(),this.walletLocalData.blockHeight=s,this.localDataDirty(),this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight));const t=yield this.multicastServers("getBlock",e),r=new Date(`${e.head_block_time}Z`);r.setSeconds(r.getSeconds()+180);const o=r.toISOString();this.refBlock={expiration:o.substring(0,o.length-1),ref_block_num:t.block_num&65535,ref_block_prefix:t.ref_block_prefix}}catch(e){this.error("checkBlockchainInnerLoop Error fetching height: ",e)}})}getBalance(e){return super.getBalance(e)}doInitialBalanceCallback(){var e;super.doInitialBalanceCallback();const s=this.networkInfo.balanceCurrencyCodes;for(const t of Object.values(s))try{this.currencyEngineCallbacks.onBalanceChanged(t,(e=this.walletLocalData.totalBalances[t])!=null?e:"0")}catch(r){this.log.error("doInitialBalanceCallback Error for currencyCode",t,r)}try{this.currencyEngineCallbacks.onStakingStatusChanged(x({},this.otherData.stakingStatus))}catch(t){this.error("doInitialBalanceCallback onStakingStatusChanged",t)}}checkUnStakeTx(e){return e.name===c.BP[c.aO.unStakeFioTokens]||e.data!=null&&e.data.memo===c.Nd}updateStakingStatus(e,s,t,r){const o=this.getUnlockDate(new Date(this.getUTCDate(s))),l=this.otherData.stakingStatus.stakedAmounts.findIndex(a=>{var n;return((n=a.unlockDate)==null?void 0:n.getTime())===o.getTime()});if(l<0){const a=this.otherData.stakingStatus.stakedAmounts.findIndex(i=>{var d,h;return o.getTime()>=((h=(d=i.unlockDate)==null?void 0:d.getTime())!=null?h:0)}),n=a<0?this.otherData.stakingStatus.stakedAmounts.length:a;this.otherData.stakingStatus.stakedAmounts.splice(n,0,{nativeAmount:e,unlockDate:o,otherParams:{date:new Date(s),txs:[{txId:t,nativeAmount:e,blockTime:s,txName:r}]}})}else{const a=H(x({},this.otherData.stakingStatus.stakedAmounts[l]),{nativeAmount:"0"}),n=a.otherParams.txs.findIndex(({txId:i,txName:d})=>i===t&&d===r);n<0?a.otherParams.txs.push({txId:t,nativeAmount:e,blockTime:s,txName:r}):a.otherParams.txs[n]={txId:t,nativeAmount:e,blockTime:s,txName:r};for(const i of a.otherParams.txs)a.nativeAmount=(0,O.add)(a.nativeAmount,i.nativeAmount);this.otherData.stakingStatus.stakedAmounts[l]=a}this.localDataDirty();try{this.currencyEngineCallbacks.onStakingStatusChanged(x({},this.otherData.stakingStatus))}catch{this.error("onStakingStatusChanged error")}}getStakingStatus(){return p(this,null,function*(){return x({},this.otherData.stakingStatus)})}processTransaction(e,s,t=this.currencyInfo.currencyCode){var r,o,l,a,n,i,d,h,v;const{act:{name:I,data:_,account:y,authorization:E}}=e.action_trace;let C,m,k="0",A={account:y,name:I,authorization:E,data:_,meta:{}};const $=[];if(e.block_num<=this.otherData.highestTxHeight)return e.block_num;if(be.includes(I)){C="0",I==="regaddress"&&e.action_trace.act.authorization.some(U=>U.actor===this.actor)&&(k=String((r=e.action_trace.act.data.max_fee)!=null?r:0),C=`-${k}`),I===c.BP[c.aO.transferTokens]&&_.amount!=null&&(C=_.amount.toString(),m=_.actor,_.payee_public_key===this.walletInfo.keys.publicKey?($.push(this.walletInfo.keys.publicKey),m===s&&(C="0")):C=`-${C}`);const N=this.findTransaction(t,e.action_trace.trx_id);if(N>-1){const U=this.transactionList[t][N];if(A=H(x(x({},U.otherParams),A),{data:x(x({},(l=(o=U.otherParams)==null?void 0:o.data)!=null?l:{}),A.data),meta:x(x({},(n=(a=U.otherParams)==null?void 0:a.meta)!=null?n:{}),A.meta)}),A.meta.isTransferProcessed!=null)return e.block_num;A.meta.isFeeProcessed!=null?I===c.BP[c.aO.transferTokens]?(C=(0,O.sub)(C,U.networkFee),k=U.networkFee):(C=U.nativeAmount,k="0"):this.error("processTransaction error - existing spend transaction should have isTransferProcessed or isFeeProcessed set")}this.checkUnStakeTx(A)&&this.updateStakingStatus(_.amount!=null?_.amount.toString():"0",e.block_time,e.action_trace.trx_id,I),A.meta.isTransferProcessed=!0;const M={txid:e.action_trace.trx_id,date:this.getUTCDate(e.block_time)/1e3,currencyCode:t,blockHeight:e.block_num>0?e.block_num:0,nativeAmount:C,isSend:C.startsWith("-"),networkFee:k,ourReceiveAddresses:$,signedTx:"",otherParams:A,walletId:this.walletId};this.addTransaction(t,M)}if(I===c.BP.transfer&&_.quantity!=null){const[N]=_.quantity.split(" "),M=N.toString(),U=(0,D.aL)(t,this.currencyInfo,this.allTokensMap);if(U==null)return this.error(`Received unsupported currencyCode: ${t}`),0;const X=(0,O.mul)(M,U.multiplier);_.to===s?(C=`${X}`,k=`-${X}`):(C=`-${X}`,k=X);const re=this.findTransaction(t,e.action_trace.trx_id);if(re>-1){const oe=this.transactionList[t][re];if(A=H(x(x({},A),oe.otherParams),{data:x(x({},A.data),(d=(i=oe.otherParams)==null?void 0:i.data)!=null?d:{}),meta:x(x({},A.meta),(v=(h=oe.otherParams)==null?void 0:h.meta)!=null?v:{})}),A.meta.isFeeProcessed!=null)return e.block_num;A.meta.isTransferProcessed!=null?_.to!==s?C=(0,O.sub)(oe.nativeAmount,k):k="0":this.error("processTransaction error - existing spend transaction should have isTransferProcessed or isFeeProcessed set")}this.checkUnStakeTx(A)&&this.updateStakingStatus(X,e.block_time,e.action_trace.trx_id,I),A.meta.isFeeProcessed=!0;const Pe={txid:e.action_trace.trx_id,date:this.getUTCDate(e.block_time)/1e3,currencyCode:t,blockHeight:e.block_num>0?e.block_num:0,nativeAmount:C,isSend:C.startsWith("-"),networkFee:k,signedTx:"",ourReceiveAddresses:[],otherParams:A,walletId:this.walletId};this.addTransaction(t,Pe)}return e.block_num}getSortedHistoryNodesLastActionSeqNumbers(){return p(this,null,function*(){const e=this.networkInfo.historyNodeUrls.map((t,r)=>p(this,null,function*(){var o;try{const l=yield this.requestHistory(r,{account_name:this.actor,pos:-1},c.pg.getActions);return((o=l==null?void 0:l.error)==null?void 0:o.noNodeForIndex)!=null?{nodeIndex:r,seqNumber:-1}:(z(l),l.actions.length===0?{nodeIndex:r,seqNumber:-1}:{nodeIndex:r,seqNumber:l.actions[l.actions.length-1].account_action_seq})}catch{return{nodeIndex:r,seqNumber:-1}}})),s=yield Promise.all(e);return s.sort((t,r)=>r.seqNumber-t.seqNumber),s})}checkTransactions(e){return p(this,null,function*(){var s,t;if((e==null?void 0:e.length)===0)return!1;if(e=e!=null?e:yield this.getSortedHistoryNodesLastActionSeqNumbers(),e.reduce((i,d)=>i+d.seqNumber,0)===-e.length)return!0;let r=this.otherData.highestTxHeight;const o=e[0].seqNumber,l=e[0].nodeIndex;let a=Math.max(0,o-c.WX+1),n=!1;for(;!n;){let i;try{if(i=yield this.requestHistory(l,{account_name:this.actor,pos:a,offset:c.WX-1},c.pg.getActions),((s=i.error)==null?void 0:s.noNodeForIndex)!=null)return!1;let d=[];if(((t=i.actions)==null?void 0:t.length)>0)d=i.actions;else break;for(let h=d.length-1;h>-1;h--){const v=d[h];K(v);const I=this.processTransaction(v,this.actor);if(I>r)r=I;else if(I===r&&h===c.WX-1||I<this.otherData.highestTxHeight){n=!0;break}}if(a===0)break;a=Math.max(0,a-c.WX);continue}catch{return yield this.checkTransactions(e.slice(1))}}return r>this.otherData.highestTxHeight&&(this.otherData.highestTxHeight=r,this.localDataDirty()),!0})}checkTransactionsInnerLoop(){return p(this,null,function*(){let e;try{e=yield this.checkTransactions()}catch(s){this.error("checkTransactionsInnerLoop fetches failed with error: ",s);return}e&&(this.tokenCheckTransactionsStatus.FIO=1,this.updateOnAddressesChecked()),this.transactionsChangedArray.length>0&&(this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[])})}requestHistory(e,s,t){return p(this,null,function*(){if(this.networkInfo.historyNodeUrls[e]==null)return{error:{noNodeForIndex:!0}};const r=this.networkInfo.historyNodeUrls[e],o=JSON.stringify(s);return yield(yield fetch(`${r}history/${t}`,{method:"POST",headers:{"Content-Length":(o.length*2).toString(),Accept:"application/json","Content-Type":"application/json"},body:o})).json()})}fioApiRequest(e,s,t,r=!1){return p(this,null,function*(){var o,l,a,n;const i=new F.rn("",this.walletInfo.keys.publicKey,e,this.fetchCors,void 0,this.tpid,r);let d;try{switch(s){case"getChainInfo":d=yield i.transactions.getChainInfo();break;case"getBlock":d=yield i.transactions.getBlock(t);break;case"getObtData":case"getPendingFioRequests":case"getSentFioRequests":{const{endpoint:h,body:v}=t;d=yield i.transactions.executeCall(h,JSON.stringify(v));break}default:d=yield i.genericAction(s,t)}}catch(h){if(h.errorCode!=null&&P.lI.includes(h.errorCode))((a=(l=(o=h.json)==null?void 0:o.fields)==null?void 0:l[0])==null?void 0:a.error)!=null&&(h.message=h.json.fields[0].error),d={isError:!0,data:{code:h.errorCode,message:(n=h.message)!=null?n:(0,D.HY)(h),json:h.json,list:h.list}},h.errorCode!==404&&this.log(`fioApiRequest error. actionName: ${s} - apiUrl: ${e} - message: ${JSON.stringify(h.json)}`);else throw this.log(`fioApiRequest error. actionName: ${s} - apiUrl: ${e} - message: `,h),h}return d})}executePreparedTrx(e,s,t){return p(this,null,function*(){var r,o,l;const a=new F.rn("",this.walletInfo.keys.publicKey,e,this.fetchCors,void 0,this.tpid,!0);let n;this.warn(`executePreparedTrx. preparedTrx: ${JSON.stringify(t)} - apiUrl: ${e}`);try{n=yield a.executePreparedTrx(s,t),this.warn(`executePreparedTrx. res: ${JSON.stringify(n)} - apiUrl: ${e} - endpoint: ${s}`)}catch(i){throw i.errorCode!=null&&P.lI.includes(i.errorCode)?(this.log(`executePreparedTrx error. requestParams: ${JSON.stringify(t)} - apiUrl: ${e} - endpoint: ${s} - message: ${JSON.stringify(i.json)}`),((l=(o=(r=i.json)==null?void 0:r.fields)==null?void 0:o[0])==null?void 0:l.error)!=null&&(i.message=i.json.fields[0].error),i):(this.log(`executePreparedTrx error. requestParams: ${JSON.stringify(t)} - apiUrl: ${e} - endpoint: ${s} - message: `,i),i)}return n})}multicastServers(e,s){return p(this,null,function*(){var t,r,o,l,a;let n;if(c.K1[e]){const i=(0,f.h0)(s);if(this.warn(`multicastServers executePreparedTrx. actionName: ${e} - res: ${JSON.stringify(i)}`),n=yield(0,D.Wp)((0,D.Sy)(this.networkInfo.apiUrls.map(d=>p(this,null,function*(){return yield(0,D.Vs)(this.executePreparedTrx(d,S.EndPoint[c.VW[e]],i),1e4)})))),this.warn(`multicastServers res. actionName: ${e} - res: ${JSON.stringify(n)}`),n==null)throw new Error("Service is unavailable")}else e==="getFioNames"?(n=yield(0,D.ml)(this.networkInfo.apiUrls.map(i=>p(this,null,function*(){return yield(0,D.Vs)(this.fioApiRequest(i,e,s),1e4)})),i=>{const d=(0,f.$K)(c.Mi)(i);return d!=null?d.data.json.message:(0,f.e1)(i)},2),((r=(t=n==null?void 0:n.data)==null?void 0:t.json)==null?void 0:r.message)===c.Mi&&(n={fio_domains:[],fio_addresses:[]})):e==="getFioBalance"?(n=yield(0,D.ml)(this.networkInfo.apiUrls.map(i=>p(this,null,function*(){return yield(0,D.Vs)(this.fioApiRequest(i,e,s),1e4)})),i=>{const d=(0,f.$K)(c.d9)(i);return d!=null?d.data.json.message:(0,f.sq)(i)},2),((l=(o=n==null?void 0:n.data)==null?void 0:o.json)==null?void 0:l.message)===c.d9&&(n={balance:0,available:0,staked:0,srps:0,roe:""})):e==="getFees"?n=yield(0,D.QJ)((0,D.Sy)(this.networkInfo.apiUrls.map(i=>()=>p(this,null,function*(){const d=new F.rn("",this.walletInfo.keys.publicKey,i,this.fetchCors,void 0,this.tpid),{endpoint:h,param:v}=s,I=yield d.getFee(h,v);return(0,f.lZ)(I).fee.toString()})))):n=yield(0,D.QJ)((0,D.Sy)(this.networkInfo.apiUrls.map(i=>()=>p(this,null,function*(){return yield this.fioApiRequest(i,e,s)}))));if(n.isError!=null){const i=new P.OU((a=n.errorMessage)!=null?a:n.data.message);throw i.json=n.data.json,i.list=n.data.list,i.errorCode=n.data.code,i}return n})}checkAccountInnerLoop(){return p(this,null,function*(){const e=this.currencyInfo.currencyCode,s=this.networkInfo.balanceCurrencyCodes;typeof this.walletLocalData.totalBalances[e]>"u"&&this.updateBalance(e,"0");try{const t={staked:"0",locked:"0"},{balance:r,available:o,staked:l,srps:a,roe:n}=R(yield this.multicastServers("getFioBalance")),i=String(r);t.staked=String(l),t.locked=(0,O.sub)(i,String(o)),this.otherData.srps=a,this.otherData.stakingRoe=n,this.updateBalance(e,i),this.updateBalance(s.staked,t.staked),this.updateBalance(s.locked,t.locked)}catch(t){this.log.warn("checkAccountInnerLoop getFioBalance error: ",t)}try{const t=q(yield this.multicastServers("getFioNames",{fioPublicKey:this.walletInfo.keys.publicKey}));let r=!1,o=!1,l=!1;if(t.fio_addresses.length!==this.otherData.fioAddresses.length)o=!0;else{for(const a of t.fio_addresses){const n=this.otherData.fioAddresses.find(i=>i.name===a.fio_address);if(n!=null){if(n.bundledTxs!==a.remaining_bundled_tx){o=!0;break}}else{o=!0;break}}if(!o){for(const a of this.otherData.fioAddresses)if(t.fio_addresses.findIndex(n=>n.fio_address===a.name)<0){o=!0;break}}}if(t.fio_domains.length!==this.otherData.fioDomains.length)l=!0;else{for(const a of t.fio_domains){const n=this.otherData.fioDomains.find(i=>i.name===a.fio_domain);if(n!=null){if(n.expiration!==a.expiration){l=!0;break}if(n.isPublic!==(a.is_public===1)){l=!0;break}}else{l=!0;break}}if(!l){for(const a of this.otherData.fioDomains)if(t.fio_domains.findIndex(n=>n.fio_domain===a.name)<0){l=!0;break}}}o&&(r=!0,this.otherData.fioAddresses=t.fio_addresses.map(a=>({name:a.fio_address,bundledTxs:a.remaining_bundled_tx}))),l&&(r=!0,this.otherData.fioDomains=t.fio_domains.map(a=>({name:a.fio_domain,expiration:a.expiration,isPublic:a.is_public===1}))),r&&this.localDataDirty()}catch(t){this.warn("checkAccountInnerLoop getFioNames error: ",t)}})}fetchEncryptedFioRequests(e,s){return p(this,null,function*(){const r=e==="PENDING"?"getPendingFioRequests":"getSentFioRequests";let o=100,l=1;const a=[];for(;o===100;)try{const n=yield this.multicastServers(r,{endpoint:s.getEndPoint(),body:{fio_public_key:this.walletInfo.keys.publicKey,limit:100,offset:(l-1)*100}}),i=(0,f.S_)(n),{requests:d,more:h}=i;if(a.push(...d),h===0)break;l++,o=d.length}catch(n){const i=(0,u.Vk)(f.Pq)(n.json);(i==null?void 0:i.message)!=="No FIO Requests"&&this.error("fetchEncryptedFioRequests error: ",n);break}return a})}fetchEncryptedObtData(e,s){return p(this,null,function*(){let r=100,o=1;const l=[];for(;r===100;){let a;try{a=yield this.multicastServers(e,{endpoint:s.getEndPoint(),body:{fio_public_key:this.walletInfo.keys.publicKey,limit:100,offset:(o-1)*100}});const n=(0,f._v)(a),{obt_data_records:i,more:d}=n;if(l.push(...i),d===0)break;o++,r=i.length}catch(n){const i=(0,u.Vk)(f.Pq)(n.json);(i==null?void 0:i.message)!=="No FIO Requests"&&this.error("fetchEncryptedObtData error: ",n);break}}return l})}syncNetwork(e){return p(this,null,function*(){var s;const t=(0,f.UW)(e==null?void 0:e.privateKeys);let r=!1;const o=(i,d)=>p(this,null,function*(){var h;const v=yield this.fetchEncryptedFioRequests(i,d);d.privateKey=t.fioKey,d.publicKey=this.walletInfo.keys.publicKey;const I=(h=d.decrypt({requests:v}))!=null?h:{requests:[]};this.fioRequestsListChanged(this.otherData.fioRequests[i],I.requests)&&(this.otherData.fioRequests[i]=[...I.requests],r=!0)});yield o("PENDING",new W.PendingFioRequests(this.walletInfo.keys.publicKey)),yield o("SENT",new W.SentFioRequests(this.walletInfo.keys.publicKey)),r&&this.localDataDirty();const l=new W.GetObtData(this.walletInfo.keys.publicKey),a=yield this.fetchEncryptedObtData("getObtData",l);l.privateKey=t.fioKey,l.publicKey=this.walletInfo.keys.publicKey;const n=(s=l.decrypt({obt_data_records:a}))!=null?s:{obt_data_records:[]};return this.obtData=n.obt_data_records,we})}getFee(e,s){return p(this,null,function*(){let t=this.fees.get(e);if(t==null||t.expiration+30*1e3<Date.now()){const o={fee:yield this.multicastServers("getFees",{endpoint:e,param:s}),expiration:Date.now()};this.fees.set(e,o),t=o}return t.fee})}startEngine(){return p(this,null,function*(){this.engineOn=!0,this.addToLoop("checkBlockchainInnerLoop",_e).catch(()=>{}),this.addToLoop("checkAccountInnerLoop",ge).catch(()=>{}),this.addToLoop("checkTransactionsInnerLoop",ke).catch(()=>{}),yield fe(ne.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return p(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getMaxSpendable(e){return p(this,null,function*(){var s;const t=this.getBalance({currencyCode:e.currencyCode}),r=(s=this.walletLocalData.totalBalances[this.networkInfo.balanceCurrencyCodes.locked])!=null?s:"0";e.spendTargets[0].nativeAmount="1";const o=yield this.makeSpend(e),l=(0,O.sub)((0,O.sub)(t,o.networkFee),r);if((0,O.lt)(l,"0"))throw new b.C_({networkFee:o.networkFee});return l})}makeSpend(e){return p(this,null,function*(){var s,t;const{edgeSpendInfo:r,nativeBalance:o,currencyCode:l}=this.makeSpendCheck(e),a=(s=this.walletLocalData.totalBalances[this.networkInfo.balanceCurrencyCodes.locked])!=null?s:"0",n=(0,O.sub)(o,a),i=r.spendTargets[0],{publicAddress:d}=i,{nativeAmount:h}=i;if(d==null)throw new Error("makeSpend Missing publicAddress");if(h==null)throw new b.$D;let{otherParams:v}=r;(v==null||Object.keys(v).length===0)&&(v={action:{name:c.aO.transferTokens,params:{payeeFioPublicKey:d,amount:h,maxFee:0}}});const{name:I,params:_}=(0,f.iR)(v.action);let y,E;switch(I){case c.aO.transferTokens:{y=yield this.getFee(S.EndPoint.transferTokens),E={account:"fio.token",action:c.BP[c.aO.transferTokens],data:{payee_public_key:d,amount:h,max_fee:y}};break}case c.aO.stakeFioTokens:{const{fioAddress:m}=(0,f.NB)(_);y=yield this.getFee(S.EndPoint.stakeFioTokens,m),E={account:"fio.staking",action:c.BP[I],data:{amount:h,fio_address:m,actor:this.actor,max_fee:y}};break}case c.aO.unStakeFioTokens:{const{fioAddress:m}=(0,f.NB)(_);y=yield this.getFee(S.EndPoint.unStakeFioTokens,m),E={account:"fio.staking",action:c.BP[I],data:{amount:h,fio_address:m,actor:this.actor,max_fee:y}};const k=this.getUnlockDate(new Date),A=(t=this.walletLocalData.totalBalances[this.networkInfo.balanceCurrencyCodes.staked])!=null?t:"0";if((0,O.gt)(h,A)||(0,O.gt)(`${y}`,n))throw new b.C_;const $=(0,O.mul)((0,O.mul)((0,O.div)(h,A,18),`${this.otherData.srps}`),this.otherData.stakingRoe),N=(0,O.max)((0,O.sub)($,h),"0");v.ui={accrued:$,estReward:N,unlockDate:k};break}case c.aO.transferFioAddress:{const{fioAddress:m}=(0,f.NB)(_);y=yield this.getFee(S.EndPoint.transferFioAddress,m),E={account:"fio.address",action:"xferaddress",data:{fio_address:m,new_owner_fio_public_key:d,actor:this.actor,max_fee:y}};break}case c.aO.transferFioDomain:{const{fioDomain:m}=(0,f.L2)(_);y=yield this.getFee(S.EndPoint.transferFioDomain),E={account:"fio.address",action:"xferdomain",data:{fio_domain:m,new_owner_fio_public_key:d,actor:this.actor,max_fee:y}};break}case c.aO.addPublicAddresses:{const{fioAddress:m,publicAddresses:k}=(0,f.PH)(_);y=yield this.getFee(S.EndPoint.addPubAddress,m),E={account:"fio.address",action:"addaddress",data:{fio_address:m,public_addresses:k,actor:this.actor,max_fee:y}};break}case c.aO.removePublicAddresses:{const{fioAddress:m,publicAddresses:k}=(0,f.PH)(_);y=yield this.getFee(S.EndPoint.removePubAddress,m),E={account:"fio.address",action:"remaddress",data:{fio_address:m,public_addresses:k,actor:this.actor,max_fee:y}};break}case c.aO.registerFioAddress:{const{fioAddress:m}=(0,f.NB)(_);y=yield this.getFee(S.EndPoint.registerFioAddress),E={account:"fio.address",action:"regaddress",data:{fio_address:m,owner_fio_public_key:this.walletInfo.keys.publicKey,max_fee:y,actor:this.actor}};break}case c.aO.registerFioDomain:{const{fioDomain:m}=(0,f.AJ)(_);y=yield this.getFee(S.EndPoint.registerFioDomain),E={account:"fio.address",action:"regdomain",data:{fio_domain:m,owner_fio_public_key:this.walletInfo.keys.publicKey,max_fee:y,actor:this.actor}};break}case c.aO.renewFioDomain:{const{fioDomain:m}=(0,f.AJ)(_);y=yield this.getFee(S.EndPoint.renewFioDomain),E={account:"fio.address",action:"renewdomain",data:{fio_domain:m,max_fee:y,actor:this.actor}};break}case c.aO.addBundledTransactions:{const{bundleSets:m,fioAddress:k}=(0,f.Ej)(_);y=yield this.getFee(S.EndPoint.addBundledTransactions,k),E={account:"fio.address",action:"addbundles",data:{fio_address:k,bundle_sets:m,actor:this.actor,max_fee:y}};break}case c.aO.setFioDomainPublic:{const{fioDomain:m,isPublic:k}=(0,f.oY)(_);y=yield this.getFee(S.EndPoint.setFioDomainPublic),E={account:"fio.address",action:"setdomainpub",data:{fio_domain:m,is_public:k?1:0,max_fee:y,actor:this.actor}};break}case c.aO.rejectFundsRequest:{const{fioRequestId:m,payerFioAddress:k}=(0,f.OR)(_);y=yield this.getFee(S.EndPoint.rejectFundsRequest,k),E={account:"fio.reqobt",action:"rejectfndreq",data:{fio_request_id:m,max_fee:y,actor:this.actor}};break}case c.aO.cancelFundsRequest:{const{fioAddress:m,fioRequestId:k}=(0,f.mO)(_);y=yield this.getFee(S.EndPoint.cancelFundsRequest,m),E={account:"fio.reqobt",action:"cancelfndreq",data:{fio_request_id:k,max_fee:y,actor:this.actor}};break}case c.aO.recordObtData:{const{payerFioAddress:m}=(0,f.XB)(_);y=yield this.getFee(S.EndPoint.recordObtData,m);break}case c.aO.requestFunds:{const{payeeFioAddress:m}=(0,f.Vd)(_);y=yield this.getFee(S.EndPoint.newFundsRequest,m);break}default:throw new Error("Unrecognized FIO action")}return{txid:"",date:0,currencyCode:l,blockHeight:0,nativeAmount:(0,O.sub)(`-${h}`,`${y}`),isSend:!0,networkFee:`${y}`,ourReceiveAddresses:[],signedTx:"",otherParams:H(x({},v),{txParams:E}),walletId:this.walletId}})}signTx(e,s){return p(this,null,function*(){const t=(0,f.UW)(s),r=(0,D.Xp)(e);let o=(0,u.Vk)(f.B3)(r.txParams);const l=new ae.Transactions;if(o==null){const{name:h,params:v}=(0,f.iR)(r.action),{networkFee:I}=e;switch(h){case c.aO.recordObtData:{const{payerFioAddress:_,payeeFioAddress:y,payerPublicAddress:E,payeePublicAddress:C,amount:m,tokenCode:k,chainCode:A,obtId:$,memo:N,status:M,fioRequestId:U}=(0,f.XB)(v),X={payer_public_address:E,payee_public_address:C,amount:m,chain_code:A,token_code:k,status:M,obt_id:$,memo:N,hash:void 0,offline_url:void 0},re=l.getCipherContent("record_obt_data_content",X,t.fioKey,E);o={account:"fio.reqobt",action:"recordobt",data:{payer_fio_address:_,payee_fio_address:y,content:re,fio_request_id:U,max_fee:I,actor:this.actor}};break}case c.aO.requestFunds:{const{payerFioAddress:_,payerFioPublicKey:y,payeeFioAddress:E,payeeTokenPublicAddress:C,amount:m,chainCode:k,tokenCode:A,memo:$}=(0,f.Vd)(v),N={payee_public_address:C,amount:m,chain_code:k,token_code:A,memo:$,hash:void 0,offline_url:void 0},M=l.getCipherContent("new_funds_content",N,t.fioKey,y);o={account:"fio.reqobt",action:"newfundsreq",data:{payer_fio_address:_,payee_fio_address:E,content:M,max_fee:I,actor:this.actor}};break}default:throw new Error("Unknown FIO action")}}const a=yield l.createRawTransaction({action:o.action,account:o.account,data:H(x({},o.data),{tpid:this.tpid}),publicKey:this.walletInfo.keys.publicKey,chainData:this.refBlock}),{serializedContextFreeData:n,serializedTransaction:i}=yield l.serialize({chainId:this.networkInfo.chainId,transaction:a}),d=yield l.sign({chainId:this.networkInfo.chainId,privateKeys:[t.fioKey],transaction:a,serializedTransaction:i,serializedContextFreeData:n});return e.otherParams=H(x({},e.otherParams),{signedTx:d}),e})}broadcastTx(e){return p(this,null,function*(){var s;const t=(0,D.Xp)(e);if(((s=t.action)==null?void 0:s.name)==null)throw new Error('Action is not set, "action" prop of otherParams is required for FIO actions');const r=(0,f.h0)(t.signedTx),o=(0,f.Yd)(yield this.multicastServers(t.action.name,r));e.metadata={notes:o.transaction_id},e.txid=o.transaction_id,e.date=Date.now()/1e3,e.blockHeight=o.block_num,this.warn(`SUCCESS broadcastTx
|
|
2
|
+
${(0,D.oX)(e)}`);const l=o,{block_num:a,block_time:n,transaction_id:i}=l,d=pe(l,["block_num","block_time","transaction_id"]);return e.otherParams=H(x({},t),{broadcastResult:d}),e})}saveTx(e){return p(this,null,function*(){var s;const t=(0,D.Xp)(e),{broadcastResult:r={},action:o}=t,{name:l,params:a}=(0,f.iR)(o);try{switch(l){case c.aO.transferFioDomain:{const n=this.otherData.fioDomains.findIndex(({name:i})=>i===a.fioDomain);n>=0&&(this.otherData.fioDomains.splice(n,1),this.localDataDirty());break}case c.aO.transferFioAddress:{const n=this.otherData.fioAddresses.findIndex(({name:i})=>i===a.fioAddress);n>=0&&(this.otherData.fioAddresses.splice(n,1),this.localDataDirty());break}case c.aO.registerFioAddress:{const{fioAddress:n}=(0,f.NB)(a);this.otherData.fioAddresses.find(({name:d})=>d===n)==null&&(this.otherData.fioAddresses.push({name:n,bundledTxs:void 0}),this.localDataDirty());break}case c.aO.registerFioDomain:{const{fioDomain:n}=(0,f.AJ)(a);if(r.expiration==null)throw new Error("expiration not present");const i=this.otherData.fioDomains.find(({name:d})=>d===n);i!=null&&(i.expiration=r.expiration,this.localDataDirty());break}case c.aO.renewFioDomain:{const{fioDomain:n}=(0,f.AJ)(a);if(r.expiration==null)throw new Error("expiration not present");const i=this.otherData.fioDomains.find(({name:d})=>d===n);i!=null&&(i.expiration=r.expiration,this.localDataDirty());break}case c.aO.addBundledTransactions:{const{fioAddress:n}=(0,f.Ej)(a),i=this.otherData.fioAddresses.find(({name:d})=>d===n);if(i==null)throw new P.OU("Fio Address is not found in engine");i.bundledTxs=((s=i.bundledTxs)!=null?s:0)+c.BB,this.localDataDirty();break}case c.aO.rejectFundsRequest:{const{fioRequestId:n}=(0,f.OR)(a);typeof n=="string"&&(this.removeFioRequest(n,"PENDING"),this.localDataDirty());break}case c.aO.cancelFundsRequest:{const{fioRequestId:n}=(0,f.mO)(a);typeof n=="string"&&(this.removeFioRequest(n,"SENT"),this.localDataDirty());break}case c.aO.recordObtData:{const{fioRequestId:n}=(0,f.XB)(a);n!=null&&r.status==="sent_to_blockchain"&&(this.removeFioRequest(n,"PENDING"),this.localDataDirty());break}}}catch(n){this.log.warn(`Error attempting post-broadcast action ${l}:`,n)}yield fe(ne.prototype,this,"saveTx").call(this,e)})}getFreshAddress(e){return p(this,null,function*(){return{publicAddress:this.walletInfo.keys.publicKey}})}}function De(g,e,s,t){return p(this,null,function*(){const{tpid:r="finance@edge"}=g.initOptions,o=(0,f.RB)(s),l=new ne(g,e,o,t,r);return yield l.loadEngine(),l})}var ve=w(48764).Buffer,B=(g,e,s)=>new Promise((t,r)=>{var o=n=>{try{a(s.next(n))}catch(i){r(i)}},l=n=>{try{a(s.throw(n))}catch(i){r(i)}},a=n=>n.done?t(n.value):Promise.resolve(n.value).then(o,l);a((s=s.apply(g,e)).next())});const le="FIO",ce="fio",Ie="";function de(g){const e=g.startsWith(le),s=g.length===53;return e&&s}class me{constructor(e){const{builtinTokens:s,currencyInfo:t,initOptions:r,io:o,networkInfo:l}=e;this.builtinTokens=s,this.currencyInfo=t,this.io=o,this.networkInfo=l;const{tpid:a="finance@edge",fioRegApiToken:n=Ie}=r;this.fetchCors=(0,D.zR)(e.io),this.fioRegApiToken=n,this.tpid=a;for(const i of this.networkInfo.apiUrls)new F.rn("","",i,this.fetchCors,void 0,a)}getDisplayPrivateKey(e){return B(this,null,function*(){return(0,f.UW)(e.keys).fioKey})}getDisplayPublicKey(e){return B(this,null,function*(){const{keys:s}=(0,f.RB)(e);return s.publicKey})}importPrivateKey(e){return B(this,null,function*(){const{pluginId:s}=this.currencyInfo,t={};if(/[0-9a-zA-Z]{51}$/.test(e))ue._q.fromString(e),t.fioKey=e;else{if(!(0,ie.validateMnemonic)(e))throw new Error("Invalid input");const o=yield F.rn.createPrivateKeyMnemonic(e);t.fioKey=o.fioKey,t.mnemonic=o.mnemonic}const r=yield this.derivePublicKey({type:`wallet:${s}`,id:"fake",keys:t});return t.publicKey=r.publicKey,t})}createPrivateKey(e){return B(this,null,function*(){if(e.replace("wallet:","")===ce){const t=ve.from(this.io.random(32));return yield F.rn.createPrivateKey(t)}else throw new Error("InvalidWalletType")})}derivePublicKey(e){return B(this,null,function*(){if(e.type.replace("wallet:","")===ce)return F.rn.derivedPublicKey(e.keys.fioKey);throw new Error("InvalidWalletType")})}parseUri(e){return B(this,null,function*(){var s;const{edgeParsedUri:t}=(0,Q.k)(ee.j,e,{fio:!0},le);if(!de((s=t.publicAddress)!=null?s:""))throw new Error("InvalidPublicAddressError");return t})}encodeUri(e){return B(this,arguments,function*(s,t=[]){if(!de(s.publicAddress))throw new Error("InvalidPublicAddressError");let o;if(typeof s.nativeAmount=="string"){const a=le,n=s.nativeAmount,i=(0,D.Qs)(a,ee.j,t);if(i==null)throw new Error("InternalErrorInvalidCurrencyCode");o=(0,O.div)(n,i.multiplier,16)}return(0,Q.Q)(s,ce,o)})}getConnectedPublicAddress(e,s,t){return B(this,null,function*(){var r;try{F.rn.isFioAddressValid(e)}catch{throw new P.OU("",400,this.networkInfo.errorCodes.INVALID_FIO_ADDRESS)}try{if((yield this.multicastServers("isAvailable",{fioName:e})).is_registered===0)throw new P.OU("",404,this.networkInfo.errorCodes.FIO_ADDRESS_IS_NOT_EXIST)}catch(o){throw o.name==="FioError"&&((r=o.json)==null?void 0:r.fields)!=null&&o.errorCode===400&&(o.labelCode=this.networkInfo.errorCodes.INVALID_FIO_ADDRESS),o}try{const o=yield this.multicastServers("getPublicAddress",{fioAddress:e,chainCode:s,tokenCode:t});if(o.public_address==null||o.public_address==="0")throw new P.OU("",404,this.networkInfo.errorCodes.FIO_ADDRESS_IS_NOT_LINKED);return o}catch(o){throw o.name==="FioError"&&o.labelCode===this.networkInfo.errorCodes.FIO_ADDRESS_IS_NOT_LINKED||o.errorCode===404?new P.OU("",404,this.networkInfo.errorCodes.FIO_ADDRESS_IS_NOT_LINKED):o}})}isFioAddressValid(e){return B(this,null,function*(){try{return F.rn.isFioAddressValid(e)}catch{return!1}})}validateAccount(e,s=!1){return B(this,null,function*(){var t;try{if(s){if(!F.rn.isFioDomainValid(e))return!1}else if(!F.rn.isFioAddressValid(e))return!1}catch{throw new P.OU("",400,this.networkInfo.errorCodes.INVALID_FIO_ADDRESS)}try{return(yield this.multicastServers("isAvailable",{fioName:e})).is_registered===0}catch(r){throw r.name==="FioError"&&((t=r.json)==null?void 0:t.fields)!=null&&r.errorCode===400&&(r.labelCode=this.networkInfo.errorCodes.INVALID_FIO_ADDRESS),r}})}isDomainPublic(e){return B(this,null,function*(){if((yield this.multicastServers("isAvailable",{fioName:e})).is_registered===0)throw new P.OU("",400,this.networkInfo.errorCodes.FIO_DOMAIN_IS_NOT_EXIST);const t=yield this.fetchCors(`${this.networkInfo.fioRegApiUrl}${c.n3.isDomainPublic}/${e}`,{method:"GET"});if(!t.ok){const o=yield t.json();throw new P.OU("",t.status,this.networkInfo.errorCodes.IS_DOMAIN_PUBLIC_ERROR,o)}const{isPublic:r}=yield t.json();return r})}doesAccountExist(e){return B(this,null,function*(){try{if(!F.rn.isFioAddressValid(e))return!1}catch{return!1}try{return(yield this.multicastServers("isAvailable",{fioName:e})).is_registered===1}catch(s){return this.error("doesAccountExist error: ",s),!1}})}buyAddressRequest(e,s=!1){return B(this,null,function*(){const t={Accept:"application/json","Content-Type":"application/json"};s&&(e.apiToken=this.fioRegApiToken);try{const r=yield this.fetchCors(`${this.networkInfo.fioRegApiUrl}${c.n3.buyAddress}`,{method:"POST",headers:t,body:JSON.stringify(e)});if(!r.ok){const o=yield r.json();throw this.networkInfo.errorCodes[o.errorCode]!=null?new P.OU(o.error,r.status,this.networkInfo.errorCodes[o.errorCode],o):o.error==="Already registered"?new P.OU(o.error,r.status,this.networkInfo.errorCodes.ALREADY_REGISTERED,o):new Error(o.error)}return yield r.json()}catch(r){throw r.labelCode!=null?r:new P.OU((0,D.HY)(r),500,this.networkInfo.errorCodes.SERVER_ERROR)}})}getDomains(e=""){return B(this,null,function*(){e==null&&(e=this.networkInfo.defaultRef);try{const s=yield this.fetchCors(`${this.networkInfo.fioRegApiUrl}${c.n3.getDomains}/${e}`,{method:"GET"}),t=yield s.json();if(!s.ok)throw this.networkInfo.errorCodes[t.errorCode]!=null?new P.OU(t.error,s.status,this.networkInfo.errorCodes[t.errorCode],t):new Error(t.error);return t.domains}catch(s){throw s.labelCode!=null?s:new P.OU((0,D.HY)(s),500,this.networkInfo.errorCodes.SERVER_ERROR)}})}getStakeEstReturn(){return B(this,null,function*(){try{const e=yield this.fetchCors(`${this.networkInfo.fioStakingApyUrl}`,{method:"GET"}),s=yield e.json();if(!e.ok)throw new Error(this.networkInfo.errorCodes.SERVER_ERROR);const t=s.historical_apr["7day"];return t!=null&&t>c.OT||t==null?c.OT:t}catch(e){throw e.labelCode!=null?e:new P.OU(e.message,500,this.networkInfo.errorCodes.SERVER_ERROR)}})}multicastServers(e,s){return B(this,null,function*(){const t=yield(0,D.QJ)((0,D.Sy)(this.networkInfo.apiUrls.map(r=>()=>B(this,null,function*(){let o;const l=new F.rn("","",r,this.fetchCors,void 0,this.tpid);try{o=yield l.genericAction(e,s)}catch(a){if(a.errorCode!=null&&P.lI.includes(a.errorCode))o={isError:!0,data:{code:a.errorCode,message:(0,D.HY)(a),json:a.json,list:a.list}};else throw a}return o}))));if(t.isError!=null){const r=new P.OU(t.errorMessage);throw r.json=t.data.json,r.list=t.data.list,r.errorCode=t.data.code,r}return t})}}function Ae(g){return B(this,null,function*(){return new me(g)})}},89214:function(){},52361:function(){},94616:function(){}}]);
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[
|
|
2
|
-
${yield T.text()}`),new Error("ErrorActivationPayment")}catch(T){throw this.warn("submitActivationPayment error: ",T),T}return this.otherData.paymentSubmitted=!0,this.walletLocalDataDirty=!0,h})}}checkAccountCreationStatus(){return v(this,null,function*(){if(this.accountNameChecked)return;const{activationRequestId:t,paymentSubmitted:e}=this.otherData;let r;try{const n=yield this.fetchCors(`${this.mirrorNodes[0]}/api/v1/accounts?account.publickey=${this.walletInfo.keys.publicKey}`),{accounts:o}=(0,E.DP)(yield n.json());for(const i of o)this.walletInfo.keys.publicKey.includes(i.key.key)&&(r=i.account);this.accountNameChecked=!0}catch(n){this.warn(`checkAccountCreationStatus ${this.mirrorNodes[0]} error`,n)}if(r==null&&e&&t!=null)try{const n=yield this.fetchCors(`${this.creatorApiServers[0]}/request/${t}/status`),o=(0,E.qv)(yield n.json());if(o.status==="transaction_error")throw this.otherData.activationRequestId=void 0,this.otherData.accountActivationQuoteAddress=void 0,this.otherData.accountActivationQuoteAmount=void 0,this.walletLocalDataDirty=!0,this.warn(`hederaEngine error from account activation status ${JSON.stringify(o)}`),new Error("ErrorAccountActivation");o.status==="success"&&o.account_id!=null&&(r=o.account_id)}catch(n){if(this.warn(`error checking Hedera account creation status, ID: ${t} error `,n),(n==null?void 0:n.message)==="ErrorAccountActivation")throw n}r!=null&&(this.otherData.hederaAccount=r,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onAddressChanged(),this.accountNameChecked=!0)})}setOtherData(t){this.otherData=(0,E.nG)(t)}queryBalance(){return v(this,null,function*(){const t=this.otherData.hederaAccount;if(t==null){this.accountNameChecked&&this.updateBalance(this.currencyInfo.currencyCode,"0");return}const e=`${this.mirrorNodes[0]}/api/v1/balances?account.id=${t}`;try{const r=yield this.fetchCors(e);if(!r.ok){const i=yield r.text();throw new Error(i)}const o=(0,E.sd)(yield r.json()).balances.find(i=>i.account===t);if(o==null)throw new Error("Unable to find matching balanceObj");this.updateBalance(this.currencyInfo.currencyCode,o.balance.toString())}catch(r){this.warn("queryBalance error checking balance:",r)}})}getNewTransactions(){return v(this,null,function*(){if(this.otherData.hederaAccount==null){this.accountNameChecked&&(this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=1,this.updateOnAddressesChecked());return}try{for(;;){const t=yield this.getTransactionsMirrorNode(this.otherData.latestTimestamp);if(t.length>0)this.processTxs(t);else break}this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=1,this.updateOnAddressesChecked()}catch(t){this.warn("getNewTransactions error getting transactions:",t)}})}processTxs(t){if(t.length>0){const e=t[t.length-1];if(e.otherParams==null)throw new Error("hederaEngine: EdgeTransaction must have otherParams");this.otherData.latestTimestamp!==e.otherParams.consensusAt&&(this.otherData.latestTimestamp=e.otherParams.consensusAt,this.walletLocalDataDirty=!0),t.forEach(r=>this.addTransaction(this.currencyInfo.currencyCode,r)),this.currencyEngineCallbacks.onTransactionsChanged(t)}}getTransactionsMirrorNode(t){return v(this,null,function*(){var e;if(this.otherData.hederaAccount==null)throw new Error("no Hedera account ID");const r=(e=this.otherData.hederaAccount)!=null?e:"",n=`${this.mirrorNodes[0]}/api/v1/transactions?transactionType=CRYPTOTRANSFER&account.id=${r}&order=asc×tamp=gt:${t}`,o=yield this.fetchCors(n);if(!o.ok)return this.warn(`getTransactionsMirrorNode error fetching MirrorNode transactions: ${n}`),[];const i=(0,E.Vf)(yield o.json()),a=[];for(const s of i.transactions){const h=s.transfers.find(C=>C.account===r);if(h==null)continue;const m=h.amount.toString(),P=[];(0,b.gt)(m,"0")&&P.push(r),a.push({txid:$(D.US.parse(s.transaction_hash)),date:parseInt(s.valid_start_timestamp),currencyCode:this.currencyInfo.currencyCode,blockHeight:1,nativeAmount:m,isSend:m.startsWith("-"),networkFee:s.charged_tx_fee.toString(),ourReceiveAddresses:P,signedTx:"",otherParams:{consensusAt:s.consensus_timestamp},walletId:this.walletId})}return a})}startEngine(){return v(this,null,function*(){this.engineOn=!0,this.accountNameChecked=this.otherData.hederaAccount!=null,this.addToLoop("getNewTransactions",1e3),this.addToLoop("queryBalance",5e3),this.addToLoop("checkAccountCreationStatus",5e3),yield I(x.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return v(this,null,function*(){this.accountNameChecked=!1,yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}makeSpend(t){return v(this,null,function*(){var e;if(this.otherData.hederaAccount==null)throw Error("ErrorAccountNotActivated");const{edgeSpendInfo:r,currencyCode:n}=this.makeSpendCheck(t);if(r.spendTargets.length!==1)throw new Error("Error: only one output allowed");const{publicAddress:o,uniqueIdentifier:i=""}=r.spendTargets[0];let{nativeAmount:a}=r.spendTargets[0];if(o==null)throw new Error("makeSpend Missing publicAddress");if(a==null)throw new K.$D;if((0,b.eq)(a,"0"))throw new K.$D;const s=g.Hbar.fromTinybar(a),h=g.Hbar.fromTinybar(this.maxFee),m=h.asTinybar().toString();if(a=(0,b.add)(a,m),(0,b.gt)(a,(e=this.walletLocalData.totalBalances[n])!=null?e:"0"))throw new K.C_;if(this.otherData.hederaAccount==null)throw new Error("creating a transfer without an account ID");const P=new g.TransactionId(this.otherData.hederaAccount),C=new g.TransferTransaction().setTransactionId(P).addHbarTransfer(this.otherData.hederaAccount,s.negated()).addHbarTransfer(o,s).setMaxTransactionFee(h).setTransactionMemo(i).build(this.client);return{txid:"",date:0,currencyCode:n,blockHeight:0,nativeAmount:`-${a}`,isSend:!0,networkFee:m,ourReceiveAddresses:[],signedTx:"",otherParams:{fromAddress:this.walletLocalData.publicKey,toAddress:o,transferTx:D.US.stringify(C.toBytes())},walletId:this.walletId}})}signTx(t,e){return v(this,null,function*(){const r=(0,E.cG)(this.currencyInfo.pluginId)(e);if(t.otherParams==null||t.otherParams.transferTx==null)throw new Error("missing otherParam transferTx");const n=r.privateKey;if(n==null)throw new Error("missing privateKey in walletInfo");const o=g.Transaction.fromBytes(D.US.parse(t.otherParams.transferTx));return yield o.sign(g.Ed25519PrivateKey.fromString(n)),z(O({},t),{signedTx:D.US.stringify(o.toBytes()),txid:$(o.hash()),date:Date.now()/1e3,otherParams:O({},t.otherParams)})})}broadcastTx(t){return v(this,null,function*(){if(t.signedTx==null)throw new Error("InvalidTransactionParams");try{yield g.Transaction.fromBytes(D.US.parse(t.signedTx)).execute(this.client)}catch(e){throw this.warn("broadcastTx error",e),e}return t.blockHeight=1,t})}getFreshAddress(t){return v(this,null,function*(){var e;return{publicAddress:(e=this.otherData.hederaAccount)!=null?e:""}})}getBlockHeight(){return Math.floor(Date.now()/1e3)}}function $(c){return D.YU.stringify(c).toLowerCase()}function N(c,t,e,r){return v(this,null,function*(){const n=(0,E.y_)(e),o=new x(c,t,n,r);return yield o.loadEngine(),o})}var A=(c,t,e)=>new Promise((r,n)=>{var o=s=>{try{a(e.next(s))}catch(h){n(h)}},i=s=>{try{a(e.throw(s))}catch(h){n(h)}},a=s=>s.done?r(s.value):Promise.resolve(s.value).then(o,i);a((e=e.apply(c,t)).next())});const M="",V="302e020100300506032b657004220420";class J{constructor(t){const{builtinTokens:e,currencyInfo:r,io:n,log:o,networkInfo:i}=t;this.builtinTokens=e,this.currencyInfo=r,this.fetchCors=(0,S.zR)(n),this.io=n,this.log=o,this.networkInfo=i}getDisplayPrivateKey(t){return A(this,null,function*(){var e;const{pluginId:r}=this.currencyInfo,n=(0,E.cG)(r)(t.keys);return(e=n.mnemonic)!=null?e:n.privateKey})}getDisplayPublicKey(t){return A(this,null,function*(){const{keys:e}=(0,E.y_)(t);return e.publicKey})}createPrivateKey(t){return A(this,null,function*(){if(t!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const e=this.io.random(32),r=(0,B.entropyToMnemonic)(e);return yield this.importPrivateKey(r)})}importPrivateKey(t){return A(this,null,function*(){const{pluginId:e}=this.currencyInfo;try{let r,n;if(/^(0x)?[0-9a-fA-F]{64}$/.test(t.replace(V,""))){const o=t.replace(/^0x/,"").replace(V,"");n=g.Ed25519PrivateKey.fromString(o).toString()}else if((0,B.validateMnemonic)(t)){const i=yield g.Mnemonic.fromString(t).toPrivateKey(M);r=t,n=i.toString()}else throw new Error("InvalidPrivateKey");return{[`${e}Mnemonic`]:r,[`${e}Key`]:n}}catch{throw new Error("InvalidPrivateKey")}})}derivePublicKey(t){return A(this,null,function*(){var e;const{pluginId:r}=this.currencyInfo;if(t.type!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");if(t.keys==null||((e=t.keys)==null?void 0:e[`${r}Key`])==null)throw new Error("Invalid private key");return{publicKey:g.Ed25519PrivateKey.fromString(t.keys[`${r}Key`]).publicKey.toString()}})}parseUri(t){return A(this,null,function*(){const{pluginId:e}=this.currencyInfo,{edgeParsedUri:r,edgeParsedUri:{publicAddress:n}}=(0,L.k)(this.currencyInfo,t,{[`${e}`]:!0},this.currencyInfo.currencyCode);if(n!=null){const{checksumNetworkID:o}=this.networkInfo,[i,a]=n.split("-");if(!H(n)||a!=null&&a!==j(i,o))throw new Error("InvalidPublicAddressError")}return r})}encodeUri(t){return A(this,arguments,function*(e,r=[]){const{pluginId:n}=this.currencyInfo,{publicAddress:o,nativeAmount:i}=e;if(!H(o))throw new Error("InvalidPublicAddressError");if(i==null||typeof i!="string")return o;const a=(0,S.Qs)(this.currencyInfo.currencyCode,this.currencyInfo,r);if(a==null)throw new Error("InternalErrorInvalidCurrencyCode");const s=(0,b.div)(i,a.multiplier,8);return(0,L.Q)(e,n,s)})}getActivationSupportedCurrencies(){return A(this,null,function*(){return{result:{ETH:!0}}})}getActivationCost(){return A(this,null,function*(){const t=this.networkInfo.creatorApiServers[0];try{const e=yield this.fetchCors(`${t}/account/cost`);return(0,E.NV)(yield e.json()).hbar}catch(e){throw this.log.warn("getActivationCost error unable to get account activation cost",e),new Error("ErrorUnableToGetCost")}})}validateAccount(){return A(this,null,function*(){return{result:"AccountAvailable"}})}}function tt(c){return A(this,null,function*(){return new J(c)})}},55024:function(){}}]);
|
|
1
|
+
(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[9894],{79014:function(X,R,f){"use strict";f.d(R,{Q:function(){return G},k:function(){return q}});var g=f(77591),b=f.n(g),B=f(24350),L=f(84564),S=f.n(L),E=f(76714),H=Object.defineProperty,j=Object.getOwnPropertySymbols,K=Object.prototype.hasOwnProperty,D=Object.prototype.propertyIsEnumerable,F=(l,y,p)=>y in l?H(l,y,{enumerable:!0,configurable:!0,writable:!0,value:p}):l[y]=p,W=(l,y)=>{for(var p in y||(y={}))K.call(y,p)&&F(l,p,y[p]);if(j)for(var p of j(y))D.call(y,p)&&F(l,p,y[p]);return l};function q(l,y,p,w,_=[]){const d=W({},S()(y,{},!0)),O=y.startsWith(`${l.pluginId}://`);if(d.protocol!=null&&(d.protocol=d.protocol.replace(":","")),d.protocol!=null&&d.protocol!==""&&!p[d.protocol])throw new Error(`Uri protocol '${d.protocol}' is not supported for ${l.pluginId}.`);if(d.host===""&&d.pathname==="")throw new Error("Path and host not found in uri.");const I={publicAddress:d.host!==""?d.host:d.pathname.split("/")[0]},v=d.query.label,x=d.query.message,$=d.query.category;(v!=null||x!=null||$!=null||O)&&(I.metadata={},I.metadata.name=v,I.metadata.notes=x,I.metadata.category=$,I.metadata.gateway=O!=null?O:!1);const N=d.query.amount;if(N!=null&&typeof N=="string"){w==null&&(w=l.currencyCode);const A=(0,E.Qs)(w!=null?w:"",l,_);if(A==null)throw new Error("InternalErrorInvalidCurrencyCode");let M=(0,g.mul)(N,A.multiplier);M=(0,g.toFixed)(M,0,0),I.nativeAmount=M,I.currencyCode=w}return{edgeParsedUri:I,parsedUri:d}}function G(l,y,p){if(l.publicAddress==null)throw new Error("InvalidPublicAddressError");if(p==null&&l.label==null&&l.message==null)return l.publicAddress;{let w="";p!=null&&(w+="amount="+p+"&"),(l.label!=null||l.message!=null)&&(typeof l.label=="string"&&(w+="label="+l.label+"&"),typeof l.message=="string"&&(w+="message="+l.message+"&")),w=w.substr(0,w.length-1);const _={scheme:y,path:l.publicAddress,query:w};return(0,B.qC)(_)}}},20212:function(X,R,f){"use strict";f.r(R),f.d(R,{HederaTools:function(){return J},makeCurrencyEngine:function(){return N},makeCurrencyTools:function(){return tt}});var g=f(17481),b=f(77591),B=f(2153),L=f(79014),S=f(76714),E=f(825);const H=(c="")=>/^(0|(?:[1-9]\d*))\.(0|(?:[1-9]\d*))\.(0|(?:[1-9]\d*))(?:-([a-z]{5}))?$/.test(c),j=(c,t)=>{let e="";const r=[];let n=0,o=0,i=0,a=0,s=0,h=0;const m=26*26*26,P=26*26*26*26*26,C=97,T=1000003,Q=31,k=`${t}000000000000`,U=[];for(let u=0;u<k.length;u+=2)U.push(parseInt(k.substr(u,2),16));for(let u=0;u<c.length;u++)r.push(c[u]==="."?10:parseInt(c[u],10));for(let u=0;u<r.length;u++)i=(Q*i+r[u])%m,u%2===0?n=(n+r[u])%11:o=(o+r[u])%11;for(let u=0;u<U.length;u++)a=(Q*a+U[u])%P;s=(((c.length%5*11+n)*11+o)*m+i+a)%P,h=s*T%P;for(let u=0;u<5;u++)e=String.fromCharCode(C+h%26)+e,h/=26;return e};var K=f(94935),D=f(35620),F=f(84650),W=Object.defineProperty,q=Object.defineProperties,G=Object.getOwnPropertyDescriptors,l=Object.getOwnPropertySymbols,y=Object.getPrototypeOf,p=Object.prototype.hasOwnProperty,w=Object.prototype.propertyIsEnumerable,_=Reflect.get,d=(c,t,e)=>t in c?W(c,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):c[t]=e,O=(c,t)=>{for(var e in t||(t={}))p.call(t,e)&&d(c,e,t[e]);if(l)for(var e of l(t))w.call(t,e)&&d(c,e,t[e]);return c},z=(c,t)=>q(c,G(t)),I=(c,t,e)=>_(y(c),e,t),v=(c,t,e)=>new Promise((r,n)=>{var o=s=>{try{a(e.next(s))}catch(h){n(h)}},i=s=>{try{a(e.throw(s))}catch(h){n(h)}},a=s=>s.done?r(s.value):Promise.resolve(s.value).then(o,i);a((e=e.apply(c,t)).next())});class x extends F.P{constructor(t,e,r,n){super(t,e,r,n);const{client:o,creatorApiServers:i,mirrorNodes:a,maxFee:s}=t.networkInfo;this.client=g.Client[`for${o}`](),this.fetchCors=(0,S.zR)(t.io),this.accountNameChecked=!1,this.creatorApiServers=i,this.mirrorNodes=a,this.maxFee=s,this.otherMethods={getAccountActivationQuote:h=>v(this,null,function*(){const{currencyCode:m,activePublicKey:P}=h;if(m==null||P==null)throw new Error("ErrorInvalidParams");const{accountActivationQuoteAmount:C,accountActivationQuoteAddress:T}=this.otherData;if(C!=null&&T!=null)return{paymentAddress:T,currencyCode:m,amount:(0,b.toFixed)(C,3,9),exchangeAmount:"0"};const Q={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({currency:m,public_key:P})};try{const k=yield this.fetchCors(`${this.creatorApiServers[0]}/account`,Q);if(!k.ok)throw new Error(yield k.text());const U=(0,E.LZ)(yield k.json()),{request_id:u,address:Y,amount:Z}=U;return this.warn(`activationRequestId: ${u}`),this.otherData.activationRequestId=u,this.otherData.accountActivationQuoteAddress=Y,this.otherData.accountActivationQuoteAmount=Z,this.walletLocalDataDirty=!0,{paymentAddress:Y,currencyCode:m,amount:(0,b.toFixed)(Z,3,18),exchangeAmount:"0"}}catch(k){throw this.warn("getAccountActivationQuote: error submitting account activation request",k),new Error("ErrorActivationRequest")}}),submitActivationPayment:h=>v(this,null,function*(){const m=this.otherData.activationRequestId;if(m==null)throw new Error({message:"ErrorNoActivationPending"});const P={method:"PUT",headers:{Accept:"application/octet-stream","Content-Type":"application/octet-stream"},body:(0,S.ah)(h.signedTx)},C=`${this.creatorApiServers[0]}/request/${m}/payment`;try{const T=yield this.fetchCors(C,P);if(!T.ok)throw this.warn(`submitActivationPayment failed to submit payment
|
|
2
|
+
${yield T.text()}`),new Error("ErrorActivationPayment")}catch(T){throw this.warn("submitActivationPayment error: ",T),T}return this.otherData.paymentSubmitted=!0,this.walletLocalDataDirty=!0,h})}}checkAccountCreationStatus(){return v(this,null,function*(){if(this.accountNameChecked)return;const{activationRequestId:t,paymentSubmitted:e}=this.otherData;let r;try{const n=yield this.fetchCors(`${this.mirrorNodes[0]}/api/v1/accounts?account.publickey=${this.walletInfo.keys.publicKey}`),{accounts:o}=(0,E.DP)(yield n.json());for(const i of o)this.walletInfo.keys.publicKey.includes(i.key.key)&&(r=i.account);this.accountNameChecked=!0}catch(n){this.warn(`checkAccountCreationStatus ${this.mirrorNodes[0]} error`,n)}if(r==null&&e&&t!=null)try{const n=yield this.fetchCors(`${this.creatorApiServers[0]}/request/${t}/status`),o=(0,E.qv)(yield n.json());if(o.status==="transaction_error")throw this.otherData.activationRequestId=void 0,this.otherData.accountActivationQuoteAddress=void 0,this.otherData.accountActivationQuoteAmount=void 0,this.walletLocalDataDirty=!0,this.warn(`hederaEngine error from account activation status ${JSON.stringify(o)}`),new Error("ErrorAccountActivation");o.status==="success"&&o.account_id!=null&&(r=o.account_id)}catch(n){if(this.warn(`error checking Hedera account creation status, ID: ${t} error `,n),(n==null?void 0:n.message)==="ErrorAccountActivation")throw n}r!=null&&(this.otherData.hederaAccount=r,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onAddressChanged(),this.accountNameChecked=!0)})}setOtherData(t){this.otherData=(0,E.nG)(t)}queryBalance(){return v(this,null,function*(){const t=this.otherData.hederaAccount;if(t==null){this.accountNameChecked&&this.updateBalance(this.currencyInfo.currencyCode,"0");return}const e=`${this.mirrorNodes[0]}/api/v1/balances?account.id=${t}`;try{const r=yield this.fetchCors(e);if(!r.ok){const i=yield r.text();throw new Error(i)}const o=(0,E.sd)(yield r.json()).balances.find(i=>i.account===t);if(o==null)throw new Error("Unable to find matching balanceObj");this.updateBalance(this.currencyInfo.currencyCode,o.balance.toString())}catch(r){this.warn("queryBalance error checking balance:",r)}})}getNewTransactions(){return v(this,null,function*(){if(this.otherData.hederaAccount==null){this.accountNameChecked&&(this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=1,this.updateOnAddressesChecked());return}try{for(;;){const t=yield this.getTransactionsMirrorNode(this.otherData.latestTimestamp);if(t.length>0)this.processTxs(t);else break}this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=1,this.updateOnAddressesChecked()}catch(t){this.warn("getNewTransactions error getting transactions:",t)}})}processTxs(t){if(t.length>0){const e=t[t.length-1];if(e.otherParams==null)throw new Error("hederaEngine: EdgeTransaction must have otherParams");this.otherData.latestTimestamp!==e.otherParams.consensusAt&&(this.otherData.latestTimestamp=e.otherParams.consensusAt,this.walletLocalDataDirty=!0),t.forEach(r=>this.addTransaction(this.currencyInfo.currencyCode,r)),this.currencyEngineCallbacks.onTransactionsChanged(t)}}getTransactionsMirrorNode(t){return v(this,null,function*(){var e;if(this.otherData.hederaAccount==null)throw new Error("no Hedera account ID");const r=(e=this.otherData.hederaAccount)!=null?e:"",n=`${this.mirrorNodes[0]}/api/v1/transactions?transactionType=CRYPTOTRANSFER&account.id=${r}&order=asc×tamp=gt:${t}`,o=yield this.fetchCors(n);if(!o.ok)return this.warn(`getTransactionsMirrorNode error fetching MirrorNode transactions: ${n}`),[];const i=(0,E.Vf)(yield o.json()),a=[];for(const s of i.transactions){const h=s.transfers.find(C=>C.account===r);if(h==null)continue;const m=h.amount.toString(),P=[];(0,b.gt)(m,"0")&&P.push(r),a.push({txid:$(D.US.parse(s.transaction_hash)),date:parseInt(s.valid_start_timestamp),currencyCode:this.currencyInfo.currencyCode,blockHeight:1,nativeAmount:m,isSend:m.startsWith("-"),networkFee:s.charged_tx_fee.toString(),ourReceiveAddresses:P,signedTx:"",otherParams:{consensusAt:s.consensus_timestamp},walletId:this.walletId})}return a})}startEngine(){return v(this,null,function*(){this.engineOn=!0,this.accountNameChecked=this.otherData.hederaAccount!=null,this.addToLoop("getNewTransactions",1e3),this.addToLoop("queryBalance",5e3),this.addToLoop("checkAccountCreationStatus",5e3),yield I(x.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return v(this,null,function*(){this.accountNameChecked=!1,yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}makeSpend(t){return v(this,null,function*(){var e;if(this.otherData.hederaAccount==null)throw Error("ErrorAccountNotActivated");const{edgeSpendInfo:r,currencyCode:n}=this.makeSpendCheck(t);if(r.spendTargets.length!==1)throw new Error("Error: only one output allowed");const{publicAddress:o,uniqueIdentifier:i=""}=r.spendTargets[0];let{nativeAmount:a}=r.spendTargets[0];if(o==null)throw new Error("makeSpend Missing publicAddress");if(a==null)throw new K.$D;if((0,b.eq)(a,"0"))throw new K.$D;const s=g.Hbar.fromTinybar(a),h=g.Hbar.fromTinybar(this.maxFee),m=h.asTinybar().toString();if(a=(0,b.add)(a,m),(0,b.gt)(a,(e=this.walletLocalData.totalBalances[n])!=null?e:"0"))throw new K.C_;if(this.otherData.hederaAccount==null)throw new Error("creating a transfer without an account ID");const P=new g.TransactionId(this.otherData.hederaAccount),C=new g.TransferTransaction().setTransactionId(P).addHbarTransfer(this.otherData.hederaAccount,s.negated()).addHbarTransfer(o,s).setMaxTransactionFee(h).setTransactionMemo(i).build(this.client);return{txid:"",date:0,currencyCode:n,blockHeight:0,nativeAmount:`-${a}`,isSend:!0,networkFee:m,ourReceiveAddresses:[],signedTx:"",otherParams:{fromAddress:this.walletLocalData.publicKey,toAddress:o,transferTx:D.US.stringify(C.toBytes())},walletId:this.walletId}})}signTx(t,e){return v(this,null,function*(){const r=(0,E.cG)(this.currencyInfo.pluginId)(e);if(t.otherParams==null||t.otherParams.transferTx==null)throw new Error("missing otherParam transferTx");const n=r.privateKey;if(n==null)throw new Error("missing privateKey in walletInfo");const o=g.Transaction.fromBytes(D.US.parse(t.otherParams.transferTx));return yield o.sign(g.Ed25519PrivateKey.fromString(n)),z(O({},t),{signedTx:D.US.stringify(o.toBytes()),txid:$(o.hash()),date:Date.now()/1e3,otherParams:O({},t.otherParams)})})}broadcastTx(t){return v(this,null,function*(){if(t.signedTx==null)throw new Error("InvalidTransactionParams");try{yield g.Transaction.fromBytes(D.US.parse(t.signedTx)).execute(this.client)}catch(e){throw this.warn("broadcastTx error",e),e}return t.blockHeight=1,t})}getFreshAddress(t){return v(this,null,function*(){var e;return{publicAddress:(e=this.otherData.hederaAccount)!=null?e:""}})}getBlockHeight(){return Math.floor(Date.now()/1e3)}}function $(c){return D.YU.stringify(c).toLowerCase()}function N(c,t,e,r){return v(this,null,function*(){const n=(0,E.y_)(e),o=new x(c,t,n,r);return yield o.loadEngine(),o})}var A=(c,t,e)=>new Promise((r,n)=>{var o=s=>{try{a(e.next(s))}catch(h){n(h)}},i=s=>{try{a(e.throw(s))}catch(h){n(h)}},a=s=>s.done?r(s.value):Promise.resolve(s.value).then(o,i);a((e=e.apply(c,t)).next())});const M="",V="302e020100300506032b657004220420";class J{constructor(t){const{builtinTokens:e,currencyInfo:r,io:n,log:o,networkInfo:i}=t;this.builtinTokens=e,this.currencyInfo=r,this.fetchCors=(0,S.zR)(n),this.io=n,this.log=o,this.networkInfo=i}getDisplayPrivateKey(t){return A(this,null,function*(){var e;const{pluginId:r}=this.currencyInfo,n=(0,E.cG)(r)(t.keys);return(e=n.mnemonic)!=null?e:n.privateKey})}getDisplayPublicKey(t){return A(this,null,function*(){const{keys:e}=(0,E.y_)(t);return e.publicKey})}createPrivateKey(t){return A(this,null,function*(){if(t!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const e=this.io.random(32),r=(0,B.entropyToMnemonic)(e);return yield this.importPrivateKey(r)})}importPrivateKey(t){return A(this,null,function*(){const{pluginId:e}=this.currencyInfo;try{let r,n;if(/^(0x)?[0-9a-fA-F]{64}$/.test(t.replace(V,""))){const o=t.replace(/^0x/,"").replace(V,"");n=g.Ed25519PrivateKey.fromString(o).toString()}else if((0,B.validateMnemonic)(t)){const i=yield g.Mnemonic.fromString(t).toPrivateKey(M);r=t,n=i.toString()}else throw new Error("InvalidPrivateKey");return{[`${e}Mnemonic`]:r,[`${e}Key`]:n}}catch{throw new Error("InvalidPrivateKey")}})}derivePublicKey(t){return A(this,null,function*(){var e;const{pluginId:r}=this.currencyInfo;if(t.type!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");if(t.keys==null||((e=t.keys)==null?void 0:e[`${r}Key`])==null)throw new Error("Invalid private key");return{publicKey:g.Ed25519PrivateKey.fromString(t.keys[`${r}Key`]).publicKey.toString()}})}parseUri(t){return A(this,null,function*(){const{pluginId:e}=this.currencyInfo,{edgeParsedUri:r,edgeParsedUri:{publicAddress:n}}=(0,L.k)(this.currencyInfo,t,{[`${e}`]:!0},this.currencyInfo.currencyCode);if(n!=null){const{checksumNetworkID:o}=this.networkInfo,[i,a]=n.split("-");if(!H(n)||a!=null&&a!==j(i,o))throw new Error("InvalidPublicAddressError")}return r})}encodeUri(t){return A(this,arguments,function*(e,r=[]){const{pluginId:n}=this.currencyInfo,{publicAddress:o,nativeAmount:i}=e;if(!H(o))throw new Error("InvalidPublicAddressError");if(i==null||typeof i!="string")return o;const a=(0,S.Qs)(this.currencyInfo.currencyCode,this.currencyInfo,r);if(a==null)throw new Error("InternalErrorInvalidCurrencyCode");const s=(0,b.div)(i,a.multiplier,8);return(0,L.Q)(e,n,s)})}getActivationSupportedCurrencies(){return A(this,null,function*(){return{result:{ETH:!0}}})}getActivationCost(){return A(this,null,function*(){const t=this.networkInfo.creatorApiServers[0];try{const e=yield this.fetchCors(`${t}/account/cost`);return(0,E.NV)(yield e.json()).hbar}catch(e){throw this.log.warn("getActivationCost error unable to get account activation cost",e),new Error("ErrorUnableToGetCost")}})}validateAccount(){return A(this,null,function*(){return{result:"AccountAvailable"}})}}function tt(c){return A(this,null,function*(){return new J(c)})}},89214:function(){},52361:function(){},94616:function(){},55024:function(){}}]);
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[591],{79014:function(et,M,d){d.d(M,{Q:function(){return _},k:function(){return V}});var S=d(77591),j=d.n(S),W=d(24350),X=d(84564),i=d.n(X),L=d(76714),U=Object.defineProperty,T=Object.getOwnPropertySymbols,F=Object.prototype.hasOwnProperty,I=Object.prototype.propertyIsEnumerable,a=(c,g,m)=>g in c?U(c,g,{enumerable:!0,configurable:!0,writable:!0,value:m}):c[g]=m,Q=(c,g)=>{for(var m in g||(g={}))F.call(g,m)&&a(c,m,g[m]);if(T)for(var m of T(g))I.call(g,m)&&a(c,m,g[m]);return c};function V(c,g,m,k,P=[]){const y=Q({},i()(g,{},!0)),O=g.startsWith(`${c.pluginId}://`);if(y.protocol!=null&&(y.protocol=y.protocol.replace(":","")),y.protocol!=null&&y.protocol!==""&&!m[y.protocol])throw new Error(`Uri protocol '${y.protocol}' is not supported for ${c.pluginId}.`);if(y.host===""&&y.pathname==="")throw new Error("Path and host not found in uri.");const C={publicAddress:y.host!==""?y.host:y.pathname.split("/")[0]},H=y.query.label,x=y.query.message,R=y.query.category;(H!=null||x!=null||R!=null||O)&&(C.metadata={},C.metadata.name=H,C.metadata.notes=x,C.metadata.category=R,C.metadata.gateway=O!=null?O:!1);const B=y.query.amount;if(B!=null&&typeof B=="string"){k==null&&(k=c.currencyCode);const $=(0,L.Qs)(k!=null?k:"",c,P);if($==null)throw new Error("InternalErrorInvalidCurrencyCode");let D=(0,S.mul)(B,$.multiplier);D=(0,S.toFixed)(D,0,0),C.nativeAmount=D,C.currencyCode=k}return{edgeParsedUri:C,parsedUri:y}}function _(c,g,m){if(c.publicAddress==null)throw new Error("InvalidPublicAddressError");if(m==null&&c.label==null&&c.message==null)return c.publicAddress;{let k="";m!=null&&(k+="amount="+m+"&"),(c.label!=null||c.message!=null)&&(typeof c.label=="string"&&(k+="label="+c.label+"&"),typeof c.message=="string"&&(k+="message="+c.message+"&")),k=k.substr(0,k.length-1);const P={scheme:g,path:c.publicAddress,query:k};return(0,W.qC)(P)}}},34765:function(et,M,d){d.r(M),d.d(M,{PolkadotTools:function(){return tt},makeCurrencyEngine:function(){return it},makeCurrencyTools:function(){return ct}});var S=d(58170),j=d(21293),W=d(18534),X=d(23670),i=d(77591),L=d(2153),U=d(48764),T=d(20918),F=d(79014),I=d(76714),a=d(82448),Q=d(62177);const V=(0,a.su)({txCount:(0,a.Vk)(a.mH,0)}),_=(0,a.su)({code:a.mH,message:a.XC,data:(0,a.Zz)((0,a.su)(a.JC))}),c=(0,a.su)({from:a.XC,to:a.XC,success:a.jK,hash:a.XC,block_num:a.mH,block_timestamp:a.mH,module:a.XC,amount:a.XC,fee:a.XC}),g=(0,a.su)({count:a.mH,transfers:(0,a.Vk)((0,a._2)(c),()=>[])}),m=Q.BQ,k=u=>{const t=(0,a.su)({[`${u}Mnemonic`]:(0,a.Zz)(a.XC),[`${u}Key`]:a.XC});return(0,a.W1)(e=>{const r=t(e);return{mnemonic:r[`${u}Mnemonic`],privateKey:r[`${u}Key`]}},e=>({[`${u}Mnemonic`]:e.mnemonic,[`${u}Key`]:e.privateKey}))};var P=d(94935),y=d(35620),O=d(84650),z=Object.defineProperty,C=Object.defineProperties,H=Object.getOwnPropertyDescriptors,x=Object.getOwnPropertySymbols,R=Object.getPrototypeOf,B=Object.prototype.hasOwnProperty,$=Object.prototype.propertyIsEnumerable,D=Reflect.get,G=(u,t,e)=>t in u?z(u,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):u[t]=e,Y=(u,t)=>{for(var e in t||(t={}))B.call(t,e)&&G(u,e,t[e]);if(x)for(var e of x(t))$.call(t,e)&&G(u,e,t[e]);return u},J=(u,t)=>C(u,H(t)),Z=(u,t,e)=>D(R(u),e,t),w=(u,t,e)=>new Promise((r,n)=>{var s=o=>{try{h(e.next(o))}catch(f){n(f)}},l=o=>{try{h(e.throw(o))}catch(f){n(f)}},h=o=>o.done?r(o.value):Promise.resolve(o.value).then(s,l);h((e=e.apply(u,t)).next())});const nt=5e3,rt=2e4,st=3e3,ot=(0,I.jT)();class N extends O.P{constructor(t,e,r,n){super(t,e,r,n),this.getRecipientBalance=s=>w(this,null,function*(){try{return(yield this.api.query.system.account(s)).data.free.toString()}catch{return this.minimumAddressBalance}}),this.fetchCors=(0,I.zR)(t.io),this.networkInfo=t.networkInfo,this.nonce=0}setOtherData(t){this.otherData=V(t)}fetchSubscan(t,e){return w(this,null,function*(){if(this.networkInfo.subscanBaseUrl==null)throw new Error("Missing subscan url");const r={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(e)},n=yield this.fetchCors(this.networkInfo.subscanBaseUrl+t,r);if(!n.ok||n.status===429)throw new Error(`Subscan ${t} failed with ${n.status}`);const s=yield n.json();return _(s)})}queryBalance(){return w(this,null,function*(){const t=yield this.api.query.system.account(this.walletInfo.keys.publicKey);this.nonce=t.nonce.toNumber(),this.updateBalance(this.currencyInfo.currencyCode,t.data.free.toString());for(const e of this.enabledTokenIds){const r=this.allTokensMap[e];if(r==null)continue;const n=(0,T.Oj)(r.networkLocation);if(n==null)continue;const s=yield this.api.query.assets.account(n.contractAddress,this.walletInfo.keys.publicKey);let l="0";s.isSome&&(l=s.unwrap().balance.toString()),this.updateBalance(r.currencyCode,l)}})}queryBlockheight(){return w(this,null,function*(){try{const e=(yield this.api.rpc.chain.getBlock()).block.header.number.toNumber();e>this.walletLocalData.blockHeight&&(this.walletLocalData.blockHeight=e,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight))}catch(t){this.warn("queryBlockheight failed with error: ",t)}})}processPolkadotTransaction(t){const{from:e,to:r,success:n,hash:s,block_num:l,block_timestamp:h,module:o,amount:f,fee:p}=t;if(!n||o!=="balances")return;const E=(0,I.aL)(this.currencyInfo.currencyCode,this.currencyInfo,this.allTokensMap);if(E==null)return;const A=[];let v=(0,i.mul)(f,E.multiplier);e===this.walletInfo.keys.publicKey?v=`-${(0,i.add)(v,p)}`:A.push(r);const K={txid:s,date:h,currencyCode:this.currencyInfo.currencyCode,blockHeight:l,nativeAmount:v,isSend:v.startsWith("-"),networkFee:p,ourReceiveAddresses:A,signedTx:"",walletId:this.walletId};this.addTransaction(this.currencyInfo.currencyCode,K)}queryTransactions(){return w(this,null,function*(){if(this.networkInfo.subscanBaseUrl==null){for(const t of this.enabledTokens)this.tokenCheckTransactionsStatus[t]=1;this.updateOnAddressesChecked();return}return yield ot(()=>w(this,null,function*(){return yield this.queryTransactionsInner()}))})}queryTransactionsInner(){return w(this,null,function*(){let t=Math.floor(this.otherData.txCount/this.networkInfo.subscanQueryLimit);for(;;){const e={row:this.networkInfo.subscanQueryLimit,page:t,address:this.walletInfo.keys.publicKey};let r=0,n=[];try{const s=yield this.fetchSubscan("/scan/transfers",e),l=g(s.data);r=l.count,n=l.transfers}catch(s){if(s instanceof Error&&s.message.includes("Subscan /scan/transfers failed with 429")){this.log(s.message);continue}else throw s}if(r===this.otherData.txCount||(n.forEach(s=>{try{this.processPolkadotTransaction(c(s))}catch{const h=s!=null&&typeof s.hash=="string"?s.hash:"";this.warn(`Ignoring invalid transfer ${h}`)}}),this.otherData.txCount=t*this.networkInfo.subscanQueryLimit+n.length,this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=Math.min(1,r===0?1:this.otherData.txCount/r),this.updateOnAddressesChecked(),r===this.otherData.txCount))break;t++}this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=1,this.updateOnAddressesChecked(),this.transactionsChangedArray.length>0&&(this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[])})}startEngine(){return w(this,null,function*(){this.engineOn=!0,yield this.tools.connectApi(this.walletId),this.api=this.tools.polkadotApi,this.minimumAddressBalance=this.api.consts.balances.existentialDeposit.toString(),this.addToLoop("queryBlockheight",rt).catch(()=>{}),this.addToLoop("queryBalance",nt).catch(()=>{}),this.addToLoop("queryTransactions",st).catch(()=>{}),yield Z(N.prototype,this,"startEngine").call(this)})}killEngine(){return w(this,null,function*(){yield Z(N.prototype,this,"killEngine").call(this),yield this.tools.disconnectApi(this.walletId)})}resyncBlockchain(){return w(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getMaxSpendable(t){return w(this,null,function*(){if(t.spendTargets.length===0||t.spendTargets[0].publicAddress==null)throw new Error("Missing public address");const e=this.getBalance({currencyCode:t.currencyCode});if(t.currencyCode!==this.currencyInfo.currencyCode){const f=[{publicAddress:t.spendTargets[0].publicAddress,nativeAmount:e}],p=J(Y({},t),{spendTargets:f});return yield this.makeSpend(p),e}const r=(0,i.sub)(e,this.api.consts.balances.existentialDeposit.toString()),n=[{publicAddress:t.spendTargets[0].publicAddress,nativeAmount:"0"}],s=J(Y({},t),{spendTargets:n}),h=(yield this.makeSpend(s)).networkFee,o=(f,p)=>{const E=(0,i.sub)(p,f);if((0,i.lte)(E,"1"))return f;const A=(0,i.add)(f,(0,i.div)(E,"2")),v=(0,I.X0)(A).replace("0x",""),K=v.length%2===1?`0${v}`:v,ut=(0,i.mul)((0,i.div)(K.length.toString(),"2"),this.networkInfo.lengthFeePerByte),dt=(0,i.add)((0,i.add)(ut,h),A);return(0,i.gt)(dt,r)?o(f,A):o(A,p)};return o("0",(0,i.add)(r,"1"))})}makeSpend(t){return w(this,null,function*(){const{edgeSpendInfo:e,currencyCode:r}=this.makeSpendCheck(t);if(e.spendTargets.length!==1)throw new Error("Error: only one output allowed");const{nativeAmount:n,publicAddress:s}=e.spendTargets[0];if(s==null)throw new Error("makeSpend Missing publicAddress");if(n==null)throw new P.$D;const l=this.getBalance({currencyCode:r});let h,o;if(e.tokenId==null){const E=(0,i.sub)(l,this.api.consts.balances.existentialDeposit.toString());if((0,i.gt)(n,E))throw new P.C_;const v=yield(yield this.api.tx.balances.transferKeepAlive(s,n)).paymentInfo(this.walletInfo.keys.publicKey);if(o=(0,i.sub)(v.partialFee.toString(),(0,i.mul)(this.networkInfo.lengthFeePerByte,this.networkInfo.partialFeeOffsetMultiplier)),h=(0,i.add)(n,o),(0,i.gt)(h,E))throw new P.C_}else{if((0,i.gt)(n,l))throw new P.C_;h=n;const A=yield(yield this.api.tx.assets.transfer(parseInt(e.tokenId),s,n)).paymentInfo(this.walletInfo.keys.publicKey);o=(0,i.sub)(A.partialFee.toString(),(0,i.mul)(this.networkInfo.lengthFeePerByte,this.networkInfo.partialFeeOffsetMultiplier));const v=this.getBalance({currencyCode:this.currencyInfo.currencyCode}),K=(0,i.sub)(v,this.api.consts.balances.existentialDeposit.toString());if((0,i.gt)(o,K))throw new P.C_({currencyCode:this.currencyInfo.currencyCode,networkFee:o})}const f={publicAddress:s};return{txid:"",date:0,currencyCode:r,blockHeight:0,nativeAmount:(0,i.mul)(h,"-1"),isSend:!0,networkFee:o,ourReceiveAddresses:[],signedTx:"",otherParams:f,walletId:this.walletId}})}signTx(t,e){return w(this,null,function*(){const r=k(this.currencyInfo.pluginId)(e),{publicAddress:n}=(0,I.Xp)(t);if(n==null)throw new Error("Missing publicAddress from makeSpend");const s=this.allTokens.find(p=>p.currencyCode===t.currencyCode);let l;if(s==null){const p=(0,i.abs)((0,i.add)(t.nativeAmount,t.networkFee));yield this.checkRecipientMinimumBalance(this.getRecipientBalance,p,n),l=yield this.api.tx.balances.transferKeepAlive(n,p)}else if(s.contractAddress!=null){const p=(0,i.abs)(t.nativeAmount);l=yield this.api.tx.assets.transfer(parseInt(s.contractAddress),n,p)}else throw new Error("Unrecognized asset");const h=this.api.createType("SignerPayload",{method:l,nonce:this.nonce,genesisHash:this.api.genesisHash,blockHash:this.api.genesisHash,runtimeVersion:this.api.runtimeVersion,version:this.api.extrinsicVersion}),o=this.api.createType("ExtrinsicPayload",h.toPayload(),{version:this.api.extrinsicVersion});if(this.keypair==null)if(this.keypair=new S.Y({ss58Format:0}),r.mnemonic!=null)this.keypair.addFromUri(r.mnemonic);else{const p=y.YU.parse(r.privateKey);this.keypair.addFromSeed(p)}const f=o.sign(this.keypair.getPair(this.walletInfo.keys.publicKey));return l.addSignature(this.walletInfo.keys.publicKey,f.signature,h.toPayload()),t.signedTx=l.toHex(),t})}broadcastTx(t){return w(this,null,function*(){try{const e=yield this.api.rpc.author.submitExtrinsic(t.signedTx);t.txid=e.toHex(),t.date=Date.now()/1e3,this.warn(`SUCCESS broadcastTx
|
|
2
|
-
${(0,I.oX)(t)}`)}catch(e){throw this.warn("FAILURE broadcastTx failed: ",e),e}return t})}}function it(u,t,e,r){return w(this,null,function*(){const n=m(e),s=new N(u,t,n,r);return yield s.loadEngine(),s})}var b=(u,t,e)=>new Promise((r,n)=>{var s=o=>{try{h(e.next(o))}catch(f){n(f)}},l=o=>{try{h(e.throw(o))}catch(f){n(f)}},h=o=>o.done?r(o.value):Promise.resolve(o.value).then(s,l);h((e=e.apply(u,t)).next())});const{ed25519PairFromSeed:at,isAddress:q,mnemonicToMiniSecret:lt}=X;class tt{constructor(t){const{builtinTokens:e,currencyInfo:r,io:n,networkInfo:s}=t;this.builtinTokens=e,this.currencyInfo=r,this.io=n,this.networkInfo=s,this.polkadotApiSubscribers=new Set}getDisplayPrivateKey(t){return b(this,null,function*(){var e;const{pluginId:r}=this.currencyInfo,n=k(r)(t.keys);return(e=n.mnemonic)!=null?e:n.privateKey})}getDisplayPublicKey(t){return b(this,null,function*(){const{keys:e}=m(t);return e.publicKey})}importPrivateKey(t){return b(this,null,function*(){const{pluginId:e}=this.currencyInfo;if((0,L.validateMnemonic)(t)){const r=lt(t),{secretKey:n}=at(r);return{[`${e}Mnemonic`]:t,[`${e}Key`]:U.Buffer.from(n).toString("hex")}}else{if((0,I.vq)(t))return{[`${e}Key`]:t};throw new Error("InvalidPrivateKey")}})}createPrivateKey(t){return b(this,null,function*(){if(t!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const e=U.Buffer.from(this.io.random(32)),r=(0,L.entropyToMnemonic)(e);return yield this.importPrivateKey(r)})}derivePublicKey(t){return b(this,null,function*(){const{pluginId:e}=this.currencyInfo;return{publicKey:new S.Y({ss58Format:0}).addFromUri(t.keys[`${e}Mnemonic`]).address}})}parseUri(t,e,r){return b(this,null,function*(){var n,s;const{pluginId:l}=this.currencyInfo,h={[l]:!0},{parsedUri:o,edgeParsedUri:f}=(0,F.k)(this.currencyInfo,t,h,e!=null?e:this.currencyInfo.currencyCode,r),p=(n=f.publicAddress)!=null?n:"";if(!q(p))throw new Error("InvalidPublicAddressError");return f.uniqueIdentifier=(s=o.query.memo)!=null?s:void 0,f})}encodeUri(t){return b(this,arguments,function*(e,r=[]){const{pluginId:n}=this.currencyInfo,{nativeAmount:s,currencyCode:l,publicAddress:h}=e;if(!q(h))throw new Error("InvalidPublicAddressError");let o;if(typeof s=="string"){const p=(0,I.Qs)(l!=null?l:this.currencyInfo.currencyCode,this.currencyInfo,r);if(p==null)throw new Error("InternalErrorInvalidCurrencyCode");o=(0,i.div)(s,p.multiplier,10)}return(0,F.Q)(e,n,o)})}connectApi(t){return b(this,null,function*(){return this.polkadotApi==null&&(this.polkadotApi=yield j.G.create({initWasm:!1,provider:new W.U(this.networkInfo.rpcNodes[0])})),this.polkadotApiSubscribers.add(t),this.polkadotApi})}disconnectApi(t){return b(this,null,function*(){this.polkadotApiSubscribers.delete(t),this.polkadotApiSubscribers.size===0&&(yield this.polkadotApi.disconnect(),this.polkadotApi=void 0)})}getTokenId(t){return b(this,null,function*(){(0,T.Rp)(t);const e=(0,T.Oj)(t.networkLocation);if(e==null)throw new Error("ErrorInvalidContractAddress");return e.contractAddress})}}function ct(u){return b(this,null,function*(){return new tt(u)})}}}]);
|
|
1
|
+
(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[3591],{79014:function(et,M,d){"use strict";d.d(M,{Q:function(){return _},k:function(){return V}});var S=d(77591),j=d.n(S),W=d(24350),X=d(84564),i=d.n(X),L=d(76714),U=Object.defineProperty,T=Object.getOwnPropertySymbols,F=Object.prototype.hasOwnProperty,I=Object.prototype.propertyIsEnumerable,a=(c,g,m)=>g in c?U(c,g,{enumerable:!0,configurable:!0,writable:!0,value:m}):c[g]=m,Q=(c,g)=>{for(var m in g||(g={}))F.call(g,m)&&a(c,m,g[m]);if(T)for(var m of T(g))I.call(g,m)&&a(c,m,g[m]);return c};function V(c,g,m,k,P=[]){const y=Q({},i()(g,{},!0)),O=g.startsWith(`${c.pluginId}://`);if(y.protocol!=null&&(y.protocol=y.protocol.replace(":","")),y.protocol!=null&&y.protocol!==""&&!m[y.protocol])throw new Error(`Uri protocol '${y.protocol}' is not supported for ${c.pluginId}.`);if(y.host===""&&y.pathname==="")throw new Error("Path and host not found in uri.");const C={publicAddress:y.host!==""?y.host:y.pathname.split("/")[0]},H=y.query.label,x=y.query.message,R=y.query.category;(H!=null||x!=null||R!=null||O)&&(C.metadata={},C.metadata.name=H,C.metadata.notes=x,C.metadata.category=R,C.metadata.gateway=O!=null?O:!1);const B=y.query.amount;if(B!=null&&typeof B=="string"){k==null&&(k=c.currencyCode);const $=(0,L.Qs)(k!=null?k:"",c,P);if($==null)throw new Error("InternalErrorInvalidCurrencyCode");let D=(0,S.mul)(B,$.multiplier);D=(0,S.toFixed)(D,0,0),C.nativeAmount=D,C.currencyCode=k}return{edgeParsedUri:C,parsedUri:y}}function _(c,g,m){if(c.publicAddress==null)throw new Error("InvalidPublicAddressError");if(m==null&&c.label==null&&c.message==null)return c.publicAddress;{let k="";m!=null&&(k+="amount="+m+"&"),(c.label!=null||c.message!=null)&&(typeof c.label=="string"&&(k+="label="+c.label+"&"),typeof c.message=="string"&&(k+="message="+c.message+"&")),k=k.substr(0,k.length-1);const P={scheme:g,path:c.publicAddress,query:k};return(0,W.qC)(P)}}},34765:function(et,M,d){"use strict";d.r(M),d.d(M,{PolkadotTools:function(){return tt},makeCurrencyEngine:function(){return it},makeCurrencyTools:function(){return ct}});var S=d(58170),j=d(21293),W=d(18534),X=d(23670),i=d(77591),L=d(2153),U=d(48764),T=d(20918),F=d(79014),I=d(76714),a=d(82448),Q=d(62177);const V=(0,a.su)({txCount:(0,a.Vk)(a.mH,0)}),_=(0,a.su)({code:a.mH,message:a.XC,data:(0,a.Zz)((0,a.su)(a.JC))}),c=(0,a.su)({from:a.XC,to:a.XC,success:a.jK,hash:a.XC,block_num:a.mH,block_timestamp:a.mH,module:a.XC,amount:a.XC,fee:a.XC}),g=(0,a.su)({count:a.mH,transfers:(0,a.Vk)((0,a._2)(c),()=>[])}),m=Q.BQ,k=u=>{const t=(0,a.su)({[`${u}Mnemonic`]:(0,a.Zz)(a.XC),[`${u}Key`]:a.XC});return(0,a.W1)(e=>{const r=t(e);return{mnemonic:r[`${u}Mnemonic`],privateKey:r[`${u}Key`]}},e=>({[`${u}Mnemonic`]:e.mnemonic,[`${u}Key`]:e.privateKey}))};var P=d(94935),y=d(35620),O=d(84650),z=Object.defineProperty,C=Object.defineProperties,H=Object.getOwnPropertyDescriptors,x=Object.getOwnPropertySymbols,R=Object.getPrototypeOf,B=Object.prototype.hasOwnProperty,$=Object.prototype.propertyIsEnumerable,D=Reflect.get,G=(u,t,e)=>t in u?z(u,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):u[t]=e,Y=(u,t)=>{for(var e in t||(t={}))B.call(t,e)&&G(u,e,t[e]);if(x)for(var e of x(t))$.call(t,e)&&G(u,e,t[e]);return u},J=(u,t)=>C(u,H(t)),Z=(u,t,e)=>D(R(u),e,t),w=(u,t,e)=>new Promise((r,n)=>{var s=o=>{try{h(e.next(o))}catch(f){n(f)}},l=o=>{try{h(e.throw(o))}catch(f){n(f)}},h=o=>o.done?r(o.value):Promise.resolve(o.value).then(s,l);h((e=e.apply(u,t)).next())});const nt=5e3,rt=2e4,st=3e3,ot=(0,I.jT)();class N extends O.P{constructor(t,e,r,n){super(t,e,r,n),this.getRecipientBalance=s=>w(this,null,function*(){try{return(yield this.api.query.system.account(s)).data.free.toString()}catch{return this.minimumAddressBalance}}),this.fetchCors=(0,I.zR)(t.io),this.networkInfo=t.networkInfo,this.nonce=0}setOtherData(t){this.otherData=V(t)}fetchSubscan(t,e){return w(this,null,function*(){if(this.networkInfo.subscanBaseUrl==null)throw new Error("Missing subscan url");const r={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(e)},n=yield this.fetchCors(this.networkInfo.subscanBaseUrl+t,r);if(!n.ok||n.status===429)throw new Error(`Subscan ${t} failed with ${n.status}`);const s=yield n.json();return _(s)})}queryBalance(){return w(this,null,function*(){const t=yield this.api.query.system.account(this.walletInfo.keys.publicKey);this.nonce=t.nonce.toNumber(),this.updateBalance(this.currencyInfo.currencyCode,t.data.free.toString());for(const e of this.enabledTokenIds){const r=this.allTokensMap[e];if(r==null)continue;const n=(0,T.Oj)(r.networkLocation);if(n==null)continue;const s=yield this.api.query.assets.account(n.contractAddress,this.walletInfo.keys.publicKey);let l="0";s.isSome&&(l=s.unwrap().balance.toString()),this.updateBalance(r.currencyCode,l)}})}queryBlockheight(){return w(this,null,function*(){try{const e=(yield this.api.rpc.chain.getBlock()).block.header.number.toNumber();e>this.walletLocalData.blockHeight&&(this.walletLocalData.blockHeight=e,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight))}catch(t){this.warn("queryBlockheight failed with error: ",t)}})}processPolkadotTransaction(t){const{from:e,to:r,success:n,hash:s,block_num:l,block_timestamp:h,module:o,amount:f,fee:p}=t;if(!n||o!=="balances")return;const E=(0,I.aL)(this.currencyInfo.currencyCode,this.currencyInfo,this.allTokensMap);if(E==null)return;const A=[];let v=(0,i.mul)(f,E.multiplier);e===this.walletInfo.keys.publicKey?v=`-${(0,i.add)(v,p)}`:A.push(r);const K={txid:s,date:h,currencyCode:this.currencyInfo.currencyCode,blockHeight:l,nativeAmount:v,isSend:v.startsWith("-"),networkFee:p,ourReceiveAddresses:A,signedTx:"",walletId:this.walletId};this.addTransaction(this.currencyInfo.currencyCode,K)}queryTransactions(){return w(this,null,function*(){if(this.networkInfo.subscanBaseUrl==null){for(const t of this.enabledTokens)this.tokenCheckTransactionsStatus[t]=1;this.updateOnAddressesChecked();return}return yield ot(()=>w(this,null,function*(){return yield this.queryTransactionsInner()}))})}queryTransactionsInner(){return w(this,null,function*(){let t=Math.floor(this.otherData.txCount/this.networkInfo.subscanQueryLimit);for(;;){const e={row:this.networkInfo.subscanQueryLimit,page:t,address:this.walletInfo.keys.publicKey};let r=0,n=[];try{const s=yield this.fetchSubscan("/scan/transfers",e),l=g(s.data);r=l.count,n=l.transfers}catch(s){if(s instanceof Error&&s.message.includes("Subscan /scan/transfers failed with 429")){this.log(s.message);continue}else throw s}if(r===this.otherData.txCount||(n.forEach(s=>{try{this.processPolkadotTransaction(c(s))}catch{const h=s!=null&&typeof s.hash=="string"?s.hash:"";this.warn(`Ignoring invalid transfer ${h}`)}}),this.otherData.txCount=t*this.networkInfo.subscanQueryLimit+n.length,this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=Math.min(1,r===0?1:this.otherData.txCount/r),this.updateOnAddressesChecked(),r===this.otherData.txCount))break;t++}this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=1,this.updateOnAddressesChecked(),this.transactionsChangedArray.length>0&&(this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[])})}startEngine(){return w(this,null,function*(){this.engineOn=!0,yield this.tools.connectApi(this.walletId),this.api=this.tools.polkadotApi,this.minimumAddressBalance=this.api.consts.balances.existentialDeposit.toString(),this.addToLoop("queryBlockheight",rt).catch(()=>{}),this.addToLoop("queryBalance",nt).catch(()=>{}),this.addToLoop("queryTransactions",st).catch(()=>{}),yield Z(N.prototype,this,"startEngine").call(this)})}killEngine(){return w(this,null,function*(){yield Z(N.prototype,this,"killEngine").call(this),yield this.tools.disconnectApi(this.walletId)})}resyncBlockchain(){return w(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getMaxSpendable(t){return w(this,null,function*(){if(t.spendTargets.length===0||t.spendTargets[0].publicAddress==null)throw new Error("Missing public address");const e=this.getBalance({currencyCode:t.currencyCode});if(t.currencyCode!==this.currencyInfo.currencyCode){const f=[{publicAddress:t.spendTargets[0].publicAddress,nativeAmount:e}],p=J(Y({},t),{spendTargets:f});return yield this.makeSpend(p),e}const r=(0,i.sub)(e,this.api.consts.balances.existentialDeposit.toString()),n=[{publicAddress:t.spendTargets[0].publicAddress,nativeAmount:"0"}],s=J(Y({},t),{spendTargets:n}),h=(yield this.makeSpend(s)).networkFee,o=(f,p)=>{const E=(0,i.sub)(p,f);if((0,i.lte)(E,"1"))return f;const A=(0,i.add)(f,(0,i.div)(E,"2")),v=(0,I.X0)(A).replace("0x",""),K=v.length%2===1?`0${v}`:v,ut=(0,i.mul)((0,i.div)(K.length.toString(),"2"),this.networkInfo.lengthFeePerByte),dt=(0,i.add)((0,i.add)(ut,h),A);return(0,i.gt)(dt,r)?o(f,A):o(A,p)};return o("0",(0,i.add)(r,"1"))})}makeSpend(t){return w(this,null,function*(){const{edgeSpendInfo:e,currencyCode:r}=this.makeSpendCheck(t);if(e.spendTargets.length!==1)throw new Error("Error: only one output allowed");const{nativeAmount:n,publicAddress:s}=e.spendTargets[0];if(s==null)throw new Error("makeSpend Missing publicAddress");if(n==null)throw new P.$D;const l=this.getBalance({currencyCode:r});let h,o;if(e.tokenId==null){const E=(0,i.sub)(l,this.api.consts.balances.existentialDeposit.toString());if((0,i.gt)(n,E))throw new P.C_;const v=yield(yield this.api.tx.balances.transferKeepAlive(s,n)).paymentInfo(this.walletInfo.keys.publicKey);if(o=(0,i.sub)(v.partialFee.toString(),(0,i.mul)(this.networkInfo.lengthFeePerByte,this.networkInfo.partialFeeOffsetMultiplier)),h=(0,i.add)(n,o),(0,i.gt)(h,E))throw new P.C_}else{if((0,i.gt)(n,l))throw new P.C_;h=n;const A=yield(yield this.api.tx.assets.transfer(parseInt(e.tokenId),s,n)).paymentInfo(this.walletInfo.keys.publicKey);o=(0,i.sub)(A.partialFee.toString(),(0,i.mul)(this.networkInfo.lengthFeePerByte,this.networkInfo.partialFeeOffsetMultiplier));const v=this.getBalance({currencyCode:this.currencyInfo.currencyCode}),K=(0,i.sub)(v,this.api.consts.balances.existentialDeposit.toString());if((0,i.gt)(o,K))throw new P.C_({currencyCode:this.currencyInfo.currencyCode,networkFee:o})}const f={publicAddress:s};return{txid:"",date:0,currencyCode:r,blockHeight:0,nativeAmount:(0,i.mul)(h,"-1"),isSend:!0,networkFee:o,ourReceiveAddresses:[],signedTx:"",otherParams:f,walletId:this.walletId}})}signTx(t,e){return w(this,null,function*(){const r=k(this.currencyInfo.pluginId)(e),{publicAddress:n}=(0,I.Xp)(t);if(n==null)throw new Error("Missing publicAddress from makeSpend");const s=this.allTokens.find(p=>p.currencyCode===t.currencyCode);let l;if(s==null){const p=(0,i.abs)((0,i.add)(t.nativeAmount,t.networkFee));yield this.checkRecipientMinimumBalance(this.getRecipientBalance,p,n),l=yield this.api.tx.balances.transferKeepAlive(n,p)}else if(s.contractAddress!=null){const p=(0,i.abs)(t.nativeAmount);l=yield this.api.tx.assets.transfer(parseInt(s.contractAddress),n,p)}else throw new Error("Unrecognized asset");const h=this.api.createType("SignerPayload",{method:l,nonce:this.nonce,genesisHash:this.api.genesisHash,blockHash:this.api.genesisHash,runtimeVersion:this.api.runtimeVersion,version:this.api.extrinsicVersion}),o=this.api.createType("ExtrinsicPayload",h.toPayload(),{version:this.api.extrinsicVersion});if(this.keypair==null)if(this.keypair=new S.Y({ss58Format:0}),r.mnemonic!=null)this.keypair.addFromUri(r.mnemonic);else{const p=y.YU.parse(r.privateKey);this.keypair.addFromSeed(p)}const f=o.sign(this.keypair.getPair(this.walletInfo.keys.publicKey));return l.addSignature(this.walletInfo.keys.publicKey,f.signature,h.toPayload()),t.signedTx=l.toHex(),t})}broadcastTx(t){return w(this,null,function*(){try{const e=yield this.api.rpc.author.submitExtrinsic(t.signedTx);t.txid=e.toHex(),t.date=Date.now()/1e3,this.warn(`SUCCESS broadcastTx
|
|
2
|
+
${(0,I.oX)(t)}`)}catch(e){throw this.warn("FAILURE broadcastTx failed: ",e),e}return t})}}function it(u,t,e,r){return w(this,null,function*(){const n=m(e),s=new N(u,t,n,r);return yield s.loadEngine(),s})}var b=(u,t,e)=>new Promise((r,n)=>{var s=o=>{try{h(e.next(o))}catch(f){n(f)}},l=o=>{try{h(e.throw(o))}catch(f){n(f)}},h=o=>o.done?r(o.value):Promise.resolve(o.value).then(s,l);h((e=e.apply(u,t)).next())});const{ed25519PairFromSeed:at,isAddress:q,mnemonicToMiniSecret:lt}=X;class tt{constructor(t){const{builtinTokens:e,currencyInfo:r,io:n,networkInfo:s}=t;this.builtinTokens=e,this.currencyInfo=r,this.io=n,this.networkInfo=s,this.polkadotApiSubscribers=new Set}getDisplayPrivateKey(t){return b(this,null,function*(){var e;const{pluginId:r}=this.currencyInfo,n=k(r)(t.keys);return(e=n.mnemonic)!=null?e:n.privateKey})}getDisplayPublicKey(t){return b(this,null,function*(){const{keys:e}=m(t);return e.publicKey})}importPrivateKey(t){return b(this,null,function*(){const{pluginId:e}=this.currencyInfo;if((0,L.validateMnemonic)(t)){const r=lt(t),{secretKey:n}=at(r);return{[`${e}Mnemonic`]:t,[`${e}Key`]:U.Buffer.from(n).toString("hex")}}else{if((0,I.vq)(t))return{[`${e}Key`]:t};throw new Error("InvalidPrivateKey")}})}createPrivateKey(t){return b(this,null,function*(){if(t!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const e=U.Buffer.from(this.io.random(32)),r=(0,L.entropyToMnemonic)(e);return yield this.importPrivateKey(r)})}derivePublicKey(t){return b(this,null,function*(){const{pluginId:e}=this.currencyInfo;return{publicKey:new S.Y({ss58Format:0}).addFromUri(t.keys[`${e}Mnemonic`]).address}})}parseUri(t,e,r){return b(this,null,function*(){var n,s;const{pluginId:l}=this.currencyInfo,h={[l]:!0},{parsedUri:o,edgeParsedUri:f}=(0,F.k)(this.currencyInfo,t,h,e!=null?e:this.currencyInfo.currencyCode,r),p=(n=f.publicAddress)!=null?n:"";if(!q(p))throw new Error("InvalidPublicAddressError");return f.uniqueIdentifier=(s=o.query.memo)!=null?s:void 0,f})}encodeUri(t){return b(this,arguments,function*(e,r=[]){const{pluginId:n}=this.currencyInfo,{nativeAmount:s,currencyCode:l,publicAddress:h}=e;if(!q(h))throw new Error("InvalidPublicAddressError");let o;if(typeof s=="string"){const p=(0,I.Qs)(l!=null?l:this.currencyInfo.currencyCode,this.currencyInfo,r);if(p==null)throw new Error("InternalErrorInvalidCurrencyCode");o=(0,i.div)(s,p.multiplier,10)}return(0,F.Q)(e,n,o)})}connectApi(t){return b(this,null,function*(){return this.polkadotApi==null&&(this.polkadotApi=yield j.G.create({initWasm:!1,provider:new W.U(this.networkInfo.rpcNodes[0])})),this.polkadotApiSubscribers.add(t),this.polkadotApi})}disconnectApi(t){return b(this,null,function*(){this.polkadotApiSubscribers.delete(t),this.polkadotApiSubscribers.size===0&&(yield this.polkadotApi.disconnect(),this.polkadotApi=void 0)})}getTokenId(t){return b(this,null,function*(){(0,T.Rp)(t);const e=(0,T.Oj)(t.networkLocation);if(e==null)throw new Error("ErrorInvalidContractAddress");return e.contractAddress})}}function ct(u){return b(this,null,function*(){return new tt(u)})}},52361:function(){},94616:function(){}}]);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
|
|
1
|
+
(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[8603],{79014:function(fe,Y,p){"use strict";p.d(Y,{Q:function(){return K},k:function(){return re}});var c=p(77591),oe=p.n(c),ee=p(24350),P=p(84564),z=p.n(P),$=p(76714),J=Object.defineProperty,R=Object.getOwnPropertySymbols,I=Object.prototype.hasOwnProperty,te=Object.prototype.propertyIsEnumerable,Z=(u,T,E)=>T in u?J(u,T,{enumerable:!0,configurable:!0,writable:!0,value:E}):u[T]=E,ne=(u,T)=>{for(var E in T||(T={}))I.call(T,E)&&Z(u,E,T[E]);if(R)for(var E of R(T))te.call(T,E)&&Z(u,E,T[E]);return u};function re(u,T,E,v,G=[]){const g=ne({},z()(T,{},!0)),M=T.startsWith(`${u.pluginId}://`);if(g.protocol!=null&&(g.protocol=g.protocol.replace(":","")),g.protocol!=null&&g.protocol!==""&&!E[g.protocol])throw new Error(`Uri protocol '${g.protocol}' is not supported for ${u.pluginId}.`);if(g.host===""&&g.pathname==="")throw new Error("Path and host not found in uri.");const N={publicAddress:g.host!==""?g.host:g.pathname.split("/")[0]},H=g.query.label,Q=g.query.message,W=g.query.category;(H!=null||Q!=null||W!=null||M)&&(N.metadata={},N.metadata.name=H,N.metadata.notes=Q,N.metadata.category=W,N.metadata.gateway=M!=null?M:!1);const F=g.query.amount;if(F!=null&&typeof F=="string"){v==null&&(v=u.currencyCode);const V=(0,$.Qs)(v!=null?v:"",u,G);if(V==null)throw new Error("InternalErrorInvalidCurrencyCode");let q=(0,c.mul)(F,V.multiplier);q=(0,c.toFixed)(q,0,0),N.nativeAmount=q,N.currencyCode=v}return{edgeParsedUri:N,parsedUri:g}}function K(u,T,E){if(u.publicAddress==null)throw new Error("InvalidPublicAddressError");if(E==null&&u.label==null&&u.message==null)return u.publicAddress;{let v="";E!=null&&(v+="amount="+E+"&"),(u.label!=null||u.message!=null)&&(typeof u.label=="string"&&(v+="label="+u.label+"&"),typeof u.message=="string"&&(v+="message="+u.message+"&")),v=v.substr(0,v.length-1);const G={scheme:T,path:u.publicAddress,query:v};return(0,ee.qC)(G)}}},82017:function(fe,Y,p){"use strict";p.r(Y),p.d(Y,{RippleTools:function(){return pe},makeCurrencyEngine:function(){return Re},makeCurrencyTools:function(){return be}});var c=p(77591),oe=p(84564),ee=p.n(oe),P=p(48726),z=p(31528),$=p(20918),J=p(79014),R=p(76714),I=p(82448),te=p(62177);const Z=(0,I.Vk)((0,I.su)({activateTokenId:I.XC})),ne=(0,I.su)({recommendedFee:(0,I.Vk)(I.XC,"0")}),re=(0,I.su)({date:I.mH,hash:I.XC,Fee:(0,I.Zz)(I.XC),ledger_index:I.mH}),K=(0,I.su)({currency:I.XC,issuer:I.XC}),u=te.BQ,T=(0,I.su)({rippleKey:I.XC});var E=p(48764).Buffer;const v=({issuer:d,currency:e})=>{if(!(0,P.isValidAddress)(d))throw new Error("InvalidTokenIssuerError");return`${e}-${d}`},G=40,g=d=>d.length>3?E.from(d,"ascii").toString("hex").toUpperCase().padEnd(G,"0"):d;var M=p(94935),se=p(96510),N=p(84650);const H=[400,403,404],Q={XRP_ERROR:"XrpError"},W={UNIQUE_IDENTIFIER_EXCEEDS_LENGTH:"UNIQUE_IDENTIFIER_EXCEEDS_LENGTH",UNIQUE_IDENTIFIER_EXCEEDS_LIMIT:"UNIQUE_IDENTIFIER_EXCEEDS_LIMIT",UNIQUE_IDENTIFIER_FORMAT:"UNIQUE_IDENTIFIER_FORMAT"};class F extends Error{constructor(e,t,n,o,r){super(e),Error.captureStackTrace&&Error.captureStackTrace(this,F),this.name=t!=null?t:"PluginError",n&&(this.errorCode=n),o&&(this.labelCode=o),r&&(this.json=r)}}var V=p(49349),q=Object.defineProperty,me=Object.defineProperties,ye=Object.getOwnPropertyDescriptors,ie=Object.getOwnPropertySymbols,ge=Object.getPrototypeOf,Ie=Object.prototype.hasOwnProperty,Te=Object.prototype.propertyIsEnumerable,Ee=Reflect.get,ae=(d,e,t)=>e in d?q(d,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):d[e]=t,ve=(d,e)=>{for(var t in e||(e={}))Ie.call(e,t)&&ae(d,t,e[t]);if(ie)for(var t of ie(e))Te.call(e,t)&&ae(d,t,e[t]);return d},we=(d,e)=>me(d,ye(e)),le=(d,e,t)=>Ee(ge(d),t,e),A=(d,e,t)=>new Promise((n,o)=>{var r=s=>{try{a(t.next(s))}catch(l){o(l)}},i=s=>{try{a(t.throw(s))}catch(l){o(l)}},a=s=>s.done?n(s.value):Promise.resolve(s.value).then(r,i);a((t=t.apply(d,e)).next())});const ke=1e4,Ae=15e3,De=3e3,ce=30*60,Ce=1e3*60*1,Pe=60*5,Le=20,ue="12",de=131072,_e="1000000",he="12";class j extends N.P{constructor(e,t,n,o){super(e,t,n,o),this.getRecipientBalance=i=>A(this,null,function*(){var a;try{return(yield this.tools.rippleApi.request({command:"account_info",account:i})).result.account_data.Balance}catch(s){return((a=s.data)==null?void 0:a.error)==="actNotFound"?"0":this.minimumAddressBalance}}),this.engineGetActivationAssets=i=>A(this,null,function*(){return{assetOptions:[{paymentWalletId:this.walletId,currencyPluginId:this.currencyInfo.pluginId}]}}),this.engineActivateWallet=i=>A(this,[i],function*({activateTokenIds:a,paymentTokenId:s,paymentWallet:l}){if(a==null)throw new Error(`Must specify activateTokenIds for ${this.currencyInfo.currencyCode}`);if(s!=null)throw new Error(`Must activate with ${this.currencyInfo.currencyCode}`);if((l==null?void 0:l.id)!==this.walletId)throw new Error("Must pay with same wallet you are activating token with");for(const f of a)if(this.allTokensMap[f]==null)throw new Error(`Invalid tokenId to activate ${f}`);return{paymentWalletId:this.walletId,fromNativeAmount:"0",networkFee:{nativeAmount:(0,c.mul)(he,a.length.toString()),currencyPluginId:this.currencyInfo.pluginId},approve:(...f)=>A(this,[...f],function*(m={}){const{metadata:h}=m,y=[];for(const w of a){const _=yield l.makeSpend({spendTargets:[],metadata:h,otherParams:{activateTokenId:w}}),C=yield l.signTx(_),S=yield l.broadcastTx(C);this.warn(`SUCCESS activateWallet.approve()
|
|
2
2
|
${(0,R.oX)(S)}`),y.push(S),yield this.saveTx(S)}return{transactions:y}}),close:()=>A(this,null,function*(){})}});const{networkInfo:r}=e;this.networkInfo=r,this.nonce=0,this.minimumAddressBalance=this.networkInfo.baseReserve,this.otherMethods={makeTx:i=>A(this,null,function*(){var a,s;if(i.type==="MakeTxDexSwap"){const{expiration:l,metadata:D,fromNativeAmount:f,fromTokenId:m,toNativeAmount:h,toTokenId:y}=i,w=this.nativeToXrpAmount(f,m),_=this.nativeToXrpAmount(h,y),C=(0,P.unixTimeToRippleTime)((l!=null?l:Pe)*1e3),S={Account:this.walletLocalData.publicKey,Expiration:C,TransactionType:"OfferCreate",TakerGets:w,TakerPays:_},B=yield this.tools.rippleApi.autofill(S),k=((a=B.LastLedgerSequence)!=null?a:this.walletLocalData.blockHeight)+Ce/V.u7;B.LastLedgerSequence=Math.floor(k);const L=(s=B.Fee)!=null?s:"0",{currencyCode:O}=m==null?this.currencyInfo:this.allTokensMap[m];return{txid:"",date:Date.now()/1e3,currencyCode:O,blockHeight:0,metadata:D,nativeAmount:`-${(0,c.add)(f,L)}`,isSend:!0,networkFee:L,ourReceiveAddresses:[],signedTx:"",otherParams:{xrpTransaction:B},walletId:this.walletId}}throw new Error(`Invalid type: ${i.type}`)})}}nativeToXrpAmount(e,t){if(t==null)return e;{const{networkLocation:n,denominations:o}=this.allTokensMap[t],{currency:r,issuer:i}=K(n);return{value:(0,c.div)(e,o[0].multiplier,V.w7),currency:g(r),issuer:i}}}setOtherData(e){this.otherData=ne(e)}getTotalReserve(){const e=this.enabledTokens.length-1-this.walletLocalData.unactivatedTokenIds.length,t=(0,c.mul)(this.networkInfo.baseReservePerToken,e.toString());return(0,c.add)(this.networkInfo.baseReserve,t)}checkServerInfoInnerLoop(){return A(this,null,function*(){var e;try{const t=yield this.tools.rippleApi.request({command:"fee"});this.otherData.recommendedFee=t.result.drops.open_ledger_fee,this.walletLocalDataDirty=!0}catch(t){this.error(`Error fetching recommended fee: ${(0,R.HY)(t)}. Using default fee.`),this.otherData.recommendedFee!==this.networkInfo.defaultFee&&(this.otherData.recommendedFee=this.networkInfo.defaultFee,this.walletLocalDataDirty=!0)}try{const n=(e=(yield this.tools.rippleApi.request({command:"server_info"})).result.info.validated_ledger)==null?void 0:e.seq;if(n==null)throw new Error("Received response without ledger info");this.log(`Got block height ${n}`),this.walletLocalData.blockHeight!==n&&(this.checkDroppedTransactionsThrottled(),this.walletLocalData.blockHeight=n,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight))}catch(t){this.error("Error fetching height: ",t)}})}processRippleTransaction(e){var t,n,o;const{log:r}=this,{publicKey:i}=this.walletLocalData,{meta:a,tx:s}=e;if(s==null){r("processRippleTransaction: no tx");return}if(typeof a!="object"){r(`processRippleTransaction: hash:${(t=s.hash)==null?void 0:t.toString()} no meta`);return}let l;try{l=re(s)}catch(y){r(String(y));return}const D=(0,P.getBalanceChanges)(a),{date:f,hash:m,Fee:h}=l;for(const y of D){const{account:w}=y;if(w===i)for(const _ of y.balances){const{currency:C,issuer:S,value:B}=_;if(C===this.currencyInfo.currencyCode){if(S!=null){r(`Transaction has parent code ${C} with issuer ${S}`);return}const k=this.currencyInfo.denominations.find(X=>X.name===C);if(k==null){r(`Unknown denom ${C}`);continue}const L=(0,c.mul)(B,k.multiplier);let O=!1,x="0";const U=[];(0,c.lt)(L,"0")?(O=!0,x=h!=null?h:"0"):U.push(i),this.addTransaction(C,{txid:m.toLowerCase(),date:(0,P.rippleTimeToUnixTime)(f)/1e3,currencyCode:C,blockHeight:(n=s.ledger_index)!=null?n:-1,nativeAmount:L,isSend:O,networkFee:x,ourReceiveAddresses:U,signedTx:"",otherParams:{},walletId:this.walletId})}else{if(S==null){r(`Transaction has token code ${C} with no issuer`);return}const k=v({currency:C,issuer:S}),L=this.allTokensMap[k];if(L==null)return;const{currencyCode:O}=L,x=(0,c.mul)(B,L.denominations[0].multiplier);let U=!1;const X=[];(0,c.lt)(x,"0")?U=!0:X.push(i),this.addTransaction(O,{txid:m.toLowerCase(),date:(0,P.rippleTimeToUnixTime)(f)/1e3,currencyCode:O,blockHeight:(o=s.ledger_index)!=null?o:-1,nativeAmount:x,isSend:U,networkFee:"0",ourReceiveAddresses:X,signedTx:"",otherParams:{},walletId:this.walletId})}}}}checkTransactionsInnerLoop(){return A(this,null,function*(){const e=this.walletLocalData.blockHeight,t=this.walletLocalData.publicKey;let n=-1;this.walletLocalData.lastAddressQueryHeight>ce&&(n=this.walletLocalData.lastAddressQueryHeight-ce);try{const o=yield this.tools.rippleApi.request({command:"account_tx",account:t,forward:!0,ledger_index_min:n}),{transactions:r}=o.result;this.log(`Fetched transactions count: ${r.length} startBlock:${n}`);for(const i of r)i.tx!=null&&this.processRippleTransaction(i);this.transactionsChangedArray.length>0&&(this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[]),this.walletLocalData.lastAddressQueryHeight=e,this.tokenCheckTransactionsStatus.XRP=1,this.enabledTokens.forEach(i=>{this.tokenCheckTransactionsStatus[i]=1}),this.updateOnAddressesChecked()}catch(o){this.error("Error fetching transactions: ",o)}})}checkAccountInnerLoop(){return A(this,null,function*(){var e,t;const n=this.walletLocalData.publicKey,o=[];try{const r=yield this.tools.rippleApi.request({command:"account_info",account:n,ledger_index:"current"}),{Balance:i,Sequence:a}=r.result.account_data;if(this.updateBalance(this.currencyInfo.currencyCode,i),this.nonce=a,(yield this.tools.rippleApi.getBalances(n)).forEach(({currency:l,issuer:D,value:f})=>{if(D==null)return;const m=v({currency:l,issuer:D}),h=this.allTokensMap[m];if(h!=null){const y=h.denominations[0].multiplier;if(y==null)return;const w=(0,c.toFixed)((0,c.mul)(f,y),0,0);this.updateBalance(h.currencyCode,w)}}),this.enabledTokens.forEach(l=>{this.tokenCheckBalanceStatus[l]=1}),this.updateOnAddressesChecked(),this.enabledTokens.length>1){const l=yield this.tools.rippleApi.request({command:"account_lines",account:n});this.enabledTokens.forEach(D=>{if(l.result.lines.find(m=>{const{account:h,currency:y}=m,w=v({currency:y,issuer:h}),_=this.allTokensMap[w];return _!=null&&D===_.currencyCode})==null){const m=(0,$.dK)(D,this.allTokensMap);m!=null&&o.push(m)}})}}catch(r){if(((e=r==null?void 0:r.data)==null?void 0:e.error)==="actNotFound"||((t=r==null?void 0:r.data)==null?void 0:t.error_code)===19)this.log("Account not found. Probably not activated w/minimum XRP"),this.updateBalance(this.currencyInfo.currencyCode,"0"),this.enabledTokens.forEach(i=>{if(i!==this.currencyInfo.currencyCode){const a=(0,$.dK)(i,this.allTokensMap);a!=null&&o.push(a),this.updateBalance(i,"0")}});else{this.error("Error fetching address info: ",r);return}}(0,R.dQ)(o,this.walletLocalData.unactivatedTokenIds)||(this.walletLocalData.unactivatedTokenIds=o,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onUnactivatedTokenIdsChanged(this.walletLocalData.unactivatedTokenIds))})}startEngine(){return A(this,null,function*(){this.engineOn=!0;try{yield this.tools.connectApi(this.walletId)}catch(e){this.error("Error connecting to server ",e),setTimeout(()=>{this.engineOn&&this.startEngine().catch(t=>console.log(t.message))},1e4);return}this.addToLoop("checkServerInfoInnerLoop",Ae).catch(e=>console.log(e.message)),this.addToLoop("checkAccountInnerLoop",ke).catch(e=>console.log(e.message)),this.addToLoop("checkTransactionsInnerLoop",De).catch(e=>console.log(e.message)),yield le(j.prototype,this,"startEngine").call(this)})}killEngine(){return A(this,null,function*(){yield le(j.prototype,this,"killEngine").call(this),yield this.tools.disconnectApi(this.walletId)})}resyncBlockchain(){return A(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getMaxSpendable(e){return A(this,null,function*(){const{currencyCode:t}=e;let n=this.getBalance({currencyCode:t});const o=this.getTotalReserve();if(t===this.currencyInfo.currencyCode&&(n=(0,c.sub)(n,o)),(0,c.lte)(n,"0"))throw new M.C_;return n})}makeSpend(e){return A(this,null,function*(){var t,n,o,r,i;const{edgeSpendInfo:a,currencyCode:s,nativeBalance:l}=this.makeSpendCheck(e),D=this.currencyInfo.currencyCode,f=Z(a.otherParams);if((f==null?void 0:f.activateTokenId)!=null){const k=f.activateTokenId,L=this.allTokensMap[k],{currency:O,issuer:x}=K(L.networkLocation),U=he,X=yield this.tools.rippleApi.autofill({TransactionType:"TrustSet",Account:this.walletLocalData.publicKey,Fee:U,Flags:de,LimitAmount:{currency:O,issuer:x,value:_e}});return{txid:"",date:Date.now()/1e3,currencyCode:this.currencyInfo.currencyCode,blockHeight:0,metadata:a.metadata,nativeAmount:`-${U}`,isSend:!0,networkFee:U,ourReceiveAddresses:[],signedTx:"",otherParams:{xrpTransaction:X},walletId:this.walletId}}if(a.spendTargets.length!==1)throw new Error("Error: only one output allowed");const{publicAddress:m}=a.spendTargets[0];let{nativeAmount:h}=a.spendTargets[0];if(m==null)throw new Error("makeSpend Missing publicAddress");if(h==null)throw new M.$D;if((0,c.eq)(h,"0"))throw new M.$D;let y="0",w;if(s===D){y=this.otherData.recommendedFee;const k=this.getTotalReserve();if((0,c.gt)((0,c.add)(h,k),l))throw new M.C_}else{if(w=ue,(0,c.gt)(h,l))throw new M.C_;const k=(t=this.walletLocalData.totalBalances[D])!=null?t:"0";if((0,c.gt)(w,k))throw new M.C_({currencyCode:D,networkFee:w})}const _=(i=(r=(n=a.spendTargets[0].memo)!=null?n:a.spendTargets[0].uniqueIdentifier)!=null?r:(o=a.spendTargets[0].otherParams)==null?void 0:o.uniqueIdentifier)!=null?i:"";if(_!==""){const{memoMaxLength:k=1/0,memoMaxValue:L}=this.currencyInfo;if(Number.isNaN(parseInt(_)))throw new F("Please enter a valid Destination Tag",Q.XRP_ERROR,H[0],W.UNIQUE_IDENTIFIER_FORMAT);if(_.length>k)throw new F(`Destination Tag must be ${k} characters or less`,Q.XRP_ERROR,H[0],W.UNIQUE_IDENTIFIER_EXCEEDS_LENGTH);if(L!=null&&(0,c.gt)(_,L))throw new F("XRP Destination Tag is above its maximum limit",Q.XRP_ERROR,H[0],W.UNIQUE_IDENTIFIER_EXCEEDS_LIMIT)}let C;if(s===D)C={Amount:h,TransactionType:"Payment",Account:this.walletLocalData.publicKey,Destination:m,Fee:y},h=`-${(0,c.add)(h,y)}`;else{const k=(0,$.dK)(s,this.allTokensMap);if(k==null)throw new Error("Error: Token not supported");const L=this.allTokensMap[k],{networkLocation:O,denominations:[x]}=L,{currency:U,issuer:X}=K(O);C={TransactionType:"Payment",Account:this.walletLocalData.publicKey,Fee:w!=null?w:ue,Amount:{currency:U,issuer:X,value:(0,c.div)(h,x.multiplier,(0,c.log10)(x.multiplier))},Destination:m,Flags:de},h=`-${h}`}_!==""&&(C.DestinationTag=parseInt(_));const B={txid:"",date:0,currencyCode:s,blockHeight:0,nativeAmount:h,isSend:!0,networkFee:y,parentNetworkFee:w,ourReceiveAddresses:[],signedTx:"",otherParams:{preparedTx:C},walletId:this.walletId};return this.warn("Payment transaction prepared..."),B})}signTx(e,t){return A(this,null,function*(){const n=T(t),o=(0,R.Xp)(e);if(o.xrpTransaction!=null){const f=o.xrpTransaction,m=t.rippleKey,h=P.Wallet.fromSeed(m),{tx_blob:y,hash:w}=h.sign(f);return this.warn("Activation transaction signed..."),e.signedTx=y,e.txid=w.toLowerCase(),e.date=Date.now()/1e3,this.warn(`signTx
|
|
3
3
|
${(0,R.oX)(e)}`),e}const r=we(ve({},o.preparedTx),{Sequence:this.nonce,LastLedgerSequence:this.walletLocalData.blockHeight+Le});(0,se.validatePayment)(r);const i=r.Destination;if(i==null)throw new Error("makeSpend Missing publicAddress");if(e.currencyCode===this.currencyInfo.currencyCode){const f=(0,c.abs)((0,c.add)(e.nativeAmount,e.networkFee));yield this.checkRecipientMinimumBalance(this.getRecipientBalance,f,i)}const a=n.rippleKey,s=P.Wallet.fromSeed(a),{tx_blob:l,hash:D}=s.sign(r);return this.warn("Payment transaction signed..."),e.signedTx=l,e.txid=D.toLowerCase(),e.date=Date.now()/1e3,this.warn(`signTx
|
|
4
4
|
${(0,R.oX)(e)}`),e})}broadcastTx(e){return A(this,null,function*(){const t=yield this.tools.rippleApi.submit(e.signedTx),{engine_result_code:n,engine_result_message:o}=t.result;if(n>=-199&&n<=-100||n>=-299&&n<=-200||n>=-399&&n<=-300)throw this.warn(`FAILURE broadcastTx ${n} ${o}`),new Error(o);return this.warn(`SUCCESS broadcastTx
|
|
5
|
-
${(0,R.oX)(e)}`),e})}}function Re(d,e,t,n){return A(this,null,function*(){const o=u(t),r=new j(d,e,o,n);return yield r.loadEngine(),r})}var b=(d,e,t)=>new Promise((n,o)=>{var r=s=>{try{a(t.next(s))}catch(l){o(l)}},i=s=>{try{a(t.throw(s))}catch(l){o(l)}},a=s=>s.done?n(s.value):Promise.resolve(s.value).then(r,i);a((t=t.apply(d,e)).next())});class pe{constructor(e){const{builtinTokens:t,currencyInfo:n,io:o,networkInfo:r}=e;this.builtinTokens=t,this.currencyInfo=n,this.io=o,this.networkInfo=r,this.rippleApiSubscribers={}}getDisplayPrivateKey(e){return b(this,null,function*(){return T(e.keys).rippleKey})}getDisplayPublicKey(e){return b(this,null,function*(){const{keys:t}=u(e);return t.publicKey})}connectApi(e){return b(this,null,function*(){if(Object.keys(this.rippleApiSubscribers).length===0){const t=this.networkInfo.rippledServers.map(o=>()=>b(this,null,function*(){const r=new P.Client(o);return yield r.connect(),r})),n=yield(0,R.QJ)(t);this.rippleApi=n}this.rippleApiSubscribers[e]=!0})}disconnectApi(e){return b(this,null,function*(){delete this.rippleApiSubscribers[e],Object.keys(this.rippleApiSubscribers).length===0&&(yield this.rippleApi.disconnect())})}importPrivateKey(e){return b(this,null,function*(){e=e.replace(/\s/g,"");try{return(0,P.decodeSeed)(e),{rippleKey:e}}catch(t){throw new Error(`Invalid private key: ${(0,R.HY)(t)}`)}})}createPrivateKey(e){return b(this,null,function*(){const t=e.replace("wallet:","");if(t==="ripple"||t==="ripple-secp256k1"){const n=t==="ripple-secp256k1"?z.default.secp256k1:z.default.ed25519,o=Array.from(this.io.random(32));return{rippleKey:P.Wallet.fromEntropy(o,{algorithm:n}).seed}}else throw new Error("InvalidWalletType")})}derivePublicKey(e){return b(this,null,function*(){const t=e.type.replace("wallet:","");if(t==="ripple"||t==="ripple-secp256k1")return{publicKey:P.Wallet.fromSeed(e.keys.rippleKey).classicAddress};throw new Error("InvalidWalletType")})}parseUri(e){return b(this,null,function*(){var t;const n={ripple:!0,"xrp-ledger":!0},o="https://ripple.com//send";try{const{classicAddress:s,tag:l}=(0,P.xAddressToClassicAddress)(e);e=`ripple:${s}?to=${s}${l!==!1?`&dt=${l}`:""}`}catch{}if(e.includes(o)){const l=ee()(e,{},!0).query.to;l!=null&&(e=e.replace(o,`ripple:${l}`))}const{parsedUri:r,edgeParsedUri:i}=(0,J.k)(this.currencyInfo,e,n);if(!(0,P.isValidAddress)((t=i.publicAddress)!=null?t:""))throw new Error("InvalidPublicAddressError");return i.uniqueIdentifier=r.query.dt,i})}encodeUri(e){return b(this,arguments,function*(t,n=[]){if(!(0,P.isValidAddress)(t.publicAddress))throw new Error("InvalidPublicAddressError");let r;if(typeof t.nativeAmount=="string"){const a="XRP",s=t.nativeAmount,l=(0,R.Qs)(a,this.currencyInfo,n);if(l==null)throw new Error("InternalErrorInvalidCurrencyCode");r=(0,c.div)(s,l.multiplier,6)}return(0,J.Q)(t,"ripple",r)})}getTokenId(e){return b(this,null,function*(){(0,$.Rp)(e);const t=e==null?void 0:e.networkLocation;if(t==null)throw new Error("ErrorInvalidNetworkLocation");const n=K(t);return v(n)})}}function be(d){return b(this,null,function*(){return new pe(d)})}}}]);
|
|
5
|
+
${(0,R.oX)(e)}`),e})}}function Re(d,e,t,n){return A(this,null,function*(){const o=u(t),r=new j(d,e,o,n);return yield r.loadEngine(),r})}var b=(d,e,t)=>new Promise((n,o)=>{var r=s=>{try{a(t.next(s))}catch(l){o(l)}},i=s=>{try{a(t.throw(s))}catch(l){o(l)}},a=s=>s.done?n(s.value):Promise.resolve(s.value).then(r,i);a((t=t.apply(d,e)).next())});class pe{constructor(e){const{builtinTokens:t,currencyInfo:n,io:o,networkInfo:r}=e;this.builtinTokens=t,this.currencyInfo=n,this.io=o,this.networkInfo=r,this.rippleApiSubscribers={}}getDisplayPrivateKey(e){return b(this,null,function*(){return T(e.keys).rippleKey})}getDisplayPublicKey(e){return b(this,null,function*(){const{keys:t}=u(e);return t.publicKey})}connectApi(e){return b(this,null,function*(){if(Object.keys(this.rippleApiSubscribers).length===0){const t=this.networkInfo.rippledServers.map(o=>()=>b(this,null,function*(){const r=new P.Client(o);return yield r.connect(),r})),n=yield(0,R.QJ)(t);this.rippleApi=n}this.rippleApiSubscribers[e]=!0})}disconnectApi(e){return b(this,null,function*(){delete this.rippleApiSubscribers[e],Object.keys(this.rippleApiSubscribers).length===0&&(yield this.rippleApi.disconnect())})}importPrivateKey(e){return b(this,null,function*(){e=e.replace(/\s/g,"");try{return(0,P.decodeSeed)(e),{rippleKey:e}}catch(t){throw new Error(`Invalid private key: ${(0,R.HY)(t)}`)}})}createPrivateKey(e){return b(this,null,function*(){const t=e.replace("wallet:","");if(t==="ripple"||t==="ripple-secp256k1"){const n=t==="ripple-secp256k1"?z.default.secp256k1:z.default.ed25519,o=Array.from(this.io.random(32));return{rippleKey:P.Wallet.fromEntropy(o,{algorithm:n}).seed}}else throw new Error("InvalidWalletType")})}derivePublicKey(e){return b(this,null,function*(){const t=e.type.replace("wallet:","");if(t==="ripple"||t==="ripple-secp256k1")return{publicKey:P.Wallet.fromSeed(e.keys.rippleKey).classicAddress};throw new Error("InvalidWalletType")})}parseUri(e){return b(this,null,function*(){var t;const n={ripple:!0,"xrp-ledger":!0},o="https://ripple.com//send";try{const{classicAddress:s,tag:l}=(0,P.xAddressToClassicAddress)(e);e=`ripple:${s}?to=${s}${l!==!1?`&dt=${l}`:""}`}catch{}if(e.includes(o)){const l=ee()(e,{},!0).query.to;l!=null&&(e=e.replace(o,`ripple:${l}`))}const{parsedUri:r,edgeParsedUri:i}=(0,J.k)(this.currencyInfo,e,n);if(!(0,P.isValidAddress)((t=i.publicAddress)!=null?t:""))throw new Error("InvalidPublicAddressError");return i.uniqueIdentifier=r.query.dt,i})}encodeUri(e){return b(this,arguments,function*(t,n=[]){if(!(0,P.isValidAddress)(t.publicAddress))throw new Error("InvalidPublicAddressError");let r;if(typeof t.nativeAmount=="string"){const a="XRP",s=t.nativeAmount,l=(0,R.Qs)(a,this.currencyInfo,n);if(l==null)throw new Error("InternalErrorInvalidCurrencyCode");r=(0,c.div)(s,l.multiplier,6)}return(0,J.Q)(t,"ripple",r)})}getTokenId(e){return b(this,null,function*(){(0,$.Rp)(e);const t=e==null?void 0:e.networkLocation;if(t==null)throw new Error("ErrorInvalidNetworkLocation");const n=K(t);return v(n)})}}function be(d){return b(this,null,function*(){return new pe(d)})}},89214:function(){},52361:function(){},94616:function(){}}]);
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[
|
|
1
|
+
(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[8601],{79014:function(Y,O,u){"use strict";u.d(O,{Q:function(){return x},k:function(){return Q}});var C=u(77591),T=u.n(C),I=u(24350),S=u(84564),$=u.n(S),A=u(76714),w=Object.defineProperty,r=Object.getOwnPropertySymbols,H=Object.prototype.hasOwnProperty,W=Object.prototype.propertyIsEnumerable,B=(a,f,m)=>f in a?w(a,f,{enumerable:!0,configurable:!0,writable:!0,value:m}):a[f]=m,N=(a,f)=>{for(var m in f||(f={}))H.call(f,m)&&B(a,m,f[m]);if(r)for(var m of r(f))W.call(f,m)&&B(a,m,f[m]);return a};function Q(a,f,m,p,b=[]){const d=N({},$()(f,{},!0)),E=f.startsWith(`${a.pluginId}://`);if(d.protocol!=null&&(d.protocol=d.protocol.replace(":","")),d.protocol!=null&&d.protocol!==""&&!m[d.protocol])throw new Error(`Uri protocol '${d.protocol}' is not supported for ${a.pluginId}.`);if(d.host===""&&d.pathname==="")throw new Error("Path and host not found in uri.");const h={publicAddress:d.host!==""?d.host:d.pathname.split("/")[0]},k=d.query.label,D=d.query.message,L=d.query.category;(k!=null||D!=null||L!=null||E)&&(h.metadata={},h.metadata.name=k,h.metadata.notes=D,h.metadata.category=L,h.metadata.gateway=E!=null?E:!1);const P=d.query.amount;if(P!=null&&typeof P=="string"){p==null&&(p=a.currencyCode);const R=(0,A.Qs)(p!=null?p:"",a,b);if(R==null)throw new Error("InternalErrorInvalidCurrencyCode");let K=(0,C.mul)(P,R.multiplier);K=(0,C.toFixed)(K,0,0),h.nativeAmount=K,h.currencyCode=p}return{edgeParsedUri:h,parsedUri:d}}function x(a,f,m){if(a.publicAddress==null)throw new Error("InvalidPublicAddressError");if(m==null&&a.label==null&&a.message==null)return a.publicAddress;{let p="";m!=null&&(p+="amount="+m+"&"),(a.label!=null||a.message!=null)&&(typeof a.label=="string"&&(p+="label="+a.label+"&"),typeof a.message=="string"&&(p+="message="+a.message+"&")),p=p.substr(0,p.length-1);const b={scheme:f,path:a.publicAddress,query:p};return(0,I.qC)(b)}}},18226:function(Y,O,u){"use strict";u.r(O),u.d(O,{SolanaTools:function(){return V},makeCurrencyEngine:function(){return j},makeCurrencyTools:function(){return ne}});var C=u(75885),T=u(77591),I=u(2153),S=u(48764),$=u(62678),A=u(79014),w=u(76714),r=u(82448),H=u(62177);const W=(0,r.su)({newestTxid:(0,r.Vk)(r.XC,"")}),B=(0,r.su)({value:r.mH}),N=(0,r.su)({meta:(0,r.su)({err:(0,r.Zz)(r.JC),fee:r.mH,innerInstructions:(0,r._2)(r.JC),postBalances:(0,r._2)(r.mH),postTokenBalances:(0,r._2)(r.JC),preBalances:(0,r._2)(r.mH),preTokenBalances:(0,r._2)(r.JC)}),slot:r.mH,transaction:(0,r.su)({message:(0,r.su)({accountKeys:(0,r._2)(r.XC),recentBlockhash:r.XC}),signatures:(0,r._2)(r.XC)})}),Q=(0,r.su)({value:(0,r.su)({blockhash:r.XC,feeCalculator:(0,r.su)({lamportsPerSignature:r.mH})})}),x=H.BQ,a=y=>{const e=(0,r.su)({[`${y}Mnemonic`]:r.XC,[`${y}Key`]:r.XC});return(0,r.W1)(t=>{const n=e(t);return{mnemonic:n[`${y}Mnemonic`],privateKey:n[`${y}Key`]}},t=>({[`${y}Mnemonic`]:t.mnemonic,[`${y}Key`]:t.privateKey}))};var f=u(94935),m=u(35620),p=u(84650),b=u(48764).Buffer,d=Object.getPrototypeOf,E=Reflect.get,_=(y,e,t)=>E(d(y),t,e),h=(y,e,t)=>new Promise((n,o)=>{var s=i=>{try{l(t.next(i))}catch(g){o(g)}},c=i=>{try{l(t.throw(i))}catch(g){o(g)}},l=i=>i.done?n(i.value):Promise.resolve(i.value).then(s,c);l((t=t.apply(y,e)).next())});const{PublicKey:k,Keypair:D,SystemProgram:L,Transaction:P,TransactionInstruction:R}=C,K=5e3,G=2e4,Z=3e3;class X extends p.P{constructor(e,t,n,o){super(e,t,n,o),this.networkInfo=e.networkInfo,this.chainCode=t.currencyInfo.currencyCode,this.fetchCors=(0,w.zR)(e.io),this.feePerSignature="5000",this.recentBlockhash="",this.base58PublicKey=n.keys.publicKey,this.progressRatio=0}setOtherData(e){this.otherData=W(e)}fetchRpc(e){return h(this,arguments,function*(t,n=[]){const o={jsonrpc:"2.0",id:1,method:t,params:n},s={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(o)},c=this.networkInfo.rpcNodes.map(i=>()=>h(this,null,function*(){const g=yield this.fetchCors(i,s);if(!g.ok)throw new Error(`fetchRpc ${s.method} failed error: ${g.status}`);return yield g.json()}));return(yield(0,w.QJ)(c)).result})}queryBalance(){return h(this,null,function*(){try{const e=yield this.fetchRpc("getBalance",[this.base58PublicKey,{commitment:this.networkInfo.commitment}]),t=B(e);this.updateBalance(this.chainCode,t.value.toString())}catch(e){this.error(`Error checking ${this.chainCode} address balance`,e)}})}queryBlockheight(){return h(this,null,function*(){try{const e=(0,r.mH)(yield this.fetchRpc("getSlot"));e>this.walletLocalData.blockHeight&&(this.walletLocalData.blockHeight=e,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight))}catch(e){this.error("queryBlockheight Error ",e)}})}queryFee(){return h(this,null,function*(){try{const e=yield this.fetchRpc("getRecentBlockhash"),{blockhash:t,feeCalculator:{lamportsPerSignature:n}}=Q(e).value;this.feePerSignature=n.toString(),this.recentBlockhash=t}catch(e){this.error("queryFee Error ",e)}})}processSolanaTransaction(e,t){const n=[],o=e.transaction.message.accountKeys.findIndex(i=>i===this.base58PublicKey);if(o<0||e.meta==null)return;const s=e.meta.postBalances[o]-e.meta.preBalances[o],c=e.meta.fee;if(s>=0){if(e.meta.err!=null)return;n.push(this.base58PublicKey)}const l={txid:e.transaction.signatures[0],date:t,currencyCode:this.chainCode,blockHeight:e.slot,nativeAmount:s.toString(),isSend:s.toString().startsWith("-"),networkFee:c.toString(),ourReceiveAddresses:n,signedTx:"",walletId:this.walletId};this.addTransaction(this.chainCode,l)}queryTransactions(){return h(this,null,function*(){let e=null;const t=this.otherData.newestTxid!==""?this.otherData.newestTxid:null;let n=[];try{for(;;){const s=[this.base58PublicKey,{until:t,before:e,limit:this.networkInfo.txQueryLimit,commitment:this.networkInfo.commitment}],c=yield this.fetchRpc("getSignaturesForAddress",s);if(n=n.concat(c),c.length<this.networkInfo.txQueryLimit)break;e=c[this.networkInfo.txQueryLimit-1].signature}}catch(s){this.error("getTransactionSignatures failed with error: ",s);return}if(n.length===0){this.tokenCheckTransactionsStatus[this.chainCode]=1,this.updateOnAddressesChecked();return}let o=-1;for(let s=n.length-1;s>=0;s--)try{const c=N(yield this.fetchRpc("getTransaction",[n[s].signature,{encoding:"json",commitment:this.networkInfo.commitment}]));let l=n[s].blocktime;(l==null||isNaN(l))&&(l=(0,r.mH)(yield this.fetchRpc("getBlockTime",[c.slot]))),this.processSolanaTransaction(c,l);const i=1-s/n.length;i!==this.progressRatio&&(Math.abs(i-this.progressRatio)>.25||i===1)&&(this.progressRatio=i,this.tokenCheckTransactionsStatus[this.chainCode]=this.progressRatio,this.updateOnAddressesChecked())}catch{o=s;break}o===-1?this.otherData.newestTxid=n[0].signature:n.length>o+1&&(this.otherData.newestTxid=n[o+1].signature),this.walletLocalDataDirty=!0,this.tokenCheckTransactionsStatus[this.chainCode]=1,this.updateOnAddressesChecked(),this.transactionsChangedArray.length>0&&(this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[])})}startEngine(){return h(this,null,function*(){this.engineOn=!0,this.addToLoop("queryBlockheight",G),this.addToLoop("queryFee",G),this.addToLoop("queryBalance",K),this.addToLoop("queryTransactions",Z),_(X.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return h(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}makeSpend(e){return h(this,null,function*(){var t,n,o;const{edgeSpendInfo:s,currencyCode:c}=this.makeSpendCheck(e);if(s.spendTargets.length!==1)throw new Error("Error: only one output allowed");const{nativeAmount:l,publicAddress:i}=s.spendTargets[0];if(i==null)throw new Error("makeSpend Missing publicAddress");if(l==null)throw new f.$D;const g=this.feePerSignature,U=(t=this.walletLocalData.totalBalances[this.chainCode])!=null?t:"0";let F="0";if(F=(0,T.add)(l,g),(0,T.gt)(F,U))throw new f.C_;const z=new k(this.base58PublicKey),re={recentBlockhash:this.recentBlockhash,feePayer:z},q=new P(re).add(L.transfer({fromPubkey:z,toPubkey:new k(i),lamports:parseInt(l)})),J=(o=(n=s.spendTargets[0])==null?void 0:n.otherParams)==null?void 0:o.uniqueIdentifier;if(J!=null&&J!==""){const oe=new R({keys:[{pubkey:z,isSigner:!0,isWritable:!0}],programId:new k(this.networkInfo.memoPublicKey),data:b.from(J)});q.add(oe)}const se={unsignedSerializedSolTx:q.serialize({requireAllSignatures:!1})};return{txid:"",date:0,currencyCode:c,blockHeight:0,nativeAmount:(0,T.mul)(F,"-1"),isSend:!0,networkFee:g,ourReceiveAddresses:[],signedTx:"",otherParams:se,walletId:this.walletId}})}signTx(e,t){return h(this,null,function*(){const n=a(this.currencyInfo.pluginId)(t),{unsignedSerializedSolTx:o}=(0,w.Xp)(e);if(o==null)throw new Error("Missing unsignedSerializedSolTx");const s=D.fromSecretKey(Uint8Array.from(m.YU.parse(n.privateKey))),c=P.from(o);return c.recentBlockhash=this.recentBlockhash,c.sign({publicKey:s.publicKey,secretKey:s.secretKey}),e.signedTx=c.serialize().toString("base64"),this.warn(`signTx
|
|
2
2
|
${(0,w.oX)(e)}`),e})}broadcastTx(e){return h(this,null,function*(){if(e.signedTx==null)throw new Error("Missing signedTx");try{const t=[e.signedTx,{encoding:"base64"}],n=yield this.fetchRpc("sendTransaction",t);e.txid=n,e.date=Date.now()/1e3,this.warn(`SUCCESS broadcastTx
|
|
3
|
-
${(0,w.oX)(e)}`)}catch(t){throw this.warn("FAILURE broadcastTx failed: ",t),t}return e})}}function j(
|
|
3
|
+
${(0,w.oX)(e)}`)}catch(t){throw this.warn("FAILURE broadcastTx failed: ",t),t}return e})}}function j(y,e,t,n){return h(this,null,function*(){const o=x(t),s=new X(y,e,o,n);return yield s.loadEngine(),s})}var v=(y,e,t)=>new Promise((n,o)=>{var s=i=>{try{l(t.next(i))}catch(g){o(g)}},c=i=>{try{l(t.throw(i))}catch(g){o(g)}},l=i=>i.done?n(i.value):Promise.resolve(i.value).then(s,c);l((t=t.apply(y,e)).next())});const{Keypair:ee,PublicKey:M}=C,te=(y,e)=>v(void 0,null,function*(){const t=yield(0,I.mnemonicToSeed)(y),n=$.derivePath(e,t.toString("hex")).key;return ee.fromSeed(Uint8Array.from(S.Buffer.from(n,"hex")))});class V{constructor(e){const{builtinTokens:t,currencyInfo:n,io:o,networkInfo:s}=e;this.builtinTokens=t,this.currencyInfo=n,this.io=o,this.networkInfo=s}getDisplayPrivateKey(e){return v(this,null,function*(){const{pluginId:t}=this.currencyInfo;return a(t)(e.keys).mnemonic})}getDisplayPublicKey(e){return v(this,null,function*(){const{keys:t}=x(e);return t.publicKey})}importPrivateKey(e){return v(this,null,function*(){const{pluginId:t}=this.currencyInfo;if(!(0,I.validateMnemonic)(e))throw new Error("Invalid mnemonic");const o=yield te(e,this.networkInfo.derivationPath);return{[`${t}Mnemonic`]:e,[`${t}Key`]:S.Buffer.from(o.secretKey).toString("hex"),publicKey:o.publicKey.toBase58()}})}createPrivateKey(e){return v(this,null,function*(){if(e!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const t=S.Buffer.from(this.io.random(32)),n=(0,I.entropyToMnemonic)(t);return yield this.importPrivateKey(n)})}derivePublicKey(e){return v(this,null,function*(){const{pluginId:t}=this.currencyInfo;if(e.type!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");if(e.keys[`${t}Mnemonic`]==null)throw new Error("Missing mnemonic");return{publicKey:(yield this.importPrivateKey(e.keys[`${t}Mnemonic`])).publicKey.toString()}})}parseUri(e,t,n){return v(this,null,function*(){const{pluginId:o}=this.currencyInfo,s={[o]:!0},{parsedUri:c,edgeParsedUri:l}=(0,A.k)(this.currencyInfo,e,s,t||this.currencyInfo.currencyCode,n);let i="";if(l.publicAddress&&(i=l.publicAddress),!M.isOnCurve(new M(i).toBytes()))throw new Error("InvalidPublicAddressError");return l.uniqueIdentifier=c.query.memo,l})}encodeUri(e){return v(this,arguments,function*(t,n=[]){const{pluginId:o}=this.currencyInfo,{nativeAmount:s,currencyCode:c,publicAddress:l}=t;if(!M.isOnCurve(new M(l).toBytes()))throw new Error("InvalidPublicAddressError");let i;if(typeof s=="string"){const U=(0,w.Qs)(c!=null?c:this.currencyInfo.currencyCode,this.currencyInfo,n);if(U==null)throw new Error("InternalErrorInvalidCurrencyCode");i=(0,T.div)(s,U.multiplier,18)}return(0,A.Q)(t,o,i)})}}function ne(y){return v(this,null,function*(){return new V(y)})}},89214:function(){},52361:function(){},94616:function(){},55024:function(){}}]);
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[870],{79014:function(j,K,u){"use strict";u.d(K,{Q:function(){return _},k:function(){return R}});var y=u(77591),Q=u.n(y),g=u(24350),H=u(84564),X=u.n(H),$=u(76714),q=Object.defineProperty,d=Object.getOwnPropertySymbols,w=Object.prototype.hasOwnProperty,F=Object.prototype.propertyIsEnumerable,B=(c,p,f)=>p in c?q(c,p,{enumerable:!0,configurable:!0,writable:!0,value:f}):c[p]=f,N=(c,p)=>{for(var f in p||(p={}))w.call(p,f)&&B(c,f,p[f]);if(d)for(var f of d(p))F.call(p,f)&&B(c,f,p[f]);return c};function R(c,p,f,v,L=[]){const i=N({},X()(p,{},!0)),D=p.startsWith(`${c.pluginId}://`);if(i.protocol!=null&&(i.protocol=i.protocol.replace(":","")),i.protocol!=null&&i.protocol!==""&&!f[i.protocol])throw new Error(`Uri protocol '${i.protocol}' is not supported for ${c.pluginId}.`);if(i.host===""&&i.pathname==="")throw new Error("Path and host not found in uri.");const I={publicAddress:i.host!==""?i.host:i.pathname.split("/")[0]},U=i.query.label,S=i.query.message,C=i.query.category;(U!=null||S!=null||C!=null||D)&&(I.metadata={},I.metadata.name=U,I.metadata.notes=S,I.metadata.category=C,I.metadata.gateway=D!=null?D:!1);const O=i.query.amount;if(O!=null&&typeof O=="string"){v==null&&(v=c.currencyCode);const k=(0,$.Qs)(v!=null?v:"",c,L);if(k==null)throw new Error("InternalErrorInvalidCurrencyCode");let E=(0,y.mul)(O,k.multiplier);E=(0,y.toFixed)(E,0,0),I.nativeAmount=E,I.currencyCode=v}return{edgeParsedUri:I,parsedUri:i}}function _(c,p,f){if(c.publicAddress==null)throw new Error("InvalidPublicAddressError");if(f==null&&c.label==null&&c.message==null)return c.publicAddress;{let v="";f!=null&&(v+="amount="+f+"&"),(c.label!=null||c.message!=null)&&(typeof c.label=="string"&&(v+="label="+c.label+"&"),typeof c.message=="string"&&(v+="message="+c.message+"&")),v=v.substr(0,v.length-1);const L={scheme:p,path:c.publicAddress,query:v};return(0,g.qC)(L)}}},85309:function(j,K,u){"use strict";u.r(K),u.d(K,{StellarTools:function(){return J},makeCurrencyEngine:function(){return O},makeCurrencyTools:function(){return ee}});var y=u(77591),Q=u(13620),g=u.n(Q),H=u(24350),X=u(84564),$=u.n(X),q=u(79014),d=u(76714),w=u(82448),F=u(62177);const B=(0,w.su)({lastPagingToken:(0,w.Vk)(w.XC,"0"),accountSequence:(0,w.Vk)(w.mH,0)}),N=(0,w.su)({fee_charged:(0,w.su)({p50:w.XC,p70:w.XC,p95:w.XC})}),R=F.BQ,_=(0,w.su)({stellarKey:w.XC});var c=u(94935),p=u(84650),f=Object.getPrototypeOf,v=Reflect.get,L=(A,e,t)=>v(f(A),t,e),i=(A,e,t)=>new Promise((s,r)=>{var n=l=>{try{o(t.next(l))}catch(h){r(h)}},a=l=>{try{o(t.throw(l))}catch(h){r(h)}},o=l=>l.done?s(l.value):Promise.resolve(l.value).then(n,a);o((t=t.apply(A,e)).next())});const D=2,G=15e3,I=3e4,U=5e3,S=100;class C extends p.P{constructor(e,t,s,r){super(e,t,s,r),this.getRecipientBalance=n=>i(this,null,function*(){var a;try{const l=(yield this.multicastServers("loadAccount",n)).balances.find(m=>m.asset_type==="native");if(l==null)return"0";const h=(0,d.aL)(this.currencyInfo.currencyCode,this.currencyInfo,this.allTokensMap);if(h==null)throw new Error("Unknown denom");return(0,y.mul)(l.balance,h.multiplier)}catch(o){return((a=o.response)==null?void 0:a.title)==="Resource Missing"?"0":this.minimumAddressBalance}}),this.networkInfo=e.networkInfo,this.fetchCors=(0,d.zR)(e.io),this.activatedAccountsCache={},this.pendingTransactionsIndex=0,this.pendingTransactionsMap={},this.fees={low:S,standard:S,high:S},this.minimumAddressBalance=this.networkInfo.baseReserve}setOtherData(e){this.otherData=B(e)}multicastServers(e,...t){return i(this,null,function*(){let s={result:"",server:""},r;switch(e){case"feeStats":r=this.networkInfo.stellarServers.map(n=>()=>i(this,null,function*(){const a=yield this.fetchCors(`${n}/fee_stats`),o=N(yield a.json());return{server:n,result:o}})),s=yield(0,d.QJ)(r);break;case"loadAccount":r=this.tools.stellarApiServers.map(n=>()=>i(this,null,function*(){const a=yield n[e](...t);return{server:n.serverName,result:a}})),s=yield(0,d.QJ)(r);break;case"ledgers":r=this.tools.stellarApiServers.map(n=>()=>i(this,null,function*(){const a=yield n.ledgers().order("desc").limit(1).call(),o=a.records[0].sequence;if(this.walletLocalData.blockHeight<=o&&this.tools.highestTxHeight<=o)return{server:n.serverName,result:a};throw new Error("Height out of date")})),s=yield(0,d.QJ)(r);break;case"payments":r=this.tools.stellarApiServers.map(n=>()=>i(this,null,function*(){const a=yield n.payments().limit(D).cursor(this.otherData.lastPagingToken).forAccount(...t).call();return{server:n.serverName,result:a}})),s=yield(0,d.QJ)(r);break;case"submitTransaction":s=yield(0,d.Wp)(this.tools.stellarApiServers.map(n=>i(this,null,function*(){const a=yield n[e](...t);return{server:n.serverName,result:a}})));break}return this.log(`multicastServers ${e} ${s.server} won`),s.result})}processTransaction(e){return i(this,null,function*(){const t=[];let s="",r="",n="",a,o,l;e.type==="create_account"?(n=e.source_account,a=e.account,r=e.starting_balance,s=this.currencyInfo.currencyCode):e.type==="payment"&&(n=e.from,a=e.to,r=e.amount,e.asset_type==="native"?s=this.currencyInfo.currencyCode:s=e.asset_type);const h=Date.parse(e.created_at)/1e3,m=(0,d.aL)(s,this.currencyInfo,this.allTokensMap);if(m!=null&&m.multiplier)o=(0,y.mul)(r,m.multiplier);else throw new Error("ErrorDenomNotFound");let T;try{T=yield e.transaction(),l=T.fee_charged.toString()}catch(M){throw this.error("processTransaction rawTx Error ",M),M}a===this.walletLocalData.publicKey?(t.push(n),n===this.walletLocalData.publicKey&&(o="-"+l)):(o=(0,y.add)(o,l),o="-"+o);const P={txid:e.transaction_hash,date:h,currencyCode:s,blockHeight:T.ledger_attr>0?T.ledger_attr:0,nativeAmount:o,isSend:o.startsWith("-"),networkFee:l,parentNetworkFee:"0",ourReceiveAddresses:t,signedTx:"",otherParams:{fromAddress:n,toAddress:a},walletId:this.walletId};return P.blockHeight>this.tools.highestTxHeight&&(this.tools.highestTxHeight=P.blockHeight),this.addTransaction(s,P),e.paging_token})}checkTransactionsInnerLoop(){return i(this,null,function*(){const e=this.walletLocalData.blockHeight,t=this.walletLocalData.publicKey;let s,r;for(;;)try{if(s?s=yield s.next():s=yield this.multicastServers("payments",t),s.records.length===0)break;for(const n of s.records)r=yield this.processTransaction(n)}catch(n){n.response&&n.response.title==="Resource Missing"?(this.log("Account not found. Probably not activated w/minimum XLM"),this.tokenCheckTransactionsStatus.XLM=1,this.updateOnAddressesChecked()):this.error("checkTransactionsInnerLoop Error fetching transaction info: ",n);return}this.transactionsChangedArray.length>0&&(this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[]),r&&(this.otherData.lastPagingToken=r,this.walletLocalDataDirty=!0),this.walletLocalData.lastAddressQueryHeight=e,this.tokenCheckTransactionsStatus.XLM=1,this.updateOnAddressesChecked()})}checkUnconfirmedTransactionsFetch(){return i(this,null,function*(){})}checkAccountInnerLoop(){return i(this,null,function*(){const e=this.walletLocalData.publicKey;try{const t=yield this.multicastServers("loadAccount",e);t.sequence!==this.otherData.accountSequence&&(this.otherData.accountSequence=t.sequence);for(const s of t.balances){let r;s.asset_type==="native"?(r=this.currencyInfo.currencyCode,this.log("--Got balances--")):r=s.asset_type;const n=(0,d.aL)(r,this.currencyInfo,this.allTokensMap);if(n!=null&&n.multiplier){const a=(0,y.mul)(s.balance,n.multiplier);this.updateBalance(r,a)}}}catch(t){t.response&&t.response.title==="Resource Missing"?(this.log("Account not found. Probably not activated w/minimum XLM"),this.tokenCheckBalanceStatus.XLM=1,this.updateOnAddressesChecked()):this.error("checkAccountInnerLoop Error fetching address info: ",t)}})}checkBlockchainInnerLoop(){this.multicastServers("ledgers").then(e=>{const t=e.records[0].sequence;this.walletLocalData.blockHeight!==t&&(this.checkDroppedTransactionsThrottled(),this.walletLocalData.blockHeight=t,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight))}).catch(e=>{this.error("checkBlockchainInnerLoop Error ",e)})}queryFee(){return i(this,null,function*(){try{const e=yield this.multicastServers("feeStats"),{p50:t,p70:s,p95:r}=e.fee_charged;this.fees={low:parseInt(t),standard:parseInt(s),high:parseInt(r)}}catch(e){this.error("queryFee Error ",e)}})}clearBlockchainCache(){return i(this,null,function*(){this.activatedAccountsCache={},this.pendingTransactionsIndex=0,this.pendingTransactionsMap={},yield L(C.prototype,this,"clearBlockchainCache").call(this),this.otherData.accountSequence=0})}startEngine(){return i(this,null,function*(){this.engineOn=!0,this.addToLoop("queryFee",I).catch(()=>{}),this.addToLoop("checkBlockchainInnerLoop",I).catch(()=>{}),this.addToLoop("checkAccountInnerLoop",G).catch(()=>{}),this.addToLoop("checkTransactionsInnerLoop",U).catch(()=>{}),yield L(C.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return i(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}makeSpend(e){return i(this,null,function*(){var t,s,r;const{edgeSpendInfo:n,currencyCode:a,nativeBalance:o,denom:l}=this.makeSpendCheck(e);if(n.spendTargets.length!==1)throw new Error("Error: only one output allowed");const{publicAddress:h}=n.spendTargets[0];let{nativeAmount:m}=n.spendTargets[0];if(h==null)throw new Error("makeSpend Missing publicAddress");if(m==null)throw new c.$D;let T=!1;const P=this.activatedAccountsCache[h];if(P===void 0)try{yield this.multicastServers("loadAccount",h),this.activatedAccountsCache[h]=!0}catch{this.activatedAccountsCache[h]=!1,T=!0}else P||(T=!0);if((0,y.eq)(m,"0"))throw new c.$D;const M=(0,y.div)(m,l.multiplier,7),te=new(g()).Account(this.walletLocalData.publicKey,this.otherData.accountSequence),x=n.spendTargets[0],z=(r=(t=x.memo)!=null?t:x.uniqueIdentifier)!=null?r:(s=x.otherParams)==null?void 0:s.uniqueIdentifier,ne=n.networkFeeOption!==void 0&&n.networkFeeOption!=="custom"?this.fees[n.networkFeeOption]:S;let b=new(g()).TransactionBuilder(te,{fee:ne});if(T?b=b.addOperation(g().Operation.createAccount({destination:h,startingBalance:M})):b=b.addOperation(g().Operation.payment({destination:h,asset:g().Asset.native(),amount:M})),z!=null){const Z=g().Memo.id(z);b=b.addMemo(Z)}const V=b.build(),Y=V.fee.toString();m=(0,y.add)(Y,m);const re=(0,y.sub)(o,this.networkInfo.baseReserve);if((0,y.gt)(m,re))throw new c.C_;m=`-${m}`;const W=this.pendingTransactionsIndex,se={txid:"",date:0,currencyCode:a,blockHeight:0,nativeAmount:m,isSend:m.startsWith("-"),networkFee:Y,ourReceiveAddresses:[],signedTx:"",otherParams:{idInternal:W,fromAddress:this.walletLocalData.publicKey,toAddress:h},walletId:this.walletId};return this.pendingTransactionsMap[W]=V,this.pendingTransactionsIndex++,this.pendingTransactionsMap[this.pendingTransactionsIndex-20]&&delete this.pendingTransactionsMap[this.pendingTransactionsIndex-20],this.warn("Stellar transaction prepared"),this.warn(`idInternal: ${W}`),this.warn(`${m} ${this.walletLocalData.publicKey} -> ${h}`),se})}signTx(e,t){return i(this,null,function*(){const s=_(t),r=(0,d.Xp)(e),n=(0,y.abs)((0,y.add)(e.nativeAmount,e.networkFee));yield this.checkRecipientMinimumBalance(this.getRecipientBalance,n,r.toAddress);try{const{idInternal:a}=r,o=this.pendingTransactionsMap[a];if(!o)throw new Error("ErrorInvalidTransaction");this.warn("Signing...");const l=g().Keypair.fromSecret(s.stellarKey);yield o.sign(l)}catch(a){throw this.error(`FAILURE signTx
|
|
1
|
+
(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[4870],{79014:function(j,K,u){"use strict";u.d(K,{Q:function(){return _},k:function(){return R}});var y=u(77591),Q=u.n(y),g=u(24350),H=u(84564),X=u.n(H),$=u(76714),q=Object.defineProperty,d=Object.getOwnPropertySymbols,w=Object.prototype.hasOwnProperty,F=Object.prototype.propertyIsEnumerable,B=(c,p,f)=>p in c?q(c,p,{enumerable:!0,configurable:!0,writable:!0,value:f}):c[p]=f,N=(c,p)=>{for(var f in p||(p={}))w.call(p,f)&&B(c,f,p[f]);if(d)for(var f of d(p))F.call(p,f)&&B(c,f,p[f]);return c};function R(c,p,f,v,L=[]){const i=N({},X()(p,{},!0)),D=p.startsWith(`${c.pluginId}://`);if(i.protocol!=null&&(i.protocol=i.protocol.replace(":","")),i.protocol!=null&&i.protocol!==""&&!f[i.protocol])throw new Error(`Uri protocol '${i.protocol}' is not supported for ${c.pluginId}.`);if(i.host===""&&i.pathname==="")throw new Error("Path and host not found in uri.");const I={publicAddress:i.host!==""?i.host:i.pathname.split("/")[0]},U=i.query.label,S=i.query.message,C=i.query.category;(U!=null||S!=null||C!=null||D)&&(I.metadata={},I.metadata.name=U,I.metadata.notes=S,I.metadata.category=C,I.metadata.gateway=D!=null?D:!1);const O=i.query.amount;if(O!=null&&typeof O=="string"){v==null&&(v=c.currencyCode);const k=(0,$.Qs)(v!=null?v:"",c,L);if(k==null)throw new Error("InternalErrorInvalidCurrencyCode");let E=(0,y.mul)(O,k.multiplier);E=(0,y.toFixed)(E,0,0),I.nativeAmount=E,I.currencyCode=v}return{edgeParsedUri:I,parsedUri:i}}function _(c,p,f){if(c.publicAddress==null)throw new Error("InvalidPublicAddressError");if(f==null&&c.label==null&&c.message==null)return c.publicAddress;{let v="";f!=null&&(v+="amount="+f+"&"),(c.label!=null||c.message!=null)&&(typeof c.label=="string"&&(v+="label="+c.label+"&"),typeof c.message=="string"&&(v+="message="+c.message+"&")),v=v.substr(0,v.length-1);const L={scheme:p,path:c.publicAddress,query:v};return(0,g.qC)(L)}}},85309:function(j,K,u){"use strict";u.r(K),u.d(K,{StellarTools:function(){return J},makeCurrencyEngine:function(){return O},makeCurrencyTools:function(){return ee}});var y=u(77591),Q=u(13620),g=u.n(Q),H=u(24350),X=u(84564),$=u.n(X),q=u(79014),d=u(76714),w=u(82448),F=u(62177);const B=(0,w.su)({lastPagingToken:(0,w.Vk)(w.XC,"0"),accountSequence:(0,w.Vk)(w.mH,0)}),N=(0,w.su)({fee_charged:(0,w.su)({p50:w.XC,p70:w.XC,p95:w.XC})}),R=F.BQ,_=(0,w.su)({stellarKey:w.XC});var c=u(94935),p=u(84650),f=Object.getPrototypeOf,v=Reflect.get,L=(A,e,t)=>v(f(A),t,e),i=(A,e,t)=>new Promise((s,r)=>{var n=l=>{try{o(t.next(l))}catch(h){r(h)}},a=l=>{try{o(t.throw(l))}catch(h){r(h)}},o=l=>l.done?s(l.value):Promise.resolve(l.value).then(n,a);o((t=t.apply(A,e)).next())});const D=2,G=15e3,I=3e4,U=5e3,S=100;class C extends p.P{constructor(e,t,s,r){super(e,t,s,r),this.getRecipientBalance=n=>i(this,null,function*(){var a;try{const l=(yield this.multicastServers("loadAccount",n)).balances.find(m=>m.asset_type==="native");if(l==null)return"0";const h=(0,d.aL)(this.currencyInfo.currencyCode,this.currencyInfo,this.allTokensMap);if(h==null)throw new Error("Unknown denom");return(0,y.mul)(l.balance,h.multiplier)}catch(o){return((a=o.response)==null?void 0:a.title)==="Resource Missing"?"0":this.minimumAddressBalance}}),this.networkInfo=e.networkInfo,this.fetchCors=(0,d.zR)(e.io),this.activatedAccountsCache={},this.pendingTransactionsIndex=0,this.pendingTransactionsMap={},this.fees={low:S,standard:S,high:S},this.minimumAddressBalance=this.networkInfo.baseReserve}setOtherData(e){this.otherData=B(e)}multicastServers(e,...t){return i(this,null,function*(){let s={result:"",server:""},r;switch(e){case"feeStats":r=this.networkInfo.stellarServers.map(n=>()=>i(this,null,function*(){const a=yield this.fetchCors(`${n}/fee_stats`),o=N(yield a.json());return{server:n,result:o}})),s=yield(0,d.QJ)(r);break;case"loadAccount":r=this.tools.stellarApiServers.map(n=>()=>i(this,null,function*(){const a=yield n[e](...t);return{server:n.serverName,result:a}})),s=yield(0,d.QJ)(r);break;case"ledgers":r=this.tools.stellarApiServers.map(n=>()=>i(this,null,function*(){const a=yield n.ledgers().order("desc").limit(1).call(),o=a.records[0].sequence;if(this.walletLocalData.blockHeight<=o&&this.tools.highestTxHeight<=o)return{server:n.serverName,result:a};throw new Error("Height out of date")})),s=yield(0,d.QJ)(r);break;case"payments":r=this.tools.stellarApiServers.map(n=>()=>i(this,null,function*(){const a=yield n.payments().limit(D).cursor(this.otherData.lastPagingToken).forAccount(...t).call();return{server:n.serverName,result:a}})),s=yield(0,d.QJ)(r);break;case"submitTransaction":s=yield(0,d.Wp)(this.tools.stellarApiServers.map(n=>i(this,null,function*(){const a=yield n[e](...t);return{server:n.serverName,result:a}})));break}return this.log(`multicastServers ${e} ${s.server} won`),s.result})}processTransaction(e){return i(this,null,function*(){const t=[];let s="",r="",n="",a,o,l;e.type==="create_account"?(n=e.source_account,a=e.account,r=e.starting_balance,s=this.currencyInfo.currencyCode):e.type==="payment"&&(n=e.from,a=e.to,r=e.amount,e.asset_type==="native"?s=this.currencyInfo.currencyCode:s=e.asset_type);const h=Date.parse(e.created_at)/1e3,m=(0,d.aL)(s,this.currencyInfo,this.allTokensMap);if(m!=null&&m.multiplier)o=(0,y.mul)(r,m.multiplier);else throw new Error("ErrorDenomNotFound");let T;try{T=yield e.transaction(),l=T.fee_charged.toString()}catch(M){throw this.error("processTransaction rawTx Error ",M),M}a===this.walletLocalData.publicKey?(t.push(n),n===this.walletLocalData.publicKey&&(o="-"+l)):(o=(0,y.add)(o,l),o="-"+o);const P={txid:e.transaction_hash,date:h,currencyCode:s,blockHeight:T.ledger_attr>0?T.ledger_attr:0,nativeAmount:o,isSend:o.startsWith("-"),networkFee:l,parentNetworkFee:"0",ourReceiveAddresses:t,signedTx:"",otherParams:{fromAddress:n,toAddress:a},walletId:this.walletId};return P.blockHeight>this.tools.highestTxHeight&&(this.tools.highestTxHeight=P.blockHeight),this.addTransaction(s,P),e.paging_token})}checkTransactionsInnerLoop(){return i(this,null,function*(){const e=this.walletLocalData.blockHeight,t=this.walletLocalData.publicKey;let s,r;for(;;)try{if(s?s=yield s.next():s=yield this.multicastServers("payments",t),s.records.length===0)break;for(const n of s.records)r=yield this.processTransaction(n)}catch(n){n.response&&n.response.title==="Resource Missing"?(this.log("Account not found. Probably not activated w/minimum XLM"),this.tokenCheckTransactionsStatus.XLM=1,this.updateOnAddressesChecked()):this.error("checkTransactionsInnerLoop Error fetching transaction info: ",n);return}this.transactionsChangedArray.length>0&&(this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[]),r&&(this.otherData.lastPagingToken=r,this.walletLocalDataDirty=!0),this.walletLocalData.lastAddressQueryHeight=e,this.tokenCheckTransactionsStatus.XLM=1,this.updateOnAddressesChecked()})}checkUnconfirmedTransactionsFetch(){return i(this,null,function*(){})}checkAccountInnerLoop(){return i(this,null,function*(){const e=this.walletLocalData.publicKey;try{const t=yield this.multicastServers("loadAccount",e);t.sequence!==this.otherData.accountSequence&&(this.otherData.accountSequence=t.sequence);for(const s of t.balances){let r;s.asset_type==="native"?(r=this.currencyInfo.currencyCode,this.log("--Got balances--")):r=s.asset_type;const n=(0,d.aL)(r,this.currencyInfo,this.allTokensMap);if(n!=null&&n.multiplier){const a=(0,y.mul)(s.balance,n.multiplier);this.updateBalance(r,a)}}}catch(t){t.response&&t.response.title==="Resource Missing"?(this.log("Account not found. Probably not activated w/minimum XLM"),this.tokenCheckBalanceStatus.XLM=1,this.updateOnAddressesChecked()):this.error("checkAccountInnerLoop Error fetching address info: ",t)}})}checkBlockchainInnerLoop(){this.multicastServers("ledgers").then(e=>{const t=e.records[0].sequence;this.walletLocalData.blockHeight!==t&&(this.checkDroppedTransactionsThrottled(),this.walletLocalData.blockHeight=t,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight))}).catch(e=>{this.error("checkBlockchainInnerLoop Error ",e)})}queryFee(){return i(this,null,function*(){try{const e=yield this.multicastServers("feeStats"),{p50:t,p70:s,p95:r}=e.fee_charged;this.fees={low:parseInt(t),standard:parseInt(s),high:parseInt(r)}}catch(e){this.error("queryFee Error ",e)}})}clearBlockchainCache(){return i(this,null,function*(){this.activatedAccountsCache={},this.pendingTransactionsIndex=0,this.pendingTransactionsMap={},yield L(C.prototype,this,"clearBlockchainCache").call(this),this.otherData.accountSequence=0})}startEngine(){return i(this,null,function*(){this.engineOn=!0,this.addToLoop("queryFee",I).catch(()=>{}),this.addToLoop("checkBlockchainInnerLoop",I).catch(()=>{}),this.addToLoop("checkAccountInnerLoop",G).catch(()=>{}),this.addToLoop("checkTransactionsInnerLoop",U).catch(()=>{}),yield L(C.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return i(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}makeSpend(e){return i(this,null,function*(){var t,s,r;const{edgeSpendInfo:n,currencyCode:a,nativeBalance:o,denom:l}=this.makeSpendCheck(e);if(n.spendTargets.length!==1)throw new Error("Error: only one output allowed");const{publicAddress:h}=n.spendTargets[0];let{nativeAmount:m}=n.spendTargets[0];if(h==null)throw new Error("makeSpend Missing publicAddress");if(m==null)throw new c.$D;let T=!1;const P=this.activatedAccountsCache[h];if(P===void 0)try{yield this.multicastServers("loadAccount",h),this.activatedAccountsCache[h]=!0}catch{this.activatedAccountsCache[h]=!1,T=!0}else P||(T=!0);if((0,y.eq)(m,"0"))throw new c.$D;const M=(0,y.div)(m,l.multiplier,7),te=new(g()).Account(this.walletLocalData.publicKey,this.otherData.accountSequence),x=n.spendTargets[0],z=(r=(t=x.memo)!=null?t:x.uniqueIdentifier)!=null?r:(s=x.otherParams)==null?void 0:s.uniqueIdentifier,ne=n.networkFeeOption!==void 0&&n.networkFeeOption!=="custom"?this.fees[n.networkFeeOption]:S;let b=new(g()).TransactionBuilder(te,{fee:ne});if(T?b=b.addOperation(g().Operation.createAccount({destination:h,startingBalance:M})):b=b.addOperation(g().Operation.payment({destination:h,asset:g().Asset.native(),amount:M})),z!=null){const Z=g().Memo.id(z);b=b.addMemo(Z)}const V=b.build(),Y=V.fee.toString();m=(0,y.add)(Y,m);const re=(0,y.sub)(o,this.networkInfo.baseReserve);if((0,y.gt)(m,re))throw new c.C_;m=`-${m}`;const W=this.pendingTransactionsIndex,se={txid:"",date:0,currencyCode:a,blockHeight:0,nativeAmount:m,isSend:m.startsWith("-"),networkFee:Y,ourReceiveAddresses:[],signedTx:"",otherParams:{idInternal:W,fromAddress:this.walletLocalData.publicKey,toAddress:h},walletId:this.walletId};return this.pendingTransactionsMap[W]=V,this.pendingTransactionsIndex++,this.pendingTransactionsMap[this.pendingTransactionsIndex-20]&&delete this.pendingTransactionsMap[this.pendingTransactionsIndex-20],this.warn("Stellar transaction prepared"),this.warn(`idInternal: ${W}`),this.warn(`${m} ${this.walletLocalData.publicKey} -> ${h}`),se})}signTx(e,t){return i(this,null,function*(){const s=_(t),r=(0,d.Xp)(e),n=(0,y.abs)((0,y.add)(e.nativeAmount,e.networkFee));yield this.checkRecipientMinimumBalance(this.getRecipientBalance,n,r.toAddress);try{const{idInternal:a}=r,o=this.pendingTransactionsMap[a];if(!o)throw new Error("ErrorInvalidTransaction");this.warn("Signing...");const l=g().Keypair.fromSecret(s.stellarKey);yield o.sign(l)}catch(a){throw this.error(`FAILURE signTx
|
|
2
2
|
${JSON.stringify((0,d.oX)(e))} `,a),a}return this.warn(`signTx
|
|
3
3
|
${(0,d.oX)(e)}`),e})}broadcastTx(e){return i(this,null,function*(){const t=(0,d.Xp)(e);try{const{idInternal:s}=t,r=this.pendingTransactionsMap[s];if(!r)throw new Error("ErrorInvalidTransaction");this.warn(`Broadcasting...
|
|
4
4
|
${(0,d.oX)(e)}`);const n=yield this.multicastServers("submitTransaction",r);e.txid=n.hash,e.date=Date.now()/1e3,this.activatedAccountsCache[t.toAddress]=!0,this.otherData.accountSequence++,this.walletLocalDataDirty=!0,this.warn(`SUCCESS broadcastTx
|
|
5
5
|
${(0,d.oX)(e)}`)}catch(s){throw this.error(`FAILURE broadcastTx
|
|
6
|
-
${JSON.stringify((0,d.oX)(e))} `,s),s}return e})}}function O(A,e,t,s){return i(this,null,function*(){const r=R(t),n=new C(A,e,r,s);return yield n.loadEngine(),n})}var k=(A,e,t)=>new Promise((s,r)=>{var n=l=>{try{o(t.next(l))}catch(h){r(h)}},a=l=>{try{o(t.throw(l))}catch(h){r(h)}},o=l=>l.done?s(l.value):Promise.resolve(l.value).then(n,a);o((t=t.apply(A,e)).next())});const E="web+stellar";class J{constructor(e){this.highestTxHeight=0;const{builtinTokens:t,currencyInfo:s,io:r,networkInfo:n}=e;this.builtinTokens=t,this.currencyInfo=s,this.io=r,this.networkInfo=n,g().Network.usePublicNetwork(),this.stellarApiServers=[];for(const a of this.networkInfo.stellarServers){const o=new(g()).Server(a);o.serverName=a,this.stellarApiServers.push(o)}}getDisplayPrivateKey(e){return k(this,null,function*(){return _(e.keys).stellarKey})}getDisplayPublicKey(e){return k(this,null,function*(){const{keys:t}=R(e);return t.publicKey})}checkAddress(e){try{return g().Keypair.fromPublicKey(e),!0}catch{return!1}}createPrivateKey(e){return k(this,null,function*(){if(e!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const t=Array.from(this.io.random(32));return{stellarKey:g().Keypair.fromRawEd25519Seed(t).secret()}})}importPrivateKey(e){return k(this,null,function*(){if(e.replace(/ /g,""),g().Keypair.fromSecret(e),e.length!==56)throw new Error("Private key wrong length");return yield Promise.resolve({stellarKey:e})})}derivePublicKey(e){return k(this,null,function*(){if(e.type!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");return{publicKey:g().Keypair.fromSecret(e.keys.stellarKey).publicKey()}})}parseUri(e){return k(this,null,function*(){const t={};t[E]=!0;const s=`${E}:pay`;if(e.includes(s)){const l=$()(e,{},!0).query.destination;l&&(e=e.replace(s,`${E}:${l}`))}const{parsedUri:r,edgeParsedUri:n}=(0,q.k)(this.currencyInfo,e,t);if(!this.checkAddress(n.publicAddress||""))throw new Error("InvalidPublicAddressError");if(r.query.msg&&(n.metadata={notes:r.query.msg}),r.query.asset_code&&r.query.asset_code.toUpperCase()!=="XLM")throw new Error("ErrorInvalidCurrencyCode");if(r.query.memo_type&&r.query.memo_type!=="MEMO_ID")throw new Error("ErrorInvalidMemoType");if(r.query.memo){if((0,y.add)(r.query.memo,"0")!==r.query.memo)throw new Error("ErrorInvalidMemoId");n.uniqueIdentifier=r.query.memo}return n})}encodeUri(e){return k(this,arguments,function*(t,s=[]){if(!this.checkAddress(t.publicAddress))throw new Error("InvalidPublicAddressError");let n;if(typeof t.nativeAmount=="string"){const a="XLM",o=t.nativeAmount,l=(0,d.Qs)(a,this.currencyInfo,s);if(l==null)throw new Error("InternalErrorInvalidCurrencyCode");n=(0,y.div)(o,l.multiplier,7)}if(!n&&!t.label&&!t.message)return t.publicAddress;{let a=`destination=${t.publicAddress}&`;n&&(a+="amount="+n+"&"),(t.label||t.message)&&(typeof t.label=="string"&&(a+="label="+t.label+"&"),typeof t.message=="string"&&(a+="msg="+t.message+"&")),a=a.substr(0,a.length-1);const o={scheme:E,path:"pay",query:a};return(0,H.qC)(o)}})}}function ee(A){return k(this,null,function*(){return new J(A)})}},17002:function(){},55024:function(){}}]);
|
|
6
|
+
${JSON.stringify((0,d.oX)(e))} `,s),s}return e})}}function O(A,e,t,s){return i(this,null,function*(){const r=R(t),n=new C(A,e,r,s);return yield n.loadEngine(),n})}var k=(A,e,t)=>new Promise((s,r)=>{var n=l=>{try{o(t.next(l))}catch(h){r(h)}},a=l=>{try{o(t.throw(l))}catch(h){r(h)}},o=l=>l.done?s(l.value):Promise.resolve(l.value).then(n,a);o((t=t.apply(A,e)).next())});const E="web+stellar";class J{constructor(e){this.highestTxHeight=0;const{builtinTokens:t,currencyInfo:s,io:r,networkInfo:n}=e;this.builtinTokens=t,this.currencyInfo=s,this.io=r,this.networkInfo=n,g().Network.usePublicNetwork(),this.stellarApiServers=[];for(const a of this.networkInfo.stellarServers){const o=new(g()).Server(a);o.serverName=a,this.stellarApiServers.push(o)}}getDisplayPrivateKey(e){return k(this,null,function*(){return _(e.keys).stellarKey})}getDisplayPublicKey(e){return k(this,null,function*(){const{keys:t}=R(e);return t.publicKey})}checkAddress(e){try{return g().Keypair.fromPublicKey(e),!0}catch{return!1}}createPrivateKey(e){return k(this,null,function*(){if(e!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const t=Array.from(this.io.random(32));return{stellarKey:g().Keypair.fromRawEd25519Seed(t).secret()}})}importPrivateKey(e){return k(this,null,function*(){if(e.replace(/ /g,""),g().Keypair.fromSecret(e),e.length!==56)throw new Error("Private key wrong length");return yield Promise.resolve({stellarKey:e})})}derivePublicKey(e){return k(this,null,function*(){if(e.type!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");return{publicKey:g().Keypair.fromSecret(e.keys.stellarKey).publicKey()}})}parseUri(e){return k(this,null,function*(){const t={};t[E]=!0;const s=`${E}:pay`;if(e.includes(s)){const l=$()(e,{},!0).query.destination;l&&(e=e.replace(s,`${E}:${l}`))}const{parsedUri:r,edgeParsedUri:n}=(0,q.k)(this.currencyInfo,e,t);if(!this.checkAddress(n.publicAddress||""))throw new Error("InvalidPublicAddressError");if(r.query.msg&&(n.metadata={notes:r.query.msg}),r.query.asset_code&&r.query.asset_code.toUpperCase()!=="XLM")throw new Error("ErrorInvalidCurrencyCode");if(r.query.memo_type&&r.query.memo_type!=="MEMO_ID")throw new Error("ErrorInvalidMemoType");if(r.query.memo){if((0,y.add)(r.query.memo,"0")!==r.query.memo)throw new Error("ErrorInvalidMemoId");n.uniqueIdentifier=r.query.memo}return n})}encodeUri(e){return k(this,arguments,function*(t,s=[]){if(!this.checkAddress(t.publicAddress))throw new Error("InvalidPublicAddressError");let n;if(typeof t.nativeAmount=="string"){const a="XLM",o=t.nativeAmount,l=(0,d.Qs)(a,this.currencyInfo,s);if(l==null)throw new Error("InternalErrorInvalidCurrencyCode");n=(0,y.div)(o,l.multiplier,7)}if(!n&&!t.label&&!t.message)return t.publicAddress;{let a=`destination=${t.publicAddress}&`;n&&(a+="amount="+n+"&"),(t.label||t.message)&&(typeof t.label=="string"&&(a+="label="+t.label+"&"),typeof t.message=="string"&&(a+="msg="+t.message+"&")),a=a.substr(0,a.length-1);const o={scheme:E,path:"pay",query:a};return(0,H.qC)(o)}})}}function ee(A){return k(this,null,function*(){return new J(A)})}},89214:function(){},52361:function(){},94616:function(){},17002:function(){},55024:function(){}}]);
|