Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

refactor!: Reorganize exports and modules exposed #102

Merged
merged 7 commits into from
Apr 4, 2022
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 3 additions & 8 deletions examples/src/ref_finance.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::{collections::HashMap, convert::TryInto};

use near_units::{parse_gas, parse_near};
use workspaces::network::Sandbox;
use workspaces::{prelude::*, BlockHeight, DevNetwork};
use workspaces::{Account, AccountId, Contract, Network, Worker};

Expand All @@ -15,10 +16,7 @@ const BLOCK_HEIGHT: BlockHeight = 50_000_000;

/// Pull down the ref-finance contract and deploy it to the sandbox network,
/// initializing it with all data required to run the tests.
async fn create_ref(
owner: &Account,
worker: &Worker<impl Network + StatePatcher>,
) -> anyhow::Result<Contract> {
async fn create_ref(owner: &Account, worker: &Worker<Sandbox>) -> anyhow::Result<Contract> {
let mainnet = workspaces::mainnet_archival();
let ref_finance_id: AccountId = REF_FINANCE_ACCOUNT_ID.parse()?;

Expand Down Expand Up @@ -56,10 +54,7 @@ async fn create_ref(
}

/// Pull down the WNear contract from mainnet and initilize it with our own metadata.
async fn create_wnear(
owner: &Account,
worker: &Worker<impl Network + StatePatcher>,
) -> anyhow::Result<Contract> {
async fn create_wnear(owner: &Account, worker: &Worker<Sandbox>) -> anyhow::Result<Contract> {
let mainnet = workspaces::mainnet_archival();
let wnear_id: AccountId = "wrap.near".to_string().try_into()?;
let wnear = worker
Expand Down
10 changes: 6 additions & 4 deletions workspaces/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,18 @@ mod cargo;
#[cfg(feature = "unstable")]
pub use cargo::compile_project;

mod network;
mod rpc;
mod types;
mod worker;

pub mod network;
pub mod operations;
pub mod prelude;
pub mod result;

pub use network::result;
pub use network::transaction::Function;
pub use network::{Account, AccountDetails, Block, Contract, DevNetwork, Network};
pub use network::variants::{DevNetwork, Network};
pub use types::account::{Account, AccountDetails, Contract};
pub use types::block::Block;
pub use types::{AccessKey, AccountId, BlockHeight, CryptoHash, InMemorySigner};
pub use worker::{
mainnet, mainnet_archival, sandbox, testnet, testnet_archival, with_mainnet,
Expand Down
5 changes: 3 additions & 2 deletions workspaces/src/network/mainnet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ use std::path::PathBuf;
use async_trait::async_trait;

use crate::network::Info;
use crate::network::{Account, CallExecution, NetworkClient, NetworkInfo, TopLevelAccountCreator};
use crate::network::{NetworkClient, NetworkInfo, TopLevelAccountCreator};
use crate::result::CallExecution;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this type not exposed? It is returned by exposed functions. So if a user wants to make a function that returns the result of one of the exposed function they reference the type.

Copy link
Contributor Author

@austinabell austinabell Apr 4, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What are you referring to? This is just a type that wraps the type returned that includes metadata.

Edit: Also confused on what you're asking. It is exposed

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry I meant from the crate: https://github.com/near/workspaces-rs/pull/102/files#diff-f2509a15c16bf20cbd905fc2d19c6b77363687408bf1020327da68936ec19ef9

Account exposes CallExecutionDetails and CallExecution, but they aren't exported.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

those are exposed under the result module which we have exported via pub mod result; in lib.rs

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah I see thanks!

use crate::rpc::client::Client;
use crate::types::{AccountId, SecretKey};
use crate::Contract;
use crate::{Account, Contract};

const RPC_URL: &str = "https://rpc.mainnet.near.org";
const ARCHIVAL_URL: &str = "https://archival-rpc.mainnet.near.org";
Expand Down
160 changes: 13 additions & 147 deletions workspaces/src/network/mod.rs
Original file line number Diff line number Diff line change
@@ -1,154 +1,20 @@
mod account;
mod block;
//! All builtin network types and traits.
//!
//! Currently the builtin network types are [`Mainnet`], [`Testnet`], and [`Sandbox`].

mod info;
mod mainnet;
pub mod result;
mod sandbox;
mod server;
mod testnet;
pub(crate) mod variants;

pub mod transaction;

use async_trait::async_trait;

use near_jsonrpc_client::methods::sandbox_patch_state::RpcSandboxPatchStateRequest;
use near_primitives::state_record::StateRecord;

pub(crate) use crate::network::info::Info;
use crate::rpc::client::Client;
use crate::rpc::patch::ImportContractTransaction;
use crate::types::{AccountId, KeyType, SecretKey};
use crate::Worker;

pub use crate::network::account::{Account, AccountDetails, Contract};
pub use crate::network::block::Block;
pub use crate::network::mainnet::Mainnet;
pub use crate::network::result::{CallExecution, CallExecutionDetails, ViewResultDetails};
pub use crate::network::sandbox::Sandbox;
pub use crate::network::testnet::Testnet;

pub(crate) const DEV_ACCOUNT_SEED: &str = "testificate";

pub trait NetworkClient {
fn client(&self) -> &Client;
}

pub trait NetworkInfo {
fn info(&self) -> &Info;
}

#[async_trait]
pub trait TopLevelAccountCreator {
async fn create_tla(
&self,
id: AccountId,
sk: SecretKey,
) -> anyhow::Result<CallExecution<Account>>;

async fn create_tla_and_deploy(
&self,
id: AccountId,
sk: SecretKey,
wasm: &[u8],
) -> anyhow::Result<CallExecution<Contract>>;
}

// NOTE: Not all networks/runtimes will have the ability to be able to do dev_deploy.
// This trait acts as segmented boundary for only specific networks such as sandbox and testnet.
pub trait AllowDevAccountCreation {}

#[async_trait]
pub trait DevAccountDeployer {
async fn dev_generate(&self) -> (AccountId, SecretKey);
async fn dev_create_account(&self) -> anyhow::Result<Account>;
async fn dev_deploy(&self, wasm: &[u8]) -> anyhow::Result<Contract>;
}

#[async_trait]
impl<T> DevAccountDeployer for T
where
T: TopLevelAccountCreator + NetworkInfo + AllowDevAccountCreation + Send + Sync,
{
async fn dev_generate(&self) -> (AccountId, SecretKey) {
let id = crate::rpc::tool::random_account_id();
let sk = SecretKey::from_seed(KeyType::ED25519, DEV_ACCOUNT_SEED);
(id, sk)
}

async fn dev_create_account(&self) -> anyhow::Result<Account> {
let (id, sk) = self.dev_generate().await;
let account = self.create_tla(id.clone(), sk).await?;
account.into()
}

async fn dev_deploy(&self, wasm: &[u8]) -> anyhow::Result<Contract> {
let (id, sk) = self.dev_generate().await;
let contract = self.create_tla_and_deploy(id.clone(), sk, wasm).await?;
contract.into()
}
}

pub trait AllowStatePatching {}

#[async_trait]
pub trait StatePatcher {
async fn patch_state(
&self,
contract_id: &AccountId,
key: &[u8],
value: &[u8],
) -> anyhow::Result<()>;

fn import_contract<'a, 'b>(
&'b self,
id: &AccountId,
worker: &'a Worker<impl Network>,
) -> ImportContractTransaction<'a, 'b>;
}

#[async_trait]
impl<T> StatePatcher for T
where
T: AllowStatePatching + NetworkClient + Send + Sync,
{
async fn patch_state(
&self,
contract_id: &AccountId,
key: &[u8],
value: &[u8],
) -> anyhow::Result<()> {
let state = StateRecord::Data {
account_id: contract_id.to_owned(),
data_key: key.to_vec(),
value: value.to_vec(),
};
let records = vec![state];

// NOTE: RpcSandboxPatchStateResponse is an empty struct with no fields, so don't do anything with it:
let _patch_resp = self
.client()
.query(&RpcSandboxPatchStateRequest { records })
.await
.map_err(|err| anyhow::anyhow!("Failed to patch state: {:?}", err))?;

Ok(())
}

fn import_contract<'a, 'b>(
&'b self,
id: &AccountId,
worker: &'a Worker<impl Network>,
) -> ImportContractTransaction<'a, 'b> {
ImportContractTransaction::new(id.to_owned(), worker.client(), self.client())
}
}

pub trait Network: TopLevelAccountCreator + NetworkInfo + NetworkClient + Send + Sync {}

impl<T> Network for T where T: TopLevelAccountCreator + NetworkInfo + NetworkClient + Send + Sync {}

/// DevNetwork is a Network that can call into `dev_create` and `dev_deploy` to create developer accounts.
pub trait DevNetwork: AllowDevAccountCreation + Network {}
pub(crate) use variants::DEV_ACCOUNT_SEED;

// Implemented by default if we have `AllowDevAccountCreation`
impl<T> DevNetwork for T where T: AllowDevAccountCreation + Network {}
pub use self::info::Info;
pub use self::mainnet::Mainnet;
pub use self::sandbox::Sandbox;
pub use self::testnet::Testnet;
pub use self::variants::{
AllowDevAccountCreation, DevAccountDeployer, NetworkClient, NetworkInfo, TopLevelAccountCreator,
};
10 changes: 3 additions & 7 deletions workspaces/src/network/sandbox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,13 @@ use std::str::FromStr;

use async_trait::async_trait;

use super::{
Account, AllowDevAccountCreation, AllowStatePatching, CallExecution, Contract, NetworkClient,
NetworkInfo, TopLevelAccountCreator,
};

use super::{AllowDevAccountCreation, NetworkClient, NetworkInfo, TopLevelAccountCreator};
use crate::network::server::SandboxServer;
use crate::network::Info;
use crate::result::CallExecution;
use crate::rpc::client::Client;
use crate::types::{AccountId, Balance, InMemorySigner, SecretKey};
use crate::{Account, Contract};

// Constant taken from nearcore crate to avoid dependency
pub(crate) const NEAR_BASE: Balance = 1_000_000_000_000_000_000_000_000;
Expand Down Expand Up @@ -58,8 +56,6 @@ impl Sandbox {
}
}

impl AllowStatePatching for Sandbox {}

impl AllowDevAccountCreation for Sandbox {}

#[async_trait]
Expand Down
9 changes: 3 additions & 6 deletions workspaces/src/network/testnet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,11 @@ use url::Url;
use near_primitives::views::{ExecutionStatusView, FinalExecutionStatus};

use crate::network::Info;
use crate::network::{
Account, AllowDevAccountCreation, CallExecution, CallExecutionDetails, NetworkClient,
NetworkInfo, TopLevelAccountCreator,
};
use crate::result::ExecutionOutcome;
use crate::network::{AllowDevAccountCreation, NetworkClient, NetworkInfo, TopLevelAccountCreator};
use crate::result::{CallExecution, CallExecutionDetails, ExecutionOutcome};
use crate::rpc::{client::Client, tool};
use crate::types::{AccountId, InMemorySigner, SecretKey};
use crate::{Contract, CryptoHash};
use crate::{Account, Contract, CryptoHash};

const RPC_URL: &str = "https://rpc.testnet.near.org";
const HELPER_URL: &str = "https://helper.testnet.near.org";
Expand Down
77 changes: 77 additions & 0 deletions workspaces/src/network/variants.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
use crate::network::Info;
use crate::result::CallExecution;
use crate::rpc::client::Client;
use crate::types::{AccountId, KeyType, SecretKey};
use crate::{Account, Contract};
use async_trait::async_trait;

pub(crate) const DEV_ACCOUNT_SEED: &str = "testificate";

pub trait NetworkClient {
fn client(&self) -> &Client;
}

pub trait NetworkInfo {
fn info(&self) -> &Info;
}

#[async_trait]
pub trait TopLevelAccountCreator {
async fn create_tla(
&self,
id: AccountId,
sk: SecretKey,
) -> anyhow::Result<CallExecution<Account>>;

async fn create_tla_and_deploy(
&self,
id: AccountId,
sk: SecretKey,
wasm: &[u8],
) -> anyhow::Result<CallExecution<Contract>>;
}

// NOTE: Not all networks/runtimes will have the ability to be able to do dev_deploy.
// This trait acts as segmented boundary for only specific networks such as sandbox and testnet.
pub trait AllowDevAccountCreation {}

#[async_trait]
pub trait DevAccountDeployer {
async fn dev_generate(&self) -> (AccountId, SecretKey);
async fn dev_create_account(&self) -> anyhow::Result<Account>;
async fn dev_deploy(&self, wasm: &[u8]) -> anyhow::Result<Contract>;
}

#[async_trait]
impl<T> DevAccountDeployer for T
where
T: TopLevelAccountCreator + NetworkInfo + AllowDevAccountCreation + Send + Sync,
{
async fn dev_generate(&self) -> (AccountId, SecretKey) {
let id = crate::rpc::tool::random_account_id();
let sk = SecretKey::from_seed(KeyType::ED25519, DEV_ACCOUNT_SEED);
(id, sk)
}

async fn dev_create_account(&self) -> anyhow::Result<Account> {
let (id, sk) = self.dev_generate().await;
let account = self.create_tla(id.clone(), sk).await?;
account.into()
}

async fn dev_deploy(&self, wasm: &[u8]) -> anyhow::Result<Contract> {
let (id, sk) = self.dev_generate().await;
let contract = self.create_tla_and_deploy(id.clone(), sk, wasm).await?;
contract.into()
}
}

pub trait Network: TopLevelAccountCreator + NetworkInfo + NetworkClient + Send + Sync {}

impl<T> Network for T where T: TopLevelAccountCreator + NetworkInfo + NetworkClient + Send + Sync {}

/// DevNetwork is a Network that can call into `dev_create` and `dev_deploy` to create developer accounts.
pub trait DevNetwork: AllowDevAccountCreation + Network {}

// Implemented by default if we have `AllowDevAccountCreation`
impl<T> DevNetwork for T where T: AllowDevAccountCreation + Network {}
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
use std::convert::TryInto;

use near_crypto::KeyType;
use near_primitives::transaction::{
Action, AddKeyAction, CreateAccountAction, DeleteAccountAction, DeleteKeyAction,
DeployContractAction, FunctionCallAction, StakeAction, TransferAction,
};
use near_primitives::views::FinalExecutionOutcomeView;
//! All operation types that are generated/used when making transactions or view calls.

use crate::network::{CallExecution, CallExecutionDetails, Network, ViewResultDetails};
use crate::result::{CallExecution, CallExecutionDetails, ViewResultDetails};
use crate::rpc::client::{
send_batch_tx_and_retry, Client, DEFAULT_CALL_DEPOSIT, DEFAULT_CALL_FN_GAS,
};
use crate::types::{AccessKey, AccountId, Balance, Gas, InMemorySigner, PublicKey, SecretKey};
use crate::worker::Worker;
use crate::Account;
use crate::Network;
use near_crypto::KeyType;
use near_primitives::transaction::{
Action, AddKeyAction, CreateAccountAction, DeleteAccountAction, DeleteKeyAction,
DeployContractAction, FunctionCallAction, StakeAction, TransferAction,
};
use near_primitives::views::FinalExecutionOutcomeView;
use std::convert::TryInto;

const MAX_GAS: Gas = 300_000_000_000_000;

Expand Down
2 changes: 1 addition & 1 deletion workspaces/src/prelude.rs
Original file line number Diff line number Diff line change
@@ -1 +1 @@
pub use crate::network::{DevAccountDeployer, StatePatcher, TopLevelAccountCreator};
pub use crate::network::{DevAccountDeployer, TopLevelAccountCreator};
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
//! Result and execution types from results of RPC calls to the network.

use near_account_id::AccountId;
use near_primitives::views::{
CallResult, ExecutionOutcomeWithIdView, ExecutionStatusView, FinalExecutionOutcomeView,
Expand Down
Loading