Skip to content

Commit

Permalink
improve register block (#360)
Browse files Browse the repository at this point in the history
  • Loading branch information
ermalkaleci authored Aug 2, 2023
1 parent e8f409e commit 8803721
Showing 1 changed file with 15 additions and 5 deletions.
20 changes: 15 additions & 5 deletions packages/chopsticks/src/blockchain/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,17 +87,26 @@ export class Blockchain {
this.offchainWorker = new OffchainWorker()
}

if (maxMemoryBlockCount < 1) {
throw new Error('MaxMemoryBlockCount value must be equalOrGreater than 1.')
}

this.#maxMemoryBlockCount = maxMemoryBlockCount
}

#registerBlock(block: Block) {
// if exceed max memory block count, delete the oldest block
if (this.#blocksByNumber.size === this.#maxMemoryBlockCount) {
const firstKey = this.#blocksByNumber.keys().next().value
this.#blocksByNumber.delete(firstKey)
}
this.#blocksByNumber.set(block.number, block)
this.#blocksByHash[block.hash] = block

// if exceed max memory block count, delete the earliest block
if (this.#blocksByNumber.size > this.#maxMemoryBlockCount) {
const earliestBlockNumber = Math.min(...this.#blocksByNumber.keys())
const earliestBlock = this.#blocksByNumber.get(earliestBlockNumber)
this.#blocksByNumber.delete(earliestBlockNumber)
if (earliestBlock) {
delete this.#blocksByHash[earliestBlock.hash]
}
}
}

get head(): Block {
Expand Down Expand Up @@ -173,6 +182,7 @@ export class Blockchain {
'setHead',
)
this.#head = block
// TODO: unregister blocks from current head to new head
this.#registerBlock(block)
await this.headState.setHead(block)

Expand Down

0 comments on commit 8803721

Please sign in to comment.