edge-currency-accountbased 2.2.3 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/android/src/main/assets/edge-currency-accountbased/234.chunk.js +35 -0
- package/android/src/main/assets/edge-currency-accountbased/248.chunk.js +35 -0
- package/android/src/main/assets/edge-currency-accountbased/336.chunk.js +9 -0
- package/android/src/main/assets/edge-currency-accountbased/612.chunk.js +1 -0
- package/android/src/main/assets/edge-currency-accountbased/{945.chunk.js → 814.chunk.js} +8 -8
- package/android/src/main/assets/edge-currency-accountbased/935.chunk.js +1 -1
- package/android/src/main/assets/edge-currency-accountbased/94.chunk.js +8 -0
- package/android/src/main/assets/edge-currency-accountbased/algorand.chunk.js +2 -2
- package/android/src/main/assets/edge-currency-accountbased/bnb.chunk.js +4 -4
- package/android/src/main/assets/edge-currency-accountbased/edge-currency-accountbased.js +10 -10
- package/android/src/main/assets/edge-currency-accountbased/eos.chunk.js +12 -12
- package/android/src/main/assets/edge-currency-accountbased/ethereum.chunk.js +5 -5
- 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 +5 -5
- package/android/src/main/assets/edge-currency-accountbased/solana.chunk.js +3 -3
- package/android/src/main/assets/edge-currency-accountbased/stellar.chunk.js +4 -4
- package/android/src/main/assets/edge-currency-accountbased/tezos.chunk.js +3 -3
- 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/algorand/AlgorandEngine.js +46 -24
- package/lib/algorand/algorandInfo.js +8 -7
- package/lib/algorand/algorandTestnetInfo.js +8 -7
- package/lib/binance/BinanceEngine.js +19 -17
- package/lib/binance/binanceInfo.js +10 -7
- package/lib/common/types.js +10 -0
- package/lib/common/upgradeMemos.js +52 -0
- package/lib/common/utf8.js +32 -0
- package/lib/common/validateMemos.js +107 -0
- package/lib/eos/EosEngine.js +42 -41
- package/lib/eos/info/eosCommonInfo.js +10 -0
- package/lib/eos/info/eosInfo.js +15 -17
- package/lib/eos/info/telosInfo.js +15 -15
- package/lib/eos/info/waxInfo.js +15 -16
- package/lib/ethereum/EthereumEngine.js +13 -12
- package/lib/ethereum/EthereumNetwork.js +16 -14
- package/lib/ethereum/info/avalancheInfo.js +17 -7
- package/lib/ethereum/info/binancesmartchainInfo.js +9 -7
- package/lib/ethereum/info/celoInfo.js +9 -7
- package/lib/ethereum/info/ethDevInfo.js +9 -7
- package/lib/ethereum/info/ethereumCommonInfo.js +10 -0
- package/lib/ethereum/info/ethereumInfo.js +17 -7
- package/lib/ethereum/info/ethereumclassicInfo.js +9 -7
- package/lib/ethereum/info/ethereumpowInfo.js +9 -7
- package/lib/ethereum/info/fantomInfo.js +9 -7
- package/lib/ethereum/info/goerliInfo.js +9 -7
- package/lib/ethereum/info/kovanInfo.js +9 -7
- package/lib/ethereum/info/optimismInfo.js +9 -7
- package/lib/ethereum/info/polygonInfo.js +9 -7
- package/lib/ethereum/info/pulsechainInfo.js +9 -7
- package/lib/ethereum/info/rinkebyInfo.js +9 -7
- package/lib/ethereum/info/ropstenInfo.js +9 -7
- package/lib/ethereum/info/rskInfo.js +9 -7
- package/lib/ethereum/info/zksyncInfo.js +9 -7
- package/lib/filecoin/FilecoinEngine.js +125 -87
- package/lib/filecoin/Filfox.js +68 -1
- package/lib/filecoin/filecoinInfo.js +5 -7
- package/lib/fio/FioEngine.js +25 -17
- package/lib/fio/fioInfo.js +8 -6
- package/lib/hedera/HederaEngine.js +22 -18
- package/lib/hedera/hederaInfo.js +11 -8
- package/lib/hedera/hederaTestnetInfo.js +6 -6
- package/lib/polkadot/PolkadotEngine.js +15 -9
- package/lib/polkadot/info/liberlandInfo.js +3 -2
- package/lib/polkadot/info/liberlandTestnetInfo.js +3 -2
- package/lib/polkadot/info/polkadotInfo.js +8 -5
- package/lib/ripple/RippleEngine.js +53 -75
- package/lib/ripple/rippleInfo.js +16 -8
- package/lib/solana/SolanaEngine.js +17 -12
- package/lib/solana/solanaInfo.js +9 -5
- package/lib/stellar/StellarEngine.js +31 -22
- package/lib/stellar/stellarInfo.js +16 -7
- package/lib/tezos/TezosEngine.js +17 -11
- package/lib/tezos/tezosInfo.js +8 -5
- package/lib/tron/TronEngine.js +85 -68
- package/lib/tron/tronInfo.js +8 -7
- package/lib/zcash/ZcashEngine.js +23 -23
- package/lib/zcash/piratechainInfo.js +8 -6
- package/lib/zcash/zcashInfo.js +7 -6
- package/package.json +2 -2
- package/android/src/main/assets/edge-currency-accountbased/124.chunk.js +0 -35
- package/android/src/main/assets/edge-currency-accountbased/223.chunk.js +0 -9
- package/android/src/main/assets/edge-currency-accountbased/650.chunk.js +0 -1
- package/android/src/main/assets/edge-currency-accountbased/689.chunk.js +0 -8
- package/android/src/main/assets/edge-currency-accountbased/826.chunk.js +0 -35
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[603],{79014:function(
|
|
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
|
-
${(0,
|
|
4
|
-
${(0,
|
|
5
|
-
${(0,
|
|
1
|
+
"use strict";(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[603],{79014:function(ie,N,c){c.d(N,{Q:function(){return X},k:function(){return oe}});var u=c(77591),K=c.n(u),_=c(24350),p=c(84564),U=c.n(p),L=c(76714),$=Object.defineProperty,D=Object.getOwnPropertySymbols,T=Object.prototype.hasOwnProperty,ne=Object.prototype.propertyIsEnumerable,Z=(d,k,I)=>k in d?$(d,k,{enumerable:!0,configurable:!0,writable:!0,value:I}):d[k]=I,re=(d,k)=>{for(var I in k||(k={}))T.call(k,I)&&Z(d,I,k[I]);if(D)for(var I of D(k))ne.call(k,I)&&Z(d,I,k[I]);return d};function oe(d,k,I,A,G=[]){const w=re({},U()(k,{},!0)),B=k.startsWith(`${d.pluginId}://`);if(w.protocol!=null&&(w.protocol=w.protocol.replace(":","")),w.protocol!=null&&w.protocol!==""&&!I[w.protocol])throw new Error(`Uri protocol '${w.protocol}' is not supported for ${d.pluginId}.`);if(w.host===""&&w.pathname==="")throw new Error("Path and host not found in uri.");const F={publicAddress:w.host!==""?w.host:w.pathname.split("/")[0]},j=w.query.label,V=w.query.message,Y=w.query.category;(j!=null||V!=null||Y!=null||B)&&(F.metadata={},F.metadata.name=j,F.metadata.notes=V,F.metadata.category=Y,F.metadata.gateway=B!=null?B:!1);const W=w.query.amount;if(W!=null&&typeof W=="string"){A==null&&(A=d.currencyCode);const q=(0,L.Qs)(A!=null?A:"",d,G);if(q==null)throw new Error("InternalErrorInvalidCurrencyCode");let z=(0,u.mul)(W,q.multiplier);z=(0,u.toFixed)(z,0,0),F.nativeAmount=z,F.currencyCode=A}return{edgeParsedUri:F,parsedUri:w}}function X(d,k,I){if(d.publicAddress==null)throw new Error("InvalidPublicAddressError");if(I==null&&d.label==null&&d.message==null)return d.publicAddress;{let A="";I!=null&&(A+="amount="+I+"&"),(d.label!=null||d.message!=null)&&(typeof d.label=="string"&&(A+="label="+d.label+"&"),typeof d.message=="string"&&(A+="message="+d.message+"&")),A=A.substr(0,A.length-1);const G={scheme:k,path:d.publicAddress,query:A};return(0,_.qC)(G)}}},99599:function(ie,N,c){c.d(N,{K:function(){return u}});const u={parse(K){const _=encodeURI(K),p=new Uint8Array(_.length);let U=0;for(let L=0;L<_.length;++L){const $=_.charCodeAt(L);$===37?(p[U++]=parseInt(_.slice(L+1,L+3),16),L+=2):p[U++]=$}return p.subarray(0,U)},stringify(K){let _="";for(let p=0;p<K.length;++p){const U=K[p];_+="%"+(U>>4).toString(16)+(U&15).toString(16)}return decodeURIComponent(_)}}},60814:function(ie,N,c){c.r(N),c.d(N,{RippleTools:function(){return fe},makeCurrencyEngine:function(){return De},makeCurrencyTools:function(){return Se}});var u=c(77591),K=c(84564),_=c.n(K),p=c(48726),U=c(31528),L=c(20918),$=c(79014),D=c(76714),T=c(82448),ne=c(62177);const Z=(0,T.Vk)((0,T.su)({activateTokenId:T.XC})),re=(0,T.su)({recommendedFee:(0,T.Vk)(T.XC,"0")}),oe=(0,T.su)({date:T.mH,hash:T.XC,Fee:(0,T.Zz)(T.XC),ledger_index:T.mH}),X=(0,T.su)({currency:T.XC,issuer:T.XC}),d=ne.BQ,k=(0,T.su)({rippleKey:T.XC});var I=c(48764).Buffer;const A=({issuer:h,currency:e})=>{if(!(0,p.isValidAddress)(h))throw new Error("InvalidTokenIssuerError");return`${e}-${h}`},G=40,w=h=>h.length>3?I.from(h,"ascii").toString("hex").toUpperCase().padEnd(G,"0"):h;var B=c(94935),se=c(35620),F=c(96510),j=c(84650),V=c(72681),Y=c(99599),W=c(49349),q=Object.defineProperty,z=Object.defineProperties,ye=Object.getOwnPropertyDescriptors,ae=Object.getOwnPropertySymbols,me=Object.getPrototypeOf,ge=Object.prototype.hasOwnProperty,ve=Object.prototype.propertyIsEnumerable,we=Reflect.get,le=(h,e,t)=>e in h?q(h,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):h[e]=t,Te=(h,e)=>{for(var t in e||(e={}))ge.call(e,t)&&le(h,t,e[t]);if(ae)for(var t of ae(e))ve.call(e,t)&&le(h,t,e[t]);return h},ke=(h,e)=>z(h,ye(e)),ce=(h,e,t)=>we(me(h),t,e),E=(h,e,t)=>new Promise((n,r)=>{var o=s=>{try{l(t.next(s))}catch(a){r(a)}},i=s=>{try{l(t.throw(s))}catch(a){r(a)}},l=s=>s.done?n(s.value):Promise.resolve(s.value).then(o,i);l((t=t.apply(h,e)).next())});const Ie=1e4,Ae=15e3,Ee=3e3,ue=30*60,Ce=1e3*60*1,Pe=60*5,be=20,de="12",he=131072,Le="1000000",pe="12";class ee extends j.P{constructor(e,t,n,r){super(e,t,n,r),this.getRecipientBalance=i=>E(this,null,function*(){var l;try{return(yield this.tools.rippleApi.request({command:"account_info",account:i})).result.account_data.Balance}catch(s){return((l=s.data)==null?void 0:l.error)==="actNotFound"?"0":this.minimumAddressBalance}}),this.engineGetActivationAssets=i=>E(this,null,function*(){return{assetOptions:[{paymentWalletId:this.walletId,currencyPluginId:this.currencyInfo.pluginId}]}}),this.engineActivateWallet=i=>E(this,[i],function*({activateTokenIds:l,paymentTokenId:s,paymentWallet:a}){if(l==null)throw new Error(`Must specify activateTokenIds for ${this.currencyInfo.currencyCode}`);if(s!=null)throw new Error(`Must activate with ${this.currencyInfo.currencyCode}`);if((a==null?void 0:a.id)!==this.walletId)throw new Error("Must pay with same wallet you are activating token with");for(const m of l)if(this.allTokensMap[m]==null)throw new Error(`Invalid tokenId to activate ${m}`);return{paymentWalletId:this.walletId,fromNativeAmount:"0",networkFee:{nativeAmount:(0,u.mul)(pe,l.length.toString()),currencyPluginId:this.currencyInfo.pluginId},approve:(...m)=>E(this,[...m],function*(y={}){const{metadata:g}=y,C=[];for(const S of l){const v=yield a.makeSpend({spendTargets:[],metadata:g,otherParams:{activateTokenId:S}}),P=yield a.signTx(v),b=yield a.broadcastTx(P);this.warn(`SUCCESS activateWallet.approve()
|
|
2
|
+
${(0,D.oX)(b)}`),C.push(b),yield this.saveTx(b)}return{transactions:C}}),close:()=>E(this,null,function*(){})}});const{networkInfo:o}=e;this.networkInfo=o,this.nonce=0,this.minimumAddressBalance=this.networkInfo.baseReserve,this.otherMethods={makeTx:i=>E(this,null,function*(){var l,s;if(i.type==="MakeTxDexSwap"){const{expiration:a,metadata:f,fromNativeAmount:m,fromTokenId:y,toNativeAmount:g,toTokenId:C}=i,S=this.nativeToXrpAmount(m,y),v=this.nativeToXrpAmount(g,C),P=(0,p.unixTimeToRippleTime)((a!=null?a:Pe)*1e3),b={Account:this.walletLocalData.publicKey,Expiration:P,TransactionType:"OfferCreate",TakerGets:S,TakerPays:v},R=yield this.tools.rippleApi.autofill(b),M=((l=R.LastLedgerSequence)!=null?l:this.walletLocalData.blockHeight)+Ce/W.u7;R.LastLedgerSequence=Math.floor(M);const O=(s=R.Fee)!=null?s:"0",{currencyCode:H}=y==null?this.currencyInfo:this.allTokensMap[y];return{blockHeight:0,currencyCode:H,date:Date.now()/1e3,isSend:!0,memos:[],metadata:f,nativeAmount:`-${(0,u.add)(m,O)}`,networkFee:O,otherParams:{xrpTransaction:R},ourReceiveAddresses:[],signedTx:"",txid:"",walletId:this.walletId}}throw new Error(`Invalid type: ${i.type}`)})}}nativeToXrpAmount(e,t){if(t==null)return e;{const{networkLocation:n,denominations:r}=this.allTokensMap[t],{currency:o,issuer:i}=X(n);return{value:(0,u.div)(e,r[0].multiplier,W.w7),currency:w(o),issuer:i}}}setOtherData(e){this.otherData=re(e)}getTotalReserve(){const e=this.enabledTokens.length-1-this.walletLocalData.unactivatedTokenIds.length,t=(0,u.mul)(this.networkInfo.baseReservePerToken,e.toString());return(0,u.add)(this.networkInfo.baseReserve,t)}checkServerInfoInnerLoop(){return E(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,D.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,r;const{log:o}=this,{publicKey:i}=this.walletLocalData,{meta:l,tx:s}=e;if(s==null){o("processRippleTransaction: no tx");return}if(typeof l!="object"){o(`processRippleTransaction: hash:${(t=s.hash)==null?void 0:t.toString()} no meta`);return}let a;try{a=oe(s)}catch(C){o(String(C));return}const f=(0,p.getBalanceChanges)(l),{date:m,hash:y,Fee:g}=a;for(const C of f){const{account:S}=C;if(S===i)for(const v of C.balances){const{currency:P,issuer:b,value:R}=v;if(P===this.currencyInfo.currencyCode){if(b!=null){o(`Transaction has parent code ${P} with issuer ${b}`);return}const M=this.currencyInfo.denominations.find(te=>te.name===P);if(M==null){o(`Unknown denom ${P}`);continue}const O=(0,u.mul)(R,M.multiplier);let H=!1,Q="0";const J=[];(0,u.lt)(O,"0")?(H=!0,Q=g!=null?g:"0"):J.push(i),this.addTransaction(P,{blockHeight:(n=s.ledger_index)!=null?n:-1,currencyCode:P,date:(0,p.rippleTimeToUnixTime)(m)/1e3,isSend:H,memos:[],nativeAmount:O,networkFee:Q,otherParams:{},ourReceiveAddresses:J,signedTx:"",txid:y.toLowerCase(),walletId:this.walletId})}else{if(b==null){o(`Transaction has token code ${P} with no issuer`);return}const M=A({currency:P,issuer:b}),O=this.allTokensMap[M];if(O==null)return;const{currencyCode:H}=O,Q=(0,u.mul)(R,O.denominations[0].multiplier);let J=!1;const te=[];(0,u.lt)(Q,"0")?J=!0:te.push(i),this.addTransaction(H,{blockHeight:(r=s.ledger_index)!=null?r:-1,currencyCode:H,date:(0,p.rippleTimeToUnixTime)(m)/1e3,isSend:J,memos:[],nativeAmount:Q,networkFee:"0",otherParams:{},ourReceiveAddresses:te,signedTx:"",txid:y.toLowerCase(),walletId:this.walletId})}}}}checkTransactionsInnerLoop(){return E(this,null,function*(){const e=this.walletLocalData.blockHeight,t=this.walletLocalData.publicKey;let n=-1;this.walletLocalData.lastAddressQueryHeight>ue&&(n=this.walletLocalData.lastAddressQueryHeight-ue);try{const r=yield this.tools.rippleApi.request({command:"account_tx",account:t,forward:!0,ledger_index_min:n}),{transactions:o}=r.result;this.log(`Fetched transactions count: ${o.length} startBlock:${n}`);for(const i of o)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(r){this.error("Error fetching transactions: ",r)}})}checkAccountInnerLoop(){return E(this,null,function*(){var e,t;const n=this.walletLocalData.publicKey,r=[];try{const o=yield this.tools.rippleApi.request({command:"account_info",account:n,ledger_index:"current"}),{Balance:i,Sequence:l}=o.result.account_data;if(this.updateBalance(this.currencyInfo.currencyCode,i),this.nonce=l,(yield this.tools.rippleApi.getBalances(n)).forEach(({currency:a,issuer:f,value:m})=>{if(f==null)return;const y=A({currency:a,issuer:f}),g=this.allTokensMap[y];if(g!=null){const C=g.denominations[0].multiplier;if(C==null)return;const S=(0,u.toFixed)((0,u.mul)(m,C),0,0);this.updateBalance(g.currencyCode,S)}}),this.enabledTokens.forEach(a=>{this.tokenCheckBalanceStatus[a]=1}),this.updateOnAddressesChecked(),this.enabledTokens.length>1){const a=yield this.tools.rippleApi.request({command:"account_lines",account:n});this.enabledTokens.forEach(f=>{if(a.result.lines.find(y=>{const{account:g,currency:C}=y,S=A({currency:C,issuer:g}),v=this.allTokensMap[S];return v!=null&&f===v.currencyCode})==null){const y=(0,L.dK)(f,this.allTokensMap);y!=null&&r.push(y)}})}}catch(o){if(((e=o==null?void 0:o.data)==null?void 0:e.error)==="actNotFound"||((t=o==null?void 0:o.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 l=(0,L.dK)(i,this.allTokensMap);l!=null&&r.push(l),this.updateBalance(i,"0")}});else{this.error("Error fetching address info: ",o);return}}(0,D.dQ)(r,this.walletLocalData.unactivatedTokenIds)||(this.walletLocalData.unactivatedTokenIds=r,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onUnactivatedTokenIdsChanged(this.walletLocalData.unactivatedTokenIds))})}startEngine(){return E(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",Ie).catch(e=>console.log(e.message)),this.addToLoop("checkTransactionsInnerLoop",Ee).catch(e=>console.log(e.message)),yield ce(ee.prototype,this,"startEngine").call(this)})}killEngine(){return E(this,null,function*(){yield ce(ee.prototype,this,"killEngine").call(this),yield this.tools.disconnectApi(this.walletId)})}resyncBlockchain(){return E(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getMaxSpendable(e){return E(this,null,function*(){e=(0,V.s)(e,this.currencyInfo);const{currencyCode:t}=e;let n=this.getBalance({currencyCode:t});const r=this.getTotalReserve();if(t===this.currencyInfo.currencyCode&&(n=(0,u.sub)(n,r)),(0,u.lte)(n,"0"))throw new B.C_;return n})}makeSpend(e){return E(this,null,function*(){var t;e=(0,V.s)(e,this.currencyInfo);const{edgeSpendInfo:n,currencyCode:r,nativeBalance:o}=this.makeSpendCheck(e),{memos:i=[]}=n,l=this.currencyInfo.currencyCode,s=Z(n.otherParams);if((s==null?void 0:s.activateTokenId)!=null){const v=s.activateTokenId,P=this.allTokensMap[v],{currency:b,issuer:R}=X(P.networkLocation),M=pe,O=yield this.tools.rippleApi.autofill({TransactionType:"TrustSet",Account:this.walletLocalData.publicKey,Fee:M,Flags:he,LimitAmount:{currency:b,issuer:R,value:Le}});return{blockHeight:0,currencyCode:this.currencyInfo.currencyCode,date:Date.now()/1e3,isSend:!0,memos:i,metadata:n.metadata,nativeAmount:`-${M}`,networkFee:M,otherParams:{xrpTransaction:O},ourReceiveAddresses:[],signedTx:"",txid:"",walletId:this.walletId}}if(n.spendTargets.length!==1)throw new Error("Error: only one output allowed");const{publicAddress:a}=n.spendTargets[0];let{nativeAmount:f}=n.spendTargets[0];if(a==null)throw new Error("makeSpend Missing publicAddress");if(f==null)throw new B.$D;if((0,u.eq)(f,"0"))throw new B.$D;let m="0",y;if(r===l){m=this.otherData.recommendedFee;const v=this.getTotalReserve();if((0,u.gt)((0,u.add)(f,v),o))throw new B.C_}else{if(y=de,(0,u.gt)(f,o))throw new B.C_;const v=(t=this.walletLocalData.totalBalances[l])!=null?t:"0";if((0,u.gt)(y,v))throw new B.C_({currencyCode:l,networkFee:y})}let g;if(r===l)g={Amount:f,TransactionType:"Payment",Account:this.walletLocalData.publicKey,Destination:a,Fee:m},f=`-${(0,u.add)(f,m)}`;else{const v=(0,L.dK)(r,this.allTokensMap);if(v==null)throw new Error("Error: Token not supported");const P=this.allTokensMap[v],{networkLocation:b,denominations:[R]}=P,{currency:M,issuer:O}=X(b);g={TransactionType:"Payment",Account:this.walletLocalData.publicKey,Fee:y!=null?y:de,Amount:{currency:M,issuer:O,value:(0,u.div)(f,R.multiplier,(0,u.log10)(R.multiplier))},Destination:a,Flags:he},f=`-${f}`}for(const v of i)v.type==="number"?g.DestinationTag=parseInt(i[0].value):v.type==="text"&&(g.Memos==null&&(g.Memos=[]),g.Memos.push({Memo:{MemoFormat:se.YU.stringify(Y.K.parse("text/plain")),MemoData:se.YU.stringify(Y.K.parse(v.value))}}));const S={blockHeight:0,currencyCode:r,date:0,isSend:!0,memos:[],nativeAmount:f,networkFee:m,otherParams:{preparedTx:g},ourReceiveAddresses:[],parentNetworkFee:y,signedTx:"",txid:"",walletId:this.walletId};return this.warn("Payment transaction prepared..."),S})}signTx(e,t){return E(this,null,function*(){const n=k(t),r=(0,D.Xp)(e);if(r.xrpTransaction!=null){const m=r.xrpTransaction,y=t.rippleKey,g=p.Wallet.fromSeed(y),{tx_blob:C,hash:S}=g.sign(m);return this.warn("Activation transaction signed..."),e.signedTx=C,e.txid=S.toLowerCase(),e.date=Date.now()/1e3,this.warn(`signTx
|
|
3
|
+
${(0,D.oX)(e)}`),e}const o=ke(Te({},r.preparedTx),{Sequence:this.nonce,LastLedgerSequence:this.walletLocalData.blockHeight+be});(0,F.validatePayment)(o);const i=o.Destination;if(i==null)throw new Error("makeSpend Missing publicAddress");if(e.currencyCode===this.currencyInfo.currencyCode){const m=(0,u.abs)((0,u.add)(e.nativeAmount,e.networkFee));yield this.checkRecipientMinimumBalance(this.getRecipientBalance,m,i)}const l=n.rippleKey,s=p.Wallet.fromSeed(l),{tx_blob:a,hash:f}=s.sign(o);return this.warn("Payment transaction signed..."),e.signedTx=a,e.txid=f.toLowerCase(),e.date=Date.now()/1e3,this.warn(`signTx
|
|
4
|
+
${(0,D.oX)(e)}`),e})}broadcastTx(e){return E(this,null,function*(){const t=yield this.tools.rippleApi.submit(e.signedTx),{engine_result_code:n,engine_result_message:r}=t.result;if(n>=-199&&n<=-100||n>=-299&&n<=-200||n>=-399&&n<=-300)throw this.warn(`FAILURE broadcastTx ${n} ${r}`),new Error(r);return this.warn(`SUCCESS broadcastTx
|
|
5
|
+
${(0,D.oX)(e)}`),e})}}function De(h,e,t,n){return E(this,null,function*(){const r=d(t),o=new ee(h,e,r,n);return yield o.loadEngine(),o})}var x=(h,e,t)=>new Promise((n,r)=>{var o=s=>{try{l(t.next(s))}catch(a){r(a)}},i=s=>{try{l(t.throw(s))}catch(a){r(a)}},l=s=>s.done?n(s.value):Promise.resolve(s.value).then(o,i);l((t=t.apply(h,e)).next())});class fe{constructor(e){const{builtinTokens:t,currencyInfo:n,io:r,networkInfo:o}=e;this.builtinTokens=t,this.currencyInfo=n,this.io=r,this.networkInfo=o,this.rippleApiSubscribers={}}getDisplayPrivateKey(e){return x(this,null,function*(){return k(e.keys).rippleKey})}getDisplayPublicKey(e){return x(this,null,function*(){const{keys:t}=d(e);return t.publicKey})}connectApi(e){return x(this,null,function*(){if(Object.keys(this.rippleApiSubscribers).length===0){const t=this.networkInfo.rippledServers.map(r=>()=>x(this,null,function*(){const o=new p.Client(r);return yield o.connect(),o})),n=yield(0,D.QJ)(t);this.rippleApi=n}this.rippleApiSubscribers[e]=!0})}disconnectApi(e){return x(this,null,function*(){delete this.rippleApiSubscribers[e],Object.keys(this.rippleApiSubscribers).length===0&&(yield this.rippleApi.disconnect())})}importPrivateKey(e){return x(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,D.HY)(t)}`)}})}createPrivateKey(e){return x(this,null,function*(){const t=e.replace("wallet:","");if(t==="ripple"||t==="ripple-secp256k1"){const n=t==="ripple-secp256k1"?U.default.secp256k1:U.default.ed25519,r=Array.from(this.io.random(32));return{rippleKey:p.Wallet.fromEntropy(r,{algorithm:n}).seed}}else throw new Error("InvalidWalletType")})}derivePublicKey(e){return x(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 x(this,null,function*(){var t;const n={ripple:!0,"xrp-ledger":!0},r="https://ripple.com//send";try{const{classicAddress:s,tag:a}=(0,p.xAddressToClassicAddress)(e);e=`ripple:${s}?to=${s}${a!==!1?`&dt=${a}`:""}`}catch{}if(e.includes(r)){const a=_()(e,{},!0).query.to;a!=null&&(e=e.replace(r,`ripple:${a}`))}const{parsedUri:o,edgeParsedUri:i}=(0,$.k)(this.currencyInfo,e,n);if(!(0,p.isValidAddress)((t=i.publicAddress)!=null?t:""))throw new Error("InvalidPublicAddressError");return i.uniqueIdentifier=o.query.dt,i})}encodeUri(e){return x(this,arguments,function*(t,n=[]){if(!(0,p.isValidAddress)(t.publicAddress))throw new Error("InvalidPublicAddressError");let o;if(typeof t.nativeAmount=="string"){const l="XRP",s=t.nativeAmount,a=(0,D.Qs)(l,this.currencyInfo,n);if(a==null)throw new Error("InternalErrorInvalidCurrencyCode");o=(0,u.div)(s,a.multiplier,6)}return(0,$.Q)(t,"ripple",o)})}getTokenId(e){return x(this,null,function*(){(0,L.Rp)(e);const t=e==null?void 0:e.networkLocation;if(t==null)throw new Error("ErrorInvalidNetworkLocation");const n=X(t);return A(n)})}}function Se(h){return x(this,null,function*(){return new fe(h)})}}}]);
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[601],{79014:function(
|
|
2
|
-
${(0,
|
|
3
|
-
${(0,
|
|
1
|
+
(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[601],{79014:function(J,E,c){"use strict";c.d(E,{Q:function(){return L},k:function(){return Q}});var I=c(77591),b=c.n(I),v=c(24350),w=c(84564),P=c.n(w),C=c(76714),k=Object.defineProperty,r=Object.getOwnPropertySymbols,H=Object.prototype.hasOwnProperty,W=Object.prototype.propertyIsEnumerable,D=(l,d,f)=>d in l?k(l,d,{enumerable:!0,configurable:!0,writable:!0,value:f}):l[d]=f,N=(l,d)=>{for(var f in d||(d={}))H.call(d,f)&&D(l,f,d[f]);if(r)for(var f of r(d))W.call(d,f)&&D(l,f,d[f]);return l};function Q(l,d,f,m,O=[]){const h=N({},P()(d,{},!0)),B=d.startsWith(`${l.pluginId}://`);if(h.protocol!=null&&(h.protocol=h.protocol.replace(":","")),h.protocol!=null&&h.protocol!==""&&!f[h.protocol])throw new Error(`Uri protocol '${h.protocol}' is not supported for ${l.pluginId}.`);if(h.host===""&&h.pathname==="")throw new Error("Path and host not found in uri.");const S={publicAddress:h.host!==""?h.host:h.pathname.split("/")[0]},R=h.query.label,p=h.query.message,K=h.query.category;(R!=null||p!=null||K!=null||B)&&(S.metadata={},S.metadata.name=R,S.metadata.notes=p,S.metadata.category=K,S.metadata.gateway=B!=null?B:!1);const x=h.query.amount;if(x!=null&&typeof x=="string"){m==null&&(m=l.currencyCode);const M=(0,C.Qs)(m!=null?m:"",l,O);if(M==null)throw new Error("InternalErrorInvalidCurrencyCode");let A=(0,I.mul)(x,M.multiplier);A=(0,I.toFixed)(A,0,0),S.nativeAmount=A,S.currencyCode=m}return{edgeParsedUri:S,parsedUri:h}}function L(l,d,f){if(l.publicAddress==null)throw new Error("InvalidPublicAddressError");if(f==null&&l.label==null&&l.message==null)return l.publicAddress;{let m="";f!=null&&(m+="amount="+f+"&"),(l.label!=null||l.message!=null)&&(typeof l.label=="string"&&(m+="label="+l.label+"&"),typeof l.message=="string"&&(m+="message="+l.message+"&")),m=m.substr(0,m.length-1);const O={scheme:d,path:l.publicAddress,query:m};return(0,v.qC)(O)}}},99599:function(J,E,c){"use strict";c.d(E,{K:function(){return I}});const I={parse(b){const v=encodeURI(b),w=new Uint8Array(v.length);let P=0;for(let C=0;C<v.length;++C){const k=v.charCodeAt(C);k===37?(w[P++]=parseInt(v.slice(C+1,C+3),16),C+=2):w[P++]=k}return w.subarray(0,P)},stringify(b){let v="";for(let w=0;w<b.length;++w){const P=b[w];v+="%"+(P>>4).toString(16)+(P&15).toString(16)}return decodeURIComponent(v)}}},18226:function(J,E,c){"use strict";c.r(E),c.d(E,{SolanaTools:function(){return Y},makeCurrencyEngine:function(){return ee},makeCurrencyTools:function(){return re}});var I=c(75885),b=c(77591),v=c(2153),w=c(48764),P=c(62678),C=c(79014),k=c(76714),r=c(82448),H=c(62177);const W=(0,r.su)({newestTxid:(0,r.Vk)(r.XC,"")}),D=(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})})}),L=H.BQ,l=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 d=c(94935),f=c(35620),m=c(84650),O=c(72681),h=c(99599),B=c(48764).Buffer,G=Object.getPrototypeOf,S=Reflect.get,R=(y,e,t)=>S(G(y),t,e),p=(y,e,t)=>new Promise((n,s)=>{var o=i=>{try{u(t.next(i))}catch(g){s(g)}},a=i=>{try{u(t.throw(i))}catch(g){s(g)}},u=i=>i.done?n(i.value):Promise.resolve(i.value).then(o,a);u((t=t.apply(y,e)).next())});const{PublicKey:K,Keypair:x,SystemProgram:M,Transaction:A,TransactionInstruction:j}=I,q=5e3,V=2e4,_=3e3;class X extends m.P{constructor(e,t,n,s){super(e,t,n,s),this.networkInfo=e.networkInfo,this.chainCode=t.currencyInfo.currencyCode,this.fetchCors=(0,k.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 p(this,arguments,function*(t,n=[]){const s={jsonrpc:"2.0",id:1,method:t,params:n},o={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(s)},a=this.networkInfo.rpcNodes.map(i=>()=>p(this,null,function*(){const g=yield this.fetchCors(i,o);if(!g.ok)throw new Error(`fetchRpc ${o.method} failed error: ${g.status}`);return yield g.json()}));return(yield(0,k.QJ)(a)).result})}queryBalance(){return p(this,null,function*(){try{const e=yield this.fetchRpc("getBalance",[this.base58PublicKey,{commitment:this.networkInfo.commitment}]),t=D(e);this.updateBalance(this.chainCode,t.value.toString())}catch(e){this.error(`Error checking ${this.chainCode} address balance`,e)}})}queryBlockheight(){return p(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 p(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=[],s=e.transaction.message.accountKeys.findIndex(i=>i===this.base58PublicKey);if(s<0||e.meta==null)return;const o=e.meta.postBalances[s]-e.meta.preBalances[s],a=e.meta.fee;if(o>=0){if(e.meta.err!=null)return;n.push(this.base58PublicKey)}const u={blockHeight:e.slot,currencyCode:this.chainCode,date:t,isSend:o.toString().startsWith("-"),memos:[],nativeAmount:o.toString(),networkFee:a.toString(),ourReceiveAddresses:n,signedTx:"",txid:e.transaction.signatures[0],walletId:this.walletId};this.addTransaction(this.chainCode,u)}queryTransactions(){return p(this,null,function*(){let e=null;const t=this.otherData.newestTxid!==""?this.otherData.newestTxid:null;let n=[];try{for(;;){const o=[this.base58PublicKey,{until:t,before:e,limit:this.networkInfo.txQueryLimit,commitment:this.networkInfo.commitment}],a=yield this.fetchRpc("getSignaturesForAddress",o);if(n=n.concat(a),a.length<this.networkInfo.txQueryLimit)break;e=a[this.networkInfo.txQueryLimit-1].signature}}catch(o){this.error("getTransactionSignatures failed with error: ",o);return}if(n.length===0){this.tokenCheckTransactionsStatus[this.chainCode]=1,this.updateOnAddressesChecked();return}let s=-1;for(let o=n.length-1;o>=0;o--)try{const a=N(yield this.fetchRpc("getTransaction",[n[o].signature,{encoding:"json",commitment:this.networkInfo.commitment}]));let u=n[o].blocktime;(u==null||isNaN(u))&&(u=(0,r.mH)(yield this.fetchRpc("getBlockTime",[a.slot]))),this.processSolanaTransaction(a,u);const i=1-o/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{s=o;break}s===-1?this.otherData.newestTxid=n[0].signature:n.length>s+1&&(this.otherData.newestTxid=n[s+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 p(this,null,function*(){this.engineOn=!0,this.addToLoop("queryBlockheight",V),this.addToLoop("queryFee",V),this.addToLoop("queryBalance",q),this.addToLoop("queryTransactions",_),R(X.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return p(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}makeSpend(e){return p(this,null,function*(){var t,n;e=(0,O.s)(e,this.currencyInfo);const{edgeSpendInfo:s,currencyCode:o}=this.makeSpendCheck(e),{memos:a=[]}=s;if(s.spendTargets.length!==1)throw new Error("Error: only one output allowed");const{nativeAmount:u,publicAddress:i}=s.spendTargets[0];if(i==null)throw new Error("makeSpend Missing publicAddress");if(u==null)throw new d.$D;const g=this.feePerSignature,$=(t=this.walletLocalData.totalBalances[this.chainCode])!=null?t:"0";let F="0";if(F=(0,b.add)(u,g),(0,b.gt)(F,$))throw new d.C_;const z=new K(this.base58PublicKey),se={recentBlockhash:this.recentBlockhash,feePayer:z},Z=new A(se).add(M.transfer({fromPubkey:z,toPubkey:new K(i),lamports:parseInt(u)}));if(((n=a[0])==null?void 0:n.type)==="text"){const ie=new j({keys:[{pubkey:z,isSigner:!0,isWritable:!0}],programId:new K(this.networkInfo.memoPublicKey),data:B.from(h.K.parse(a[0].value))});Z.add(ie)}const oe={unsignedSerializedSolTx:Z.serialize({requireAllSignatures:!1})};return{blockHeight:0,currencyCode:o,date:0,isSend:!0,memos:a,nativeAmount:(0,b.mul)(F,"-1"),networkFee:g,otherParams:oe,ourReceiveAddresses:[],signedTx:"",txid:"",walletId:this.walletId}})}signTx(e,t){return p(this,null,function*(){const n=l(this.currencyInfo.pluginId)(t),{unsignedSerializedSolTx:s}=(0,k.Xp)(e);if(s==null)throw new Error("Missing unsignedSerializedSolTx");const o=x.fromSecretKey(Uint8Array.from(f.YU.parse(n.privateKey))),a=A.from(s);return a.recentBlockhash=this.recentBlockhash,a.sign({publicKey:o.publicKey,secretKey:o.secretKey}),e.signedTx=a.serialize().toString("base64"),this.warn(`signTx
|
|
2
|
+
${(0,k.oX)(e)}`),e})}broadcastTx(e){return p(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,k.oX)(e)}`)}catch(t){throw this.warn("FAILURE broadcastTx failed: ",t),t}return e})}}function ee(y,e,t,n){return p(this,null,function*(){const s=L(t),o=new X(y,e,s,n);return yield o.loadEngine(),o})}var T=(y,e,t)=>new Promise((n,s)=>{var o=i=>{try{u(t.next(i))}catch(g){s(g)}},a=i=>{try{u(t.throw(i))}catch(g){s(g)}},u=i=>i.done?n(i.value):Promise.resolve(i.value).then(o,a);u((t=t.apply(y,e)).next())});const{Keypair:te,PublicKey:U}=I,ne=(y,e)=>T(void 0,null,function*(){const t=yield(0,v.mnemonicToSeed)(y),n=P.derivePath(e,t.toString("hex")).key;return te.fromSeed(Uint8Array.from(w.Buffer.from(n,"hex")))});class Y{constructor(e){const{builtinTokens:t,currencyInfo:n,io:s,networkInfo:o}=e;this.builtinTokens=t,this.currencyInfo=n,this.io=s,this.networkInfo=o}getDisplayPrivateKey(e){return T(this,null,function*(){const{pluginId:t}=this.currencyInfo;return l(t)(e.keys).mnemonic})}getDisplayPublicKey(e){return T(this,null,function*(){const{keys:t}=L(e);return t.publicKey})}importPrivateKey(e){return T(this,null,function*(){const{pluginId:t}=this.currencyInfo;if(!(0,v.validateMnemonic)(e))throw new Error("Invalid mnemonic");const s=yield ne(e,this.networkInfo.derivationPath);return{[`${t}Mnemonic`]:e,[`${t}Key`]:w.Buffer.from(s.secretKey).toString("hex"),publicKey:s.publicKey.toBase58()}})}createPrivateKey(e){return T(this,null,function*(){if(e!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const t=w.Buffer.from(this.io.random(32)),n=(0,v.entropyToMnemonic)(t);return yield this.importPrivateKey(n)})}derivePublicKey(e){return T(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 T(this,null,function*(){const{pluginId:s}=this.currencyInfo,o={[s]:!0},{parsedUri:a,edgeParsedUri:u}=(0,C.k)(this.currencyInfo,e,o,t||this.currencyInfo.currencyCode,n);let i="";if(u.publicAddress&&(i=u.publicAddress),!U.isOnCurve(new U(i).toBytes()))throw new Error("InvalidPublicAddressError");return u.uniqueIdentifier=a.query.memo,u})}encodeUri(e){return T(this,arguments,function*(t,n=[]){const{pluginId:s}=this.currencyInfo,{nativeAmount:o,currencyCode:a,publicAddress:u}=t;if(!U.isOnCurve(new U(u).toBytes()))throw new Error("InvalidPublicAddressError");let i;if(typeof o=="string"){const $=(0,k.Qs)(a!=null?a:this.currencyInfo.currencyCode,this.currencyInfo,n);if($==null)throw new Error("InternalErrorInvalidCurrencyCode");i=(0,b.div)(o,$.multiplier,18)}return(0,C.Q)(t,s,i)})}}function re(y){return T(this,null,function*(){return new Y(y)})}},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([[870],{79014:function(Z,M,c){"use strict";c.d(M,{Q:function(){return R},k:function(){return B}});var y=c(77591),G=c.n(y),m=c(24350),x=c(84564),_=c.n(x),F=c(76714),N=Object.defineProperty,d=Object.getOwnPropertySymbols,w=Object.prototype.hasOwnProperty,q=Object.prototype.propertyIsEnumerable,K=(l,p,f)=>p in l?N(l,p,{enumerable:!0,configurable:!0,writable:!0,value:f}):l[p]=f,W=(l,p)=>{for(var f in p||(p={}))w.call(p,f)&&K(l,f,p[f]);if(d)for(var f of d(p))q.call(p,f)&&K(l,f,p[f]);return l};function B(l,p,f,v,L=[]){const h=W({},_()(p,{},!0)),u=p.startsWith(`${l.pluginId}://`);if(h.protocol!=null&&(h.protocol=h.protocol.replace(":","")),h.protocol!=null&&h.protocol!==""&&!f[h.protocol])throw new Error(`Uri protocol '${h.protocol}' is not supported for ${l.pluginId}.`);if(h.host===""&&h.pathname==="")throw new Error("Path and host not found in uri.");const A={publicAddress:h.host!==""?h.host:h.pathname.split("/")[0]},P=h.query.label,U=h.query.message,C=h.query.category;(P!=null||U!=null||C!=null||u)&&(A.metadata={},A.metadata.name=P,A.metadata.notes=U,A.metadata.category=C,A.metadata.gateway=u!=null?u:!1);const T=h.query.amount;if(T!=null&&typeof T=="string"){v==null&&(v=l.currencyCode);const H=(0,F.Qs)(v!=null?v:"",l,L);if(H==null)throw new Error("InternalErrorInvalidCurrencyCode");let k=(0,y.mul)(T,H.multiplier);k=(0,y.toFixed)(k,0,0),A.nativeAmount=k,A.currencyCode=v}return{edgeParsedUri:A,parsedUri:h}}function R(l,p,f){if(l.publicAddress==null)throw new Error("InvalidPublicAddressError");if(f==null&&l.label==null&&l.message==null)return l.publicAddress;{let v="";f!=null&&(v+="amount="+f+"&"),(l.label!=null||l.message!=null)&&(typeof l.label=="string"&&(v+="label="+l.label+"&"),typeof l.message=="string"&&(v+="message="+l.message+"&")),v=v.substr(0,v.length-1);const L={scheme:p,path:l.publicAddress,query:v};return(0,m.qC)(L)}}},85309:function(Z,M,c){"use strict";c.r(M),c.d(M,{StellarTools:function(){return z},makeCurrencyEngine:function(){return H},makeCurrencyTools:function(){return j}});var y=c(77591),G=c(13620),m=c.n(G),x=c(24350),_=c(84564),F=c.n(_),N=c(79014),d=c(76714),w=c(82448),q=c(62177);const K=(0,w.su)({lastPagingToken:(0,w.Vk)(w.XC,"0"),accountSequence:(0,w.Vk)(w.mH,0)}),W=(0,w.su)({fee_charged:(0,w.su)({p50:w.XC,p70:w.XC,p95:w.XC})}),B=q.BQ,R=(0,w.su)({stellarKey:w.XC});var l=c(94935),p=c(84650),f=c(72681),v=Object.getPrototypeOf,L=Reflect.get,h=(E,e,t)=>L(v(E),t,e),u=(E,e,t)=>new Promise((s,n)=>{var r=i=>{try{o(t.next(i))}catch(g){n(g)}},a=i=>{try{o(t.throw(i))}catch(g){n(g)}},o=i=>i.done?s(i.value):Promise.resolve(i.value).then(r,a);o((t=t.apply(E,e)).next())});const J=2,A=15e3,P=3e4,U=5e3,C=100;class T extends p.P{constructor(e,t,s,n){super(e,t,s,n),this.getRecipientBalance=r=>u(this,null,function*(){var a;try{const i=(yield this.multicastServers("loadAccount",r)).balances.find(S=>S.asset_type==="native");if(i==null)return"0";const g=(0,d.aL)(this.currencyInfo.currencyCode,this.currencyInfo,this.allTokensMap);if(g==null)throw new Error("Unknown denom");return(0,y.mul)(i.balance,g.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:C,standard:C,high:C},this.minimumAddressBalance=this.networkInfo.baseReserve}setOtherData(e){this.otherData=K(e)}multicastServers(e,...t){return u(this,null,function*(){let s={result:"",server:""},n;switch(e){case"feeStats":n=this.networkInfo.stellarServers.map(r=>()=>u(this,null,function*(){const a=yield this.fetchCors(`${r}/fee_stats`),o=W(yield a.json());return{server:r,result:o}})),s=yield(0,d.QJ)(n);break;case"loadAccount":n=this.tools.stellarApiServers.map(r=>()=>u(this,null,function*(){const a=yield r[e](...t);return{server:r.serverName,result:a}})),s=yield(0,d.QJ)(n);break;case"ledgers":n=this.tools.stellarApiServers.map(r=>()=>u(this,null,function*(){const a=yield r.ledgers().order("desc").limit(1).call(),o=a.records[0].sequence;if(this.walletLocalData.blockHeight<=o&&this.tools.highestTxHeight<=o)return{server:r.serverName,result:a};throw new Error("Height out of date")})),s=yield(0,d.QJ)(n);break;case"payments":n=this.tools.stellarApiServers.map(r=>()=>u(this,null,function*(){const a=yield r.payments().limit(J).cursor(this.otherData.lastPagingToken).forAccount(...t).call();return{server:r.serverName,result:a}})),s=yield(0,d.QJ)(n);break;case"submitTransaction":s=yield(0,d.Wp)(this.tools.stellarApiServers.map(r=>u(this,null,function*(){const a=yield r[e](...t);return{server:r.serverName,result:a}})));break}return this.log(`multicastServers ${e} ${s.server} won`),s.result})}processTransaction(e){return u(this,null,function*(){const t=[];let s="",n="",r="",a,o,i;e.type==="create_account"?(r=e.source_account,a=e.account,n=e.starting_balance,s=this.currencyInfo.currencyCode):e.type==="payment"&&(r=e.from,a=e.to,n=e.amount,e.asset_type==="native"?s=this.currencyInfo.currencyCode:s=e.asset_type);const g=Date.parse(e.created_at)/1e3,S=(0,d.aL)(s,this.currencyInfo,this.allTokensMap);if(S!=null&&S.multiplier)o=(0,y.mul)(n,S.multiplier);else throw new Error("ErrorDenomNotFound");let b;try{b=yield e.transaction(),i=b.fee_charged.toString()}catch($){throw this.error("processTransaction rawTx Error ",$),$}a===this.walletLocalData.publicKey?(t.push(r),r===this.walletLocalData.publicKey&&(o="-"+i)):(o=(0,y.add)(o,i),o="-"+o);const D={blockHeight:b.ledger_attr>0?b.ledger_attr:0,currencyCode:s,date:g,isSend:o.startsWith("-"),memos:[],nativeAmount:o,networkFee:i,otherParams:{fromAddress:r,toAddress:a},ourReceiveAddresses:t,parentNetworkFee:"0",signedTx:"",txid:e.transaction_hash,walletId:this.walletId};return D.blockHeight>this.tools.highestTxHeight&&(this.tools.highestTxHeight=D.blockHeight),this.addTransaction(s,D),e.paging_token})}checkTransactionsInnerLoop(){return u(this,null,function*(){const e=this.walletLocalData.blockHeight,t=this.walletLocalData.publicKey;let s,n;for(;;)try{if(s?s=yield s.next():s=yield this.multicastServers("payments",t),s.records.length===0)break;for(const r of s.records)n=yield this.processTransaction(r)}catch(r){r.response&&r.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: ",r);return}this.transactionsChangedArray.length>0&&(this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[]),n&&(this.otherData.lastPagingToken=n,this.walletLocalDataDirty=!0),this.walletLocalData.lastAddressQueryHeight=e,this.tokenCheckTransactionsStatus.XLM=1,this.updateOnAddressesChecked()})}checkUnconfirmedTransactionsFetch(){return u(this,null,function*(){})}checkAccountInnerLoop(){return u(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 n;s.asset_type==="native"?(n=this.currencyInfo.currencyCode,this.log("--Got balances--")):n=s.asset_type;const r=(0,d.aL)(n,this.currencyInfo,this.allTokensMap);if(r!=null&&r.multiplier){const a=(0,y.mul)(s.balance,r.multiplier);this.updateBalance(n,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 u(this,null,function*(){try{const e=yield this.multicastServers("feeStats"),{p50:t,p70:s,p95:n}=e.fee_charged;this.fees={low:parseInt(t),standard:parseInt(s),high:parseInt(n)}}catch(e){this.error("queryFee Error ",e)}})}clearBlockchainCache(){return u(this,null,function*(){this.activatedAccountsCache={},this.pendingTransactionsIndex=0,this.pendingTransactionsMap={},yield h(T.prototype,this,"clearBlockchainCache").call(this),this.otherData.accountSequence=0})}startEngine(){return u(this,null,function*(){this.engineOn=!0,this.addToLoop("queryFee",P).catch(()=>{}),this.addToLoop("checkBlockchainInnerLoop",P).catch(()=>{}),this.addToLoop("checkAccountInnerLoop",A).catch(()=>{}),this.addToLoop("checkTransactionsInnerLoop",U).catch(()=>{}),yield h(T.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return u(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}makeSpend(e){return u(this,null,function*(){e=(0,f.s)(e,this.currencyInfo);const{edgeSpendInfo:t,currencyCode:s,nativeBalance:n,denom:r}=this.makeSpendCheck(e),{memos:a=[]}=t;if(t.spendTargets.length!==1)throw new Error("Error: only one output allowed");const{publicAddress:o}=t.spendTargets[0];let{nativeAmount:i}=t.spendTargets[0];if(o==null)throw new Error("makeSpend Missing publicAddress");if(i==null)throw new l.$D;let g=!1;const S=this.activatedAccountsCache[o];if(S===void 0)try{yield this.multicastServers("loadAccount",o),this.activatedAccountsCache[o]=!0}catch{this.activatedAccountsCache[o]=!1,g=!0}else S||(g=!0);if((0,y.eq)(i,"0"))throw new l.$D;const b=(0,y.div)(i,r.multiplier,7),D=new(m()).Account(this.walletLocalData.publicKey,this.otherData.accountSequence),$=t.networkFeeOption!==void 0&&t.networkFeeOption!=="custom"?this.fees[t.networkFeeOption]:C;let I=new(m()).TransactionBuilder(D,{fee:$});g?I=I.addOperation(m().Operation.createAccount({destination:o,startingBalance:b})):I=I.addOperation(m().Operation.payment({destination:o,asset:m().Asset.native(),amount:b}));for(const O of a)switch(O.type){case"hex":I=I.addMemo(m().Memo.hash(O.value));break;case"number":I=I.addMemo(m().Memo.id(O.value));break;case"text":I=I.addMemo(m().Memo.text(O.value));break}const V=I.build(),Y=V.fee.toString();i=(0,y.add)(Y,i);const ee=(0,y.sub)(n,this.networkInfo.baseReserve);if((0,y.gt)(i,ee))throw new l.C_;i=`-${i}`;const Q=this.pendingTransactionsIndex,te={blockHeight:0,currencyCode:s,date:0,isSend:i.startsWith("-"),memos:a,nativeAmount:i,networkFee:Y,otherParams:{idInternal:Q,fromAddress:this.walletLocalData.publicKey,toAddress:o},ourReceiveAddresses:[],signedTx:"",txid:"",walletId:this.walletId};return this.pendingTransactionsMap[Q]=V,this.pendingTransactionsIndex++,this.pendingTransactionsMap[this.pendingTransactionsIndex-20]&&delete this.pendingTransactionsMap[this.pendingTransactionsIndex-20],this.warn("Stellar transaction prepared"),this.warn(`idInternal: ${Q}`),this.warn(`${i} ${this.walletLocalData.publicKey} -> ${o}`),te})}signTx(e,t){return u(this,null,function*(){const s=R(t),n=(0,d.Xp)(e),r=(0,y.abs)((0,y.add)(e.nativeAmount,e.networkFee));yield this.checkRecipientMinimumBalance(this.getRecipientBalance,r,n.toAddress);try{const{idInternal:a}=n,o=this.pendingTransactionsMap[a];if(!o)throw new Error("ErrorInvalidTransaction");this.warn("Signing...");const i=m().Keypair.fromSecret(s.stellarKey);yield o.sign(i)}catch(a){throw this.error(`FAILURE signTx
|
|
2
2
|
${JSON.stringify((0,d.oX)(e))} `,a),a}return this.warn(`signTx
|
|
3
|
-
${(0,d.oX)(e)}`),e})}broadcastTx(e){return
|
|
4
|
-
${(0,d.oX)(e)}`);const
|
|
3
|
+
${(0,d.oX)(e)}`),e})}broadcastTx(e){return u(this,null,function*(){const t=(0,d.Xp)(e);try{const{idInternal:s}=t,n=this.pendingTransactionsMap[s];if(!n)throw new Error("ErrorInvalidTransaction");this.warn(`Broadcasting...
|
|
4
|
+
${(0,d.oX)(e)}`);const r=yield this.multicastServers("submitTransaction",n);e.txid=r.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
|
|
6
|
+
${JSON.stringify((0,d.oX)(e))} `,s),s}return e})}}function H(E,e,t,s){return u(this,null,function*(){const n=B(t),r=new T(E,e,n,s);return yield r.loadEngine(),r})}var k=(E,e,t)=>new Promise((s,n)=>{var r=i=>{try{o(t.next(i))}catch(g){n(g)}},a=i=>{try{o(t.throw(i))}catch(g){n(g)}},o=i=>i.done?s(i.value):Promise.resolve(i.value).then(r,a);o((t=t.apply(E,e)).next())});const X="web+stellar";class z{constructor(e){this.highestTxHeight=0;const{builtinTokens:t,currencyInfo:s,io:n,networkInfo:r}=e;this.builtinTokens=t,this.currencyInfo=s,this.io=n,this.networkInfo=r,m().Network.usePublicNetwork(),this.stellarApiServers=[];for(const a of this.networkInfo.stellarServers){const o=new(m()).Server(a);o.serverName=a,this.stellarApiServers.push(o)}}getDisplayPrivateKey(e){return k(this,null,function*(){return R(e.keys).stellarKey})}getDisplayPublicKey(e){return k(this,null,function*(){const{keys:t}=B(e);return t.publicKey})}checkAddress(e){try{return m().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:m().Keypair.fromRawEd25519Seed(t).secret()}})}importPrivateKey(e){return k(this,null,function*(){if(e.replace(/ /g,""),m().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:m().Keypair.fromSecret(e.keys.stellarKey).publicKey()}})}parseUri(e){return k(this,null,function*(){const t={};t[X]=!0;const s=`${X}:pay`;if(e.includes(s)){const i=F()(e,{},!0).query.destination;i&&(e=e.replace(s,`${X}:${i}`))}const{parsedUri:n,edgeParsedUri:r}=(0,N.k)(this.currencyInfo,e,t);if(!this.checkAddress(r.publicAddress||""))throw new Error("InvalidPublicAddressError");if(n.query.msg&&(r.metadata={notes:n.query.msg}),n.query.asset_code&&n.query.asset_code.toUpperCase()!=="XLM")throw new Error("ErrorInvalidCurrencyCode");if(n.query.memo_type&&n.query.memo_type!=="MEMO_ID")throw new Error("ErrorInvalidMemoType");if(n.query.memo){if((0,y.add)(n.query.memo,"0")!==n.query.memo)throw new Error("ErrorInvalidMemoId");r.uniqueIdentifier=n.query.memo}return r})}encodeUri(e){return k(this,arguments,function*(t,s=[]){if(!this.checkAddress(t.publicAddress))throw new Error("InvalidPublicAddressError");let r;if(typeof t.nativeAmount=="string"){const a="XLM",o=t.nativeAmount,i=(0,d.Qs)(a,this.currencyInfo,s);if(i==null)throw new Error("InternalErrorInvalidCurrencyCode");r=(0,y.div)(o,i.multiplier,7)}if(!r&&!t.label&&!t.message)return t.publicAddress;{let a=`destination=${t.publicAddress}&`;r&&(a+="amount="+r+"&"),(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:X,path:"pay",query:a};return(0,x.qC)(o)}})}}function j(E){return k(this,null,function*(){return new z(E)})}},17002:function(){},55024:function(){}}]);
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[92],{19156:function(
|
|
2
|
-
${(0,
|
|
3
|
-
${(0,
|
|
1
|
+
(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[92],{19156:function(J,T,d){"use strict";d.r(T),d.d(T,{TezosTools:function(){return L},makeCurrencyEngine:function(){return F},makeCurrencyTools:function(){return W}});var h=d(19971),I=d(39143),l=d(82448),D=d(62177);const P=(0,l.su)({numberTransactions:(0,l.Vk)(l.mH,0)}),K=(0,l.su)({level:l.mH,timestamp:l.XC,hash:l.XC,sender:(0,l.su)({address:l.XC}),bakerFee:l.mH,allocationFee:l.mH,target:(0,l.su)({address:l.XC}),amount:l.mH,status:l.XC}),b=(0,D.jd)((0,l.su)({publicKey:l.XC,publicKeyEd:l.XC})),E=(0,l.su)({mnemonic:l.XC,privateKey:l.XC});var m=d(77591),z=d(94935),N=d(84650),B=d(72681),f=d(76714),R=d(81649),X=Object.getPrototypeOf,x=Reflect.get,S=(y,t,e)=>x(X(y),e,t),a=(y,t,e)=>new Promise((s,n)=>{var r=o=>{try{c(e.next(o))}catch(u){n(u)}},i=o=>{try{c(e.throw(o))}catch(u){n(u)}},c=o=>o.done?s(o.value):Promise.resolve(o.value).then(r,i);c((e=e.apply(y,t)).next())});const H=15e3,j=3e4,$=5e3,M=(0,f.jT)(),A=R.j.currencyCode;class v extends N.P{constructor(t,e,s,n){super(t,e,s,n),this.walletInfo=b(s),this.networkInfo=t.networkInfo,this.fetchCors=(0,f.zR)(t.io)}setOtherData(t){this.otherData=P(t)}multicastServers(t,...e){return a(this,null,function*(){let s={result:"",server:"no server"},n;switch(t){case"getHead":{n=this.tools.tezosRpcNodes.map(i=>()=>a(this,null,function*(){const c=yield this.fetchCors(i+"/chains/main/blocks/head/header").then(function(o){return a(this,null,function*(){return yield o.json()})}).then(function(o){return o});return{server:i,result:c}})),s=yield(0,f.QJ)(n);break}case"getBalance":{n=this.tools.tezosRpcNodes.map(i=>()=>a(this,null,function*(){h.eztz.node.setProvider(i);const c=yield h.eztz.rpc.getBalance(e[0]);return{server:i,result:c}})),s=yield(0,f.QJ)(n);break}case"getNumberOfOperations":n=this.tools.tezosApiServers.map(r=>()=>a(this,null,function*(){const i=yield this.fetchCors(`${r}/v1/accounts/${e[0]}`).then(function(c){return a(this,null,function*(){return yield c.json()})}).then(function(c){return c.numTransactions});return{server:r,result:i}})),s=yield(0,f.QJ)(n);break;case"getTransactions":n=this.tools.tezosApiServers.map(r=>()=>a(this,null,function*(){const i=r.includes("tzkt")?"":`&p='${e[1]}&number=50`,c=yield this.fetchCors(`${r}/v1/accounts/${e[0]}/operations?type=transaction`+i).then(function(o){return a(this,null,function*(){return yield o.json()})});return{server:r,result:c}})),s=yield(0,f.QJ)(n);break;case"createTransaction":n=this.tools.tezosRpcNodes.map(r=>()=>a(this,null,function*(){h.eztz.node.setProvider(r);const i=yield h.eztz.rpc.transfer(e[0],e[1],e[2],e[3],e[4],null,this.networkInfo.limit.gas,this.networkInfo.limit.storage,this.networkInfo.fee.reveal).then(function(c){return c});return{server:r,result:i}})),s=yield(0,f.QJ)(n);break;case"injectOperation":{let r="";n=this.tools.tezosRpcNodes.map(i=>()=>a(this,null,function*(){h.eztz.node.setProvider(i);const c=yield h.eztz.rpc.inject(e[0],e[1]).catch(o=>{this.error("Error when injection operation: ",o);const u=this.formatError(o);throw!r&&u!==""&&(r=u),o});return this.multicastServers("silentInjection",i,e[1]),{server:i,result:c}})),s=yield(0,f.QJ)(n).catch(i=>{throw this.error("Error from waterfall: ",i),r!==""?new Error(r):i});break}case"silentInjection":{const r=this.tools.tezosRpcNodes.indexOf(e[0]),i=this.tools.tezosRpcNodes.slice(r+1);s=yield(0,f.Wp)(i.map(c=>a(this,null,function*(){h.eztz.node.setProvider(c);const o=yield h.eztz.rpc.silentInject(e[1]);return this.warn(`Injected silently to: ${c}`),{server:c,result:o}})));break}}return this.log(`XTZ multicastServers ${t} ${s.server} won with result ${s.result}`),s.result})}formatError(t){if(typeof t=="string")return t;try{if(t.error&&t.error==="Operation Failed"&&t.errors&&t.errors[0].id)return"Failed in preapply with an error code ("+t.errors[0].id+")";if(t[0]&&t[0].kind&&t[0].kind==="branch"&&t[0].id)return"Failed in preapply with an error code ("+t[0].id+")"}catch{}return""}processTezosTransaction(t){const e=K(t),s=this.walletLocalData.publicKey,n=[],r=A,i=new Date(e.timestamp).getTime()/1e3,c=e.level;let o=e.amount.toString();const u=(e.bakerFee+e.allocationFee).toString(),k=e.status==="failed";s===e.target.address?(n.push(s),e.sender.address===s&&(o="-"+u)):o="-"+(0,m.add)(o,u);const C={blockHeight:c,currencyCode:r,date:i,isSend:o.startsWith("-"),memos:[],nativeAmount:o,networkFee:u,otherParams:{},ourReceiveAddresses:n,signedTx:"",txid:t.hash,walletId:this.walletId};k||this.addTransaction(r,C)}checkTransactionsInnerLoop(){return a(this,null,function*(){const t=this.walletLocalData.publicKey;this.otherData.numberTransactions||(this.otherData.numberTransactions=0);const e=yield this.multicastServers("getNumberOfOperations",t);if(e!==this.otherData.numberTransactions){let s=[],n=0,r;this.tokenCheckTransactionsStatus.XTZ=.5;do r=yield this.multicastServers("getTransactions",t,n++),s=s.concat(r);while(r.length>0&&n<10);for(const i of s)this.processTezosTransaction(i);this.transactionsChangedArray.length>0&&(this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[]),this.otherData.numberTransactions=e,this.walletLocalDataDirty=!0}this.tokenCheckTransactionsStatus.XTZ=1,this.updateOnAddressesChecked()})}checkUnconfirmedTransactionsFetch(){return a(this,null,function*(){})}checkAccountInnerLoop(){return a(this,null,function*(){const t=A,e=this.walletLocalData.publicKey;typeof this.walletLocalData.totalBalances[t]>"u"&&(this.walletLocalData.totalBalances[t]="0");const s=yield this.multicastServers("getBalance",e);this.updateBalance(t,s)})}checkBlockchainInnerLoop(){return a(this,null,function*(){const e=(yield this.multicastServers("getHead")).level;this.walletLocalData.blockHeight!==e&&(this.walletLocalData.blockHeight=e,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight))})}clearBlockchainCache(){return a(this,null,function*(){yield S(v.prototype,this,"clearBlockchainCache").call(this)})}isBurn(t){return a(this,null,function*(){return t.kind==="origination"||t.kind==="transaction"&&t.destination.slice(0,2)==="tz"&&(yield this.multicastServers("getBalance",t.destination))==="0"})}startEngine(){return a(this,null,function*(){this.engineOn=!0,this.addToLoop("checkBlockchainInnerLoop",j),this.addToLoop("checkAccountInnerLoop",H),this.addToLoop("checkTransactionsInnerLoop",$),S(v.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return a(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}makeSpend(t){return a(this,null,function*(){return t=(0,B.s)(t,this.currencyInfo),yield M(()=>a(this,null,function*(){return yield this.makeSpendInner(t)}))})}makeSpendInner(t){return a(this,null,function*(){const{edgeSpendInfo:e,currencyCode:s,nativeBalance:n,denom:r}=this.makeSpendCheck(t),{memos:i=[]}=e;if(e.spendTargets.length!==1)throw new Error("Error: only one output allowed");const{publicAddress:c}=e.spendTargets[0];let{nativeAmount:o}=e.spendTargets[0];if(c==null)throw new Error("makeSpend Missing publicAddress");if(o==null)throw new z.$D;if((0,m.eq)(o,"0"))throw new z.$D;const u={pk:this.walletInfo.keys.publicKeyEd,pkh:this.walletInfo.keys.publicKey,sk:!1};let k,C=0,O;do try{k=yield this.multicastServers("createTransaction",u.pkh,u,c,(0,m.div)(o,r.multiplier,6),this.networkInfo.fee.transaction)}catch(g){O=g}while((typeof k>"u"||k.opOb.contents.length>2)&&C++<5);if(typeof k>"u")throw O;let w="0";for(const g of k.opOb.contents)w=(0,m.add)(w,g.fee),(yield this.isBurn(g))&&(w=(0,m.add)(w,this.networkInfo.fee.burn));if(o=(0,m.add)(o,w),(0,m.gt)(o,n))throw new z.C_;return o="-"+o,{blockHeight:0,currencyCode:s,date:0,isSend:o.startsWith("-"),memos:i,nativeAmount:o,networkFee:w,otherParams:{idInternal:0,fromAddress:this.walletLocalData.publicKey,toAddress:c,fullOp:k},ourReceiveAddresses:[],signedTx:"",txid:"",walletId:this.walletId}})}signTx(t,e){return a(this,null,function*(){const s=E(e),n=(0,f.Xp)(t);if(t.signedTx===""){const r=s.privateKey,i=h.eztz.crypto.sign(n.fullOp.opbytes,r,h.eztz.watermark.generic);n.fullOp.opbytes=i.sbytes,n.fullOp.opOb.signature=i.edsig,t.signedTx=i.sbytes}return this.warn(`signTx
|
|
2
|
+
${(0,f.oX)(t)}`),t})}broadcastTx(t){return a(this,null,function*(){const e=(0,f.Xp)(t),s=e.fullOp.opbytes,n=e.fullOp.opOb,r=yield this.multicastServers("injectOperation",n,s);return t.txid=r.hash,t.date=Date.now()/1e3,this.warn(`SUCCESS broadcastTx
|
|
3
|
+
${(0,f.oX)(t)}`),t})}}function F(y,t,e,s){return a(this,null,function*(){const n=b(e),r=new v(y,t,n,s);return yield r.loadEngine(),r})}var U=d(48764).Buffer,p=(y,t,e)=>new Promise((s,n)=>{var r=o=>{try{c(e.next(o))}catch(u){n(u)}},i=o=>{try{c(e.throw(o))}catch(u){n(u)}},c=o=>o.done?s(o.value):Promise.resolve(o.value).then(r,i);c((e=e.apply(y,t)).next())});class L{constructor(t){const{builtinTokens:e,currencyInfo:s,io:n,networkInfo:r}=t;this.builtinTokens=e,this.currencyInfo=s,this.io=n,this.networkInfo=r,this.tezosRpcNodes=[...this.networkInfo.tezosRpcNodes],this.tezosApiServers=[...this.networkInfo.tezosApiServers]}getDisplayPrivateKey(t){return p(this,null,function*(){return E(t.keys).mnemonic})}getDisplayPublicKey(t){return p(this,null,function*(){const{keys:e}=b(t);return e.publicKey})}checkAddress(t){try{return h.eztz.crypto.checkAddress(t)}catch{return!1}}importPrivateKey(t){return p(this,null,function*(){if(/\d/.test(t))throw new Error("Input must be mnemonic phrase");if(t.split(" ").length!==24)throw new Error("Mnemonic phrase must be 24 words long");const n=h.eztz.crypto.generateKeys(t,"");return this.derivePublicKey({type:"wallet:tezos",id:"fake",keys:n}),{mnemonic:n.mnemonic,privateKey:n.sk}})}createPrivateKey(t){return p(this,null,function*(){if(t.replace("wallet:","")==="tezos"){const s=U.from(this.io.random(32)).toString("hex"),n=h.eztz.library.bip39.entropyToMnemonic(s),r=h.eztz.crypto.generateKeys(n,"").sk;return{mnemonic:n,privateKey:r}}else throw new Error("InvalidWalletType")})}derivePublicKey(t){return p(this,null,function*(){if(t.type.replace("wallet:","")==="tezos"){const s=h.eztz.crypto.generateKeys(t.keys.mnemonic,"");return{publicKey:s.pkh,publicKeyEd:s.pk}}else throw new Error("InvalidWalletType")})}parseUri(t){return p(this,null,function*(){let e,s,n;if(this.checkAddress(t))e=t;else if(t.slice(0,10)==="web+tezos:"){if(s=(0,I.decodeMainnet)(t),!s[0]||!s[0].content)throw new Error("InvalidUriError");if(n=s[0].content,e=n.destination,!this.checkAddress(e))throw new Error("InvalidPublicAddressError")}else throw new Error("InvalidUriError");const r={publicAddress:e};return r.nativeAmount=n!=null&&n.amount!=="0"?n.amount:void 0,r.currencyCode="XTZ",r})}encodeUri(t){return p(this,null,function*(){if(!this.checkAddress(t.publicAddress))throw new Error("InvalidPublicAddressError");if(t.currencyCode!=="XTZ")throw new Error("InvalidCurrencyCodeError");const n={kind:"transaction",amount:typeof t.nativeAmount=="string"?t.nativeAmount:"0",destination:t.publicAddress};return(0,I.encodeMainnet)([{content:n}])})}}function W(y){return p(this,null,function*(){return new L(y)})}},75992:function(){}}]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[5],{86352:function(mt,Z,h){h.d(Z,{Vn:function(){return tt},lF:function(){return j},sp:function(){return V}});var m=h(76714),F=(t,P,x)=>new Promise((R,H)=>{var L=p=>{try{T(x.next(p))}catch(f){H(f)}},y=p=>{try{T(x.throw(p))}catch(f){H(f)}},T=p=>p.done?R(p.value):Promise.resolve(p.value).then(L,y);T((x=x.apply(t,P)).next())});const G=["https://info1.edge.app","https://info2.edge.app"];function Y(t,P,x){return F(this,arguments,function*(R,H,L,y=5e3,T=fetch){const p=R.map(f=>()=>F(this,null,function*(){const M=yield T(f+"/"+H,L);if(typeof M!="object"){const b=`Invalid return value ${H} in ${f}`;throw console.log(b),new Error(b)}return M}));return yield(0,m.QJ)(p,y)})}function j(t,P,x,R,H=5e3,L){return F(this,null,function*(){const y=yield Y((0,m.Sy)(P),x,R,H,L);if(!y.ok){const f=yield y.text();throw console.error(f),new Error(`Error fetching ${x}: ${f}`)}const T=yield y.json();return t(T)})}function q(t,P,x,R=5e3,H){return F(this,null,function*(){return yield Y((0,m.Sy)(t),P,x,R,H)})}const tt=(t,P,x,R)=>F(void 0,null,function*(){return yield q(G,t,P,x,R)}),V=t=>Object.keys(t).map(P=>{const x=t[P];return x==null?P:`${P}=${encodeURIComponent(x)}`}).join("&")},79014:function(mt,Z,h){h.d(Z,{Q:function(){return L},k:function(){return H}});var m=h(77591),F=h.n(m),G=h(24350),Y=h(84564),j=h.n(Y),q=h(76714),tt=Object.defineProperty,V=Object.getOwnPropertySymbols,t=Object.prototype.hasOwnProperty,P=Object.prototype.propertyIsEnumerable,x=(y,T,p)=>T in y?tt(y,T,{enumerable:!0,configurable:!0,writable:!0,value:p}):y[T]=p,R=(y,T)=>{for(var p in T||(T={}))t.call(T,p)&&x(y,p,T[p]);if(V)for(var p of V(T))P.call(T,p)&&x(y,p,T[p]);return y};function H(y,T,p,f,M=[]){const b=R({},j()(T,{},!0)),et=T.startsWith(`${y.pluginId}://`);if(b.protocol!=null&&(b.protocol=b.protocol.replace(":","")),b.protocol!=null&&b.protocol!==""&&!p[b.protocol])throw new Error(`Uri protocol '${b.protocol}' is not supported for ${y.pluginId}.`);if(b.host===""&&b.pathname==="")throw new Error("Path and host not found in uri.");const U={publicAddress:b.host!==""?b.host:b.pathname.split("/")[0]},nt=b.query.label,rt=b.query.message,it=b.query.category;(nt!=null||rt!=null||it!=null||et)&&(U.metadata={},U.metadata.name=nt,U.metadata.notes=rt,U.metadata.category=it,U.metadata.gateway=et!=null?et:!1);const st=b.query.amount;if(st!=null&&typeof st=="string"){f==null&&(f=y.currencyCode);const ot=(0,q.Qs)(f!=null?f:"",y,M);if(ot==null)throw new Error("InternalErrorInvalidCurrencyCode");let at=(0,m.mul)(st,ot.multiplier);at=(0,m.toFixed)(at,0,0),U.nativeAmount=at,U.currencyCode=f}return{edgeParsedUri:U,parsedUri:b}}function L(y,T,p){if(y.publicAddress==null)throw new Error("InvalidPublicAddressError");if(p==null&&y.label==null&&y.message==null)return y.publicAddress;{let f="";p!=null&&(f+="amount="+p+"&"),(y.label!=null||y.message!=null)&&(typeof y.label=="string"&&(f+="label="+y.label+"&"),typeof y.message=="string"&&(f+="message="+y.message+"&")),f=f.substr(0,f.length-1);const M={scheme:T,path:y.publicAddress,query:f};return(0,G.qC)(M)}}},58780:function(mt,Z,h){h.r(Z),h.d(Z,{TronTools:function(){return _t},makeCurrencyEngine:function(){return Te},makeCurrencyTools:function(){return Ce}});var m=h(77591),F=h(2153),G=h(21964),Y=h.n(G),j=h(48367),q=h.n(j),tt=h(3666),V=h.n(tt),t=h(82448),P=h(86352);const x=s=>{if(s.includes("@"))return R(s)?[!0,s.toLowerCase()]:[!1,"Invalid Email"];if(s.includes("+"))return s="+"+s.replace(/[^\d]+/g,""),s.length!==14?[!1,"Invalid Phone number"]:s.substring(0,3)!=="+55"?[!1,"Not brasilian number"]:[!0,s];if(s.length===36)return[!0,s];if(s.length===18)return/^\d{2}\.\d{3}\.\d{3}\/\d{4}-\d{2}$/.test(s)?L(s)?(s=s.replace(/[^\d]+/g,""),[!0,s]):[!1,"invalid cnpj"]:[!1,"invalid pixkey"];if(s.length===13&&/^\d+$/.test(s))return s.substr(0,2)!=="55"?[!1,"invalid pixkey"]:[!0,"+"+s];if(s.length<11)return[!1,"invalid pixkey"];if(s.length===14){if(/^\d+$/.test(s))return L(s)?[!0,s]:[!1,"invalid pixkey"];if(/^\d{3}\.\d{3}\.\d{3}-\d{2}$/.test(s))return H(s)?[!0,s.replace(/[^\d]+/g,"")]:[!1,"invalid cpf"]}return s.length===11?/^\d+$/.test(s)?H(s)?[!0,s.replace(/[^\d]+/g,"")]:s.charAt(0)==="0"?[!1,"invalid pixkey"]:[!0,"+55"+s]:[!1,"invalid pixkey"]:(s=s.replace(/[^\d]+/g,""),s.length===12?s.charAt(0)!=="0"?[!1,"invalid pixkey"]:[!0,"+55"+s.substr(1)]:s.length===11?H(s)?[!0,s]:[!0,"+55"+s]:[!1,"invalid pixkey"])};function R(s){return/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(String(s).toLowerCase())}function H(s){if(s=s.replace(/[^\d]+/g,""),s===""||s.length!==11||s==="00000000000"||s==="11111111111"||s==="22222222222"||s==="33333333333"||s==="44444444444"||s==="55555555555"||s==="66666666666"||s==="77777777777"||s==="88888888888"||s==="99999999999")return!1;let e,n;e=0;for(let r=1;r<=9;r++)e=e+parseInt(s.substring(r-1,r))*(11-r);if(n=e*10%11,(n===10||n===11)&&(n=0),n!==parseInt(s.substring(9,10)))return!1;e=0;for(let r=1;r<=10;r++)e=e+parseInt(s.substring(r-1,r))*(12-r);return n=e*10%11,(n===10||n===11)&&(n=0),n===parseInt(s.substring(10,11))}function L(s){if(s=s.replace(/[^\d]+/g,""),s===""||s.length!==14||s==="00000000000000"||s==="11111111111111"||s==="22222222222222"||s==="33333333333333"||s==="44444444444444"||s==="55555555555555"||s==="66666666666666"||s==="77777777777777"||s==="88888888888888"||s==="99999999999999")return!1;let e=s.length-2,n=s.substring(0,e);const r=s.substring(e);let a=0,o=e-7;for(let i=e;i>=1;i--)a+=Number(n.charAt(e-i))*o--,o<2&&(o=9);let c=a%11<2?0:11-a%11;if(c!==Number(r.charAt(0)))return!1;e=e+1,n=s.substring(0,e),a=0,o=e-7;for(let i=e;i>=1;i--)a+=Number(n.charAt(e-i))*o--,o<2&&(o=9);return c=a%11<2?0:11-a%11,c===Number(r.charAt(1))}function y(s,e=!1){const n=p(s),r=[0,4129,8258,12387,16516,20645,24774,28903,33032,37161,41290,45419,49548,53677,57806,61935,4657,528,12915,8786,21173,17044,29431,25302,37689,33560,45947,41818,54205,50076,62463,58334,9314,13379,1056,5121,25830,29895,17572,21637,42346,46411,34088,38153,58862,62927,50604,54669,13907,9842,5649,1584,30423,26358,22165,18100,46939,42874,38681,34616,63455,59390,55197,51132,18628,22757,26758,30887,2112,6241,10242,14371,51660,55789,59790,63919,35144,39273,43274,47403,23285,19156,31415,27286,6769,2640,14899,10770,56317,52188,64447,60318,39801,35672,47931,43802,27814,31879,19684,23749,11298,15363,3168,7233,60846,64911,52716,56781,44330,48395,36200,40265,32407,28342,24277,20212,15891,11826,7761,3696,65439,61374,57309,53244,48923,44858,40793,36728,37256,33193,45514,41451,53516,49453,61774,57711,4224,161,12482,8419,20484,16421,28742,24679,33721,37784,41979,46042,49981,54044,58239,62302,689,4752,8947,13010,16949,21012,25207,29270,46570,42443,38312,34185,62830,58703,54572,50445,13538,9411,5280,1153,29798,25671,21540,17413,42971,47098,34713,38840,59231,63358,50973,55100,9939,14066,1681,5808,26199,30326,17941,22068,55628,51565,63758,59695,39368,35305,47498,43435,22596,18533,30726,26663,6336,2273,14466,10403,52093,56156,60223,64286,35833,39896,43963,48026,19061,23124,27191,31254,2801,6864,10931,14994,64814,60687,56684,52557,48554,44427,40424,36297,31782,27655,23652,19525,15522,11395,7392,3265,61215,65342,53085,57212,44955,49082,36825,40952,28183,32310,20053,24180,11923,16050,3793,7920];let a=65535;for(let i=0;i<n.length;i++){const u=(n[i]^a>>8)&255;a=r[u]^a<<8}const o=(a^0)&65535,c=T(o,4);return e?c.slice(2)+c.slice(0,2):c}function T(s,e){const n=s.toString(16).toUpperCase();return e>0?("0".repeat(e)+n).slice(-e):n.length%2===0?n:"0"+n}function p(s){let e=0;const n=s.length;let r=0,a=Math.max(32,n+(n>>>1)+7),o=new Uint8Array(a>>>3<<3);for(;e<n;){let c=s.charCodeAt(e++);if(c>=55296&&c<=56319){if(e<n){const i=s.charCodeAt(e);(i&64512)===56320&&(++e,c=((c&1023)<<10)+(i&1023)+65536)}if(c>=55296&&c<=56319)continue}if(r+4>o.length){a+=8,a*=1+e/s.length*2,a=a>>>3<<3;const i=new Uint8Array(a);i.set(o),o=i}if((c&4294967168)===0){o[r++]=c;continue}else if((c&4294965248)===0)o[r++]=c>>>6&31|192;else if((c&4294901760)===0)o[r++]=c>>>12&15|224,o[r++]=c>>>6&63|128;else if((c&4292870144)===0)o[r++]=c>>>18&7|240,o[r++]=c>>>12&63|128,o[r++]=c>>>6&63|128;else continue;o[r++]=c&63|128}return o.slice!=null?o.slice(0,r):o.subarray(0,r)}var f=h(76714),M=(s,e,n)=>new Promise((r,a)=>{var o=l=>{try{i(n.next(l))}catch(u){a(u)}},c=l=>{try{i(n.throw(l))}catch(u){a(u)}},i=l=>l.done?r(l.value):Promise.resolve(l.value).then(o,c);i((n=n.apply(s,e)).next())});const b=60*60*24*7,et=(0,t._C)((0,t.su)({status:(0,t.Wf)("ok"),msg:t.XC,data:(0,t.su)({amount:t.mH,name:t.XC,key:t.XC,timeout:t.mH})}),(0,t.su)({status:(0,t.Wf)("failed"),msg:t.XC})),yt=(0,t.su)({status:(0,t.Wf)("ok"),msg:t.XC,data:(0,t.su)({amount_usd:t.XC,price_brl:t.XC,total_brl:t.XC,fee_brl:t.XC,send_brl:t.XC,timeout:t.mH,amount_txusdt:t.XC,price_txusdt:t.mH,value_usd:t.XC,total_txusdt:t.XC})}),U=(s,e,n,r,a)=>M(void 0,null,function*(){const o=new Date,c=Object.keys(e).find(u=>e[u].currencyCode==="USDT");if(c==null)return;const i=e[c],l=(0,m.mul)("0.5",i.denominations[0].multiplier);if(n.length>36){const u=y(n.slice(0,-4));if(!n.endsWith(u))return;try{const d=(0,f.zR)(s),w=encodeURIComponent(n),k=yield(0,P.lF)(et,["https://connect.smartpay.com.vc"],`api/pix/qrdecode?qrcode=${w}`,void 0,void 0,d);if(k.status!=="ok")throw new Error(k.msg);const{data:_}=k,{amount:A,key:S,name:z,timeout:C}=_;if(C>0&&C<120)throw new Error("ErrorPixExpired");let E,v;if(A!==0){const D={type:"buy",profile:"transfer",currency:"brl",conv:"txusdt",target:"amount",user:a,amount:A===0?100:A},B=(0,P.sp)(D),J=yield(0,P.lF)(yt,["https://connect.smartpay.com.vc"],`api/swapix/swapquote?${B}`,void 0,void 0,d),{data:ct}=J,{amount_txusdt:K,timeout:W}=ct;if(W>0&&W<120)throw new Error("ErrorPixExpired");E=(0,m.mul)(K,i.denominations[0].multiplier);const N=Math.min(C>0?C:b,W>0?W:b);v=new Date(o.getTime()+N*1e3)}return{currencyCode:"USDT",metadata:{name:z,notes:`To PIX: ${S}`},expireDate:v,nativeAmount:E,minNativeAmount:l,publicAddress:r,uniqueIdentifier:n}}catch(d){console.log(`Could not query PIX address ${n}: ${d.message}`)}}else{const[u,d]=x(n);return u?{currencyCode:"USDT",minNativeAmount:l,metadata:{name:`PIX: ${d}`,notes:`To PIX: ${d}`},publicAddress:"TUmgPbM5J6om7Z2PJjzrbSEbXit84ZhVCj",uniqueIdentifier:d}:void 0}});var nt=h(20918),rt=h(79014),it=h(62177);const st=(0,t.su)({smartPayPublicAddress:(0,t.Zz)(t.XC,"TUmgPbM5J6om7Z2PJjzrbSEbXit84ZhVCj"),smartPayUserId:(0,t.Zz)(t.XC,"edge")}),ot=(0,t.su)({txid:t.XC,timestamp:t.mH}),at=(0,t.su)({txQueryCache:(0,t.Vk)((0,t.su)({mainnet:ot,trc20:ot}),()=>({mainnet:{txid:"",timestamp:0},trc20:{txid:"",timestamp:0}}))}),gt=(0,t.Wf)("ENERGY"),It=(0,t.Wf)("BANDWIDTH"),ut=(0,t._C)(gt,It),Pt=(0,t.Wf)("ENERGY_V2"),St=(0,t.Wf)("BANDWIDTH_V2"),pt=(0,t._C)(Pt,St),Dt=(0,t.su)({type:(0,t.Wf)("remove"),params:(0,t.su)({resource:ut})}),Bt=(0,t.su)({type:(0,t.Wf)("addV2"),params:(0,t.su)({nativeAmount:t.XC,resource:pt})}),Ht=(0,t.su)({type:(0,t.Wf)("removeV2"),params:(0,t.su)({nativeAmount:t.XC,resource:pt})}),Nt=(0,t.su)({chainParameter:(0,t._2)((0,t.su)({key:t.XC,value:(0,t.Zz)(t.mH)}))}),Ot=(0,t.su)({blockID:t.XC,block_header:(0,t.su)({raw_data:(0,t.su)({number:t.mH,timestamp:t.mH})})}),vt=(0,t.su)({freeNetUsed:(0,t.Vk)(t.mH,0),freeNetLimit:t.mH,EnergyUsed:(0,t.Vk)(t.mH,0),EnergyLimit:(0,t.Vk)(t.mH,0)}),Rt=(0,t.su)({frozen:(0,t.Zz)((0,t.vq)((0,t.su)({frozen_balance:t.mH,expire_time:t.mH}))),account_resource:(0,t.su)({frozen_balance_for_energy:(0,t.Zz)((0,t.su)({frozen_balance:t.mH,expire_time:t.mH}))}),frozenV2:(0,t.vq)((0,t.su)({amount:(0,t.Zz)(t.mH)}),(0,t.su)({type:gt,amount:(0,t.Zz)(t.mH)}),(0,t.su)({type:(0,t.Wf)("TRON_POWER")})),balance:(0,t.Vk)(t.mH,0)}),zt=(0,t.su)({constant_result:(0,t.vq)(t.XC)}),Ft=(0,t.su)({ret:(0,t._2)((0,t.su)({contractRet:t.XC,fee:t.mH})),txID:t.XC,unfreeze_amount:(0,t.Zz)(t.mH),blockNumber:t.mH,block_timestamp:t.mH,raw_data:(0,t.su)({contract:(0,t._2)(t.JC)})}),Lt=(0,t.su)({transaction_id:t.XC,token_info:(0,t.su)({address:t.XC}),block_timestamp:t.mH,from:t.XC,to:t.XC,type:t.XC,value:t.XC}),Ut=(0,t.su)({fee:(0,t.Zz)(t.mH,0),blockNumber:t.mH}),Xt=(0,t.su)({parameter:(0,t.su)({value:(0,t.su)({amount:t.mH,owner_address:t.XC,to_address:t.XC})}),type:(0,t.Wf)("TransferContract")}),Kt=(0,t.su)({parameter:(0,t.su)({value:(0,t.su)({data:t.XC,owner_address:t.XC,contract_address:t.XC})}),type:(0,t.Wf)("TriggerSmartContract")}),Wt=(0,t.su)({parameter:(0,t.su)({value:(0,t.su)({frozen_balance:t.mH,resource_type:ut,owner_address:t.XC})}),type:(0,t.Wf)("FreezeBalanceContract")}),Vt=(0,t.su)({parameter:(0,t.su)({value:(0,t.su)({resource_type:ut,owner_address:t.XC})}),type:(0,t.Wf)("UnfreezeBalanceContract")}),Mt=(0,t.su)({parameter:(0,t.su)({value:(0,t.su)({frozen_balance:t.mH,owner_address:t.XC})}),type:(0,t.Wf)("FreezeBalanceV2Contract")}),$t=(0,t.su)({parameter:(0,t.su)({value:(0,t.su)({unfreeze_balance:t.mH,owner_address:t.XC})}),type:(0,t.Wf)("UnfreezeBalanceV2Contract")}),Jt=s=>(0,t.su)({data:(0,t._2)(s),success:t.jK,meta:(0,t.su)({links:(0,t.Zz)((0,t.su)({next:t.XC})),page_size:t.mH})}),Zt=(0,t.su)({energy_used:t.mH,transaction:(0,t.su)({ret:(0,t._2)((0,t.su)({ret:(0,t.Zz)(t.XC)}))})}),Yt=(0,t.su)({result:t.jK,txid:t.XC,message:t.XC}),Tt=it.BQ,dt=(0,t.su)({tronMnemonic:(0,t.Zz)(t.XC),tronKey:t.XC,derivationPath:(0,t.Zz)(t.XC)});var wt=h(94935),Q=h(35620),Qt=h(84650),Gt=h(68142),jt=h.n(Gt),qt=h(48764).Buffer;const{utils:{crypto:{decode58Check:te,getBase58CheckAddress:ee}}}=V(),O=s=>{const e=te(s);return Q.YU.stringify(e)},$=s=>{const e=Q.YU.parse(s);return ee(Array.from(e))},Ct="a9059cbb",be=s=>{if(!s.startsWith(Ct))throw new Error("Not a TRC20 data payload");const e=s.replace(Ct,""),n=`41${e.substring(24,64)}`,r=$(n),a=e.substring(64,128),o=hexToDecimal(a);return[r,o]},ne=(s,e)=>{const n=O(s).replace(/^(41)/,"0x"),r=jt().simpleEncode("transfer(address,uint256):(uint256)",n,e);return qt.from(r).toString("hex")};var re=h(48764).Buffer,se=Object.defineProperty,oe=Object.defineProperties,ae=Object.getOwnPropertyDescriptors,bt=Object.getOwnPropertySymbols,ce=Object.getPrototypeOf,ie=Object.prototype.hasOwnProperty,le=Object.prototype.propertyIsEnumerable,ue=Reflect.get,At=(s,e,n)=>e in s?se(s,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[e]=n,ht=(s,e)=>{for(var n in e||(e={}))ie.call(e,n)&&At(s,n,e[n]);if(bt)for(var n of bt(e))le.call(e,n)&&At(s,n,e[n]);return s},de=(s,e)=>oe(s,ae(e)),Et=(s,e,n)=>ue(ce(s),n,e),g=(s,e,n)=>new Promise((r,a)=>{var o=l=>{try{i(n.next(l))}catch(u){a(u)}},c=l=>{try{i(n.throw(l))}catch(u){a(u)}},i=l=>l.done?r(l.value):Promise.resolve(l.value).then(o,c);i((n=n.apply(s,e)).next())});const{utils:{crypto:{signTransaction:he},transaction:{txJsonToPb:fe,txPbToTxID:me}}}=V(),ye=(0,f.jT)(),kt=2e4,ge=2e4,pe=3e3,ve=60*10*1e3;class lt extends Qt.P{constructor(e,n,r,a){super(e,n,r,a);const{networkInfo:o}=e;this.fetchCors=(0,f.zR)(e.io),this.networkInfo=o,this.recentBlock={hash:"0",number:0,timestamp:0},this.accountResources={BANDWIDTH:0,ENERGY:0},this.networkFees={getCreateAccountFee:1e5,getTransactionFee:1e3,getEnergyFee:280,getMemoFee:1e6},this.accountExistsCache={},this.energyEstimateCache={},this.processTRXTransaction=this.processTRXTransaction.bind(this),this.processTRC20Transaction=this.processTRC20Transaction.bind(this),this.stakingStatus={stakedAmounts:[{nativeAmount:"0",otherParams:{type:"BANDWIDTH"}},{nativeAmount:"0",otherParams:{type:"ENERGY"}}]}}setOtherData(e){this.otherData=at(e)}fetch(e,n){return g(this,arguments,function*(r,a,o={}){const c=r+a,i=yield this.fetchCors(c,o);if(!i.ok||i.status!==200)throw this.log(`The server returned error code ${i.status} for ${c}`),new Error(`The server returned error code ${i.status} for ${c}`);const l=yield i.json();if(typeof l!="object"){const u=`Invalid return value ${a} in ${r}`;throw this.log(u),new Error(u)}return{server:r,result:l}})}checkBlockchainInnerLoop(){return g(this,null,function*(){try{const e=yield this.multicastServers("trx_blockNumber","/wallet/getnowblock"),n=Ot(e),r=n.block_header.raw_data.number;Object.assign(this.recentBlock,{hash:n.blockID,number:r,timestamp:n.block_header.raw_data.timestamp}),this.walletLocalData.blockHeight!==r&&(this.checkDroppedTransactionsThrottled(),this.walletLocalData.blockHeight=r,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight))}catch(e){this.log.error("Error fetching height: ",e)}})}checkTokenBalances(){return g(this,null,function*(){const e=O(this.walletLocalData.publicKey);for(const n of this.enabledTokens){const r=this.allTokens.find(c=>c.currencyCode===n);if((r==null?void 0:r.contractAddress)==null)continue;const o={contract_address:O(r.contractAddress),function_selector:"balanceOf(address)",parameter:(0,f.gc)(e,32),owner_address:e};try{const c=yield this.multicastServers("trx_getBalance","/wallet/triggerconstantcontract",o),i=zt(c);r!=null&&this.updateBalance(r.currencyCode,(0,f.Z8)(i.constant_result[0]))}catch(c){this.log.error(`Failed to get balance of ${n}`,c)}}})}checkAccountInnerLoop(){return g(this,null,function*(){const e={address:O(this.walletLocalData.publicKey)};try{const n=yield this.multicastServers("trx_getBalance","/wallet/getaccount",e),r=(0,t.Vk)(Rt)(n);if(r==null){this.updateBalance(this.currencyInfo.currencyCode,"0");return}this.updateBalance(this.currencyInfo.currencyCode,r.balance.toString());const{frozen:a,account_resource:{frozen_balance_for_energy:o}}=r,c=[];if(a!=null){const u=a[0].frozen_balance.toString(),d=new Date(a[0].expire_time);c.push({nativeAmount:u,unlockDate:d,otherParams:{type:"BANDWIDTH"}})}if(o!=null){const u=o.frozen_balance.toString(),d=new Date(o.expire_time);c.push({nativeAmount:u,unlockDate:d,otherParams:{type:"ENERGY"}})}const[i,l]=r.frozenV2;i.amount!=null&&c.push({nativeAmount:i.amount.toFixed(),otherParams:{type:"BANDWIDTH_V2"}}),l.amount!=null&&c.push({nativeAmount:l.amount.toFixed(),otherParams:{type:"ENERGY_V2"}}),this.stakingStatus={stakedAmounts:c},this.currencyEngineCallbacks.onStakingStatusChanged(ht({},this.stakingStatus))}catch(n){this.log.error("Error checking TRX address balance: ",n)}try{const n=yield this.multicastServers("trx_getAccountResource","/wallet/getaccountresource",e),r=vt(n);this.accountResources={BANDWIDTH:r.freeNetLimit-r.freeNetUsed,ENERGY:r.EnergyLimit-r.EnergyUsed}}catch(n){this.log.error("Error checking TRX address resources: ",n)}})}queryTransactions(){return g(this,null,function*(){return yield ye(()=>g(this,null,function*(){return yield this.queryTransactionsInnerLoop()}))})}queryTransactionsInnerLoop(){return g(this,null,function*(){try{yield this.fetchTrxTransactions(),yield this.fetchTrc20Transactions()}catch(e){throw this.log.error("Error checkTransactionsFetch fetchTrxTransactions: ",e),e}this.transactionsChangedArray.length>0&&(this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[]);for(const e of this.enabledTokens)this.tokenCheckTransactionsStatus[e]=1;this.updateOnAddressesChecked()})}fetchTrxTransactions(){return g(this,null,function*(){let e=!1;for(;!e;)e=yield this.fetchTransactions("mainnet",Ft,this.processTRXTransaction)})}fetchTrc20Transactions(){return g(this,null,function*(){let e=!1;for(;!e;)e=yield this.fetchTransactions("trc20",Lt,this.processTRC20Transaction)})}fetchTransactions(e,n,r){return g(this,null,function*(){var a;const o=e==="trc20"?e:"",c=this.otherData.txQueryCache[e].timestamp,i=`/v1/accounts/${this.walletLocalData.publicKey}/transactions/${o}?limit=200&order_by=block_timestamp,asc&min_timestamp=${c}`,l=yield this.multicastServers("trx_getTransactions",i),{data:u,meta:d,success:w}=Jt(n)(l),k=((a=d==null?void 0:d.links)==null?void 0:a.next)==null;if(!w)throw new Error("Failed to query TRX transactions");for(const _ of u){const{timestamp:A,txid:S}=yield r(_);this.otherData.txQueryCache[e].txid=S,this.otherData.txQueryCache[e].timestamp=A,this.walletLocalDataDirty=!0}return k})}processTRXTransaction(e){const{txID:n,block_timestamp:r,blockNumber:a,ret:o,unfreeze_amount:c,raw_data:{contract:i}}=e,l={txid:n,timestamp:r};if(n===this.otherData.txQueryCache.mainnet.txid||o.length<1)return l;const u=[];for(const d of i){const w=(0,t.Vk)(Xt)(d);if(w!=null){const{parameter:{value:{amount:C,owner_address:E,to_address:v}}}=w,{contractRet:I,fee:D}=o[0];let B=D.toString();const J=$(E),ct=$(v);let K=C.toString();if(J===this.walletLocalData.publicKey)J===ct?K=(0,m.mul)(B,"-1"):K=(0,m.mul)((0,m.add)(K,B),"-1"),I!=="SUCCESS"&&(K="0");else{if(I!=="SUCCESS")return l;u.push(this.walletLocalData.publicKey),B="0"}const{currencyCode:W}=this.currencyInfo,N={txid:n,date:Math.floor(r/1e3),currencyCode:W,blockHeight:a,nativeAmount:K,isSend:K.startsWith("-"),networkFee:B,ourReceiveAddresses:u,signedTx:"",walletId:this.walletId};return this.addTransaction(W,N),l}const k=(0,t.Vk)(Kt)(d);if(k!=null){const{parameter:{value:{owner_address:C}}}=k;if($(C)!==this.walletLocalData.publicKey)break;const E=o[0].fee.toString(),{currencyCode:v}=this.currencyInfo,I={txid:n,date:Math.floor(r/1e3),currencyCode:v,blockHeight:a,nativeAmount:(0,m.mul)(E,"-1"),isSend:!0,networkFee:E,ourReceiveAddresses:u,signedTx:"",walletId:this.walletId};return this.addTransaction(v,I),l}const _=(0,t.Vk)(Wt)(d);if(_!=null){const{parameter:{value:{owner_address:C,frozen_balance:E}}}=_;if($(C)!==this.walletLocalData.publicKey)break;const v=o[0].fee.toString(),I=(0,m.add)(E.toString(),v),{currencyCode:D}=this.currencyInfo,B={txid:n,date:Math.floor(r/1e3),currencyCode:D,blockHeight:a,nativeAmount:(0,m.mul)(I,"-1"),isSend:!0,networkFee:v,ourReceiveAddresses:u,signedTx:"",walletId:this.walletId};return this.addTransaction(D,B),l}const A=(0,t.Vk)(Vt)(d);if(A!=null){if(c==null)return l;const{parameter:{value:{owner_address:C}}}=A;if($(C)!==this.walletLocalData.publicKey)break;const E=o[0].fee.toString(),{currencyCode:v}=this.currencyInfo,I=(0,m.sub)(c.toString(),E),D={txid:n,date:Math.floor(r/1e3),currencyCode:v,blockHeight:a,nativeAmount:I,isSend:I.startsWith("-"),networkFee:E,ourReceiveAddresses:u,signedTx:"",walletId:this.walletId};return this.addTransaction(v,D),l}const S=(0,t.Vk)(Mt)(d);if(S!=null){const{parameter:{value:{owner_address:C,frozen_balance:E}}}=S;if($(C)!==this.walletLocalData.publicKey)break;const v=o[0].fee.toString(),I=(0,m.add)(E.toString(),v),{currencyCode:D}=this.currencyInfo,B={txid:n,date:Math.floor(r/1e3),currencyCode:D,blockHeight:a,nativeAmount:(0,m.mul)(I,"-1"),isSend:!0,networkFee:v,ourReceiveAddresses:u,signedTx:"",walletId:this.walletId};return this.addTransaction(D,B),l}const z=(0,t.Vk)($t)(d);if(z!=null){const{parameter:{value:{unfreeze_balance:C,owner_address:E}}}=z;if($(E)!==this.walletLocalData.publicKey)break;const v=o[0].fee.toString(),{currencyCode:I}=this.currencyInfo,D=(0,m.sub)(C.toString(),v),B={txid:n,date:Math.floor(r/1e3),currencyCode:I,blockHeight:a,nativeAmount:D,isSend:D.startsWith("-"),networkFee:v,ourReceiveAddresses:u,signedTx:"",walletId:this.walletId};return this.addTransaction(I,B),l}}return l}processTRC20Transaction(e){return g(this,null,function*(){const{transaction_id:n,token_info:{address:r},block_timestamp:a,from:o,to:c,type:i,value:l}=e,u={txid:n,timestamp:a};if(n===this.otherData.txQueryCache.trc20.txid)return u;const d=yield this.multicastServers("trx_getTransactionInfo","/wallet/gettransactioninfobyid",{value:n}),{blockNumber:w,fee:k}=Ut(d),_=this.allTokens.find(E=>E.contractAddress===r);if(i!=="Transfer"||_==null)return u;const A=[];let S=l;const z=k;if(o===this.walletLocalData.publicKey)S=(0,m.mul)(l,"-1");else if(c===this.walletLocalData.publicKey)A.push(this.walletLocalData.publicKey);else return u;const C={txid:n,date:Math.floor(a/1e3),currencyCode:_.currencyCode,blockHeight:w,nativeAmount:S,isSend:S.startsWith("-"),networkFee:"0",ourReceiveAddresses:A,signedTx:"",walletId:this.walletId};return(0,m.lt)(S,"0")&&(C.parentNetworkFee=z.toString()),this.addTransaction(_.currencyCode,C),u})}checkUpdateNetworkFees(){return g(this,null,function*(){try{const e=yield this.multicastServers("trx_chainParams","/wallet/getchainparameters"),n=Nt(e).chainParameter;for(const r of Object.keys(this.networkFees)){const a=n.find(o=>o.key===r);a!=null&&(this.networkFees=de(ht({},this.networkFees),{[r]:a.value}))}}catch(e){this.log.error("checkUpdateNetworkFees error: ",e)}})}multicastServers(e,n){return g(this,arguments,function*(r,a,o={}){let c={result:"",server:"no server"},i=[];switch(r){case"trx_chainParams":i=this.networkInfo.tronNodeServers.map(l=>()=>g(this,null,function*(){return yield this.fetch(l,a)}));break;case"trx_blockNumber":case"trx_broadcastTx":case"trx_estimateEnergy":case"trx_getAccountResource":case"trx_getBalance":case"trx_getTransactionInfo":i=this.networkInfo.tronNodeServers.map(l=>()=>g(this,null,function*(){const u={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(o)};return yield this.fetch(l,a,u)}));break;case"trx_getTransactions":i=this.networkInfo.tronApiServers.map(l=>()=>g(this,null,function*(){const u={headers:{Accept:"application/json","Content-Type":"application/json"}};return yield this.fetch(l,a,u)}));break}return i=(0,f.Sy)(i),c=yield(0,f.QJ)(i),this.log(`TRX multicastServers ${r} ${c.server} won`),c.result})}calcTxFee(e){return g(this,null,function*(){var n,r;const{note:a,receiverAddress:o,tokenOpts:c,unsignedTxHex:i}=e,l=(0,f.aL)(this.currencyInfo.currencyCode,this.currencyInfo,this.allTokensMap);if(l==null)throw new Error("calcTxFee unknown denom");let u=0;if(c!=null&&o!=null){const{contractAddress:A,data:S}=c;if(this.energyEstimateCache[`${o}:${A}`]==null){const z={owner_address:O(this.walletLocalData.publicKey),contract_address:O(A),function_selector:"transfer(address,uint256)",parameter:S.slice(8)};try{const C=yield this.multicastServers("trx_estimateEnergy","/wallet/triggerconstantcontract",z),E=Zt(C),v=(n=E.transaction.ret[0])==null?void 0:n.ret;if(v!=null&&v!=="SUCCESS")throw new Error("calcTxFee Failed to estimate fee");this.energyEstimateCache[`${o}:${A}`]=E.energy_used}catch(C){this.log.warn("trx_estimateEnergy error. Using a high default.",C)}}u=Math.max(((r=this.energyEstimateCache[`${o}:${A}`])!=null?r:1e5)-this.accountResources.ENERGY,0)}this.log("Account energy: ",this.accountResources.ENERGY),this.log("Energy needed: ",u);let d=i.length/2+65+64+5;if(i.length/2<128&&d--,o!=null&&this.accountExistsCache[o]===void 0)try{const A=yield this.multicastServers("trx_getAccountResource","/wallet/getaccountresource",{address:O(o)});this.accountExistsCache[o]=(0,t.Vk)(vt)(A)!=null}catch(A){this.log.error("calcTxFee error: Failed to call trx_getAccountResource. Allowing the user to proceed assuming high fee.",A)}c==null&&o!=null&&!this.accountExistsCache[o]&&(d=100),d<this.accountResources.BANDWIDTH&&(d=0),this.log("Account bandwidth: ",this.accountResources.BANDWIDTH),this.log("Bandwidth needed: ",d);let w=0;c==null&&o!=null&&!this.accountExistsCache[o]&&(w=this.networkFees.getCreateAccountFee+parseInt(l.multiplier)),this.log("Create account fee: ",w);const k=a!=null?this.networkFees.getMemoFee:0;this.log("Transaction note fee: ",k);const _=u*this.networkFees.getEnergyFee+d*this.networkFees.getTransactionFee+w+k;return this.log("Total fee in SUN: ",_),_.toString()})}txBuilder(e){return g(this,null,function*(){const{contractJson:n,feeLimit:r,note:a}=e,o=this.recentBlock.number.toString(16).padStart(8,"0").slice(4,8),c=this.recentBlock.hash.slice(16,32),i=this.recentBlock.timestamp+60*5*1e3,l=a==null?void 0:Q.YU.stringify(re.from(a,"ascii")),u=fe({raw_data:{contract:[n],ref_block_bytes:o,ref_block_hash:c,expiration:i,timestamp:this.recentBlock.timestamp,data:l,fee_limit:r}}),d=Q.YU.stringify(u.getRawData().serializeBinary());return{transaction:u,transactionHex:d}})}makeTransferJson(e){return g(this,null,function*(){const{currencyCode:n,toAddress:r,nativeAmount:a,data:o,note:c}=e;let i,l;if(n===this.currencyInfo.currencyCode)l={parameter:{value:{to_address:O(r),owner_address:O(this.walletLocalData.publicKey),amount:parseInt(a)}},type:"TransferContract"};else{const u=this.allTokens.find(d=>d.currencyCode===n);if((u==null?void 0:u.contractAddress)==null)throw new Error(`txBuilder unknown currency code ${n}`);l={parameter:{value:{owner_address:O(this.walletLocalData.publicKey),contract_address:O(u.contractAddress),data:o,call_value:0}},type:"TriggerSmartContract"},i=this.networkInfo.defaultFeeLimit}return{contractJson:l,feeLimit:i,note:c}})}makeUnfreezeTransaction(e){return g(this,null,function*(){const{params:{resource:n}}=e,r=this.stakingStatus.stakedAmounts.find(u=>{var d;return((d=u.otherParams)==null?void 0:d.type)===n});if(r==null)throw new Error("Nothing to unfreeze");const o={contractJson:{parameter:{value:{owner_address:O(this.walletLocalData.publicKey),resource:n}},type:"UnfreezeBalanceContract"}},{transactionHex:c}=yield this.txBuilder(o),i=yield this.calcTxFee({unsignedTxHex:c});return{txid:"",date:0,currencyCode:this.currencyInfo.currencyCode,blockHeight:0,nativeAmount:r.nativeAmount,isSend:r.nativeAmount.startsWith("-"),networkFee:i,ourReceiveAddresses:[],signedTx:"",otherParams:o,walletId:this.walletId,metadata:{notes:n}}})}makeFreezeV2Transaction(e){return g(this,null,function*(){const{params:{nativeAmount:n,resource:r}}=e,o={contractJson:{parameter:{value:{owner_address:O(this.walletLocalData.publicKey),frozen_balance:parseInt(n),resource:r==="ENERGY_V2"?"ENERGY":"BANDWIDTH"}},type:"FreezeBalanceV2Contract"}},{transactionHex:c}=yield this.txBuilder(o),i=yield this.calcTxFee({unsignedTxHex:c});return{txid:"",date:0,currencyCode:this.currencyInfo.currencyCode,blockHeight:0,nativeAmount:(0,m.mul)(n,"-1"),isSend:!0,networkFee:i,ourReceiveAddresses:[],signedTx:"",otherParams:o,walletId:this.walletId,metadata:{notes:r}}})}makeUnfreezeV2Transaction(e){return g(this,null,function*(){const{params:{nativeAmount:n,resource:r}}=e,a=this.stakingStatus.stakedAmounts.find(d=>{var w;return((w=d.otherParams)==null?void 0:w.type)===r});if(a==null)throw new Error("Nothing to unfreeze");const c={contractJson:{parameter:{value:{owner_address:O(this.walletLocalData.publicKey),unfreeze_balance:parseInt(n),resource:r==="ENERGY_V2"?"ENERGY":"BANDWIDTH"}},type:"UnfreezeBalanceV2Contract"}},{transactionHex:i}=yield this.txBuilder(c),l=yield this.calcTxFee({unsignedTxHex:i});return{txid:"",date:0,currencyCode:this.currencyInfo.currencyCode,blockHeight:0,nativeAmount:a.nativeAmount,isSend:a.nativeAmount.startsWith("-"),networkFee:l,ourReceiveAddresses:[],signedTx:"",otherParams:c,walletId:this.walletId,metadata:{notes:r}}})}startEngine(){return g(this,null,function*(){this.engineOn=!0,this.addToLoop("checkBlockchainInnerLoop",ge).catch(()=>{}),this.addToLoop("checkAccountInnerLoop",kt).catch(()=>{}),this.addToLoop("checkTokenBalances",kt).catch(()=>{}),this.addToLoop("checkUpdateNetworkFees",ve).catch(()=>{}),this.addToLoop("queryTransactions",pe).catch(()=>{}),yield Et(lt.prototype,this,"startEngine").call(this)})}getStakingStatus(){return g(this,null,function*(){return ht({},this.stakingStatus)})}resyncBlockchain(){return g(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getMaxSpendable(e){return g(this,null,function*(){const n=this.getBalance({currencyCode:e.currencyCode});if(e.spendTargets.length!==1)throw new Error("Error: only one output allowed");const{publicAddress:r,memo:a}=e.spendTargets[0],o=a===""?void 0:a;if(r==null||e.currencyCode==null)throw new Error("Error: need recipient address and/or currencyCode");if(e.currencyCode===this.currencyInfo.currencyCode){const c=(i,l)=>g(this,null,function*(){const u=(0,m.sub)(l,i);if((0,m.lte)(u,"1"))return i;const d=(0,m.add)(i,(0,m.div)(u,"2")),w={toAddress:r,currencyCode:this.currencyInfo.currencyCode,nativeAmount:d},{contractJson:k,feeLimit:_}=yield this.makeTransferJson(w),{transactionHex:A}=yield this.txBuilder({contractJson:k,feeLimit:_,note:o});e.spendTargets[0].nativeAmount=d;const S=yield this.calcTxFee({receiverAddress:r,unsignedTxHex:A,note:o}),z=(0,m.add)(d,S);return(0,m.gt)(z,n)?yield c(i,d):yield c(d,l)});return yield c("0",(0,m.add)(n,"1"))}else return e.spendTargets[0].nativeAmount=n,yield this.makeSpend(e),n})}makeSpend(e){return g(this,null,function*(){var n,r;if(e.otherParams!=null){let N;if(N=(0,t.Vk)(Dt)(e.otherParams),N!=null)return yield this.makeUnfreezeTransaction(N);if(N=(0,t.Vk)(Bt)(e.otherParams),N!=null)return yield this.makeFreezeV2Transaction(N);if(N=(0,t.Vk)(Ht)(e.otherParams),N!=null)return yield this.makeUnfreezeV2Transaction(N)}const{edgeSpendInfo:a,currencyCode:o}=Et(lt.prototype,this,"makeSpendCheck").call(this,e),c=o!==this.currencyInfo.currencyCode;if(a.spendTargets.length!==1)throw new Error("Error: only one output allowed");const{nativeAmount:i,publicAddress:l,otherParams:u,memo:d}=a.spendTargets[0];if(l==null)throw new Error("makeSpend Missing publicAddress");if(i==null)throw new wt.$D;const w=(n=u==null?void 0:u.data)!=null?n:o!==this.currencyInfo.currencyCode?ne(l,i):void 0,k=c?this.allTokens.find(N=>N.currencyCode===o):void 0,_=d===""?void 0:d,A={currencyCode:o,toAddress:l,nativeAmount:i,contractAddress:k==null?void 0:k.contractAddress,data:w,note:_},{contractJson:S,feeLimit:z}=yield this.makeTransferJson(A),{transactionHex:C}=yield this.txBuilder({contractJson:S,feeLimit:z,note:_}),E=(k==null?void 0:k.contractAddress)!=null&&w!=null?{contractAddress:k==null?void 0:k.contractAddress,data:w}:void 0,v=yield this.calcTxFee({receiverAddress:l,unsignedTxHex:C,tokenOpts:E,note:_});let I,D,B,J;c?(I=i,D="0",B=v,J=B):(I=(0,m.add)(i,v),D=v,J=I);const ct=(r=this.walletLocalData.totalBalances[this.currencyInfo.currencyCode])!=null?r:"0";if((0,m.gt)(J,ct))throw new wt.C_({currencyCode:this.currencyInfo.currencyCode,networkFee:v});const K={contractJson:S,feeLimit:z,note:_},W={txid:"",date:0,currencyCode:o,blockHeight:0,nativeAmount:(0,m.mul)(I,"-1"),isSend:!0,networkFee:D,ourReceiveAddresses:[],signedTx:"",otherParams:K,walletId:this.walletId};return B!=null&&(W.parentNetworkFee=B),W})}signTx(e,n){return g(this,null,function*(){const r=(0,f.Xp)(e),a=yield this.txBuilder(r),{tronKey:o}=dt(n),c=me(a.transaction);a.transaction.txID=c.replace("0x","");const i=yield he(o,a.transaction);i.addSignature(Q.YU.parse(i.signature[0]));const l=Q.YU.stringify(i.serializeBinary());return e.signedTx=l,e})}broadcastTx(e){return g(this,null,function*(){const n={transaction:e.signedTx},r=yield this.multicastServers("trx_broadcastTx","/wallet/broadcasthex",n),a=Yt(r);if(!a.result)throw new Error(a.message);const{toAddress:o,contractAddress:c}=(0,f.Xp)(e);return e.currencyCode===this.currencyInfo.currencyCode&&o!=null&&(this.accountExistsCache[o]=!0),c!=null&&delete this.energyEstimateCache[`${o}:${c}`],e.txid=a.txid,e.date=Date.now()/1e3,e})}}function Te(s,e,n,r){return g(this,null,function*(){const a=Tt(n),o=new lt(s,e,a,r);return yield o.loadEngine(),o})}var xt=h(48764).Buffer,X=(s,e,n)=>new Promise((r,a)=>{var o=l=>{try{i(n.next(l))}catch(u){a(u)}},c=l=>{try{i(n.throw(l))}catch(u){a(u)}},i=l=>l.done?r(l.value):Promise.resolve(l.value).then(o,c);i((n=n.apply(s,e)).next())});const{utils:{crypto:{isAddressValid:ft,pkToAddress:we}}}=V();class _t{constructor(e){const{builtinTokens:n,currencyInfo:r,initOptions:a,io:o,log:c,networkInfo:i}=e;this.builtinTokens=n,this.currencyInfo=r,this.initOptions=st(a),this.io=o,this.log=c,this.networkInfo=i}getDisplayPrivateKey(e){return X(this,null,function*(){var n;const r=dt(e.keys);return(n=r.tronMnemonic)!=null?n:r.tronKey})}getDisplayPublicKey(e){return X(this,null,function*(){const{keys:n}=Tt(e);return n.publicKey})}importPrivateKey(e,n){return X(this,null,function*(){var r;if(/^(0x)?[0-9a-fA-F]{64}$/.test(e)){const a=xt.from(e.replace(/^0x/,""),"hex");if(Y().isValidPrivate(a)===!0)throw new Error("Invalid private key");return{tronKey:a.toString("hex")}}else{if(!(0,F.validateMnemonic)(e))throw new Error("Invalid input");const a=(r=n==null?void 0:n.derivationPath)!=null?r:this.networkInfo.defaultDerivationPath,o=yield this._mnemonicToTronKey(e,a);return{tronMnemonic:e,tronKey:o,derivationPath:a}}})}createPrivateKey(e){return X(this,null,function*(){if(e!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const n=xt.from(this.io.random(32)).toString("hex"),r=(0,F.entropyToMnemonic)(n);return yield this.importPrivateKey(r)})}_mnemonicToTronKey(e,n){return X(this,null,function*(){const r=yield(0,F.mnemonicToSeed)(e);return q().fromMasterSeed(r).derivePath(n).getWallet().getPrivateKeyString().replace("0x","")})}derivePublicKey(e){return X(this,null,function*(){if(e.type!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const{tronKey:n}=dt(e.keys);return{publicKey:we(n)}})}parseUri(e,n,r){return X(this,null,function*(){var a;const o={[this.currencyInfo.pluginId]:!0},{smartPayPublicAddress:c,smartPayUserId:i}=this.initOptions,{parsedUri:l,edgeParsedUri:u}=(0,rt.k)(this.currencyInfo,e,o,n!=null?n:this.currencyInfo.currencyCode,r),d=(a=u.publicAddress)!=null?a:"";if(ft(d))return u.uniqueIdentifier=l.query.memo,u;if(n==null||n==="USDT"){const w=yield U(this.io,this.builtinTokens,e,c,i);if(w!=null)return w}throw new Error("InvalidPublicAddressError")})}encodeUri(e){return X(this,arguments,function*(n,r=[]){const{publicAddress:a,nativeAmount:o,currencyCode:c}=n;if(!ft(a))throw new Error("InvalidPublicAddressError");let i;if(typeof o=="string"){const u=(0,f.Qs)(c!=null?c:this.currencyInfo.currencyCode,this.currencyInfo,r);if(u==null)throw new Error("InternalErrorInvalidCurrencyCode");i=(0,m.div)(o,u.multiplier,18)}return(0,rt.Q)(n,this.currencyInfo.pluginId,i)})}getTokenId(e){return X(this,null,function*(){(0,nt.Rp)(e);const n=(0,nt.Oj)(e.networkLocation);if(n==null||!ft(n.contractAddress))throw new Error("ErrorInvalidContractAddress");return n.contractAddress})}}function Ce(s){return X(this,null,function*(){return new _t(s)})}}}]);
|
|
1
|
+
"use strict";(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[5],{86352:function(yt,Y,h){h.d(Y,{Vn:function(){return nt},lF:function(){return tt},sp:function(){return M}});var m=h(76714),F=(t,S,x)=>new Promise((O,H)=>{var L=p=>{try{C(x.next(p))}catch(f){H(f)}},y=p=>{try{C(x.throw(p))}catch(f){H(f)}},C=p=>p.done?O(p.value):Promise.resolve(p.value).then(L,y);C((x=x.apply(t,S)).next())});const q=["https://info1.edge.app","https://info2.edge.app"];function Q(t,S,x){return F(this,arguments,function*(O,H,L,y=5e3,C=fetch){const p=O.map(f=>()=>F(this,null,function*(){const $=yield C(f+"/"+H,L);if(typeof $!="object"){const b=`Invalid return value ${H} in ${f}`;throw console.log(b),new Error(b)}return $}));return yield(0,m.QJ)(p,y)})}function tt(t,S,x,O,H=5e3,L){return F(this,null,function*(){const y=yield Q((0,m.Sy)(S),x,O,H,L);if(!y.ok){const f=yield y.text();throw console.error(f),new Error(`Error fetching ${x}: ${f}`)}const C=yield y.json();return t(C)})}function et(t,S,x,O=5e3,H){return F(this,null,function*(){return yield Q((0,m.Sy)(t),S,x,O,H)})}const nt=(t,S,x,O)=>F(void 0,null,function*(){return yield et(q,t,S,x,O)}),M=t=>Object.keys(t).map(S=>{const x=t[S];return x==null?S:`${S}=${encodeURIComponent(x)}`}).join("&")},79014:function(yt,Y,h){h.d(Y,{Q:function(){return L},k:function(){return H}});var m=h(77591),F=h.n(m),q=h(24350),Q=h(84564),tt=h.n(Q),et=h(76714),nt=Object.defineProperty,M=Object.getOwnPropertySymbols,t=Object.prototype.hasOwnProperty,S=Object.prototype.propertyIsEnumerable,x=(y,C,p)=>C in y?nt(y,C,{enumerable:!0,configurable:!0,writable:!0,value:p}):y[C]=p,O=(y,C)=>{for(var p in C||(C={}))t.call(C,p)&&x(y,p,C[p]);if(M)for(var p of M(C))S.call(C,p)&&x(y,p,C[p]);return y};function H(y,C,p,f,$=[]){const b=O({},tt()(C,{},!0)),rt=C.startsWith(`${y.pluginId}://`);if(b.protocol!=null&&(b.protocol=b.protocol.replace(":","")),b.protocol!=null&&b.protocol!==""&&!p[b.protocol])throw new Error(`Uri protocol '${b.protocol}' is not supported for ${y.pluginId}.`);if(b.host===""&&b.pathname==="")throw new Error("Path and host not found in uri.");const U={publicAddress:b.host!==""?b.host:b.pathname.split("/")[0]},st=b.query.label,ot=b.query.message,lt=b.query.category;(st!=null||ot!=null||lt!=null||rt)&&(U.metadata={},U.metadata.name=st,U.metadata.notes=ot,U.metadata.category=lt,U.metadata.gateway=rt!=null?rt:!1);const at=b.query.amount;if(at!=null&&typeof at=="string"){f==null&&(f=y.currencyCode);const ct=(0,et.Qs)(f!=null?f:"",y,$);if(ct==null)throw new Error("InternalErrorInvalidCurrencyCode");let it=(0,m.mul)(at,ct.multiplier);it=(0,m.toFixed)(it,0,0),U.nativeAmount=it,U.currencyCode=f}return{edgeParsedUri:U,parsedUri:b}}function L(y,C,p){if(y.publicAddress==null)throw new Error("InvalidPublicAddressError");if(p==null&&y.label==null&&y.message==null)return y.publicAddress;{let f="";p!=null&&(f+="amount="+p+"&"),(y.label!=null||y.message!=null)&&(typeof y.label=="string"&&(f+="label="+y.label+"&"),typeof y.message=="string"&&(f+="message="+y.message+"&")),f=f.substr(0,f.length-1);const $={scheme:C,path:y.publicAddress,query:f};return(0,q.qC)($)}}},58780:function(yt,Y,h){h.r(Y),h.d(Y,{TronTools:function(){return Pt},makeCurrencyEngine:function(){return Ce},makeCurrencyTools:function(){return Ae}});var m=h(77591),F=h(2153),q=h(21964),Q=h.n(q),tt=h(48367),et=h.n(tt),nt=h(3666),M=h.n(nt),t=h(82448),S=h(86352);const x=s=>{if(s.includes("@"))return O(s)?[!0,s.toLowerCase()]:[!1,"Invalid Email"];if(s.includes("+"))return s="+"+s.replace(/[^\d]+/g,""),s.length!==14?[!1,"Invalid Phone number"]:s.substring(0,3)!=="+55"?[!1,"Not brasilian number"]:[!0,s];if(s.length===36)return[!0,s];if(s.length===18)return/^\d{2}\.\d{3}\.\d{3}\/\d{4}-\d{2}$/.test(s)?L(s)?(s=s.replace(/[^\d]+/g,""),[!0,s]):[!1,"invalid cnpj"]:[!1,"invalid pixkey"];if(s.length===13&&/^\d+$/.test(s))return s.substr(0,2)!=="55"?[!1,"invalid pixkey"]:[!0,"+"+s];if(s.length<11)return[!1,"invalid pixkey"];if(s.length===14){if(/^\d+$/.test(s))return L(s)?[!0,s]:[!1,"invalid pixkey"];if(/^\d{3}\.\d{3}\.\d{3}-\d{2}$/.test(s))return H(s)?[!0,s.replace(/[^\d]+/g,"")]:[!1,"invalid cpf"]}return s.length===11?/^\d+$/.test(s)?H(s)?[!0,s.replace(/[^\d]+/g,"")]:s.charAt(0)==="0"?[!1,"invalid pixkey"]:[!0,"+55"+s]:[!1,"invalid pixkey"]:(s=s.replace(/[^\d]+/g,""),s.length===12?s.charAt(0)!=="0"?[!1,"invalid pixkey"]:[!0,"+55"+s.substr(1)]:s.length===11?H(s)?[!0,s]:[!0,"+55"+s]:[!1,"invalid pixkey"])};function O(s){return/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(String(s).toLowerCase())}function H(s){if(s=s.replace(/[^\d]+/g,""),s===""||s.length!==11||s==="00000000000"||s==="11111111111"||s==="22222222222"||s==="33333333333"||s==="44444444444"||s==="55555555555"||s==="66666666666"||s==="77777777777"||s==="88888888888"||s==="99999999999")return!1;let e,n;e=0;for(let r=1;r<=9;r++)e=e+parseInt(s.substring(r-1,r))*(11-r);if(n=e*10%11,(n===10||n===11)&&(n=0),n!==parseInt(s.substring(9,10)))return!1;e=0;for(let r=1;r<=10;r++)e=e+parseInt(s.substring(r-1,r))*(12-r);return n=e*10%11,(n===10||n===11)&&(n=0),n===parseInt(s.substring(10,11))}function L(s){if(s=s.replace(/[^\d]+/g,""),s===""||s.length!==14||s==="00000000000000"||s==="11111111111111"||s==="22222222222222"||s==="33333333333333"||s==="44444444444444"||s==="55555555555555"||s==="66666666666666"||s==="77777777777777"||s==="88888888888888"||s==="99999999999999")return!1;let e=s.length-2,n=s.substring(0,e);const r=s.substring(e);let a=0,o=e-7;for(let i=e;i>=1;i--)a+=Number(n.charAt(e-i))*o--,o<2&&(o=9);let c=a%11<2?0:11-a%11;if(c!==Number(r.charAt(0)))return!1;e=e+1,n=s.substring(0,e),a=0,o=e-7;for(let i=e;i>=1;i--)a+=Number(n.charAt(e-i))*o--,o<2&&(o=9);return c=a%11<2?0:11-a%11,c===Number(r.charAt(1))}function y(s,e=!1){const n=p(s),r=[0,4129,8258,12387,16516,20645,24774,28903,33032,37161,41290,45419,49548,53677,57806,61935,4657,528,12915,8786,21173,17044,29431,25302,37689,33560,45947,41818,54205,50076,62463,58334,9314,13379,1056,5121,25830,29895,17572,21637,42346,46411,34088,38153,58862,62927,50604,54669,13907,9842,5649,1584,30423,26358,22165,18100,46939,42874,38681,34616,63455,59390,55197,51132,18628,22757,26758,30887,2112,6241,10242,14371,51660,55789,59790,63919,35144,39273,43274,47403,23285,19156,31415,27286,6769,2640,14899,10770,56317,52188,64447,60318,39801,35672,47931,43802,27814,31879,19684,23749,11298,15363,3168,7233,60846,64911,52716,56781,44330,48395,36200,40265,32407,28342,24277,20212,15891,11826,7761,3696,65439,61374,57309,53244,48923,44858,40793,36728,37256,33193,45514,41451,53516,49453,61774,57711,4224,161,12482,8419,20484,16421,28742,24679,33721,37784,41979,46042,49981,54044,58239,62302,689,4752,8947,13010,16949,21012,25207,29270,46570,42443,38312,34185,62830,58703,54572,50445,13538,9411,5280,1153,29798,25671,21540,17413,42971,47098,34713,38840,59231,63358,50973,55100,9939,14066,1681,5808,26199,30326,17941,22068,55628,51565,63758,59695,39368,35305,47498,43435,22596,18533,30726,26663,6336,2273,14466,10403,52093,56156,60223,64286,35833,39896,43963,48026,19061,23124,27191,31254,2801,6864,10931,14994,64814,60687,56684,52557,48554,44427,40424,36297,31782,27655,23652,19525,15522,11395,7392,3265,61215,65342,53085,57212,44955,49082,36825,40952,28183,32310,20053,24180,11923,16050,3793,7920];let a=65535;for(let i=0;i<n.length;i++){const u=(n[i]^a>>8)&255;a=r[u]^a<<8}const o=(a^0)&65535,c=C(o,4);return e?c.slice(2)+c.slice(0,2):c}function C(s,e){const n=s.toString(16).toUpperCase();return e>0?("0".repeat(e)+n).slice(-e):n.length%2===0?n:"0"+n}function p(s){let e=0;const n=s.length;let r=0,a=Math.max(32,n+(n>>>1)+7),o=new Uint8Array(a>>>3<<3);for(;e<n;){let c=s.charCodeAt(e++);if(c>=55296&&c<=56319){if(e<n){const i=s.charCodeAt(e);(i&64512)===56320&&(++e,c=((c&1023)<<10)+(i&1023)+65536)}if(c>=55296&&c<=56319)continue}if(r+4>o.length){a+=8,a*=1+e/s.length*2,a=a>>>3<<3;const i=new Uint8Array(a);i.set(o),o=i}if((c&4294967168)===0){o[r++]=c;continue}else if((c&4294965248)===0)o[r++]=c>>>6&31|192;else if((c&4294901760)===0)o[r++]=c>>>12&15|224,o[r++]=c>>>6&63|128;else if((c&4292870144)===0)o[r++]=c>>>18&7|240,o[r++]=c>>>12&63|128,o[r++]=c>>>6&63|128;else continue;o[r++]=c&63|128}return o.slice!=null?o.slice(0,r):o.subarray(0,r)}var f=h(76714),$=(s,e,n)=>new Promise((r,a)=>{var o=l=>{try{i(n.next(l))}catch(u){a(u)}},c=l=>{try{i(n.throw(l))}catch(u){a(u)}},i=l=>l.done?r(l.value):Promise.resolve(l.value).then(o,c);i((n=n.apply(s,e)).next())});const b=60*60*24*7,rt=(0,t._C)((0,t.su)({status:(0,t.Wf)("ok"),msg:t.XC,data:(0,t.su)({amount:t.mH,name:t.XC,key:t.XC,timeout:t.mH})}),(0,t.su)({status:(0,t.Wf)("failed"),msg:t.XC})),gt=(0,t.su)({status:(0,t.Wf)("ok"),msg:t.XC,data:(0,t.su)({amount_usd:t.XC,price_brl:t.XC,total_brl:t.XC,fee_brl:t.XC,send_brl:t.XC,timeout:t.mH,amount_txusdt:t.XC,price_txusdt:t.mH,value_usd:t.XC,total_txusdt:t.XC})}),U=(s,e,n,r,a)=>$(void 0,null,function*(){const o=new Date,c=Object.keys(e).find(u=>e[u].currencyCode==="USDT");if(c==null)return;const i=e[c],l=(0,m.mul)("0.5",i.denominations[0].multiplier);if(n.length>36){const u=y(n.slice(0,-4));if(!n.endsWith(u))return;try{const d=(0,f.zR)(s),v=encodeURIComponent(n),I=yield(0,S.lF)(rt,["https://connect.smartpay.com.vc"],`api/pix/qrdecode?qrcode=${v}`,void 0,void 0,d);if(I.status!=="ok")throw new Error(I.msg);const{data:k}=I,{amount:w,key:D,name:R,timeout:T}=k;if(T>0&&T<120)throw new Error("ErrorPixExpired");let E,A;if(w!==0){const P={type:"buy",profile:"transfer",currency:"brl",conv:"txusdt",target:"amount",user:a,amount:w===0?100:w},B=(0,S.sp)(P),W=yield(0,S.lF)(gt,["https://connect.smartpay.com.vc"],`api/swapix/swapquote?${B}`,void 0,void 0,d),{data:Z}=W,{amount_txusdt:K,timeout:V}=Z;if(V>0&&V<120)throw new Error("ErrorPixExpired");E=(0,m.mul)(K,i.denominations[0].multiplier);const j=Math.min(T>0?T:b,V>0?V:b);A=new Date(o.getTime()+j*1e3)}return{currencyCode:"USDT",metadata:{name:R,notes:`To PIX: ${D}`},expireDate:A,nativeAmount:E,minNativeAmount:l,publicAddress:r,uniqueIdentifier:n}}catch(d){console.log(`Could not query PIX address ${n}: ${d.message}`)}}else{const[u,d]=x(n);return u?{currencyCode:"USDT",minNativeAmount:l,metadata:{name:`PIX: ${d}`,notes:`To PIX: ${d}`},publicAddress:"TUmgPbM5J6om7Z2PJjzrbSEbXit84ZhVCj",uniqueIdentifier:d}:void 0}});var st=h(20918),ot=h(79014),lt=h(62177);const at=(0,t.su)({smartPayPublicAddress:(0,t.Zz)(t.XC,"TUmgPbM5J6om7Z2PJjzrbSEbXit84ZhVCj"),smartPayUserId:(0,t.Zz)(t.XC,"edge")}),ct=(0,t.su)({txid:t.XC,timestamp:t.mH}),it=(0,t.su)({txQueryCache:(0,t.Vk)((0,t.su)({mainnet:ct,trc20:ct}),()=>({mainnet:{txid:"",timestamp:0},trc20:{txid:"",timestamp:0}}))}),pt=(0,t.Wf)("ENERGY"),St=(0,t.Wf)("BANDWIDTH"),dt=(0,t._C)(pt,St),Dt=(0,t.Wf)("ENERGY_V2"),Bt=(0,t.Wf)("BANDWIDTH_V2"),vt=(0,t._C)(Dt,Bt),Ht=(0,t.su)({type:(0,t.Wf)("remove"),params:(0,t.su)({resource:dt})}),Nt=(0,t.su)({type:(0,t.Wf)("addV2"),params:(0,t.su)({nativeAmount:t.XC,resource:vt})}),Ot=(0,t.su)({type:(0,t.Wf)("removeV2"),params:(0,t.su)({nativeAmount:t.XC,resource:vt})}),Rt=(0,t.su)({chainParameter:(0,t._2)((0,t.su)({key:t.XC,value:(0,t.Zz)(t.mH)}))}),zt=(0,t.su)({blockID:t.XC,block_header:(0,t.su)({raw_data:(0,t.su)({number:t.mH,timestamp:t.mH})})}),Tt=(0,t.su)({freeNetUsed:(0,t.Vk)(t.mH,0),freeNetLimit:t.mH,EnergyUsed:(0,t.Vk)(t.mH,0),EnergyLimit:(0,t.Vk)(t.mH,0)}),Ft=(0,t.su)({frozen:(0,t.Zz)((0,t.vq)((0,t.su)({frozen_balance:t.mH,expire_time:t.mH}))),account_resource:(0,t.su)({frozen_balance_for_energy:(0,t.Zz)((0,t.su)({frozen_balance:t.mH,expire_time:t.mH}))}),frozenV2:(0,t.vq)((0,t.su)({amount:(0,t.Zz)(t.mH)}),(0,t.su)({type:pt,amount:(0,t.Zz)(t.mH)}),(0,t.su)({type:(0,t.Wf)("TRON_POWER")})),balance:(0,t.Vk)(t.mH,0)}),Lt=(0,t.su)({constant_result:(0,t.vq)(t.XC)}),Ut=(0,t.su)({ret:(0,t._2)((0,t.su)({contractRet:t.XC,fee:t.mH})),txID:t.XC,unfreeze_amount:(0,t.Zz)(t.mH),blockNumber:t.mH,block_timestamp:t.mH,raw_data:(0,t.su)({contract:(0,t._2)(t.JC)})}),Xt=(0,t.su)({transaction_id:t.XC,token_info:(0,t.su)({address:t.XC}),block_timestamp:t.mH,from:t.XC,to:t.XC,type:t.XC,value:t.XC}),Kt=(0,t.su)({fee:(0,t.Zz)(t.mH,0),blockNumber:t.mH}),Wt=(0,t.su)({parameter:(0,t.su)({value:(0,t.su)({amount:t.mH,owner_address:t.XC,to_address:t.XC})}),type:(0,t.Wf)("TransferContract")}),Vt=(0,t.su)({parameter:(0,t.su)({value:(0,t.su)({data:t.XC,owner_address:t.XC,contract_address:t.XC})}),type:(0,t.Wf)("TriggerSmartContract")}),Mt=(0,t.su)({parameter:(0,t.su)({value:(0,t.su)({frozen_balance:t.mH,resource_type:dt,owner_address:t.XC})}),type:(0,t.Wf)("FreezeBalanceContract")}),$t=(0,t.su)({parameter:(0,t.su)({value:(0,t.su)({resource_type:dt,owner_address:t.XC})}),type:(0,t.Wf)("UnfreezeBalanceContract")}),Jt=(0,t.su)({parameter:(0,t.su)({value:(0,t.su)({frozen_balance:t.mH,owner_address:t.XC})}),type:(0,t.Wf)("FreezeBalanceV2Contract")}),Zt=(0,t.su)({parameter:(0,t.su)({value:(0,t.su)({unfreeze_balance:t.mH,owner_address:t.XC})}),type:(0,t.Wf)("UnfreezeBalanceV2Contract")}),Yt=s=>(0,t.su)({data:(0,t._2)(s),success:t.jK,meta:(0,t.su)({links:(0,t.Zz)((0,t.su)({next:t.XC})),page_size:t.mH})}),Qt=(0,t.su)({energy_used:t.mH,transaction:(0,t.su)({ret:(0,t._2)((0,t.su)({ret:(0,t.Zz)(t.XC)}))})}),Gt=(0,t.su)({result:t.jK,txid:t.XC,message:t.XC}),wt=lt.BQ,ht=(0,t.su)({tronMnemonic:(0,t.Zz)(t.XC),tronKey:t.XC,derivationPath:(0,t.Zz)(t.XC)});var Ct=h(94935),G=h(35620),jt=h(84650),bt=h(72681),qt=h(68142),te=h.n(qt),ee=h(48764).Buffer;const{utils:{crypto:{decode58Check:ne,getBase58CheckAddress:re}}}=M(),N=s=>{const e=ne(s);return G.YU.stringify(e)},J=s=>{const e=G.YU.parse(s);return re(Array.from(e))},At="a9059cbb",Ee=s=>{if(!s.startsWith(At))throw new Error("Not a TRC20 data payload");const e=s.replace(At,""),n=`41${e.substring(24,64)}`,r=J(n),a=e.substring(64,128),o=hexToDecimal(a);return[r,o]},se=(s,e)=>{const n=N(s).replace(/^(41)/,"0x"),r=te().simpleEncode("transfer(address,uint256):(uint256)",n,e);return ee.from(r).toString("hex")};var oe=h(48764).Buffer,ae=Object.defineProperty,ce=Object.defineProperties,ie=Object.getOwnPropertyDescriptors,Et=Object.getOwnPropertySymbols,le=Object.getPrototypeOf,ue=Object.prototype.hasOwnProperty,de=Object.prototype.propertyIsEnumerable,he=Reflect.get,kt=(s,e,n)=>e in s?ae(s,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[e]=n,ft=(s,e)=>{for(var n in e||(e={}))ue.call(e,n)&&kt(s,n,e[n]);if(Et)for(var n of Et(e))de.call(e,n)&&kt(s,n,e[n]);return s},fe=(s,e)=>ce(s,ie(e)),xt=(s,e,n)=>he(le(s),n,e),g=(s,e,n)=>new Promise((r,a)=>{var o=l=>{try{i(n.next(l))}catch(u){a(u)}},c=l=>{try{i(n.throw(l))}catch(u){a(u)}},i=l=>l.done?r(l.value):Promise.resolve(l.value).then(o,c);i((n=n.apply(s,e)).next())});const{utils:{crypto:{signTransaction:me},transaction:{txJsonToPb:ye,txPbToTxID:ge}}}=M(),pe=(0,f.jT)(),_t=2e4,ve=2e4,Te=3e3,we=60*10*1e3;class ut extends jt.P{constructor(e,n,r,a){super(e,n,r,a);const{networkInfo:o}=e;this.fetchCors=(0,f.zR)(e.io),this.networkInfo=o,this.recentBlock={hash:"0",number:0,timestamp:0},this.accountResources={BANDWIDTH:0,ENERGY:0},this.networkFees={getCreateAccountFee:1e5,getTransactionFee:1e3,getEnergyFee:280,getMemoFee:1e6},this.accountExistsCache={},this.energyEstimateCache={},this.processTRXTransaction=this.processTRXTransaction.bind(this),this.processTRC20Transaction=this.processTRC20Transaction.bind(this),this.stakingStatus={stakedAmounts:[{nativeAmount:"0",otherParams:{type:"BANDWIDTH"}},{nativeAmount:"0",otherParams:{type:"ENERGY"}}]}}setOtherData(e){this.otherData=it(e)}fetch(e,n){return g(this,arguments,function*(r,a,o={}){const c=r+a,i=yield this.fetchCors(c,o);if(!i.ok||i.status!==200)throw this.log(`The server returned error code ${i.status} for ${c}`),new Error(`The server returned error code ${i.status} for ${c}`);const l=yield i.json();if(typeof l!="object"){const u=`Invalid return value ${a} in ${r}`;throw this.log(u),new Error(u)}return{server:r,result:l}})}checkBlockchainInnerLoop(){return g(this,null,function*(){try{const e=yield this.multicastServers("trx_blockNumber","/wallet/getnowblock"),n=zt(e),r=n.block_header.raw_data.number;Object.assign(this.recentBlock,{hash:n.blockID,number:r,timestamp:n.block_header.raw_data.timestamp}),this.walletLocalData.blockHeight!==r&&(this.checkDroppedTransactionsThrottled(),this.walletLocalData.blockHeight=r,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight))}catch(e){this.log.error("Error fetching height: ",e)}})}checkTokenBalances(){return g(this,null,function*(){const e=N(this.walletLocalData.publicKey);for(const n of this.enabledTokens){const r=this.allTokens.find(c=>c.currencyCode===n);if((r==null?void 0:r.contractAddress)==null)continue;const o={contract_address:N(r.contractAddress),function_selector:"balanceOf(address)",parameter:(0,f.gc)(e,32),owner_address:e};try{const c=yield this.multicastServers("trx_getBalance","/wallet/triggerconstantcontract",o),i=Lt(c);r!=null&&this.updateBalance(r.currencyCode,(0,f.Z8)(i.constant_result[0]))}catch(c){this.log.error(`Failed to get balance of ${n}`,c)}}})}checkAccountInnerLoop(){return g(this,null,function*(){const e={address:N(this.walletLocalData.publicKey)};try{const n=yield this.multicastServers("trx_getBalance","/wallet/getaccount",e),r=(0,t.Vk)(Ft)(n);if(r==null){this.updateBalance(this.currencyInfo.currencyCode,"0");return}this.updateBalance(this.currencyInfo.currencyCode,r.balance.toString());const{frozen:a,account_resource:{frozen_balance_for_energy:o}}=r,c=[];if(a!=null){const u=a[0].frozen_balance.toString(),d=new Date(a[0].expire_time);c.push({nativeAmount:u,unlockDate:d,otherParams:{type:"BANDWIDTH"}})}if(o!=null){const u=o.frozen_balance.toString(),d=new Date(o.expire_time);c.push({nativeAmount:u,unlockDate:d,otherParams:{type:"ENERGY"}})}const[i,l]=r.frozenV2;i.amount!=null&&c.push({nativeAmount:i.amount.toFixed(),otherParams:{type:"BANDWIDTH_V2"}}),l.amount!=null&&c.push({nativeAmount:l.amount.toFixed(),otherParams:{type:"ENERGY_V2"}}),this.stakingStatus={stakedAmounts:c},this.currencyEngineCallbacks.onStakingStatusChanged(ft({},this.stakingStatus))}catch(n){this.log.error("Error checking TRX address balance: ",n)}try{const n=yield this.multicastServers("trx_getAccountResource","/wallet/getaccountresource",e),r=Tt(n);this.accountResources={BANDWIDTH:r.freeNetLimit-r.freeNetUsed,ENERGY:r.EnergyLimit-r.EnergyUsed}}catch(n){this.log.error("Error checking TRX address resources: ",n)}})}queryTransactions(){return g(this,null,function*(){return yield pe(()=>g(this,null,function*(){return yield this.queryTransactionsInnerLoop()}))})}queryTransactionsInnerLoop(){return g(this,null,function*(){try{yield this.fetchTrxTransactions(),yield this.fetchTrc20Transactions()}catch(e){throw this.log.error("Error checkTransactionsFetch fetchTrxTransactions: ",e),e}this.transactionsChangedArray.length>0&&(this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[]);for(const e of this.enabledTokens)this.tokenCheckTransactionsStatus[e]=1;this.updateOnAddressesChecked()})}fetchTrxTransactions(){return g(this,null,function*(){let e=!1;for(;!e;)e=yield this.fetchTransactions("mainnet",Ut,this.processTRXTransaction)})}fetchTrc20Transactions(){return g(this,null,function*(){let e=!1;for(;!e;)e=yield this.fetchTransactions("trc20",Xt,this.processTRC20Transaction)})}fetchTransactions(e,n,r){return g(this,null,function*(){var a;const o=e==="trc20"?e:"",c=this.otherData.txQueryCache[e].timestamp,i=`/v1/accounts/${this.walletLocalData.publicKey}/transactions/${o}?limit=200&order_by=block_timestamp,asc&min_timestamp=${c}`,l=yield this.multicastServers("trx_getTransactions",i),{data:u,meta:d,success:v}=Yt(n)(l),I=((a=d==null?void 0:d.links)==null?void 0:a.next)==null;if(!v)throw new Error("Failed to query TRX transactions");for(const k of u){const{timestamp:w,txid:D}=yield r(k);this.otherData.txQueryCache[e].txid=D,this.otherData.txQueryCache[e].timestamp=w,this.walletLocalDataDirty=!0}return I})}processTRXTransaction(e){const{txID:n,block_timestamp:r,blockNumber:a,ret:o,unfreeze_amount:c,raw_data:{contract:i}}=e,l={txid:n,timestamp:r};if(n===this.otherData.txQueryCache.mainnet.txid||o.length<1)return l;const u=[];for(const d of i){const v=(0,t.Vk)(Wt)(d);if(v!=null){const{parameter:{value:{amount:T,owner_address:E,to_address:A}}}=v,{contractRet:_,fee:P}=o[0];let B=P.toString();const W=J(E),Z=J(A);let K=T.toString();if(W===this.walletLocalData.publicKey)W===Z?K=(0,m.mul)(B,"-1"):K=(0,m.mul)((0,m.add)(K,B),"-1"),_!=="SUCCESS"&&(K="0");else{if(_!=="SUCCESS")return l;u.push(this.walletLocalData.publicKey),B="0"}const{currencyCode:V}=this.currencyInfo,j={blockHeight:a,currencyCode:V,date:Math.floor(r/1e3),isSend:K.startsWith("-"),memos:[],nativeAmount:K,networkFee:B,ourReceiveAddresses:u,signedTx:"",txid:n,walletId:this.walletId};return this.addTransaction(V,j),l}const I=(0,t.Vk)(Vt)(d);if(I!=null){const{parameter:{value:{owner_address:T}}}=I;if(J(T)!==this.walletLocalData.publicKey)break;const E=o[0].fee.toString(),{currencyCode:A}=this.currencyInfo,_={blockHeight:a,currencyCode:A,date:Math.floor(r/1e3),isSend:!0,memos:[],nativeAmount:(0,m.mul)(E,"-1"),networkFee:E,ourReceiveAddresses:u,signedTx:"",txid:n,walletId:this.walletId};return this.addTransaction(A,_),l}const k=(0,t.Vk)(Mt)(d);if(k!=null){const{parameter:{value:{owner_address:T,frozen_balance:E}}}=k;if(J(T)!==this.walletLocalData.publicKey)break;const A=o[0].fee.toString(),_=(0,m.add)(E.toString(),A),{currencyCode:P}=this.currencyInfo,B={blockHeight:a,currencyCode:P,date:Math.floor(r/1e3),isSend:!0,memos:[],nativeAmount:(0,m.mul)(_,"-1"),networkFee:A,ourReceiveAddresses:u,signedTx:"",txid:n,walletId:this.walletId};return this.addTransaction(P,B),l}const w=(0,t.Vk)($t)(d);if(w!=null){if(c==null)return l;const{parameter:{value:{owner_address:T}}}=w;if(J(T)!==this.walletLocalData.publicKey)break;const E=o[0].fee.toString(),{currencyCode:A}=this.currencyInfo,_=(0,m.sub)(c.toString(),E),P={blockHeight:a,currencyCode:A,date:Math.floor(r/1e3),isSend:_.startsWith("-"),memos:[],nativeAmount:_,networkFee:E,ourReceiveAddresses:u,signedTx:"",txid:n,walletId:this.walletId};return this.addTransaction(A,P),l}const D=(0,t.Vk)(Jt)(d);if(D!=null){const{parameter:{value:{owner_address:T,frozen_balance:E}}}=D;if(J(T)!==this.walletLocalData.publicKey)break;const A=o[0].fee.toString(),_=(0,m.add)(E.toString(),A),{currencyCode:P}=this.currencyInfo,B={blockHeight:a,currencyCode:P,date:Math.floor(r/1e3),memos:[],isSend:!0,nativeAmount:(0,m.mul)(_,"-1"),networkFee:A,ourReceiveAddresses:u,signedTx:"",txid:n,walletId:this.walletId};return this.addTransaction(P,B),l}const R=(0,t.Vk)(Zt)(d);if(R!=null){const{parameter:{value:{unfreeze_balance:T,owner_address:E}}}=R;if(J(E)!==this.walletLocalData.publicKey)break;const A=o[0].fee.toString(),{currencyCode:_}=this.currencyInfo,P=(0,m.sub)(T.toString(),A),B={blockHeight:a,currencyCode:_,date:Math.floor(r/1e3),isSend:P.startsWith("-"),memos:[],nativeAmount:P,networkFee:A,ourReceiveAddresses:u,signedTx:"",txid:n,walletId:this.walletId};return this.addTransaction(_,B),l}}return l}processTRC20Transaction(e){return g(this,null,function*(){const{transaction_id:n,token_info:{address:r},block_timestamp:a,from:o,to:c,type:i,value:l}=e,u={txid:n,timestamp:a};if(n===this.otherData.txQueryCache.trc20.txid)return u;const d=yield this.multicastServers("trx_getTransactionInfo","/wallet/gettransactioninfobyid",{value:n}),{blockNumber:v,fee:I}=Kt(d),k=this.allTokens.find(E=>E.contractAddress===r);if(i!=="Transfer"||k==null)return u;const w=[];let D=l;const R=I;if(o===this.walletLocalData.publicKey)D=(0,m.mul)(l,"-1");else if(c===this.walletLocalData.publicKey)w.push(this.walletLocalData.publicKey);else return u;const T={blockHeight:v,currencyCode:k.currencyCode,date:Math.floor(a/1e3),isSend:D.startsWith("-"),memos:[],nativeAmount:D,networkFee:"0",ourReceiveAddresses:w,signedTx:"",txid:n,walletId:this.walletId};return(0,m.lt)(D,"0")&&(T.parentNetworkFee=R.toString()),this.addTransaction(k.currencyCode,T),u})}checkUpdateNetworkFees(){return g(this,null,function*(){try{const e=yield this.multicastServers("trx_chainParams","/wallet/getchainparameters"),n=Rt(e).chainParameter;for(const r of Object.keys(this.networkFees)){const a=n.find(o=>o.key===r);a!=null&&(this.networkFees=fe(ft({},this.networkFees),{[r]:a.value}))}}catch(e){this.log.error("checkUpdateNetworkFees error: ",e)}})}multicastServers(e,n){return g(this,arguments,function*(r,a,o={}){let c={result:"",server:"no server"},i=[];switch(r){case"trx_chainParams":i=this.networkInfo.tronNodeServers.map(l=>()=>g(this,null,function*(){return yield this.fetch(l,a)}));break;case"trx_blockNumber":case"trx_broadcastTx":case"trx_estimateEnergy":case"trx_getAccountResource":case"trx_getBalance":case"trx_getTransactionInfo":i=this.networkInfo.tronNodeServers.map(l=>()=>g(this,null,function*(){const u={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(o)};return yield this.fetch(l,a,u)}));break;case"trx_getTransactions":i=this.networkInfo.tronApiServers.map(l=>()=>g(this,null,function*(){const u={headers:{Accept:"application/json","Content-Type":"application/json"}};return yield this.fetch(l,a,u)}));break}return i=(0,f.Sy)(i),c=yield(0,f.QJ)(i),this.log(`TRX multicastServers ${r} ${c.server} won`),c.result})}calcTxFee(e){return g(this,null,function*(){var n,r;const{note:a,receiverAddress:o,tokenOpts:c,unsignedTxHex:i}=e,l=(0,f.aL)(this.currencyInfo.currencyCode,this.currencyInfo,this.allTokensMap);if(l==null)throw new Error("calcTxFee unknown denom");let u=0;if(c!=null&&o!=null){const{contractAddress:w,data:D}=c;if(this.energyEstimateCache[`${o}:${w}`]==null){const R={owner_address:N(this.walletLocalData.publicKey),contract_address:N(w),function_selector:"transfer(address,uint256)",parameter:D.slice(8)};try{const T=yield this.multicastServers("trx_estimateEnergy","/wallet/triggerconstantcontract",R),E=Qt(T),A=(n=E.transaction.ret[0])==null?void 0:n.ret;if(A!=null&&A!=="SUCCESS")throw new Error("calcTxFee Failed to estimate fee");this.energyEstimateCache[`${o}:${w}`]=E.energy_used}catch(T){this.log.warn("trx_estimateEnergy error. Using a high default.",T)}}u=Math.max(((r=this.energyEstimateCache[`${o}:${w}`])!=null?r:1e5)-this.accountResources.ENERGY,0)}this.log("Account energy: ",this.accountResources.ENERGY),this.log("Energy needed: ",u);let d=i.length/2+65+64+5;if(i.length/2<128&&d--,o!=null&&this.accountExistsCache[o]===void 0)try{const w=yield this.multicastServers("trx_getAccountResource","/wallet/getaccountresource",{address:N(o)});this.accountExistsCache[o]=(0,t.Vk)(Tt)(w)!=null}catch(w){this.log.error("calcTxFee error: Failed to call trx_getAccountResource. Allowing the user to proceed assuming high fee.",w)}c==null&&o!=null&&!this.accountExistsCache[o]&&(d=100),d<this.accountResources.BANDWIDTH&&(d=0),this.log("Account bandwidth: ",this.accountResources.BANDWIDTH),this.log("Bandwidth needed: ",d);let v=0;c==null&&o!=null&&!this.accountExistsCache[o]&&(v=this.networkFees.getCreateAccountFee+parseInt(l.multiplier)),this.log("Create account fee: ",v);const I=a!=null?this.networkFees.getMemoFee:0;this.log("Transaction note fee: ",I);const k=u*this.networkFees.getEnergyFee+d*this.networkFees.getTransactionFee+v+I;return this.log("Total fee in SUN: ",k),k.toString()})}txBuilder(e){return g(this,null,function*(){const{contractJson:n,feeLimit:r,note:a}=e,o=this.recentBlock.number.toString(16).padStart(8,"0").slice(4,8),c=this.recentBlock.hash.slice(16,32),i=this.recentBlock.timestamp+60*5*1e3,l=a==null?void 0:G.YU.stringify(oe.from(a,"ascii")),u=ye({raw_data:{contract:[n],ref_block_bytes:o,ref_block_hash:c,expiration:i,timestamp:this.recentBlock.timestamp,data:l,fee_limit:r}}),d=G.YU.stringify(u.getRawData().serializeBinary());return{transaction:u,transactionHex:d}})}makeTransferJson(e){return g(this,null,function*(){const{currencyCode:n,toAddress:r,nativeAmount:a,data:o,note:c}=e;let i,l;if(n===this.currencyInfo.currencyCode)l={parameter:{value:{to_address:N(r),owner_address:N(this.walletLocalData.publicKey),amount:parseInt(a)}},type:"TransferContract"};else{const u=this.allTokens.find(d=>d.currencyCode===n);if((u==null?void 0:u.contractAddress)==null)throw new Error(`txBuilder unknown currency code ${n}`);l={parameter:{value:{owner_address:N(this.walletLocalData.publicKey),contract_address:N(u.contractAddress),data:o,call_value:0}},type:"TriggerSmartContract"},i=this.networkInfo.defaultFeeLimit}return{contractJson:l,feeLimit:i,note:c}})}makeUnfreezeTransaction(e){return g(this,null,function*(){const{params:{resource:n}}=e,r=this.stakingStatus.stakedAmounts.find(u=>{var d;return((d=u.otherParams)==null?void 0:d.type)===n});if(r==null)throw new Error("Nothing to unfreeze");const o={contractJson:{parameter:{value:{owner_address:N(this.walletLocalData.publicKey),resource:n}},type:"UnfreezeBalanceContract"}},{transactionHex:c}=yield this.txBuilder(o),i=yield this.calcTxFee({unsignedTxHex:c});return{blockHeight:0,currencyCode:this.currencyInfo.currencyCode,date:0,isSend:r.nativeAmount.startsWith("-"),memos:[],metadata:{notes:n},nativeAmount:r.nativeAmount,networkFee:i,otherParams:o,ourReceiveAddresses:[],signedTx:"",txid:"",walletId:this.walletId}})}makeFreezeV2Transaction(e){return g(this,null,function*(){const{params:{nativeAmount:n,resource:r}}=e,o={contractJson:{parameter:{value:{owner_address:N(this.walletLocalData.publicKey),frozen_balance:parseInt(n),resource:r==="ENERGY_V2"?"ENERGY":"BANDWIDTH"}},type:"FreezeBalanceV2Contract"}},{transactionHex:c}=yield this.txBuilder(o),i=yield this.calcTxFee({unsignedTxHex:c});return{blockHeight:0,currencyCode:this.currencyInfo.currencyCode,date:0,isSend:!0,memos:[],metadata:{notes:r},nativeAmount:(0,m.mul)(n,"-1"),networkFee:i,otherParams:o,ourReceiveAddresses:[],signedTx:"",txid:"",walletId:this.walletId}})}makeUnfreezeV2Transaction(e){return g(this,null,function*(){const{params:{nativeAmount:n,resource:r}}=e,a=this.stakingStatus.stakedAmounts.find(d=>{var v;return((v=d.otherParams)==null?void 0:v.type)===r});if(a==null)throw new Error("Nothing to unfreeze");const c={contractJson:{parameter:{value:{owner_address:N(this.walletLocalData.publicKey),unfreeze_balance:parseInt(n),resource:r==="ENERGY_V2"?"ENERGY":"BANDWIDTH"}},type:"UnfreezeBalanceV2Contract"}},{transactionHex:i}=yield this.txBuilder(c),l=yield this.calcTxFee({unsignedTxHex:i});return{blockHeight:0,currencyCode:this.currencyInfo.currencyCode,date:0,isSend:a.nativeAmount.startsWith("-"),memos:[],metadata:{notes:r},nativeAmount:a.nativeAmount,networkFee:l,otherParams:c,ourReceiveAddresses:[],signedTx:"",txid:"",walletId:this.walletId}})}startEngine(){return g(this,null,function*(){this.engineOn=!0,this.addToLoop("checkBlockchainInnerLoop",ve).catch(()=>{}),this.addToLoop("checkAccountInnerLoop",_t).catch(()=>{}),this.addToLoop("checkTokenBalances",_t).catch(()=>{}),this.addToLoop("checkUpdateNetworkFees",we).catch(()=>{}),this.addToLoop("queryTransactions",Te).catch(()=>{}),yield xt(ut.prototype,this,"startEngine").call(this)})}getStakingStatus(){return g(this,null,function*(){return ft({},this.stakingStatus)})}resyncBlockchain(){return g(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getMaxSpendable(e){return g(this,null,function*(){var n;e=(0,bt.s)(e,this.currencyInfo);const{memos:r=[]}=e,a=this.getBalance({currencyCode:e.currencyCode});if(e.spendTargets.length!==1)throw new Error("Error: only one output allowed");const{publicAddress:o}=e.spendTargets[0],c=((n=r[0])==null?void 0:n.type)==="text"?r[0].value:void 0;if(o==null||e.currencyCode==null)throw new Error("Error: need recipient address and/or currencyCode");if(e.currencyCode===this.currencyInfo.currencyCode){const i=(l,u)=>g(this,null,function*(){const d=(0,m.sub)(u,l);if((0,m.lte)(d,"1"))return l;const v=(0,m.add)(l,(0,m.div)(d,"2")),I={toAddress:o,currencyCode:this.currencyInfo.currencyCode,nativeAmount:v},{contractJson:k,feeLimit:w}=yield this.makeTransferJson(I),{transactionHex:D}=yield this.txBuilder({contractJson:k,feeLimit:w,note:c});e.spendTargets[0].nativeAmount=v;const R=yield this.calcTxFee({receiverAddress:o,unsignedTxHex:D,note:c}),T=(0,m.add)(v,R);return(0,m.gt)(T,a)?yield i(l,v):yield i(v,u)});return yield i("0",(0,m.add)(a,"1"))}else return e.spendTargets[0].nativeAmount=a,yield this.makeSpend(e),a})}makeSpend(e){return g(this,null,function*(){var n,r,a;if(e=(0,bt.s)(e,this.currencyInfo),e.otherParams!=null){let z;if(z=(0,t.Vk)(Ht)(e.otherParams),z!=null)return yield this.makeUnfreezeTransaction(z);if(z=(0,t.Vk)(Nt)(e.otherParams),z!=null)return yield this.makeFreezeV2Transaction(z);if(z=(0,t.Vk)(Ot)(e.otherParams),z!=null)return yield this.makeUnfreezeV2Transaction(z)}const{edgeSpendInfo:o,currencyCode:c}=xt(ut.prototype,this,"makeSpendCheck").call(this,e),{memos:i=[]}=o,l=c!==this.currencyInfo.currencyCode;if(o.spendTargets.length!==1)throw new Error("Error: only one output allowed");const{nativeAmount:u,publicAddress:d,otherParams:v}=o.spendTargets[0];if(d==null)throw new Error("makeSpend Missing publicAddress");if(u==null)throw new Ct.$D;const I=(n=v==null?void 0:v.data)!=null?n:c!==this.currencyInfo.currencyCode?se(d,u):void 0,k=l?this.allTokens.find(z=>z.currencyCode===c):void 0,w=((r=i[0])==null?void 0:r.type)==="text"?i[0].value:void 0,D={currencyCode:c,toAddress:d,nativeAmount:u,contractAddress:k==null?void 0:k.contractAddress,data:I,note:w},{contractJson:R,feeLimit:T}=yield this.makeTransferJson(D),{transactionHex:E}=yield this.txBuilder({contractJson:R,feeLimit:T,note:w}),A=(k==null?void 0:k.contractAddress)!=null&&I!=null?{contractAddress:k==null?void 0:k.contractAddress,data:I}:void 0,_=yield this.calcTxFee({receiverAddress:d,unsignedTxHex:E,tokenOpts:A,note:w});let P,B,W,Z;l?(P=u,B="0",W=_,Z=W):(P=(0,m.add)(u,_),B=_,Z=P);const K=(a=this.walletLocalData.totalBalances[this.currencyInfo.currencyCode])!=null?a:"0";if((0,m.gt)(Z,K))throw new Ct.C_({currencyCode:this.currencyInfo.currencyCode,networkFee:_});const V={contractJson:R,feeLimit:T,note:w},j={blockHeight:0,currencyCode:c,date:0,isSend:!0,memos:i,nativeAmount:(0,m.mul)(P,"-1"),networkFee:B,otherParams:V,ourReceiveAddresses:[],signedTx:"",txid:"",walletId:this.walletId};return W!=null&&(j.parentNetworkFee=W),j})}signTx(e,n){return g(this,null,function*(){const r=(0,f.Xp)(e),a=yield this.txBuilder(r),{tronKey:o}=ht(n),c=ge(a.transaction);a.transaction.txID=c.replace("0x","");const i=yield me(o,a.transaction);i.addSignature(G.YU.parse(i.signature[0]));const l=G.YU.stringify(i.serializeBinary());return e.signedTx=l,e})}broadcastTx(e){return g(this,null,function*(){const n={transaction:e.signedTx},r=yield this.multicastServers("trx_broadcastTx","/wallet/broadcasthex",n),a=Gt(r);if(!a.result)throw new Error(a.message);const{toAddress:o,contractAddress:c}=(0,f.Xp)(e);return e.currencyCode===this.currencyInfo.currencyCode&&o!=null&&(this.accountExistsCache[o]=!0),c!=null&&delete this.energyEstimateCache[`${o}:${c}`],e.txid=a.txid,e.date=Date.now()/1e3,e})}}function Ce(s,e,n,r){return g(this,null,function*(){const a=wt(n),o=new ut(s,e,a,r);return yield o.loadEngine(),o})}var It=h(48764).Buffer,X=(s,e,n)=>new Promise((r,a)=>{var o=l=>{try{i(n.next(l))}catch(u){a(u)}},c=l=>{try{i(n.throw(l))}catch(u){a(u)}},i=l=>l.done?r(l.value):Promise.resolve(l.value).then(o,c);i((n=n.apply(s,e)).next())});const{utils:{crypto:{isAddressValid:mt,pkToAddress:be}}}=M();class Pt{constructor(e){const{builtinTokens:n,currencyInfo:r,initOptions:a,io:o,log:c,networkInfo:i}=e;this.builtinTokens=n,this.currencyInfo=r,this.initOptions=at(a),this.io=o,this.log=c,this.networkInfo=i}getDisplayPrivateKey(e){return X(this,null,function*(){var n;const r=ht(e.keys);return(n=r.tronMnemonic)!=null?n:r.tronKey})}getDisplayPublicKey(e){return X(this,null,function*(){const{keys:n}=wt(e);return n.publicKey})}importPrivateKey(e,n){return X(this,null,function*(){var r;if(/^(0x)?[0-9a-fA-F]{64}$/.test(e)){const a=It.from(e.replace(/^0x/,""),"hex");if(Q().isValidPrivate(a)===!0)throw new Error("Invalid private key");return{tronKey:a.toString("hex")}}else{if(!(0,F.validateMnemonic)(e))throw new Error("Invalid input");const a=(r=n==null?void 0:n.derivationPath)!=null?r:this.networkInfo.defaultDerivationPath,o=yield this._mnemonicToTronKey(e,a);return{tronMnemonic:e,tronKey:o,derivationPath:a}}})}createPrivateKey(e){return X(this,null,function*(){if(e!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const n=It.from(this.io.random(32)).toString("hex"),r=(0,F.entropyToMnemonic)(n);return yield this.importPrivateKey(r)})}_mnemonicToTronKey(e,n){return X(this,null,function*(){const r=yield(0,F.mnemonicToSeed)(e);return et().fromMasterSeed(r).derivePath(n).getWallet().getPrivateKeyString().replace("0x","")})}derivePublicKey(e){return X(this,null,function*(){if(e.type!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const{tronKey:n}=ht(e.keys);return{publicKey:be(n)}})}parseUri(e,n,r){return X(this,null,function*(){var a;const o={[this.currencyInfo.pluginId]:!0},{smartPayPublicAddress:c,smartPayUserId:i}=this.initOptions,{parsedUri:l,edgeParsedUri:u}=(0,ot.k)(this.currencyInfo,e,o,n!=null?n:this.currencyInfo.currencyCode,r),d=(a=u.publicAddress)!=null?a:"";if(mt(d))return u.uniqueIdentifier=l.query.memo,u;if(n==null||n==="USDT"){const v=yield U(this.io,this.builtinTokens,e,c,i);if(v!=null)return v}throw new Error("InvalidPublicAddressError")})}encodeUri(e){return X(this,arguments,function*(n,r=[]){const{publicAddress:a,nativeAmount:o,currencyCode:c}=n;if(!mt(a))throw new Error("InvalidPublicAddressError");let i;if(typeof o=="string"){const u=(0,f.Qs)(c!=null?c:this.currencyInfo.currencyCode,this.currencyInfo,r);if(u==null)throw new Error("InternalErrorInvalidCurrencyCode");i=(0,m.div)(o,u.multiplier,18)}return(0,ot.Q)(n,this.currencyInfo.pluginId,i)})}getTokenId(e){return X(this,null,function*(){(0,st.Rp)(e);const n=(0,st.Oj)(e.networkLocation);if(n==null||!mt(n.contractAddress))throw new Error("ErrorInvalidContractAddress");return n.contractAddress})}}function Ae(s){return X(this,null,function*(){return new Pt(s)})}}}]);
|