Smart Contract
PackNFT
A.0b2a3299cc857e29.PackNFT
1import Crypto
2import NonFungibleToken from 0x1d7e57aa55817448
3import FungibleToken from 0xf233dcee88fe0abe
4import IPackNFT from 0x18ddf0823a55a0ee
5import MetadataViews from 0x1d7e57aa55817448
6import ViewResolver from 0x1d7e57aa55817448
7
8/// Contract that defines Pack NFTs.
9///
10access(all) contract PackNFT: NonFungibleToken, IPackNFT {
11
12 access(all) var totalSupply: UInt64
13 access(all) let version: String
14 access(all) let CollectionStoragePath: StoragePath
15 access(all) let CollectionPublicPath: PublicPath
16 access(all) let CollectionIPackNFTPublicPath: PublicPath
17 access(all) let OperatorStoragePath: StoragePath
18
19 /// Dictionary that stores Pack resources in the contract state (i.e., Pack NFT representations to keep track of states).
20 ///
21 access(contract) let packs: @{UInt64: Pack}
22
23 access(all) event RevealRequest(id: UInt64, openRequest: Bool)
24 access(all) event OpenRequest(id: UInt64)
25 access(all) event Revealed(id: UInt64, salt: [UInt8], nfts: String)
26 access(all) event Opened(id: UInt64)
27 access(all) event Minted(id: UInt64, hash: [UInt8], distId: UInt64)
28 access(all) event Burned(id: UInt64)
29 access(all) event ContractInitialized()
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 ///
156 access(all) let issuer: Address
157
158 /// Event emitted when a NFT is destroyed (replaces Burned event before Cadence 1.0 update)
159 ///
160 access(all) event ResourceDestroyed(id: UInt64 = self.id)
161
162 /// Executed by calling the Burner contract's burn method (i.e., conforms to the Burnable interface)
163 ///
164 access(contract) fun burnCallback() {
165 PackNFT.totalSupply = PackNFT.totalSupply - 1
166 destroy <- PackNFT.packs.remove(key: self.id) ?? panic("no such pack")
167 }
168
169 /// NFT resource initializer.
170 ///
171 view init(commitHash: String, issuer: Address) {
172 self.id = self.uuid
173 self.hash = commitHash.decodeHex()
174 self.issuer = issuer
175 }
176
177 /// Create an empty Collection for Pinnacle NFTs and return it to the caller
178 ///
179 access(all) fun createEmptyCollection(): @{NonFungibleToken.Collection} {
180 return <- PackNFT.createEmptyCollection(nftType: Type<@NFT>())
181 }
182
183 /// Return the metadata view types available for this NFT.
184 ///
185 access(all) view fun getViews(): [Type] {
186 return [
187 Type<MetadataViews.Display>(),
188 Type<MetadataViews.ExternalURL>(),
189 Type<MetadataViews.Medias>(),
190 Type<MetadataViews.NFTCollectionData>(),
191 Type<MetadataViews.NFTCollectionDisplay>(),
192 Type<MetadataViews.Royalties>(),
193 Type<MetadataViews.Serial>()
194 ]
195 }
196
197 /// Resolve this NFT's metadata views.
198 ///
199 access(all) view fun resolveView(_ view: Type): AnyStruct? {
200 switch view {
201 case Type<MetadataViews.Display>():
202 return MetadataViews.Display(
203 name: "NBA Top Shot Pack",
204 description: "Reveals official NBA Top Shot Moments when opened",
205 thumbnail: MetadataViews.HTTPFile(url: self.getImage(imageType: "image", format: "jpeg", width: 256))
206 )
207 case Type<MetadataViews.ExternalURL>():
208 return MetadataViews.ExternalURL("https://nbatopshot.com/packnfts/".concat(self.id.toString())) // might have to make a URL that redirects to packs page based on packNFT id -> distribution id
209 case Type<MetadataViews.Medias>():
210 return MetadataViews.Medias(
211 [
212 MetadataViews.Media(
213 file: MetadataViews.HTTPFile(url: self.getImage(imageType: "image", format: "jpeg", width: 512)),
214 mediaType: "image/jpeg"
215 )
216 ]
217 )
218 case Type<MetadataViews.NFTCollectionData>():
219 return MetadataViews.NFTCollectionData(
220 storagePath: PackNFT.CollectionStoragePath,
221 publicPath: PackNFT.CollectionPublicPath,
222 publicCollection: Type<&Collection>(),
223 publicLinkedType: Type<&Collection>(),
224 createEmptyCollectionFunction: (fun (): @{NonFungibleToken.Collection} {
225 return <-PackNFT.createEmptyCollection(nftType: Type<@NFT>())
226 })
227 )
228 case Type<MetadataViews.NFTCollectionDisplay>():
229 let bannerImage = MetadataViews.Media(
230 file: MetadataViews.HTTPFile(
231 url: "https://nbatopshot.com/static/img/top-shot-logo-horizontal-white.svg"
232 ),
233 mediaType: "image/svg+xml"
234 )
235 let squareImage = MetadataViews.Media(
236 file: MetadataViews.HTTPFile(
237 url: "https://nbatopshot.com/static/img/og/og.png"
238 ),
239 mediaType: "image/png"
240 )
241 return MetadataViews.NFTCollectionDisplay(
242 name: "NBA-Top-Shot-Packs",
243 description: "NBA Top Shot is your chance to own, sell, and trade official digital collectibles of the NBA and WNBA's greatest plays and players",
244 externalURL: MetadataViews.ExternalURL("https://nbatopshot.com/"),
245 squareImage: squareImage,
246 bannerImage: bannerImage,
247 socials: {
248 "twitter": MetadataViews.ExternalURL("https://twitter.com/nbatopshot"),
249 "discord": MetadataViews.ExternalURL("https://discord.com/invite/nbatopshot"),
250 "instagram": MetadataViews.ExternalURL("https://www.instagram.com/nbatopshot")
251 }
252 )
253 case Type<MetadataViews.Royalties>():
254 let royaltyReceiver: Capability<&{FungibleToken.Receiver}> =
255 getAccount(0xfaf0cc52c6e3acaf).capabilities.get<&{FungibleToken.Receiver}>(MetadataViews.getRoyaltyReceiverPublicPath())
256 return MetadataViews.Royalties(
257 [
258 MetadataViews.Royalty(
259 receiver: royaltyReceiver,
260 cut: 0.05,
261 description: "NBA Top Shot marketplace royalty"
262 )
263 ]
264 )
265 case Type<MetadataViews.Serial>():
266 return MetadataViews.Serial(self.id)
267 }
268 return nil
269 }
270
271 /// Return an asset path.
272 ///
273 access(all) view fun assetPath(): String {
274 // this path is normative -> it does not yet have pack related assets here
275 return "https://media.nbatopshot.com/packnfts/".concat(self.id.toString()).concat("/media/")
276 }
277
278 /// Return an image path.
279 ///
280 access(all) view fun getImage(imageType: String, format: String, width: Int): String {
281 return self.assetPath().concat(imageType).concat("?format=").concat(format).concat("&width=").concat(width.toString())
282 }
283 }
284
285 /// Resource that defines a Collection of Pack NFTs.
286 ///
287 access(all) resource Collection: NonFungibleToken.Collection, IPackNFT.IPackNFTCollectionPublic, ViewResolver.ResolverCollection {
288 /// Dictionary of NFT conforming tokens.
289 /// NFT is a resource type with a UInt64 ID field.
290 ///
291 access(all) var ownedNFTs: @{UInt64: {NonFungibleToken.NFT}}
292
293 /// Collection resource initializer,
294 ///
295 view init() {
296 self.ownedNFTs <- {}
297 }
298
299 /// Remove an NFT from the collection and moves it to the caller.
300 ///
301 access(NonFungibleToken.Withdraw) fun withdraw(withdrawID: UInt64): @{NonFungibleToken.NFT} {
302 let token <- self.ownedNFTs.remove(key: withdrawID) ?? panic("missing NFT")
303
304 // Withdrawn event emitted from NonFungibleToken contract interface.
305 emit Withdraw(id: token.id, from: self.owner?.address) // TODO: Consider removing
306 return <- token
307 }
308
309 /// Deposit an NFT into this Collection.
310 ///
311 access(all) fun deposit(token: @{NonFungibleToken.NFT}) {
312 let token <- token as! @NFT
313 let id: UInt64 = token.id
314 // Add the new token to the dictionary which removes the old one.
315 let oldToken <- self.ownedNFTs[id] <- token
316
317 // Deposited event emitted from NonFungibleToken contract interface.
318 emit Deposit(id: id, to: self.owner?.address) // TODO: Consider removing
319 destroy oldToken
320 }
321
322 /// Emit a RevealRequest event to signal a Sealed Pack NFT should be revealed.
323 ///
324 access(NonFungibleToken.Update) fun emitRevealRequestEvent(id: UInt64, openRequest: Bool) {
325 pre {
326 self.borrowNFT(id) != nil: "NFT with provided ID must exist in the collection"
327 PackNFT.borrowPackRepresentation(id: id)!.status.rawValue == Status.Sealed.rawValue: "Pack status must be Sealed for reveal request"
328 }
329 emit RevealRequest(id: id, openRequest: openRequest)
330 }
331
332 /// Emit an OpenRequest event to signal a Revealed Pack NFT should be opened.
333 ///
334 access(NonFungibleToken.Update) fun emitOpenRequestEvent(id: UInt64) {
335 pre {
336 self.borrowNFT(id) != nil: "NFT with provided ID must exist in the collection"
337 PackNFT.borrowPackRepresentation(id: id)!.status.rawValue == Status.Revealed.rawValue: "Pack status must be Revealed for open request"
338 }
339 emit OpenRequest(id: id)
340 }
341
342 /// Return an array of the IDs that are in the collection.
343 ///
344 access(all) view fun getIDs(): [UInt64] {
345 return self.ownedNFTs.keys
346 }
347
348 /// Return the amount of NFTs stored in the collection.
349 ///
350 access(all) view fun getLength(): Int {
351 return self.ownedNFTs.length
352 }
353
354 /// Return a list of NFT types that this receiver accepts.
355 ///
356 access(all) view fun getSupportedNFTTypes(): {Type: Bool} {
357 let supportedTypes: {Type: Bool} = {}
358 supportedTypes[Type<@NFT>()] = true
359 return supportedTypes
360 }
361
362 /// Return whether or not the given type is accepted by the collection.
363 ///
364 access(all) view fun isSupportedNFTType(type: Type): Bool {
365 if type == Type<@NFT>() {
366 return true
367 }
368 return false
369 }
370
371 /// Return a reference to an NFT in the Collection.
372 ///
373 access(all) view fun borrowNFT(_ id: UInt64): &{NonFungibleToken.NFT}? {
374 return &self.ownedNFTs[id]
375 }
376
377 /// Return a reference to a ViewResolver for an NFT in the Collection.
378 ///
379 access(all) view fun borrowViewResolver(id: UInt64): &{ViewResolver.Resolver}? {
380 if let nft = &self.ownedNFTs[id] as &{NonFungibleToken.NFT}? {
381 return nft as &{ViewResolver.Resolver}
382 }
383 return nil
384 }
385
386 /// Create an empty Collection of the same type and returns it to the caller.
387 ///
388 access(all) fun createEmptyCollection(): @{NonFungibleToken.Collection} {
389 return <-PackNFT.createEmptyCollection(nftType: Type<@NFT>())
390 }
391 }
392
393 access(all) fun publicReveal(id: UInt64, nfts: [{IPackNFT.Collectible}], salt: String) {
394 let p = PackNFT.borrowPackRepresentation(id: id) ?? panic ("No such pack")
395 p.reveal(id: id, nfts: nfts, salt: salt)
396 }
397
398 /// Return a reference to a Pack resource stored in the contract state.
399 ///
400 access(all) view fun borrowPackRepresentation(id: UInt64): &Pack? {
401 return (&self.packs[id] as &Pack?)!
402 }
403
404 /// Create an empty Collection for Pack NFTs and return it to the caller.
405 ///
406 access(all) fun createEmptyCollection(nftType: Type): @{NonFungibleToken.Collection} {
407 if nftType != Type<@NFT>() {
408 panic("NFT type is not supported")
409 }
410 return <- create Collection()
411 }
412
413 /// Return the metadata views implemented by this contract.
414 ///
415 /// @return An array of Types defining the implemented views. This value will be used by
416 /// developers to know which parameter to pass to the resolveView() method.
417 ///
418 access(all) view fun getContractViews(resourceType: Type?): [Type] {
419 return [
420 Type<MetadataViews.NFTCollectionData>()
421 ]
422 }
423
424 /// Resolve a metadata view for this contract.
425 ///
426 /// @param view: The Type of the desired view.
427 /// @return A structure representing the requested view.
428 ///
429 access(all) view fun resolveContractView(resourceType: Type?, viewType: Type): AnyStruct? {
430 switch viewType {
431 case Type<MetadataViews.NFTCollectionData>():
432 let collectionData = MetadataViews.NFTCollectionData(
433 storagePath: PackNFT.CollectionStoragePath,
434 publicPath: PackNFT.CollectionPublicPath,
435 publicCollection: Type<&Collection>(),
436 publicLinkedType: Type<&Collection>(),
437 createEmptyCollectionFunction: (fun(): @{NonFungibleToken.Collection} {
438 return <-PackNFT.createEmptyCollection(nftType: Type<@NFT>())
439 })
440 )
441 return collectionData
442 }
443 return nil
444 }
445
446 /// PackNFT contract initializer.
447 ///
448 init(
449 CollectionStoragePath: StoragePath,
450 CollectionPublicPath: PublicPath,
451 CollectionIPackNFTPublicPath: PublicPath,
452 OperatorStoragePath: StoragePath,
453 version: String
454 ) {
455 self.totalSupply = 0
456 self.packs <- {}
457 self.CollectionStoragePath = CollectionStoragePath
458 self.CollectionPublicPath = CollectionPublicPath
459 self.CollectionIPackNFTPublicPath = CollectionIPackNFTPublicPath
460 self.OperatorStoragePath = OperatorStoragePath
461 self.version = version
462
463 // Create a collection to receive Pack NFTs and publish public receiver capabilities.
464 self.account.storage.save(<- create Collection(), to: self.CollectionStoragePath)
465 self.account.capabilities.publish(
466 self.account.capabilities.storage.issue<&{NonFungibleToken.CollectionPublic}>(self.CollectionStoragePath),
467 at: self.CollectionPublicPath
468 )
469 self.account.capabilities.publish(
470 self.account.capabilities.storage.issue<&{IPackNFT.IPackNFTCollectionPublic}>(self.CollectionStoragePath),
471 at: self.CollectionIPackNFTPublicPath
472 )
473
474 // Create a Pack NFT operator to share mint capability with proxy.
475 self.account.storage.save(<- create PackNFTOperator(), to: self.OperatorStoragePath)
476 self.account.capabilities.storage.issue<&{IPackNFT.IOperator}>(self.OperatorStoragePath)
477 }
478
479}