Random Mint NFT

In this example, we simplify the Aptogotchi code used in previous tutorials. Instead of letting users choose Aptogotchi parts, we use the randomness API to generate random Aptogotchi parts.


fun create_aptogotchi_internal(user: &signer): address acquires CollectionCapability {
let body = randomness::u8_range(0, BODY_MAX_VALUE_EXCL);
let ear = randomness::u8_range(0, EAR_MAX_VALUE_EXCL);
let face = randomness::u8_range(0, FACE_MAX_VALUE_EXCL);
let uri = utf8(APTOGOTCHI_COLLECTION_URI);
let description = utf8(APTOGOTCHI_COLLECTION_DESCRIPTION);
let user_address = address_of(user);
let token_name = to_string(&user_address);
let parts = AptogotchiParts {
body,
ear,
face,
};
let collection_address = get_collection_address();
let constructor_ref = &token::create(
&get_collection_signer(collection_address),
utf8(APTOGOTCHI_COLLECTION_NAME),
description,
token_name,
option::none(),
uri,
);
let token_signer_ref = &object::generate_signer(constructor_ref);
let aptogotchi_address = address_of(token_signer_ref);
let extend_ref = object::generate_extend_ref(constructor_ref);
let mutator_ref = token::generate_mutator_ref(constructor_ref);
let burn_ref = token::generate_burn_ref(constructor_ref);
let transfer_ref = object::generate_transfer_ref(constructor_ref);
// Initialize and set default Aptogotchi struct values
let aptogotchi = Aptogotchi {
live: true,
health: DEFAULT_BEGINNING_HEALTH,
parts,
extend_ref,
mutator_ref,
burn_ref,
};
move_to(token_signer_ref, aptogotchi);
// Emit event for minting Aptogotchi token
event::emit<MintAptogotchiEvent>(
MintAptogotchiEvent {
aptogotchi_address: address_of(token_signer_ref),
token_name,
parts,
},
);
// Transfer the Aptogotchi to the user
object::transfer_with_ref(object::generate_linear_transfer_ref(&transfer_ref), address_of(user));
aptogotchi_address
}