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(contract-standards): add events to FT contract standard #723

Merged
merged 5 commits into from
Feb 1, 2022
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
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Changelog

## [unreleased]
- Added event logs to `near-contract-standards`. Currently only NFT related events. [PR 627](https://github.com/near/near-sdk-rs/pull/627)
- Added FT and NFT event logs to `near-contract-standards`. [PR 627](https://github.com/near/near-sdk-rs/pull/627) and [PR 723](https://github.com/near/near-sdk-rs/pull/723)

## `4.0.0-pre.6` [01-21-2021]

Expand Down
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.
Binary file modified examples/non-fungible-token/res/non_fungible_token.wasm
Binary file not shown.
1 change: 1 addition & 0 deletions near-contract-standards/src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use serde::Serialize;
#[serde(rename_all = "snake_case")]
pub(crate) enum NearEvent<'a> {
Nep171(crate::non_fungible_token::events::Nep171Event<'a>),
Nep141(crate::fungible_token::events::Nep141Event<'a>),
}

impl<'a> NearEvent<'a> {
Expand Down
10 changes: 7 additions & 3 deletions near-contract-standards/src/fungible_token/core_impl.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::fungible_token::core::FungibleTokenCore;
use crate::fungible_token::events::FtTransfer;
use crate::fungible_token::resolver::FungibleTokenResolver;
use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize};
use near_sdk::collections::LookupMap;
Expand Down Expand Up @@ -138,10 +139,13 @@ impl FungibleToken {
require!(amount > 0, "The amount should be a positive number");
self.internal_withdraw(sender_id, amount);
self.internal_deposit(receiver_id, amount);
log!("Transfer {} from {} to {}", amount, sender_id, receiver_id);
if let Some(memo) = memo {
log!("Memo: {}", memo);
FtTransfer {
old_owner_id: sender_id,
new_owner_id: receiver_id,
amount: &U128(amount),
memo: memo.as_deref(),
}
.emit();
}

pub fn internal_register_account(&mut self, account_id: &AccountId) {
Expand Down
215 changes: 215 additions & 0 deletions near-contract-standards/src/fungible_token/events.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
//! Standard for nep141 (Fungible Token) events.
//!
//! These events will be picked up by the NEAR indexer.
//!
//! <https://github.com/near/NEPs/blob/master/specs/Standards/FungibleToken/Event.md>
//!
//! This is an extension of the events format (nep-297):
//! <https://github.com/near/NEPs/blob/master/specs/Standards/EventsFormat.md>
//!
//! The three events in this standard are [`FtMint`], [`FtTransfer`], and [`FtBurn`].
//!
//! These events can be logged by calling `.emit()` on them if a single event, or calling
//! [`FtMint::emit_many`], [`FtTransfer::emit_many`],
//! or [`FtBurn::emit_many`] respectively.

use crate::event::NearEvent;
use near_sdk::json_types::U128;
use near_sdk::AccountId;
use serde::Serialize;

/// Data to log for an FT mint event. To log this event, call [`.emit()`](FtMint::emit).
#[must_use]
#[derive(Serialize, Debug, Clone)]
pub struct FtMint<'a> {
pub owner_id: &'a AccountId,
pub amount: &'a U128,
#[serde(skip_serializing_if = "Option::is_none")]
pub memo: Option<&'a str>,
}

impl FtMint<'_> {
/// Logs the event to the host. This is required to ensure that the event is triggered
/// and to consume the event.
pub fn emit(self) {
Self::emit_many(&[self])
}

/// Emits an FT mint event, through [`env::log_str`](near_sdk::env::log_str),
/// where each [`FtMint`] represents the data of each mint.
pub fn emit_many(data: &[FtMint<'_>]) {
new_141_v1(Nep141EventKind::FtMint(data)).emit()
}
}

/// Data to log for an FT transfer event. To log this event,
/// call [`.emit()`](FtTransfer::emit).
#[must_use]
#[derive(Serialize, Debug, Clone)]
pub struct FtTransfer<'a> {
pub old_owner_id: &'a AccountId,
pub new_owner_id: &'a AccountId,
pub amount: &'a U128,
#[serde(skip_serializing_if = "Option::is_none")]
pub memo: Option<&'a str>,
}

impl FtTransfer<'_> {
/// Logs the event to the host. This is required to ensure that the event is triggered
/// and to consume the event.
pub fn emit(self) {
Self::emit_many(&[self])
}

/// Emits an FT transfer event, through [`env::log_str`](near_sdk::env::log_str),
/// where each [`FtTransfer`] represents the data of each transfer.
pub fn emit_many(data: &[FtTransfer<'_>]) {
new_141_v1(Nep141EventKind::FtTransfer(data)).emit()
}
}

/// Data to log for an FT burn event. To log this event, call [`.emit()`](FtBurn::emit).
#[must_use]
#[derive(Serialize, Debug, Clone)]
pub struct FtBurn<'a> {
pub owner_id: &'a AccountId,
pub amount: &'a U128,
#[serde(skip_serializing_if = "Option::is_none")]
pub memo: Option<&'a str>,
}

impl FtBurn<'_> {
/// Logs the event to the host. This is required to ensure that the event is triggered
/// and to consume the event.
pub fn emit(self) {
Self::emit_many(&[self])
}

/// Emits an FT burn event, through [`env::log_str`](near_sdk::env::log_str),
/// where each [`FtBurn`] represents the data of each burn.
pub fn emit_many<'a>(data: &'a [FtBurn<'a>]) {
new_141_v1(Nep141EventKind::FtBurn(data)).emit()
}
}

#[derive(Serialize, Debug)]
pub(crate) struct Nep141Event<'a> {
version: &'static str,
#[serde(flatten)]
event_kind: Nep141EventKind<'a>,
}

