Skip to content

Instantly share code, notes, and snippets.

View harry830622's full-sized avatar

Harry Chang harry830622

View GitHub Profile
transaction(metadata: {String: String}) {
// Local variable for the topshot Admin object
let adminRef: &TopShot.Admin
let currPlayID: UInt32
prepare(acct: AuthAccount) {
// borrow a reference to the admin resource
self.currPlayID = TopShot.nextPlayID;
self.adminRef = acct.borrow<&TopShot.Admin>(from: /storage/TopShotAdmin)
transaction {
prepare(acct: AuthAccount) {
// First, check to see if a moment collection already exists
if acct.borrow<&TopShot.Collection>(from: /storage/MomentCollection) == nil {
// create a new TopShot Collection
let collection <- TopShot.createEmptyCollection() as! @TopShot.Collection
// 初始化合約,
// 創造一個全新 collection 作為官方 reserve ,
// 然後也創造一個 Admin 來管裡所有 NBA Top Shot 卡片的狀態,
// 並發出合約已經初始化的 event
init() {
// Initialize contract fields
self.currentSeries = 0
self.playDatas = {}
self.setDatas = {}
self.sets <- {}
// Admin 是管理者的 resource,
// 讓管理者可以創造新的 play、set、series
pub resource Admin {
// 創造新的 play,
// 並發出創造新 play 的 event
pub fun createPlay(metadata: {String: String}): UInt32 {
// Create the new Play
var newPlay = Play(metadata: metadata)
let newID = newPlay.playID
// Increment the ID so that it isn't used again
// Set resource 主要掌控一個系列要加入什麼 play 的卡片,
// 以及要 retire 哪張卡片或是 lock 整個系列,
// 不過當然只能由 Admin 操作這些動作
pub resource Set {
// 每個 set 有一個獨特的 ID 表示
pub let setID: UInt32
// 紀錄這個系列中有哪些 play
access(contract) var plays: [UInt32]
// 紀錄某個 play 是否已經被 retire 了
// 是一個 play ID -> 是否 retire 的 mapping
// 這裡定義一個卡片 collection 可以公開的介面,基本上就是一些非提領或是改動的動作
// 像是將卡片加入帳戶 collection、存取帳戶 collection 中有哪些卡片等等
pub resource interface MomentCollectionPublic {
pub fun deposit(token: @NonFungibleToken.NFT)
pub fun batchDeposit(tokens: @NonFungibleToken.Collection)
pub fun getIDs(): [UInt64]
pub fun borrowNFT(id: UInt64): &NonFungibleToken.NFT
pub fun borrowMoment(id: UInt64): &TopShot.NFT? {
// If the result isn't nil, the id of the returned reference
// should be the same as the argument to the function
// NFT 代表的就是一個 moment,也就是一張卡片
// 它實作官方 NFT contract 裡的 INFT interface
// 以及 MetadataViews.Resolver interface
pub resource NFT: NonFungibleToken.INFT, MetadataViews.Resolver {
// 每一張卡片都有獨特的 ID 代表,
// 並且這也是實作 NonFungibleToken.INFT 必須要有的
pub let id: UInt64
pub let data: MomentData
// 創建 struct 時候的初始化 function
// TopShotMomentMetadataView 就如變數名字所意,
// 儲存所有 moment 相關的 metadata,
// 像是球員名字、球員生日、所屬球隊等等
pub struct TopShotMomentMetadataView {
pub let fullName: String?
pub let firstName: String?
pub let lastName: String?
pub let birthdate: String?
pub let birthplace: String?
// Moment 也就是一張卡片,
pub struct MomentData {
// 是在哪個 set 裡
pub let setID: UInt32
// 是哪個 play
pub let playID: UInt32
// 序號是多少
// Set 就是一個系列,裡面可以包含很多個精彩好球 play
pub struct SetData {
// 每個 Set 有一個獨特的 ID 表示
pub let setID: UInt32
// Set 名字,例如 "Cool Cats" 系列
pub let name: String
// Set 所屬的世代,像現在已經到了世代 3,