Skip to content

Commit

Permalink
fix starcoin-state-api error
Browse files Browse the repository at this point in the history
  • Loading branch information
nkysg committed Sep 26, 2024
1 parent a3ff95c commit 7f296df
Show file tree
Hide file tree
Showing 6 changed files with 73 additions and 58 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions state/api/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ starcoin-types = { workspace = true }
starcoin-vm-types = { workspace = true }
forkable-jellyfish-merkle = { workspace = true }
once_cell = { workspace = true }
bytes = { workspace = true }

[dev-dependencies]

Expand Down
20 changes: 9 additions & 11 deletions state/api/src/chain_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use crate::StateReaderExt;
use crate::TABLE_PATH_LIST;
use anyhow::{ensure, Result};
use forkable_jellyfish_merkle::{blob::Blob, proof::SparseMerkleProof, RawKey};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use starcoin_crypto::HashValue;
use starcoin_state_tree::AccountStateSetIterator;
Expand All @@ -20,10 +19,9 @@ use starcoin_vm_types::account_config::TABLE_HANDLE_ADDRESS_LIST;
use starcoin_vm_types::genesis_config::ChainId;
use starcoin_vm_types::on_chain_resource::{Epoch, EpochInfo, GlobalTimeOnChain};
use starcoin_vm_types::state_store::table::{TableHandle, TableInfo};
use starcoin_vm_types::state_store::StateView;
use starcoin_vm_types::token::token_code::TokenCode;
use starcoin_vm_types::{
move_resource::MoveResource, on_chain_config::OnChainConfig, state_view::StateView,
};
use starcoin_vm_types::{move_resource::MoveResource, on_chain_config::OnChainConfig};
use std::convert::TryFrom;

#[derive(Debug, Default, Eq, PartialEq, Clone, Serialize, Deserialize)]
Expand Down Expand Up @@ -174,30 +172,30 @@ where
pub fn get_account_resource(
&self,
address: &AccountAddress,
) -> Result<Option<AccountResource>> {
) -> Result<AccountResource> {
self.reader.get_account_resource(*address)
}

/// Get Resource by type
pub fn get_resource<R>(&self, address: AccountAddress) -> Result<Option<R>>
pub fn get_resource<R>(&self, address: AccountAddress) -> Result<R>
where
R: MoveResource,
{
self.reader.get_resource_type(address)
self.reader.get_resource_type::<R>(address)
}

pub fn get_sequence_number(&self, address: AccountAddress) -> Result<u64> {
self.reader.get_sequence_number(address)
}

pub fn get_on_chain_config<C>(&self) -> Result<Option<C>>
pub fn get_on_chain_config<C>(&self) -> Option<C>
where
C: OnChainConfig,
{
self.reader.get_on_chain_config()
}

pub fn get_balance(&self, address: &AccountAddress) -> Result<Option<u128>> {
pub fn get_balance(&self, address: &AccountAddress) -> Result<u128> {
self.reader.get_balance(*address)
}

Expand All @@ -206,15 +204,15 @@ where
&self,
address: &AccountAddress,
type_tag: StructTag,
) -> Result<Option<u128>> {
) -> Result<u128> {
self.reader.get_balance_by_type(*address, type_tag)
}

pub fn get_balance_by_token_code(
&self,
address: &AccountAddress,
token_code: TokenCode,
) -> Result<Option<u128>> {
) -> Result<u128> {
self.reader.get_balance_by_token_code(*address, token_code)
}

Expand Down
76 changes: 45 additions & 31 deletions state/api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0

use crate::message::{StateRequest, StateResponse};
use anyhow::Result;
use anyhow::{format_err, Result};
use once_cell::sync::Lazy;
use starcoin_crypto::HashValue;
use starcoin_service_registry::{ActorService, ServiceHandler, ServiceRef};
Expand All @@ -15,18 +15,19 @@ pub use chain_state::{
AccountStateReader, ChainStateReader, ChainStateWriter, StateProof, StateWithProof,
StateWithTableItemProof,
};
use serde::de::DeserializeOwned;
pub use starcoin_state_tree::StateNodeStore;
use starcoin_types::state_set::AccountStateSet;
use starcoin_vm_types::access_path::DataPath;
use starcoin_vm_types::account_config::TABLE_HANDLE_ADDRESS_LIST;
use starcoin_vm_types::move_resource::MoveResource;
use starcoin_vm_types::state_store::state_key::StateKey;
use starcoin_vm_types::state_store::table::{TableHandle, TableInfo};
pub use starcoin_vm_types::state_view::{StateReaderExt, StateView};
pub use starcoin_vm_types::state_view::StateReaderExt;

