From f651afa6025311090414601cf03735f1587613a5 Mon Sep 17 00:00:00 2001 From: Lea Lobanov Date: Thu, 14 Nov 2024 17:17:58 +0900 Subject: [PATCH 1/9] Migrate code to C1.0 --- cadence/contract.cdc | 46 ++++++++++++++++------------------------- cadence/transaction.cdc | 10 ++++----- index.js | 7 +++---- 3 files changed, 26 insertions(+), 37 deletions(-) diff --git a/cadence/contract.cdc b/cadence/contract.cdc index 77c650e..20c218e 100644 --- a/cadence/contract.cdc +++ b/cadence/contract.cdc @@ -1,25 +1,24 @@ -pub contract NFTStorefront { +access(all) contract NFTStorefront { - ..... + ... // Storefront // A resource that allows its owner to manage a list of Listings, and anyone to interact with them // in order to query their details and purchase the NFTs that they represent. - // - pub resource Storefront : StorefrontManager, StorefrontPublic { - // The dictionary of Listing uuids to Listing resources. + access(all) resource Storefront : StorefrontManager, StorefrontPublic { + + // The dictionary of Listing UUIDs to Listing resources. access(self) var listings: @{UInt64: Listing} // insert // Create and publish a Listing for an NFT. - // - pub fun createListing( + access(all) fun createListing( nftProviderCapability: Capability<&{NonFungibleToken.Provider, NonFungibleToken.CollectionPublic}>, nftType: Type, nftID: UInt64, salePaymentVaultType: Type, saleCuts: [SaleCut] - ): UInt64 { + ): UInt64 { let listing <- create Listing( nftProviderCapability: nftProviderCapability, nftType: nftType, @@ -34,7 +33,6 @@ pub contract NFTStorefront { // Add the new listing to the dictionary. let oldListing <- self.listings[listingResourceID] <- listing - // Note that oldListing will always be nil, but we have to handle it. destroy oldListing emit ListingAvailable( @@ -51,39 +49,32 @@ pub contract NFTStorefront { // removeListing // Remove a Listing that has not yet been purchased from the collection and destroy it. - // - pub fun removeListing(listingResourceID: UInt64) { + access(all) fun removeListing(listingResourceID: UInt64) { let listing <- self.listings.remove(key: listingResourceID) ?? panic("missing Listing") - - // This will emit a ListingCompleted event. + destroy listing } // getListingIDs // Returns an array of the Listing resource IDs that are in the collection - // - pub fun getListingIDs(): [UInt64] { + access(all) fun getListingIDs(): [UInt64] { return self.listings.keys } // borrowSaleItem // Returns a read-only view of the SaleItem for the given listingID if it is contained by this collection. - // - pub fun borrowListing(listingResourceID: UInt64): &Listing{ListingPublic}? { + access(all) fun borrowListing(listingResourceID: UInt64): &Listing{ListingPublic}? { if self.listings[listingResourceID] != nil { - return &self.listings[listingResourceID] as! &Listing{ListingPublic} + return &self.listings[listingResourceID] as &Listing{ListingPublic} } else { return nil } } // cleanup - // Remove an listing *if* it has been purchased. - // Anyone can call, but at present it only benefits the account owner to do so. - // Kind purchasers can however call it if they like. - // - pub fun cleanup(listingResourceID: UInt64) { + // Remove a listing *if* it has been purchased. + access(all) fun cleanup(listingResourceID: UInt64) { pre { self.listings[listingResourceID] != nil: "could not find listing with given id" } @@ -94,7 +85,6 @@ pub contract NFTStorefront { } // destructor - // destroy () { destroy self.listings @@ -103,7 +93,6 @@ pub contract NFTStorefront { } // constructor - // init () { self.listings <- {} @@ -112,8 +101,9 @@ pub contract NFTStorefront { } } - pub fun createStorefront(): @Storefront { + access(all) fun createStorefront(): @Storefront { return <-create Storefront() } -.... -} \ No newline at end of file + + ... +} diff --git a/cadence/transaction.cdc b/cadence/transaction.cdc index ab50e63..58163ad 100644 --- a/cadence/transaction.cdc +++ b/cadence/transaction.cdc @@ -3,11 +3,11 @@ import NFTStorefront from 0x03 // This transaction sets up account 0x01 for the marketplace tutorial // by publishing a Vault reference and creating an empty NFT Collection. transaction { - prepare(acct: AuthAccount) { - - acct.save<@NFTStorefront.Storefront>(<- NFTStorefront.createStorefront() , to: NFTStorefront.StorefrontStoragePath) + prepare(acct: auth(Storage) &Account) { - log("storefront created") + // Save the newly created storefront resource into account storage + acct.storage.save(<-NFTStorefront.createStorefront(), to: NFTStorefront.StorefrontStoragePath) + + log("Storefront created") } } - diff --git a/index.js b/index.js index 429c57e..f5e9efa 100644 --- a/index.js +++ b/index.js @@ -9,7 +9,7 @@ const transactionPath = `${recipe}/cadence/transaction.cdc`; const smartContractExplanationPath = `${recipe}/explanations/contract.txt`; const transactionExplanationPath = `${recipe}/explanations/transaction.txt`; -export const createAMarketplace= { +export const createAMarketplace = { slug: recipe, title: "Create a Marketplace", createdAt: new Date(2022, 9, 14), @@ -23,7 +23,6 @@ export const createAMarketplace= { transactionCode: transactionPath, transactionExplanation: transactionExplanationPath, filters: { - difficulty: "intermediate" - } + difficulty: "intermediate", + }, }; - From e360b7f3978e0c98b24eb29f89a9c43654cfdcf5 Mon Sep 17 00:00:00 2001 From: Lea Lobanov Date: Fri, 29 Nov 2024 14:34:04 +0000 Subject: [PATCH 2/9] GH 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 1e13218966dd72df66b2d946a2e7311d763103b9 Mon Sep 17 00:00:00 2001 From: Lea Lobanov Date: Sun, 8 Dec 2024 16:14:59 +0400 Subject: [PATCH 3/9] Restructure repo --- .github/workflows/cadence_lint.yml | 29 +- .gitignore | 4 +- cadence/contract.cdc | 110 +---- cadence/contracts/Recipe.cdc | 516 +++++++++++++++++++++ cadence/tests/Recipe_test.cdc | 6 + cadence/transaction.cdc | 14 +- cadence/transactions/create_storefront.cdc | 13 + emulator-account.pkey | 1 + flow.json | 69 ++- 9 files changed, 632 insertions(+), 130 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/create_storefront.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 20c218e..0000000 --- a/cadence/contract.cdc +++ /dev/null @@ -1,109 +0,0 @@ -access(all) contract NFTStorefront { - - ... - - // Storefront - // A resource that allows its owner to manage a list of Listings, and anyone to interact with them - // in order to query their details and purchase the NFTs that they represent. - access(all) resource Storefront : StorefrontManager, StorefrontPublic { - - // The dictionary of Listing UUIDs to Listing resources. - access(self) var listings: @{UInt64: Listing} - - // insert - // Create and publish a Listing for an NFT. - access(all) fun createListing( - nftProviderCapability: Capability<&{NonFungibleToken.Provider, NonFungibleToken.CollectionPublic}>, - nftType: Type, - nftID: UInt64, - salePaymentVaultType: Type, - saleCuts: [SaleCut] - ): UInt64 { - let listing <- create Listing( - nftProviderCapability: nftProviderCapability, - nftType: nftType, - nftID: nftID, - salePaymentVaultType: salePaymentVaultType, - saleCuts: saleCuts, - storefrontID: self.uuid - ) - - let listingResourceID = listing.uuid - let listingPrice = listing.getDetails().salePrice - - // Add the new listing to the dictionary. - let oldListing <- self.listings[listingResourceID] <- listing - destroy oldListing - - emit ListingAvailable( - storefrontAddress: self.owner?.address!, - listingResourceID: listingResourceID, - nftType: nftType, - nftID: nftID, - ftVaultType: salePaymentVaultType, - price: listingPrice - ) - - return listingResourceID - } - - // removeListing - // Remove a Listing that has not yet been purchased from the collection and destroy it. - access(all) fun removeListing(listingResourceID: UInt64) { - let listing <- self.listings.remove(key: listingResourceID) - ?? panic("missing Listing") - - destroy listing - } - - // getListingIDs - // Returns an array of the Listing resource IDs that are in the collection - access(all) fun getListingIDs(): [UInt64] { - return self.listings.keys - } - - // borrowSaleItem - // Returns a read-only view of the SaleItem for the given listingID if it is contained by this collection. - access(all) fun borrowListing(listingResourceID: UInt64): &Listing{ListingPublic}? { - if self.listings[listingResourceID] != nil { - return &self.listings[listingResourceID] as &Listing{ListingPublic} - } else { - return nil - } - } - - // cleanup - // Remove a listing *if* it has been purchased. - access(all) fun cleanup(listingResourceID: UInt64) { - pre { - self.listings[listingResourceID] != nil: "could not find listing with given id" - } - - let listing <- self.listings.remove(key: listingResourceID)! - assert(listing.getDetails().purchased == true, message: "listing is not purchased, only admin can remove") - destroy listing - } - - // destructor - destroy () { - destroy self.listings - - // Let event consumers know that this storefront will no longer exist - emit StorefrontDestroyed(storefrontResourceID: self.uuid) - } - - // constructor - init () { - self.listings <- {} - - // Let event consumers know that this storefront exists - emit StorefrontInitialized(storefrontResourceID: self.uuid) - } - } - - access(all) fun createStorefront(): @Storefront { - return <-create Storefront() - } - - ... -} 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..814f9df --- /dev/null +++ b/cadence/contracts/Recipe.cdc @@ -0,0 +1,516 @@ +import "FungibleToken" +import "NonFungibleToken" +import "Burner" + +/// NB: This contract is no longer supported. NFT Storefront V2 is recommended + +/// A general purpose sale support contract for Flow NonFungibleTokens. +/// +/// Each account that wants to list NFTs for sale installs a Storefront, +/// and lists individual sales within that Storefront as Listings. +/// There is one Storefront per account, it handles sales of all NFT types +/// for that account. +/// +/// Each Listing can have one or more "cut"s of the sale price that +/// goes to one or more addresses. Cuts can be used to pay listing fees +/// or other considerations. +/// Each NFT may be listed in one or more Listings, the validity of each +/// Listing can easily be checked. +/// +/// Purchasers can watch for Listing events and check the NFT type and +/// ID to see if they wish to buy the listed item. +/// Marketplaces and other aggregators can watch for Listing events +/// and list items of interest. +/// +access(all) contract NFTStorefront { + + access(all) entitlement CreateListing + access(all) entitlement RemoveListing + + /// StorefrontInitialized + /// A Storefront resource has been created. + /// Event consumers can now expect events from this Storefront. + /// Note that we do not specify an address: we cannot and should not. + /// Created resources do not have an owner address, and may be moved + /// after creation in ways we cannot check. + /// ListingAvailable events can be used to determine the address + /// of the owner of the Storefront (...its location) at the time of + /// the listing but only at that precise moment in that precise transaction. + /// If the seller moves the Storefront while the listing is valid, + /// that is on them. + /// + access(all) event StorefrontInitialized(storefrontResourceID: UInt64) + + /// StorefrontDestroyed + /// A Storefront has been destroyed. + /// Event consumers can now stop processing events from this Storefront. + /// Note that we do not specify an address. + /// + access(all) event StorefrontDestroyed(storefrontResourceID: UInt64) + + /// ListingAvailable + /// A listing has been created and added to a Storefront resource. + /// The Address values here are valid when the event is emitted, but + /// the state of the accounts they refer to may be changed outside of the + /// NFTStorefront workflow, so be careful to check when using them. + /// + access(all) event ListingAvailable( + storefrontAddress: Address, + listingResourceID: UInt64, + nftType: Type, + nftID: UInt64, + ftVaultType: Type, + price: UFix64 + ) + + /// ListingCompleted + /// The listing has been resolved. It has either been purchased, or removed and destroyed. + /// + access(all) event ListingCompleted( + listingResourceID: UInt64, + storefrontResourceID: UInt64, + purchased: Bool, + nftType: Type, + nftID: UInt64 + ) + + /// StorefrontStoragePath + /// The location in storage that a Storefront resource should be located. + access(all) let StorefrontStoragePath: StoragePath + + /// StorefrontPublicPath + /// The public location for a Storefront link. + access(all) let StorefrontPublicPath: PublicPath + + + /// SaleCut + /// A struct representing a recipient that must be sent a certain amount + /// of the payment when a token is sold. + /// + access(all) struct SaleCut { + /// The receiver for the payment. + /// Note that we do not store an address to find the Vault that this represents, + /// as the link or resource that we fetch in this way may be manipulated, + /// so to find the address that a cut goes to you must get this struct and then + /// call receiver.borrow()!.owner.address on it. + /// This can be done efficiently in a script. + access(all) let receiver: Capability<&{FungibleToken.Receiver}> + + /// The amount of the payment FungibleToken that will be paid to the receiver. + access(all) let amount: UFix64 + + /// initializer + /// + init(receiver: Capability<&{FungibleToken.Receiver}>, amount: UFix64) { + self.receiver = receiver + self.amount = amount + } + } + + + /// ListingDetails + /// A struct containing a Listing's data. + /// + access(all) struct ListingDetails { + /// The Storefront that the Listing is stored in. + /// Note that this resource cannot be moved to a different Storefront, + /// so this is OK. If we ever make it so that it *can* be moved, + /// this should be revisited. + access(all) var storefrontID: UInt64 + /// Whether this listing has been purchased or not. + access(all) var purchased: Bool + /// The Type of the NonFungibleToken.NFT that is being listed. + access(all) let nftType: Type + /// The ID of the NFT within that type. + access(all) let nftID: UInt64 + /// The Type of the FungibleToken that payments must be made in. + access(all) let salePaymentVaultType: Type + /// The amount that must be paid in the specified FungibleToken. + access(all) let salePrice: UFix64 + /// This specifies the division of payment between recipients. + access(all) let saleCuts: [SaleCut] + + /// setToPurchased + /// Irreversibly set this listing as purchased. + /// + access(contract) fun setToPurchased() { + self.purchased = true + } + + /// initializer + /// + init ( + nftType: Type, + nftID: UInt64, + salePaymentVaultType: Type, + saleCuts: [SaleCut], + storefrontID: UInt64 + ) { + self.storefrontID = storefrontID + self.purchased = false + self.nftType = nftType + self.nftID = nftID + self.salePaymentVaultType = salePaymentVaultType + // Store the cuts + assert(saleCuts.length > 0, message: "Listing must have at least one payment cut recipient") + self.saleCuts = saleCuts + + // Calculate the total price from the cuts + var salePrice = 0.0 + // Perform initial check on capabilities, and calculate sale price from cut amounts. + for cut in self.saleCuts { + // Make sure we can borrow the receiver. + // We will check this again when the token is sold. + cut.receiver.borrow() + ?? panic("Cannot borrow receiver") + // Add the cut amount to the total price + salePrice = salePrice + cut.amount + } + assert(salePrice > 0.0, message: "Listing must have non-zero price") + + // Store the calculated sale price + self.salePrice = salePrice + } + } + + + /// ListingPublic + /// An interface providing a useful public interface to a Listing. + /// + access(all) resource interface ListingPublic { + /// borrowNFT + /// This will assert in the same way as the NFT standard borrowNFT() + /// if the NFT is absent, for example if it has been sold via another listing. + /// + access(all) fun borrowNFT(): &{NonFungibleToken.NFT}? + + /// purchase + /// Purchase the listing, buying the token. + /// This pays the beneficiaries and returns the token to the buyer. + /// + access(all) fun purchase(payment: @{FungibleToken.Vault}): @{NonFungibleToken.NFT} + + /// getDetails + /// + access(all) fun getDetails(): ListingDetails + + } + + + /// Listing + /// A resource that allows an NFT to be sold for an amount of a given FungibleToken, + /// and for the proceeds of that sale to be split between several recipients. + /// + access(all) resource Listing: ListingPublic, Burner.Burnable { + // Event to be emitted when this listing is destroyed. + // If the listing has not been purchased, we regard it as completed here. + // There is a separate event in purchase for purchased listings + access(all) event ResourceDestroyed( + listingResourceID: UInt64 = self.uuid, + storefrontResourceID: UInt64 = self.details.storefrontID, + purchased: Bool = self.details.purchased, + nftType: String = self.details.nftType.identifier, + nftID: UInt64 = self.details.nftID + ) + + access(contract) fun burnCallback() { + // If the listing has not been purchased, we regard it as completed here. + // Otherwise we regard it as completed in purchase(). + // This is because we destroy the listing in Storefront.removeListing() + // or Storefront.cleanup() . + // If we change this destructor, revisit those functions. + if !self.details.purchased { + emit ListingCompleted( + listingResourceID: self.uuid, + storefrontResourceID: self.details.storefrontID, + purchased: self.details.purchased, + nftType: self.details.nftType, + nftID: self.details.nftID + ) + } + } + + /// The simple (non-Capability, non-complex) details of the sale + access(self) let details: ListingDetails + + /// A capability allowing this resource to withdraw the NFT with the given ID from its collection. + /// This capability allows the resource to withdraw *any* NFT, so you should be careful when giving + /// such a capability to a resource and always check its code to make sure it will use it in the + /// way that it claims. + access(contract) let nftProviderCapability: Capability + + /// borrowNFT + /// This will assert in the same way as the NFT standard borrowNFT() + /// if the NFT is absent, for example if it has been sold via another listing. + /// + access(all) fun borrowNFT(): &{NonFungibleToken.NFT}? { + let ref = self.nftProviderCapability.borrow()!.borrowNFT(self.getDetails().nftID) + assert(ref != nil, message: "Could not borrow a reference to the NFT") + assert(ref!.isInstance(self.getDetails().nftType), message: "token has wrong type") + assert(ref?.id == self.getDetails().nftID, message: "token has wrong ID") + return (ref as &{NonFungibleToken.NFT}?) + } + + /// getDetails + /// Get the details of the current state of the Listing as a struct. + /// This avoids having more public variables and getter methods for them, and plays + /// nicely with scripts (which cannot return resources). + /// + access(all) fun getDetails(): ListingDetails { + return self.details + } + + /// purchase + /// Purchase the listing, buying the token. + /// This pays the beneficiaries and returns the token to the buyer. + /// + access(all) fun purchase(payment: @{FungibleToken.Vault}): @{NonFungibleToken.NFT} { + pre { + self.details.purchased == false: "listing has already been purchased" + payment.isInstance(self.details.salePaymentVaultType): "payment vault is not requested fungible token" + payment.balance == self.details.salePrice: "payment vault does not contain requested price" + } + + // Make sure the listing cannot be purchased again. + self.details.setToPurchased() + + + // Fetch the token to return to the purchaser. + let nft <-self.nftProviderCapability.borrow()!.withdraw(withdrawID: self.details.nftID) + // Neither receivers nor providers are trustworthy, they must implement the correct + // interface but beyond complying with its pre/post conditions they are not gauranteed + // to implement the functionality behind the interface in any given way. + // Therefore we cannot trust the Collection resource behind the interface, + // and we must check the NFT resource it gives us to make sure that it is the correct one. + assert(nft.isInstance(self.details.nftType), message: "withdrawn NFT is not of specified type") + assert(nft.id == self.details.nftID, message: "withdrawn NFT does not have specified ID") + + // Rather than aborting the transaction if any receiver is absent when we try to pay it, + // we send the cut to the first valid receiver. + // The first receiver should therefore either be the seller, or an agreed recipient for + // any unpaid cuts. + var residualReceiver: &{FungibleToken.Receiver}? = nil + + // Pay each beneficiary their amount of the payment. + for cut in self.details.saleCuts { + if let receiver = cut.receiver.borrow() { + let paymentCut <- payment.withdraw(amount: cut.amount) + receiver.deposit(from: <-paymentCut) + if (residualReceiver == nil) { + residualReceiver = receiver + } + } + } + + assert(residualReceiver != nil, message: "No valid payment receivers") + + // At this point, if all recievers were active and availabile, then the payment Vault will have + // zero tokens left, and this will functionally be a no-op that consumes the empty vault + residualReceiver!.deposit(from: <-payment) + + // If the listing is purchased, we regard it as completed here. + // Otherwise we regard it as completed in the destructor. + + emit ListingCompleted( + listingResourceID: self.uuid, + storefrontResourceID: self.details.storefrontID, + purchased: self.details.purchased, + nftType: self.details.nftType, + nftID: self.details.nftID + ) + + return <-nft + } + + /// initializer + /// + init ( + nftProviderCapability: Capability, + nftType: Type, + nftID: UInt64, + salePaymentVaultType: Type, + saleCuts: [SaleCut], + storefrontID: UInt64 + ) { + // Store the sale information + self.details = ListingDetails( + nftType: nftType, + nftID: nftID, + salePaymentVaultType: salePaymentVaultType, + saleCuts: saleCuts, + storefrontID: storefrontID + ) + + // Store the NFT provider + self.nftProviderCapability = nftProviderCapability + + // Check that the provider contains the NFT. + // We will check it again when the token is sold. + // We cannot move this into a function because initializers cannot call member functions. + let provider = self.nftProviderCapability.borrow() + assert(provider != nil, message: "cannot borrow nftProviderCapability") + + let nft = provider!.borrowNFT(self.details.nftID) + // This will precondition assert if the token is not available. + assert(nft != nil, message: "Could not borrow a reference to the NFT") + assert(nft!.isInstance(self.details.nftType), message: "token is not of specified type") + assert(nft?.id == self.details.nftID, message: "token does not have specified ID") + } + } + + /// StorefrontManager + /// An interface for adding and removing Listings within a Storefront, + /// intended for use by the Storefront's own + /// + access(all) resource interface StorefrontManager { + /// createListing + /// Allows the Storefront owner to create and insert Listings. + /// + access(CreateListing) fun createListing( + nftProviderCapability: Capability, + nftType: Type, + nftID: UInt64, + salePaymentVaultType: Type, + saleCuts: [SaleCut] + ): UInt64 + /// removeListing + /// Allows the Storefront owner to remove any sale listing, acepted or not. + /// + access(RemoveListing) fun removeListing(listingResourceID: UInt64) + } + + /// StorefrontPublic + /// An interface to allow listing and borrowing Listings, and purchasing items via Listings + /// in a Storefront. + /// + access(all) resource interface StorefrontPublic { + access(all) view fun getListingIDs(): [UInt64] + access(all) view fun borrowListing(listingResourceID: UInt64): &{ListingPublic}? { + post { + result == nil || result!.getType() == Type<@Listing>(): + "Cannot borrow a non-NFTStorefront.Listing!" + } + } + access(all) fun cleanup(listingResourceID: UInt64) + } + + /// Storefront + /// A resource that allows its owner to manage a list of Listings, and anyone to interact with them + /// in order to query their details and purchase the NFTs that they represent. + /// + access(all) resource Storefront: StorefrontManager, StorefrontPublic { + // Event to be emitted when this storefront is destroyed. + access(all) event ResourceDestroyed( + storefrontResourceID: UInt64 = self.uuid + ) + + /// The dictionary of Listing uuids to Listing resources. + access(self) var listings: @{UInt64: Listing} + + /// insert + /// Create and publish a Listing for an NFT. + /// + access(CreateListing) fun createListing( + nftProviderCapability: Capability, + nftType: Type, + nftID: UInt64, + salePaymentVaultType: Type, + saleCuts: [SaleCut] + ): UInt64 { + let listing <- create Listing( + nftProviderCapability: nftProviderCapability, + nftType: nftType, + nftID: nftID, + salePaymentVaultType: salePaymentVaultType, + saleCuts: saleCuts, + storefrontID: self.uuid + ) + + let listingResourceID = listing.uuid + let listingPrice = listing.getDetails().salePrice + + // Add the new listing to the dictionary. + let oldListing <- self.listings[listingResourceID] <- listing + // Note that oldListing will always be nil, but we have to handle it. + + Burner.burn(<-oldListing) + + emit ListingAvailable( + storefrontAddress: self.owner?.address!, + listingResourceID: listingResourceID, + nftType: nftType, + nftID: nftID, + ftVaultType: salePaymentVaultType, + price: listingPrice + ) + + return listingResourceID + } + + + /// removeListing + /// Remove a Listing that has not yet been purchased from the collection and destroy it. + /// + access(RemoveListing) fun removeListing(listingResourceID: UInt64) { + let listing <- self.listings.remove(key: listingResourceID) + ?? panic("missing Listing") + + // This will emit a ListingCompleted event. + Burner.burn(<-listing) + } + + /// getListingIDs + /// Returns an array of the Listing resource IDs that are in the collection + /// + access(all) view fun getListingIDs(): [UInt64] { + return self.listings.keys + } + + /// borrowSaleItem + /// Returns a read-only view of the SaleItem for the given listingID if it is contained by this collection. + /// + access(all) view fun borrowListing(listingResourceID: UInt64): &{ListingPublic}? { + if self.listings[listingResourceID] != nil { + return &self.listings[listingResourceID] as &{ListingPublic}? + } else { + return nil + } + } + + /// cleanup + /// Remove an listing *if* it has been purchased. + /// Anyone can call, but at present it only benefits the account owner to do so. + /// Kind purchasers can however call it if they like. + /// + access(all) fun cleanup(listingResourceID: UInt64) { + pre { + self.listings[listingResourceID] != nil: "could not find listing with given id" + } + + let listing <- self.listings.remove(key: listingResourceID)! + assert(listing.getDetails().purchased == true, message: "listing is not purchased, only admin can remove") + Burner.burn(<-listing) + } + + /// constructor + /// + init () { + self.listings <- {} + + // Let event consumers know that this storefront exists + emit StorefrontInitialized(storefrontResourceID: self.uuid) + } + } + + /// createStorefront + /// Make creating a Storefront publicly accessible. + /// + access(all) fun createStorefront(): @Storefront { + return <-create Storefront() + } + + init () { + self.StorefrontStoragePath = /storage/NFTStorefront + self.StorefrontPublicPath = /public/NFTStorefront + } +} \ 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 58163ad..0000000 --- a/cadence/transaction.cdc +++ /dev/null @@ -1,13 +0,0 @@ -import NFTStorefront from 0x03 - -// This transaction sets up account 0x01 for the marketplace tutorial -// by publishing a Vault reference and creating an empty NFT Collection. -transaction { - prepare(acct: auth(Storage) &Account) { - - // Save the newly created storefront resource into account storage - acct.storage.save(<-NFTStorefront.createStorefront(), to: NFTStorefront.StorefrontStoragePath) - - log("Storefront created") - } -} diff --git a/cadence/transaction.cdc b/cadence/transaction.cdc new file mode 120000 index 0000000..bb6daf2 --- /dev/null +++ b/cadence/transaction.cdc @@ -0,0 +1 @@ +./cadence/transactions/create_storefront.cdc \ No newline at end of file diff --git a/cadence/transactions/create_storefront.cdc b/cadence/transactions/create_storefront.cdc new file mode 100644 index 0000000..5ad1f62 --- /dev/null +++ b/cadence/transactions/create_storefront.cdc @@ -0,0 +1,13 @@ +import "NFTStorefront" + +// This transaction sets up account 0x01 for the marketplace tutorial +// by publishing a Vault reference and creating an empty NFT Collection. +transaction { + prepare(acct: auth(Storage) &Account) { + + // Save the newly created storefront resource into account storage + acct.storage.save(<-NFTStorefront.createStorefront(), to: NFTStorefront.StorefrontStoragePath) + + log("Storefront created") + } +} 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..151c65b 100644 --- a/flow.json +++ b/flow.json @@ -1,9 +1,56 @@ { "contracts": { - "Counter": { - "source": "cadence/contracts/Counter.cdc", + "NFTStorefront": { + "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" + } + }, + "FungibleToken": { + "source": "mainnet://f233dcee88fe0abe.FungibleToken", + "hash": "050328d01c6cde307fbe14960632666848d9b7ea4fef03ca8c0bbfb0f2884068", + "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 +59,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": [ + "NFTStorefront" + ] + } } } \ No newline at end of file From f164cf341cc3e721d6392b24a99bcb4f91e5e56b Mon Sep 17 00:00:00 2001 From: Lea Lobanov Date: Sun, 8 Dec 2024 16:21:01 +0400 Subject: [PATCH 4/9] Improve explanation text --- explanations/contract.txt | 5 ++--- explanations/transaction.txt | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/explanations/contract.txt b/explanations/contract.txt index 3b2f81a..ddcfc5d 100644 --- a/explanations/contract.txt +++ b/explanations/contract.txt @@ -1,5 +1,4 @@ -The NFT Storefront contract is used to be able to list NFTS that a user owns for sale on your marketplace. Users can also purchase other NFTS, borrow listings, and do tons of other things related to the Storefront contract. -Before doing any of this, you need to create a Storefront resource from the NFTStorefront contract and save it to your account. Once that resource is saved you then have access to the Storefront resource which will give you the ability to create listings, remove listings, getListings, borrowListings, cleanupListings, and destroy your own Storefront. +The NFT Storefront contract enables users to list their NFTs for sale on a marketplace, purchase NFTs from others, borrow listings, and perform various other operations related to managing and interacting with the Storefront. To use these features, a user must first create a Storefront resource from the NFT Storefront contract and save it to their account. This Storefront resource acts as a gateway to functionalities such as creating and removing listings, retrieving and borrowing listings, cleaning up outdated listings, and even destroying the Storefront itself when no longer needed. -The createStorefront function allows anyone to create a storefront and save it to their account. +The createStorefront function facilitates this process, allowing anyone to easily create and save a Storefront resource to their account, unlocking full access to the Storefront’s capabilities. \ No newline at end of file diff --git a/explanations/transaction.txt b/explanations/transaction.txt index 6bd0a59..bec8f16 100644 --- a/explanations/transaction.txt +++ b/explanations/transaction.txt @@ -1 +1 @@ -Here you are simply calling the createStorefront function to save a storefront to your account. \ No newline at end of file +This transaction demonstrates how to set up a user account to participate in the marketplace by creating and saving a Storefront resource using the NFTStorefront contract. The createStorefront function is called to generate a new Storefront resource, which is then stored in the account's storage at the predefined NFTStorefront.StorefrontStoragePath. \ No newline at end of file From c17bf827febe0135a7c7423e3eab6e88df7af643 Mon Sep 17 00:00:00 2001 From: Lea Lobanov Date: Wed, 11 Dec 2024 01:52:56 +0400 Subject: [PATCH 5/9] Update readme --- README.md | 61 ++++++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 49 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 5edea06..f63e25e 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ Create a secondary marketplace for your NFTS using the NFT Storefront Contract. - [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/create_storefront.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 From 18eb9ae68b4c31a78d0b8691c9238a816f65b45f Mon Sep 17 00:00:00 2001 From: Jerome P Date: Thu, 12 Dec 2024 15:58:28 -0800 Subject: [PATCH 6/9] Added setup method to pull in Recipe into test execution Updated flow.json to denote the deployed address for testing context --- cadence/tests/Recipe_test.cdc | 12 ++++++++++++ flow.json | 5 +++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/cadence/tests/Recipe_test.cdc b/cadence/tests/Recipe_test.cdc index 986e8fe..49c0bec 100644 --- a/cadence/tests/Recipe_test.cdc +++ b/cadence/tests/Recipe_test.cdc @@ -1,4 +1,16 @@ import Test +import "test_helpers.cdc" + +access(all) +fun setup() { + let err = Test.deployContract( + name: "NFTStorefront", + path: "../contracts/Recipe.cdc", + arguments: [], + ) + + Test.expect(err, Test.beNil()) +} access(all) fun testExample() { let array = [1, 2, 3] diff --git a/flow.json b/flow.json index 151c65b..a8782d5 100644 --- a/flow.json +++ b/flow.json @@ -1,9 +1,10 @@ { "contracts": { "NFTStorefront": { - "source": "./cadence/contracts/Recipe.cdc", + "source": "cadence/contracts/Recipe.cdc", "aliases": { - "emulator": "f8d6e0586b0a20c7" + "emulator": "f8d6e0586b0a20c7", + "testing": "0000000000000007" } } }, From 27f9ae60669cd3310e1f819e61f3a78a7ab72f55 Mon Sep 17 00:00:00 2001 From: Lea Lobanov Date: Sat, 14 Dec 2024 00:45:52 +0400 Subject: [PATCH 7/9] Storefront v2 --- cadence/contract.cdc | 1 - cadence/contracts/Recipe.cdc | 516 --------------------- cadence/tests/Recipe_test.cdc | 18 - cadence/transactions/create_storefront.cdc | 6 +- flow.json | 11 +- 5 files changed, 13 insertions(+), 539 deletions(-) delete mode 120000 cadence/contract.cdc delete mode 100644 cadence/contracts/Recipe.cdc delete mode 100644 cadence/tests/Recipe_test.cdc diff --git a/cadence/contract.cdc b/cadence/contract.cdc deleted file mode 120000 index b64184f..0000000 --- a/cadence/contract.cdc +++ /dev/null @@ -1 +0,0 @@ -./cadence/contracts/Recipe.cdc \ No newline at end of file diff --git a/cadence/contracts/Recipe.cdc b/cadence/contracts/Recipe.cdc deleted file mode 100644 index 814f9df..0000000 --- a/cadence/contracts/Recipe.cdc +++ /dev/null @@ -1,516 +0,0 @@ -import "FungibleToken" -import "NonFungibleToken" -import "Burner" - -/// NB: This contract is no longer supported. NFT Storefront V2 is recommended - -/// A general purpose sale support contract for Flow NonFungibleTokens. -/// -/// Each account that wants to list NFTs for sale installs a Storefront, -/// and lists individual sales within that Storefront as Listings. -/// There is one Storefront per account, it handles sales of all NFT types -/// for that account. -/// -/// Each Listing can have one or more "cut"s of the sale price that -/// goes to one or more addresses. Cuts can be used to pay listing fees -/// or other considerations. -/// Each NFT may be listed in one or more Listings, the validity of each -/// Listing can easily be checked. -/// -/// Purchasers can watch for Listing events and check the NFT type and -/// ID to see if they wish to buy the listed item. -/// Marketplaces and other aggregators can watch for Listing events -/// and list items of interest. -/// -access(all) contract NFTStorefront { - - access(all) entitlement CreateListing - access(all) entitlement RemoveListing - - /// StorefrontInitialized - /// A Storefront resource has been created. - /// Event consumers can now expect events from this Storefront. - /// Note that we do not specify an address: we cannot and should not. - /// Created resources do not have an owner address, and may be moved - /// after creation in ways we cannot check. - /// ListingAvailable events can be used to determine the address - /// of the owner of the Storefront (...its location) at the time of - /// the listing but only at that precise moment in that precise transaction. - /// If the seller moves the Storefront while the listing is valid, - /// that is on them. - /// - access(all) event StorefrontInitialized(storefrontResourceID: UInt64) - - /// StorefrontDestroyed - /// A Storefront has been destroyed. - /// Event consumers can now stop processing events from this Storefront. - /// Note that we do not specify an address. - /// - access(all) event StorefrontDestroyed(storefrontResourceID: UInt64) - - /// ListingAvailable - /// A listing has been created and added to a Storefront resource. - /// The Address values here are valid when the event is emitted, but - /// the state of the accounts they refer to may be changed outside of the - /// NFTStorefront workflow, so be careful to check when using them. - /// - access(all) event ListingAvailable( - storefrontAddress: Address, - listingResourceID: UInt64, - nftType: Type, - nftID: UInt64, - ftVaultType: Type, - price: UFix64 - ) - - /// ListingCompleted - /// The listing has been resolved. It has either been purchased, or removed and destroyed. - /// - access(all) event ListingCompleted( - listingResourceID: UInt64, - storefrontResourceID: UInt64, - purchased: Bool, - nftType: Type, - nftID: UInt64 - ) - - /// StorefrontStoragePath - /// The location in storage that a Storefront resource should be located. - access(all) let StorefrontStoragePath: StoragePath - - /// StorefrontPublicPath - /// The public location for a Storefront link. - access(all) let StorefrontPublicPath: PublicPath - - - /// SaleCut - /// A struct representing a recipient that must be sent a certain amount - /// of the payment when a token is sold. - /// - access(all) struct SaleCut { - /// The receiver for the payment. - /// Note that we do not store an address to find the Vault that this represents, - /// as the link or resource that we fetch in this way may be manipulated, - /// so to find the address that a cut goes to you must get this struct and then - /// call receiver.borrow()!.owner.address on it. - /// This can be done efficiently in a script. - access(all) let receiver: Capability<&{FungibleToken.Receiver}> - - /// The amount of the payment FungibleToken that will be paid to the receiver. - access(all) let amount: UFix64 - - /// initializer - /// - init(receiver: Capability<&{FungibleToken.Receiver}>, amount: UFix64) { - self.receiver = receiver - self.amount = amount - } - } - - - /// ListingDetails - /// A struct containing a Listing's data. - /// - access(all) struct ListingDetails { - /// The Storefront that the Listing is stored in. - /// Note that this resource cannot be moved to a different Storefront, - /// so this is OK. If we ever make it so that it *can* be moved, - /// this should be revisited. - access(all) var storefrontID: UInt64 - /// Whether this listing has been purchased or not. - access(all) var purchased: Bool - /// The Type of the NonFungibleToken.NFT that is being listed. - access(all) let nftType: Type - /// The ID of the NFT within that type. - access(all) let nftID: UInt64 - /// The Type of the FungibleToken that payments must be made in. - access(all) let salePaymentVaultType: Type - /// The amount that must be paid in the specified FungibleToken. - access(all) let salePrice: UFix64 - /// This specifies the division of payment between recipients. - access(all) let saleCuts: [SaleCut] - - /// setToPurchased - /// Irreversibly set this listing as purchased. - /// - access(contract) fun setToPurchased() { - self.purchased = true - } - - /// initializer - /// - init ( - nftType: Type, - nftID: UInt64, - salePaymentVaultType: Type, - saleCuts: [SaleCut], - storefrontID: UInt64 - ) { - self.storefrontID = storefrontID - self.purchased = false - self.nftType = nftType - self.nftID = nftID - self.salePaymentVaultType = salePaymentVaultType - // Store the cuts - assert(saleCuts.length > 0, message: "Listing must have at least one payment cut recipient") - self.saleCuts = saleCuts - - // Calculate the total price from the cuts - var salePrice = 0.0 - // Perform initial check on capabilities, and calculate sale price from cut amounts. - for cut in self.saleCuts { - // Make sure we can borrow the receiver. - // We will check this again when the token is sold. - cut.receiver.borrow() - ?? panic("Cannot borrow receiver") - // Add the cut amount to the total price - salePrice = salePrice + cut.amount - } - assert(salePrice > 0.0, message: "Listing must have non-zero price") - - // Store the calculated sale price - self.salePrice = salePrice - } - } - - - /// ListingPublic - /// An interface providing a useful public interface to a Listing. - /// - access(all) resource interface ListingPublic { - /// borrowNFT - /// This will assert in the same way as the NFT standard borrowNFT() - /// if the NFT is absent, for example if it has been sold via another listing. - /// - access(all) fun borrowNFT(): &{NonFungibleToken.NFT}? - - /// purchase - /// Purchase the listing, buying the token. - /// This pays the beneficiaries and returns the token to the buyer. - /// - access(all) fun purchase(payment: @{FungibleToken.Vault}): @{NonFungibleToken.NFT} - - /// getDetails - /// - access(all) fun getDetails(): ListingDetails - - } - - - /// Listing - /// A resource that allows an NFT to be sold for an amount of a given FungibleToken, - /// and for the proceeds of that sale to be split between several recipients. - /// - access(all) resource Listing: ListingPublic, Burner.Burnable { - // Event to be emitted when this listing is destroyed. - // If the listing has not been purchased, we regard it as completed here. - // There is a separate event in purchase for purchased listings - access(all) event ResourceDestroyed( - listingResourceID: UInt64 = self.uuid, - storefrontResourceID: UInt64 = self.details.storefrontID, - purchased: Bool = self.details.purchased, - nftType: String = self.details.nftType.identifier, - nftID: UInt64 = self.details.nftID - ) - - access(contract) fun burnCallback() { - // If the listing has not been purchased, we regard it as completed here. - // Otherwise we regard it as completed in purchase(). - // This is because we destroy the listing in Storefront.removeListing() - // or Storefront.cleanup() . - // If we change this destructor, revisit those functions. - if !self.details.purchased { - emit ListingCompleted( - listingResourceID: self.uuid, - storefrontResourceID: self.details.storefrontID, - purchased: self.details.purchased, - nftType: self.details.nftType, - nftID: self.details.nftID - ) - } - } - - /// The simple (non-Capability, non-complex) details of the sale - access(self) let details: ListingDetails - - /// A capability allowing this resource to withdraw the NFT with the given ID from its collection. - /// This capability allows the resource to withdraw *any* NFT, so you should be careful when giving - /// such a capability to a resource and always check its code to make sure it will use it in the - /// way that it claims. - access(contract) let nftProviderCapability: Capability - - /// borrowNFT - /// This will assert in the same way as the NFT standard borrowNFT() - /// if the NFT is absent, for example if it has been sold via another listing. - /// - access(all) fun borrowNFT(): &{NonFungibleToken.NFT}? { - let ref = self.nftProviderCapability.borrow()!.borrowNFT(self.getDetails().nftID) - assert(ref != nil, message: "Could not borrow a reference to the NFT") - assert(ref!.isInstance(self.getDetails().nftType), message: "token has wrong type") - assert(ref?.id == self.getDetails().nftID, message: "token has wrong ID") - return (ref as &{NonFungibleToken.NFT}?) - } - - /// getDetails - /// Get the details of the current state of the Listing as a struct. - /// This avoids having more public variables and getter methods for them, and plays - /// nicely with scripts (which cannot return resources). - /// - access(all) fun getDetails(): ListingDetails { - return self.details - } - - /// purchase - /// Purchase the listing, buying the token. - /// This pays the beneficiaries and returns the token to the buyer. - /// - access(all) fun purchase(payment: @{FungibleToken.Vault}): @{NonFungibleToken.NFT} { - pre { - self.details.purchased == false: "listing has already been purchased" - payment.isInstance(self.details.salePaymentVaultType): "payment vault is not requested fungible token" - payment.balance == self.details.salePrice: "payment vault does not contain requested price" - } - - // Make sure the listing cannot be purchased again. - self.details.setToPurchased() - - - // Fetch the token to return to the purchaser. - let nft <-self.nftProviderCapability.borrow()!.withdraw(withdrawID: self.details.nftID) - // Neither receivers nor providers are trustworthy, they must implement the correct - // interface but beyond complying with its pre/post conditions they are not gauranteed - // to implement the functionality behind the interface in any given way. - // Therefore we cannot trust the Collection resource behind the interface, - // and we must check the NFT resource it gives us to make sure that it is the correct one. - assert(nft.isInstance(self.details.nftType), message: "withdrawn NFT is not of specified type") - assert(nft.id == self.details.nftID, message: "withdrawn NFT does not have specified ID") - - // Rather than aborting the transaction if any receiver is absent when we try to pay it, - // we send the cut to the first valid receiver. - // The first receiver should therefore either be the seller, or an agreed recipient for - // any unpaid cuts. - var residualReceiver: &{FungibleToken.Receiver}? = nil - - // Pay each beneficiary their amount of the payment. - for cut in self.details.saleCuts { - if let receiver = cut.receiver.borrow() { - let paymentCut <- payment.withdraw(amount: cut.amount) - receiver.deposit(from: <-paymentCut) - if (residualReceiver == nil) { - residualReceiver = receiver - } - } - } - - assert(residualReceiver != nil, message: "No valid payment receivers") - - // At this point, if all recievers were active and availabile, then the payment Vault will have - // zero tokens left, and this will functionally be a no-op that consumes the empty vault - residualReceiver!.deposit(from: <-payment) - - // If the listing is purchased, we regard it as completed here. - // Otherwise we regard it as completed in the destructor. - - emit ListingCompleted( - listingResourceID: self.uuid, - storefrontResourceID: self.details.storefrontID, - purchased: self.details.purchased, - nftType: self.details.nftType, - nftID: self.details.nftID - ) - - return <-nft - } - - /// initializer - /// - init ( - nftProviderCapability: Capability, - nftType: Type, - nftID: UInt64, - salePaymentVaultType: Type, - saleCuts: [SaleCut], - storefrontID: UInt64 - ) { - // Store the sale information - self.details = ListingDetails( - nftType: nftType, - nftID: nftID, - salePaymentVaultType: salePaymentVaultType, - saleCuts: saleCuts, - storefrontID: storefrontID - ) - - // Store the NFT provider - self.nftProviderCapability = nftProviderCapability - - // Check that the provider contains the NFT. - // We will check it again when the token is sold. - // We cannot move this into a function because initializers cannot call member functions. - let provider = self.nftProviderCapability.borrow() - assert(provider != nil, message: "cannot borrow nftProviderCapability") - - let nft = provider!.borrowNFT(self.details.nftID) - // This will precondition assert if the token is not available. - assert(nft != nil, message: "Could not borrow a reference to the NFT") - assert(nft!.isInstance(self.details.nftType), message: "token is not of specified type") - assert(nft?.id == self.details.nftID, message: "token does not have specified ID") - } - } - - /// StorefrontManager - /// An interface for adding and removing Listings within a Storefront, - /// intended for use by the Storefront's own - /// - access(all) resource interface StorefrontManager { - /// createListing - /// Allows the Storefront owner to create and insert Listings. - /// - access(CreateListing) fun createListing( - nftProviderCapability: Capability, - nftType: Type, - nftID: UInt64, - salePaymentVaultType: Type, - saleCuts: [SaleCut] - ): UInt64 - /// removeListing - /// Allows the Storefront owner to remove any sale listing, acepted or not. - /// - access(RemoveListing) fun removeListing(listingResourceID: UInt64) - } - - /// StorefrontPublic - /// An interface to allow listing and borrowing Listings, and purchasing items via Listings - /// in a Storefront. - /// - access(all) resource interface StorefrontPublic { - access(all) view fun getListingIDs(): [UInt64] - access(all) view fun borrowListing(listingResourceID: UInt64): &{ListingPublic}? { - post { - result == nil || result!.getType() == Type<@Listing>(): - "Cannot borrow a non-NFTStorefront.Listing!" - } - } - access(all) fun cleanup(listingResourceID: UInt64) - } - - /// Storefront - /// A resource that allows its owner to manage a list of Listings, and anyone to interact with them - /// in order to query their details and purchase the NFTs that they represent. - /// - access(all) resource Storefront: StorefrontManager, StorefrontPublic { - // Event to be emitted when this storefront is destroyed. - access(all) event ResourceDestroyed( - storefrontResourceID: UInt64 = self.uuid - ) - - /// The dictionary of Listing uuids to Listing resources. - access(self) var listings: @{UInt64: Listing} - - /// insert - /// Create and publish a Listing for an NFT. - /// - access(CreateListing) fun createListing( - nftProviderCapability: Capability, - nftType: Type, - nftID: UInt64, - salePaymentVaultType: Type, - saleCuts: [SaleCut] - ): UInt64 { - let listing <- create Listing( - nftProviderCapability: nftProviderCapability, - nftType: nftType, - nftID: nftID, - salePaymentVaultType: salePaymentVaultType, - saleCuts: saleCuts, - storefrontID: self.uuid - ) - - let listingResourceID = listing.uuid - let listingPrice = listing.getDetails().salePrice - - // Add the new listing to the dictionary. - let oldListing <- self.listings[listingResourceID] <- listing - // Note that oldListing will always be nil, but we have to handle it. - - Burner.burn(<-oldListing) - - emit ListingAvailable( - storefrontAddress: self.owner?.address!, - listingResourceID: listingResourceID, - nftType: nftType, - nftID: nftID, - ftVaultType: salePaymentVaultType, - price: listingPrice - ) - - return listingResourceID - } - - - /// removeListing - /// Remove a Listing that has not yet been purchased from the collection and destroy it. - /// - access(RemoveListing) fun removeListing(listingResourceID: UInt64) { - let listing <- self.listings.remove(key: listingResourceID) - ?? panic("missing Listing") - - // This will emit a ListingCompleted event. - Burner.burn(<-listing) - } - - /// getListingIDs - /// Returns an array of the Listing resource IDs that are in the collection - /// - access(all) view fun getListingIDs(): [UInt64] { - return self.listings.keys - } - - /// borrowSaleItem - /// Returns a read-only view of the SaleItem for the given listingID if it is contained by this collection. - /// - access(all) view fun borrowListing(listingResourceID: UInt64): &{ListingPublic}? { - if self.listings[listingResourceID] != nil { - return &self.listings[listingResourceID] as &{ListingPublic}? - } else { - return nil - } - } - - /// cleanup - /// Remove an listing *if* it has been purchased. - /// Anyone can call, but at present it only benefits the account owner to do so. - /// Kind purchasers can however call it if they like. - /// - access(all) fun cleanup(listingResourceID: UInt64) { - pre { - self.listings[listingResourceID] != nil: "could not find listing with given id" - } - - let listing <- self.listings.remove(key: listingResourceID)! - assert(listing.getDetails().purchased == true, message: "listing is not purchased, only admin can remove") - Burner.burn(<-listing) - } - - /// constructor - /// - init () { - self.listings <- {} - - // Let event consumers know that this storefront exists - emit StorefrontInitialized(storefrontResourceID: self.uuid) - } - } - - /// createStorefront - /// Make creating a Storefront publicly accessible. - /// - access(all) fun createStorefront(): @Storefront { - return <-create Storefront() - } - - init () { - self.StorefrontStoragePath = /storage/NFTStorefront - self.StorefrontPublicPath = /public/NFTStorefront - } -} \ No newline at end of file diff --git a/cadence/tests/Recipe_test.cdc b/cadence/tests/Recipe_test.cdc deleted file mode 100644 index 49c0bec..0000000 --- a/cadence/tests/Recipe_test.cdc +++ /dev/null @@ -1,18 +0,0 @@ -import Test -import "test_helpers.cdc" - -access(all) -fun setup() { - let err = Test.deployContract( - name: "NFTStorefront", - path: "../contracts/Recipe.cdc", - arguments: [], - ) - - Test.expect(err, Test.beNil()) -} - -access(all) fun testExample() { - let array = [1, 2, 3] - Test.expect(array.length, Test.equal(3)) -} diff --git a/cadence/transactions/create_storefront.cdc b/cadence/transactions/create_storefront.cdc index 5ad1f62..1f66c3b 100644 --- a/cadence/transactions/create_storefront.cdc +++ b/cadence/transactions/create_storefront.cdc @@ -1,12 +1,12 @@ -import "NFTStorefront" +import "NFTStorefrontV2" -// This transaction sets up account 0x01 for the marketplace tutorial +// This transaction sets up the emulator account for the marketplace tutorial // by publishing a Vault reference and creating an empty NFT Collection. transaction { prepare(acct: auth(Storage) &Account) { // Save the newly created storefront resource into account storage - acct.storage.save(<-NFTStorefront.createStorefront(), to: NFTStorefront.StorefrontStoragePath) + acct.storage.save(<-NFTStorefrontV2.createStorefront(), to: NFTStorefrontV2.StorefrontStoragePath) log("Storefront created") } diff --git a/flow.json b/flow.json index a8782d5..476652e 100644 --- a/flow.json +++ b/flow.json @@ -36,6 +36,14 @@ "testnet": "631e88ae7f1d7c20" } }, + "NFTStorefrontV2": { + "source": "mainnet://4eb8a10cb9f87357.NFTStorefrontV2", + "hash": "f455b556f350f20b71de45ed71da42f0c60ab4d003e4e164e9f6e9d35e3c4c4b", + "aliases": { + "mainnet": "4eb8a10cb9f87357", + "testnet": "2d55b98eb200daef" + } + }, "NonFungibleToken": { "source": "mainnet://1d7e57aa55817448.NonFungibleToken", "hash": "b63f10e00d1a814492822652dac7c0574428a200e4c26cb3c832c4829e2778f0", @@ -73,7 +81,8 @@ "deployments": { "emulator": { "emulator-account": [ - "NFTStorefront" + "NFTStorefront", + "NFTStorefrontV2" ] } } From 385b32d51ff27411ac3e79c6d6ccdfbcd5fbb968 Mon Sep 17 00:00:00 2001 From: Lea Lobanov Date: Sat, 14 Dec 2024 00:47:08 +0400 Subject: [PATCH 8/9] Storefront v2 --- flow.json | 8 -------- 1 file changed, 8 deletions(-) diff --git a/flow.json b/flow.json index 476652e..856f72a 100644 --- a/flow.json +++ b/flow.json @@ -1,12 +1,5 @@ { "contracts": { - "NFTStorefront": { - "source": "cadence/contracts/Recipe.cdc", - "aliases": { - "emulator": "f8d6e0586b0a20c7", - "testing": "0000000000000007" - } - } }, "dependencies": { "Burner": { @@ -81,7 +74,6 @@ "deployments": { "emulator": { "emulator-account": [ - "NFTStorefront", "NFTStorefrontV2" ] } From 99ef3defbe979cba9beab28d6ba8859c3d396f3d Mon Sep 17 00:00:00 2001 From: Lea Lobanov Date: Sat, 14 Dec 2024 00:47:15 +0400 Subject: [PATCH 9/9] Storefront v2 --- flow.json | 157 ++++++++++++++++++++++++++---------------------------- 1 file changed, 77 insertions(+), 80 deletions(-) diff --git a/flow.json b/flow.json index 856f72a..7a88364 100644 --- a/flow.json +++ b/flow.json @@ -1,81 +1,78 @@ { - "contracts": { - }, - "dependencies": { - "Burner": { - "source": "mainnet://f233dcee88fe0abe.Burner", - "hash": "71af18e227984cd434a3ad00bb2f3618b76482842bae920ee55662c37c8bf331", - "aliases": { - "emulator": "f8d6e0586b0a20c7", - "mainnet": "f233dcee88fe0abe", - "testnet": "9a0766d93b6608b7" - } - }, - "FungibleToken": { - "source": "mainnet://f233dcee88fe0abe.FungibleToken", - "hash": "050328d01c6cde307fbe14960632666848d9b7ea4fef03ca8c0bbfb0f2884068", - "aliases": { - "emulator": "ee82856bf20e2aa6", - "mainnet": "f233dcee88fe0abe", - "testnet": "9a0766d93b6608b7" - } - }, - "MetadataViews": { - "source": "mainnet://1d7e57aa55817448.MetadataViews", - "hash": "10a239cc26e825077de6c8b424409ae173e78e8391df62750b6ba19ffd048f51", - "aliases": { - "emulator": "f8d6e0586b0a20c7", - "mainnet": "1d7e57aa55817448", - "testnet": "631e88ae7f1d7c20" - } - }, - "NFTStorefrontV2": { - "source": "mainnet://4eb8a10cb9f87357.NFTStorefrontV2", - "hash": "f455b556f350f20b71de45ed71da42f0c60ab4d003e4e164e9f6e9d35e3c4c4b", - "aliases": { - "mainnet": "4eb8a10cb9f87357", - "testnet": "2d55b98eb200daef" - } - }, - "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" - } - } - }, - "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" - }, - "accounts": { - "emulator-account": { - "address": "f8d6e0586b0a20c7", - "key": { - "type": "file", - "location": "emulator-account.pkey" - } - } - }, - "deployments": { - "emulator": { - "emulator-account": [ - "NFTStorefrontV2" - ] - } - } -} \ No newline at end of file + "contracts": {}, + "dependencies": { + "Burner": { + "source": "mainnet://f233dcee88fe0abe.Burner", + "hash": "71af18e227984cd434a3ad00bb2f3618b76482842bae920ee55662c37c8bf331", + "aliases": { + "emulator": "f8d6e0586b0a20c7", + "mainnet": "f233dcee88fe0abe", + "testnet": "9a0766d93b6608b7" + } + }, + "FungibleToken": { + "source": "mainnet://f233dcee88fe0abe.FungibleToken", + "hash": "050328d01c6cde307fbe14960632666848d9b7ea4fef03ca8c0bbfb0f2884068", + "aliases": { + "emulator": "ee82856bf20e2aa6", + "mainnet": "f233dcee88fe0abe", + "testnet": "9a0766d93b6608b7" + } + }, + "MetadataViews": { + "source": "mainnet://1d7e57aa55817448.MetadataViews", + "hash": "10a239cc26e825077de6c8b424409ae173e78e8391df62750b6ba19ffd048f51", + "aliases": { + "emulator": "f8d6e0586b0a20c7", + "mainnet": "1d7e57aa55817448", + "testnet": "631e88ae7f1d7c20" + } + }, + "NFTStorefrontV2": { + "source": "mainnet://4eb8a10cb9f87357.NFTStorefrontV2", + "hash": "f455b556f350f20b71de45ed71da42f0c60ab4d003e4e164e9f6e9d35e3c4c4b", + "aliases": { + "mainnet": "4eb8a10cb9f87357", + "testnet": "2d55b98eb200daef" + } + }, + "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" + } + } + }, + "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" + }, + "accounts": { + "emulator-account": { + "address": "f8d6e0586b0a20c7", + "key": { + "type": "file", + "location": "emulator-account.pkey" + } + } + }, + "deployments": { + "emulator": { + "emulator-account": ["NFTStorefrontV2"] + } + } +}