Skip to content

Commit

Permalink
chore: update nearcore crates from 0.17 -> 0.19
Browse files Browse the repository at this point in the history
  • Loading branch information
dj8yf0μl committed Jan 11, 2024
1 parent 1343059 commit 81bb8bc
Show file tree
Hide file tree
Showing 15 changed files with 309 additions and 134 deletions.
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.19", optional = true }
near-primitives-core = { version = "0.19", optional = true }
near-primitives = { version = "0.19", optional = true }
near-crypto = { version = "0.19", optional = true }
near-parameters = { version = "0.19", 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
2 changes: 1 addition & 1 deletion near-sdk/src/environment/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ 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
/// ```ignore
/// # let context = near_sdk::test_utils::VMContextBuilder::new().build();
/// # let vm_config = near_sdk::VMConfig::test();
/// # let fees_config = near_sdk::RuntimeFeesConfig::test();
Expand Down
134 changes: 131 additions & 3 deletions near-sdk/src/environment/mock/external.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,23 @@
use near_gas::NearGas;
use near_primitives::types::TrieNodesCount;
use near_primitives_core::hash::{hash, CryptoHash};
use near_primitives_core::types::{AccountId, Balance};
use near_vm_logic::{External, StorageGetMode, ValuePtr};
use near_primitives_core::types::{AccountId, Balance, Gas, GasWeight};
use near_token::NearToken;
use near_vm_runner::logic::types::ReceiptIndex;
use near_vm_runner::logic::{External, StorageGetMode, ValuePtr};
use std::collections::HashMap;

type Result<T> = ::core::result::Result<T, near_vm_logic::VMLogicError>;
use super::receipt::MockAction;

type Result<T> = ::core::result::Result<T, near_vm_runner::logic::errors::VMLogicError>;

#[derive(Default, Clone)]
/// Emulates the trie and the mock handling code for the SDK. This is a modified version of
/// `MockedExternal` from `near_vm_logic`.
pub(crate) struct SdkExternal {
pub fake_trie: HashMap<Vec<u8>, Vec<u8>>,
pub validators: HashMap<AccountId, Balance>,
pub action_log: Vec<MockAction>,
data_count: u64,
}

Expand Down Expand Up @@ -85,4 +91,126 @@ impl External for SdkExternal {
fn validator_total_stake(&self) -> Result<Balance> {
Ok(self.validators.values().sum())
}

fn create_receipt(
&mut self,
receipt_indices: Vec<ReceiptIndex>,
receiver_id: AccountId,
) -> Result<ReceiptIndex> {
let index = self.action_log.len();
self.action_log.push(MockAction::CreateReceipt { receipt_indices, receiver_id });
Ok(index as u64)
}

fn append_action_create_account(&mut self, receipt_index: ReceiptIndex) -> Result<()> {
self.action_log.push(MockAction::CreateAccount { receipt_index });
Ok(())
}

fn append_action_deploy_contract(
&mut self,
receipt_index: ReceiptIndex,
code: Vec<u8>,
) -> Result<()> {
self.action_log.push(MockAction::DeployContract { receipt_index, code });
Ok(())
}

fn append_action_function_call_weight(
&mut self,
receipt_index: ReceiptIndex,
method_name: Vec<u8>,
args: Vec<u8>,
attached_deposit: Balance,
prepaid_gas: Gas,
gas_weight: GasWeight,
) -> Result<()> {
self.action_log.push(MockAction::FunctionCallWeight {
receipt_index,
method_name,
args,
attached_deposit: NearToken::from_yoctonear(attached_deposit),
prepaid_gas: NearGas::from_gas(prepaid_gas),
gas_weight,
});
Ok(())
}

fn append_action_transfer(
&mut self,
receipt_index: ReceiptIndex,
deposit: Balance,
) -> Result<()> {
self.action_log.push(MockAction::Transfer {
receipt_index,
deposit: NearToken::from_yoctonear(deposit),
});
Ok(())
}

fn append_action_stake(
&mut self,
receipt_index: ReceiptIndex,
stake: Balance,
public_key: near_crypto::PublicKey,
) {
self.action_log.push(MockAction::Stake {
receipt_index,
stake: NearToken::from_yoctonear(stake),
public_key,
});
}

fn append_action_add_key_with_full_access(
&mut self,
receipt_index: ReceiptIndex,
public_key: near_crypto::PublicKey,
nonce: near_primitives_core::types::Nonce,
) {
self.action_log.push(MockAction::AddKeyWithFullAccess { receipt_index, public_key, nonce });
}

fn append_action_add_key_with_function_call(
&mut self,
receipt_index: ReceiptIndex,
public_key: near_crypto::PublicKey,
nonce: near_primitives_core::types::Nonce,
allowance: Option<Balance>,
receiver_id: AccountId,
method_names: Vec<Vec<u8>>,
) -> Result<()> {
self.action_log.push(MockAction::AddKeyWithFunctionCall {
receipt_index,
public_key,
nonce,
allowance: allowance.map(NearToken::from_yoctonear),
receiver_id,
method_names,
});
Ok(())
}

fn append_action_delete_key(
&mut self,
receipt_index: ReceiptIndex,
public_key: near_crypto::PublicKey,
) {
self.action_log.push(MockAction::DeleteKey { receipt_index, public_key });
}

fn append_action_delete_account(
&mut self,
receipt_index: ReceiptIndex,
beneficiary_id: AccountId,
) -> Result<()> {
self.action_log.push(MockAction::DeleteAccount { receipt_index, beneficiary_id });
Ok(())
}

fn get_receipt_receiver(&self, receipt_index: ReceiptIndex) -> &AccountId {
match &self.action_log[receipt_index as usize] {
MockAction::CreateReceipt { receiver_id, .. } => receiver_id,
_ => panic!("not a valid receipt index!"),
}
}
}
134 changes: 55 additions & 79 deletions near-sdk/src/environment/mock/mocked_blockchain.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
use super::{Receipt, SdkExternal};
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::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 +24,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 @@ -44,14 +52,14 @@ struct LogicFixture {
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>>,
Expand All @@ -71,14 +79,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 +99,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;
println!("{:#?}", action_log);
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();
println!("{:#?}", result);
result
}

pub fn gas(&mut self, gas_amount: u32) {
Expand All @@ -113,8 +144,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 +169,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 81bb8bc

Please sign in to comment.