Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NFT withdrawl and offer #815

Open
cryptoalchemist1 opened this issue Feb 10, 2025 · 0 comments
Open

NFT withdrawl and offer #815

cryptoalchemist1 opened this issue Feb 10, 2025 · 0 comments

Comments

@cryptoalchemist1
Copy link

I am missing my NFT I purchased and never received the offer I recieved in my wallet who do I speak to in regards to this? I love the project.
Definitely have some bugs in your system needing to be coded properly and security issues.
It was NFT Space Pirate #10. That I purchased with for $1 APT. This is very special to me.
See my wallet below. The gas fees are ridiculous what I paid for it too. I love that NFT I spent all night trying to figure out how to convert my funds and figured it out after trying to convert my fiat to APT. Thank you so much for your help!

0x7ae10d8838243456577b0dc0f195d2c71c95448f47bff21011d52c749880d725

Aptos-Pontem Wallet

NFT and Balance

0xc0050dc68b85576c521ea8c61cc06ac8a0142ef7aea7cefbcca457ce38df91b8

Google Adress Aptos:

0xc0050dc68b85576c521ea8c61cc06ac8a0142ef7aea7cefbcca457ce38df91b8

Crypto.Alchemist.Petra
NFT and BalanceNow its no longer in my portfolio.
Seems very odd.
Thank you.
please email me directly
[email protected]

