Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add block metadata and size calculation #29

Merged
merged 3 commits into from
Nov 20, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions schema.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,74 @@ type SupplyDenom @entity {
id: ID!
}

type BlockIdParts @jsonField(indexed: false) {
total: Int!
hash: String!
}

type BlockId @jsonField(indexed: false) {
hash: String!
parts: BlockIdParts!
}

type BlockVersion @jsonField(indexed: false) {
version: BigInt!
app: Int!
}

type BlockHeader @jsonField {
chainId: String!
height: BigInt! @index
time: Date!
version: BlockVersion!
lastBlockId: BlockId!
lastCommitHash: String!
dataHash: String!
validatorsHash: String!
nextValidatorsHash: String!
consensusHash: String!
appHash: String!
lastResultsHash: String!
evidenceHash: String!
proposerAddress: String!
}

type BlockCommitSignature @jsonField(indexed: false) {
blockIdFlag: Int!
validatorAddress: String!
timestamp: Date!
signature: String!
}

type BlockLastCommit @jsonField(indexed: false) {
id: ID!
blockIdHash: String!
blockIdPartsTotal: Int!
blockIdPartsHash: String!
height: BigInt! @index
round: Int!
signatures: [BlockCommitSignature]!
}

# This handle all the information that is coming with the block but is not often used
# but could help in some debug environment.
type BlockMetadata @entity {
id: ID!
blockId: BlockId!
header: BlockHeader!
# first block has this null on js
lastCommit: BlockLastCommit
}

type Block @entity {
id: ID! # The block header hash
chainId: String! @index
height: BigInt! @index
timestamp: Date!
proposerAddress: String!
metadata: BlockMetadata!
size: Int!
# relations
transactions: [Transaction] @derivedFrom(field: "block")
messages: [Message] @derivedFrom(field: "block")
events: [Event] @derivedFrom(field: "block")
Expand Down
19 changes: 14 additions & 5 deletions src/mappings/authz/exec.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
import util from "util";
import {CosmosMessage} from "@subql/types-cosmos";
import { CosmosMessage } from "@subql/types-cosmos";
import allModuleTypes from "../../cosmjs/proto";
import { AuthzExec, AuthzMsgExec, Message } from "../../types";
import {
AuthzExec,
AuthzMsgExec,
Message,
} from "../../types";
import { _handleUpdateParam } from "../poktroll/params";
import { AuthzExecMsg } from "../types";
import { attemptHandling, messageId, stringify, unprocessedEventHandler } from "../utils";
import {
attemptHandling,
unprocessedEventHandler,
} from "../utils/handlers";
import { messageId } from "../utils/ids";
import { stringify } from "../utils/json";

// This is required for the binary reader to work. It expects TextEncoder and TextDecoder to be set in globalThis.
globalThis.TextEncoder = util.TextEncoder;
Expand Down Expand Up @@ -44,7 +53,7 @@ async function _handleAuthzExec(msg: CosmosMessage<AuthzExecMsg>): Promise<void>
//_handleUpdateParam will return the decoded message if it is a param update
// otherwise it will return undefined.
//_handleUpdateParam will decode and save the message using its specific entity
let decodedMsg: unknown = await _handleUpdateParam(encodedMsg, msg.block.block.id)
let decodedMsg: unknown = await _handleUpdateParam(encodedMsg, msg.block.block.id);

if (!decodedMsg) {
for (const [typeUrl, msgType] of allModuleTypes) {
Expand All @@ -53,7 +62,7 @@ async function _handleAuthzExec(msg: CosmosMessage<AuthzExecMsg>): Promise<void>
const bytes = new Uint8Array(Object.values(encodedMsg.value));

decodedMsg = msgType.decode(bytes);
break
break;
}
}
}
Expand Down
42 changes: 37 additions & 5 deletions src/mappings/bank/balanceChange.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,50 @@
import { CosmosEvent } from "@subql/types-cosmos";
import { parseCoins } from "../../cosmjs/utils";
import {
Account,
Balance,
NativeBalanceChange,
Transaction,
} from "../../types";
import {
attemptHandling,
checkBalancesAccount,
unprocessedEventHandler,
} from "../utils/handlers";
import {
getBalanceId,
getEventId,
messageId,
stringify,
unprocessedEventHandler,
updateAccountBalance,
} from "../utils";
} from "../utils/ids";
import { stringify } from "../utils/json";

export async function updateAccountBalance(address: string, denom: string, offset: bigint, blockId: string): Promise<void> {
let balance = await Balance.get(getBalanceId(address, denom));

if (!balance) {
balance = Balance.create({
id: getBalanceId(address, denom),
accountId: address,
denom,
amount: offset,
lastUpdatedBlockId: blockId,
});
} else {
balance.amount = balance.amount + offset;
balance.lastUpdatedBlockId = blockId;
}

await balance.save();

logger.debug(`[updateAccountBalance] (address): ${address}, (denom): ${denom}, (offset): ${offset}, (newBalance): ${balance?.amount}`);
}

export async function checkBalancesAccount(address: string, chainId: string): Promise<void> {
let accountEntity = await Account.get(address);
if (typeof (accountEntity) === "undefined") {
accountEntity = Account.create({ id: address, chainId });
await accountEntity.save();
}
}

export async function saveNativeBalanceEvent(id: string, address: string, amount: bigint, denom: string, event: CosmosEvent): Promise<void> {
await checkBalancesAccount(address, event.block.block.header.chainId);
Expand Down
4 changes: 2 additions & 2 deletions src/mappings/bank/supply.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
BlockSupply,
Supply,
} from "../../types";
import { stringify } from "../utils";
import { stringify } from "../utils/json";

export const getSupplyId = function(denom: string, height: number): string {
return `${denom}@${height}`;
Expand All @@ -26,7 +26,7 @@ export async function queryTotalSupply(): Promise<Coin[]> {
let paginationKey: Uint8Array | undefined;

try {
// Here we force the use of a private property, breaking typescript limitation, due to the need of call a total supply
// Here we force the use of a private property, breaking TypeScript limitation, due to the need of call a total supply
// rpc query of cosmosjs that is not exposed on the implemented client by SubQuery team.
// To avoid this, we need to move to implement our own rpc client and also use `unsafe` parameter which I prefer to avoid.
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
Expand Down
6 changes: 3 additions & 3 deletions src/mappings/bank/transfer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ import { NativeTransfer } from "../../types";
import { NativeTransferMsg } from "../types";
import {
attemptHandling,
messageId,
stringify,
unprocessedEventHandler,
} from "../utils";
} from "../utils/handlers";
import { messageId } from "../utils/ids";
import { stringify } from "../utils/json";

export async function handleNativeTransfer(event: CosmosEvent): Promise<void> {
await attemptHandling(event, _handleNativeTransfer, unprocessedEventHandler);
Expand Down
2 changes: 1 addition & 1 deletion src/mappings/constants.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ApplicationUnbondingReason as ApplicationUnbondingReasonEnum } from "../client/poktroll/application/event";

export const PREFIX = "poktroll";
export const PREFIX = "pokt";

export enum StakeStatus {
Staked = 0,
Expand Down
5 changes: 3 additions & 2 deletions src/mappings/genesis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,9 @@ import {
getMsgStakeServiceId,
getParamId,
getStakeServiceId,
stringify,
} from "./utils";
} from "./utils/ids";
import { stringify } from "./utils/json";


export async function handleGenesis(block: CosmosBlock): Promise<void> {
// we MUST load the JSON this way due to the sandboxed environment
Expand Down
Loading