Events

To Share and +4 nLEARNs

In this tutorial, you’ll learn about the events standard and how to implement it in your smart contract.

Introduction

To get started, either switch to the 6.royalty branch from our GitHub repository, or continue your work from the previous tutorials.

git checkout 6.royalty
:::tip
If you’re joining us for the first time, feel free to clone this repository and checkout the 6.royalty branch to follow along.
::

Understanding the use case

Have you ever wondered how the wallet knows which NFTs you own and how it can display them in the collectibles tab? Originally, an indexer was used and it listened for any functions starting with nft_ on your account. These contracts were then flagged on your account as likely NFT contracts.

When you navigated to your collectibles tab, the wallet would then query all those contracts for the list of NFTs you owned using the nft_tokens_for_owner function you saw in the enumeration tutorial.

The problem

This method of flagging contracts was not reliable as each NFT-driven application might have its own way of minting or transferring NFTs. In addition, it’s common for apps to transfer or mint many tokens at a time using batch functions.

The solution

A standard was introduced so that smart contracts could emit an event anytime NFTs were transferred, minted, or burnt. This event was in the form of a log. No matter how a contract implemented the functionality, an indexer could now listen for those standardized logs.

As per the standard, you need to implement a logging functionality that gets fired when NFTs are transferred or minted. In this case, the contract doesn’t support burning so you don’t need to worry about that for now.

It’s important to note the standard dictates that the log should begin with "EVENT_JSON:". The structure of your log should, however, always contain the 3 following things:

  • standard: the current name of the standard (e.g. nep171)
  • version: the version of the standard you’re using (e.g. 1.0.0)
  • event: a list of events you’re emitting.

The event interface differs based on whether you’re recording transfers or mints. The interface for both events is outlined below.

Transfer events:

  • Optionalauthorized_id: the account approved to transfer on behalf of the owner.
  • old_owner_id: the old owner of the NFT.
  • new_owner_id: the new owner that the NFT is being transferred to.
  • token_ids: a list of NFTs being transferred.
  • Optionalmemo: an optional message to include with the event.

Minting events:

  • owner_id: the owner that the NFT is being minted to.
  • token_ids: a list of NFTs being transferred.
  • Optionalmemo: an optional message to include with the event.

Examples

In order to solidify your understanding of the standard, let’s walk through three scenarios and see what the logs should look like.

Scenario A – simple mint

In this scenario, Benji wants to mint an NFT to Mike with a token ID "team-token" and he doesn’t include a message. The log should look as follows.

EVENT_JSON:{
  "standard": "nep171",
  "version": "1.0.0",
  "event": "nft_mint",
  "data": [
    {"owner_id": "mike.testnet", "token_ids": ["team-token"]}
  ]
}

Scenario B – batch mint

In this scenario, Benji wants to perform a batch mint. He will mint an NFT to Mike, Damian, Josh, and Dorian. Dorian, however, will get two NFTs. Each token ID will be "team-token" followed by an incrementing number. The log is as follows.

EVENT_JSON:{
  "standard": "nep171",
  "version": "1.0.0",
  "event": "nft_mint",
  "data": [
    {"owner_id": "mike.testnet", "token_ids": ["team-token0"]},
    {"owner_id": "damian.testnet", "token_ids": ["team-token1"]},
    {"owner_id": "josh.testnet", "token_ids": ["team-token2"]}
    {"owner_id": "dorian.testnet", "token_ids": ["team-token3", "team-token4"]},
  ]
}

Scenario C – transfer NFTs

In this scenario, Mike is transferring both his team tokens to Josh. The log should look as follows.

EVENT_JSON:{
  "standard": "nep171",
  "version": "1.0.0",
  "event": "nft_transfer",
  "data": [
    {"old_owner_id": "mike.testnet", "new_owner_id": "josh.testnet", "token_ids": ["team-token", "team-token0"], "memo": "Go Team!"}
  ]
}

Modifications to the contract

At this point, you should have a good understanding of what the end goal should be so let’s get to work! Open the repository and create a new file in the nft-contract/src directory called events.rs. This is where your log structs will live.

Creating the events file

