Skip to content

Commit

Permalink
cleanup and readme
Browse files Browse the repository at this point in the history
info messages
  • Loading branch information
miloszm committed Aug 6, 2024
1 parent b6f716c commit ac8788e
Show file tree
Hide file tree
Showing 9 changed files with 90 additions and 61 deletions.
6 changes: 4 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

## [0.1.1] - 2023-12-01
## [0.1.0] - 2024-08-06

### Added

- Add initial Moat implementation.
- Add initial dusk-deploy-cli implementation. [#1]

<!-- ISSUES -->
[#1]: https://github.com/dusk-network/dusk-deploy-cli/issues/1


<!-- VERSIONS -->
[Unreleased]: https://github.com/dusk-network/dusk-deploy-cli/compare/v0.1.0...HEAD
Expand Down
45 changes: 44 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,49 @@
# dusk-deploy-cli
Tool for smart contracts' deployment to Dusk blockchain.

Minimal set of arguments, long argument names:
```sh
cargo r --release --
cargo r -- --contract-path ./test/alice.wasm --seed "spice property autumn primary undo innocent pole legend stereo mom eternal topic"
```

Minimal set of arguments, short argument names:
```sh
cargo r -- -c ./test/alice.wasm -s "spice property autumn primary undo innocent pole legend stereo mom eternal topic"
```

Full set of arguments:
```sh
cargo r -- --contract-path=./test/bob.wasm --seed="spice property autumn primary undo innocent pole legend stereo mom eternal topic" --config-path=./config.toml --gas-limit=100000000 --gas-price=1 --owner="2e3f56b01f7a43c274714a6d22b93164d561f1247a8cfa7a79eede21420438aa" --nonce=0 --args="3e"
```


```
ARGUMENTS:
-c, --contract-path Path to contract bytecode file (.wasm) to be deployed
-s, --seed Seed mneumonic phrase, a string of 12 words encoding your secret and public keys
, --config-path Path to config file containing data needed to establish blockchain connection
, --gas-limit Maximum number of gas points allowed to be used when executing the deployment transaction,
if omitted, a 500_000_000 default will be used
--gas-price Gas price to be used when executing the deployment transaction,
if omitted, price value 1 will be used
-o, --owner Hexadecimal string representing the owner of the contract
-n, --nonce Number used when calculating contract is, used when there is a need to deploy
multiple contracts with the same bytecode and owner, and/or to obtain
a vanity contract did,
if omittted, 0 will be used
-a, --args Optional argument passed to contract's constructor. Contract may have a constructor
method named 'init' which will be executed automatically upon deployment and may accept
arguments. Argument must be passed in a form of a hexadecimal string representing an
rkyv serialization of the argument proper. Multiple arguments are serialized as a tuple.
If omitted, no argument will be passed to the constructor. If contract does not have a
constructor, this argument may be omitted.
```

Example configuration file for blockchain connection:

```
rusk_address = "http://127.0.0.1:8080"
prover_address = "http://127.0.0.1:8080"
```
10 changes: 7 additions & 3 deletions dusk-deploy-cli/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ pub struct Args {
pub config_path: PathBuf,

/// Seed phrase [default: ``]
#[clap(long, default_value_t = String::from("spice property autumn primary undo innocent pole legend stereo mom eternal topic"))]
#[clap(short, long, default_value_t = String::from(""))]
pub seed: String,

/// Gas limit [default: `500000000`]
Expand All @@ -29,14 +29,18 @@ pub struct Args {
pub gas_price: u64,

/// Path to contract code
#[clap(short, long, default_value = "./test/bob.wasm")]
#[clap(short, long, default_value = "")]
pub contract_path: PathBuf,

/// Hexadecimal string of contract's owner [default: ``]
#[clap(short, long, default_value_t = String::from(""))]
pub owner: String,

/// Nonce [default: `0`]
#[clap(long, default_value_t = 0)]
#[clap(short, long, default_value_t = 0)]
pub nonce: u64,

/// Hexadecimal string of contract's constructor arguments [default: ``]
#[clap(short, long, default_value_t = String::from(""))]
pub args: String,
}
3 changes: 2 additions & 1 deletion dusk-deploy-cli/src/dcli_prover_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use execution_core::transfer::Transaction;
use rusk_http_client::{RuskHttpClient, RuskRequest};
use rusk_prover::UnprovenTransaction;
use std::fmt::Debug;
use tracing::info;

pub struct DCliProverClient {
state: RuskHttpClient,
Expand All @@ -24,7 +25,7 @@ impl DCliProverClient {
DCliProverClient {
state,
prover,
status: |a| println!("{}", a),
status: |a| info!("{}", a),
}
}

Expand Down
12 changes: 4 additions & 8 deletions dusk-deploy-cli/src/dcli_state_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use std::sync::{Arc, RwLock};
use tracing::info;
use wallet::StateClient;

pub const CONTRACT_ID_BYTES: usize = 32;
const CONTRACT_ID_BYTES: usize = 32;

#[inline]
const fn reserved(b: u8) -> ContractId {
Expand All @@ -28,12 +28,11 @@ const fn reserved(b: u8) -> ContractId {
bytes
}

/// ID of the genesis transfer contract
pub const TRANSFER_CONTRACT: ContractId = reserved(0x1);
const TRANSFER_CONTRACT: ContractId = reserved(0x1);

pub const POSEIDON_TREE_DEPTH: usize = 17; // todo
const POSEIDON_TREE_DEPTH: usize = 17;

pub const TRANSFER_CONTRACT_STR: &str =
const TRANSFER_CONTRACT_STR: &str =
"0100000000000000000000000000000000000000000000000000000000000000";

const ITEM_LEN: usize = mem::size_of::<TreeLeaf>();
Expand Down Expand Up @@ -100,17 +99,14 @@ impl StateClient for DCliStateClient {
"leaves_from_height",
)
.wait()?;
println!("obtained stream");
StreamAux::find_items::<TreeLeaf, ITEM_LEN>(
|leaf| {
if vk.owns(leaf.note.stealth_address()) {
println!("owned note value={:?}", leaf.note.value(None));
response_notes.push((leaf.block_height, leaf.note.clone()))
}
},
&mut stream,
)?;
println!("after find items, notes size={}", response_notes.len());

for (block_height, note) in response_notes {
// Filter out duplicated notes and update the last
Expand Down
1 change: 0 additions & 1 deletion dusk-deploy-cli/src/dcli_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ impl Store for DCliStore {
type Error = ();

fn get_seed(&self) -> Result<[u8; 64], Self::Error> {
println!("seed={}", hex::encode(self.seed.clone()));
Ok(self.seed.clone())
}
}
5 changes: 4 additions & 1 deletion dusk-deploy-cli/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,14 @@ pub enum Error {
#[error("Prover error occurred: {0:?}")]
Prover(Arc<rusk_prover::ProverError>),
/// Wallet Errors
#[error("Wallet error occurred")] // todo
#[error("Wallet error occurred")]
Wallet(Arc<wallet::Error<DCliStore, DCliStateClient, DCliProverClient>>),
/// Seed phrase is not valid
#[error("Invalid recovery phrase")]
InvalidMnemonicPhrase,
/// Tracing errors
#[error("Tracing error")]
Tracing,
}

impl From<wallet::Error<DCliStore, DCliStateClient, DCliProverClient>> for Error {
Expand Down
63 changes: 24 additions & 39 deletions dusk-deploy-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,22 @@ use crate::config::BlockchainAccessConfig;
use crate::error::Error;
use bip39::{Language, Mnemonic, Seed};
use clap::Parser;
use execution_core::transfer::ContractId;
use rusk_http_client::{ContractInquirer, RuskHttpClient};
use std::fs::File;
use std::io::Read;
use std::thread;
use toml_base_config::BaseConfig;
use tracing::info;

use crate::deployer::Deployer;
use crate::gen_id::gen_contract_id;

#[tokio::main]
#[allow(non_snake_case)]
async fn main() -> Result<(), Error> {
let subscriber = tracing_subscriber::fmt::Subscriber::builder()
.with_writer(std::io::stderr)
.finish();
tracing::subscriber::set_global_default(subscriber).map_err(|_| Error::Tracing)?;

let cli = Args::parse();

let config_path = cli.config_path.as_path();
Expand All @@ -42,28 +45,23 @@ async fn main() -> Result<(), Error> {
let contract_path = cli.contract_path.as_path();
let owner = cli.owner;
let nonce = cli.nonce;
let args = cli.args;

let blockchain_access_config = BlockchainAccessConfig::load_path(config_path)?;

let mut bytecode_file = File::open(contract_path)?;
let mut bytecode = Vec::new();
bytecode_file.read_to_end(&mut bytecode)?;

let constructor_args: Option<Vec<u8>> = Some(vec![38u8]);
let mut constructor_args: Option<Vec<u8>> = None;
if !args.is_empty() {
let v = hex::decode(args).expect("decoding constructore arguments should succeed");
constructor_args = Some(v);
}

let wallet_index = 0;

// let seed_vec = hex::decode("7965013909185294fa0f0d2a2be850ee89389e45d17e0c7da9a7588901648086c5b3ac52d95b6fd421104b6a77ca21772f0a041f031c3c8039ae3b24c48467bd")
// .expect("decoding seed should succeed");
// let mut seed = [0u8; 64];
// seed.copy_from_slice(seed_vec.as_slice());

let phrase = seed_phrase.to_string();
let mnemonic = Mnemonic::from_phrase(&phrase, Language::English)
.map_err(|_| Error::InvalidMnemonicPhrase)?;
let seed_obj = Seed::new(&mnemonic, "");
let mut seed = [0u8; 64];
seed.copy_from_slice(seed_obj.as_bytes());
let seed = seed_from_phrase(seed_phrase)?;

let owner = hex::decode(owner).expect("decoding owner should succeed");

Expand All @@ -80,35 +78,22 @@ async fn main() -> Result<(), Error> {
&seed,
);

println!(
"deployment result for contract: {:?} is: {:?}",
info!(
"Deployment result for contract {:?} is: {:?}",
contract_path, result
);
let deployed_id = gen_contract_id(bytecode, nonce, owner);
println!("deployed contract id: {}", hex::encode(&deployed_id));

verify_deployment(deployed_id, blockchain_access_config.rusk_address).await;
info!("Deployed contract id: {}", hex::encode(&deployed_id));

Ok(())
}

async fn verify_deployment(contract_id: [u8; 32], rusk_url: impl AsRef<str>) {
const METHOD: &str = "value";
println!(
"verifying deployment by calling contract's method: {}",
METHOD
);

thread::sleep(std::time::Duration::from_secs(10));

let client = RuskHttpClient::new(rusk_url.as_ref().to_string());
let r = ContractInquirer::query_contract::<(), u8>(
&client,
(),
ContractId::from(contract_id),
METHOD,
)
.await;

println!("result of calling the contract's method: {:?}", r);
// converts seed phrase into a binary seed
fn seed_from_phrase(phrase: impl AsRef<str>) -> Result<[u8; 64], Error> {
let mnemonic = Mnemonic::from_phrase(phrase.as_ref(), Language::English)
.map_err(|_| Error::InvalidMnemonicPhrase)?;
let seed_obj = Seed::new(&mnemonic, "");
let mut seed = [0u8; 64];
seed.copy_from_slice(seed_obj.as_bytes());
Ok(seed)
}
6 changes: 1 addition & 5 deletions wallet/src/imp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use core::convert::Infallible;
use alloc::string::FromUtf8Error;
use alloc::vec::Vec;

use dusk_bytes::{Error as BytesError, Serializable};
use dusk_bytes::Error as BytesError;
use execution_core::transfer::AccountData;
use execution_core::{
stake::StakeData,
Expand Down Expand Up @@ -241,7 +241,6 @@ where
),
Error<S, SC, PC>,
> {
println!("about to fetch nodes");
let notes = self.unspent_notes(sender_sk)?;
let mut notes_and_values = Vec::with_capacity(notes.len());

Expand Down Expand Up @@ -358,15 +357,12 @@ where
where
Rng: RngCore + CryptoRng,
{
println!("about to fetch secret key");
let sender_sk = self
.store
.fetch_secret_key(sender_index)
.map_err(Error::from_store_err)?;
let receiver_pk = PublicKey::from(&sender_sk);

println!("secret_key={}", hex::encode(sender_sk.to_bytes()));

self.phoenix_transaction(
rng,
&sender_sk,
Expand Down

0 comments on commit ac8788e

Please sign in to comment.