From e13392b85701a087fcfcae4ec65755c756945df3 Mon Sep 17 00:00:00 2001 From: Lea Lobanov Date: Mon, 18 Nov 2024 19:51:55 +0100 Subject: [PATCH 01/11] C1 migration --- cadence/contract.cdc | 88 ++++++++++++++++++++++++++++++++++++++++- cadence/transaction.cdc | 21 +++++----- index.js | 4 +- 3 files changed, 100 insertions(+), 13 deletions(-) diff --git a/cadence/contract.cdc b/cadence/contract.cdc index 486ca3f..4a5db5d 100644 --- a/cadence/contract.cdc +++ b/cadence/contract.cdc @@ -7,7 +7,93 @@ pub struct Traits{ init( power: String - will: String + will: String// Structure created so that a traits view can be displayed +access(all) +struct Traits { + access(all) + let power: String + access(all) + let will: String + access(all) + let determination: String + + init( + power: String, + will: String, + determination: String + ) { + self.power = power + self.will = will + self.determination = determination + } +} + +// NFT resource +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: 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 + } +} + determination: String ){ self.power=power diff --git a/cadence/transaction.cdc b/cadence/transaction.cdc index 977e784..457ed80 100644 --- a/cadence/transaction.cdc +++ b/cadence/transaction.cdc @@ -1,28 +1,29 @@ import MetadataViews from 0x01 import NewExampleNFT from 0x02 -pub fun main(): AnyStruct { +access(all) +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") + // Borrow the collection's ResolverCollection capability + let collection = account.capabilities.borrow<&{MetadataViews.ResolverCollection}>( + /public/exampleNFTCollection + ) ?? panic("Could not borrow a reference to the collection") + // Borrow the NFT's Resolver reference let nft = collection.borrowViewResolver(id: id) - - // Get the basic display information for this NFT - - + // Get the Traits view for the NFT let view = nft.resolveView(Type()) + + // Get the Display view for the NFT let oview = nft.resolveView(Type()) + // Combine the views into a dictionary let object = {"Traits": view, "Display": oview} return object } - diff --git a/index.js b/index.js index 8116e71..38196b5 100644 --- a/index.js +++ b/index.js @@ -23,6 +23,6 @@ export const multipleMetadataViews = { transactionCode: transactionPath, transactionExplanation: transactionExplanationPath, filters: { - difficulty: "intermediate" - } + difficulty: "intermediate", + }, }; From eafe7e2fb907b8aeb02549b730d56c59469dc4c6 Mon Sep 17 00:00:00 2001 From: Lea Lobanov Date: Mon, 18 Nov 2024 19:54:38 +0100 Subject: [PATCH 02/11] C1 migration --- cadence/contract.cdc | 76 +------------------------------------------- 1 file changed, 1 insertion(+), 75 deletions(-) diff --git a/cadence/contract.cdc b/cadence/contract.cdc index 4a5db5d..4b4dfc9 100644 --- a/cadence/contract.cdc +++ b/cadence/contract.cdc @@ -1,13 +1,4 @@ -//Structure created so that a traits view can be displayed -pub struct Traits{ - pub let power: String - pub let will: String - pub let determination: String - - - init( - power: String - will: String// Structure created so that a traits view can be displayed +// Structure created so that a traits view can be displayed access(all) struct Traits { access(all) @@ -93,68 +84,3 @@ resource NFT: NonFungibleToken.INFT, MetadataViews.Resolver { self.determination = determination } } - - determination: String - ){ - self.power=power - self.will=will - self.determination=determination - } -} - -//NFT resources -pub resource NFT: NonFungibleToken.INFT, MetadataViews.Resolver { - pub 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 - - - pub fun getViews(): [Type] { - return [ - Type(), - Type() - ] - } - - pub fun resolveView(_ view: Type): AnyStruct? { - switch view { - case Type(): - return MetadataViews.Display( - name: self.name, - description: self.description, - thumbnail: 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 - } -} From dcbc345e0b05bd9a633a01d34433a0483c4b1565 Mon Sep 17 00:00:00 2001 From: Lea Lobanov Date: Fri, 29 Nov 2024 14:11:26 +0000 Subject: [PATCH 03/11] GH actions 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 c68c96cf10457a3d9c23d7ecdabdef041f2b17e9 Mon Sep 17 00:00:00 2001 From: Lea Lobanov Date: Thu, 12 Dec 2024 00:38:34 +0400 Subject: [PATCH 04/11] Working on repo structure --- .github/workflows/cadence_lint.yml | 29 +++- .gitignore | 4 +- cadence/contract.cdc | 86 ---------- cadence/contracts/Recipe.cdc | 157 ++++++++++++++++++ cadence/tests/Recipe_test.cdc | 6 + .../combine_views.cdc} | 19 ++- emulator-account.pkey | 1 + flow.json | 114 ++++++++++++- 8 files changed, 314 insertions(+), 102 deletions(-) delete mode 100644 cadence/contract.cdc create mode 100644 cadence/contracts/Recipe.cdc create mode 100644 cadence/tests/Recipe_test.cdc rename cadence/{transaction.cdc => transactions/combine_views.cdc} (50%) 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 4b4dfc9..0000000 --- a/cadence/contract.cdc +++ /dev/null @@ -1,86 +0,0 @@ -// Structure created so that a traits view can be displayed -access(all) -struct Traits { - access(all) - let power: String - access(all) - let will: String - access(all) - let determination: String - - init( - power: String, - will: String, - determination: String - ) { - self.power = power - self.will = will - self.determination = determination - } -} - -// NFT resource -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: 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/contracts/Recipe.cdc b/cadence/contracts/Recipe.cdc new file mode 100644 index 0000000..30f5ebb --- /dev/null +++ b/cadence/contracts/Recipe.cdc @@ -0,0 +1,157 @@ +import "NonFungibleToken" +import "MetadataViews" + +access(all) contract ExampleNFT: NonFungibleToken { + + /// Standard Paths for the Collection + access(all) let CollectionStoragePath: StoragePath + access(all) let CollectionPublicPath: PublicPath + + /// Path where the minter should be stored + access(all) let MinterStoragePath: StoragePath + + /// NFT Resource + access(all) resource NFT: NonFungibleToken.NFT, MetadataViews.Resolver { + + access(all) let id: UInt64 + access(all) let name: String + access(all) let description: String + access(all) let thumbnail: String + access(all) let traits: {String: String} + + access(self) let royalties: [MetadataViews.Royalty] + + init( + name: String, + description: String, + thumbnail: String, + traits: {String: String}, + royalties: [MetadataViews.Royalty] + ) { + self.id = self.uuid + self.name = name + self.description = description + self.thumbnail = thumbnail + self.traits = traits + self.royalties = royalties + } + + /// Returns the views supported by this NFT + access(all) view fun getViews(): [Type] { + return [ + Type(), + Type(), + Type() + ] + } + + /// Resolves the specified view for this NFT + 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 MetadataViews.Royalties( + self.royalties + ) + case Type(): + return MetadataViews.dictToTraits(self.traits) + } + return nil + } + } + + /// NFT Collection + access(all) resource Collection: NonFungibleToken.Collection { + + /// Dictionary of owned NFTs + access(all) var ownedNFTs: @{UInt64: {NonFungibleToken.NFT}} + + init() { + self.ownedNFTs <- {} + } + + /// Withdraws an NFT from the Collection + access(NonFungibleToken.Withdraw) fun withdraw(withdrawID: UInt64): @{NonFungibleToken.NFT} { + let token <- self.ownedNFTs.remove(key: withdrawID) + ?? panic("CustomNFT.Collection: Cannot withdraw NFT. ID not found.") + return <-token + } + + /// Deposits an NFT into the Collection + access(all) fun deposit(token: @{NonFungibleToken.NFT}) { + let token <- token as! @CustomNFT.NFT + let id = token.id + let oldToken <- self.ownedNFTs[id] <- token + destroy oldToken + } + + /// Returns all NFT IDs in the Collection + access(all) view fun getIDs(): [UInt64] { + return self.ownedNFTs.keys + } + + /// Returns the number of NFTs in the Collection + access(all) view fun getLength(): Int { + return self.ownedNFTs.length + } + + /// Borrows a reference to an NFT in the Collection + access(all) view fun borrowNFT(_ id: UInt64): &{NonFungibleToken.NFT}? { + return &self.ownedNFTs[id] + } + + /// Creates an empty Collection and returns it + access(all) fun createEmptyCollection(): @{NonFungibleToken.Collection} { + return <-CustomNFT.createEmptyCollection() + } + } + + /// Minter for the NFT + access(all) resource Minter { + + /// Mints a new NFT + access(all) fun mintNFT( + name: String, + description: String, + thumbnail: String, + traits: {String: String}, + royalties: [MetadataViews.Royalty] + ): @CustomNFT.NFT { + return <-create NFT( + name: name, + description: description, + thumbnail: thumbnail, + traits: traits, + royalties: royalties + ) + } + } + + /// Creates an empty Collection + access(all) fun createEmptyCollection(): @{NonFungibleToken.Collection} { + return <-create Collection() + } + + init() { + self.CollectionStoragePath = /storage/customNFTCollection + self.CollectionPublicPath = /public/customNFTCollection + self.MinterStoragePath = /storage/customNFTMinter + + // Create and save a Collection + let collection <- create Collection() + self.account.storage.save(<-collection, to: self.CollectionStoragePath) + + // Publish the Collection's capability + let collectionCap = self.account.capabilities.storage.issue<&CustomNFT.Collection>(self.CollectionStoragePath) + self.account.capabilities.publish(collectionCap, at: self.CollectionPublicPath) + + // Create and save a Minter + let minter <- create Minter() + self.account.storage.save(<-minter, to: self.MinterStoragePath) + } +} 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/transactions/combine_views.cdc similarity index 50% rename from cadence/transaction.cdc rename to cadence/transactions/combine_views.cdc index 457ed80..5a29f22 100644 --- a/cadence/transaction.cdc +++ b/cadence/transactions/combine_views.cdc @@ -1,5 +1,5 @@ -import MetadataViews from 0x01 -import NewExampleNFT from 0x02 +import "MetadataViews" +import "ExampleNFT" access(all) fun main(): AnyStruct { @@ -11,19 +11,22 @@ fun main(): AnyStruct { // Borrow the collection's ResolverCollection capability let collection = account.capabilities.borrow<&{MetadataViews.ResolverCollection}>( /public/exampleNFTCollection - ) ?? panic("Could not borrow a reference to the collection") + ) ?? panic("Could not borrow a reference to the collection at /public/exampleNFTCollection") // Borrow the NFT's Resolver reference let nft = collection.borrowViewResolver(id: id) + ?? panic("Could not resolve NFT with ID \(id) in the collection") // Get the Traits view for the NFT - let view = nft.resolveView(Type()) - + let traitsView = nft.resolveView(Type()) + ?? panic("Traits view not found for NFT with ID \(id)") + // Get the Display view for the NFT - let oview = nft.resolveView(Type()) + let displayView = nft.resolveView(Type()) + ?? panic("Display view not found for NFT with ID \(id)") // Combine the views into a dictionary - let object = {"Traits": view, "Display": oview} + let object = {"Traits": traitsView, "Display": displayView} return object -} +} \ No newline at end of file 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..3a64c03 100644 --- a/flow.json +++ b/flow.json @@ -1,9 +1,101 @@ { "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" + } + }, + "TopShot": { + "source": "mainnet://0b2a3299cc857e29.TopShot", + "hash": "804d7381441bea4ed1a0c74e91e0c7c54322b353d236af911f67783263f177f9", + "aliases": { + "emulator": "f8d6e0586b0a20c7", + "mainnet": "0b2a3299cc857e29", + "testnet": "877931736ee77cff" + } + }, + "TopShotLocking": { + "source": "mainnet://0b2a3299cc857e29.TopShotLocking", + "hash": "f9b527269a947bbbf5e120ae05ecdb38b8e5f9a6be704e73f5a2e36d33b687b1", + "aliases": { + "emulator": "f8d6e0586b0a20c7", + "mainnet": "0b2a3299cc857e29", + "testnet": "877931736ee77cff" + } + }, + "ViewResolver": { + "source": "mainnet://1d7e57aa55817448.ViewResolver", + "hash": "374a1994046bac9f6228b4843cb32393ef40554df9bd9907a702d098a2987bde", + "aliases": { + "emulator": "f8d6e0586b0a20c7", + "mainnet": "1d7e57aa55817448", + "testnet": "631e88ae7f1d7c20" } } }, @@ -12,5 +104,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 b470d098c5c2dbf6a34911906150d7a106a0f2db Mon Sep 17 00:00:00 2001 From: Lea Lobanov Date: Thu, 12 Dec 2024 00:40:42 +0400 Subject: [PATCH 05/11] Working on repo structure --- cadence/contracts/Recipe.cdc | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/cadence/contracts/Recipe.cdc b/cadence/contracts/Recipe.cdc index 30f5ebb..0056f7f 100644 --- a/cadence/contracts/Recipe.cdc +++ b/cadence/contracts/Recipe.cdc @@ -78,13 +78,13 @@ access(all) contract ExampleNFT: NonFungibleToken { /// Withdraws an NFT from the Collection access(NonFungibleToken.Withdraw) fun withdraw(withdrawID: UInt64): @{NonFungibleToken.NFT} { let token <- self.ownedNFTs.remove(key: withdrawID) - ?? panic("CustomNFT.Collection: Cannot withdraw NFT. ID not found.") + ?? panic("ExampleNFT.Collection: Cannot withdraw NFT. ID not found.") return <-token } /// Deposits an NFT into the Collection access(all) fun deposit(token: @{NonFungibleToken.NFT}) { - let token <- token as! @CustomNFT.NFT + let token <- token as! @ExampleNFT.NFT let id = token.id let oldToken <- self.ownedNFTs[id] <- token destroy oldToken @@ -107,7 +107,7 @@ access(all) contract ExampleNFT: NonFungibleToken { /// Creates an empty Collection and returns it access(all) fun createEmptyCollection(): @{NonFungibleToken.Collection} { - return <-CustomNFT.createEmptyCollection() + return <-ExampleNFT.createEmptyCollection() } } @@ -121,7 +121,7 @@ access(all) contract ExampleNFT: NonFungibleToken { thumbnail: String, traits: {String: String}, royalties: [MetadataViews.Royalty] - ): @CustomNFT.NFT { + ): @ExampleNFT.NFT { return <-create NFT( name: name, description: description, @@ -138,16 +138,16 @@ access(all) contract ExampleNFT: NonFungibleToken { } init() { - self.CollectionStoragePath = /storage/customNFTCollection - self.CollectionPublicPath = /public/customNFTCollection - self.MinterStoragePath = /storage/customNFTMinter + self.CollectionStoragePath = /storage/ExampleNFTCollection + self.CollectionPublicPath = /public/ExampleNFTCollection + self.MinterStoragePath = /storage/ExampleNFTMinter // Create and save a Collection let collection <- create Collection() self.account.storage.save(<-collection, to: self.CollectionStoragePath) // Publish the Collection's capability - let collectionCap = self.account.capabilities.storage.issue<&CustomNFT.Collection>(self.CollectionStoragePath) + let collectionCap = self.account.capabilities.storage.issue<&ExampleNFT.Collection>(self.CollectionStoragePath) self.account.capabilities.publish(collectionCap, at: self.CollectionPublicPath) // Create and save a Minter From 962a59a136f76c0e5d8d58a24cfbfa2732c822e0 Mon Sep 17 00:00:00 2001 From: Lea Lobanov Date: Thu, 12 Dec 2024 00:50:30 +0400 Subject: [PATCH 06/11] Working on repo structure --- cadence/contracts/Recipe.cdc | 304 +++++++++++++++++++++++++++++------ flow.json | 18 --- 2 files changed, 259 insertions(+), 63 deletions(-) diff --git a/cadence/contracts/Recipe.cdc b/cadence/contracts/Recipe.cdc index 0056f7f..c21d32c 100644 --- a/cadence/contracts/Recipe.cdc +++ b/cadence/contracts/Recipe.cdc @@ -1,157 +1,371 @@ +/* +* +* 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 for the Collection + /// 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 - /// NFT Resource - access(all) resource NFT: NonFungibleToken.NFT, MetadataViews.Resolver { + /// 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 - access(all) let traits: {String: 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, - traits: {String: String}, - royalties: [MetadataViews.Royalty] + royalties: [MetadataViews.Royalty], + metadata: {String: AnyStruct}, ) { self.id = self.uuid self.name = name self.description = description self.thumbnail = thumbnail - self.traits = traits 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>()) } - /// Returns the views supported by this NFT access(all) view fun getViews(): [Type] { return [ Type(), Type(), - Type() + Type(), + Type(), + Type(), + Type(), + Type(), + Type(), + Type() ] } - /// Resolves the specified view for this NFT 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) + 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(): - return MetadataViews.dictToTraits(self.traits) + // 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. + let mintedTimeTrait = MetadataViews.Trait(name: "mintedTime", value: self.metadata["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 } } - /// NFT Collection - access(all) resource Collection: NonFungibleToken.Collection { + // Deprecated: Only here for backward compatibility. + access(all) resource interface ExampleNFTCollectionPublic {} - /// Dictionary of owned NFTs + 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() { + init () { self.ownedNFTs <- {} } - /// Withdraws an NFT from the Collection + /// 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: Cannot withdraw NFT. ID not found.") + ?? 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 } - /// Deposits an NFT into the Collection + /// 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 - let oldToken <- self.ownedNFTs[id] <- token + + // 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) } - /// Returns all NFT IDs in the Collection + /// getIDs returns an array of the IDs that are in the collection access(all) view fun getIDs(): [UInt64] { return self.ownedNFTs.keys } - /// Returns the number of NFTs in the Collection + /// Gets the amount of NFTs stored in the collection access(all) view fun getLength(): Int { return self.ownedNFTs.length } - /// Borrows a reference to an NFT in the Collection access(all) view fun borrowNFT(_ id: UInt64): &{NonFungibleToken.NFT}? { return &self.ownedNFTs[id] } - /// Creates an empty Collection and returns it + /// 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() + return <-ExampleNFT.createEmptyCollection(nftType: Type<@ExampleNFT.NFT>()) } } - /// Minter for the NFT - access(all) resource Minter { + /// 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() + } - /// Mints a new NFT + /// 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, - traits: {String: String}, royalties: [MetadataViews.Royalty] ): @ExampleNFT.NFT { - return <-create NFT( + + let metadata: {String: AnyStruct} = {} + let currentBlock = getCurrentBlock() + metadata["mintedBlock"] = currentBlock.height + metadata["mintedTime"] = currentBlock.timestamp + + // this piece of metadata will be used to show embedding rarity into a trait + metadata["foo"] = "bar" + + // create a new NFT + var newNFT <- create NFT( name: name, description: description, thumbnail: thumbnail, - traits: traits, - royalties: royalties + royalties: royalties, + metadata: metadata, ) - } - } - /// Creates an empty Collection - access(all) fun createEmptyCollection(): @{NonFungibleToken.Collection} { - return <-create Collection() + return <-newNFT + } } init() { - self.CollectionStoragePath = /storage/ExampleNFTCollection - self.CollectionPublicPath = /public/ExampleNFTCollection - self.MinterStoragePath = /storage/ExampleNFTMinter - // Create and save a Collection + // 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) - // Publish the Collection's capability + // 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 and save a Minter - let minter <- create Minter() + // Create a Minter resource and save it to storage + let minter <- create NFTMinter() self.account.storage.save(<-minter, to: self.MinterStoragePath) } -} +} \ No newline at end of file diff --git a/flow.json b/flow.json index 3a64c03..498f52f 100644 --- a/flow.json +++ b/flow.json @@ -71,24 +71,6 @@ "testnet": "631e88ae7f1d7c20" } }, - "TopShot": { - "source": "mainnet://0b2a3299cc857e29.TopShot", - "hash": "804d7381441bea4ed1a0c74e91e0c7c54322b353d236af911f67783263f177f9", - "aliases": { - "emulator": "f8d6e0586b0a20c7", - "mainnet": "0b2a3299cc857e29", - "testnet": "877931736ee77cff" - } - }, - "TopShotLocking": { - "source": "mainnet://0b2a3299cc857e29.TopShotLocking", - "hash": "f9b527269a947bbbf5e120ae05ecdb38b8e5f9a6be704e73f5a2e36d33b687b1", - "aliases": { - "emulator": "f8d6e0586b0a20c7", - "mainnet": "0b2a3299cc857e29", - "testnet": "877931736ee77cff" - } - }, "ViewResolver": { "source": "mainnet://1d7e57aa55817448.ViewResolver", "hash": "374a1994046bac9f6228b4843cb32393ef40554df9bd9907a702d098a2987bde", From 41711e3b87a6062c6f57c56e1ddbe7bbd8084bfa Mon Sep 17 00:00:00 2001 From: Lea Lobanov Date: Thu, 12 Dec 2024 01:17:01 +0400 Subject: [PATCH 07/11] Debug tx --- cadence/contracts/Recipe.cdc | 18 +++--- cadence/transactions/combine_views.cdc | 80 ++++++++++++++++---------- 2 files changed, 59 insertions(+), 39 deletions(-) diff --git a/cadence/contracts/Recipe.cdc b/cadence/contracts/Recipe.cdc index c21d32c..0850b8a 100644 --- a/cadence/contracts/Recipe.cdc +++ b/cadence/contracts/Recipe.cdc @@ -115,8 +115,10 @@ access(all) contract ExampleNFT: NonFungibleToken { 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. - let mintedTimeTrait = MetadataViews.Trait(name: "mintedTime", value: self.metadata["mintedTime"]!, displayType: "Date", rarity: nil) - traitsView.addTrait(mintedTimeTrait) + 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") @@ -325,16 +327,12 @@ access(all) contract ExampleNFT: NonFungibleToken { name: String, description: String, thumbnail: String, - royalties: [MetadataViews.Royalty] + royalties: [MetadataViews.Royalty], + metadata: {String: String}, ): @ExampleNFT.NFT { - let metadata: {String: AnyStruct} = {} + //let metadata: {String: AnyStruct} = {} let currentBlock = getCurrentBlock() - metadata["mintedBlock"] = currentBlock.height - metadata["mintedTime"] = currentBlock.timestamp - - // this piece of metadata will be used to show embedding rarity into a trait - metadata["foo"] = "bar" // create a new NFT var newNFT <- create NFT( @@ -365,7 +363,7 @@ access(all) contract ExampleNFT: NonFungibleToken { self.account.capabilities.publish(collectionCap, at: self.CollectionPublicPath) // Create a Minter resource and save it to storage - let minter <- create NFTMinter() + let minter: @ExampleNFT.NFTMinter <- create NFTMinter() self.account.storage.save(<-minter, to: self.MinterStoragePath) } } \ No newline at end of file diff --git a/cadence/transactions/combine_views.cdc b/cadence/transactions/combine_views.cdc index 5a29f22..dfe2b2f 100644 --- a/cadence/transactions/combine_views.cdc +++ b/cadence/transactions/combine_views.cdc @@ -1,32 +1,54 @@ import "MetadataViews" import "ExampleNFT" -access(all) -fun main(): AnyStruct { - let address: Address = 0x02 - let id: UInt64 = 0 - - let account = getAccount(address) - - // Borrow the collection's ResolverCollection capability - let collection = account.capabilities.borrow<&{MetadataViews.ResolverCollection}>( - /public/exampleNFTCollection - ) ?? panic("Could not borrow a reference to the collection at /public/exampleNFTCollection") - - // Borrow the NFT's Resolver reference - let nft = collection.borrowViewResolver(id: id) - ?? panic("Could not resolve NFT with ID \(id) in the collection") - - // Get the Traits view for the NFT - let traitsView = nft.resolveView(Type()) - ?? panic("Traits view not found for NFT with ID \(id)") - - // Get the Display view for the NFT - let displayView = nft.resolveView(Type()) - ?? panic("Display view not found for NFT with ID \(id)") - - // Combine the views into a dictionary - let object = {"Traits": traitsView, "Display": displayView} - - return object -} \ No newline at end of file +transaction { + + prepare(signer: auth(Storage, Capabilities) &Account) { + // Use the caller's address + let address: Address = signer.address + + // 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 a new NFT + 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" + }, + + ) + + let id = nft.id + + // Borrow the collection capability to deposit the minted NFT + let collection = signer.capabilities.borrow<&ExampleNFT.Collection>( + /public/exampleNFTCollection + ) ?? panic("Could not borrow the collection reference at /public/exampleNFTCollection.") + + // Deposit the minted NFT into the collection + collection.deposit(token: <-nft) + + // Borrow the ViewResolver for the given NFT ID + let resolver = collection.borrowViewResolver(id: id) + ?? panic("Could not borrow the ViewResolver for the NFT ID.") + + // Get the Traits view for the NFT + let traitsView = resolver.resolveView(Type()) + ?? panic("Traits view not found for NFT ID.") + + // Get the Display view for the NFT + let displayView = resolver.resolveView(Type()) + ?? panic("Display view not found for NFT ID.") + + let object = {"Traits": traitsView, "Display": displayView} + log(object) + } +} From a18e1d5d5ec2e28ea131480978d16439b56dcf0b Mon Sep 17 00:00:00 2001 From: Lea Lobanov Date: Thu, 12 Dec 2024 01:18:38 +0400 Subject: [PATCH 08/11] Repo structure --- README.md | 61 +++++++++++++++++++++++++++++++++-------- cadence/contract.cdc | 1 + cadence/transaction.cdc | 1 + 3 files changed, 51 insertions(+), 12 deletions(-) create mode 120000 cadence/contract.cdc create mode 120000 cadence/transaction.cdc diff --git a/README.md b/README.md index a6418fa..ab06547 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ Have more views you want to create for metadata? This is how you create new view - [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/combine_views.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 @@ -95,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/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/transaction.cdc b/cadence/transaction.cdc new file mode 120000 index 0000000..cb96150 --- /dev/null +++ b/cadence/transaction.cdc @@ -0,0 +1 @@ +./cadence/transactions/combine_views.cdc \ No newline at end of file From 7c3c23d9210d07c5456ad66cab608ed5c568a16c Mon Sep 17 00:00:00 2001 From: Lea Lobanov Date: Thu, 12 Dec 2024 01:21:43 +0400 Subject: [PATCH 09/11] Improve expl --- explanations/contract.txt | 4 +--- explanations/transaction.txt | 4 ++-- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/explanations/contract.txt b/explanations/contract.txt index 40a2a1a..d1c7a62 100644 --- a/explanations/contract.txt +++ b/explanations/contract.txt @@ -1,3 +1 @@ -To have more than just the display view, you can create your own Struct in your contract so that it may be used as a view in your NFT. - -Here we create a Traits structure. We then include the Traits view in the getViews function as well as include it as an option in the resolve view function. \ No newline at end of file +You can enhance your NFT contract by adding custom views, like a Traits structure, to provide more detailed information about your NFTs. The Traits view can represent specific attributes, such as characteristics or rarity, making your NFTs more informative and versatile. To enable this, you include the Traits view in the getViews function to indicate that it is supported and update the resolveView function to return the appropriate data when the Traits view is requested. This allows your NFTs to offer richer metadata, making them suitable for a wide range of applications like gaming or collectibles. \ No newline at end of file diff --git a/explanations/transaction.txt b/explanations/transaction.txt index 7535f5c..62f3f45 100644 --- a/explanations/transaction.txt +++ b/explanations/transaction.txt @@ -1,3 +1,3 @@ -Now, just as we did with the Display view, we resolve the view for the Traits view and can return it as a dictionary, or however you choose. +Just as we implemented the Display view, we also resolve the Traits view by defining how it retrieves and returns its data. -Now we have both views and metadata available with very little code needed. +With this setup, both the Display view and the Traits view are accessible, along with the associated metadata. \ No newline at end of file From 303f00131e3e790b50816b7cc85dab440fe07c71 Mon Sep 17 00:00:00 2001 From: Lea Lobanov Date: Mon, 16 Dec 2024 02:56:33 +0400 Subject: [PATCH 10/11] Update tests --- cadence/tests/Recipe_test.cdc | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/cadence/tests/Recipe_test.cdc b/cadence/tests/Recipe_test.cdc index 986e8fe..7aaae54 100644 --- a/cadence/tests/Recipe_test.cdc +++ b/cadence/tests/Recipe_test.cdc @@ -4,3 +4,14 @@ access(all) fun testExample() { let array = [1, 2, 3] Test.expect(array.length, Test.equal(3)) } + +access(all) +fun setup() { + let err = Test.deployContract( + name: "ExampleNFT", + path: "../contracts/Recipe.cdc", + arguments: [], + ) + + Test.expect(err, Test.beNil()) +} \ No newline at end of file From 71940654dbb95fb0d9b901ce292b1ed36587e054 Mon Sep 17 00:00:00 2001 From: Jerome P Date: Mon, 16 Dec 2024 11:04:35 -0800 Subject: [PATCH 11/11] Fix so that test loads Recipe and it's dependencies when run --- flow.json | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/flow.json b/flow.json index 498f52f..fe21df7 100644 --- a/flow.json +++ b/flow.json @@ -3,7 +3,8 @@ "ExampleNFT": { "source": "./cadence/contracts/Recipe.cdc", "aliases": { - "emulator": "f8d6e0586b0a20c7" + "emulator": "f8d6e0586b0a20c7", + "testing": "0000000000000007" } } }, @@ -59,6 +60,7 @@ "aliases": { "emulator": "f8d6e0586b0a20c7", "mainnet": "1d7e57aa55817448", + "testing": "0000000000000007", "testnet": "631e88ae7f1d7c20" } }, @@ -68,6 +70,7 @@ "aliases": { "emulator": "f8d6e0586b0a20c7", "mainnet": "1d7e57aa55817448", + "testing": "0000000000000007", "testnet": "631e88ae7f1d7c20" } }, @@ -77,6 +80,7 @@ "aliases": { "emulator": "f8d6e0586b0a20c7", "mainnet": "1d7e57aa55817448", + "testing": "0000000000000007", "testnet": "631e88ae7f1d7c20" } }