Copy the following into your file. This will outline the structs for your EventLog, NftMintLog, and NftTransferLog. In addition, we’ve added a way for EVENT_JSON: to be prefixed whenever you log the EventLog.

https://github.com/near-examples/nft-tutorial/blob/7.events/nft-contract/src/events.rs#L1-L79

This requires the serde_json package which you can easily add to your nft-contract/Cargo.toml file:

https://github.com/near-examples/nft-tutorial/blob/7.events/nft-contract/Cargo.toml#L1-L20

Adding modules and constants

Now that you’ve created a new file, you need to add the module to the lib.rs file. In addition, you can define two constants for the standard and version that will be used across our contract.

https://github.com/near-examples/nft-tutorial/blob/7.events/nft-contract/src/lib.rs#L10-L30

Logging minted tokens

Now that all the tools are set in place, you can now implement the actual logging functionality. Since the contract will only be minting tokens in one place, it’s trivial where you should place the log. Open the nft-contract/src/mint.rs file and navigate to the bottom of the file. This is where you’ll construct the log for minting. Anytime someone successfully mints an NFT, it will now correctly emit a log.

https://github.com/near-examples/nft-tutorial/blob/7.events/nft-contract/src/mint.rs#L52-L81

Logging transfers

Let’s open the nft-contract/src/internal.rs file and navigate to the internal_transfer function. This is the location where you’ll build your transfer logs. Whenever an NFT is transferred, this function is called and so you’ll correctly be logging the transfers.

https://github.com/near-examples/nft-tutorial/blob/7.events/nft-contract/src/internal.rs#L201-L241

This solution, unfortunately, has an edge case which will break things. If an NFT is transferred via the nft_transfer_call function, there’s a chance that the transfer will be reverted if the nft_on_transfer function returns true. Taking a look at the logic for nft_transfer_call, you can see why this is a problem.

When nft_transfer_call is invoked, it will:

  • Call internal_transfer to perform the actual transfer logic.
  • Initiate a cross-contract call and invoke the nft_on_transfer function.
  • Resolve the promise and perform logic in nft_resolve_transfer.
    • This will either return true meaning the transfer went fine or it will revert the transfer and return false.

If you only place the log in the internal_transfer function, the log will be emitted and the indexer will think that the NFT was transferred. If the transfer is reverted during nft_resolve_transfer, however, that event should also be emitted. Anywhere that an NFT could be transferred, we should add logs. Replace the nft_resolve_transfer with the following code.

https://github.com/near-examples/nft-tutorial/blob/7.events/nft-contract/src/nft_core.rs#L216-L314

In addition, you need to add an authorized_id and memo to the parameters for nft_resolve_transfer as shown below.

https://github.com/near-examples/nft-tutorial/blob/7.events/nft-contract/src/nft_core.rs#L49-L88

This solution, however, still has an edge case which will break things. If a user were to invoke nft_transfer_call and they attached enough GAS for internal_transfer to go through, but not enough GAS to invoke the cross-contract call, it would log that the NFT was transferred, but panic and revert all the logic since there wasn’t enough GAS.

A simple fix for this is to make sure that the user will always have enough GAS by adding an assertion. Add the following constant to the top of your nft_core.rs file:

https://github.com/near-examples/nft-tutorial/blob/7.events/nft-contract/src/nft_core.rs#L4-L7

You can then assert that the user has attached more GAS than the constant you’ve declared above. This will make sure that the user has at least 100 TGas to complete the nft_transfer_call logic.

https://github.com/near-examples/nft-tutorial/blob/7.events/nft-contract/src/nft_core.rs#L125-L194

With that finished, you’ve successfully implemented the events standard and it’s time to start testing.

Deploying the contract

For the purpose of readability and ease of development, instead of redeploying the contract to the same account, let’s create a sub-account and deploy to that instead. You could have deployed to the same account as none of the changes you implemented in this tutorial would have caused errors.

Creating a sub-account

Run the following command to create a sub-account events of your main account with an initial balance of 25 NEAR which will be transferred from the original to your new account.

near create-account events.$NFT_CONTRACT_ID --masterAccount $NFT_CONTRACT_ID --initialBalance 25

Next, you’ll want to export an environment variable for ease of development:

