require(`../../../../_virtual/_rolldown/runtime.cjs`);const e=require(`../../constants/protocol.constants.cjs`),t=require(`../../types/cache.types.cjs`),n=require(`../../functions/utils/erc20tokenFunctions.cjs`),r=require(`../../functions/utils/caseInsensitive.utils.cjs`),i=require(`../../API/API.cjs`),a=require(`../../error-handling/logger.cjs`),o=require(`../../functions/utils/string.utils.cjs`),s=require(`./token-visibility-db.cjs`),c=require(`../../functions/utils/create-provider.cjs`),l=require(`../../constants/events.constants.cjs`);require(`../../constants/index.cjs`),require(`../../functions/index.cjs`);let u=require(`ethers`),d=require(`idb-keyval`),f=require(`async-mutex`);var p=new class{fetchedTokens={};updateMutexes={};transferEventTopic=u.ethers.id(`Transfer(address,address,uint256)`);chunkSize=2e3;getMutex(e){return this.updateMutexes[e]||(this.updateMutexes[e]=new f.Mutex),this.updateMutexes[e]}withRegistryOverlay(e,t){let r=n.getERC20Token(e.erc20TokenAddress,t);return r?{...e,name:r.name,symbol:r.symbol,logoURI:r.logoURI,decimals:r.decimals}:e}async getPublicTokens(e,r){let i=o.getStateKey(r,e);return((await(0,d.get)(t.StorageKeys.EVENTS_PUBLIC_TOKENS))?.[i]||[]).map(t=>n.overlayTokenWithRegistryData(t,e))}getFetchedTokens(e,t){let r=o.getStateKey(t,e);return(this.fetchedTokens[r]||[]).map(t=>n.overlayTokenWithRegistryData(t,e))}async fetchAndUpdatePublicTokens(e,n){let i=o.getStateKey(e,n);await this.getMutex(i).runExclusive(async()=>{try{let a=(await this.getPublicTokens(n,e)).map(e=>e.erc20TokenAddress),{toEvents:o,fromEvents:c,latestBlock:l}=await this.getEvents(e,n),u=[...o,...c],{erc20Tokens:f}=await this.fetchPublicTokens(u,n,a),p=await s.tokenVisibilityStorage.hideSpamsAndFetchHiddenTokensAddresses(n,f),m=f.filter(e=>!r.lowerCaseIncludes(p,e.erc20TokenAddress));await(0,d.update)(t.StorageKeys.EVENTS_PUBLIC_TOKENS,(e={})=>{let t=e[i]||[],n=t.map(e=>e.erc20TokenAddress),a=m.filter(e=>!r.lowerCaseIncludes(n,e.erc20TokenAddress));t.push(...a);let s=this.updateTokenIds(c,o,t),l={...e,[i]:s};return this.fetchedTokens=l,l}),l&&await this.updateLastProcessedBlock(n,e,l)}catch(e){a.Logger.error(`public tokens db error`,e)}})}async getLastProcessedBlock(e,n){return(await(0,d.get)(t.StorageKeys.PUBLIC_TOKENS_LAST_PROCESSED_BLOCKS)||{})[o.getStateKey(n,e)]||l.EVENTS_INITIAL_BLOCKS[e]}async updateLastProcessedBlock(e,n,r){await(0,d.update)(t.StorageKeys.PUBLIC_TOKENS_LAST_PROCESSED_BLOCKS,(t={})=>{let i=o.getStateKey(n,e);return{...t,[i]:r}})}async getEvents(e,t){try{let n=c.createJsonRpcProvider(t),r=await this.getLastProcessedBlock(t,e)+1,i=await n.getBlockNumber(),a=u.ethers.zeroPadValue(e.toLowerCase(),32),o=[],s=[];for(let e=r;e<=i;e+=this.chunkSize){let t=Math.min(e+this.chunkSize-1,i),r={topics:[this.transferEventTopic,null,a],fromBlock:e,toBlock:t},c={topics:[this.transferEventTopic,a,null],fromBlock:e,toBlock:t},[l,u]=await Promise.all([n.getLogs(r),n.getLogs(c)]);o.push(...l),s.push(...u)}return{toEvents:o,fromEvents:s,latestBlock:i}}catch(n){return a.Logger.error(`Error fetching events:`,n,`chainId`,t,`walletAddress`,e),{toEvents:[],fromEvents:[],latestBlock:void 0}}}updateTokenIds(e,t,r){let i=new Map;return r.forEach(e=>{if(n.isNFTToken(e)&&e.tokenIds){let t=e.erc20TokenAddress.toLowerCase();i.set(t,[...e.tokenIds])}}),t.forEach(e=>{if(e.topics.length<=3)return;let t=e.address.toLowerCase(),n=BigInt(e.topics[3]).toString();i.has(t)||i.set(t,[]),i.get(t)?.push(n)}),e.forEach(e=>{if(e.topics.length<=3)return;let t=e.address.toLowerCase(),n=i.get(t);if(n?.length){let t=BigInt(e.topics[3]).toString(),r=n.indexOf(t);r!==-1&&n.splice(r,1)}}),r.forEach(e=>{if(n.isNFTToken(e)){let t=e.erc20TokenAddress.toLowerCase(),n=i.get(t);e.tokenIds=n?.length&&n.length>0?n:void 0}}),r}async fetchPublicTokens(t,n,o){try{let a=[e.zeroAddress,...new Set(t.map(e=>e.address))].filter(e=>e&&!r.lowerCaseIncludes(o,e));return a.length?{erc20Tokens:(await i.API.tokensInfoCall(n,a)).filter(e=>!!e)}:{erc20Tokens:[]}}catch(e){return a.Logger.error(`Error fetching public tokens:`,e),{erc20Tokens:[]}}}};exports.eventsPublicTokensDB=p;