Skip to content

Commit

Permalink
Merge pull request #218 from Concordium/node8-support
Browse files Browse the repository at this point in the history
Additional support for Node 8 APIs
  • Loading branch information
eb-concordium authored Dec 11, 2024
2 parents eb4a3ea + 57bfd43 commit 61678e6
Show file tree
Hide file tree
Showing 7 changed files with 164 additions and 24 deletions.
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,16 @@
suspended.
- New `UpdatePayload` type `ValidatorScoreParametersCPV3`, which updates the maximum number of
consecutive failures a validator can have before it faces suspension.
- `ContractInitializedEvent` adds the `parameter` used to initialize the contract (supported from
node version >= 8).
- New functionality for querying which accounts have scheduled releases or cooldowns (supported
from node version >= 8):
- `get_scheduled_release_accounts`: Get the accounts (by index) with scheduled releases, and the
timestamp of the first release.
- `get_cooldown_accounts`: Get the accounts (by index) with stake in cooldown, and the timestamp
at which the first cooldown expires.
- `get_pre_cooldown_accounts`: Get the accounts (by index) with stake in pre-cooldown.
- `get_pre_pre_cooldown_accounts`: Get the accounts (by index) with stake in pre-pre-cooldown.

## 5.0.0

Expand Down
14 changes: 7 additions & 7 deletions src/cis3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,11 +111,11 @@ impl Cis3Contract {
/// # Arguments
///
/// * `bi` - The block to query. The query will be executed in the state of
/// the chain at the end of the block.
/// the chain at the end of the block.
/// * `sender` - The (sponsor) address that is invoking the entrypoint.
/// * `params` - The parameters for the permit invocation. Includes the
/// signature of the sponsoree, the address of the sponsoree, and the
/// signed message.
/// signature of the sponsoree, the address of the sponsoree, and the
/// signed message.
pub async fn permit_dry_run(
&mut self,
bi: impl IntoBlockIdentifier,
Expand Down Expand Up @@ -150,8 +150,8 @@ impl Cis3Contract {
/// smart contract update transaction.
/// * `metadata` - Metadata for constructing the transaction.
/// * `params` - The parameters for the permit invocation. Includes the
/// signature of the sponsoree, the address of the sponsoree, and the
/// signed message.
/// signature of the sponsoree, the address of the sponsoree, and the
/// signed message.
pub async fn permit(
&mut self,
signer: &impl transactions::ExactSizeTransactionSigner,
Expand All @@ -174,8 +174,8 @@ impl Cis3Contract {
/// smart contract update transaction.
/// * `metadata` - Metadata for constructing the transaction.
/// * `params` - The parameters for the permit invocation. Includes the
/// signature of the sponsoree, the address of the sponsoree, and the
/// signed message.
/// signature of the sponsoree, the address of the sponsoree, and the
/// signed message.
pub fn make_permit(
&mut self,
signer: &impl transactions::ExactSizeTransactionSigner,
Expand Down
20 changes: 13 additions & 7 deletions src/contract_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -908,14 +908,15 @@ pub fn decode_concordium_std_error(reject_reason: i32) -> Option<ConcordiumStdRe
/// How is the `return_value` and `error_code` assigned in rejected
/// transactions:
/// - If the transaction reverts due to an error in the `concordium-std` crate,
/// the `return_value` is None and the `error_code` is assigned as defined in
/// the `concordium-std` crate.
/// the `return_value` is None and the `error_code` is assigned as defined in
/// the `concordium-std` crate.
/// - If the transaction reverts due to an error in the smart contract logic:
/// A smart contract V1 needs to implement a conversion to `Reject` for its
/// smart contract errors.
/// `<https://docs.rs/concordium-std/latest/concordium_std/struct.Reject.html>`
/// A smart contract V1 needs to implement a conversion to `Reject` for its
/// smart contract errors.
/// `<https://docs.rs/concordium-std/latest/concordium_std/struct.Reject.html>`
///
/// 1. Example: Deriving `Reject` in the smart contract.
///
/// The simplest way to implement `Reject` in the smart contract is by deriving
/// it.
///
Expand All @@ -940,6 +941,7 @@ pub fn decode_concordium_std_error(reject_reason: i32) -> Option<ConcordiumStdRe
/// ```
///
/// 2. Example: Deriving `Reject` in the smart contract with nested errors.
///
/// Nested errors are often used to inherit the errors from a smart
/// contract library such as the cis2-library.
/// `<https://github.com/Concordium/concordium-rust-smart-contracts/blob/dde42fa62254a55b46a4c9c52c32bbe661127001/concordium-cis2/src/lib.rs#L1093>`
Expand Down Expand Up @@ -996,6 +998,7 @@ pub fn decode_concordium_std_error(reject_reason: i32) -> Option<ConcordiumStdRe
/// ```
///
/// 3. Example: `Reject::default()`.
///
/// The historical `Reject::default()` can be used by implementing the
/// conversion to `Reject` manually.
///
Expand Down Expand Up @@ -1025,6 +1028,7 @@ pub fn decode_concordium_std_error(reject_reason: i32) -> Option<ConcordiumStdRe
/// ```
///
/// 4. Example: Implementing the conversion to `Reject` manually.
///
/// A smart contract can implement the conversion to `Reject` manually and
/// define custom error codes. The convention for the `return_value` is to set
/// the value to the serialization of the enum variants so that decoding of the
Expand Down Expand Up @@ -1636,8 +1640,10 @@ impl ContractUpdateHandle {
crate::types::BlockItemSummaryDetails::AccountTransaction(at) => match at.effects {
AccountTransactionEffects::ContractUpdateIssued { effects } => {
let Some(execution_tree) = crate::types::execution_tree(effects) else {
return mk_error("Expected smart contract update, but received invalid execution tree.");
};
return mk_error(
"Expected smart contract update, but received invalid execution tree.",
);
};
Ok(ContractUpdateInfo {
execution_tree,
energy_cost: result.energy_cost,
Expand Down
10 changes: 5 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@
//! structured around multiple modules.
//!
//! - [`v2`] contains the main entrypoint to the library. In particular it
//! contains the [`Client`](v2::Client) struct
//! which maintains a connection to the node, and supports queries and node
//! manipulation. This client uses gRPC API version 2 of the Concordium node.
//! contains the [`Client`](v2::Client) struct which maintains a connection to
//! the node, and supports queries and node manipulation. This client uses
//! gRPC API version 2 of the Concordium node.
//! - [`constants`] contains a number of constants and type definitions that are
//! relevant when using the chain.
//! - [`types`] contains most type definitions to model responses as well as
//! types defining transactions.
//! The latter are in a submodule [`types::transactions`].
//! types defining transactions. The latter are in a submodule
//! [`types::transactions`].
//!
//! In addition to these, the library re-exports a number of core crates that
//! implement the core cryptographic protocols of the Concordium blockchain.
Expand Down
12 changes: 12 additions & 0 deletions src/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2264,6 +2264,9 @@ pub struct ContractInitializedEvent {
/// Any contract events that might have been generated by the contract
/// initialization.
pub events: Vec<smart_contracts::ContractEvent>,
/// The parameter passed to the initializer. This should not be `None` when
/// querying node version >= 8.
pub parameter: Option<smart_contracts::OwnedParameter>,
}

// re-export for backwards compatibility
Expand Down Expand Up @@ -2812,6 +2815,15 @@ pub struct WinningBaker {
pub present: bool,
}

/// An account that is pending either a scheduled release or a cooldown.
#[derive(Debug)]
pub struct AccountPending {
/// The account that is pending.
pub account_index: AccountIndex,
/// The timestamp at which the first pending event is set to occur.
pub first_timestamp: Timestamp,
}

/// Information of a baker for a certain reward period.
#[derive(Debug)]
pub struct BakerRewardPeriodInfo {
Expand Down
12 changes: 12 additions & 0 deletions src/v2/conversions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1657,6 +1657,7 @@ impl TryFrom<AccountTransactionEffects> for super::types::AccountTransactionEffe
amount: cie.amount.require()?.into(),
init_name: cie.init_name.require()?.try_into()?,
events: cie.events.into_iter().map(Into::into).collect(),
parameter: cie.parameter.map(TryInto::try_into).transpose()?,
},
})
}
Expand Down Expand Up @@ -3472,6 +3473,17 @@ impl TryFrom<WinningBaker> for super::types::WinningBaker {
}
}

impl TryFrom<AccountPending> for super::types::AccountPending {
type Error = tonic::Status;

fn try_from(pending: AccountPending) -> Result<Self, Self::Error> {
Ok(Self {
account_index: pending.account_index.require()?.into(),
first_timestamp: pending.first_timestamp.require()?.into(),
})
}
}

impl TryFrom<BakerRewardPeriodInfo> for super::types::BakerRewardPeriodInfo {
type Error = tonic::Status;

Expand Down
110 changes: 105 additions & 5 deletions src/v2/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,17 @@ use crate::{
ContractContext, InstanceInfo, InvokeContractResult, ModuleReference, WasmModule,
},
transactions::{self, InitContractPayload, UpdateContractPayload, UpdateInstruction},
AbsoluteBlockHeight, AccountInfo, BlockItemSummary, CredentialRegistrationID, Energy, Memo,
Nonce, RegisteredData, SpecialTransactionOutcome, TransactionStatus, UpdateSequenceNumber,
AbsoluteBlockHeight, AccountInfo, AccountPending, BlockItemSummary,
CredentialRegistrationID, Energy, Memo, Nonce, RegisteredData, SpecialTransactionOutcome,
TransactionStatus, UpdateSequenceNumber,
},
};
use anyhow::Context;
use concordium_base::{
base::{
BlockHeight, ChainParameterVersion0, ChainParameterVersion1, CredentialsPerBlockLimit,
ElectionDifficulty, Epoch, ExchangeRate, GenesisIndex, MintDistributionV0,
MintDistributionV1,
AccountIndex, BlockHeight, ChainParameterVersion0, ChainParameterVersion1,
CredentialsPerBlockLimit, ElectionDifficulty, Epoch, ExchangeRate, GenesisIndex,
MintDistributionV0, MintDistributionV1,
},
common::{
self,
Expand Down Expand Up @@ -2485,6 +2486,105 @@ impl Client {
})
}

/// Get all accounts that have scheduled releases, with the timestamp of the
/// first pending scheduled release for that account. (Note, this only
/// identifies accounts by index, and only indicates the first pending
/// release for each account.)
pub async fn get_scheduled_release_accounts(
&mut self,
block_id: impl IntoBlockIdentifier,
) -> endpoints::QueryResult<
QueryResponse<impl Stream<Item = Result<AccountPending, tonic::Status>>>,
> {
let response = self
.client
.get_scheduled_release_accounts(&block_id.into_block_identifier())
.await?;
let block_hash = extract_metadata(&response)?;
let stream = response.into_inner().map(|result| match result {
Ok(pending) => pending.try_into(),
Err(err) => Err(err),
});
Ok(QueryResponse {
block_hash,
response: stream,
})
}

/// Get all accounts that have stake in cooldown, with the timestamp of the
/// first pending cooldown expiry for each account. (Note, this only
/// identifies accounts by index, and only indicates the first pending
/// cooldown for each account.) Prior to protocol version 7, the
/// resulting stream will always be empty.
pub async fn get_cooldown_accounts(
&mut self,
block_id: impl IntoBlockIdentifier,
) -> endpoints::QueryResult<
QueryResponse<impl Stream<Item = Result<AccountPending, tonic::Status>>>,
> {
let response = self
.client
.get_cooldown_accounts(&block_id.into_block_identifier())
.await?;
let block_hash = extract_metadata(&response)?;
let stream = response.into_inner().map(|result| match result {
Ok(pending) => pending.try_into(),
Err(err) => Err(err),
});
Ok(QueryResponse {
block_hash,
response: stream,
})
}

/// Get all accounts that have stake in pre-cooldown.
/// (This only identifies accounts by index.)
/// Prior to protocol version 7, the resulting stream will always be empty.
pub async fn get_pre_cooldown_accounts(
&mut self,
block_id: impl IntoBlockIdentifier,
) -> endpoints::QueryResult<
QueryResponse<impl Stream<Item = Result<AccountIndex, tonic::Status>>>,
> {
let response = self
.client
.get_pre_cooldown_accounts(&block_id.into_block_identifier())
.await?;
let block_hash = extract_metadata(&response)?;
let stream = response.into_inner().map(|result| match result {
Ok(account) => Ok(account.into()),
Err(err) => Err(err),
});
Ok(QueryResponse {
block_hash,
response: stream,
})
}

/// Get all accounts that have stake in pre-pre-cooldown.
/// (This only identifies accounts by index.)
/// Prior to protocol version 7, the resulting stream will always be empty.
pub async fn get_pre_pre_cooldown_accounts(
&mut self,
block_id: impl IntoBlockIdentifier,
) -> endpoints::QueryResult<
QueryResponse<impl Stream<Item = Result<AccountIndex, tonic::Status>>>,
> {
let response = self
.client
.get_pre_pre_cooldown_accounts(&block_id.into_block_identifier())
.await?;
let block_hash = extract_metadata(&response)?;
let stream = response.into_inner().map(|result| match result {
Ok(account) => Ok(account.into()),
Err(err) => Err(err),
});
Ok(QueryResponse {
block_hash,
response: stream,
})
}

/// Get the chain parameters in effect after a given block.
/// If the block does not exist [`QueryError::NotFound`] is returned.
pub async fn get_block_chain_parameters(
Expand Down

0 comments on commit 61678e6

Please sign in to comment.