text: (()=>{"use strict";var e={533:function(e,t,r){var a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const n=a(r(364)),s=r(51),i=a(r(458)),o=a(r(409));function l(e){return`0x${e.getAddress().toString("hex")}`}a(r(748)).default.install({errorFormatterForce:!0}),t.default=class{constructor(e,t,r,a){this.accounts=[],this.web3=new o.default(e),this.chainId=t,this.config=r,this.signWithProviderImpl=null!=a?a:this._signWithProviderDefault}addAccount(e){const t=n.default.fromPrivateKey(e.privateKey);if(!s.isSameAddress(l(t),e.address))throw new Error("invalid keypair");this.accounts.push(e)}newAccount(){const e=n.default.generate(),t={privateKey:e.getPrivateKey(),address:l(e)};return this.addAccount(t),t}isDeployRequest(e){let t=!1;return void 0!==e.request.recoverer&&(t=!0),t}async sign(e){const t=Object.assign({},e),r=this.isDeployRequest(e)?new s.TypedDeployRequestData(this.chainId,e.relayData.callForwarder,t):new s.TypedRequestData(this.chainId,e.relayData.callForwarder,t),a=this.accounts.find((t=>s.isSameAddress(t.address,e.request.from)));let n,o;try{o=null!=a?this._signWithControlledKey(a,r):await this._signWithProvider(r),n=i.default.recoverTypedSignature_v4({data:r,sig:o})}catch(t){throw new Error(`Failed to sign relayed transaction for ${e.request.from}: ${t}`)}if(!s.isSameAddress(e.request.from.toLowerCase(),n))throw new Error(`Internal RelayClient exception: signature is not correct: sender=${e.request.from}, recovered=${n}`);return o}async _signWithProvider(e){return await this.signWithProviderImpl(e)}async _signWithProviderDefault(e){var t,r;return await s.getEip712Signature(this.web3,e,null!==(t=this.config.methodSuffix)&&void 0!==t?t:"",null!==(r=this.config.jsonStringifyRequest)&&void 0!==r&&r)}_signWithControlledKey(e,t){return i.default.signTypedData_v4(e.privateKey,{data:t})}getAccounts(){return this.accounts.map((e=>e.address))}}},64:function(e,t,r){var a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.getDependencies=t.resolveConfiguration=t.configure=void 0;const n=r(51),s=a(r(533)),i=a(r(522)),o=a(r(883)),l=r(434),c=a(r(68)),d=r(473),u={preferredRelays:[],onlyPreferredRelays:!1,relayLookupWindowParts:1,relayLookupWindowBlocks:6e4,gasPriceFactorPercent:0,minGasPrice:6e7,maxRelayNonceGap:3,sliceSize:3,relayTimeoutGrace:1800,methodSuffix:"",jsonStringifyRequest:!1,chainId:n.defaultEnvironment.chainId,relayHubAddress:n.constants.ZERO_ADDRESS,deployVerifierAddress:n.constants.ZERO_ADDRESS,relayVerifierAddress:n.constants.ZERO_ADDRESS,forwarderAddress:n.constants.ZERO_ADDRESS,smartWalletFactoryAddress:n.constants.ZERO_ADDRESS,logLevel:0,clientId:"1"};t.configure=function(e){return Object.assign({},u,e)},t.resolveConfiguration=async function(e,t){var r,a,s,i;if(null==e.send&&null==e.sendAsync)throw new Error("First param is not a web3 provider");if(null!=t.relayHubAddress)throw new Error("Resolve cannot override passed values");const o=new n.ContractInteractor(e,u),[l,c]=await Promise.all([null!==(r=t.chainId)&&void 0!==r?r:o.getAsyncChainId(),null!==(a=t.forwarderAddress)&&void 0!==a?a:""]),d=e.isMetaMask,h={forwarderAddress:c,chainId:l,methodSuffix:null!==(s=t.methodSuffix)&&void 0!==s?s:d?"_v4":u.methodSuffix,jsonStringifyRequest:null!==(i=t.jsonStringifyRequest)&&void 0!==i?i:!!d||u.jsonStringifyRequest};return Object.assign(Object.assign(Object.assign({},u),t),h)},t.getDependencies=function(e,t,r){var a,u,h,y,f,g,p;let v=null==r?void 0:r.contractInteractor;if(null==v){if(null==t)throw new Error("either contract interactor or web3 provider must be non-null");v=new n.ContractInteractor(t,e)}let R=null==r?void 0:r.accountManager;if(null==R){if(null==t)throw new Error("either account manager or web3 provider must be non-null");R=new s.default(t,null!==(a=e.chainId)&&void 0!==a?a:v.getChainId(),e)}const w=null!==(u=null==r?void 0:r.httpClient)&&void 0!==u?u:new i.default(new o.default,e),m=null!==(h=null==r?void 0:r.pingFilter)&&void 0!==h?h:d.GasPricePingFilter,S=null!==(y=null==r?void 0:r.relayFilter)&&void 0!==y?y:l.EmptyFilter,E=null!==(f=null==r?void 0:r.scoreCalculator)&&void 0!==f?f:l.DefaultRelayScore,A={httpClient:w,contractInteractor:v,knownRelaysManager:null!==(g=null==r?void 0:r.knownRelaysManager)&&void 0!==g?g:new l.KnownRelaysManager(v,e,S),accountManager:R,transactionValidator:null!==(p=null==r?void 0:r.transactionValidator)&&void 0!==p?p:new c.default(v,e),pingFilter:m,relayFilter:S,scoreCalculator:E,config:e};for(const e in r)if(null==A[e])throw new Error(`Unexpected override key ${e}`);return A}},450:function(e,t,r){var a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const n=a(r(522)),s=r(51),i=a(r(883)),o=r(64),l=r(865),c=r(88),d=r(784),u=s.constants.ZERO_ADDRESS;t.default=class{constructor(e,t,r){this.config=e,this.initialized=!1,this.dependencies=o.getDependencies(this.config,t.currentProvider),this.relayWorkerAddress=r}async _init(){if(this.initialized)throw new Error("_init was already called");await this.dependencies.contractInteractor.init(),this.initialized=!0}async createDeployRequest(e,t,r,a,n,i,o){return{request:{relayHub:this.config.relayHubAddress,from:e,to:u,value:"0",nonce:(await this.getFactoryNonce(this.config.smartWalletFactoryAddress,e)).toString(),data:"0x",tokenContract:t,tokenAmount:r,tokenGas:a,recoverer:null!=o?o:s.constants.ZERO_ADDRESS,index:null!=i?i:"0"},relayData:{gasPrice:null!=n?n:await web3.eth.getGasPrice(),relayWorker:this.relayWorkerAddress,callForwarder:this.config.smartWalletFactoryAddress,callVerifier:this.config.deployVerifierAddress,domainSeparator:s.getDomainSeparatorHash(this.config.smartWalletFactoryAddress,this.config.chainId)}}}async estimateDestinationContractInternalCallGas(e,t,r,a,n=!0){return await this.dependencies.contractInteractor.estimateDestinationContractCallGas({from:e,to:t,gasPrice:null!=a?a:await web3.eth.getGasPrice(),data:r},n)}async createRelayRequest(e,t,r,a,n,i,o,l,c){let u=l;const h=null!=c?c:await web3.eth.getGasPrice();if(void 0===u||null==u){const e=await this.estimateDestinationContractInternalCallGas(r,t,a,h);u=d.toHex(e)}return{request:{relayHub:this.config.relayHubAddress,from:e,to:t,data:a,value:"0",gas:u,nonce:(await this.getSenderNonce(r)).toString(),tokenContract:n,tokenAmount:i,tokenGas:o},relayData:{gasPrice:h,relayWorker:this.relayWorkerAddress,callForwarder:r,callVerifier:this.config.relayVerifierAddress,domainSeparator:s.getDomainSeparatorHash(r,this.config.chainId)}}}signDeployRequest(e,t){const r=Object.assign({},t),a=new s.TypedDeployRequestData(this.config.chainId,this.config.smartWalletFactoryAddress,r);return this.signAndVerify(e,a,t)}signRelayRequest(e,t){const r=Object.assign({},t),a=new s.TypedRequestData(this.config.chainId,t.relayData.callForwarder,r);return this.signAndVerify(e,a,t)}signAndVerify(e,t,r){const a=e.sign(t);if(!e.verifySign(a,t,r))throw new Error("Internal exception: signature is not correct");return a}async generateDeployTransactionRequest(e,t){return{relayRequest:t,metadata:await this.generateMetadata(e)}}async generateRelayTransactionRequest(e,t){return{relayRequest:t,metadata:await this.generateMetadata(e)}}async generateMetadata(e){return{relayHubAddress:this.config.relayHubAddress,signature:e,relayMaxNonce:await this.dependencies.contractInteractor.getTransactionCount(this.relayWorkerAddress)+this.config.maxRelayNonceGap}}async getSenderNonce(e){return await this.dependencies.contractInteractor.getSenderNonce(e)}async getFactoryNonce(e,t){return await this.dependencies.contractInteractor.getFactoryNonce(e,t)}async sendTransaction(e,t){const r=new n.default(new i.default,{});try{const a=await r.relayTransaction(e,t);console.log(`hexTrx is ${a}`);const n=new l.Transaction(a,this.dependencies.contractInteractor.getRawTxOptions()),s=`0x${n.hash(!0).toString("hex")}`;return console.log("tx hash: "+s),{transaction:n}}catch(e){if(e instanceof Error){const t=e instanceof Error?e.message:JSON.stringify(e);return console.log(`GOT ERROR - Reason: ${t}`),{error:e}}console.error(e)}}static async discoverAccountsUsingMnemonic(e,t,r,a,n){const s=new c.SmartWalletDiscovery(t,n);return await s.discoverAccountsFromMnemonic(e,r,a),s.accounts}static async discoverAccountsFromExtendedPublicKeys(e,t,r,a){const n=new c.SmartWalletDiscovery(t,a);return await n.discoverAccountsFromExtendedPublicKeys(e,r),n.accounts}static async discoverAccounts(e,t,r,a){const n=new c.SmartWalletDiscovery(t,a);return await n.discoverAccounts(e,r),n.accounts}}},522:function(e,t,r){var a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const n=a(r(732));t.default=class{constructor(e,t){this.httpWrapper=e,this.config=t}async getPingResponse(e,t){const r=null==t?"":"?verifier="+t,a=await this.httpWrapper.sendPromise(e+"/getaddr"+r);if(null==a)throw new Error("Relay responded without a body");return n.default.info(`pingResponse: ${JSON.stringify(a)}`),a}async relayTransaction(e,t){const{signedTx:r,error:a}=await this.httpWrapper.sendPromise(e+"/relay",t);if(n.default.info("relayTransaction response:",r,a),null!=a)throw new Error(`Got error response from relay: ${a}`);if(null==r)throw new Error("body.signedTx field missing.");return r}}},883:function(e,t,r){var a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const n=a(r(376));class s{constructor(e={},t=!1){this.provider=n.default.create(Object.assign({timeout:3e4,headers:{"Content-Type":"application/json"}},e)),this.logreq=t,this.logreq&&this.provider.interceptors.response.use((function(e){return console.log("got response:",e.config.url,JSON.stringify(e.data).slice(0,120)),e}),(async function(e){const t=null!=e.response?e.response.data:{error:e.message},r=("string"==typeof t?t:JSON.stringify(t)).slice(0,120),a=null!=e.response?e.response.config.url:e.address;return console.log("got response:",a,"err=",r),await Promise.reject(e)}))}async sendPromise(e,t){return this.logreq&&console.log("sending request:",e,JSON.stringify(null!=t?t:{}).slice(0,120)),(await this.provider.request({url:e,method:null!=t?"POST":"GET",data:t})).data}}t.default=s,e.exports=s},434:function(e,t,r){var a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.KnownRelaysManager=t.DefaultRelayScore=t.EmptyFilter=void 0;const n=a(r(732));t.EmptyFilter=()=>!0,t.DefaultRelayScore=async function(e,t,r){return Math.pow(.9,r.length)},t.KnownRelaysManager=class{constructor(e,r,a,n){this.latestScannedBlock=0,this.relayFailures=new Map,this.preferredRelayers=[],this.allRelayers=[],this.config=r,this.relayFilter=null!=a?a:t.EmptyFilter,this.scoreCalculator=null!=n?n:t.DefaultRelayScore,this.contractInteractor=e,this.relayLookupWindowParts=this.config.relayLookupWindowParts}async refresh(){this._refreshFailures(),n.default.debug("KnownRelaysManager - Refresh failures done");const e=await this._fetchRecentlyActiveRelayManagers();n.default.debug("KnownRelaysManager - Fetched recently active Relay Managers done"),this.preferredRelayers=this.config.preferredRelays.map((e=>Object.assign({},{url:e}))),this.allRelayers=await this.getRelayDataForManagers(e),n.default.debug("KnownRelaysManager - Get relay info for Managers done"),n.default.debug("KnownRelaysManager - Refresh done")}async getRelayDataForManagers(e){return 0===e.size?[]:(await this.contractInteractor.getActiveRelayInfo(e)).filter(this.relayFilter)}splitRange(e,t,r){const a=t-e+1,n=Math.ceil(a/r),s=[];let i;for(i=e;i<t;i+=n)s.push({fromBlock:i,toBlock:Math.min(t,i+n-1)});return s}async getPastEventsForHub(e,t){let r;for(;;){const a=this.splitRange(e,t,this.relayLookupWindowParts);try{const e=a.map((({fromBlock:e,toBlock:t})=>this.contractInteractor.getPastEventsForHub([],{fromBlock:e,toBlock:t})));r=await Promise.all(e);break}catch(e){if(!(null!=e.toString().match(/query returned more than/)&&this.config.relayLookupWindowBlocks>this.relayLookupWindowParts))throw e;if(this.relayLookupWindowParts>=16)throw new Error(`Too many events after splitting by ${this.relayLookupWindowParts}`);this.relayLookupWindowParts*=4}}return r.flat()}async _fetchRecentlyActiveRelayManagers(){const e=await this.contractInteractor.getBlockNumber(),t=Math.max(0,e-this.config.relayLookupWindowBlocks),r=await this.getPastEventsForHub(t,e);n.default.info(`fetchRelaysAdded: found ${r.length} events`);const a=new Set;return r.forEach((e=>{a.add(e.returnValues.relayManager)})),n.default.info(`fetchRelaysAdded: found unique relays: ${JSON.stringify(Array.from(a.values()))}`),this.latestScannedBlock=e,a}_refreshFailures(){const e=new Map;this.relayFailures.forEach(((t,r)=>{e.set(r,t.filter((e=>((new Date).getTime()-e.lastErrorTime)/1e3<this.config.relayTimeoutGrace)))})),this.relayFailures=e}async getRelaysSortedForTransaction(e){const t=[];return t[0]=Array.from(this.preferredRelayers),t[1]=await this._sortRelaysInternal(e,this.allRelayers),t}async _sortRelaysInternal(e,t){var r;const a=new Map;for(const n of t){let t=0;t=await this.scoreCalculator(n,e,null!==(r=this.relayFailures.get(n.url))&&void 0!==r?r:[]),a.set(n.manager,t)}return Array.from(t.values()).sort(((e,t)=>{var r,n;const s=null!==(r=a.get(e.manager))&&void 0!==r?r:0;return(null!==(n=a.get(t.manager))&&void 0!==n?n:0)-s}))}saveRelayFailure(e,t,r){const a=this.relayFailures.get(r),n={lastErrorTime:e,relayManager:t,relayUrl:r};null==a?this.relayFailures.set(r,[n]):a.push(n)}}},473:function(e,t,r){var a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t._dumpRelayingResult=t.RelayClient=t.GasPricePingFilter=void 0;const n=a(r(732)),s=r(865),i=r(51),o=a(r(743)),l=r(64),c=r(614),d=r(153),u=r(784);t.GasPricePingFilter=(e,t)=>{if(null!=t.gasPrice&&parseInt(e.minGasPrice)>parseInt(t.gasPrice))throw new Error(`Proposed gas price: ${t.gasPrice}; relay's MinGasPrice: ${e.minGasPrice}`)},t.RelayClient=class{constructor(e,t,r){this.emitter=new c.EventEmitter,this.initialized=!1;const a=l.configure(t),s=l.getDependencies(a,e,r);this.config=s.config,this.httpClient=s.httpClient,this.contractInteractor=s.contractInteractor,this.knownRelaysManager=s.knownRelaysManager,this.transactionValidator=s.transactionValidator,this.accountManager=s.accountManager,this.pingFilter=s.pingFilter,n.default.setLevel(this.config.logLevel)}registerEventListener(e){this.emitter.on("enveloping",e)}unregisterEventListener(e){this.emitter.off("enveloping",e)}emit(e){this.emitter.emit("enveloping",e)}async _broadcastRawTx(e){const t="0x"+e.serialize().toString("hex"),r="0x"+e.hash(!0).toString("hex");n.default.info(`Broadcasting raw transaction signed by relay. TxHash: ${r}`);try{return await this._isAlreadySubmitted(r)||await this.contractInteractor.sendSignedTransaction(t),{hasReceipt:!0}}catch(e){if(e instanceof Error)return null!=(null==e?void 0:e.message.match(/the tx doesn't have the correct nonce|known transaction/))?{hasReceipt:!1,wrongNonce:!0,broadcastError:e}:{hasReceipt:!1,broadcastError:e};console.error(e)}}async _isAlreadySubmitted(e){const[t,r]=await Promise.all([this.contractInteractor.web3.eth.getTransactionReceipt(e),this.contractInteractor.web3.eth.getTransaction(e)]);return null!=t||null!=r}async _init(){this.initialized||(this.emit(new d.InitEvent),await this.contractInteractor.init(),this.initialized=!0)}async estimateMaxPossibleRelayGasWithLinearFit(e,t){var r,a;const n=Object.assign({},e);let s;n.gasPrice=null!==(r=n.forceGasPrice)&&void 0!==r?r:await this._calculateGasPrice();const o=null!==(a=n.isSmartWalletDeploy)&&void 0!==a&&a;let l;if(void 0===n.tokenGas||null==n.tokenGas?(l=await this.estimateTokenTransferGas(n,t),n.tokenGas=u.toHex(l)):l=u.toBN(n.tokenGas).toNumber(),o){let e=0;n.gas="0x00";const r=await this._prepareFactoryGasEstimationRequest(n,t);e=await this.calculateDeployCallGas(r)+Number(n.tokenGas),s=i.calculateDeployTransactionMaxPossibleGas(e.toString(),n.tokenGas).toNumber()}else{let e;e=void 0===n.gas||null==n.gas?await this.contractInteractor.estimateDestinationContractCallGas(n):u.toBN(n.gas).toNumber(),s=i.estimateMaxPossibleRelayCallWithLinearFit(e,l)}return s}async estimateMaxPossibleRelayGas(e,t){var r,a,n;const s=Object.assign({},e);let o;s.gasPrice=null!==(r=s.forceGasPrice)&&void 0!==r?r:await this._calculateGasPrice();const l=null!==(a=s.isSmartWalletDeploy)&&void 0!==a&&a;s.tokenGas=null!==(n=s.tokenGas)&&void 0!==n?n:(await this.estimateTokenTransferGas(s,t)).toString();let c=0;if(l){s.gas="0x00";const e=await this._prepareFactoryGasEstimationRequest(s,t);c=await this.calculateDeployCallGas(e)+Number(s.tokenGas),o=i.calculateDeployTransactionMaxPossibleGas(c.toString(),s.tokenGas)}else{const e=await this.calculateSmartWalletRelayGas(s,t)+Number(s.tokenGas);o=u.toBN(Math.ceil(e*i.constants.ESTIMATED_GAS_CORRECTION_FACTOR))}return o.toNumber()}async calculateDeployCallGas(e){return await this.contractInteractor.walletFactoryEstimateGasOfDeployCall(e)}async calculateSmartWalletRelayGas(e,t){const r=await this._prepareRelayHttpRequest({pingResponse:{relayWorkerAddress:t,relayManagerAddress:i.constants.ZERO_ADDRESS,relayHubAddress:i.constants.ZERO_ADDRESS,minGasPrice:"0",ready:!0,version:""},relayInfo:{manager:"",url:"",registered:!1,currentlyStaked:!1}},Object.assign(Object.assign({},e),{tokenAmount:"0"}));if(void 0===e.relayHub||null===e.relayHub||e.relayHub===i.constants.ZERO_ADDRESS)throw new Error("calculateSmartWalletDeployGasNewWay: RelayHub must be defined");return await this.contractInteractor.estimateRelayTransactionMaxPossibleGasWithTransactionRequest(r)}async _prepareFactoryGasEstimationRequest(e,t){var r,a,n,s,o,l,c;if(void 0===e.isSmartWalletDeploy||!e.isSmartWalletDeploy)throw new Error("Request type is not for SmartWallet deploy");const d=this.resolveForwarder(e),u=await this.contractInteractor.getFactoryNonce(d,e.from),h=BigInt(null!==(r=e.gasPrice)&&void 0!==r?r:"0x00").toString(),y=BigInt(null!==(a=e.value)&&void 0!==a?a:"0").toString(),f=BigInt("0x00").toString(),g=BigInt("0x00").toString(),p={request:{relayHub:null!==(n=e.relayHub)&&void 0!==n?n:this.config.relayHubAddress,to:e.to,data:e.data,from:e.from,value:y,nonce:u,tokenAmount:f,tokenGas:g,tokenContract:null!==(s=e.tokenContract)&&void 0!==s?s:i.constants.ZERO_ADDRESS,recoverer:null!==(o=e.recoverer)&&void 0!==o?o:i.constants.ZERO_ADDRESS,index:null!==(l=e.index)&&void 0!==l?l:"0"},relayData:{gasPrice:h,callVerifier:null!==(c=e.callVerifier)&&void 0!==c?c:i.constants.ZERO_ADDRESS,domainSeparator:i.getDomainSeparatorHash(d,this.accountManager.chainId),callForwarder:d,relayWorker:t}},v=await this.accountManager.sign(p);return{relayRequest:p,metadata:{relayHubAddress:this.config.relayHubAddress,signature:v,relayMaxNonce:0}}}async estimateTokenTransferGas(e,t){var r,a,n,s,o;let l=0;const c=null!==(r=e.tokenContract)&&void 0!==r?r:i.constants.ZERO_ADDRESS;if(c!==i.constants.ZERO_ADDRESS&&u.toBN(null!==(a=e.tokenAmount)&&void 0!==a?a:"0").gt(u.toBN(0))){let r;if(null!==(n=e.isSmartWalletDeploy)&&void 0!==n&&n){const t=null!==(s=e.smartWalletAddress)&&void 0!==s?s:i.constants.ZERO_ADDRESS;if(t===i.constants.ZERO_ADDRESS)throw Error("In a deploy, if tokenGas is not defined, then the calculated SmartWallet address is needed to estimate the tokenGas value");r=t}else r=this.resolveForwarder(e);if(r!==i.constants.ZERO_ADDRESS){const a=this.contractInteractor.web3.eth.abi.encodeFunctionCall({name:"transfer",type:"function",inputs:[{type:"address",name:"recipient"},{type:"uint256",name:"amount"}]},[t,null!==(o=e.tokenAmount)&&void 0!==o?o:"0"]);l=await this.contractInteractor.estimateGas({from:r,to:c,gasPrice:e.gasPrice,data:a})}}let d=l>i.constants.INTERNAL_TRANSACTION_ESTIMATE_CORRECTION?l-i.constants.INTERNAL_TRANSACTION_ESTIMATE_CORRECTION:l;return d*=i.constants.ESTIMATED_GAS_CORRECTION_FACTOR,d}async relayTransaction(e){var t,r,a;await this._init(),n.default.debug("Relay Client - Relaying transaction"),n.default.debug(`Relay Client - Relay Hub:${e.relayHub}`),this.emit(new d.RefreshRelaysEvent),await this.knownRelaysManager.refresh(),e.gasPrice=null!==(t=e.forceGasPrice)&&void 0!==t?t:await this._calculateGasPrice();const s=(void 0===e.tokenGas||null===e.tokenGas)&&void 0!==e.tokenAmount&&null!==e.tokenAmount&&Number(e.tokenAmount)>0;if(null!==(r=e.isSmartWalletDeploy)&&void 0!==r&&r)e.gas="0x00";else if(void 0===e.gas||null==e.gas){const t=await this.contractInteractor.estimateDestinationContractCallGas(this.getEstimateGasParams(e));e.gas=u.toHex(t)}n.default.debug(`Relay Client - Estimated gas for relaying: ${e.gas}`);const i=await new o.default(e,this.knownRelaysManager,this.httpClient,this.pingFilter,this.config).init(),l=i.relaysLeft().length;if(this.emit(new d.DoneRefreshRelaysEvent(l)),0===l)throw new Error("no registered relayers");const c=new Map;for(n.default.debug("Relay Client - Selecting active relay");;){let t;const r=await i.selectNextRelay();if(null!=r){if(this.emit(new d.NextRelayEvent(r.relayInfo.url)),s&&(e.tokenGas=(await this.estimateTokenTransferGas(e,r.pingResponse.relayWorkerAddress)).toString()),t=await this._attemptRelay(r,e).catch((e=>({error:e}))),void 0===t.transaction||null===t.transaction){c.set(r.relayInfo.url,null!==(a=t.error)&&void 0!==a?a:new Error("No error reason was given"));continue}n.default.debug("Relay Client - Relayed done")}return{transaction:null==t?void 0:t.transaction,relayingErrors:c,pingErrors:i.errors}}}async _calculateGasPrice(){const e=this.config.gasPriceFactorPercent,t=await this.contractInteractor.getGasPrice();let r=Math.round(parseInt(t)*(e+100)/100);return null!=this.config.minGasPrice&&r<this.config.minGasPrice&&(r=this.config.minGasPrice),`0x${r.toString(16)}`}async _attemptRelay(e,t){var r,a,o;let l,c,u;if(n.default.info(`attempting relay: ${JSON.stringify(e)} transaction: ${JSON.stringify(t)}`),null!==(r=t.isSmartWalletDeploy)&&void 0!==r&&r){const r=await this._prepareDeployHttpRequest(e,t);this.emit(new d.ValidateRequestEvent),c=await this.contractInteractor.validateAcceptDeployCall(r),l=r}else if(l=await this._prepareRelayHttpRequest(e,t),this.emit(new d.ValidateRequestEvent),c=await this.contractInteractor.validateAcceptRelayCall(l.relayRequest,l.metadata.signature),c.revertedInDestination)return{error:new Error(`Destination contract method reverted in local view call : ${i.decodeRevertReason(null!==(a=c.returnValue)&&void 0!==a?a:"")}`)};if(c.reverted)return{error:new Error(`local view call reverted: ${i.decodeRevertReason(c.returnValue)}`)};if(!c.verifierAccepted)return{error:new Error(`verifier rejected in local view call : ${i.decodeRevertReason(null!==(o=c.returnValue)&&void 0!==o?o:"")}`)};this.emit(new d.SendToRelayerEvent(e.relayInfo.url));try{u=await this.httpClient.relayTransaction(e.relayInfo.url,l)}catch(t){if(t instanceof Error)return null!=(null==t?void 0:t.message)&&-1===t.message.indexOf("timeout")||this.knownRelaysManager.saveRelayFailure((new Date).getTime(),e.relayInfo.manager,e.relayInfo.url),n.default.info("relayTransaction: ",JSON.stringify(l)),{error:t};console.error(t)}const h=new s.Transaction(u,this.contractInteractor.getRawTxOptions());return this.transactionValidator.validateRelayResponse(l,u)?(this.emit(new d.RelayerResponseEvent(!0)),await this._broadcastRawTx(h),{transaction:h}):(this.emit(new d.RelayerResponseEvent(!1)),this.knownRelaysManager.saveRelayFailure((new Date).getTime(),e.relayInfo.manager,e.relayInfo.url),{error:new Error("Returned transaction did not pass validation")})}async _prepareDeployHttpRequest(e,t){var r,a,s,o,l,c,u,h;const y=this.resolveForwarder(t),f=await this.contractInteractor.getFactoryNonce(y,t.from),g=null!==(r=t.callVerifier)&&void 0!==r?r:this.config.deployVerifierAddress,p=e.pingResponse.relayWorkerAddress,v=t.gasPrice;if(null==v)throw new Error("RelayClient internal exception. Gas price not calculated. Cannot happen.");if(0!==v.indexOf("0x"))throw new Error(`Invalid gasPrice hex string: ${v}`);const R=parseInt(v,16).toString(),w=null!==(a=t.value)&&void 0!==a?a:"0",m={request:{relayHub:null!==(s=t.relayHub)&&void 0!==s?s:i.constants.ZERO_ADDRESS,to:t.to,data:t.data,from:t.from,value:w,nonce:f,tokenAmount:null!==(o=t.tokenAmount)&&void 0!==o?o:"0x00",tokenGas:null!==(l=t.tokenGas)&&void 0!==l?l:"0x00",tokenContract:null!==(c=t.tokenContract)&&void 0!==c?c:i.constants.ZERO_ADDRESS,recoverer:null!==(u=t.recoverer)&&void 0!==u?u:i.constants.ZERO_ADDRESS,index:null!==(h=t.index)&&void 0!==h?h:"0"},relayData:{gasPrice:R,callVerifier:g,domainSeparator:i.getDomainSeparatorHash(y,this.accountManager.chainId),callForwarder:y,relayWorker:p}};this.emit(new d.SignRequestEvent);const S=await this.accountManager.sign(m),E=await this.contractInteractor.getTransactionCount(p)+this.config.maxRelayNonceGap,A={relayRequest:m,metadata:{relayHubAddress:this.config.relayHubAddress,signature:S,relayMaxNonce:E}};return n.default.info(`Created HTTP deploy request: ${JSON.stringify(A)}`),A}async _prepareRelayHttpRequest(e,t){var r,a,s,o,l,c;const u=this.resolveForwarder(t),h=await this.contractInteractor.getSenderNonce(u),y=null!==(r=t.callVerifier)&&void 0!==r?r:this.config.relayVerifierAddress,f=e.pingResponse.relayWorkerAddress,g=t.gasPrice,p=t.gas;if(null==g||null==p)throw new Error("RelayClient internal exception. Gas price or gas limit still not calculated. Cannot happen.");if(0!==g.indexOf("0x"))throw new Error(`Invalid gasPrice hex string: ${g}`);if(0!==p.indexOf("0x"))throw new Error(`Invalid gasLimit hex string: ${p}`);const v=parseInt(p,16).toString(),R=parseInt(g,16).toString(),w=null!==(a=t.value)&&void 0!==a?a:"0",m={request:{relayHub:null!==(s=t.relayHub)&&void 0!==s?s:i.constants.ZERO_ADDRESS,to:t.to,data:t.data,from:t.from,value:w,nonce:h,gas:v,tokenAmount:null!==(o=t.tokenAmount)&&void 0!==o?o:"0x00",tokenGas:null!==(l=t.tokenGas)&&void 0!==l?l:"0x00",tokenContract:null!==(c=t.tokenContract)&&void 0!==c?c:i.constants.ZERO_ADDRESS},relayData:{gasPrice:R,callVerifier:y,domainSeparator:i.getDomainSeparatorHash(u,this.accountManager.chainId),callForwarder:u,relayWorker:f}};this.emit(new d.SignRequestEvent);const S=await this.accountManager.sign(m),E=await this.contractInteractor.getTransactionCount(f)+this.config.maxRelayNonceGap,A={relayRequest:m,metadata:{relayHubAddress:this.config.relayHubAddress,signature:S,relayMaxNonce:E}};return n.default.info(`Created HTTP relay request: ${JSON.stringify(A)}`),A}resolveForwarder(e){var t;const r=null!==(t=e.callForwarder)&&void 0!==t?t:i.constants.ZERO_ADDRESS;if(r===i.constants.ZERO_ADDRESS)throw new Error("No callForwarder address configured");return r}getEstimateGasParams(e){return{from:this.resolveForwarder(e),to:e.to,gasPrice:e.gasPrice,data:e.data}}async getTransactionReceipt(e,t=i.constants.WAIT_FOR_RECEIPT_RETRIES,r=i.constants.WAIT_FOR_RECEIPT_INITIAL_BACKOFF){return await this.contractInteractor.getTransactionReceipt(e,t,r)}},t._dumpRelayingResult=function(e){let t="";return e.pingErrors.size>0&&(t+=`Ping errors (${e.pingErrors.size}):`,Array.from(e.pingErrors.keys()).forEach((r=>{var a,n;const s=e.pingErrors.get(r),i=null!==(n=null!==(a=null==s?void 0:s.message)&&void 0!==a?a:null==s?void 0:s.toString())&&void 0!==n?n:"";t+=`\n${r} => ${i}\n`}))),e.relayingErrors.size>0&&(t+=`Relaying errors (${e.relayingErrors.size}):\n`,Array.from(e.relayingErrors.keys()).forEach((r=>{var a,n;const s=e.relayingErrors.get(r),i=null!==(n=null!==(a=null==s?void 0:s.message)&&void 0!==a?a:null==s?void 0:s.toString())&&void 0!==n?n:"";t+=`${r} => ${i}`}))),t}},153:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RelayerResponseEvent=t.SendToRelayerEvent=t.ValidateRequestEvent=t.SignRequestEvent=t.NextRelayEvent=t.DoneRefreshRelaysEvent=t.RefreshRelaysEvent=t.InitEvent=t.RelayEvent=void 0;class r{constructor(e,t){this.event=e,this.step=t,this.total=8}}t.RelayEvent=r,t.InitEvent=class extends r{constructor(){super("init",0)}},t.RefreshRelaysEvent=class extends r{constructor(){super("refresh-relays",1)}},t.DoneRefreshRelaysEvent=class extends r{constructor(e){super("refreshed-relays",2),this.relaysCount=e}},t.NextRelayEvent=class extends r{constructor(e){super("next-relay",3),this.relayUrl=e}},t.SignRequestEvent=class extends r{constructor(){super("sign-request",4)}},t.ValidateRequestEvent=class extends r{constructor(){super("validate-request",5)}},t.SendToRelayerEvent=class extends r{constructor(e){super("send-to-relayer",6),this.relayUrl=e}},t.RelayerResponseEvent=class extends r{constructor(e){super("relayer-response",7),this.success=e}}},36:function(e,t,r){var a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const n=a(r(573)),s=a(r(732)),i=r(820),o=r(473),l=r(51),c=r(64),d=r(784);n.default.addABI(i.IRelayHub.abi),n.default.addABI(i.IWalletFactory.abi),t.default=class{constructor(e,t,r,a){const n=c.configure(t);this.host=e.host,this.connected=e.connected,this.origProvider=e,this.config=n,"function"==typeof this.origProvider.sendAsync?this.origProviderSend=this.origProvider.sendAsync.bind(this.origProvider):this.origProviderSend=this.origProvider.send.bind(this.origProvider),this.relayClient=null!=a?a:new o.RelayClient(e,t,r),this._delegateEventsApi(e)}registerEventListener(e){this.relayClient.registerEventListener(e)}unregisterEventListener(e){this.relayClient.unregisterEventListener(e)}_delegateEventsApi(e){["on","removeListener","removeAllListeners","reset","disconnect","addDefaultEvents","once","reconnect"].forEach((t=>{void 0!==e[t]&&(this[t]=e[t].bind(e))}))}send(e,t){if(this._useEnveloping(e)){if("eth_sendTransaction"===e.method){if(void 0===e.params[0].to)throw new Error("Enveloping cannot relay contract deployment transactions. Add {from: accountWithRBTC, useEnveloping: false}.");return this._ethSendTransaction(e,t),void s.default.debug("Relay Provider - Transaction sent")}if("eth_getTransactionReceipt"===e.method)return void this._ethGetTransactionReceipt(e,t);if("eth_accounts"===e.method)return void this._getAccounts(e,t)}this.origProviderSend(this._getPayloadForRSKProvider(e),((e,r)=>{t(e,r)}))}async deploySmartWallet(e){var t,r,a,n;s.default.debug("Relay Provider - Deploying Smart wallet");let i=e.isSmartWalletDeploy,c=e.relayHub,u=e.onlyPreferredRelays,h=!1;if(null==i&&(i=!0,h=!0),!i)throw new Error("Request is not for SmartWallet deploy");null!=c&&c!==l.constants.ZERO_ADDRESS||(c=this.config.relayHubAddress,h=!0),null==u&&(u=this.config.onlyPreferredRelays,h=!0),h&&(e=Object.assign(Object.assign({},e),{isSmartWalletDeploy:i,relayHub:c,onlyPreferredRelays:u})),s.default.debug(`Relay Provider - Relay hub: ${e.relayHub}`);const y=null!==(t=e.tokenGas)&&void 0!==t?t:"0",f=null!==(r=e.tokenContract)&&void 0!==r?r:l.constants.ZERO_ADDRESS;if(s.default.debug(`Relay Provider - Token gas: ${y}`),s.default.debug(`Relay Provider - Token contract: ${f}`),f!==l.constants.ZERO_ADDRESS&&d.toBN(null!==(a=e.tokenAmount)&&void 0!==a?a:"0").gt(d.toBN("0"))&&d.toBN(y).isZero()&&(null!==(n=e.smartWalletAddress)&&void 0!==n?n:l.constants.ZERO_ADDRESS)===l.constants.ZERO_ADDRESS)throw Error("In a deploy, if tokenGas is not defined, then the calculated SmartWallet address is needed to estimate the tokenGas value");try{s.default.debug("Relay Provider - Relaying transaction started");const t=await this.relayClient.relayTransaction(e);if(null!=t.transaction){const e=`0x${t.transaction.hash(!0).toString("hex")}`;return s.default.debug(`Relay Provider - Transaction relay done, txHash: ${e}`),e}{const e=`Failed to relay call. Results:\n${o._dumpRelayingResult(t)}`;throw s.default.error(e),new Error(e)}}catch(e){const t=e instanceof Error?e.message:JSON.stringify(e);throw s.default.info("Rejected deploy wallet call",e),new Error(`Rejected deploy wallet call - Reason: ${t}`)}}calculateCustomSmartWalletAddress(e,t,r,a,n,s,i){var o,c;const u=null!==(o=web3.utils.soliditySha3({t:"address",v:t},{t:"address",v:r},{t:"address",v:a},{t:"bytes32",v:null!=i?i:l.constants.SHA3_NULL_S},{t:"uint256",v:n}))&&void 0!==o?o:"",h=null!==(c=web3.utils.soliditySha3({t:"bytes1",v:"0xff"},{t:"address",v:e},{t:"bytes32",v:u},{t:"bytes32",v:s}))&&void 0!==c?c:"";return d.toChecksumAddress("0x"+h.slice(26,h.length),this.config.chainId)}calculateSmartWalletAddress(e,t,r,a,n){var s,i;const o=null!==(s=web3.utils.soliditySha3({t:"address",v:t},{t:"address",v:r},{t:"uint256",v:a}))&&void 0!==s?s:"",l=null!==(i=web3.utils.soliditySha3({t:"bytes1",v:"0xff"},{t:"address",v:e},{t:"bytes32",v:o},{t:"bytes32",v:n}))&&void 0!==i?i:"";return d.toChecksumAddress("0x"+l.slice(26,l.length),this.config.chainId)}_ethGetTransactionReceipt(e,t){s.default.info("calling sendAsync"+JSON.stringify(e)),this.origProviderSend(e,((e,r)=>{e||null!=r&&r.result,t(e,r)}))}_ethSendTransaction(e,t){s.default.info("calling sendAsync"+JSON.stringify(e)),s.default.debug("Relay Provider - _ethSendTransaction called");let r=e.params[0],a=r.callForwarder,n=r.relayHub,i=r.onlyPreferredRelays,c=r.forceGas;null!=a&&a!==l.constants.ZERO_ADDRESS||(a=this.config.forwarderAddress),null!=n&&n!==l.constants.ZERO_ADDRESS||(n=this.config.relayHubAddress),null==i&&(i=this.config.onlyPreferredRelays),null!=c&&(c=d.toHex(c)),r=Object.assign(Object.assign({},r),{callForwarder:a,relayHub:n,onlyPreferredRelays:i,gas:c}),s.default.debug(`Relay Provider - Relay hub: ${r.relayHub}`),s.default.debug(`Relay Provider - callForwarder: ${r.callForwarder}`),this.relayClient.relayTransaction(r).then((a=>{if(void 0!==a.transaction&&null!==a.transaction){const n="0x"+a.transaction.hash(!0).toString("hex"),{retries:i,initialBackoff:o}=r;this.relayClient.getTransactionReceipt(n,i,o).then((r=>{const s=this._getRelayStatus(r);if(void 0===a.transaction||null===a.transaction)t(new Error(`Unknown Runtime error while processing result of txHash: ${n}`));else if(s.transactionRelayed){const r=this._convertTransactionToRpcSendResponse(a.transaction,e);t(null,r)}else if(s.relayRevertedOnRecipient)t(new Error(`Transaction Relayed but reverted on recipient - TxHash: ${n} , Reason: ${s.reason}`));else{const r=this._convertTransactionToRpcSendResponse(a.transaction,e);t(null,r)}}),(e=>{const r=e instanceof Error?e.message:JSON.stringify(e);s.default.info("Error while fetching transaction receipt",e),t(new Error(`Rejected relayTransaction call - Reason: ${r}`))}))}else{const e=`Failed to relay call. Results:\n${o._dumpRelayingResult(a)}`;s.default.error(e),t(new Error(e))}}),(e=>{const r=e instanceof Error?e.message:JSON.stringify(e);s.default.info("Rejected relayTransaction call",e),t(new Error(`Rejected relayTransaction call - Reason: ${r}`))}))}_convertTransactionToRpcSendResponse(e,t){var r;const a=`0x${e.hash(!0).toString("hex")}`,n=null!==(r="string"==typeof t.id?parseInt(t.id):t.id)&&void 0!==r?r:-1;return s.default.debug("Relay Provider - rpc message sent, jsonRpcResult"),s.default.debug("Relay Provider - txHash: "+a),s.default.debug("Relay Provider - id: "+n.toString()),{jsonrpc:"2.0",id:n,result:a}}_getRelayStatus(e){if(null===e.logs||0===e.logs.length)return{relayRevertedOnRecipient:!1,transactionRelayed:!1,reason:"Tx logs not found"};const t=n.default.decodeLogs(e.logs),r=t.find((e=>null!=e&&"TransactionRelayedButRevertedByRecipient"===e.name));if(null!=r){const e=r.events.find((e=>"reason"===e.name));let t="Unknown";return null!=e&&(s.default.info(`Recipient rejected on-chain: ${e.value}`),t=e.value),{relayRevertedOnRecipient:!0,transactionRelayed:!1,reason:t}}if(null!=t.find((e=>null!=e&&"TransactionRelayed"===e.name)))return{relayRevertedOnRecipient:!1,transactionRelayed:!0,reason:""};return null!=t.find((e=>null!=e&&"Deployed"===e.name))?{relayRevertedOnRecipient:!1,transactionRelayed:!0,reason:""}:(s.default.info("Neither TransactionRelayed, Deployed, nor TransactionRelayedButRevertedByRecipient events found. This might be a non-enveloping transaction "),{relayRevertedOnRecipient:!1,transactionRelayed:!1,reason:"Neither TransactionRelayed, Deployed, nor TransactionRelayedButRevertedByRecipient events found. This might be a non-enveloping transaction"})}_useEnveloping(e){var t;if("eth_accounts"===e.method)return!0;if(void 0===e.params[0])return!1;const r=e.params[0];return null===(t=null==r?void 0:r.useEnveloping)||void 0===t||t}supportsSubscriptions(){return this.origProvider.supportsSubscriptions()}disconnect(){return this.origProvider.disconnect()}newAccount(){return this.relayClient.accountManager.newAccount()}addAccount(e){this.relayClient.accountManager.addAccount(e)}_getAccounts(e,t){this.origProviderSend(e,((e,r)=>{if(null!=r&&Array.isArray(r.result)){const e=this.relayClient.accountManager.getAccounts();r.result=r.result.concat(e)}t(e,r)}))}_getPayloadForRSKProvider(e){let t=e;return t=JSON.parse(JSON.stringify(e)),Object.prototype.hasOwnProperty.call(e.params[0],"useEnveloping")&&delete t.params[0].useEnveloping,Object.prototype.hasOwnProperty.call(e.params[0],"callVerifier")&&delete t.params[0].callVerifier,Object.prototype.hasOwnProperty.call(e.params[0],"forceGasPrice")&&delete t.params[0].forceGasPrice,Object.prototype.hasOwnProperty.call(e.params[0],"callForwarder")&&delete t.params[0].callForwarder,Object.prototype.hasOwnProperty.call(e.params[0],"isSmartWalletDeploy")&&delete t.params[0].isSmartWalletDeploy,Object.prototype.hasOwnProperty.call(e.params[0],"onlyPreferredRelays")&&delete t.params[0].onlyPreferredRelays,Object.prototype.hasOwnProperty.call(e.params[0],"tokenAmount")&&delete t.params[0].tokenAmount,Object.prototype.hasOwnProperty.call(e.params[0],"tokenContract")&&delete t.params[0].tokenContract,Object.prototype.hasOwnProperty.call(e.params[0],"forceGas")&&delete t.params[0].forceGas,t}}},743:function(e,t,r){var a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const n=a(r(732)),s=r(51);t.default=class{constructor(e,t,r,a,n){this.remainingRelays=[],this.isInitialized=!1,this.errors=new Map,this.transactionDetails=e,this.knownRelaysManager=t,this.httpClient=r,this.pingFilter=a,this.config=n}async selectNextRelay(){var e;if(null!==(e=this.transactionDetails.onlyPreferredRelays)&&void 0!==e&&e){n.default.info("Only using preferred relays");let e=0;const t=!0;for(;t;){let t;const r=this._getPreferredRelaysNextSlice(e);if(!(r.length>0&&(t=await this._nextRelayInternal(r),null==t)))return t;e+=r.length}}else{const e=!0;for(;e;){const e=this._getNextSlice();let t;if(!(e.length>0&&(t=await this._nextRelayInternal(e),null==t)))return t}}}_getPreferredRelaysNextSlice(e){if(!this.isInitialized)throw new Error("init() not called");let t=[];if(this.remainingRelays[0].length>=e+1){const r=this.remainingRelays[0].slice(e,this.remainingRelays[0].length),a=Math.min(this.config.sliceSize,r.length);t=r.slice(0,a)}return t}async _nextRelayInternal(e){n.default.info("nextRelay: find fastest relay from: "+JSON.stringify(e));const t=await this._raceToSuccess(e);if(n.default.info(`race finished with a result: ${JSON.stringify(t,s.replaceErrors)}`),this._handleRaceResults(t),null!=t.winner){const e=t.winner.pingResponse.relayManagerAddress;n.default.info(`finding relay register info for manager address: ${e}; known info: ${JSON.stringify(t.winner.relayInfo)}`);const r=await this.knownRelaysManager.getRelayDataForManagers(new Set([e]));if(1==r.length)return{pingResponse:t.winner.pingResponse,relayInfo:r[0]};throw new Error(`unexpected amount of active relays for manager address: ${e}`)}n.default.info(`no race winner found for relays: ${JSON.stringify(e)})`)}async init(){return this.remainingRelays=await this.knownRelaysManager.getRelaysSortedForTransaction(this.transactionDetails),this.isInitialized=!0,this}relaysLeft(){return this.remainingRelays.flatMap((e=>e))}_getNextSlice(){if(!this.isInitialized)throw new Error("init() not called");for(const e of this.remainingRelays){const t=Math.min(this.config.sliceSize,e.length),r=e.slice(0,t);if(0!==r.length)return r}return[]}async _getRelayAddressPing(e){n.default.info(`getRelayAddressPing URL: ${e.url}`);const t=await this.httpClient.getPingResponse(e.url,this.transactionDetails.callVerifier);if(!t.ready)throw new Error(`Relay not ready ${JSON.stringify(t)}`);return this.pingFilter(t,this.transactionDetails),{pingResponse:t,relayInfo:e}}async _raceToSuccess(e){const t=new Map;return await new Promise((r=>{e.forEach((a=>{this._getRelayAddressPing(a).then((e=>{r({winner:e,errors:t})})).catch((n=>{t.set(a.url,n),t.size===e.length&&r({errors:t})}))}))}))}_handleRaceResults(e){if(!this.isInitialized)throw new Error("init() not called");this.errors=new Map([...this.errors,...e.errors]),this.remainingRelays=this.remainingRelays.map((t=>t.filter((t=>{var r;return t.url!==(null===(r=e.winner)||void 0===r?void 0:r.relayInfo.url)})).filter((t=>!Array.from(e.errors.keys()).includes(t.url)))))}}},68:function(e,t,r){var a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const n=a(r(732)),s=r(865),i=r(519),o=r(51);t.default=class{constructor(e,t){this.contractInteractor=e,this.config=t}validateRelayResponse(e,t){const r=new s.Transaction(t,this.contractInteractor.getRawTxOptions());n.default.info("returnedTx is",r.v,r.r,r.s,r.to,r.data,r.gasLimit,r.gasPrice,r.value);const a=i.bufferToHex(r.getSenderAddress());let l=!1;void 0!==e.relayRequest.request.recoverer&&(l=!0);const c=l?this.contractInteractor.encodeDeployCallABI(e.relayRequest,e.metadata.signature):this.contractInteractor.encodeRelayCallABI(e.relayRequest,e.metadata.signature);if(o.isSameAddress(i.bufferToHex(r.to),this.config.relayHubAddress)&&c===i.bufferToHex(r.data)&&o.isSameAddress(e.relayRequest.relayData.relayWorker,a)){n.default.info("validateRelayResponse - valid transaction response");const t=0===r.nonce.length?0:r.nonce.readUIntBE(0,r.nonce.byteLength);if(t>e.metadata.relayMaxNonce)throw new Error(`Relay used a tx nonce higher than requested. Requested ${e.metadata.relayMaxNonce} got ${t}`);return!0}return console.error("validateRelayResponse: req",c,this.config.relayHubAddress,e.relayRequest.relayData.relayWorker),console.error("validateRelayResponse: rsp",i.bufferToHex(r.data),i.bufferToHex(r.to),a),!1}}},88:function(e,t,r){var a=this&&this.__createBinding||(Object.create?function(e,t,r,a){void 0===a&&(a=r),Object.defineProperty(e,a,{enumerable:!0,get:function(){return t[r]}})}:function(e,t,r,a){void 0===a&&(a=r),e[a]=t[r]}),n=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),s=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)"default"!==r&&Object.prototype.hasOwnProperty.call(e,r)&&a(t,e,r);return n(t,e),t},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.SmartWalletDiscovery=t.DiscoveryConfig=t.TMnemonicLanguage=void 0;const o=r(364),l=i(r(409)),c=s(r(519)),d=r(51),u=r(784),h=r(820),y=s(r(212)),f=r(471),g=r(918),p=r(144),v=r(219),R=r(835),w=r(722),m=r(371),S=r(936),E=r(791);var A;!function(e){e[e.CZECH=1]="CZECH",e[e.ENGLISH=2]="ENGLISH",e[e.FRENCH=3]="FRENCH",e[e.ITALIAN=4]="ITALIAN",e[e.JAPANESE=5]="JAPANESE",e[e.KOREAN=6]="KOREAN",e[e.SIMPLIFIED_CHINESE=7]="SIMPLIFIED_CHINESE",e[e.SPANISH=8]="SPANISH",e[e.TRADITIONAL_CHINESE=9]="TRADITIONAL_CHINESE"}(A=t.TMnemonicLanguage||(t.TMnemonicLanguage={})),t.DiscoveryConfig=class{constructor(e){var t,r,a,n,s,i,o,l,c;this.eoaGap=null!==(t=e.eoaGap)&&void 0!==t?t:20,this.sWalletGap=null!==(r=e.sWalletGap)&&void 0!==r?r:20,this.searchBalance=null===(a=e.searchBalance)||void 0===a||a,this.searchNonce=null===(n=e.searchNonce)||void 0===n||n,this.searchTokenBalance=null===(s=e.searchTokenBalance)||void 0===s||s,this.searchDeployEvents=null===(i=e.searchDeployEvents)||void 0===i||i,this.isTestNet=null!==(o=e.isTestNet)&&void 0!==o&&o,this.factory=e.factory,this.mnemonicLanguage=null!==(l=e.mnemonicLanguage)&&void 0!==l?l:A.ENGLISH,this.recoverer=null!==(c=e.recoverer)&&void 0!==c?c:d.constants.ZERO_ADDRESS,this.logic=e.logic,this.logicParamsHash=e.logicParamsHash,this.isCustomWallet=e.isCustomWallet}};class b{constructor(e,t,r=4){this.web3=new l.default(e),this.provider=e,this.accounts=[],this.tokens=null!=t?t:[],this.reconnectionAttempts=r}async discoverAccountsFromMnemonic(e,t,r){var a,n;const s=b.getRootExtKeyFromMnemonic(t,r,e.mnemonicLanguage);let i=!1,o=0;const l=new this.web3.eth.Contract(h.ISmartWalletFactory.abi,e.factory),c=await l.methods.getCreationBytecode().call(),u=this.web3.utils.keccak256(c),y=await this.web3.eth.getChainId(),f=null!==(a=e.logic)&&void 0!==a?a:d.constants.ZERO_ADDRESS,g=null!==(n=e.logicParamsHash)&&void 0!==n?n:d.constants.SHA3_NULL_S;for(;!i;){const t=`m/44'/${e.isTestNet?"37310":"137"}'`,r=e.eoaGap;let a=0,n=0,c=0,h=0;for(;c<=r;){const r=s.derivePath(`${t}/${o}'/0/${h}`).getWallet().getAddressString(),i=await this.searchTrx(r,l),p={eoaAccount:d.constants.ZERO_ADDRESS,swAccounts:[]};i?(p.eoaAccount=r,a++,c=0):c++,h++;let v=0,R=0;for(;v<=e.sWalletGap;){const t=e.isCustomWallet?this.calculateCustomSmartWalletAddress(r,e.recoverer,f,g,R,e.factory,u,y):this.calculateSmartWalletAddress(r,e.recoverer,R,e.factory,u,y);await this.searchTrx(t,l)?(p.swAccounts.push(t),n++,v=0,c=0):v++,R++}p.swAccounts.length>0&&p.eoaAccount===d.constants.ZERO_ADDRESS&&(p.eoaAccount=r),(p.eoaAccount!==d.constants.ZERO_ADDRESS||p.swAccounts.length>0)&&this.accounts.push(p)}0===a&&0===n?i=!0:o++}}async discoverAccountsFromExtendedPublicKeys(e,t){var r,a;const n=new this.web3.eth.Contract(h.ISmartWalletFactory.abi,e.factory),s=await n.methods.getCreationBytecode().call(),i=this.web3.utils.keccak256(s),l=await this.web3.eth.getChainId(),c=null!==(r=e.logic)&&void 0!==r?r:d.constants.ZERO_ADDRESS,u=null!==(a=e.logicParamsHash)&&void 0!==a?a:d.constants.SHA3_NULL_S;for(let r=0;r<t.length;r++){const a=t[r],s=o.hdkey.fromExtendedKey(a),h=e.eoaGap;let y=0,f=0;for(;y<=h;){const t=s.deriveChild(f).getWallet().getAddressString(),r=await this.searchTrx(t,n),a={eoaAccount:d.constants.ZERO_ADDRESS,swAccounts:[]};r?(a.eoaAccount=t,y=0):y++,f++;let o=0,h=0;for(;o<=e.sWalletGap;){const r=e.isCustomWallet?this.calculateCustomSmartWalletAddress(t,e.recoverer,c,u,h,e.factory,i,l):this.calculateSmartWalletAddress(t,e.recoverer,h,e.factory,i,l);await this.searchTrx(r,n)?(a.swAccounts.push(r),o=0,y=0):o++,h++}a.swAccounts.length>0&&a.eoaAccount===d.constants.ZERO_ADDRESS&&(a.eoaAccount=t),(a.eoaAccount!==d.constants.ZERO_ADDRESS||a.swAccounts.length>0)&&this.accounts.push(a)}}}async discoverAccounts(e,t){var r,a;let n=!1,s=0;const i=new this.web3.eth.Contract(h.ISmartWalletFactory.abi,e.factory),l=await i.methods.getCreationBytecode().call(),c=this.web3.utils.keccak256(l),u=await this.web3.eth.getChainId(),y=null!==(r=e.logic)&&void 0!==r?r:d.constants.ZERO_ADDRESS,f=null!==(a=e.logicParamsHash)&&void 0!==a?a:d.constants.SHA3_NULL_S;for(;!n;){const r=e.eoaGap;let a=0,l=0,h=0,g=0;const p=null!=t?t:this.getAccountExtendedPublicKey,v=await p(s);if(null==v){n=!0;break}const R=o.hdkey.fromExtendedKey(v);for(;h<=r;){const t=R.deriveChild(g).getWallet().getAddressString(),r=await this.searchTrx(t,i),n={eoaAccount:d.constants.ZERO_ADDRESS,swAccounts:[]};r?(n.eoaAccount=t,a++,h=0):h++,g++;let s=0,o=0;for(;s<=e.sWalletGap;){const r=e.isCustomWallet?this.calculateCustomSmartWalletAddress(t,e.recoverer,y,f,o,e.factory,c,u):this.calculateSmartWalletAddress(t,e.recoverer,o,e.factory,c,u);await this.searchTrx(r,i)?(n.swAccounts.push(r),l++,s=0,h=0):s++,o++}n.swAccounts.length>0&&n.eoaAccount===d.constants.ZERO_ADDRESS&&(n.eoaAccount=t),(n.eoaAccount!==d.constants.ZERO_ADDRESS||n.swAccounts.length>0)&&this.accounts.push(n)}0===a&&0===l?n=!0:s++}}static getRootExtKeyFromMnemonic(e,t,r){let a;switch(r){case A.CZECH:a=f.wordlist;break;case A.ENGLISH:a=g.wordlist;break;case A.FRENCH:a=p.wordlist;break;case A.ITALIAN:a=v.wordlist;break;case A.JAPANESE:a=R.wordlist;break;case A.KOREAN:a=w.wordlist;break;case A.SIMPLIFIED_CHINESE:a=m.wordlist;break;case A.SPANISH:a=S.wordlist;break;case A.TRADITIONAL_CHINESE:a=E.wordlist;break;default:a=g.wordlist}if(!y.validateMnemonic(e,a))throw new Error("Mnemonic invalid or undefined");return o.hdkey.fromMasterSeed(y.mnemonicToSeedSync(e,t))}async getAccountExtendedPublicKey(e){console.debug("Account index",e)}pubKeyToAddress(e){return c.default.bufferToHex(c.default.pubToAddress(e))}async sleep(e){return await new Promise((t=>setTimeout(t,e)))}async reconnect(){let e=!1,t=0;for(;!e&&t<=this.reconnectionAttempts;){await this.sleep(5e3);try{this.web3=new l.default(this.provider),e=!0}catch(e){t++}if(!e)throw new Error("Unable to reconnect to RSKJ Node")}}async searchTrx(e,t){console.debug("Factory",t);let r=!1;try{r=new c.BN(await this.web3.eth.getBalance(e)).gtn(0)}catch(t){await this.reconnect(),r=new c.BN(await this.web3.eth.getBalance(e)).gtn(0)}if(!r){try{r=await this.web3.eth.getTransactionCount(e)>0}catch(t){await this.reconnect(),r=await this.web3.eth.getTransactionCount(e)>0}if(!r){const t=this.web3.eth.abi.encodeFunctionCall({name:"balanceOf",type:"function",inputs:[{type:"address",name:"_owner"}]},[e]);let a=0,n=0;for(;!r&&a<this.tokens.length&&n<this.reconnectionAttempts;)try{const e=await this.web3.eth.call({to:this.tokens[a],data:t});null!=e&&"string"==typeof e&&(r=Number(e)>0),a++,n=0}catch(e){n++,await this.reconnect()}}}return r}calculateSmartWalletAddress(e,t,r,a,n,s){var i,o;const l=null!==(i=web3.utils.soliditySha3({t:"address",v:e},{t:"address",v:t},{t:"uint256",v:r}))&&void 0!==i?i:"",c=null!==(o=web3.utils.soliditySha3({t:"bytes1",v:"0xff"},{t:"address",v:a},{t:"bytes32",v:l},{t:"bytes32",v:n}))&&void 0!==o?o:"";return u.toChecksumAddress("0x"+c.slice(26,c.length),s)}calculateCustomSmartWalletAddress(e,t,r,a,n,s,i,o){var l,c;const h=null!==(l=web3.utils.soliditySha3({t:"address",v:e},{t:"address",v:t},{t:"address",v:r},{t:"bytes32",v:null!=a?a:d.constants.SHA3_NULL_S},{t:"uint256",v:n}))&&void 0!==l?l:"",y=null!==(c=web3.utils.soliditySha3({t:"bytes1",v:"0xff"},{t:"address",v:s},{t:"bytes32",v:h},{t:"bytes32",v:i}))&&void 0!==c?c:"";return u.toChecksumAddress("0x"+y.slice(26,y.length),o)}}t.SmartWalletDiscovery=b},607:function(e,t,r){var a=this&&this.__createBinding||(Object.create?function(e,t,r,a){void 0===a&&(a=r),Object.defineProperty(e,a,{enumerable:!0,get:function(){return t[r]}})}:function(e,t,r,a){void 0===a&&(a=r),e[a]=t[r]}),n=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||a(t,e,r)},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.RelaySelectionManager=t.RelayProvider=t.RelayedTransactionValidator=t.HttpWrapper=t.HttpClient=t.Enveloping=t.AccountManager=void 0;const i=s(r(533));t.AccountManager=i.default;const o=s(r(450));t.Enveloping=o.default;const l=s(r(522));t.HttpClient=l.default;const c=s(r(883));t.HttpWrapper=c.default;const d=s(r(68));t.RelayedTransactionValidator=d.default;const u=s(r(36));t.RelayProvider=u.default;const h=s(r(743));t.RelaySelectionManager=h.default,n(r(488),t),n(r(301),t),n(r(681),t),n(r(828),t),n(r(635),t),n(r(533),t),n(r(64),t),n(r(450),t),n(r(434),t),n(r(473),t),n(r(153),t),n(r(36),t),n(r(743),t),n(r(88),t)},488:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.notNull=void 0,t.notNull=function(e){return null!=e}},301:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},681:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},828:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},635:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},51:e=>{e.exports=require("@rsksmart/rif-relay-common")},820:e=>{e.exports=require("@rsksmart/rif-relay-contracts")},573:e=>{e.exports=require("abi-decoder")},376:e=>{e.exports=require("axios")},458:e=>{e.exports=require("eth-sig-util")},212:e=>{e.exports=require("ethereum-cryptography/bip39")},471:e=>{e.exports=require("ethereum-cryptography/bip39/wordlists/czech")},918:e=>{e.exports=require("ethereum-cryptography/bip39/wordlists/english")},144:e=>{e.exports=require("ethereum-cryptography/bip39/wordlists/french")},219:e=>{e.exports=require("ethereum-cryptography/bip39/wordlists/italian")},835:e=>{e.exports=require("ethereum-cryptography/bip39/wordlists/japanese")},722:e=>{e.exports=require("ethereum-cryptography/bip39/wordlists/korean")},371:e=>{e.exports=require("ethereum-cryptography/bip39/wordlists/simplified-chinese")},936:e=>{e.exports=require("ethereum-cryptography/bip39/wordlists/spanish")},791:e=>{e.exports=require("ethereum-cryptography/bip39/wordlists/traditional-chinese")},865:e=>{e.exports=require("ethereumjs-tx")},519:e=>{e.exports=require("ethereumjs-util")},364:e=>{e.exports=require("ethereumjs-wallet")},614:e=>{e.exports=require("events")},732:e=>{e.exports=require("loglevel")},748:e=>{e.exports=require("source-map-support")},409:e=>{e.exports=require("web3")},784:e=>{e.exports=require("web3-utils")}},t={},r=function r(a){var n=t[a];if(void 0!==n)return n.exports;var s=t[a]={exports:{}};return e[a].call(s.exports,s,s.exports,r),s.exports}(607);module.exports=r})();