Cadence Cookbook

Contribute

Metadata Views

Metadata Views

01 Apr 2022

Contributed by Flow Blockchain

Beginner

This is how you use the metadata contract to actually access the views to show your metadata.

Smart Contract Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 //Here is where the rest of your NFT resource code will go... // Below is the metadata functions to include in your NFT resource... // Checkout the NFT Metadata example to see it all put together pub fun getViews(): [Type] { return [ Type<MetadataViews.Display>() ] } pub fun resolveView(_ view: Type): AnyStruct? { switch view { case Type<MetadataViews.Display>(): return MetadataViews.Display( name: self.name, description: self.description, thumbnail: self.thumbnail ) } return nil } // below is where you will have your metadata in your NFT initialzied ..... //the following code is in your collections resource pub fun borrowViewResolver(id: UInt64): &AnyResource{MetadataViews.Resolver} { let nft = &self.ownedNFTs[id] as auth &NonFungibleToken.NFT let exampleNFT = nft as! &NewExampleNFT.NFT return exampleNFT as &AnyResource{MetadataViews.Resolver} }

The following functions are to be included in your NFT resource when creating a contract.

getViews tells someone all the views your NFT has, while resolveView returns the metadata from that view.

In your Collection resource you will have the borrowViewResolver function that is available in the Metadata Contract. You will need to import the MetadataViews.ResolverCollection interface into your collection.

This returns the capability for the NFT to use the above functions.

Transaction Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 import MetadataViews from 0x01 pub fun main(): AnyStruct { let address: Address = 0x02 let id: UInt64 = 0 let account = getAccount(address) let collection = account .getCapability(/public/exampleNFTCollection) .borrow<&{MetadataViews.ResolverCollection}>() ?? panic("Could not borrow a reference to the collection") let nft = collection.borrowViewResolver(id: id) // Get the basic display information for this NFT let display = nft.resolveView(Type<MetadataViews.Display>()) return display }

Here we borrow the capability to use the borrowViewResolver function.

When that is done, we then have the ability to use the functions resolveView and getViews if they are in our NFT resource.

After that we return the display.


ProgressNFT Fundamentals

Up Next: Multiple Metadata Views

38%


Related Recipes

14 Oct 2022
Mint NFT
Beginner
14 Oct 2022
Collection for Holding NFTs
Beginner
14 Oct 2022
NFT with Metadata
Beginner