Skip to content

Commit

Permalink
fix block range finding
Browse files Browse the repository at this point in the history
  • Loading branch information
kajoseph committed Nov 12, 2024
1 parent 8b6b300 commit d43c0ee
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 9 deletions.
6 changes: 4 additions & 2 deletions packages/bitcore-node/src/modules/moralis/api/csp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,10 @@ export class MoralisStateProvider extends BaseEVMStateProvider {
const date = new Date(time || Date.now());
const chainId = await this.getChainId({ network });
const blockNum = await this._getBlockNumberByDate({ chainId, date });
// moralis returns the block after the given date
const blockId = Math.max(blockNum - 1, 0).toString();
if (!blockNum) {
return null;
}
const blockId = blockNum.toString();
const blocks = await this._getBlocks({ chain, network, blockId, args: { limit: 1 } });
return blocks.blocks[0] || null;
}
Expand Down
16 changes: 9 additions & 7 deletions packages/bitcore-node/src/providers/chain-state/evm/api/csp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -790,6 +790,9 @@ export class BaseEVMStateProvider extends InternalStateProvider implements IChai
throw new Error('Missing required chain and/or network param');
}

// limit - 1 because startBlock is inclusive; ensure limit is >= 0
limit = Math.max(limit - 1, 0);

let height: number | null = null;
if (blockId && blockId.length < 64) {
height = parseInt(blockId, 10);
Expand Down Expand Up @@ -848,17 +851,16 @@ export class BaseEVMStateProvider extends InternalStateProvider implements IChai
query.startBlock = query.startBlock ?? query.endBlock - limit;
}

if (limit > 0 && (query.endBlock - query.startBlock) > limit) {
if (query.endBlock - query.startBlock > limit) {
query.endBlock = query.startBlock + limit;
}

if (sort?.height === -1) {
let b = query.startBlock;
query.startBlock = query.endBlock;
query.endBlock = b - 1; // subtract 1 to fix the range() below which adds 1 to the endBlock
}
const r = range(query.startBlock, query.endBlock + 1); // +1 since range is [start, end)

return range(query.startBlock, query.endBlock + 1);
if (sort?.height === -1 && query.startBlock < query.endBlock) {
return r.reverse();
}
return r;
}

async _getBlockNumberByDate(params) {
Expand Down

0 comments on commit d43c0ee

Please sign in to comment.