Skip to content

Commit

Permalink
[asset-mapping] 1. replace BalanceResource with CoinStoreResource; 2.…
Browse files Browse the repository at this point in the history
… Add fungible get into StateViewExt::get_balance_by_type
  • Loading branch information
welbon committed Jan 21, 2025
1 parent 6be64ab commit 340c59b
Show file tree
Hide file tree
Showing 12 changed files with 203 additions and 142 deletions.
33 changes: 22 additions & 11 deletions asset-mapping/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,22 @@ use anyhow::Result;
use starcoin_crypto::{hash::PlainCryptoHash, HashValue};

use forkable_jellyfish_merkle::{blob::Blob, node_type::SparseMerkleLeafNode, RawKey};
use starcoin_cached_packages::starcoin_framework_sdk_builder::{asset_mapping_assign_to_account_test, asset_mapping_assign_to_account_with_proof};
use starcoin_cached_packages::starcoin_framework_sdk_builder::{
asset_mapping_assign_to_account_test, asset_mapping_assign_to_account_with_proof,
};
use starcoin_chain::{BlockChain, ChainReader, ChainWriter};
use starcoin_config::{ChainNetwork, NodeConfig, G_TEST_CONFIG};
use starcoin_consensus::Consensus;
use starcoin_state_api::ChainStateReader;
use starcoin_transaction_builder::{create_signed_txn_with_association_account, DEFAULT_MAX_GAS_AMOUNT, peer_to_peer_txn_sent_as_association};
use starcoin_transaction_builder::{
create_signed_txn_with_association_account, peer_to_peer_txn_sent_as_association,
DEFAULT_MAX_GAS_AMOUNT,
};
use starcoin_types::{
account::DEFAULT_EXPIRATION_TIME, account_address::AccountAddress,
account::Account, account::DEFAULT_EXPIRATION_TIME, account_address::AccountAddress,
account_config::CORE_CODE_ADDRESS, identifier::Identifier, language_storage::StructTag,
account::Account,
};
use starcoin_vm_types::account_config::association_address;
use starcoin_vm_types::{
access_path::AccessPath,
account_config::{self, genesis_address, stc_type_tag},
Expand All @@ -24,7 +29,6 @@ use starcoin_vm_types::{
state_view::StateReaderExt,
transaction::SignedUserTransaction,
};
use starcoin_vm_types::account_config::association_address;
use test_helper::dao::quorum_vote;
use test_helper::executor::prepare_genesis;

Expand Down Expand Up @@ -87,7 +91,7 @@ fn test_sha3_256_diffrent_with_crypto_macro() -> Result<()> {
HashValue::sha3_256_of(STARCOIN_HASH_PREFIX).as_slice(),
ser.as_slice(),
]
.concat();
.concat();

let move_hash = HashValue::sha3_256_of(&hash_vec[..]);
println!(
Expand Down Expand Up @@ -135,7 +139,9 @@ fn test_simple_asset_mapping_without_proof() -> Result<()> {
// let (chain_state, net) = prepare_genesis();
let test_net = ChainNetwork::new_test();
let mut block_chain = test_helper::gen_blockchain_with_blocks_for_test(0, &test_net)?;
let associal_sequence_number = block_chain.chain_state_reader().get_sequence_number(association_address())?;
let associal_sequence_number = block_chain
.chain_state_reader()
.get_sequence_number(association_address())?;

// Build alice and transfer STC to alice
let amount = 1000000000;
Expand All @@ -153,11 +159,17 @@ fn test_simple_asset_mapping_without_proof() -> Result<()> {

// Check alice's balance
{
assert_eq!(block_chain.chain_state_reader().get_balance(alice)?, amount, "alice balance not expect");
assert_eq!(
block_chain.chain_state_reader().get_balance(alice)?,
amount,
"alice balance not expect"
);
}

let genesis_sequence_number = {
block_chain.chain_state_reader().get_sequence_number(genesis_address())?
block_chain
.chain_state_reader()
.get_sequence_number(genesis_address())?
};
// Execute assign asset mapping to alice
local_block_chain_excecute_txn(
Expand Down Expand Up @@ -185,7 +197,6 @@ fn test_simple_asset_mapping_without_proof() -> Result<()> {
Ok(())
}


#[test]
fn test_asset_mapping_whole_process() -> Result<()> {
starcoin_logger::init_for_test();
Expand Down Expand Up @@ -336,7 +347,7 @@ fn local_build_peer_to_peer_from_association(
net.time_service().now_secs() + DEFAULT_EXPIRATION_TIME,
net,
)
.try_into()?,
.try_into()?,
)
}

Expand Down
4 changes: 2 additions & 2 deletions cmd/airdrop/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use starcoin_types::language_storage::ModuleId;
use starcoin_types::transaction::authenticator::AccountPrivateKey;
use starcoin_types::transaction::{EntryFunction, RawUserTransaction};
use starcoin_vm_types::account_config::auto_accept_token::AutoAcceptToken;
use starcoin_vm_types::account_config::{stc_type_tag, BalanceResource, G_STC_TOKEN_CODE};
use starcoin_vm_types::account_config::{stc_type_tag, CoinStoreResource, G_STC_TOKEN_CODE};
use starcoin_vm_types::language_storage::{StructTag, TypeTag};
use starcoin_vm_types::state_store::state_key::StateKey;
use starcoin_vm_types::token::token_code::TokenCode;
Expand Down Expand Up @@ -80,7 +80,7 @@ async fn is_accept_token(
let balance = client
.get_resource(
address,
BalanceResource::struct_tag_for_token(token_type).into(),
CoinStoreResource::struct_tag_for_token(token_type).into(),
None,
)
.await
Expand Down
6 changes: 3 additions & 3 deletions cmd/starcoin/src/account/show_cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use starcoin_crypto::ValidCryptoMaterialStringExt;
use starcoin_rpc_client::StateRootOption;
use starcoin_state_api::{ChainStateReader, StateReaderExt};
use starcoin_vm_types::account_address::AccountAddress;
use starcoin_vm_types::account_config::BalanceResource;
use starcoin_vm_types::account_config::CoinStoreResource;
use starcoin_vm_types::token::token_code::TokenCode;
use std::collections::HashMap;

Expand Down Expand Up @@ -74,9 +74,9 @@ impl CommandAction for ShowCommand {
.resources
.into_iter()
.filter_map(|(resource_type, resource)| {
if let Some(token_code) = BalanceResource::token_code(&resource_type.0) {
if let Some(token_code) = CoinStoreResource::token_code(&resource_type.0) {
let balance = resource
.decode::<BalanceResource>()
.decode::<CoinStoreResource>()
.ok()
.map(|balance| balance.token());
Some((token_code, balance.unwrap_or(0)))
Expand Down
12 changes: 6 additions & 6 deletions executor/tests/executor_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ use starcoin_state_api::{ChainStateReader, StateReaderExt};
// use test_helper::Account;
use starcoin_statedb::ChainStateDB;
use starcoin_transaction_builder::{
build_batch_payload_same_amount, build_transfer_txn, DEFAULT_EXPIRATION_TIME,
DEFAULT_MAX_GAS_AMOUNT, empty_test_metadata, encode_transfer_script_by_token_code,
raw_peer_to_peer_txn,
build_batch_payload_same_amount, build_transfer_txn, empty_test_metadata,
encode_transfer_script_by_token_code, raw_peer_to_peer_txn, DEFAULT_EXPIRATION_TIME,
DEFAULT_MAX_GAS_AMOUNT,
};
use starcoin_vm_runtime::{
data_cache::AsMoveResolver,
Expand All @@ -25,7 +25,7 @@ use starcoin_vm_runtime::{
};
use starcoin_vm_types::{
access_path::AccessPath,
account_config::{AccountResource, core_code_address, genesis_address, ModuleUpgradeStrategy},
account_config::{core_code_address, genesis_address, AccountResource, ModuleUpgradeStrategy},
genesis_config::ChainId,
on_chain_config::{ConsensusConfig, OnChainConfig},
state_store::{state_key::StateKey, state_value::StateValue, TStateView},
Expand All @@ -50,10 +50,10 @@ use starcoin_types::{
account_config,
account_config::G_STC_TOKEN_CODE,
block_metadata::BlockMetadata,
transaction::{Transaction, TransactionPayload, TransactionStatus},
identifier::Identifier,
language_storage::{ModuleId, StructTag, TypeTag, CORE_CODE_ADDRESS}
language_storage::{ModuleId, StructTag, TypeTag, CORE_CODE_ADDRESS},
transaction::{EntryFunction, RawUserTransaction, TransactionArgument},
transaction::{Transaction, TransactionPayload, TransactionStatus},
};

#[derive(Default)]
Expand Down
6 changes: 3 additions & 3 deletions vm/e2e-tests/src/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use starcoin_crypto::ed25519::{Ed25519PrivateKey, Ed25519PublicKey};
use starcoin_crypto::keygen::KeyGen;
use starcoin_vm_types::access_path::AccessPath;
use starcoin_vm_types::account_address::AccountAddress;
use starcoin_vm_types::account_config::{genesis_address, AccountResource, BalanceResource};
use starcoin_vm_types::account_config::{genesis_address, AccountResource, CoinStoreResource};
use starcoin_vm_types::event::{EventHandle, EventKey};
use starcoin_vm_types::genesis_config::ChainId;
use starcoin_vm_types::language_storage::StructTag;
Expand Down Expand Up @@ -135,7 +135,7 @@ impl Account {
pub fn make_coin_store_access_path(&self) -> AccessPath {
// TODO(BobOng):
// self.make_access_path(CoinStoreResource::struct_tag())
self.make_access_path(BalanceResource::struct_tag())
self.make_access_path(CoinStoreResource::struct_tag())
}

// TODO: plug in the account type
Expand Down Expand Up @@ -619,7 +619,7 @@ impl AccountData {
.simple_serialize(&CoinStore::layout())
.unwrap();
write_set.push((
StateKey::resource_typed::<BalanceResource>(self.address()).unwrap(),
StateKey::resource_typed::<CoinStoreResource>(self.address()).unwrap(),
WriteOp::legacy_modification(balance.into()),
));

Expand Down
6 changes: 3 additions & 3 deletions vm/e2e-tests/src/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use starcoin_vm_runtime::VMExecutor;
use starcoin_vm_types::{
account_address::AccountAddress,
account_config::block::NewBlockEvent,
account_config::{AccountResource, BalanceResource, CORE_CODE_ADDRESS},
account_config::{AccountResource, CoinStoreResource, CORE_CODE_ADDRESS},
block_metadata::BlockMetadata,
errors::Location,
genesis_config::ChainId,
Expand Down Expand Up @@ -297,7 +297,7 @@ impl FakeExecutor {
}

/// Reads the CoinStore resource value for an account from this executor's data store.
pub fn read_coin_store_resource(&self, account: &Account) -> Option<BalanceResource> {
pub fn read_coin_store_resource(&self, account: &Account) -> Option<CoinStoreResource> {
self.read_coin_store_resource_at_address(account.address())
}

Expand All @@ -306,7 +306,7 @@ impl FakeExecutor {
pub fn read_coin_store_resource_at_address(
&self,
addr: &AccountAddress,
) -> Option<BalanceResource> {
) -> Option<CoinStoreResource> {
self.read_resource(addr)
}

Expand Down
6 changes: 3 additions & 3 deletions vm/starcoin-transactional-test-harness/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ use starcoin_vm_types::transaction::authenticator::AccountPrivateKey;
use starcoin_vm_types::transaction::SignedUserTransaction;
use starcoin_vm_types::write_set::{WriteOp, WriteSetMut};
use starcoin_vm_types::{
account_config::BalanceResource,
account_config::CoinStoreResource,
block_metadata::BlockMetadata,
genesis_config::ChainId,
on_chain_config::VMConfig,
Expand Down Expand Up @@ -497,9 +497,9 @@ impl<'a> StarcoinTestAdapter<'a> {
&self,
signer_addr: &AccountAddress,
balance_currency_code: String,
) -> Result<BalanceResource> {
) -> Result<CoinStoreResource> {
let token_code = TokenCode::from_str(balance_currency_code.as_str())?;
let balance_resource_tag = BalanceResource::struct_tag_for_token(token_code.try_into()?);
let balance_resource_tag = CoinStoreResource::struct_tag_for_token(token_code.try_into()?);
let balance_access_key = StateKey::resource(signer_addr, &balance_resource_tag)?;

let balance_blob = self
Expand Down
80 changes: 0 additions & 80 deletions vm/types/src/account_config/resources/balance.rs

This file was deleted.

41 changes: 37 additions & 4 deletions vm/types/src/account_config/resources/coin_store.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
// Copyright © Aptos Foundation
// SPDX-License-Identifier: Apache-2.0

use crate::{event::EventHandle, utility_coin::STARCOIN_COIN_TYPE};
use move_core_types::{
ident_str,
identifier::IdentStr,
language_storage::TypeTag,
identifier::{IdentStr, Identifier},
language_storage::{StructTag, TypeTag, CORE_CODE_ADDRESS},
move_resource::{MoveResource, MoveStructType},
};

use serde::{Deserialize, Serialize};

use crate::access_path::{AccessPath, DataPath};
use crate::account_config::token_code::TokenCode;
use crate::{event::EventHandle, utility_coin::STARCOIN_COIN_TYPE};

/// The balance resource held under an account.
#[derive(Debug, Serialize, Deserialize)]
pub struct CoinStoreResource {
Expand Down Expand Up @@ -50,6 +52,37 @@ impl CoinStoreResource {
pub fn withdraw_events(&self) -> &EventHandle {
&self.withdraw_events
}

// TODO/XXX: remove this once the MoveResource trait allows type arguments to `struct_tag`.
pub fn struct_tag_for_token(token_type_tag: StructTag) -> StructTag {
StructTag {
address: CORE_CODE_ADDRESS,
name: Self::struct_identifier(),
module: Self::module_identifier(),
type_args: vec![TypeTag::Struct(Box::new(token_type_tag))],
}
}

// TODO: remove this once the MoveResource trait allows type arguments to `resource_path`.
pub fn access_path_for(token_type_tag: StructTag) -> DataPath {
AccessPath::resource_data_path(Self::struct_tag_for_token(token_type_tag))
}

/// Get token code from Balance StructTag, return None if struct tag is not a valid Balance StructTag
pub fn token_code(struct_tag: &StructTag) -> Option<TokenCode> {
if struct_tag.address == CORE_CODE_ADDRESS
&& struct_tag.module == Identifier::from(Self::MODULE_NAME)
&& struct_tag.name == Identifier::from(Self::STRUCT_NAME)
{
if let Some(TypeTag::Struct(token_tag)) = struct_tag.type_args.first() {
Some((*(token_tag.clone())).into())
} else {
None
}
} else {
None
}
}
}

impl MoveStructType for CoinStoreResource {
Expand Down
Loading

0 comments on commit 340c59b

Please sign in to comment.