require(`../../_virtual/_rolldown/runtime.cjs`);const e=require(`../../functions/utils/caseInsensitive.utils.cjs`),t=require(`../../functions/utils/addresses.cjs`),n=require(`../../error-handling/logger.cjs`);require(`../../functions/index.cjs`);let r=require(`idb-keyval`);var i=new class{STORAGE_KEY=`contacts`;checkForDuplicate(e,t,n){if(e.find(({ethereumAddress:e,nickname:r})=>(e===t.ethereumAddress||r===t.nickname)&&e!==n)!==void 0)throw Error(`Duplicate Contact attribute`)}async createContact(e,t){let n=e.toLowerCase();await(0,r.update)(this.STORAGE_KEY,e=>{let r=e??{},i=r[n]??[];return this.checkForDuplicate(i,t),i.push(t),r[n]=i,r})}async getContacts(e){try{await this.removeOldStylePrivateAddressContacts(e);let t=e.toLowerCase(),n=await(0,r.get)(this.STORAGE_KEY);return!n||!n[t]?[]:n[t]}catch(e){return n.Logger.error(`Error while getting contacts:`,e),[]}}async editContact(t,n,i){let a=t.toLowerCase();await(0,r.update)(this.STORAGE_KEY,t=>{let r=t??{},o=r[a];if(!r||!o)throw Error(`Contacts could not be fetched`);this.checkForDuplicate(o,i,n);let s=o.findIndex(({ethereumAddress:t})=>e.caseInsensitiveEqual(t,n));if(s===-1)throw Error(`Contact to be edited was not found`);return o[s]=i,r[a]=o,r})}async removeOldStylePrivateAddressContacts(e){let n=e.toLowerCase(),i=0;return await(0,r.update)(this.STORAGE_KEY,e=>{let r=e??{},a=r[n];if(!a?.length)return r;let o=a.filter(e=>{let n=e.ethereumAddress;return!t.isValidOldStylePrivateAddress(n)||t.isValidPrivateAddress(n)?!0:(i+=1,!1)});return i===0||(r[n]=o),r}),i}async deleteContact(e,t){let n=e.toLowerCase();await(0,r.update)(this.STORAGE_KEY,e=>{let r=e??{},i=r[n];if(!r||!i)throw Error(`Contacts could not be fetched`);return r[n]=i.filter(({ethereumAddress:e})=>e!==t),r})}};exports.contactStorage=i;