export EVENTS_NFT_CONTRACT_ID=events.$NFT_CONTRACT_ID

Using the build script, build the deploy the contract as you did in the previous tutorials:

yarn build && near deploy --wasmFile out/main.wasm --accountId $EVENTS_NFT_CONTRACT_ID

Initialization and minting

Since this is a new contract, you’ll need to initialize and mint a token. Use the following command to initialize the contract:

near call $EVENTS_NFT_CONTRACT_ID new_default_meta '{"owner_id": "'$EVENTS_NFT_CONTRACT_ID'"}' --accountId $EVENTS_NFT_CONTRACT_ID

Next, you’ll need to mint a token. By running this command, you’ll mint a token with a token ID "events-token" and the receiver will be your new account. In addition, you’re passing in a map with two accounts that will get perpetual royalties whenever your token is sold.

near call $EVENTS_NFT_CONTRACT_ID nft_mint '{"token_id": "events-token", "metadata": {"title": "Events Token", "description": "testing out the new events extension of the standard", "media": "https://bafybeiftczwrtyr3k7a2k4vutd3amkwsmaqyhrdzlhvpt33dyjivufqusq.ipfs.dweb.link/goteam-gif.gif"}, "receiver_id": "'$EVENTS_NFT_CONTRACT_ID'"}' --accountId $EVENTS_NFT_CONTRACT_ID --amount 0.1

You can check to see if everything went through properly by looking at the output in your CLI:

Doing account.functionCall()
Receipts: F4oxNfv54cqwUwLUJ7h74H1iE66Y3H7QDfZMmGENwSxd, BJxKNFRuLDdbhbGeLA3UBSbL8UicU7oqHsWGink5WX7S
    Log [events.goteam.examples.testnet]: EVENT_JSON:{"standard":"nep171","version":"1.0.0","event":"nft_mint","data":[{"owner_id":"events.goteam.examples.testnet","token_ids":["events-token"]}]}
Transaction Id 4Wy2KQVTuAWQHw5jXcRAbrz7bNyZBoiPEvLcGougciyk
To see the transaction in the transaction explorer, please open this url in your browser
https://explorer.testnet.near.org/transactions/4Wy2KQVTuAWQHw5jXcRAbrz7bNyZBoiPEvLcGougciyk
''

You can see that the event was properly logged!

Transferring

You can now test if your transfer log works as expected by sending benjiman.testnet your NFT.

near call $EVENTS_NFT_CONTRACT_ID nft_transfer '{"receiver_id": "benjiman.testnet", "token_id": "events-token", "memo": "Go Team :)", "approval_id": 0}' --accountId $EVENTS_NFT_CONTRACT_ID --depositYocto 1

This should return an output similar to the following:

Doing account.functionCall()
Receipts: EoqBxrpv9Dgb8KqK4FdeREawVVLWepEUR15KPNuZ4fGD, HZ4xQpbgc8EfU3PiV72LvfXb2f3dVC1n9aVTbQds9zfR
    Log [events.goteam.examples.testnet]: Memo: Go Team :)
    Log [events.goteam.examples.testnet]: EVENT_JSON:{"standard":"nep171","version":"1.0.0","event":"nft_transfer","data":[{"authorized_id":"events.goteam.examples.testnet","old_owner_id":"events.goteam.examples.testnet","new_owner_id":"benjiman.testnet","token_ids":["events-token"],"memo":"Go Team :)"}]}
Transaction Id 4S1VrepKzA6HxvPj3cK12vaT7Dt4vxJRWESA1ym1xdvH
To see the transaction in the transaction explorer, please open this url in your browser
https://explorer.testnet.near.org/transactions/4S1VrepKzA6HxvPj3cK12vaT7Dt4vxJRWESA1ym1xdvH
''

Hurray! At this point, your NFT contract is fully complete and the events standard has been implemented.

Conclusion

Today you went through the events standard and implemented the necessary logic in your smart contract. You created events for minting and transferring NFTs. You then deployed and tested your changes by minting and transferring NFTs.

In the next tutorial, you’ll look at the basics of a marketplace contract and how it was built.

Generate comment with AI 2 nL
Scroll to Top