Skip to content

Commit

Permalink
refactor: centralize account loading
Browse files Browse the repository at this point in the history
  • Loading branch information
xJonathanLEI committed Sep 1, 2023
1 parent 055013b commit aa62521
Show file tree
Hide file tree
Showing 4 changed files with 74 additions and 97 deletions.
55 changes: 53 additions & 2 deletions src/account.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,23 @@
use std::fmt::Display;
use std::{fmt::Display, path::PathBuf};

use anyhow::Result;
use clap::Parser;
use serde::{Deserialize, Serialize};
use serde_with::serde_as;
use starknet::{
accounts::SingleOwnerAccount,
core::{
serde::unsigned_field_element::UfeHex, types::FieldElement, utils::get_contract_address,
serde::unsigned_field_element::UfeHex,
types::{BlockId, BlockTag, FieldElement},
utils::get_contract_address,
},
macros::{felt, selector},
providers::Provider,
signers::Signer,
};

use crate::path::ExpandedPathbufParser;

const BRAAVOS_SIGNER_TYPE_STARK: FieldElement = FieldElement::ONE;

pub const KNOWN_ACCOUNT_CLASSES: [KnownAccountClass; 3] = [
Expand All @@ -30,6 +38,17 @@ pub const KNOWN_ACCOUNT_CLASSES: [KnownAccountClass; 3] = [
},
];

#[derive(Debug, Clone, Parser)]
pub struct AccountArgs {
#[clap(
long,
env = "STARKNET_ACCOUNT",
value_parser = ExpandedPathbufParser,
help = "Path to account config JSON file"
)]
account: PathBuf,
}

