From 55dfbfd9b9e06f4de8dba2036cf096b063364e1c Mon Sep 17 00:00:00 2001 From: Lea Lobanov Date: Mon, 18 Nov 2024 19:56:49 +0100 Subject: [PATCH 1/6] C1 migration --- cadence/contract.cdc | 33 +++++++++++++++++++++------------ cadence/transaction.cdc | 19 ++++++++++--------- index.js | 4 ++-- 3 files changed, 33 insertions(+), 23 deletions(-) diff --git a/cadence/contract.cdc b/cadence/contract.cdc index c983174..30bb4ea 100644 --- a/cadence/contract.cdc +++ b/cadence/contract.cdc @@ -1,22 +1,31 @@ -pub resource NFT: NonFungibleToken.INFT, MetadataViews.Resolver { - pub let id: UInt64 +access(all) +resource NFT: NonFungibleToken.INFT, MetadataViews.Resolver { + access(all) + let id: UInt64 - pub let name: String - pub let thumbnail: String - pub let description: String - pub let power: String - pub let will: String - pub let determination: String + access(all) + let name: String + access(all) + let thumbnail: String + access(all) + let description: String + access(all) + let power: String + access(all) + let will: String + access(all) + let determination: String - - pub fun getViews(): [Type] { + access(all) + fun getViews(): [Type] { return [ Type(), Type() ] } - pub fun resolveView(_ view: Type): AnyStruct? { + access(all) + fun resolveView(_ view: Type): AnyStruct? { switch view { case Type(): return MetadataViews.Display( @@ -52,6 +61,6 @@ pub resource NFT: NonFungibleToken.INFT, MetadataViews.Resolver { self.description = description self.power = power self.will = will - self.determination= determination + self.determination = determination } } diff --git a/cadence/transaction.cdc b/cadence/transaction.cdc index 6da8d6a..85b2684 100644 --- a/cadence/transaction.cdc +++ b/cadence/transaction.cdc @@ -5,22 +5,23 @@ import NewExampleNFT from 0x02 // It must be run with the account that has the minter resource // stored in /storage/NFTMinter -transaction{ +transaction { - // local variable for storing the minter reference - let minter: &NewExampleNFT.NFTMinter + // Local variable for storing the minter reference + let minter: auth(MinterEntitlement) &NewExampleNFT.NFTMinter - prepare(signer: AuthAccount) { - // borrow a reference to the NFTMinter resource in storage - self.minter = signer.borrow<&NewExampleNFT.NFTMinter>(from: NewExampleNFT.MinterStoragePath) - ?? panic("Could not borrow a reference to the NFT minter") + prepare(signer: auth(Storage, Capabilities) &Account) { + // Borrow a reference to the NFTMinter resource in storage + self.minter = signer.capabilities.storage.borrow<&NewExampleNFT.NFTMinter>( + from: NewExampleNFT.MinterStoragePath + ) ?? panic("Could not borrow a reference to the NFT minter") } execute { // Borrow the recipient's public NFT collection reference let receiver = getAccount(0x02) - .getCapability(NewExampleNFT.CollectionPublicPath) - .borrow<&{NonFungibleToken.CollectionPublic}>() + .capabilities + .borrow<&{NonFungibleToken.CollectionPublic}>(NewExampleNFT.CollectionPublicPath) ?? panic("Could not get receiver reference to the NFT Collection") // Mint the NFT and deposit it to the recipient's collection diff --git a/index.js b/index.js index aca1f13..d01e87c 100644 --- a/index.js +++ b/index.js @@ -23,6 +23,6 @@ export const nftWithMetdata = { transactionCode: transactionPath, transactionExplanation: transactionExplanationPath, filters: { - difficulty: "beginner" - } + difficulty: "beginner", + }, }; From df1ab101b31d11aa476ab2d63257b0a278360864 Mon Sep 17 00:00:00 2001 From: Lea Lobanov Date: Fri, 29 Nov 2024 14:10:05 +0000 Subject: [PATCH 2/6] Add GH CI and flow config --- .github/workflows/cadence_lint.yml | 30 +++++++++++++++++++++++++ .github/workflows/cadence_tests.yml | 34 +++++++++++++++++++++++++++++ flow.json | 16 ++++++++++++++ 3 files changed, 80 insertions(+) create mode 100644 .github/workflows/cadence_lint.yml create mode 100644 .github/workflows/cadence_tests.yml create mode 100644 flow.json diff --git a/.github/workflows/cadence_lint.yml b/.github/workflows/cadence_lint.yml new file mode 100644 index 0000000..58565d0 --- /dev/null +++ b/.github/workflows/cadence_lint.yml @@ -0,0 +1,30 @@ +name: Run Cadence Lint +on: push + +jobs: + run-cadence-lint: + runs-on: macos-latest + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + submodules: 'true' + + - name: Install Flow CLI + run: | + brew update + brew install flow-cli + + - name: Initialize Flow + run: | + if [ ! -f flow.json ]; then + echo "Initializing Flow project..." + flow init + else + echo "Flow project already initialized." + fi + + - name: Run Cadence Lint + run: | + echo "Running Cadence linter on all .cdc files in the current repository" + flow cadence lint **/*.cdc diff --git a/.github/workflows/cadence_tests.yml b/.github/workflows/cadence_tests.yml new file mode 100644 index 0000000..9a51f78 --- /dev/null +++ b/.github/workflows/cadence_tests.yml @@ -0,0 +1,34 @@ +name: Run Cadence Tests +on: push + +jobs: + run-cadence-tests: + runs-on: macos-latest + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + submodules: 'true' + + - name: Install Flow CLI + run: | + brew update + brew install flow-cli + + - name: Initialize Flow + run: | + if [ ! -f flow.json ]; then + echo "Initializing Flow project..." + flow init + else + echo "Flow project already initialized." + fi + + - name: Run Cadence Tests + run: | + if test -f "cadence/tests.cdc"; then + echo "Running Cadence tests in the current repository" + flow test cadence/tests.cdc + else + echo "No Cadence tests found. Skipping tests." + fi diff --git a/flow.json b/flow.json new file mode 100644 index 0000000..e81ec35 --- /dev/null +++ b/flow.json @@ -0,0 +1,16 @@ +{ + "contracts": { + "Counter": { + "source": "cadence/contracts/Counter.cdc", + "aliases": { + "testing": "0000000000000007" + } + } + }, + "networks": { + "emulator": "127.0.0.1:3569", + "mainnet": "access.mainnet.nodes.onflow.org:9000", + "testing": "127.0.0.1:3569", + "testnet": "access.devnet.nodes.onflow.org:9000" + } +} \ No newline at end of file From 588eeef357baf69842b4a095877e2b7f351bcbbf Mon Sep 17 00:00:00 2001 From: Lea Lobanov Date: Thu, 12 Dec 2024 01:25:20 +0400 Subject: [PATCH 3/6] Repo structure --- .github/workflows/cadence_lint.yml | 29 ++- .gitignore | 4 +- cadence/contract.cdc | 67 +----- cadence/contracts/Recipe.cdc | 369 +++++++++++++++++++++++++++++ cadence/tests/Recipe_test.cdc | 6 + cadence/transaction.cdc | 41 +--- cadence/transactions/mint_nft.cdc | 40 ++++ emulator-account.pkey | 1 + flow.json | 96 +++++++- 9 files changed, 539 insertions(+), 114 deletions(-) mode change 100644 => 120000 cadence/contract.cdc create mode 100644 cadence/contracts/Recipe.cdc create mode 100644 cadence/tests/Recipe_test.cdc mode change 100644 => 120000 cadence/transaction.cdc create mode 100644 cadence/transactions/mint_nft.cdc create mode 100644 emulator-account.pkey diff --git a/.github/workflows/cadence_lint.yml b/.github/workflows/cadence_lint.yml index 58565d0..1100626 100644 --- a/.github/workflows/cadence_lint.yml +++ b/.github/workflows/cadence_lint.yml @@ -1,4 +1,4 @@ -name: Run Cadence Lint +name: Run Cadence Contract Compilation, Deployment, Transaction Execution, and Lint on: push jobs: @@ -9,7 +9,7 @@ jobs: uses: actions/checkout@v3 with: submodules: 'true' - + - name: Install Flow CLI run: | brew update @@ -23,8 +23,29 @@ jobs: else echo "Flow project already initialized." fi + flow dependencies install + + - name: Start Flow Emulator + run: | + echo "Starting Flow emulator in the background..." + nohup flow emulator start > emulator.log 2>&1 & + sleep 5 # Wait for the emulator to start + flow project deploy --network=emulator # Deploy the recipe contracts indicated in flow.json + + - name: Run All Transactions + run: | + echo "Running all transactions in the transactions folder..." + for file in ./cadence/transactions/*.cdc; do + echo "Running transaction: $file" + TRANSACTION_OUTPUT=$(flow transactions send "$file" --signer emulator-account) + echo "$TRANSACTION_OUTPUT" + if echo "$TRANSACTION_OUTPUT" | grep -q "Transaction Error"; then + echo "Transaction Error detected in $file, failing the action..." + exit 1 + fi + done - name: Run Cadence Lint run: | - echo "Running Cadence linter on all .cdc files in the current repository" - flow cadence lint **/*.cdc + echo "Running Cadence linter on .cdc files in the current repository" + flow cadence lint ./cadence/**/*.cdc diff --git a/.gitignore b/.gitignore index 496ee2c..b1d92af 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,3 @@ -.DS_Store \ No newline at end of file +.DS_Store +/imports/ +/.idea/ \ No newline at end of file diff --git a/cadence/contract.cdc b/cadence/contract.cdc deleted file mode 100644 index 30bb4ea..0000000 --- a/cadence/contract.cdc +++ /dev/null @@ -1,66 +0,0 @@ -access(all) -resource NFT: NonFungibleToken.INFT, MetadataViews.Resolver { - access(all) - let id: UInt64 - - access(all) - let name: String - access(all) - let thumbnail: String - access(all) - let description: String - access(all) - let power: String - access(all) - let will: String - access(all) - let determination: String - - access(all) - fun getViews(): [Type] { - return [ - Type(), - Type() - ] - } - - access(all) - fun resolveView(_ view: Type): AnyStruct? { - switch view { - case Type(): - return MetadataViews.Display( - name: self.name, - description: self.description, - thumbnail: MetadataViews.HTTPFile( - url: self.thumbnail - ) - ) - case Type(): - return NewExampleNFT.Traits( - power: self.power, - will: self.will, - determination: self.determination - ) - } - - return nil - } - - init( - id: UInt64, - name: String, - description: String, - thumbnail: String, - power: String, - will: String, - determination: String - ) { - self.id = id - self.name = name - self.thumbnail = thumbnail - self.description = description - self.power = power - self.will = will - self.determination = determination - } -} diff --git a/cadence/contract.cdc b/cadence/contract.cdc new file mode 120000 index 0000000..b64184f --- /dev/null +++ b/cadence/contract.cdc @@ -0,0 +1 @@ +./cadence/contracts/Recipe.cdc \ No newline at end of file diff --git a/cadence/contracts/Recipe.cdc b/cadence/contracts/Recipe.cdc new file mode 100644 index 0000000..0850b8a --- /dev/null +++ b/cadence/contracts/Recipe.cdc @@ -0,0 +1,369 @@ +/* +* +* This is an example implementation of a Flow Non-Fungible Token +* using the V2 standard: https://github.com/onflow/flow-nft/blob/master/contracts/ExampleNFT.cdc +* It is not part of the official standard but it assumed to be +* similar to how many NFTs would implement the core functionality. +* +* This contract does not implement any sophisticated classification +* system for its NFTs. It defines a simple NFT with minimal metadata. +* +*/ + +import "NonFungibleToken" +import "ViewResolver" +import "MetadataViews" + +access(all) contract ExampleNFT: NonFungibleToken { + + /// Standard Paths + access(all) let CollectionStoragePath: StoragePath + access(all) let CollectionPublicPath: PublicPath + + /// Path where the minter should be stored + /// The standard paths for the collection are stored in the collection resource type + access(all) let MinterStoragePath: StoragePath + + /// We choose the name NFT here, but this type can have any name now + /// because the interface does not require it to have a specific name any more + access(all) resource NFT: NonFungibleToken.NFT { + + access(all) let id: UInt64 + + /// From the Display metadata view + access(all) let name: String + access(all) let description: String + access(all) let thumbnail: String + + /// For the Royalties metadata view + access(self) let royalties: [MetadataViews.Royalty] + + /// Generic dictionary of traits the NFT has + access(self) let metadata: {String: AnyStruct} + + init( + name: String, + description: String, + thumbnail: String, + royalties: [MetadataViews.Royalty], + metadata: {String: AnyStruct}, + ) { + self.id = self.uuid + self.name = name + self.description = description + self.thumbnail = thumbnail + self.royalties = royalties + self.metadata = metadata + } + + /// createEmptyCollection creates an empty Collection + /// and returns it to the caller so that they can own NFTs + /// @{NonFungibleToken.Collection} + access(all) fun createEmptyCollection(): @{NonFungibleToken.Collection} { + return <-ExampleNFT.createEmptyCollection(nftType: Type<@ExampleNFT.NFT>()) + } + + access(all) view fun getViews(): [Type] { + return [ + Type(), + Type(), + Type(), + Type(), + Type(), + Type(), + Type(), + Type(), + Type() + ] + } + + access(all) fun resolveView(_ view: Type): AnyStruct? { + switch view { + case Type(): + return MetadataViews.Display( + name: self.name, + description: self.description, + thumbnail: MetadataViews.HTTPFile( + url: self.thumbnail + ) + ) + case Type(): + // There is no max number of NFTs that can be minted from this contract + // so the max edition field value is set to nil + let editionInfo = MetadataViews.Edition(name: "Example NFT Edition", number: self.id, max: nil) + let editionList: [MetadataViews.Edition] = [editionInfo] + return MetadataViews.Editions( + editionList + ) + case Type(): + return MetadataViews.Serial( + self.id + ) + case Type(): + return MetadataViews.Royalties( + self.royalties + ) + case Type(): + return MetadataViews.ExternalURL("https://example-nft.onflow.org/".concat(self.id.toString())) + case Type(): + return ExampleNFT.resolveContractView(resourceType: Type<@ExampleNFT.NFT>(), viewType: Type()) + case Type(): + return ExampleNFT.resolveContractView(resourceType: Type<@ExampleNFT.NFT>(), viewType: Type()) + case Type(): + // exclude mintedTime and foo to show other uses of Traits + let excludedTraits = ["mintedTime", "foo"] + let traitsView = MetadataViews.dictToTraits(dict: self.metadata, excludedNames: excludedTraits) + + // mintedTime is a unix timestamp, we should mark it with a displayType so platforms know how to show it. + if let mintedTime = self.metadata["mintedTime"] as? String { + let mintedTimeTrait = MetadataViews.Trait(name: "mintedTime", value: mintedTime, displayType: "Date", rarity: nil) + traitsView.addTrait(mintedTimeTrait) + } + + // foo is a trait with its own rarity + let fooTraitRarity = MetadataViews.Rarity(score: 10.0, max: 100.0, description: "Common") + let fooTrait = MetadataViews.Trait(name: "foo", value: self.metadata["foo"], displayType: nil, rarity: fooTraitRarity) + traitsView.addTrait(fooTrait) + + return traitsView + case Type(): + // Implementing this view gives the project control over how the bridged NFT is represented as an + // ERC721 when bridged to EVM on Flow via the public infrastructure bridge. + + // Get the contract-level name and symbol values + let contractLevel = ExampleNFT.resolveContractView( + resourceType: nil, + viewType: Type() + ) as! MetadataViews.EVMBridgedMetadata? + + if let contractMetadata = contractLevel { + // Compose the token-level URI based on a base URI and the token ID, pointing to a JSON file. This + // would be a file you've uploaded and are hosting somewhere - in this case HTTP, but this could be + // IPFS, S3, a data URL containing the JSON directly, etc. + let baseURI = "https://example-nft.onflow.org/token-metadata/" + let uriValue = self.id.toString().concat(".json") + + return MetadataViews.EVMBridgedMetadata( + name: contractMetadata.name, + symbol: contractMetadata.symbol, + uri: MetadataViews.URI( + baseURI: baseURI, // defining baseURI results in a concatenation of baseURI and value + value: self.id.toString().concat(".json") + ) + ) + } else { + return nil + } + } + return nil + } + } + + // Deprecated: Only here for backward compatibility. + access(all) resource interface ExampleNFTCollectionPublic {} + + access(all) resource Collection: NonFungibleToken.Collection, ExampleNFTCollectionPublic { + /// dictionary of NFT conforming tokens + /// NFT is a resource type with an `UInt64` ID field + access(all) var ownedNFTs: @{UInt64: {NonFungibleToken.NFT}} + + init () { + self.ownedNFTs <- {} + } + + /// getSupportedNFTTypes returns a list of NFT types that this receiver accepts + access(all) view fun getSupportedNFTTypes(): {Type: Bool} { + let supportedTypes: {Type: Bool} = {} + supportedTypes[Type<@ExampleNFT.NFT>()] = true + return supportedTypes + } + + /// Returns whether or not the given type is accepted by the collection + /// A collection that can accept any type should just return true by default + access(all) view fun isSupportedNFTType(type: Type): Bool { + return type == Type<@ExampleNFT.NFT>() + } + + /// withdraw removes an NFT from the collection and moves it to the caller + access(NonFungibleToken.Withdraw) fun withdraw(withdrawID: UInt64): @{NonFungibleToken.NFT} { + let token <- self.ownedNFTs.remove(key: withdrawID) + ?? panic("ExampleNFT.Collection.withdraw: Could not withdraw an NFT with ID " + .concat(withdrawID.toString()) + .concat(". Check the submitted ID to make sure it is one that this collection owns.")) + + return <-token + } + + /// deposit takes a NFT and adds it to the collections dictionary + /// and adds the ID to the id array + access(all) fun deposit(token: @{NonFungibleToken.NFT}) { + let token <- token as! @ExampleNFT.NFT + let id = token.id + + // add the new token to the dictionary which removes the old one + let oldToken <- self.ownedNFTs[token.id] <- token + + destroy oldToken + + // This code is for testing purposes only + // Do not add to your contract unless you have a specific + // reason to want to emit the NFTUpdated event somewhere + // in your contract + let authTokenRef = (&self.ownedNFTs[id] as auth(NonFungibleToken.Update) &{NonFungibleToken.NFT}?)! + //authTokenRef.updateTransferDate(date: getCurrentBlock().timestamp) + ExampleNFT.emitNFTUpdated(authTokenRef) + } + + /// getIDs returns an array of the IDs that are in the collection + access(all) view fun getIDs(): [UInt64] { + return self.ownedNFTs.keys + } + + /// Gets the amount of NFTs stored in the collection + access(all) view fun getLength(): Int { + return self.ownedNFTs.length + } + + access(all) view fun borrowNFT(_ id: UInt64): &{NonFungibleToken.NFT}? { + return &self.ownedNFTs[id] + } + + /// Borrow the view resolver for the specified NFT ID + access(all) view fun borrowViewResolver(id: UInt64): &{ViewResolver.Resolver}? { + if let nft = &self.ownedNFTs[id] as &{NonFungibleToken.NFT}? { + return nft as &{ViewResolver.Resolver} + } + return nil + } + + /// createEmptyCollection creates an empty Collection of the same type + /// and returns it to the caller + /// @return A an empty collection of the same type + access(all) fun createEmptyCollection(): @{NonFungibleToken.Collection} { + return <-ExampleNFT.createEmptyCollection(nftType: Type<@ExampleNFT.NFT>()) + } + } + + /// createEmptyCollection creates an empty Collection for the specified NFT type + /// and returns it to the caller so that they can own NFTs + access(all) fun createEmptyCollection(nftType: Type): @{NonFungibleToken.Collection} { + return <- create Collection() + } + + /// Function that returns all the Metadata Views implemented by a Non Fungible Token + /// + /// @return An array of Types defining the implemented views. This value will be used by + /// developers to know which parameter to pass to the resolveView() method. + /// + access(all) view fun getContractViews(resourceType: Type?): [Type] { + return [ + Type(), + Type(), + Type() + ] + } + + /// Function that resolves a metadata view for this contract. + /// + /// @param view: The Type of the desired view. + /// @return A structure representing the requested view. + /// + access(all) fun resolveContractView(resourceType: Type?, viewType: Type): AnyStruct? { + switch viewType { + case Type(): + let collectionData = MetadataViews.NFTCollectionData( + storagePath: self.CollectionStoragePath, + publicPath: self.CollectionPublicPath, + publicCollection: Type<&ExampleNFT.Collection>(), + publicLinkedType: Type<&ExampleNFT.Collection>(), + createEmptyCollectionFunction: (fun(): @{NonFungibleToken.Collection} { + return <-ExampleNFT.createEmptyCollection(nftType: Type<@ExampleNFT.NFT>()) + }) + ) + return collectionData + case Type(): + let media = MetadataViews.Media( + file: MetadataViews.HTTPFile( + url: "https://assets.website-files.com/5f6294c0c7a8cdd643b1c820/5f6294c0c7a8cda55cb1c936_Flow_Wordmark.svg" + ), + mediaType: "image/svg+xml" + ) + return MetadataViews.NFTCollectionDisplay( + name: "The Example Collection", + description: "This collection is used as an example to help you develop your next Flow NFT.", + externalURL: MetadataViews.ExternalURL("https://example-nft.onflow.org"), + squareImage: media, + bannerImage: media, + socials: { + "twitter": MetadataViews.ExternalURL("https://twitter.com/flow_blockchain") + } + ) + case Type(): + // Implementing this view gives the project control over how the bridged NFT is represented as an ERC721 + // when bridged to EVM on Flow via the public infrastructure bridge. + + // Compose the contract-level URI. In this case, the contract metadata is located on some HTTP host, + // but it could be IPFS, S3, a data URL containing the JSON directly, etc. + return MetadataViews.EVMBridgedMetadata( + name: "ExampleNFT", + symbol: "XMPL", + uri: MetadataViews.URI( + baseURI: nil, // setting baseURI as nil sets the given value as the uri field value + value: "https://example-nft.onflow.org/contract-metadata.json" + ) + ) + } + return nil + } + + /// Resource that an admin or something similar would own to be + /// able to mint new NFTs + /// + access(all) resource NFTMinter { + + /// mintNFT mints a new NFT with a new ID + /// and returns it to the calling context + access(all) fun mintNFT( + name: String, + description: String, + thumbnail: String, + royalties: [MetadataViews.Royalty], + metadata: {String: String}, + ): @ExampleNFT.NFT { + + //let metadata: {String: AnyStruct} = {} + let currentBlock = getCurrentBlock() + + // create a new NFT + var newNFT <- create NFT( + name: name, + description: description, + thumbnail: thumbnail, + royalties: royalties, + metadata: metadata, + ) + + return <-newNFT + } + } + + init() { + + // Set the named paths + self.CollectionStoragePath = /storage/exampleNFTCollection + self.CollectionPublicPath = /public/exampleNFTCollection + self.MinterStoragePath = /storage/exampleNFTMinter + + // Create a Collection resource and save it to storage + let collection <- create Collection() + self.account.storage.save(<-collection, to: self.CollectionStoragePath) + + // create a public capability for the collection + let collectionCap = self.account.capabilities.storage.issue<&ExampleNFT.Collection>(self.CollectionStoragePath) + self.account.capabilities.publish(collectionCap, at: self.CollectionPublicPath) + + // Create a Minter resource and save it to storage + let minter: @ExampleNFT.NFTMinter <- create NFTMinter() + self.account.storage.save(<-minter, to: self.MinterStoragePath) + } +} \ No newline at end of file diff --git a/cadence/tests/Recipe_test.cdc b/cadence/tests/Recipe_test.cdc new file mode 100644 index 0000000..986e8fe --- /dev/null +++ b/cadence/tests/Recipe_test.cdc @@ -0,0 +1,6 @@ +import Test + +access(all) fun testExample() { + let array = [1, 2, 3] + Test.expect(array.length, Test.equal(3)) +} diff --git a/cadence/transaction.cdc b/cadence/transaction.cdc deleted file mode 100644 index 85b2684..0000000 --- a/cadence/transaction.cdc +++ /dev/null @@ -1,40 +0,0 @@ -import NonFungibleToken from 0x03 -import NewExampleNFT from 0x02 - -// This transaction uses the NFTMinter resource to mint a new NFT -// It must be run with the account that has the minter resource -// stored in /storage/NFTMinter - -transaction { - - // Local variable for storing the minter reference - let minter: auth(MinterEntitlement) &NewExampleNFT.NFTMinter - - prepare(signer: auth(Storage, Capabilities) &Account) { - // Borrow a reference to the NFTMinter resource in storage - self.minter = signer.capabilities.storage.borrow<&NewExampleNFT.NFTMinter>( - from: NewExampleNFT.MinterStoragePath - ) ?? panic("Could not borrow a reference to the NFT minter") - } - - execute { - // Borrow the recipient's public NFT collection reference - let receiver = getAccount(0x02) - .capabilities - .borrow<&{NonFungibleToken.CollectionPublic}>(NewExampleNFT.CollectionPublicPath) - ?? panic("Could not get receiver reference to the NFT Collection") - - // Mint the NFT and deposit it to the recipient's collection - self.minter.mintNFT( - recipient: receiver, - name: "Second NFT", - description: "The Best NFT", - thumbnail: "NFT: Thumbnail", - power: "The best", - will: "The strongest", - determination: "unbeatable" - ) - - log("Minted an NFT") - } -} diff --git a/cadence/transaction.cdc b/cadence/transaction.cdc new file mode 120000 index 0000000..5cfe5e4 --- /dev/null +++ b/cadence/transaction.cdc @@ -0,0 +1 @@ +./cadence/transactions/mint_nft.cdc \ No newline at end of file diff --git a/cadence/transactions/mint_nft.cdc b/cadence/transactions/mint_nft.cdc new file mode 100644 index 0000000..85b2684 --- /dev/null +++ b/cadence/transactions/mint_nft.cdc @@ -0,0 +1,40 @@ +import NonFungibleToken from 0x03 +import NewExampleNFT from 0x02 + +// This transaction uses the NFTMinter resource to mint a new NFT +// It must be run with the account that has the minter resource +// stored in /storage/NFTMinter + +transaction { + + // Local variable for storing the minter reference + let minter: auth(MinterEntitlement) &NewExampleNFT.NFTMinter + + prepare(signer: auth(Storage, Capabilities) &Account) { + // Borrow a reference to the NFTMinter resource in storage + self.minter = signer.capabilities.storage.borrow<&NewExampleNFT.NFTMinter>( + from: NewExampleNFT.MinterStoragePath + ) ?? panic("Could not borrow a reference to the NFT minter") + } + + execute { + // Borrow the recipient's public NFT collection reference + let receiver = getAccount(0x02) + .capabilities + .borrow<&{NonFungibleToken.CollectionPublic}>(NewExampleNFT.CollectionPublicPath) + ?? panic("Could not get receiver reference to the NFT Collection") + + // Mint the NFT and deposit it to the recipient's collection + self.minter.mintNFT( + recipient: receiver, + name: "Second NFT", + description: "The Best NFT", + thumbnail: "NFT: Thumbnail", + power: "The best", + will: "The strongest", + determination: "unbeatable" + ) + + log("Minted an NFT") + } +} diff --git a/emulator-account.pkey b/emulator-account.pkey new file mode 100644 index 0000000..75611bd --- /dev/null +++ b/emulator-account.pkey @@ -0,0 +1 @@ +0xdc07d83a937644ff362b279501b7f7a3735ac91a0f3647147acf649dda804e28 \ No newline at end of file diff --git a/flow.json b/flow.json index e81ec35..498f52f 100644 --- a/flow.json +++ b/flow.json @@ -1,9 +1,83 @@ { "contracts": { - "Counter": { - "source": "cadence/contracts/Counter.cdc", + "ExampleNFT": { + "source": "./cadence/contracts/Recipe.cdc", "aliases": { - "testing": "0000000000000007" + "emulator": "f8d6e0586b0a20c7" + } + } + }, + "dependencies": { + "Burner": { + "source": "mainnet://f233dcee88fe0abe.Burner", + "hash": "71af18e227984cd434a3ad00bb2f3618b76482842bae920ee55662c37c8bf331", + "aliases": { + "emulator": "f8d6e0586b0a20c7", + "mainnet": "f233dcee88fe0abe", + "testnet": "9a0766d93b6608b7" + } + }, + "FlowToken": { + "source": "mainnet://1654653399040a61.FlowToken", + "hash": "cefb25fd19d9fc80ce02896267eb6157a6b0df7b1935caa8641421fe34c0e67a", + "aliases": { + "emulator": "0ae53cb6e3f42a79", + "mainnet": "1654653399040a61", + "testnet": "7e60df042a9c0868" + } + }, + "FungibleToken": { + "source": "mainnet://f233dcee88fe0abe.FungibleToken", + "hash": "050328d01c6cde307fbe14960632666848d9b7ea4fef03ca8c0bbfb0f2884068", + "aliases": { + "emulator": "ee82856bf20e2aa6", + "mainnet": "f233dcee88fe0abe", + "testnet": "9a0766d93b6608b7" + } + }, + "FungibleTokenMetadataViews": { + "source": "mainnet://f233dcee88fe0abe.FungibleTokenMetadataViews", + "hash": "dff704a6e3da83997ed48bcd244aaa3eac0733156759a37c76a58ab08863016a", + "aliases": { + "emulator": "ee82856bf20e2aa6", + "mainnet": "f233dcee88fe0abe", + "testnet": "9a0766d93b6608b7" + } + }, + "FungibleTokenSwitchboard": { + "source": "mainnet://f233dcee88fe0abe.FungibleTokenSwitchboard", + "hash": "10f94fe8803bd1c2878f2323bf26c311fb4fb2beadba9f431efdb1c7fa46c695", + "aliases": { + "emulator": "ee82856bf20e2aa6", + "mainnet": "f233dcee88fe0abe", + "testnet": "9a0766d93b6608b7" + } + }, + "MetadataViews": { + "source": "mainnet://1d7e57aa55817448.MetadataViews", + "hash": "10a239cc26e825077de6c8b424409ae173e78e8391df62750b6ba19ffd048f51", + "aliases": { + "emulator": "f8d6e0586b0a20c7", + "mainnet": "1d7e57aa55817448", + "testnet": "631e88ae7f1d7c20" + } + }, + "NonFungibleToken": { + "source": "mainnet://1d7e57aa55817448.NonFungibleToken", + "hash": "b63f10e00d1a814492822652dac7c0574428a200e4c26cb3c832c4829e2778f0", + "aliases": { + "emulator": "f8d6e0586b0a20c7", + "mainnet": "1d7e57aa55817448", + "testnet": "631e88ae7f1d7c20" + } + }, + "ViewResolver": { + "source": "mainnet://1d7e57aa55817448.ViewResolver", + "hash": "374a1994046bac9f6228b4843cb32393ef40554df9bd9907a702d098a2987bde", + "aliases": { + "emulator": "f8d6e0586b0a20c7", + "mainnet": "1d7e57aa55817448", + "testnet": "631e88ae7f1d7c20" } } }, @@ -12,5 +86,21 @@ "mainnet": "access.mainnet.nodes.onflow.org:9000", "testing": "127.0.0.1:3569", "testnet": "access.devnet.nodes.onflow.org:9000" + }, + "accounts": { + "emulator-account": { + "address": "f8d6e0586b0a20c7", + "key": { + "type": "file", + "location": "emulator-account.pkey" + } + } + }, + "deployments": { + "emulator": { + "emulator-account": [ + "ExampleNFT" + ] + } } } \ No newline at end of file From 80834f571fe08871d43eb6d0298161139e83ef2c Mon Sep 17 00:00:00 2001 From: Lea Lobanov Date: Thu, 12 Dec 2024 01:28:02 +0400 Subject: [PATCH 4/6] Repo structure --- cadence/transactions/mint_nft.cdc | 51 ++++++++++++------------------- 1 file changed, 20 insertions(+), 31 deletions(-) diff --git a/cadence/transactions/mint_nft.cdc b/cadence/transactions/mint_nft.cdc index 85b2684..0f57d70 100644 --- a/cadence/transactions/mint_nft.cdc +++ b/cadence/transactions/mint_nft.cdc @@ -1,40 +1,29 @@ -import NonFungibleToken from 0x03 -import NewExampleNFT from 0x02 - -// This transaction uses the NFTMinter resource to mint a new NFT -// It must be run with the account that has the minter resource -// stored in /storage/NFTMinter +import "MetadataViews" +import "ExampleNFT" transaction { - // Local variable for storing the minter reference - let minter: auth(MinterEntitlement) &NewExampleNFT.NFTMinter - prepare(signer: auth(Storage, Capabilities) &Account) { - // Borrow a reference to the NFTMinter resource in storage - self.minter = signer.capabilities.storage.borrow<&NewExampleNFT.NFTMinter>( - from: NewExampleNFT.MinterStoragePath - ) ?? panic("Could not borrow a reference to the NFT minter") - } + // Use the caller's address + let address: Address = signer.address - execute { - // Borrow the recipient's public NFT collection reference - let receiver = getAccount(0x02) - .capabilities - .borrow<&{NonFungibleToken.CollectionPublic}>(NewExampleNFT.CollectionPublicPath) - ?? panic("Could not get receiver reference to the NFT Collection") + // Borrow the NFTMinter from the caller's storage + let minter = signer.storage.borrow<&ExampleNFT.NFTMinter>( + from: /storage/exampleNFTMinter + ) ?? panic("Could not borrow the NFT minter reference.") - // Mint the NFT and deposit it to the recipient's collection - self.minter.mintNFT( - recipient: receiver, - name: "Second NFT", - description: "The Best NFT", - thumbnail: "NFT: Thumbnail", - power: "The best", - will: "The strongest", - determination: "unbeatable" + // Mint a new NFT with metadata + let nft <- minter.mintNFT( + name: "Example NFT", + description: "Minting a sample NFT", + thumbnail: "https://example.com/thumbnail.png", + royalties: [], + metadata: { + "Power": "100", + "Will": "Strong", + "Determination": "Unyielding" + }, + ) - - log("Minted an NFT") } } From e93c2faf4046174c61aae6f0caefea80fdc918f4 Mon Sep 17 00:00:00 2001 From: Lea Lobanov Date: Thu, 12 Dec 2024 01:46:32 +0400 Subject: [PATCH 5/6] Repo structure --- README.md | 62 +++++++++++++++++++++++++------ cadence/transactions/mint_nft.cdc | 8 ++++ 2 files changed, 58 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index c1a6364..6d1a236 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ An NFT with metadata in it. This NFT also uses the metadata contract to establis - [Description](#description) - [What is included in this repository?](#what-is-included-in-this-repository) - [Supported Recipe Data](#recipe-data) +- [Deploying Recipe Contracts and Running Transactions Locally (Flow Emulator)](#deploying-recipe-contracts-and-running-transactions-locally-flow-emulator) - [License](#license) ## Description @@ -19,7 +20,6 @@ The Cadence Cookbook is a collection of code examples, recipes, and tutorials de Each recipe in the Cadence Cookbook is a practical coding example that showcases a specific aspect of Cadence or use-case on Flow, including smart contract development, interaction, and best practices. By following these recipes, you can gain hands-on experience and learn how to leverage Cadence for your blockchain projects. - ### Contributing to the Cadence Cookbook Learn more about the contribution process [here](https://github.com/onflow/cadence-cookbook/blob/main/contribute.md). @@ -34,17 +34,17 @@ Recipe metadata, such as title, author, and category labels, is stored in `index ``` recipe-name/ -├── cadence/ # Cadence files for recipe examples -│ ├── contract.cdc # Contract code -│ ├── transaction.cdc # Transaction code -│ ├── tests.cdc # Tests code -├── explanations/ # Explanation files for recipe examples -│ ├── contract.txt # Contract code explanation -│ ├── transaction.txt # Transaction code explanation -│ ├── tests.txt # Tests code explanation -├── index.js # Root file for storing recipe metadata -├── README.md # This README file -└── LICENSE # License information +├── cadence/ # Cadence files for recipe examples +│ ├── contracts/Recipe.cdc # Contract code +│ ├── transactions/mint_nft.cdc # Transaction code +│ ├── tests/Recipe_test.cdc # Tests code +├── explanations/ # Explanation files for recipe examples +│ ├── contract.txt # Contract code explanation +│ ├── transaction.txt # Transaction code explanation +│ ├── tests.txt # Tests code explanation +├── index.js # Root file for storing recipe metadata +├── README.md # This README file +└── LICENSE # License information ``` ## Supported Recipe Data @@ -66,6 +66,7 @@ recipe-name/ - `filters`: the filters object is used to perform filtering on recipes in the cookbook - `difficulty`: the difficulty filter supports one of ['beginner', 'intermediate', 'advanced'] + ``` // Pass the repo name const recipe = "sample-recipe-name"; @@ -94,6 +95,43 @@ export const sampleRecipe= { transactionExplanation: transactionExplanationPath, }; ``` +## Deploying Recipe Contracts and Running Transactions Locally (Flow Emulator) + +This section explains how to deploy the recipe's contracts to the Flow emulator, run the associated transaction with sample arguments, and verify the results. + +### Prerequisites + +Before deploying and running the recipe: + +1. Install the Flow CLI. You can find installation instructions [here](https://docs.onflow.org/flow-cli/install/). +2. Ensure the Flow emulator is installed and ready to use with `flow version`. + +### Step 1: Start the Flow Emulator + +Start the Flow emulator to simulate the blockchain environment locally + +```bash +flow emulator start +``` + +### Step 2: Install Dependencies and Deploy Project Contracts + +Deploy contracts to the emulator. This will deploy all the contracts specified in the _deployments_ section of `flow.json` whether project contracts or dependencies. + +```bash +flow dependencies install +flow project deploy --network=emulator +``` + +### Step 3: Run the Transaction + +Transactions associated with the recipe are located in `./cadence/transactions`. To run a transaction, execute the following command: + +```bash +flow transactions send cadence/transactions/TRANSACTION_NAME.cdc --signer emulator-account +``` + +To verify the transaction's execution, check the emulator logs printed during the transaction for confirmation messages. You can add the `--log-level debug` flag to your Flow CLI command for more detailed output during contract deployment or transaction execution. ## License diff --git a/cadence/transactions/mint_nft.cdc b/cadence/transactions/mint_nft.cdc index 0f57d70..618e226 100644 --- a/cadence/transactions/mint_nft.cdc +++ b/cadence/transactions/mint_nft.cdc @@ -25,5 +25,13 @@ transaction { }, ) + + // Borrow the collection from the caller's storage + let collection = signer.storage.borrow<&ExampleNFT.Collection>( + from: /storage/exampleNFTCollection + ) ?? panic("Could not borrow the NFT collection reference.") + + // Deposit the newly minted NFT into the caller's collection + collection.deposit(token: <-nft) } } From fb3533dcc069ca3a5d774ab223cd58723434ee1c Mon Sep 17 00:00:00 2001 From: Lea Lobanov Date: Thu, 12 Dec 2024 01:51:24 +0400 Subject: [PATCH 6/6] Repo structure --- explanations/contract.txt | 4 ++-- explanations/transaction.txt | 7 +++++-- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/explanations/contract.txt b/explanations/contract.txt index 0e43f12..6250d67 100644 --- a/explanations/contract.txt +++ b/explanations/contract.txt @@ -1,3 +1,3 @@ -This is a NFT resource that abides by the NFT standard and the Metadata standard. It imports both interfaces into the resource. +This contract defines an NFT resource that fully complies with both the Flow NFT standard and the Metadata standard. The NFT resource includes metadata fields such as id, name, thumbnail, description, power, will, and determination, which are all initialized during the resource's creation. -From there, metadata such as id, name, thumbnail, description, power, will, and determination are defined and initialized. The functions to resolveView and getViews are also included to make viewing the metadata easy. +To facilitate access to this metadata, the contract includes a resolveView function that retrieves specific views based on client requests and a getViews function that lists all the supported views. These functions streamline the process of retrieving and displaying metadata, ensuring that the NFT's information can be easily accessed and used by external applications. \ No newline at end of file diff --git a/explanations/transaction.txt b/explanations/transaction.txt index 6279934..f5ff515 100644 --- a/explanations/transaction.txt +++ b/explanations/transaction.txt @@ -1,3 +1,6 @@ -Because the above smart contract has metadata in the NFT that is initialized, when minting the NFT you will need to send in those parameters in your transaction. -Here we borrow the minter from the account that holds the NFT Minter. We then take the address of the recepient and make sure they have the capability to store the NFT. Afterwards we mint the NFT with the parameters specified. +Since the smart contract requires metadata to be initialized for each NFT, the minting transaction must include these metadata parameters. This ensures that every NFT created is properly defined with the necessary information. + +n the transaction, we first borrow the NFTMinter resource from the account's storage that holds it. Then, we verify that the recipient's account has the capability to store NFTs by checking their collection. If the capability is missing, the transaction will fail to prevent the NFT from being lost. + +Finally, we mint the NFT by calling the mintNFT function on the NFTMinter, passing in the required metadata parameters (such as name, description, thumbnail, and custom attributes). Once minted, the NFT is deposited into the recipient's collection, completing the process securely and ensuring that the NFT is properly stored in the intended account. \ No newline at end of file