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

feat(CLI): add --wasm args to bump/restore #775

Merged
merged 7 commits into from
Jul 20, 2023
Merged
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
78 changes: 49 additions & 29 deletions cmd/soroban-cli/src/commands/contract/bump.rs
Original file line number Diff line number Diff line change
@@ -1,35 +1,47 @@
use std::{fmt::Debug, path::Path, str::FromStr};
use std::{
fmt::Debug,
path::{Path, PathBuf},
str::FromStr,
};

use clap::{command, Parser};
use soroban_env_host::xdr::{
BumpFootprintExpirationOp, ContractDataEntry, ContractEntryBodyType, Error as XdrError,
ExtensionPoint, Hash, LedgerEntry, LedgerEntryChange, LedgerEntryData, LedgerFootprint,
LedgerKey, LedgerKeyContractData, Memo, MuxedAccount, Operation, OperationBody, Preconditions,
ReadXdr, ScAddress, ScSpecTypeDef, ScVal, SequenceNumber, SorobanResources,
SorobanTransactionData, Transaction, TransactionExt, TransactionMeta, TransactionMetaV3,
Uint256,
BumpFootprintExpirationOp, ContractCodeEntry, ContractDataEntry, ContractEntryBodyType,
Error as XdrError, ExtensionPoint, Hash, LedgerEntry, LedgerEntryChange, LedgerEntryData,
LedgerFootprint, LedgerKey, LedgerKeyContractData, Memo, MuxedAccount, Operation,
OperationBody, Preconditions, ReadXdr, ScAddress, ScSpecTypeDef, ScVal, SequenceNumber,
SorobanResources, SorobanTransactionData, Transaction, TransactionExt, TransactionMeta,
TransactionMetaV3, Uint256,
};
use stellar_strkey::DecodeError;

use crate::{
commands::config,
commands::contract::Durability,
rpc::{self, Client},
utils, Pwd,
utils, wasm, Pwd,
};

