module example::nft_collection {
use iota::package::{Self, Publisher};
use iota::display::{Self, Display};
use iota::object::{Self, UID, ID};
use iota::transfer;
use iota::tx_context::TxContext;
use std::string::String;
/// One-Time Witness
public struct NFT_COLLECTION has drop {}
public struct NFT has key, store {
id: UID,
name: String,
description: String,
image_url: String,
collection_id: ID,
}
public struct Collection has key {
id: UID,
name: String,
publisher: ID,
}
public struct MintCap has key, store {
id: UID,
collection_id: ID,
}
fun init(otw: NFT_COLLECTION, ctx: &mut TxContext) {
// Claim Publisher
let publisher = package::claim(otw, ctx);
let publisher_id = object::id(&publisher);
// Create Display for NFT type
let mut display = display::new<NFT>(&publisher, ctx);
display::add(&mut display, b"name", b"{name}");
display::add(&mut display, b"description", b"{description}");
display::add(&mut display, b"image_url", b"{image_url}");
display::update_version(&mut display);
// Create collection
let collection = Collection {
id: object::new(ctx),
name: string::utf8(b"My NFT Collection"),
publisher: publisher_id,
};
let collection_id = object::id(&collection);
// Create mint capability
let mint_cap = MintCap {
id: object::new(ctx),
collection_id,
};
// Transfer objects
transfer::public_transfer(publisher, ctx.sender());
transfer::public_transfer(display, ctx.sender());
transfer::share_object(collection);
transfer::transfer(mint_cap, ctx.sender());
}
public fun mint(
cap: &MintCap,
collection: &Collection,
name: String,
description: String,
image_url: String,
recipient: address,
ctx: &mut TxContext
) {
assert!(object::id(collection) == cap.collection_id, 0);
let nft = NFT {
id: object::new(ctx),
name,
description,
image_url,
collection_id: cap.collection_id,
};
transfer::public_transfer(nft, recipient);
}
}