Skip to content

Commit

Permalink
Revised return values
Browse files Browse the repository at this point in the history
  • Loading branch information
DOBEN committed Oct 17, 2023
1 parent 90ec7d7 commit ae2dd29
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 56 deletions.
2 changes: 1 addition & 1 deletion templates/default/deploy-scripts/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,4 @@ tokio = {version = "1.18", features = ["rt", "macros", "rt-multi-thread"] }
clap = { version = "4", features = ["derive", "env"]}
concordium-rust-sdk="2.4"
itertools = "0.11.0"
{{crate_name}} = {path = "../"}
default = {path = "../"}
79 changes: 35 additions & 44 deletions templates/default/deploy-scripts/src/deployer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,6 @@ use concordium_rust_sdk::{
};
use std::path::Path;

/// A struct representing a smart contract instance on the chain.
#[derive(Clone, Debug)]
pub struct ContractInitialized {
/// Smart contract address on the chain.
pub contract: ContractAddress,
}

/// A struct containing connection and wallet information.
#[derive(Debug)]
pub struct Deployer {
Expand All @@ -39,10 +32,7 @@ pub struct Deployer {

impl Deployer {
/// A function to create a new deployer instance from a network client and a path to the wallet.
pub fn new(
client: v2::Client,
wallet_account_file: &Path,
) -> Result<Deployer, DeployError> {
pub fn new(client: v2::Client, wallet_account_file: &Path) -> Result<Deployer, DeployError> {
let key_data = WalletAccount::from_json_file(wallet_account_file)
.context("Unable to read wallet file.")?;

Expand Down Expand Up @@ -85,7 +75,14 @@ impl Deployer {
wasm_module: WasmModule,
expiry: Option<TransactionTime>,
logging: bool,
) -> Result<(Option<TransactionHash>, ModuleReference), DeployError> {
) -> Result<
(
Option<TransactionHash>,
Option<BlockItemSummary>,
ModuleReference,
),
DeployError,
> {
if logging {
println!("\nDeploying module....");
}
Expand All @@ -101,7 +98,7 @@ impl Deployer {
module_reference
);
}
return Ok((None, module_reference));
return Ok((None, None, module_reference));
}

let nonce = self.get_nonce(self.key.address).await?;
Expand Down Expand Up @@ -136,7 +133,7 @@ impl Deployer {

let (_, block_item) = self.client.wait_until_finalized(&tx_hash).await?;

let module_reference = self.check_outcome_of_deploy_transaction(block_item)?;
self.check_outcome_of_deploy_transaction(&block_item)?;

if logging {
println!(
Expand All @@ -145,7 +142,7 @@ impl Deployer {
);
}

Ok((Some(tx_hash), module_reference))
Ok((Some(tx_hash), Some(block_item), module_reference))
}

/// A function to initialize a smart contract instance on the chain.
Expand All @@ -163,7 +160,7 @@ impl Deployer {
energy: Option<Energy>,
expiry: Option<TransactionTime>,
logging: bool,
) -> Result<(TransactionHash, ContractAddress), DeployError> {
) -> Result<(TransactionHash, BlockItemSummary, ContractAddress), DeployError> {
if logging {
println!("\nInitializing contract....");
}
Expand Down Expand Up @@ -204,16 +201,16 @@ impl Deployer {

let (_, block_item) = self.client.wait_until_finalized(&tx_hash).await?;

let contract_init = self.check_outcome_of_initialization_transaction(block_item)?;
let contract_address = self.check_outcome_of_initialization_transaction(&block_item)?;

if logging {
println!(
"Transaction finalized: tx_hash={} contract=({}, {})",
tx_hash, contract_init.contract.index, contract_init.contract.subindex,
tx_hash, contract_address.index, contract_address.subindex,
);
}

Ok((tx_hash, contract_init.contract))
Ok((tx_hash, block_item, contract_address))
}

/// A function to update a smart contract instance on the chain.
Expand All @@ -232,7 +229,7 @@ impl Deployer {
energy: Option<GivenEnergy>,
expiry: Option<TransactionTime>,
logging: bool,
) -> Result<TransactionHash, DeployError> {
) -> Result<(TransactionHash, BlockItemSummary), DeployError> {
if logging {
println!("\nUpdating contract....");
}
Expand Down Expand Up @@ -276,13 +273,13 @@ impl Deployer {

let (_, block_item) = self.client.wait_until_finalized(&tx_hash).await?;

self.check_outcome_of_update_transaction(block_item)?;
self.check_outcome_of_update_transaction(&block_item)?;

if logging {
println!("Transaction finalized: tx_hash={}", tx_hash,);
}

Ok(tx_hash)
Ok((tx_hash, block_item))
}

/// A function to estimate the energy needed to send a transaction on the
Expand Down Expand Up @@ -336,15 +333,15 @@ impl Deployer {
/// It returns the error code if the transaction reverted.
fn check_outcome_of_deploy_transaction(
&self,
block_item: BlockItemSummary,
) -> Result<ModuleReference, DeployError> {
match block_item.details {
BlockItemSummaryDetails::AccountTransaction(a) => match a.effects {
block_item: &BlockItemSummary,
) -> Result<(), DeployError> {
match &block_item.details {
BlockItemSummaryDetails::AccountTransaction(a) => match &a.effects {
AccountTransactionEffects::None {
transaction_type,
reject_reason,
} => {
if transaction_type != Some(TransactionType::DeployModule) {
if *transaction_type != Some(TransactionType::DeployModule) {
return Err(DeployError::InvalidBlockItem(
"Expected transaction type to be DeployModule".into(),
));
Expand All @@ -354,9 +351,7 @@ impl Deployer {
"Module deploy rejected with reason: {reject_reason:?}"
)))
}
AccountTransactionEffects::ModuleDeployed { module_ref } => {
Ok( module_ref )
}
AccountTransactionEffects::ModuleDeployed { module_ref: _ } => Ok(()),
_ => Err(DeployError::InvalidBlockItem(
"The parsed account transaction effect should be of type `ModuleDeployed` or \
`None` (in case the transaction reverted)"
Expand All @@ -376,15 +371,15 @@ impl Deployer {
/// It returns the error code if the transaction reverted.
fn check_outcome_of_initialization_transaction(
&self,
block_item: BlockItemSummary,
) -> Result<ContractInitialized, DeployError> {
match block_item.details {
BlockItemSummaryDetails::AccountTransaction(a) => match a.effects {
block_item: &BlockItemSummary,
) -> Result<ContractAddress, DeployError> {
match &block_item.details {
BlockItemSummaryDetails::AccountTransaction(a) => match &a.effects {
AccountTransactionEffects::None {
transaction_type,
reject_reason,
} => {
if transaction_type != Some(TransactionType::InitContract) {
if *transaction_type != Some(TransactionType::InitContract) {
return Err(DeployError::InvalidBlockItem(
"Expected transaction type to be InitContract".into(),
));
Expand All @@ -394,11 +389,7 @@ impl Deployer {
"Contract init rejected with reason: {reject_reason:?}"
)))
}
AccountTransactionEffects::ContractInitialized { data } => {
Ok(ContractInitialized {
contract: data.address,
})
}
AccountTransactionEffects::ContractInitialized { data } => Ok(data.address),
_ => Err(DeployError::InvalidBlockItem(
"The parsed account transaction effect should be of type \
`ContractInitialized` or `None` (in case the transaction reverted)"
Expand All @@ -418,15 +409,15 @@ impl Deployer {
/// It returns the error code if the transaction reverted.
fn check_outcome_of_update_transaction(
&self,
block_item: BlockItemSummary,
block_item: &BlockItemSummary,
) -> Result<(), DeployError> {
match block_item.details {
BlockItemSummaryDetails::AccountTransaction(a) => match a.effects {
match &block_item.details {
BlockItemSummaryDetails::AccountTransaction(a) => match &a.effects {
AccountTransactionEffects::None {
transaction_type,
reject_reason,
} => {
if transaction_type != Some(TransactionType::Update) {
if *transaction_type != Some(TransactionType::Update) {
return Err(DeployError::InvalidBlockItem(
"Expected transaction type to be Update".into(),
));
Expand Down
33 changes: 22 additions & 11 deletions templates/default/deploy-scripts/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use concordium_rust_sdk::{
types::{OwnedContractName, OwnedParameter, OwnedReceiveName},
},
types::{
smart_contracts::{ExceedsParameterSize, WasmModule, ModuleReference},
smart_contracts::{ExceedsParameterSize, ModuleReference, WasmModule},
transactions,
transactions::send::GivenEnergy,
},
Expand Down Expand Up @@ -76,6 +76,8 @@ fn get_wasm_module(file: &Path) -> Result<WasmModule, DeployError> {
Ok(wasm_module)
}

//wasm_module.get_module_ref();

/// Command line flags.
#[derive(clap::Parser, Debug)]
#[clap(author, version, about)]
Expand All @@ -85,20 +87,20 @@ struct App {
default_value = "http://node.testnet.concordium.com:20000",
help = "V2 API of the Concordium node."
)]
url: v2::Endpoint,
url: v2::Endpoint,
#[clap(
long = "account",
help = "Path to the file containing the Concordium account keys exported from the wallet \
(e.g. ./myPath/3PXwJYYPf6fyVb4GJquxSZU8puxrHfzc4XogdMVot8MUQK53tW.export)."
)]
key_file: PathBuf,
key_file: PathBuf,
#[clap(
long = "module",
help = "Path of the Concordium smart contract module. Use this flag several times if you \
have several smart contract modules to be deployed (e.g. --module \
./myPath/default.wasm.v1 --module ./default2.wasm.v1)."
)]
module: Vec<PathBuf>,
module: Vec<PathBuf>,
#[clap(
long = "no_logging",
help = "To specify if verbose logging should be disabled when running the script."
Expand All @@ -116,14 +118,16 @@ async fn main() -> Result<(), DeployError> {

let concordium_client = v2::Client::new(app.url).await?;

let mut deployer = Deployer::new( concordium_client, &app.key_file)?;
let mut deployer = Deployer::new(concordium_client, &app.key_file)?;

let mut modules_deployed: Vec<ModuleReference> = Vec::new();

for contract in app.module.iter().unique() {
let wasm_module = get_wasm_module(contract.as_path())?;

let (_, module) = deployer.deploy_wasm_module(wasm_module, None, !app.no_logging).await?;
let (_, _, module) = deployer
.deploy_wasm_module(wasm_module, None, !app.no_logging)
.await?;

modules_deployed.push(module);
}
Expand All @@ -142,7 +146,9 @@ async fn main() -> Result<(), DeployError> {
param,
}; // Example

let (_, contract) = deployer.init_contract(payload, None, None, !app.no_logging).await?; // Example
let (_, _, contract) = deployer
.init_contract(payload, None, None, !app.no_logging)
.await?; // Example

// This is how you can use a type from your smart contract.
use {{crate_name}}::MyInputType; // Example
Expand All @@ -154,10 +160,10 @@ async fn main() -> Result<(), DeployError> {
let bytes = contracts_common::to_bytes(&input_parameter); // Example

let update_payload = transactions::UpdateContractPayload {
amount: Amount::from_ccd(0),
address: contract,
amount: Amount::from_ccd(0),
address: contract,
receive_name: OwnedReceiveName::new_unchecked("{{crate_name}}.receive".to_string()),
message: bytes.try_into()?,
message: bytes.try_into()?,
}; // Example

let mut energy = deployer.estimate_energy(update_payload.clone()).await?; // Example
Expand All @@ -166,7 +172,12 @@ async fn main() -> Result<(), DeployError> {
energy.energy += 100; // Example

let _update_contract = deployer
.update_contract(update_payload, Some(GivenEnergy::Add(energy)), None, !app.no_logging)
.update_contract(
update_payload,
Some(GivenEnergy::Add(energy)),
None,
!app.no_logging,
)
.await?; // Example

// Write your own deployment/initialization script above. An example is given
Expand Down

0 comments on commit ae2dd29

Please sign in to comment.