mod chain_state;
pub mod message;
pub mod mock;
use bytes::Bytes;

pub static TABLE_PATH_LIST: Lazy<Vec<DataPath>> = Lazy::new(|| {
let mut path_list = vec![];
Expand All @@ -42,44 +43,49 @@ pub static TABLE_PATH_LIST: Lazy<Vec<DataPath>> = Lazy::new(|| {

#[async_trait::async_trait]
pub trait ChainStateAsyncService: Clone + std::marker::Unpin + Send + Sync {
async fn get(self, access_path: AccessPath) -> Result<Option<Vec<u8>>>;
async fn get(self, state_key: &StateKey) -> Result<Option<Bytes>>;

async fn get_with_proof(self, access_path: AccessPath) -> Result<StateWithProof>;
async fn get_with_proof(self, state_key: &StateKey) -> Result<StateWithProof>;

async fn get_resource<R>(self, address: AccountAddress) -> Result<Option<R>>
async fn get_resource<R>(self, address: AccountAddress) -> Result<R>
where
R: MoveResource,
{
let access_path = AccessPath::new(address, R::resource_path());
let r = self.get(access_path).await.and_then(|state| match state {
Some(state) => Ok(Some(bcs_ext::from_bytes::<R>(state.as_slice())?)),
None => Ok(None),
})?;
Ok(r)
let rsrc_bytes = self.get(&StateKey::resource_typed::<R>(&address)?).await?.ok_or_else(
|| {
format_err!(
"Resource {:?} not exists at address:{}",
R::module_identifier(),
address
)
},
)?;
let rsrc = bcs_ext::from_bytes::<R>(&rsrc_bytes)?;
Ok(rsrc)
}

async fn get_account_state(self, address: AccountAddress) -> Result<Option<AccountState>>;
async fn get_account_state(self, address: AccountAddress) -> Result<AccountState>;

/// get account stateset on state_root(if empty, use current state root).
async fn get_account_state_set(
self,
address: AccountAddress,
state_root: Option<HashValue>,
) -> Result<Option<AccountStateSet>>;
) -> Result<AccountStateSet>;

async fn state_root(self) -> Result<HashValue>;

async fn get_with_proof_by_root(
self,
access_path: AccessPath,
state_key: StateKey,
state_root: HashValue,
) -> Result<StateWithProof>;

async fn get_account_state_by_root(
self,
address: AccountAddress,
state_root: HashValue,
) -> Result<Option<AccountState>>;
) -> Result<AccountState>;

async fn get_with_table_item_proof(
self,
Expand All @@ -93,36 +99,38 @@ pub trait ChainStateAsyncService: Clone + std::marker::Unpin + Send + Sync {
state_root: HashValue,
) -> Result<StateWithTableItemProof>;

async fn get_table_info(self, address: AccountAddress) -> Result<Option<TableInfo>>;
async fn get_table_info(self, address: AccountAddress) -> Result<TableInfo>;
}

#[async_trait::async_trait]
impl<S> ChainStateAsyncService for ServiceRef<S>
where
S: ActorService + ServiceHandler<S, StateRequest>,
{
async fn get(self, access_path: AccessPath) -> Result<Option<Vec<u8>>> {
let response = self.send(StateRequest::Get(access_path)).await??;
async fn get(self, state_key: &StateKey) -> Result<Option<Bytes>> {
let response = self.send(StateRequest::Get(state_key.clone())).await??;
if let StateResponse::State(state) = response {
Ok(state)
} else {
panic!("Unexpect response type.")
}
}

async fn get_with_proof(self, access_path: AccessPath) -> Result<StateWithProof> {
let response = self.send(StateRequest::GetWithProof(access_path)).await??;
async fn get_with_proof(self, state_key: &StateKey) -> Result<StateWithProof> {
let response = self.send(StateRequest::GetWithProof(state_key.clone())).await??;
if let StateResponse::StateWithProof(state) = response {
Ok(*state)
} else {
panic!("Unexpect response type.")
}
}

async fn get_account_state(self, address: AccountAddress) -> Result<Option<AccountState>> {
async fn get_account_state(self, address: AccountAddress) -> Result<AccountState> {
let response = self.send(StateRequest::GetAccountState(address)).await??;
if let StateResponse::AccountState(state) = response {
Ok(state)
Ok(state.ok_or_else(|| {
format_err!("AccountState not exists for address: {}", address)
})?)
} else {
panic!("Unexpect response type.")
}
Expand All @@ -131,15 +139,17 @@ where
self,
address: AccountAddress,
state_root: Option<HashValue>,
) -> Result<Option<AccountStateSet>> {
) -> Result<AccountStateSet> {
let response = self
.send(StateRequest::GetAccountStateSet {
address,
state_root,
})
.await??;
if let StateResponse::AccountStateSet(state) = response {
Ok(state)
Ok(state.ok_or_else(|| {
format_err!("AccountStateSet not exists for address: {}", address)
})?)
} else {
panic!("Unexpected response type.")
}
Expand All @@ -155,11 +165,11 @@ where

async fn get_with_proof_by_root(
self,
access_path: AccessPath,
state_key: StateKey,
state_root: HashValue,
) -> Result<StateWithProof> {
let response = self
.send(StateRequest::GetWithProofByRoot(access_path, state_root))
.send(StateRequest::GetWithProofByRoot(state_key, state_root))
.await??;
if let StateResponse::StateWithProof(state) = response {
Ok(*state)
Expand All @@ -172,15 +182,17 @@ where
self,
account_address: AccountAddress,
state_root: HashValue,
) -> Result<Option<AccountState>> {
) -> Result<AccountState> {
let response = self
.send(StateRequest::GetAccountStateByRoot(
account_address,
state_root,
))
.await??;
if let StateResponse::AccountState(state) = response {
Ok(state)
Ok(state.ok_or_else(|| {
format_err!("AccountState not exists for address: {}", account_address)
})?)
} else {
panic!("Unexpect response type.")
}
Expand Down Expand Up @@ -219,10 +231,12 @@ where
}
}

async fn get_table_info(self, address: AccountAddress) -> Result<Option<TableInfo>> {
async fn get_table_info(self, address: AccountAddress) -> Result<TableInfo> {
let response = self.send(StateRequest::GetTableInfo(address)).await??;
if let StateResponse::TableInfo(state) = response {
Ok(state)
Ok(state.ok_or_else(|| {
format_err!("TableInfo not exists for address: {}", address)
})?)
} else {
panic!("Unexpect response type.")
}
Expand Down
14 changes: 7 additions & 7 deletions state/api/src/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,19 @@

use crate::{StateWithProof, StateWithTableItemProof};
use anyhow::Result;
use bytes::Bytes;
use starcoin_crypto::HashValue;
use starcoin_service_registry::ServiceRequest;
use starcoin_types::state_set::AccountStateSet;
use starcoin_types::{
access_path::AccessPath, account_address::AccountAddress, account_state::AccountState,
};
use starcoin_types::{account_address::AccountAddress, account_state::AccountState};
use starcoin_vm_types::state_store::state_key::StateKey;
use starcoin_vm_types::state_store::table::{TableHandle, TableInfo};

#[derive(Debug, Clone)]
pub enum StateRequest {
Get(AccessPath),
GetWithProof(AccessPath),
GetWithProofByRoot(AccessPath, HashValue),
Get(StateKey),
GetWithProof(StateKey),
GetWithProofByRoot(StateKey, HashValue),
GetAccountState(AccountAddress),
GetAccountStateSet {
address: AccountAddress,
Expand All @@ -34,7 +34,7 @@ impl ServiceRequest for StateRequest {

#[derive(Debug, Clone)]
pub enum StateResponse {
State(Option<Vec<u8>>),
State(Option<Bytes>),
StateWithProof(Box<StateWithProof>),
StateRoot(HashValue),
AccountState(Option<AccountState>),
Expand Down
Loading

0 comments on commit 7f296df

Please sign in to comment.