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 all 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.
31 changes: 8 additions & 23 deletions examples/callback-results/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,41 +1,26 @@
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 d(value: u8);
fn handle_callbacks(
#[callback_unwrap] a: u8,
#[callback_result] b: Result<String, PromiseError>,
#[callback_result] c: Result<u8, PromiseError>,
#[callback_result] d: Result<(), 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, d_value: u8) -> Promise {
let gas_per_promise = env::prepaid_gas() / 7;
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))
.and(ext::d(d_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))
.and(Self::ext(env::current_account_id()).d(d_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
24 changes: 6 additions & 18 deletions examples/cross-contract-calls/high-level/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,35 +1,23 @@
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::{env, Gas};
use near_sdk::{ext_contract, log, near_bindgen, PromiseOrValue};

// Prepaid gas for a single (not inclusive of recursion) `factorial` call.
const FACTORIAL_CALL_GAS: Gas = Gas(20_000_000_000_000);

// Prepaid gas for a single `factorial_mult` call.
const FACTORIAL_MULT_CALL_GAS: Gas = Gas(10_000_000_000_000);
use near_sdk::env;
use near_sdk::{log, near_bindgen, 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 factorial(&self, n: u32) -> PromiseOrValue<u32>;
fn factorial_mult(&self, n: u32, #[callback_unwrap] cur: u32) -> u32;
}

#[near_bindgen]
impl CrossContract {
pub fn factorial(&self, n: u32) -> PromiseOrValue<u32> {
if n <= 1 {
return PromiseOrValue::Value(1);
}
let account_id = env::current_account_id();
let prepaid_gas = env::prepaid_gas() - FACTORIAL_CALL_GAS;

ext::factorial(n - 1, account_id.clone(), 0, prepaid_gas - FACTORIAL_MULT_CALL_GAS)
.then(ext::factorial_mult(n, account_id, 0, FACTORIAL_MULT_CALL_GAS))
Self::ext(account_id.clone())
.with_unused_gas_weight(6)
.factorial(n - 1)
.then(Self::ext(account_id).factorial_mult(n))
.into()
}

Expand Down
Binary file modified examples/cross-contract-calls/res/cross_contract_high_level.wasm
Binary file not shown.
Binary file not shown.
26 changes: 5 additions & 21 deletions examples/factory-contract/high-level/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,6 @@ use near_sdk::{env, ext_contract, json_types::U128, near_bindgen, AccountId, Pro
#[derive(Default, BorshDeserialize, BorshSerialize)]
pub struct FactoryContract {}

// One can provide a name, e.g. `ext` to use for generated methods.
#[ext_contract(ext)]
pub trait ExtFactoryContract {
fn get_result(
&self,
account_id: AccountId,
#[callback_result] set_status_result: Result<(), PromiseError>,
) -> Option<String>;
}

// If the `ext_contract` name is not provided explicitly, the namespace for generated methods is
// derived by applying snake case to the trait name, e.g. ext_status_message.
#[ext_contract]
Expand All @@ -37,16 +27,16 @@ impl FactoryContract {
}

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();
ext_status_message::set_status(message, account_id.clone(), 0, prepaid_gas / 3)
.then(ext::get_result(account_id, env::current_account_id(), 0, prepaid_gas / 3))
ext_status_message::ext(account_id.clone())
.set_status(message)
.then(Self::ext(env::current_account_id()).get_result(account_id))
}

#[handle_result]
Expand All @@ -55,14 +45,8 @@ impl FactoryContract {
account_id: AccountId,
#[callback_result] set_status_result: Result<(), PromiseError>,
) -> Result<Promise, &'static str> {
let prepaid_gas = env::prepaid_gas();
match set_status_result {
Ok(_) => Ok(ext_status_message::get_status(
env::signer_account_id(),
account_id,
0,
prepaid_gas / 2,
)),
Ok(_) => Ok(ext_status_message::ext(account_id).get_status(env::signer_account_id())),
Err(_) => Err("Failed to set status"),
}
}
Expand Down
Binary file modified examples/factory-contract/res/factory_contract_high_level.wasm
Binary file not shown.
Binary file modified examples/factory-contract/res/factory_contract_low_level.wasm
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.
Binary file modified examples/versioned/res/versioned.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::{FtBurn, 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 @@ -176,23 +136,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
Loading