Skip to content

Commit

Permalink
chore!: update nearcore crates from 0.17 -> 0.20 (#1130)
Browse files Browse the repository at this point in the history
  • Loading branch information
dj8yfo authored Jan 16, 2024
1 parent 1343059 commit 9ce0cdc
Show file tree
Hide file tree
Showing 17 changed files with 277 additions and 241 deletions.
11 changes: 1 addition & 10 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
strategy:
matrix:
platform: [ubuntu-latest, macos-latest]
toolchain: [stable, 1.69.0]
toolchain: [stable, 1.72.1]
steps:
- uses: actions/checkout@v3
- name: "${{ matrix.toolchain }} with rustfmt, and wasm32"
Expand All @@ -23,15 +23,6 @@ jobs:
toolchain: ${{ matrix.toolchain }}
default: true
target: wasm32-unknown-unknown
- name: downgrade `anstyle`,`anstyle-parse`,`anstyle-query`,`clap`,`clap_lex`, `home` crates to support older Rust toolchain
if: matrix.toolchain == '1.69.0'
run: |
cargo update -p anstyle --precise 1.0.2
cargo update -p anstyle-query --precise 1.0.0
cargo update -p anstyle-parse --precise 0.2.1
cargo update -p clap --precise 4.3.24
cargo update -p clap_lex --precise 0.5.0
cargo update -p home --precise 0.5.5
- uses: Swatinem/rust-cache@v1
- name: Test
run: cargo test --all --features unstable,legacy
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
<a href="https://crates.io/crates/near-sdk"><img src="https://img.shields.io/crates/v/near-sdk.svg?style=flat-square" alt="Crates.io version" /></a>
<a href="https://crates.io/crates/near-sdk"><img src="https://img.shields.io/crates/d/near-sdk.svg?style=flat-square" alt="Download" /></a>
<a href="https://docs.rs/near-sdk"><img src="https://docs.rs/near-sdk/badge.svg" alt="Reference Documentation" /></a>
<a href="https://blog.rust-lang.org/2023/04/20/Rust-1.69.0.html"><img src="https://img.shields.io/badge/rustc-1.69+-lightgray.svg" alt="MSRV" /></a>
<a href="https://blog.rust-lang.org/2023/08/24/Rust-1.72.0.html"><img src="https://img.shields.io/badge/rustc-1.72+-lightgray.svg" alt="MSRV" /></a>
<a href="https://discord.gg/gBtUFKR"><img src="https://img.shields.io/discord/490367152054992913.svg" alt="Join the community on Discord" /></a>
<a href="https://github.com/near/near-sdk-rs/actions"><img src="https://github.com/near/near-sdk-rs/actions/workflows/test.yml/badge.svg" alt="GitHub Actions Build" /></a>
</p>
Expand Down Expand Up @@ -260,7 +260,7 @@ State breaking changes (low-level serialization format of any data type) will be

### MSRV

The minimum supported Rust version is currently `1.69`. There are no guarantees that this will be upheld if a security patch release needs to come in that requires a Rust toolchain increase.
The minimum supported Rust version is currently `1.72`. There are no guarantees that this will be upheld if a security patch release needs to come in that requires a Rust toolchain increase.

## Contributing

Expand Down
14 changes: 8 additions & 6 deletions near-sdk/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,17 @@ wee_alloc = { version = "0.4.5", default-features = false, optional = true }
once_cell = { version = "1.17", default-features = false }

near-abi = { version = "0.4.0", features = ["__chunked-entries"], optional = true }
near-account-id = { version="1.0.0-alpha.4", features = ["serde", "borsh"] }
near-account-id = { version="1.0.0", features = ["serde", "borsh"] }
near-gas = { version = "0.2.3", features = ["serde", "borsh"] }
near-token = { version = "0.2.0", features = ["serde", "borsh"] }


[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
near-vm-logic = { version = "0.17", optional = true }
near-primitives-core = { version = "0.17", optional = true }
near-primitives = { version = "0.17", optional = true }
near-crypto = { version = "0.17", optional = true }
near-vm-runner = { version = "0.20", optional = true }
near-primitives-core = { version = "0.20", optional = true }
near-primitives = { version = "0.20", optional = true }
near-crypto = { version = "0.20", optional = true }
near-parameters = { version = "0.20", optional = true }

[dev-dependencies]
rand = "0.8.4"
Expand All @@ -63,7 +65,7 @@ expensive-debug = []
unstable = []
legacy = []
abi = ["borsh/unstable__schema", "near-abi", "schemars", "near-sdk-macros/abi", "near-account-id/abi", "near-gas/abi", "near-token/abi"]
unit-testing = ["near-vm-logic", "near-primitives-core", "near-primitives", "near-crypto"]
unit-testing = ["near-vm-runner", "near-primitives-core", "near-primitives", "near-crypto", "near-parameters"]

__abi-embed = ["near-sdk-macros/__abi-embed"]
__abi-generate = ["abi", "near-sdk-macros/__abi-generate"]
Expand Down
4 changes: 2 additions & 2 deletions near-sdk/src/environment/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,9 @@ pub(crate) unsafe fn read_register_fixed_64(register_id: u64) -> [u8; 64] {
/// low-level blockchain interfacr that implements `BlockchainInterface` trait. In most cases you
/// want to use `testing_env!` macro to set it.
///
/// ```no_run
/// ```
/// # let context = near_sdk::test_utils::VMContextBuilder::new().build();
/// # let vm_config = near_sdk::VMConfig::test();
/// # let vm_config = near_sdk::test_vm_config();
/// # let fees_config = near_sdk::RuntimeFeesConfig::test();
/// # let storage = Default::default();
/// # let validators = Default::default();
Expand Down
88 changes: 0 additions & 88 deletions near-sdk/src/environment/mock/external.rs

This file was deleted.

141 changes: 59 additions & 82 deletions near-sdk/src/environment/mock/mocked_blockchain.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
use super::{Receipt, SdkExternal};
use super::Receipt;
use crate::mock::MockAction;
// TODO replace with near_vm_logic::mocks::mock_memory::MockedMemory after updating version from 0.17
use crate::mock::mocked_memory::MockedMemory;
use crate::mock::VmAction;
use crate::test_utils::VMContextBuilder;
use crate::types::{NearToken, PromiseResult};
use crate::{CurveType, Gas, RuntimeFeesConfig};
use crate::{PublicKey, VMContext};
use near_crypto::PublicKey as VmPublicKey;
use near_primitives::transaction::Action as PrimitivesAction;
use near_vm_logic::types::PromiseResult as VmPromiseResult;
use near_vm_logic::{External, MemoryLike, VMConfig, VMLogic};
use crate::VMContext;
use near_parameters::{RuntimeConfigStore, RuntimeFeesConfig};
use near_primitives_core::version::PROTOCOL_VERSION;
use near_vm_runner::logic::mocks::mock_external::MockedExternal;
use near_vm_runner::logic::types::{PromiseResult as VmPromiseResult, ReceiptIndex};
use near_vm_runner::logic::{External, MemoryLike, VMLogic};
use std::cell::RefCell;
use std::collections::HashMap;

Expand All @@ -25,11 +25,20 @@ pub struct MockedBlockchain {
logic_fixture: LogicFixture,
}

pub fn test_vm_config() -> near_parameters::vm::Config {
let store = RuntimeConfigStore::test();
let config = store.get_config(PROTOCOL_VERSION).wasm_config.clone();
near_parameters::vm::Config {
vm_kind: config.vm_kind.replace_with_wasmtime_if_unsupported(),
..config
}
}

impl Default for MockedBlockchain {
fn default() -> Self {
MockedBlockchain::new(
VMContextBuilder::new().build(),
VMConfig::test(),
test_vm_config(),
RuntimeFeesConfig::test(),
vec![],
Default::default(),
Expand All @@ -40,25 +49,25 @@ impl Default for MockedBlockchain {
}

struct LogicFixture {
ext: Box<SdkExternal>,
ext: Box<MockedExternal>,
memory: Box<dyn MemoryLike>,
#[allow(clippy::box_collection)]
promise_results: Box<Vec<VmPromiseResult>>,
config: Box<VMConfig>,
config: Box<near_parameters::vm::Config>,
fees_config: Box<RuntimeFeesConfig>,
}

impl MockedBlockchain {
pub fn new(
context: VMContext,
config: VMConfig,
config: near_parameters::vm::Config,
fees_config: RuntimeFeesConfig,
promise_results: Vec<PromiseResult>,
storage: HashMap<Vec<u8>, Vec<u8>>,
validators: HashMap<String, NearToken>,
memory_opt: Option<Box<dyn MemoryLike>>,
) -> Self {
let mut ext = Box::new(SdkExternal::new());
let mut ext = Box::new(MockedExternal::new());
let context = sdk_context_to_vm_context(context);
ext.fake_trie = storage;
ext.validators =
Expand All @@ -71,14 +80,13 @@ impl MockedBlockchain {
let mut logic_fixture = LogicFixture { ext, memory, promise_results, config, fees_config };

let logic = unsafe {
VMLogic::new_with_protocol_version(
VMLogic::new(
&mut *(logic_fixture.ext.as_mut() as *mut dyn External),
context,
&*(logic_fixture.config.as_mut() as *const VMConfig),
&*(logic_fixture.config.as_mut() as *const near_parameters::vm::Config),
&*(logic_fixture.fees_config.as_mut() as *const RuntimeFeesConfig),
&*(logic_fixture.promise_results.as_ref().as_slice() as *const [VmPromiseResult]),
&mut *(logic_fixture.memory.as_mut() as *mut dyn MemoryLike),
u32::MAX,
)
};

Expand All @@ -92,15 +100,39 @@ impl MockedBlockchain {

/// Returns metadata about the receipts created
pub fn created_receipts(&self) -> Vec<Receipt> {
self.logic
.borrow()
.action_receipts()
.iter()
.map(|(receiver, receipt)| {
let actions = receipt.actions.iter().map(action_to_sdk_action).collect();
Receipt { receiver_id: receiver.as_str().parse().unwrap(), actions }
let action_log = &self.logic_fixture.ext.action_log;
let action_log: Vec<MockAction> =
action_log.clone().into_iter().map(<MockAction as From<_>>::from).collect();
let create_receipts: Vec<(usize, MockAction)> = action_log
.clone()
.into_iter()
.enumerate()
.filter(|(_receipt_idx, action)| matches!(action, MockAction::CreateReceipt { .. }))
.collect();

let result = create_receipts
.into_iter()
.map(|(receipt_idx, create_receipt)| {
let (receiver_id, receipt_indices) = match create_receipt {
MockAction::CreateReceipt { receiver_id, receipt_indices } => {
(receiver_id, receipt_indices)
}
_ => panic!("not a CreateReceipt action!"),
};
let actions: Vec<MockAction> = action_log
.iter()
.filter(|action| match action.receipt_index() {
None => false,
Some(action_receipt_idx) => {
action_receipt_idx == (receipt_idx as ReceiptIndex)
}
})
.cloned()
.collect();
Receipt { receiver_id, actions, receipt_indices }
})
.collect()
.collect();
result
}

pub fn gas(&mut self, gas_amount: u32) {
Expand All @@ -113,8 +145,8 @@ impl MockedBlockchain {
}
}

fn sdk_context_to_vm_context(context: VMContext) -> near_vm_logic::VMContext {
near_vm_logic::VMContext {
fn sdk_context_to_vm_context(context: VMContext) -> near_vm_runner::logic::VMContext {
near_vm_runner::logic::VMContext {
current_account_id: context.current_account_id.as_str().parse().unwrap(),
signer_account_id: context.signer_account_id.as_str().parse().unwrap(),
signer_account_pk: context.signer_account_pk.into_bytes(),
Expand All @@ -138,64 +170,9 @@ fn sdk_context_to_vm_context(context: VMContext) -> near_vm_logic::VMContext {
}
}

fn action_to_sdk_action(action: &PrimitivesAction) -> VmAction {
match action {
PrimitivesAction::CreateAccount(_) => VmAction::CreateAccount,
PrimitivesAction::DeployContract(c) => VmAction::DeployContract { code: c.code.clone() },
PrimitivesAction::FunctionCall(f) => VmAction::FunctionCall {
function_name: f.method_name.clone(),
args: f.args.clone(),
gas: Gas::from_gas(f.gas),
deposit: NearToken::from_yoctonear(f.deposit),
},
PrimitivesAction::Transfer(t) => {
VmAction::Transfer { deposit: NearToken::from_yoctonear(t.deposit) }
}
PrimitivesAction::Stake(s) => VmAction::Stake {
stake: NearToken::from_yoctonear(s.stake),
public_key: pub_key_conversion(&s.public_key),
},
PrimitivesAction::AddKey(k) => match &k.access_key.permission {
near_primitives::account::AccessKeyPermission::FunctionCall(f) => {
VmAction::AddKeyWithFunctionCall {
public_key: pub_key_conversion(&k.public_key),
nonce: k.access_key.nonce,
allowance: f.allowance.map(NearToken::from_yoctonear),
receiver_id: f.receiver_id.parse().unwrap(),
function_names: f.method_names.clone(),
}
}
near_primitives::account::AccessKeyPermission::FullAccess => {
VmAction::AddKeyWithFullAccess {
public_key: pub_key_conversion(&k.public_key),
nonce: k.access_key.nonce,
}
}
},
PrimitivesAction::DeleteKey(k) => {
VmAction::DeleteKey { public_key: pub_key_conversion(&k.public_key) }
}
PrimitivesAction::DeleteAccount(a) => {
VmAction::DeleteAccount { beneficiary_id: a.beneficiary_id.parse().unwrap() }
}
PrimitivesAction::Delegate(_d) => {
panic!("Unimplemented")
}
}
}

fn pub_key_conversion(key: &VmPublicKey) -> PublicKey {
let curve_type = match key.key_type() {
near_crypto::KeyType::ED25519 => CurveType::ED25519,
near_crypto::KeyType::SECP256K1 => CurveType::SECP256K1,
};
PublicKey::from_parts(curve_type, key.key_data().to_vec()).unwrap()
}

#[cfg(not(target_arch = "wasm32"))]
mod mock_chain {
use near_vm_logic::{VMLogic, VMLogicError};

use near_vm_runner::logic::{errors::VMLogicError, VMLogic};
fn with_mock_interface<F, R>(f: F) -> R
where
F: FnOnce(&mut VMLogic) -> Result<R, VMLogicError>,
Expand Down
Loading

0 comments on commit 9ce0cdc

Please sign in to comment.