diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.yml index 56ffbf090..d2d429624 100644 --- a/.github/workflows/pipeline.yml +++ b/.github/workflows/pipeline.yml @@ -3,9 +3,9 @@ name: Build, lint and typecheck examples on: # Triggers the workflow on push or pull request events but only for the main branch push: - branches: [main, release**] + branches: [main, release**, feature**] pull_request: - branches: [main, release**] + branches: [main, release**, feature**] # Don't run on draft PR's, see: https://github.com/orgs/community/discussions/25722#discussioncomment-3248917 types: [opened, synchronize, reopened, ready_for_review] # Allows us to run the workflow manually from the Actions tab diff --git a/packages/common/CHANGELOG.md b/packages/common/CHANGELOG.md index abdfa2234..5f1f8b753 100644 --- a/packages/common/CHANGELOG.md +++ b/packages/common/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## 9.5.0 + +### Added + +New consensus endpoints: + +- `getBakerEarliestWinTime` +- `getBlockCertificates` +- `getBakersRewardPeriod` +- `getWinningBakersEpoch` +- `getFirstBlockEpoch` +- `commissionRates` is now added to the `getPoolInfo` under `bakerPoolStatus.PoolInfo` + ## 9.4.0 ### Added @@ -10,12 +23,12 @@ - Smart contract related types `ContractName`, `EntrypointName` and helper functions `isInitName`, `isReceiveName`, `getContractNameFromInit` and `getNamesFromReceive`. ### Fixed + - Added missing fields to `getBlockChainParameters` response. (rootKeys, level1Keys, level2Keys) - Use of bigint exponentiation causing issues in web. ## 9.3.0 - ### Added - `sendRawAccountTransaction` to the gRPC Client. @@ -35,26 +48,28 @@ ### Added -- `CIS4Contract` class for seemlessly interacting with contracts adhering to the CIS4 standard. -- Validation of type values when verifying statements. -- Exposed `replaceDateWithTimeStampAttribute` and `reviveDateFromTimeStampAttribute`. +- `CIS4Contract` class for seemlessly interacting with contracts adhering to the CIS4 standard. +- Validation of type values when verifying statements. +- Exposed `replaceDateWithTimeStampAttribute` and `reviveDateFromTimeStampAttribute`. ### Fixed -- Aligned credential schema types with the tested types in the browser wallet. -- `addMinimumAge` now creates the precise age statement instead of one day off. +- Aligned credential schema types with the tested types in the browser wallet. +- `addMinimumAge` now creates the precise age statement instead of one day off. ## 9.1.1 ### Fixes - - `verifyWeb3IdCredentialSignature` now supports dates/timestamp attributes. - - `canProveAtomicStatement` now supports timestamp attributes, handles undefined attribute value correctly and handles strings correctly for range statements. + +- `verifyWeb3IdCredentialSignature` now supports dates/timestamp attributes. +- `canProveAtomicStatement` now supports timestamp attributes, handles undefined attribute value correctly and handles strings correctly for range statements. ## 9.1.0 ### Added Added a functions that handle conversions between CCD and micro CCD. The CCD amounts are handled as `Big`'s: + - `toMicroCcd` returns the amount of micro CCD as a `Big`. - `toCcd`: returns the amount of CCD as a `Big`. - `fromCcd`: constructs a `CcdAmount` from an amount of CCD passed as a `Big` @@ -77,337 +92,337 @@ All function parameters now also accepts strings, these strings can use comma as ### Breaking changes -- Renamed `AccountTransactionType.TransferWithScheduleWithMemo` to `AccountTransactionType.TransferWithScheduleAndMemo`. +- Renamed `AccountTransactionType.TransferWithScheduleWithMemo` to `AccountTransactionType.TransferWithScheduleAndMemo`. ### Changed -- Bumped @concordium/rust-bindings to 1.1.0 (adds `display_type_schema_template` function) +- Bumped @concordium/rust-bindings to 1.1.0 (adds `display_type_schema_template` function) ### Added -- `getTransactionKindString` function. -- `displayTypeSchemaTemplate` function. +- `getTransactionKindString` function. +- `displayTypeSchemaTemplate` function. ## 8.0.0 ### Breaking changes -- Bumped @concordium/rust-bindings to 1.0.0. (Throws proper `Error`s when execution fails for any WASM entrypoint, with improved error messages) -- Updated `types.ts` to conform to updated GRPC API, which includes adding more variants to existing types (all new variants take effect from protocol version 6): - - `ChainParametersV2` added to `ChainParameters` - - `BlockInfo` changed to `BlockInfoV0 | BlockInfoV1` - - `ConsensusStatus` changed to `ConsensusStatusV0 | ConsensusStatusV1` - - `ElectionInfo` changed to `ElectionInfoV0 | ElectionInfoV1` +- Bumped @concordium/rust-bindings to 1.0.0. (Throws proper `Error`s when execution fails for any WASM entrypoint, with improved error messages) +- Updated `types.ts` to conform to updated GRPC API, which includes adding more variants to existing types (all new variants take effect from protocol version 6): + - `ChainParametersV2` added to `ChainParameters` + - `BlockInfo` changed to `BlockInfoV0 | BlockInfoV1` + - `ConsensusStatus` changed to `ConsensusStatusV0 | ConsensusStatusV1` + - `ElectionInfo` changed to `ElectionInfoV0 | ElectionInfoV1` ### Fixed -- Cost calculation for `deployModule` transaction. -- Fixed a bug where protocol version was different (i.e. 1 less than what it should be) when using the gRPCv2 API (compared to what is returned by the gRPCv1 API). +- Cost calculation for `deployModule` transaction. +- Fixed a bug where protocol version was different (i.e. 1 less than what it should be) when using the gRPCv2 API (compared to what is returned by the gRPCv1 API). ### Changes -- Function `uleb128Decode` now parses correctly and throws an error if the given input contains more than a single ULEB128 encoded number. +- Function `uleb128Decode` now parses correctly and throws an error if the given input contains more than a single ULEB128 encoded number. ### Added -- A `parseWallet` function to parse wallet export files -- Helper functions to determine version of versioned types mentioned in "Breaking Changes" have been added. -- Support for new chain update types. -- Function `uleb128DecodeWithIndex` that can also parse more than a single ULEB128 bigint -- Added `tokenAddressFromBase58` and `tokenAddressToBase58` to CIS2 +- A `parseWallet` function to parse wallet export files +- Helper functions to determine version of versioned types mentioned in "Breaking Changes" have been added. +- Support for new chain update types. +- Function `uleb128DecodeWithIndex` that can also parse more than a single ULEB128 bigint +- Added `tokenAddressFromBase58` and `tokenAddressToBase58` to CIS2 ### Changed -- The following functions now all have an additional parameter controlling whether errors are in a verbose format or not: - - `deserializeContractState` - - `deserializeReceiveReturnValue` - - `deserializeReceiveError` - - `deserializeInitError` - - `deserializeTypeValue` - - `serializeInitContractParameters` - - `serializeUpdateContractParameters` - - `serializeTypeValue` +- The following functions now all have an additional parameter controlling whether errors are in a verbose format or not: + - `deserializeContractState` + - `deserializeReceiveReturnValue` + - `deserializeReceiveError` + - `deserializeInitError` + - `deserializeTypeValue` + - `serializeInitContractParameters` + - `serializeUpdateContractParameters` + - `serializeTypeValue` ## 7.0.1 2023-05-25 ### Fixed -- Cost calculation for `deployModule` transaction. +- Cost calculation for `deployModule` transaction. ## 7.0.0 2023-05-15 ### Breaking changes -- Updated `blockInfo` so that the `bakerId` field is optional, since it will be undefined for genesis blocks. -- `waitForTransactionFinalization` now returns a `BlockItemSummaryInBlock` -- Added missing version return type in `getModuleSchema`. It now returns an object containing the schema source and version. +- Updated `blockInfo` so that the `bakerId` field is optional, since it will be undefined for genesis blocks. +- `waitForTransactionFinalization` now returns a `BlockItemSummaryInBlock` +- Added missing version return type in `getModuleSchema`. It now returns an object containing the schema source and version. ### Added -- Helpers for calculating energy cost for a transaction and microCCD cost from energy cost: - - `getEnergyCost` - - `getExchangeRate` - - `convertEnergyToMicroCcd` -- Utility functions for extracting information from `BlockItemSummary`: - - `isInitContractSummary` - - `isUpdateContractSummary` - - `isTransferLikeSummary` - - `isRejectTransaction` - - `isSuccessTransaction` - - `getTransactionRejectReason` - - `getReceiverAccount` - - `affectedContracts` - - `affectedAccounts` -- Utility functions for extracting information from `BlockSpecialEvent`: - - `specialEventAffectedAccounts` -- Helper methods on `GRPCClient` for chain traversal: - - `getFinalizedBlocksFrom` - - `findEarliestFinalized` - - `findInstanceCreation` - - `findFirstFinalizedBlockNoLaterThan` -- Extended HdWallet with support for verifiable credential key deriviation. +- Helpers for calculating energy cost for a transaction and microCCD cost from energy cost: + - `getEnergyCost` + - `getExchangeRate` + - `convertEnergyToMicroCcd` +- Utility functions for extracting information from `BlockItemSummary`: + - `isInitContractSummary` + - `isUpdateContractSummary` + - `isTransferLikeSummary` + - `isRejectTransaction` + - `isSuccessTransaction` + - `getTransactionRejectReason` + - `getReceiverAccount` + - `affectedContracts` + - `affectedAccounts` +- Utility functions for extracting information from `BlockSpecialEvent`: + - `specialEventAffectedAccounts` +- Helper methods on `GRPCClient` for chain traversal: + - `getFinalizedBlocksFrom` + - `findEarliestFinalized` + - `findInstanceCreation` + - `findFirstFinalizedBlockNoLaterThan` +- Extended HdWallet with support for verifiable credential key deriviation. ### Changed -- Bumped @concordium/rust-bindings to 0.12.0. (Adds key derivation for verifiable credentials) +- Bumped @concordium/rust-bindings to 0.12.0. (Adds key derivation for verifiable credentials) ## 6.5.0 2023-5-03 ### Added -- Utility functions `uleb128Decode` and `uleb128Encode` functions for decoding and encoding as unsigned leb128 respectively. -- `CIS2Contract` class for interacting with smart contracts adhering to the CIS-2 standard. -- `cis0Supports` function for checking standard support in smart contracts. -- Made the `streamToList` function public. -- Made the `unwrap` function public. -- Added `wasmToSchema` utility function. -- Added `getEmbeddedSchema` to client. -- Exposed `RpcError` type and created helper `isRpcError`. -- Build function `buildAccountSigner` for creating `AccountSigner` objects from genesis format, wallet export format, and a simple representation of credentials with keys. +- Utility functions `uleb128Decode` and `uleb128Encode` functions for decoding and encoding as unsigned leb128 respectively. +- `CIS2Contract` class for interacting with smart contracts adhering to the CIS-2 standard. +- `cis0Supports` function for checking standard support in smart contracts. +- Made the `streamToList` function public. +- Made the `unwrap` function public. +- Added `wasmToSchema` utility function. +- Added `getEmbeddedSchema` to client. +- Exposed `RpcError` type and created helper `isRpcError`. +- Build function `buildAccountSigner` for creating `AccountSigner` objects from genesis format, wallet export format, and a simple representation of credentials with keys. ### Changed -- Fixed bug where `AccountCreationSummary` type did not have fields: `index`, `energyCost`, `hash` +- Fixed bug where `AccountCreationSummary` type did not have fields: `index`, `energyCost`, `hash` ## 6.4.2 2023-04-21 ### Changed -- `generateBakerKeys` now also returns the private baker keys. +- `generateBakerKeys` now also returns the private baker keys. ## 6.4.1 2023-03-31 ### Changed -- Replace use of `setImmediate` with `setTimeout` since the former is not +- Replace use of `setImmediate` with `setTimeout` since the former is not supported in browsers. ## 6.4.0 2023-03-22 ### Added -- General function for deserializing smart contract values `deserializeTypeValue`. +- General function for deserializing smart contract values `deserializeTypeValue`. ### Changed -- Bumped @concordium/rust-bindings to 0.11.0. (Includes a fix to serialization of negative numbers for smart contract values) -- `signMessage` and `verifyMessageSignature` can now handle the message being a buffer/Uint8Array instead of only a utf8 string. +- Bumped @concordium/rust-bindings to 0.11.0. (Includes a fix to serialization of negative numbers for smart contract values) +- `signMessage` and `verifyMessageSignature` can now handle the message being a buffer/Uint8Array instead of only a utf8 string. ### Fixed -- `serializeTypeValue` now reports an error when called with invalid data, such as a receive function with missing schema, or a schema that cannot be parsed. +- `serializeTypeValue` now reports an error when called with invalid data, such as a receive function with missing schema, or a schema that cannot be parsed. ## 6.3.0 2023-02-27 ### Added -- Added a client for version 2 of the Concordium gRPC API to communicate with a Concordium node. +- Added a client for version 2 of the Concordium gRPC API to communicate with a Concordium node. - - including helper function `waitForTransactionFinalization` that returns a promise that resolves when the transaction finalizes. + - including helper function `waitForTransactionFinalization` that returns a promise that resolves when the transaction finalizes. -- Serialization: +- Serialization: - - `serializeAccountTransactionPayload` - - `serializeCredentialDeploymentPayload` + - `serializeAccountTransactionPayload` + - `serializeCredentialDeploymentPayload` -- Credential deployment helpers: +- Credential deployment helpers: - - `createCredentialTransaction` - - `createCredentialTransactionNoSeed` - - `signCredentialTransaction` + - `createCredentialTransaction` + - `createCredentialTransactionNoSeed` + - `signCredentialTransaction` -- Function to generate baker keys: `generateBakerKeys`. +- Function to generate baker keys: `generateBakerKeys`. ### Fixed -- `getInitContractParameterSchema`, `getUpdateContractParameterSchema`, +- `getInitContractParameterSchema`, `getUpdateContractParameterSchema`, `serializeInitContractParameters` and `serializeUpdateContractParameters` now report an error when called with invalid data, such as a receive function with missing schema, or a schema that cannot be parsed. ### Deprecated -- The JSON-RPC client has been deprecated in favor of the new gRPC v2 client. -- Various types and helper functions used by the JSON-RPC client (and the v1 gRPC client) have also been deprecated. +- The JSON-RPC client has been deprecated in favor of the new gRPC v2 client. +- Various types and helper functions used by the JSON-RPC client (and the v1 gRPC client) have also been deprecated. ## 6.2.0 2023-01-04 ### Added -- `serializeTypeValue` that allows smart contract types to be serialized using the specific schema, instead of only by providing the entire module's schema. -- `getInitContractParameterSchema` Given a buffer containing the schema for a module, extract the schema for a given contract's init function's parameters. -- `getReceiveContractParameterSchema` Given a buffer containing the schema for a module, extract the schema for a given contract's receive methods' parameters. +- `serializeTypeValue` that allows smart contract types to be serialized using the specific schema, instead of only by providing the entire module's schema. +- `getInitContractParameterSchema` Given a buffer containing the schema for a module, extract the schema for a given contract's init function's parameters. +- `getReceiveContractParameterSchema` Given a buffer containing the schema for a module, extract the schema for a given contract's receive methods' parameters. ## 6.1.0 2022-11-30 ### Added -- `IdStatementBuilder` class to help build id statements. -- `verifyIdStatement` function to verify that a statement is well-formed and complies with rules for id statements. -- `getIdProof` function to prove a statement holds for the given identity/account. -- Enums for sex and idDocType values. +- `IdStatementBuilder` class to help build id statements. +- `verifyIdStatement` function to verify that a statement is well-formed and complies with rules for id statements. +- `getIdProof` function to prove a statement holds for the given identity/account. +- Enums for sex and idDocType values. ## 6.0.0 2022-11-15 ### Breaking changes -- Change AccountTransactionType names/string values to align with those in Concordium base. -- Change some field names in UpdateConcractPayload, InitContractPayload and DeployModule to align with those in Concordium base. -- Rename GtuAmount class to CcdAmount. And change the microGtuAmount field to microCcdAmount. -- Add custom toJSON methods for the classes CcdAmount, AccountAddress, ModuleReference, CredentialRegistrationId, DataBlob and TransactionExpiry, in order to match the serialisation of their equivalents in Concordium base. +- Change AccountTransactionType names/string values to align with those in Concordium base. +- Change some field names in UpdateConcractPayload, InitContractPayload and DeployModule to align with those in Concordium base. +- Rename GtuAmount class to CcdAmount. And change the microGtuAmount field to microCcdAmount. +- Add custom toJSON methods for the classes CcdAmount, AccountAddress, ModuleReference, CredentialRegistrationId, DataBlob and TransactionExpiry, in order to match the serialisation of their equivalents in Concordium base. ### Added -- The ability to deserialize error values of receive and init functions using `deserializeReceiveError()` and `deserializeInitError()` respectfully. -- Refactored the `upserializeUpdateContractParameters()` and `serializeInitContractParameters()` to call into rust functions. +- The ability to deserialize error values of receive and init functions using `deserializeReceiveError()` and `deserializeInitError()` respectfully. +- Refactored the `upserializeUpdateContractParameters()` and `serializeInitContractParameters()` to call into rust functions. ## 5.2.0 2022-11-8 ### Added -- The ability to deserialize the return values of receive functions using `deserializeReceiveReturnValue()`. +- The ability to deserialize the return values of receive functions using `deserializeReceiveReturnValue()`. ## 5.1.0 2022-9-29 ### Added -- Additional arguments to the JSON-RPC HttpProvider, to enable is to receive and forward cookies. +- Additional arguments to the JSON-RPC HttpProvider, to enable is to receive and forward cookies. ### Fixed -- getAccountInfo no longer relies on instanceof to determine the type of input. +- getAccountInfo no longer relies on instanceof to determine the type of input. ## 5.0.0 2022-9-29 ### Added -- `getCredentialId` to the HdWallet. +- `getCredentialId` to the HdWallet. ### Breaking changes -- Updated the signature of helper functions for accounts to sign messages. (and changed the prepend) +- Updated the signature of helper functions for accounts to sign messages. (and changed the prepend) ## 4.0.0 2022-8-26 ### Breaking changes -- ConcordiumHdWallet methods now take the identity provider index as arguments. -- Bumped @concordium/rust-bindings to 0.4.0. +- ConcordiumHdWallet methods now take the identity provider index as arguments. +- Bumped @concordium/rust-bindings to 0.4.0. ### Fixed -- Added missing `accountAddress` field to `AccountInfo` types. +- Added missing `accountAddress` field to `AccountInfo` types. ## 3.0.0 2022-8-26 ### Added -- Support for new V2 schemas which can specify error types. +- Support for new V2 schemas which can specify error types. ### Breaking changes -- SchemaVersion, Module, and schema types are now 0-indexed instead of 1-indexed. This means that the schemas used for V0 contracts are now version 0, and so is the associated types. And the first schema version for V1 contracts are now version 1. +- SchemaVersion, Module, and schema types are now 0-indexed instead of 1-indexed. This means that the schemas used for V0 contracts are now version 0, and so is the associated types. And the first schema version for V1 contracts are now version 1. ## 2.4.0 2022-8-15 ### Added -- `createIdentityRequest`, to create identity requests. -- `createCredentialV1`, to create credentials using a seedPhrase. -- `createIdentityRecoveryRequest`, to create identity recovery requests. -- Added `sendCredentialDeployment` to send credentials created from `createCredentialV1` to the chain. -- `getSignedCredentialDeploymentTransactionHash` to get the transaction hash of credentials created from `createCredentialV1`. -- Added `ConfigureBaker` to `AccountTransactionType` enum. -- Added `ConcordiumHdWallet` with functions to get keys and randomness from a seed phrase. +- `createIdentityRequest`, to create identity requests. +- `createCredentialV1`, to create credentials using a seedPhrase. +- `createIdentityRecoveryRequest`, to create identity recovery requests. +- Added `sendCredentialDeployment` to send credentials created from `createCredentialV1` to the chain. +- `getSignedCredentialDeploymentTransactionHash` to get the transaction hash of credentials created from `createCredentialV1`. +- Added `ConfigureBaker` to `AccountTransactionType` enum. +- Added `ConcordiumHdWallet` with functions to get keys and randomness from a seed phrase. ## 2.3.2 2022-7-26 ### Fixed -- `deserializeTransaction` no longer throws an error on expired transactions. +- `deserializeTransaction` no longer throws an error on expired transactions. ## 2.3.1 2022-7-26 ### Fixed -- `deserializeTransaction` is now exported from index. +- `deserializeTransaction` is now exported from index. ## 2.3.0 2022-7-25 ### Added -- `deserializeTransaction` function to deserialize transaction created by `serializeAccountTransactionForSubmission` and `serializeCredentialDeploymentTransactionForSubmission`. (Currently SimpleTransfer, SimpleTransferWithMemo and RegisterData are the only supported account transactions kinds) +- `deserializeTransaction` function to deserialize transaction created by `serializeAccountTransactionForSubmission` and `serializeCredentialDeploymentTransactionForSubmission`. (Currently SimpleTransfer, SimpleTransferWithMemo and RegisterData are the only supported account transactions kinds) ## 2.2.0 2022-7-21 ### Added -- Add support for getAccountInfo, InvokeContract, getCryptographicParameters and getModuleSource with JSON-RPC +- Add support for getAccountInfo, InvokeContract, getCryptographicParameters and getModuleSource with JSON-RPC ## 2.1.1 2022-7-8 ### Fixed -- Fixed contract schema serialization for ByteList +- Fixed contract schema serialization for ByteList ## 2.1.0 2022-7-5 ### Added -- Support deserializing new schema types: ULeb128, ILeb128, ByteArray and ByteList. -- Support deserializing schemas with versioning information. +- Support deserializing new schema types: ULeb128, ILeb128, ByteArray and ByteList. +- Support deserializing schemas with versioning information. ### Changes -- The function for deserializing a module schema `deserialModuleFromBuffer` now have the schema version as an optional argument. The function will try to extract the version from the buffer. When a version is provided it falls back to this, otherwise it throws an error. +- The function for deserializing a module schema `deserialModuleFromBuffer` now have the schema version as an optional argument. The function will try to extract the version from the buffer. When a version is provided it falls back to this, otherwise it throws an error. ## 2.0.1 2022-6-27 ### Fixed -- @noble/ed25519 and cross-fetch moved from devDependencies to dependencies. +- @noble/ed25519 and cross-fetch moved from devDependencies to dependencies. ## 2.0.0 2022-6-24 ### Added -- Support deserializing version 2 schemas. -- Support serializing parameters for contracts using version 2 schemas. -- Support for deploying versioned smart contract modules, which is the format used in cargo-concordium v2+. (This is done by not supplying the version field in the payload) +- Support deserializing version 2 schemas. +- Support serializing parameters for contracts using version 2 schemas. +- Support for deploying versioned smart contract modules, which is the format used in cargo-concordium v2+. (This is done by not supplying the version field in the payload) ### Breaking changes -- `serializeInitContractParameters` and `serializeUpdateContractParameters` each have an additional parameter, which denotes the version of the schema provided. For existing users that are using V0 contracts, that parameter should be `SchemaVersion.V1`. -- Deserialization of schemas have been changed: types and functions have been renamed and `deserialModuleFromBuffer` have an additional parameter. +- `serializeInitContractParameters` and `serializeUpdateContractParameters` each have an additional parameter, which denotes the version of the schema provided. For existing users that are using V0 contracts, that parameter should be `SchemaVersion.V1`. +- Deserialization of schemas have been changed: types and functions have been renamed and `deserialModuleFromBuffer` have an additional parameter. ## 1.0.1 2022-6-2 ### Fixed -- Fixed JSON-RPC client crash on empty response when calling getInstanceInfo. +- Fixed JSON-RPC client crash on empty response when calling getInstanceInfo. (And update the format of the arguments for the server) -- Fixed issue by bumping rust bindings version +- Fixed issue by bumping rust bindings version ## 1.0.0 2022-5-25 -- Initial release +- Initial release diff --git a/packages/common/package.json b/packages/common/package.json index dcc1523d5..9a2a0dcfb 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -1,6 +1,6 @@ { "name": "@concordium/common-sdk", - "version": "9.4.0", + "version": "9.5.0", "license": "Apache-2.0", "engines": { "node": ">=14.16.0" diff --git a/packages/common/src/GRPCClient.ts b/packages/common/src/GRPCClient.ts index d953b8b11..d8631d373 100644 --- a/packages/common/src/GRPCClient.ts +++ b/packages/common/src/GRPCClient.ts @@ -308,7 +308,7 @@ export class ConcordiumGRPCClient { * * @param transaction the transaction to send to the node * @param signature the signatures on the signing digest of the transaction - * @returns The transaction hash as a byte array + * @returns The transaction hash as a hex-encoded string */ async sendAccountTransaction( transaction: v1.AccountTransaction, @@ -1503,6 +1503,126 @@ export class ConcordiumGRPCClient { ); } + /** + * Get the projected earliest time at which a particular baker will be required to bake a block. + * + * If the baker is not a baker for the current reward period, this returns a timestamp at the + * start of the next reward period. If the baker is a baker for the current reward period, the + * earliest win time is projected from the current round forward, assuming that each round after + * the last finalized round will take the minimum block time. (If blocks take longer, or timeouts + * occur, the actual time may be later, and the reported time in subsequent queries may reflect + * this.) At the end of an epoch (or if the baker is not projected to bake before the end of the + * epoch) the earliest win time for a (current) baker will be projected as the start of the next + * epoch. This is because the seed for the leader election is updated at the epoch boundary, and + * so the winners cannot be predicted beyond that. Note that in some circumstances the returned + * timestamp can be in the past, especially at the end of an epoch. + * + * @throws an `UNAVAILABLE` RPC error if the current consensus version is 0 (prior to protocol version 6), as the endpoint is only supported from consensus version 1 (from protocol version 6). + * + * @param {v1.BakerId} baker - The baker that should be queried for. + * + * @returns {v1.Timestamp} The projected earliest time at which a particular baker will be required to bake a block, as a unix timestamp in milliseconds. + */ + async getBakerEarliestWinTime(baker: v1.BakerId): Promise { + const bakerId = { + value: baker, + }; + const winTime = await this.client.getBakerEarliestWinTime(bakerId) + .response; + return winTime.value; + } + + /** + * For a non-genesis block, this returns the quorum certificate, a timeout + * certificate (if present) and epoch finalization entry (if present). + * + * @throws an `UNIMPLEMENTED` RPC error if the endpoint is not enabled by the node. + * @throws an `INVALID_ARGUMENT` if the block being pointed to is not a product of ConcordiumBFT + * + * @param blockHash optional block hash to get the cryptographic parameters at, otherwise retrieves from last finalized block. + * + * @returns the requested block certificates. + */ + async getBlockCertificates( + blockHash?: HexString + ): Promise { + const blockHashInput = getBlockHashInput(blockHash); + const blockCertificates = await this.client.getBlockCertificates( + blockHashInput + ).response; + return translate.blockCertificates(blockCertificates); + } + + /** + * Get all bakers in the reward period of a block. + * This endpoint is only supported for protocol version 6 and onwards. + * + * @throws an `IllegalArgument` RPC error if the protocol does not support the endpoint. + * + * @param blockHash optional block hash to get the cryptographic parameters at, otherwise retrieves from last finalized block. + * + * @returns All bakers in the reward period of a block + */ + getBakersRewardPeriod( + blockHash?: HexString + ): AsyncIterable { + const blockHashInput = getBlockHashInput(blockHash); + const bakersRewardPeriod = + this.client.getBakersRewardPeriod(blockHashInput).responses; + return mapStream(bakersRewardPeriod, translate.bakerRewardPeriodInfo); + } + + /** + * Get the list of bakers that won the lottery in a particular historical epoch (i.e. the + * last finalized block is in a later epoch). This lists the winners for each round in the + * epoch, starting from the round after the last block in the previous epoch, running to + * the round before the first block in the next epoch. It also indicates if a block in each + * round was included in the finalized chain. + * + * The following error cases are possible: + * @throws a `NOT_FOUND` RPC error if the query specifies an unknown block. + * @throws an `UNAVAILABLE` RPC error if the query is for an epoch that is not finalized in the current genesis index, or is for a future genesis index. + * @throws an `INVALID_ARGUMENT` RPC error if the query is for an epoch that is not finalized for a past genesis index. + * @throws an `INVALID_ARGUMENT` RPC error if the query is for a genesis index at consensus version 0. + * @throws an `INVALID_ARGUMENT` RPC error if the input `EpochRequest` is malformed. + * @throws an `UNAVAILABLE` RPC error if the endpoint is disabled on the node. + * + * @param {HexString | v1.RelativeEpochRequest } epochRequest - Consists of either a hex-encoded block hash or a relative epoch request consisting of a genesis index and an epoch. If none is passed, it queries the last finalized block. + * + * @returns {v1.WinningBaker} A stream of winning bakers for a given epoch. + */ + getWinningBakersEpoch( + epochRequest?: HexString | v1.RelativeEpochRequest + ): AsyncIterable { + const req = getEpochRequest(epochRequest); + const winningBakers = this.client.getWinningBakersEpoch(req).responses; + + return mapStream(winningBakers, translate.winningBaker); + } + + /** + * Get the block hash of the first finalized block in a specified epoch. + * + * The following error cases are possible: + * @throws - a `NOT_FOUND` RPC error if the query specifies an unknown block. + * @throws - an `UNAVAILABLE` RPC error if the query is for an epoch that is not finalized in the current genesis index, or is for a future genesis index. + * @throws - an `INVALID_ARGUMENT` RPC error if the query is for an epoch with no finalized blocks for a past genesis index. + * @throws - an `INVALID_ARGUMENT` RPC error if the input `EpochRequest` is malformed. + * @throws - an `UNAVAILABLE` RPC error if the endpoint is disabled on the node. + * + * @param {HexString | v1.RelativeEpochRequest } epochRequest - Consists of either a hex-encoded block hash or a relative epoch request consisting of a genesis index and an epoch. If none is passed, it queries the last finalized block. + * + * @returns {HexString} The block hash as a hex encoded string. + */ + async getFirstBlockEpoch( + epochRequest?: HexString | v1.RelativeEpochRequest + ): Promise { + const req = getEpochRequest(epochRequest); + const blockHash = await this.client.getFirstBlockEpoch(req).response; + + return translate.unwrapValToHex(blockHash); + } + private async getConsensusHeight() { return (await this.getConsensusStatus()).lastFinalizedBlockHeight; } @@ -1602,6 +1722,32 @@ export function getInvokerInput( } } +function getEpochRequest( + epochRequest?: HexString | v1.RelativeEpochRequest +): v2.EpochRequest { + if ( + typeof epochRequest === 'string' || + typeof epochRequest === 'undefined' + ) { + return { + epochRequestInput: { + oneofKind: 'blockHash', + blockHash: getBlockHashInput(epochRequest), + }, + }; + } else { + return { + epochRequestInput: { + oneofKind: 'relativeEpoch', + relativeEpoch: { + genesisIndex: { value: epochRequest.genesisIndex }, + epoch: { value: epochRequest.epoch }, + }, + }, + }; + } +} + function assertValidIp(ip: v1.IpAddressString): void { if (!isValidIp(ip)) { throw new Error('The input was not a valid ip: ' + ip); diff --git a/packages/common/src/GRPCTypeTranslation.ts b/packages/common/src/GRPCTypeTranslation.ts index 008aeecd2..9fca9cabd 100644 --- a/packages/common/src/GRPCTypeTranslation.ts +++ b/packages/common/src/GRPCTypeTranslation.ts @@ -343,6 +343,7 @@ function transPaydayStatus( lotteryPower: status.lotteryPower, bakerEquityCapital: unwrap(status.bakerEquityCapital?.value), delegatedCapital: unwrap(status.delegatedCapital?.value), + commissionRates: trCommissionRates(status.commissionRates), }; } @@ -2737,6 +2738,95 @@ export function blockFinalizationSummary( } } +export function blockCertificates( + certs: v2.BlockCertificates +): v1.BlockCertificates { + return { + ...(certs.quorumCertificate !== undefined && { + quorumCertificate: quorumCertificate(certs.quorumCertificate), + }), + ...(certs.timeoutCertificate !== undefined && { + timeoutCertificate: timeoutCertificate(certs.timeoutCertificate), + }), + ...(certs.epochFinalizationEntry !== undefined && { + epochFinalizationEntry: epochFinalizationEntry( + certs.epochFinalizationEntry + ), + }), + }; +} + +export function quorumCertificate( + cert: v2.QuorumCertificate +): v1.QuorumCertificate { + return { + blockHash: unwrapValToHex(cert.blockHash), + round: unwrap(cert.round?.value), + epoch: unwrap(cert.epoch?.value), + aggregateSignature: unwrapValToHex(cert.aggregateSignature), + signatories: cert.signatories.map((x) => unwrap(x.value)), + }; +} + +export function timeoutCertificate( + cert: v2.TimeoutCertificate +): v1.TimeoutCertificate { + return { + round: unwrap(cert.round?.value), + minEpoch: unwrap(cert.minEpoch?.value), + qcRoundsFirstEpoch: cert.qcRoundsFirstEpoch.map(finalizerRound), + qcRoundsSecondEpoch: cert.qcRoundsSecondEpoch.map(finalizerRound), + aggregateSignature: unwrapValToHex(cert.aggregateSignature), + }; +} + +export function epochFinalizationEntry( + cert: v2.EpochFinalizationEntry +): v1.EpochFinalizationEntry { + return { + finalizedQc: quorumCertificate(unwrap(cert.finalizedQc)), + successorQc: quorumCertificate(unwrap(cert.successorQc)), + successorProof: unwrapValToHex(cert.successorProof), + }; +} + +export function finalizerRound(round: v2.FinalizerRound): v1.FinalizerRound { + return { + round: unwrap(round.round?.value), + finalizers: round.finalizers.map((x) => x.value), + }; +} + +export function bakerRewardPeriodInfo( + bakerRewardPeriod: v2.BakerRewardPeriodInfo +): v1.BakerRewardPeriodInfo { + return { + baker: bakerInfo(unwrap(bakerRewardPeriod.baker)), + effectiveStake: unwrap(bakerRewardPeriod.effectiveStake?.value), + commissionRates: trCommissionRates(bakerRewardPeriod.commissionRates), + equityCapital: unwrap(bakerRewardPeriod.equityCapital?.value), + delegatedCapital: unwrap(bakerRewardPeriod.equityCapital?.value), + isFinalizer: bakerRewardPeriod.isFinalizer, + }; +} + +export function bakerInfo(bakerInfo: v2.BakerInfo): v1.BakerInfo { + return { + bakerId: unwrap(bakerInfo.bakerId?.value), + electionKey: unwrapValToHex(bakerInfo.electionKey), + signatureKey: unwrapValToHex(bakerInfo.signatureKey), + aggregationKey: unwrapValToHex(bakerInfo.aggregationKey), + }; +} + +export function winningBaker(winningBaker: v2.WinningBaker): v1.WinningBaker { + return { + round: unwrap(winningBaker.round?.value), + winner: unwrap(winningBaker.winner?.value), + present: winningBaker.present, + }; +} + // ---------------------------- // // --- V1 => V2 translation --- // // ---------------------------- // diff --git a/packages/common/src/types.ts b/packages/common/src/types.ts index 0afc74839..5baa8ffc2 100644 --- a/packages/common/src/types.ts +++ b/packages/common/src/types.ts @@ -34,7 +34,30 @@ export type UrlString = string; export type IpAddressString = string; export type JsonString = string; +/** A smart contract module reference. This is always 32 bytes long. */ export type ModuleRef = HexString; +/** The signature of a 'QuorumCertificate'. the bytes have a fixed length of 48 bytes. */ +export type QuorumSignature = HexString; +/** The signature of a 'TimeoutCertificate'. the bytes have a fixed length of 48 bytes. */ +export type TimeoutSignature = HexString; +/** + * A proof that establishes that the successor block of + * a 'EpochFinalizationEntry' is the immediate successor of + * the finalized block. + * + * The bytes have a fixed length of 32 bytes. + */ +export type SuccessorProof = HexString; +/** Baker's public key used to check whether they won the lottery or not. */ +export type BakerElectionVerifyKey = HexString; +/** Baker's public key used to check that they are indeed the ones who produced the block. */ +export type BakerSignatureVerifyKey = HexString; +/** + * Baker's public key used to check signatures on finalization records. + * This is only used if the baker has sufficient stake to participate in + * finalization. + */ +export type BakerAggregationVerifyKey = HexString; /** A number of milliseconds */ export type Duration = bigint; @@ -45,6 +68,14 @@ export type Round = bigint; /** An amount of energy */ export type Energy = bigint; +/** + * The number of chain restarts via a protocol update. An effected + * protocol update instruction might not change the protocol version + * specified in the previous field, but it always increments the genesis + * index. + */ +export type GenesisIndex = number; + /** * Makes keys of type optional * @@ -57,6 +88,7 @@ export type MakeOptional = Omit & /** Makes keys of type required (i.e. non-optional) */ export type MakeRequired = Required> & Omit; + /** * Returns a union of all keys of type T with values matching type V. */ @@ -790,7 +822,7 @@ export interface BlockInfoCommon { * The genesis index for the block. This counst the number of protocol updates that have * preceeded this block, and defines the era of the block. */ - genesisIndex: number; + genesisIndex: GenesisIndex; /** The height of this block relative to the (re)genesis block of its era */ eraBlockHeight: number; /** The protocol version the block belongs to */ @@ -824,7 +856,7 @@ export type FinalizedBlockInfo = CommonBlockInfo; export type AbsoluteBlocksAtHeightRequest = bigint; export interface RelativeBlocksAtHeightRequest { - genesisIndex: number; + genesisIndex: GenesisIndex; height: bigint; restrict: boolean; } @@ -905,7 +937,7 @@ export interface ConsensusStatusCommon { * specified in the previous field, but it always increments the genesis * index. */ - genesisIndex: number; + genesisIndex: GenesisIndex; /** Currently active protocol version. */ protocolVersion: bigint; @@ -1205,6 +1237,7 @@ export interface CurrentPaydayBakerPoolStatus { lotteryPower: number; bakerEquityCapital: Amount; delegatedCapital: Amount; + commissionRates: CommissionRates; } export enum BakerPoolPendingChangeType { @@ -2048,6 +2081,224 @@ export type SmartContractTypeValues = | string | boolean; +/** + * Certificates for a block for protocols supporting + * ConcordiumBFT. + */ +export interface BlockCertificates { + /** + * The quorum certificate. Is present if and only if the block is + * not a genesis block. + */ + quorumCertificate?: QuorumCertificate; + /** + * The timeout certificate. Is present only if the round prior to the + * round of the block timed out. + */ + timeoutCertificate?: TimeoutCertificate; + /** + * The epoch finalization entry. Is present only if the block initiates + * a new epoch. + */ + epochFinalizationEntry?: EpochFinalizationEntry; +} + +/** + * A quorum certificate is the certificate that the + * finalization comittee issues in order to certify a block. + * A block must be certified before it will be part of the + * authorative part of the chain. + */ +export interface QuorumCertificate { + /** + * The hash of the block that the quorum certificate refers to. + */ + blockHash: HexString; + /** + * The round of the block. + */ + round: Round; + /** + * The epoch of the block. + */ + epoch: Epoch; + /** + * The aggregated signature by the finalization committee on the block. + */ + aggregateSignature: QuorumSignature; + /** + * A list of the finalizers that formed the quorum certificate + * i.e., the ones who have contributed to the 'aggregateSignature'. + * The finalizers are identified by their baker id as this is stable + * across protocols and epochs. + */ + signatories: BakerId[]; +} + +/** + * A timeout certificate is the certificate that the + * finalization committee issues when a round times out, + * thus making it possible for the protocol to proceed to the + * next round. + */ +export interface TimeoutCertificate { + /** + * The round that timed out. + */ + round: Round; + /** + * The minimum epoch of which signatures are included + * in the 'aggregate_signature'. + */ + minEpoch: Epoch; + /** + * The rounds of which finalizers have their best + * quorum certificates in the 'minEpoch'. + */ + qcRoundsFirstEpoch: FinalizerRound[]; + /** + * The rounds of which finalizers have their best + * quorum certificates in the epoch 'minEpoch' + 1. + */ + qcRoundsSecondEpoch: FinalizerRound[]; + /** + * The aggregated signature by the finalization committee that witnessed + * the 'round' timed out. + */ + aggregateSignature: TimeoutSignature; +} + +/** + * The finalizer round is a map from a 'Round' + * to the list of finalizers (identified by their 'BakerId') that signed + * off the round. + */ +export interface FinalizerRound { + /** + * The round that was signed off. + */ + round: Round; + /** + * The finalizers (identified by their 'BakerId' that + * signed off the in 'round'. + */ + finalizers: BakerId[]; +} + +/** + * The epoch finalization entry is the proof that + * makes the protocol able to advance to a new epoch. + * I.e. the 'EpochFinalizationEntry' is present if and only if + * the block is the first block of a new 'Epoch'. + */ +export interface EpochFinalizationEntry { + /** + * The quorum certificate for the finalized block. + */ + finalizedQc: QuorumCertificate; + /** + * The quorum certificate for the block that finalizes + * the block that 'finalizedQc' points to. + */ + successorQc: QuorumCertificate; + /** + * A proof that the successor block is an immediate + * successor of the finalized block. + */ + successorProof: SuccessorProof; +} + +/** + * Information about a particular baker with respect to + * the current reward period. + */ +export interface BakerRewardPeriodInfo { + /** + * The baker id and public keys for the baker. + */ + baker: BakerInfo; + /** + * The effective stake of the baker for the consensus protocol. + * The returned amount accounts for delegation, capital bounds and leverage bounds. + */ + effectiveStake: Amount; + /** + * The effective commission rate for the baker that applies for the reward period. + */ + commissionRates: CommissionRates; + /** + * The amount staked by the baker itself. + */ + equityCapital: Amount; + /** + * The total amount of capital delegated to this baker pool. + */ + delegatedCapital: Amount; + /** + * Whether the baker is a finalizer or not. + */ + isFinalizer: boolean; +} + +/** + * Information about a baker. + */ +export interface BakerInfo { + /** + * Identity of the baker. This is actually the account index of + * the account controlling the baker. + */ + bakerId: BakerId; + /** + * Baker's public key used to check whether they won the lottery or not. + */ + electionKey: BakerElectionVerifyKey; + /** + * Baker's public key used to check that they are indeed the ones who + * produced the block. + */ + signatureKey: BakerSignatureVerifyKey; + /** + * Baker's public key used to check signatures on finalization records. + * This is only used if the baker has sufficient stake to participate in + * finalization. + */ + aggregationKey: BakerAggregationVerifyKey; +} + +/** + * Request an epoch by number at a given genesis index. + */ +export interface RelativeEpochRequest { + /** + * The genesis index to query at. The query is restricted to this genesis index, and + * will not return results for other indices even if the epoch number is out of bounds. + */ + genesisIndex: GenesisIndex; + /** + * The epoch number to query at. + */ + epoch: Epoch; +} + +/** + * Details of which baker won the lottery in a given round in consensus version 1. + */ +export interface WinningBaker { + /** + * The round number. + */ + round: Round; + /** + * The baker that won the round. + */ + winner: BakerId; + /** + * True if the baker produced a block in this round on the finalized chain, and False otherwise. + */ + present: boolean; +} + export type HealthCheckResponse = | { isHealthy: true; diff --git a/packages/nodejs/CHANGELOG.md b/packages/nodejs/CHANGELOG.md index 754e61ba6..894b8fcdd 100644 --- a/packages/nodejs/CHANGELOG.md +++ b/packages/nodejs/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## 9.5.0 + +- Bumped @concordium/common-sdk to 9.5.0. + ## 9.4.0 - Bumped @concordium/common-sdk to 9.4.0. @@ -91,6 +95,7 @@ - Bumped @concordium/common-sdk to 6.0.0. (Which changes transaction type names and field names to be aligned with other implementations) ## 5.0.0 2022-11-8 + Breaking Changes - Bumped @concordium/common-sdk to 5.2.0. (Which changes the function signature of ConcordiumHdWallet and sign helpers functions) @@ -189,8 +194,8 @@ Breaking Changes - Support for getting baker list from node. - Support for getting status of a Baker Pool/Passive delegation (required node to have protocol version 4 or later). - Support for getting reward status of chain at specific block. -- Helper functions for determining the version of `BlockSummary` and nested types. -- Helper functions for determining the version of `AccountInfo` variants. +- Helper functions for determining the version of `BlockSummary` and nested types. +- Helper functions for determining the version of `AccountInfo` variants. - Support for the new "configure delegation" transaction type. ### Changed @@ -210,7 +215,6 @@ Breaking Changes ## 0.7.2 2022-05-05 - ### Added - Export of serializeAccountTransactionForSubmission. diff --git a/packages/nodejs/package.json b/packages/nodejs/package.json index de0dc3cee..3ab511a11 100644 --- a/packages/nodejs/package.json +++ b/packages/nodejs/package.json @@ -1,6 +1,6 @@ { "name": "@concordium/node-sdk", - "version": "9.4.0", + "version": "9.5.0", "description": "Helpers for interacting with the Concordium node", "repository": { "type": "git", @@ -60,7 +60,7 @@ "build-dev": "tsc" }, "dependencies": { - "@concordium/common-sdk": "9.4.0", + "@concordium/common-sdk": "9.5.0", "@grpc/grpc-js": "^1.3.4", "@protobuf-ts/grpc-transport": "^2.8.2", "buffer": "^6.0.3", diff --git a/packages/nodejs/test/clientV2.test.ts b/packages/nodejs/test/clientV2.test.ts index 0d8319fdd..500352778 100644 --- a/packages/nodejs/test/clientV2.test.ts +++ b/packages/nodejs/test/clientV2.test.ts @@ -623,7 +623,32 @@ test.each([clientV2, clientWeb])( test.each([clientV2, clientWeb])('getBlockInfo', async (client) => { const blockInfo = await client.getBlockInfo(testBlockHash); - expect(blockInfo).toEqual(expected.blockInfo); + expect(blockInfo.blockParent).toEqual( + '28d92ec42dbda119f0b0207d3400b0573fe8baf4b0d3dbe44b86781ad6b655cf' + ); + expect(blockInfo.blockHash).toEqual( + 'fe88ff35454079c3df11d8ae13d5777babd61f28be58494efe51b6593e30716e' + ); + expect(blockInfo.blockStateHash).toEqual( + '6e602157d76677fc4b630b2701571d2b0166e2b08e0afe8ab92356e4d0b88a6a' + ); + expect(blockInfo.blockLastFinalized).toEqual( + '28d92ec42dbda119f0b0207d3400b0573fe8baf4b0d3dbe44b86781ad6b655cf' + ); + expect(blockInfo.blockHeight).toEqual(1259179n); + expect(blockInfo.blockBaker).toEqual(4n); + expect(blockInfo.blockArriveTime).toBeDefined(); + expect(blockInfo.blockReceiveTime).toBeDefined(); + expect(blockInfo.blockSlotTime).toEqual( + new Date('2022-11-07T10:54:10.750Z') + ); + expect(blockInfo.finalized).toEqual(true); + expect(blockInfo.transactionCount).toEqual(0n); + expect(blockInfo.transactionsSize).toEqual(0n); + expect(blockInfo.transactionEnergyCost).toEqual(0n); + expect(blockInfo.genesisIndex).toEqual(1); + expect(blockInfo.eraBlockHeight).toEqual(1258806); + expect(blockInfo.protocolVersion).toEqual(4n); }); test.each([clientV2, clientWeb])('getBakerList', async (client) => { @@ -943,3 +968,105 @@ describe('findFirstFinalizedBlockNoLaterThan', () => { } ); }); + +test.each([clientV2, clientWeb])('getBakerEarliestWinTime', async (client) => { + const bakers = await streamToList(client.getBakerList()); + const earliestWinTime = await client.getBakerEarliestWinTime(bakers[0]); + + // Arbitrary eraliestWinTime measured at the time of running the test. + // Every earliestWinTime measured after this point should be greater than this. + expect(earliestWinTime).toBeGreaterThan(1692792026500n); +}); + +test.each([clientV2, clientWeb])( + 'getBlockCertificates: With timeout certificate', + async (client) => { + const blockWithTimeoutCert = + 'ac94ab7628d44fd8b4edb3075ae156e4b85d4007f52f147df6936ff70083d1ef'; + const blockCertificates = await client.getBlockCertificates( + blockWithTimeoutCert + ); + + expect(blockCertificates.timeoutCertificate).toEqual( + expected.timeoutCertificate + ); + } +); + +test.each([clientV2, clientWeb])( + 'getBlockCertificates: With epoch finalization entry', + async (client) => { + const blockWithEpochFinalizationEntry = + '1ba4bcd28a6e014204f79a81a47bac7518066410acbeb7853f20b55e335b947a'; + const blockCertificates = await client.getBlockCertificates( + blockWithEpochFinalizationEntry + ); + + expect(blockCertificates.quorumCertificate).toEqual( + expected.quorumCertificate + ); + expect(blockCertificates.epochFinalizationEntry).toEqual( + expected.epochFinalizationEntry + ); + } +); + +test.each([clientV2, clientWeb])('getBakersRewardPeriod', async (client) => { + const bakerRewardPeriodInfo = await streamToList( + client.getBakersRewardPeriod() + ); + const brpi = bakerRewardPeriodInfo[0]; + + expect(typeof brpi.baker.bakerId).toEqual('bigint'); + expect(brpi.baker.electionKey.length).toEqual(64); + expect(brpi.baker.signatureKey.length).toEqual(64); + expect(brpi.baker.aggregationKey.length).toEqual(192); + expect(brpi.baker.aggregationKey.length).toEqual(192); + expect(typeof brpi.commissionRates.bakingCommission).toEqual('number'); + expect(typeof brpi.commissionRates.finalizationCommission).toEqual( + 'number' + ); + expect(typeof brpi.commissionRates.transactionCommission).toEqual('number'); + expect(typeof brpi.effectiveStake).toEqual('bigint'); + expect(typeof brpi.equityCapital).toEqual('bigint'); + expect(typeof brpi.isFinalizer).toEqual('boolean'); +}); + +test.each([clientV2, clientWeb])( + 'getFirstBlockEpoch - block hash', + async (client) => { + const firstBlockEpoch = await client.getFirstBlockEpoch(testBlockHash); + + expect(firstBlockEpoch).toEqual( + '1ffd2823aa0dff331cc1ec98cf8269cf22120b94e2087c107874c7e84190317b' + ); + } +); + +test.each([clientV2, clientWeb])( + 'getFirstBlockEpoch - relative epoch request', + async (client) => { + const req = { + genesisIndex: 1, + epoch: 5n, + }; + const firstBlockEpoch = await client.getFirstBlockEpoch(req); + + expect(firstBlockEpoch).toEqual( + 'ea2a11db1d20658e9dc91f70116fe3f83a5fc49ac318d8ed1848295ae93c66fa' + ); + } +); + +test.each([clientV2, clientWeb])('getWinningBakersEpoch', async (client) => { + const blockHash = + 'ae4a8e864bb71dc2b6043a31c429be4fc4a110955143753ab3963c6a829c8818'; + const winningBakers = await streamToList( + client.getWinningBakersEpoch(blockHash) + ); + const round = winningBakers.filter((x) => x.round === 296651n)[0]; + + expect(round.round).toEqual(296651n); + expect(round.winner).toEqual(5n); + expect(round.present).toEqual(true); +}); diff --git a/packages/nodejs/test/resources/expectedJsons.ts b/packages/nodejs/test/resources/expectedJsons.ts index 85336f59c..a8c15b921 100644 --- a/packages/nodejs/test/resources/expectedJsons.ts +++ b/packages/nodejs/test/resources/expectedJsons.ts @@ -1,12 +1,14 @@ import { AccountAddress, - BlockInfoV0, CcdAmount, ChainParametersV0, ChainParametersV1, ElectionInfoV0, + EpochFinalizationEntry, ModuleReference, NextUpdateSequenceNumbers, + QuorumCertificate, + TimeoutCertificate, } from '@concordium/common-sdk'; export const accountInfo = { @@ -1958,6 +1960,11 @@ export const bakerPoolStatus = { lotteryPower: 0.15552531374613243, bakerEquityCapital: 7344771840225046n, delegatedCapital: 0n, + commissionRates: { + bakingCommission: 0.1, + finalizationCommission: 1, + transactionCommission: 0.1, + }, }, allPoolTotalCapital: 46071942529284135n, }; @@ -2024,30 +2031,6 @@ export const blocksAtHeight = [ '99ceb0dfcd36714d9c141fde08e85da1d0d624994e95b35114f14193c811b76e', ]; -export const blockInfo: BlockInfoV0 = { - blockParent: - '28d92ec42dbda119f0b0207d3400b0573fe8baf4b0d3dbe44b86781ad6b655cf', - blockHash: - 'fe88ff35454079c3df11d8ae13d5777babd61f28be58494efe51b6593e30716e', - blockStateHash: - '6e602157d76677fc4b630b2701571d2b0166e2b08e0afe8ab92356e4d0b88a6a', - blockLastFinalized: - '28d92ec42dbda119f0b0207d3400b0573fe8baf4b0d3dbe44b86781ad6b655cf', - blockHeight: 1259179n, - blockBaker: 4n, - blockSlot: 50801674n, - blockArriveTime: new Date('2022-11-07T10:54:10.899Z'), - blockReceiveTime: new Date('2022-11-07T10:54:10.892Z'), - blockSlotTime: new Date('2022-11-07T10:54:10.750Z'), - finalized: true, - transactionCount: 0n, - transactionsSize: 0n, - transactionEnergyCost: 0n, - genesisIndex: 1, - eraBlockHeight: 1258806, - protocolVersion: 4n, -}; - export const bakers = [ 1n, 3n, @@ -2076,3 +2059,49 @@ export const bakers = [ 1601n, 1614n, ]; + +export const epochFinalizationEntry: EpochFinalizationEntry = { + finalizedQc: { + blockHash: + '20e3ebb41565b460615b08e994103b4a7415f4224441fc9c17c766a1ed1e040f', + round: 78524n, + epoch: 48n, + aggregateSignature: + 'a351b4f049da150731d2699bc49584af158633ec842ab6a676ab4c2402d1c917149d57c4c2ea73d3c58eae222853a6ba', + signatories: [3n, 4n, 5n, 6n, 8n, 1004n], + }, + successorQc: { + blockHash: + '524d787522286a3b2483d3c1cbec5e13ed6ba282484c6caacec56b1353a3c6bc', + round: 78525n, + epoch: 48n, + aggregateSignature: + 'b8f823d6b4c09243f77396ce62b7d33ad17d429036a0c37810d58d2cfdec293645a02c6874cf17523d41ccf373d943aa', + signatories: [3n, 4n, 5n, 6n, 8n, 1004n], + }, + successorProof: + '3c95938c7aba9c93c805390d9d93dd7f67bd868320e4dd5bcd2f27a7f6f3c011', +}; + +export const quorumCertificate: QuorumCertificate = { + blockHash: + '524d787522286a3b2483d3c1cbec5e13ed6ba282484c6caacec56b1353a3c6bc', + round: 78525n, + epoch: 48n, + aggregateSignature: + 'b8f823d6b4c09243f77396ce62b7d33ad17d429036a0c37810d58d2cfdec293645a02c6874cf17523d41ccf373d943aa', + signatories: [3n, 4n, 5n, 6n, 8n, 1004n], +}; +export const timeoutCertificate: TimeoutCertificate = { + round: 78992n, + minEpoch: 49n, + qcRoundsFirstEpoch: [ + { + round: 78991n, + finalizers: [1n, 3n, 5n, 6n, 8n, 1004n, 1010n, 1016n], + }, + ], + qcRoundsSecondEpoch: [], + aggregateSignature: + 'ad8f2c078af44f2b4002172108385c59d012e72d9c8febfa9c2cd6592697621fd4b036df2668bc65190cbf5a5c20dcad', +}; diff --git a/packages/web/CHANGELOG.md b/packages/web/CHANGELOG.md index 4f1bbfa8b..e741898ba 100644 --- a/packages/web/CHANGELOG.md +++ b/packages/web/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## 6.5.0 + +- Bumped @concordium/common-sdk to 9.5.0. + ## 6.4.0 - Bumped @concordium/common-sdk to 9.4.0. @@ -189,8 +193,8 @@ ## 0.1.1 -- Fixed issue with wasm from rust bindings +- Fixed issue with wasm from rust bindings ## 0.1.0 -- Initial release +- Initial release diff --git a/packages/web/package.json b/packages/web/package.json index cbb07e69c..f3c13a3cb 100644 --- a/packages/web/package.json +++ b/packages/web/package.json @@ -1,6 +1,6 @@ { "name": "@concordium/web-sdk", - "version": "6.4.0", + "version": "6.5.0", "license": "Apache-2.0", "browser": "lib/concordium.min.js", "types": "lib/index.d.ts", @@ -48,7 +48,7 @@ "webpack-cli": "^4.9.2" }, "dependencies": { - "@concordium/common-sdk": "9.4.0", + "@concordium/common-sdk": "9.5.0", "@concordium/rust-bindings": "1.2.0", "@grpc/grpc-js": "^1.3.4", "@protobuf-ts/grpcweb-transport": "^2.8.2", diff --git a/yarn.lock b/yarn.lock index 1f15a7dc1..0cddf50d1 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1334,7 +1334,7 @@ __metadata: languageName: unknown linkType: soft -"@concordium/common-sdk@9.4.0, @concordium/common-sdk@workspace:^, @concordium/common-sdk@workspace:packages/common": +"@concordium/common-sdk@9.5.0, @concordium/common-sdk@workspace:^, @concordium/common-sdk@workspace:packages/common": version: 0.0.0-use.local resolution: "@concordium/common-sdk@workspace:packages/common" dependencies: @@ -1374,6 +1374,27 @@ __metadata: languageName: unknown linkType: soft +"@concordium/common-sdk@npm:9.4.0": + version: 9.4.0 + resolution: "@concordium/common-sdk@npm:9.4.0" + dependencies: + "@concordium/rust-bindings": 1.2.0 + "@grpc/grpc-js": ^1.3.4 + "@noble/ed25519": ^1.7.1 + "@protobuf-ts/runtime-rpc": ^2.8.2 + "@scure/bip39": ^1.1.0 + big.js: ^6.2.0 + bs58check: ^2.1.2 + buffer: ^6.0.3 + cross-fetch: 3.1.5 + hash.js: ^1.1.7 + iso-3166-1: ^2.1.1 + json-bigint: ^1.0.0 + uuid: ^8.3.2 + checksum: 09b4f3303cca7677f48842c26dcc5692ef6c38bfd8c86f8b790a9f57ce942637264aaeccbcc4bf45313b88afbfff4bd3ef46bc6cbced5a29271df486819c41ad + languageName: node + linkType: hard + "@concordium/examples@workspace:examples": version: 0.0.0-use.local resolution: "@concordium/examples@workspace:examples" @@ -1402,7 +1423,7 @@ __metadata: version: 0.0.0-use.local resolution: "@concordium/node-sdk@workspace:packages/nodejs" dependencies: - "@concordium/common-sdk": 9.4.0 + "@concordium/common-sdk": 9.5.0 "@grpc/grpc-js": ^1.3.4 "@noble/ed25519": ^1.7.1 "@protobuf-ts/grpc-transport": ^2.8.2 @@ -1441,7 +1462,7 @@ __metadata: version: 0.0.0-use.local resolution: "@concordium/web-sdk@workspace:packages/web" dependencies: - "@concordium/common-sdk": 9.4.0 + "@concordium/common-sdk": 9.5.0 "@concordium/rust-bindings": 1.2.0 "@grpc/grpc-js": ^1.3.4 "@protobuf-ts/grpcweb-transport": ^2.8.2