Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/main' into deposit-manager
Browse files Browse the repository at this point in the history
  • Loading branch information
marijanp committed Jul 4, 2024
2 parents 548157f + cea7a71 commit 9d341c2
Show file tree
Hide file tree
Showing 48 changed files with 1,144 additions and 261 deletions.
2 changes: 2 additions & 0 deletions .env
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,5 @@ KAIROS_SERVER_MAX_BATCH_SECONDS=60
RISC0_DEV_MODE=1;
# FIXME this is a dummy value that fixes a regression that prevented server startup
KAIROS_SERVER_CASPER_RPC="http://127.0.0.1:11101/rpc"
KAIROS_SERVER_CASPER_SSE="http://127.0.0.1:18101/events/main"
KAIROS_SERVER_DEMO_CONTRACT_HASH="0000000000000000000000000000000000000000000000000000000000000000"
4 changes: 4 additions & 0 deletions Cargo.lock

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

15 changes: 9 additions & 6 deletions demo-contract-tests/tests/integration_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ mod tests {
let mut fixture = TestContext::new(None);

let user = fixture.create_funded_user();
let user_balance_before = fixture.get_user_balance(user);
let user_account_hash = user.to_account_hash();
let user_balance_before = fixture.get_user_balance(user_account_hash);

// check that the contract balance is zero before depositing
let deposit_amount = U512::from(100000000000u64);
Expand All @@ -29,7 +30,7 @@ mod tests {
let contract_balance_after = fixture.get_contract_balance();
assert_eq!(contract_balance_after, deposit_amount);

let user_balance_after = fixture.get_user_balance(user);
let user_balance_after = fixture.get_user_balance(user_account_hash);
assert!(user_balance_after <= user_balance_before - deposit_amount);
}

Expand All @@ -38,10 +39,11 @@ mod tests {
let mut fixture = TestContext::new(None);

let user = fixture.create_funded_user();
let user_account_hash = user.to_account_hash();
let amount = U512::from(100000000000u64);
fixture.deposit_succeeds(user, amount);

fixture.transfer_from_contract_purse_to_user_fails(user, amount)
fixture.transfer_from_contract_purse_to_user_fails(user_account_hash, amount)
}

#[test]
Expand All @@ -50,7 +52,7 @@ mod tests {

let user = fixture.create_funded_user();
let amount = U512::from(100000000000u64);
fixture.deposit_succeeds(user, amount);
fixture.deposit_succeeds(user.clone(), amount);

fixture.transfer_from_contract_purse_to_user_fails(fixture.admin, amount)
}
Expand All @@ -59,10 +61,11 @@ mod tests {
fn test_transfer_from_contract_purse_by_uref_to_user_fails() {
let mut fixture = TestContext::new(None);
let user = fixture.create_funded_user();
let user_account_hash = user.to_account_hash();
let amount = U512::from(100000000000u64);
fixture.deposit_succeeds(user, amount);
fixture.deposit_succeeds(user.clone(), amount);

fixture.transfer_from_contract_purse_by_uref_to_user_fails(user, amount)
fixture.transfer_from_contract_purse_by_uref_to_user_fails(user_account_hash, amount)
}

#[test]
Expand Down
18 changes: 11 additions & 7 deletions demo-contract-tests/tests/test_fixture/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ impl TestContext {
let mut builder = InMemoryWasmTestBuilder::default();
builder.run_genesis(&PRODUCTION_RUN_GENESIS_REQUEST);

let admin = create_funded_account_for_secret_key_bytes(&mut builder, ADMIN_SECRET_KEY);
let admin = create_funded_account_for_secret_key_bytes(&mut builder, ADMIN_SECRET_KEY)
.to_account_hash();
let contract_path = get_wasm_directory().0.join("demo-contract-optimized.wasm");
run_session_with_args(
&mut builder,
Expand Down Expand Up @@ -71,7 +72,7 @@ impl TestContext {
}
}

pub fn create_funded_user(&mut self) -> AccountHash {
pub fn create_funded_user(&mut self) -> PublicKey {
let mut random_secret_key: [u8; 32] = rand::random();
while random_secret_key == ADMIN_SECRET_KEY {
random_secret_key = rand::random();
Expand All @@ -88,18 +89,21 @@ impl TestContext {
self.builder.get_purse_balance(self.contract_purse)
}

pub fn deposit_succeeds(&mut self, depositor: AccountHash, amount: U512) {
pub fn deposit_succeeds(&mut self, depositor: PublicKey, amount: U512) {
let account_hash = depositor.to_account_hash();

let deposit_session_path = get_wasm_directory()
.1
.join("deposit-session-optimized.wasm");
let session_args = runtime_args! {
"amount" => amount,
"demo_contract" => self.contract_hash
"demo_contract" => self.contract_hash,
"recipient" => depositor,
};
run_session_with_args(
&mut self.builder,
deposit_session_path.as_path(),
depositor,
account_hash,
session_args,
);
self.builder.expect_success();
Expand Down Expand Up @@ -181,7 +185,7 @@ pub fn run_session_with_args(
pub fn create_funded_account_for_secret_key_bytes(
builder: &mut WasmTestBuilder<InMemoryGlobalState>,
account_secret_key_bytes: [u8; 32],
) -> AccountHash {
) -> PublicKey {
let account_secret_key = SecretKey::ed25519_from_bytes(account_secret_key_bytes).unwrap();
let account_public_key = PublicKey::from(&account_secret_key);
let account_hash = account_public_key.to_account_hash();
Expand All @@ -195,5 +199,5 @@ pub fn create_funded_account_for_secret_key_bytes(
)
.build();
builder.exec(transfer).expect_success().commit();
account_hash
account_public_key
}
16 changes: 16 additions & 0 deletions flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,18 @@
];
craneLib = inputs.crane.lib.${system}.overrideToolchain rustToolchain;

# TODO reuse in nixos tests
cctlConfig = {
chainspec = pkgs.fetchurl {
url = "https://raw.githubusercontent.com/cspr-rad/casper-node/53136ac5f004f2ae70a75b4eeb2ff7d907aff6aa/resources/local/chainspec.toml.in";
hash = "sha256-b/6c5o3JXFlaTgTHxs8JepaHzjMG75knzlKKqRd/7pc=";
};
config = pkgs.fetchurl {
url = "https://raw.githubusercontent.com/cspr-rad/casper-node/53136ac5f004f2ae70a75b4eeb2ff7d907aff6aa/resources/local/config.toml";
hash = "sha256-ZuNbxw0nBjuONEZRK8Ru96zZQak4MEQ/eM1fA6esyCM=";
};
};

kairosContractsAttrs = {
src = lib.cleanSourceWith {
src = lib.fileset.toSource {
Expand Down Expand Up @@ -149,6 +161,8 @@
CASPER_CHAIN_NAME = "cspr-dev-cctl";
PATH_TO_WASM_BINARIES = "${self'.packages.kairos-contracts}/bin";
PATH_TO_SESSION_BINARIES = "${self'.packages.kairos-session-code}/bin";
CCTL_CONFIG = "${cctlConfig.config}";
CCTL_CHAINSPEC = "${cctlConfig.chainspec}";

meta.mainProgram = "kairos-server";
};
Expand All @@ -161,6 +175,8 @@
CASPER_CHAIN_NAME = "cspr-dev-cctl";
PATH_TO_WASM_BINARIES = "${self'.packages.kairos-contracts}/bin";
PATH_TO_SESSION_BINARIES = "${self'.packages.kairos-session-code}/bin";
CCTL_CONFIG = "${cctlConfig.config}";
CCTL_CHAINSPEC = "${cctlConfig.chainspec}";
inputsFrom = [ self'.packages.kairos self'.packages.kairos-contracts ];
};

Expand Down
11 changes: 9 additions & 2 deletions kairos-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,21 +14,28 @@ license.workspace = true
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[features]
default = ["demo"]
all-tests = ["cctl-tests"]
cctl-tests = []
demo = ["dep:kairos-test-utils", "dep:tokio"]

[dependencies]
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["std", "env-filter"] }
casper-client.workspace = true
casper-client-types = { workspace = true, features = ["std"] } # TODO: Change `std` -> `std-fs-io` in the future version.
clap = { version = "4.5", features = ["derive", "deprecated"] }
clap = { version = "4", features = ["derive", "deprecated"] }
hex = "0.4"
thiserror = "1"
kairos-crypto = { path = "../kairos-crypto", features = ["std"] }
kairos-crypto = { path = "../kairos-crypto", features = [ "std", "fs" ] }
kairos-tx = { path = "../kairos-tx" }
kairos-server = { path = "../kairos-server" }
axum-extra = { version = "0.9", features = [ "typed-routing" ] }
reqwest = { version = "0.12", features = ["blocking", "json"] }
serde_json = "1.0"
serde = "1.0"
kairos-test-utils = { path = "../kairos-test-utils", optional = true }
tokio = { version = "1", features = ["full"], optional = true }

[dev-dependencies]
tokio = "1"
Expand Down
6 changes: 6 additions & 0 deletions kairos-cli/bin/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
use clap::Parser;
use std::process;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};

fn main() {
tracing_subscriber::registry()
.with(EnvFilter::try_from_default_env().unwrap_or_else(|_| "warn".into()))
.with(tracing_subscriber::fmt::layer())
.init();

let args = kairos_cli::Cli::parse();
match kairos_cli::run(args) {
Ok(output) => {
Expand Down
29 changes: 17 additions & 12 deletions kairos-cli/src/client.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use casper_client::types::DeployHash;
use casper_client::types::{DeployBuilder, ExecutableDeployItem, TimeDiff, Timestamp};
use axum_extra::routing::TypedPath;
use casper_client::types::{DeployBuilder, DeployHash, ExecutableDeployItem, TimeDiff, Timestamp};
use casper_client_types::{crypto::SecretKey, runtime_args, ContractHash, RuntimeArgs, U512};
use reqwest::{blocking, Url};
use kairos_server::routes::deposit::DepositPath;
use reqwest::Url;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::fs;
Expand Down Expand Up @@ -43,11 +44,12 @@ impl From<reqwest::Error> for KairosClientError {
}
}

pub fn deposit<A: Into<U512>>(
pub fn deposit(
base_url: &Url,
depositor_secret_key: &SecretKey,
contract_hash: &ContractHash,
amount: A,
amount: impl Into<U512>,
recipient: casper_client_types::PublicKey,
) -> Result<DeployHash, KairosClientError> {
let deposit_session_wasm_path =
Path::new(env!("PATH_TO_SESSION_BINARIES")).join("deposit-session-optimized.wasm");
Expand All @@ -59,7 +61,11 @@ pub fn deposit<A: Into<U512>>(
});
let deposit_session = ExecutableDeployItem::new_module_bytes(
deposit_session_wasm_bytes.into(),
runtime_args! { "demo_contract" => *contract_hash, "amount" => amount.into() },
runtime_args! {
"demo_contract" => *contract_hash,
"amount" => amount.into(),
"recipient" => recipient
},
);
let deploy = DeployBuilder::new(
env!("CASPER_CHAIN_NAME"),
Expand All @@ -72,20 +78,19 @@ pub fn deposit<A: Into<U512>>(
.build()
.map_err(|err| KairosClientError::CasperClientError(err.to_string()))?;

let client = blocking::Client::new();
let url = base_url.join("/api/v1/deposit").unwrap();
let response = client
.post(url)
let response = reqwest::blocking::Client::new()
.post(base_url.join(DepositPath::PATH).unwrap())
.header("Content-Type", "application/json")
.json(&deploy)
.send()
.map_err(Into::<KairosClientError>::into)?;
.map_err(KairosClientError::from)?;

let status = response.status();
if !status.is_success() {
Err(KairosClientError::KairosServerError(status.to_string()))
} else {
response
.json::<DeployHash>()
.map_err(Into::<KairosClientError>::into)
.map_err(KairosClientError::from)
}
}
5 changes: 4 additions & 1 deletion kairos-cli/src/commands/deposit.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::client;
use crate::common::args::{AmountArg, ContractHashArg, PrivateKeyPathArg};
use crate::common::args::{AmountArg, ContractHashArg, PrivateKeyPathArg, RecipientArg};
use crate::error::CliError;

use casper_client_types::{crypto::SecretKey, ContractHash};
Expand All @@ -17,6 +17,8 @@ pub struct Args {
private_key_path: PrivateKeyPathArg,
#[clap(flatten)]
contract_hash: ContractHashArg,
#[clap(flatten)]
recipient: RecipientArg,
}

pub fn run(args: Args, kairos_server_address: Url) -> Result<String, CliError> {
Expand All @@ -36,6 +38,7 @@ pub fn run(args: Args, kairos_server_address: Url) -> Result<String, CliError> {
&depositor_secret_key,
&contract_hash,
amount,
args.recipient.try_into()?,
)
.map_err(Into::<CliError>::into)
.map(|deploy_hash| {
Expand Down
2 changes: 2 additions & 0 deletions kairos-cli/src/commands/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
pub mod deposit;
#[cfg(feature = "demo")]
pub mod run_cctl;
pub mod transfer;
pub mod withdraw;
45 changes: 45 additions & 0 deletions kairos-cli/src/commands/run_cctl.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
use std::path::{Path, PathBuf};

use casper_client_types::{runtime_args, RuntimeArgs};
use kairos_test_utils::cctl::{CCTLNetwork, DeployableContract};

use crate::error::CliError;

pub fn run() -> Result<String, CliError> {
tokio::runtime::Runtime::new().unwrap().block_on(async {
let contract_wasm_path =
PathBuf::from(env!("PATH_TO_WASM_BINARIES")).join("demo-contract-optimized.wasm");
let hash_name = "kairos_contract_package_hash";
let contract_to_deploy = DeployableContract {
hash_name: hash_name.to_string(),
runtime_args: runtime_args! { "initial_trie_root" => Option::<[u8; 32]>::None },
path: contract_wasm_path,
};
println!("Deploying contract...");
let chainspec_path = Path::new(env!("CCTL_CHAINSPEC"));
let config_path = Path::new(env!("CCTL_CONFIG"));

let network = CCTLNetwork::run(None, Some(contract_to_deploy), Some(chainspec_path), Some(config_path))
.await
.unwrap();

println!("Contract deployed successfully!");
let contract_hash = network.get_contract_hash_for(hash_name);

let node = network
.nodes
.first()
.expect("Expected at least one node after successful network run");
let casper_rpc_url = format!("http://localhost:{}/rpc", node.port.rpc_port);

println!("You can find demo key pairs in `{:?}`", network.working_dir);

println!("Before running the Kairos CLI in another terminal, set the following environment variables:");
println!("export KAIROS_CONTRACT_HASH={}", contract_hash);
println!("export KAIROS_SERVER_CASPER_RPC={}", casper_rpc_url);

let _ = tokio::signal::ctrl_c().await;
});

Ok("exiting".to_string())
}
Loading

0 comments on commit 9d341c2

Please sign in to comment.