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

[Enhancement] Deprecate Fungible Token declarative macros. #1054

Merged
merged 9 commits into from
Aug 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

### Removed
- Deprecated declarative macros for NFT impl code generation. [PR 1042](https://github.com/near/near-sdk-rs/pull/1042)
- Deprecated declarative macros for FT impl code generation. [PR 1054](https://github.com/near/near-sdk-rs/pull/1054)

## [4.1.0] - 2022-11-09

Expand Down
95 changes: 85 additions & 10 deletions examples/fungible-token/ft/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,17 @@ NOTES:
use near_contract_standards::fungible_token::metadata::{
FungibleTokenMetadata, FungibleTokenMetadataProvider, FT_METADATA_SPEC,
};
use near_contract_standards::fungible_token::FungibleToken;
use near_contract_standards::fungible_token::{
FungibleToken, FungibleTokenCore, FungibleTokenResolver,
};
use near_contract_standards::storage_management::{
StorageBalance, StorageBalanceBounds, StorageManagement,
};
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::collections::LazyOption;
use near_sdk::json_types::U128;
use near_sdk::{
env, log, near_bindgen, require, AccountId, Balance, BorshStorageKey, PanicOnDefault,
PromiseOrValue,
env, log, near_bindgen, require, AccountId, BorshStorageKey, PanicOnDefault, PromiseOrValue,
};

#[near_bindgen]
Expand Down Expand Up @@ -80,22 +84,93 @@ impl Contract {
owner_id: &owner_id,
amount: &total_supply,
memo: Some("new tokens are minted"),
}.emit();
}
.emit();

this
}
}