#[derive(Serialize, Deserialize)]
pub struct AccountConfig {
pub version: u64,
Expand Down Expand Up @@ -148,6 +167,38 @@ pub struct BraavosDeploymentContext {
pub mock_implementation: FieldElement,
}

impl AccountArgs {
pub async fn into_account<P, S>(
self,
provider: P,
signer: S,
) -> Result<SingleOwnerAccount<P, S>>
where
P: Provider + Send + Sync,
P::Error: 'static,
S: Signer + Send + Sync,
{
if !self.account.exists() {
anyhow::bail!("account config file not found");
}

let account_config: AccountConfig =
serde_json::from_reader(&mut std::fs::File::open(&self.account)?)?;

let account_address = match account_config.deployment {
DeploymentStatus::Undeployed(_) => anyhow::bail!("account not deployed"),
DeploymentStatus::Deployed(inner) => inner.address,
};

let chain_id = provider.chain_id().await?;

let mut account = SingleOwnerAccount::new(provider, signer, account_address, chain_id);
account.set_block_id(BlockId::Tag(BlockTag::Pending));

Ok(account)
}
}

impl AccountConfig {
pub fn deploy_account_address(&self) -> Result<FieldElement> {
let undeployed_status = match &self.deployment {
Expand Down
31 changes: 5 additions & 26 deletions src/subcommands/declare.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use anyhow::Result;
use clap::Parser;
use colored::Colorize;
use starknet::{
accounts::{Account, SingleOwnerAccount},
accounts::Account,
core::types::{
contract::{legacy::LegacyContractClass, CompiledClass, SierraClass},
BlockId, BlockTag, FieldElement, StarknetError,
Expand All @@ -13,7 +13,7 @@ use starknet::{
};

use crate::{
account::{AccountConfig, DeploymentStatus},
account::AccountArgs,
casm::{CasmArgs, CasmHashSource},
fee::{FeeArgs, FeeSetting},
path::ExpandedPathbufParser,
Expand All @@ -30,14 +30,9 @@ pub struct Declare {
#[clap(flatten)]
signer: SignerArgs,
#[clap(flatten)]
account: AccountArgs,
#[clap(flatten)]
casm: CasmArgs,
#[clap(
long,
env = "STARKNET_ACCOUNT",
value_parser = ExpandedPathbufParser,
help = "Path to account config JSON file"
)]
account: PathBuf,
#[clap(flatten)]
fee: FeeArgs,
#[clap(long, help = "Wait for the transaction to confirm")]
Expand All @@ -59,24 +54,8 @@ impl Declare {

let provider = Arc::new(self.provider.into_provider());

if !self.account.exists() {
anyhow::bail!("account config file not found");
}

let account_config: AccountConfig =
serde_json::from_reader(&mut std::fs::File::open(&self.account)?)?;

let account_address = match account_config.deployment {
DeploymentStatus::Undeployed(_) => anyhow::bail!("account not deployed"),
DeploymentStatus::Deployed(inner) => inner.address,
};

let chain_id = provider.chain_id().await?;

let signer = self.signer.into_signer()?;
let mut account =
SingleOwnerAccount::new(provider.clone(), signer, account_address, chain_id);
account.set_block_id(BlockId::Tag(BlockTag::Pending));
let account = self.account.into_account(provider.clone(), signer).await?;

// Workaround for issue:
// https://github.com/eqlabs/pathfinder/issues/1208
Expand Down
43 changes: 9 additions & 34 deletions src/subcommands/deploy.rs
Original file line number Diff line number Diff line change
@@ -1,25 +1,23 @@
use std::{path::PathBuf, sync::Arc};
use std::sync::Arc;

use anyhow::Result;
use clap::Parser;
use colored::Colorize;
use starknet::{
accounts::SingleOwnerAccount,
accounts::Account,
contract::ContractFactory,
core::{
types::{BlockId, BlockTag, FieldElement},
types::FieldElement,
utils::{get_udc_deployed_address, UdcUniqueSettings, UdcUniqueness},
},
providers::Provider,
signers::SigningKey,
};

use crate::{
account::{AccountConfig, DeploymentStatus},
account::AccountArgs,
address_book::AddressBookResolver,
decode::FeltDecoder,
fee::{FeeArgs, FeeSetting},
path::ExpandedPathbufParser,
signer::SignerArgs,
utils::watch_tx,
verbosity::VerbosityArgs,
Expand All @@ -40,15 +38,10 @@ pub struct Deploy {
provider: ProviderArgs,
#[clap(flatten)]
signer: SignerArgs,
#[clap(flatten)]
account: AccountArgs,
#[clap(long, help = "Do not derive contract address from deployer address")]
not_unique: bool,
#[clap(
long,
env = "STARKNET_ACCOUNT",
value_parser = ExpandedPathbufParser,
help = "Path to account config JSON file"
)]
account: PathBuf,
#[clap(flatten)]
fee: FeeArgs,
#[clap(long, help = "Use the given salt to compute contract deploy address")]
Expand All @@ -72,10 +65,6 @@ impl Deploy {
let provider = Arc::new(self.provider.into_provider());
let felt_decoder = FeltDecoder::new(AddressBookResolver::new(provider.clone()));

if !self.account.exists() {
anyhow::bail!("account config file not found");
}

let class_hash = FieldElement::from_hex_be(&self.class_hash)?;
let mut ctor_args = vec![];
for element in self.ctor_args.iter() {
Expand All @@ -88,15 +77,8 @@ impl Deploy {
SigningKey::from_random().secret_scalar()
};

// TODO: refactor account & signer loading

let account_config: AccountConfig =
serde_json::from_reader(&mut std::fs::File::open(&self.account)?)?;

let account_address = match account_config.deployment {
DeploymentStatus::Undeployed(_) => anyhow::bail!("account not deployed"),
DeploymentStatus::Deployed(inner) => inner.address,
};
let signer = Arc::new(self.signer.into_signer()?);
let account = self.account.into_account(provider.clone(), signer).await?;

let deployed_address = get_udc_deployed_address(
salt,
Expand All @@ -105,20 +87,13 @@ impl Deploy {
UdcUniqueness::NotUnique
} else {
UdcUniqueness::Unique(UdcUniqueSettings {
deployer_address: account_address,
deployer_address: account.address(),
udc_contract_address: DEFAULT_UDC_ADDRESS,
})
},
&ctor_args,
);

let chain_id = provider.chain_id().await?;

let signer = Arc::new(self.signer.into_signer()?);
let mut account =
SingleOwnerAccount::new(provider.clone(), signer.clone(), account_address, chain_id);
account.set_block_id(BlockId::Tag(BlockTag::Pending));

// TODO: allow custom UDC
let factory = ContractFactory::new_with_udc(class_hash, account, DEFAULT_UDC_ADDRESS);

Expand Down
42 changes: 7 additions & 35 deletions src/subcommands/invoke.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,18 @@
use std::{path::PathBuf, sync::Arc};
use std::sync::Arc;

use anyhow::Result;
use clap::Parser;
use colored::Colorize;
use starknet::{
accounts::{Account, Call, SingleOwnerAccount},
core::{
types::{BlockId, BlockTag, FieldElement},
utils::get_selector_from_name,
},
providers::Provider,
accounts::{Account, Call},
core::{types::FieldElement, utils::get_selector_from_name},
};

use crate::{
account::{AccountConfig, DeploymentStatus},
account::AccountArgs,
address_book::AddressBookResolver,
decode::FeltDecoder,
fee::{FeeArgs, FeeSetting},
path::ExpandedPathbufParser,
signer::SignerArgs,
utils::watch_tx,
verbosity::VerbosityArgs,
Expand All @@ -30,13 +25,8 @@ pub struct Invoke {
provider: ProviderArgs,
#[clap(flatten)]
signer: SignerArgs,
#[clap(
long,
env = "STARKNET_ACCOUNT",
value_parser = ExpandedPathbufParser,
help = "Path to account config JSON file"
)]
account: PathBuf,
#[clap(flatten)]
account: AccountArgs,
#[clap(flatten)]
fee: FeeArgs,
#[clap(long, help = "Wait for the transaction to confirm")]
Expand All @@ -56,10 +46,6 @@ impl Invoke {
let provider = Arc::new(self.provider.into_provider());
let felt_decoder = FeltDecoder::new(AddressBookResolver::new(provider.clone()));

if !self.account.exists() {
anyhow::bail!("account config file not found");
}

// Parses and resolves the calls
let calls = {
// TODO: show more helpful message
Expand Down Expand Up @@ -100,22 +86,8 @@ impl Invoke {
anyhow::bail!("empty execution");
}

// TODO: refactor account & signer loading

let account_config: AccountConfig =
serde_json::from_reader(&mut std::fs::File::open(&self.account)?)?;

let account_address = match account_config.deployment {
DeploymentStatus::Undeployed(_) => anyhow::bail!("account not deployed"),
DeploymentStatus::Deployed(inner) => inner.address,
};

let chain_id = provider.chain_id().await?;

let signer = Arc::new(self.signer.into_signer()?);
let mut account =
SingleOwnerAccount::new(provider.clone(), signer, account_address, chain_id);
account.set_block_id(BlockId::Tag(BlockTag::Pending));
let account = self.account.into_account(provider.clone(), signer).await?;

let execution = account.execute(calls).fee_estimate_multiplier(1.5f64);

Expand Down

0 comments on commit aa62521

Please sign in to comment.