diff --git a/sei-cosmos/store/cachekv/store.go b/sei-cosmos/store/cachekv/store.go index 54b36a667a..51d583d2e6 100644 --- a/sei-cosmos/store/cachekv/store.go +++ b/sei-cosmos/store/cachekv/store.go @@ -33,7 +33,7 @@ func NewStore(parent types.KVStore, storeKey types.StoreKey, cacheSize int) *Sto cache: &sync.Map{}, deleted: &sync.Map{}, unsortedCache: &sync.Map{}, - sortedCache: dbm.NewMemDB(), + sortedCache: nil, parent: parent, storeKey: storeKey, cacheSize: cacheSize, @@ -120,7 +120,7 @@ func (store *Store) Write() { store.cache = &sync.Map{} store.deleted = &sync.Map{} store.unsortedCache = &sync.Map{} - store.sortedCache = dbm.NewMemDB() + store.sortedCache = nil } // CacheWrap implements CacheWrapper. @@ -146,6 +146,13 @@ func (store *Store) ReverseIterator(start, end []byte) types.Iterator { return store.iterator(start, end, false) } +func (store *Store) getOrInitSortedCache() *dbm.MemDB { + if store.sortedCache == nil { + store.sortedCache = dbm.NewMemDB() + } + return store.sortedCache +} + func (store *Store) iterator(start, end []byte, ascending bool) types.Iterator { store.mtx.Lock() defer store.mtx.Unlock() @@ -168,7 +175,7 @@ func (store *Store) iterator(start, end []byte, ascending bool) types.Iterator { } }() store.dirtyItems(start, end) - cache = newMemIterator(start, end, store.sortedCache, store.deleted, ascending) + cache = newMemIterator(start, end, store.getOrInitSortedCache(), store.deleted, ascending) return NewCacheMergeIterator(parent, cache, ascending, store.storeKey) } @@ -301,13 +308,13 @@ func (store *Store) clearUnsortedCacheSubset(unsorted []*kv.Pair, sortState sort if item.Value == nil { // deleted element, tracked by store.deleted // setting arbitrary value - if err := store.sortedCache.Set(item.Key, []byte{}); err != nil { + if err := store.getOrInitSortedCache().Set(item.Key, []byte{}); err != nil { panic(err) } continue } - if err := store.sortedCache.Set(item.Key, item.Value); err != nil { + if err := store.getOrInitSortedCache().Set(item.Key, item.Value); err != nil { panic(err) } }