#[near_bindgen]
impl FungibleTokenCore for Contract {
#[payable]
fn ft_transfer(&mut self, receiver_id: AccountId, amount: U128, memo: Option<String>) {
self.token.ft_transfer(receiver_id, amount, memo)
}

fn on_account_closed(&mut self, account_id: AccountId, balance: Balance) {
log!("Closed @{} with {}", account_id, balance);
#[payable]
fn ft_transfer_call(
&mut self,
receiver_id: AccountId,
amount: U128,
memo: Option<String>,
msg: String,
) -> PromiseOrValue<U128> {
self.token.ft_transfer_call(receiver_id, amount, memo, msg)
}

fn on_tokens_burned(&mut self, account_id: AccountId, amount: Balance) {
log!("Account @{} burned {}", account_id, amount);
fn ft_total_supply(&self) -> U128 {
self.token.ft_total_supply()
}

fn ft_balance_of(&self, account_id: AccountId) -> U128 {
self.token.ft_balance_of(account_id)
}
}

#[near_bindgen]
impl FungibleTokenResolver for Contract {
#[private]
fn ft_resolve_transfer(
&mut self,
sender_id: AccountId,
receiver_id: AccountId,
amount: U128,
) -> U128 {
let (used_amount, burned_amount) =
self.token.internal_ft_resolve_transfer(&sender_id, receiver_id, amount);
if burned_amount > 0 {
log!("Account @{} burned {}", sender_id, burned_amount);
}
used_amount.into()
}
}

near_contract_standards::impl_fungible_token_core!(Contract, token, on_tokens_burned);
near_contract_standards::impl_fungible_token_storage!(Contract, token, on_account_closed);
#[near_bindgen]
impl StorageManagement for Contract {
#[payable]
fn storage_deposit(
&mut self,
account_id: Option<AccountId>,
registration_only: Option<bool>,
) -> StorageBalance {
self.token.storage_deposit(account_id, registration_only)
}

#[payable]
fn storage_withdraw(&mut self, amount: Option<U128>) -> StorageBalance {
self.token.storage_withdraw(amount)
}

#[payable]
fn storage_unregister(&mut self, force: Option<bool>) -> bool {
#[allow(unused_variables)]
if let Some((account_id, balance)) = self.token.internal_storage_unregister(force) {
log!("Closed @{} with {}", account_id, balance);
true
} else {
false
}
}

fn storage_balance_bounds(&self) -> StorageBalanceBounds {
self.token.storage_balance_bounds()
}

fn storage_balance_of(&self, account_id: AccountId) -> Option<StorageBalance> {
self.token.storage_balance_of(account_id)
}
}

#[near_bindgen]
impl FungibleTokenMetadataProvider for Contract {
Expand Down
3 changes: 1 addition & 2 deletions examples/fungible-token/test-contract-defi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ 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, log, near_bindgen, require, AccountId, Balance, Gas, PanicOnDefault,
PromiseOrValue,
env, log, near_bindgen, require, AccountId, Balance, Gas, PanicOnDefault, PromiseOrValue,
};

const BASE_GAS: u64 = 5_000_000_000_000;
Expand Down
70 changes: 18 additions & 52 deletions examples/fungible-token/tests/workspaces.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@

use near_sdk::json_types::U128;
use near_sdk::ONE_YOCTO;
use near_units::parse_near;
use workspaces::{Account, AccountId, Contract,DevNetwork, Worker};
use workspaces::operations::Function;
use workspaces::result::ValueOrReceiptId;
use workspaces::{Account, AccountId, Contract, DevNetwork, Worker};

async fn register_user(
contract: &Contract,
account_id: &AccountId,
) -> anyhow::Result<()> {
async fn register_user(contract: &Contract, account_id: &AccountId) -> anyhow::Result<()> {
let res = contract
.call("storage_deposit")
.args_json((account_id, Option::<bool>::None))
Expand All @@ -26,8 +22,7 @@ async fn init(
worker: &Worker<impl DevNetwork>,
initial_balance: U128,
) -> anyhow::Result<(Contract, Account, Contract)> {
let ft_contract =
worker.dev_deploy(include_bytes!("../res/fungible_token.wasm")).await?;
let ft_contract = worker.dev_deploy(include_bytes!("../res/fungible_token.wasm")).await?;

let res = ft_contract
.call("new_default_meta")
Expand All @@ -39,12 +34,7 @@ async fn init(

let defi_contract = worker.dev_deploy(include_bytes!("../res/defi.wasm")).await?;

let res = defi_contract
.call("new")
.args_json((ft_contract.id(),))
.max_gas()
.transact()
.await?;
let res = defi_contract.call("new").args_json((ft_contract.id(),)).max_gas().transact().await?;
assert!(res.is_success());

let alice = ft_contract
Expand Down Expand Up @@ -96,18 +86,10 @@ async fn test_simple_transfer() -> anyhow::Result<()> {
.await?;
assert!(res.is_success());

let root_balance = contract
.call("ft_balance_of")
.args_json((contract.id(),))
.view()
.await?
.json::<U128>()?;
let alice_balance = contract
.call("ft_balance_of")
.args_json((alice.id(),))
.view()
.await?
.json::<U128>()?;
let root_balance =
contract.call("ft_balance_of").args_json((contract.id(),)).view().await?.json::<U128>()?;
let alice_balance =
contract.call("ft_balance_of").args_json((alice.id(),)).view().await?.json::<U128>()?;
assert_eq!(initial_balance.0 - transfer_amount.0, root_balance.0);
assert_eq!(transfer_amount.0, alice_balance.0);

Expand Down Expand Up @@ -199,13 +181,13 @@ async fn simulate_transfer_call_with_burned_amount() -> anyhow::Result<()> {
Function::new("ft_transfer_call")
.args_json((defi_contract.id(), transfer_amount, Option::<String>::None, "10"))
.deposit(ONE_YOCTO)
.gas(300_000_000_000_000 / 2)
.gas(300_000_000_000_000 / 2),
)
.call(
Function::new("storage_unregister")
.args_json((Some(true),))
.deposit(ONE_YOCTO)
.gas(300_000_000_000_000 / 2)
.gas(300_000_000_000_000 / 2),
)
.transact()
.await?;
Expand Down Expand Up @@ -261,12 +243,8 @@ async fn simulate_transfer_call_with_immediate_return_and_no_refund() -> anyhow:
.await?;
assert!(res.is_success());

let root_balance = contract
.call("ft_balance_of")
.args_json((contract.id(),))
.view()
.await?
.json::<U128>()?;
let root_balance =
contract.call("ft_balance_of").args_json((contract.id(),)).view().await?.json::<U128>()?;
let defi_balance = contract
.call("ft_balance_of")
.args_json((defi_contract.id(),))
Expand Down Expand Up @@ -298,12 +276,8 @@ async fn simulate_transfer_call_when_called_contract_not_registered_with_ft() ->
assert!(res.is_failure());

// balances remain unchanged
let root_balance = contract
.call("ft_balance_of")
.args_json((contract.id(),))
.view()
.await?
.json::<U128>()?;
let root_balance =
contract.call("ft_balance_of").args_json((contract.id(),)).view().await?.json::<U128>()?;
let defi_balance = contract
.call("ft_balance_of")
.args_json((defi_contract.id(),))
Expand Down Expand Up @@ -341,12 +315,8 @@ async fn simulate_transfer_call_with_promise_and_refund() -> anyhow::Result<()>
.await?;
assert!(res.is_success());

let root_balance = contract
.call("ft_balance_of")
.args_json((contract.id(),))
.view()
.await?
.json::<U128>()?;
let root_balance =
contract.call("ft_balance_of").args_json((contract.id(),)).view().await?.json::<U128>()?;
let defi_balance = contract
.call("ft_balance_of")
.args_json((defi_contract.id(),))
Expand Down Expand Up @@ -394,12 +364,8 @@ async fn simulate_transfer_call_promise_panics_for_a_full_refund() -> anyhow::Re
}

// balances remain unchanged
let root_balance = contract
.call("ft_balance_of")
.args_json((contract.id(),))
.view()
.await?
.json::<U128>()?;
let root_balance =
contract.call("ft_balance_of").args_json((contract.id(),)).view().await?.json::<U128>()?;
let defi_balance = contract
.call("ft_balance_of")
.args_json((defi_contract.id(),))
Expand Down
49 changes: 48 additions & 1 deletion near-contract-standards/src/fungible_token/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,54 @@ use near_sdk::ext_contract;
use near_sdk::json_types::U128;
use near_sdk::AccountId;
use near_sdk::PromiseOrValue;

/// The core methods for a basic fungible token. Extension standards may be
/// added in addition to this trait.
///
/// # Examples
///
/// ```
/// use near_sdk::{near_bindgen, PanicOnDefault, AccountId, PromiseOrValue};
/// use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
/// use near_sdk::collections::LazyOption;
/// use near_sdk::json_types::U128;
/// use near_contract_standards::fungible_token::{FungibleToken, FungibleTokenCore};
/// use near_contract_standards::fungible_token::metadata::FungibleTokenMetadata;
///
/// #[near_bindgen]
/// #[derive(BorshDeserialize, BorshSerialize, PanicOnDefault)]
/// pub struct Contract {
/// token: FungibleToken,
/// metadata: LazyOption<FungibleTokenMetadata>,
/// }
///
/// #[near_bindgen]
/// impl FungibleTokenCore for Contract {
/// #[payable]
/// fn ft_transfer(&mut self, receiver_id: AccountId, amount: U128, memo: Option<String>) {
/// self.token.ft_transfer(receiver_id, amount, memo)
/// }
///
/// #[payable]
/// fn ft_transfer_call(
/// &mut self,
/// receiver_id: AccountId,
/// amount: U128,
/// memo: Option<String>,
/// msg: String,
/// ) -> PromiseOrValue<U128> {
/// self.token.ft_transfer_call(receiver_id, amount, memo, msg)
/// }
///
/// fn ft_total_supply(&self) -> U128 {
/// self.token.ft_total_supply()
/// }
///
/// fn ft_balance_of(&self, account_id: AccountId) -> U128 {
/// self.token.ft_balance_of(account_id)
/// }
/// }
/// ```
///
#[ext_contract(ext_ft_core)]
pub trait FungibleTokenCore {
/// Transfers positive `amount` of tokens from the `env::predecessor_account_id` to `receiver_id`.
Expand Down
6 changes: 6 additions & 0 deletions near-contract-standards/src/fungible_token/macros.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
/// The core methods for a basic fungible token. Extension standards may be
/// added in addition to this macro.
#[macro_export]
#[deprecated(
note = "implement the near_contract_standards::fungible_token::{FungibleTokenCore, FungibleTokenResolver} traits manually instead."
)]
macro_rules! impl_fungible_token_core {
($contract: ident, $token: ident $(, $on_tokens_burned_fn:ident)?) => {
use $crate::fungible_token::core::FungibleTokenCore;
Expand Down Expand Up @@ -64,6 +67,9 @@ macro_rules! impl_fungible_token_core {
/// Takes name of the Contract struct, the inner field for the token and optional method name to
/// call when the account was closed.
#[macro_export]
#[deprecated(
note = "implement the near_contract_standards::fungible_token::StorageManagement trait manually instead."
)]
macro_rules! impl_fungible_token_storage {
($contract: ident, $token: ident $(, $on_account_closed_fn:ident)?) => {
use $crate::storage_management::{
Expand Down
8 changes: 8 additions & 0 deletions near-contract-standards/src/fungible_token/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
//! This module represents a Fungible Token standard.
//!
//! # Examples
//! See [`FungibleTokenCore`] and [`FungibleTokenResolver`] for example usage and [`FungibleToken`]
//! for core standard implementation.

pub mod core;
pub mod core_impl;
pub mod events;
Expand All @@ -7,5 +13,7 @@ pub mod receiver;
pub mod resolver;
pub mod storage_impl;

pub use crate::fungible_token::core::FungibleTokenCore;
frol marked this conversation as resolved.
Show resolved Hide resolved
pub use core_impl::FungibleToken;
pub use macros::*;
pub use resolver::FungibleTokenResolver;
Loading
Loading