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

feat: refactor ext API and add new NEP264 functionality #742

Merged
merged 20 commits into from
May 12, 2022
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
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
Binary file modified examples/callback-results/res/callback_results.wasm
Binary file not shown.
27 changes: 7 additions & 20 deletions examples/callback-results/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,38 +1,25 @@
use near_sdk::require;
use near_sdk::{env, ext_contract, near_bindgen, Promise, PromiseError};
use near_sdk::{env, near_bindgen, Promise, PromiseError};

const A_VALUE: u8 = 8;

#[near_bindgen]
pub struct Callback;

// One can provide a name, e.g. `ext` to use for generated methods.
#[ext_contract(ext)]
pub trait ExtCrossContract {
fn a() -> Promise;
fn b(fail: bool) -> &'static str;
fn c(value: u8) -> u8;
fn handle_callbacks(
#[callback_unwrap] a: u8,
#[callback_result] b: Result<String, PromiseError>,
#[callback_result] c: Result<u8, PromiseError>,
) -> (bool, bool, bool);
}

#[near_bindgen]
impl Callback {
/// Call functions a, b, and c asynchronously and handle results with `handle_callbacks`.
pub fn call_all(fail_b: bool, c_value: u8) -> Promise {
let gas_per_promise = env::prepaid_gas() / 5;
ext::a(env::current_account_id(), 0, gas_per_promise)
.and(ext::b(fail_b, env::current_account_id(), 0, gas_per_promise))
.and(ext::c(c_value, env::current_account_id(), 0, gas_per_promise))
.then(ext::handle_callbacks(env::current_account_id(), 0, gas_per_promise))
Self::ext(env::current_account_id())
.a()
.and(Self::ext(env::current_account_id()).b(fail_b))
.and(Self::ext(env::current_account_id()).c(c_value))
.then(Self::ext(env::current_account_id()).handle_callbacks())
}

/// Calls function c with a value that will always succeed
pub fn a() -> Promise {
ext::c(A_VALUE, env::current_account_id(), 0, env::prepaid_gas() / 2)
Self::ext(env::current_account_id()).c(A_VALUE)
}

/// Returns a static string if fail is false, return
Expand Down
Binary file not shown.
46 changes: 9 additions & 37 deletions examples/cross-contract-high-level/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,34 +1,12 @@
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::{
env,
ext_contract,
json_types::U128,
log,
near_bindgen,
AccountId,
Promise,
PromiseOrValue,
env, ext_contract, json_types::U128, log, near_bindgen, AccountId, Promise, PromiseOrValue,
};

#[near_bindgen]
#[derive(Default, BorshDeserialize, BorshSerialize)]
pub struct CrossContract {}

// One can provide a name, e.g. `ext` to use for generated methods.
#[ext_contract(ext)]
pub trait ExtCrossContract {
fn merge_sort(&self, arr: Vec<u8>) -> PromiseOrValue<Vec<u8>>;
fn merge(
&self,
#[callback_unwrap]
#[serializer(borsh)]
data0: Vec<u8>,
#[callback_unwrap]
#[serializer(borsh)]
data1: Vec<u8>,
) -> Vec<u8>;
}

// If the name is not provided, the namespace for generated methods in derived by applying snake
// case to the trait name, e.g. ext_status_message.
#[ext_contract]
Expand Down Expand Up @@ -57,12 +35,12 @@ impl CrossContract {
let pivot = arr.len() / 2;
let arr0 = arr[..pivot].to_vec();
let arr1 = arr[pivot..].to_vec();
let prepaid_gas = env::prepaid_gas();
let account_id = env::current_account_id();

ext::merge_sort(arr0, account_id.clone(), 0, prepaid_gas / 4)
.and(ext::merge_sort(arr1, account_id.clone(), 0, prepaid_gas / 4))
.then(ext::merge(account_id, 0, prepaid_gas / 4))
Self::ext(account_id.clone())
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wouldn't account_id always be env::current_account_id() here since we are calling the current contract?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yep, it is. This is just cloning that every time to avoid using the host function three times (unnecessary gas usage)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well then perhaps the Self could handle this making the API a little more ergonomic and preventing users from calling another contract.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But they can call the self API to another contract. I thought you meant only in this case. The account_id can absolutely be different than the current.

I don't think it's worth adding another method for calling it on self, because cases like this you might want to avoid calling the host function more than once

Copy link
Contributor

@willemneal willemneal Mar 15, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another contract might have the same interface as the current contract, but I would personally propose Self always be calling the current contract. It would make reading over the contract easier:

Self::merge_sort(arr0).and(Self::merge_sort(arr1)).then(Self::merge())

And my point with Self handling the account_id is that it could lazily load and cache it.

Also You could still have Self::ext if you need the functionality, but for most uses of Self this would be a better DevX.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't work. These methods already exist. Feel free to create a commit/diff if you have an idea for this working, and I'll happily consider it

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah silly me forgot it's the same Self, thought it was generated. You would need to generate another module current_contract, which is a bit longer than Self. I'll think about it more because this is a pain point.

.merge_sort(arr0)
.and(Self::ext(account_id.clone()).merge_sort(arr1))
.then(Self::ext(account_id).merge())
.into()
}

Expand Down Expand Up @@ -117,23 +95,17 @@ impl CrossContract {
// }

pub fn simple_call(&mut self, account_id: AccountId, message: String) {
ext_status_message::set_status(message, account_id, 0, env::prepaid_gas() / 2);
ext_status_message::ext(account_id).set_status(message);
}
pub fn complex_call(&mut self, account_id: AccountId, message: String) -> Promise {
// 1) call status_message to record a message from the signer.
// 2) call status_message to retrieve the message of the signer.
// 3) return that message as its own result.
// Note, for a contract to simply call another contract (1) is sufficient.
let prepaid_gas = env::prepaid_gas();
log!("complex_call");
ext_status_message::set_status(message, account_id.clone(), 0, prepaid_gas / 3).then(
ext_status_message::get_status(
env::signer_account_id(),
account_id,
0,
prepaid_gas / 3,
),
)
ext_status_message::ext(account_id.clone())
.set_status(message)
.then(ext_status_message::ext(account_id).get_status(env::signer_account_id()))
}

pub fn transfer_money(&mut self, account_id: AccountId, amount: u64) {
Expand Down
Binary file not shown.
Binary file modified examples/fungible-token/res/defi.wasm
Binary file not shown.
Binary file modified examples/fungible-token/res/fungible_token.wasm
Binary file not shown.
21 changes: 5 additions & 16 deletions examples/fungible-token/test-contract-defi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,20 @@ use near_contract_standards::fungible_token::receiver::FungibleTokenReceiver;
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::json_types::U128;
use near_sdk::{
env, ext_contract, log, near_bindgen, require, AccountId, Balance, Gas, PanicOnDefault,
env, log, near_bindgen, require, AccountId, Balance, Gas, PanicOnDefault,
PromiseOrValue,
};

const BASE_GAS: u64 = 5_000_000_000_000;
const PROMISE_CALL: u64 = 5_000_000_000_000;
const GAS_FOR_FT_ON_TRANSFER: Gas = Gas(BASE_GAS + PROMISE_CALL);

const NO_DEPOSIT: Balance = 0;

#[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize, PanicOnDefault)]
pub struct DeFi {
fungible_token_account_id: AccountId,
}

// Defining cross-contract interface. This allows to create a new promise.
#[ext_contract(ext_self)]
pub trait ValueReturnTrait {
fn value_please(&self, amount_to_return: String) -> PromiseOrValue<U128>;
}

// Have to repeat the same trait for our own implementation.
trait ValueReturnTrait {
fn value_please(&self, amount_to_return: String) -> PromiseOrValue<U128>;
Expand Down Expand Up @@ -63,13 +55,10 @@ impl FungibleTokenReceiver for DeFi {
_ => {
let prepaid_gas = env::prepaid_gas();
let account_id = env::current_account_id();
ext_self::value_please(
msg,
account_id,
NO_DEPOSIT,
prepaid_gas - GAS_FOR_FT_ON_TRANSFER,
)
.into()
Self::ext(account_id)
.with_static_gas(prepaid_gas - GAS_FOR_FT_ON_TRANSFER)
.value_please(msg)
.into()
}
}
}
Expand Down
Binary file not shown.
Binary file modified examples/mission-control/res/mission_control.wasm
Binary file not shown.
Binary file modified examples/non-fungible-token/res/approval_receiver.wasm
Binary file not shown.
Binary file modified examples/non-fungible-token/res/non_fungible_token.wasm
Binary file not shown.
Binary file modified examples/non-fungible-token/res/token_receiver.wasm
Binary file not shown.
14 changes: 4 additions & 10 deletions examples/non-fungible-token/test-approval-receiver/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,20 @@ use near_contract_standards::non_fungible_token::approval::NonFungibleTokenAppro
use near_contract_standards::non_fungible_token::TokenId;
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::{
env, ext_contract, log, near_bindgen, require, AccountId, Balance, Gas, PanicOnDefault,
env, log, near_bindgen, require, AccountId, Gas, PanicOnDefault,
PromiseOrValue,
};

const BASE_GAS: u64 = 5_000_000_000_000;
const PROMISE_CALL: u64 = 5_000_000_000_000;
const GAS_FOR_NFT_ON_APPROVE: Gas = Gas(BASE_GAS + PROMISE_CALL);

const NO_DEPOSIT: Balance = 0;

#[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize, PanicOnDefault)]
pub struct ApprovalReceiver {
non_fungible_token_account_id: AccountId,
}

// Defining cross-contract interface. This allows to create a new promise.
#[ext_contract(ext_self)]
pub trait ValueReturnTrait {
fn ok_go(&self, msg: String) -> PromiseOrValue<String>;
}

// Have to repeat the same trait for our own implementation.
trait ValueReturnTrait {
fn ok_go(&self, msg: String) -> PromiseOrValue<String>;
Expand Down Expand Up @@ -72,7 +64,9 @@ impl NonFungibleTokenApprovalReceiver for ApprovalReceiver {
_ => {
let prepaid_gas = env::prepaid_gas();
let account_id = env::current_account_id();
ext_self::ok_go(msg, account_id, NO_DEPOSIT, prepaid_gas - GAS_FOR_NFT_ON_APPROVE)
Self::ext(account_id)
.with_static_gas(prepaid_gas - GAS_FOR_NFT_ON_APPROVE)
.ok_go(msg)
.into()
}
}
Expand Down
26 changes: 8 additions & 18 deletions examples/non-fungible-token/test-token-receiver/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,19 @@ use near_contract_standards::non_fungible_token::core::NonFungibleTokenReceiver;
use near_contract_standards::non_fungible_token::TokenId;
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::{
env, ext_contract, log, near_bindgen, require, AccountId, Balance, Gas, PanicOnDefault,
PromiseOrValue,
env, log, near_bindgen, require, AccountId, Gas, PanicOnDefault, PromiseOrValue,
};

const BASE_GAS: u64 = 5_000_000_000_000;
const PROMISE_CALL: u64 = 5_000_000_000_000;
const GAS_FOR_NFT_ON_TRANSFER: Gas = Gas(BASE_GAS + PROMISE_CALL);

const NO_DEPOSIT: Balance = 0;

#[near_bindgen]
#[derive(BorshDeserialize, BorshSerialize, PanicOnDefault)]
pub struct TokenReceiver {
non_fungible_token_account_id: AccountId,
}

// Defining cross-contract interface. This allows to create a new promise.
#[ext_contract(ext_self)]
pub trait ValueReturnTrait {
fn ok_go(&self, return_it: bool) -> PromiseOrValue<bool>;
}

// Have to repeat the same trait for our own implementation.
trait ValueReturnTrait {
fn ok_go(&self, return_it: bool) -> PromiseOrValue<bool>;
Expand Down Expand Up @@ -73,20 +64,19 @@ impl NonFungibleTokenReceiver for TokenReceiver {
"return-it-later" => {
let prepaid_gas = env::prepaid_gas();
let account_id = env::current_account_id();
ext_self::ok_go(true, account_id, NO_DEPOSIT, prepaid_gas - GAS_FOR_NFT_ON_TRANSFER)
Self::ext(account_id)
.with_static_gas(prepaid_gas - GAS_FOR_NFT_ON_TRANSFER)
.ok_go(true)
.into()
}
"keep-it-now" => PromiseOrValue::Value(false),
"keep-it-later" => {
let prepaid_gas = env::prepaid_gas();
let account_id = env::current_account_id();
ext_self::ok_go(
false,
account_id,
NO_DEPOSIT,
prepaid_gas - GAS_FOR_NFT_ON_TRANSFER,
)
.into()
Self::ext(account_id)
.with_static_gas(prepaid_gas - GAS_FOR_NFT_ON_TRANSFER)
.ok_go(false)
.into()
}
_ => env::panic_str("unsupported msg"),
}
Expand Down
Binary file not shown.
Binary file modified examples/status-message/res/status_message.wasm
Binary file not shown.
Binary file modified examples/test-contract/res/test_contract.wasm
Binary file not shown.
2 changes: 2 additions & 0 deletions near-contract-standards/src/fungible_token/core.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use near_sdk::ext_contract;
use near_sdk::json_types::U128;
use near_sdk::AccountId;
use near_sdk::PromiseOrValue;

#[ext_contract(ext_ft_core)]
pub trait FungibleTokenCore {
/// Transfers positive `amount` of tokens from the `env::predecessor_account_id` to `receiver_id`.
/// Both accounts must be registered with the contract for transfer to succeed. (See [NEP-145](https://github.com/near/NEPs/discussions/145))
Expand Down
74 changes: 13 additions & 61 deletions near-contract-standards/src/fungible_token/core_impl.rs
Original file line number Diff line number Diff line change
@@ -1,58 +1,18 @@
use crate::fungible_token::core::FungibleTokenCore;
use crate::fungible_token::events::FtTransfer;
use crate::fungible_token::resolver::FungibleTokenResolver;
use crate::fungible_token::receiver::ext_ft_receiver;
use crate::fungible_token::resolver::{ext_ft_resolver, FungibleTokenResolver};
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::collections::LookupMap;
use near_sdk::json_types::U128;
use near_sdk::{
assert_one_yocto, env, ext_contract, log, require, AccountId, Balance, Gas, IntoStorageKey,
PromiseOrValue, PromiseResult, StorageUsage,
assert_one_yocto, env, log, require, AccountId, Balance, Gas, IntoStorageKey, PromiseOrValue,
PromiseResult, StorageUsage,
};

const GAS_FOR_RESOLVE_TRANSFER: Gas = Gas(5_000_000_000_000);
const GAS_FOR_FT_TRANSFER_CALL: Gas = Gas(25_000_000_000_000 + GAS_FOR_RESOLVE_TRANSFER.0);

const NO_DEPOSIT: Balance = 0;

#[ext_contract(ext_self)]
trait FungibleTokenResolver {
fn ft_resolve_transfer(
&mut self,
sender_id: AccountId,
receiver_id: AccountId,
amount: U128,
) -> U128;
}

#[ext_contract(ext_fungible_token_receiver)]
pub trait FungibleTokenReceiver {
fn ft_on_transfer(
&mut self,
sender_id: AccountId,
amount: U128,
msg: String,
) -> PromiseOrValue<U128>;
}

#[ext_contract(ext_fungible_token)]
pub trait FungibleTokenContract {
fn ft_transfer(&mut self, receiver_id: AccountId, amount: U128, memo: Option<String>);

fn ft_transfer_call(
&mut self,
receiver_id: AccountId,
amount: U128,
memo: Option<String>,
msg: String,
) -> PromiseOrValue<U128>;

/// Returns the total supply of the token in a decimal string representation.
fn ft_total_supply(&self) -> U128;

/// Returns the balance of the account. If the account doesn't exist, `"0"` must be returned.
fn ft_balance_of(&self, account_id: AccountId) -> U128;
}

/// Implementation of a FungibleToken standard.
/// Allows to include NEP-141 compatible token to any contract.
/// There are next traits that any contract may implement:
Expand Down Expand Up @@ -179,23 +139,15 @@ impl FungibleTokenCore for FungibleToken {
let amount: Balance = amount.into();
self.internal_transfer(&sender_id, &receiver_id, amount, memo);
// Initiating receiver's call and the callback
ext_fungible_token_receiver::ft_on_transfer(
sender_id.clone(),
amount.into(),
msg,
receiver_id.clone(),
NO_DEPOSIT,
env::prepaid_gas() - GAS_FOR_FT_TRANSFER_CALL,
)
.then(ext_self::ft_resolve_transfer(
sender_id,
receiver_id,
amount.into(),
env::current_account_id(),
NO_DEPOSIT,
GAS_FOR_RESOLVE_TRANSFER,
))
.into()
ext_ft_receiver::ext(receiver_id.clone())
.with_static_gas(env::prepaid_gas() - GAS_FOR_FT_TRANSFER_CALL)
.ft_on_transfer(sender_id.clone(), amount.into(), msg)
.then(
ext_ft_resolver::ext(env::current_account_id())
.with_static_gas(GAS_FOR_RESOLVE_TRANSFER)
.ft_resolve_transfer(sender_id, receiver_id, amount.into()),
)
.into()
}

fn ft_total_supply(&self) -> U128 {
Expand Down
3 changes: 2 additions & 1 deletion near-contract-standards/src/fungible_token/receiver.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use near_sdk::json_types::U128;
use near_sdk::{AccountId, PromiseOrValue};
use near_sdk::{ext_contract, AccountId, PromiseOrValue};

#[ext_contract(ext_ft_receiver)]
pub trait FungibleTokenReceiver {
/// Called by fungible token contract after `ft_transfer_call` was initiated by
/// `sender_id` of the given `amount` with the transfer message given in `msg` field.
Expand Down
3 changes: 2 additions & 1 deletion near-contract-standards/src/fungible_token/resolver.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use near_sdk::{json_types::U128, AccountId};
use near_sdk::{ext_contract, json_types::U128, AccountId};

#[ext_contract(ext_ft_resolver)]
pub trait FungibleTokenResolver {
fn ft_resolve_transfer(
&mut self,
Expand Down
Loading