repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/cmd/mod.rs
wasmer-deploy-cli/src/cmd/mod.rs
mod balance; mod cancel_deposit; mod coin_carve; mod coin_collect; mod coin_combine; mod coin_rotate; mod contract; mod contract_action; mod contract_cancel; mod contract_create; mod contract_details; mod contract_elevate; mod contract_list; mod core; mod deposit; mod history; mod login; mod logout; mod service; mod service_find; mod transfer; mod wallet; mod withdraw; mod instance; mod cidr; mod peering; pub(crate) mod network; pub use wasmer_auth::cmd::*; pub use self::core::*; pub use balance::*; pub use cancel_deposit::*; pub use coin_carve::*; pub use coin_collect::*; pub use coin_combine::*; pub use coin_rotate::*; pub use contract::*; pub use contract_action::*; pub use contract_cancel::*; pub use contract_create::*; pub use contract_details::*; pub use contract_elevate::*; pub use contract_list::*; pub use deposit::*; pub use history::*; pub use login::*; pub use logout::*; pub use service::*; pub use service_find::*; pub use transfer::*; pub use wallet::*; pub use withdraw::*; pub use instance::*; pub use cidr::*; pub use peering::*; pub use network::*;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/cmd/contract_details.rs
wasmer-deploy-cli/src/cmd/contract_details.rs
#[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use crate::api::*; use crate::error::*; use crate::opt::*; pub async fn main_opts_contract_details( opts: OptsContractDetails, api: &mut DeployApi, ) -> Result<(), ContractError> { let contract = match api.contract_get(opts.reference_number.as_str()).await { Ok(a) => a, Err(ContractError(ContractErrorKind::InvalidReference(reference_number), _)) => { eprintln!("No contract exists with this ID ({}).", reference_number); std::process::exit(1); } Err(err) => return Err(err), }; let service = contract.service; println!("{}", service.description); for rate_card in service.rate_cards { println!("=================="); println!("{}", serde_json::to_string_pretty(&rate_card).unwrap()); } println!("=================="); println!( "{}", serde_json::to_string_pretty(&contract.metrics).unwrap() ); println!("=================="); println!("status: {}", contract.status); Ok(()) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/cmd/wallet.rs
wasmer-deploy-cli/src/cmd/wallet.rs
use std::sync::Arc; #[allow(unused_imports)] use tracing::{debug, error, info}; use ate::prelude::*; use crate::error::*; use crate::api::*; use crate::cmd::*; use crate::model::*; use crate::opt::*; use crate::model::WALLET_COLLECTION_ID; use super::core::*; pub(super) async fn get_or_create_wallet( purpose: &dyn OptsPurpose<OptWalletAction>, dio: &Arc<DioMut>, auth: &url::Url, registry: &Arc<Registry>, identity: &String, ) -> Result<DaoMut<Wallet>, AteError> { let action = purpose.action(); // Make sure the parent exists let parent_key = PrimaryKey::from(identity.clone()); debug!("parent_key={}", parent_key); if dio.exists(&parent_key).await == false { eprintln!("The parent user or group does not exist in the chain-or-trust."); std::process::exit(1); } // Grab a reference to the wallet let wallet_name = get_wallet_name(purpose)?; let mut wallet_vec = DaoVec::<Wallet>::new_orphaned_mut(dio, parent_key, WALLET_COLLECTION_ID); let wallet = wallet_vec .iter_mut() .await? .into_iter() .filter(|a| a.name.eq_ignore_ascii_case(wallet_name.as_str())) .next(); // Create the wallet if it does not exist (otherwise make sure it was loaded) let wallet = match action { OptWalletAction::Create(opts) => { if wallet.is_some() { eprintln!("Wallet ({}) already exists (with same name).", wallet_name); std::process::exit(1); } create_wallet( dio, auth, registry, &identity, &wallet_name, &parent_key, opts.country, ) .await? } _ => match wallet { Some(a) => a, None => { eprintln!("Wallet ({}) does not exist - you must first 'create' the wallet before using it.", wallet_name); std::process::exit(1); } }, }; Ok(wallet) } #[allow(unreachable_code)] pub async fn main_opts_remove(opts: OptsRemoveWallet, api: DeployApi) -> Result<(), WalletError> { match api.delete_wallet(opts.force).await { Ok(_) => {} Err(WalletError(WalletErrorKind::WalletNotEmpty, _)) => { eprintln!("The wallet is not empty and thus can not be removed."); std::process::exit(1); } Err(err) => return Err(err), }; Ok(()) } pub async fn main_opts_wallet( opts_wallet: OptsWalletSource, token_path: String, auth_url: url::Url, ) -> Result<(), WalletError> { let sudo = match opts_wallet.action() { OptWalletAction::Balance(_) => true, OptWalletAction::History(_) => true, OptWalletAction::Create(_) => true, OptWalletAction::Remove(_) => true, OptWalletAction::Deposit(_) => true, OptWalletAction::Transfer(_) => true, OptWalletAction::Withdraw(_) => true, #[allow(unreachable_patterns)] _ => false, }; // Create the API to the wallet let inner = PurposeContextPrelude::new(&opts_wallet, token_path.as_str(), &auth_url, sudo).await?; let wallet = get_or_create_wallet( &opts_wallet, &inner.dio, &auth_url, &inner.registry, &inner.identity, ) .await?; let api = crate::api::build_api_accessor(&inner.dio, wallet, auth_url, None, &inner.registry).await; let mut context = PurposeContext::<OptWalletAction> { inner, api }; // Determine what we need to do match context.inner.action { OptWalletAction::Create(_) => { context.api.commit().await?; // This was handled earlier eprintln!("Wallet successfully created.") } OptWalletAction::Remove(opts_remove_wallet) => { main_opts_remove(opts_remove_wallet, context.api).await?; return Ok(()); } OptWalletAction::Balance(opts_balance) => { main_opts_balance(opts_balance, &mut context.api).await?; } OptWalletAction::History(opts_history) => { main_opts_transaction_history(opts_history, &mut context.api).await?; } OptWalletAction::Deposit(opts_deposit) => { main_opts_deposit(opts_deposit, &mut context.api).await?; } OptWalletAction::Transfer(opts_transfer) => { main_opts_transfer(opts_transfer, &opts_wallet, &mut context.api).await?; } OptWalletAction::Withdraw(opts_withdraw) => { main_opts_withdraw(opts_withdraw, &opts_wallet, &mut context.api).await?; } } context.api.commit().await?; Ok(()) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/cmd/logout.rs
wasmer-deploy-cli/src/cmd/logout.rs
use ate::error::AteError; #[cfg(target_os = "wasi")] use wasmer_bus_process::prelude::*; use crate::opt::*; pub async fn main_opts_logout( _opts_logout: OptsLogout, token_path: String, ) -> Result<(), AteError> { // Convert the token path to a real path let token_network_path = format!("{}.network", token_path); let token_network_path = shellexpand::tilde(&token_network_path).to_string(); let token_path = shellexpand::tilde(&token_path).to_string(); // Remove any old paths if let Ok(old) = std::fs::canonicalize(token_network_path.clone()) { let _ = std::fs::remove_file(old); } let _ = std::fs::remove_file(token_network_path.clone()); if let Ok(old) = std::fs::canonicalize(token_path.clone()) { let _ = std::fs::remove_file(old); } let _ = std::fs::remove_file(token_path.clone()); // If we are in WASM mode and there is a logout script then run it #[cfg(target_os = "wasi")] if std::path::Path::new("/usr/etc/logout.sh").exists() == true { Command::new(format!("source").as_str()) .args(&["/usr/etc/logout.sh"]) .execute() .await?; } #[cfg(target_os = "wasi")] if std::path::Path::new("/etc/logout.sh").exists() == true { Command::new(format!("source").as_str()) .args(&["/etc/logout.sh"]) .execute() .await?; } Ok(()) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/cmd/contract_cancel.rs
wasmer-deploy-cli/src/cmd/contract_cancel.rs
#[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use crate::api::*; use crate::error::*; use crate::opt::*; pub async fn main_opts_contract_cancel( opts: OptsContractCancel, api: &mut DeployApi, identity: &str, ) -> Result<(), ContractError> { match api .contract_cancel(opts.reference_number.as_str(), identity) .await { Ok(a) => a, Err(ContractError(ContractErrorKind::InvalidReference(reference_number), _)) => { eprintln!("No contract exists with this ID ({}).", reference_number); std::process::exit(1); } Err(err) => return Err(err), }; Ok(()) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/cmd/deposit.rs
wasmer-deploy-cli/src/cmd/deposit.rs
use error_chain::*; use std::sync::Arc; #[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use url::Url; use ate::prelude::*; use crate::api::*; use crate::error::*; use crate::model::*; use crate::opt::*; use crate::request::*; #[allow(dead_code)] pub async fn deposit_command( registry: &Arc<Registry>, amount: Decimal, currency: NationalCurrency, session: &'_ dyn AteSession, auth: Url, ) -> Result<DepositResponse, WalletError> { // Open a command chain let chain = registry.open_cmd(&auth).await?; // Get the email and build the proof let email = session.user().identity().to_string(); let sign_key = match session.write_keys(AteSessionKeyCategory::SudoKeys).next() { Some(a) => a.clone(), None => { bail!(WalletErrorKind::CoreError(CoreErrorKind::MissingTokenKey)); } }; // Create the login command let deposit = DepositRequest { proof: CoinProof { inner: SignedProtectedData::new( &sign_key, CoinProofInner { amount, currency, email, }, )?, }, }; // Attempt the login request with a 10 second timeout let response: Result<DepositResponse, DepositFailed> = chain.invoke(deposit).await?; let result = response?; Ok(result) } #[allow(unreachable_code)] pub async fn main_opts_deposit_new( opts: OptsDepositNew, api: &mut DeployApi, ) -> Result<(), WalletError> { let ret = api.deposit_create(opts.currency, opts.amount).await?; println!("Deposit invoice created (id={})", ret.invoice_id); println!(""); // Display the QR code println!("Below is a URL you can use to pay the invoice via PayPal:"); println!("{}", ret.pay_url); println!(""); println!("Alternatively below is an QR code - scan it on your phone to pay"); println!(""); println!("{}", ret.qr_code); // Done Ok(()) } #[allow(unreachable_code)] pub async fn main_opts_deposit_pending( _opts: OptsDepositPending, api: &mut DeployApi, ) -> Result<(), WalletError> { let query = api.deposit_query().await?; println!("Id Status Value"); for c in query.pending_deposits { println!( "{:16} UNPAID {} {} - {}", c.invoice_number, c.reserve, c.currency, c.pay_url ); } Ok(()) } #[allow(unreachable_code)] pub async fn main_opts_deposit_cancel( opts: OptsDepositCancel, api: &mut DeployApi, ) -> Result<(), WalletError> { match api.deposit_cancel(opts.id.as_str()).await { Ok(a) => a, Err(WalletError(WalletErrorKind::InvalidReference(invoice_number), _)) => { eprintln!( "Wallet has no deposit request with this ID ({}).", invoice_number ); std::process::exit(1); } Err(WalletError(WalletErrorKind::InvoiceAlreadyPaid(invoice_number), _)) => { eprintln!( "Can not cancel a deposit that is already paid ({}).", invoice_number ); std::process::exit(1); } Err(err) => return Err(err), }; println!("{} has been cancelled.", opts.id); Ok(()) } #[allow(unreachable_code)] pub async fn main_opts_deposit(opts: OptsDeposit, api: &mut DeployApi) -> Result<(), WalletError> { match opts.action { OptsDepositAction::Pending(opts) => { main_opts_deposit_pending(opts, api).await?; } OptsDepositAction::New(opts) => { main_opts_deposit_new(opts, api).await?; } OptsDepositAction::Cancel(opts) => { main_opts_deposit_cancel(opts, api).await?; } } Ok(()) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/cmd/balance.rs
wasmer-deploy-cli/src/cmd/balance.rs
use ate::prelude::*; #[allow(unused_imports)] use tracing::{debug, error, info}; use crate::api::*; use crate::error::*; use crate::opt::*; pub async fn main_opts_balance(opts: OptsBalance, api: &mut DeployApi) -> Result<(), WalletError> { if opts.no_reconcile == false { api.reconcile().await?; } let result = api.wallet_summary().await?; let short_form = opts.coins == false; if short_form == true { println!("Currency Balance for {}", api.wallet.key()); } let mut first = true; for currency in result.currencies.values() { // Display this currency summary to the user if short_form == false { if first == false { println!(""); } println!("Currency Balance"); } println!("{:8} {}", currency.currency, currency.total); if opts.coins { println!(""); println!("Denomination Quantity Total ({})", currency.currency); for denomination in currency.denominations.values() { println!( "{:12} {:8} {}", denomination.denomination, denomination.cnt, denomination.total ); } } first = false; } Ok(()) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/cmd/coin_combine.rs
wasmer-deploy-cli/src/cmd/coin_combine.rs
use std::sync::Arc; #[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use url::Url; use ate::prelude::*; use crate::error::*; use crate::model::*; use crate::request::*; pub async fn coin_combine_command( registry: &Arc<Registry>, coins: Vec<CarvedCoin>, new_ownership: Ownership, auth: Url, ) -> Result<CoinCombineResponse, CoinError> { let req = CoinCombineRequest { coins, new_ownership, }; // Attempt the login request with a 10 second timeout let chain = registry.open_cmd(&auth).await?; let response: Result<CoinCombineResponse, CoinCombineFailed> = chain.invoke(req).await?; let result = response?; Ok(result) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/cmd/contract_elevate.rs
wasmer-deploy-cli/src/cmd/contract_elevate.rs
use error_chain::*; use std::sync::Arc; #[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use url::Url; use ate::prelude::*; use crate::error::*; use crate::helper::*; use crate::request::*; pub async fn contract_elevate_command( registry: &Arc<Registry>, session: &dyn AteSession, auth: Url, service_code: String, requester_identity: String, consumer_identity: String, ) -> Result<EncryptKey, ContractError> { trace!( "contract elevate service_code={}, consumer_identity={}", service_code, consumer_identity ); // Open a command chain let chain = registry.open_cmd(&auth).await?; let (sign_key, broker_read) = session_sign_and_broker_key(session, requester_identity.contains("@"))?; let response: Result<ContractActionResponse, ContractActionFailed> = chain .invoke(ContractActionRequest { requester_identity: requester_identity.clone(), action_key: None, params: SignedProtectedData::new( sign_key, ContractActionRequestParams { service_code: service_code.clone(), consumer_identity: consumer_identity.clone(), action: ContractAction::Elevate, }, )?, }) .await?; let action_key = match response? { ContractActionResponse::Elevated { broker_key } => broker_key.unwrap(broker_read)?, _ => { warn!("server returned an invalid broker key"); bail!(CoreError::from_kind(CoreErrorKind::Other( "The server did not return a valid broker key for this service contract." .to_string() ))); } }; debug!("broker-key-acquired - hash={}", action_key.hash()); Ok(action_key) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/cmd/instance.rs
wasmer-deploy-cli/src/cmd/instance.rs
use std::ops::Deref; use std::io::Read; use ate::prelude::*; use chrono::NaiveDateTime; use error_chain::bail; use async_stream::stream; use futures_util::pin_mut; use futures_util::stream::StreamExt; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; use ate_comms::StreamSecurity; use crate::error::*; use crate::model::{HistoricActivity, activities, InstanceHello, InstanceCommand, InstanceExport, InstanceCall}; use crate::opt::*; use crate::api::{DeployApi, InstanceClient}; use super::*; pub async fn main_opts_instance_list(api: &mut DeployApi) -> Result<(), InstanceError> { println!("|-------name-------|-------created-------|-exports"); let instances = api.instances().await; let instances = instances.iter_ext(true, true).await?; let instances_ext = { let api = api.clone(); stream! { for instance in instances { let name = instance.name.clone(); yield ( api.instance_chain(instance.name.as_str()) .await .map(|chain| (instance, chain)), name, ) } } }; pin_mut!(instances_ext); while let Some((res, name)) = instances_ext.next().await { let (wallet_instance, _) = match res { Ok(a) => a, Err(err) => { debug!("error loading wallet instance - {} - {}", name, err); println!( "- {:<16} - {:<19} - {}", name, "error", err ); continue; } }; match api.instance_load(&wallet_instance).await { Ok(instance) => { let secs = instance.when_created() / 1000; let nsecs = (instance.when_created() % 1000) * 1000 * 1000; let when = NaiveDateTime::from_timestamp(secs as i64, nsecs as u32); let mut exports = String::new(); for export in instance.exports.iter().await? { if exports.len() > 0 { exports.push_str(","); } exports.push_str(export.binary.as_str()); if export.distributed == false { exports.push_str("*"); } } println!( "- {:<16} - {:<19} - {}", wallet_instance.name, when.format("%Y-%m-%d %H:%M:%S"), exports ); } Err(err) => { debug!("error loading service chain - {}", err); println!( "- {:<16} - {:<19} - {}", wallet_instance.name, "error", err ); } } } Ok(()) } pub async fn main_opts_instance_details( api: &mut DeployApi, inst_url: url::Url, opts: OptsInstanceDetails, ) -> Result<(), InstanceError> { let instance = api.instance_find(opts.name.as_str()) .await; let instance = match instance { Ok(a) => a, Err(InstanceError(InstanceErrorKind::InvalidInstance, _)) => { eprintln!("An instance does not exist for this token."); std::process::exit(1); } Err(err) => { bail!(err); } }; println!("Instance"); println!("{}", serde_json::to_string_pretty(instance.deref()).unwrap()); if let Ok(service_instance) = api.instance_load(instance.deref()).await { println!("{}", serde_json::to_string_pretty(&service_instance.subnet).unwrap()); if service_instance.exports.len().await? > 0 { let id = service_instance.id_str(); let chain = ChainKey::from(service_instance.chain.clone()); println!("ID: {}", id); println!(""); println!("Exports"); for export in service_instance.exports.iter().await? { let url = compute_export_url(&inst_url, &chain, export.binary.as_str()); println!("POST {}", url); println!("{}", serde_json::to_string_pretty(export.deref()).unwrap()); } } } Ok(()) } pub async fn main_opts_instance_create( api: &mut DeployApi, name: Option<String>, group: Option<String>, db_url: url::Url, instance_authority: String, force: bool, ) -> Result<(), InstanceError> { let name = match name { Some(a) => a, None => { ate::crypto::AteHash::generate().to_hex_string()[0..16].to_string() } }; if let Err(err) = api.instance_create(name.clone(), group, db_url, instance_authority, force).await { bail!(err); }; println!("Instance created ({})", name); Ok(()) } pub async fn main_opts_instance_kill( api: &mut DeployApi, name: &str, force: bool, ) -> Result<(), InstanceError> { let (service_instance, wallet_instance) = api.instance_action(name).await?; let name = match service_instance { Ok(service_instance) => { let dio = service_instance.dio_mut(); let name = service_instance.id_str(); debug!("deleting all the roots in the chain"); dio.delete_all_roots().await?; dio.commit().await?; drop(dio); name } Err(err) if force => { warn!("failed to read service instance data - forcing through - {}", err); name.to_string() } Err(err) => { bail!(err); } }; // Now add the history if let Err(err) = api .record_activity(HistoricActivity::InstanceDestroyed( activities::InstanceDestroyed { when: chrono::offset::Utc::now(), by: api.user_identity(), alias: Some(name.clone()), }, )) .await { error!("Error writing activity: {}", err); } debug!("deleting the instance from the user/group"); let _ = wallet_instance.delete()?; api.dio.commit().await?; println!("Instance ({}) has been killed", name); Ok(()) } pub async fn main_opts_instance_shell( api: &mut DeployApi, inst_url: url::Url, name: &str, security: StreamSecurity ) -> Result<(), InstanceError> { let (instance, _) = api.instance_action(name).await?; let instance = instance?; let mut client = InstanceClient::new_ext(inst_url, InstanceClient::PATH_INST, security).await .unwrap(); client.send_hello(InstanceHello { access_token: instance.admin_token.clone(), chain: ChainKey::from(instance.chain.clone()), }).await.unwrap(); client.send_cmd(InstanceCommand::Shell) .await.unwrap(); client.run_shell() .await .map_err(|err| { InstanceErrorKind::InternalError(ate::utils::obscure_error_str(err.to_string().as_str())) })?; Ok(()) } pub async fn main_opts_instance_call( api: &mut DeployApi, inst_url: url::Url, name: &str, format: SerializationFormat, binary: &str, topic: &str, security: StreamSecurity ) -> Result<(), InstanceError> { // Read the object into stdin let mut request = Vec::new(); std::io::stdin() .lock() .read_to_end(&mut request) .map_err(|_| InstanceErrorKind::NoInput)?; let (instance, _) = api.instance_action(name).await?; let instance = instance?; let mut client = InstanceClient::new_ext(inst_url, InstanceClient::PATH_INST, security).await .unwrap(); // Search for an export that matches this binary let export = instance.exports .iter() .await? .filter(|e| e.binary.eq_ignore_ascii_case(binary)) .next() .ok_or_else(|| InstanceErrorKind::NotExported)?; client.send_hello(InstanceHello { access_token: export.access_token.clone(), chain: ChainKey::from(instance.chain.clone()), }).await.unwrap(); client.send_cmd(InstanceCommand::Call(InstanceCall { parent: None, handle: fastrand::u64(..), format, binary: binary.to_string(), topic: topic.to_string(), })).await.unwrap(); client.send_data(request).await.unwrap(); client.run_read() .await .map_err(|err| { InstanceErrorKind::InternalError(ate::utils::obscure_error_str(err.to_string().as_str())) })?; Ok(()) } pub async fn main_opts_instance_export( api: &mut DeployApi, inst_url: url::Url, name: &str, binary: &str, pinned: bool, no_http: bool, no_https: bool, no_bus: bool, ) -> Result<(), InstanceError> { let (service_instance, _wallet_instance) = api.instance_action(name).await?; let access_token = AteHash::generate().to_hex_string(); let (chain, id_str) = match service_instance { Ok(mut service_instance) => { let dio = service_instance.dio_mut(); let chain = service_instance.chain.clone(); let id_str = service_instance.id_str(); service_instance.as_mut().exports.push(InstanceExport { access_token: access_token.clone(), binary: binary.to_string(), distributed: pinned == false, http: no_http == false, https: no_https == false, bus: no_bus == false, pinned: None, })?; dio.commit().await?; drop(dio); (chain, id_str) } Err(err) => { bail!(err); } }; let chain = ChainKey::from(chain); // Build the URL that can be used to access this binary let url = compute_export_url(&inst_url, &chain, binary); // Now add the history if let Err(err) = api .record_activity(HistoricActivity::InstanceExported( activities::InstanceExported { when: chrono::offset::Utc::now(), by: api.user_identity(), alias: Some(id_str.to_string()), binary: binary.to_string(), }, )) .await { error!("Error writing activity: {}", err); } api.dio.commit().await?; println!("Instance ({}) has exported binary ({})", id_str, binary); println!("Authorization: {}", access_token); println!("POST: {}arg0/arg1/...", url); println!("PUT: {}[request]", url); Ok(()) } fn compute_export_url(inst_url: &url::Url, chain: &ChainKey, binary: &str) -> String { // Build the URL that can be used to access this binary let domain = inst_url.domain().unwrap_or_else(|| "localhost"); let url = format!("https://{}{}/{}/{}/", domain, inst_url.path(), chain.to_string(), binary); url } pub async fn main_opts_instance_deport( api: &mut DeployApi, name: &str, access_token: &str, ) -> Result<(), InstanceError> { let (service_instance, _wallet_instance) = api.instance_action(name).await?; let (id, binary) = match service_instance { Ok(mut service_instance) => { let dio = service_instance.dio_mut(); let id = service_instance.id_str(); let export = service_instance.as_mut().exports.iter_mut().await? .filter(|e| e.access_token.eq_ignore_ascii_case(access_token)) .next() .ok_or(InstanceErrorKind::InvalidAccessToken)?; let binary = export.binary.clone(); export.delete()?; dio.commit().await?; drop(dio); (id, binary) } Err(err) => { bail!(err); } }; // Now add the history if let Err(err) = api .record_activity(HistoricActivity::InstanceDeported( activities::InstanceDeported { when: chrono::offset::Utc::now(), by: api.user_identity(), alias: Some(id.clone()), binary: binary.to_string(), }, )) .await { error!("Error writing activity: {}", err); } api.dio.commit().await?; println!("Instance ({}) has deported binary ({})", id, binary); Ok(()) } pub async fn main_opts_instance_clone( _api: &mut DeployApi, _name: &str, ) -> Result<(), InstanceError> { Err(InstanceErrorKind::Unsupported.into()) } pub async fn main_opts_instance_mount( _api: &mut DeployApi, _name: &str, ) -> Result<(), InstanceError> { Err(InstanceErrorKind::Unsupported.into()) } pub async fn main_opts_instance_cidr( api: &mut DeployApi, name: &str, action: OptsCidrAction, ) -> Result<(), InstanceError> { let (instance, _) = api.instance_action(name).await?; let instance = instance?; main_opts_cidr(instance, action).await?; Ok(()) } pub async fn main_opts_instance_peering( api: &mut DeployApi, name: &str, action: OptsPeeringAction, ) -> Result<(), InstanceError> { let (instance, wallet_instance) = api.instance_action(name).await?; let instance = instance?; main_opts_peering(api, instance, wallet_instance, action).await?; Ok(()) } pub async fn main_opts_instance_reset( api: &mut DeployApi, name: &str, ) -> Result<(), InstanceError> { let (instance, _) = api.instance_action(name).await?; let mut instance = instance?; let dio = instance.dio_mut(); { let mut instance = instance.as_mut(); let _ = instance.mesh_nodes.clear().await; } dio.commit().await?; Ok(()) } pub async fn main_opts_instance( opts: OptsInstanceFor, token_path: String, auth_url: url::Url, db_url: url::Url, inst_url: url::Url, security: StreamSecurity ) -> Result<(), InstanceError> { // Check if sudo is needed let needs_sudo = if opts.action().needs_sudo() { true } else { false }; // Determine the instance authority from the session URL let mut instance_authority = inst_url.domain() .map(|a| a.to_string()) .unwrap_or_else(|| "wasmer.sh".to_string()); if instance_authority == "localhost" { instance_authority = "wasmer.sh".to_string(); } // Perform the action let name = opts.action().name(); let mut context = PurposeContext::new(&opts, token_path.as_str(), &auth_url, Some(&db_url), needs_sudo).await?; // Determine what we need to do let purpose: &dyn OptsPurpose<OptsInstanceAction> = &opts; match purpose.action() { OptsInstanceAction::List => { main_opts_instance_list(&mut context.api).await?; } OptsInstanceAction::Details(opts) => { main_opts_instance_details(&mut context.api, inst_url, opts).await?; } OptsInstanceAction::Create(opts) => { main_opts_instance_create(&mut context.api, opts.name, purpose.group_name(), db_url, instance_authority, opts.force).await?; } OptsInstanceAction::Kill(opts_kill) => { if name.is_none() { bail!(InstanceErrorKind::InvalidInstance); } let name = name.unwrap(); main_opts_instance_kill(&mut context.api, name.as_str(), opts_kill.force).await?; } OptsInstanceAction::Shell(_opts_exec) => { if name.is_none() { bail!(InstanceErrorKind::InvalidInstance); } let name = name.unwrap(); main_opts_instance_shell(&mut context.api, inst_url, name.as_str(), security).await?; } OptsInstanceAction::Call(opts_call) => { if name.is_none() { bail!(InstanceErrorKind::InvalidInstance); } let name = name.unwrap(); main_opts_instance_call(&mut context.api, inst_url, name.as_str(), opts_call.format, opts_call.data.as_str(), opts_call.topic.as_str(), security).await?; } OptsInstanceAction::Export(opts_export) => { if name.is_none() { bail!(InstanceErrorKind::InvalidInstance); } let name = name.unwrap(); main_opts_instance_export(&mut context.api, inst_url, name.as_str(), opts_export.binary.as_str(), opts_export.pinned, opts_export.no_http, opts_export.no_https, opts_export.no_bus).await?; } OptsInstanceAction::Deport(opts_deport) => { if name.is_none() { bail!(InstanceErrorKind::InvalidInstance); } let name = name.unwrap(); main_opts_instance_deport(&mut context.api, name.as_str(), opts_deport.token.as_str()).await?; } OptsInstanceAction::Clone(_opts_clone) => { if name.is_none() { bail!(InstanceErrorKind::InvalidInstance); } let name = name.unwrap(); main_opts_instance_clone(&mut context.api, name.as_str()).await?; } OptsInstanceAction::Mount(_opts_mount) => { if name.is_none() { bail!(InstanceErrorKind::InvalidInstance); } let name = name.unwrap(); main_opts_instance_mount(&mut context.api, name.as_str()).await?; } OptsInstanceAction::Cidr(opts_cidr) => { if name.is_none() { bail!(InstanceErrorKind::InvalidInstance); } let name = name.unwrap(); main_opts_instance_cidr(&mut context.api, name.as_str(), opts_cidr.action).await?; } OptsInstanceAction::Peering(opts_peering) => { if name.is_none() { bail!(InstanceErrorKind::InvalidInstance); } let name = name.unwrap(); main_opts_instance_peering(&mut context.api, name.as_str(), opts_peering.action).await?; } OptsInstanceAction::Reset(_opts_reset) => { if name.is_none() { bail!(InstanceErrorKind::InvalidInstance); } let name = name.unwrap(); main_opts_instance_reset(&mut context.api, name.as_str()).await?; } } Ok(()) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/error/core_error.rs
wasmer-deploy-cli/src/error/core_error.rs
use error_chain::error_chain; use crate::request::*; error_chain! { types { CoreError, CoreErrorKind, ResultExt, Result; } links { AteError(::ate::error::AteError, ::ate::error::AteErrorKind); ChainCreationError(::ate::error::ChainCreationError, ::ate::error::ChainCreationErrorKind); SerializationError(::ate::error::SerializationError, ::ate::error::SerializationErrorKind); InvokeError(::ate::error::InvokeError, ::ate::error::InvokeErrorKind); TimeError(::ate::error::TimeError, ::ate::error::TimeErrorKind); LoadError(::ate::error::LoadError, ::ate::error::LoadErrorKind); CommitError(::ate::error::CommitError, ::ate::error::CommitErrorKind); LockError(::ate::error::LockError, ::ate::error::LockErrorKind); } foreign_links { IO(tokio::io::Error); } errors { OperatorBanned { description("the operator is currently banned"), display("the operator is currently banned"), } OperatorNotFound { description("the operator could not be found"), display("the operator could not be found"), } AccountSuspended { description("the account is currently suspended"), display("the account is currently suspended"), } AuthenticationFailed { description("the caller has no authentication to this coin"), display("the caller has no authentication to this coin"), } NoMasterKey { description("this server has not been properly initialized (master key)"), display("this server has not been properly initialized (master key)"), } Forbidden { description("this operation is forbidden"), display("this operation is forbidden"), } MissingTokenIdentity { description("supplied token is missing an identity"), display("supplied token is missing an identity"), } MissingTokenKey { description("supplied token is missing an authentication key"), display("supplied token is missing an authentication key"), } MissingBrokerKey { description("the caller did not provider a broker key"), display("the caller did not provider a broker key"), } NoPayPalConfig { description("this server has not been properly initialized (paypal config)"), display("this server has not been properly initialized (paypal config)"), } SafetyCheckFailed { description("one of the saftey and security failsafes was triggered"), display("one of the saftey and security failsafes was triggered"), } InternalError(code: u16) { description("the server experienced an internal error") display("the server experienced an internal error - code={}", code) } Other(err: String) { description("this server experienced an error"), display("this server experienced an error - {}", err), } } } impl From<ServiceFindFailed> for CoreError { fn from(err: ServiceFindFailed) -> CoreError { match err { ServiceFindFailed::Forbidden => CoreErrorKind::Forbidden.into(), ServiceFindFailed::InternalError(code) => CoreErrorKind::InternalError(code).into(), } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/error/contract_error.rs
wasmer-deploy-cli/src/error/contract_error.rs
use error_chain::error_chain; use crate::model::*; use crate::request::*; use ate::prelude::*; use super::*; error_chain! { types { ContractError, ContractErrorKind, ResultExt, Result; } links { CoreError(super::CoreError, super::CoreErrorKind); QueryError(super::QueryError, super::QueryErrorKind); } foreign_links { IO(tokio::io::Error); } errors { InvalidService { description("service with this code could not be found") display("service with this code could not be found") } UnsupportedCurrency(currency: NationalCurrency) { description("service does not support this currency") display("service does not support this currency ({})", currency) } AlreadyExists(msg: String) { description("the contract already exists") display("{}", msg) } InvalidReference(reference_number: String) { description("invalid reference number"), display("invalid reference number ({})", reference_number), } } } impl From<ContractError> for AteError { fn from(err: ContractError) -> AteError { AteErrorKind::ServiceError(err.to_string()).into() } } impl From<::ate::error::AteError> for ContractError { fn from(err: ::ate::error::AteError) -> Self { ContractErrorKind::CoreError(CoreErrorKind::AteError(err.0)).into() } } impl From<::ate::error::AteErrorKind> for ContractErrorKind { fn from(err: ::ate::error::AteErrorKind) -> Self { ContractErrorKind::CoreError(CoreErrorKind::AteError(err)) } } impl From<::ate::error::ChainCreationError> for ContractError { fn from(err: ::ate::error::ChainCreationError) -> Self { ContractErrorKind::CoreError(CoreErrorKind::ChainCreationError(err.0)).into() } } impl From<::ate::error::ChainCreationErrorKind> for ContractErrorKind { fn from(err: ::ate::error::ChainCreationErrorKind) -> Self { ContractErrorKind::CoreError(CoreErrorKind::ChainCreationError(err)) } } impl From<::ate::error::SerializationError> for ContractError { fn from(err: ::ate::error::SerializationError) -> Self { ContractErrorKind::CoreError(CoreErrorKind::SerializationError(err.0)).into() } } impl From<::ate::error::SerializationErrorKind> for ContractErrorKind { fn from(err: ::ate::error::SerializationErrorKind) -> Self { ContractErrorKind::CoreError(CoreErrorKind::SerializationError(err)) } } impl From<::ate::error::InvokeError> for ContractError { fn from(err: ::ate::error::InvokeError) -> Self { ContractErrorKind::CoreError(CoreErrorKind::InvokeError(err.0)).into() } } impl From<::ate::error::InvokeErrorKind> for ContractErrorKind { fn from(err: ::ate::error::InvokeErrorKind) -> Self { ContractErrorKind::CoreError(CoreErrorKind::InvokeError(err)) } } impl From<::ate::error::TimeError> for ContractError { fn from(err: ::ate::error::TimeError) -> Self { ContractErrorKind::CoreError(CoreErrorKind::TimeError(err.0)).into() } } impl From<::ate::error::TimeErrorKind> for ContractErrorKind { fn from(err: ::ate::error::TimeErrorKind) -> Self { ContractErrorKind::CoreError(CoreErrorKind::TimeError(err)) } } impl From<::ate::error::LoadError> for ContractError { fn from(err: ::ate::error::LoadError) -> Self { ContractErrorKind::CoreError(CoreErrorKind::LoadError(err.0)).into() } } impl From<::ate::error::LoadErrorKind> for ContractErrorKind { fn from(err: ::ate::error::LoadErrorKind) -> Self { ContractErrorKind::CoreError(CoreErrorKind::LoadError(err)) } } impl From<::ate::error::CommitError> for ContractError { fn from(err: ::ate::error::CommitError) -> Self { ContractErrorKind::CoreError(CoreErrorKind::CommitError(err.0)).into() } } impl From<::ate::error::CommitErrorKind> for ContractErrorKind { fn from(err: ::ate::error::CommitErrorKind) -> Self { ContractErrorKind::CoreError(CoreErrorKind::CommitError(err)) } } impl From<::ate::error::LockError> for ContractError { fn from(err: ::ate::error::LockError) -> Self { ContractErrorKind::CoreError(CoreErrorKind::LockError(err.0)).into() } } impl From<::ate::error::LockErrorKind> for ContractErrorKind { fn from(err: ::ate::error::LockErrorKind) -> Self { ContractErrorKind::CoreError(CoreErrorKind::LockError(err)) } } impl From<ContractCreateFailed> for ContractError { fn from(err: ContractCreateFailed) -> ContractError { match err { ContractCreateFailed::AccountSuspended => { ContractErrorKind::CoreError(CoreErrorKind::AccountSuspended).into() } ContractCreateFailed::AlreadyExists(msg) => { ContractErrorKind::AlreadyExists(msg).into() } ContractCreateFailed::AuthenticationFailed => { ContractErrorKind::CoreError(CoreErrorKind::AuthenticationFailed).into() } ContractCreateFailed::Forbidden => { ContractErrorKind::CoreError(CoreErrorKind::Forbidden).into() } ContractCreateFailed::InvalidService => ContractErrorKind::InvalidService.into(), ContractCreateFailed::NoMasterKey => { ContractErrorKind::CoreError(CoreErrorKind::NoMasterKey).into() } ContractCreateFailed::OperatorBanned => { ContractErrorKind::CoreError(CoreErrorKind::OperatorBanned).into() } ContractCreateFailed::OperatorNotFound => { ContractErrorKind::CoreError(CoreErrorKind::OperatorNotFound).into() } ContractCreateFailed::UnsupportedCurrency(currency) => { ContractErrorKind::UnsupportedCurrency(currency).into() } ContractCreateFailed::InternalError(code) => { ContractErrorKind::CoreError(CoreErrorKind::InternalError(code)).into() } } } } impl From<ContractActionFailed> for ContractError { fn from(err: ContractActionFailed) -> ContractError { match err { ContractActionFailed::AccountSuspended => { ContractErrorKind::CoreError(CoreErrorKind::AccountSuspended).into() } ContractActionFailed::AuthenticationFailed => { ContractErrorKind::CoreError(CoreErrorKind::AuthenticationFailed).into() } ContractActionFailed::OperatorBanned => { ContractErrorKind::CoreError(CoreErrorKind::OperatorBanned).into() } ContractActionFailed::OperatorNotFound => { ContractErrorKind::CoreError(CoreErrorKind::OperatorNotFound).into() } ContractActionFailed::NoMasterKey => { ContractErrorKind::CoreError(CoreErrorKind::NoMasterKey).into() } ContractActionFailed::Forbidden => { ContractErrorKind::CoreError(CoreErrorKind::Forbidden).into() } ContractActionFailed::InvalidContractReference(reference) => { ContractErrorKind::InvalidReference(reference).into() } ContractActionFailed::InternalError(code) => { ContractErrorKind::CoreError(CoreErrorKind::InternalError(code)).into() } } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/error/coin_error.rs
wasmer-deploy-cli/src/error/coin_error.rs
use error_chain::error_chain; use crate::request::*; use super::*; error_chain! { types { CoinError, CoinErrorKind, ResultExt, Result; } links { CoreError(super::CoreError, super::CoreErrorKind); } foreign_links { IO(tokio::io::Error); } errors { InvalidReference(reference_number: String) { description("invalid reference number"), display("invalid reference number ({})", reference_number), } EmailError(err: String) { description("failed to send email"), display("failed to send email - {}", err), } InvalidCurrencyError(currency: String) { description("invalid currency"), display("invalid currency ({})", currency), } InvalidCommodity { description("tHe supplied commodity is not vaild"), display("the supplied commodity is not vaild"), } InvalidCoin { description("the supplied coin is not valid"), display("the supplied coin is not valid") } NoOwnership { description("the coins you are accessing are not owned by you anymore"), display("the coins you are accessing are not owned by you anymore"), } InvalidAmount { description("the coin is not big enough to be carved by this amount of the carvng amount is invalid"), display("the coin is not big enough to be carved by this amount of the carvng amount is invalid"), } } } impl From<::ate::error::AteError> for CoinError { fn from(err: ::ate::error::AteError) -> Self { CoinErrorKind::CoreError(CoreErrorKind::AteError(err.0)).into() } } impl From<::ate::error::AteErrorKind> for CoinErrorKind { fn from(err: ::ate::error::AteErrorKind) -> Self { CoinErrorKind::CoreError(CoreErrorKind::AteError(err)) } } impl From<::ate::error::ChainCreationError> for CoinError { fn from(err: ::ate::error::ChainCreationError) -> Self { CoinErrorKind::CoreError(CoreErrorKind::ChainCreationError(err.0)).into() } } impl From<::ate::error::ChainCreationErrorKind> for CoinErrorKind { fn from(err: ::ate::error::ChainCreationErrorKind) -> Self { CoinErrorKind::CoreError(CoreErrorKind::ChainCreationError(err)) } } impl From<::ate::error::SerializationError> for CoinError { fn from(err: ::ate::error::SerializationError) -> Self { CoinErrorKind::CoreError(CoreErrorKind::SerializationError(err.0)).into() } } impl From<::ate::error::SerializationErrorKind> for CoinError { fn from(err: ::ate::error::SerializationErrorKind) -> Self { CoinErrorKind::CoreError(CoreErrorKind::SerializationError(err)).into() } } impl From<::ate::error::InvokeError> for CoinError { fn from(err: ::ate::error::InvokeError) -> Self { CoinErrorKind::CoreError(CoreErrorKind::InvokeError(err.0)).into() } } impl From<::ate::error::InvokeErrorKind> for CoinError { fn from(err: ::ate::error::InvokeErrorKind) -> Self { CoinErrorKind::CoreError(CoreErrorKind::InvokeError(err)).into() } } impl From<::ate::error::TimeError> for CoinError { fn from(err: ::ate::error::TimeError) -> Self { CoinErrorKind::CoreError(CoreErrorKind::TimeError(err.0)).into() } } impl From<::ate::error::TimeErrorKind> for CoinErrorKind { fn from(err: ::ate::error::TimeErrorKind) -> Self { CoinErrorKind::CoreError(CoreErrorKind::TimeError(err)) } } impl From<::ate::error::LoadError> for CoinError { fn from(err: ::ate::error::LoadError) -> Self { CoinErrorKind::CoreError(CoreErrorKind::LoadError(err.0)).into() } } impl From<::ate::error::LoadErrorKind> for CoinErrorKind { fn from(err: ::ate::error::LoadErrorKind) -> Self { CoinErrorKind::CoreError(CoreErrorKind::LoadError(err)) } } impl From<::ate::error::CommitError> for CoinError { fn from(err: ::ate::error::CommitError) -> Self { CoinErrorKind::CoreError(CoreErrorKind::CommitError(err.0)).into() } } impl From<::ate::error::CommitErrorKind> for CoinErrorKind { fn from(err: ::ate::error::CommitErrorKind) -> Self { CoinErrorKind::CoreError(CoreErrorKind::CommitError(err)) } } impl From<::ate::error::LockError> for CoinError { fn from(err: ::ate::error::LockError) -> Self { CoinErrorKind::CoreError(CoreErrorKind::LockError(err.0)).into() } } impl From<::ate::error::LockErrorKind> for CoinErrorKind { fn from(err: ::ate::error::LockErrorKind) -> Self { CoinErrorKind::CoreError(CoreErrorKind::LockError(err)) } } impl From<CoinCarveFailed> for CoinError { fn from(err: CoinCarveFailed) -> CoinError { match err { CoinCarveFailed::AuthenticationFailed => { CoinErrorKind::CoreError(CoreErrorKind::AuthenticationFailed).into() } CoinCarveFailed::InvalidAmount => CoinErrorKind::InvalidAmount.into(), CoinCarveFailed::InvalidCommodity => CoinErrorKind::InvalidCommodity.into(), CoinCarveFailed::InvalidCoin => CoinErrorKind::InvalidCoin.into(), CoinCarveFailed::InternalError(code) => { CoinErrorKind::CoreError(CoreErrorKind::InternalError(code)).into() } } } } impl From<CoinCollectFailed> for CoinError { fn from(err: CoinCollectFailed) -> CoinError { match err { CoinCollectFailed::AuthenticationFailed => { CoinErrorKind::CoreError(CoreErrorKind::AuthenticationFailed).into() } CoinCollectFailed::InvalidCommodity => CoinErrorKind::InvalidCommodity.into(), CoinCollectFailed::InvalidCoin => CoinErrorKind::InvalidCoin.into(), CoinCollectFailed::OperatorBanned => { CoinErrorKind::CoreError(CoreErrorKind::OperatorBanned).into() } CoinCollectFailed::InternalError(code) => { CoinErrorKind::CoreError(CoreErrorKind::InternalError(code)).into() } } } } impl From<CoinRotateFailed> for CoinError { fn from(err: CoinRotateFailed) -> CoinError { match err { CoinRotateFailed::NoOwnership => CoinErrorKind::NoOwnership.into(), CoinRotateFailed::OperatorBanned => { CoinErrorKind::CoreError(CoreErrorKind::OperatorBanned).into() } CoinRotateFailed::OperatorNotFound => { CoinErrorKind::CoreError(CoreErrorKind::OperatorNotFound).into() } CoinRotateFailed::AuthenticationFailed => { CoinErrorKind::CoreError(CoreErrorKind::AuthenticationFailed).into() } CoinRotateFailed::InvalidCommodity => CoinErrorKind::InvalidCommodity.into(), CoinRotateFailed::InvalidCoin => CoinErrorKind::InvalidCoin.into(), CoinRotateFailed::AccountSuspended => { CoinErrorKind::CoreError(CoreErrorKind::AccountSuspended).into() } CoinRotateFailed::InternalError(code) => { CoinErrorKind::CoreError(CoreErrorKind::InternalError(code)).into() } } } } impl From<CoinCombineFailed> for CoinError { fn from(err: CoinCombineFailed) -> CoinError { match err { CoinCombineFailed::AuthenticationFailed => { CoinErrorKind::CoreError(CoreErrorKind::AuthenticationFailed).into() } CoinCombineFailed::OperatorBanned => { CoinErrorKind::CoreError(CoreErrorKind::OperatorBanned).into() } CoinCombineFailed::InvalidCommodity => CoinErrorKind::InvalidCommodity.into(), CoinCombineFailed::InvalidCoin => CoinErrorKind::InvalidCoin.into(), CoinCombineFailed::InvalidRequest(err) => CoinErrorKind::CoreError( CoreErrorKind::InternalError(ate::utils::obscure_error_str(&err)), ) .into(), CoinCombineFailed::InternalError(code) => { CoinErrorKind::CoreError(CoreErrorKind::InternalError(code)).into() } } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/error/mod.rs
wasmer-deploy-cli/src/error/mod.rs
pub mod bus_error; pub mod coin_error; pub mod contract_error; pub mod core_error; pub mod wallet_error; pub mod instance_error; pub use wasmer_auth::error::*; pub use bus_error::BusError; pub use bus_error::BusErrorKind; pub use coin_error::CoinError; pub use coin_error::CoinErrorKind; pub use contract_error::ContractError; pub use contract_error::ContractErrorKind; pub use core_error::CoreError; pub use core_error::CoreErrorKind; pub use wallet_error::WalletError; pub use wallet_error::WalletErrorKind; pub use instance_error::InstanceError; pub use instance_error::InstanceErrorKind;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/error/wallet_error.rs
wasmer-deploy-cli/src/error/wallet_error.rs
use super::*; use crate::request::*; use error_chain::error_chain; error_chain! { types { WalletError, WalletErrorKind, ResultExt, Result; } links { CoreError(super::CoreError, super::CoreErrorKind); CoinError(super::CoinError, super::CoinErrorKind); GatherError(super::GatherError, super::GatherErrorKind); } foreign_links { IO(tokio::io::Error); } errors { InvalidReference(reference_number: String) { description("invalid reference number"), display("invalid reference number ({})", reference_number), } WalletNotEmpty { description("wallet is not empty"), display("wallet is not empty"), } InvoiceAlreadyPaid(invoice_number: String) { description("invoice is already paid"), display("invoice is already paid ({})", invoice_number), } AlreadyPaid { description("the deposit has already been paid"), display("the deposit has already been paid"), } InsufficientCoins { description("insufficient coins"), display("insufficient coins"), } TooSmall { description("the withdrawl amount is too small"), display("the withdrawl amount is too small"), } NotDeposited { description("the funds do not exist as the deposit was never completed") display("the funds do not exist as the deposit was never completed") } WalletLocked { description("the wallet is currently locked for modification due to a concurrent operation"), display("the wallet is currently locked for modification due to a concurrent operation"), } EmailError(err: String) { description("failed to send email"), display("failed to send email - {}", err), } } } impl From<::ate::error::AteError> for WalletError { fn from(err: ::ate::error::AteError) -> Self { WalletErrorKind::CoreError(CoreErrorKind::AteError(err.0)).into() } } impl From<::ate::error::AteErrorKind> for WalletErrorKind { fn from(err: ::ate::error::AteErrorKind) -> Self { WalletErrorKind::CoreError(CoreErrorKind::AteError(err)) } } impl From<::ate::error::ChainCreationError> for WalletError { fn from(err: ::ate::error::ChainCreationError) -> Self { WalletErrorKind::CoreError(CoreErrorKind::ChainCreationError(err.0)).into() } } impl From<::ate::error::ChainCreationErrorKind> for WalletErrorKind { fn from(err: ::ate::error::ChainCreationErrorKind) -> Self { WalletErrorKind::CoreError(CoreErrorKind::ChainCreationError(err)) } } impl From<::ate::error::SerializationError> for WalletError { fn from(err: ::ate::error::SerializationError) -> Self { WalletErrorKind::CoreError(CoreErrorKind::SerializationError(err.0)).into() } } impl From<::ate::error::SerializationErrorKind> for WalletErrorKind { fn from(err: ::ate::error::SerializationErrorKind) -> Self { WalletErrorKind::CoreError(CoreErrorKind::SerializationError(err)) } } impl From<::ate::error::InvokeError> for WalletError { fn from(err: ::ate::error::InvokeError) -> Self { WalletErrorKind::CoreError(CoreErrorKind::InvokeError(err.0)).into() } } impl From<::ate::error::InvokeErrorKind> for WalletErrorKind { fn from(err: ::ate::error::InvokeErrorKind) -> Self { WalletErrorKind::CoreError(CoreErrorKind::InvokeError(err)) } } impl From<::ate::error::TimeError> for WalletError { fn from(err: ::ate::error::TimeError) -> Self { WalletErrorKind::CoreError(CoreErrorKind::TimeError(err.0)).into() } } impl From<::ate::error::TimeErrorKind> for WalletErrorKind { fn from(err: ::ate::error::TimeErrorKind) -> Self { WalletErrorKind::CoreError(CoreErrorKind::TimeError(err)) } } impl From<::ate::error::LoadError> for WalletError { fn from(err: ::ate::error::LoadError) -> Self { WalletErrorKind::CoreError(CoreErrorKind::LoadError(err.0)).into() } } impl From<::ate::error::LoadErrorKind> for WalletErrorKind { fn from(err: ::ate::error::LoadErrorKind) -> Self { WalletErrorKind::CoreError(CoreErrorKind::LoadError(err)) } } impl From<::ate::error::CommitError> for WalletError { fn from(err: ::ate::error::CommitError) -> Self { WalletErrorKind::CoreError(CoreErrorKind::CommitError(err.0)).into() } } impl From<::ate::error::CommitErrorKind> for WalletErrorKind { fn from(err: ::ate::error::CommitErrorKind) -> Self { WalletErrorKind::CoreError(CoreErrorKind::CommitError(err)) } } impl From<::ate::error::LockError> for WalletError { fn from(err: ::ate::error::LockError) -> Self { WalletErrorKind::CoreError(CoreErrorKind::LockError(err.0)).into() } } impl From<::ate::error::LockErrorKind> for WalletErrorKind { fn from(err: ::ate::error::LockErrorKind) -> Self { WalletErrorKind::CoreError(CoreErrorKind::LockError(err)) } } impl From<CancelDepositFailed> for WalletError { fn from(err: CancelDepositFailed) -> WalletError { match err { CancelDepositFailed::AuthenticationFailed => { WalletErrorKind::CoreError(CoreErrorKind::AuthenticationFailed).into() } CancelDepositFailed::AlreadyPaid => WalletErrorKind::AlreadyPaid.into(), CancelDepositFailed::InvalidCommodity => { WalletErrorKind::CoinError(CoinErrorKind::InvalidCommodity).into() } CancelDepositFailed::InvalidCoin => { WalletErrorKind::CoinError(CoinErrorKind::InvalidCoin).into() } CancelDepositFailed::Forbidden => { WalletErrorKind::CoreError(CoreErrorKind::Forbidden).into() } CancelDepositFailed::InternalError(code) => { WalletErrorKind::CoreError(CoreErrorKind::InternalError(code)).into() } } } } impl From<DepositFailed> for WalletError { fn from(err: DepositFailed) -> WalletError { match err { DepositFailed::OperatorBanned => { WalletErrorKind::CoreError(CoreErrorKind::OperatorBanned).into() } DepositFailed::OperatorNotFound => { WalletErrorKind::CoreError(CoreErrorKind::OperatorNotFound).into() } DepositFailed::AuthenticationFailed => { WalletErrorKind::CoreError(CoreErrorKind::AuthenticationFailed).into() } DepositFailed::AccountSuspended => { WalletErrorKind::CoreError(CoreErrorKind::AccountSuspended).into() } DepositFailed::Forbidden => WalletErrorKind::CoreError(CoreErrorKind::Forbidden).into(), DepositFailed::UnsupportedCurrency(code) => { WalletErrorKind::CoinError(CoinErrorKind::InvalidCurrencyError(code.to_string())) .into() } DepositFailed::InternalError(code) => { WalletErrorKind::CoreError(CoreErrorKind::InternalError(code)).into() } } } } impl From<WithdrawFailed> for WalletError { fn from(err: WithdrawFailed) -> WalletError { match err { WithdrawFailed::OperatorBanned => { WalletErrorKind::CoreError(CoreErrorKind::OperatorBanned).into() } WithdrawFailed::OperatorNotFound => { WalletErrorKind::CoreError(CoreErrorKind::OperatorNotFound).into() } WithdrawFailed::AuthenticationFailed => { WalletErrorKind::CoreError(CoreErrorKind::AuthenticationFailed).into() } WithdrawFailed::AccountSuspended => { WalletErrorKind::CoreError(CoreErrorKind::AccountSuspended).into() } WithdrawFailed::AlreadyWithdrawn => WalletErrorKind::AlreadyPaid.into(), WithdrawFailed::NotDeposited => WalletErrorKind::NotDeposited.into(), WithdrawFailed::TooSmall => WalletErrorKind::TooSmall.into(), WithdrawFailed::Forbidden => { WalletErrorKind::CoreError(CoreErrorKind::Forbidden).into() } WithdrawFailed::InvalidCoin => { WalletErrorKind::CoinError(CoinErrorKind::InvalidCoin).into() } WithdrawFailed::InvalidCommodity => { WalletErrorKind::CoinError(CoinErrorKind::InvalidCommodity).into() } WithdrawFailed::UnsupportedCurrency(code) => { WalletErrorKind::CoinError(CoinErrorKind::InvalidCurrencyError(code.to_string())) .into() } WithdrawFailed::InternalError(code) => { WalletErrorKind::CoreError(CoreErrorKind::InternalError(code)).into() } } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/error/instance_error.rs
wasmer-deploy-cli/src/error/instance_error.rs
use error_chain::error_chain; use super::*; error_chain! { types { InstanceError, InstanceErrorKind, ResultExt, Result; } links { CoreError(super::CoreError, super::CoreErrorKind); QueryError(super::QueryError, super::QueryErrorKind); ContractError(super::ContractError, super::ContractErrorKind); FileSystemError(ate_files::error::FileSystemError, ate_files::error::FileSystemErrorKind); } foreign_links { IO(tokio::io::Error); } errors { Unauthorized { description("insufficient access rights - login with sudo") display("insufficient access rights") } AlreadyExists { description("an instance with this name already exists") display("an instance with this name already exists") } InvalidInstance { description("the instance was this name could not be found") display("the instance was this name could not be found") } InvalidAccessToken { description("the access token supplied was not valid") display("the access token supplied was not valid") } NotExported { description("the binary has not been exported on this channel") display("the binary has not been exported on this channel") } InternalError(code: u16) { description("an internal error has occured") display("an internal error has occured - code={}", code) } NoInput { description("no input was supplied to the command") display("no input was supplied to the command") } Unsupported { description("the operation is not yet supported") display("the operation is not yet supported") } } } impl From<::ate::error::AteError> for InstanceError { fn from(err: ::ate::error::AteError) -> Self { InstanceErrorKind::CoreError(CoreErrorKind::AteError(err.0)).into() } } impl From<::ate::error::AteErrorKind> for InstanceErrorKind { fn from(err: ::ate::error::AteErrorKind) -> Self { InstanceErrorKind::CoreError(CoreErrorKind::AteError(err)) } } impl From<::ate::error::ChainCreationError> for InstanceError { fn from(err: ::ate::error::ChainCreationError) -> Self { InstanceErrorKind::CoreError(CoreErrorKind::ChainCreationError(err.0)).into() } } impl From<::ate::error::ChainCreationErrorKind> for InstanceErrorKind { fn from(err: ::ate::error::ChainCreationErrorKind) -> Self { InstanceErrorKind::CoreError(CoreErrorKind::ChainCreationError(err)) } } impl From<::ate::error::SerializationError> for InstanceError { fn from(err: ::ate::error::SerializationError) -> Self { InstanceErrorKind::CoreError(CoreErrorKind::SerializationError(err.0)).into() } } impl From<::ate::error::SerializationErrorKind> for InstanceErrorKind { fn from(err: ::ate::error::SerializationErrorKind) -> Self { InstanceErrorKind::CoreError(CoreErrorKind::SerializationError(err)) } } impl From<::ate::error::InvokeError> for InstanceError { fn from(err: ::ate::error::InvokeError) -> Self { InstanceErrorKind::CoreError(CoreErrorKind::InvokeError(err.0)).into() } } impl From<::ate::error::InvokeErrorKind> for InstanceErrorKind { fn from(err: ::ate::error::InvokeErrorKind) -> Self { InstanceErrorKind::CoreError(CoreErrorKind::InvokeError(err)) } } impl From<::ate::error::TimeError> for InstanceError { fn from(err: ::ate::error::TimeError) -> Self { InstanceErrorKind::CoreError(CoreErrorKind::TimeError(err.0)).into() } } impl From<::ate::error::TimeErrorKind> for InstanceErrorKind { fn from(err: ::ate::error::TimeErrorKind) -> Self { InstanceErrorKind::CoreError(CoreErrorKind::TimeError(err)) } } impl From<::ate::error::LoadError> for InstanceError { fn from(err: ::ate::error::LoadError) -> Self { InstanceErrorKind::CoreError(CoreErrorKind::LoadError(err.0)).into() } } impl From<::ate::error::LoadErrorKind> for InstanceErrorKind { fn from(err: ::ate::error::LoadErrorKind) -> Self { InstanceErrorKind::CoreError(CoreErrorKind::LoadError(err)) } } impl From<::ate::error::CommitError> for InstanceError { fn from(err: ::ate::error::CommitError) -> Self { InstanceErrorKind::CoreError(CoreErrorKind::CommitError(err.0)).into() } } impl From<::ate::error::CommitErrorKind> for InstanceErrorKind { fn from(err: ::ate::error::CommitErrorKind) -> Self { InstanceErrorKind::CoreError(CoreErrorKind::CommitError(err)) } } impl From<::ate::error::LockError> for InstanceError { fn from(err: ::ate::error::LockError) -> Self { InstanceErrorKind::CoreError(CoreErrorKind::LockError(err.0)).into() } } impl From<::ate::error::LockErrorKind> for InstanceErrorKind { fn from(err: ::ate::error::LockErrorKind) -> Self { InstanceErrorKind::CoreError(CoreErrorKind::LockError(err)) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/error/bus_error.rs
wasmer-deploy-cli/src/error/bus_error.rs
use error_chain::error_chain; error_chain! { types { BusError, BusErrorKind, ResultExt, Result; } foreign_links { IO(tokio::io::Error); } errors { LoginFailed { description("failed to login with the supplied token"), display("failed to login with the supplied token"), } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/model/service_instance.rs
wasmer-deploy-cli/src/model/service_instance.rs
use ate::{prelude::DaoVec}; use serde::*; use super::{InstanceExport, InstanceSubnet, MeshNode}; /// Running instance of a particular web assembly application /// within the hosting environment #[derive(Serialize, Deserialize, Debug, Clone)] pub struct ServiceInstance { /// Unique ID of this instance pub id: u128, /// Chain key for this service instance pub chain: String, /// Subnet associated with this instance pub subnet: InstanceSubnet, /// Admin token associated with an instance pub admin_token: String, /// List of all the binaries that are exposed by this instance /// and hence can be invoked by clients pub exports: DaoVec<InstanceExport>, /// List of active nodes currently partipating in the mesh pub mesh_nodes: DaoVec<MeshNode>, } impl ServiceInstance { pub fn id_str(&self) -> String { hex::encode(&self.id.to_be_bytes()) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/model/bag_of_coins.rs
wasmer-deploy-cli/src/model/bag_of_coins.rs
use serde::{Deserialize, Serialize}; #[allow(unused_imports)] use tracing::{debug, error, info, warn}; use crate::model::*; #[derive(Debug, Serialize, Deserialize, Clone)] pub struct BagOfCoins { pub coins: Vec<CarvedCoin>, } impl Default for BagOfCoins { fn default() -> BagOfCoins { BagOfCoins { coins: Vec::new() } } } impl BagOfCoins { pub async fn to_ownerships(&self) -> Vec<Ownership> { let mut owners = self.coins.iter().map(|a| &a.owner).collect::<Vec<_>>(); owners.sort_by(|a, b| a.cmp(b)); owners.dedup_by(|a, b| (*a).eq(b)); let owners = owners.into_iter().map(|a| a.clone()).collect::<Vec<_>>(); owners } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/model/national_currency.rs
wasmer-deploy-cli/src/model/national_currency.rs
use clap::Parser; use serde::*; use std::str::FromStr; use strum::IntoEnumIterator; use strum_macros::Display; use strum_macros::EnumIter; /// Lists all the different national currencies that are available in the /// world plus a set of attributes. #[derive( Serialize, Deserialize, Display, Debug, Parser, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, EnumIter, )] pub enum NationalCurrency { #[clap()] NON, #[clap()] TOK, #[clap()] INV, #[clap()] BIT, #[clap()] EUR, #[clap()] USD, #[clap()] AUD, #[clap()] HKD, #[clap()] CNY, #[clap()] GBP, #[clap()] AAD, #[clap()] AFN, #[clap()] ALL, #[clap()] DZD, #[clap()] AOA, #[clap()] XCD, #[clap()] ARS, #[clap()] AMD, #[clap()] AWG, #[clap()] AZN, #[clap()] BSD, #[clap()] BHD, #[clap()] BDT, #[clap()] BBD, #[clap()] BYR, #[clap()] BZD, #[clap()] BMD, #[clap()] BTN, #[clap()] INR, #[clap()] BOB, #[clap()] BOV, #[clap()] BWP, #[clap()] NOK, #[clap()] BRL, #[clap()] BND, #[clap()] BGN, #[clap()] BIF, #[clap()] KHR, #[clap()] CAD, #[clap()] CVE, #[clap()] KYD, #[clap()] CLF, #[clap()] CLP, #[clap()] COP, #[clap()] COU, #[clap()] KMF, #[clap()] CDF, #[clap()] NZD, #[clap()] CRC, #[clap()] HRK, #[clap()] CUC, #[clap()] CUP, #[clap()] ANG, #[clap()] CZK, #[clap()] DKK, #[clap()] DJF, #[clap()] DOP, #[clap()] EGP, #[clap()] SVC, #[clap()] ERN, #[clap()] ETB, #[clap()] FKP, #[clap()] FJD, #[clap()] GMD, #[clap()] GEL, #[clap()] GHS, #[clap()] GIP, #[clap()] GTQ, #[clap()] GNF, #[clap()] GYD, #[clap()] HTG, #[clap()] HNL, #[clap()] HUF, #[clap()] ISK, #[clap()] IDR, #[clap()] IRR, #[clap()] IQD, #[clap()] ILS, #[clap()] JMD, #[clap()] JPY, #[clap()] JOD, #[clap()] KZT, #[clap()] KES, #[clap()] KPW, #[clap()] KRW, #[clap()] KWD, #[clap()] KGS, #[clap()] LAK, #[clap()] LBP, #[clap()] LSL, #[clap()] ZAR, #[clap()] LRD, #[clap()] LYD, #[clap()] CHF, #[clap()] LTL, #[clap()] MOP, #[clap()] MKD, #[clap()] MGA, #[clap()] MWK, #[clap()] MYR, #[clap()] MVR, #[clap()] MRO, #[clap()] MUR, #[clap()] MXN, #[clap()] MDL, #[clap()] MNT, #[clap()] MAD, #[clap()] MZN, #[clap()] MMK, #[clap()] NAD, #[clap()] NPR, #[clap()] NIO, #[clap()] NGN, #[clap()] OMR, #[clap()] PKR, #[clap()] PAB, #[clap()] PGK, #[clap()] PYG, #[clap()] PEN, #[clap()] PHP, #[clap()] PLN, #[clap()] QAR, #[clap()] RON, #[clap()] RUB, #[clap()] RWF, #[clap()] SHP, #[clap()] WST, #[clap()] STD, #[clap()] SAR, #[clap()] RSD, #[clap()] SCR, #[clap()] SLL, #[clap()] SGD, #[clap()] XSU, #[clap()] SBD, #[clap()] SOS, #[clap()] SSP, #[clap()] LKR, #[clap()] SDG, #[clap()] SRD, #[clap()] SZL, #[clap()] SEK, #[clap()] CHE, #[clap()] CHW, #[clap()] SYP, #[clap()] TWD, #[clap()] TJS, #[clap()] TZS, #[clap()] THB, #[clap()] TOP, #[clap()] TTD, #[clap()] TND, #[clap()] TRY, #[clap()] TMT, #[clap()] UGX, #[clap()] UAH, #[clap()] AED, #[clap()] UYU, #[clap()] UZS, #[clap()] VUV, #[clap()] VEF, #[clap()] VND, #[clap()] YER, #[clap()] XAF, #[clap()] XOF, #[clap()] BAM, #[clap()] ZMW, #[clap()] ZWL, #[clap()] XPF, } impl NationalCurrency { pub fn name(&self) -> &str { self.params().0 } pub fn description(&self) -> String { format!("National currency of feign money ({})", self.name()) } pub fn code(&self) -> &str { self.params().1 } pub fn decimal_points(&self) -> i32 { self.params().2 } /// Can this currency be used as a trade medium between good and services pub fn can_trade(&self) -> bool { self.params().3 } /// Can this currency be exchanged for other currencies pub fn can_exchange(&self) -> bool { self.params().4 } pub fn can_use_in_paypal(&self) -> bool { self.params().5 } pub fn auto_convert(&self) -> bool { self.params().6 } pub fn crypto_url(&self) -> Option<&str> { self.params().7 } fn params(&self) -> (&str, &str, i32, bool, bool, bool, bool, Option<&str>) { match self { NationalCurrency::NON => ( "Unknown currency", "000", 0, false, false, false, false, None, ), NationalCurrency::TOK => ( "Wasmer Coin", "001", 0, true, true, false, true, Some("coin.wasmer.sh"), ), NationalCurrency::INV => ( "Wasmer Invest", "002", 0, false, true, false, false, Some("invest.wasmer.sh"), ), NationalCurrency::BIT => ( "Bitcoin", "003", 0, false, false, false, false, Some("bitcoin.exchange.wasmer.sh"), ), NationalCurrency::EUR => ( "Euro", "978", 2, false, true, true, false, Some("eur.exchange.wasmer.sh"), ), NationalCurrency::USD => ( "US Dollar", "840", 2, false, true, true, false, Some("usd.exchange.wasmer.sh"), ), NationalCurrency::AUD => ( "Australian Dollar", "036", 2, false, true, true, false, Some("aud.exchange.wasmer.sh"), ), NationalCurrency::HKD => ( "Hong Kong Dollar", "344", 2, false, true, true, false, Some("hkd.exchange.wasmer.sh"), ), NationalCurrency::CNY => ( "Yuan Renminbi", "156", 2, false, true, false, false, Some("cny.exchange.wasmer.sh"), ), NationalCurrency::GBP => ( "Pound Sterling", "826", 2, false, true, true, false, Some("gbp.exchange.wasmer.sh"), ), NationalCurrency::AAD => ( "Antarctic Dollar", "004", 2, false, false, true, false, None, ), NationalCurrency::AFN => ("Afghani", "971", 2, false, false, false, false, None), NationalCurrency::ALL => ("Lek", "008", 2, false, false, false, false, None), NationalCurrency::DZD => ("Algerian Dinar", "012", 2, false, false, false, false, None), NationalCurrency::AOA => ("Kwanza", "973", 2, false, false, false, false, None), NationalCurrency::XCD => ( "East Caribbean Dollar", "951", 2, false, false, false, false, None, ), NationalCurrency::ARS => ("Argentine Peso", "032", 2, false, false, false, false, None), NationalCurrency::AMD => ("Armenian Dram", "051", 2, false, false, false, false, None), NationalCurrency::AWG => ("Aruban Florin", "533", 2, false, false, false, false, None), NationalCurrency::AZN => ( "Azerbaijanian Manat", "944", 2, false, false, false, false, None, ), NationalCurrency::BSD => ( "Bahamian Dollar", "044", 2, false, false, false, false, None, ), NationalCurrency::BHD => ("Bahraini Dinar", "048", 3, false, false, false, false, None), NationalCurrency::BDT => ("Taka", "050", 2, false, false, false, false, None), NationalCurrency::BBD => ( "Barbados Dollar", "052", 2, false, false, false, false, None, ), NationalCurrency::BYR => ( "Belarussian Ruble", "974", 0, false, false, false, false, None, ), NationalCurrency::BZD => ("Belize Dollar", "084", 2, false, false, false, false, None), NationalCurrency::BMD => ( "Bermudian Dollar", "060", 2, false, false, false, false, None, ), NationalCurrency::BTN => ("Ngultrum", "064", 2, false, false, false, false, None), NationalCurrency::INR => ("Indian Rupee", "356", 2, false, false, false, false, None), NationalCurrency::BOB => ("Boliviano", "068", 2, false, false, false, false, None), NationalCurrency::BOV => ("Mvdol", "984", 2, false, false, false, false, None), NationalCurrency::BWP => ("Pula", "072", 2, false, false, false, false, None), NationalCurrency::NOK => ( "Norwegian Krone", "578", 2, false, false, false, false, None, ), NationalCurrency::BRL => ("Brazilian Real", "986", 2, false, false, false, false, None), NationalCurrency::BND => ("Brunei Dollar", "096", 2, false, false, false, false, None), NationalCurrency::BGN => ("Bulgarian Lev", "975", 2, false, false, false, false, None), NationalCurrency::BIF => ("Burundi Franc", "108", 0, false, false, false, false, None), NationalCurrency::KHR => ("Riel", "116", 2, false, false, false, false, None), NationalCurrency::CAD => ( "Canadian Dollar", "124", 2, false, false, false, false, None, ), NationalCurrency::CVE => ( "Cape Verde Escudo", "132", 2, false, false, false, false, None, ), NationalCurrency::KYD => ( "Cayman Islands Dollar", "136", 2, false, false, false, false, None, ), NationalCurrency::CLF => ( "Unidad de Fomento", "990", 4, false, false, false, false, None, ), NationalCurrency::CLP => ("Chilean Peso", "152", 0, false, false, false, false, None), NationalCurrency::COP => ("Colombian Peso", "170", 2, false, false, false, false, None), NationalCurrency::COU => ( "Unidad de Valor Real", "970", 2, false, false, false, false, None, ), NationalCurrency::KMF => ("Comoro Franc", "174", 0, false, false, false, false, None), NationalCurrency::CDF => ( "Congolese Franc", "976", 2, false, false, false, false, None, ), NationalCurrency::NZD => ( "New Zealand Dollar", "554", 2, false, false, false, false, None, ), NationalCurrency::CRC => ( "Costa Rican Colon", "188", 2, false, false, false, false, None, ), NationalCurrency::HRK => ("Croatian Kuna", "191", 2, false, false, false, false, None), NationalCurrency::CUC => ( "Peso Convertible", "931", 2, false, false, false, false, None, ), NationalCurrency::CUP => ("Cuban Peso", "192", 2, false, false, false, false, None), NationalCurrency::ANG => ( "Netherlands Antillean Guilder", "532", 2, false, false, false, false, None, ), NationalCurrency::CZK => ("Czech Koruna", "203", 2, false, false, false, false, None), NationalCurrency::DKK => ("Danish Krone", "208", 2, false, false, false, false, None), NationalCurrency::DJF => ("Djibouti Franc", "262", 0, false, false, false, false, None), NationalCurrency::DOP => ("Dominican Peso", "214", 2, false, false, false, false, None), NationalCurrency::EGP => ("Egyptian Pound", "818", 2, false, false, false, false, None), NationalCurrency::SVC => ( "El Salvador Colon", "222", 2, false, false, false, false, None, ), NationalCurrency::ERN => ("Nakfa", "232", 2, false, false, false, false, None), NationalCurrency::ETB => ("Ethiopian Birr", "230", 2, false, false, false, false, None), NationalCurrency::FKP => ( "Falkland Islands Pound", "238", 2, false, false, false, false, None, ), NationalCurrency::FJD => ("Fiji Dollar", "242", 2, false, false, false, false, None), NationalCurrency::GMD => ("Dalasi", "270", 2, false, false, false, false, None), NationalCurrency::GEL => ("Lari", "981", 2, false, false, false, false, None), NationalCurrency::GHS => ("Ghana Cedi", "936", 2, false, false, false, false, None), NationalCurrency::GIP => ( "Gibraltar Pound", "292", 2, false, false, false, false, None, ), NationalCurrency::GTQ => ("Quetzal", "320", 2, false, false, false, false, None), NationalCurrency::GNF => ("Guinea Franc", "324", 0, false, false, false, false, None), NationalCurrency::GYD => ("Guyana Dollar", "328", 2, false, false, false, false, None), NationalCurrency::HTG => ("Gourde", "332", 2, false, false, false, false, None), NationalCurrency::HNL => ("Lempira", "340", 2, false, false, false, false, None), NationalCurrency::HUF => ("Forint", "348", 2, false, false, false, false, None), NationalCurrency::ISK => ("Iceland Krona", "352", 0, false, false, false, false, None), NationalCurrency::IDR => ("Rupiah", "360", 2, false, false, false, false, None), NationalCurrency::IRR => ("Iranian Rial", "364", 2, false, false, false, false, None), NationalCurrency::IQD => ("Iraqi Dinar", "368", 3, false, false, false, false, None), NationalCurrency::ILS => ( "New Israeli Sheqel", "376", 2, false, false, false, false, None, ), NationalCurrency::JMD => ( "Jamaican Dollar", "388", 2, false, false, false, false, None, ), NationalCurrency::JPY => ("Yen", "392", 0, false, false, false, false, None), NationalCurrency::JOD => ( "Jordanian Dinar", "400", 3, false, false, false, false, None, ), NationalCurrency::KZT => ("Tenge", "398", 2, false, false, false, false, None), NationalCurrency::KES => ( "Kenyan Shilling", "404", 2, false, false, false, false, None, ), NationalCurrency::KPW => ( "North Korean Won", "408", 2, false, false, false, false, None, ), NationalCurrency::KRW => ("Won", "410", 0, false, false, false, false, None), NationalCurrency::KWD => ("Kuwaiti Dinar", "414", 3, false, false, false, false, None), NationalCurrency::KGS => ("Som", "417", 2, false, false, false, false, None), NationalCurrency::LAK => ("Kip", "418", 2, false, false, false, false, None), NationalCurrency::LBP => ("Lebanese Pound", "422", 2, false, false, false, false, None), NationalCurrency::LSL => ("Loti", "426", 2, false, false, false, false, None), NationalCurrency::ZAR => ("Rand", "710", 2, false, false, false, false, None), NationalCurrency::LRD => ( "Liberian Dollar", "430", 2, false, false, false, false, None, ), NationalCurrency::LYD => ("Libyan Dinar", "434", 3, false, false, false, false, None), NationalCurrency::CHF => ("Swiss Franc", "756", 2, false, false, false, false, None), NationalCurrency::LTL => ( "Lithuanian Litas", "440", 2, false, false, false, false, None, ), NationalCurrency::MOP => ("Pataca", "446", 2, false, false, false, false, None), NationalCurrency::MKD => ("Denar", "807", 2, false, false, false, false, None), NationalCurrency::MGA => ( "Malagasy Ariary", "969", 2, false, false, false, false, None, ), NationalCurrency::MWK => ("Kwacha", "454", 2, false, false, false, false, None), NationalCurrency::MYR => ( "Malaysian Ringgit", "458", 2, false, false, false, false, None, ), NationalCurrency::MVR => ("Rufiyaa", "462", 2, false, false, false, false, None), NationalCurrency::MRO => ("Ouguiya", "478", 2, false, false, false, false, None), NationalCurrency::MUR => ( "Mauritius Rupee", "480", 2, false, false, false, false, None, ), NationalCurrency::MXN => ("Mexican Peso", "484", 2, false, false, false, false, None), NationalCurrency::MDL => ("Moldovan Leu", "498", 2, false, false, false, false, None), NationalCurrency::MNT => ("Tugrik", "496", 2, false, false, false, false, None), NationalCurrency::MAD => ( "Moroccan Dirham", "504", 2, false, false, false, false, None, ), NationalCurrency::MZN => ( "Mozambique Metical", "943", 2, false, false, false, false, None, ), NationalCurrency::MMK => ("Kyat", "104", 2, false, false, false, false, None), NationalCurrency::NAD => ("Namibia Dollar", "516", 2, false, false, false, false, None), NationalCurrency::NPR => ("Nepalese Rupee", "524", 2, false, false, false, false, None), NationalCurrency::NIO => ("Cordoba Oro", "558", 2, false, false, false, false, None), NationalCurrency::NGN => ("Naira", "566", 2, false, false, false, false, None), NationalCurrency::OMR => ("Rial Omani", "512", 3, false, false, false, false, None), NationalCurrency::PKR => ("Pakistan Rupee", "586", 2, false, false, false, false, None), NationalCurrency::PAB => ("Balboa", "590", 2, false, false, false, false, None), NationalCurrency::PGK => ("Kina", "598", 2, false, false, false, false, None), NationalCurrency::PYG => ("Guarani", "600", 0, false, false, false, false, None), NationalCurrency::PEN => ("Nuevo Sol", "604", 2, false, false, false, false, None), NationalCurrency::PHP => ( "Philippine Peso", "608", 2, false, false, false, false, None, ), NationalCurrency::PLN => ("Zloty", "985", 2, false, false, false, false, None), NationalCurrency::QAR => ("Qatari Rial", "634", 2, false, false, false, false, None), NationalCurrency::RON => ( "New Romanian Leu", "946", 2, false, false, false, false, None, ), NationalCurrency::RUB => ("Russian Ruble", "643", 2, false, false, false, false, None), NationalCurrency::RWF => ("Rwanda Franc", "646", 0, false, false, false, false, None), NationalCurrency::SHP => ( "Saint Helena Pound", "654", 2, false, false, false, false, None, ), NationalCurrency::WST => ("Tala", "882", 2, false, false, false, false, None), NationalCurrency::STD => ("Dobra", "678", 2, false, false, false, false, None), NationalCurrency::SAR => ("Saudi Riyal", "682", 2, false, false, false, false, None), NationalCurrency::RSD => ("Serbian Dinar", "941", 2, false, false, false, false, None), NationalCurrency::SCR => ( "Seychelles Rupee", "690", 2, false, false, false, false, None, ), NationalCurrency::SLL => ("Leone", "694", 2, false, false, false, false, None), NationalCurrency::SGD => ( "Singapore Dollar", "702", 2, false, false, false, false, None, ), NationalCurrency::XSU => ("Sucre", "994", 0, false, false, false, false, None), NationalCurrency::SBD => ( "Solomon Islands Dollar", "090", 2, false, false, false, false, None, ), NationalCurrency::SOS => ( "Somali Shilling", "706", 2, false, false, false, false, None, ), NationalCurrency::SSP => ( "South Sudanese Pound", "728", 2, false, false, false, false, None, ), NationalCurrency::LKR => ( "Sri Lanka Rupee", "144", 2, false, false, false, false, None, ), NationalCurrency::SDG => ("Sudanese Pound", "938", 2, false, false, false, false, None), NationalCurrency::SRD => ("Surinam Dollar", "968", 2, false, false, false, false, None), NationalCurrency::SZL => ("Lilangeni", "748", 2, false, false, false, false, None), NationalCurrency::SEK => ("Swedish Krona", "752", 2, false, false, false, false, None), NationalCurrency::CHE => ("WIR Euro", "947", 2, false, false, false, false, None), NationalCurrency::CHW => ("WIR Franc", "948", 2, false, false, false, false, None), NationalCurrency::SYP => ("Syrian Pound", "760", 2, false, false, false, false, None), NationalCurrency::TWD => ( "New Taiwan Dollar", "901", 2, false, false, false, false, None, ), NationalCurrency::TJS => ("Somoni", "972", 2, false, false, false, false, None), NationalCurrency::TZS => ( "Tanzanian Shilling", "834", 2, false, false, false, false, None, ), NationalCurrency::THB => ("Baht", "764", 2, false, false, false, false, None), NationalCurrency::TOP => ("Pa’anga", "776", 2, false, false, false, false, None), NationalCurrency::TTD => ( "Trinidad and Tobago Dollar", "780", 2, false, false, false, false, None, ), NationalCurrency::TND => ("Tunisian Dinar", "788", 3, false, false, false, false, None), NationalCurrency::TRY => ("Turkish Lira", "949", 2, false, false, false, false, None), NationalCurrency::TMT => ( "Turkmenistan New Manat", "934", 2, false, false, false, false, None, ), NationalCurrency::UGX => ( "Uganda Shilling", "800", 0, false, false, false, false, None, ), NationalCurrency::UAH => ("Hryvnia", "980", 2, false, false, false, false, None), NationalCurrency::AED => ("UAE Dirham", "784", 2, false, false, false, false, None), NationalCurrency::UYU => ("Peso Uruguayo", "858", 2, false, false, false, false, None), NationalCurrency::UZS => ("Uzbekistan Sum", "860", 2, false, false, false, false, None), NationalCurrency::VUV => ("Vatu", "548", 0, false, false, false, false, None), NationalCurrency::VEF => ("Bolivar", "937", 2, false, false, false, false, None), NationalCurrency::VND => ("Dong", "704", 0, false, false, false, false, None), NationalCurrency::YER => ("Yemeni Rial", "886", 2, false, false, false, false, None), NationalCurrency::XAF => ( "Central African CFA franc", "950", 0, false, false, false, false, None, ), NationalCurrency::XOF => ( "West African CFA franc", "952", 0, false, false, false, false, None, ), NationalCurrency::BAM => ( "Bosnia and Herzegovina convertible mark", "977", 2, false, false, false, false, None, ), NationalCurrency::ZMW => ("Zambian Kwacha", "967", 2, false, false, false, false, None), NationalCurrency::ZWL => ( "Zimbabwe Dollar", "932", 2, false, false, false, false, None, ), NationalCurrency::XPF => ("CFP franc", "953", 0, false, false, false, false, None), } } } impl FromStr for NationalCurrency { type Err = std::io::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { for currency in NationalCurrency::iter() { if currency.to_string().eq_ignore_ascii_case(s) { return Ok(currency); } if currency.name().eq_ignore_ascii_case(s) { return Ok(currency); } if currency.code().eq_ignore_ascii_case(s) { return Ok(currency); } } Err(std::io::Error::new( std::io::ErrorKind::Other, format!("Currency is not valid: {}.", s), )) } } impl Default for NationalCurrency { fn default() -> Self { Self::EUR } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/model/instance_subnet.rs
wasmer-deploy-cli/src/model/instance_subnet.rs
use serde::*; use ate::prelude::*; use super::IpCidr; /// Subnets make up all the networks for a specific network #[derive(Debug, Serialize, Deserialize, Clone)] pub struct InstanceSubnet { /// List of all the IP addresses for this subnet pub cidrs: Vec<IpCidr>, /// Access token used to grant access to this subnet pub network_token: String, /// List of all the networks this instance is peered with pub peerings: Vec<InstancePeering>, } /// Peerings allow this network to communicate with other /// networks #[derive(Debug, Serialize, Deserialize, Clone)] pub struct InstancePeering { /// ID of the instance this is peered with pub id: u128, /// Name of the instance this is paired with pub name: String, /// Chain key for this switch pub chain: ChainKey, /// Access token used to connect with the peered network pub access_token: String, }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/model/historic_day.rs
wasmer-deploy-cli/src/model/historic_day.rs
use serde::*; use super::*; /// Represents a day of activity that has happened /// in ones account #[derive(Serialize, Deserialize, Debug, Clone)] pub struct HistoricDay { // Which day does this data relate to pub day: u32, // Represents an activity that has occured on this day pub activities: Vec<HistoricActivity>, }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/model/master_authority.rs
wasmer-deploy-cli/src/model/master_authority.rs
use ate::{prelude::*}; use serde::*; /// Master authority is a row that holds the access rights /// to one or more elements in a chain-of-trust. The keys /// can be rotated periodically. #[derive(Serialize, Deserialize, Debug, Clone)] pub struct MasterAuthorityInner { /// Read key used access the service instance pub read: EncryptKey, /// Write key used to access the service instance pub write: PrivateSignKey, } /// Running instance of a particular web assembly application /// within the hosting environment #[derive(Serialize, Deserialize, Debug, Clone)] pub struct MasterAuthority { /// Inner area that is protected by a master key and is only accessible by the broker pub inner_broker: PublicEncryptedSecureData<MasterAuthorityInner>, /// Inner area that is protected by a master key and is only accessible by the owner pub inner_owner: PublicEncryptedSecureData<MasterAuthorityInner>, } impl std::fmt::Display for MasterAuthority { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "master_authority(broker={},owner={})", self.inner_broker, self.inner_owner) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/model/contract.rs
wasmer-deploy-cli/src/model/contract.rs
use ate::prelude::*; use chrono::DateTime; use chrono::Utc; use serde::*; use super::*; /// Contracts are agreement between a consumer and provider for /// particular services. Only brokers may perform actions on /// active contracts #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Contract { /// Reference number assigned to this contract pub reference_number: String, /// The country that you pay GST tax in for this services pub gst_country: Country, /// The wallet that will be debited pub debit_wallet: PrimaryKey, /// The rate card that will be used for this contract pub rate_card: RateCard, /// The advertised service being consumed by the provider pub service: AdvertisedService, /// Status of the contract pub status: ContractStatus, /// Limited duration contracts will expire after a /// certain period of time without incurring further /// charges pub expires: Option<DateTime<Utc>>, /// Key used by the broker to gain access to the wallet /// (only after the provider supplies their key) pub broker_unlock_key: EncryptKey, /// Broker key encrypted with the providers public key pub broker_key: PublicEncryptedSecureData<EncryptKey>, /// Metrics for difference instance of this service with /// unqiue reference numbers (field=related_to) pub metrics: DaoVec<ContractMetrics>, }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/model/wallet_instance.rs
wasmer-deploy-cli/src/model/wallet_instance.rs
use serde::*; use ate::prelude::ChainKey; /// Running instance of a particular web assembly application /// within the hosting environment #[derive(Serialize, Deserialize, Debug, Clone)] pub struct WalletInstance { /// Name of the instance attached to the identity pub name: String, /// ID of this instance within Wasmer pub id: u128, /// Chain key for this service instance pub chain: ChainKey, } impl WalletInstance { pub fn id_str(&self) -> String { hex::encode(&self.id.to_be_bytes()) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/model/country.rs
wasmer-deploy-cli/src/model/country.rs
use clap::Parser; use serde::*; use std::str::FromStr; use strum::IntoEnumIterator; use strum_macros::Display; use strum_macros::EnumIter; use crate::model::*; /// Lists all the different national currencies that are available in the /// world plus a set of attributes. #[derive( Serialize, Deserialize, Display, Debug, Parser, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, EnumIter, )] pub enum Country { #[clap()] ABW, #[clap()] AFG, #[clap()] AGO, #[clap()] AIA, #[clap()] ALA, #[clap()] ALB, #[clap()] AND, #[clap()] ARE, #[clap()] ARG, #[clap()] ARM, #[clap()] ASM, #[clap()] ATA, #[clap()] ATF, #[clap()] ATG, #[clap()] AUS, #[clap()] AUT, #[clap()] AZE, #[clap()] BDI, #[clap()] BEL, #[clap()] BEN, #[clap()] BES, #[clap()] BFA, #[clap()] BGD, #[clap()] BGR, #[clap()] BHR, #[clap()] BHS, #[clap()] BIH, #[clap()] BLM, #[clap()] BLR, #[clap()] BLZ, #[clap()] BMU, #[clap()] BOL, #[clap()] BRA, #[clap()] BRB, #[clap()] BRN, #[clap()] BTN, #[clap()] BVT, #[clap()] BWA, #[clap()] CAF, #[clap()] CAN, #[clap()] CCK, #[clap()] CHE, #[clap()] CHL, #[clap()] CHN, #[clap()] CIV, #[clap()] CMR, #[clap()] COD, #[clap()] COG, #[clap()] COK, #[clap()] COL, #[clap()] COM, #[clap()] CPV, #[clap()] CPI, #[clap()] CUB, #[clap()] CUW, #[clap()] CXR, #[clap()] CYM, #[clap()] CYP, #[clap()] CZE, #[clap()] DEU, #[clap()] DJI, #[clap()] DMA, #[clap()] DNK, #[clap()] DOM, #[clap()] DZA, #[clap()] ECU, #[clap()] EGY, #[clap()] ERI, #[clap()] ESP, #[clap()] EST, #[clap()] ETH, #[clap()] FIN, #[clap()] FJI, #[clap()] FLK, #[clap()] FRA, #[clap()] FRO, #[clap()] FSM, #[clap()] GAB, #[clap()] GBR, #[clap()] GEO, #[clap()] GGY, #[clap()] GHA, #[clap()] GIB, #[clap()] GIN, #[clap()] GLP, #[clap()] GMB, #[clap()] GNB, #[clap()] GNQ, #[clap()] GRC, #[clap()] GRD, #[clap()] GRL, #[clap()] GTM, #[clap()] GUF, #[clap()] GUM, #[clap()] GUY, #[clap()] HKG, #[clap()] HMD, #[clap()] HND, #[clap()] HRV, #[clap()] HTI, #[clap()] HUN, #[clap()] IDN, #[clap()] IMN, #[clap()] IND, #[clap()] IOT, #[clap()] IRL, #[clap()] IRN, #[clap()] IRQ, #[clap()] ISL, #[clap()] ISR, #[clap()] ITA, #[clap()] JAM, #[clap()] JEY, #[clap()] JOR, #[clap()] JPN, #[clap()] KAZ, #[clap()] KEN, #[clap()] KGZ, #[clap()] KHM, #[clap()] KIR, #[clap()] KNA, #[clap()] KOR, #[clap()] KWT, #[clap()] LAO, #[clap()] LBN, #[clap()] LBR, #[clap()] LBY, #[clap()] LCA, #[clap()] LIE, #[clap()] LKA, #[clap()] LSO, #[clap()] LTU, #[clap()] LUX, #[clap()] LVA, #[clap()] MAC, #[clap()] MAF, #[clap()] MAR, #[clap()] MCO, #[clap()] MDA, #[clap()] MDG, #[clap()] MDV, #[clap()] MEX, #[clap()] MHL, #[clap()] MKD, #[clap()] MLI, #[clap()] MLT, #[clap()] MMR, #[clap()] MNE, #[clap()] MNG, #[clap()] MNP, #[clap()] MOZ, #[clap()] MRT, #[clap()] MSR, #[clap()] MTQ, #[clap()] MUS, #[clap()] MWI, #[clap()] MYS, #[clap()] MYT, #[clap()] NAM, #[clap()] NCL, #[clap()] NER, #[clap()] NFK, #[clap()] NGA, #[clap()] NIC, #[clap()] NIU, #[clap()] NLD, #[clap()] NOR, #[clap()] NPL, #[clap()] NRU, #[clap()] NZL, #[clap()] OMN, #[clap()] PAK, #[clap()] PAN, #[clap()] PCN, #[clap()] PER, #[clap()] PHL, #[clap()] PLW, #[clap()] PNG, #[clap()] POL, #[clap()] PRI, #[clap()] PRK, #[clap()] PRT, #[clap()] PRY, #[clap()] PSE, #[clap()] PYF, #[clap()] QAT, #[clap()] REU, #[clap()] ROU, #[clap()] RUS, #[clap()] RWA, #[clap()] SAU, #[clap()] SDN, #[clap()] SEN, #[clap()] SGP, #[clap()] SGS, #[clap()] SHN, #[clap()] SJM, #[clap()] SLB, #[clap()] SLE, #[clap()] SLV, #[clap()] SMR, #[clap()] SOM, #[clap()] SPM, #[clap()] SRB, #[clap()] SSD, #[clap()] STP, #[clap()] SUR, #[clap()] SVK, #[clap()] SVN, #[clap()] SWE, #[clap()] SWZ, #[clap()] SXM, #[clap()] SYC, #[clap()] SYR, #[clap()] TCA, #[clap()] TCD, #[clap()] TGO, #[clap()] THA, #[clap()] TJK, #[clap()] TKL, #[clap()] TKM, #[clap()] TLS, #[clap()] TON, #[clap()] TTO, #[clap()] TUN, #[clap()] TUR, #[clap()] TUV, #[clap()] TWN, #[clap()] TZA, #[clap()] UGA, #[clap()] UKR, #[clap()] UMI, #[clap()] URY, #[clap()] USA, #[clap()] UZB, #[clap()] VAT, #[clap()] VCT, #[clap()] VEN, #[clap()] VGB, #[clap()] VIR, #[clap()] VNM, #[clap()] VUT, #[clap()] WLF, #[clap()] WSM, #[clap()] YEM, #[clap()] ZAF, #[clap()] ZMB, #[clap()] ZWE, } impl Country { pub fn official_name(&self) -> &str { self.params().0 } pub fn short_name(&self) -> &str { self.params().1 } pub fn iso2(&self) -> &str { self.params().2 } pub fn iso3(&self) -> &str { self.params().3 } pub fn num3(&self) -> u16 { self.params().4 } pub fn national_currency(&self) -> NationalCurrency { self.params().5 } pub fn digital_gst(&self) -> Option<Decimal> { self.params().6 } fn params( &self, ) -> ( &str, &str, &str, &str, u16, NationalCurrency, Option<Decimal>, ) { match self { Country::ABW => ( "Aruba", "Aruba", "AW", "ABW", 533, NationalCurrency::AWG, None, ), Country::AFG => ( "Islamic Republic of Afghanistan", "Afghanistan", "AF", "AFG", 004, NationalCurrency::AFN, None, ), Country::AGO => ( "Republic of Angola", "Angola", "AO", "AGO", 024, NationalCurrency::AOA, Some(Decimal::from_str("14.0").unwrap()), ), Country::AIA => ( "Anguilla", "Anguilla", "AI", "AIA", 660, NationalCurrency::XCD, None, ), Country::ALA => ( "Åland Islands", "Åland Islands", "AX", "ALA", 248, NationalCurrency::EUR, None, ), Country::ALB => ( "Republic of Albania", "Albania", "AL", "ALB", 008, NationalCurrency::ALL, Some(Decimal::from_str("20.0").unwrap()), ), Country::AND => ( "Principality of Andorra", "Andorra", "AN", "AND", 020, NationalCurrency::EUR, Some(Decimal::from_str("4.5").unwrap()), ), Country::ARE => ( "United Arab Emirates", "Emirates", "AE", "ARE", 784, NationalCurrency::AED, None, ), Country::ARG => ( "Argentine Republic", "Argentina", "AR", "ARG", 032, NationalCurrency::ARS, Some(Decimal::from_str("20.0").unwrap()), ), Country::ARM => ( "Republic of Armenia", "Armenia", "AM", "ARM", 051, NationalCurrency::AMD, Some(Decimal::from_str("20.0").unwrap()), ), Country::ASM => ( "American Samoa", "American Samoa", "AS", "ASM", 016, NationalCurrency::WST, None, ), Country::ATA => ( "Antarctica", "Antarctica", "AQ", "ATA", 010, NationalCurrency::AAD, None, ), Country::ATF => ( "French Southern and Antarctic Lands", "French Southern Territories", "TF", "ATF", 260, NationalCurrency::EUR, None, ), Country::ATG => ( "Antigua and Barbuda", "Antigua and Barbuda", "AG", "ATG", 028, NationalCurrency::XCD, None, ), Country::AUS => ( "Commonwealth of Australia", "Australia", "AU", "AUS", 036, NationalCurrency::AUD, Some(Decimal::from_str("10.0").unwrap()), ), Country::AUT => ( "Republic of Austria", "Austria", "AT", "AUT", 040, NationalCurrency::EUR, Some(Decimal::from_str("20.0").unwrap()), ), Country::AZE => ( "Republic of Azerbaijan", "Azerbaijan", "AZ", "AZE", 031, NationalCurrency::AZN, Some(Decimal::from_str("12.0").unwrap()), ), Country::BDI => ( "Republic of Burundi", "Burundi", "BI", "BDI", 108, NationalCurrency::BIF, None, ), Country::BEL => ( "Kingdom of Belgium", "Belgium", "BE", "BEL", 056, NationalCurrency::EUR, Some(Decimal::from_str("21.0").unwrap()), ), Country::BEN => ( "Republic of Benin", "Benin", "BJ", "BEN", 204, NationalCurrency::XOF, None, ), Country::BES => ( "Bonaire, Sint Eustatius and Saba", "Caribbean Netherlands", "BQ", "BES", 535, NationalCurrency::USD, None, ), Country::BFA => ( "Burkina Faso", "Burkina Faso", "BF", "BFA", 854, NationalCurrency::XOF, None, ), Country::BGD => ( "People's Republic of Bangladesh", "Bangladesh", "BD", "BGD", 050, NationalCurrency::BDT, Some(Decimal::from_str("15.0").unwrap()), ), Country::BGR => ( "Republic of Bulgaria", "Bulgaria", "BG", "BGR", 100, NationalCurrency::BGN, None, ), Country::BHR => ( "Kingdom of Bahrain", "Bahrain", "BH", "BHR", 048, NationalCurrency::BHD, None, ), Country::BHS => ( "Commonwealth of The Bahamas", "Bahamas", "BS", "BHS", 044, NationalCurrency::BSD, Some(Decimal::from_str("12.0").unwrap()), ), Country::BIH => ( "Bosnia and Herzegovina", "Bosnia and Herzegovina", "BA", "BIH", 070, NationalCurrency::BAM, None, ), Country::BLM => ( "Saint Barthélemy", "Saint Barthélemy", "BL", "BLM", 652, NationalCurrency::EUR, None, ), Country::BLR => ( "Republic of Belarus", "Belarus", "BY", "BLR", 112, NationalCurrency::BYR, Some(Decimal::from_str("20.0").unwrap()), ), Country::BLZ => ( "Belize", "Belize", "BZ", "BLZ", 084, NationalCurrency::BZD, None, ), Country::BMU => ( "Bermuda", "Bermuda", "BM", "BMU", 060, NationalCurrency::BMD, None, ), Country::BOL => ( "Plurinational State of Bolivia", "Bolivia", "BO", "BOL", 068, NationalCurrency::BOB, None, ), Country::BRA => ( "Federative Republic of Brazil", "Brazil", "BR", "BRA", 076, NationalCurrency::BRL, Some(Decimal::from_str("2.0").unwrap()), ), Country::BRB => ( "Barbados", "Barbados", "BB", "BRB", 052, NationalCurrency::BBD, None, ), Country::BRN => ( "Nation of Brunei, the Abode of Peace", "Brunei", "BN", "BRN", 096, NationalCurrency::BND, None, ), Country::BTN => ( "Kingdom of Bhutan", "Bhutan", "BT", "BTN", 064, NationalCurrency::BTN, None, ), Country::BVT => ( "Bouvet Island", "Bouvet Island", "BV", "BVT", 074, NationalCurrency::NOK, None, ), Country::BWA => ( "Republic of Botswana", "Botswana", "BW", "BWA", 072, NationalCurrency::BWP, None, ), Country::CAF => ( "Central African Republic", "Central African Republic", "CF", "CAF", 140, NationalCurrency::XAF, None, ), Country::CAN => ( "Canada", "Canada", "CA", "CAN", 124, NationalCurrency::CAD, Some(Decimal::from_str("5.0").unwrap()), ), Country::CCK => ( "Territory of Cocos {Keeling} Islands", "Cocos {Keeling} Islands", "CC", "CCK", 166, NationalCurrency::AUD, Some(Decimal::from_str("10.0").unwrap()), ), Country::CHE => ( "Swiss Confederation", "Switzerland", "CH", "CHE", 756, NationalCurrency::CHF, None, ), Country::CHL => ( "Republic of Chile", "Chile", "CL", "CHL", 152, NationalCurrency::CLP, Some(Decimal::from_str("19.0").unwrap()), ), Country::CHN => ( "People's Republic of China", "China", "CN", "CHN", 156, NationalCurrency::CNY, Some(Decimal::from_str("6.0").unwrap()), ), Country::CIV => ( "Republic of Côte d'Ivoire", "Côte d'Ivoire", "CI", "CIV", 384, NationalCurrency::XOF, None, ), Country::CMR => ( "Republic of Cameroon", "Cameroon", "CM", "CMR", 120, NationalCurrency::XAF, Some(Decimal::from_str("20.0").unwrap()), ), Country::COD => ( "Democratic Republic of the Congo", "Congo", "CD", "COD", 180, NationalCurrency::XAF, None, ), Country::COG => ( "Republic of the Congo", "Congo Republic", "CG", "COG", 178, NationalCurrency::XAF, None, ), Country::COK => ( "Cook Islands", "Cook Islands", "CK", "COK", 184, NationalCurrency::NZD, None, ), Country::COL => ( "Republic of Colombia", "Colombia", "CO", "COL", 170, NationalCurrency::COP, Some(Decimal::from_str("19.0").unwrap()), ), Country::COM => ( "Union of the Comoros", "Comoros", "KM", "COM", 174, NationalCurrency::KMF, None, ), Country::CPV => ( "Republic of Cabo Verde", "Cape Verde", "CV", "CPV", 132, NationalCurrency::CVE, None, ), Country::CPI => ( "Republic of Costa Rica", "Costa Rica", "CR", "CPI", 188, NationalCurrency::CRC, Some(Decimal::from_str("19.0").unwrap()), ), Country::CUB => ( "Republic of Cuba", "Cuba", "CU", "CUB", 192, NationalCurrency::CUP, Some(Decimal::from_str("12.0").unwrap()), ), Country::CUW => ( "Curaçao", "Curaçao", "CW", "CUW", 531, NationalCurrency::ANG, None, ), Country::CXR => ( "Territory of Christmas Island", "Christmas Island", "CX", "CXR", 162, NationalCurrency::AUD, Some(Decimal::from_str("10.0").unwrap()), ), Country::CYM => ( "Cayman Islands", "Cayman Islands", "CX", "CYM", 136, NationalCurrency::KYD, None, ), Country::CYP => ( "Republic of Cyprus", "Cyprus", "CY", "CYP", 196, NationalCurrency::EUR, Some(Decimal::from_str("19.0").unwrap()), ), Country::CZE => ( "Czech Republic", "Czechia", "CZ", "CZE", 203, NationalCurrency::CZK, None, ), Country::DEU => ( "Federal Republic of Germany", "Germany", "DE", "DEU", 276, NationalCurrency::EUR, Some(Decimal::from_str("19.0").unwrap()), ), Country::DJI => ( "Republic of Djibouti", "Djibouti", "DJ", "DJI", 262, NationalCurrency::DJF, None, ), Country::DMA => ( "Commonwealth of Dominica", "Dominica", "DM", "DMA", 212, NationalCurrency::DOP, None, ), Country::DNK => ( "Kingdom of Denmark", "Denmark", "DK", "DNK", 208, NationalCurrency::DKK, None, ), Country::DOM => ( "Dominican Republic", "Dominican Republic", "DO", "DOM", 214, NationalCurrency::DOP, None, ), Country::DZA => ( "People's Democratic Republic of Algeria", "Algeria", "DZ", "DZA", 012, NationalCurrency::DZD, Some(Decimal::from_str("9.0").unwrap()), ), Country::ECU => ( "Republic of Ecuador", "Ecuador", "EC", "ECU", 218, NationalCurrency::USD, None, ), Country::EGY => ( "Arab Republic of Egypt", "Egypt", "EG", "EGY", 818, NationalCurrency::EGP, Some(Decimal::from_str("14.0").unwrap()), ), Country::ERI => ( "State of Eritrea", "Eritrea", "ER", "ERI", 232, NationalCurrency::ERN, None, ), Country::ESP => ( "Kingdom of Spain", "Spain", "ES", "ESP", 724, NationalCurrency::EUR, Some(Decimal::from_str("21.0").unwrap()), ), Country::EST => ( "Republic of Estonia", "Estonia", "EE", "EST", 233, NationalCurrency::EUR, Some(Decimal::from_str("20.0").unwrap()), ), Country::ETH => ( "Federal Democratic Republic of Ethiopia", "Ethiopia", "ET", "ETH", 231, NationalCurrency::ETB, None, ), Country::FIN => ( "Republic of Finland", "Finland", "FI", "FIN", 246, NationalCurrency::EUR, Some(Decimal::from_str("24.0").unwrap()), ), Country::FJI => ( "Republic of Fiji", "Fiji", "FJ", "FJI", 242, NationalCurrency::FJD, None, ), Country::FLK => ( "Falkland Islands", "Falkland Islands", "FK", "FLK", 238, NationalCurrency::FKP, None, ), Country::FRA => ( "French Republic", "France", "FR", "FRA", 250, NationalCurrency::EUR, Some(Decimal::from_str("20.0").unwrap()), ), Country::FRO => ( "Faroe Islands", "Faroe Islands", "FO", "FRO", 234, NationalCurrency::DKK, None, ), Country::FSM => ( "Federated States of Micronesia", "Micronesia", "FM", "FSM", 583, NationalCurrency::USD, None, ), Country::GAB => ( "Gabonese Republic", "Gabon", "GA", "GAB", 266, NationalCurrency::XAF, None, ), Country::GBR => ( "United Kingdom of Great Britain and Northern Ireland", "United Kingdom", "GB", "GBR", 826, NationalCurrency::GBP, None, ), Country::GEO => ( "Georgia", "Georgia", "GE", "GEO", 268, NationalCurrency::GEL, None, ), Country::GGY => ( "Bailiwick of Guernsey", "Guernsey", "GG", "GGY", 831, NationalCurrency::GBP, None, ), Country::GHA => ( "Republic of Ghana", "Ghana", "GH", "GHA", 288, NationalCurrency::GHS, Some(Decimal::from_str("17.0").unwrap()), ), Country::GIB => ( "Gibraltar", "Gibraltar", "GI", "GIB", 292, NationalCurrency::GIP, None, ), Country::GIN => ( "Republic of Guinea", "Guinea", "GN", "GIN", 324, NationalCurrency::GNF, None, ), Country::GLP => ( "Guadeloupe", "Guadeloupe", "GP", "GLP", 312, NationalCurrency::EUR, None, ), Country::GMB => ( "Republic of the Gambia", "Gambia", "GM", "GMB", 270, NationalCurrency::GMD, None, ), Country::GNB => ( "Republic of Guinea-Bissau", "Guinea-Bissau", "GW", "GNB", 624, NationalCurrency::XOF, None, ), Country::GNQ => ( "Republic of Equatorial Guinea", "Equatorial Guinea", "GQ", "GNQ", 226, NationalCurrency::PGK, None, ), Country::GRC => ( "Hellenic Republic", "Greece", "GR", "GRC", 300, NationalCurrency::EUR, Some(Decimal::from_str("24.0").unwrap()), ), Country::GRD => ( "Grenada", "Grenada", "GD", "GRD", 308, NationalCurrency::XCD, None, ), Country::GRL => ( "Greenland", "Greenland", "GL", "GRL", 304, NationalCurrency::DKK, None, ), Country::GTM => ( "Republic of Guatemala", "Guatemala", "GT", "GTM", 320, NationalCurrency::GTQ, None, ), Country::GUF => ( "French Guiana", "French Guiana", "GF", "GUF", 254, NationalCurrency::EUR, None, ), Country::GUM => ( "Guam", "Guam", "GU", "GUM", 316, NationalCurrency::USD, None, ), Country::GUY => ( "Co‑operative Republic of Guyana", "Guyana", "GY", "GUY", 328, NationalCurrency::GYD, None, ), Country::HKG => ( "Hong Kong Special Administrative Region of the People's Republic of China", "Hong Kong", "HK", "HKG", 344, NationalCurrency::HKD, None, ), Country::HMD => ( "Territory of Heard Island and McDonald Islands", "Heard Island and McDonald Islands", "HM", "HMD", 334, NationalCurrency::AUD, Some(Decimal::from_str("10.0").unwrap()), ), Country::HND => ( "Republic of Honduras", "Honduras", "HN", "HND", 340, NationalCurrency::HNL, None, ), Country::HRV => ( "Republic of Croatia", "Croatia", "HR", "HRV", 191, NationalCurrency::HRK, None, ), Country::HTI => ( "Republic of Haiti", "Haiti", "HT", "HTI", 332, NationalCurrency::HTG, None, ), Country::HUN => ( "Hungary", "Hungary", "HU", "HUN", 348, NationalCurrency::HUF, None, ), Country::IDN => ( "Republic of Indonesia", "Indonesia", "ID", "IDN", 360, NationalCurrency::IDR, Some(Decimal::from_str("10.0").unwrap()),
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
true
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/model/instance_command.rs
wasmer-deploy-cli/src/model/instance_command.rs
use ate_crypto::SerializationFormat; use serde::*; pub use wasmer_bus::prelude::CallHandle; pub use wasmer_bus::prelude::BusError; use std::fmt; #[derive(Debug, Serialize, Deserialize, Clone)] pub struct InstanceCall { #[serde(default)] pub parent: Option<u64>, pub handle: u64, pub format: SerializationFormat, pub binary: String, pub topic: String, } impl fmt::Display for InstanceCall { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}(", self.topic)?; if let Some(parent) = self.parent { write!(f, "parent={},", parent)?; } write!(f, ")") } } #[derive(Debug, Serialize, Deserialize, Clone)] pub enum InstanceCommand { Shell, Call(InstanceCall), } impl fmt::Display for InstanceCommand { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { InstanceCommand::Shell => write!(f, "shell"), InstanceCommand::Call(call) => write!(f, "call({})", call), } } } #[derive(Debug, Serialize, Deserialize, Clone)] pub enum InstanceReply { FeedBytes { handle: CallHandle, format: SerializationFormat, data: Vec<u8> }, Stdout { data: Vec<u8> }, Stderr { data: Vec<u8> }, Error { handle: CallHandle, error: BusError }, Terminate { handle: CallHandle }, Exit } impl fmt::Display for InstanceReply { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { InstanceReply::Stdout { data } => write!(f, "stdout(len={})", data.len()), InstanceReply::Stderr{ data } => write!(f, "stdout(len={})", data.len()), InstanceReply::FeedBytes { handle, format, data} => write!(f, "feed-bytes(handle={}, format={}, len={})", handle, format, data.len()), InstanceReply::Error { handle, error } => write!(f, "error(handle={}, {})", handle, error), InstanceReply::Terminate { handle, .. } => write!(f, "terminate(handle={})", handle), InstanceReply::Exit => write!(f, "exit"), } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/model/commodity_category.rs
wasmer-deploy-cli/src/model/commodity_category.rs
use serde::*; use super::*; /// The commodity category allows the buyers to easily /// find, search and filter what they specifically want to buy. #[derive(Serialize, Deserialize, Debug, Clone)] pub enum CommodityCategory { /// National currency backed by a national government NationalCurrency(NationalCurrency), /// Digital asset such as a game account/item DigitalAsset(DigitalAsset), /// Digital service such as a subscription DigitalService(DigitalService), } impl CommodityCategory { pub fn name(&self) -> &str { self.params().0 } pub fn description(&self) -> String { self.params().1 } fn params(&self) -> (&str, String) { match self { CommodityCategory::NationalCurrency(a) => (a.name(), a.description()), CommodityCategory::DigitalAsset(a) => (a.name(), a.description().to_string()), CommodityCategory::DigitalService(a) => (a.name(), a.description().to_string()), } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/model/historic_activity.rs
wasmer-deploy-cli/src/model/historic_activity.rs
pub mod activities { use crate::model::*; use chrono::prelude::*; use serde::*; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct WalletCreated { pub when: DateTime<Utc>, pub by: String, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct DepositCreated { pub when: DateTime<Utc>, pub by: String, pub invoice_number: String, pub invoice_id: String, pub amount: Decimal, pub currency: NationalCurrency, pub pay_url: String, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct DepositCompleted { pub when: DateTime<Utc>, pub by: String, pub invoice_number: String, pub amount: Decimal, pub currency: NationalCurrency, pub invoice_url: String, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct FundsTransferred { pub when: DateTime<Utc>, pub by: String, pub amount: Decimal, pub currency: NationalCurrency, pub from: String, pub to: String, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct FundsWithdrawn { pub when: DateTime<Utc>, pub by: String, pub amount_less_fees: Decimal, pub fees: Decimal, pub currency: NationalCurrency, pub receipt_number: String, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct ContractCreated { pub when: DateTime<Utc>, pub by: String, pub service: AdvertisedService, pub contract_reference: String, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct ContractInvoice { pub when: DateTime<Utc>, pub by: String, pub invoice: Invoice, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct InstanceCreated { pub when: DateTime<Utc>, pub by: String, pub alias: Option<String>, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct InstanceDestroyed { pub when: DateTime<Utc>, pub by: String, pub alias: Option<String>, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct InstanceExported { pub when: DateTime<Utc>, pub by: String, pub alias: Option<String>, pub binary: String, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct InstanceDeported { pub when: DateTime<Utc>, pub by: String, pub alias: Option<String>, pub binary: String, } } use chrono::prelude::*; use num_traits::*; use serde::*; use crate::model::*; use activities::*; #[derive(Serialize, Deserialize, Debug, Clone)] pub enum HistoricActivity { WalletCreated(WalletCreated), DepositCreated(DepositCreated), DepositCompleted(DepositCompleted), TransferOut(FundsTransferred), TransferIn(FundsTransferred), FundsWithdrawn(FundsWithdrawn), ContractCreated(ContractCreated), ContractCharge(ContractInvoice), ContractIncome(ContractInvoice), InstanceCreated(InstanceCreated), InstanceDestroyed(InstanceDestroyed), InstanceExported(InstanceExported), InstanceDeported(InstanceDeported), } impl HistoricActivity { pub fn when(&self) -> &DateTime<Utc> { match self { HistoricActivity::WalletCreated(a) => &a.when, HistoricActivity::DepositCreated(a) => &a.when, HistoricActivity::DepositCompleted(a) => &a.when, HistoricActivity::TransferIn(a) => &a.when, HistoricActivity::TransferOut(a) => &a.when, HistoricActivity::FundsWithdrawn(a) => &a.when, HistoricActivity::ContractCreated(a) => &a.when, HistoricActivity::ContractCharge(a) => &a.when, HistoricActivity::ContractIncome(a) => &a.when, HistoricActivity::InstanceCreated(a) => &a.when, HistoricActivity::InstanceDestroyed(a) => &a.when, HistoricActivity::InstanceExported(a) => &a.when, HistoricActivity::InstanceDeported(a) => &a.when, } } pub fn by(&self) -> &str { match self { HistoricActivity::WalletCreated(a) => a.by.as_str(), HistoricActivity::DepositCreated(a) => a.by.as_str(), HistoricActivity::DepositCompleted(a) => a.by.as_str(), HistoricActivity::TransferIn(a) => a.by.as_str(), HistoricActivity::TransferOut(a) => a.by.as_str(), HistoricActivity::FundsWithdrawn(a) => a.by.as_str(), HistoricActivity::ContractCreated(a) => a.by.as_str(), HistoricActivity::ContractCharge(a) => a.by.as_str(), HistoricActivity::ContractIncome(a) => a.by.as_str(), HistoricActivity::InstanceCreated(a) => a.by.as_str(), HistoricActivity::InstanceDestroyed(a) => a.by.as_str(), HistoricActivity::InstanceExported(a) => a.by.as_str(), HistoricActivity::InstanceDeported(a) => a.by.as_str(), } } pub fn financial<'a>(&'a self) -> Option<HistoricFinancialActivity<'a>> { match self { HistoricActivity::WalletCreated(_) => None, HistoricActivity::DepositCreated(_) => None, HistoricActivity::InstanceCreated(_) => None, HistoricActivity::InstanceDestroyed(_) => None, HistoricActivity::InstanceExported(_) => None, HistoricActivity::InstanceDeported(_) => None, HistoricActivity::ContractCreated(_) => None, HistoricActivity::ContractCharge(a) => Some(HistoricFinancialActivity { activity: self, amount: Decimal::zero() - a.invoice.total_due, currency: a.invoice.currency, }), HistoricActivity::ContractIncome(a) => Some(HistoricFinancialActivity { activity: self, amount: a.invoice.total_due, currency: a.invoice.currency, }), HistoricActivity::DepositCompleted(a) => Some(HistoricFinancialActivity { activity: self, amount: a.amount, currency: a.currency, }), HistoricActivity::TransferIn(a) => Some(HistoricFinancialActivity { activity: self, amount: a.amount, currency: a.currency, }), HistoricActivity::TransferOut(a) => Some(HistoricFinancialActivity { activity: self, amount: Decimal::zero() - a.amount, currency: a.currency, }), HistoricActivity::FundsWithdrawn(a) => Some(HistoricFinancialActivity { activity: self, amount: Decimal::zero() - (a.amount_less_fees + a.fees), currency: a.currency, }), } } pub fn summary(&self) -> String { match self { HistoricActivity::WalletCreated(_) => { format!("Wallet created") } HistoricActivity::ContractCreated(a) => { format!("Contract created ({})", a.contract_reference) } HistoricActivity::ContractCharge(a) => { format!("Invoice was paid ({})", a.invoice.related_to) } HistoricActivity::ContractIncome(a) => { format!("Invoice was paid ({})", a.invoice.related_to) } HistoricActivity::DepositCreated(a) => { format!("Deposit invoiced ({})", a.invoice_number) } HistoricActivity::DepositCompleted(a) => { format!("Deposit was paid ({})", a.invoice_number) } HistoricActivity::TransferIn(a) => { format!("Transfer from {}", a.from) } HistoricActivity::TransferOut(a) => { format!("Transfer to {}", a.to) } HistoricActivity::FundsWithdrawn(_) => { format!("Funds withdrawn") } HistoricActivity::InstanceCreated(a) => { if let Some(alias) = &a.alias { format!("Instance created ({})", alias) } else { format!("Instance created") } } HistoricActivity::InstanceDestroyed(a) => { if let Some(alias) = &a.alias { format!("Instance destroyed ({})", alias) } else { format!("Instance destroyed") } } HistoricActivity::InstanceExported(a) => { if let Some(alias) = &a.alias { format!("Instance ({}) exported binary ({})", alias, a.binary) } else { format!("Instance exported binary ({})", a.binary) } } HistoricActivity::InstanceDeported(a) => { if let Some(alias) = &a.alias { format!("Instance ({}) deported binary ({})", alias, a.binary) } else { format!("Instance deported binary ({})", a.binary) } } } } pub fn details(&self) -> std::result::Result<String, serde_json::Error> { Ok(serde_json::to_string_pretty(self)?) } } pub struct HistoricFinancialActivity<'a> { pub activity: &'a HistoricActivity, pub currency: NationalCurrency, pub amount: Decimal, }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/model/decimal.rs
wasmer-deploy-cli/src/model/decimal.rs
use rust_decimal::Decimal as InnerDecimal; use serde::de::{Unexpected, Visitor}; use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; use std::fmt; use std::str::FromStr; use std::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}; use std::iter::Sum; use std::ops::{ Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Rem, RemAssign, Sub, SubAssign, }; #[allow(unused_imports)] // It's not actually dead code below, but the compiler thinks it is. #[cfg(not(feature = "std"))] use num_traits::float::FloatCore; use num_traits::{ CheckedAdd, CheckedDiv, CheckedMul, CheckedRem, CheckedSub, FromPrimitive, Num, One, Signed, ToPrimitive, Zero, }; pub use rust_decimal::prelude::RoundingStrategy; #[derive(Copy, Clone)] pub struct Decimal(InnerDecimal); impl Serialize for Decimal { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_str(&self.0.to_string()) } } impl<'de> Deserialize<'de> for Decimal { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_str(DecimalVisitor) } } struct DecimalVisitor; impl<'de> Visitor<'de> for DecimalVisitor { type Value = Decimal; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a Decimal value") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { InnerDecimal::from_str(value) .map_err(|_| E::invalid_value(Unexpected::Str(value), &self)) .map(Decimal) } } impl std::ops::Deref for Decimal { type Target = InnerDecimal; fn deref(&self) -> &Self::Target { &self.0 } } impl std::ops::DerefMut for Decimal { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl Decimal { #[must_use] pub fn new(num: i64, scale: u32) -> Decimal { Decimal(InnerDecimal::new(num, scale)) } #[must_use] pub fn from_i128_with_scale(num: i128, scale: u32) -> Decimal { Decimal(InnerDecimal::from_i128_with_scale(num, scale)) } #[must_use] pub const fn from_parts(lo: u32, mid: u32, hi: u32, negative: bool, scale: u32) -> Decimal { Decimal(InnerDecimal::from_parts(lo, mid, hi, negative, scale)) } pub fn from_scientific(value: &str) -> Result<Decimal, rust_decimal::Error> { Ok(Decimal(InnerDecimal::from_scientific(value)?)) } #[must_use] pub fn round_dp(&self, dp: u32) -> Decimal { Decimal(self.0.round_dp(dp)) } #[must_use] pub fn round_dp_with_strategy(&self, dp: u32, strategy: RoundingStrategy) -> Decimal { Decimal(self.0.round_dp_with_strategy(dp, strategy)) } #[must_use] pub fn round(&self) -> Decimal { self.round_dp(0) } #[must_use] pub fn normalize(&self) -> Decimal { Decimal(self.0.normalize()) } #[must_use] pub fn max(self, other: Decimal) -> Decimal { Decimal(self.0.max(other.0)) } #[must_use] pub fn min(self, other: Decimal) -> Decimal { Decimal(self.0.min(other.0)) } #[inline(always)] #[must_use] pub fn checked_add(self, other: Decimal) -> Option<Decimal> { self.0.checked_add(other.0).map(|a| Decimal(a)) } #[inline(always)] #[must_use] pub fn checked_sub(self, other: Decimal) -> Option<Decimal> { self.0.checked_sub(other.0).map(|a| Decimal(a)) } #[inline] #[must_use] pub fn checked_mul(self, other: Decimal) -> Option<Decimal> { self.0.checked_mul(other.0).map(|a| Decimal(a)) } #[inline] #[must_use] pub fn checked_div(self, other: Decimal) -> Option<Decimal> { self.0.checked_div(other.0).map(|a| Decimal(a)) } #[inline] #[must_use] pub fn checked_rem(self, other: Decimal) -> Option<Decimal> { self.0.checked_rem(other.0).map(|a| Decimal(a)) } pub fn from_str_radix(str: &str, radix: u32) -> Result<Self, rust_decimal::Error> { Ok(Decimal(InnerDecimal::from_str_radix(str, radix)?)) } #[must_use] pub const fn serialize(&self) -> [u8; 16] { self.0.serialize() } #[must_use] pub fn deserialize(bytes: [u8; 16]) -> Decimal { Decimal(InnerDecimal::deserialize(bytes)) } } impl Default for Decimal { fn default() -> Self { Decimal::zero() } } impl Zero for Decimal { fn zero() -> Decimal { Decimal(InnerDecimal::zero()) } fn is_zero(&self) -> bool { self.0.is_zero() } } impl One for Decimal { fn one() -> Decimal { Decimal(InnerDecimal::one()) } } macro_rules! impl_from { ($T:ty, $from_ty:path) => { impl core::convert::From<$T> for Decimal { #[inline] fn from(t: $T) -> Self { $from_ty(t).unwrap() } } }; } impl_from!(isize, FromPrimitive::from_isize); impl_from!(i8, FromPrimitive::from_i8); impl_from!(i16, FromPrimitive::from_i16); impl_from!(i32, FromPrimitive::from_i32); impl_from!(i64, FromPrimitive::from_i64); impl_from!(usize, FromPrimitive::from_usize); impl_from!(u8, FromPrimitive::from_u8); impl_from!(u16, FromPrimitive::from_u16); impl_from!(u32, FromPrimitive::from_u32); impl_from!(u64, FromPrimitive::from_u64); impl_from!(i128, FromPrimitive::from_i128); impl_from!(u128, FromPrimitive::from_u128); macro_rules! forward_val_val_binop { (impl $imp:ident for $res:ty, $method:ident) => { impl $imp<$res> for $res { type Output = $res; #[inline] fn $method(self, other: $res) -> $res { (&self).$method(&other) } } }; } macro_rules! forward_ref_val_binop { (impl $imp:ident for $res:ty, $method:ident) => { impl<'a> $imp<$res> for &'a $res { type Output = $res; #[inline] fn $method(self, other: $res) -> $res { self.$method(&other) } } }; } macro_rules! forward_val_ref_binop { (impl $imp:ident for $res:ty, $method:ident) => { impl<'a> $imp<&'a $res> for $res { type Output = $res; #[inline] fn $method(self, other: &$res) -> $res { (&self).$method(other) } } }; } macro_rules! forward_all_binop { (impl $imp:ident for $res:ty, $method:ident) => { forward_val_val_binop!(impl $imp for $res, $method); forward_ref_val_binop!(impl $imp for $res, $method); forward_val_ref_binop!(impl $imp for $res, $method); }; } impl Signed for Decimal { fn abs(&self) -> Self { Decimal(self.0.abs()) } fn abs_sub(&self, other: &Self) -> Self { if self <= other { Decimal::zero() } else { Decimal(self.0.abs()) } } fn signum(&self) -> Self { if self.is_zero() { Decimal::zero() } else { let mut value = Decimal::one(); if self.is_sign_negative() { value.set_sign_negative(true); } value } } fn is_positive(&self) -> bool { self.0.is_sign_positive() } fn is_negative(&self) -> bool { self.0.is_sign_negative() } } impl CheckedAdd for Decimal { #[inline] fn checked_add(&self, v: &Decimal) -> Option<Decimal> { Decimal::checked_add(*self, *v) } } impl CheckedSub for Decimal { #[inline] fn checked_sub(&self, v: &Decimal) -> Option<Decimal> { Decimal::checked_sub(*self, *v) } } impl CheckedMul for Decimal { #[inline] fn checked_mul(&self, v: &Decimal) -> Option<Decimal> { Decimal::checked_mul(*self, *v) } } impl CheckedDiv for Decimal { #[inline] fn checked_div(&self, v: &Decimal) -> Option<Decimal> { Decimal::checked_div(*self, *v) } } impl CheckedRem for Decimal { #[inline] fn checked_rem(&self, v: &Decimal) -> Option<Decimal> { Decimal::checked_rem(*self, *v) } } impl Num for Decimal { type FromStrRadixErr = rust_decimal::Error; fn from_str_radix(str: &str, radix: u32) -> Result<Self, Self::FromStrRadixErr> { Decimal::from_str_radix(str, radix) } } impl FromStr for Decimal { type Err = rust_decimal::Error; fn from_str(value: &str) -> Result<Decimal, Self::Err> { Ok(Decimal(std::str::FromStr::from_str(value)?)) } } impl FromPrimitive for Decimal { fn from_i32(n: i32) -> Option<Decimal> { InnerDecimal::from_i32(n).map(|a| Decimal(a)) } fn from_i64(n: i64) -> Option<Decimal> { InnerDecimal::from_i64(n).map(|a| Decimal(a)) } fn from_i128(n: i128) -> Option<Decimal> { InnerDecimal::from_i128(n).map(|a| Decimal(a)) } fn from_u32(n: u32) -> Option<Decimal> { InnerDecimal::from_u32(n).map(|a| Decimal(a)) } fn from_u64(n: u64) -> Option<Decimal> { InnerDecimal::from_u64(n).map(|a| Decimal(a)) } fn from_u128(n: u128) -> Option<Decimal> { InnerDecimal::from_u128(n).map(|a| Decimal(a)) } fn from_f32(n: f32) -> Option<Decimal> { InnerDecimal::from_f32(n).map(|a| Decimal(a)) } fn from_f64(n: f64) -> Option<Decimal> { InnerDecimal::from_f64(n).map(|a| Decimal(a)) } } impl ToPrimitive for Decimal { fn to_i64(&self) -> Option<i64> { self.0.to_i64() } fn to_i128(&self) -> Option<i128> { self.0.to_i128() } fn to_u64(&self) -> Option<u64> { self.0.to_u64() } fn to_u128(&self) -> Option<u128> { self.0.to_u128() } fn to_f64(&self) -> Option<f64> { self.0.to_f64() } } impl core::convert::TryFrom<f32> for Decimal { type Error = rust_decimal::Error; fn try_from(value: f32) -> Result<Self, rust_decimal::Error> { Ok(Decimal(InnerDecimal::try_from(value)?)) } } impl core::convert::TryFrom<f64> for Decimal { type Error = rust_decimal::Error; fn try_from(value: f64) -> Result<Self, rust_decimal::Error> { Ok(Decimal(InnerDecimal::try_from(value)?)) } } impl core::convert::TryFrom<Decimal> for f32 { type Error = rust_decimal::Error; fn try_from(value: Decimal) -> Result<Self, Self::Error> { core::convert::TryFrom::<InnerDecimal>::try_from(value.0) } } impl core::convert::TryFrom<Decimal> for f64 { type Error = rust_decimal::Error; fn try_from(value: Decimal) -> Result<Self, Self::Error> { core::convert::TryFrom::<InnerDecimal>::try_from(value.0) } } impl fmt::Display for Decimal { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { Ok(self.0.fmt(f)?) } } impl fmt::Debug for Decimal { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { Ok(self.0.fmt(f)?) } } impl fmt::LowerExp for Decimal { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { Ok(self.0.fmt(f)?) } } impl fmt::UpperExp for Decimal { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { Ok(self.0.fmt(f)?) } } impl Neg for Decimal { type Output = Decimal; fn neg(self) -> Decimal { Decimal(self.0.neg()) } } impl<'a> Neg for &'a Decimal { type Output = Decimal; fn neg(self) -> Decimal { Decimal(self.0.neg()) } } forward_all_binop!(impl Add for Decimal, add); impl<'a, 'b> Add<&'b Decimal> for &'a Decimal { type Output = Decimal; #[inline(always)] fn add(self, other: &Decimal) -> Decimal { Decimal(self.0.add(&other.0)) } } impl AddAssign for Decimal { fn add_assign(&mut self, other: Decimal) { self.0.add_assign(other.0) } } impl<'a> AddAssign<&'a Decimal> for Decimal { fn add_assign(&mut self, other: &'a Decimal) { self.0.add_assign(&other.0) } } impl<'a> AddAssign<Decimal> for &'a mut Decimal { fn add_assign(&mut self, other: Decimal) { self.0.add_assign(other.0) } } impl<'a> AddAssign<&'a Decimal> for &'a mut Decimal { fn add_assign(&mut self, other: &'a Decimal) { self.0.add_assign(&other.0) } } forward_all_binop!(impl Sub for Decimal, sub); impl<'a, 'b> Sub<&'b Decimal> for &'a Decimal { type Output = Decimal; #[inline(always)] fn sub(self, other: &Decimal) -> Decimal { Decimal(self.0.sub(&other.0)) } } impl SubAssign for Decimal { fn sub_assign(&mut self, other: Decimal) { self.0.sub_assign(other.0) } } impl<'a> SubAssign<&'a Decimal> for Decimal { fn sub_assign(&mut self, other: &'a Decimal) { self.0.sub_assign(&other.0) } } impl<'a> SubAssign<Decimal> for &'a mut Decimal { fn sub_assign(&mut self, other: Decimal) { self.0.sub_assign(&other.0) } } impl<'a> SubAssign<&'a Decimal> for &'a mut Decimal { fn sub_assign(&mut self, other: &'a Decimal) { self.0.sub_assign(&other.0) } } forward_all_binop!(impl Mul for Decimal, mul); impl<'a, 'b> Mul<&'b Decimal> for &'a Decimal { type Output = Decimal; #[inline] fn mul(self, other: &Decimal) -> Decimal { Decimal(self.0.mul(&other.0)) } } impl MulAssign for Decimal { fn mul_assign(&mut self, other: Decimal) { self.0.mul_assign(other.0) } } impl<'a> MulAssign<&'a Decimal> for Decimal { fn mul_assign(&mut self, other: &'a Decimal) { self.0.mul_assign(&other.0) } } impl<'a> MulAssign<Decimal> for &'a mut Decimal { fn mul_assign(&mut self, other: Decimal) { self.0.mul_assign(other.0) } } impl<'a> MulAssign<&'a Decimal> for &'a mut Decimal { fn mul_assign(&mut self, other: &'a Decimal) { self.0.mul_assign(&other.0) } } forward_all_binop!(impl Div for Decimal, div); impl<'a, 'b> Div<&'b Decimal> for &'a Decimal { type Output = Decimal; fn div(self, other: &Decimal) -> Decimal { Decimal(self.0.div(&other.0)) } } impl DivAssign for Decimal { fn div_assign(&mut self, other: Decimal) { self.0.div_assign(other.0) } } impl<'a> DivAssign<&'a Decimal> for Decimal { fn div_assign(&mut self, other: &'a Decimal) { self.0.div_assign(&other.0) } } impl<'a> DivAssign<Decimal> for &'a mut Decimal { fn div_assign(&mut self, other: Decimal) { self.0.div_assign(other.0) } } impl<'a> DivAssign<&'a Decimal> for &'a mut Decimal { fn div_assign(&mut self, other: &'a Decimal) { self.0.div_assign(&other.0) } } forward_all_binop!(impl Rem for Decimal, rem); impl<'a, 'b> Rem<&'b Decimal> for &'a Decimal { type Output = Decimal; #[inline] fn rem(self, other: &Decimal) -> Decimal { Decimal(self.0.rem(&other.0)) } } impl RemAssign for Decimal { fn rem_assign(&mut self, other: Decimal) { self.0.rem_assign(other.0) } } impl<'a> RemAssign<&'a Decimal> for Decimal { fn rem_assign(&mut self, other: &'a Decimal) { self.0.rem_assign(&other.0) } } impl<'a> RemAssign<Decimal> for &'a mut Decimal { fn rem_assign(&mut self, other: Decimal) { self.0.rem_assign(other.0) } } impl<'a> RemAssign<&'a Decimal> for &'a mut Decimal { fn rem_assign(&mut self, other: &'a Decimal) { self.0.rem_assign(&other.0) } } impl PartialEq for Decimal { #[inline] fn eq(&self, other: &Decimal) -> bool { self.0.cmp(&other.0) == Ordering::Equal } } impl Eq for Decimal {} impl std::hash::Hash for Decimal { fn hash<H: std::hash::Hasher>(&self, mut state: &mut H) { self.0.hash(&mut state); } } impl PartialOrd for Decimal { #[inline] fn partial_cmp(&self, other: &Decimal) -> Option<Ordering> { self.0.partial_cmp(&other.0) } } impl Ord for Decimal { fn cmp(&self, other: &Decimal) -> Ordering { self.0.cmp(&other.0) } } impl Sum for Decimal { fn sum<I: Iterator<Item = Decimal>>(iter: I) -> Self { let iter = iter.map(|a| a.0); Decimal(Sum::sum(iter)) } } impl<'a> Sum<&'a Decimal> for Decimal { fn sum<I: Iterator<Item = &'a Decimal>>(iter: I) -> Self { let iter = iter.map(|a| &a.0); Decimal(Sum::sum(iter)) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/model/instance_hello.rs
wasmer-deploy-cli/src/model/instance_hello.rs
use ate::chain::ChainKey; use serde::*; use std::fmt; #[derive(Debug, Serialize, Deserialize, Clone)] pub struct InstanceHello { pub chain: ChainKey, pub access_token: String, } impl fmt::Display for InstanceHello { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "instance-hello(key={})", self.chain) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/model/mesh_node.rs
wasmer-deploy-cli/src/model/mesh_node.rs
use serde::*; use std::net::IpAddr; use std::net::Ipv4Addr; use std::net::Ipv6Addr; use std::collections::HashSet; use std::collections::HashMap; use std::fmt; use crate::model::HardwareAddress; #[derive(Debug, Serialize, Deserialize, Clone)] pub struct DhcpReservation { pub mac: HardwareAddress, pub addr4: Ipv4Addr, #[serde(default)] pub addr6: Vec<Ipv6Addr>, } /// Subnets make up all the networks for a specific network #[derive(Debug, Serialize, Deserialize, Clone)] pub struct MeshNode { /// Address of the node participating in the mesh pub node_addr: IpAddr, /// List of all the ports that are in this mesh node pub switch_ports: HashSet<HardwareAddress>, /// List of all the assigned MAC addresses to IPv4 used by the DHCP server #[serde(default)] pub dhcp_reservation: HashMap<String, DhcpReservation>, /// List of all the ports that are in promiscuous mode #[serde(default)] pub promiscuous: HashSet<HardwareAddress>, } impl fmt::Display for MeshNode { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "mesh_node(node_addr={}", self.node_addr)?; if self.switch_ports.len() > 0 { write!(f, ",switch_ports(")?; for switch_port in self.switch_ports.iter() { write!(f, "{},", switch_port)?; } write!(f, ")")?; } if self.dhcp_reservation.len() > 0 { write!(f, ",dhcp_reservation(")?; for (mac, ip) in self.dhcp_reservation.iter() { write!(f, "{}={},", mac, ip.addr4)?; } write!(f, ")")?; } write!(f, ")") } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/model/automation_time.rs
wasmer-deploy-cli/src/model/automation_time.rs
use serde::*; /// Automation time is a safe and secure way to automate grinding activities /// in a commercial way to drive revenue for digital creators. #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum AutomationTime { ExclusiveBot, } impl AutomationTime { pub fn name(&self) -> &str { self.params().0 } pub fn description(&self) -> &str { self.params().1 } fn params(&self) -> (&str, &str) { match self { AutomationTime::ExclusiveBot => ( "Exclusive Bot", "Rental of a legal bot that will automate a particular task.", ), } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/model/digital_asset.rs
wasmer-deploy-cli/src/model/digital_asset.rs
use serde::*; /// Digital assets are virtual things that have an intrinsic value to the humans /// that interact with that particular digital environment/ecosystem. #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum DigitalAsset { GameAccount, GameAsset, GameCurrency, } impl DigitalAsset { pub fn name(&self) -> &str { self.params().0 } pub fn description(&self) -> &str { self.params().1 } fn params(&self) -> (&str, &str) { match self { DigitalAsset::GameAccount => ("Game Account", "Access rights and ownership of a gaming account within a virtual world."), DigitalAsset::GameAsset => ("Game Item", "Tradable game asset within a unique virtual world that may hold some value in that realm."), DigitalAsset::GameCurrency => ("Game Current", "Internal currency within the virtual world of a particular game."), } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/model/charge.rs
wasmer-deploy-cli/src/model/charge.rs
use serde::*; use std::fmt; use super::*; use crate::model::Decimal; #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum ChargeMetric { DownloadBandwidth, UploadBandwidth, DataStorage, Compute, } impl fmt::Display for ChargeMetric { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { ChargeMetric::DownloadBandwidth => write!(f, "downloaded bandwidth"), ChargeMetric::UploadBandwidth => write!(f, "uploaded bandwidth"), ChargeMetric::DataStorage => write!(f, "data storage usage"), ChargeMetric::Compute => write!(f, "compute usage"), } } } #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum ChargeUnits { FlatRate, Seconds(ChargeMetric), Minutes(ChargeMetric), Hours(ChargeMetric), Days(ChargeMetric), Weeks(ChargeMetric), Bytes(ChargeMetric), KiloBytes(ChargeMetric), MegaBytes(ChargeMetric), GigaBytes(ChargeMetric), TeraBytes(ChargeMetric), PetaBytes(ChargeMetric), } impl ChargeUnits { pub fn scale(&self) -> Decimal { match self { ChargeUnits::FlatRate => Decimal::from(1u64), ChargeUnits::Bytes(_) => Decimal::from(1u64), ChargeUnits::KiloBytes(_) => Decimal::from(1000u64), ChargeUnits::MegaBytes(_) => Decimal::from(1000000u64), ChargeUnits::GigaBytes(_) => Decimal::from(1000000000u64), ChargeUnits::TeraBytes(_) => Decimal::from(1000000000000u64), ChargeUnits::PetaBytes(_) => Decimal::from(1000000000000000u64), ChargeUnits::Seconds(_) => Decimal::from(1u64), ChargeUnits::Minutes(_) => Decimal::from(60u64), ChargeUnits::Hours(_) => Decimal::from(3600u64), ChargeUnits::Days(_) => Decimal::from(86400u64), ChargeUnits::Weeks(_) => Decimal::from(604800u64), } } pub fn abbreviation(&self) -> &'static str { match self { ChargeUnits::FlatRate => "flat", ChargeUnits::Bytes(_) => "B", ChargeUnits::KiloBytes(_) => "KB", ChargeUnits::MegaBytes(_) => "MB", ChargeUnits::GigaBytes(_) => "GB", ChargeUnits::TeraBytes(_) => "TB", ChargeUnits::PetaBytes(_) => "PB", ChargeUnits::Seconds(_) => "s", ChargeUnits::Minutes(_) => "m", ChargeUnits::Hours(_) => "h", ChargeUnits::Days(_) => "d", ChargeUnits::Weeks(_) => "w", } } pub fn metric(&self) -> Option<ChargeMetric> { match self { ChargeUnits::FlatRate => None, ChargeUnits::Bytes(a) => Some(a.clone()), ChargeUnits::KiloBytes(a) => Some(a.clone()), ChargeUnits::MegaBytes(a) => Some(a.clone()), ChargeUnits::GigaBytes(a) => Some(a.clone()), ChargeUnits::TeraBytes(a) => Some(a.clone()), ChargeUnits::PetaBytes(a) => Some(a.clone()), ChargeUnits::Seconds(a) => Some(a.clone()), ChargeUnits::Minutes(a) => Some(a.clone()), ChargeUnits::Hours(a) => Some(a.clone()), ChargeUnits::Days(a) => Some(a.clone()), ChargeUnits::Weeks(a) => Some(a.clone()), } } } impl fmt::Display for ChargeUnits { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { ChargeUnits::FlatRate => write!(f, "flat"), ChargeUnits::Bytes(a) => write!(f, "bytes {}", a), ChargeUnits::KiloBytes(a) => write!(f, "kilobytes {}", a), ChargeUnits::MegaBytes(a) => write!(f, "megabytes {}", a), ChargeUnits::GigaBytes(a) => write!(f, "gigabytes {}", a), ChargeUnits::TeraBytes(a) => write!(f, "terabytes {}", a), ChargeUnits::PetaBytes(a) => write!(f, "petabytes {}", a), ChargeUnits::Seconds(a) => write!(f, "secs {}", a), ChargeUnits::Minutes(a) => write!(f, "mins {}", a), ChargeUnits::Hours(a) => write!(f, "hours {}", a), ChargeUnits::Days(a) => write!(f, "days {}", a), ChargeUnits::Weeks(a) => write!(f, "weeks {}", a), } } } /// Represents a particular charge that will be applied to your /// wallet thats triggered at specific trigger points #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Charge { pub amount: Decimal, pub units: ChargeUnits, pub frequency: ChargeFrequency, } impl fmt::Display for Charge { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let freq = self.frequency.to_string().replace("-", " "); write!(f, "{} per {} {}", self.amount, self.units, freq) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/model/invoice.rs
wasmer-deploy-cli/src/model/invoice.rs
use ate::prelude::*; use serde::*; use strum_macros::Display; use strum_macros::EnumIter; use crate::model::*; /// Represent a line item in an invoice that breaks down the /// charges and what they are for. #[derive(Serialize, Deserialize, Debug, Clone)] pub struct InvoiceItem { /// The name of the line item pub name: String, /// Amount of quantity that was consumed pub quantity: Decimal, /// Amount for this particular line item pub amount: Decimal, /// Any sales tax to be paid on this line item pub gst: Option<Decimal>, /// Amount plus the GST pub total: Decimal, } /// Determines the status of the invoice #[derive( Serialize, Deserialize, Debug, Display, Clone, Copy, PartialOrd, Ord, PartialEq, Eq, EnumIter, )] pub enum InvoiceStatus { Unpaid, Paid, } /// Represents an invoice for some services that were charged /// to a customer #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Invoice { /// The current status of this invoice pub status: InvoiceStatus, /// Reference number of the contract this invoice is related to pub reference_number: String, /// What this invoice is related to pub related_to: String, /// Who paid the funds pub from_identity: String, /// Who received the funds pub to_identity: String, /// Wallet that the sender used pub from_wallet: PrimaryKey, /// The currency that the invoice will be paid in pub currency: NationalCurrency, /// The country you are resident in for tax purposes pub gst_country: Country, /// List of the line items that make up the invoice pub items: Vec<InvoiceItem>, /// Total amount from all the line item pub total_amount: Decimal, /// Total TAX to be paid for this line item pub total_gst: Option<Decimal>, /// Total amount paid for this invoice pub total_due: Decimal, }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/model/carved_coin.rs
wasmer-deploy-cli/src/model/carved_coin.rs
use ate::prelude::*; use serde::*; use super::*; #[derive(Debug, Serialize, Deserialize, Clone)] pub struct CarvedCoin { pub value: Decimal, pub currency: NationalCurrency, pub coin: PrimaryKey, pub owner: Ownership, }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/model/contract_status.rs
wasmer-deploy-cli/src/model/contract_status.rs
use chrono::DateTime; use chrono::Utc; use serde::*; #[derive(Serialize, Deserialize, Debug, Clone, Default)] pub struct ThrottleTriggers { pub download_per_second: Option<u64>, pub upload_per_second: Option<u64>, pub delete_only_threshold: Option<u64>, } /// The contract status determines if aggrements are being honoured #[derive(Serialize, Deserialize, Debug, Clone)] pub enum ContractStatus { MissingContract { throttle: ThrottleTriggers, }, Nominal { throttle: ThrottleTriggers, }, InDefault { since: DateTime<Utc>, throttle: ThrottleTriggers, }, } impl ContractStatus { pub fn throttle(&self) -> &ThrottleTriggers { match self { ContractStatus::Nominal { throttle } => throttle, ContractStatus::MissingContract { throttle } => throttle, ContractStatus::InDefault { since: _, throttle } => throttle, } } } impl std::fmt::Display for ContractStatus { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { ContractStatus::Nominal { throttle: _ } => write!(f, "nominal"), ContractStatus::MissingContract { throttle: _ } => write!(f, "missing"), ContractStatus::InDefault { since, throttle: _ } => { write!(f, "default-since-{}", since) } } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/model/mod.rs
wasmer-deploy-cli/src/model/mod.rs
mod advertised_service; mod automation_time; mod bag_of_coins; mod carved_coin; mod charge; mod charge_frequency; mod commodity_category; mod commodity_kind; mod contract; mod contract_metrics; mod contract_status; mod country; mod decimal; mod denomination; mod digital_asset; mod digital_service; mod historic_activity; mod historic_day; mod historic_month; mod invoice; mod national_currency; mod ownership; mod rate_card; mod wallet; mod service_instance; mod master_authority; mod wallet_instance; mod instance_command; mod instance_hello; mod instance_export; mod instance_subnet; mod mesh_node; pub use advertised_service::*; pub use automation_time::*; pub use bag_of_coins::*; pub use carved_coin::*; pub use charge::*; pub use charge_frequency::*; pub use commodity_category::*; pub use commodity_kind::*; pub use contract::*; pub use contract_metrics::*; pub use contract_status::*; pub use country::*; pub use decimal::*; pub use denomination::*; pub use digital_asset::*; pub use digital_service::*; pub use historic_activity::*; pub use historic_day::*; pub use historic_month::*; pub use invoice::*; pub use national_currency::*; pub use ownership::*; pub use rate_card::*; pub use wallet::*; pub use service_instance::*; pub use master_authority::*; pub use wallet_instance::*; pub use instance_command::*; pub use instance_hello::*; pub use instance_export::*; pub use instance_subnet::*; pub use mesh_node::*; pub use wasmer_bus_mio::model::*; pub const WALLET_COLLECTION_ID: u64 = 2259995437953076879u64; pub const CONTRACT_COLLECTION_ID: u64 = 8278931753731734656u64; pub const INSTANCE_COLLECTION_ID: u64 = 5476918267819474034u64; pub const INVOICE_COLLECTION_ID: u64 = 1234960345778345782u64; pub const MASTER_AUTHORITY_ID: u64 = 12743381463764637636u64; pub const INSTANCE_ROOT_ID: u64 = 9384758237459681256u64; pub const COINS_PER_STACK_TO_BE_COMBINED: usize = 10usize;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/model/denomination.rs
wasmer-deploy-cli/src/model/denomination.rs
use serde::*; use super::*; #[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Denomination { pub value: Decimal, pub currency: NationalCurrency, } impl Denomination { pub fn to_string(&self) -> String { format!("{} {}", self.value, self.currency) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/model/ownership.rs
wasmer-deploy-cli/src/model/ownership.rs
use ate::prelude::*; use serde::*; use super::*; /// Represents ownership of a particular commodity. This is normally /// used in a person of groups wallet so that they can access a /// particular asset or redeem it #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Ownership { pub kind: CommodityKind, pub chain: ChainKey, pub what: PrimaryKey, pub token: EncryptKey, }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/model/wallet.rs
wasmer-deploy-cli/src/model/wallet.rs
use ate::prelude::*; use serde::*; use super::*; /// Wallets are attached to users (persons) or to groups /// which allows ownership of commodities. Proof of ownership /// can be used to access or consume commodities which can be /// achieved by proving ownership of the wallet itself. Attaching /// the wallet is done by making it a child of user/group. #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Wallet { /// Name that can be associated with the wallet for organization purposes (default=default) pub name: String, /// The country you are resident in for tax purposes pub gst_country: Country, /// All the coins that need to be processed again (e.g. deposits) pub inbox: DaoVec<Ownership>, /// Represents all the bags of coins pub bags: DaoMap<Denomination, BagOfCoins>, /// Represents everything that has happened in this wallet pub history: DaoVec<HistoricMonth>, /// This secure broker key is used by Wasmer to access this wallet but can only /// be acquired by the owner of the wallet sharing it (given that Wasmer does not store it) pub broker_key: EncryptKey, /// The broker unlock key needs to be supplied in order to access the broker key /// (this one is given to the broker key - which makes creates the trust trinity) pub broker_unlock_key: EncryptKey, }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/model/digital_service.rs
wasmer-deploy-cli/src/model/digital_service.rs
use serde::*; use super::*; #[derive(Serialize, Deserialize, Debug, Clone)] pub enum DigitalService { // Service provider will offer their services iteratively as a subscription Subscription, /// Time executing some automation for a particular digital task AutomationTime(AutomationTime), } impl DigitalService { pub fn name(&self) -> &str { self.params().0 } pub fn description(&self) -> &str { self.params().1 } fn params(&self) -> (&str, &str) { match self { DigitalService::Subscription => ( "Subscription", "Service provider will offer their services iteratively as a subscription.", ), DigitalService::AutomationTime(a) => (a.name(), a.description()), } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/model/contract_metrics.rs
wasmer-deploy-cli/src/model/contract_metrics.rs
use chrono::DateTime; use chrono::Utc; use serde::*; /// Metrics are used to track provider services so that charges can /// be made to the consumer at appropriate moments #[derive(Serialize, Deserialize, Debug, Clone, Default)] pub struct ContractMetrics { /// What are these metrics related to pub related_to: String, /// Last time the flat rate was charged pub last_flat_rate: Option<DateTime<Utc>>, /// Last time the download charge was incurred pub last_per_download_terabyte: Option<DateTime<Utc>>, /// Last time the upload charge was incurred pub last_per_upload_terabyte: Option<DateTime<Utc>>, /// Last time the data storage charge was incurred pub last_per_stored_gigabyte: Option<DateTime<Utc>>, /// Last time the compute charge waas incurred pub last_per_compute_second: Option<DateTime<Utc>>, /// Current amount of compute usage accumilated since the last charge was made /// (measured in microseconds) pub current_accumilated_compute: u64, /// Current amount of download bandwidth accumilated since the last charge was made /// (measured in bytes) pub current_accumilated_download: u64, /// Current amount of upload bandwidth accumilated since the last charge was made /// (measured in bytes) pub current_accumilated_upload: u64, /// Current amount of storage capacity that is being consumed /// (measured in bytes) pub current_storage: u64, }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/model/advertised_service.rs
wasmer-deploy-cli/src/model/advertised_service.rs
use serde::*; use std::time::Duration; use super::*; /// The commodity kind determines how this commodity will be listed /// on the market interaction interface. This metadata helps users /// identify what they are subscribing for. #[derive(Serialize, Deserialize, Debug, Clone)] pub struct AdvertisedService { /// Code assigned to this service pub code: String, /// The name of the service as seen by all consumers pub name: String, /// Detailed description of what the service is pub description: String, /// These charges that will be applied to your account for this service /// if you subscribe to it pub rate_cards: Vec<RateCard>, /// Identity of the owner of this particular service (the owner of /// the service is able to incur charges on your wallet) pub owner_identity: String, /// Terms and conditions for consuming this service pub terms_and_conditions: String, /// Amount of time before the services will be suspended pub grace_period: Duration, /// The subscription may still have some throttles pub throttle: Option<ThrottleTriggers>, }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/model/rate_card.rs
wasmer-deploy-cli/src/model/rate_card.rs
use serde::*; use super::*; /// Rate cards represent a series of charges incurred for consumption /// of various services and or commodities. #[derive(Serialize, Deserialize, Debug, Clone, Default)] pub struct RateCard { /// The currency that the rate card make charges at pub currency: NationalCurrency, // List of all the charges associated with this rate card pub charges: Vec<Charge>, }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/model/charge_frequency.rs
wasmer-deploy-cli/src/model/charge_frequency.rs
use chrono::Duration; use serde::*; use std::fmt; /// Determines the frequency that you will be charged #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum ChargeFrequency { Once, PerMinute, PerHour, PerDay, PerWeek, PerMonth, PerYear, } impl ChargeFrequency { pub fn as_duration(&self) -> Duration { match self { ChargeFrequency::Once => Duration::max_value(), ChargeFrequency::PerMinute => Duration::seconds(60), ChargeFrequency::PerHour => Duration::hours(1), ChargeFrequency::PerDay => Duration::days(1), ChargeFrequency::PerWeek => Duration::days(7), ChargeFrequency::PerMonth => Duration::days(30) .checked_add(&Duration::hours(10)) .unwrap() .checked_add(&Duration::seconds(2)) .unwrap() .checked_add(&Duration::milliseconds(880)) .unwrap(), ChargeFrequency::PerYear => Duration::hours(8760), } } } impl fmt::Display for ChargeFrequency { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { ChargeFrequency::Once => write!(f, "once-off"), ChargeFrequency::PerMinute => write!(f, "per-minute"), ChargeFrequency::PerHour => write!(f, "per-hour"), ChargeFrequency::PerDay => write!(f, "per-day"), ChargeFrequency::PerWeek => write!(f, "per-week"), ChargeFrequency::PerMonth => write!(f, "per-month"), ChargeFrequency::PerYear => write!(f, "per-year"), } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/model/instance_export.rs
wasmer-deploy-cli/src/model/instance_export.rs
use ate::comms::NodeId; use serde::*; /// Exports are web assembly binaries that are exposed to the world /// as consumable targets for anyone who possesses the access token #[derive(Debug, Serialize, Deserialize, Clone)] pub struct InstanceExport { /// Access token that allows access to this exported binary pub access_token: String, /// Name of the binary that can be invoked pub binary: String, /// Indicates if this export is fully distributed across the globe, if it is /// not then when it starts up then it pins itself to a particular location /// until it goes idle again. pub distributed: bool, /// Can be accessed via HTTP calls pub http: bool, /// Can be accessed via HTTPS calls pub https: bool, /// Can be accessed using the wasmer-bus pub bus: bool, /// Indicates where the service instance is currently pinned (when its stateful) pub pinned: Option<NodeId>, }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/model/commodity_kind.rs
wasmer-deploy-cli/src/model/commodity_kind.rs
use serde::*; use super::*; /// The commodity kind determines how this commodity will be listed /// on the market interaction interface. This metadata helps users /// identify what they are trading. #[derive(Serialize, Deserialize, Debug, Clone)] pub struct CommodityKindType { pub name: String, pub category: CommodityCategory, pub description: Option<String>, pub details: Option<String>, pub image: Option<Vec<u8>>, } #[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum CommodityKind { Coin(NationalCurrency), } impl CommodityKind { pub fn params(&self) -> CommodityKindType { match self { CommodityKind::Coin(c) => CommodityKindType { name: "Coin".to_string(), category: CommodityCategory::NationalCurrency(c.clone()), description: None, details: None, image: None, }, } } pub fn name(&self) -> String { self.params().name } pub fn category(&self) -> CommodityCategory { self.params().category } pub fn description(&self) -> Option<String> { self.params().description } pub fn details(&self) -> Option<String> { self.params().details } pub fn image(&self) -> Option<Vec<u8>> { self.params().image } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/model/historic_month.rs
wasmer-deploy-cli/src/model/historic_month.rs
use serde::*; use super::*; use ate::prelude::*; /// Represents a month of activity that has happened /// in ones account #[derive(Serialize, Deserialize, Debug, Clone)] pub struct HistoricMonth { // Which month does this data relate to pub month: u32, // The year that this history occured pub year: i32, /// Represents everything that happened within this month pub days: DaoVec<HistoricDay>, }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/opt/source.rs
wasmer-deploy-cli/src/opt/source.rs
use clap::Parser; use super::purpose::*; use super::wallet_action::*; #[derive(Parser, Clone)] pub enum OptsWalletSource { /// One of your personal wallets #[clap()] Personal(OptWalletPersonal), /// Particular wallet attached to a domain group #[clap()] Domain(OptWalletDomain), } impl OptsWalletSource { pub fn action<'a>(&'a self) -> &'a OptWalletAction { match self { OptsWalletSource::Personal(a) => &a.action, OptsWalletSource::Domain(a) => &a.action, } } } #[derive(Parser, Clone)] #[clap()] pub struct OptWalletPersonal { /// Name of the personal wallet to perform this action on #[clap(index = 1, default_value = "default")] pub name: String, /// Action to perform on the wallet #[clap(subcommand)] pub action: OptWalletAction, } #[derive(Parser, Clone)] #[clap()] pub struct OptWalletDomain { /// Name of the group that the wallet is attached to #[clap(index = 1)] pub domain: String, /// Name of the wallet within this group to perform this action on #[clap(index = 2, default_value = "default")] pub name: String, /// Action to performed in this context #[clap(subcommand)] pub action: OptWalletAction, } impl OptsPurpose<OptWalletAction> for OptsWalletSource { fn purpose(&self) -> Purpose<OptWalletAction> { match self { OptsWalletSource::Personal(a) => Purpose::Personal { wallet_name: a.name.clone(), action: a.action.clone(), }, OptsWalletSource::Domain(a) => Purpose::Domain { domain_name: a.domain.clone(), wallet_name: a.name.clone(), action: a.action.clone(), }, } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/opt/contract.rs
wasmer-deploy-cli/src/opt/contract.rs
use clap::Parser; use super::purpose::*; #[allow(dead_code)] #[derive(Parser, Clone)] #[clap(version = "1.5", author = "Wasmer Inc <info@wasmer.io>")] pub struct OptsContract { /// Category of contracts to perform an action upon #[clap(subcommand)] pub purpose: OptsContractFor, } #[derive(Parser, Clone)] pub enum OptsContractFor { /// Contracts associated to you personally #[clap()] Personal(OptsContractForPersonal), /// Contracts associated with a particular group you can authorize on behalf of #[clap()] Domain(OptsContractForDomain), } impl OptsContractFor { pub fn action<'a>(&'a self) -> &'a OptsContractAction { match self { OptsContractFor::Personal(a) => &a.action, OptsContractFor::Domain(a) => &a.action, } } } #[derive(Parser, Clone)] #[clap()] pub struct OptsContractForPersonal { /// Name of the personal wallet to use in this context (if required) #[clap(index = 1, default_value = "default")] pub wallet_name: String, /// Action to perform on the contract #[clap(subcommand)] pub action: OptsContractAction, } #[derive(Parser, Clone)] #[clap()] pub struct OptsContractForDomain { /// Name of the group that the wallet is attached to #[clap(index = 1)] pub domain: String, /// Name of the group wallet to use in this context (if required) #[clap(index = 2, default_value = "default")] pub wallet_name: String, /// Action to perform on the contract #[clap(subcommand)] pub action: OptsContractAction, } #[derive(Parser, Clone)] #[clap()] pub enum OptsContractAction { /// Lists all the active contracts #[clap()] List, /// Details the details of a particular active contract #[clap()] Details(OptsContractDetails), /// Cancels a particular contract #[clap()] Cancel(OptsContractCancel), } #[derive(Parser, Clone)] #[clap()] pub struct OptsContractDetails { /// Name of the contract to retrieve details for #[clap(index = 1)] pub reference_number: String, } #[derive(Parser, Clone)] #[clap()] pub struct OptsContractCancel { /// Name of the contract to be cancelled #[clap(index = 1)] pub reference_number: String, } impl OptsPurpose<OptsContractAction> for OptsContractFor { fn purpose(&self) -> Purpose<OptsContractAction> { match self { OptsContractFor::Personal(a) => Purpose::Personal { wallet_name: a.wallet_name.clone(), action: a.action.clone(), }, OptsContractFor::Domain(a) => Purpose::Domain { domain_name: a.domain.clone(), wallet_name: a.wallet_name.clone(), action: a.action.clone(), }, } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/opt/wallet_action.rs
wasmer-deploy-cli/src/opt/wallet_action.rs
use clap::Parser; use super::OptsBalance; use super::OptsCreateWallet; use super::OptsDeposit; use super::OptsRemoveWallet; use super::OptsTransactionHistory; use super::OptsTransfer; use super::OptsWithdraw; #[derive(Parser, Clone)] pub enum OptWalletAction { /// Creates this wallet with the supplied name #[clap()] Create(OptsCreateWallet), /// Removes this empty wallet #[clap()] Remove(OptsRemoveWallet), /// Displays the current balance #[clap()] Balance(OptsBalance), /// Displays the transaction history #[clap()] History(OptsTransactionHistory), /// Transfers a commodity (e.g. money) between two wallets #[clap()] Transfer(OptsTransfer), /// Deposit a wallet from an external source (e.g. PayPal Transfer) #[clap()] Deposit(OptsDeposit), /// Withdraws from the wallet to an external destination (e.g. PayPal Account) #[clap()] Withdraw(OptsWithdraw), }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/opt/withdraw.rs
wasmer-deploy-cli/src/opt/withdraw.rs
use clap::Parser; use crate::model::Decimal; use crate::model::NationalCurrency; #[derive(Parser, Clone)] #[clap()] pub struct OptsWithdraw { /// Amount to be deposited into this account #[clap(index = 1)] pub amount: Decimal, /// National currency to be deposited into this account (e.g. aud,eur,gbp,usd,hkd) #[clap(index = 2)] pub currency: NationalCurrency, }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/opt/transfer.rs
wasmer-deploy-cli/src/opt/transfer.rs
use clap::Parser; use super::destination::*; use crate::model::Decimal; use crate::model::NationalCurrency; #[derive(Parser, Clone)] #[clap()] pub struct OptsTransfer { /// Amount to be deposited into this account #[clap(index = 1)] pub amount: Decimal, /// National currency to be deposited into this account (e.g. aud,eur,gbp,usd,hkd) #[clap(index = 2)] pub currency: NationalCurrency, /// Wallet to transfer the funds to #[clap(subcommand)] pub destination: OptsWalletDestination, /// Repreats the transfer multiple times (used for testing purposes) #[clap(long)] pub repeat: Option<u32>, /// Indicates if the confirmation email should be suppressed #[clap(short, long)] pub silent: bool, }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/opt/network.rs
wasmer-deploy-cli/src/opt/network.rs
use clap::Parser; use url::Url; use ate_comms::StreamSecurity; use super::purpose::*; use super::OptsCidrAction; use super::OptsPeeringAction; #[allow(dead_code)] #[derive(Parser)] #[clap(version = "1.5", author = "Wasmer Inc <info@wasmer.io>")] pub struct OptsNetwork { #[clap(subcommand)] pub cmd: OptsNetworkCommand, /// URL where the data is remotely stored on a distributed commit log (e.g. wss://wasmer.sh/db). #[clap(short, long)] pub db_url: Option<Url>, /// Level of security to apply to the connection #[clap(long, default_value = "any")] pub security: StreamSecurity } #[derive(Parser)] pub enum OptsNetworkCommand { /// Performs an action on a particular grouping of networks or a specific network in a group #[clap()] For(OptsNetworkCommandFor), /// Reconnects to a network using an access token that was previously exported for a network #[clap()] Reconnect(OptsNetworkReconnect), /// Disconnects from the network #[clap()] Disconnect, /// Monitors the local network and sends the output to packet metadata to STDOUT #[clap()] Monitor(OptsNetworkMonitor), /// Create a TAP device that bridges the local network with the remote network #[cfg(feature = "enable_bridge")] #[cfg(any(target_os = "linux", target_os = "macos"))] #[clap()] Bridge(OptsNetworkBridge), } #[allow(dead_code)] #[derive(Parser, Clone)] #[clap(version = "1.5", author = "Wasmer Inc <info@wasmer.io>")] pub struct OptsNetworkCommandFor { /// Category of networks to perform an action upon #[clap(subcommand)] pub purpose: OptsNetworkPurpose, } #[allow(dead_code)] #[derive(Parser, Clone)] #[clap(version = "1.5", author = "Wasmer Inc <info@wasmer.io>")] pub struct OptsNetworkMonitor { /// Overrides the URL where the network can be accessed from (e.g. wss://wasmer.sh/net) /// (the default is to use the URL contained within the token) #[clap(short, long)] pub net_url: Option<Url>, } #[cfg(feature = "enable_bridge")] #[cfg(any(target_os = "linux", target_os = "macos"))] #[allow(dead_code)] #[derive(Parser, Clone)] #[clap(version = "1.5", author = "Wasmer Inc <info@wasmer.io>")] pub struct OptsNetworkBridge { /// Overrides the URL where the network can be accessed from (e.g. wss://wasmer.sh/net) /// (the default is to use the URL contained within the token) #[clap(short, long)] pub net_url: Option<Url>, /// Port will receive all packets on the network and not just those destined for this port #[clap(short, long)] pub promiscuous: bool, /// Runs the port as a daemon in the background after forking the process #[clap(short, long)] pub daemon: bool, /// Sets the MTU for this device #[clap(long)] pub mtu: Option<u32>, } #[allow(dead_code)] #[derive(Parser, Clone)] #[clap(version = "1.5", author = "Wasmer Inc <info@wasmer.io>")] pub struct OptsNetworkConnect { /// Name of the network to connect to #[clap(index = 1)] pub name: String, /// Exports the token to STDOUT rather than storing it so that it may be used later to reconnect #[clap(short, long)] pub export: bool, } #[allow(dead_code)] #[derive(Parser, Clone)] #[clap(version = "1.5", author = "Wasmer Inc <info@wasmer.io>")] pub struct OptsNetworkReconnect { /// Reconnects to a network using an access token that was previously exported #[clap(index = 1)] pub token: String, } #[derive(Parser, Clone)] #[clap()] pub struct OptsNetworkCidr { /// Name of the network to be modify routing tables #[clap(index = 1)] pub name: String, /// Action to perform on the cidr #[clap(subcommand)] pub action: OptsCidrAction, } #[derive(Parser, Clone)] #[clap()] pub struct OptsNetworkPeering { /// Name of the network to modify peering #[clap(index = 1)] pub name: String, /// Action to perform on the peerings #[clap(subcommand)] pub action: OptsPeeringAction, } #[derive(Parser, Clone)] #[clap()] pub struct OptsNetworkCreate { /// Name of the new network (which will be generated if you dont supply one) #[clap(index = 1)] pub name: Option<String>, /// Forces the creation of this network even if there is a duplicate #[clap(short, long)] pub force: bool, } #[derive(Parser, Clone)] #[clap()] pub struct OptsNetworkKill { /// Name of the network to be killed /// (killed networks are perminently destroyed) #[clap(index = 1)] pub name: String, /// Forces the removal of the network from the wallet even /// if access is denied to its data and thus this would create an orphan chain. #[clap(short, long)] pub force: bool, } #[derive(Parser, Clone)] #[clap()] pub struct OptsNetworkReset { /// Name of the network to destroy #[clap(index = 1)] pub name: String, } #[derive(Parser, Clone)] #[clap()] pub struct OptsNetworkDetails { /// Name of the network to get the details for #[clap(index = 1)] pub name: String, } #[derive(Parser, Clone)] #[clap()] pub enum OptsNetworkAction { /// List all the networks that can be connected to #[clap()] List, /// Details the details of a particular network #[clap()] Details(OptsNetworkDetails), /// List, add or remove a CIDR (subnet) #[clap()] Cidr(OptsNetworkCidr), /// List, add or remove a network peering between different networks #[clap()] Peering(OptsNetworkPeering), /// Connects this machine/instance with a remote network #[clap()] Connect(OptsNetworkConnect), /// Creates a new network #[clap()] Create(OptsNetworkCreate), /// Kills are particular network #[clap()] Kill(OptsNetworkKill), /// Resets an network and its attached mesh nodes #[clap()] Reset(OptsNetworkReset), } #[derive(Parser, Clone)] pub enum OptsNetworkPurpose { /// Networks associated to you personally #[clap()] Personal(OptsNetworkForPersonal), /// Networks associated with a particular group you can authorize on behalf of #[clap()] Domain(OptsNetworkForDomain), } impl OptsNetworkPurpose { pub fn is_personal(&self) -> bool { if let OptsNetworkPurpose::Personal(..) = self { true } else { false } } } #[derive(Parser, Clone)] #[clap()] pub struct OptsNetworkForPersonal { /// Name of the personal wallet to use for this network (if required) #[clap(index = 1, default_value = "default")] pub wallet_name: String, /// Action to perform on this network #[clap(subcommand)] pub action: OptsNetworkAction, } #[derive(Parser, Clone)] #[clap()] pub struct OptsNetworkForDomain { /// Name of the group that the network is attached to #[clap(index = 1)] pub domain: String, /// Name of the group wallet to use in this context (if required) #[clap(index = 2, default_value = "default")] pub wallet_name: String, /// Action to perform on this network #[clap(subcommand)] pub action: OptsNetworkAction, } impl OptsPurpose<OptsNetworkAction> for OptsNetworkPurpose { fn purpose(&self) -> Purpose<OptsNetworkAction> { match self { OptsNetworkPurpose::Personal(a) => Purpose::Personal { wallet_name: a.wallet_name.clone(), action: a.action.clone(), }, OptsNetworkPurpose::Domain(a) => Purpose::Domain { domain_name: a.domain.clone(), wallet_name: a.wallet_name.clone(), action: a.action.clone(), }, } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/opt/login.rs
wasmer-deploy-cli/src/opt/login.rs
use clap::Parser; #[allow(dead_code)] #[derive(Parser)] #[clap(version = "1.5", author = "Wasmer Inc <info@wasmer.io>")] pub struct OptsLogin { /// Email address that you wish to login using #[clap(index = 1)] pub email: Option<String>, /// Password associated with this account #[clap(index = 2)] pub password: Option<String>, /// Flag that indicates if you will login as SUDO which is a high priv session /// that has access to make changes to the wallet without MFA challenges #[clap(long)] pub sudo: bool, /// Supplies an encoded token as a login context #[clap(long)] pub token: Option<String>, }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/opt/destination.rs
wasmer-deploy-cli/src/opt/destination.rs
use clap::Parser; use super::purpose::*; #[derive(Parser, Clone)] #[clap()] pub struct OptWalletDestinationPersonal { /// Name of the personal wallet #[clap(index = 1, default_value = "default")] pub name: String, } #[derive(Parser, Clone)] #[clap()] pub struct OptWalletDestinationDomain { /// Name of the domain group that the wallet is attached to #[clap(index = 1)] pub domain: String, /// Name of the wallet within this domain #[clap(index = 2, default_value = "default")] pub name: String, } #[derive(Parser, Clone)] pub enum OptsWalletDestination { /// One of your personal wallets #[clap()] Personal(OptWalletDestinationPersonal), /// Particular wallet attached to a group #[clap()] Domain(OptWalletDestinationDomain), } impl OptsPurpose<()> for OptsWalletDestination { fn purpose(&self) -> Purpose<()> { match self { OptsWalletDestination::Personal(a) => Purpose::Personal { wallet_name: a.name.clone(), action: (), }, OptsWalletDestination::Domain(a) => Purpose::Domain { domain_name: a.domain.clone(), wallet_name: a.name.clone(), action: (), }, } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/opt/remove_wallet.rs
wasmer-deploy-cli/src/opt/remove_wallet.rs
use clap::Parser; #[derive(Parser, Clone)] #[clap()] pub struct OptsRemoveWallet { /// Forces the wallet to be destroyed even if it has commodities in it #[clap(short, long)] pub force: bool, }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/opt/service.rs
wasmer-deploy-cli/src/opt/service.rs
use clap::Parser; use super::purpose::*; #[allow(dead_code)] #[derive(Parser, Clone)] #[clap(version = "1.5", author = "Wasmer Inc <info@wasmer.io>")] pub struct OptsService { /// Type of services to perform an action upon #[clap(subcommand)] pub purpose: OptsServiceFor, } #[derive(Parser, Clone)] pub enum OptsServiceFor { /// Services associated to you personally #[clap()] Personal(OptsServiceForPersonal), /// Services associated with a particular domain you can authorize on behalf of #[clap()] Domain(OptsServiceForDomain), } #[derive(Parser, Clone)] #[clap()] pub struct OptsServiceForPersonal { /// Name of the personal wallet to use in this context (if required) #[clap(index = 1, default_value = "default")] pub wallet_name: String, /// Action to perform on the wallet #[clap(subcommand)] pub action: OptsServiceAction, } #[derive(Parser, Clone)] #[clap()] pub struct OptsServiceForDomain { /// Name of the domain that the wallet is attached to #[clap(index = 1)] pub domain: String, /// Name of the domain wallet to use in this context (if required) #[clap(index = 2, default_value = "default")] pub wallet_name: String, /// Action to perform on the wallet #[clap(subcommand)] pub action: OptsServiceAction, } #[derive(Parser, Clone)] #[clap()] pub struct OptsSubscribe { /// Name of the service to be subscribed to /// (refer to the list command for available services) #[clap(index = 1)] pub service_name: String, /// Forces the contract to be created even if one already exists #[clap(short, long)] pub force: bool, } #[derive(Parser, Clone)] #[clap()] pub struct OptsServiceDetails { /// Name of the service to retrieve more details for #[clap(index = 1)] pub service_name: String, } #[derive(Parser, Clone)] #[clap()] pub enum OptsServiceAction { /// Lists all the services available under this context #[clap()] List, /// Displays the details of a specific service #[clap()] Details(OptsServiceDetails), /// Subscribes to a particular service #[clap()] Subscribe(OptsSubscribe), } impl OptsPurpose<OptsServiceAction> for OptsServiceFor { fn purpose(&self) -> Purpose<OptsServiceAction> { match self { OptsServiceFor::Personal(a) => Purpose::Personal { wallet_name: a.wallet_name.clone(), action: a.action.clone(), }, OptsServiceFor::Domain(a) => Purpose::Domain { domain_name: a.domain.clone(), wallet_name: a.wallet_name.clone(), action: a.action.clone(), }, } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/opt/history.rs
wasmer-deploy-cli/src/opt/history.rs
use clap::Parser; #[derive(Parser, Clone)] #[clap()] pub struct OptsTransactionHistory { /// Returns the history only for a particular year #[clap(long)] pub year: Option<i32>, /// Returns the history only for a particular month #[clap(long)] pub month: Option<u32>, /// Returns the history only for a particular day #[clap(long)] pub day: Option<u32>, /// Indicates if the details of each event should be displayed #[clap(short, long)] pub details: bool, /// Also show the current balance of the account #[clap(short, long)] pub balance: bool, /// When reading the balance the wallet is first reconciled - to prevent this happening then set this flag #[clap(long)] pub no_reconcile: bool, }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/opt/purpose.rs
wasmer-deploy-cli/src/opt/purpose.rs
pub enum Purpose<A> where A: Clone, { Personal { wallet_name: String, action: A, }, Domain { domain_name: String, wallet_name: String, action: A, }, } impl<A> Purpose<A> where A: Clone, { pub fn is_personal(&self) -> bool { if let Purpose::Personal { .. } = self { true } else { false } } } pub trait OptsPurpose<A> where A: Clone, { fn purpose(&self) -> Purpose<A>; } impl<'a, A> dyn OptsPurpose<A> + 'a where A: Clone, { pub fn fullname(&'a self, my_identity: &'_ str) -> String { match self.purpose() { Purpose::Personal { wallet_name, action: _, } => format!("{}({})", my_identity, wallet_name), Purpose::Domain { domain_name, wallet_name, action: _, } => format!("{}({})", domain_name, wallet_name), } } pub fn group_name(&'a self) -> Option<String> { match self.purpose() { Purpose::Personal { wallet_name: _, action: _, } => None, Purpose::Domain { domain_name, wallet_name: _, action: _, } => Some(domain_name), } } pub fn wallet_name(&'a self) -> String { match self.purpose() { Purpose::Personal { wallet_name, action: _, } => wallet_name, Purpose::Domain { domain_name: _, wallet_name, action: _, } => wallet_name, } } pub fn action(&'a self) -> A { match self.purpose() { Purpose::Personal { wallet_name: _, action, } => action, Purpose::Domain { domain_name: _, wallet_name: _, action, } => action, } } pub fn is_personal(&'a self) -> bool { self.purpose().is_personal() } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/opt/mod.rs
wasmer-deploy-cli/src/opt/mod.rs
mod balance; mod bus; mod contract; mod create_wallet; mod deposit; mod destination; mod history; mod login; mod logout; mod purpose; mod remove_wallet; mod service; mod source; mod transfer; mod wallet; mod wallet_action; mod withdraw; mod instance; mod network; pub use wasmer_auth::opt::*; pub use balance::*; pub use bus::*; pub use contract::*; pub use create_wallet::*; pub use deposit::*; pub use destination::*; pub use history::*; pub use login::*; pub use logout::*; pub use purpose::*; pub use remove_wallet::*; pub use service::*; pub use source::*; pub use transfer::*; pub use wallet::*; pub use wallet_action::*; pub use withdraw::*; pub use instance::*; pub use network::*;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/opt/wallet.rs
wasmer-deploy-cli/src/opt/wallet.rs
use clap::Parser; use super::source::*; #[allow(dead_code)] #[derive(Parser, Clone)] #[clap(version = "1.5", author = "Wasmer Inc <info@wasmer.io>")] pub struct OptsWallet { /// Wallet to perform the action on #[clap(subcommand)] pub source: OptsWalletSource, }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/opt/create_wallet.rs
wasmer-deploy-cli/src/opt/create_wallet.rs
use clap::Parser; use crate::model::*; #[derive(Parser, Clone)] #[clap()] pub struct OptsCreateWallet { /// Country of residence for tax purposes (ISO 3166) - this is the alpha-3 letter code (e.g. USA) #[clap(index = 1)] pub country: Country, }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/opt/logout.rs
wasmer-deploy-cli/src/opt/logout.rs
use clap::Parser; #[allow(dead_code)] #[derive(Parser)] #[clap(version = "1.5", author = "Wasmer Inc <info@wasmer.io>")] pub struct OptsLogout {}
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/opt/bus.rs
wasmer-deploy-cli/src/opt/bus.rs
use clap::Parser; #[allow(dead_code)] #[derive(Parser)] pub struct OptsBus { /// URL where the data is remotely stored on a distributed commit log (e.g. wss://wasmer.sh/db). #[clap(short, long)] pub remote: Option<url::Url>, /// Determines how the file-system will react while it is nominal and when it is /// recovering from a communication failure (valid options are 'async', 'readonly-async', /// 'readonly-sync' or 'sync') #[clap(long, default_value = "readonly-async")] pub recovery_mode: ate::mesh::RecoveryMode, /// Configure the log file for <raw>, <barebone>, <speed>, <compatibility>, <balanced> or <security> #[clap(long, default_value = "speed")] pub configured_for: ate::conf::ConfiguredFor, /// Format of the metadata in the log file as <bincode>, <json> or <mpack> #[clap(long, default_value = "bincode")] pub meta_format: ate::spec::SerializationFormat, /// Format of the data in the log file as <bincode>, <json> or <mpack> #[clap(long, default_value = "bincode")] pub data_format: ate::spec::SerializationFormat, /// Mode that the compaction will run under (valid modes are 'never', 'modified', 'timer', 'factor', 'size', 'factor-or-timer', 'size-or-timer') #[clap(long, default_value = "factor-or-timer")] pub compact_mode: ate::compact::CompactMode, /// Time in seconds between compactions of the log file (default: 1 hour) - this argument is ignored if you select a compact_mode that has no timer #[clap(long, default_value = "3600")] pub compact_timer: u64, /// Factor growth in the log file which will trigger compaction - this argument is ignored if you select a compact_mode that has no growth trigger #[clap(long, default_value = "0.4")] pub compact_threshold_factor: f32, /// Size of growth in bytes in the log file which will trigger compaction (default: 100MB) - this argument is ignored if you select a compact_mode that has no growth trigger #[clap(long, default_value = "104857600")] pub compact_threshold_size: u64, }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/opt/deposit.rs
wasmer-deploy-cli/src/opt/deposit.rs
use clap::Parser; use crate::model::Decimal; use crate::model::NationalCurrency; #[derive(Parser, Clone)] #[clap()] pub struct OptsDepositPending {} #[derive(Parser, Clone)] #[clap()] pub struct OptsDepositNew { /// Amount to be deposited into this account #[clap(index = 1)] pub amount: Decimal, /// National currency to be deposited into this account (e.g. aud,eur,gbp,usd,hkd) #[clap(index = 2)] pub currency: NationalCurrency, } #[derive(Parser, Clone)] #[clap()] pub struct OptsDepositCancel { /// ID of the pending request to be cancelled #[clap(index = 1)] pub id: String, } #[derive(Parser, Clone)] pub enum OptsDepositAction { /// Lists all the pending deposit requests that have not yet been paid #[clap()] Pending(OptsDepositPending), /// Creates a new deposit request #[clap()] New(OptsDepositNew), /// Cancels a specific deposit request that will not be paid #[clap()] Cancel(OptsDepositCancel), } #[derive(Parser, Clone)] #[clap()] pub struct OptsDeposit { #[clap(subcommand)] pub action: OptsDepositAction, }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/opt/balance.rs
wasmer-deploy-cli/src/opt/balance.rs
use clap::Parser; #[derive(Parser, Clone)] #[clap()] pub struct OptsBalance { /// Show the individual coins that make up the balance #[clap(short, long)] pub coins: bool, /// When reading the balance the wallet is first reconciled - to prevent this happening then set this flag #[clap(long)] pub no_reconcile: bool, }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/opt/instance.rs
wasmer-deploy-cli/src/opt/instance.rs
use std::net::IpAddr; use ate_crypto::SerializationFormat; use clap::Parser; use url::Url; use super::purpose::*; use ate_comms::StreamSecurity; #[allow(dead_code)] #[derive(Parser, Clone)] #[clap(version = "1.5", author = "Wasmer Inc <info@wasmer.io>")] pub struct OptsInstance { /// Category of instances to perform an action upon #[clap(subcommand)] pub purpose: OptsInstanceFor, /// URL where the data is remotely stored on a distributed commit log (e.g. wss://wasmer.sh/db). #[clap(short, long)] pub db_url: Option<Url>, /// URL where the instances can be accessed from (e.g. wss://wasmer.sh/inst) #[clap(short, long)] pub inst_url: Option<Url>, /// Level of security to apply to the connection #[clap(long, default_value = "any")] pub security: StreamSecurity } #[derive(Parser, Clone)] pub enum OptsInstanceFor { /// Instances associated to you personally #[clap()] Personal(OptsInstanceForPersonal), /// Instances associated with a particular group you can authorize on behalf of #[clap()] Domain(OptsInstanceForDomain), } impl OptsInstanceFor { pub fn action<'a>(&'a self) -> &'a OptsInstanceAction { match self { OptsInstanceFor::Personal(a) => &a.action, OptsInstanceFor::Domain(a) => &a.action, } } pub fn is_personal(&self) -> bool { if let OptsInstanceFor::Personal(..) = self { true } else { false } } } #[derive(Parser, Clone)] #[clap()] pub struct OptsInstanceForPersonal { /// Name of the personal wallet to use for this instance (if required) #[clap(index = 1, default_value = "default")] pub wallet_name: String, /// Action to perform on the instance #[clap(subcommand)] pub action: OptsInstanceAction, } #[derive(Parser, Clone)] #[clap()] pub struct OptsInstanceForDomain { /// Name of the group that the instance is attached to #[clap(index = 1)] pub domain: String, /// Name of the group wallet to use in this context (if required) #[clap(index = 2, default_value = "default")] pub wallet_name: String, /// Action to perform on the instance #[clap(subcommand)] pub action: OptsInstanceAction, } #[derive(Parser, Clone)] #[clap()] pub enum OptsInstanceAction { /// Lists all the active instances #[clap()] List, /// Details the details of a particular active instance #[clap()] Details(OptsInstanceDetails), /// Creates a new instance #[clap()] Create(OptsInstanceCreate), /// Exports an interface from a particular instance #[clap()] Export(OptsInstanceExport), /// Deports a previously exposed interface for a particular instance #[clap()] Deport(OptsInstanceDeport), /// Kills are particular instance - killed instances are totally destroyed #[clap()] Kill(OptsInstanceKill), /// Switches to a shell that runs against a particular instance #[clap()] Shell(OptsInstanceShell), /// Calls a function within a process in a particular instance #[clap()] Call(OptsInstanceCall), /// Mount an existing instance file system to a particular path #[clap()] Mount(OptsInstanceMount), /// Clones a particular instance #[clap()] Clone(OptsInstanceClone), /// List, add or remove a CIDR (subnet) from the instance #[clap()] Cidr(OptsInstanceCidr), /// List, add or remove a network peering from the instance #[clap()] Peering(OptsInstancePeering), /// Resets an instance #[clap()] Reset(OptsInstanceReset), } impl OptsInstanceAction { pub fn needs_sudo(&self) -> bool { /* match self { OptsInstanceAction::Create(_) => true, OptsInstanceAction::Kill(_) => true, OptsInstanceAction::Restore(_) => true, OptsInstanceAction::Upgrade(_) => true, OptsInstanceAction::Stop(_) => true, OptsInstanceAction::Start(_) => true, _ => false, } */ true } pub fn name(&self) -> Option<String> { match self { OptsInstanceAction::List => None, OptsInstanceAction::Create(_) => None, OptsInstanceAction::Details(opts) => Some(opts.name.clone()), OptsInstanceAction::Kill(opts) => Some(opts.name.clone()), OptsInstanceAction::Clone(opts) => Some(opts.name.clone()), OptsInstanceAction::Shell(opts) => Some(opts.name.clone()), OptsInstanceAction::Call(opts) => Some(opts.name.clone()), OptsInstanceAction::Export(opts) => Some(opts.name.clone()), OptsInstanceAction::Deport(opts) => Some(opts.name.clone()), OptsInstanceAction::Mount(opts) => Some(opts.name.clone()), OptsInstanceAction::Cidr(opts) => Some(opts.name.clone()), OptsInstanceAction::Peering(opts) => Some(opts.name.clone()), OptsInstanceAction::Reset(opts) => Some(opts.name.clone()), } } } #[derive(Parser, Clone)] #[clap()] pub struct OptsInstanceDetails { /// Token of the instance to get details for #[clap(index = 1)] pub name: String, } #[derive(Parser, Clone)] #[clap()] pub struct OptsInstanceCreate { /// Name of the new instance (which will be generated if you dont supply one) #[clap(index = 1)] pub name: Option<String>, /// Forces the creation of this instance even if there is a duplicate #[clap(short, long)] pub force: bool, } #[derive(Parser, Clone)] #[clap()] pub struct OptsInstanceExport { /// Name of the instance to export an interface from #[clap(index = 1)] pub name: String, /// Name of the binary that will be exported #[clap(index = 2)] pub binary: String, /// Distributed instances run all over the world concurrently on the same file system /// They are started on-demand as needed and shutdown when idle. Pinned instances on /// the other hand are bound to a particular location after startup until they go /// idle which allows them to be stateful #[clap(short, long)] pub pinned: bool, /// Indicates if the exported endpoint will be accessible via http (API calls) #[clap(long)] pub no_http: bool, /// Indicates if the exported endpoint will be accessible via https (API calls) #[clap(long)] pub no_https: bool, /// Indicates if the exported endpoint will be accessible via wasmer-bus #[clap(long)] pub no_bus: bool, } #[derive(Parser, Clone)] #[clap()] pub struct OptsInstanceDeport { /// Name of the instance to export an interface from #[clap(index = 1)] pub name: String, /// Token of the exported interface to be deleted #[clap(index = 2)] pub token: String, } #[derive(Parser, Clone)] #[clap()] pub struct OptsInstanceKill { /// Name of the instance to be killed /// (killed instances are perminently destroyed) #[clap(index = 1)] pub name: String, /// Forces the removal of the instance from the wallet even /// if access is denied to its data and thus this would create an orphan chain. #[clap(short, long)] pub force: bool, } #[derive(Parser, Clone)] #[clap()] pub struct OptsInstanceClone { /// Name of the instance to be cloned #[clap(index = 1)] pub name: String, } #[derive(Parser, Clone)] #[clap()] pub struct OptsInstanceShell { /// Name of the instance to run commmands against #[clap(index = 1)] pub name: String, } #[derive(Parser, Clone)] #[clap()] pub struct OptsInstanceCall { /// Name of the instance to run commmands against #[clap(index = 1)] pub name: String, /// WAPM name of the process to be invoked #[clap(index = 2)] pub data: String, /// Topic of the invocation call #[clap(index = 3)] pub topic: String, /// Format of the data passed into this call #[clap(short, long, default_value = "json")] pub format: SerializationFormat, } #[derive(Parser, Clone)] #[clap()] pub struct OptsInstanceMount { /// Name of the instance to mounted #[clap(index = 1)] pub name: String, /// Path that the instance will be mounted at #[clap(index = 2)] pub path: String, } #[derive(Parser, Clone)] #[clap()] pub struct OptsInstanceCidr { /// Name of the instance #[clap(index = 1)] pub name: String, /// Action to perform on the cidr #[clap(subcommand)] pub action: OptsCidrAction, } #[derive(Parser, Clone)] #[clap()] pub enum OptsCidrAction { /// Lists all the cidrs for this instance #[clap()] List, /// Adds a new cidr to this instance #[clap()] Add(OptsCidrAdd), /// Removes a cidr from this instance #[clap()] Remove(OptsCidrRemove), } #[derive(Parser, Clone)] #[clap()] pub struct OptsCidrAdd { /// IP address of the new CIDR #[clap(index = 1)] pub ip: IpAddr, /// Prefix of the cidr #[clap(index = 2)] pub prefix: u8, } #[derive(Parser, Clone)] #[clap()] pub struct OptsCidrRemove { /// IP address of the CIDR to be removed #[clap(index = 1)] pub ip: IpAddr, } #[derive(Parser, Clone)] #[clap()] pub struct OptsInstancePeering { /// Name of the instance #[clap(index = 1)] pub name: String, /// Action to perform on the peerings #[clap(subcommand)] pub action: OptsPeeringAction, } #[derive(Parser, Clone)] #[clap()] pub struct OptsInstanceReset { /// Name of the instance #[clap(index = 1)] pub name: String, } #[derive(Parser, Clone)] #[clap()] pub enum OptsPeeringAction { /// Lists all the cidrs for this instance #[clap()] List, /// Adds a new peering for this instance #[clap()] Add(OptsPeeringAdd), /// Removes a peering from this instance #[clap()] Remove(OptsPeeringRemove), } #[derive(Parser, Clone)] #[clap()] pub struct OptsPeeringAdd { /// Name of the other instance to be peered against #[clap(index = 1)] pub peer: String } #[derive(Parser, Clone)] #[clap()] pub struct OptsPeeringRemove { /// Name of the other instance to be unpeered from #[clap(index = 1)] pub peer: String } impl OptsPurpose<OptsInstanceAction> for OptsInstanceFor { fn purpose(&self) -> Purpose<OptsInstanceAction> { match self { OptsInstanceFor::Personal(a) => Purpose::Personal { wallet_name: a.wallet_name.clone(), action: a.action.clone(), }, OptsInstanceFor::Domain(a) => Purpose::Domain { domain_name: a.domain.clone(), wallet_name: a.wallet_name.clone(), action: a.action.clone(), }, } } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/api/instance_action.rs
wasmer-deploy-cli/src/api/instance_action.rs
use ate::header::PrimaryKey; use ate::prelude::*; use error_chain::bail; #[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use std::ops::Deref; use crate::error::*; use crate::model::{INSTANCE_ROOT_ID, ServiceInstance, WalletInstance, MasterAuthority, MASTER_AUTHORITY_ID}; use super::*; impl DeployApi { pub async fn instance_load(&self, wallet_instance: &WalletInstance) -> Result<DaoMut<ServiceInstance>, LoadError> { // Get the sudo rights from the session (as we will use these for the wallet) let sudo_private_read = match self.session().private_read_keys(AteSessionKeyCategory::SudoKeys).next() { Some(a) => a.clone(), None => bail!(LoadErrorKind::IO("the current session does not have private read key.".to_string())) }; // First we load the chain which we need to get the master authority object let instance_key = ChainKey::from(wallet_instance.chain.clone()); let db_url: Result<_, LoadError> = self.db_url.clone().ok_or_else(|| LoadErrorKind::IO("the db_url is not set which is required to access instances".to_string()).into()); let chain = self.registry.open(&db_url?, &instance_key, true).await?; let dio = chain.dio(self.session().deref()).await; // Now we read the chain of trust and attempt to get the master authority object let master_authority = dio.load::<MasterAuthority>(&PrimaryKey::from(MASTER_AUTHORITY_ID)).await?; let master_authority = master_authority.inner_owner.unwrap(&sudo_private_read)?; // Build the session using the master authority let mut chain_session = AteSessionUser::default(); chain_session.add_user_read_key(&master_authority.read); chain_session.add_user_write_key(&master_authority.write); chain_session.add_user_uid(0); let mut chain_session = AteSessionGroup::new(AteSessionInner::User(chain_session), self.session().identity().to_string()); chain_session.add_group_gid(&AteRolePurpose::Observer, 0); chain_session.add_group_gid(&AteRolePurpose::Contributor, 0); chain_session.add_group_read_key(&AteRolePurpose::Observer, &master_authority.read); chain_session.add_group_write_key(&AteRolePurpose::Contributor, &master_authority.write); // Load the instance let chain_dio = chain.dio_full(&chain_session).await; chain_dio.load::<ServiceInstance>(&PrimaryKey::from(INSTANCE_ROOT_ID)).await } pub async fn instance_action( &mut self, name: &str, ) -> Result<(Result<DaoMut<ServiceInstance>, LoadError>, DaoMut<WalletInstance>), InstanceError> { // If the name supplied is not good enough then fail let name = name.to_lowercase(); if name.len() <= 0 { bail!(InstanceErrorKind::InvalidInstance); } let name = name.as_str(); // Find the instance that best matches the name supplied let mut instances = self.instances().await; let instances = instances .iter_mut_ext(true, true) .await? .filter(|i| i.name.to_lowercase().starts_with(name)) .collect::<Vec<_>>(); // If there are too many instances that match this name then fail if instances.len() > 1 { bail!(InstanceErrorKind::InvalidInstance); } // Otherwise get the instance let wallet_instance = instances .into_iter() .next() .ok_or_else(|| InstanceErrorKind::InvalidInstance)?; let service_instance = self.instance_load(wallet_instance.deref()).await; Ok((service_instance, wallet_instance)) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/api/carve.rs
wasmer-deploy-cli/src/api/carve.rs
use error_chain::bail; use num_traits::*; use std::collections::BTreeMap; #[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use crate::cmd::*; use crate::error::*; use crate::helper::*; use crate::model::*; use super::*; impl DeployApi { pub async fn carve_bag( &mut self, currency: NationalCurrency, needed_total_amount: Decimal, auto_recover_coins: bool, ) -> Result<BagOfCoins, WalletError> { // If anything has been left on the DIO then we need to fail // as this loop will invoke cancel during its recovery process if self.dio.has_uncommitted() { bail!(WalletErrorKind::CoreError(CoreErrorKind::InternalError(ate::utils::obscure_error_str("unable to transfer from the wallet when there are uncommitted transactions on the DIO")))); } // Lock the wallet let lock = self.wallet.try_lock_with_timeout(self.lock_timeout).await?; if lock == false { bail!(WalletErrorKind::WalletLocked); } let ret = self .__carve_bag(currency, needed_total_amount, auto_recover_coins) .await; // Commit unlock and return the result self.dio.commit().await?; self.wallet.unlock().await?; ret } pub(crate) async fn __carve_bag( &mut self, currency: NationalCurrency, needed_total_amount: Decimal, auto_recover_coins: bool, ) -> Result<BagOfCoins, WalletError> { // If anything has been left on the DIO then we need to fail // as this loop will invoke cancel during its recovery process if self.dio.has_uncommitted() { bail!(WalletErrorKind::CoreError(CoreErrorKind::InternalError(ate::utils::obscure_error_str("unable to cave a bag of coins when there are uncommitted transactions on the DIO")))); } // Loop a limited number of times for n in 1..=50 { trace!("carve: attempt={}", n); // First reconcile the wallet to recover any coins or deposits // (this reconcile is also needed to collect any coins that have been carved up) trace!("carve: collect coins"); self.__collect_coins().await?; // Now do a quick check to make sure we actually have enough coins of this currency let currency_summary = self.__wallet_currency_summary(currency).await?; if needed_total_amount > currency_summary.total { trace!( "carve: insufficient coins-needed={} available={}", needed_total_amount, currency_summary.total ); bail!(WalletErrorKind::InsufficientCoins); } // Grab a reference to all the chests that will be used to carve out this bag of coins let bags = self .wallet .as_mut() .bags .iter_mut() .await? .filter(|(k, _)| k.currency == currency) .collect::<Vec<_>>(); trace!("carve: found {} bags of coins", bags.len()); let mut bags = { let mut r = BTreeMap::default(); bags.into_iter().for_each(|(k, v)| { r.insert(k.value, v); }); r }; // Prepare a bag of coins let mut ret_bag = BagOfCoins::default(); let mut ret_bag_total = Decimal::zero(); // Build the bag of coins for these denomination brackets to make a certain total amount let needed_coins = carve_denominations(needed_total_amount, currency); trace!( "needed_coins: {}", serde_json::to_string_pretty(&needed_coins).unwrap() ); for (needed_denomination, needed_denomination_count) in needed_coins.iter().rev() { let needed_denomination = needed_denomination.clone(); let needed_denomination_count = needed_denomination_count.clone(); let needed_amount = needed_denomination * Decimal::from(needed_denomination_count); // Add all the coins we need to make up this amount // (until we run out of coins to add) let mut added = Decimal::zero(); for (denomination, bag) in bags.range_mut(Decimal::zero()..=needed_denomination).rev() { let total_bag_coins = bag.coins.len(); trace!( "processing chest (denomination={}, total_coins={}", denomination, total_bag_coins ); while added < needed_amount { if added + *denomination > needed_amount { break; } match self .__remove_coin_from_wallet(Denomination { value: denomination.clone(), currency, }) .await? { Some(coin) => { trace!("carve: adding coin of value {}", coin.value); added += coin.value; ret_bag_total += coin.value; ret_bag.coins.push(coin); } None => { break; } } } } // If we have enough then move onto the next denomination if added == needed_amount { continue; } // We don't have enough coins of this denomination so lets go and make some more after // all the chests are reset trace!("carve: we dont have enough coins - lets unzip some bags"); self.dio.cancel(); trace!("carve: time to carve up some of the bigger coins"); // Grab a carved coin from one of the higher denominations // Grab a reference to all the chests that will be used to carve out this bag of coins let mut bigger_bags = self .wallet .bags .iter_mut_with_dio(&self.dio) .await? .filter(|(k, _)| k.value > needed_denomination) .collect::<Vec<_>>(); bigger_bags.sort_by(|(k1, _), (k2, _)| k1.value.cmp(&k2.value)); for (bigger_denomination, _) in bigger_bags { if let Some(bigger_coin) = self.__remove_coin_from_wallet(bigger_denomination).await? { trace!("carve: splitting coin of value {}", bigger_coin.value); // Before we attempt to carve up the coin we add it back into the inbox // so that if something goes wrong the parts of the coin can be recovered // on the next reconcile. Otherwise on success the this will pick up // all the carved coins anyway self.wallet .inbox .push_with_dio(&self.dio, bigger_coin.owner.clone())?; self.dio.commit().await?; // Now we carve the coin and collect the results coin_carve_command( &self.registry, bigger_coin.owner.clone(), bigger_coin.coin, needed_denomination, bigger_coin.owner.token, self.auth.clone(), ) .await?; break; } } break; } // Make sure we have the right amount in the bag (if not we have to try again) if ret_bag_total != needed_total_amount { trace!( "carve: attempt failed - not enough change - found={} needed={}", ret_bag_total, needed_total_amount ); continue; } // We need to add all the coins back into the inbox processor so that if // they are lost in the future rotation or transfer operations that the // original wallet can claim them back if auto_recover_coins { let mut wallet = self.wallet.as_mut(); let ancestors = ret_bag.to_ownerships().await; for ancestor in ancestors { wallet.inbox.push(ancestor)?; } } // Now we commit the transaction which gets us ready for the rotates self.dio.commit().await?; // Return the bag of coins return Ok(ret_bag); } // We gave it a good go but for some reason we just can't // seem to build a bag of coins to represent this amount debug!("insufficient coins: loop count exceeded"); bail!(WalletErrorKind::InsufficientCoins); } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/api/withdraw.rs
wasmer-deploy-cli/src/api/withdraw.rs
use error_chain::*; use std::ops::Deref; #[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use crate::cmd::*; use crate::error::*; use crate::model::*; use crate::request::*; use super::*; impl DeployApi { pub async fn withdraw( &mut self, currency: NationalCurrency, amount: Decimal, wallet_name: String, ) -> Result<WithdrawResponse, WalletError> { // If anything has been left on the DIO then we need to fail // as this loop will invoke cancel during its recovery process if self.dio.has_uncommitted() { bail!(WalletErrorKind::CoreError(CoreErrorKind::InternalError(ate::utils::obscure_error_str("unable to withdraw from the wallet when there are uncommitted transactions on the DIO")))); } // Lock the wallet let lock = self.wallet.try_lock_with_timeout(self.lock_timeout).await?; if lock == false { bail!(WalletErrorKind::WalletLocked); } let ret = self.__withdraw(currency, amount, wallet_name).await; // Commit, unlock and return the result self.dio.commit().await?; self.wallet.unlock().await?; ret } pub async fn __withdraw( &mut self, currency: NationalCurrency, amount: Decimal, wallet_name: String, ) -> Result<WithdrawResponse, WalletError> { // Make the session let session = self.dio.session().clone_session(); // First carve out the coins we want let carved = self.__carve_bag(currency, amount, true).await?; // Now withdraw the amount specified let ret = withdraw_command( &self.registry, carved.coins, session.deref(), self.auth.clone(), wallet_name, ) .await?; // Now add the history if let Err(err) = self .record_activity(HistoricActivity::FundsWithdrawn( activities::FundsWithdrawn { when: chrono::offset::Utc::now(), by: self.user_identity(), receipt_number: ret.receipt_number.clone(), amount_less_fees: ret.amount_less_fees, fees: ret.fees, currency, }, )) .await { error!("Error writing activity: {}", err); } Ok(ret) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/api/collect.rs
wasmer-deploy-cli/src/api/collect.rs
use ate::prelude::*; use fxhash::FxHashSet; use std::ops::Deref; #[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use crate::cmd::*; use crate::error::*; use crate::model::*; use crate::request::*; use super::*; impl DeployApi { pub(crate) async fn __coin_collect_internal( &mut self, coin_ancestors: Vec<Ownership>, ) -> Result<CoinCollectResponse, CoinError> { // Make the request to carve the coins (if we have a local tok service then use it) let query = coin_collect_command(&self.registry, coin_ancestors, self.auth.clone()).await?; // Now add the history for confirm in query.confirmations.iter() { if let Err(err) = self .record_activity(HistoricActivity::DepositCompleted( activities::DepositCompleted { when: confirm.when.clone(), by: self.user_identity(), invoice_number: confirm.invoice_number.clone(), amount: confirm.amount.clone(), currency: confirm.currency.clone(), invoice_url: confirm.invoice_url.clone(), }, )) .await { error!("Error writing activity: {}", err); } } return Ok(query); } pub(super) async fn __collect_coins(&mut self) -> Result<(), WalletError> { // Determine what currencies are currently stored within the wallet let mut currencies = self .wallet .inbox .iter() .await? .filter_map(|a| { if let CommodityCategory::NationalCurrency(b) = a.kind.category() { Some(b) } else { None } }) .collect::<Vec<_>>(); currencies.sort(); currencies.dedup(); for currency in currencies { let mut ancestors = self .wallet .inbox .iter_ext(true, true) .await? .filter(|a| { if let CommodityCategory::NationalCurrency(b) = a.kind.category() { currency == b } else { false } }) .collect::<Vec<Dao<Ownership>>>(); // We process in batches of 50 so that we dont have timeouts // while processing wallets that have huge numbers of deposits while ancestors.len() > 0 { // Build a list of all the coin ancestors let ancestors = { let mut a = Vec::new(); while let Some(b) = ancestors.pop() { a.push(b); if a.len() > 50 { break; } } a }; // Query the currency let query = { let query_ancestors = ancestors .iter() .map(|a| a.deref().clone()) .collect::<Vec<_>>(); self.__coin_collect_internal(query_ancestors).await? }; // Build a list of all the coin ancestors that would be destroyed by this operation let mut pending_deposits = FxHashSet::default(); query.pending_deposits.iter().for_each(|o| { pending_deposits.insert(o.owner.clone()); }); // If the query returned any bags of coins we need to add them to // the wallet in the right chests for coin in query.cleared_coins { self.__add_coin_to_wallet(coin).await?; } // Delete any ancestors that completed (not in a pending state) // (they will be added to the chests instead) let delete_me = ancestors .iter() .filter(|a| pending_deposits.contains(a.deref()) == false) .map(|a| a.key().clone()) .collect::<Vec<_>>(); for d in delete_me { self.dio.delete(&d).await?; } // Commit the transaction self.dio.commit().await?; } } Ok(()) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/api/transfer.rs
wasmer-deploy-cli/src/api/transfer.rs
use error_chain::*; use std::ops::Deref; use std::sync::Arc; #[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use crate::cmd::*; use crate::error::*; use crate::model::*; use crate::opt::*; use crate::request::*; use ate::prelude::*; use super::*; impl DeployApi { pub async fn deposit_coins( &mut self, coins: BagOfCoins, notify: Option<CoinRotateNotification>, ) -> std::result::Result<CoinRotateResponse, WalletError> { // Add the new ownership coins to the destination wallet let new_token = EncryptKey::generate(KeySize::Bit192); let new_owners = coins.clone().to_ownerships().await; for mut new_owner in new_owners.into_iter() { new_owner.token = new_token.clone(); self.wallet.inbox.push_with_dio(&self.dio, new_owner)?; } self.dio.commit().await?; // Now rotate ownerships let session = self.dio.session().clone_session(); let ret = coin_rotate_command( &self.registry, coins.coins, new_token, session.deref(), self.auth.clone(), notify, ) .await?; // Lastly we need to reconcile so that the coins get put into chests self.reconcile().await?; Ok(ret) } pub async fn transfer<A, B>( &mut self, amount: Decimal, currency: NationalCurrency, destination: &dyn OptsPurpose<A>, source: &dyn OptsPurpose<B>, should_notify: bool, ) -> std::result::Result<CoinRotateResponse, WalletError> where A: Clone, B: Clone, { // If anything has been left on the DIO then we need to fail // as this loop will invoke cancel during its recovery process if self.dio.has_uncommitted() { bail!(WalletErrorKind::CoreError(CoreErrorKind::InternalError(ate::utils::obscure_error_str("unable to transfer from the wallet when there are uncommitted transactions on the DIO")))); } // Lock the wallet let lock = self.wallet.try_lock_with_timeout(self.lock_timeout).await?; if lock == false { bail!(WalletErrorKind::WalletLocked); } let ret = self .__transfer::<A, B>(amount, currency, destination, source, should_notify) .await; // Commit unlock and return the result self.dio.commit().await?; self.wallet.unlock().await?; ret } pub(super) async fn __transfer<A, B>( &mut self, amount: Decimal, currency: NationalCurrency, destination: &dyn OptsPurpose<A>, source: &dyn OptsPurpose<B>, should_notify: bool, ) -> std::result::Result<CoinRotateResponse, WalletError> where A: Clone, B: Clone, { // Get the session and identity let session = self.dio.session().clone_session(); let identity = get_identity(destination, session.deref()).await?; // Open the chain let registry = Arc::clone(&self.registry); let chain_key = chain_key_4hex(&identity, Some("redo")); debug!("chain_url={}", self.auth); debug!("chain_key={}", chain_key); let chain = registry.open(&self.auth, &chain_key, true).await?; // Load the API for the destination // Open the DIO and load the wallet debug!("getting destination wallet"); let mut api_destination = { let session = session.clone_inner(); let session: AteSessionType = if let Purpose::<A>::Domain { domain_name: group_name, wallet_name: _, action: _, } = destination.purpose() { gather_command( &self.registry, group_name.clone(), session, self.auth.clone(), ) .await? .into() } else { session.into() }; let mut dio = chain.dio_trans(&session, TransactionScope::Full).await; let wallet = get_wallet(destination, &mut dio, &identity).await?; build_api_accessor(&dio, wallet, self.auth.clone(), self.db_url.clone(), &registry).await }; // Carve out the coins from the wallet debug!("carving bag"); let carved = self.__carve_bag(currency, amount, true).await?; // Lets build the notify let email = session.user().identity().to_string(); let notify = if should_notify { let notify = CoinRotateNotification { operator: email.clone(), receipt_number: AteHash::generate().to_hex_string().to_uppercase(), from: source.fullname(email.as_str()), to: destination.fullname(email.as_str()), }; Some(notify) } else { None }; // Deposit the coins debug!("depositing coins"); let ret = api_destination.deposit_coins(carved, notify).await?; // Now add the history into both wallets { let activity = activities::FundsTransferred { when: chrono::offset::Utc::now(), by: self.user_identity(), amount, currency, from: source.fullname(email.as_str()), to: destination.fullname(email.as_str()), }; if let Err(err) = self .record_activity(HistoricActivity::TransferOut(activity.clone())) .await { error!("Error writing activity: {}", err); } match api_destination .record_activity(HistoricActivity::TransferIn(activity.clone())) .await { Ok(_) => { if let Err(err) = api_destination.commit().await { error!("Error writing activity: {}", err); } } Err(err) => error!("Error writing activity: {}", err), } } // Success Ok(ret) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/api/instance_create.rs
wasmer-deploy-cli/src/api/instance_create.rs
use wasmer_auth::cmd::query_command; #[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use error_chain::bail; use ate_files::accessor::FileAccessor; use ate::crypto::AteHash; use ate::chain::ChainKey; use std::sync::Arc; use ate::prelude::*; use std::net::IpAddr; use std::net::Ipv4Addr; use std::net::Ipv6Addr; use crate::error::*; use crate::model::*; use super::*; impl DeployApi { pub async fn instance_create( &mut self, name: String, group: Option<String>, db_url: url::Url, instance_authority: String, force: bool, ) -> Result<WalletInstance, InstanceError> { // Get the sudo rights from the session (as we will use these for the wallet) let (sudo_read, sudo_private_read) = { let session = self.dio.session(); let sudo_read = match session.read_keys(AteSessionKeyCategory::SudoKeys).next() { Some(a) => a, None => bail!(InstanceErrorKind::Unauthorized) }; let sudo_private_read = match session.private_read_keys(AteSessionKeyCategory::SudoKeys).next() { Some(a) => a, None => bail!(InstanceErrorKind::Unauthorized) }; if session .write_keys(AteSessionKeyCategory::SudoKeys) .next() .is_none() { bail!(InstanceErrorKind::Unauthorized); }; (sudo_read.clone(), sudo_private_read.clone()) }; let all_write_keys = self.session().write_keys(AteSessionKeyCategory::AllKeys).map(|a| a.clone()).collect::<Vec<_>>(); // If it already exists then fail let instance_key_entropy = format!("instance://{}/{}", self.session_identity(), name); let instance_key = PrimaryKey::from(instance_key_entropy); if force == false { if self.dio.exists(&instance_key).await { bail!(InstanceErrorKind::AlreadyExists); } // Check if the instance already exists let instances = self.instances().await; if instances.iter_ext(true, true).await?.any(|i| i.name.eq_ignore_ascii_case(name.as_str())) { bail!(InstanceErrorKind::AlreadyExists); } } // Generate encryption keys and modify the root of the tree so that it // uses them let key_size = sudo_read.size(); let read_key = EncryptKey::generate(key_size); let write_key = PrivateSignKey::generate(key_size); let mut chain_session = AteSessionUser::default(); chain_session.add_user_read_key(&read_key); chain_session.add_user_write_key(&write_key); for write_key in all_write_keys { chain_session.add_user_write_key(&write_key); } chain_session.add_user_uid(0); let mut chain_session = AteSessionGroup::new(AteSessionInner::User(chain_session), self.session_identity()); chain_session.add_group_gid(&AteRolePurpose::Observer, 0); chain_session.add_group_gid(&AteRolePurpose::Contributor, 0); chain_session.add_group_read_key(&AteRolePurpose::Observer, &read_key); chain_session.add_group_write_key(&AteRolePurpose::Contributor, &write_key); // Create the edge chain-of-trust let instance_id = fastrand::u128(..); let key_name = format!("{}/{}_edge", self.session_identity(), hex::encode(&instance_id.to_be_bytes())); let key = ChainKey::from(key_name.clone()); let chain = self.registry.open(&db_url, &key, true).await?; let chain_api = Arc::new( FileAccessor::new( chain.as_arc(), group, AteSessionType::Group(chain_session), TransactionScope::Full, TransactionScope::Full, false, false, ) .await, ); // Initialize and save the chain_api debug!("intiializing chain-of-trust: {}", key); let root = chain_api.init(&chain_api.session_context()).await?; for dir in vec![ "bin", "dev", "etc", "tmp" ] { if chain_api.search(&chain_api.session_context(), format!("/{}", dir).as_str()).await?.is_none() { debug!("creating directory: {}", dir); chain_api.mkdir(&chain_api.session_context(), root.key().as_u64(), dir, root.dentry.mode).await?; } } // Perform an authenticator query to get the edge key let query = query_command(&self.registry, instance_authority.clone(), self.auth.clone()).await?; let master_public = query.advert.broker_encrypt; // Output what we are encrypting with debug!("using instance authority ({}) public encryption key ({})", instance_authority, master_public.hash()); // Add the master authority record so that the master servers can read this let admin_token = AteHash::generate().to_hex_string(); let dio = chain_api.dio_mut_meta().await; let mut master_authority = dio.store_with_key( MasterAuthority { inner_broker: PublicEncryptedSecureData::new(&master_public, MasterAuthorityInner { read: read_key, write: write_key.clone(), })?, inner_owner: PublicEncryptedSecureData::new(sudo_private_read.as_public_key(), MasterAuthorityInner { read: read_key, write: write_key.clone(), })? }, PrimaryKey::from(MASTER_AUTHORITY_ID), )?; master_authority.auth_mut().read = ReadOption::Everyone(None); master_authority.attach_orphaned(root.key())?; // Create the network access code and select a random subnet let network_token = AteHash::generate().to_hex_string(); let subnets = vec![ IpCidr { ip: IpAddr::V4(Ipv4Addr::new(10, fastrand::u8(..), fastrand::u8(..), 0)), prefix: 24 }, IpCidr { ip: IpAddr::V6(Ipv6Addr::new(64512, fastrand::u16(..), fastrand::u16(..), fastrand::u16(..), 0, 0, 0, 0)), prefix: 64 }]; // Add the object directly to the chain let mut instance_dao = dio.store_with_key( ServiceInstance { id: instance_id, chain: key.name.clone(), subnet: InstanceSubnet { network_token, cidrs: subnets, peerings: Vec::new(), }, admin_token, exports: DaoVec::new(), mesh_nodes: DaoVec::new(), }, PrimaryKey::from(INSTANCE_ROOT_ID), )?; instance_dao.attach_orphaned(root.key())?; chain_api.commit().await?; dio.commit().await?; // Create the instance and add it to the identities collection debug!("adding service instance: {}", name); let instance = WalletInstance { name: name.clone(), id: instance_id, chain: ChainKey::from(key.name.clone()), }; let mut wallet_instance_dao = self.dio.store_with_key( instance.clone(), instance_key, )?; // Set its permissions and attach it to the parent wallet_instance_dao.auth_mut().read = ReadOption::from_key(&sudo_read); wallet_instance_dao.auth_mut().write = WriteOption::Inherit; wallet_instance_dao.attach_orphaned_ext(&self.wallet.parent_id().unwrap(), INSTANCE_COLLECTION_ID)?; // Now add the history if let Err(err) = self .record_activity(HistoricActivity::InstanceCreated( activities::InstanceCreated { when: chrono::offset::Utc::now(), by: self.user_identity(), alias: Some(name), }, )) .await { error!("Error writing activity: {}", err); } self.dio.commit().await?; Ok(instance) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/api/accessor.rs
wasmer-deploy-cli/src/api/accessor.rs
use std::sync::Arc; use std::time::Duration; use crate::model::*; use ate::prelude::*; #[derive(Clone)] pub struct DeployApi { pub dio: Arc<DioMut>, pub wallet: DaoMut<Wallet>, pub auth: url::Url, pub auth_cmd: Option<ChainGuard>, pub db_url: Option<url::Url>, pub registry: Arc<Registry>, pub lock_timeout: Duration, } pub async fn build_api_accessor( dio: &Arc<DioMut>, wallet: DaoMut<Wallet>, auth: url::Url, db_url: Option<url::Url>, registry: &Arc<Registry>, ) -> DeployApi { DeployApi { dio: Arc::clone(dio), wallet, auth, auth_cmd: None, db_url, registry: Arc::clone(&registry), lock_timeout: Duration::from_millis(500), } } impl DeployApi { pub async fn commit(&mut self) -> Result<(), CommitError> { self.dio.commit().await?; Ok(()) } pub fn remote<'a>(&'a self) -> Option<&'a url::Url> { self.dio.remote() } pub fn session<'a>(&'a self) -> DioSessionGuard<'a> { self.dio.session() } pub fn session_identity(&self) -> String { self.dio.session().identity().to_string() } pub fn user_identity(&self) -> String { self.dio.session().user().identity().to_string() } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/api/contract_get.rs
wasmer-deploy-cli/src/api/contract_get.rs
use error_chain::*; #[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use crate::error::*; use super::*; impl DeployApi { pub async fn contract_get( &mut self, reference_number: &str, ) -> Result<ContractSummary, ContractError> { let contracts = self.contract_summary().await?; let reference_number = reference_number.trim(); let contract = contracts .iter() .filter(|a| { a.reference_number.eq_ignore_ascii_case(reference_number) || a.service.code.eq_ignore_ascii_case(reference_number) }) .next(); let contract = match contract { Some(a) => a.clone(), None => { bail!(ContractErrorKind::InvalidReference( reference_number.to_string() )); } }; Ok(contract) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/api/contract_action.rs
wasmer-deploy-cli/src/api/contract_action.rs
use std::ops::Deref; #[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use crate::cmd::*; use crate::error::*; use crate::request::*; use ate::prelude::*; use super::*; impl DeployApi { pub async fn contract_elevate( &mut self, service_code: &str, requester_identity: &str, consumer_identity: &str, ) -> Result<EncryptKey, ContractError> { // Execute the action let session = self.dio.session().clone_session(); let ret = contract_elevate_command( &self.registry, session.deref(), self.auth.clone(), service_code.to_string(), requester_identity.to_string(), consumer_identity.to_string(), ) .await?; Ok(ret) } pub async fn contract_action( &mut self, service_code: &str, requester_identity: &str, consumer_identity: &str, action: ContractAction, action_key: Option<EncryptKey>, ) -> Result<ContractActionResponse, ContractError> { // Execute the action let session = self.dio.session().clone_session(); let ret = contract_action_command( &self.registry, session.deref(), self.auth.clone(), service_code.to_string(), requester_identity.to_string(), consumer_identity.to_string(), action_key, action, ) .await?; Ok(ret) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/api/contract_summary.rs
wasmer-deploy-cli/src/api/contract_summary.rs
use chrono::DateTime; use chrono::Utc; #[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use crate::error::*; use crate::model::*; use ate::prelude::*; use super::*; #[derive(Debug, Clone)] pub struct ContractSummary { /// Primary key of this contract pub key: PrimaryKey, /// Reference number assocaited with this contract pub reference_number: String, /// The advertised service being consumed by the provider pub service: AdvertisedService, /// Status of the contract pub status: ContractStatus, /// Limited duration contracts will expire after a /// certain period of time without incurring further /// charges pub expires: Option<DateTime<Utc>>, /// Metrics currently tracked for this contract pub metrics: Vec<ContractMetrics>, } impl DeployApi { pub async fn contract_summary(&mut self) -> Result<Vec<ContractSummary>, ContractError> { // Query all the contracts for this wallet let mut ret = Vec::new(); if let Some(parent_id) = self.wallet.parent_id() { let contracts = self .dio .children_ext::<Contract>(parent_id, CONTRACT_COLLECTION_ID, true, true) .await?; for contract in contracts { ret.push(self.get_contract_summary(contract.as_immutable()).await?) } } Ok(ret) } pub(super) async fn get_contract_summary(&self, contract: &Dao<Contract>) -> Result<ContractSummary, ContractError> { let metrics = contract .metrics .iter() .await? .map(|a| a.take()) .collect::<Vec<_>>(); Ok(ContractSummary { key: contract.key().clone(), reference_number: contract.reference_number.clone(), service: contract.service.clone(), status: contract.status.clone(), expires: contract.expires, metrics, }) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/api/instance_summary.rs
wasmer-deploy-cli/src/api/instance_summary.rs
use error_chain::bail; #[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use std::sync::Arc; use crate::error::*; use crate::model::*; use ate::prelude::*; use super::*; #[derive(Debug, Clone)] pub struct InstanceSummary { /// Primary key of this instance pub key: PrimaryKey, /// Name of the instance pub name: String, /// ID of this instance within Wasmer pub id_str: String, /// Chain that the instance is attached to pub chain: ChainKey, } impl DeployApi { pub async fn instance_summary(&mut self) -> Result<Vec<InstanceSummary>, InstanceError> { // Query all the instances for this wallet let mut ret = Vec::new(); for instance in self.instances().await.iter_ext(true, true).await? { let id_str = instance.id_str(); let chain = ChainKey::from(instance.chain.clone()); ret.push(InstanceSummary { key: instance.key().clone(), name: instance.name.clone(), chain, id_str, }) } Ok(ret) } pub async fn instances(&self) -> DaoVec<WalletInstance> { DaoVec::<WalletInstance>::new_orphaned_mut( &self.dio, self.wallet.parent_id().unwrap(), INSTANCE_COLLECTION_ID ) } pub async fn instance_find_exact(&self, name: &str) -> Result<DaoMut<WalletInstance>, InstanceError> { let instance = self.instances() .await .iter_mut_ext(true, true) .await? .filter(|i| i.name.eq_ignore_ascii_case(name)) .next(); let instance = match instance { Some(a) => a, None => { bail!(InstanceErrorKind::InvalidInstance); } }; Ok(instance) } pub async fn instance_find(&self, name: &str) -> Result<DaoMut<WalletInstance>, InstanceError> { // If the name supplied is not good enough then fail let name = name.to_lowercase(); if name.len() <= 0 { bail!(InstanceErrorKind::InvalidInstance); } let name = name.as_str(); // Find the instance that best matches the name supplied let mut instances = self.instances().await; let instances = instances .iter_mut_ext(true, true) .await? .filter(|i| i.name.to_lowercase().starts_with(name)) .collect::<Vec<_>>(); // If there are too many instances that match this name then fail if instances.len() > 1 { bail!(InstanceErrorKind::InvalidInstance); } let instance = instances.into_iter().next(); let instance = match instance { Some(a) => a, None => { bail!(InstanceErrorKind::InvalidInstance); } }; Ok(instance) } pub async fn instance_chain(&self, name: &str) -> Result<Arc<Chain>, InstanceError> { let instance = self.instance_find(name).await?; let instance_key = ChainKey::from(instance.chain.clone()); let db_url: Result<_, InstanceError> = self.db_url.clone().ok_or_else(|| InstanceErrorKind::Unsupported.into()); let chain = self.registry.open(&db_url?, &instance_key, true).await?; Ok(chain.as_arc()) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/api/contract_create.rs
wasmer-deploy-cli/src/api/contract_create.rs
use error_chain::*; use std::ops::Deref; #[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use crate::cmd::*; use crate::error::*; use crate::model::*; use crate::request::*; use ate::prelude::*; use super::*; impl DeployApi { pub async fn contract_create( &mut self, service: AdvertisedService, force: bool, ) -> Result<ContractCreateResponse, ContractError> { // Make the session let session = self.dio.session().clone_session(); // Grab the latest encryption key for the provider (this will be used to encrypt // the broker key) let advert = { match query_command(&self.registry, service.owner_identity.clone(), self.auth.clone()).await { Ok(a) => a, Err(err) => { let err_code = ate::utils::obscure_error_str(format!("Failed to create the contract as the query to the authentication server failed - {}.", err.to_string()).as_str()); bail!(ContractErrorKind::CoreError(CoreErrorKind::InternalError(err_code))); } }.advert }; let broker_key = PublicEncryptedSecureData::new(&advert.broker_encrypt, self.wallet.broker_key.clone())?; // Create the contract let gst_country = self.wallet.gst_country; let ret = contract_create_command( &self.registry, session.deref(), self.auth.clone(), service.code.clone(), self.session_identity(), gst_country, self.wallet.key().clone(), broker_key, self.wallet.broker_unlock_key.clone(), force ) .await?; // Now add the history if let Err(err) = self .record_activity(HistoricActivity::ContractCreated( activities::ContractCreated { when: chrono::offset::Utc::now(), by: self.user_identity(), service: service.clone(), contract_reference: ret.contract_reference.clone(), }, )) .await { error!("Error writing activity: {}", err); } Ok(ret) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/api/history.rs
wasmer-deploy-cli/src/api/history.rs
use chrono::*; #[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use crate::error::*; use crate::model::*; use ate::prelude::*; use super::*; impl DeployApi { pub async fn get_or_create_this_month(&mut self) -> Result<DaoMut<HistoricMonth>, WalletError> { let now = chrono::offset::Utc::now().date(); let mut wallet = self.wallet.as_mut(); for month in wallet.history.iter_mut().await? { if now.month() == month.month && now.year() == month.year { return Ok(month); } } let ret = wallet.history.push(HistoricMonth { month: now.month(), year: now.year(), days: DaoVec::default(), })?; Ok(ret) } pub async fn get_or_create_today(&mut self) -> Result<DaoMut<HistoricDay>, WalletError> { let now = chrono::offset::Utc::now().date(); let this_month = self.get_or_create_this_month().await?; for day in this_month.days.iter_mut_with_dio(&self.dio).await? { if day.day == now.day() { return Ok(day); } } let ret = this_month.days.push_with_dio( &self.dio, HistoricDay { day: now.day(), activities: Vec::new(), }, )?; Ok(ret) } pub async fn record_activity( &mut self, activity: HistoricActivity, ) -> Result<DaoMut<HistoricDay>, WalletError> { let mut today = self.get_or_create_today().await?; today.as_mut().activities.push(activity); Ok(today) } pub async fn read_activity( &mut self, filter_year: Option<i32>, filter_month: Option<u32>, filter_day: Option<u32>, ) -> Result<Vec<HistoricActivity>, WalletError> { let mut ret = Vec::new(); for month in self.wallet.history.iter().await? { if let Some(a) = filter_year { if a != month.year { continue; } } if let Some(a) = filter_month { if a != month.month { continue; } } for day in month.days.iter().await? { if let Some(a) = filter_day { if a != day.day { continue; } } let mut day = day.take(); ret.append(&mut day.activities); } } ret.sort_by(|a, b| a.when().cmp(b.when())); Ok(ret) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/api/reconcile.rs
wasmer-deploy-cli/src/api/reconcile.rs
use error_chain::*; #[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use crate::error::*; use super::*; impl DeployApi { pub async fn reconcile(&mut self) -> Result<(), WalletError> { // If anything has been left on the DIO then we need to fail // as this loop will invoke cancel during its recovery process if self.dio.has_uncommitted() { bail!(WalletErrorKind::CoreError(CoreErrorKind::InternalError(ate::utils::obscure_error_str("unable to reconcile the wallet when there are uncommitted transactions on the DIO")))); } // Lock the wallet let lock = self.wallet.try_lock_with_timeout(self.lock_timeout).await?; if lock == false { bail!(WalletErrorKind::WalletLocked); } trace!("wallet has been locked"); let ret = self.__reconcile().await; // Unlock and return the result self.wallet.unlock().await?; self.dio.commit().await?; trace!("wallet has been unlocked and DIO committed"); ret } pub(super) async fn __reconcile(&mut self) -> Result<(), WalletError> { trace!("collecting coins..."); self.__collect_coins().await?; trace!("combining coins..."); self.__combine_coins().await?; Ok(()) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/api/mod.rs
wasmer-deploy-cli/src/api/mod.rs
mod accessor; mod bag; mod carve; mod collect; mod combine; mod contract_action; mod contract_cancel; mod contract_create; mod contract_get; mod contract_summary; mod delete_wallet; mod deposit; mod history; mod reconcile; mod transfer; mod wallet_summary; mod withdraw; mod instance_create; mod instance_summary; mod instance_action; mod instance_client; pub use accessor::*; pub use bag::*; pub use carve::*; pub use collect::*; pub use combine::*; pub use contract_action::*; pub use contract_cancel::*; pub use contract_create::*; pub use contract_get::*; pub use contract_summary::*; pub use delete_wallet::*; pub use deposit::*; pub use history::*; pub use reconcile::*; pub use transfer::*; pub use wallet_summary::*; pub use withdraw::*; pub use instance_create::*; pub use instance_summary::*; pub use instance_action::*; pub use instance_client::*;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/api/combine.rs
wasmer-deploy-cli/src/api/combine.rs
use ate::prelude::*; #[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use crate::cmd::*; use crate::error::*; use crate::model::*; use super::*; impl DeployApi { pub(super) async fn __combine_coins(&mut self) -> Result<(), CoinError> { // Loop through all the chests let mut wallet_mut = self.wallet.as_mut(); let bags = wallet_mut.bags.iter_mut().await?.collect::<Vec<_>>(); for (_, mut bag) in bags { // If the active bag is not full enough yet then move onto the next one let loose_coins = bag.coins.len(); let coins_per_zipped_bag_plus_plus = ((COINS_PER_STACK_TO_BE_COMBINED * 12usize) / 10usize) + 1usize; if loose_coins <= coins_per_zipped_bag_plus_plus { continue; } trace!("enough loose coins ({}) to combine", loose_coins); // Start a new bag and take out the margin we use to stop combine thrashing let mut bag_mut = bag.as_mut(); let mut bag_to_combine = BagOfCoins::default(); while let Some(coin) = bag_mut.coins.pop() { bag_to_combine.coins.push(coin); if bag_to_combine.coins.len() >= COINS_PER_STACK_TO_BE_COMBINED { break; } } drop(bag_mut); drop(bag); // Create a new ownership for the coins let mut new_ownership = match bag_to_combine.to_ownerships().await.into_iter().next() { Some(a) => a, None => { continue; } }; new_ownership.token = EncryptKey::generate(new_ownership.token.size()); new_ownership.what = PrimaryKey::generate(); trace!( "built a bag to combine with {} coins", bag_to_combine.coins.len() ); // Create a rollback and commit the change (so that if something // goes wrong we can recover the coins) - we also add the new ownership // here so the coin can be collected let temp_ownership = { let mut to = Vec::new(); let ownership = bag_to_combine.to_ownerships().await; trace!( "adding ({}) ownership(s) as fallback coins", ownership.len() ); for ownership in ownership { to.push(wallet_mut.inbox.push_with_dio(&self.dio, ownership)?); } to.push( wallet_mut .inbox .push_with_dio(&self.dio, new_ownership.clone())?, ); to }; wallet_mut.commit()?; self.dio.commit().await?; trace!("combining bag of coins..."); let res = coin_combine_command( &self.registry, bag_to_combine.coins, new_ownership, self.auth.clone(), ) .await?; // We can now add the coin and remove the rollback objects let denomination = Denomination { currency: res.super_coin.currency.clone(), value: res.super_coin.value.clone(), }; wallet_mut .bags .get_or_default(denomination) .await? .as_mut() .coins .push(res.super_coin); wallet_mut.commit()?; for temp in temp_ownership { temp.delete()?; } self.dio.commit().await?; } Ok(()) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/api/instance_client.rs
wasmer-deploy-cli/src/api/instance_client.rs
use wasmer_bus_tty::prelude::*; use ate::comms::{StreamTx, StreamRx, StreamSecurity}; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; use crate::model::{InstanceCommand, InstanceHello, InstanceReply}; pub struct InstanceClient { rx: StreamRx, tx: StreamTx, } impl InstanceClient { pub const PATH_INST: &'static str = "/inst"; pub async fn new(connect_url: url::Url) -> Result<Self, Box<dyn std::error::Error>> { Self::new_ext(connect_url, Self::PATH_INST, StreamSecurity::AnyEncryption).await } pub async fn new_ext(connect_url: url::Url, path: &str, security: StreamSecurity) -> Result<Self, Box<dyn std::error::Error>> { let port = ate_comms::StreamClient::connect( connect_url, path, security, Some("8.8.8.8".to_string()), false) .await?; let (rx, tx) = port.split(); Ok( Self { rx, tx, } ) } pub fn split(self) -> (StreamTx, StreamRx) { ( self.tx, self.rx, ) } pub async fn send_hello(&mut self, hello: InstanceHello) -> Result<(), Box<dyn std::error::Error>> { let data = serde_json::to_vec(&hello)?; self.send_data(data).await?; Ok(()) } pub async fn send_cmd(&mut self, cmd: InstanceCommand) -> Result<(), Box<dyn std::error::Error>> { let data = serde_json::to_vec(&cmd)?; self.send_data(data).await?; Ok(()) } pub async fn send_data(&mut self, data: Vec<u8>) -> Result<(), Box<dyn std::error::Error>> { self.tx.write(&data[..]).await?; Ok(()) } pub async fn run_shell(&mut self) -> Result<(), Box<dyn std::error::Error>> { let mut stdin = Tty::stdin().await?; let mut stdout = Tty::stdout().await?; loop { tokio::select! { data = self.rx.read() => { if let Ok(data) = data { if data.len() <= 0 { break; } stdout.write(data).await?; stdout.flush().await?; } else { break; } } data = stdin.read() => { if let Some(data) = data { self.tx.write(&data[..]).await?; } else { break; } } } } Ok(()) } pub async fn run_read(&mut self) -> Result<(), Box<dyn std::error::Error>> { let mut stdout = Tty::stdout().await?; let mut stderr = Tty::stderr().await?; loop { match self.rx.read().await { Ok(data) => { if data.len() <= 0 { break; } let reply: InstanceReply = bincode::deserialize(&data[..])?; match reply { InstanceReply::FeedBytes { handle: _, format: _, data, } => { stdout.write(data).await?; stdout.write("\r\n".as_bytes().to_vec()).await?; stdout.flush().await?; break; }, InstanceReply::Stdout { data } => { stdout.write(data).await?; stdout.write("\r\n".as_bytes().to_vec()).await?; stdout.flush().await?; }, InstanceReply::Stderr { data } => { stderr.write(data).await?; stderr.write("\r\n".as_bytes().to_vec()).await?; stderr.flush().await?; }, InstanceReply::Error { handle: _, error, } => { let error = format!("error: {}\r\n", error); let mut stderr = Tty::stderr().await?; stderr.write(error.into_bytes()).await?; stderr.flush().await?; break; } InstanceReply::Terminate { handle: _, } => { break; } InstanceReply::Exit => { break; } } } _ => { break; } } } Ok(()) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/api/bag.rs
wasmer-deploy-cli/src/api/bag.rs
#![allow(unused_imports)] use ate::prelude::*; use error_chain::bail; use fxhash::FxHashSet; use std::ops::Deref; use std::sync::Arc; use tracing::{debug, error, info, trace, warn}; use crate::api::DeployApi; use crate::error::*; use crate::model::*; impl DeployApi { pub(super) async fn __get_bag( &mut self, denomination: Denomination, ) -> Result<Option<DaoMut<BagOfCoins>>, WalletError> { let ret = self.wallet.as_mut().bags.get_mut(&denomination).await?; Ok(ret) } pub(super) async fn __get_or_create_bag( &mut self, denomination: Denomination, ) -> Result<DaoMut<BagOfCoins>, WalletError> { let ret = self .wallet .as_mut() .bags .get_or_default(denomination) .await?; Ok(ret) } pub async fn add_coin_to_wallet(&mut self, coin: CarvedCoin) -> Result<(), WalletError> { // Lock the wallet let lock = self.wallet.try_lock_with_timeout(self.lock_timeout).await?; if lock == false { bail!(WalletErrorKind::WalletLocked); } // Add the coin to the chest self.__add_coin_to_wallet(coin).await?; // Unlock and return the result self.wallet.unlock().await?; Ok(()) } pub async fn add_coins_to_wallet( &mut self, coins: impl IntoIterator<Item = CarvedCoin>, ) -> Result<(), WalletError> { // Lock the wallet let lock = self.wallet.try_lock_with_timeout(self.lock_timeout).await?; if lock == false { bail!(WalletErrorKind::WalletLocked); } // Add the coins to the chest for coin in coins { self.__add_coin_to_wallet(coin).await?; } // Unlock and return the result self.wallet.unlock().await?; Ok(()) } pub(super) async fn __add_coin_to_wallet( &mut self, coin: CarvedCoin, ) -> Result<(), WalletError> { // Get or create the chest let mut bag = self .__get_or_create_bag(Denomination { value: coin.value, currency: coin.currency, }) .await?; let mut active_bag = bag.as_mut(); // If it exists then ignore it if active_bag.coins.iter().any(|c| c.coin == coin.coin) { trace!( "ignoing coin (value={}{}) - already in wallet", coin.value, coin.currency ); return Ok(()); } // Add the coin to the active wallet trace!( "adding coin to wallet (value={}{})", coin.value, coin.currency ); active_bag.coins.push(coin); Ok(()) } pub async fn remove_coin_from_wallet( &mut self, denomination: Denomination, ) -> Result<(), WalletError> { // Lock the wallet let lock = self.wallet.try_lock_with_timeout(self.lock_timeout).await?; if lock == false { bail!(WalletErrorKind::WalletLocked); } // Remove the coin from the chest self.__remove_coin_from_wallet(denomination).await?; // Unlock and return the result self.wallet.unlock().await?; Ok(()) } pub(super) async fn __remove_coin_from_wallet( &mut self, denomination: Denomination, ) -> Result<Option<CarvedCoin>, WalletError> { // Get or create the chest let mut bag = match self.__get_bag(denomination).await? { Some(a) => a, None => { return Ok(None); } }; let mut bag = bag.as_mut(); // Extract a coin from the chest (if there are any left) let ret = bag.coins.pop(); Ok(ret) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/api/contract_cancel.rs
wasmer-deploy-cli/src/api/contract_cancel.rs
use error_chain::*; #[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use crate::error::*; use crate::request::*; use super::*; impl DeployApi { pub async fn contract_cancel( &mut self, reference_number: &str, consumer_identity: &str, ) -> Result<ContractActionResponse, ContractError> { let contracts = self.contract_summary().await?; // Grab the contract this action is for let reference_number = reference_number.trim(); let contract = contracts .iter() .filter(|a| a.reference_number.eq_ignore_ascii_case(reference_number)) .next(); let contract = match contract { Some(a) => a.clone(), None => { bail!(ContractErrorKind::InvalidReference( reference_number.to_string() )); } }; let ret = self .contract_action( &contract.service.code, consumer_identity, consumer_identity, ContractAction::Cancel, None, ) .await?; Ok(ret) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/api/wallet_summary.rs
wasmer-deploy-cli/src/api/wallet_summary.rs
use num_traits::*; use std::collections::BTreeMap; #[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use crate::error::*; use crate::model::*; use super::*; #[derive(Debug, Clone)] pub struct DenominationSummary { pub denomination: Decimal, pub total: Decimal, pub cnt: usize, } #[derive(Debug, Clone)] pub struct CurrencySummary { pub currency: NationalCurrency, pub total: Decimal, pub denominations: BTreeMap<Decimal, DenominationSummary>, } #[derive(Debug, Clone, Default)] pub struct WalletSummary { pub currencies: BTreeMap<NationalCurrency, CurrencySummary>, } impl DeployApi { pub async fn wallet_summary(&mut self) -> Result<WalletSummary, WalletError> { // Determine what currencies are currently stored within the wallet let mut currencies = self .wallet .bags .iter() .await? .map(|(a, _)| a.currency) .collect::<Vec<_>>(); currencies.sort(); currencies.dedup(); let mut ret = WalletSummary::default(); for currency in currencies { let currency_summary = self.__wallet_currency_summary(currency).await?; if currency_summary.total <= Decimal::zero() { continue; } ret.currencies.insert(currency, currency_summary); } Ok(ret) } pub async fn wallet_currency_summary( &mut self, currency: NationalCurrency, ) -> Result<CurrencySummary, WalletError> { // First we reconcile any deposits that have been made self.reconcile().await?; // Now make the currency summary self.__wallet_currency_summary(currency).await } pub(super) async fn __wallet_currency_summary( &mut self, currency: NationalCurrency, ) -> Result<CurrencySummary, WalletError> { // Compute the total for all chests of this currency let bags = self .wallet .bags .iter() .await? .filter(|(a, _)| a.currency == currency) .collect::<Vec<_>>(); trace!("{} bags", bags.len()); for (denomination, _) in bags.iter() { trace!("bag= {} {:?}", denomination.to_string(), denomination); } let mut total = Decimal::zero(); for (_, bag) in bags.iter() { let sub_total: Decimal = bag.coins.iter().map(|a| a.value).sum(); total += sub_total; } let mut coin_denominations = bags.iter().map(|(a, _)| a.value).collect::<Vec<_>>(); coin_denominations.sort(); coin_denominations.dedup(); coin_denominations.reverse(); let mut denominations = BTreeMap::default(); for coin_denomination in coin_denominations { let mut cnt = 0usize; for (denomination, bag) in bags.iter() { if denomination.value == coin_denomination { cnt += bag.coins.len(); } } let total = coin_denomination * Decimal::from(cnt); if total <= Decimal::zero() { continue; } denominations.insert( coin_denomination, DenominationSummary { denomination: coin_denomination, total, cnt: cnt, }, ); } Ok(CurrencySummary { currency, total, denominations, }) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/api/deposit.rs
wasmer-deploy-cli/src/api/deposit.rs
use error_chain::*; use std::ops::Deref; #[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use crate::cmd::*; use crate::error::*; use crate::model::*; use crate::request::*; use super::*; impl DeployApi { pub async fn deposit_create( &mut self, currency: NationalCurrency, amount: Decimal, ) -> Result<DepositResponse, WalletError> { // Invoke the command let session = self.dio.session().clone_session(); let ret = deposit_command( &self.registry, amount, currency, session.deref(), self.auth.clone(), ) .await?; // Load the new set of coins into the wallet self.wallet .inbox .push_with_dio(&self.dio, ret.coin_ancestor.clone())?; // Now add the history if let Err(err) = self .record_activity(HistoricActivity::DepositCreated( activities::DepositCreated { when: chrono::offset::Utc::now(), by: self.user_identity(), invoice_number: ret.invoice_number.clone(), invoice_id: ret.invoice_id.clone(), amount, currency, pay_url: ret.pay_url.clone(), }, )) .await { error!("Error writing activity: {}", err); } self.dio.commit().await?; Ok(ret) } pub async fn deposit_query(&mut self) -> Result<CoinCollectResponse, WalletError> { // If anything has been left on the DIO then we need to fail // as this loop will invoke cancel during its recovery process if self.dio.has_uncommitted() { bail!(WalletErrorKind::CoreError(CoreErrorKind::InternalError(ate::utils::obscure_error_str("unable to query despoits on the wallet when there are uncommitted transactions on the DIO")))); } // Lock the wallet let lock = self.wallet.try_lock_with_timeout(self.lock_timeout).await?; if lock == false { bail!(WalletErrorKind::WalletLocked); } let ret = self.__deposit_query().await; // Unlock and return the result self.dio.commit().await?; self.wallet.unlock().await?; ret } pub(super) async fn __deposit_query(&mut self) -> Result<CoinCollectResponse, WalletError> { let things = self .wallet .inbox .iter() .await? .filter(|a| { if let CommodityCategory::NationalCurrency(_) = a.kind.category() { true } else { false } }) .map(|a| a.take()) .collect::<Vec<_>>(); let query = self.__coin_collect_internal(things).await?; Ok(query) } pub async fn deposit_cancel(&mut self, invoice_number: &str) -> Result<(), WalletError> { // If anything has been left on the DIO then we need to fail // as this loop will invoke cancel during its recovery process if self.dio.has_uncommitted() { bail!(WalletErrorKind::CoreError(CoreErrorKind::InternalError(ate::utils::obscure_error_str("unable to cancel deposit for the wallet when there are uncommitted transactions on the DIO")))); } // Lock the wallet let lock = self.wallet.try_lock_with_timeout(self.lock_timeout).await?; if lock == false { bail!(WalletErrorKind::WalletLocked); } let ret = self.__deposit_cancel(invoice_number).await; // Unlock and return the result self.dio.commit().await?; self.wallet.unlock().await?; ret } pub(super) async fn __deposit_cancel( &mut self, invoice_number: &str, ) -> Result<(), WalletError> { let coins = self .wallet .inbox .iter() .await? .filter(|a| { if let CommodityCategory::NationalCurrency(_) = a.kind.category() { true } else { false } }) .map(|a| a.take()) .collect::<Vec<_>>(); let query = self.__coin_collect_internal(coins).await?; let ancestor = query .pending_deposits .iter() .filter(|a| a.invoice_number.as_str() == invoice_number) .next(); let ancestor = match ancestor { Some(a) => a, None => { bail!(WalletErrorKind::CoinError(CoinErrorKind::InvalidReference( invoice_number.to_string() ))); } }; let to_delete = self .wallet .as_mut() .inbox .iter_mut() .await? .filter(|a| ancestor.key.eq(&a.what)) .next() .unwrap(); let _ = cancel_deposit_command(&self.registry, to_delete.clone().take(), self.auth.clone()) .await?; to_delete.delete()?; self.dio.commit().await?; Ok(()) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/api/delete_wallet.rs
wasmer-deploy-cli/src/api/delete_wallet.rs
use error_chain::*; #[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use crate::error::*; use super::*; impl DeployApi { pub async fn is_wallet_empty(&self) -> Result<bool, WalletError> { if self.wallet.inbox.iter().await?.next().is_some() == true { return Ok(false); } for (_, bag) in self.wallet.bags.iter().await? { if bag.coins.len() > 0 { return Ok(false); } } Ok(true) } pub async fn delete_wallet(self, force: bool) -> Result<(), WalletError> { if self.is_wallet_empty().await? == false && force == false { bail!(WalletErrorKind::WalletNotEmpty); } self.wallet.delete()?; self.dio.commit().await?; Ok(()) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/bin/wasmer-deploy.rs
wasmer-deploy-cli/src/bin/wasmer-deploy.rs
#![allow(unused_imports)] use ate::prelude::*; use clap::Parser; use std::ffi::OsString; use std::path::{Path, PathBuf}; use std::sync::Arc; #[cfg(feature = "bus")] use wasmer_deploy_cli::bus::*; use wasmer_deploy_cli::cmd::*; use wasmer_deploy_cli::error::*; use wasmer_deploy_cli::opt::*; use wasmer_deploy_cli::prelude::*; use tokio::sync::mpsc; use tracing::{debug, error, info, warn}; #[allow(dead_code)] #[derive(Parser)] #[clap(version = "1.2", author = "Wasmer Inc <info@wasmer.io>")] struct Opts { /// Sets the level of log verbosity, can be used multiple times #[clap(short, long, parse(from_occurrences))] pub verbose: i32, /// Token file to read that holds a previously created token to be used for this operation #[cfg(not(target_os = "wasi"))] #[clap(long, default_value = "~/wasmer/token")] pub token_path: String, /// Token file to read that holds a previously created token to be used for this operation #[cfg(target_os = "wasi")] #[clap(long, default_value = "/.private/token")] pub token_path: String, /// URL that this command will send all its authentication requests to (e.g. wss://wasmer.sh/auth) #[clap(long)] pub auth_url: Option<url::Url>, /// NTP server address that the file-system will synchronize with #[clap(long)] pub ntp_pool: Option<String>, /// NTP server port that the file-system will synchronize with #[clap(long)] pub ntp_port: Option<u16>, /// Determines if ATE will use DNSSec or just plain DNS #[clap(long)] pub dns_sec: bool, /// Address that DNS queries will be sent to #[clap(long, default_value = "8.8.8.8")] pub dns_server: String, /// Logs debug info to the console #[clap(short, long)] pub debug: bool, #[clap(subcommand)] pub subcmd: SubCommand, } #[derive(Parser)] enum SubCommand { /// Users are personal accounts and services that have an authentication context. /// Every user comes with a personal wallet that can hold commodities. #[clap()] User(OptsUser), /// Domain groups are collections of users that share something together in association /// with an internet domain name. Every group has a built in wallet(s) that you can /// use instead of a personal wallet. In order to claim a domain group you will need /// DNS access to an owned internet domain that can be validated. #[clap()] Domain(OptsDomain), /// Databases are chains of data that make up a particular shard. These databases can be /// use for application data persistance, file systems and web sites. #[clap()] Db(OptsDatabase), /// Starts the process in BUS mode which will allow it to accept calls from other /// processes. #[cfg(feature = "bus")] #[clap()] Bus(OptsBus), /// Tokens are stored authentication and authorization secrets used by other processes. /// Using this command you may generate a custom token however the usual method for /// authentication is to use the login command instead. #[cfg(not(feature_os = "wasi"))] #[clap()] Token(OptsToken), /// Services offered by Wasmer (and other 3rd parties) are accessible via this /// sub command menu, including viewing the available services and subscribing /// to them. #[clap()] Service(OptsService), /// Contracts represent all the subscriptions you have made to specific services /// you personally consume or a group consume that you act on your authority on /// behalf of. This sub-menu allows you to perform actions such as cancel said /// contracts. #[clap()] Contract(OptsContract), /// Instances are running web assembly applications that can accessed from /// anywhere via API calls and/or the wasmer-bus. #[clap()] Instance(OptsInstance), /// Performs a networking action (e.g. connect, disconnect, bridge, etc...) #[clap()] Network(OptsNetwork), /// Wallets are directly attached to groups and users - they hold a balance, /// store transaction history and facilitate transfers, deposits and withdraws. #[clap()] Wallet(OptsWallet), /// Login to an account and store the token locally for reuse. #[clap()] Login(OptsLogin), /// Logout of the account by deleting the local token. #[clap()] Logout(OptsLogout), } #[allow(dead_code)] fn binary_path(args: &mut impl Iterator<Item = OsString>) -> PathBuf { match args.next() { Some(ref s) if !s.is_empty() => PathBuf::from(s), _ => std::env::current_exe().unwrap(), } } #[allow(dead_code)] fn name(binary_path: &Path) -> &str { binary_path.file_stem().unwrap().to_str().unwrap() } #[cfg(target_os = "wasi")] async fn init_wasi_hook() { std::panic::set_hook(Box::new(|panic_info| { if let Some(location) = panic_info.location() { println!( "panic occurred in file '{}' at line {}", location.file(), location.line(), ); } else { println!("panic occurred but can't get location information..."); } eprintln!("{:?}", backtrace::Backtrace::new()); })); } #[cfg(target_os = "wasi")] async fn init_wasi_ws() { // Add the main Wasmer certificate and connect via a wasmer_bus web socket add_global_certificate(&AteHash::from_hex_string("9c960f3ba2ece59881be0b45f39ef989").unwrap()); set_comm_factory(move |addr| { let schema = match addr.port() { 80 => "ws", _ => "wss", }; let addr = url::Url::from_str(format!("{}://{}", schema, addr).as_str()).unwrap(); Box::pin(async move { tracing::trace!("opening wasmer_bus::web_socket"); let ws = wasmer_bus_ws::prelude::SocketBuilder::new(addr) .open() .await .unwrap(); let (tx, rx) = ws.split(); let rx: Box<dyn tokio::io::AsyncRead + Send + Sync + Unpin + 'static> = Box::new(rx); let tx: Box<dyn tokio::io::AsyncWrite + Send + Sync + Unpin + 'static> = Box::new(tx); Some((rx, tx)) }) }) .await; } #[tokio::main(flavor = "multi_thread")] async fn main() -> Result<(), Box<dyn std::error::Error>> { main_async().await?; std::process::exit(0); } async fn main_async() -> Result<(), Box<dyn std::error::Error>> { // Initialize the logging and panic hook #[cfg(target_os = "wasi")] init_wasi_hook().await; // Set the origin #[cfg(target_os = "wasi")] init_wasi_ws().await; // Allow for symbolic links to the main binary let args = wild::args_os().collect::<Vec<_>>(); let mut args = args.iter().cloned(); let binary = binary_path(&mut args); let binary_as_util = name(&binary); let mut opts = { let cmd = match binary_as_util { "user" => Some(SubCommand::User(OptsUser::parse())), "domain" => Some(SubCommand::Domain(OptsDomain::parse())), "db" => Some(SubCommand::Db(OptsDatabase::parse())), #[cfg(feature = "bus")] "bus" => Some(SubCommand::Bus(OptsBus::parse())), "service" => Some(SubCommand::Service(OptsService::parse())), "inst" => Some(SubCommand::Instance(OptsInstance::parse())), "instance" => Some(SubCommand::Instance(OptsInstance::parse())), "net" => Some(SubCommand::Network(OptsNetwork::parse())), "network" => Some(SubCommand::Network(OptsNetwork::parse())), "contract" => Some(SubCommand::Contract(OptsContract::parse())), "wallet" => Some(SubCommand::Wallet(OptsWallet::parse())), "login" => Some(SubCommand::Login(OptsLogin::parse())), "logout" => Some(SubCommand::Logout(OptsLogout::parse())), _ => None, }; match cmd { Some(cmd) => Opts { verbose: 1, #[cfg(not(target_os = "wasi"))] token_path: "~/wasmer/token".to_string(), #[cfg(target_os = "wasi")] token_path: "/.private/token".to_string(), auth_url: None, ntp_pool: None, ntp_port: None, dns_sec: false, dns_server: "8.8.8.8".to_string(), debug: false, subcmd: cmd, }, None => Opts::parse(), } }; // We upgrade the verbosity for certain commands by default opts.verbose = opts.verbose.max(match &opts.subcmd { #[cfg(feature = "bus")] SubCommand::Bus(..) => 4, _ => 0, }); ate::log_init(opts.verbose, opts.debug); let auth = wasmer_auth::prelude::origin_url(&opts.auth_url, "auth"); // Build the ATE configuration object let mut conf = AteConfig::default(); conf.dns_sec = opts.dns_sec; conf.dns_server = opts.dns_server; #[cfg(feature = "enable_ntp")] if let Some(pool) = opts.ntp_pool { conf.ntp_pool = pool; } #[cfg(feature = "enable_ntp")] if let Some(port) = opts.ntp_port { conf.ntp_port = port; } // If the domain is localhost then load certificates from dev.wasmer.sh #[cfg(feature = "enable_dns")] if let Some(domain) = auth.domain() { if domain == "localhost" { let test_registry = Registry::new(&conf).await; for cert in test_registry.dns_certs("dev.wasmer.sh").await.unwrap() { add_global_certificate(&cert); } } } // Do we need a token let needs_token = match &opts.subcmd { SubCommand::Login(..) => false, SubCommand::Token(..) => false, #[cfg(feature = "bus")] SubCommand::Bus(..) => false, SubCommand::Network(a) => match a.cmd { OptsNetworkCommand::For(..) => true, OptsNetworkCommand::Reconnect(..) => false, OptsNetworkCommand::Disconnect => false, OptsNetworkCommand::Monitor(..) => false, #[cfg(any(target_os = "linux", target_os = "macos"))] OptsNetworkCommand::Bridge(..) => false, }, SubCommand::User(a) => match a.action { UserAction::Create(..) => false, UserAction::Recover(..) => false, _ => true, }, _ => true, }; // Make sure the token exists if needs_token { let token_path = shellexpand::tilde(&opts.token_path).to_string(); if std::path::Path::new(&token_path).exists() == false { eprintln!("Token not found - please first login."); std::process::exit(1); } } // Determine what we need to do match opts.subcmd { SubCommand::User(opts_user) => { main_opts_user(opts_user, None, Some(opts.token_path), auth).await?; } SubCommand::Domain(opts_group) => { main_opts_group(opts_group, None, Some(opts.token_path), auth, "Domain name").await?; } SubCommand::Db(opts_db) => { main_opts_db(opts_db, None, Some(opts.token_path), auth, "Domain name").await?; } #[cfg(feature = "bus")] SubCommand::Bus(opts_bus) => { main_opts_bus(opts_bus, conf, opts.token_path, auth).await?; } #[cfg(not(feature_os = "wasi"))] SubCommand::Token(opts_token) => { main_opts_token(opts_token, None, Some(opts.token_path), auth, "Domain name").await?; } SubCommand::Wallet(opts_wallet) => { main_opts_wallet(opts_wallet.source, opts.token_path, auth).await? } SubCommand::Contract(opts_contract) => { main_opts_contract(opts_contract.purpose, opts.token_path, auth).await?; } SubCommand::Service(opts_service) => { main_opts_service(opts_service.purpose, opts.token_path, auth).await?; } SubCommand::Network(opts_network) => { main_opts_network(opts_network, opts.token_path, auth).await?; } SubCommand::Instance(opts_instance) => { let db_url = wasmer_auth::prelude::origin_url(&opts_instance.db_url, "db"); let inst_url = wasmer_auth::prelude::origin_url(&opts_instance.inst_url, "inst"); main_opts_instance(opts_instance.purpose, opts.token_path, auth, db_url, inst_url, opts_instance.security).await?; } SubCommand::Login(opts_login) => { main_opts_login(opts_login, opts.token_path, auth).await? }, SubCommand::Logout(opts_logout) => { main_opts_logout(opts_logout, opts.token_path).await? }, } // We are done Ok(()) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/helper/session.rs
wasmer-deploy-cli/src/helper/session.rs
use error_chain::bail; #[allow(unused_imports)] use tracing::{debug, error, info, trace, warn}; use ate::prelude::*; use crate::error::*; pub fn session_sign_key<'a>( session: &'a dyn AteSession, force_user_keys: bool, ) -> Result<&'a PrivateSignKey, CoreError> { Ok(if force_user_keys { match session.user().user.write_keys().next() { Some(a) => a, None => { warn!("no master key - in session provided to the contract elevate command"); bail!(CoreError::from_kind(CoreErrorKind::NoMasterKey)); } } } else { match session .role(&AteRolePurpose::Owner) .iter() .filter_map(|a| a.write_keys().next()) .next() { Some(a) => a, None => { warn!("no master key - in session provided to the contract elevate command"); bail!(CoreError::from_kind(CoreErrorKind::NoMasterKey)); } } }) } pub fn session_sign_and_broker_key<'a>( session: &'a dyn AteSession, force_user_keys: bool, ) -> Result<(&'a PrivateSignKey, &'a PrivateEncryptKey), CoreError> { // The signature key needs to be present to send the notification let (sign_key, broker_read) = if force_user_keys { match session.user().user.write_keys().next() { Some(a) => (a, session.user().broker_read()), None => { warn!("no master key - in session provided to the contract elevate command"); bail!(CoreError::from_kind(CoreErrorKind::NoMasterKey)); } } } else { match session .role(&AteRolePurpose::Owner) .iter() .filter_map(|a| a.write_keys().next()) .next() { Some(a) => (a, session.broker_read()), None => { warn!("no master key - in session provided to the contract elevate command"); bail!(CoreError::from_kind(CoreErrorKind::NoMasterKey)); } } }; let broker_read = match broker_read { Some(a) => a, None => { warn!("missing broker read key - in session provided to the contract elevate command"); bail!(CoreError::from_kind(CoreErrorKind::MissingBrokerKey)); } }; Ok((sign_key, broker_read)) }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/helper/coins.rs
wasmer-deploy-cli/src/helper/coins.rs
use num_traits::*; use std::collections::BTreeMap; use crate::model::*; pub fn shrink_denomination(mut denomination: Decimal) -> Decimal { let scalar = Decimal::new(1000, 0); match denomination.checked_mul(scalar).unwrap().to_string() { a if a.starts_with("1") => { denomination = denomination / Decimal::new(2, 0); } a if a.starts_with("5") => { denomination = denomination * Decimal::new(2, 0); denomination = denomination / Decimal::new(5, 0); } a if a.starts_with("2") => { denomination = denomination / Decimal::new(2, 0); } _ => { denomination = denomination / Decimal::new(10, 0); } } denomination } pub fn grow_denomination(mut denomination: Decimal) -> Decimal { let scalar = Decimal::new(1000, 0); match denomination.checked_mul(scalar).unwrap().to_string() { a if a.starts_with("1") => { denomination *= Decimal::new(2, 0); } a if a.starts_with("2") => { denomination *= Decimal::new(5, 0); denomination /= Decimal::new(2, 0); } a if a.starts_with("5") => { denomination *= Decimal::new(2, 0); } _ => { denomination *= Decimal::new(10, 0); } } denomination } pub fn carve_denominations( mut amount: Decimal, currency: NationalCurrency, ) -> BTreeMap<Decimal, usize> { // Select a starting denomination that makes sense let lowest_denomination = Decimal::new(1, currency.decimal_points() as u32); let mut denomination = lowest_denomination; while grow_denomination(denomination) <= amount { denomination = grow_denomination(denomination); } // Now lets work the amount down into smaller chunks let mut ret = BTreeMap::default(); while amount > Decimal::zero() { // Shrink the denomination if its too big while denomination > amount && denomination > lowest_denomination { denomination = shrink_denomination(denomination); } if denomination > amount { return ret; } // Record the coin and reduce the amount let v = ret.entry(denomination).or_default(); *v += 1usize; amount = amount - denomination; } ret }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/helper/mod.rs
wasmer-deploy-cli/src/helper/mod.rs
mod coins; mod session; pub use coins::*; pub use session::*;
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/bus/file_system.rs
wasmer-deploy-cli/src/bus/file_system.rs
use async_trait::async_trait; use ate_files::codes::*; use ate_files::prelude::*; use derivative::*; use std::sync::Arc; use std::sync::Mutex; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; use wasmer_bus_fuse::api; use wasmer_bus_fuse::prelude::*; use super::conv_err; use super::opened_file::*; #[derive(Derivative, Clone)] #[derivative(Debug)] pub struct FileSystem { #[derivative(Debug = "ignore")] accessor: Arc<FileAccessor>, context: RequestContext, } impl FileSystem { pub fn new(accessor: Arc<FileAccessor>, context: RequestContext) -> FileSystem { FileSystem { accessor, context } } pub async fn open( &self, path: String, options: api::OpenOptions, ) -> Arc<OpenedFile> { // Determine all the flags let mut flags = 0i32; if options.append { flags |= O_APPEND; } if options.create { flags |= O_CREAT; } if options.create_new { flags |= O_CREAT | O_TRUNC; } if options.read && options.write { flags |= O_RDWR; } else if options.read { flags |= O_RDONLY; } else if options.write { flags |= O_WRONLY; } if options.truncate { flags |= O_TRUNC; } let append = options.append; let create = options.create | options.create_new; // Open the file! let handle = if let Ok(Some(file)) = self.accessor.search(&self.context, path.as_str()).await { match self .accessor .open(&self.context, file.ino, flags as u32) .await { Ok(a) => Ok(a), Err(err) => { debug!("open failed (path={}) - {}", path, err); Err(conv_err(err)) } } } else if create == true { let path = std::path::Path::new(&path); let name = path.file_name().ok_or_else(|| FsError::InvalidInput); match name { Ok(name) => { let parent = path.parent().ok_or_else(|| FsError::InvalidInput); match parent { Ok(parent) => { if let Ok(Some(parent)) = self .accessor .search(&self.context, parent.to_string_lossy().as_ref()) .await { match self .accessor .create( &self.context, parent.ino, name.to_string_lossy().as_ref(), 0o666 as u32, ) .await { Ok(a) => Ok(a), Err(err) => { debug!( "open failed (path={}) - {}", path.to_string_lossy(), err ); Err(conv_err(err)) } } } else { debug!( "open failed - parent not found ({})", parent.to_string_lossy() ); Err(FsError::EntityNotFound) } } Err(err) => { debug!( "open failed failed - invalid input ({})", path.to_string_lossy() ); Err(err) } } } Err(err) => { debug!("open failed - invalid input ({})", path.to_string_lossy()); Err(err) } } } else { debug!("open failed - not found ({})", path); Err(FsError::EntityNotFound) }; // Every file as an offset pointer // If we are in append mode then we need to change the offeset let offset = if let Ok(handle) = &handle { if append { Arc::new(Mutex::new(handle.spec.size() as u64)) } else { Arc::new(Mutex::new(0u64)) } } else { Arc::new(Mutex::new(0u64)) }; // Return an opened file Arc::new(OpenedFile::new( handle, offset, self.context.clone(), append, path, self.accessor.clone(), )) } } #[async_trait] impl api::FileSystemSimplified for FileSystem { async fn init(&self) -> FsResult<()> { self.accessor.init(&self.context).await.map_err(conv_err)?; Ok(()) } async fn read_dir(&self, path: String) -> FsResult<api::Dir> { if let Ok(Some(file)) = self.accessor.search(&self.context, path.as_str()).await { match self .accessor .opendir(&self.context, file.ino, O_RDONLY as u32) .await { Ok(fh) => { let mut ret = api::Dir::default(); for entry in fh.children.iter() { if entry.name == "." || entry.name == ".." { continue; } trace!("bus::read-dir::found - {}", entry.name); ret.data.push(api::DirEntry { path: entry.name.clone(), metadata: Some(super::conv_meta(entry.attr.clone())), }); } let _ = self .accessor .releasedir(&self.context, file.ino, fh.fh, 0) .await; FsResult::Ok(ret) } Err(err) => { debug!("read_dir failed - {}", err); FsResult::Err(conv_err(err)) } } } else { debug!("read_dir failed - not found ({})", path); FsResult::Err(FsError::EntityNotFound) } } async fn create_dir(&self, path: String) -> FsResult<api::Metadata> { let path = std::path::Path::new(&path); let name = path.file_name().ok_or_else(|| FsError::InvalidInput)?; let parent = path.parent().ok_or_else(|| FsError::InvalidInput)?; if let Ok(Some(parent)) = self .accessor .search(&self.context, parent.to_string_lossy().as_ref()) .await { self.accessor .mkdir( &self.context, parent.ino, name.to_string_lossy().as_ref(), parent.mode, ) .await .map_err(|err| { debug!("create_dir failed - {}", err); conv_err(err) }) .map(super::conv_meta) } else { debug!( "create_dir failed - parent not found ({})", parent.to_string_lossy() ); Err(FsError::EntityNotFound) } } async fn remove_dir(&self, path: String) -> FsResult<()> { let path = std::path::Path::new(&path); let name = path.file_name().ok_or_else(|| FsError::InvalidInput)?; let parent = path.parent().ok_or_else(|| FsError::InvalidInput)?; if let Ok(Some(parent)) = self .accessor .search(&self.context, parent.to_string_lossy().as_ref()) .await { let _ = self .accessor .rmdir(&self.context, parent.ino, name.to_string_lossy().as_ref()) .await; Ok(()) } else { debug!( "remove_dir failed - parent not found ({})", parent.to_string_lossy() ); Err(FsError::EntityNotFound) } } async fn rename(&self, from: String, to: String) -> FsResult<()> { let path = std::path::Path::new(&from); let new_path = std::path::Path::new(&to); let name = path.file_name().ok_or_else(|| FsError::InvalidInput)?; let new_name = new_path.file_name().ok_or_else(|| FsError::InvalidInput)?; let parent = path.parent().ok_or_else(|| FsError::InvalidInput)?; let new_parent = new_path.parent().ok_or_else(|| FsError::InvalidInput)?; if let Ok(Some(parent)) = self .accessor .search(&self.context, parent.to_string_lossy().as_ref()) .await { if let Ok(Some(new_parent)) = self .accessor .search(&self.context, new_parent.to_string_lossy().as_ref()) .await { let _ = self .accessor .rename( &self.context, parent.ino, name.to_string_lossy().as_ref(), new_parent.ino, new_name.to_string_lossy().as_ref(), ) .await; Ok(()) } else { debug!("remove_dir failed - new parent not found"); Err(FsError::EntityNotFound) } } else { debug!("rename failed - parent not found"); Err(FsError::EntityNotFound) } } async fn remove_file(&self, path: String) -> FsResult<()> { let path = std::path::Path::new(&path); let name = path.file_name().ok_or_else(|| FsError::InvalidInput)?; let parent = path.parent().ok_or_else(|| FsError::InvalidInput)?; if let Ok(Some(parent)) = self .accessor .search(&self.context, parent.to_string_lossy().as_ref()) .await { let _ = self .accessor .unlink(&self.context, parent.ino, name.to_string_lossy().as_ref()) .await; Ok(()) } else { debug!("remove_file failed - parent not found"); Err(FsError::EntityNotFound) } } async fn read_metadata(&self, path: String) -> FsResult<api::Metadata> { if let Ok(Some(file)) = self.accessor.search(&self.context, path.as_str()).await { FsResult::Ok(super::conv_meta(file)) } else { debug!("read_metadata failed - not found ({})", path); FsResult::Err(FsError::EntityNotFound) } } async fn read_symlink_metadata(&self, path: String) -> FsResult<api::Metadata> { if let Ok(Some(file)) = self.accessor.search(&self.context, path.as_str()).await { FsResult::Ok(super::conv_meta(file)) } else { debug!("read_symlink_metadata failed - not found ({})", path); FsResult::Err(FsError::EntityNotFound) } } async fn open( &self, path: String, options: api::OpenOptions, ) -> Result<Arc<dyn api::OpenedFile>, BusError> { let ret = FileSystem::open(self, path, options).await; Ok(ret) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/bus/file_io.rs
wasmer-deploy-cli/src/bus/file_io.rs
use async_trait::async_trait; use ate_files::prelude::*; use derivative::*; use std::sync::Arc; use std::sync::Mutex; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; use wasmer_bus_fuse::api; use wasmer_bus_fuse::prelude::*; #[derive(Derivative, Clone)] #[derivative(Debug)] pub struct FileIo { #[derivative(Debug = "ignore")] handle: Arc<OpenHandle>, offset: Arc<Mutex<u64>>, append: bool, } impl FileIo { pub fn new(handle: Arc<OpenHandle>, offset: Arc<Mutex<u64>>, append: bool) -> FileIo { FileIo { handle, offset, append, } } } #[async_trait] impl api::FileIOSimplified for FileIo { async fn seek(&self, from: api::SeekFrom) -> FsResult<u64> { let file = self.handle.as_ref(); let mut offset = { self.offset.lock().unwrap() }; match from { api::SeekFrom::Current(a) if a > 0 => { if let Some(a) = offset.checked_add(a.abs() as u64) { *offset = a; } else { return Err(FsError::InvalidInput); } } api::SeekFrom::Current(a) if a < 0 => { if let Some(a) = offset.checked_sub(a.abs() as u64) { *offset = a; } else { return Err(FsError::InvalidInput); } } api::SeekFrom::Current(_) => {} api::SeekFrom::End(a) if a > 0 => { if let Some(a) = file.spec.size().checked_add(a.abs() as u64) { *offset = a; } else { return Err(FsError::InvalidInput); } } api::SeekFrom::End(a) if a < 0 => { if let Some(a) = file.spec.size().checked_sub(a.abs() as u64) { *offset = a; } else { return Err(FsError::InvalidInput); } } api::SeekFrom::End(_) => {} api::SeekFrom::Start(a) => { *offset = a; } } Ok(*offset) } async fn flush(&self) -> FsResult<()> { let file = self.handle.as_ref(); file.spec.commit().await.map_err(|err| { debug!("flush failed - {}", err); FsError::IOError }) } async fn write(&self, data: Vec<u8>) -> FsResult<u64> { let file = self.handle.as_ref(); let offset = { let mut offset = self.offset.lock().unwrap(); if self.append { *offset = file.spec.size(); } *offset }; let written = file.spec.write(offset, &data[..]).await.map_err(|err| { debug!("write failed - {}", err); FsError::IOError })?; { let mut guard = self.offset.lock().unwrap(); *guard = offset + written; } Ok(written) } async fn read(&self, len: u64) -> FsResult<Vec<u8>> { let file = self.handle.as_ref(); let offset = { self.offset.lock().unwrap().clone() }; let ret = file .spec .read(offset, len) .await .map_err(|err| { debug!("read failed - {}", err); FsError::IOError }) .map(|a| a.to_vec())?; { let mut guard = self.offset.lock().unwrap(); *guard = offset + (ret.len() as u64); } Ok(ret) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/bus/mod.rs
wasmer-deploy-cli/src/bus/mod.rs
pub mod file_io; pub mod file_system; mod fuse; mod main; mod server; pub mod opened_file; pub use main::*; use wasmer_bus_fuse::api; fn conv_file_type(kind: ate_files::api::FileKind) -> api::FileType { let mut ret = api::FileType::default(); match kind { ate_files::api::FileKind::Directory => { ret.dir = true; } ate_files::api::FileKind::RegularFile => { ret.file = true; } ate_files::api::FileKind::FixedFile => { ret.file = true; } ate_files::api::FileKind::SymLink => { ret.symlink = true; } } ret } fn conv_meta(file: ate_files::attr::FileAttr) -> api::Metadata { api::Metadata { ft: conv_file_type(file.kind), accessed: file.accessed, created: file.created, modified: file.updated, len: file.size, } } use ate_files::error::FileSystemError; fn conv_err(err: FileSystemError) -> api::FsError { use ate_files::error::FileSystemErrorKind; match err { FileSystemError(FileSystemErrorKind::AlreadyExists, _) => api::FsError::AlreadyExists, FileSystemError(FileSystemErrorKind::NotDirectory, _) => api::FsError::BaseNotDirectory, FileSystemError(FileSystemErrorKind::IsDirectory, _) => api::FsError::InvalidInput, FileSystemError(FileSystemErrorKind::DoesNotExist, _) => api::FsError::EntityNotFound, FileSystemError(FileSystemErrorKind::NoAccess, _) => api::FsError::PermissionDenied, FileSystemError(FileSystemErrorKind::PermissionDenied, _) => api::FsError::PermissionDenied, FileSystemError(FileSystemErrorKind::ReadOnly, _) => api::FsError::PermissionDenied, FileSystemError(FileSystemErrorKind::InvalidArguments, _) => api::FsError::InvalidInput, FileSystemError(FileSystemErrorKind::NoEntry, _) => api::FsError::EntityNotFound, FileSystemError(FileSystemErrorKind::NotImplemented, _) => api::FsError::NoDevice, FileSystemError(_, _) => api::FsError::IOError, } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false
wasmerio/ate
https://github.com/wasmerio/ate/blob/87635b5b49c4163885ce840f4f1c2f30977f40cc/wasmer-deploy-cli/src/bus/fuse.rs
wasmer-deploy-cli/src/bus/fuse.rs
#![allow(unused_imports, dead_code)] use async_trait::async_trait; use ate::loader::DummyLoader; use ate::prelude::*; use ate::utils::LoadProgress; use wasmer_auth::prelude::*; use ate_files::codes::*; use ate_files::prelude::*; use derivative::*; use std::io::Write; use std::sync::Arc; use std::time::Duration; #[allow(unused_imports, dead_code)] use tracing::{debug, error, info, trace, warn}; use wasmer_bus::prelude::*; use wasmer_bus_fuse::api; use wasmer_bus_fuse::prelude::*; use wasmer_bus_deploy::prelude::*; use super::file_system::FileSystem; use crate::opt::OptsBus; #[derive(Derivative)] #[derivative(Debug)] pub struct FuseServer { #[derivative(Debug = "ignore")] registry: Arc<Registry>, #[derivative(Debug = "ignore")] opts: Arc<OptsBus>, conf: AteConfig, session_user: AteSessionUser, auth_url: url::Url, } impl FuseServer { pub async fn listen( opts: Arc<OptsBus>, registry: Arc<Registry>, session_user: AteSessionUser, conf: AteConfig, auth_url: url::Url, ) -> Result<(), crate::error::BusError> { // Register so we can respond to calls let server = Arc::new(FuseServer { registry, opts, conf, session_user, auth_url, }); api::FuseService::listen(server); Ok(()) } } #[async_trait] impl api::FuseSimplified for FuseServer { async fn mount( &self, name: String, ) -> Result<Arc<dyn api::FileSystem>, wasmer_bus_deploy::prelude::BusError> { // Derive the group from the mount address let mut group = None; if let Some((group_str, _)) = name.split_once("/") { group = Some(group_str.to_string()); } // Attempt to grab additional permissions for the group (if it has any) let session: AteSessionType = if group.is_some() { match main_gather( group.clone(), self.session_user.clone().into(), self.auth_url.clone(), "Group", ) .await { Ok(a) => a.into(), Err(err) => { debug!("Group authentication failed: {} - falling back to user level authorization", err); self.session_user.clone().into() } } } else { self.session_user.clone().into() }; // Build the request context let mut context = RequestContext::default(); context.uid = session.uid().unwrap_or_default(); context.gid = session.gid().unwrap_or_default(); let remote = self.opts.remote.clone(); // Create a progress bar loader let progress_local = DummyLoader::default(); let progress_remote = LoadProgress::new(std::io::stdout()); println!("Loading the chain-of-trust"); // Load the chain let remote = crate::prelude::origin_url(&remote, "db"); let key = ChainKey::from(name.clone()); let chain = match self .registry .open_ext(&remote, &key, false, progress_local, progress_remote) .await { Ok(a) => a, Err(err) => { warn!("failed to open chain - {}", err); return Err(wasmer_bus_deploy::prelude::BusError::BadRequest); } }; let accessor = Arc::new( FileAccessor::new( chain.as_arc(), group, session, TransactionScope::Local, TransactionScope::Local, false, false, ) .await, ); let _ = std::io::stdout().flush(); // Create the file system Ok(Arc::new(FileSystem::new(accessor, context))) } }
rust
Apache-2.0
87635b5b49c4163885ce840f4f1c2f30977f40cc
2026-01-04T20:14:33.413949Z
false