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: switch to near-gas crate for Gas where possible #305

Merged
merged 9 commits into from
Sep 24, 2023
Merged
Show file tree
Hide file tree
Changes from 2 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
5 changes: 5 additions & 0 deletions examples/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ anyhow = "1.0"
borsh = "0.10"
maplit = "1.0"
near-units = "0.2.0"
near-gas = { git = "https://github.com/iho/near-gas.git", rev = "1c6574ddc1d1de82f79685441e55831f95936897", features = [
"serde",
"borsh",
"schemars",
] }
near-jsonrpc-primitives = "0.17"
near-primitives = "0.17"
serde = "1.0"
Expand Down
5 changes: 3 additions & 2 deletions examples/src/croncat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
// This is perfect to showcase cron.cat which will schedule calling into contract functions
// at a set amount of time we supply.

use near_gas::NearGas;
use near_units::{parse_gas, parse_near};
use serde::Deserialize;
use serde_json::json;
Expand Down Expand Up @@ -134,7 +135,7 @@ pub async fn run_scheduled_tasks(
// here, so the agent should be executing the task.
agent
.call(contract.id(), "proxy_call")
.gas(parse_gas!("200 Tgas") as u64)
.gas(NearGas::from_gas(parse_gas!("200 Tgas") as u64))
frol marked this conversation as resolved.
Show resolved Hide resolved
.transact()
.await?
.into_result()?;
Expand All @@ -144,7 +145,7 @@ pub async fn run_scheduled_tasks(
worker.fast_forward(4500).await?;
agent
.call(contract.id(), "proxy_call")
.gas(parse_gas!("200 Tgas") as u64)
.gas(NearGas::from_gas(parse_gas!("200 Tgas") as u64))
.transact()
.await?
.into_result()?;
Expand Down
7 changes: 4 additions & 3 deletions examples/src/ref_finance.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::collections::HashMap;
use std::convert::TryInto;

use near_gas::NearGas;
use near_units::{parse_gas, parse_near};
use serde_json::json;
use workspaces::network::Sandbox;
Expand Down Expand Up @@ -173,7 +174,7 @@ async fn deposit_tokens(
"amount": amount.to_string(),
"msg": "",
}))
.gas(parse_gas!("200 Tgas") as u64)
.gas(NearGas::from_gas(parse_gas!("200 Tgas") as u64))
iho marked this conversation as resolved.
Show resolved Hide resolved
.deposit(1)
.transact()
.await?
Expand Down Expand Up @@ -310,7 +311,7 @@ async fn main() -> anyhow::Result<()> {
})],
}))
.deposit(1)
.gas(parse_gas!("100 Tgas") as u64)
.gas(NearGas::from_gas(parse_gas!("100 Tgas") as u64))
iho marked this conversation as resolved.
Show resolved Hide resolved
.transact()
.await?;
let gas_burnt = actual_out.total_gas_burnt;
Expand All @@ -320,7 +321,7 @@ async fn main() -> anyhow::Result<()> {
actual_out
);
assert_eq!(actual_out, expected_return);
println!("Gas burnt from swapping: {}", gas_burnt);
println!("Gas burnt from swapping: {}", gas_burnt.as_gas());
frol marked this conversation as resolved.
Show resolved Hide resolved