Heres the code/// This module provides the foundation for Tokens.
/// Checkout our developer doc on our token standard https://aptos.dev/standards
module aptos_token::token {
use std::error;
use std::option::{Self, Option};
use std::signer;
use std::string::{Self, String};
use std::vector;

use aptos_framework::account;
use aptos_framework::event::{Self, EventHandle};
use aptos_framework::timestamp;
use aptos_std::table::{Self, Table};
use aptos_token::property_map::{Self, PropertyMap, PropertyValue};
use aptos_token::token_event_store;

//
// Constants
//

const TOKEN_MAX_MUTABLE_IND: u64 = 0;
const TOKEN_URI_MUTABLE_IND: u64 = 1;
const TOKEN_ROYALTY_MUTABLE_IND: u64 = 2;
const TOKEN_DESCRIPTION_MUTABLE_IND: u64 = 3;
const TOKEN_PROPERTY_MUTABLE_IND: u64 = 4;
const TOKEN_PROPERTY_VALUE_MUTABLE_IND: u64 = 5;

const COLLECTION_DESCRIPTION_MUTABLE_IND: u64 = 0;
const COLLECTION_URI_MUTABLE_IND: u64 = 1;
const COLLECTION_MAX_MUTABLE_IND: u64 = 2;

const MAX_COLLECTION_NAME_LENGTH: u64 = 128;
const MAX_NFT_NAME_LENGTH: u64 = 128;
const MAX_URI_LENGTH: u64 = 512;

// Property key stored in default_properties controlling who can burn the token.
// the corresponding property value is BCS serialized bool.
const BURNABLE_BY_CREATOR: vector<u8> = b"TOKEN_BURNABLE_BY_CREATOR";
const BURNABLE_BY_OWNER: vector<u8> = b"TOKEN_BURNABLE_BY_OWNER";
const TOKEN_PROPERTY_MUTABLE: vector<u8> = b"TOKEN_PROPERTY_MUTATBLE";

//
// Errors
//
/// The token has balance and cannot be initialized
const EALREADY_HAS_BALANCE: u64 = 0;

/// There isn't any collection under this account
const ECOLLECTIONS_NOT_PUBLISHED: u64 = 1;

/// Cannot find collection in creator's account
const ECOLLECTION_NOT_PUBLISHED: u64 = 2;

/// The collection already exists
const ECOLLECTION_ALREADY_EXISTS: u64 = 3;

/// Exceeds the collection's maximal number of token_data
const ECREATE_WOULD_EXCEED_COLLECTION_MAXIMUM: u64 = 4;

/// Insufficient token balance
const EINSUFFICIENT_BALANCE: u64 = 5;

/// Cannot merge the two tokens with different token id
const EINVALID_TOKEN_MERGE: u64 = 6;

/// Exceed the token data maximal allowed
const EMINT_WOULD_EXCEED_TOKEN_MAXIMUM: u64 = 7;

/// No burn capability
const ENO_BURN_CAPABILITY: u64 = 8;

/// TokenData already exists
const ETOKEN_DATA_ALREADY_EXISTS: u64 = 9;

/// TokenData not published
const ETOKEN_DATA_NOT_PUBLISHED: u64 = 10;

/// TokenStore doesn't exist
const ETOKEN_STORE_NOT_PUBLISHED: u64 = 11;

/// Cannot split token to an amount larger than its amount
const ETOKEN_SPLIT_AMOUNT_LARGER_OR_EQUAL_TO_TOKEN_AMOUNT: u64 = 12;

/// The field is not mutable
const EFIELD_NOT_MUTABLE: u64 = 13;

/// Not authorized to mutate
const ENO_MUTATE_CAPABILITY: u64 = 14;

/// Token not in the token store
const ENO_TOKEN_IN_TOKEN_STORE: u64 = 15;

/// User didn't opt-in direct transfer
const EUSER_NOT_OPT_IN_DIRECT_TRANSFER: u64 = 16;

/// Cannot withdraw 0 token
const EWITHDRAW_ZERO: u64 = 17;

/// Cannot split a token that only has 1 amount
const ENFT_NOT_SPLITABLE: u64 = 18;

/// No mint capability
const ENO_MINT_CAPABILITY: u64 = 19;

/// The collection name is too long
const ECOLLECTION_NAME_TOO_LONG: u64 = 25;

/// The NFT name is too long
const ENFT_NAME_TOO_LONG: u64 = 26;

/// The URI is too long
const EURI_TOO_LONG: u64 = 27;

/// Cannot deposit a Token with 0 amount
const ENO_DEPOSIT_TOKEN_WITH_ZERO_AMOUNT: u64 = 28;

/// Cannot burn 0 Token
const ENO_BURN_TOKEN_WITH_ZERO_AMOUNT: u64 = 29;

/// Token is not burnable by owner
const EOWNER_CANNOT_BURN_TOKEN: u64 = 30;

/// Token is not burnable by creator
const ECREATOR_CANNOT_BURN_TOKEN: u64 = 31;

/// Reserved fields for token contract
/// Cannot be updated by user
const ECANNOT_UPDATE_RESERVED_PROPERTY: u64 = 32;

/// TOKEN with 0 amount is not allowed
const ETOKEN_CANNOT_HAVE_ZERO_AMOUNT: u64 = 33;

/// Royalty invalid if the numerator is larger than the denominator
const EINVALID_ROYALTY_NUMERATOR_DENOMINATOR: u64 = 34;

/// Royalty payee account does not exist
const EROYALTY_PAYEE_ACCOUNT_DOES_NOT_EXIST: u64 = 35;

/// Collection or tokendata maximum must be larger than supply
const EINVALID_MAXIMUM: u64 = 36;

/// Token Properties count doesn't match
const ETOKEN_PROPERTIES_COUNT_NOT_MATCH: u64 = 37;


/// Withdraw capability doesn't have sufficient amount
const EINSUFFICIENT_WITHDRAW_CAPABILITY_AMOUNT: u64 = 38;

/// Withdraw proof expires
const EWITHDRAW_PROOF_EXPIRES: u64 = 39;

/// The property is reserved by token standard
const EPROPERTY_RESERVED_BY_STANDARD: u64 = 40;

//
// Core data structures for holding tokens
//
struct Token has store {
    id: TokenId,
    /// the amount of tokens. Only property_version = 0 can have a value bigger than 1.
    amount: u64,
    /// The properties with this token.
    /// when property_version = 0, the token_properties are the same as default_properties in TokenData, we don't store it.
    /// when the property_map mutates, a new property_version is assigned to the token.
    token_properties: PropertyMap,
}

/// global unique identifier of a token
struct TokenId has store, copy, drop {
    /// the id to the common token data shared by token with different property_version
    token_data_id: TokenDataId,
    /// The version of the property map; when a fungible token is mutated, a new property version is created and assigned to the token to make it an NFT
    property_version: u64,
}

/// globally unique identifier of tokendata
struct TokenDataId has copy, drop, store {
    /// The address of the creator, eg: 0xcafe
    creator: address,
    /// The name of collection; this is unique under the same account, eg: "Aptos Animal Collection"
    collection: String,
    /// The name of the token; this is the same as the name field of TokenData
    name: String,
}

/// The shared TokenData by tokens with different property_version
struct TokenData has store {
    /// The maximal number of tokens that can be minted under this TokenData; if the maximum is 0, there is no limit
    maximum: u64,
    /// The current largest property version of all tokens with this TokenData
    largest_property_version: u64,
    /// The number of tokens with this TokenData. Supply is only tracked for the limited token whose maximum is not 0
    supply: u64,
    /// The Uniform Resource Identifier (uri) pointing to the JSON file stored in off-chain storage; the URL length should be less than 512 characters, eg: https://arweave.net/Fmmn4ul-7Mv6vzm7JwE69O-I-vd6Bz2QriJO1niwCh4
    uri: String,
    /// The denominator and numerator for calculating the royalty fee; it also contains payee account address for depositing the Royalty
    royalty: Royalty,
    /// The name of the token, which should be unique within the collection; the length of name should be smaller than 128, characters, eg: "Aptos Animal #1234"
    name: String,
    /// Describes this Token
    description: String,
    /// The properties are stored in the TokenData that are shared by all tokens
    default_properties: PropertyMap,
    /// Control the TokenData field mutability
    mutability_config: TokenMutabilityConfig,
}

/// The royalty of a token
struct Royalty has copy, drop, store {
    royalty_points_numerator: u64,
    royalty_points_denominator: u64,
    /// if the token is jointly owned by multiple creators, the group of creators should create a shared account.
    /// the payee_address will be the shared account address.
    payee_address: address,
}

/// This config specifies which fields in the TokenData are mutable
struct TokenMutabilityConfig has copy, store, drop {
    /// control if the token maximum is mutable
    maximum: bool,
    /// control if the token uri is mutable
    uri: bool,
    /// control if the token royalty is mutable
    royalty: bool,
    /// control if the token description is mutable
    description: bool,
    /// control if the property map is mutable
    properties: bool,
}

/// Represents token resources owned by token owner
struct TokenStore has key {
    /// the tokens owned by a token owner
    tokens: Table<TokenId, Token>,
    direct_transfer: bool,
    deposit_events: EventHandle<DepositEvent>,
    withdraw_events: EventHandle<WithdrawEvent>,
    burn_events: EventHandle<BurnTokenEvent>,
    mutate_token_property_events: EventHandle<MutateTokenPropertyMapEvent>,
}

/// This config specifies which fields in the Collection are mutable
struct CollectionMutabilityConfig has copy, store, drop {
    /// control if description is mutable
    description: bool,
    /// control if uri is mutable
    uri: bool,
    /// control if collection maxium is mutable
    maximum: bool,
}

/// Represent collection and token metadata for a creator
struct Collections has key {
    collection_data: Table<String, CollectionData>,
    token_data: Table<TokenDataId, TokenData>,
    create_collection_events: EventHandle<CreateCollectionEvent>,
    create_token_data_events: EventHandle<CreateTokenDataEvent>,
    mint_token_events: EventHandle<MintTokenEvent>,
}

/// Represent the collection metadata
struct CollectionData has store {
    /// A description for the token collection Eg: "Aptos Toad Overload"
    description: String,
    /// The collection name, which should be unique among all collections by the creator; the name should also be smaller than 128 characters, eg: "Animal Collection"
    name: String,
    /// The URI for the collection; its length should be smaller than 512 characters
    uri: String,
    /// The number of different TokenData entries in this collection
    supply: u64,
    /// If maximal is a non-zero value, the number of created TokenData entries should be smaller or equal to this maximum
    /// If maximal is 0, Aptos doesn't track the supply of this collection, and there is no limit
    maximum: u64,
    /// control which collectionData field is mutable
    mutability_config: CollectionMutabilityConfig,
}

/// capability to withdraw without signer, this struct should be non-copyable
struct WithdrawCapability has drop, store {
    token_owner: address,
    token_id: TokenId,
    amount: u64,
    expiration_sec: u64,
}

/// Set of data sent to the event stream during a receive
struct DepositEvent has drop, store {
    id: TokenId,
    amount: u64,
}

#[event]
/// Set of data sent to the event stream during a receive
struct TokenDeposit has drop, store {
    account: address,
    id: TokenId,
    amount: u64,
}

#[deprecated]
#[event]
/// Set of data sent to the event stream during a receive
struct Deposit has drop, store {
    id: TokenId,
    amount: u64,
}

/// Set of data sent to the event stream during a withdrawal
struct WithdrawEvent has drop, store {
    id: TokenId,
    amount: u64,
}

#[deprecated]
#[event]
/// Set of data sent to the event stream during a withdrawal
struct Withdraw has drop, store {
    id: TokenId,
    amount: u64,
}

#[event]
/// Set of data sent to the event stream during a withdrawal
struct TokenWithdraw has drop, store {
    account: address,
    id: TokenId,
    amount: u64,
}

/// token creation event id of token created
struct CreateTokenDataEvent has drop, store {
    id: TokenDataId,
    description: String,
    maximum: u64,
    uri: String,
    royalty_payee_address: address,
    royalty_points_denominator: u64,
    royalty_points_numerator: u64,
    name: String,
    mutability_config: TokenMutabilityConfig,
    property_keys: vector<String>,
    property_values: vector<vector<u8>>,
    property_types: vector<String>,
}

#[deprecated]
#[event]
struct CreateTokenData has drop, store {
    id: TokenDataId,
    description: String,
    maximum: u64,
    uri: String,
    royalty_payee_address: address,
    royalty_points_denominator: u64,
    royalty_points_numerator: u64,
    name: String,
    mutability_config: TokenMutabilityConfig,
    property_keys: vector<String>,
    property_values: vector<vector<u8>>,
    property_types: vector<String>,
}

#[event]
struct TokenDataCreation has drop, store {
    creator: address,
    id: TokenDataId,
    description: String,
    maximum: u64,
    uri: String,
    royalty_payee_address: address,
    royalty_points_denominator: u64,
    royalty_points_numerator: u64,
    name: String,
    mutability_config: TokenMutabilityConfig,
    property_keys: vector<String>,
    property_values: vector<vector<u8>>,
    property_types: vector<String>,
}

/// mint token event. This event triggered when creator adds more supply to existing token
struct MintTokenEvent has drop, store {
    id: TokenDataId,
    amount: u64,
}

#[deprecated]
#[event]
struct MintToken has drop, store {
    id: TokenDataId,
    amount: u64,
}

#[event]
struct Mint has drop, store {
    creator: address,
    id: TokenDataId,
    amount: u64,
}

///
struct BurnTokenEvent has drop, store {
    id: TokenId,
    amount: u64,
}

#[deprecated]
#[event]
struct BurnToken has drop, store {
    id: TokenId,
    amount: u64,
}

#[event]
struct Burn has drop, store {
    account: address,
    id: TokenId,
    amount: u64,
}


///
struct MutateTokenPropertyMapEvent has drop, store {
    old_id: TokenId,
    new_id: TokenId,
    keys: vector<String>,
    values: vector<vector<u8>>,
    types: vector<String>,
}

#[deprecated]
#[event]
struct MutateTokenPropertyMap has drop, store {
    old_id: TokenId,
    new_id: TokenId,
    keys: vector<String>,
    values: vector<vector<u8>>,
    types: vector<String>,
}

#[event]
struct MutatePropertyMap has drop, store {
    account: address,
    old_id: TokenId,
    new_id: TokenId,
    keys: vector<String>,
    values: vector<vector<u8>>,
    types: vector<String>,
}

/// create collection event with creator address and collection name
struct CreateCollectionEvent has drop, store {
    creator: address,
    collection_name: String,
    uri: String,
    description: String,
    maximum: u64,
}

#[event]
struct CreateCollection has drop, store {
    creator: address,
    collection_name: String,
    uri: String,
    description: String,
    maximum: u64,
}

//
// Creator Entry functions
//

/// create a empty token collection with parameters
public entry fun create_collection_script(
    creator: &signer,
    name: String,
    description: String,
    uri: String,
    maximum: u64,
    mutate_setting: vector<bool>,
) acquires Collections {
    create_collection(
        creator,
        name,
        description,
        uri,
        maximum,
        mutate_setting
    );
}

/// create token with raw inputs
public entry fun create_token_script(
    account: &signer,
    collection: String,
    name: String,
    description: String,
    balance: u64,
    maximum: u64,
    uri: String,
    royalty_payee_address: address,
    royalty_points_denominator: u64,
    royalty_points_numerator: u64,
    mutate_setting: vector<bool>,
    property_keys: vector<String>,
    property_values: vector<vector<u8>>,
    property_types: vector<String>
) acquires Collections, TokenStore {
    let token_mut_config = create_token_mutability_config(&mutate_setting);
    let tokendata_id = create_tokendata(
        account,
        collection,
        name,
        description,
        maximum,
        uri,
        royalty_payee_address,
        royalty_points_denominator,
        royalty_points_numerator,
        token_mut_config,
        property_keys,
        property_values,
        property_types
    );

    mint_token(
        account,
        tokendata_id,
        balance,
    );
}

/// Mint more token from an existing token_data. Mint only adds more token to property_version 0
public entry fun mint_script(
    account: &signer,
    token_data_address: address,
    collection: String,
    name: String,
    amount: u64,
) acquires Collections, TokenStore {
    let token_data_id = create_token_data_id(
        token_data_address,
        collection,
        name,
    );
    // only creator of the tokendata can mint more tokens for now
    assert!(token_data_id.creator == signer::address_of(account), error::permission_denied(ENO_MINT_CAPABILITY));
    mint_token(
        account,
        token_data_id,
        amount,
    );
}

/// mutate the token property and save the new property in TokenStore
/// if the token property_version is 0, we will create a new property_version per token to generate a new token_id per token
/// if the token property_version is not 0, we will just update the propertyMap and use the existing token_id (property_version)
public entry fun mutate_token_properties(
    account: &signer,
    token_owner: address,
    creator: address,
    collection_name: String,
    token_name: String,
    token_property_version: u64,
    amount: u64,
    keys: vector<String>,
    values: vector<vector<u8>>,
    types: vector<String>,
) acquires Collections, TokenStore {
    assert!(signer::address_of(account) == creator, error::not_found(ENO_MUTATE_CAPABILITY));
    let i = 0;
    let token_id = create_token_id_raw(
        creator,
        collection_name,
        token_name,
        token_property_version,
    );
    // give a new property_version for each token
    while (i < amount) {
        mutate_one_token(account, token_owner, token_id, keys, values, types);
        i = i + 1;
    };
}

//
// Transaction Entry functions
//

public entry fun direct_transfer_script(
    sender: &signer,
    receiver: &signer,
    creators_address: address,
    collection: String,
    name: String,
    property_version: u64,
    amount: u64,
) acquires TokenStore {
    let token_id = create_token_id_raw(creators_address, collection, name, property_version);
    direct_transfer(sender, receiver, token_id, amount);
}

public entry fun opt_in_direct_transfer(account: &signer, opt_in: bool) acquires TokenStore {
    let addr = signer::address_of(account);
    initialize_token_store(account);
    let opt_in_flag = &mut borrow_global_mut<TokenStore>(addr).direct_transfer;
    *opt_in_flag = opt_in;
    token_event_store::emit_token_opt_in_event(account, opt_in);
}

/// Transfers `amount` of tokens from `from` to `to`.
/// The receiver `to` has to opt-in direct transfer first
public entry fun transfer_with_opt_in(
    from: &signer,
    creator: address,
    collection_name: String,
    token_name: String,
    token_property_version: u64,
    to: address,
    amount: u64,
) acquires TokenStore {
    let token_id = create_token_id_raw(creator, collection_name, token_name, token_property_version);
    transfer(from, token_id, to, amount);
}

/// Burn a token by creator when the token's BURNABLE_BY_CREATOR is true
/// The token is owned at address owner
public entry fun burn_by_creator(
    creator: &signer,
    owner: address,
    collection: String,
    name: String,
    property_version: u64,
    amount: u64,
) acquires Collections, TokenStore {
    let creator_address = signer::address_of(creator);
    assert!(amount > 0, error::invalid_argument(ENO_BURN_TOKEN_WITH_ZERO_AMOUNT));
    let token_id = create_token_id_raw(creator_address, collection, name, property_version);
    let creator_addr = token_id.token_data_id.creator;
    assert!(
        exists<Collections>(creator_addr),
        error::not_found(ECOLLECTIONS_NOT_PUBLISHED),
    );

    let collections = borrow_global_mut<Collections>(creator_address);
    assert!(
        table::contains(&collections.token_data, token_id.token_data_id),
        error::not_found(ETOKEN_DATA_NOT_PUBLISHED),
    );

    let token_data = table::borrow_mut(
        &mut collections.token_data,
        token_id.token_data_id,
    );

    // The property should be explicitly set in the property_map for creator to burn the token
    assert!(
        property_map::contains_key(&token_data.default_properties, &string::utf8(BURNABLE_BY_CREATOR)),
        error::permission_denied(ECREATOR_CANNOT_BURN_TOKEN)
    );

    let burn_by_creator_flag = property_map::read_bool(&token_data.default_properties, &string::utf8(BURNABLE_BY_CREATOR));
    assert!(burn_by_creator_flag, error::permission_denied(ECREATOR_CANNOT_BURN_TOKEN));

    // Burn the tokens.
    let Token { id: _, amount: burned_amount, token_properties: _ } = withdraw_with_event_internal(owner, token_id, amount);
    let token_store = borrow_global_mut<TokenStore>(owner);
    if (std::features::module_event_migration_enabled()) {
        event::emit(Burn { account: owner, id: token_id, amount: burned_amount });
    } else {
        event::emit_event<BurnTokenEvent>(
            &mut token_store.burn_events,
            BurnTokenEvent { id: token_id, amount: burned_amount }
        );
    };

    if (token_data.maximum > 0) {
        token_data.supply = token_data.supply - burned_amount;

        // Delete the token_data if supply drops to 0.
        if (token_data.supply == 0) {
            destroy_token_data(table::remove(&mut collections.token_data, token_id.token_data_id));

            // update the collection supply
            let collection_data = table::borrow_mut(
                &mut collections.collection_data,
                token_id.token_data_id.collection
            );
            if (collection_data.maximum > 0) {
                collection_data.supply = collection_data.supply - 1;
                // delete the collection data if the collection supply equals 0
                if (collection_data.supply == 0) {
                    destroy_collection_data(table::remove(&mut collections.collection_data, collection_data.name));
                };
            };
        };
    };
}

/// Burn a token by the token owner
public entry fun burn(
    owner: &signer,
    creators_address: address,
    collection: String,
    name: String,
    property_version: u64,
    amount: u64
) acquires Collections, TokenStore {
    assert!(amount > 0, error::invalid_argument(ENO_BURN_TOKEN_WITH_ZERO_AMOUNT));
    let token_id = create_token_id_raw(creators_address, collection, name, property_version);
    let creator_addr = token_id.token_data_id.creator;
    assert!(
        exists<Collections>(creator_addr),
        error::not_found(ECOLLECTIONS_NOT_PUBLISHED),
    );

    let collections = borrow_global_mut<Collections>(creator_addr);
    assert!(
        table::contains(&collections.token_data, token_id.token_data_id),
        error::not_found(ETOKEN_DATA_NOT_PUBLISHED),
    );

    let token_data = table::borrow_mut(
        &mut collections.token_data,
        token_id.token_data_id,
    );

    assert!(
        property_map::contains_key(&token_data.default_properties, &string::utf8(BURNABLE_BY_OWNER)),
        error::permission_denied(EOWNER_CANNOT_BURN_TOKEN)
    );
    let burn_by_owner_flag = property_map::read_bool(&token_data.default_properties, &string::utf8(BURNABLE_BY_OWNER));
    assert!(burn_by_owner_flag, error::permission_denied(EOWNER_CANNOT_BURN_TOKEN));

    // Burn the tokens.
    let Token { id: _, amount: burned_amount, token_properties: _ } = withdraw_token(owner, token_id, amount);
    let token_store = borrow_global_mut<TokenStore>(signer::address_of(owner));
    if (std::features::module_event_migration_enabled()) {
        event::emit(Burn { account: signer::address_of(owner), id: token_id, amount: burned_amount });
    } else {
        event::emit_event<BurnTokenEvent>(
            &mut token_store.burn_events,
            BurnTokenEvent { id: token_id, amount: burned_amount }
        );
    };

    // Decrease the supply correspondingly by the amount of tokens burned.
    let token_data = table::borrow_mut(
        &mut collections.token_data,
        token_id.token_data_id,
    );

    // only update the supply if we tracking the supply and maximal
    // maximal == 0 is reserved for unlimited token and collection with no tracking info.
    if (token_data.maximum > 0) {
        token_data.supply = token_data.supply - burned_amount;

        // Delete the token_data if supply drops to 0.
        if (token_data.supply == 0) {
            destroy_token_data(table::remove(&mut collections.token_data, token_id.token_data_id));

            // update the collection supply
            let collection_data = table::borrow_mut(
                &mut collections.collection_data,
                token_id.token_data_id.collection
            );

            // only update and check the supply for unlimited collection
            if (collection_data.maximum > 0){
                collection_data.supply = collection_data.supply - 1;
                // delete the collection data if the collection supply equals 0
                if (collection_data.supply == 0) {
                    destroy_collection_data(table::remove(&mut collections.collection_data, collection_data.name));
                };
            };
        };
    };
}

//
// Public functions for creating and maintaining tokens
//

// Functions for mutating CollectionData fields
public fun mutate_collection_description(creator: &signer, collection_name: String, description: String) acquires Collections {
    let creator_address = signer::address_of(creator);
    assert_collection_exists(creator_address, collection_name);
    let collection_data = table::borrow_mut(&mut borrow_global_mut<Collections>(creator_address).collection_data, collection_name);
    assert!(collection_data.mutability_config.description, error::permission_denied(EFIELD_NOT_MUTABLE));
    token_event_store::emit_collection_description_mutate_event(creator, collection_name, collection_data.description, description);
    collection_data.description = description;
}

public fun mutate_collection_uri(creator: &signer, collection_name: String, uri: String) acquires Collections {
    assert!(string::length(&uri) <= MAX_URI_LENGTH, error::invalid_argument(EURI_TOO_LONG));
    let creator_address = signer::address_of(creator);
    assert_collection_exists(creator_address, collection_name);
    let collection_data = table::borrow_mut(&mut borrow_global_mut<Collections>(creator_address).collection_data, collection_name);
    assert!(collection_data.mutability_config.uri, error::permission_denied(EFIELD_NOT_MUTABLE));
    token_event_store::emit_collection_uri_mutate_event(creator, collection_name, collection_data.uri , uri);
    collection_data.uri = uri;
}

public fun mutate_collection_maximum(creator: &signer, collection_name: String, maximum: u64) acquires Collections {
    let creator_address = signer::address_of(creator);
    assert_collection_exists(creator_address, collection_name);
    let collection_data = table::borrow_mut(&mut borrow_global_mut<Collections>(creator_address).collection_data, collection_name);
    // cannot change maximum from 0 and cannot change maximum to 0
    assert!(collection_data.maximum != 0 && maximum != 0, error::invalid_argument(EINVALID_MAXIMUM));
    assert!(maximum >= collection_data.supply, error::invalid_argument(EINVALID_MAXIMUM));
    assert!(collection_data.mutability_config.maximum, error::permission_denied(EFIELD_NOT_MUTABLE));
    token_event_store::emit_collection_maximum_mutate_event(creator, collection_name, collection_data.maximum, maximum);
    collection_data.maximum = maximum;
}

// Functions for mutating TokenData fields
public fun mutate_tokendata_maximum(creator: &signer, token_data_id: TokenDataId, maximum: u64) acquires Collections {
    assert_tokendata_exists(creator, token_data_id);
    let all_token_data = &mut borrow_global_mut<Collections>(token_data_id.creator).token_data;
    let token_data = table::borrow_mut(all_token_data, token_data_id);
    // cannot change maximum from 0 and cannot change maximum to 0
    assert!(token_data.maximum != 0 && maximum != 0, error::invalid_argument(EINVALID_MAXIMUM));
    assert!(maximum >= token_data.supply, error::invalid_argument(EINVALID_MAXIMUM));
    assert!(token_data.mutability_config.maximum, error::permission_denied(EFIELD_NOT_MUTABLE));
    token_event_store::emit_token_maximum_mutate_event(creator, token_data_id.collection, token_data_id.name, token_data.maximum, maximum);
    token_data.maximum = maximum;
}

public fun mutate_tokendata_uri(
    creator: &signer,
    token_data_id: TokenDataId,
    uri: String
) acquires Collections {
    assert!(string::length(&uri) <= MAX_URI_LENGTH, error::invalid_argument(EURI_TOO_LONG));
    assert_tokendata_exists(creator, token_data_id);

    let all_token_data = &mut borrow_global_mut<Collections>(token_data_id.creator).token_data;
    let token_data = table::borrow_mut(all_token_data, token_data_id);
    assert!(token_data.mutability_config.uri, error::permission_denied(EFIELD_NOT_MUTABLE));
    token_event_store::emit_token_uri_mutate_event(creator, token_data_id.collection, token_data_id.name, token_data.uri ,uri);
    token_data.uri = uri;
}

public fun mutate_tokendata_royalty(creator: &signer, token_data_id: TokenDataId, royalty: Royalty) acquires Collections {
    assert_tokendata_exists(creator, token_data_id);

    let all_token_data = &mut borrow_global_mut<Collections>(token_data_id.creator).token_data;
    let token_data = table::borrow_mut(all_token_data, token_data_id);
    assert!(token_data.mutability_config.royalty, error::permission_denied(EFIELD_NOT_MUTABLE));

    token_event_store::emit_token_royalty_mutate_event(
        creator,
        token_data_id.collection,
        token_data_id.name,
        token_data.royalty.royalty_points_numerator,
        token_data.royalty.royalty_points_denominator,
        token_data.royalty.payee_address,
        royalty.royalty_points_numerator,
        royalty.royalty_points_denominator,
        royalty.payee_address
    );
    token_data.royalty = royalty;
}

public fun mutate_tokendata_description(creator: &signer, token_data_id: TokenDataId, description: String) acquires Collections {
    assert_tokendata_exists(creator, token_data_id);

    let all_token_data = &mut borrow_global_mut<Collections>(token_data_id.creator).token_data;
    let token_data = table::borrow_mut(all_token_data, token_data_id);
    assert!(token_data.mutability_config.description, error::permission_denied(EFIELD_NOT_MUTABLE));
    token_event_store::emit_token_descrition_mutate_event(creator, token_data_id.collection, token_data_id.name, token_data.description, description);
    token_data.description = description;
}

/// Allow creator to mutate the default properties in TokenData
public fun mutate_tokendata_property(
    creator: &signer,
    token_data_id: TokenDataId,
    keys: vector<String>,
    values: vector<vector<u8>>,
    types: vector<String>,
) acquires Collections {
    assert_tokendata_exists(creator, token_data_id);
    let key_len = vector::length(&keys);
    let val_len = vector::length(&values);
    let typ_len = vector::length(&types);
    assert!(key_len == val_len, error::invalid_state(ETOKEN_PROPERTIES_COUNT_NOT_MATCH));
    assert!(key_len == typ_len, error::invalid_state(ETOKEN_PROPERTIES_COUNT_NOT_MATCH));

    let all_token_data = &mut borrow_global_mut<Collections>(token_data_id.creator).token_data;
    let token_data = table::borrow_mut(all_token_data, token_data_id);
    assert!(token_data.mutability_config.properties, error::permission_denied(EFIELD_NOT_MUTABLE));
    let i: u64 = 0;
    let old_values: vector<Option<PropertyValue>> = vector::empty();
    let new_values: vector<PropertyValue> = vector::empty();
    assert_non_standard_reserved_property(&keys);
    while (i < vector::length(&keys)){
        let key = vector::borrow(&keys, i);
        let old_pv = if (property_map::contains_key(&token_data.default_properties, key)) {
            option::some(*property_map::borrow(&token_data.default_properties, key))
        } else {
            option::none<PropertyValue>()
        };
        vector::push_back(&mut old_values, old_pv);
        let new_pv = property_map::create_property_value_raw(*vector::borrow(&values, i), *vector::borrow(&types, i));
        vector::push_back(&mut new_values, new_pv);
        if (option::is_some(&old_pv)) {
            property_map::update_property_value(&mut token_data.default_properties, key, new_pv);
        } else {
            property_map::add(&mut token_data.default_properties, *key, new_pv);
        };
        i = i + 1;
    };
    token_event_store::emit_default_property_mutate_event(creator, token_data_id.collection, token_data_id.name, keys, old_values, new_values);
}

/// Mutate the token_properties of one token.
public fun mutate_one_token(
    account: &signer,
    token_owner: address,
    token_id: TokenId,
    keys: vector<String>,
    values: vector<vector<u8>>,
    types: vector<String>,
): TokenId acquires Collections, TokenStore {
    let creator = token_id.token_data_id.creator;
    assert!(signer::address_of(account) == creator, error::permission_denied(ENO_MUTATE_CAPABILITY));
    // validate if the properties is mutable
    assert!(exists<Collections>(creator), error::not_found(ECOLLECTIONS_NOT_PUBLISHED));
    let all_token_data = &mut borrow_global_mut<Collections>(
        creator
    ).token_data;

    assert!(table::contains(all_token_data, token_id.token_data_id), error::not_found(ETOKEN_DATA_NOT_PUBLISHED));
    let token_data = table::borrow_mut(all_token_data, token_id.token_data_id);

    // if default property is mutatable, token property is alwasy mutable
    // we only need to check TOKEN_PROPERTY_MUTABLE when default property is immutable
    if (!token_data.mutability_config.properties) {
        assert!(
            property_map::contains_key(&token_data.default_properties, &string::utf8(TOKEN_PROPERTY_MUTABLE)),
            error::permission_denied(EFIELD_NOT_MUTABLE)
        );

        let token_prop_mutable = property_map::read_bool(&token_data.default_properties, &string::utf8(TOKEN_PROPERTY_MUTABLE));
        assert!(token_prop_mutable, error::permission_denied(EFIELD_NOT_MUTABLE));
    };

    // check if the property_version is 0 to determine if we need to update the property_version
    if (token_id.property_version == 0) {
        let token = withdraw_with_event_internal(token_owner, token_id, 1);
        // give a new property_version for each token
        let cur_property_version = token_data.largest_property_version + 1;
        let new_token_id = create_token_id(token_id.token_data_id, cur_property_version);
        let new_token = Token {
            id: new_token_id,
            amount: 1,
            token_properties: token_data.default_properties,
        };
        direct_deposit(token_owner, new_token);
        update_token_property_internal(token_owner, new_token_id, keys, values, types);
        if (std::features::module_event_migration_enabled()) {
            event::emit(MutatePropertyMap {
                account: token_owner,
                old_id: token_id,
                new_id: new_token_id,
                keys,
                values,
                types
            });
        } else {
            event::emit_event<MutateTokenPropertyMapEvent>(
                &mut borrow_global_mut<TokenStore>(token_owner).mutate_token_property_events,
                MutateTokenPropertyMapEvent {
                    old_id: token_id,
                    new_id: new_token_id,
                    keys,
                    values,
                    types
                },
            );
        };

        token_data.largest_property_version = cur_property_version;
        // burn the orignial property_version 0 token after mutation
        let Token { id: _, amount: _, token_properties: _ } = token;
        new_token_id
    } else {
        // only 1 copy for the token with property verion bigger than 0
        update_token_property_internal(token_owner, token_id, keys, values, types);
        if (std::features::module_event_migration_enabled()) {
            event::emit(MutatePropertyMap {
                account: token_owner,
                old_id: token_id,
                new_id: token_id,
                keys,
                values,
                types
            });
        } else {
            event::emit_event<MutateTokenPropertyMapEvent>(
                &mut borrow_global_mut<TokenStore>(token_owner).mutate_token_property_events,
                MutateTokenPropertyMapEvent {
                    old_id: token_id,
                    new_id: token_id,
                    keys,
                    values,
                    types
                },
            );
        };
        token_id
    }
}

public fun create_royalty(royalty_points_numerator: u64, royalty_points_denominator: u64, payee_address: address): Royalty {
    assert!(royalty_points_numerator <= royalty_points_denominator, error::invalid_argument(EINVALID_ROYALTY_NUMERATOR_DENOMINATOR));
    assert!(account::exists_at(payee_address), error::invalid_argument(EROYALTY_PAYEE_ACCOUNT_DOES_NOT_EXIST));
    Royalty {
        royalty_points_numerator,
        royalty_points_denominator,
        payee_address
    }
}

/// Deposit the token balance into the owner's account and emit an event.
public fun deposit_token(account: &signer, token: Token) acquires TokenStore {
    let account_addr = signer::address_of(account);
    initialize_token_store(account);
    direct_deposit(account_addr, token)
}

/// direct deposit if user opt in direct transfer
public fun direct_deposit_with_opt_in(account_addr: address, token: Token) acquires TokenStore {
    let opt_in_transfer = borrow_global<TokenStore>(account_addr).direct_transfer;
    assert!(opt_in_transfer, error::permission_denied(EUSER_NOT_OPT_IN_DIRECT_TRANSFER));
    direct_deposit(account_addr, token);
}

public fun direct_transfer(
    sender: &signer,
    receiver: &signer,
    token_id: TokenId,
    amount: u64,
) acquires TokenStore {
    let token = withdraw_token(sender, token_id, amount);
    deposit_token(receiver, token);
}

public fun initialize_token_store(account: &signer) {
    if (!exists<TokenStore>(signer::address_of(account))) {
        move_to(
            account,
            TokenStore {
                tokens: table::new(),
                direct_transfer: false,
                deposit_events: account::new_event_handle<DepositEvent>(account),
                withdraw_events: account::new_event_handle<WithdrawEvent>(account),
                burn_events: account::new_event_handle<BurnTokenEvent>(account),
                mutate_token_property_events: account::new_event_handle<MutateTokenPropertyMapEvent>(account),
            },
        );
    }
}

public fun merge(dst_token: &mut Token, source_token: Token) {
    assert!(&dst_token.id == &source_token.id, error::invalid_argument(EINVALID_TOKEN_MERGE));
    dst_token.amount = dst_token.amount + source_token.amount;
    let Token { id: _, amount: _, token_properties: _ } = source_token;
}

public fun split(dst_token: &mut Token, amount: u64): Token {
    assert!(dst_token.id.property_version == 0, error::invalid_state(ENFT_NOT_SPLITABLE));
    assert!(dst_token.amount > amount, error::invalid_argument(ETOKEN_SPLIT_AMOUNT_LARGER_OR_EQUAL_TO_TOKEN_AMOUNT));
    assert!(amount > 0, error::invalid_argument(ETOKEN_CANNOT_HAVE_ZERO_AMOUNT));
    dst_token.amount = dst_token.amount - amount;
    Token {
        id: dst_token.id,
        amount,
        token_properties: property_map::empty(),
    }
}

public fun token_id(token: &Token): &TokenId {
    &token.id
}

/// Transfers `amount` of tokens from `from` to `to`.
public fun transfer(
    from: &signer,
    id: TokenId,
    to: address,
    amount: u64,
) acquires TokenStore {
    let opt_in_transfer = borrow_global<TokenStore>(to).direct_transfer;
    assert!(opt_in_transfer, error::permission_denied(EUSER_NOT_OPT_IN_DIRECT_TRANSFER));
    let token = withdraw_token(from, id, amount);
    direct_deposit(to, token);
}


/// Token owner can create this one-time withdraw capability with an expiration time
public fun create_withdraw_capability(
    owner: &signer,
    token_id: TokenId,
    amount: u64,
    expiration_sec: u64,
): WithdrawCapability {
    WithdrawCapability {
        token_owner: signer::address_of(owner),
        token_id,
        amount,
        expiration_sec,
    }
}

/// Withdraw the token with a capability
public fun withdraw_with_capability(
    withdraw_proof: WithdrawCapability,
): Token acquires TokenStore {
    // verify the delegation hasn't expired yet
    assert!(timestamp::now_seconds() <= withdraw_proof.expiration_sec, error::invalid_argument(EWITHDRAW_PROOF_EXPIRES));

    withdraw_with_event_internal(
        withdraw_proof.token_owner,
        withdraw_proof.token_id,
        withdraw_proof.amount,
    )
}

/// Withdraw the token with a capability.
public fun partial_withdraw_with_capability(
    withdraw_proof: WithdrawCapability,
    withdraw_amount: u64,
): (Token, Option<WithdrawCapability>) acquires TokenStore {
    // verify the delegation hasn't expired yet
    assert!(timestamp::now_seconds() <= withdraw_proof.expiration_sec, error::invalid_argument(EWITHDRAW_PROOF_EXPIRES));

    assert!(withdraw_amount <= withdraw_proof.amount, error::invalid_argument(EINSUFFICIENT_WITHDRAW_CAPABILITY_AMOUNT));

    let res: Option<WithdrawCapability> = if (withdraw_amount == withdraw_proof.amount) {
        option::none<WithdrawCapability>()
    } else {
        option::some(
            WithdrawCapability {
                token_owner: withdraw_proof.token_owner,
                token_id: withdraw_proof.token_id,
                amount: withdraw_proof.amount - withdraw_amount,
                expiration_sec: withdraw_proof.expiration_sec,
            }
        )
    };

    (
        withdraw_with_event_internal(
            withdraw_proof.token_owner,
            withdraw_proof.token_id,
            withdraw_amount,
        ),
        res
    )

}
    assert!(table::contains(all_token_data, token_data_id), error::not_found(ETOKEN_DATA_NOT_PUBLISHED));
    table::borrow(all_token_data, token_data_id).mutability_config
}

/// return if the token's maximum is mutable
public fun get_token_mutability_maximum(config: &TokenMutabilityConfig): bool {
    config.maximum
}

/// return if the token royalty is mutable with a token mutability config
public fun get_token_mutability_royalty(config: &TokenMutabilityConfig): bool {
    config.royalty
}

/// return if the token uri is mutable with a token mutability config
public fun get_token_mutability_uri(config: &TokenMutabilityConfig): bool {
    config.uri
}

/// return if the token description is mutable with a token mutability config
public fun get_token_mutability_description(config: &TokenMutabilityConfig): bool {
    config.description
}

/// return if the tokendata's default properties is mutable with a token mutability config
public fun get_token_mutability_default_properties(config: &TokenMutabilityConfig): bool {
    config.properties
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant