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: Migrate to NearToken #333

Merged
merged 10 commits into from
Oct 29, 2023
Merged
Show file tree
Hide file tree
Changes from 7 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
10 changes: 4 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,6 @@ A simple test to get us going and familiar with `near-workspaces` framework. Her
First, we need to declare some imports for convenience.

```rust
// macro allowing us to convert human readable units to workspace units.
use near_units::parse_near;

// macro allowing us to convert args into JSON bytes to be read by the contract.
use serde_json::json;
```
Expand Down Expand Up @@ -197,7 +194,7 @@ We can check the balance of our accounts like so:
```rs
#[test(tokio::test)]
async fn test_contract_transfer() -> anyhow::Result<()> {
let transfer_amount = near_units::parse_near!("0.1");
let transfer_amount = NearToken::from_millinear(100);
let worker = near_workspaces::sandbox().await?;

let contract = worker
Expand Down Expand Up @@ -236,7 +233,7 @@ This example will showcase spooning state from a testnet contract into our local
We will first start with the usual imports:

```rust
use near_units::{parse_gas, parse_near};
use near_units::parse_gas;
frol marked this conversation as resolved.
Show resolved Hide resolved
use near_workspaces::network::Sandbox;
use near_workspaces::{Account, AccountId, BlockHeight, Contract, Worker};
```
Expand Down Expand Up @@ -267,9 +264,10 @@ Following that we will have to init the contract again with our own metadata. Th

```rust

use near_token::NearToken;
frol marked this conversation as resolved.
Show resolved Hide resolved
let contract = worker
.import_contract(&contract_id, &testnet)
.initial_balance(parse_near!("1000 N"))
.initial_balance(NearToken::from_near(1000))
.block_height(BLOCK_HEIGHT)
.transact()
.await?;
Expand Down
25 changes: 15 additions & 10 deletions examples/src/croncat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
// at a set amount of time we supply.

