Skip to content

Commit

Permalink
Merge branch 'miraclx/fix-abi-embed-compile-error' into miraclx/fix-s…
Browse files Browse the repository at this point in the history
…elf-references
  • Loading branch information
miraclx committed Jan 21, 2023
2 parents 91cce49 + 2aac191 commit 7f95609
Show file tree
Hide file tree
Showing 19 changed files with 350 additions and 81 deletions.
2 changes: 1 addition & 1 deletion CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
@@ -1 +1 @@
* @austinabell @ChaoticTempest @itegulov
* @ChaoticTempest @itegulov
1 change: 0 additions & 1 deletion near-contract-standards/src/fungible_token/core_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,6 @@ impl FungibleToken {

// Get the unused amount from the `ft_on_transfer` call result.
let unused_amount = match env::promise_result(0) {
PromiseResult::NotReady => env::abort(),
PromiseResult::Successful(value) => {
if let Ok(unused_amount) = near_sdk::serde_json::from_slice::<U128>(&value) {
std::cmp::min(amount, unused_amount.0)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -428,7 +428,6 @@ impl NonFungibleTokenResolver for NonFungibleToken {
) -> bool {
// Get whether token should be returned
let must_revert = match env::promise_result(0) {
PromiseResult::NotReady => env::abort(),
PromiseResult::Successful(value) => {
if let Ok(yes_or_no) = near_sdk::serde_json::from_slice::<bool>(&value) {
yes_or_no
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,11 @@ impl NonFungibleTokenEnumeration for NonFungibleToken {
} else {
return vec![];
};

if token_set.is_empty() {
return vec![];
}

let limit = limit.map(|v| v as usize).unwrap_or(usize::MAX);
require!(limit != 0, "Cannot provide limit of 0.");
let start_index: u128 = from_index.map(From::from).unwrap_or_default();
Expand Down
4 changes: 3 additions & 1 deletion near-contract-standards/src/non_fungible_token/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ pub struct NFTContractMetadata {
}

/// Metadata on the individual token level.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, BorshDeserialize, BorshSerialize)]
#[derive(
Debug, Clone, Serialize, Deserialize, PartialEq, Eq, BorshDeserialize, BorshSerialize, Default,
)]
#[cfg_attr(feature = "abi", derive(schemars::JsonSchema))]
#[serde(crate = "near_sdk::serde")]
pub struct TokenMetadata {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,6 @@ impl AttrSigInfo {
let result = quote! {
match near_sdk::env::promise_result(#idx) {
#deserialization_branch,
near_sdk::PromiseResult::NotReady => Err(near_sdk::PromiseError::NotReady),
near_sdk::PromiseResult::Failed => Err(near_sdk::PromiseError::Failed),
}
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -404,12 +404,10 @@ mod tests {
}
let mut x: Result<u64, PromiseError> = match near_sdk::env::promise_result(0u64) {
near_sdk::PromiseResult::Successful(data) => Ok(near_sdk::serde_json::from_slice(&data).expect("Failed to deserialize callback using JSON")),
near_sdk::PromiseResult::NotReady => Err(near_sdk::PromiseError::NotReady),
near_sdk::PromiseResult::Failed => Err(near_sdk::PromiseError::Failed),
};
let y: Result<String, PromiseError> = match near_sdk::env::promise_result(1u64) {
near_sdk::PromiseResult::Successful(data) => Ok(near_sdk::serde_json::from_slice(&data).expect("Failed to deserialize callback using JSON")),
near_sdk::PromiseResult::NotReady => Err(near_sdk::PromiseError::NotReady),
near_sdk::PromiseResult::Failed => Err(near_sdk::PromiseError::Failed),
};
let contract: Hello = near_sdk::env::state_read().unwrap_or_default();
Expand Down
2 changes: 1 addition & 1 deletion near-sdk-macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -584,7 +584,7 @@ pub fn derive_event_attributes(item: TokenStream) -> TokenStream {

TokenStream::from(quote! {
impl #impl_generics #name #type_generics #where_clause {
fn emit(&self) {
pub fn emit(&self) {
let (standard, version): (String, String) = match self {
#(#event_meta),*
};
Expand Down
3 changes: 3 additions & 0 deletions near-sdk/src/collections/legacy_tree_map.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
//! Legacy `TreeMap` implementation that is using `UnorderedMap`.
//! DEPRECATED. This implementation is deprecated and may be removed in the future.
#![allow(clippy::all)]
// This suppresses the depreciation warnings for uses of LegacyTreeMap in this module
#![allow(deprecated)]

use borsh::{BorshDeserialize, BorshSerialize};
use std::ops::Bound;
Expand All @@ -18,6 +20,7 @@ use crate::IntoStorageKey;
/// - `above`/`below`: O(log(N))
/// - `range` of K elements: O(Klog(N))
///
#[deprecated(since = "4.1.0", note = "Use near_sdk::collections::TreeMap")]
#[derive(BorshSerialize, BorshDeserialize)]
pub struct LegacyTreeMap<K, V> {
root: u64,
Expand Down
1 change: 1 addition & 0 deletions near-sdk/src/collections/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
//! that seemlessly integrated with the rest of the Rust standard library.
mod legacy_tree_map;
#[allow(deprecated)]
pub use legacy_tree_map::LegacyTreeMap;

mod lookup_map;
Expand Down
33 changes: 31 additions & 2 deletions near-sdk/src/environment/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use std::{convert::TryFrom, mem::MaybeUninit};

#[cfg(all(not(target_arch = "wasm32"), feature = "unit-testing"))]
use crate::mock::MockedBlockchain;
use crate::promise::Allowance;
use crate::types::{
AccountId, Balance, BlockHeight, Gas, PromiseIndex, PromiseResult, PublicKey, StorageUsage,
};
Expand Down Expand Up @@ -553,15 +554,45 @@ pub fn promise_batch_action_add_key_with_full_access(
)
}
}

/// This is a short lived function while we migrate between the Balance and the allowance type
pub(crate) fn migrate_to_allowance(allowance: Balance) -> Allowance {
Allowance::limited(allowance).unwrap_or(Allowance::Unlimited)
}

#[deprecated(since = "5.0.0", note = "Use add_access_key_allowance instead")]
pub fn promise_batch_action_add_key_with_function_call(
promise_index: PromiseIndex,
public_key: &PublicKey,
nonce: u64,
allowance: Balance,
receiver_id: &AccountId,
function_names: &str,
) {
let allowance = migrate_to_allowance(allowance);
promise_batch_action_add_key_allowance_with_function_call(
promise_index,
public_key,
nonce,
allowance,
receiver_id,
function_names,
)
}

pub fn promise_batch_action_add_key_allowance_with_function_call(
promise_index: PromiseIndex,
public_key: &PublicKey,
nonce: u64,
allowance: Allowance,
receiver_id: &AccountId,
function_names: &str,
) {
let receiver_id: &str = receiver_id.as_ref();
let allowance = match allowance {
Allowance::Limited(x) => x.get(),
Allowance::Unlimited => 0,
};
unsafe {
sys::promise_batch_action_add_key_with_function_call(
promise_index,
Expand Down Expand Up @@ -610,7 +641,6 @@ pub fn promise_results_count() -> u64 {
/// promises that caused the callback.
pub fn promise_result(result_idx: u64) -> PromiseResult {
match promise_result_internal(result_idx) {
Err(PromiseError::NotReady) => PromiseResult::NotReady,
Ok(()) => {
let data = expect_register(read_register(ATOMIC_OP_REGISTER));
PromiseResult::Successful(data)
Expand All @@ -621,7 +651,6 @@ pub fn promise_result(result_idx: u64) -> PromiseResult {

pub(crate) fn promise_result_internal(result_idx: u64) -> Result<(), PromiseError> {
match unsafe { sys::promise_result(result_idx, ATOMIC_OP_REGISTER) } {
0 => Err(PromiseError::NotReady),
1 => Ok(()),
2 => Err(PromiseError::Failed),
_ => abort(),
Expand Down
2 changes: 1 addition & 1 deletion near-sdk/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub use environment::env;
pub use near_sys as sys;

mod promise;
pub use promise::{Promise, PromiseOrValue};
pub use promise::{Allowance, Promise, PromiseOrValue};

// Private types just used within macro generation, not stable to be used.
#[doc(hidden)]
Expand Down
68 changes: 63 additions & 5 deletions near-sdk/src/promise.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,31 @@ use borsh::BorshSchema;
use std::cell::RefCell;
use std::collections::HashMap;
use std::io::{Error, Write};
use std::num::NonZeroU128;
use std::rc::Rc;

use crate::env::migrate_to_allowance;
use crate::{AccountId, Balance, Gas, GasWeight, PromiseIndex, PublicKey};

/// Allow an access key to spend either an unlimited or limited amount of gas
// This wrapper prevents incorrect construction
#[derive(Clone, Copy)]
pub enum Allowance {
Unlimited,
Limited(NonZeroU128),
}

impl Allowance {
pub fn unlimited() -> Allowance {
Allowance::Unlimited
}

/// This will return an None if you try to pass a zero value balance
pub fn limited(balance: Balance) -> Option<Allowance> {
NonZeroU128::new(balance).map(Allowance::Limited)
}
}

enum PromiseAction {
CreateAccount,
DeployContract {
Expand Down Expand Up @@ -37,7 +58,7 @@ enum PromiseAction {
},
AddAccessKey {
public_key: PublicKey,
allowance: Balance,
allowance: Allowance,
receiver_id: AccountId,
function_names: String,
nonce: u64,
Expand Down Expand Up @@ -91,7 +112,7 @@ impl PromiseAction {
)
}
AddAccessKey { public_key, allowance, receiver_id, function_names, nonce } => {
crate::env::promise_batch_action_add_key_with_function_call(
crate::env::promise_batch_action_add_key_allowance_with_function_call(
promise_index,
public_key,
*nonce,
Expand Down Expand Up @@ -312,21 +333,39 @@ impl Promise {
/// Add an access key that is restricted to only calling a smart contract on some account using
/// only a restricted set of methods. Here `function_names` is a comma separated list of methods,
/// e.g. `"method_a,method_b".to_string()`.
pub fn add_access_key_allowance(
self,
public_key: PublicKey,
allowance: Allowance,
receiver_id: AccountId,
function_names: String,
) -> Self {
self.add_access_key_allowance_with_nonce(
public_key,
allowance,
receiver_id,
function_names,
0,
)
}

#[deprecated(since = "5.0.0", note = "Use add_access_key_allowance instead")]
pub fn add_access_key(
self,
public_key: PublicKey,
allowance: Balance,
receiver_id: AccountId,
function_names: String,
) -> Self {
self.add_access_key_with_nonce(public_key, allowance, receiver_id, function_names, 0)
let allowance = migrate_to_allowance(allowance);
self.add_access_key_allowance(public_key, allowance, receiver_id, function_names)
}

/// Add an access key with a provided nonce.
pub fn add_access_key_with_nonce(
pub fn add_access_key_allowance_with_nonce(
self,
public_key: PublicKey,
allowance: Balance,
allowance: Allowance,
receiver_id: AccountId,
function_names: String,
nonce: u64,
Expand All @@ -340,6 +379,25 @@ impl Promise {
})
}

#[deprecated(since = "5.0.0", note = "Use add_access_key_allowance_with_nonce instead")]
pub fn add_access_key_with_nonce(
self,
public_key: PublicKey,
allowance: Balance,
receiver_id: AccountId,
function_names: String,
nonce: u64,
) -> Self {
let allowance = migrate_to_allowance(allowance);
self.add_access_key_allowance_with_nonce(
public_key,
allowance,
receiver_id,
function_names,
nonce,
)
}

/// Delete access key from the given account.
pub fn delete_key(self, public_key: PublicKey) -> Self {
self.add_action(PromiseAction::DeleteKey { public_key })
Expand Down
Loading

0 comments on commit 7f95609

Please sign in to comment.