#[derive(Serialize, Debug)]
#[serde(tag = "event", content = "data")]
#[serde(rename_all = "snake_case")]
#[allow(clippy::enum_variant_names)]
enum Nep141EventKind<'a> {
FtMint(&'a [FtMint<'a>]),
FtTransfer(&'a [FtTransfer<'a>]),
FtBurn(&'a [FtBurn<'a>]),
}

fn new_141<'a>(version: &'static str, event_kind: Nep141EventKind<'a>) -> NearEvent<'a> {
NearEvent::Nep141(Nep141Event { version, event_kind })
}

fn new_141_v1(event_kind: Nep141EventKind) -> NearEvent {
new_141("1.0.0", event_kind)
}

#[cfg(test)]
mod tests {
use super::*;
use near_sdk::{test_utils, AccountId};

fn bob() -> AccountId {
AccountId::new_unchecked("bob".to_string())
}

fn alice() -> AccountId {
AccountId::new_unchecked("alice".to_string())
}

#[test]
fn ft_mint() {
let owner_id = &bob();
let amount = &U128(100);
FtMint { owner_id, amount, memo: None }.emit();
assert_eq!(
test_utils::get_logs()[0],
r#"EVENT_JSON:{"standard":"nep141","version":"1.0.0","event":"ft_mint","data":[{"owner_id":"bob","amount":"100"}]}"#
);
}

#[test]
fn ft_mints() {
let owner_id = &bob();
let amount = &U128(100);
let mint_log = FtMint { owner_id, amount, memo: None };
FtMint::emit_many(&[
mint_log,
FtMint { owner_id: &alice(), amount: &U128(200), memo: Some("has memo") },
]);
assert_eq!(
test_utils::get_logs()[0],
r#"EVENT_JSON:{"standard":"nep141","version":"1.0.0","event":"ft_mint","data":[{"owner_id":"bob","amount":"100"},{"owner_id":"alice","amount":"200","memo":"has memo"}]}"#
);
}

#[test]
fn ft_burn() {
let owner_id = &bob();
let amount = &U128(100);
FtBurn { owner_id, amount, memo: None }.emit();
assert_eq!(
test_utils::get_logs()[0],
r#"EVENT_JSON:{"standard":"nep141","version":"1.0.0","event":"ft_burn","data":[{"owner_id":"bob","amount":"100"}]}"#
);
}

#[test]
fn nft_burns() {
Copy link
Contributor

Choose a reason for hiding this comment

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

ft_burns

Copy link
Contributor

Choose a reason for hiding this comment

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

Oh it's merged 😅 I just noticed that
Created PR with the fix #735

let owner_id = &bob();
let amount = &U128(100);
FtBurn::emit_many(&[
FtBurn { owner_id: &alice(), amount: &U128(200), memo: Some("has memo") },
FtBurn { owner_id, amount, memo: None },
]);
assert_eq!(
test_utils::get_logs()[0],
r#"EVENT_JSON:{"standard":"nep141","version":"1.0.0","event":"ft_burn","data":[{"owner_id":"alice","amount":"200","memo":"has memo"},{"owner_id":"bob","amount":"100"}]}"#
);
}

#[test]
fn ft_transfer() {
let old_owner_id = &bob();
let new_owner_id = &alice();
let amount = &U128(100);
FtTransfer { old_owner_id, new_owner_id, amount, memo: None }.emit();
assert_eq!(
test_utils::get_logs()[0],
r#"EVENT_JSON:{"standard":"nep141","version":"1.0.0","event":"ft_transfer","data":[{"old_owner_id":"bob","new_owner_id":"alice","amount":"100"}]}"#
);
}

#[test]
fn nft_transfers() {
Copy link
Collaborator

Choose a reason for hiding this comment

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

nit: it should be tf_transfers

Copy link
Contributor

Choose a reason for hiding this comment

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

ft_transfers 🙂

let old_owner_id = &bob();
let new_owner_id = &alice();
let amount = &U128(100);
FtTransfer::emit_many(&[
FtTransfer {
old_owner_id: &alice(),
new_owner_id: &bob(),
amount: &U128(200),
memo: Some("has memo"),
},
FtTransfer { old_owner_id, new_owner_id, amount, memo: None },
]);
assert_eq!(
test_utils::get_logs()[0],
r#"EVENT_JSON:{"standard":"nep141","version":"1.0.0","event":"ft_transfer","data":[{"old_owner_id":"alice","new_owner_id":"bob","amount":"200","memo":"has memo"},{"old_owner_id":"bob","new_owner_id":"alice","amount":"100"}]}"#
);
}
}
1 change: 1 addition & 0 deletions near-contract-standards/src/fungible_token/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
pub mod core;
pub mod core_impl;
pub mod events;
pub mod macros;
pub mod metadata;
pub mod receiver;
Expand Down
18 changes: 9 additions & 9 deletions near-contract-standards/src/non_fungible_token/events.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,17 @@
//! This is an extension of the events format (nep-297):
//! <https://github.com/near/NEPs/blob/master/specs/Standards/EventsFormat.md>
//!
//! The three events in this standard are [`NftMintData`], [`NftTransferData`], and [`NftBurnData`].
//! The three events in this standard are [`NftMint`], [`NftTransfer`], and [`NftBurn`].
Copy link
Member

