Smart Contract
PackNFT
A.edf9df96c92f4595.PackNFT
1import Crypto
2import NonFungibleToken from 0x1d7e57aa55817448
3import IPackNFT from 0x18ddf0823a55a0ee
4import MetadataViews from 0x1d7e57aa55817448
5import ViewResolver from 0x1d7e57aa55817448
6
7/// Contract that defines Pack NFTs.
8///
9access(all) contract PackNFT: NonFungibleToken, IPackNFT {
10
11 access(all) var totalSupply: UInt64
12 access(all) let version: String
13 access(all) let CollectionStoragePath: StoragePath
14 access(all) let CollectionPublicPath: PublicPath
15 access(all) let CollectionIPackNFTPublicPath: PublicPath
16 access(all) let OperatorStoragePath: StoragePath
17
18 /// Dictionary that stores Pack resources in the contract state (i.e., Pack NFT representations to keep track of states).
19 ///
20 access(contract) let packs: @{UInt64: Pack}
21
22 access(all) event RevealRequest(id: UInt64, openRequest: Bool)
23 access(all) event OpenRequest(id: UInt64)
24 access(all) event Revealed(id: UInt64, salt: [UInt8], nfts: String)
25 access(all) event Opened(id: UInt64)
26 access(all) event Minted(id: UInt64, hash: [UInt8], distId: UInt64)
27 access(all) event ContractInitialized()
28
29 // TODO: Consider removing 'Withdraw' and 'Deposit' events now that similar 'Withdrawn' and 'Deposited' events are emitted in NonFungibleToken contract interface
30 access(all) event Withdraw(id: UInt64, from: Address?)
31 access(all) event Deposit(id: UInt64, to: Address?)
32
33 /// Enum that defines the status of a Pack resource.
34 ///
35 access(all) enum Status: UInt8 {
36 access(all) case Sealed
37 access(all) case Revealed
38 access(all) case Opened
39 }
40
41 /// Resource that defines a Pack NFT Operator, responsible for:
42 /// - Minting Pack NFTs and the corresponding Pack resources that keep track of states,
43 /// - Revealing sealed Pack resources, and
44 /// - opening revealed Pack resources.
45 ///
46 access(all) resource PackNFTOperator: IPackNFT.IOperator {
47
48 /// Mint a new Pack NFT resource and corresponding Pack resource; store the Pack resource in the contract's packs dictionary
49 /// and return the Pack NFT resource to the caller.
50 ///
51 access(IPackNFT.Operate) fun mint(distId: UInt64, commitHash: String, issuer: Address): @{IPackNFT.NFT} {
52 let nft <- create NFT(commitHash: commitHash, issuer: issuer)
53 PackNFT.totalSupply = PackNFT.totalSupply + 1
54 let p <- create Pack(commitHash: commitHash, issuer: issuer)
55 PackNFT.packs[nft.id] <-! p
56 emit Minted(id: nft.id, hash: commitHash.decodeHex(), distId: distId)
57 return <- nft
58 }
59
60 /// Reveal a Sealed Pack resource.
61 ///
62 access(IPackNFT.Operate) fun reveal(id: UInt64, nfts: [{IPackNFT.Collectible}], salt: String) {
63 let p <- PackNFT.packs.remove(key: id) ?? panic("no such pack")
64 p.reveal(id: id, nfts: nfts, salt: salt)
65 PackNFT.packs[id] <-! p
66 }
67
68 /// Open a Revealed Pack NFT resource.
69 ///
70 access(IPackNFT.Operate) fun open(id: UInt64, nfts: [{IPackNFT.Collectible}]) {
71 let p <- PackNFT.packs.remove(key: id) ?? panic("no such pack")
72 p.open(id: id, nfts: nfts)
73 PackNFT.packs[id] <-! p
74 }
75
76 /// PackNFTOperator resource initializer.
77 ///
78 view init() {}
79 }
80
81 /// Resource that defines a Pack NFT.
82 ///
83 access(all) resource Pack {
84 access(all) let hash: [UInt8]
85 access(all) let issuer: Address
86 access(all) var status: Status
87 access(all) var salt: [UInt8]?
88
89 access(all) view fun verify(nftString: String): Bool {
90 assert(self.status != Status.Sealed, message: "Pack not revealed yet")
91 var hashString = String.encodeHex(self.salt!)
92 hashString = hashString.concat(",").concat(nftString)
93 let hash = HashAlgorithm.SHA2_256.hash(hashString.utf8)
94 assert(String.encodeHex(self.hash) == String.encodeHex(hash), message: "CommitHash was not verified")
95 return true
96 }
97
98 access(self) fun _verify(nfts: [{IPackNFT.Collectible}], salt: String, commitHash: String): String {
99 var hashString = salt
100 var nftString = nfts[0].hashString()
101 var i = 1
102 while i < nfts.length {
103 let s = nfts[i].hashString()
104 nftString = nftString.concat(",").concat(s)
105 i = i + 1
106 }
107 hashString = hashString.concat(",").concat(nftString)
108 let hash = HashAlgorithm.SHA2_256.hash(hashString.utf8)
109 assert(String.encodeHex(self.hash) == String.encodeHex(hash), message: "CommitHash was not verified")
110 return nftString
111 }
112
113 access(contract) fun reveal(id: UInt64, nfts: [{IPackNFT.Collectible}], salt: String) {
114 assert(self.status == Status.Sealed, message: "Pack status is not Sealed")
115 let v = self._verify(nfts: nfts, salt: salt, commitHash: String.encodeHex(self.hash))
116 self.salt = salt.decodeHex()
117 self.status = Status.Revealed
118 emit Revealed(id: id, salt: salt.decodeHex(), nfts: v)
119 }
120
121 access(contract) fun open(id: UInt64, nfts: [{IPackNFT.Collectible}]) {
122 assert(self.status == Status.Revealed, message: "Pack status is not Revealed")
123 self._verify(nfts: nfts, salt: String.encodeHex(self.salt!), commitHash: String.encodeHex(self.hash))
124 self.status = Status.Opened
125 emit Opened(id: id)
126 }
127
128 /// Pack resource initializer.
129 ///
130 view init(commitHash: String, issuer: Address) {
131 // Set the hash and issuer from the arguments.
132 self.hash = commitHash.decodeHex()
133 self.issuer = issuer
134
135 // Initial status is Sealed.
136 self.status = Status.Sealed
137
138 // Salt is nil until reveal.
139 self.salt = nil
140 }
141 }
142
143 /// Resource that defines a Pack NFT.
144 ///
145 access(all) resource NFT: NonFungibleToken.NFT, IPackNFT.NFT, IPackNFT.IPackNFTToken, IPackNFT.IPackNFTOwnerOperator, ViewResolver.Resolver {
146 /// This NFT's unique ID.
147 ///
148 access(all) let id: UInt64
149
150 /// This NFT's commit hash, used to verify the IDs of the NFTs in the Pack.
151 ///
152 access(all) let hash: [UInt8]
153
154 /// This NFT's issuer.
155 access(all) let issuer: Address
156
157 /// Event emitted when a NFT is destroyed (replaces Burned event before Cadence 1.0 update)
158 ///
159 access(all) event ResourceDestroyed(id: UInt64 = self.id)
160
161 /// Executed by calling the Burner contract's burn method (i.e., conforms to the Burnable interface)
162 ///
163 access(contract) fun burnCallback() {
164 PackNFT.totalSupply = PackNFT.totalSupply - 1
165 destroy <- PackNFT.packs.remove(key: self.id) ?? panic("no such pack")
166 }
167
168 /// NFT resource initializer.
169 ///
170 view init(commitHash: String, issuer: Address) {
171 self.id = self.uuid
172 self.hash = commitHash.decodeHex()
173 self.issuer = issuer
174 }
175
176 /// Create an empty Collection for Pinnacle NFTs and return it to the caller
177 ///
178 access(all) fun createEmptyCollection(): @{NonFungibleToken.Collection} {
179 return <- PackNFT.createEmptyCollection(nftType: Type<@NFT>())
180 }
181
182 /// Return the metadata view types available for this NFT.
183 ///
184 access(all) view fun getViews(): [Type] {
185 return []
186 }
187
188 /// Resolve this NFT's metadata views.
189 //// TODO: Implement metadata views as needed for the NFT the PackNFT is intended to contain
190 ///
191 access(all) view fun resolveView(_ view: Type): AnyStruct? {
192 return nil
193 }
194 }
195
196 /// Resource that defines a Collection of Pack NFTs.
197 ///
198 access(all) resource Collection: NonFungibleToken.Collection, IPackNFT.IPackNFTCollectionPublic, ViewResolver.ResolverCollection {
199 /// Dictionary of NFT conforming tokens.
200 /// NFT is a resource type with a UInt64 ID field.
201 ///
202 access(all) var ownedNFTs: @{UInt64: {NonFungibleToken.NFT}}
203
204 /// Collection resource initializer.
205 ///
206 view init() {
207 self.ownedNFTs <- {}
208 }
209
210 /// Remove an NFT from the collection and moves it to the caller.
211 ///
212 access(NonFungibleToken.Withdraw) fun withdraw(withdrawID: UInt64): @{NonFungibleToken.NFT} {
213 let token <- self.ownedNFTs.remove(key: withdrawID) ?? panic("missing NFT")
214
215 // Withdrawn event emitted from NonFungibleToken contract interface.
216 emit Withdraw(id: token.id, from: self.owner?.address) // TODO: Consider removing
217 return <- token
218 }
219
220 /// Deposit an NFT into this Collection.
221 ///
222 access(all) fun deposit(token: @{NonFungibleToken.NFT}) {
223 let token <- token as! @NFT
224 let id: UInt64 = token.id
225 // Add the new token to the dictionary which removes the old one.
226 let oldToken <- self.ownedNFTs[id] <- token
227
228 // Deposited event emitted from NonFungibleToken contract interface.
229 emit Deposit(id: id, to: self.owner?.address) // TODO: Consider removing
230 destroy oldToken
231 }
232
233 /// Emit a RevealRequest event to signal a Sealed Pack NFT should be revealed.
234 ///
235 access(NonFungibleToken.Update) fun emitRevealRequestEvent(id: UInt64, openRequest: Bool) {
236 pre {
237 self.borrowNFT(id) != nil: "NFT with provided ID must exist in the collection"
238 PackNFT.borrowPackRepresentation(id: id)!.status.rawValue == Status.Sealed.rawValue: "Pack status must be Sealed for reveal request"
239 }
240 emit RevealRequest(id: id, openRequest: openRequest)
241 }
242
243 /// Emit an OpenRequest event to signal a Revealed Pack NFT should be opened.
244 ///
245 access(NonFungibleToken.Update) fun emitOpenRequestEvent(id: UInt64) {
246 pre {
247 self.borrowNFT(id) != nil: "NFT with provided ID must exist in the collection"
248 PackNFT.borrowPackRepresentation(id: id)!.status.rawValue == Status.Revealed.rawValue: "Pack status must be Revealed for open request"
249 }
250 emit OpenRequest(id: id)
251 }
252
253 /// Return an array of the IDs that are in the collection.
254 ///
255 access(all) view fun getIDs(): [UInt64] {
256 return self.ownedNFTs.keys
257 }
258
259 /// Return the amount of NFTs stored in the collection.
260 ///
261 access(all) view fun getLength(): Int {
262 return self.ownedNFTs.length
263 }
264
265 /// Return a list of NFT types that this receiver accepts.
266 ///
267 access(all) view fun getSupportedNFTTypes(): {Type: Bool} {
268 let supportedTypes: {Type: Bool} = {}
269 supportedTypes[Type<@NFT>()] = true
270 return supportedTypes
271 }
272
273 /// Return whether or not the given type is accepted by the collection.
274 ///
275 access(all) view fun isSupportedNFTType(type: Type): Bool {
276 if type == Type<@NFT>() {
277 return true
278 }
279 return false
280 }
281
282 /// Return a reference to an NFT in the Collection.
283 ///
284 access(all) view fun borrowNFT(_ id: UInt64): &{NonFungibleToken.NFT}? {
285 return &self.ownedNFTs[id]
286 }
287
288 /// Return a reference to a ViewResolver for an NFT in the Collection.
289 ///
290 access(all) view fun borrowViewResolver(id: UInt64): &{ViewResolver.Resolver}? {
291 if let nft = &self.ownedNFTs[id] as &{NonFungibleToken.NFT}? {
292 return nft as &{ViewResolver.Resolver}
293 }
294 return nil
295 }
296
297 /// Create an empty Collection of the same type and returns it to the caller.
298 ///
299 access(all) fun createEmptyCollection(): @{NonFungibleToken.Collection} {
300 return <-PackNFT.createEmptyCollection(nftType: Type<@NFT>())
301 }
302 }
303
304 /// Reveal a Sealed Pack NFT.
305 ///
306 access(all) fun publicReveal(id: UInt64, nfts: [{IPackNFT.Collectible}], salt: String) {
307 let p = PackNFT.borrowPackRepresentation(id: id) ?? panic ("No such pack")
308 p.reveal(id: id, nfts: nfts, salt: salt)
309 }
310
311 /// Return a reference to a Pack resource stored in the contract state.
312 ///
313 access(all) view fun borrowPackRepresentation(id: UInt64): &Pack? {
314 return (&self.packs[id] as &Pack?)!
315 }
316
317 /// Create an empty Collection for Pack NFTs and return it to the caller.
318 ///
319 access(all) fun createEmptyCollection(nftType: Type): @{NonFungibleToken.Collection} {
320 if nftType != Type<@NFT>() {
321 panic("NFT type is not supported")
322 }
323 return <- create Collection()
324 }
325
326 /// Return the metadata views implemented by this contract.
327 ///
328 /// @return An array of Types defining the implemented views. This value will be used by
329 /// developers to know which parameter to pass to the resolveView() method.
330 ///
331 access(all) view fun getContractViews(resourceType: Type?): [Type] {
332 return [
333 Type<MetadataViews.NFTCollectionData>(),
334 Type<MetadataViews.NFTCollectionDisplay>()
335 ]
336 }
337
338 /// Resolve a metadata view for this contract.
339 ///
340 /// @param view: The Type of the desired view.
341 /// @return A structure representing the requested view.
342 ///
343 access(all) view fun resolveContractView(resourceType: Type?, viewType: Type): AnyStruct? {
344 switch viewType {
345 case Type<MetadataViews.NFTCollectionData>():
346 let collectionData = MetadataViews.NFTCollectionData(
347 storagePath: /storage/PinnaclePackNFTCollection,
348 publicPath: /public/PinnaclePackNFTCollectionPub,
349 publicCollection: Type<&Collection>(),
350 publicLinkedType: Type<&Collection>(),
351 createEmptyCollectionFunction: (fun(): @{NonFungibleToken.Collection} {
352 return <-PackNFT.createEmptyCollection(nftType: Type<@NFT>())
353 })
354 )
355 return collectionData
356 case Type<MetadataViews.NFTCollectionDisplay>():
357 let media = MetadataViews.Media(
358 file: MetadataViews.HTTPFile(
359 url: "https://assets.website-files.com/5f6294c0c7a8cdd643b1c820/5f6294c0c7a8cda55cb1c936_Flow_Wordmark.svg"
360 ),
361 mediaType: "image/svg+xml"
362 )
363 return MetadataViews.NFTCollectionDisplay(
364 name: "Pinnacle Pack NFT Collection",
365 description: "",
366 externalURL: MetadataViews.ExternalURL(""),
367 squareImage: media,
368 bannerImage: media,
369 socials: {
370 "twitter": MetadataViews.ExternalURL("https://twitter.com/flow_blockchain")
371 }
372 )
373 }
374 return nil
375 }
376
377 /// PackNFT contract initializer.
378 ///
379 init(
380 CollectionStoragePath: StoragePath,
381 CollectionPublicPath: PublicPath,
382 CollectionIPackNFTPublicPath: PublicPath,
383 OperatorStoragePath: StoragePath,
384 version: String
385 ) {
386 self.totalSupply = 0
387 self.packs <- {}
388 self.CollectionStoragePath = CollectionStoragePath
389 self.CollectionPublicPath = CollectionPublicPath
390 self.CollectionIPackNFTPublicPath = CollectionIPackNFTPublicPath
391 self.OperatorStoragePath = OperatorStoragePath
392 self.version = version
393
394 // Create a collection to receive Pack NFTs and publish public receiver capabilities.
395 self.account.storage.save(<- create Collection(), to: self.CollectionStoragePath)
396 self.account.capabilities.publish(
397 self.account.capabilities.storage.issue<&{NonFungibleToken.CollectionPublic}>(self.CollectionStoragePath),
398 at: self.CollectionPublicPath
399 )
400
401 // Create a Pack NFT operator to share mint capability with proxy.
402 self.account.storage.save(<- create PackNFTOperator(), to: self.OperatorStoragePath)
403 self.account.capabilities.storage.issue<&{IPackNFT.IOperator}>(self.OperatorStoragePath)
404 }
405}
406