#[derive(Parser, Debug, Clone)]
#[group(skip)]
pub struct Cmd {
/// Contract ID to which owns the data entries
#[arg(long = "id")]
contract_id: String,
#[arg(long = "id", required_unless_present = "wasm")]
contract_id: Option<String>,
/// Storage key (symbols only)
#[arg(long = "key", conflicts_with = "key_xdr")]
key: Option<String>,
/// Storage key (base64-encoded XDR)
#[arg(long = "key-xdr", conflicts_with = "key")]
key_xdr: Option<String>,
/// Path to Wasm file of contract code to bump
#[arg(
long,
conflicts_with = "contract_id",
conflicts_with = "key",
conflicts_with = "key_xdr"
)]
wasm: Option<PathBuf>,
/// Storage entry durability
#[arg(long, value_enum, required = true)]
durability: Durability,
Expand Down Expand Up @@ -82,6 +94,8 @@ pub enum Error {
MissingOperationResult,
#[error(transparent)]
Rpc(#[from] rpc::Error),
#[error(transparent)]
Wasm(#[from] wasm::Error),
}

impl Cmd {
Expand All @@ -101,8 +115,7 @@ impl Cmd {
async fn run_against_rpc_server(&self) -> Result<u32, Error> {
let network = self.config.get_network()?;
tracing::trace!(?network);
let contract_id = self.contract_id()?;
let needle = self.parse_key(contract_id)?;
let needle = self.parse_key()?;
let network = &self.config.get_network()?;
let client = Client::new(&network.rpc_url)?;
let key = self.config.key_pair()?;
Expand Down Expand Up @@ -147,6 +160,7 @@ impl Cmd {
.await?;

tracing::debug!(?result);
tracing::debug!(?meta);
if !events.is_empty() {
tracing::debug!(?events);
}
Expand All @@ -167,25 +181,28 @@ impl Cmd {
return Err(Error::LedgerEntryNotFound);
}

let (
LedgerEntryChange::State(_state),
LedgerEntryChange::Updated(LedgerEntry{
data: LedgerEntryData::ContractData(ContractDataEntry{
expiration_ledger_seq,
match (&operations[0].changes[0], &operations[0].changes[1]) {
(
LedgerEntryChange::State(_),
LedgerEntryChange::Updated(LedgerEntry {
data:
LedgerEntryData::ContractData(ContractDataEntry {
expiration_ledger_seq,
..
})
| LedgerEntryData::ContractCode(ContractCodeEntry {
expiration_ledger_seq,
..
}),
..
}),
..
})
) = (&operations[0].changes[0], &operations[0].changes[1]) else {
return Err(Error::LedgerEntryNotFound);
};

Ok(*expiration_ledger_seq)
) => Ok(*expiration_ledger_seq),
_ => Err(Error::LedgerEntryNotFound),
}
}

fn run_in_sandbox(&self) -> Result<u32, Error> {
let contract_id = self.contract_id()?;
let needle = self.parse_key(contract_id)?;
let needle = self.parse_key()?;

// Initialize storage and host
// TODO: allow option to separate input and output file
Expand Down Expand Up @@ -222,11 +239,11 @@ impl Cmd {
}

fn contract_id(&self) -> Result<[u8; 32], Error> {
utils::contract_id_from_str(&self.contract_id)
.map_err(|e| Error::CannotParseContractId(self.contract_id.clone(), e))
utils::contract_id_from_str(self.contract_id.as_ref().unwrap())
.map_err(|e| Error::CannotParseContractId(self.contract_id.clone().unwrap(), e))
}

fn parse_key(&self, contract_id: [u8; 32]) -> Result<LedgerKey, Error> {
fn parse_key(&self) -> Result<LedgerKey, Error> {
let key = if let Some(key) = &self.key {
soroban_spec_tools::from_string_primitive(key, &ScSpecTypeDef::Symbol).map_err(|e| {
Error::CannotParseKey {
Expand All @@ -239,9 +256,12 @@ impl Cmd {
key: key.clone(),
error: e,
})?
} else if let Some(wasm) = &self.wasm {
return Ok(crate::wasm::Args { wasm: wasm.clone() }.try_into()?);
} else {
return Err(Error::KeyIsRequired);
};
let contract_id = self.contract_id()?;

Ok(LedgerKey::ContractData(LedgerKeyContractData {
contract: ScAddress::Contract(Hash(contract_id)),
Expand Down
92 changes: 70 additions & 22 deletions cmd/soroban-cli/src/commands/contract/restore.rs
Original file line number Diff line number Diff line change
@@ -1,34 +1,54 @@
use std::{fmt::Debug, path::Path, str::FromStr};
use std::{
fmt::Debug,
path::{Path, PathBuf},
str::FromStr,
};

use clap::{command, Parser};
use soroban_env_host::xdr::{
ContractDataDurability, ContractDataEntry, ContractEntryBodyType, Error as XdrError,
ExtensionPoint, Hash, LedgerEntry, LedgerEntryChange, LedgerEntryData, LedgerFootprint,
LedgerKey, LedgerKeyContractData, Memo, MuxedAccount, Operation, OperationBody, Preconditions,
ReadXdr, RestoreFootprintOp, ScAddress, ScSpecTypeDef, ScVal, SequenceNumber, SorobanResources,
SorobanTransactionData, Transaction, TransactionExt, TransactionMeta, TransactionMetaV3,
Uint256,
ContractCodeEntry, ContractDataDurability, ContractDataEntry, ContractEntryBodyType,
Error as XdrError, ExtensionPoint, Hash, LedgerEntry, LedgerEntryChange, LedgerEntryData,
LedgerFootprint, LedgerKey, LedgerKeyContractData, Memo, MuxedAccount, Operation,
OperationBody, Preconditions, ReadXdr, RestoreFootprintOp, ScAddress, ScSpecTypeDef, ScVal,
SequenceNumber, SorobanResources, SorobanTransactionData, Transaction, TransactionExt,
TransactionMeta, TransactionMetaV3, Uint256,
};
use stellar_strkey::DecodeError;

use crate::{
commands::config::{self, locator},
rpc::{self, Client},
utils, Pwd,
utils, wasm, Pwd,
};

#[derive(Parser, Debug, Clone)]
#[group(skip)]
pub struct Cmd {
/// Contract ID to which owns the data entries
#[arg(long = "id")]
contract_id: String,
#[arg(long = "id", required_unless_present = "wasm")]
contract_id: Option<String>,
/// Storage key (symbols only)
#[arg(long = "key", required_unless_present = "key_xdr")]
#[arg(
long = "key",
required_unless_present = "key_xdr",
required_unless_present = "wasm"
)]
key: Vec<String>,
/// Storage key (base64-encoded XDR)
#[arg(long = "key-xdr", required_unless_present = "key")]
#[arg(
long = "key-xdr",
required_unless_present = "key",
required_unless_present = "wasm"
)]
key_xdr: Vec<String>,
/// Path to Wasm file of contract code to restore
#[arg(
long,
conflicts_with = "key",
conflicts_with = "key_xdr",
conflicts_with = "contract_id"
)]
wasm: Option<PathBuf>,

#[command(flatten)]
config: config::Args,
Expand Down Expand Up @@ -76,6 +96,8 @@ pub enum Error {
MissingOperationResult,
#[error(transparent)]
Rpc(#[from] rpc::Error),
#[error(transparent)]
Wasm(#[from] wasm::Error),
}

impl Cmd {
Expand All @@ -95,8 +117,12 @@ impl Cmd {
async fn run_against_rpc_server(&self) -> Result<u32, Error> {
let network = self.config.get_network()?;
tracing::trace!(?network);
let contract_id = self.contract_id()?;
let entry_keys = self.parse_keys(contract_id)?;
let entry_keys = if let Some(wasm) = &self.wasm {
vec![crate::wasm::Args { wasm: wasm.clone() }.try_into()?]
} else {
let contract_id = self.contract_id()?;
self.parse_keys(contract_id)?
};
let network = &self.config.get_network()?;
let client = Client::new(&network.rpc_url)?;
let key = self.config.key_pair()?;
Expand Down Expand Up @@ -140,6 +166,7 @@ impl Cmd {
.await?;

tracing::debug!(?result);
tracing::debug!(?meta);
if !events.is_empty() {
tracing::debug!(?events);
}
Expand All @@ -159,12 +186,33 @@ impl Cmd {
if operations[0].changes.len() != 1 {
return Err(Error::LedgerEntryNotFound);
}

let LedgerEntryChange::Created(LedgerEntry{ data: LedgerEntryData::ContractData(ContractDataEntry{expiration_ledger_seq, ..}), ..}) = &operations[0].changes[0] else {
return Err(Error::LedgerEntryNotFound);
};

Ok(*expiration_ledger_seq)
match operations[0].changes[0] {
LedgerEntryChange::Updated(LedgerEntry {
data:
LedgerEntryData::ContractData(ContractDataEntry {
expiration_ledger_seq,
..
})
| LedgerEntryData::ContractCode(ContractCodeEntry {
expiration_ledger_seq,
..
}),
..
})
| LedgerEntryChange::Created(LedgerEntry {
data:
LedgerEntryData::ContractData(ContractDataEntry {
expiration_ledger_seq,
..
})
| LedgerEntryData::ContractCode(ContractCodeEntry {
expiration_ledger_seq,
..
}),
..
}) => Ok(expiration_ledger_seq),
_ => Err(Error::LedgerEntryNotFound),
}
}

fn run_in_sandbox(&self) -> Result<u32, Error> {
Expand All @@ -174,8 +222,8 @@ impl Cmd {
}

fn contract_id(&self) -> Result<[u8; 32], Error> {
utils::contract_id_from_str(&self.contract_id)
.map_err(|e| Error::CannotParseContractId(self.contract_id.clone(), e))
utils::contract_id_from_str(self.contract_id.as_ref().unwrap())
.map_err(|e| Error::CannotParseContractId(self.contract_id.clone().unwrap(), e))
}

fn parse_keys(&self, contract_id: [u8; 32]) -> Result<Vec<LedgerKey>, Error> {
Expand Down
15 changes: 13 additions & 2 deletions cmd/soroban-cli/src/wasm.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use clap::arg;
use soroban_env_host::xdr;
use soroban_env_host::xdr::{self, ContractEntryBodyType, LedgerKey, LedgerKeyContractCode};
use std::{fs, io, path::Path};

use crate::utils::contract_spec::ContractSpec;
use crate::utils::{self, contract_spec::ContractSpec};

#[derive(thiserror::Error, Debug)]
pub enum Error {
Expand Down Expand Up @@ -63,6 +63,17 @@ impl Args {
}
}

impl TryInto<LedgerKey> for Args {
type Error = Error;

fn try_into(self) -> Result<LedgerKey, Self::Error> {
Ok(LedgerKey::ContractCode(LedgerKeyContractCode {
hash: utils::contract_hash(&self.read()?)?,
body_type: ContractEntryBodyType::DataEntry,
}))
}
}

/// # Errors
/// May fail to read wasm file
pub fn len(p: &Path) -> Result<u64, Error> {
Expand Down
6 changes: 4 additions & 2 deletions docs/soroban-cli-full-docs.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,13 +203,14 @@ To view the commands that will be executed, without executing them, use the --pr

Extend the expiry ledger of a contract-data ledger entry

**Usage:** `soroban contract bump [OPTIONS] --id <CONTRACT_ID> --durability <DURABILITY> --ledgers-to-expire <LEDGERS_TO_EXPIRE>`
**Usage:** `soroban contract bump [OPTIONS] --durability <DURABILITY> --ledgers-to-expire <LEDGERS_TO_EXPIRE>`
tsachiherman marked this conversation as resolved.
Show resolved Hide resolved

###### **Options:**

* `--id <CONTRACT_ID>` — Contract ID to which owns the data entries
* `--key <KEY>` — Storage key (symbols only)
* `--key-xdr <KEY_XDR>` — Storage key (base64-encoded XDR)
* `--wasm <WASM>` — Path to Wasm file of contract code to bump
* `--durability <DURABILITY>` — Storage entry durability

Possible values:
Expand Down Expand Up @@ -409,13 +410,14 @@ Print the current value of a contract-data ledger entry

Restore an evicted value for a contract-data legder entry

**Usage:** `soroban contract restore [OPTIONS] --id <CONTRACT_ID>`
**Usage:** `soroban contract restore [OPTIONS]`

###### **Options:**

* `--id <CONTRACT_ID>` — Contract ID to which owns the data entries
* `--key <KEY>` — Storage key (symbols only)
* `--key-xdr <KEY_XDR>` — Storage key (base64-encoded XDR)
* `--wasm <WASM>` — Path to Wasm file of contract code to restore
* `--rpc-url <RPC_URL>` — RPC server endpoint
* `--network-passphrase <NETWORK_PASSPHRASE>` — Network passphrase to sign the transaction sent to the rpc server
* `--network <NETWORK>` — Name of network to use from config
Expand Down