Skip to content

Commit

Permalink
Merge pull request #31 from klayrHQ/fix-block-count
Browse files Browse the repository at this point in the history
Fix block count
  • Loading branch information
Theezr authored Aug 13, 2024
2 parents c7f57cb + 74b5a5d commit 12d74bc
Show file tree
Hide file tree
Showing 7 changed files with 26 additions and 44 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,7 @@ sunset arctic describe battle negative grace fame pottery spin warm wasp arctic
```bash
./bin/run transaction:create token transfer 20000000 --params='{"tokenID": "0400000000000000", "recipientAddress": "klys9u6yy466q2mpbj92cmbp64eg7gvpuz7v4efm8", "amount": "1000000", "data": ""}' --json --pretty
```

# Start postgresql dev server docker image:

docker run --rm --name pg -p 5432:5432 -e POSTGRES_PASSWORD=welcome postgres:15
7 changes: 4 additions & 3 deletions prisma/schema/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ generator client {
previewFeatures = ["prismaSchemaFolder"]
}


datasource db {
provider = "sqlite"
url = "file:./db/dev.db"
}
provider = "postgresql"
url = "postgres://postgres:welcome@localhost/postgres"
}
2 changes: 1 addition & 1 deletion src/block/block.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,6 @@ import { TransactionModule } from 'src/transaction/transaction.module';
],
providers: [PrismaService, BlockService, BlockRepoService],
controllers: [BlockController],
exports: [BlockService],
exports: [BlockService, BlockRepoService],
})
export class BlockModule {}
6 changes: 3 additions & 3 deletions src/indexer/indexer.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ export class IndexerService {
}

// modifying the blocks array here
this.newBlock({ event: Events.NEW_BLOCKS_EVENT, blocks: blocks.reverse() });
await this.newBlock({ event: Events.NEW_BLOCKS_EVENT, blocks: blocks.reverse() });

await this.updateNextBlockToSync(blocks.at(-1).header.height + 1);

Expand Down Expand Up @@ -110,8 +110,8 @@ export class IndexerService {
this.nextBlockToSync = (await this.indexerRepoService.updateNextBlockToSync({ height })).height;
}

private newBlock(blockEvent: BlockEvent): void {
this.eventService.pushToBlockEventQ(blockEvent);
private async newBlock(blockEvent: BlockEvent): Promise<void> {
await this.eventService.pushToBlockEventQ(blockEvent);
}

private async getBlocks(): Promise<Block[]> {
Expand Down
9 changes: 0 additions & 9 deletions src/prisma/prisma.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,5 @@ export class PrismaService extends PrismaClient implements OnModuleInit {
await this.nextBlockToSync.deleteMany({});
await this.validator.deleteMany({});
await this.account.deleteMany({});

// reset autoincrement
await this.$executeRaw`DELETE FROM sqlite_sequence WHERE name='ChainEvents'`;
await this.$executeRaw`DELETE FROM sqlite_sequence WHERE name='Transaction'`;
await this.$executeRaw`DELETE FROM sqlite_sequence WHERE name='Asset'`;
await this.$executeRaw`DELETE FROM sqlite_sequence WHERE name='Validator'`;
await this.$executeRaw`DELETE FROM sqlite_sequence WHERE name='Account'`;
await this.$executeRaw`DELETE FROM sqlite_sequence WHERE name='Block'`;
await this.$executeRaw`DELETE FROM sqlite_sequence WHERE name='NextBlockToSync'`;
}
}
3 changes: 2 additions & 1 deletion src/validator/validator.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@ import { AccountModule } from 'src/account/account.module';
import { NodeApiModule } from 'src/node-api/node-api.module';
import { StateModule } from 'src/state/state.module';
import { DbCacheModule } from 'src/db-cache/db-cache.module';
import { BlockModule } from 'src/block/block.module';

@Module({
imports: [StateModule, AccountModule, NodeApiModule, DbCacheModule],
imports: [StateModule, AccountModule, NodeApiModule, DbCacheModule, BlockModule],
providers: [ValidatorRepoService, ValidatorService, PrismaService],
exports: [ValidatorService, ValidatorRepoService],
controllers: [ValidatorController],
Expand Down
39 changes: 12 additions & 27 deletions src/validator/validator.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,15 @@ import {
ValidatorInfo,
ValidatorKeys,
} from 'src/node-api/types';
import { GeneratorInfo, ValidatorStakedData, ValidatorStatus } from './types';
import { ValidatorStakedData, ValidatorStatus } from './types';
import { OnEvent } from '@nestjs/event-emitter';
import { ChainEvents, GatewayEvents } from 'src/event/types';
import { NodeApi, NodeApiService } from 'src/node-api/node-api.service';
import { getAddressFromKlayr32Address } from 'src/utils/helpers';
import { ACTIVE_VALIDATORS, MINIMUM_VALIDATOR_WEIGHT } from 'src/utils/constants';
import { IndexerState, Modules } from 'src/state/types';
import { StateService } from 'src/state/state.service';
import { BlockRepoService } from 'src/block/block-repo.service';

@Injectable()
export class ValidatorService {
Expand All @@ -31,6 +32,7 @@ export class ValidatorService {
private readonly validatorRepoService: ValidatorRepoService,
private readonly accountService: AccountService,
private readonly nodeApiService: NodeApiService,
private readonly blockRepoService: BlockRepoService,
) {}

@OnEvent(GatewayEvents.PROCESS_POS_ASSET)
Expand Down Expand Up @@ -151,45 +153,28 @@ export class ValidatorService {

@OnEvent(GatewayEvents.UPDATE_BLOCK_GENERATOR)
public async updateBlockGenerator(blocks: Block[]) {
const generatorMap = new Map<string, GeneratorInfo>();
const validatorData = new Map<string, number>();

this.populateGeneratorMap(blocks, generatorMap);
await this.updateValidators(generatorMap);
}

private populateGeneratorMap(blocks: Block[], generatorMap: Map<string, GeneratorInfo>) {
blocks.forEach((block) => {
const validatorAddress = block.header.generatorAddress;
if (block.header.height === 0) return; // Skip genesis block

if (generatorMap.has(validatorAddress)) {
const entry = generatorMap.get(validatorAddress)!;
entry.count++;
entry.lastGeneratedHeight = block.header.height;
} else {
generatorMap.set(validatorAddress, {
count: 1,
lastGeneratedHeight: block.header.height,
});
}
validatorData.set(validatorAddress, block.header.height);
});

await this.updateValidators(validatorData);
}

private async updateValidators(generatorMap: Map<string, GeneratorInfo>) {
for (const [validatorAddress, { count, lastGeneratedHeight }] of generatorMap.entries()) {
const validator = await this.validatorRepoService.getValidator({
address: validatorAddress,
private async updateValidators(validatorAddresses: Map<string, number>) {
for (const [validatorAddress, lastGeneratedHeight] of validatorAddresses) {
const blockCount = await this.blockRepoService.countBlocks({
where: { generatorAddress: validatorAddress },
});
if (!validator) {
this.logger.error(`Validator ${validatorAddress} not found when updating generator`);
continue;
}

await this.validatorRepoService.updateValidator({
where: { address: validatorAddress },
data: {
lastGeneratedHeight,
generatedBlocks: validator.generatedBlocks + count,
generatedBlocks: blockCount,
},
});
}
Expand Down

0 comments on commit 12d74bc

Please sign in to comment.