Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

rusk-wallet: Implement http contract query #3169

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 60 additions & 26 deletions rusk-wallet/src/bin/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,12 @@ pub(crate) enum Command {
#[arg(short = 'f', long)]
fn_args: Vec<u8>,

/// If query is true then HTTP contract call is done to obtain return
/// value of function if query is false then a transaction is
/// sent for mutation of the state of the contract
#[arg(short, long)]
query: bool,

/// Max amount of gas for this transaction
#[arg(short = 'l', long, default_value_t = DEFAULT_LIMIT_CALL)]
gas_limit: u64,
Expand Down Expand Up @@ -567,6 +573,7 @@ impl Command {
fn_args,
gas_limit,
gas_price,
query,
} => {
let gas = Gas::new(gas_limit).with_price(gas_price);

Expand All @@ -577,35 +584,52 @@ impl Command {
.try_into()
.map_err(|_| Error::InvalidContractId)?;

let call = ContractCall::new(contract_id, fn_name, &fn_args)
.map_err(|_| Error::Rkyv)?;
match query {
true => {
let contract_id = hex::encode(contract_id);

let tx = match address {
Address::Shielded(_) => {
wallet.sync().await?;
wallet
.phoenix_execute(
addr_idx,
Dusk::from(0),
gas,
call.into(),
)
.await
}
Address::Public(_) => {
wallet
.moonlight_execute(
addr_idx,
Dusk::from(0),
Dusk::from(0),
gas,
call.into(),
)
.await
let http_call = wallet
.http_contract_call(contract_id, &fn_name, fn_args)
.await?;

Ok(RunResult::ContractCallQuery(http_call))
}
}?;
false => {
let call = ContractCall::new(
contract_id,
fn_name.clone(),
&fn_args,
)
.map_err(|_| Error::Rkyv)?;

let tx = match address {
Address::Shielded(_) => {
wallet.sync().await?;
wallet
.phoenix_execute(
addr_idx,
Dusk::from(0),
gas,
call.into(),
)
.await
}
Address::Public(_) => {
wallet
.moonlight_execute(
addr_idx,
Dusk::from(0),
Dusk::from(0),
gas,
call.into(),
)
.await
}
}?;

Ok(RunResult::Tx(tx.hash()))
Ok(RunResult::ContractCallTx(tx.hash()))
}
}
}

Self::ContractDeploy {
Expand Down Expand Up @@ -696,6 +720,8 @@ pub enum RunResult<'a> {
Profile((u8, &'a Profile)),
Profiles(&'a Vec<Profile>),
ContractId([u8; CONTRACT_ID_BYTES]),
ContractCallTx(BlsScalar),
ContractCallQuery(Vec<u8>),
ExportedKeys(PathBuf, PathBuf),
Create(),
Restore(),
Expand Down Expand Up @@ -773,6 +799,14 @@ impl fmt::Display for RunResult<'_> {
ContractId(bytes) => {
write!(f, "> Contract ID: {}", hex::encode(bytes))
}
ContractCallTx(scalar) => {
let hash = hex::encode(scalar.to_bytes());

writeln!(f, "> Contract call transaction hash: {hash}",)
}
ContractCallQuery(bytes) => {
writeln!(f, "> Http contract query: {:?}", hex::encode(bytes))
}
ExportedKeys(pk, kp) => {
let pk = pk.display();
let kp = kp.display();
Expand Down
60 changes: 45 additions & 15 deletions rusk-wallet/src/bin/interactive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,22 +92,26 @@ pub(crate) async fn run_loop(
prompt::show_cursor()?;
// output results
println!("\r{}", res);
if let RunResult::Tx(hash) = res {
let tx_id = hex::encode(hash.to_bytes());

// Wait for transaction confirmation
// from network
let gql = GraphQL::new(
settings.state.to_string(),
io::status::interactive,
)?;
gql.wait_for(&tx_id).await?;

if let Some(explorer) = &settings.explorer {
let url = format!("{explorer}{tx_id}");
println!("> URL: {url}");
prompt::launch_explorer(url)?;
match res {
RunResult::Tx(hash)
| RunResult::ContractCallTx(hash) => {
let tx_id = hex::encode(hash.to_bytes());

// Wait for transaction confirmation
// from network
let gql = GraphQL::new(
settings.state.to_string(),
io::status::interactive,
)?;
gql.wait_for(&tx_id).await?;

if let Some(explorer) = &settings.explorer {
let url = format!("{explorer}{tx_id}");
println!("> URL: {url}");
prompt::launch_explorer(url)?;
}
}
_ => (),
}
}
}
Expand Down Expand Up @@ -464,6 +468,32 @@ fn confirm(cmd: &Command, wallet: &Wallet<WalletFile>) -> anyhow::Result<bool> {
}
prompt::ask_confirm()
}
Command::ContractCall {
address,
contract_id,
fn_name,
fn_args,
query,
gas_limit,
gas_price,
} => {
println!(" > Function name {}", fn_name);
println!(" > Function arguments {}", hex::encode(fn_args));
println!(" > Contract ID {}", hex::encode(contract_id));
println!(" > Is HTTP query? {}", query);

if !query {
let max_fee = gas_limit * gas_price;

println!(" > Max fee = {} DUSK", Dusk::from(max_fee));

if let Some(Address::Public(_)) = address {
println!(" > ALERT: THIS IS A PUBLIC TRANSACTION");
}
}

prompt::ask_confirm()
}
_ => Ok(true),
}
}
Expand Down
48 changes: 30 additions & 18 deletions rusk-wallet/src/bin/interactive/command_menu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use rusk_wallet::{
MIN_CONVERTIBLE,
};

use super::prompt::request_contract_call_method;
use super::ProfileOp;
use crate::settings::Settings;
use crate::{prompt, Command, WalletFile};
Expand Down Expand Up @@ -314,27 +315,37 @@ pub(crate) async fn online(
}))
}
MenuItem::ContractCall => {
let (addr, balance) = pick_transaction_model(
wallet,
profile_idx,
phoenix_spendable,
moonlight_balance,
)?;

if check_min_gas_balance(
balance,
DEFAULT_LIMIT_CALL,
"a contract call",
)
.is_err()
{
return Ok(ProfileOp::Stay);
}

let mempool_gas_prices = wallet.get_mempool_gas_prices().await?;
let mut address = None;

let query = match request_contract_call_method()? {
prompt::ContractCall::Query => true,
prompt::ContractCall::Transaction => {
let (addr, balance) = pick_transaction_model(
wallet,
profile_idx,
phoenix_spendable,
moonlight_balance,
)?;

address = Some(addr);

if check_min_gas_balance(
balance,
DEFAULT_LIMIT_CALL,
"a contract call",
)
.is_err()
{
return Ok(ProfileOp::Stay);
}

false
}
};

ProfileOp::Run(Box::new(Command::ContractCall {
address: Some(addr),
address,
contract_id: prompt::request_bytes("contract id")?,
fn_name: prompt::request_str(
"function name to call",
Expand All @@ -348,6 +359,7 @@ pub(crate) async fn online(
DEFAULT_PRICE,
mempool_gas_prices,
)?,
query,
}))
}
MenuItem::History => {
Expand Down
29 changes: 28 additions & 1 deletion rusk-wallet/src/bin/io/prompt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,32 @@ pub(crate) fn request_transaction_model() -> anyhow::Result<TransactionModel> {
)
}

pub enum ContractCall {
/// Call by http query (return values)
Query,
/// Call by a transaction (mutating state)
Transaction,
}

impl Display for ContractCall {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
ContractCall::Query => write!(f, "By HTTP Query"),
ContractCall::Transaction => write!(f, "By Transaction"),
}
}
}

/// Request transaction model to use
pub(crate) fn request_contract_call_method() -> anyhow::Result<ContractCall> {
let choices = vec![ContractCall::Query, ContractCall::Transaction];

Ok(
Select::new("Please specify the contract call method to use", choices)
.prompt()?,
)
}

/// Request transaction model to use
pub(crate) fn request_address(
current_idx: u8,
Expand All @@ -372,7 +398,8 @@ pub(crate) fn request_address(
pub(crate) fn request_contract_code() -> anyhow::Result<PathBuf> {
let validator = |path_str: &str| {
let path = PathBuf::from(path_str);
if path.extension().map_or(false, |ext| ext == "wasm") {
if path.extension().map_or(false, |ext| ext == "wasm") && path.exists()
{
Ok(Validation::Valid)
} else {
Ok(Validation::Invalid("Not a valid directory".into()))
Expand Down
12 changes: 12 additions & 0 deletions rusk-wallet/src/bin/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,18 @@ async fn exec() -> anyhow::Result<()> {
RunResult::ContractId(id) => {
println!("Contract ID: {:?}", id);
}
RunResult::ContractCallTx(scalar) => {
let tx_id = hex::encode(scalar.to_bytes());

// Wait for transaction confirmation from network
let gql = GraphQL::new(settings.state, status::headless)?;
gql.wait_for(&tx_id).await?;

println!("{tx_id}");
}
RunResult::ContractCallQuery(bytes) => {
println!("HTTP call result: {:?}", bytes);
}
RunResult::Settings() => {}
RunResult::Create() | RunResult::Restore() => {}
}
Expand Down
2 changes: 1 addition & 1 deletion rusk-wallet/src/clients/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ pub(crate) async fn sync_db(
let mut stream = client
.call_raw(
CONTRACTS_TARGET,
TRANSFER_CONTRACT,
Some(TRANSFER_CONTRACT.to_string()),
"leaves_from_pos",
&req,
true,
Expand Down
2 changes: 1 addition & 1 deletion rusk-wallet/src/gql.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ impl GraphQL {
/// Call the graphql endpoint of a node
pub async fn query(&self, query: &str) -> Result<Vec<u8>, Error> {
self.client
.call("graphql", None, "query", query.as_bytes())
.call("graphql", None::<String>, "query", query.as_bytes())
.await
}
}
Expand Down
9 changes: 6 additions & 3 deletions rusk-wallet/src/rues.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,11 @@ impl RuesHttpClient {
{
let data = rkyv::to_bytes(value).map_err(|_| Error::Rkyv)?.to_vec();

let contract: Option<&str> = contract.into();
let contract: Option<String> = contract.map(|e| e.to_owned());

let response = self
.call_raw(CONTRACTS_TARGET, contract.into(), method, &data, false)
.call_raw(CONTRACTS_TARGET, contract, method, &data, false)
.await?;

Ok(response.bytes().await?.to_vec())
Expand All @@ -79,7 +82,7 @@ impl RuesHttpClient {
request: &[u8],
) -> Result<Vec<u8>, Error>
where
E: Into<Option<&'static str>>,
E: Into<Option<String>>,
{
let response =
self.call_raw(target, entity, topic, request, false).await?;
Expand All @@ -97,7 +100,7 @@ impl RuesHttpClient {
feed: bool,
) -> Result<Response, Error>
where
E: Into<Option<&'static str>>,
E: Into<Option<String>>,
{
let uri = &self.uri;
let entity = entity.into().map(|e| format!(":{e}")).unwrap_or_default();
Expand Down
Loading
Loading