Choose a reason for hiding this comment

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

Nice, thanks for the catching this!

//!
//! These events can be logged by calling `.emit()` on them if a single event, or calling
//! [`NftMintData::emit_many`], [`NftTransferData::emit_many`],
//! or [`NftBurnData::emit_many`] respectively.
//! [`NftMint::emit_many`], [`NftTransfer::emit_many`],
//! or [`NftBurn::emit_many`] respectively.

use crate::event::NearEvent;
use near_sdk::AccountId;
use serde::Serialize;

/// Data to log for an NFT mint event. To log this event, call [`.emit()`](NftMintData::emit).
/// Data to log for an NFT mint event. To log this event, call [`.emit()`](NftMint::emit).
#[must_use]
#[derive(Serialize, Debug, Clone)]
pub struct NftMint<'a> {
Expand All @@ -35,14 +35,14 @@ impl NftMint<'_> {
}

/// Emits an nft mint event, through [`env::log_str`](near_sdk::env::log_str),
/// where each [`NftMintData`] represents the data of each mint.
/// where each [`NftMint`] represents the data of each mint.
pub fn emit_many(data: &[NftMint<'_>]) {
new_171_v1(Nep171EventKind::NftMint(data)).emit()
}
}

/// Data to log for an NFT transfer event. To log this event,
/// call [`.emit()`](NftTransferData::emit).
/// call [`.emit()`](NftTransfer::emit).
#[must_use]
#[derive(Serialize, Debug, Clone)]
pub struct NftTransfer<'a> {
Expand All @@ -63,13 +63,13 @@ impl NftTransfer<'_> {
}

/// Emits an nft transfer event, through [`env::log_str`](near_sdk::env::log_str),
/// where each [`NftTransferData`] represents the data of each transfer.
/// where each [`NftTransfer`] represents the data of each transfer.
pub fn emit_many(data: &[NftTransfer<'_>]) {
new_171_v1(Nep171EventKind::NftTransfer(data)).emit()
}
}

/// Data to log for an NFT burn event. To log this event, call [`.emit()`](NftBurnData::emit).
/// Data to log for an NFT burn event. To log this event, call [`.emit()`](NftBurn::emit).
#[must_use]
#[derive(Serialize, Debug, Clone)]
pub struct NftBurn<'a> {
Expand All @@ -89,7 +89,7 @@ impl NftBurn<'_> {
}

/// Emits an nft burn event, through [`env::log_str`](near_sdk::env::log_str),
/// where each [`NftBurnData`] represents the data of each burn.
/// where each [`NftBurn`] represents the data of each burn.
pub fn emit_many<'a>(data: &'a [NftBurn<'a>]) {
new_171_v1(Nep171EventKind::NftBurn(data)).emit()
}
Expand Down