Skip to content

Commit

Permalink
Merge pull request #826 from golemfactory/feature/metamask
Browse files Browse the repository at this point in the history
Feature/metamask
  • Loading branch information
prekucki authored Nov 25, 2020
2 parents 92e00d2 + 5f6d06d commit 8d41ac7
Show file tree
Hide file tree
Showing 12 changed files with 291 additions and 27 deletions.
6 changes: 4 additions & 2 deletions agent/provider/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@ pub fn config_get(config: ProviderConfig, name: Option<String>) -> anyhow::Resul
if config.json {
println!("{}", serde_json::to_string_pretty(&state)?);
} else {
for var in state.as_object().unwrap().iter() {
println!("{}: {}", var.0, var.1.as_str().unwrap());
for (key, v) in state.as_object().unwrap().iter() {
if v.is_string() {
println!("{}: {}", key, v.as_str().unwrap());
}
}
}
}
Expand Down
34 changes: 31 additions & 3 deletions agent/provider/src/provider_agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::hardware;
use crate::market::provider_market::{OfferKind, Unsubscribe, UpdateMarket};
use crate::market::{CreateOffer, Preset, PresetManager, ProviderMarket};
use crate::payments::{LinearPricingOffer, Payments, PricingOffer};
use crate::startup_config::{FileMonitor, NodeConfig, ProviderConfig, RunConfig};
use crate::startup_config::{FileMonitor, NodeConfig, ProviderConfig, RecvAccount, RunConfig};
use crate::task_manager::{InitializeTaskManager, TaskManager};
use actix::prelude::*;
use actix::utils::IntervalFunc;
Expand Down Expand Up @@ -73,6 +73,7 @@ impl GlobalsManager {
pub struct GlobalsState {
pub node_name: String,
pub subnet: Option<String>,
pub account: Option<RecvAccount>,
}

impl GlobalsState {
Expand Down Expand Up @@ -107,6 +108,9 @@ impl GlobalsState {
if node_config.subnet.is_some() {
self.subnet = node_config.subnet;
}
if node_config.account.is_some() {
self.account = node_config.account;
}
self.save(path)
}

Expand All @@ -123,7 +127,6 @@ impl ProviderAgent {
log::info!("Loading payment accounts...");
let accounts: Vec<Account> = api.payment.get_accounts().await?;
log::info!("Payment accounts: {:#?}", accounts);

let registry = config.registry()?;
registry.validate()?;

Expand Down Expand Up @@ -234,6 +237,31 @@ impl ProviderAgent {
}
node_info
}

fn accounts(&self) -> Vec<Account> {
let globals = self.globals.get_state();
if let Some(account) = &globals.account {
let mut accounts = Vec::new();
if account.platform.is_some() {
let zkaddr = Account {
platform: account.platform.clone().unwrap(),
address: account.address.to_lowercase(),
};
accounts.push(zkaddr);
} else {
for &platform in &["NGNT", "ZK-NGNT"] {
accounts.push(Account {
platform: platform.to_string(),
address: account.address.to_lowercase(),
})
}
}

accounts
} else {
self.accounts.clone()
}
}
}

fn get_prices(
Expand Down Expand Up @@ -392,7 +420,7 @@ impl Handler<CreateOffers> for ProviderAgent {
let runner = self.runner.clone();
let market = self.market.clone();
let node_info = self.create_node_info();
let accounts = self.accounts.clone();
let accounts = self.accounts();
let inf_node_info = InfNodeInfo::from(self.hardware.capped());
let preset_names = match msg.0 {
OfferKind::Any => self.presets.active(),
Expand Down
53 changes: 53 additions & 0 deletions agent/provider/src/startup_config.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use notify::*;
use serde::{Deserialize, Serialize};
use std::error::Error;
use std::path::{Path, PathBuf};
use structopt::{clap, StructOpt};
Expand All @@ -8,6 +9,7 @@ use crate::hardware::{Resources, UpdateResources};
use directories::UserDirs;
use futures::channel::oneshot;

use std::str::FromStr;
use std::sync::mpsc;
use std::time::Duration;
use ya_client::cli::ApiOpts;
Expand Down Expand Up @@ -80,6 +82,51 @@ impl ProviderConfig {
}
}

#[derive(Clone, Serialize, Deserialize)]
pub struct RecvAccount {
pub platform: Option<String>,
pub address: String,
}

impl FromStr for RecvAccount {
type Err = anyhow::Error;

fn from_str(s: &str) -> anyhow::Result<Self> {
let mut it = s.split("/").fuse();
match (it.next(), it.next(), it.next()) {
(Some(addr), None, None) => {
if addr.starts_with("0x") {
Ok(RecvAccount {
platform: None,
address: addr.to_string(),
})
} else {
anyhow::bail!("invalid address format expected 0x..")
}
}
(Some(driver), Some(addr), None) => {
let platform = Some(
match driver {
"zksync" | "zk" => "ZK-NGNT",
"eth" | "l1" => "NGTN",
_ => anyhow::bail!("unknown driver: {}", driver),
}
.to_string(),
);
if addr.starts_with("0x") {
Ok(RecvAccount {
platform,
address: addr.to_string(),
})
} else {
anyhow::bail!("invalid address format expected 0x..")
}
}
_ => anyhow::bail!("invalid account desription: {}", s),
}
}
}

#[derive(StructOpt)]
pub struct NodeConfig {
/// Your human readable identity in the network.
Expand All @@ -89,6 +136,12 @@ pub struct NodeConfig {
/// with other identifiers than selected. Useful for test purposes.
#[structopt(long, env = "SUBNET")]
pub subnet: Option<String>,

/// Account for payments
/// Format: `[<driver>/]<address>`
///
#[structopt(long, env = "YA_ACCOUNT")]
pub account: Option<RecvAccount>,
}

#[derive(StructOpt)]
Expand Down
2 changes: 1 addition & 1 deletion core/model/src/payment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ pub mod local {
type Error = GenericError;
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
pub struct StatusResult {
pub amount: BigDecimal,
pub reserved: BigDecimal,
Expand Down
6 changes: 5 additions & 1 deletion core/serv-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,11 @@ impl CommandOutput {

pub fn print(&self, json_output: bool) {
match self {
CommandOutput::NoOutput => {}
CommandOutput::NoOutput => {
if json_output {
println!("null");
}
}
CommandOutput::Table {
columns,
values,
Expand Down
2 changes: 1 addition & 1 deletion golem_cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ authors = ["Golem Factory <[email protected]>"]
edition = "2018"

[dependencies]
actix-rt="1.1"
ya-compile-time-utils = "0.1"
actix-rt = "1.0"
anyhow = "1.0"
bigdecimal = { version = "0.1.0"}
byte-unit = "4.0"
Expand Down
16 changes: 16 additions & 0 deletions golem_cli/src/command/provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,16 @@ pub struct YaProviderCommand {
}

#[derive(Deserialize)]
pub struct RecvAccount {
pub platform: Option<String>,
pub address: String,
}

#[derive(Deserialize, Default)]
pub struct ProviderConfig {
pub node_name: Option<String>,
pub subnet: Option<String>,
pub account: Option<RecvAccount>,
}

#[derive(Deserialize)]
Expand Down Expand Up @@ -66,6 +73,15 @@ impl YaProviderCommand {
cmd.arg("--subnet").arg(subnet);
}

if let Some(account) = &config.account {
if let Some(platform) = &account.platform {
cmd.arg("--account")
.arg(format!("{}/{}", platform, &account.address));
} else {
cmd.arg("--account").arg(&account.address);
}
}

let output = cmd
.stderr(Stdio::piped())
.stdin(Stdio::null())
Expand Down
50 changes: 49 additions & 1 deletion golem_cli/src/command/yagna.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,22 @@ use std::process::Stdio;
use tokio::process::{Child, Command};
use ya_core_model::payment::local::{InvoiceStats, InvoiceStatusNotes, StatusNotes, StatusResult};

pub struct PaymentType {
pub platform: &'static str,
pub driver: &'static str,
}

impl PaymentType {
pub const ZK: PaymentType = PaymentType {
platform: "ZK-NGNT",
driver: "zksync",
};
pub const PLAIN: PaymentType = PaymentType {
platform: "NGNT",
driver: "ngnt",
};
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Id {
Expand Down Expand Up @@ -105,8 +121,35 @@ impl YagnaCommand {
output.map_err(anyhow::Error::msg)
}

pub async fn payment_status(mut self) -> anyhow::Result<StatusResult> {
pub async fn payment_status(
mut self,
address: Option<&str>,
payment_type: Option<&PaymentType>,
) -> anyhow::Result<StatusResult> {
self.cmd.args(&["--json", "payment", "status"]);
if let Some(payment_type) = payment_type {
self.cmd.arg("-p").arg(payment_type.platform);
}
if let Some(addr) = address {
self.cmd.arg(addr);
}
self.run().await
}

pub async fn payment_init(
mut self,
address: &str,
payment_type: &PaymentType,
) -> anyhow::Result<()> {
self.cmd.args(&[
"--json",
"payment",
"init",
"-p",
"--driver",
payment_type.driver,
address,
]);
self.run().await
}

Expand All @@ -127,6 +170,11 @@ impl YagnaCommand {
cmd.stdin(Stdio::null())
.stderr(Stdio::inherit())
.stdout(Stdio::inherit());
if let Some(core_log) = std::env::var_os("YA_CORE_LOG") {
cmd.env("RUST_LOG", core_log);
} else {
cmd.env("RUST_LOG", "info,actix_web::middleware=warn");
}

#[cfg(target_os = "linux")]
unsafe {
Expand Down
22 changes: 21 additions & 1 deletion golem_cli/src/service.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::appkey;
use crate::command::YaCommand;
use crate::command::{PaymentType, YaCommand};
use crate::setup::RunConfig;
use anyhow::{Context, Result};
use futures::channel::{mpsc, oneshot};
Expand Down Expand Up @@ -112,6 +112,26 @@ pub async fn run(mut config: RunConfig) -> Result</*exit code*/ i32> {
let cmd = YaCommand::new()?;
let service = cmd.yagna()?.service_run().await?;
let app_key = appkey::get_app_key().await?;

let provider_config = cmd.ya_provider()?.get_config().await?;
if let Some(account) = provider_config.account {
let address = account.address.to_lowercase();
cmd.yagna()?
.payment_init(&address, &PaymentType::PLAIN)
.await?;
cmd.yagna()?
.payment_init(&address, &PaymentType::ZK)
.await?;
} else {
let id = cmd.yagna()?.default_id().await?;
cmd.yagna()?
.payment_init(&id.node_id, &PaymentType::PLAIN)
.await?;
cmd.yagna()?
.payment_init(&id.node_id, &PaymentType::ZK)
.await?;
}

let provider = cmd.ya_provider()?.spawn(&app_key).await?;
let ctrl_c = tokio::signal::ctrl_c();

Expand Down
25 changes: 20 additions & 5 deletions golem_cli/src/settings.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::command::{ProviderConfig, YaCommand};
use crate::command::{ProviderConfig, RecvAccount, YaCommand};
use anyhow::Result;
use byte_unit::{Byte as Bytes, ByteUnit};
use structopt::{clap, StructOpt};
Expand Down Expand Up @@ -26,16 +26,19 @@ pub struct Settings {
disk: Option<Bytes>,

/// Price for starting a task
#[structopt(long, group = "set", value_name = "NGNT (float)")]
#[structopt(long, group = "set", value_name = "GLM (float)")]
starting_fee: Option<f64>,

/// Price for working environment per hour
#[structopt(long, group = "set", value_name = "NGNT (float)")]
#[structopt(long, group = "set", value_name = "GLM (float)")]
env_per_hour: Option<f64>,

/// Price for CPU per hour
#[structopt(long, group = "set", value_name = "NGNT (float)")]
#[structopt(long, group = "set", value_name = "GLM (float)")]
cpu_per_hour: Option<f64>,
/// Wallet address
#[structopt(long, group = "set")]
address: Option<String>,
}

pub async fn run(settings: Settings) -> Result</*exit code*/ i32> {
Expand All @@ -46,7 +49,19 @@ pub async fn run(settings: Settings) -> Result</*exit code*/ i32> {
cmd.ya_provider()?
.set_config(&ProviderConfig {
node_name: Some(node_name),
subnet: None,
..ProviderConfig::default()
})
.await?;
}

if let Some(address) = settings.address {
cmd.ya_provider()?
.set_config(&ProviderConfig {
account: Some(RecvAccount {
platform: None,
address,
}),
..ProviderConfig::default()
})
.await?;
}
Expand Down
Loading

0 comments on commit 8d41ac7

Please sign in to comment.