edge-currency-accountbased 0.22.21 → 0.23.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 +7 -0
- package/android/src/main/assets/edge-currency-accountbased/{645.chunk.js → 216.chunk.js} +6 -6
- package/android/src/main/assets/edge-currency-accountbased/244.chunk.js +1 -1
- package/android/src/main/assets/edge-currency-accountbased/387.chunk.js +9 -0
- package/android/src/main/assets/edge-currency-accountbased/491.chunk.js +1 -1
- package/android/src/main/assets/edge-currency-accountbased/549.chunk.js +1 -1
- package/android/src/main/assets/edge-currency-accountbased/94.chunk.js +8 -9
- package/android/src/main/assets/edge-currency-accountbased/bnb.chunk.js +3 -3
- package/android/src/main/assets/edge-currency-accountbased/edge-currency-accountbased.js +2 -2
- package/android/src/main/assets/edge-currency-accountbased/eos.chunk.js +11 -11
- package/android/src/main/assets/edge-currency-accountbased/ethereum.chunk.js +9 -9
- 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 -4
- package/android/src/main/assets/edge-currency-accountbased/solana.chunk.js +3 -3
- package/android/src/main/assets/edge-currency-accountbased/stellar.chunk.js +6 -6
- 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/binance/bnbEngine.js +28 -16
- package/lib/binance/bnbTypes.js +11 -0
- package/lib/common/engine.js +47 -3
- package/lib/common/types.js +20 -0
- package/lib/declare-modules.d.js +0 -22
- package/lib/eos/eosEngine.js +32 -21
- package/lib/eos/eosTypes.js +16 -0
- package/lib/eos/info/eosInfo.js +3 -1
- package/lib/ethereum/ethEngine.js +90 -140
- package/lib/ethereum/ethTypes.js +64 -0
- package/lib/fio/fioConst.js +26 -55
- package/lib/fio/fioEngine.js +830 -609
- package/lib/fio/fioError.js +15 -22
- package/lib/fio/fioInfo.js +13 -23
- package/lib/fio/fioPlugin.js +85 -94
- package/lib/fio/fioTypes.js +180 -1
- package/lib/hedera/hederaEngine.js +24 -12
- package/lib/hedera/hederaTypes.js +37 -0
- package/lib/polkadot/polkadotEngine.js +30 -10
- package/lib/polkadot/polkadotTypes.js +37 -0
- package/lib/solana/solanaEngine.js +25 -27
- package/lib/solana/solanaTypes.js +37 -0
- package/lib/stellar/stellarEngine.js +21 -19
- package/lib/stellar/stellarTypes.js +10 -0
- package/lib/tezos/tezosEngine.js +23 -18
- package/lib/tezos/tezosTypes.js +16 -0
- package/lib/tron/tronEngine.js +14 -7
- package/lib/tron/tronPlugin.js +1 -1
- package/lib/tron/tronTypes.js +15 -11
- package/lib/xrp/xrpEngine.js +86 -59
- package/lib/xrp/xrpTypes.js +16 -0
- package/lib/zcash/zecEngine.js +33 -27
- package/lib/zcash/zecInfo.js +4 -1
- package/lib/zcash/zecPlugin.js +20 -6
- package/lib/zcash/zecTypes.js +57 -1
- package/package.json +3 -3
- package/android/src/main/assets/edge-currency-accountbased/206.chunk.js +0 -8
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[805],{79014:function(ce,M,p){"use strict";p.d(M,{Q:function(){return V},k:function(){return x}});var P=p(77591),j=p.n(P),Q=p(24350),E=p(84564),ee=p.n(E),X=p(76714),m=Object.defineProperty,c=Object.getOwnPropertySymbols,y=Object.prototype.hasOwnProperty,q=Object.prototype.propertyIsEnumerable,F=(g,b,a)=>b in g?m(g,b,{enumerable:!0,configurable:!0,writable:!0,value:a}):g[b]=a,A=(g,b)=>{for(var a in b||(b={}))y.call(b,a)&&F(g,a,b[a]);if(c)for(var a of c(b))q.call(b,a)&&F(g,a,b[a]);return g};function x(g,b,a,T,N){const k=A({},ee()(b,{},!0)),B=b.startsWith(`${g.pluginId}://`);if(k.protocol!=null&&(k.protocol=k.protocol.replace(":","")),k.protocol!=null&&k.protocol!==""&&!a[k.protocol])throw new Error(`Uri protocol '${k.protocol}' is not supported for ${g.pluginId}.`);if(k.host===""&&k.pathname==="")throw new Error("Path and host not found in uri.");const w={publicAddress:k.host!==""?k.host:k.pathname.split("/")[0]},z=k.query.label,K=k.query.message,J=k.query.category;(z!=null||K!=null||J!=null||B)&&(w.metadata={},w.metadata.name=z,w.metadata.notes=K,w.metadata.category=J,w.metadata.gateway=B!=null?B:!1);const U=k.query.amount;if(U!=null&&typeof U=="string"){T==null&&(T=g.currencyCode);const Y=(0,X.cp)(g,T!=null?T:"",N);if(Y==null)throw new Error("InternalErrorInvalidCurrencyCode");let G=(0,P.mul)(U,Y.multiplier);G=(0,P.toFixed)(G,0,0),w.nativeAmount=G,w.currencyCode=T}return{edgeParsedUri:w,parsedUri:k}}function V(g,b,a){if(g.publicAddress==null)throw new Error("InvalidPublicAddressError");if(a==null&&g.label==null&&g.message==null)return g.publicAddress;{let T="";a!=null&&(T+="amount="+a+"&"),(g.label!=null||g.message!=null)&&(typeof g.label=="string"&&(T+="label="+g.label+"&"),typeof g.message=="string"&&(T+="message="+g.message+"&")),T=T.substr(0,T.length-1);const N={scheme:b,path:g.publicAddress,query:T};return(0,Q.qC)(N)}}},64139:function(ce,M,p){"use strict";p.r(M),p.d(M,{FioTools:function(){return le},checkAddress:function(){return ie},makeCurrencyEngine:function(){return ye},makeCurrencyTools:function(){return pe}});var P=p(93491),j=p(37297),Q=p(45234),E=p(77591),ee=p(2153),X=p(79014),m=p(76714),c=p(5607),y=p(14023);const q=[400,403,404],F={INVALID_FIO_NAME:y.j.defaultSettings.errorCodes.INVALID_FIO_ADDRESS,ALREADY_REGISTERED:y.j.defaultSettings.errorCodes.ALREADY_REGISTERED,DOMAIN_IS_NOT_REGISTERED:y.j.defaultSettings.errorCodes.FIO_DOMAIN_IS_NOT_EXIST,DOMAIN_IS_NOT_PUBLIC:y.j.defaultSettings.errorCodes.FIO_DOMAIN_IS_NOT_PUBLIC,SERVER_ERROR:y.j.defaultSettings.errorCodes.SERVER_ERROR,ALREADY_SENT_REGISTRATION_REQ_FOR_DOMAIN:y.j.defaultSettings.errorCodes.ALREADY_SENT_REGISTRATION_REQ_FOR_DOMAIN};class A extends Error{constructor(e,s,t,n){super(e),Error.captureStackTrace&&Error.captureStackTrace(this,A),this.name="FioError",s&&(this.errorCode=s),t&&(this.labelCode=t),n&&(this.json=n)}}var x=p(37858),V=p(39011),g=p(94935),b=p(50244),a=p(82448);const T=(0,a.su)({fio_domains:(0,a._2)((0,a.su)({fio_domain:a.XC,expiration:a.XC,is_public:a.mH})),fio_addresses:(0,a._2)((0,a.su)({fio_address:a.XC,remaining_bundled_tx:a.mH}))}),N=(0,a.su)({account_action_seq:a.mH,block_num:a.mH,block_time:a.XC,action_trace:(0,a.su)({receiver:a.XC,act:(0,a.su)({account:a.XC,name:a.XC,authorization:(0,a._2)((0,a.su)({actor:a.XC,permission:a.XC})),data:(0,a.su)({payee_public_key:(0,a.Zz)(a.XC),amount:(0,a.Zz)(a.mH),max_fee:(0,a.Zz)(a.mH),actor:(0,a.Zz)(a.XC),tpid:(0,a.Zz)(a.XC),quantity:(0,a.Zz)(a.XC),memo:(0,a.Zz)(a.XC),to:(0,a.Zz)(a.XC),from:(0,a.Zz)(a.XC)}),hex_data:a.XC}),trx_id:a.XC,block_num:a.mH,block_time:a.XC,producer_block_id:a.XC})}),k=(0,a.su)({actions:(0,a._2)(N)}),B=(0,a.su)({balance:a.mH,available:a.mH,staked:a.mH,srps:a.mH,roe:a.XC});var ne=Object.defineProperty,w=Object.defineProperties,z=Object.getOwnPropertyDescriptors,K=Object.getOwnPropertySymbols,J=Object.getPrototypeOf,U=Object.prototype.hasOwnProperty,Y=Object.prototype.propertyIsEnumerable,G=Reflect.get,oe=(S,e,s)=>e in S?ne(S,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):S[e]=s,I=(S,e)=>{for(var s in e||(e={}))U.call(e,s)&&oe(S,s,e[s]);if(K)for(var s of K(e))Y.call(e,s)&&oe(S,s,e[s]);return S},W=(S,e)=>w(S,z(e)),te=(S,e,s)=>G(J(S),s,e),f=(S,e,s)=>new Promise((t,n)=>{var o=r=>{try{i(s.next(r))}catch(l){n(l)}},h=r=>{try{i(s.throw(r))}catch(l){n(l)}},i=r=>r.done?t(r.value):Promise.resolve(r.value).then(o,h);i((s=s.apply(S,e)).next())});const ae=1e4,ue=15e3,de=1e4,he=1e4,fe=[c.BP[c.aO.transferTokens],c.BP[c.aO.unStakeFioTokens]];class H extends b.P{constructor(e,s,t,n,o){super(e,s,t,n),this.fioRequestsListChanged=(i,r)=>{function l(d,u){for(const _ of d)if(u.findIndex(C=>C.fio_request_id===_.fio_request_id)<0)return!0;return!1}return!!(l(i,r)||l(r,i))},this.removeFioRequest=(i,r)=>{const l=this.otherData.fioRequests[r].findIndex(d=>d.fio_request_id===`${i}`);l>-1&&this.otherData.fioRequests[r].splice(l,1)};const h=(0,m.zR)(e);this.fetchCors=h,this.tpid=o,this.recentFioFee={publicAddress:"",fee:0},this.fioSdkInit(),this.otherMethods={fioAction:(i,r)=>f(this,null,function*(){switch(i){case"addPublicAddresses":case"addPublicAddress":case"requestFunds":{const{fee:l}=yield this.multicastServers(c.HG[i].action,{[c.HG[i].propName]:r[c.HG[i].propName]});r.maxFee=l;break}case"rejectFundsRequest":{const{fee:l}=yield this.multicastServers(c.HG[i].action,{[c.HG[i].propName]:r[c.HG[i].propName]});r.maxFee=l;const d=yield this.multicastServers(i,r);return this.removeFioRequest(r.fioRequestId,c.$G.PENDING),this.localDataDirty(),d}case"cancelFundsRequest":{const l=yield this.multicastServers(i,r);return this.removeFioRequest(r.fioRequestId,c.$G.SENT),this.localDataDirty(),l}case"recordObtData":{const{fee:l}=yield this.multicastServers(c.HG[i].action,{[c.HG[i].propName]:r[c.HG[i].propName]});if(r.maxFee=l,r.fioRequestId){this.otherData.fioRequestsToApprove[r.fioRequestId]=r,this.localDataDirty();const d=yield this.multicastServers(i,r);return d&&d.status==="sent_to_blockchain"&&(delete this.otherData.fioRequestsToApprove[r.fioRequestId],this.removeFioRequest(r.fioRequestId,c.$G.PENDING),this.localDataDirty()),d}break}case"registerFioAddress":{const{fee:l}=yield this.multicastServers("getFee",{endPoint:x.EndPoint[i]});r.maxFee=l;const d=yield this.multicastServers(i,r);return r.ownerPublicKey&&r.ownerPublicKey!==this.walletInfo.keys.publicKey?{feeCollected:d.fee_collected}:(this.otherData.fioAddresses.find(({name:_})=>_===r.fioAddress)==null&&(this.otherData.fioAddresses.push({name:r.fioAddress,bundledTxs:void 0}),this.localDataDirty()),d)}case"renewFioDomain":{const{fee:l}=yield this.multicastServers("getFee",{endPoint:x.EndPoint[i]});r.maxFee=l;const d=yield this.multicastServers(i,r),u=this.otherData.fioDomains.find(({name:_})=>_===r.fioDomain);return u!=null&&(u.expiration=d.expiration,this.localDataDirty()),d}case"registerFioDomain":{const{fee:l}=yield this.multicastServers("getFee",{endPoint:x.EndPoint.registerFioDomain});return r.max_fee=l,yield this.multicastServers("pushTransaction",{action:"regdomain",account:"",data:W(I({},r),{tpid:o})})}case"transferFioDomain":{const l=yield this.multicastServers(i,r),d=this.otherData.fioDomains.findIndex(({name:u})=>u===r.fioDomain);return d&&(this.otherData.fioDomains.splice(d,1),this.localDataDirty()),l}case"transferFioAddress":{const l=yield this.multicastServers(i,r),d=this.otherData.fioAddresses.findIndex(({name:u})=>u===r.fioAddress);return d&&(this.otherData.fioAddresses.splice(d,1),this.localDataDirty()),l}case"addBundledTransactions":{const l=this.otherData.fioAddresses.find(({name:u})=>u===r.fioAddress);if(l==null)throw new A("Fio Address is not found in engine");const d=yield this.multicastServers(i,r);return l.bundledTxs+=c.BB,this.localDataDirty(),I({bundledTxs:l.bundledTxs},d)}}return yield this.multicastServers(i,r)}),getFee:(i,r="")=>f(this,null,function*(){const{fee:l}=yield this.multicastServers("getFee",{endPoint:x.EndPoint[c.eD[i]],fioAddress:r});return l}),getFioAddresses:()=>f(this,null,function*(){return this.otherData.fioAddresses}),getFioAddressNames:()=>f(this,null,function*(){return this.otherData.fioAddresses.map(i=>i.name)}),getFioDomains:()=>f(this,null,function*(){return this.otherData.fioDomains}),getFioRequests:(i,r,l=50)=>f(this,null,function*(){const d=l*(r-1),u=l*r;return this.otherData.fioRequests[i].sort((_,C)=>_.time_stamp<C.time_stamp?1:-1).slice(d,u)})}}localDataDirty(){this.walletLocalDataDirty=!0}setOtherData(e){this.otherData=(0,c.CL)(e)}getUTCDate(e){const s=new Date(e);return Date.UTC(s.getFullYear(),s.getMonth(),s.getDate(),s.getHours(),s.getMinutes(),s.getSeconds())}getUnlockDate(e){const s=Math.floor(e.getTime()/c.qj)*c.qj;return new Date(s+c.dm)}loadEngine(e,s,t){return f(this,null,function*(){if(yield te(H.prototype,this,"loadEngine").call(this,e,s,t),typeof this.walletInfo.keys.ownerPublicKey!="string")if(s.keys.ownerPublicKey)this.walletInfo.keys.ownerPublicKey=s.keys.ownerPublicKey;else{const n=yield e.derivePublicKey(this.walletInfo);this.walletInfo.keys.ownerPublicKey=n.ownerPublicKey}yield this.checkAbiAccounts()})}fioSdkInit(){const e=(0,m.Sy)(this.currencyInfo.defaultSettings.apiUrls.map(s=>s))[0];this.fioSdk=new P.rn(this.walletInfo.keys.fioKey,this.walletInfo.keys.publicKey,e,this.fetchCors,void 0,this.tpid),this.fioSdkPreparedTrx=new P.rn(this.walletInfo.keys.fioKey,this.walletInfo.keys.publicKey,e,this.fetchCors,void 0,this.tpid,!0)}checkAbiAccounts(){return f(this,null,function*(){j.Transactions.abiMap.size!==V.Constants.rawAbiAccountName.length&&(yield(0,m.QJ)((0,m.Sy)(this.currencyInfo.defaultSettings.apiUrls.map(e=>()=>f(this,null,function*(){return yield this.loadAbiAccounts(e)})))))})}loadAbiAccounts(e){return f(this,null,function*(){this.setFioSdkBaseUrl(e);for(const s of V.Constants.rawAbiAccountName){if(j.Transactions.abiMap.get(s))continue;const t=yield this.fioSdk.getAbi(s);j.Transactions.abiMap.set(t.account_name,t)}})}setFioSdkBaseUrl(e){j.Transactions.baseUrl=e}checkBlockchainInnerLoop(){return f(this,null,function*(){try{const s=(yield this.multicastServers("getChainInfo")).head_block_num;this.walletLocalData.blockHeight!==s&&(this.checkDroppedTransactionsThrottled(),this.walletLocalData.blockHeight=s,this.localDataDirty(),this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight))}catch(e){this.error("checkBlockchainInnerLoop Error fetching height: ",e)}})}getBalance(e){return super.getBalance(e)}doInitialBalanceCallback(){var e;super.doInitialBalanceCallback();const s=this.currencyInfo.defaultSettings.balanceCurrencyCodes;for(const t in s)try{this.currencyEngineCallbacks.onBalanceChanged(s[t],(e=this.walletLocalData.totalBalances[s[t]])!=null?e:"0")}catch(n){this.log.error("doInitialBalanceCallback Error for currencyCode",s[t],n)}try{this.currencyEngineCallbacks.onStakingStatusChanged(I({stakedAmounts:[]},this.otherData.stakingStatus))}catch(t){this.error("doInitialBalanceCallback onStakingStatusChanged",t)}}checkUnStakeTx(e){return e.name===c.BP[c.aO.unStakeFioTokens]||e.data!=null&&e.data.memo===c.Nd}updateStakingStatus(e,s,t,n){(this.otherData.stakingStatus==null||this.otherData.stakingStatus.stakedAmounts==null)&&(this.otherData.stakingStatus={stakedAmounts:[]});const o=this.getUnlockDate(new Date(this.getUTCDate(s))),h=this.otherData.stakingStatus.stakedAmounts.findIndex(i=>{var r;return((r=i.unlockDate)==null?void 0:r.getTime())===o.getTime()});if(h<0){const i=this.otherData.stakingStatus.stakedAmounts.findIndex((l,d)=>{var u,_;return o.getTime()>=((_=(u=l.unlockDate)==null?void 0:u.getTime())!=null?_:0)}),r=i<0?this.otherData.stakingStatus.stakedAmounts.length:i;this.otherData.stakingStatus.stakedAmounts.splice(r,0,{nativeAmount:e,unlockDate:o,otherParams:{date:new Date(s),txs:[{txId:t,nativeAmount:e,blockTime:s,txName:n}]}})}else{const i=W(I({},this.otherData.stakingStatus.stakedAmounts[h]),{nativeAmount:"0"}),r=i.otherParams.txs.findIndex(({txId:l,txName:d})=>l===t&&d===n);r<0?i.otherParams.txs.push({txId:t,nativeAmount:e,blockTime:s,txName:n}):i.otherParams.txs[r]={txId:t,nativeAmount:e,blockTime:s,txName:n};for(const l of i.otherParams.txs)i.nativeAmount=(0,E.add)(i.nativeAmount,l.nativeAmount);this.otherData.stakingStatus.stakedAmounts[h]=i}this.localDataDirty();try{this.currencyEngineCallbacks.onStakingStatusChanged(I({},this.otherData.stakingStatus))}catch{this.error("onStakingStatusChanged error")}}getStakingStatus(){return f(this,null,function*(){return I({},this.otherData.stakingStatus)})}processTransaction(e,s,t=this.currencyInfo.currencyCode){const{act:{name:n,data:o,account:h,authorization:i}}=e.action_trace;let r,l,d="0",u={account:h,name:n,authorization:i,data:o,meta:{}};const _=[];if(e.block_num<=this.otherData.highestTxHeight)return e.block_num;if(fe.includes(n)){r="0",n===c.BP[c.aO.transferTokens]&&o.amount!=null&&(r=o.amount.toString(),l=o.actor,o.payee_public_key===this.walletInfo.keys.publicKey?(_.push(this.walletInfo.keys.publicKey),l===s&&(r="0")):r=`-${r}`);const C=this.findTransaction(t,e.action_trace.trx_id);if(C>-1){const D=this.transactionList[t][C];if(u=W(I(I({},D.otherParams),u),{data:I(I({},D.otherParams!=null&&D.otherParams.data!=null?D.otherParams.data:{}),u.data),meta:I(I({},D.otherParams!=null&&D.otherParams.meta!=null?D.otherParams.meta:{}),u.meta)}),u.meta.isTransferProcessed)return e.block_num;u.meta.isFeeProcessed?n===c.BP[c.aO.transferTokens]?(r=(0,E.sub)(r,D.networkFee),d=D.networkFee):(r=D.nativeAmount,d="0"):this.error("processTransaction error - existing spend transaction should have isTransferProcessed or isFeeProcessed set")}this.checkUnStakeTx(u)&&this.updateStakingStatus(o.amount!=null?o.amount.toString():"0",e.block_time,e.action_trace.trx_id,n),u.meta.isTransferProcessed=!0;const O={txid:e.action_trace.trx_id,date:this.getUTCDate(e.block_time)/1e3,currencyCode:t,blockHeight:e.block_num>0?e.block_num:0,nativeAmount:r,networkFee:d,parentNetworkFee:"0",ourReceiveAddresses:_,signedTx:"",otherParams:u,walletId:this.walletId};this.addTransaction(t,O)}if(n===c.BP.transfer&&o.quantity!=null){const[C]=o.quantity.split(" "),O=C.toString();let D=(0,m.cp)(this.currencyInfo,t);if(D==null&&(D=(0,m.cp)(this.currencyInfo,this.currencyInfo.currencyCode),D==null))return this.error(`Received unsupported currencyCode: ${t}`),0;const $=(0,E.mul)(O,D.multiplier);o.to===s?(r=`${$}`,d=`-${$}`):(r=`-${$}`,d=$);const L=this.findTransaction(t,e.action_trace.trx_id);if(L>-1){const R=this.transactionList[t][L];if(u=W(I(I({},u),R.otherParams),{data:I(I({},u.data),R.otherParams!=null&&R.otherParams.data!=null?R.otherParams.data:{}),meta:I(I({},u.meta),R.otherParams!=null&&R.otherParams.meta!=null?R.otherParams.meta:{})}),u.meta.isFeeProcessed)return e.block_num;u.meta.isTransferProcessed?o.to!==s?r=(0,E.sub)(R.nativeAmount,d):d="0":this.error("processTransaction error - existing spend transaction should have isTransferProcessed or isFeeProcessed set")}this.checkUnStakeTx(u)&&this.updateStakingStatus($,e.block_time,e.action_trace.trx_id,n),u.meta.isFeeProcessed=!0;const Z={txid:e.action_trace.trx_id,date:this.getUTCDate(e.block_time)/1e3,currencyCode:t,blockHeight:e.block_num>0?e.block_num:0,nativeAmount:r,networkFee:d,signedTx:"",ourReceiveAddresses:[],otherParams:u,walletId:this.walletId};this.addTransaction(t,Z)}return e.block_num}checkTransactions(e=0){return f(this,null,function*(){if(!this.currencyInfo.defaultSettings.historyNodeUrls[e])return!1;let s=this.otherData.highestTxHeight,t=0;const n=this.fioSdk.transactions.getActor(this.walletInfo.keys.publicKey);try{const i=yield this.requestHistory(e,{account_name:n,pos:-1,offset:-1},c.pg.getActions);if(i.error&&i.error.noNodeForIndex)return!1;if(k(i),i.actions.length)t=i.actions[0].account_action_seq;else return!0}catch{return yield this.checkTransactions(++e)}let o=t,h=!1;for(;!h&&!(o<0);){let i;try{if(i=yield this.requestHistory(e,{account_name:n,pos:o,offset:-c.eG+1},c.pg.getActions),i.error&&i.error.noNodeForIndex)return!1;let r=[];if(i.actions&&i.actions.length>0)r=i.actions;else break;for(let l=r.length-1;l>-1;l--){const d=r[l];N(d);const u=this.processTransaction(d,n);if(u>s)s=u;else if(u===s&&l===c.eG-1||u<this.otherData.highestTxHeight){h=!0;break}}if(!r.length||r.length<c.eG)break;o-=c.eG}catch{return yield this.checkTransactions(++e)}}return s>this.otherData.highestTxHeight&&(this.otherData.highestTxHeight=s,this.localDataDirty()),!0})}checkTransactionsInnerLoop(){return f(this,null,function*(){let e;try{e=yield this.checkTransactions()}catch(s){return this.error("checkTransactionsInnerLoop fetches failed with error: ",s),!1}e&&(this.tokenCheckTransactionsStatus.FIO=1,this.updateOnAddressesChecked()),this.transactionsChangedArray.length>0&&(this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[])})}requestHistory(e,s,t){return f(this,null,function*(){if(!this.currencyInfo.defaultSettings.historyNodeUrls[e])return{error:{noNodeForIndex:!0}};const n=this.currencyInfo.defaultSettings.historyNodeUrls[e];return yield(yield this.fetchCors(`${n}history/${t||""}`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(s)})).json()})}fioApiRequest(e,s,t,n=!1){return f(this,null,function*(){var o;const h=n?this.fioSdkPreparedTrx:this.fioSdk;this.setFioSdkBaseUrl(e);let i;try{switch(s){case"getChainInfo":i=yield h.transactions.getChainInfo();break;case"getFioBalance":if(i=yield h.genericAction(s,t),B(i),i.balance!=null&&i.balance<0)throw new Error("Invalid balance");break;default:i=yield h.genericAction(s,t)}}catch(r){if(r.errorCode&&q.includes(r.errorCode))r.json&&r.json.fields&&r.json.fields[0]&&r.json.fields[0].error&&(r.message=r.json.fields[0].error),i={isError:!0,data:{code:r.errorCode,message:(o=r.message)!=null?o:(0,m.HY)(r),json:r.json,list:r.list}},r.errorCode!==404&&this.log(`fioApiRequest error. actionName: ${s} - apiUrl: ${e} - message: ${JSON.stringify(r.json)}`);else throw this.log(`fioApiRequest error. actionName: ${s} - apiUrl: ${e} - message: `,r),r}return i})}executePreparedTrx(e,s,t){return f(this,null,function*(){this.setFioSdkBaseUrl(e);let n;this.warn(`executePreparedTrx. preparedTrx: ${JSON.stringify(t)} - apiUrl: ${e}`);try{n=yield this.fioSdk.executePreparedTrx(s,t),this.warn(`executePreparedTrx. res: ${JSON.stringify(n)} - apiUrl: ${e} - endpoint: ${s}`)}catch(o){throw o.errorCode&&q.includes(o.errorCode)?(this.log(`executePreparedTrx error. requestParams: ${JSON.stringify(t)} - apiUrl: ${e} - endpoint: ${s} - message: ${JSON.stringify(o.json)}`),o.json&&o.json.fields&&o.json.fields[0]&&o.json.fields[0].error&&(o.message=o.json.fields[0].error),o):(this.log(`executePreparedTrx error. requestParams: ${JSON.stringify(t)} - apiUrl: ${e} - endpoint: ${s} - message: `,o),o)}return n})}multicastServers(e,s){return f(this,null,function*(){let t;if(c.K1[e]){this.warn(`multicastServers prepare trx. actionName: ${e} - res: ${JSON.stringify(s)}`);const n=yield(0,m.QJ)((0,m.Sy)(this.currencyInfo.defaultSettings.apiUrls.map(o=>()=>f(this,null,function*(){return yield this.fioApiRequest(o,e,s,!0)}))));if(this.warn(`multicastServers executePreparedTrx. actionName: ${e} - res: ${JSON.stringify(n)}`),t=yield(0,m.Wp)((0,m.Sy)(this.currencyInfo.defaultSettings.apiUrls.map(o=>f(this,null,function*(){return yield this.executePreparedTrx(o,x.EndPoint[c.VW[e]],n)})))),this.warn(`multicastServers res. actionName: ${e} - res: ${JSON.stringify(t)}`),!t)throw new Error("Service is unavailable")}else e==="getFioNames"?t=yield(0,m.ml)(this.currencyInfo.defaultSettings.apiUrls.map(n=>f(this,null,function*(){return yield(0,m.Vs)(this.fioApiRequest(n,e,s),1e4)})),n=>{try{return JSON.stringify(T(n))}catch(o){this.log("getFioNames checkResult function returned error ",o)}},2):t=yield(0,m.QJ)((0,m.Sy)(this.currencyInfo.defaultSettings.apiUrls.map(n=>()=>f(this,null,function*(){return yield this.fioApiRequest(n,e,s)}))));if(t.isError){const n=new A(t.errorMessage||t.data.message);throw n.json=t.data.json,n.list=t.data.list,n.errorCode=t.data.code,n}return t})}checkAccountInnerLoop(){return f(this,null,function*(){const e=this.currencyInfo.currencyCode,s=this.currencyInfo.defaultSettings.balanceCurrencyCodes;typeof this.walletLocalData.totalBalances[e]>"u"&&this.updateBalance(e,"0");try{const t={},{balance:n,available:o,staked:h,srps:i,roe:r}=yield this.multicastServers("getFioBalance"),l=String(n);t.staked=String(h),t.locked=(0,E.sub)(l,String(o)),this.otherData.srps=i,this.otherData.stakingRoe=r,this.updateBalance(e,l),this.updateBalance(s.staked,t.staked),this.updateBalance(s.locked,t.locked)}catch(t){this.log("checkAccountInnerLoop getFioBalance error: ",t)}try{const t=yield this.multicastServers("getFioNames",{fioPublicKey:this.walletInfo.keys.publicKey});let n=!1,o=!1,h=!1;if(t.fio_addresses.length!==this.otherData.fioAddresses.length)o=!0;else{for(const i of t.fio_addresses){const r=this.otherData.fioAddresses.find(l=>l.name===i.fio_address);if(r!=null){if(r.bundledTxs!==i.remaining_bundled_tx){o=!0;break}}else{o=!0;break}}if(!o){for(const i of this.otherData.fioAddresses)if(t.fio_addresses.findIndex(r=>r.fio_address===i.name)<0){o=!0;break}}}if(t.fio_domains.length!==this.otherData.fioDomains.length)h=!0;else{for(const i of t.fio_domains){const r=this.otherData.fioDomains.find(l=>l.name===i.fio_domain);if(r!=null){if(r.expiration!==i.expiration){h=!0;break}if(r.isPublic!==!!i.is_public){h=!0;break}}else{h=!0;break}}if(!h){for(const i of this.otherData.fioDomains)if(t.fio_domains.findIndex(r=>r.fio_domain===i.name)<0){h=!0;break}}}o&&(n=!0,this.otherData.fioAddresses=t.fio_addresses.map(i=>({name:i.fio_address,bundledTxs:i.remaining_bundled_tx}))),h&&(n=!0,this.otherData.fioDomains=t.fio_domains.map(i=>({name:i.fio_domain,expiration:i.expiration,isPublic:!!i.is_public}))),n&&this.localDataDirty()}catch(t){this.warn("checkAccountInnerLoop getFioNames error: ",t)}})}checkFioRequests(){return f(this,null,function*(){yield this.fetchFioRequests(c.$G.PENDING),yield this.fetchFioRequests(c.$G.SENT)})}fetchFioRequests(e){return f(this,null,function*(){const t={[c.$G.PENDING]:"getPendingFioRequests",[c.$G.SENT]:"getSentFioRequests"};this.otherData.fioRequests==null&&(this.otherData.fioRequests={[c.$G.SENT]:[],[c.$G.PENDING]:[]});let n=!1,o=100,h=1;const i=[];for(;o===100;)try{const{requests:r}=yield this.multicastServers(t[e],{fioPublicKey:this.walletInfo.keys.publicKey,limit:100,offset:(h-1)*100});r&&(h++,i.push(...r),o=r.length)}catch(r){o=0,this.error("fetchFioRequests error: ",r)}this.fioRequestsListChanged(this.otherData.fioRequests[e],i)&&(this.otherData.fioRequests[e]=[...i],n=!0),n&&this.localDataDirty()})}approveErroredFioRequests(){return f(this,null,function*(){for(const e in this.otherData.fioRequestsToApprove)try{yield this.otherMethods.fioAction("recordObtData",this.otherData.fioRequestsToApprove[e])}catch(s){this.error(`approveErroredFioRequests recordObtData error: ${(0,m.HY)(s)} for ${this.otherData.fioRequestsToApprove[e]}`)}})}clearBlockchainCache(){return f(this,null,function*(){yield te(H.prototype,this,"clearBlockchainCache").call(this),this.otherData.highestTxHeight=0,this.otherData.fioAddresses=[],this.otherData.fioDomains=[],this.otherData.fioRequests={[c.$G.SENT]:[],[c.$G.PENDING]:[]},this.otherData.fioRequestsToApprove={},this.otherData.stakingStatus={stakedAmounts:[]}})}startEngine(){return f(this,null,function*(){this.engineOn=!0,this.addToLoop("checkBlockchainInnerLoop",ue),this.addToLoop("checkAccountInnerLoop",ae),this.addToLoop("checkTransactionsInnerLoop",de),this.addToLoop("approveErroredFioRequests",ae),this.addToLoop("checkFioRequests",he),te(H.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return f(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}makeSpend(e){return f(this,null,function*(){var s,t;const{edgeSpendInfo:n,nativeBalance:o,currencyCode:h}=this.makeSpendCheck(e),i=(s=this.walletLocalData.totalBalances[this.currencyInfo.defaultSettings.balanceCurrencyCodes.locked])!=null?s:"0",r=(0,E.sub)(o,i),l=n.spendTargets[0],{publicAddress:d}=l,{nativeAmount:u}=l;if(d==null)throw new Error("makeSpend Missing publicAddress");if(u==null)throw new g.$D;const{otherParams:_={}}=n;_.action||(_.action={name:c.aO.transferTokens,params:{payeeFioPublicKey:d,amount:u,maxFee:0}});const{name:C,params:O}=_.action;let D;if(C===c.aO.transferTokens&&d===this.recentFioFee.publicAddress)D=this.recentFioFee.fee;else{let L="";c.HG[C]!=null&&O&&(L=O[c.HG[C].propName]),D=yield this.otherMethods.getFee(C,L)}if(O.maxFee=D,C===c.aO.transferTokens&&(this.recentFioFee={publicAddress:d,fee:D}),C!==c.aO.unStakeFioTokens&&(0,E.gt)((0,E.add)(u,`${D}`),r))throw new g.C_;if([c.aO.transferFioAddress,c.aO.transferFioDomain].includes(C)&&(O.newOwnerKey=d),C===c.aO.stakeFioTokens&&(O.amount=u),C===c.aO.unStakeFioTokens){const L=this.getUnlockDate(new Date),Z=(t=this.walletLocalData.totalBalances[this.currencyInfo.defaultSettings.balanceCurrencyCodes.staked])!=null?t:"0";if((0,E.gt)(u,Z))throw new g.C_;O.amount=u;const R=(0,E.mul)((0,E.mul)((0,E.div)(u,Z,18),`${this.otherData.srps}`),this.otherData.stakingRoe),Se=(0,E.max)((0,E.sub)(R,u),"0");_.ui={accrued:R,estReward:Se,unlockDate:L}}return{txid:"",date:0,currencyCode:h,blockHeight:0,nativeAmount:(0,E.sub)(`-${u}`,`${D}`),networkFee:`${D}`,ourReceiveAddresses:[],signedTx:"",otherParams:I({},_),walletId:this.walletId}})}signTx(e){return f(this,null,function*(){return e})}broadcastTx(e){return f(this,null,function*(){let s;const{otherParams:t}=e;if(t!=null&&t.action&&t.action.name)s=yield this.otherMethods.fioAction(t.action.name,t.action.params),e.metadata={notes:s.transaction_id};else throw new Error('Action is not set, "action" prop of otherParams is required for FIO actions');return e.txid=s.transaction_id,e.date=Date.now()/1e3,e.blockHeight=s.block_num,this.warn(`SUCCESS broadcastTx
|
|
2
|
-
${(0,
|
|
1
|
+
(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[805],{79014:function(me,Y,w){"use strict";w.d(Y,{Q:function(){return ee},k:function(){return d}});var S=w(77591),he=w.n(S),R=w(24350),oe=w(84564),Z=w.n(oe),I=w(76714),c=Object.defineProperty,A=Object.getOwnPropertySymbols,Q=Object.prototype.hasOwnProperty,C=Object.prototype.propertyIsEnumerable,M=(D,T,O)=>T in D?c(D,T,{enumerable:!0,configurable:!0,writable:!0,value:O}):D[T]=O,ie=(D,T)=>{for(var O in T||(T={}))Q.call(T,O)&&M(D,O,T[O]);if(A)for(var O of A(T))C.call(T,O)&&M(D,O,T[O]);return D};function d(D,T,O,x,V){const u=ie({},Z()(T,{},!0)),J=T.startsWith(`${D.pluginId}://`);if(u.protocol!=null&&(u.protocol=u.protocol.replace(":","")),u.protocol!=null&&u.protocol!==""&&!O[u.protocol])throw new Error(`Uri protocol '${u.protocol}' is not supported for ${D.pluginId}.`);if(u.host===""&&u.pathname==="")throw new Error("Path and host not found in uri.");const K={publicAddress:u.host!==""?u.host:u.pathname.split("/")[0]},L=u.query.label,te=u.query.message,z=u.query.category;(L!=null||te!=null||z!=null||J)&&(K.metadata={},K.metadata.name=L,K.metadata.notes=te,K.metadata.category=z,K.metadata.gateway=J!=null?J:!1);const X=u.query.amount;if(X!=null&&typeof X=="string"){x==null&&(x=D.currencyCode);const se=(0,I.cp)(D,x!=null?x:"",V);if(se==null)throw new Error("InternalErrorInvalidCurrencyCode");let G=(0,S.mul)(X,se.multiplier);G=(0,S.toFixed)(G,0,0),K.nativeAmount=G,K.currencyCode=x}return{edgeParsedUri:K,parsedUri:u}}function ee(D,T,O){if(D.publicAddress==null)throw new Error("InvalidPublicAddressError");if(O==null&&D.label==null&&D.message==null)return D.publicAddress;{let x="";O!=null&&(x+="amount="+O+"&"),(D.label!=null||D.message!=null)&&(typeof D.label=="string"&&(x+="label="+D.label+"&"),typeof D.message=="string"&&(x+="message="+D.message+"&")),x=x.substr(0,x.length-1);const V={scheme:T,path:D.publicAddress,query:x};return(0,R.qC)(V)}}},62013:function(me,Y,w){"use strict";w.r(Y),w.d(Y,{FioTools:function(){return ye},checkAddress:function(){return de},makeCurrencyEngine:function(){return Ie},makeCurrencyTools:function(){return Pe}});var S=w(93491),he=w(45234),R=w(77591),oe=w(2153),Z=w(79014),I=w(76714),c=w(5607),A=w(24827),Q=w(50857),C=w(37858),M=w(82626),ie=w(37297),d=w(82448),ee=w(94935),D=w(50244);const T=(0,d.su)({fio_domains:(0,d._2)((0,d.su)({fio_domain:d.XC,expiration:d.XC,is_public:d.mH})),fio_addresses:(0,d._2)((0,d.su)({fio_address:d.XC,remaining_bundled_tx:d.mH}))}),O=(0,d.su)({account_action_seq:d.mH,block_num:d.mH,block_time:d.XC,action_trace:(0,d.su)({receiver:d.XC,act:(0,d.su)({account:d.XC,name:d.XC,authorization:(0,d._2)((0,d.su)({actor:d.XC,permission:d.XC})),data:(0,d.su)({payee_public_key:(0,d.Zz)(d.XC),amount:(0,d.Zz)(d.mH),max_fee:(0,d.Zz)(d.mH),actor:(0,d.Zz)(d.XC),tpid:(0,d.Zz)(d.XC),quantity:(0,d.Zz)(d.XC),memo:(0,d.Zz)(d.XC),to:(0,d.Zz)(d.XC),from:(0,d.Zz)(d.XC)}),hex_data:d.XC}),trx_id:d.XC,block_num:d.mH,block_time:d.XC,producer_block_id:d.XC})}),x=(0,d.su)({actions:(0,d._2)(O)}),V=(0,d.su)({balance:d.mH,available:d.mH,staked:d.mH,srps:d.mH,roe:d.XC});var u=w(3559),J=Object.defineProperty,fe=Object.defineProperties,K=Object.getOwnPropertyDescriptors,L=Object.getOwnPropertySymbols,te=Object.getPrototypeOf,z=Object.prototype.hasOwnProperty,X=Object.prototype.propertyIsEnumerable,se=Reflect.get,G=(_,e,s)=>e in _?J(_,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):_[e]=s,E=(_,e)=>{for(var s in e||(e={}))z.call(e,s)&&G(_,s,e[s]);if(L)for(var s of L(e))X.call(e,s)&&G(_,s,e[s]);return _},$=(_,e)=>fe(_,K(e)),pe=(_,e)=>{var s={};for(var t in _)z.call(_,t)&&e.indexOf(t)<0&&(s[t]=_[t]);if(_!=null&&L)for(var t of L(_))e.indexOf(t)<0&&X.call(_,t)&&(s[t]=_[t]);return s},ae=(_,e,s)=>se(te(_),s,e),g=(_,e,s)=>new Promise((t,n)=>{var r=o=>{try{i(s.next(o))}catch(a){n(a)}},l=o=>{try{i(s.throw(o))}catch(a){n(a)}},i=o=>o.done?t(o.value):Promise.resolve(o.value).then(r,l);i((s=s.apply(_,e)).next())});const ge=1e4,ke=15e3,_e=1e4,be=1e4,we=[c.BP[c.aO.transferTokens],c.BP[c.aO.unStakeFioTokens]],De=1e4;class W extends D.P{constructor(e,s,t,n,r){super(e,s,t,n),this.fioRequestsListChanged=(i,o)=>{function a(h,f){for(const v of h)if(f.findIndex(b=>b.fio_request_id===v.fio_request_id)<0)return!0;return!1}return!!(a(i,o)||a(o,i))},this.removeFioRequest=(i,o)=>{const a=this.otherData.fioRequests[o].findIndex(h=>h.fio_request_id===`${i}`);a>-1&&this.otherData.fioRequests[o].splice(a,1)};const l=(0,I.zR)(e);this.fetchCors=l,this.tpid=r,this.networkInfo=e.networkInfo,this.refBlock={expiration:"",ref_block_num:0,ref_block_prefix:0},this.fees=new Map,this.actor=S.rn.accountHash(this.walletInfo.keys.publicKey).accountnm,this.obtData=[],this.otherMethods={fioAction:(i,o)=>g(this,null,function*(){return yield this.multicastServers(i,o)}),getFioAddresses:()=>g(this,null,function*(){return this.otherData.fioAddresses}),getFioAddressNames:()=>g(this,null,function*(){return this.otherData.fioAddresses.map(i=>i.name)}),getFioDomains:()=>g(this,null,function*(){return this.otherData.fioDomains}),getFioRequests:(i,o,a=50)=>g(this,null,function*(){const h=a*(o-1),f=a*o;return this.otherData.fioRequests[i].sort((v,b)=>v.time_stamp<b.time_stamp?1:-1).slice(h,f)}),getObtData:()=>g(this,null,function*(){return this.obtData})}}localDataDirty(){this.walletLocalDataDirty=!0}setOtherData(e){this.otherData=(0,c.CL)(e)}getUTCDate(e){const s=new Date(e);return Date.UTC(s.getFullYear(),s.getMonth(),s.getDate(),s.getHours(),s.getMinutes(),s.getSeconds())}getUnlockDate(e){const s=Math.floor(e.getTime()/c.qj)*c.qj;return new Date(s+c.dm)}loadEngine(e,s,t){return g(this,null,function*(){yield ae(W.prototype,this,"loadEngine").call(this,e,s,t)})}checkBlockchainInnerLoop(){return g(this,null,function*(){try{const e=yield this.multicastServers("getChainInfo"),s=e.head_block_num;this.walletLocalData.blockHeight!==s&&(this.checkDroppedTransactionsThrottled(),this.walletLocalData.blockHeight=s,this.localDataDirty(),this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight));const t=yield this.multicastServers("getBlock",e),n=new Date(`${e.head_block_time}Z`);n.setSeconds(n.getSeconds()+180);const r=n.toISOString();this.refBlock={expiration:r.substring(0,r.length-1),ref_block_num:t.block_num&65535,ref_block_prefix:t.ref_block_prefix}}catch(e){this.error("checkBlockchainInnerLoop Error fetching height: ",e)}})}getBalance(e){return super.getBalance(e)}doInitialBalanceCallback(){var e;super.doInitialBalanceCallback();const s=this.networkInfo.balanceCurrencyCodes;for(const t of Object.values(s))try{this.currencyEngineCallbacks.onBalanceChanged(t,(e=this.walletLocalData.totalBalances[t])!=null?e:"0")}catch(n){this.log.error("doInitialBalanceCallback Error for currencyCode",t,n)}try{this.currencyEngineCallbacks.onStakingStatusChanged(E({},this.otherData.stakingStatus))}catch(t){this.error("doInitialBalanceCallback onStakingStatusChanged",t)}}checkUnStakeTx(e){return e.name===c.BP[c.aO.unStakeFioTokens]||e.data!=null&&e.data.memo===c.Nd}updateStakingStatus(e,s,t,n){const r=this.getUnlockDate(new Date(this.getUTCDate(s))),l=this.otherData.stakingStatus.stakedAmounts.findIndex(i=>{var o;return((o=i.unlockDate)==null?void 0:o.getTime())===r.getTime()});if(l<0){const i=this.otherData.stakingStatus.stakedAmounts.findIndex(a=>{var h,f;return r.getTime()>=((f=(h=a.unlockDate)==null?void 0:h.getTime())!=null?f:0)}),o=i<0?this.otherData.stakingStatus.stakedAmounts.length:i;this.otherData.stakingStatus.stakedAmounts.splice(o,0,{nativeAmount:e,unlockDate:r,otherParams:{date:new Date(s),txs:[{txId:t,nativeAmount:e,blockTime:s,txName:n}]}})}else{const i=$(E({},this.otherData.stakingStatus.stakedAmounts[l]),{nativeAmount:"0"}),o=i.otherParams.txs.findIndex(({txId:a,txName:h})=>a===t&&h===n);o<0?i.otherParams.txs.push({txId:t,nativeAmount:e,blockTime:s,txName:n}):i.otherParams.txs[o]={txId:t,nativeAmount:e,blockTime:s,txName:n};for(const a of i.otherParams.txs)i.nativeAmount=(0,R.add)(i.nativeAmount,a.nativeAmount);this.otherData.stakingStatus.stakedAmounts[l]=i}this.localDataDirty();try{this.currencyEngineCallbacks.onStakingStatusChanged(E({},this.otherData.stakingStatus))}catch{this.error("onStakingStatusChanged error")}}getStakingStatus(){return g(this,null,function*(){return E({},this.otherData.stakingStatus)})}processTransaction(e,s,t=this.currencyInfo.currencyCode){var n,r,l,i,o,a,h,f;const{act:{name:v,data:b,account:P,authorization:m}}=e.action_trace;let k,H,y="0",p={account:P,name:v,authorization:m,data:b,meta:{}};const U=[];if(e.block_num<=this.otherData.highestTxHeight)return e.block_num;if(we.includes(v)){k="0",v===c.BP[c.aO.transferTokens]&&b.amount!=null&&(k=b.amount.toString(),H=b.actor,b.payee_public_key===this.walletInfo.keys.publicKey?(U.push(this.walletInfo.keys.publicKey),H===s&&(k="0")):k=`-${k}`);const B=this.findTransaction(t,e.action_trace.trx_id);if(B>-1){const q=this.transactionList[t][B];if(p=$(E(E({},q.otherParams),p),{data:E(E({},(r=(n=q.otherParams)==null?void 0:n.data)!=null?r:{}),p.data),meta:E(E({},(i=(l=q.otherParams)==null?void 0:l.meta)!=null?i:{}),p.meta)}),p.meta.isTransferProcessed!=null)return e.block_num;p.meta.isFeeProcessed!=null?v===c.BP[c.aO.transferTokens]?(k=(0,R.sub)(k,q.networkFee),y=q.networkFee):(k=q.nativeAmount,y="0"):this.error("processTransaction error - existing spend transaction should have isTransferProcessed or isFeeProcessed set")}this.checkUnStakeTx(p)&&this.updateStakingStatus(b.amount!=null?b.amount.toString():"0",e.block_time,e.action_trace.trx_id,v),p.meta.isTransferProcessed=!0;const N={txid:e.action_trace.trx_id,date:this.getUTCDate(e.block_time)/1e3,currencyCode:t,blockHeight:e.block_num>0?e.block_num:0,nativeAmount:k,networkFee:y,parentNetworkFee:"0",ourReceiveAddresses:U,signedTx:"",otherParams:p,walletId:this.walletId};this.addTransaction(t,N)}if(v===c.BP.transfer&&b.quantity!=null){const[B]=b.quantity.split(" "),N=B.toString();let q=(0,I.cp)(this.currencyInfo,t);if(q==null&&(q=(0,I.cp)(this.currencyInfo,this.currencyInfo.currencyCode),q==null))return this.error(`Received unsupported currencyCode: ${t}`),0;const j=(0,R.mul)(N,q.multiplier);b.to===s?(k=`${j}`,y=`-${j}`):(k=`-${j}`,y=j);const re=this.findTransaction(t,e.action_trace.trx_id);if(re>-1){const ne=this.transactionList[t][re];if(p=$(E(E({},p),ne.otherParams),{data:E(E({},p.data),(a=(o=ne.otherParams)==null?void 0:o.data)!=null?a:{}),meta:E(E({},p.meta),(f=(h=ne.otherParams)==null?void 0:h.meta)!=null?f:{})}),p.meta.isFeeProcessed!=null)return e.block_num;p.meta.isTransferProcessed!=null?b.to!==s?k=(0,R.sub)(ne.nativeAmount,y):y="0":this.error("processTransaction error - existing spend transaction should have isTransferProcessed or isFeeProcessed set")}this.checkUnStakeTx(p)&&this.updateStakingStatus(j,e.block_time,e.action_trace.trx_id,v),p.meta.isFeeProcessed=!0;const ue={txid:e.action_trace.trx_id,date:this.getUTCDate(e.block_time)/1e3,currencyCode:t,blockHeight:e.block_num>0?e.block_num:0,nativeAmount:k,networkFee:y,signedTx:"",ourReceiveAddresses:[],otherParams:p,walletId:this.walletId};this.addTransaction(t,ue)}return e.block_num}checkTransactions(e=0){return g(this,null,function*(){var s,t,n;if(this.networkInfo.historyNodeUrls[e]==null)return!1;let r=this.otherData.highestTxHeight,l=0;try{const a=yield this.requestHistory(e,{account_name:this.actor,pos:-1,offset:-1},c.pg.getActions);if(((s=a==null?void 0:a.error)==null?void 0:s.noNodeForIndex)!=null)return!1;if(x(a),a.actions.length>0)l=a.actions[0].account_action_seq;else return!0}catch{return yield this.checkTransactions(++e)}let i=l,o=!1;for(;!o&&!(i<0);){let a;try{if(a=yield this.requestHistory(e,{account_name:this.actor,pos:i,offset:-c.eG+1},c.pg.getActions),((t=a.error)==null?void 0:t.noNodeForIndex)!=null)return!1;let h=[];if(((n=a.actions)==null?void 0:n.length)>0)h=a.actions;else break;for(let f=h.length-1;f>-1;f--){const v=h[f];O(v);const b=this.processTransaction(v,this.actor);if(b>r)r=b;else if(b===r&&f===c.eG-1||b<this.otherData.highestTxHeight){o=!0;break}}if(h.length<c.eG)break;i-=c.eG}catch{return yield this.checkTransactions(++e)}}return r>this.otherData.highestTxHeight&&(this.otherData.highestTxHeight=r,this.localDataDirty()),!0})}checkTransactionsInnerLoop(){return g(this,null,function*(){let e;try{e=yield this.checkTransactions()}catch(s){this.error("checkTransactionsInnerLoop fetches failed with error: ",s);return}e&&(this.tokenCheckTransactionsStatus.FIO=1,this.updateOnAddressesChecked()),this.transactionsChangedArray.length>0&&(this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[])})}requestHistory(e,s,t){return g(this,null,function*(){if(this.networkInfo.historyNodeUrls[e]==null)return{error:{noNodeForIndex:!0}};const n=this.networkInfo.historyNodeUrls[e];return yield(yield this.fetchCors(`${n}history/${t}`,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(s)})).json()})}fioApiRequest(e,s,t,n=!1){return g(this,null,function*(){var r,l,i,o;const a=new S.rn("",this.walletInfo.keys.publicKey,e,this.fetchCors,void 0,this.tpid,n);let h;try{switch(s){case"getChainInfo":h=yield a.transactions.getChainInfo();break;case"getBlock":h=yield a.transactions.getBlock(t);break;case"getFioBalance":if(h=yield a.genericAction(s,t),V(h),h.balance!=null&&h.balance<0)throw new Error("Invalid balance");break;case"getObtData":case"getPendingFioRequests":case"getSentFioRequests":{const{endpoint:f,body:v}=t;h=yield a.transactions.executeCall(f,JSON.stringify(v));break}default:h=yield a.genericAction(s,t)}}catch(f){if(f.errorCode!=null&&A.lI.includes(f.errorCode))((i=(l=(r=f.json)==null?void 0:r.fields)==null?void 0:l[0])==null?void 0:i.error)!=null&&(f.message=f.json.fields[0].error),h={isError:!0,data:{code:f.errorCode,message:(o=f.message)!=null?o:(0,I.HY)(f),json:f.json,list:f.list}},f.errorCode!==404&&this.log(`fioApiRequest error. actionName: ${s} - apiUrl: ${e} - message: ${JSON.stringify(f.json)}`);else throw this.log(`fioApiRequest error. actionName: ${s} - apiUrl: ${e} - message: `,f),f}return h})}executePreparedTrx(e,s,t){return g(this,null,function*(){var n,r,l;const i=new S.rn("",this.walletInfo.keys.publicKey,e,this.fetchCors,void 0,this.tpid,!0);let o;this.warn(`executePreparedTrx. preparedTrx: ${JSON.stringify(t)} - apiUrl: ${e}`);try{o=yield i.executePreparedTrx(s,t),this.warn(`executePreparedTrx. res: ${JSON.stringify(o)} - apiUrl: ${e} - endpoint: ${s}`)}catch(a){throw a.errorCode!=null&&A.lI.includes(a.errorCode)?(this.log(`executePreparedTrx error. requestParams: ${JSON.stringify(t)} - apiUrl: ${e} - endpoint: ${s} - message: ${JSON.stringify(a.json)}`),((l=(r=(n=a.json)==null?void 0:n.fields)==null?void 0:r[0])==null?void 0:l.error)!=null&&(a.message=a.json.fields[0].error),a):(this.log(`executePreparedTrx error. requestParams: ${JSON.stringify(t)} - apiUrl: ${e} - endpoint: ${s} - message: `,a),a)}return o})}multicastServers(e,s){return g(this,null,function*(){var t;let n;if(c.K1[e]){const r=(0,u.h0)(s);if(this.warn(`multicastServers executePreparedTrx. actionName: ${e} - res: ${JSON.stringify(r)}`),n=yield(0,I.Wp)((0,I.Sy)(this.networkInfo.apiUrls.map(l=>g(this,null,function*(){return yield this.executePreparedTrx(l,C.EndPoint[c.VW[e]],r)})))),this.warn(`multicastServers res. actionName: ${e} - res: ${JSON.stringify(n)}`),n==null)throw new Error("Service is unavailable")}else e==="getFioNames"?n=yield(0,I.ml)(this.networkInfo.apiUrls.map(r=>g(this,null,function*(){return yield(0,I.Vs)(this.fioApiRequest(r,e,s),1e4)})),r=>{try{return JSON.stringify(T(r))}catch(l){this.log("getFioNames checkResult function returned error ",l)}},2):e==="getFees"?n=yield(0,I.QJ)((0,I.Sy)(this.networkInfo.apiUrls.map(r=>()=>g(this,null,function*(){const l=new S.rn("",this.walletInfo.keys.publicKey,r,this.fetchCors,void 0,this.tpid),{endpoint:i,param:o}=s,a=yield l.getFee(i,o);return(0,u.lZ)(a).fee.toString()})))):n=yield(0,I.QJ)((0,I.Sy)(this.networkInfo.apiUrls.map(r=>()=>g(this,null,function*(){return yield this.fioApiRequest(r,e,s)}))));if(n.isError!=null){const r=new A.OU((t=n.errorMessage)!=null?t:n.data.message);throw r.json=n.data.json,r.list=n.data.list,r.errorCode=n.data.code,r}return n})}checkAccountInnerLoop(){return g(this,null,function*(){const e=this.currencyInfo.currencyCode,s=this.networkInfo.balanceCurrencyCodes;typeof this.walletLocalData.totalBalances[e]>"u"&&this.updateBalance(e,"0");try{const t={staked:"0",locked:"0"},{balance:n,available:r,staked:l,srps:i,roe:o}=yield this.multicastServers("getFioBalance"),a=String(n);t.staked=String(l),t.locked=(0,R.sub)(a,String(r)),this.otherData.srps=i,this.otherData.stakingRoe=o,this.updateBalance(e,a),this.updateBalance(s.staked,t.staked),this.updateBalance(s.locked,t.locked)}catch(t){this.log("checkAccountInnerLoop getFioBalance error: ",t)}try{const t=yield this.multicastServers("getFioNames",{fioPublicKey:this.walletInfo.keys.publicKey});let n=!1,r=!1,l=!1;if(t.fio_addresses.length!==this.otherData.fioAddresses.length)r=!0;else{for(const i of t.fio_addresses){const o=this.otherData.fioAddresses.find(a=>a.name===i.fio_address);if(o!=null){if(o.bundledTxs!==i.remaining_bundled_tx){r=!0;break}}else{r=!0;break}}if(!r){for(const i of this.otherData.fioAddresses)if(t.fio_addresses.findIndex(o=>o.fio_address===i.name)<0){r=!0;break}}}if(t.fio_domains.length!==this.otherData.fioDomains.length)l=!0;else{for(const i of t.fio_domains){const o=this.otherData.fioDomains.find(a=>a.name===i.fio_domain);if(o!=null){if(o.expiration!==i.expiration){l=!0;break}if(o.isPublic!==(i.is_public===!0)){l=!0;break}}else{l=!0;break}}if(!l){for(const i of this.otherData.fioDomains)if(t.fio_domains.findIndex(o=>o.fio_domain===i.name)<0){l=!0;break}}}r&&(n=!0,this.otherData.fioAddresses=t.fio_addresses.map(i=>({name:i.fio_address,bundledTxs:i.remaining_bundled_tx}))),l&&(n=!0,this.otherData.fioDomains=t.fio_domains.map(i=>({name:i.fio_domain,expiration:i.expiration,isPublic:i.is_public===!0}))),n&&this.localDataDirty()}catch(t){this.warn("checkAccountInnerLoop getFioNames error: ",t)}})}fetchEncryptedFioRequests(e,s){return g(this,null,function*(){const n=e==="PENDING"?"getPendingFioRequests":"getSentFioRequests";let r=100,l=1;const i=[];for(;r===100;)try{const o=yield this.multicastServers(n,{endpoint:s.getEndPoint(),body:{fio_public_key:this.walletInfo.keys.publicKey,limit:100,offset:(l-1)*100}}),a=(0,u.S_)(o),{requests:h,more:f}=a;if(i.push(...h),f===0)break;l++,r=h.length}catch(o){const a=(0,d.Vk)(u.Pq)(o.json);(a==null?void 0:a.message)!=="No FIO Requests"&&this.error("fetchEncryptedFioRequests error: ",o);break}return i})}fetchEncryptedObtData(e,s){return g(this,null,function*(){let n=100,r=1;const l=[];for(;n===100;){let i;try{i=yield this.multicastServers(e,{endpoint:s.getEndPoint(),body:{fio_public_key:this.walletInfo.keys.publicKey,limit:100,offset:(r-1)*100}});const o=(0,u._v)(i),{obt_data_records:a,more:h}=o;if(l.push(...a),h===0)break;r++,n=a.length}catch(o){const a=(0,d.Vk)(u.Pq)(o.json);(a==null?void 0:a.message)!=="No FIO Requests"&&this.error("fetchEncryptedObtData error: ",o);break}}return l})}syncNetwork(e){return g(this,null,function*(){var s;const t=(0,u.UW)(e.privateKeys);let n=!1;const r=(a,h)=>g(this,null,function*(){var f;const v=yield this.fetchEncryptedFioRequests(a,h);h.privateKey=t.fioKey,h.publicKey=this.walletInfo.keys.publicKey;const b=(f=h.decrypt({requests:v}))!=null?f:{requests:[]};this.fioRequestsListChanged(this.otherData.fioRequests[a],b.requests)&&(this.otherData.fioRequests[a]=[...b.requests],n=!0)});yield r("PENDING",new M.PendingFioRequests(this.walletInfo.keys.publicKey)),yield r("SENT",new M.SentFioRequests(this.walletInfo.keys.publicKey)),n&&this.localDataDirty();const l=new M.GetObtData(this.walletInfo.keys.publicKey),i=yield this.fetchEncryptedObtData("getObtData",l);l.privateKey=t.fioKey,l.publicKey=this.walletInfo.keys.publicKey;const o=(s=l.decrypt({obt_data_records:i}))!=null?s:{obt_data_records:[]};return this.obtData=o.obt_data_records,De})}getFee(e,s){return g(this,null,function*(){let t=this.fees.get(e);if(t==null||t.expiration+30*1e3<Date.now()){const r={fee:yield this.multicastServers("getFees",{endpoint:e,param:s}),expiration:Date.now()};this.fees.set(e,r),t=r}return t.fee})}startEngine(){return g(this,null,function*(){this.engineOn=!0,this.addToLoop("checkBlockchainInnerLoop",ke).catch(()=>{}),this.addToLoop("checkAccountInnerLoop",ge).catch(()=>{}),this.addToLoop("checkTransactionsInnerLoop",_e).catch(()=>{}),this.addToLoop("syncNetwork",be).catch(()=>{}),yield ae(W.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return g(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}makeSpend(e){return g(this,null,function*(){var s,t;const{edgeSpendInfo:n,nativeBalance:r,currencyCode:l}=this.makeSpendCheck(e),i=(s=this.walletLocalData.totalBalances[this.networkInfo.balanceCurrencyCodes.locked])!=null?s:"0",o=(0,R.sub)(r,i),a=n.spendTargets[0],{publicAddress:h}=a,{nativeAmount:f}=a;if(h==null)throw new Error("makeSpend Missing publicAddress");if(f==null)throw new ee.$D;const{otherParams:v={action:{name:c.aO.transferTokens,params:{payeeFioPublicKey:h,amount:f,maxFee:0}}}}=n,{name:b,params:P}=(0,u.iR)(v.action);let m,k;switch(b){case c.aO.transferTokens:{m=yield this.getFee(C.EndPoint.transferTokens),k={account:"fio.token",action:c.BP[c.aO.transferTokens],data:{payee_public_key:h,amount:f,max_fee:m}};break}case c.aO.stakeFioTokens:{const{fioAddress:y}=(0,u.NB)(P);m=yield this.getFee(C.EndPoint.stakeFioTokens,y),k={account:"fio.staking",action:c.BP[b],data:{amount:f,fio_address:y,actor:this.actor,max_fee:m}};break}case c.aO.unStakeFioTokens:{const{fioAddress:y}=(0,u.NB)(P);m=yield this.getFee(C.EndPoint.unStakeFioTokens,y),k={account:"fio.staking",action:c.BP[b],data:{amount:f,fio_address:y,actor:this.actor,max_fee:m}};const p=this.getUnlockDate(new Date),U=(t=this.walletLocalData.totalBalances[this.networkInfo.balanceCurrencyCodes.staked])!=null?t:"0";if((0,R.gt)(f,U)||(0,R.gt)((0,R.add)(f,`${m}`),o))throw new ee.C_;const B=(0,R.mul)((0,R.mul)((0,R.div)(f,U,18),`${this.otherData.srps}`),this.otherData.stakingRoe),N=(0,R.max)((0,R.sub)(B,f),"0");v.ui={accrued:B,estReward:N,unlockDate:p};break}case c.aO.transferFioAddress:{const{fioAddress:y}=(0,u.NB)(P);m=yield this.getFee(C.EndPoint.transferFioAddress,y),k={account:"fio.address",action:"xferaddress",data:{fio_address:y,new_owner_fio_public_key:h,actor:this.actor,max_fee:m}};break}case c.aO.transferFioDomain:{const{fioDomain:y}=(0,u.L2)(P);m=yield this.getFee(C.EndPoint.transferFioDomain),k={account:"fio.address",action:"xferdomain",data:{fio_domain:y,new_owner_fio_public_key:h,actor:this.actor,max_fee:m}};break}case c.aO.addPublicAddresses:{const{fioAddress:y,publicAddresses:p}=(0,u.PH)(P);m=yield this.getFee(C.EndPoint.addPubAddress,y),k={account:"fio.address",action:"addaddress",data:{fio_address:y,public_addresses:p,actor:this.actor,max_fee:m}};break}case c.aO.removePublicAddresses:{const{fioAddress:y,publicAddresses:p}=(0,u.PH)(P);m=yield this.getFee(C.EndPoint.removePubAddress,y),k={account:"fio.address",action:"remaddress",data:{fio_address:y,public_addresses:p,actor:this.actor,max_fee:m}};break}case c.aO.registerFioAddress:{const{fioAddress:y}=(0,u.NB)(P);m=yield this.getFee(C.EndPoint.registerFioAddress),k={account:"fio.address",action:"regaddress",data:{fio_address:y,owner_fio_public_key:this.walletInfo.keys.publicKey,max_fee:m,actor:this.actor}};break}case c.aO.registerFioDomain:{const{fioDomain:y}=(0,u.AJ)(P);m=yield this.getFee(C.EndPoint.registerFioDomain),k={account:"fio.address",action:"regdomain",data:{fio_domain:y,owner_fio_public_key:this.walletInfo.keys.publicKey,max_fee:m,actor:this.actor}};break}case c.aO.renewFioDomain:{const{fioDomain:y}=(0,u.AJ)(P);m=yield this.getFee(C.EndPoint.renewFioDomain),k={account:"fio.address",action:"renewdomain",data:{fio_domain:y,max_fee:m,actor:this.actor}};break}case c.aO.addBundledTransactions:{const{bundleSets:y,fioAddress:p}=(0,u.Ej)(P);m=yield this.getFee(C.EndPoint.addBundledTransactions,p),k={account:"fio.address",action:"addbundles",data:{fio_address:p,bundle_sets:y,actor:this.actor,max_fee:m}};break}case c.aO.setFioDomainPublic:{const{fioDomain:y,isPublic:p}=(0,u.oY)(P);m=yield this.getFee(C.EndPoint.setFioDomainPublic),k={account:"fio.address",action:"setdomainpub",data:{fio_domain:y,is_public:p?1:0,max_fee:m,actor:this.actor}};break}case c.aO.rejectFundsRequest:{const{fioRequestId:y,payerFioAddress:p}=(0,u.OR)(P);m=yield this.getFee(C.EndPoint.rejectFundsRequest,p),k={account:"fio.reqobt",action:"rejectfndreq",data:{fio_request_id:y,max_fee:m,actor:this.actor}};break}case c.aO.cancelFundsRequest:{const{fioAddress:y,fioRequestId:p}=(0,u.mO)(P);m=yield this.getFee(C.EndPoint.cancelFundsRequest,y),k={account:"fio.reqobt",action:"cancelfndreq",data:{fio_request_id:p,max_fee:m,actor:this.actor}};break}case c.aO.recordObtData:{const{payerFioAddress:y}=(0,u.XB)(P);m=yield this.getFee(C.EndPoint.recordObtData,y);break}case c.aO.requestFunds:{const{payeeFioAddress:y}=(0,u.Vd)(P);m=yield this.getFee(C.EndPoint.newFundsRequest,y);break}default:throw new Error("Unrecognized FIO action")}return{txid:"",date:0,currencyCode:l,blockHeight:0,nativeAmount:(0,R.sub)(`-${f}`,`${m}`),networkFee:`${m}`,ourReceiveAddresses:[],signedTx:"",otherParams:$(E({},v),{txParams:k}),walletId:this.walletId}})}signTx(e,s){return g(this,null,function*(){const t=(0,u.UW)(s),n=(0,I.Xp)(e);let r=(0,d.Vk)(u.B3)(n.txParams);const l=new ie.Transactions;if(r==null){const{name:f,params:v}=(0,u.iR)(n.action),{networkFee:b}=e;switch(f){case c.aO.recordObtData:{const{payerFioAddress:P,payeeFioAddress:m,payerPublicAddress:k,payeePublicAddress:H,amount:y,tokenCode:p,chainCode:U,obtId:B,memo:N,status:q,fioRequestId:j}=(0,u.XB)(v),re={payer_public_address:k,payee_public_address:H,amount:y,chain_code:U,token_code:p,status:q,obt_id:B,memo:N,hash:void 0,offline_url:void 0},ue=l.getCipherContent("record_obt_data_content",re,t.fioKey,this.walletInfo.keys.publicKey);r={account:"fio.reqobt",action:"recordobt",data:{payer_fio_address:P,payee_fio_address:m,content:ue,fio_request_id:j,max_fee:b,actor:this.actor}};break}case c.aO.requestFunds:{const{payerFioAddress:P,payeeFioAddress:m,payeeTokenPublicAddress:k,amount:H,chainCode:y,tokenCode:p,memo:U}=(0,u.Vd)(v),B={payee_public_address:k,amount:H,chain_code:y,token_code:p,memo:U,hash:void 0,offline_url:void 0},N=l.getCipherContent("new_funds_content",B,t.fioKey,this.walletInfo.keys.publicKey);r={account:"fio.reqobt",action:"newfundsreq",data:{payer_fio_address:P,payee_fio_address:m,content:N,max_fee:b,actor:this.actor}};break}default:throw new Error("Unknown FIO action")}}const i=yield l.createRawTransaction({action:r.action,account:r.account,data:$(E({},r.data),{tpid:this.tpid}),publicKey:this.walletInfo.keys.publicKey,chainData:this.refBlock}),{serializedContextFreeData:o,serializedTransaction:a}=yield l.serialize({chainId:this.networkInfo.chainId,transaction:i}),h=yield l.sign({chainId:this.networkInfo.chainId,privateKeys:[t.fioKey],transaction:i,serializedTransaction:a,serializedContextFreeData:o});return e.otherParams=$(E({},e.otherParams),{signedTx:h}),e})}broadcastTx(e){return g(this,null,function*(){var s;const t=(0,I.Xp)(e);if(((s=t.action)==null?void 0:s.name)==null)throw new Error('Action is not set, "action" prop of otherParams is required for FIO actions');const n=(0,u.h0)(t.signedTx),r=(0,u.Yd)(yield this.multicastServers(t.action.name,n));e.metadata={notes:r.transaction_id},e.txid=r.transaction_id,e.date=Date.now()/1e3,e.blockHeight=r.block_num,this.warn(`SUCCESS broadcastTx
|
|
2
|
+
${(0,I.oX)(e)}`);const l=r,{block_num:i,block_time:o,transaction_id:a}=l,h=pe(l,["block_num","block_time","transaction_id"]);return e.otherParams=$(E({},t),{broadcastResult:h}),e})}saveTx(e){return g(this,null,function*(){var s;const t=(0,I.Xp)(e),{broadcastResult:n={},action:r}=t,{name:l,params:i}=(0,u.iR)(r);try{switch(l){case c.aO.transferFioDomain:{const o=this.otherData.fioDomains.findIndex(({name:a})=>a===i.fioDomain);o>=0&&(this.otherData.fioDomains.splice(o,1),this.localDataDirty());break}case c.aO.transferFioAddress:{const o=this.otherData.fioAddresses.findIndex(({name:a})=>a===i.fioAddress);o>=0&&(this.otherData.fioAddresses.splice(o,1),this.localDataDirty());break}case c.aO.registerFioAddress:{const{fioAddress:o}=(0,u.NB)(i);this.otherData.fioAddresses.find(({name:h})=>h===o)==null&&(this.otherData.fioAddresses.push({name:o,bundledTxs:void 0}),this.localDataDirty());break}case c.aO.registerFioDomain:{const{fioDomain:o}=(0,u.AJ)(i);if(n.expiration==null)throw new Error("expiration not present");const a=this.otherData.fioDomains.find(({name:h})=>h===o);a!=null&&(a.expiration=n.expiration,this.localDataDirty());break}case c.aO.renewFioDomain:{const{fioDomain:o}=(0,u.AJ)(i);if(n.expiration==null)throw new Error("expiration not present");const a=this.otherData.fioDomains.find(({name:h})=>h===o);a!=null&&(a.expiration=n.expiration,this.localDataDirty());break}case c.aO.addBundledTransactions:{const{fioAddress:o}=(0,u.Ej)(i),a=this.otherData.fioAddresses.find(({name:h})=>h===o);if(a==null)throw new A.OU("Fio Address is not found in engine");a.bundledTxs=((s=a.bundledTxs)!=null?s:0)+c.BB,this.localDataDirty();break}case c.aO.rejectFundsRequest:{const{fioRequestId:o}=(0,u.OR)(i);typeof o=="string"&&(this.removeFioRequest(o,"PENDING"),this.localDataDirty());break}case c.aO.cancelFundsRequest:{const{fioRequestId:o}=(0,u.mO)(i);typeof o=="string"&&(this.removeFioRequest(o,"SENT"),this.localDataDirty());break}case c.aO.recordObtData:{const{fioRequestId:o}=(0,u.XB)(i);o!=null&&n.status==="sent_to_blockchain"&&(this.removeFioRequest(o,"PENDING"),this.localDataDirty());break}}}catch(o){this.log.warn(`Error attempting post-broadcast action ${l}:`,o)}yield ae(W.prototype,this,"saveTx").call(this,e)})}getFreshAddress(e){return g(this,null,function*(){return{publicAddress:this.walletInfo.keys.publicKey}})}getDisplayPrivateSeed(e){return(0,u.UW)(e).fioKey}getDisplayPublicSeed(){return this.walletInfo.keys.publicKey}}function Ie(_,e,s,t){return g(this,null,function*(){const{tpid:n="finance@edge"}=_.initOptions,r=(0,u.RB)(s),l=new W(_,e,r,t,n);return yield l.loadEngine(e,r,t),l})}var ve=w(48764).Buffer,F=(_,e,s)=>new Promise((t,n)=>{var r=o=>{try{i(s.next(o))}catch(a){n(a)}},l=o=>{try{i(s.throw(o))}catch(a){n(a)}},i=o=>o.done?t(o.value):Promise.resolve(o.value).then(r,l);i((s=s.apply(_,e)).next())});const le="FIO",ce="fio",Ae="";function de(_){const e=_.startsWith(le),s=_.length===53;return e&&s}class ye{constructor(e){const{builtinTokens:s,currencyInfo:t,initOptions:n,io:r,networkInfo:l}=e;this.builtinTokens=s,this.currencyInfo=t,this.io=r,this.networkInfo=l;const{tpid:i="finance@edge",fioRegApiToken:o=Ae}=n;this.fetchCors=(0,I.zR)(e),this.fioRegApiToken=o,this.tpid=i;for(const a of this.networkInfo.apiUrls)new S.rn("","",a,this.fetchCors,void 0,i)}importPrivateKey(e){return F(this,null,function*(){const{pluginId:s}=this.currencyInfo,t={};if(/[0-9a-zA-Z]{51}$/.test(e))he._q.fromString(e),t.fioKey=e;else{if(!(0,oe.validateMnemonic)(e))throw new Error("Invalid input");const r=yield S.rn.createPrivateKeyMnemonic(e);t.fioKey=r.fioKey,t.mnemonic=r.mnemonic}const n=yield this.derivePublicKey({type:`wallet:${s}`,id:"fake",keys:t});return t.publicKey=n.publicKey,t})}createPrivateKey(e){return F(this,null,function*(){if(e.replace("wallet:","")===ce){const t=ve.from(this.io.random(32));return yield S.rn.createPrivateKey(t)}else throw new Error("InvalidWalletType")})}derivePublicKey(e){return F(this,null,function*(){if(e.type.replace("wallet:","")===ce)return S.rn.derivedPublicKey(e.keys.fioKey);throw new Error("InvalidWalletType")})}parseUri(e){return F(this,null,function*(){var s;const{edgeParsedUri:t}=(0,Z.k)(Q.j,e,{fio:!0},le);if(!de((s=t.publicAddress)!=null?s:""))throw new Error("InvalidPublicAddressError");return t})}encodeUri(e){return F(this,null,function*(){if(!de(e.publicAddress))throw new Error("InvalidPublicAddressError");let t;if(typeof e.nativeAmount=="string"){const r=le,l=e.nativeAmount,i=(0,I.cp)(Q.j,r);if(i==null)throw new Error("InternalErrorInvalidCurrencyCode");t=(0,R.div)(l,i.multiplier,16)}return(0,Z.Q)(e,ce,t)})}getConnectedPublicAddress(e,s,t){return F(this,null,function*(){var n;try{S.rn.isFioAddressValid(e)}catch{throw new A.OU("",400,this.networkInfo.errorCodes.INVALID_FIO_ADDRESS)}try{if((yield this.multicastServers("isAvailable",{fioName:e})).is_registered===0)throw new A.OU("",404,this.networkInfo.errorCodes.FIO_ADDRESS_IS_NOT_EXIST)}catch(r){throw r.name==="FioError"&&((n=r.json)==null?void 0:n.fields)!=null&&r.errorCode===400&&(r.labelCode=this.networkInfo.errorCodes.INVALID_FIO_ADDRESS),r}try{const r=yield this.multicastServers("getPublicAddress",{fioAddress:e,chainCode:s,tokenCode:t});if(r.public_address==null||r.public_address==="0")throw new A.OU("",404,this.networkInfo.errorCodes.FIO_ADDRESS_IS_NOT_LINKED);return r}catch(r){throw r.name==="FioError"&&r.labelCode===this.networkInfo.errorCodes.FIO_ADDRESS_IS_NOT_LINKED||r.errorCode===404?new A.OU("",404,this.networkInfo.errorCodes.FIO_ADDRESS_IS_NOT_LINKED):r}})}isFioAddressValid(e){return F(this,null,function*(){try{return S.rn.isFioAddressValid(e)}catch{return!1}})}validateAccount(e,s=!1){return F(this,null,function*(){var t;try{if(s){if(!S.rn.isFioDomainValid(e))return!1}else if(!S.rn.isFioAddressValid(e))return!1}catch{throw new A.OU("",400,this.networkInfo.errorCodes.INVALID_FIO_ADDRESS)}try{return(yield this.multicastServers("isAvailable",{fioName:e})).is_registered===0}catch(n){throw n.name==="FioError"&&((t=n.json)==null?void 0:t.fields)!=null&&n.errorCode===400&&(n.labelCode=this.networkInfo.errorCodes.INVALID_FIO_ADDRESS),n}})}isDomainPublic(e){return F(this,null,function*(){if((yield this.multicastServers("isAvailable",{fioName:e})).is_registered===0)throw new A.OU("",400,this.networkInfo.errorCodes.FIO_DOMAIN_IS_NOT_EXIST);const t=yield this.fetchCors(`${this.networkInfo.fioRegApiUrl}${c.n3.isDomainPublic}/${e}`,{method:"GET"});if(!t.ok){const r=yield t.json();throw new A.OU("",t.status,this.networkInfo.errorCodes.IS_DOMAIN_PUBLIC_ERROR,r)}const{isPublic:n}=yield t.json();return n})}doesAccountExist(e){return F(this,null,function*(){try{if(!S.rn.isFioAddressValid(e))return!1}catch{return!1}try{return(yield this.multicastServers("isAvailable",{fioName:e})).is_registered===1}catch(s){return this.error("doesAccountExist error: ",s),!1}})}buyAddressRequest(e,s=!1){return F(this,null,function*(){const t={Accept:"application/json","Content-Type":"application/json"};s&&(e.apiToken=this.fioRegApiToken);try{const n=yield this.fetchCors(`${this.networkInfo.fioRegApiUrl}${c.n3.buyAddress}`,{method:"POST",headers:t,body:JSON.stringify(e)});if(!n.ok){const r=yield n.json();throw this.networkInfo.errorCodes[r.errorCode]!=null?new A.OU(r.error,n.status,this.networkInfo.errorCodes[r.errorCode],r):r.error==="Already registered"?new A.OU(r.error,n.status,this.networkInfo.errorCodes.ALREADY_REGISTERED,r):new Error(r.error)}return yield n.json()}catch(n){throw n.labelCode!=null?n:new A.OU((0,I.HY)(n),500,this.networkInfo.errorCodes.SERVER_ERROR)}})}getDomains(e=""){return F(this,null,function*(){e==null&&(e=this.networkInfo.defaultRef);try{const s=yield this.fetchCors(`${this.networkInfo.fioRegApiUrl}${c.n3.getDomains}/${e}`,{method:"GET"}),t=yield s.json();if(!s.ok)throw this.networkInfo.errorCodes[t.errorCode]!=null?new A.OU(t.error,s.status,this.networkInfo.errorCodes[t.errorCode],t):new Error(t.error);return t.domains}catch(s){throw s.labelCode!=null?s:new A.OU((0,I.HY)(s),500,this.networkInfo.errorCodes.SERVER_ERROR)}})}getStakeEstReturn(){return F(this,null,function*(){try{const e=yield this.fetchCors(`${this.networkInfo.fioStakingApyUrl}`,{method:"GET"}),s=yield e.json();if(!e.ok)throw new Error(this.networkInfo.errorCodes.SERVER_ERROR);const t=s.historical_apr["7day"];return t!=null&&t>c.OT||t==null?c.OT:t}catch(e){throw e.labelCode!=null?e:new A.OU(e.message,500,this.networkInfo.errorCodes.SERVER_ERROR)}})}multicastServers(e,s){return F(this,null,function*(){const t=yield(0,I.QJ)((0,I.Sy)(this.networkInfo.apiUrls.map(n=>()=>F(this,null,function*(){let r;const l=new S.rn("","",n,this.fetchCors,void 0,this.tpid);try{r=yield l.genericAction(e,s)}catch(i){if(i.errorCode!=null&&A.lI.includes(i.errorCode))r={isError:!0,data:{code:i.errorCode,message:(0,I.HY)(i),json:i.json,list:i.list}};else throw i}return r}))));if(t.isError!=null){const n=new A.OU(t.errorMessage);throw n.json=t.data.json,n.list=t.data.list,n.errorCode=t.data.code,n}return t})}}function Pe(_){return F(this,null,function*(){return new ye(_)})}},89214:function(){},52361:function(){},94616:function(){}}]);
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[894],{79014:function(tt,B,d){"use strict";d.d(B,{Q:function(){return G},k:function(){return
|
|
2
|
-
${yield P.text()}`),new Error("ErrorActivationPayment")}catch(P){throw this.warn("submitActivationPayment error: ",P),P}return this.otherData.paymentSubmitted=!0,this.walletLocalDataDirty=!0,this.addToLoop("checkAccountCreationStatus",5e3),A})}}checkAccountCreationStatus(){return m(this,null,function*(){const{activationRequestId:t,paymentSubmitted:e,hederaAccount:r}=this.otherData;if(r!=null&&this.accountId!=null){clearTimeout(this.timers.checkAccountCreationStatus);return}let o;try{const n=yield this.io.fetch(`${this.mirrorNodes[0]}/api/v1/accounts?account.publickey=${this.walletInfo.keys.publicKey}`),{accounts:s}=(0,b.DP)(yield n.json());for(const i of s)this.walletInfo.keys.publicKey.indexOf(i.key.key)>=0&&(o=i.account)}catch(n){this.warn(`checkAccountCreationStatus ${this.mirrorNodes[0]} error`,n)}if(o==null&&e&&t!=null)try{const n=yield this.io.fetch(`${this.creatorApiServers[0]}/request/${t}/status`),s=(0,b.qv)(yield n.json());if(s.status==="transaction_error")throw this.otherData.activationRequestId=void 0,this.otherData.accountActivationQuoteAddress=void 0,this.otherData.accountActivationQuoteAmount=void 0,this.walletLocalDataDirty=!0,clearTimeout(this.timers.checkAccountCreationStatus),this.warn(`hederaEngine error from account activation status ${JSON.stringify(s)}`),new Error("ErrorAccountActivation");s.status==="success"&&s.account_id!=null&&(o=s.account_id)}catch(n){if(this.warn(`error checking Hedera account creation status, ID: ${t} error `,n),(n==null?void 0:n.message)==="ErrorAccountActivation")throw n}o!=null&&(this.otherData.hederaAccount=o,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onAddressChanged(),this.accountId=new v.AccountId(o),clearTimeout(this.timers.checkAccountCreationStatus))})}setOtherData(t){this.otherData=(0,b.nG)(t)}queryBalance(){return m(this,null,function*(){if(this.accountId==null)return;const t=this.accountId.toString(),e=`${this.mirrorNodes[0]}/api/v1/balances?account.id=${t}`;try{const r=yield this.io.fetch(e);if(!r.ok){const s=yield r.text();throw new Error(s)}const n=(0,b.sd)(yield r.json()).balances.find(s=>s.account===t);if(n==null)throw new Error("Unable to find matching balanceObj");this.updateBalance(this.currencyInfo.currencyCode,n.balance.toString())}catch(r){this.warn("queryBalance error checking balance:",r)}})}getNewTransactions(){return m(this,null,function*(){var t;if(this.accountId!=null)try{for(;;){const e=yield this.getTransactionsMirrorNode((t=this.otherData.latestTimestamp)!=null?t:M);if(e.length>0)this.processTxs(e);else break}this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=1,this.updateOnAddressesChecked()}catch(e){this.warn("getNewTransactions error getting transactions:",e)}})}processTxs(t){if(t.length>0){const e=t[t.length-1];if(e.otherParams==null)throw new Error("hederaEngine: EdgeTransaction must have otherParams");this.otherData.latestTimestamp!==e.otherParams.consensusAt&&(this.otherData.latestTimestamp=e.otherParams.consensusAt,this.walletLocalDataDirty=!0),t.forEach(r=>this.addTransaction(this.currencyInfo.currencyCode,r)),this.currencyEngineCallbacks.onTransactionsChanged(t)}}getTransactionsMirrorNode(t){return m(this,null,function*(){var e;if(this.accountId==null)throw new Error("no Hedera account ID");const r=(e=this.otherData.hederaAccount)!=null?e:"",o=`${this.mirrorNodes[0]}/api/v1/transactions?transactionType=CRYPTOTRANSFER&account.id=${r}&order=asc×tamp=gt:${t}`,n=yield this.io.fetch(o);if(!n.ok)return this.warn(`getTransactionsMirrorNode error fetching MirrorNode transactions: ${o}`),[];const s=(0,b.Vf)(yield n.json()),i=[];for(const a of s.transactions){const f=a.transfers.find(T=>T.account===r);if(f==null)continue;const A=f.amount.toString(),g=[];(0,S.gt)(A,"0")&&g.push(r),i.push({txid:(0,C.KT)((0,C.$9)(k.US.parse(a.transaction_hash))),date:parseInt(a.valid_start_timestamp),currencyCode:this.currencyInfo.currencyCode,blockHeight:1,nativeAmount:A,networkFee:a.charged_tx_fee.toString(),ourReceiveAddresses:g,signedTx:"",otherParams:{consensusAt:a.consensus_timestamp},walletId:this.walletId})}return i})}startEngine(){return m(this,null,function*(){this.engineOn=!0,this.otherData.latestTimestamp==null&&(this.otherData.latestTimestamp=M),this.otherData.hederaAccount==null&&(this.otherData.hederaAccount=""),this.addToLoop("getNewTransactions",1e3),this.addToLoop("queryBalance",5e3),this.addToLoop("checkAccountCreationStatus",5e3),yield E(O.prototype,this,"startEngine").call(this)})}clearBlockchainCache(){return m(this,null,function*(){this.accountId=null,yield E(O.prototype,this,"clearBlockchainCache").call(this)})}resyncBlockchain(){return m(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}makeSpend(t){return m(this,null,function*(){var e;if(this.otherData.hederaAccount==null)throw Error("ErrorAccountNotActivated");const{edgeSpendInfo:r,currencyCode:o}=this.makeSpendCheck(t);if(r.spendTargets.length!==1)throw new Error("Error: only one output allowed");const{publicAddress:n,uniqueIdentifier:s=""}=r.spendTargets[0];let{nativeAmount:i}=r.spendTargets[0];if(n==null)throw new Error("makeSpend Missing publicAddress");if(i==null)throw new $.$D;if((0,S.eq)(i,"0"))throw new $.$D;const a=v.Hbar.fromTinybar(i),f=v.Hbar.fromTinybar(this.maxFee),A=f.asTinybar().toString();if(i=(0,S.add)(i,A),(0,S.gt)(i,(e=this.walletLocalData.totalBalances[o])!=null?e:"0"))throw new $.C_;if(this.accountId==null)throw new Error("creating a transfer without an account ID");const g=new v.TransactionId(this.accountId),T=new v.TransferTransaction().setTransactionId(g).addHbarTransfer(this.otherData.hederaAccount,a.negated()).addHbarTransfer(n,a).setMaxTransactionFee(f).setTransactionMemo(s).build(this.client);return{txid:"",date:0,currencyCode:o,blockHeight:0,nativeAmount:`-${i}`,networkFee:A,ourReceiveAddresses:[],signedTx:"",otherParams:{fromAddress:this.walletLocalData.publicKey,toAddress:n,transferTx:k.US.stringify(T.toBytes())},walletId:this.walletId}})}signTx(t){return m(this,null,function*(){if(t.otherParams==null||t.otherParams.transferTx==null)throw new Error("missing otherParam transferTx");const e=this.walletInfo.keys[`${this.currencyInfo.pluginId}Key`];if(e==null)throw new Error("missing privateKey in walletInfo");const r=v.Transaction.fromBytes(k.US.parse(t.otherParams.transferTx));return yield r.sign(v.Ed25519PrivateKey.fromString(e)),V(K({},t),{signedTx:k.US.stringify(r.toBytes()),txid:(0,C.KT)((0,C.$9)(r.hash())),date:Date.now()/1e3,otherParams:K({},t.otherParams)})})}broadcastTx(t){return m(this,null,function*(){if(t.signedTx==null)throw new Error("InvalidTransactionParams");try{yield v.Transaction.fromBytes(k.US.parse(t.signedTx)).execute(this.client)}catch(e){throw this.warn("broadcastTx error",e),e}return t.blockHeight=1,t})}getFreshAddress(t){return m(this,null,function*(){var e;return{publicAddress:(e=this.otherData.hederaAccount)!=null?e:""}})}getBlockHeight(){return Math.floor(Date.now()/1e3)}getDisplayPrivateSeed(){var t,e;return(e=(t=this.walletInfo.keys[`${this.currencyInfo.pluginId}Mnemonic`])!=null?t:this.walletInfo.keys[`${this.currencyInfo.pluginId}Key`])!=null?e:""}getDisplayPublicSeed(){return this.walletInfo.keys!=null&&this.walletInfo.keys.publicKey!=null?this.walletInfo.keys.publicKey:""}}function U(c,t,e,r){return m(this,null,function*(){const{io:o}=c,n=new O(c,t,e,r,o);return yield n.loadEngine(t,e,r),n})}var I=(c,t,e)=>new Promise((r,o)=>{var n=a=>{try{i(e.next(a))}catch(f){o(f)}},s=a=>{try{i(e.throw(a))}catch(f){o(f)}},i=a=>a.done?r(a.value):Promise.resolve(a.value).then(n,s);i((e=e.apply(c,t)).next())});const N="",z="302e020100300506032b657004220420";class J{constructor(t){const{builtinTokens:e,currencyInfo:r,io:o,log:n,networkInfo:s}=t;this.builtinTokens=e,this.currencyInfo=r,this.io=o,this.log=n,this.networkInfo=s}createPrivateKey(t){return I(this,null,function*(){if(t!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const e=this.io.random(32),r=(0,L.entropyToMnemonic)(e);return yield this.importPrivateKey(r)})}importPrivateKey(t){return I(this,null,function*(){const{pluginId:e}=this.currencyInfo;try{let r,o;if(/^(0x)?[0-9a-fA-F]{64}$/.test(t.replace(z,""))){const n=t.replace(/^0x/,"").replace(z,"");o=v.Ed25519PrivateKey.fromString(n).toString()}else if((0,L.validateMnemonic)(t)){const s=yield v.Mnemonic.fromString(t).toPrivateKey(N);r=t,o=s.toString()}else throw new Error("InvalidPrivateKey");return{[`${e}Mnemonic`]:r,[`${e}Key`]:o}}catch{throw new Error("InvalidPrivateKey")}})}derivePublicKey(t){return I(this,null,function*(){var e;const{pluginId:r}=this.currencyInfo;if(t.type!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");if(t.keys==null||((e=t.keys)==null?void 0:e[`${r}Key`])==null)throw new Error("Invalid private key");return{publicKey:v.Ed25519PrivateKey.fromString(t.keys[`${r}Key`]).publicKey.toString()}})}parseUri(t){return I(this,null,function*(){const{pluginId:e}=this.currencyInfo,{edgeParsedUri:r,edgeParsedUri:{publicAddress:o}}=(0,R.k)(this.currencyInfo,t,{[`${e}`]:!0},this.currencyInfo.currencyCode);if(o!=null){const{checksumNetworkID:n}=this.networkInfo,[s,i]=o.split("-");if(!j(o)||i!=null&&i!==F(s,n))throw new Error("InvalidPublicAddressError")}return r})}encodeUri(t){return I(this,null,function*(){const{pluginId:e}=this.currencyInfo,{publicAddress:r,nativeAmount:o}=t;if(!j(r))throw new Error("InvalidPublicAddressError");if(o==null||typeof o!="string")return r;const n=(0,C.cp)(this.currencyInfo,this.currencyInfo.currencyCode);if(n==null)throw new Error("InternalErrorInvalidCurrencyCode");const s=(0,S.div)(o,n.multiplier,8);return(0,R.Q)(t,e,s)})}getActivationSupportedCurrencies(){return I(this,null,function*(){return{result:{ETH:!0}}})}getActivationCost(){return I(this,null,function*(){const t=this.networkInfo.creatorApiServers[0];try{const e=yield this.io.fetch(`${t}/account/cost`);return(0,b.NV)(yield e.json()).hbar}catch(e){throw this.log.warn("getActivationCost error unable to get account activation cost",e),new Error("ErrorUnableToGetCost")}})}validateAccount(){return I(this,null,function*(){return{result:"AccountAvailable"}})}}function et(c){return I(this,null,function*(){return new J(c)})}},89214:function(){},52361:function(){},94616:function(){},55024:function(){}}]);
|
|
1
|
+
(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[894],{79014:function(tt,B,d){"use strict";d.d(B,{Q:function(){return G},k:function(){return q}});var v=d(77591),S=d.n(v),L=d(24350),R=d(84564),C=d.n(R),I=d(76714),j=Object.defineProperty,F=Object.getOwnPropertySymbols,$=Object.prototype.hasOwnProperty,k=Object.prototype.propertyIsEnumerable,H=(l,y,p)=>y in l?j(l,y,{enumerable:!0,configurable:!0,writable:!0,value:p}):l[y]=p,W=(l,y)=>{for(var p in y||(y={}))$.call(y,p)&&H(l,p,y[p]);if(F)for(var p of F(y))k.call(y,p)&&H(l,p,y[p]);return l};function q(l,y,p,w,_){const h=W({},C()(y,{},!0)),K=y.startsWith(`${l.pluginId}://`);if(h.protocol!=null&&(h.protocol=h.protocol.replace(":","")),h.protocol!=null&&h.protocol!==""&&!p[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 E={publicAddress:h.host!==""?h.host:h.pathname.split("/")[0]},m=h.query.label,M=h.query.message,O=h.query.category;(m!=null||M!=null||O!=null||K)&&(E.metadata={},E.metadata.name=m,E.metadata.notes=M,E.metadata.category=O,E.metadata.gateway=K!=null?K:!1);const U=h.query.amount;if(U!=null&&typeof U=="string"){w==null&&(w=l.currencyCode);const P=(0,I.cp)(l,w!=null?w:"",_);if(P==null)throw new Error("InternalErrorInvalidCurrencyCode");let N=(0,v.mul)(U,P.multiplier);N=(0,v.toFixed)(N,0,0),E.nativeAmount=N,E.currencyCode=w}return{edgeParsedUri:E,parsedUri:h}}function G(l,y,p){if(l.publicAddress==null)throw new Error("InvalidPublicAddressError");if(p==null&&l.label==null&&l.message==null)return l.publicAddress;{let w="";p!=null&&(w+="amount="+p+"&"),(l.label!=null||l.message!=null)&&(typeof l.label=="string"&&(w+="label="+l.label+"&"),typeof l.message=="string"&&(w+="message="+l.message+"&")),w=w.substr(0,w.length-1);const _={scheme:y,path:l.publicAddress,query:w};return(0,L.qC)(_)}}},85520:function(tt,B,d){"use strict";d.r(B),d.d(B,{HederaTools:function(){return J},makeCurrencyEngine:function(){return U},makeCurrencyTools:function(){return et}});var v=d(17481),S=d(77591),L=d(2153),R=d(79014),C=d(76714),I=d(825);const j=(c="")=>/^(0|(?:[1-9]\d*))\.(0|(?:[1-9]\d*))\.(0|(?:[1-9]\d*))(?:-([a-z]{5}))?$/.test(c),F=(c,t)=>{let e="";const r=[];let o=0,n=0,s=0,i=0,a=0,f=0;const A=26*26*26,g=26*26*26*26*26,b=97,x=1000003,T=31,Q=`${t}000000000000`,D=[];for(let u=0;u<Q.length;u+=2)D.push(parseInt(Q.substr(u,2),16));for(let u=0;u<c.length;u++)r.push(c[u]==="."?10:parseInt(c[u],10));for(let u=0;u<r.length;u++)s=(T*s+r[u])%A,u%2===0?o=(o+r[u])%11:n=(n+r[u])%11;for(let u=0;u<D.length;u++)i=(T*i+D[u])%g;a=(((c.length%5*11+o)*11+n)*A+s+i)%g,f=a*x%g;for(let u=0;u<5;u++)e=String.fromCharCode(b+f%26)+e,f/=26;return e};var $=d(94935),k=d(35620),H=d(50244),W=Object.defineProperty,q=Object.defineProperties,G=Object.getOwnPropertyDescriptors,l=Object.getOwnPropertySymbols,y=Object.getPrototypeOf,p=Object.prototype.hasOwnProperty,w=Object.prototype.propertyIsEnumerable,_=Reflect.get,h=(c,t,e)=>t in c?W(c,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):c[t]=e,K=(c,t)=>{for(var e in t||(t={}))p.call(t,e)&&h(c,e,t[e]);if(l)for(var e of l(t))w.call(t,e)&&h(c,e,t[e]);return c},V=(c,t)=>q(c,G(t)),E=(c,t,e)=>_(y(c),e,t),m=(c,t,e)=>new Promise((r,o)=>{var n=a=>{try{i(e.next(a))}catch(f){o(f)}},s=a=>{try{i(e.throw(a))}catch(f){o(f)}},i=a=>a.done?r(a.value):Promise.resolve(a.value).then(n,s);i((e=e.apply(c,t)).next())});const M="1535068800";class O extends H.P{constructor(t,e,r,o,n){super(t,e,r,o),this.log=o.log,this.io=n;const{client:s,creatorApiServers:i,mirrorNodes:a,maxFee:f}=t.networkInfo;this.client=v.Client[`for${s}`](),this.creatorApiServers=i,this.mirrorNodes=a,this.maxFee=f,this.otherMethods={getAccountActivationQuote:A=>m(this,null,function*(){const{currencyCode:g,activePublicKey:b}=A;if(g==null||b==null)throw new Error("ErrorInvalidParams");const{accountActivationQuoteAmount:x,accountActivationQuoteAddress:T}=this.otherData;if(x!=null&&T!=null)return{paymentAddress:T,currencyCode:g,amount:(0,S.toFixed)(x,3,9),exchangeAmount:"0"};const Q={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({currency:g,public_key:b})};try{const D=yield n.fetch(`${this.creatorApiServers[0]}/account`,Q);if(!D.ok)throw new Error(yield D.text());const u=(0,I.LZ)(yield D.json()),{request_id:Y,address:Z,amount:X}=u;return this.warn(`activationRequestId: ${Y}`),this.otherData.activationRequestId=Y,this.otherData.accountActivationQuoteAddress=Z,this.otherData.accountActivationQuoteAmount=X,this.walletLocalDataDirty=!0,{paymentAddress:Z,currencyCode:g,amount:(0,S.toFixed)(X,3,18),exchangeAmount:"0"}}catch(D){throw this.warn("getAccountActivationQuote: error submitting account activation request",D),new Error("ErrorActivationRequest")}}),submitActivationPayment:A=>m(this,null,function*(){const g=this.otherData.activationRequestId;if(g==null)throw new Error({message:"ErrorNoActivationPending"});const b={method:"PUT",headers:{Accept:"application/octet-stream","Content-Type":"application/octet-stream"},body:(0,C.ah)(A.signedTx)},x=`${this.creatorApiServers[0]}/request/${g}/payment`;try{const T=yield this.io.fetch(x,b);if(!T.ok)throw this.warn(`submitActivationPayment failed to submit payment
|
|
2
|
+
${yield T.text()}`),new Error("ErrorActivationPayment")}catch(T){throw this.warn("submitActivationPayment error: ",T),T}return this.otherData.paymentSubmitted=!0,this.walletLocalDataDirty=!0,this.addToLoop("checkAccountCreationStatus",5e3),A})}}checkAccountCreationStatus(){return m(this,null,function*(){const{activationRequestId:t,paymentSubmitted:e,hederaAccount:r}=this.otherData;if(r!=null&&this.accountId!=null){clearTimeout(this.timers.checkAccountCreationStatus);return}let o;try{const n=yield this.io.fetch(`${this.mirrorNodes[0]}/api/v1/accounts?account.publickey=${this.walletInfo.keys.publicKey}`),{accounts:s}=(0,I.DP)(yield n.json());for(const i of s)this.walletInfo.keys.publicKey.includes(i.key.key)&&(o=i.account)}catch(n){this.warn(`checkAccountCreationStatus ${this.mirrorNodes[0]} error`,n)}if(o==null&&e&&t!=null)try{const n=yield this.io.fetch(`${this.creatorApiServers[0]}/request/${t}/status`),s=(0,I.qv)(yield n.json());if(s.status==="transaction_error")throw this.otherData.activationRequestId=void 0,this.otherData.accountActivationQuoteAddress=void 0,this.otherData.accountActivationQuoteAmount=void 0,this.walletLocalDataDirty=!0,clearTimeout(this.timers.checkAccountCreationStatus),this.warn(`hederaEngine error from account activation status ${JSON.stringify(s)}`),new Error("ErrorAccountActivation");s.status==="success"&&s.account_id!=null&&(o=s.account_id)}catch(n){if(this.warn(`error checking Hedera account creation status, ID: ${t} error `,n),(n==null?void 0:n.message)==="ErrorAccountActivation")throw n}o!=null&&(this.otherData.hederaAccount=o,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onAddressChanged(),this.accountId=new v.AccountId(o),clearTimeout(this.timers.checkAccountCreationStatus))})}setOtherData(t){this.otherData=(0,I.nG)(t)}queryBalance(){return m(this,null,function*(){if(this.accountId==null)return;const t=this.accountId.toString(),e=`${this.mirrorNodes[0]}/api/v1/balances?account.id=${t}`;try{const r=yield this.io.fetch(e);if(!r.ok){const s=yield r.text();throw new Error(s)}const n=(0,I.sd)(yield r.json()).balances.find(s=>s.account===t);if(n==null)throw new Error("Unable to find matching balanceObj");this.updateBalance(this.currencyInfo.currencyCode,n.balance.toString())}catch(r){this.warn("queryBalance error checking balance:",r)}})}getNewTransactions(){return m(this,null,function*(){var t;if(this.accountId!=null)try{for(;;){const e=yield this.getTransactionsMirrorNode((t=this.otherData.latestTimestamp)!=null?t:M);if(e.length>0)this.processTxs(e);else break}this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=1,this.updateOnAddressesChecked()}catch(e){this.warn("getNewTransactions error getting transactions:",e)}})}processTxs(t){if(t.length>0){const e=t[t.length-1];if(e.otherParams==null)throw new Error("hederaEngine: EdgeTransaction must have otherParams");this.otherData.latestTimestamp!==e.otherParams.consensusAt&&(this.otherData.latestTimestamp=e.otherParams.consensusAt,this.walletLocalDataDirty=!0),t.forEach(r=>this.addTransaction(this.currencyInfo.currencyCode,r)),this.currencyEngineCallbacks.onTransactionsChanged(t)}}getTransactionsMirrorNode(t){return m(this,null,function*(){var e;if(this.accountId==null)throw new Error("no Hedera account ID");const r=(e=this.otherData.hederaAccount)!=null?e:"",o=`${this.mirrorNodes[0]}/api/v1/transactions?transactionType=CRYPTOTRANSFER&account.id=${r}&order=asc×tamp=gt:${t}`,n=yield this.io.fetch(o);if(!n.ok)return this.warn(`getTransactionsMirrorNode error fetching MirrorNode transactions: ${o}`),[];const s=(0,I.Vf)(yield n.json()),i=[];for(const a of s.transactions){const f=a.transfers.find(b=>b.account===r);if(f==null)continue;const A=f.amount.toString(),g=[];(0,S.gt)(A,"0")&&g.push(r),i.push({txid:(0,C.KT)((0,C.$9)(k.US.parse(a.transaction_hash))),date:parseInt(a.valid_start_timestamp),currencyCode:this.currencyInfo.currencyCode,blockHeight:1,nativeAmount:A,networkFee:a.charged_tx_fee.toString(),ourReceiveAddresses:g,signedTx:"",otherParams:{consensusAt:a.consensus_timestamp},walletId:this.walletId})}return i})}startEngine(){return m(this,null,function*(){this.engineOn=!0,this.otherData.latestTimestamp==null&&(this.otherData.latestTimestamp=M),this.otherData.hederaAccount==null&&(this.otherData.hederaAccount=""),this.addToLoop("getNewTransactions",1e3),this.addToLoop("queryBalance",5e3),this.addToLoop("checkAccountCreationStatus",5e3),yield E(O.prototype,this,"startEngine").call(this)})}clearBlockchainCache(){return m(this,null,function*(){this.accountId=null,yield E(O.prototype,this,"clearBlockchainCache").call(this)})}resyncBlockchain(){return m(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}makeSpend(t){return m(this,null,function*(){var e;if(this.otherData.hederaAccount==null)throw Error("ErrorAccountNotActivated");const{edgeSpendInfo:r,currencyCode:o}=this.makeSpendCheck(t);if(r.spendTargets.length!==1)throw new Error("Error: only one output allowed");const{publicAddress:n,uniqueIdentifier:s=""}=r.spendTargets[0];let{nativeAmount:i}=r.spendTargets[0];if(n==null)throw new Error("makeSpend Missing publicAddress");if(i==null)throw new $.$D;if((0,S.eq)(i,"0"))throw new $.$D;const a=v.Hbar.fromTinybar(i),f=v.Hbar.fromTinybar(this.maxFee),A=f.asTinybar().toString();if(i=(0,S.add)(i,A),(0,S.gt)(i,(e=this.walletLocalData.totalBalances[o])!=null?e:"0"))throw new $.C_;if(this.accountId==null)throw new Error("creating a transfer without an account ID");const g=new v.TransactionId(this.accountId),b=new v.TransferTransaction().setTransactionId(g).addHbarTransfer(this.otherData.hederaAccount,a.negated()).addHbarTransfer(n,a).setMaxTransactionFee(f).setTransactionMemo(s).build(this.client);return{txid:"",date:0,currencyCode:o,blockHeight:0,nativeAmount:`-${i}`,networkFee:A,ourReceiveAddresses:[],signedTx:"",otherParams:{fromAddress:this.walletLocalData.publicKey,toAddress:n,transferTx:k.US.stringify(b.toBytes())},walletId:this.walletId}})}signTx(t,e){return m(this,null,function*(){const r=(0,I.cG)(this.currencyInfo.pluginId)(e);if(t.otherParams==null||t.otherParams.transferTx==null)throw new Error("missing otherParam transferTx");const o=r.privateKey;if(o==null)throw new Error("missing privateKey in walletInfo");const n=v.Transaction.fromBytes(k.US.parse(t.otherParams.transferTx));return yield n.sign(v.Ed25519PrivateKey.fromString(o)),V(K({},t),{signedTx:k.US.stringify(n.toBytes()),txid:(0,C.KT)((0,C.$9)(n.hash())),date:Date.now()/1e3,otherParams:K({},t.otherParams)})})}broadcastTx(t){return m(this,null,function*(){if(t.signedTx==null)throw new Error("InvalidTransactionParams");try{yield v.Transaction.fromBytes(k.US.parse(t.signedTx)).execute(this.client)}catch(e){throw this.warn("broadcastTx error",e),e}return t.blockHeight=1,t})}getFreshAddress(t){return m(this,null,function*(){var e;return{publicAddress:(e=this.otherData.hederaAccount)!=null?e:""}})}getBlockHeight(){return Math.floor(Date.now()/1e3)}getDisplayPrivateSeed(t){var e;const r=(0,I.cG)(this.currencyInfo.pluginId)(t);return(e=r.mnemonic)!=null?e:r.privateKey}getDisplayPublicSeed(){return this.walletInfo.keys!=null&&this.walletInfo.keys.publicKey!=null?this.walletInfo.keys.publicKey:""}}function U(c,t,e,r){return m(this,null,function*(){const{io:o}=c,n=(0,I.y_)(e),s=new O(c,t,n,r,o);return yield s.loadEngine(t,n,r),s})}var P=(c,t,e)=>new Promise((r,o)=>{var n=a=>{try{i(e.next(a))}catch(f){o(f)}},s=a=>{try{i(e.throw(a))}catch(f){o(f)}},i=a=>a.done?r(a.value):Promise.resolve(a.value).then(n,s);i((e=e.apply(c,t)).next())});const N="",z="302e020100300506032b657004220420";class J{constructor(t){const{builtinTokens:e,currencyInfo:r,io:o,log:n,networkInfo:s}=t;this.builtinTokens=e,this.currencyInfo=r,this.io=o,this.log=n,this.networkInfo=s}createPrivateKey(t){return P(this,null,function*(){if(t!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const e=this.io.random(32),r=(0,L.entropyToMnemonic)(e);return yield this.importPrivateKey(r)})}importPrivateKey(t){return P(this,null,function*(){const{pluginId:e}=this.currencyInfo;try{let r,o;if(/^(0x)?[0-9a-fA-F]{64}$/.test(t.replace(z,""))){const n=t.replace(/^0x/,"").replace(z,"");o=v.Ed25519PrivateKey.fromString(n).toString()}else if((0,L.validateMnemonic)(t)){const s=yield v.Mnemonic.fromString(t).toPrivateKey(N);r=t,o=s.toString()}else throw new Error("InvalidPrivateKey");return{[`${e}Mnemonic`]:r,[`${e}Key`]:o}}catch{throw new Error("InvalidPrivateKey")}})}derivePublicKey(t){return P(this,null,function*(){var e;const{pluginId:r}=this.currencyInfo;if(t.type!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");if(t.keys==null||((e=t.keys)==null?void 0:e[`${r}Key`])==null)throw new Error("Invalid private key");return{publicKey:v.Ed25519PrivateKey.fromString(t.keys[`${r}Key`]).publicKey.toString()}})}parseUri(t){return P(this,null,function*(){const{pluginId:e}=this.currencyInfo,{edgeParsedUri:r,edgeParsedUri:{publicAddress:o}}=(0,R.k)(this.currencyInfo,t,{[`${e}`]:!0},this.currencyInfo.currencyCode);if(o!=null){const{checksumNetworkID:n}=this.networkInfo,[s,i]=o.split("-");if(!j(o)||i!=null&&i!==F(s,n))throw new Error("InvalidPublicAddressError")}return r})}encodeUri(t){return P(this,null,function*(){const{pluginId:e}=this.currencyInfo,{publicAddress:r,nativeAmount:o}=t;if(!j(r))throw new Error("InvalidPublicAddressError");if(o==null||typeof o!="string")return r;const n=(0,C.cp)(this.currencyInfo,this.currencyInfo.currencyCode);if(n==null)throw new Error("InternalErrorInvalidCurrencyCode");const s=(0,S.div)(o,n.multiplier,8);return(0,R.Q)(t,e,s)})}getActivationSupportedCurrencies(){return P(this,null,function*(){return{result:{ETH:!0}}})}getActivationCost(){return P(this,null,function*(){const t=this.networkInfo.creatorApiServers[0];try{const e=yield this.io.fetch(`${t}/account/cost`);return(0,I.NV)(yield e.json()).hbar}catch(e){throw this.log.warn("getActivationCost error unable to get account activation cost",e),new Error("ErrorUnableToGetCost")}})}validateAccount(){return P(this,null,function*(){return{result:"AccountAvailable"}})}}function et(c){return P(this,null,function*(){return new J(c)})}},89214:function(){},52361:function(){},94616:function(){},55024:function(){}}]);
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[591],{79014:function(z,M,d){"use strict";d.d(M,{Q:function(){return X},k:function(){return W}});var E=d(77591),Q=d.n(E),$=d(24350),N=d(84564),l=d.n(N),K=d(76714),U=Object.defineProperty,O=Object.getOwnPropertySymbols,k=Object.prototype.hasOwnProperty,S=Object.prototype.propertyIsEnumerable,H=(i,m,g)=>m in i?U(i,m,{enumerable:!0,configurable:!0,writable:!0,value:g}):i[m]=g,o=(i,m)=>{for(var g in m||(m={}))k.call(m,g)&&H(i,g,m[g]);if(O)for(var g of O(m))S.call(m,g)&&H(i,g,m[g]);return i};function W(i,m,g,w,T){const h=o({},l()(m,{},!0)),x=m.startsWith(`${i.pluginId}://`);if(h.protocol!=null&&(h.protocol=h.protocol.replace(":","")),h.protocol!=null&&h.protocol!==""&&!g[h.protocol])throw new Error(`Uri protocol '${h.protocol}' is not supported for ${i.pluginId}.`);if(h.host===""&&h.pathname==="")throw new Error("Path and host not found in uri.");const v={publicAddress:h.host!==""?h.host:h.pathname.split("/")[0]},_=h.query.label,D=h.query.message,F=h.query.category;(_!=null||D!=null||F!=null||x)&&(v.metadata={},v.metadata.name=_,v.metadata.notes=D,v.metadata.category=F,v.metadata.gateway=x!=null?x:!1);const B=h.query.amount;if(B!=null&&typeof B=="string"){w==null&&(w=i.currencyCode);const L=(0,K.cp)(i,w!=null?w:"",T);if(L==null)throw new Error("InternalErrorInvalidCurrencyCode");let y=(0,E.mul)(B,L.multiplier);y=(0,E.toFixed)(y,0,0),v.nativeAmount=y,v.currencyCode=w}return{edgeParsedUri:v,parsedUri:h}}function X(i,m,g){if(i.publicAddress==null)throw new Error("InvalidPublicAddressError");if(g==null&&i.label==null&&i.message==null)return i.publicAddress;{let w="";g!=null&&(w+="amount="+g+"&"),(i.label!=null||i.message!=null)&&(typeof i.label=="string"&&(w+="label="+i.label+"&"),typeof i.message=="string"&&(w+="message="+i.message+"&")),w=w.substr(0,w.length-1);const T={scheme:m,path:i.publicAddress,query:w};return(0,$.qC)(T)}}},65813:function(z,M,d){"use strict";d.r(M),d.d(M,{PolkadotTools:function(){return q},makeCurrencyEngine:function(){return et},makeCurrencyTools:function(){return st}});var E=d(58170),Q=d(17066),$=d(75441),N=d(36984),l=d(77591),K=d(2153),U=d(48764),O=d(79014),k=d(76714),S=d(94935),H=d(50244),o=d(82448);const W=(0,o.su)({txCount:(0,o.Vk)(o.mH,0)}),X=(0,o.su)({code:o.mH,message:o.XC,data:(0,o.Zz)((0,o.su)(o.JC))}),i=(0,o.su)({from:o.XC,to:o.XC,success:o.jK,hash:o.XC,block_num:o.mH,block_timestamp:o.mH,module:o.XC,amount:o.XC,fee:o.XC}),m=(0,o.su)({count:o.mH,transfers:(0,o.Vk)((0,o._2)(i),[])});var g=Object.defineProperty,w=Object.defineProperties,T=Object.getOwnPropertyDescriptors,h=Object.getOwnPropertySymbols,x=Object.getPrototypeOf,G=Object.prototype.hasOwnProperty,v=Object.prototype.propertyIsEnumerable,_=Reflect.get,D=(p,t,e)=>t in p?g(p,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):p[t]=e,F=(p,t)=>{for(var e in t||(t={}))G.call(t,e)&&D(p,e,t[e]);if(h)for(var e of h(t))v.call(t,e)&&D(p,e,t[e]);return p},B=(p,t)=>w(p,T(t)),L=(p,t,e)=>_(x(p),e,t),y=(p,t,e)=>new Promise((s,n)=>{var r=a=>{try{c(e.next(a))}catch(u){n(u)}},f=a=>{try{c(e.throw(a))}catch(u){n(u)}},c=a=>a.done?s(a.value):Promise.resolve(a.value).then(r,f);c((e=e.apply(p,t)).next())});const J=5e3,Y=2e4,Z=3e3,tt=(0,k.jT)();class R extends H.P{constructor(t,e,s,n){super(t,e,s,n),this.getRecipientBalance=r=>y(this,null,function*(){try{return(yield this.api.query.system.account(r)).data.free.toString()}catch{return this.minimumAddressBalance}}),this.networkInfo=t.networkInfo,this.nonce=0,this.minimumAddressBalance=this.networkInfo.existentialDeposit}setOtherData(t){this.otherData=W(t)}fetchSubscan(t,e){return y(this,null,function*(){const s={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(e)},n=yield this.io.fetch(this.networkInfo.subscanBaseUrl+t,s);if(!n.ok||n.status===429)throw new Error(`Subscan ${t} failed with ${n.status}`);const r=yield n.json();return X(r)})}queryBalance(){return y(this,null,function*(){const t=yield this.api.query.system.account(this.walletInfo.keys.publicKey);this.nonce=t.nonce.toNumber(),this.updateBalance(this.currencyInfo.currencyCode,t.data.free.toString())})}queryBlockheight(){return y(this,null,function*(){try{const e=(yield this.api.rpc.chain.getBlock()).block.header.number.toNumber();e>this.walletLocalData.blockHeight&&(this.walletLocalData.blockHeight=e,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight))}catch(t){this.warn("queryBlockheight failed with error: ",t)}})}processPolkadotTransaction(t){const{from:e,to:s,success:n,hash:r,block_num:f,block_timestamp:c,module:a,amount:u,fee:I}=t;if(!n||a!=="balances")return;const C=(0,k.cp)(this.currencyInfo,this.currencyInfo.currencyCode);if(C==null)return;const b=[];let A=(0,l.mul)(u,C.multiplier);e===this.walletInfo.keys.publicKey?A=`-${(0,l.add)(A,I)}`:b.push(s);const V={txid:r,date:c,currencyCode:this.currencyInfo.currencyCode,blockHeight:f,nativeAmount:A,networkFee:I,ourReceiveAddresses:b,signedTx:"",walletId:this.walletId};this.addTransaction(this.currencyInfo.currencyCode,V)}queryTransactions(){return y(this,null,function*(){return yield tt(()=>y(this,null,function*(){return yield this.queryTransactionsInner()}))})}queryTransactionsInner(){return y(this,null,function*(){let t=Math.floor(this.otherData.txCount/this.networkInfo.subscanQueryLimit);for(;;){const e={row:this.networkInfo.subscanQueryLimit,page:t,address:this.walletInfo.keys.publicKey};let s=0,n=[];try{const r=yield this.fetchSubscan("/scan/transfers",e),f=m(r.data);s=f.count,n=f.transfers}catch(r){if(r instanceof Error&&r.message.includes("Subscan /scan/transfers failed with 429")){this.log(r.message);continue}else throw r}if(n.forEach(r=>{try{this.processPolkadotTransaction(i(r))}catch{const c=r!=null&&typeof r.hash=="string"?r.hash:"";this.warn(`Ignoring invalid transfer ${c}`)}}),this.otherData.txCount=t*this.networkInfo.subscanQueryLimit+n.length,this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=Math.min(1,s===0?1:this.otherData.txCount/s),this.updateOnAddressesChecked(),s===this.otherData.txCount)break;t++}this.transactionsChangedArray.length>0&&(this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[])})}startEngine(){return y(this,null,function*(){this.engineOn=!0,yield this.tools.connectApi(this.walletId),this.api=this.tools.polkadotApi,this.addToLoop("queryBlockheight",Y).catch(()=>{}),this.addToLoop("queryBalance",J).catch(()=>{}),this.addToLoop("queryTransactions",Z).catch(()=>{}),yield L(R.prototype,this,"startEngine").call(this)})}killEngine(){return y(this,null,function*(){yield L(R.prototype,this,"killEngine").call(this),yield this.tools.disconnectApi(this.walletId)})}resyncBlockchain(){return y(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getMaxSpendable(t){return y(this,null,function*(){if(t.spendTargets.length===0||t.spendTargets[0].publicAddress==null)throw new Error("Missing public address");const e=this.getBalance({currencyCode:t.currencyCode}),s=(0,l.sub)(e,this.networkInfo.existentialDeposit),n=[{publicAddress:t.spendTargets[0].publicAddress,nativeAmount:"0"}],r=B(F({},t),{spendTargets:n}),c=(yield this.makeSpend(r)).networkFee,a=(u,I)=>{const C=(0,l.sub)(I,u);if((0,l.lte)(C,"1"))return u;const b=(0,l.add)(u,(0,l.div)(C,"2")),A=(0,k.X0)(b).replace("0x",""),V=A.length%2===1?`0${A}`:A,it=(0,l.mul)((0,l.div)(V.length.toString(),"2"),this.networkInfo.lengthFeePerByte),ot=(0,l.add)((0,l.add)(it,c),b);return(0,l.gt)(ot,s)?a(u,b):a(b,I)};return a("0",(0,l.add)(s,"1"))})}makeSpend(t){return y(this,null,function*(){const{edgeSpendInfo:e,currencyCode:s}=this.makeSpendCheck(t);if(e.spendTargets.length!==1)throw new Error("Error: only one output allowed");const{nativeAmount:n,publicAddress:r}=e.spendTargets[0];if(r==null)throw new Error("makeSpend Missing publicAddress");if(n==null)throw new S.$D;const f=this.getBalance({currencyCode:this.currencyInfo.currencyCode}),c=(0,l.sub)(f,this.networkInfo.existentialDeposit);if((0,l.gt)(n,c))throw new S.C_;const u=yield(yield this.api.tx.balances.transferKeepAlive(r,n)).paymentInfo(this.walletInfo.keys.publicKey),I=(0,l.sub)(u.partialFee.toString(),this.networkInfo.lengthFeePerByte),C=(0,l.add)(n,I);if((0,l.gt)(C,c))throw new S.C_;const b={publicAddress:r};return{txid:"",date:0,currencyCode:s,blockHeight:0,nativeAmount:(0,l.mul)(C,"-1"),networkFee:I,ourReceiveAddresses:[],signedTx:"",otherParams:b,walletId:this.walletId}})}signTx(t){return y(this,null,function*(){const{publicAddress:e}=(0,k.Xp)(t);if(e==null)throw new Error("Missing publicAddress from makeSpend");const s=(0,l.abs)((0,l.add)(t.nativeAmount,t.networkFee));yield this.checkRecipientMinimumBalance(this.getRecipientBalance,s,e);const n=yield this.api.tx.balances.transferKeepAlive(e,s),r=this.api.createType("SignerPayload",{method:n,nonce:this.nonce,genesisHash:this.api.genesisHash,blockHash:this.api.genesisHash,runtimeVersion:this.api.runtimeVersion,version:this.api.extrinsicVersion}),f=this.api.createType("ExtrinsicPayload",r.toPayload(),{version:this.api.extrinsicVersion});this.keypair==null&&(this.keypair=new E.Y({ss58Format:0}),this.keypair.addFromUri(this.walletInfo.keys[`${this.currencyInfo.pluginId}Mnemonic`]));const c=f.sign(this.keypair.getPair(this.walletInfo.keys.publicKey));return n.addSignature(this.walletInfo.keys.publicKey,c.signature,r.toPayload()),t.signedTx=n.toHex(),t})}broadcastTx(t){return y(this,null,function*(){try{const e=yield this.api.rpc.author.submitExtrinsic(t.signedTx);t.txid=e.toHex(),t.date=Date.now()/1e3,this.warn(`SUCCESS broadcastTx
|
|
2
|
-
${(0,
|
|
1
|
+
(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[591],{79014:function(J,M,u){"use strict";u.d(M,{Q:function(){return V},k:function(){return o}});var E=u(77591),z=u.n(E),X=u(24350),W=u(84564),d=u.n(W),L=u(76714),U=Object.defineProperty,O=Object.getOwnPropertySymbols,b=Object.prototype.hasOwnProperty,T=Object.prototype.propertyIsEnumerable,H=(l,m,y)=>m in l?U(l,m,{enumerable:!0,configurable:!0,writable:!0,value:y}):l[m]=y,_=(l,m)=>{for(var y in m||(m={}))b.call(m,y)&&H(l,y,m[y]);if(O)for(var y of O(m))T.call(m,y)&&H(l,y,m[y]);return l};function o(l,m,y,g,x){const f=_({},d()(m,{},!0)),D=m.startsWith(`${l.pluginId}://`);if(f.protocol!=null&&(f.protocol=f.protocol.replace(":","")),f.protocol!=null&&f.protocol!==""&&!y[f.protocol])throw new Error(`Uri protocol '${f.protocol}' is not supported for ${l.pluginId}.`);if(f.host===""&&f.pathname==="")throw new Error("Path and host not found in uri.");const k={publicAddress:f.host!==""?f.host:f.pathname.split("/")[0]},K=f.query.label,$=f.query.message,F=f.query.category;(K!=null||$!=null||F!=null||D)&&(k.metadata={},k.metadata.name=K,k.metadata.notes=$,k.metadata.category=F,k.metadata.gateway=D!=null?D:!1);const B=f.query.amount;if(B!=null&&typeof B=="string"){g==null&&(g=l.currencyCode);const R=(0,L.cp)(l,g!=null?g:"",x);if(R==null)throw new Error("InternalErrorInvalidCurrencyCode");let S=(0,E.mul)(B,R.multiplier);S=(0,E.toFixed)(S,0,0),k.nativeAmount=S,k.currencyCode=g}return{edgeParsedUri:k,parsedUri:f}}function V(l,m,y){if(l.publicAddress==null)throw new Error("InvalidPublicAddressError");if(y==null&&l.label==null&&l.message==null)return l.publicAddress;{let g="";y!=null&&(g+="amount="+y+"&"),(l.label!=null||l.message!=null)&&(typeof l.label=="string"&&(g+="label="+l.label+"&"),typeof l.message=="string"&&(g+="message="+l.message+"&")),g=g.substr(0,g.length-1);const x={scheme:m,path:l.publicAddress,query:g};return(0,X.qC)(x)}}},65813:function(J,M,u){"use strict";u.r(M),u.d(M,{PolkadotTools:function(){return Z},makeCurrencyEngine:function(){return ot},makeCurrencyTools:function(){return lt}});var E=u(58170),z=u(17066),X=u(75441),W=u(36984),d=u(77591),L=u(2153),U=u(48764),O=u(79014),b=u(76714),T=u(94935),H=u(35620),_=u(50244),o=u(82448),V=u(62177);const l=(0,o.su)({txCount:(0,o.Vk)(o.mH,0)}),m=(0,o.su)({code:o.mH,message:o.XC,data:(0,o.Zz)((0,o.su)(o.JC))}),y=(0,o.su)({from:o.XC,to:o.XC,success:o.jK,hash:o.XC,block_num:o.mH,block_timestamp:o.mH,module:o.XC,amount:o.XC,fee:o.XC}),g=(0,o.su)({count:o.mH,transfers:(0,o.Vk)((0,o._2)(y),[])}),x=V.BQ,f=i=>(0,o.W1)(t=>{const e=(0,o.su)({[`${i}Mnemonic`]:(0,o.Zz)(o.XC),[`${i}Key`]:o.XC})(t),r={mnemonic:e[`${i}Mnemonic`],privateKey:e[`${i}Key`]};return(0,o.su)({mnemonic:(0,o.Zz)(o.XC),privateKey:o.XC})(r)},t=>({[`${i}Mnemonic`]:t.mnemonic,[`${i}Key`]:t.privateKey}));var D=Object.defineProperty,G=Object.defineProperties,k=Object.getOwnPropertyDescriptors,K=Object.getOwnPropertySymbols,$=Object.getPrototypeOf,F=Object.prototype.hasOwnProperty,B=Object.prototype.propertyIsEnumerable,R=Reflect.get,S=(i,t,e)=>t in i?D(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,q=(i,t)=>{for(var e in t||(t={}))F.call(t,e)&&S(i,e,t[e]);if(K)for(var e of K(t))B.call(t,e)&&S(i,e,t[e]);return i},tt=(i,t)=>G(i,k(t)),j=(i,t,e)=>R($(i),e,t),v=(i,t,e)=>new Promise((r,n)=>{var s=a=>{try{h(e.next(a))}catch(c){n(c)}},p=a=>{try{h(e.throw(a))}catch(c){n(c)}},h=a=>a.done?r(a.value):Promise.resolve(a.value).then(s,p);h((e=e.apply(i,t)).next())});const et=5e3,nt=2e4,rt=3e3,st=(0,b.jT)();class N extends _.P{constructor(t,e,r,n){super(t,e,r,n),this.getRecipientBalance=s=>v(this,null,function*(){try{return(yield this.api.query.system.account(s)).data.free.toString()}catch{return this.minimumAddressBalance}}),this.networkInfo=t.networkInfo,this.nonce=0,this.minimumAddressBalance=this.networkInfo.existentialDeposit}setOtherData(t){this.otherData=l(t)}fetchSubscan(t,e){return v(this,null,function*(){const r={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(e)},n=yield this.io.fetch(this.networkInfo.subscanBaseUrl+t,r);if(!n.ok||n.status===429)throw new Error(`Subscan ${t} failed with ${n.status}`);const s=yield n.json();return m(s)})}queryBalance(){return v(this,null,function*(){const t=yield this.api.query.system.account(this.walletInfo.keys.publicKey);this.nonce=t.nonce.toNumber(),this.updateBalance(this.currencyInfo.currencyCode,t.data.free.toString())})}queryBlockheight(){return v(this,null,function*(){try{const e=(yield this.api.rpc.chain.getBlock()).block.header.number.toNumber();e>this.walletLocalData.blockHeight&&(this.walletLocalData.blockHeight=e,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight))}catch(t){this.warn("queryBlockheight failed with error: ",t)}})}processPolkadotTransaction(t){const{from:e,to:r,success:n,hash:s,block_num:p,block_timestamp:h,module:a,amount:c,fee:w}=t;if(!n||a!=="balances")return;const C=(0,b.cp)(this.currencyInfo,this.currencyInfo.currencyCode);if(C==null)return;const I=[];let A=(0,d.mul)(c,C.multiplier);e===this.walletInfo.keys.publicKey?A=`-${(0,d.add)(A,w)}`:I.push(r);const Q={txid:s,date:h,currencyCode:this.currencyInfo.currencyCode,blockHeight:p,nativeAmount:A,networkFee:w,ourReceiveAddresses:I,signedTx:"",walletId:this.walletId};this.addTransaction(this.currencyInfo.currencyCode,Q)}queryTransactions(){return v(this,null,function*(){return yield st(()=>v(this,null,function*(){return yield this.queryTransactionsInner()}))})}queryTransactionsInner(){return v(this,null,function*(){let t=Math.floor(this.otherData.txCount/this.networkInfo.subscanQueryLimit);for(;;){const e={row:this.networkInfo.subscanQueryLimit,page:t,address:this.walletInfo.keys.publicKey};let r=0,n=[];try{const s=yield this.fetchSubscan("/scan/transfers",e),p=g(s.data);r=p.count,n=p.transfers}catch(s){if(s instanceof Error&&s.message.includes("Subscan /scan/transfers failed with 429")){this.log(s.message);continue}else throw s}if(n.forEach(s=>{try{this.processPolkadotTransaction(y(s))}catch{const h=s!=null&&typeof s.hash=="string"?s.hash:"";this.warn(`Ignoring invalid transfer ${h}`)}}),this.otherData.txCount=t*this.networkInfo.subscanQueryLimit+n.length,this.tokenCheckTransactionsStatus[this.currencyInfo.currencyCode]=Math.min(1,r===0?1:this.otherData.txCount/r),this.updateOnAddressesChecked(),r===this.otherData.txCount)break;t++}this.transactionsChangedArray.length>0&&(this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[])})}startEngine(){return v(this,null,function*(){this.engineOn=!0,yield this.tools.connectApi(this.walletId),this.api=this.tools.polkadotApi,this.addToLoop("queryBlockheight",nt).catch(()=>{}),this.addToLoop("queryBalance",et).catch(()=>{}),this.addToLoop("queryTransactions",rt).catch(()=>{}),yield j(N.prototype,this,"startEngine").call(this)})}killEngine(){return v(this,null,function*(){yield j(N.prototype,this,"killEngine").call(this),yield this.tools.disconnectApi(this.walletId)})}resyncBlockchain(){return v(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getMaxSpendable(t){return v(this,null,function*(){if(t.spendTargets.length===0||t.spendTargets[0].publicAddress==null)throw new Error("Missing public address");const e=this.getBalance({currencyCode:t.currencyCode}),r=(0,d.sub)(e,this.networkInfo.existentialDeposit),n=[{publicAddress:t.spendTargets[0].publicAddress,nativeAmount:"0"}],s=tt(q({},t),{spendTargets:n}),h=(yield this.makeSpend(s)).networkFee,a=(c,w)=>{const C=(0,d.sub)(w,c);if((0,d.lte)(C,"1"))return c;const I=(0,d.add)(c,(0,d.div)(C,"2")),A=(0,b.X0)(I).replace("0x",""),Q=A.length%2===1?`0${A}`:A,ct=(0,d.mul)((0,d.div)(Q.length.toString(),"2"),this.networkInfo.lengthFeePerByte),ut=(0,d.add)((0,d.add)(ct,h),I);return(0,d.gt)(ut,r)?a(c,I):a(I,w)};return a("0",(0,d.add)(r,"1"))})}makeSpend(t){return v(this,null,function*(){const{edgeSpendInfo:e,currencyCode:r}=this.makeSpendCheck(t);if(e.spendTargets.length!==1)throw new Error("Error: only one output allowed");const{nativeAmount:n,publicAddress:s}=e.spendTargets[0];if(s==null)throw new Error("makeSpend Missing publicAddress");if(n==null)throw new T.$D;const p=this.getBalance({currencyCode:this.currencyInfo.currencyCode}),h=(0,d.sub)(p,this.networkInfo.existentialDeposit);if((0,d.gt)(n,h))throw new T.C_;const c=yield(yield this.api.tx.balances.transferKeepAlive(s,n)).paymentInfo(this.walletInfo.keys.publicKey),w=(0,d.sub)(c.partialFee.toString(),this.networkInfo.lengthFeePerByte),C=(0,d.add)(n,w);if((0,d.gt)(C,h))throw new T.C_;const I={publicAddress:s};return{txid:"",date:0,currencyCode:r,blockHeight:0,nativeAmount:(0,d.mul)(C,"-1"),networkFee:w,ourReceiveAddresses:[],signedTx:"",otherParams:I,walletId:this.walletId}})}signTx(t,e){return v(this,null,function*(){const r=f(this.currencyInfo.pluginId)(e),{publicAddress:n}=(0,b.Xp)(t);if(n==null)throw new Error("Missing publicAddress from makeSpend");const s=(0,d.abs)((0,d.add)(t.nativeAmount,t.networkFee));yield this.checkRecipientMinimumBalance(this.getRecipientBalance,s,n);const p=yield this.api.tx.balances.transferKeepAlive(n,s),h=this.api.createType("SignerPayload",{method:p,nonce:this.nonce,genesisHash:this.api.genesisHash,blockHash:this.api.genesisHash,runtimeVersion:this.api.runtimeVersion,version:this.api.extrinsicVersion}),a=this.api.createType("ExtrinsicPayload",h.toPayload(),{version:this.api.extrinsicVersion});if(this.keypair==null)if(this.keypair=new E.Y({ss58Format:0}),r.mnemonic!=null)this.keypair.addFromUri(r.mnemonic);else{const w=H.YU.parse(r.privateKey);this.keypair.addFromSeed(w)}const c=a.sign(this.keypair.getPair(this.walletInfo.keys.publicKey));return p.addSignature(this.walletInfo.keys.publicKey,c.signature,h.toPayload()),t.signedTx=p.toHex(),t})}broadcastTx(t){return v(this,null,function*(){try{const e=yield this.api.rpc.author.submitExtrinsic(t.signedTx);t.txid=e.toHex(),t.date=Date.now()/1e3,this.warn(`SUCCESS broadcastTx
|
|
2
|
+
${(0,b.oX)(t)}`)}catch(e){throw this.warn("FAILURE broadcastTx failed: ",e),e}return t})}getDisplayPrivateSeed(t){var e;const r=f(this.currencyInfo.pluginId)(t);return(e=r.mnemonic)!=null?e:r.privateKey}getDisplayPublicSeed(){var t;return(t=this.walletInfo.keys.publicKey)!=null?t:""}}function ot(i,t,e,r){return v(this,null,function*(){const n=x(e),s=new N(i,t,n,r);return yield s.loadEngine(t,n,r),s})}var P=(i,t,e)=>new Promise((r,n)=>{var s=a=>{try{h(e.next(a))}catch(c){n(c)}},p=a=>{try{h(e.throw(a))}catch(c){n(c)}},h=a=>a.done?r(a.value):Promise.resolve(a.value).then(s,p);h((e=e.apply(i,t)).next())});const{ed25519PairFromSeed:it,isAddress:Y,mnemonicToMiniSecret:at}=W;class Z{constructor(t){const{builtinTokens:e,currencyInfo:r,io:n,networkInfo:s}=t;this.builtinTokens=e,this.currencyInfo=r,this.io=n,this.networkInfo=s,this.polkadotApiSubscribers=new Set}importPrivateKey(t){return P(this,null,function*(){const{pluginId:e}=this.currencyInfo;if((0,L.validateMnemonic)(t)){const r=at(t),{secretKey:n}=it(r);return{[`${e}Mnemonic`]:t,[`${e}Key`]:U.Buffer.from(n).toString("hex")}}else{if((0,b.vq)(t))return{[`${e}Key`]:t};throw new Error("InvalidPrivateKey")}})}createPrivateKey(t){return P(this,null,function*(){if(t!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const e=U.Buffer.from(this.io.random(32)),r=(0,L.entropyToMnemonic)(e);return yield this.importPrivateKey(r)})}derivePublicKey(t){return P(this,null,function*(){const{pluginId:e}=this.currencyInfo;return{publicKey:new E.Y({ss58Format:0}).addFromUri(t.keys[`${e}Mnemonic`]).address}})}parseUri(t,e,r){return P(this,null,function*(){var n,s;const{pluginId:p}=this.currencyInfo,h={[p]:!0},{parsedUri:a,edgeParsedUri:c}=(0,O.k)(this.currencyInfo,t,h,e!=null?e:this.currencyInfo.currencyCode,r),w=(n=c.publicAddress)!=null?n:"";if(!Y(w))throw new Error("InvalidPublicAddressError");return c.uniqueIdentifier=(s=a.query.memo)!=null?s:void 0,c})}encodeUri(t,e){return P(this,null,function*(){const{pluginId:r}=this.currencyInfo,{nativeAmount:n,currencyCode:s,publicAddress:p}=t;if(!Y(p))throw new Error("InvalidPublicAddressError");let h;if(typeof n=="string"){const c=(0,b.cp)(this.currencyInfo,s!=null?s:this.currencyInfo.currencyCode,e);if(c==null)throw new Error("InternalErrorInvalidCurrencyCode");h=(0,d.div)(n,c.multiplier,10)}return(0,O.Q)(t,r,h)})}connectApi(t){return P(this,null,function*(){return this.polkadotApi==null&&(this.polkadotApi=yield z.G.create({initWasm:!1,provider:new X.U(this.networkInfo.rpcNodes[0])})),this.polkadotApiSubscribers.add(t),this.polkadotApi})}disconnectApi(t){return P(this,null,function*(){this.polkadotApiSubscribers.delete(t),this.polkadotApiSubscribers.size===0&&(yield this.polkadotApi.disconnect(),this.polkadotApi=void 0)})}}function lt(i){return P(this,null,function*(){return new Z(i)})}},95856:function(){},52361:function(){},94616:function(){},55024:function(){}}]);
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[603],{79014:function(ye,H,
|
|
2
|
-
${(0,
|
|
3
|
-
${(0,
|
|
4
|
-
${(0,
|
|
1
|
+
(self.webpackChunkedge_currency_accountbased=self.webpackChunkedge_currency_accountbased||[]).push([[603],{79014:function(ye,H,d){"use strict";d.d(H,{Q:function(){return F},k:function(){return te}});var u=d(77591),se=d.n(u),Z=d(24350),P=d(84564),W=d.n(P),x=d(76714),Q=Object.defineProperty,_=Object.getOwnPropertySymbols,T=Object.prototype.hasOwnProperty,j=Object.prototype.propertyIsEnumerable,G=(c,I,f)=>I in c?Q(c,I,{enumerable:!0,configurable:!0,writable:!0,value:f}):c[I]=f,ee=(c,I)=>{for(var f in I||(I={}))T.call(I,f)&&G(c,f,I[f]);if(_)for(var f of _(I))j.call(I,f)&&G(c,f,I[f]);return c};function te(c,I,f,m,M){const g=ee({},W()(I,{},!0)),O=I.startsWith(`${c.pluginId}://`);if(g.protocol!=null&&(g.protocol=g.protocol.replace(":","")),g.protocol!=null&&g.protocol!==""&&!f[g.protocol])throw new Error(`Uri protocol '${g.protocol}' is not supported for ${c.pluginId}.`);if(g.host===""&&g.pathname==="")throw new Error("Path and host not found in uri.");const L={publicAddress:g.host!==""?g.host:g.pathname.split("/")[0]},b=g.query.label,q=g.query.message,Y=g.query.category;(b!=null||q!=null||Y!=null||O)&&(L.metadata={},L.metadata.name=b,L.metadata.notes=q,L.metadata.category=Y,L.metadata.gateway=O!=null?O:!1);const K=g.query.amount;if(K!=null&&typeof K=="string"){m==null&&(m=c.currencyCode);const B=(0,x.cp)(c,m!=null?m:"",M);if(B==null)throw new Error("InternalErrorInvalidCurrencyCode");let $=(0,u.mul)(K,B.multiplier);$=(0,u.toFixed)($,0,0),L.nativeAmount=$,L.currencyCode=m}return{edgeParsedUri:L,parsedUri:g}}function F(c,I,f){if(c.publicAddress==null)throw new Error("InvalidPublicAddressError");if(f==null&&c.label==null&&c.message==null)return c.publicAddress;{let m="";f!=null&&(m+="amount="+f+"&"),(c.label!=null||c.message!=null)&&(typeof c.label=="string"&&(m+="label="+c.label+"&"),typeof c.message=="string"&&(m+="message="+c.message+"&")),m=m.substr(0,m.length-1);const M={scheme:I,path:c.publicAddress,query:m};return(0,Z.qC)(M)}}},23818:function(ye,H,d){"use strict";d.r(H),d.d(H,{RippleTools:function(){return fe},makeCurrencyEngine:function(){return De},makeCurrencyTools:function(){return Pe}});var u=d(77591),se=d(84564),Z=d.n(se),P=d(48726),W=d(31528),x=d(20918),Q=d(79014),_=d(76714),T=d(82448),j=d(62177);const G=(0,T.Vk)((0,T.su)({activateTokenId:T.XC})),ee=(0,T.su)({recommendedFee:(0,T.Vk)(T.XC,"0")}),te=(0,T.su)({date:T.mH,hash:T.XC,ledger_index:T.mH}),F=(0,T.su)({currency:T.XC,issuer:T.XC}),c=j.BQ,I=(0,T.su)({rippleKey:T.XC}),f=({issuer:h,currency:e})=>{if(!(0,P.isValidAddress)(h))throw new Error("InvalidTokenIssuerError");return`${e}-${h}`};var m=d(94935),M=d(96510),g=d(50244);const O=[400,403,404],V={XRP_ERROR:"XrpError"},L={UNIQUE_IDENTIFIER_EXCEEDS_LENGTH:"UNIQUE_IDENTIFIER_EXCEEDS_LENGTH",UNIQUE_IDENTIFIER_EXCEEDS_LIMIT:"UNIQUE_IDENTIFIER_EXCEEDS_LIMIT",UNIQUE_IDENTIFIER_FORMAT:"UNIQUE_IDENTIFIER_FORMAT"};class b extends Error{constructor(e,t,n,o,r){super(e),Error.captureStackTrace&&Error.captureStackTrace(this,b),this.name=t!=null?t:"PluginError",n&&(this.errorCode=n),o&&(this.labelCode=o),r&&(this.json=r)}}var q=Object.defineProperty,Y=Object.defineProperties,K=Object.getOwnPropertyDescriptors,B=Object.getOwnPropertySymbols,$=Object.getPrototypeOf,me=Object.prototype.hasOwnProperty,ge=Object.prototype.propertyIsEnumerable,Ie=Reflect.get,ie=(h,e,t)=>e in h?q(h,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):h[e]=t,ae=(h,e)=>{for(var t in e||(e={}))me.call(e,t)&&ie(h,t,e[t]);if(B)for(var t of B(e))ge.call(e,t)&&ie(h,t,e[t]);return h},le=(h,e)=>Y(h,K(e)),ce=(h,e,t)=>Ie($(h),t,e),k=(h,e,t)=>new Promise((n,o)=>{var r=i=>{try{s(t.next(i))}catch(l){o(l)}},a=i=>{try{s(t.throw(i))}catch(l){o(l)}},s=i=>i.done?n(i.value):Promise.resolve(i.value).then(r,a);s((t=t.apply(h,e)).next())});const ve=1e4,we=15e3,Ee=3e3,ue=30*60,Te=20,de="12",he=131072,Ae="1000000",pe="12",ke={Payment:!0,TrustSet:!0};class J extends g.P{constructor(e,t,n,o){super(e,t,n,o),this.getRecipientBalance=a=>k(this,null,function*(){var s;try{return(yield this.tools.rippleApi.request({command:"account_info",account:a})).result.account_data.Balance}catch(i){return((s=i.data)==null?void 0:s.error)==="actNotFound"?"0":this.minimumAddressBalance}}),this.engineGetActivationAssets=a=>k(this,null,function*(){return{assetOptions:[{paymentWalletId:this.walletId,currencyPluginId:this.currencyInfo.pluginId}]}}),this.engineActivateWallet=a=>k(this,[a],function*({activateTokenIds:s,paymentTokenId:i,paymentWallet:l}){if(s==null)throw new Error(`Must specify activateTokenIds for ${this.currencyInfo.currencyCode}`);if(i!=null)throw new Error(`Must activate with ${this.currencyInfo.currencyCode}`);if((l==null?void 0:l.id)!==this.walletId)throw new Error("Must pay with same wallet you are activating token with");for(const v of s)if(this.allTokensMap[v]==null)throw new Error(`Invalid tokenId to activate ${v}`);return{paymentWalletId:this.walletId,fromNativeAmount:"0",networkFee:{nativeAmount:(0,u.mul)(pe,s.length.toString()),currencyPluginId:this.currencyInfo.pluginId},approve:(...v)=>k(this,[...v],function*(y={}){const{metadata:p}=y,w=[];for(const E of s){const C=yield l.makeSpend({spendTargets:[],metadata:p,otherParams:{activateTokenId:E}}),S=yield l.signTx(C),N=yield l.broadcastTx(S);this.warn(`SUCCESS activateWallet.approve()
|
|
2
|
+
${(0,_.oX)(N)}`),w.push(N),yield this.saveTx(N)}return{transactions:w}}),close:()=>k(this,null,function*(){})}});const{networkInfo:r}=e;this.networkInfo=r,this.nonce=0,this.minimumAddressBalance=this.networkInfo.baseReserve}setOtherData(e){this.otherData=ee(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 k(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,_.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;if(e.tx==null||(te(e.tx),!ke[e.tx.TransactionType]))return;const r=e.tx,a=[];let s=typeof r.Amount=="string"?r.Amount:"0";const i=this.currencyInfo.currencyCode;let l=i,A=!1;if(typeof r.Amount=="string")s=r.Amount;else if(r.Amount!=null){const{meta:w}=e;if(typeof w=="string"){this.log.warn(`**** WARNING: String meta field in txid ${r.hash}`);return}const E=(t=w.DeliveredAmount)!=null?t:w.delivered_amount;if(E==null){this.log.warn(`**** WARNING: Undefined DeliveredAmount in txid ${r.hash}`);return}if(typeof E=="string"){this.log.warn(`**** WARNING: String DeliveredAmount in txid ${r.hash}`);return}const{currency:C,issuer:S,value:N}=E;if(S===r.Account)return;A=!0;const ne=f({currency:C,issuer:S}),D=this.allTokensMap[ne];if(D==null)return;l=D.currencyCode,s=(0,u.mul)(N,D.denominations[0].multiplier)}let v="0",y;if(r.Destination===this.walletLocalData.publicKey)a.push(this.walletLocalData.publicKey);else{if(r.Account!==this.walletLocalData.publicKey)throw new Error("tx is neither Destination or source Account");A?(y=r.Fee,s=`-${s}`):(v=(n=r.Fee)!=null?n:"0",s=`-${(0,u.add)(s,(o=r.Fee)!=null?o:"0")}`)}const p={txid:r.hash.toLowerCase(),date:(0,P.rippleTimeToUnixTime)(r.date)/1e3,currencyCode:l,blockHeight:r.ledger_index,nativeAmount:s,networkFee:v,parentNetworkFee:y,ourReceiveAddresses:a,signedTx:"",otherParams:{},walletId:this.walletId};this.addTransaction(l,p),A&&s.startsWith("-")&&this.addTransaction(i,le(ae({},p),{currencyCode:i,nativeAmount:`-${y!=null?y:""}`,networkFee:y!=null?y:"",parentNetworkFee:void 0}))}checkTransactionsInnerLoop(){return k(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 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 a of r)a.tx!=null&&this.processRippleTransaction(a);this.transactionsChangedArray.length>0&&(this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[]),this.walletLocalData.lastAddressQueryHeight=e,this.tokenCheckTransactionsStatus.XRP=1,this.enabledTokens.forEach(a=>{this.tokenCheckTransactionsStatus[a]=1}),this.updateOnAddressesChecked()}catch(o){this.error("Error fetching transactions: ",o)}})}checkAccountInnerLoop(){return k(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:a,Sequence:s}=r.result.account_data;if(this.updateBalance(this.currencyInfo.currencyCode,a),this.nonce=s,(yield this.tools.rippleApi.getBalances(n)).forEach(({currency:l,issuer:A,value:v})=>{if(A==null)return;const y=f({currency:l,issuer:A}),p=this.allTokensMap[y];if(p!=null){const w=p.denominations[0].multiplier;if(w==null)return;const E=(0,u.toFixed)((0,u.mul)(v,w),0,0);this.updateBalance(p.currencyCode,E)}}),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(A=>{if(l.result.lines.find(y=>{const{account:p,currency:w}=y,E=f({currency:w,issuer:p}),C=this.allTokensMap[E];return C!=null&&A===C.currencyCode})==null){const y=(0,x.dK)(A,this.allTokensMap);y!=null&&o.push(y)}})}}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.warn("Account not found. Probably not activated w/minimum XRP"),this.updateBalance(this.currencyInfo.currencyCode,"0"),this.enabledTokens.forEach(a=>{if(a!==this.currencyInfo.currencyCode){const s=(0,x.dK)(a,this.allTokensMap);s!=null&&o.push(s),this.updateBalance(a,"0")}});else{this.error("Error fetching address info: ",r);return}}(0,_.dQ)(o,this.walletLocalData.unactivatedTokenIds)||(this.walletLocalData.unactivatedTokenIds=o,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onUnactivatedTokenIdsChanged(this.walletLocalData.unactivatedTokenIds))})}startEngine(){return k(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",we).catch(e=>console.log(e.message)),this.addToLoop("checkAccountInnerLoop",ve).catch(e=>console.log(e.message)),this.addToLoop("checkTransactionsInnerLoop",Ee).catch(e=>console.log(e.message)),yield ce(J.prototype,this,"startEngine").call(this)})}killEngine(){return k(this,null,function*(){yield ce(J.prototype,this,"killEngine").call(this),yield this.tools.disconnectApi(this.walletId)})}resyncBlockchain(){return k(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}getMaxSpendable(e){return k(this,null,function*(){const{currencyCode:t}=e;let n=this.getBalance({currencyCode:t});const o=this.getTotalReserve();if(t===this.currencyInfo.currencyCode&&(n=(0,u.sub)(n,o)),(0,u.lte)(n,"0"))throw new m.C_;return n})}makeSpend(e){return k(this,null,function*(){var t,n,o,r,a;const{edgeSpendInfo:s,currencyCode:i,nativeBalance:l}=this.makeSpendCheck(e),A=this.currencyInfo.currencyCode,v=G(s.otherParams);if((v==null?void 0:v.activateTokenId)!=null){const D=v.activateTokenId,U=this.allTokensMap[D],{currency:re,issuer:z}=F(U.networkLocation),X=pe,oe=yield this.tools.rippleApi.autofill({TransactionType:"TrustSet",Account:this.walletLocalData.publicKey,Fee:X,Flags:he,LimitAmount:{currency:re,issuer:z,value:Ae}});return{txid:"",date:Date.now()/1e3,currencyCode:this.currencyInfo.currencyCode,blockHeight:0,metadata:s.metadata,nativeAmount:`-${X}`,networkFee:X,ourReceiveAddresses:[],signedTx:"",otherParams:{trustSetTx:oe},walletId:this.walletId}}if(s.spendTargets.length!==1)throw new Error("Error: only one output allowed");const{publicAddress:y}=s.spendTargets[0];let{nativeAmount:p}=s.spendTargets[0];if(y==null)throw new Error("makeSpend Missing publicAddress");if(p==null)throw new m.$D;if((0,u.eq)(p,"0"))throw new m.$D;let w="0",E;if(i===A){w=this.otherData.recommendedFee;const D=this.getTotalReserve();if((0,u.gt)((0,u.add)(p,D),l))throw new m.C_}else{if(E=de,(0,u.gt)(p,l))throw new m.C_;const D=(t=this.walletLocalData.totalBalances[A])!=null?t:"0";if((0,u.gt)(E,D))throw new m.C_({currencyCode:A,networkFee:E})}const C=(a=(r=(n=s.spendTargets[0].memo)!=null?n:s.spendTargets[0].uniqueIdentifier)!=null?r:(o=s.spendTargets[0].otherParams)==null?void 0:o.uniqueIdentifier)!=null?a:"";if(C!==""){const{memoMaxLength:D=1/0,memoMaxValue:U}=this.currencyInfo;if(Number.isNaN(parseInt(C)))throw new b("Please enter a valid Destination Tag",V.XRP_ERROR,O[0],L.UNIQUE_IDENTIFIER_FORMAT);if(C.length>D)throw new b(`Destination Tag must be ${D} characters or less`,V.XRP_ERROR,O[0],L.UNIQUE_IDENTIFIER_EXCEEDS_LENGTH);if(U!=null&&(0,u.gt)(C,U))throw new b("XRP Destination Tag is above its maximum limit",V.XRP_ERROR,O[0],L.UNIQUE_IDENTIFIER_EXCEEDS_LIMIT)}let S;if(i===A)S={Amount:p,TransactionType:"Payment",Account:this.walletLocalData.publicKey,Destination:y,Fee:w},p=`-${(0,u.add)(p,w)}`;else{const D=(0,x.dK)(i,this.allTokensMap);if(D==null)throw new Error("Error: Token not supported");const U=this.allTokensMap[D],{networkLocation:re,denominations:[z]}=U,{currency:X,issuer:oe}=F(re);S={TransactionType:"Payment",Account:this.walletLocalData.publicKey,Fee:E!=null?E:de,Amount:{currency:X,issuer:oe,value:(0,u.div)(p,z.multiplier,(0,u.log10)(z.multiplier))},Destination:y,Flags:he}}C!==""&&(S.DestinationTag=parseInt(C));const ne={txid:"",date:0,currencyCode:i,blockHeight:0,nativeAmount:p,networkFee:w,parentNetworkFee:E,ourReceiveAddresses:[],signedTx:"",otherParams:{preparedTx:S},walletId:this.walletId};return this.warn("Payment transaction prepared..."),ne})}signTx(e,t){return k(this,null,function*(){const n=I(t),o=(0,_.Xp)(e);if(o.trustSetTx!=null){const v=o.trustSetTx,y=t.rippleKey,p=P.Wallet.fromSeed(y),{tx_blob:w,hash:E}=p.sign(v);return this.warn("Activation transaction signed..."),e.signedTx=w,e.txid=E.toLowerCase(),e.date=Date.now()/1e3,this.warn(`signTx
|
|
3
|
+
${(0,_.oX)(e)}`),e}const r=le(ae({},o.preparedTx),{Sequence:this.nonce,LastLedgerSequence:this.walletLocalData.blockHeight+Te});(0,M.validatePayment)(r);const a=r.Destination;if(a==null)throw new Error("makeSpend Missing publicAddress");if(e.currencyCode===this.currencyInfo.currencyCode){const v=(0,u.abs)((0,u.add)(e.nativeAmount,e.networkFee));yield this.checkRecipientMinimumBalance(this.getRecipientBalance,v,a)}const s=n.rippleKey,i=P.Wallet.fromSeed(s),{tx_blob:l,hash:A}=i.sign(r);return this.warn("Payment transaction signed..."),e.signedTx=l,e.txid=A.toLowerCase(),e.date=Date.now()/1e3,this.warn(`signTx
|
|
4
|
+
${(0,_.oX)(e)}`),e})}broadcastTx(e){return k(this,null,function*(){const t=yield this.tools.rippleApi.submit(e.signedTx),{engine_result_code:n,engine_result_message:o}=t.result;if(n>=-199&&n<=-100||n>=-299&&n<=-200||n>=-399&&n<=-300)throw this.warn(`FAILURE broadcastTx ${n} ${o}`),new Error(o);return this.warn(`SUCCESS broadcastTx
|
|
5
|
+
${(0,_.oX)(e)}`),e})}getDisplayPrivateSeed(e){return I(e).rippleKey}getDisplayPublicSeed(){var e,t;return(t=(e=this.walletInfo.keys)==null?void 0:e.publicKey)!=null?t:""}}function De(h,e,t,n){return k(this,null,function*(){const o=c(t),r=new J(h,e,o,n);return yield r.loadEngine(e,o,n),r})}var R=(h,e,t)=>new Promise((n,o)=>{var r=i=>{try{s(t.next(i))}catch(l){o(l)}},a=i=>{try{s(t.throw(i))}catch(l){o(l)}},s=i=>i.done?n(i.value):Promise.resolve(i.value).then(r,a);s((t=t.apply(h,e)).next())});class fe{constructor(e){const{builtinTokens:t,currencyInfo:n,io:o,networkInfo:r}=e;this.builtinTokens=t,this.currencyInfo=n,this.io=o,this.networkInfo=r,this.rippleApiSubscribers={}}connectApi(e){return R(this,null,function*(){if(this.rippleApi==null){const t=this.networkInfo.rippledServers.map(o=>()=>R(this,null,function*(){const r=new P.Client(o);return yield r.connect(),r})),n=yield(0,_.QJ)(t);this.rippleApi==null&&(this.rippleApi=n)}this.rippleApiSubscribers[e]=!0})}disconnectApi(e){return R(this,null,function*(){delete this.rippleApiSubscribers[e],Object.keys(this.rippleApiSubscribers).length===0&&(yield this.rippleApi.disconnect())})}importPrivateKey(e){return R(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,_.HY)(t)}`)}})}createPrivateKey(e){return R(this,null,function*(){const t=e.replace("wallet:","");if(t==="ripple"||t==="ripple-secp256k1"){const n=t==="ripple-secp256k1"?W.default.secp256k1:W.default.ed25519,o=Array.from(this.io.random(32));return{rippleKey:P.Wallet.fromEntropy(o,{algorithm:n}).seed}}else throw new Error("InvalidWalletType")})}derivePublicKey(e){return R(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 R(this,null,function*(){var t;const n={ripple:!0,"xrp-ledger":!0},o="https://ripple.com//send";try{const{classicAddress:i,tag:l}=(0,P.xAddressToClassicAddress)(e);e=`ripple:${i}?to=${i}${l!==!1?`&dt=${l}`:""}`}catch{}if(e.includes(o)){const l=Z()(e,{},!0).query.to;l!=null&&(e=e.replace(o,`ripple:${l}`))}const{parsedUri:r,edgeParsedUri:a}=(0,Q.k)(this.currencyInfo,e,n);if(!(0,P.isValidAddress)((t=a.publicAddress)!=null?t:""))throw new Error("InvalidPublicAddressError");return a.uniqueIdentifier=r.query.dt,a})}encodeUri(e){return R(this,null,function*(){if(!(0,P.isValidAddress)(e.publicAddress))throw new Error("InvalidPublicAddressError");let n;if(typeof e.nativeAmount=="string"){const r="XRP",a=e.nativeAmount,s=(0,_.cp)(this.currencyInfo,r);if(s==null)throw new Error("InternalErrorInvalidCurrencyCode");n=(0,u.div)(a,s.multiplier,6)}return(0,Q.Q)(e,"ripple",n)})}getTokenId(e){return R(this,null,function*(){(0,x.Rp)(e);const t=e==null?void 0:e.networkLocation;if(t==null)throw new Error("ErrorInvalidNetworkLocation");const n=F(t);return f(n)})}}function Pe(h){return R(this,null,function*(){return new fe(h)})}},89214:function(){},52361:function(){},94616:function(){}}]);
|
|
@@ -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(q,O,u){"use strict";u.d(O,{Q:function(){return N},k:function(){return W}});var C=u(77591),I=u.n(C),T=u(24350),b=u(84564),U=u.n(b),A=u(76714),v=Object.defineProperty,r=Object.getOwnPropertySymbols,B=Object.prototype.hasOwnProperty,$=Object.prototype.propertyIsEnumerable,x=(c,y,m)=>y in c?v(c,y,{enumerable:!0,configurable:!0,writable:!0,value:m}):c[y]=m,H=(c,y)=>{for(var m in y||(y={}))B.call(y,m)&&x(c,m,y[m]);if(r)for(var m of r(y))$.call(y,m)&&x(c,m,y[m]);return c};function W(c,y,m,g,S){const d=H({},U()(y,{},!0)),E=y.startsWith(`${c.pluginId}://`);if(d.protocol!=null&&(d.protocol=d.protocol.replace(":","")),d.protocol!=null&&d.protocol!==""&&!m[d.protocol])throw new Error(`Uri protocol '${d.protocol}' is not supported for ${c.pluginId}.`);if(d.host===""&&d.pathname==="")throw new Error("Path and host not found in uri.");const h={publicAddress:d.host!==""?d.host:d.pathname.split("/")[0]},P=d.query.label,D=d.query.message,L=d.query.category;(P!=null||D!=null||L!=null||E)&&(h.metadata={},h.metadata.name=P,h.metadata.notes=D,h.metadata.category=L,h.metadata.gateway=E!=null?E:!1);const k=d.query.amount;if(k!=null&&typeof k=="string"){g==null&&(g=c.currencyCode);const R=(0,A.cp)(c,g!=null?g:"",S);if(R==null)throw new Error("InternalErrorInvalidCurrencyCode");let K=(0,C.mul)(k,R.multiplier);K=(0,C.toFixed)(K,0,0),h.nativeAmount=K,h.currencyCode=g}return{edgeParsedUri:h,parsedUri:d}}function N(c,y,m){if(c.publicAddress==null)throw new Error("InvalidPublicAddressError");if(m==null&&c.label==null&&c.message==null)return c.publicAddress;{let g="";m!=null&&(g+="amount="+m+"&"),(c.label!=null||c.message!=null)&&(typeof c.label=="string"&&(g+="label="+c.label+"&"),typeof c.message=="string"&&(g+="message="+c.message+"&")),g=g.substr(0,g.length-1);const S={scheme:y,path:c.publicAddress,query:g};return(0,T.qC)(S)}}},29016:function(q,O,u){"use strict";u.r(O),u.d(O,{SolanaTools:function(){return V},makeCurrencyEngine:function(){return Z},makeCurrencyTools:function(){return te}});var C=u(75885),I=u(77591),T=u(2153),b=u(48764),U=u(62678),A=u(79014),v=u(76714),r=u(82448),B=u(94935),$=u(35620),x=u(50244),H=u(62177);const W=(0,r.su)({newestTxid:(0,r.Vk)(r.XC,"")}),N=(0,r.su)({value:r.mH}),c=(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)})}),y=(0,r.su)({value:(0,r.su)({blockhash:r.XC,feeCalculator:(0,r.su)({lamportsPerSignature:r.mH})})}),m=H.BQ,g=f=>(0,r.W1)(e=>{const t=(0,r.su)({[`${f}Mnemonic`]:r.XC,[`${f}Key`]:r.XC})(e),n={mnemonic:t[`${f}Mnemonic`],privateKey:t[`${f}Key`]};return(0,r.su)({mnemonic:r.XC,privateKey:r.XC})(n)},e=>({[`${f}Mnemonic`]:e.mnemonic,[`${f}Key`]:e.privateKey}));var S=u(48764).Buffer,d=Object.getPrototypeOf,E=Reflect.get,J=(f,e,t)=>E(d(f),t,e),h=(f,e,t)=>new Promise((n,o)=>{var s=i=>{try{a(t.next(i))}catch(p){o(p)}},l=i=>{try{a(t.throw(i))}catch(p){o(p)}},a=i=>i.done?n(i.value):Promise.resolve(i.value).then(s,l);a((t=t.apply(f,e)).next())});const{PublicKey:P,Keypair:D,SystemProgram:L,Transaction:k,TransactionInstruction:R}=C,K=5e3,G=2e4,Y=3e3;class X extends x.P{constructor(e,t,n,o){super(e,t,n,o),this.networkInfo=e.networkInfo;const s=(0,v.zR)(e);this.chainCode=t.currencyInfo.currencyCode,this.fetchCors=s,this.feePerSignature="5000",this.recentBlockhash="",this.base58PublicKey=n.keys.publicKey,this.progressRatio=0}setOtherData(e){this.otherData=W(e)}fetchRpc(e){return h(this,arguments,function*(t,n=[]){const o={jsonrpc:"2.0",id:1,method:t,params:n},s={method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(o)},l=this.networkInfo.rpcNodes.map(i=>()=>h(this,null,function*(){const p=yield this.fetchCors(i,s);if(!p.ok)throw new Error(`fetchRpc ${s.method} failed error: ${p.status}`);return yield p.json()}));return(yield(0,v.QJ)(l)).result})}queryBalance(){return h(this,null,function*(){try{const e=yield this.fetchRpc("getBalance",[this.base58PublicKey,{commitment:this.networkInfo.commitment}]),t=N(e);this.updateBalance(this.chainCode,t.value.toString())}catch(e){this.error(`Error checking ${this.chainCode} address balance`,e)}})}queryBlockheight(){return h(this,null,function*(){try{const e=(0,r.mH)(yield this.fetchRpc("getSlot"));e>this.walletLocalData.blockHeight&&(this.walletLocalData.blockHeight=e,this.walletLocalDataDirty=!0,this.currencyEngineCallbacks.onBlockHeightChanged(this.walletLocalData.blockHeight))}catch(e){this.error("queryBlockheight Error ",e)}})}queryFee(){return h(this,null,function*(){try{const e=yield this.fetchRpc("getRecentBlockhash"),{blockhash:t,feeCalculator:{lamportsPerSignature:n}}=y(e).value;this.feePerSignature=n.toString(),this.recentBlockhash=t}catch(e){this.error("queryFee Error ",e)}})}processSolanaTransaction(e,t){const n=[],o=e.transaction.message.accountKeys.findIndex(i=>i===this.base58PublicKey);if(o<0||e.meta==null)return;const s=e.meta.postBalances[o]-e.meta.preBalances[o],l=e.meta.fee;if(s>=0){if(e.meta.err!=null)return;n.push(this.base58PublicKey)}const a={txid:e.transaction.signatures[0],date:t,currencyCode:this.chainCode,blockHeight:e.slot,nativeAmount:s.toString(),networkFee:l.toString(),ourReceiveAddresses:n,signedTx:"",walletId:this.walletId};this.addTransaction(this.chainCode,a)}queryTransactions(){return h(this,null,function*(){let e=null;const t=this.otherData.newestTxid!==""?this.otherData.newestTxid:null;let n=[];try{for(;;){const s=[this.base58PublicKey,{until:t,before:e,limit:this.networkInfo.txQueryLimit,commitment:this.networkInfo.commitment}],l=yield this.fetchRpc("getSignaturesForAddress",s);if(n=n.concat(l),l.length<this.networkInfo.txQueryLimit)break;e=l[this.networkInfo.txQueryLimit-1].signature}}catch(s){this.error("getTransactionSignatures failed with error: ",s);return}if(n.length===0){this.tokenCheckTransactionsStatus[this.chainCode]=1,this.updateOnAddressesChecked();return}let o=-1;for(let s=n.length-1;s>=0;s--)try{const l=c(yield this.fetchRpc("getTransaction",[n[s].signature,{encoding:"json",commitment:this.networkInfo.commitment}]));let a=n[s].blocktime;(a==null||isNaN(a))&&(a=(0,r.mH)(yield this.fetchRpc("getBlockTime",[l.slot]))),this.processSolanaTransaction(l,a);const i=1-s/n.length;i!==this.progressRatio&&(Math.abs(i-this.progressRatio)>.25||i===1)&&(this.progressRatio=i,this.tokenCheckTransactionsStatus[this.chainCode]=this.progressRatio,this.updateOnAddressesChecked())}catch{o=s;break}o===-1?this.otherData.newestTxid=n[0].signature:n.length>o+1&&(this.otherData.newestTxid=n[o+1].signature),this.walletLocalDataDirty=!0,this.tokenCheckTransactionsStatus[this.chainCode]=1,this.updateOnAddressesChecked(),this.transactionsChangedArray.length>0&&(this.currencyEngineCallbacks.onTransactionsChanged(this.transactionsChangedArray),this.transactionsChangedArray=[])})}startEngine(){return h(this,null,function*(){this.engineOn=!0,this.addToLoop("queryBlockheight",G),this.addToLoop("queryFee",G),this.addToLoop("queryBalance",K),this.addToLoop("queryTransactions",Y),J(X.prototype,this,"startEngine").call(this)})}resyncBlockchain(){return h(this,null,function*(){yield this.killEngine(),yield this.clearBlockchainCache(),yield this.startEngine()})}makeSpend(e){return h(this,null,function*(){var t,n,o;const{edgeSpendInfo:s,currencyCode:l}=this.makeSpendCheck(e);if(s.spendTargets.length!==1)throw new Error("Error: only one output allowed");const{nativeAmount:a,publicAddress:i}=s.spendTargets[0];if(i==null)throw new Error("makeSpend Missing publicAddress");if(a==null)throw new B.$D;const p=this.feePerSignature,ne=(t=this.walletLocalData.totalBalances[this.chainCode])!=null?t:"0";let F="0";if(F=(0,I.add)(a,p),(0,I.gt)(F,ne))throw new B.C_;const z=new P(this.base58PublicKey),re={recentBlockhash:this.recentBlockhash,feePayer:z},_=new k(re).add(L.transfer({fromPubkey:z,toPubkey:new P(i),lamports:parseInt(a)})),Q=(o=(n=s.spendTargets[0])==null?void 0:n.otherParams)==null?void 0:o.uniqueIdentifier;if(Q!=null&&Q!==""){const oe=new R({keys:[{pubkey:z,isSigner:!0,isWritable:!0}],programId:new P(this.networkInfo.memoPublicKey),data:S.from(Q)});_.add(oe)}const se={unsignedSerializedSolTx:_.serialize({requireAllSignatures:!1})};return{txid:"",date:0,currencyCode:l,blockHeight:0,nativeAmount:(0,I.mul)(F,"-1"),networkFee:p,ourReceiveAddresses:[],signedTx:"",otherParams:se,walletId:this.walletId}})}signTx(e,t){return h(this,null,function*(){const n=g(this.currencyInfo.pluginId)(t),{unsignedSerializedSolTx:o}=(0,v.Xp)(e);if(o==null)throw new Error("Missing unsignedSerializedSolTx");const s=D.fromSecretKey(Uint8Array.from($.YU.parse(n.privateKey))),l=k.from(o);return l.recentBlockhash=this.recentBlockhash,l.sign({publicKey:s.publicKey,secretKey:s.secretKey}),e.signedTx=l.serialize().toString("base64"),this.warn(`signTx
|
|
2
|
+
${(0,v.oX)(e)}`),e})}broadcastTx(e){return h(this,null,function*(){if(e.signedTx==null)throw new Error("Missing signedTx");try{const t=[e.signedTx,{encoding:"base64"}],n=yield this.fetchRpc("sendTransaction",t);e.txid=n,e.date=Date.now()/1e3,this.warn(`SUCCESS broadcastTx
|
|
3
|
+
${(0,v.oX)(e)}`)}catch(t){throw this.warn("FAILURE broadcastTx failed: ",t),t}return e})}getDisplayPrivateSeed(e){return g(this.currencyInfo.pluginId)(e).mnemonic}getDisplayPublicSeed(){return this.walletInfo.keys.publicKey}}function Z(f,e,t,n){return h(this,null,function*(){const o=m(t),s=new X(f,e,o,n);return yield s.loadEngine(e,o,n),s})}var w=(f,e,t)=>new Promise((n,o)=>{var s=i=>{try{a(t.next(i))}catch(p){o(p)}},l=i=>{try{a(t.throw(i))}catch(p){o(p)}},a=i=>i.done?n(i.value):Promise.resolve(i.value).then(s,l);a((t=t.apply(f,e)).next())});const{Keypair:j,PublicKey:M}=C,ee=(f,e)=>w(void 0,null,function*(){const t=yield(0,T.mnemonicToSeed)(f),n=U.derivePath(e,t.toString("hex")).key;return j.fromSeed(Uint8Array.from(b.Buffer.from(n,"hex")))});class V{constructor(e){const{builtinTokens:t,currencyInfo:n,io:o,networkInfo:s}=e;this.builtinTokens=t,this.currencyInfo=n,this.io=o,this.networkInfo=s}importPrivateKey(e){return w(this,null,function*(){const{pluginId:t}=this.currencyInfo;if(!(0,T.validateMnemonic)(e))throw new Error("Invalid mnemonic");const o=yield ee(e,this.networkInfo.derivationPath);return{[`${t}Mnemonic`]:e,[`${t}Key`]:b.Buffer.from(o.secretKey).toString("hex"),publicKey:o.publicKey.toBase58()}})}createPrivateKey(e){return w(this,null,function*(){if(e!==this.currencyInfo.walletType)throw new Error("InvalidWalletType");const t=b.Buffer.from(this.io.random(32)),n=(0,T.entropyToMnemonic)(t);return yield this.importPrivateKey(n)})}derivePublicKey(e){return w(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 w(this,null,function*(){const{pluginId:o}=this.currencyInfo,s={[o]:!0},{parsedUri:l,edgeParsedUri:a}=(0,A.k)(this.currencyInfo,e,s,t||this.currencyInfo.currencyCode,n);let i="";if(a.publicAddress&&(i=a.publicAddress),!M.isOnCurve(new M(i).toBytes()))throw new Error("InvalidPublicAddressError");return a.uniqueIdentifier=l.query.memo,a})}encodeUri(e,t){return w(this,null,function*(){const{pluginId:n}=this.currencyInfo,{nativeAmount:o,currencyCode:s,publicAddress:l}=e;if(!M.isOnCurve(new M(l).toBytes()))throw new Error("InvalidPublicAddressError");let a;if(typeof o=="string"){const p=(0,v.cp)(this.currencyInfo,s||this.currencyInfo.currencyCode,t);if(p==null)throw new Error("InternalErrorInvalidCurrencyCode");a=(0,I.div)(o,p.multiplier,18)}return(0,A.Q)(e,n,a)})}}function te(f){return w(this,null,function*(){return new V(f)})}},89214:function(){},52361:function(){},94616:function(){},55024:function(){}}]);
|