use near_gas::NearGas;
use near_units::parse_near;
use near_workspaces::network::Sandbox;
use near_workspaces::types::NearToken;
use near_workspaces::{Account, AccountId, Contract, Worker};
use serde::Deserialize;
use serde_json::json;
Expand Down Expand Up @@ -36,8 +36,7 @@ pub struct Agent {
pub payable_account_id: AccountId,
// NOTE: display_fromstr is used to deserialize from a U128 type returned from the contract
// which is represented as a string there, and then converted into a rust u128 here.
#[serde(with = "serde_with::rust::display_fromstr")]
pub balance: u128,
pub balance: NearToken,
#[serde(with = "serde_with::rust::display_fromstr")]
pub total_tasks_executed: u128,
pub last_missed_slot: u128,
Expand Down Expand Up @@ -74,7 +73,7 @@ async fn main() -> anyhow::Result<()> {
"recurring": true,
}))
.max_gas()
.deposit(parse_near!("1 N"))
.deposit(NearToken::from_near(1))
.transact()
.await?;
println!("-- outcome: {:#?}\n", outcome);
Expand All @@ -83,7 +82,7 @@ async fn main() -> anyhow::Result<()> {
// for executing it:
let agent_1 = croncat
.create_subaccount("agent_1")
.initial_balance(parse_near!("10 N"))
.initial_balance(NearToken::from_near(10))
.transact()
.await?
.into_result()?;
Expand All @@ -105,7 +104,7 @@ pub async fn run_scheduled_tasks(
let outcome = agent
.call(contract.id(), "register_agent")
.args_json(json!({}))
.deposit(parse_near!("0.00226 N"))
.deposit(NearToken::from_yoctonear(2260000000000000000000u128))
frol marked this conversation as resolved.
Show resolved Hide resolved
.transact()
.await?;
println!("Registering agent outcome: {:#?}\n", outcome);
Expand Down Expand Up @@ -159,7 +158,10 @@ pub async fn run_scheduled_tasks(
.json::<Option<Agent>>()?
.unwrap();
println!("Agent details after completing task: {:#?}", agent_details);
assert_eq!(agent_details.balance, parse_near!("0.00386 N"));
assert_eq!(
agent_details.balance,
NearToken::from_yoctonear(3860000000000000000000u128)
);
let before_withdraw = agent_details.balance;

// Withdraw the reward from completing the task to our agent's account
Expand All @@ -179,18 +181,21 @@ pub async fn run_scheduled_tasks(
.json::<Option<Agent>>()?
.unwrap();
println!("Agent details after withdrawing task: {:#?}", agent_details);
assert_eq!(agent_details.balance, parse_near!("0.00226 N"));
assert_eq!(
agent_details.balance,
NearToken::from_yoctonear(2260000000000000000000u128)
);

// This shows how much the agent has profitted from executing the task:
println!(
"Agent profitted {} yN and has been transferred to the agent's account",
before_withdraw - agent_details.balance
before_withdraw.as_yoctonear() - agent_details.balance.as_yoctonear()
);

// Not that everything is done, let's cleanup and unregister the agent from doing anything.
agent
.call(contract.id(), "unregister_agent")
.deposit(parse_near!("1y"))
.deposit(NearToken::from_yoctonear(1))
.transact()
.await?
.into_result()?;
Expand Down
3 changes: 2 additions & 1 deletion examples/src/nft.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use near_workspaces::types::NearToken;
use serde_json::json;

const NFT_WASM_FILEPATH: &str = "./examples/res/non_fungible_token.wasm";
Expand All @@ -18,7 +19,7 @@ async fn main() -> anyhow::Result<()> {

println!("new_default_meta outcome: {:#?}", outcome);

let deposit = 10000000000000000000000;
let deposit = NearToken::from_yoctonear(10000000000000000000000);
let outcome = contract
.call("nft_mint")
.args_json(json!({
Expand Down
48 changes: 24 additions & 24 deletions examples/src/ref_finance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ use std::collections::HashMap;
use std::convert::TryInto;

use near_gas::NearGas;
use near_units::parse_near;
use near_workspaces::network::Sandbox;
use near_workspaces::types::NearToken;
use near_workspaces::{Account, AccountId, Contract, Worker};
use near_workspaces::{BlockHeight, DevNetwork};
use serde_json::json;
Expand All @@ -27,7 +27,7 @@ async fn create_ref(owner: &Account, worker: &Worker<Sandbox>) -> anyhow::Result
// to be overriding the initial balance with 1000N instead of what's on mainnet.
let ref_finance = worker
.import_contract(&ref_finance_id, &mainnet)
.initial_balance(parse_near!("1000 N"))
.initial_balance(NearToken::from_near(1000))
.block_height(BLOCK_HEIGHT)
.transact()
.await?;
Expand All @@ -50,7 +50,7 @@ async fn create_ref(owner: &Account, worker: &Worker<Sandbox>) -> anyhow::Result
owner
.call(ref_finance.id(), "storage_deposit")
.args_json(json!({}))
.deposit(parse_near!("30 mN"))
.deposit(NearToken::from_millinear(30))
.transact()
.await?
.into_result()?;
Expand All @@ -77,14 +77,14 @@ async fn create_wnear(owner: &Account, worker: &Worker<Sandbox>) -> anyhow::Resu
owner
.call(wnear.id(), "storage_deposit")
.args_json(json!({}))
.deposit(parse_near!("0.008 N"))
.deposit(NearToken::from_millinear(8))
.transact()
.await?
.into_result()?;

owner
.call(wnear.id(), "near_deposit")
.deposit(parse_near!("200 N"))
.deposit(NearToken::from_near(200))
.transact()
.await?
.into_result()?;
Expand Down Expand Up @@ -118,7 +118,7 @@ async fn create_pool_with_liquidity(
"tokens": token_ids,
"fee": 25
}))
.deposit(parse_near!("3 mN"))
.deposit(NearToken::from_millinear(3))
.transact()
.await?
.json()?;
Expand All @@ -128,7 +128,7 @@ async fn create_pool_with_liquidity(
.args_json(json!({
"token_ids": token_ids,
}))
.deposit(1)
.deposit(NearToken::from_yoctonear(1))
.transact()
.await?
.into_result()?;
Expand All @@ -141,7 +141,7 @@ async fn create_pool_with_liquidity(
"pool_id": pool_id,
"amounts": token_amounts,
}))
.deposit(parse_near!("1 N"))
.deposit(NearToken::from_near(1))
.transact()
.await?
.into_result()?;
Expand All @@ -162,7 +162,7 @@ async fn deposit_tokens(
.args_json(json!({
"registration_only": true,
}))
.deposit(parse_near!("1 N"))
.deposit(NearToken::from_near(1))
.transact()
.await?
.into_result()?;
Expand All @@ -175,7 +175,7 @@ async fn deposit_tokens(
"msg": "",
}))
.gas(NearGas::from_tgas(200))
.deposit(1)
.deposit(NearToken::from_yoctonear(1))
.transact()
.await?
.into_result()?;
Expand All @@ -198,7 +198,7 @@ async fn create_custom_ft(
ft.call("new_default_meta")
.args_json(json!({
"owner_id": owner.id(),
"total_supply": parse_near!("1,000,000,000 N").to_string(),
"total_supply": NearToken::from_near(1_000_000_000),
}))
.transact()
.await?
Expand Down Expand Up @@ -229,8 +229,8 @@ async fn main() -> anyhow::Result<()> {
&owner,
&ref_finance,
maplit::hashmap! {
ft.id() => parse_near!("5 N"),
wnear.id() => parse_near!("10 N"),
ft.id() => NearToken::from_near(5).as_yoctonear(),
wnear.id() => NearToken::from_near(10).as_yoctonear(),
},
)
.await?;
Expand All @@ -244,8 +244,8 @@ async fn main() -> anyhow::Result<()> {
&owner,
&ref_finance,
maplit::hashmap! {
ft.id() => parse_near!("100 N"),
wnear.id() => parse_near!("100 N"),
ft.id() => NearToken::from_near(100).as_yoctonear(),
wnear.id() => NearToken::from_near(100).as_yoctonear(),
},
)
.await?;
Expand All @@ -254,7 +254,7 @@ async fn main() -> anyhow::Result<()> {
// Stage 3: View our deposited/transferred tokens in ref-finance
///////////////////////////////////////////////////////////////////////////

let ft_deposit: String = worker
let ft_deposit: NearToken = worker
.view(ref_finance.id(), "get_deposit")
.args_json(json!({
"account_id": owner.id(),
Expand All @@ -263,9 +263,9 @@ async fn main() -> anyhow::Result<()> {
.await?
.json()?;
println!("Current FT deposit: {}", ft_deposit);
assert_eq!(ft_deposit, parse_near!("100 N").to_string());
assert_eq!(ft_deposit, NearToken::from_near(100));

let wnear_deposit: String = worker
let wnear_deposit: NearToken = worker
.view(ref_finance.id(), "get_deposit")
.args_json(json!({
"account_id": owner.id(),
Expand All @@ -275,7 +275,7 @@ async fn main() -> anyhow::Result<()> {
.json()?;

println!("Current WNear deposit: {}", wnear_deposit);
assert_eq!(wnear_deposit, parse_near!("100 N").to_string());
assert_eq!(wnear_deposit, NearToken::from_near(100));

///////////////////////////////////////////////////////////////////////////
// Stage 4: Check how much our expected rate is for swapping and then swap
Expand All @@ -287,7 +287,7 @@ async fn main() -> anyhow::Result<()> {
"pool_id": pool_id,
"token_in": ft.id(),
"token_out": wnear.id(),
"amount_in": parse_near!("1 N").to_string(),
"amount_in": NearToken::from_near(1),
}))
.await?
.json()?;
Expand All @@ -305,11 +305,11 @@ async fn main() -> anyhow::Result<()> {
"pool_id": pool_id,
"token_in": ft.id(),
"token_out": wnear.id(),
"amount_in": parse_near!("1 N").to_string(),
"amount_in": NearToken::from_near(1),
"min_amount_out": "1",
})],
}))
.deposit(1)
.deposit(NearToken::from_yoctonear(1))
.gas(NearGas::from_tgas(100))
.transact()
.await?;
Expand All @@ -326,7 +326,7 @@ async fn main() -> anyhow::Result<()> {
// Stage 5: See that our swap tokens reflect in our deposits
///////////////////////////////////////////////////////////////////////////

let ft_deposit: String = worker
let ft_deposit: NearToken = worker
.view(ref_finance.id(), "get_deposit")
.args_json(json!({
"account_id": owner.id(),
Expand All @@ -335,7 +335,7 @@ async fn main() -> anyhow::Result<()> {
.await?
.json()?;
println!("New FT deposit after swap: {}", ft_deposit);
assert_eq!(ft_deposit, parse_near!("99 N").to_string());
assert_eq!(ft_deposit, NearToken::from_near(99));

let wnear_deposit: String = ref_finance
.view("get_deposit")
Expand Down
1 change: 1 addition & 0 deletions workspaces/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ tracing = "0.1"
url = { version = "2.2.2", features = ["serde"] }

near-gas = { version = "0.2.3", features = ["serde", "borsh", "schemars"] }
near-token = { version = "0.1.0", features = ["serde", "borsh", "schemars"] }
frol marked this conversation as resolved.
Show resolved Hide resolved
near-sdk = { version = "4.1", optional = true }
near-account-id = "0.17"
near-crypto = "0.17"
Expand Down
8 changes: 3 additions & 5 deletions workspaces/src/network/sandbox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,12 @@ use crate::network::server::SandboxServer;
use crate::network::Info;
use crate::result::{Execution, ExecutionFinalResult, Result};
use crate::rpc::client::Client;
use crate::types::{AccountId, Balance, InMemorySigner, SecretKey};
use crate::types::NearToken;
frol marked this conversation as resolved.
Show resolved Hide resolved
use crate::types::{AccountId, InMemorySigner, SecretKey};
use crate::{Account, Contract, Network, Worker};

// Constant taken from nearcore crate to avoid dependency
pub(crate) const NEAR_BASE: Balance = 1_000_000_000_000_000_000_000_000;

const DEFAULT_DEPOSIT: Balance = NEAR_BASE * 100;

const DEFAULT_DEPOSIT: NearToken = NearToken::from_near(100);
/// Local sandboxed environment/network, which can be used to test without interacting with
/// networks that are online such as mainnet and testnet. Look at [`workspaces::sandbox`]
/// for how to spin up a sandboxed network and interact with it.
Expand Down
4 changes: 2 additions & 2 deletions workspaces/src/network/testnet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use crate::network::Info;
use crate::network::{AllowDevAccountCreation, NetworkClient, NetworkInfo, TopLevelAccountCreator};
use crate::result::{Execution, ExecutionDetails, ExecutionFinalResult, ExecutionOutcome, Result};
use crate::rpc::{client::Client, tool};
use crate::types::{AccountId, InMemorySigner, SecretKey};
use crate::types::{AccountId, InMemorySigner, NearToken, SecretKey};
use crate::{Account, Contract, CryptoHash, Network, Worker};

/// URL to the testnet RPC node provided by near.org.
Expand Down Expand Up @@ -94,7 +94,7 @@ impl TopLevelAccountCreator for Testnet {
logs: Vec::new(),
receipt_ids: Vec::new(),
gas_burnt: NearGas::from_gas(0),
tokens_burnt: 0,
tokens_burnt: NearToken::from_near(0),
executor_id: "testnet".parse().unwrap(),
status: ExecutionStatusView::SuccessValue(Vec::new()),
},
Expand Down
Loading
Loading