///////////////////////////////////////////////////////////////////////////
// Stage 5: See that our swap tokens reflect in our deposits
Expand Down
4 changes: 2 additions & 2 deletions examples/src/various_queries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ async fn main() -> anyhow::Result<()> {
.into_result()?;
println!(
"Bob burnt {} gas callling into `set_status('Hello')`",
outcome.total_gas_burnt
outcome.total_gas_burnt.as_gas()
);

// let's get a reference point to the chain at it's current state, so we can reference it back later
Expand All @@ -67,7 +67,7 @@ async fn main() -> anyhow::Result<()> {
.into_result()?;
println!(
"Bob burnt {} gas callling into `set_status('World')`",
outcome.total_gas_burnt
outcome.total_gas_burnt.as_gas()
);

// Then view that it indeed has changed:
Expand Down
7 changes: 6 additions & 1 deletion workspaces/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ near-jsonrpc-primitives = "0.17"
near-jsonrpc-client = { version = "0.6", features = ["sandbox"] }
near-sandbox-utils = "0.6.2"
near-chain-configs = { version = "0.17.0", optional = true }
near-gas = { git = "https://github.com/iho/near-gas.git", rev = "1c6574ddc1d1de82f79685441e55831f95936897", features = [
"serde",
"borsh",
"schemars",
] }

[build-dependencies]
near-sandbox-utils = "0.6.2"
Expand All @@ -58,7 +63,7 @@ tracing-subscriber = { version = "0.3.5", features = ["env-filter"] }

[features]
default = ["install", "interop_sdk"]
install = [] # Install the sandbox binary during compile time
install = [] # Install the sandbox binary during compile time
interop_sdk = ["near-sdk"]
unstable = ["cargo_metadata"]
experimental = ["near-chain-configs"]
Expand Down
2 changes: 1 addition & 1 deletion workspaces/src/network/sandbox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ 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 = 100 * NEAR_BASE;
const DEFAULT_DEPOSIT: Balance = NEAR_BASE * 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`]
Expand Down
5 changes: 3 additions & 2 deletions workspaces/src/network/testnet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::path::PathBuf;
use std::str::FromStr;

use async_trait::async_trait;
use near_gas::NearGas;
use url::Url;

use near_primitives::views::ExecutionStatusView;
Expand Down Expand Up @@ -83,7 +84,7 @@ impl TopLevelAccountCreator for Testnet {
details: ExecutionFinalResult {
// We technically have not burnt any gas ourselves since someone else paid to
// create the account for us in testnet when we used the Helper contract.
total_gas_burnt: 0,
total_gas_burnt: NearGas::from_gas(0),

status: near_primitives::views::FinalExecutionStatus::SuccessValue(Vec::new()),
details: ExecutionDetails {
Expand All @@ -92,7 +93,7 @@ impl TopLevelAccountCreator for Testnet {
block_hash: CryptoHash::default(),
logs: Vec::new(),
receipt_ids: Vec::new(),
gas_burnt: 0,
gas_burnt: NearGas::from_gas(0),
tokens_burnt: 0,
executor_id: "testnet".parse().unwrap(),
status: ExecutionStatusView::SuccessValue(Vec::new()),
Expand Down
15 changes: 9 additions & 6 deletions workspaces/src/operations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ use crate::worker::Worker;
use crate::{Account, CryptoHash, Network};

use near_account_id::ParseAccountError;
use near_gas::NearGas;
use near_jsonrpc_client::errors::{JsonRpcError, JsonRpcServerError};
use near_jsonrpc_client::methods::tx::RpcTransactionError;
use near_primitives::transaction::{
Expand All @@ -27,7 +28,7 @@ use std::future::IntoFuture;
use std::pin::Pin;
use std::task::Poll;

const MAX_GAS: Gas = 300_000_000_000_000;
const MAX_GAS: NearGas = NearGas::from_gas(300_000_000_000_000);
iho marked this conversation as resolved.
Show resolved Hide resolved

/// A set of arguments we can provide to a transaction, containing
/// the function name, arguments, the amount of gas to use and deposit.
Expand Down Expand Up @@ -165,7 +166,7 @@ impl Transaction {
method_name: function.name.to_string(),
args,
deposit: function.deposit,
gas: function.gas,
gas: function.gas.as_gas(),
}));
}

Expand Down Expand Up @@ -214,6 +215,7 @@ impl Transaction {
/// An action which stakes the signer's tokens and setups a validator public key.
pub fn stake(mut self, stake: Balance, pk: PublicKey) -> Self {
if let Ok(actions) = &mut self.actions {
let stake = stake;
frol marked this conversation as resolved.
Show resolved Hide resolved
actions.push(
StakeAction {
stake,
Expand All @@ -228,6 +230,7 @@ impl Transaction {
/// Transfer `deposit` amount from `signer`'s account into `receiver_id`'s account.
pub fn transfer(mut self, deposit: Balance) -> Self {
if let Ok(actions) = &mut self.actions {
let deposit = deposit;
actions.push(TransferAction { deposit }.into());
}
self
Expand Down Expand Up @@ -313,13 +316,13 @@ impl CallTransaction {

/// Specify the amount of tokens to be deposited where `deposit` is the amount of
/// tokens in yocto near.
pub fn deposit(mut self, deposit: u128) -> Self {
pub fn deposit(mut self, deposit: Balance) -> Self {
self.function = self.function.deposit(deposit);
self
}

/// Specify the amount of gas to be used where `gas` is the amount of gas in yocto near.
pub fn gas(mut self, gas: u64) -> Self {
pub fn gas(mut self, gas: NearGas) -> Self {
self.function = self.function.gas(gas);
self
}
Expand All @@ -340,7 +343,7 @@ impl CallTransaction {
&self.contract_id,
self.function.name.to_string(),
self.function.args?,
self.function.gas,
self.function.gas.as_gas(),
self.function.deposit,
)
.await
Expand All @@ -363,7 +366,7 @@ impl CallTransaction {
vec![FunctionCallAction {
args: self.function.args?,
method_name: self.function.name,
gas: self.function.gas,
gas: self.function.gas.as_gas(),
deposit: self.function.deposit,
}
.into()],
Expand Down
4 changes: 3 additions & 1 deletion workspaces/src/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
use std::fmt;

use near_account_id::AccountId;
use near_gas::NearGas;
use near_primitives::errors::TxExecutionError;
use near_primitives::views::{
CallResult, ExecutionOutcomeWithIdView, ExecutionStatusView, FinalExecutionOutcomeView,
Expand Down Expand Up @@ -186,6 +187,7 @@ impl ExecutionFinalResult {
.map(ExecutionOutcome::from)
.collect();

let total_gas_burnt = NearGas::from_gas(total_gas_burnt);
Self {
total_gas_burnt,
status: view.status,
Expand Down Expand Up @@ -533,7 +535,7 @@ impl From<ExecutionOutcomeWithIdView> for ExecutionOutcome {
.into_iter()
.map(|c| CryptoHash(c.0))
.collect(),
gas_burnt: view.outcome.gas_burnt,
gas_burnt: NearGas::from_gas(view.outcome.gas_burnt),
tokens_burnt: view.outcome.tokens_burnt,
executor_id: view.outcome.executor_id,
status: view.outcome.status,
Expand Down
3 changes: 2 additions & 1 deletion workspaces/src/rpc/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::fmt::Debug;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;

use near_gas::NearGas;
use tokio::sync::RwLock;
use tokio_retry::strategy::{jitter, ExponentialBackoff};
use tokio_retry::Retry;
Expand Down Expand Up @@ -48,7 +49,7 @@ use crate::result::Result;
use crate::types::{AccountId, InMemorySigner, Nonce, PublicKey};
use crate::{Network, Worker};

pub(crate) const DEFAULT_CALL_FN_GAS: Gas = 10_000_000_000_000;
pub(crate) const DEFAULT_CALL_FN_GAS: NearGas = NearGas::from_gas(10_000_000_000_000);
iho marked this conversation as resolved.
Show resolved Hide resolved
pub(crate) const DEFAULT_CALL_DEPOSIT: Balance = 0;

/// A client that wraps around [`JsonRpcClient`], and provides more capabilities such
Expand Down
5 changes: 3 additions & 2 deletions workspaces/src/types/chunk.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use near_account_id::AccountId;
use near_gas::NearGas;
use near_primitives::views::ChunkView;

use crate::types::{Balance, Gas, ShardId};
Expand Down Expand Up @@ -48,8 +49,8 @@ impl From<ChunkView> for Chunk {
height_created: view.header.height_created,
height_included: view.header.height_included,
shard_id: view.header.shard_id,
gas_used: view.header.gas_used,
gas_limit: view.header.gas_limit,
gas_used: NearGas::from_gas(view.header.gas_used),
gas_limit: NearGas::from_gas(view.header.gas_limit),
balance_burnt: view.header.balance_burnt,

tx_root: view.header.tx_root.into(),
Expand Down
4 changes: 2 additions & 2 deletions workspaces/src/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use std::str::FromStr;

use borsh::{BorshDeserialize, BorshSerialize};
pub use near_account_id::AccountId;

use serde::{Deserialize, Serialize};
use sha2::Digest;

Expand All @@ -31,8 +32,7 @@ pub type Nonce = u64;

/// Gas units used in the execution of transactions. For a more in depth description of
/// how and where it can be used, visit [Gas](https://docs.near.org/docs/concepts/gas).
pub type Gas = u64;

pub use near_gas::NearGas as Gas;
/// Balance is type for storing amounts of tokens. Usually represents the amount of tokens
/// in yoctoNear (1e-24).
pub type Balance = u128;
Expand Down
3 changes: 2 additions & 1 deletion workspaces/tests/optional_args.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#![recursion_limit = "256"]
use near_gas::NearGas;
use near_units::parse_near;
use test_log::test;
use workspaces::{Contract, DevNetwork, Worker};
Expand Down Expand Up @@ -37,7 +38,7 @@ async fn test_empty_args_error() -> anyhow::Result<()> {
if let Some(exeuction_err) = res.err() {
assert!(format!("{}", exeuction_err).contains("Failed to deserialize input from JSON"));
assert!(
exeuction_err.total_gas_burnt > 0,
exeuction_err.total_gas_burnt > NearGas::from_gas(0),
"Gas is still burnt for transaction although inputs are incorrect"
);
} else {
Expand Down
Loading