Movement 백서

Movement

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 33쪽 중 26쪽

onError={(error) => { console.log("error", error); }} > {children} </AptosWalletAdapterProvider> ); }; ``` <details> <summary>All fields of AptosWalletAdapterProvider</summary> It is recommended to: Set autoConnect to true. Include plugins for any wallets that are using the legacy standard. | Field | Description | Example | | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------- | | `autoConnect` | A prop indicates whether the dapp should auto connect with the most recently connected wallet on page reload. | `true` | | `optInWallets` | Limit the list of supported AIP-62 wallets to just the ones with names in optedInWallets. | `['Petra']` | | `dappConfig` | Specify an alternate network to work on. This prop only works for wallets which are NOT chrome extensions. If set, this object must include the name of the network the app is connected to. The object may include a aptosConnectDappId. | `{ network: 'mainnet', aptosConnectDappId: undefined }` | | `onError` | A callback function to fire when the adapter throws an error. | `(error) => { console.log("error", error); }` | | `plugins` | Any legacy standard wallet, i.e., a wallet that is not AIP-62 standard compatible, should be installed in this array. Check [https://github.com/aptos-labs/aptos-wallet-adapter/blob/main/README.md#supported-wallet-packages](https://github.com/aptos-labs/aptos-wallet-adapter/blob/main/README.md#supported-wallet-packages) for a list of legacy standard wallet plugins. | `[new LegacyWallet()]` | </details> ### Import Provider to layout.tsx ```typescript import type { Metadata } from "next"; import localFont from "next/font/local"; import "./globals.css"; import { WalletProvider } from "@/provider"; // ... {rest code} export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { return ( <html lang="en"> <body className={`${geistSans.variable} ${geistMono.variable} antialiased`} > <WalletProvider> {children} </WalletProvider> </body> </html> ); } ``` ### Edit `src/app/page.tsx` & import `useWallet` to access data from the `Provider` ```typescript title="src/app/page.tsx" 'use client' import {useWallet} from '@aptos-labs/wallet-adapter-react' export default function Home() { const { account, connected, wallet, changeNetwork } = useWallet(); return ( <div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]"> {account && account.address} </div> ); } ``` For more information about the `useWallet` hook, you can refer to the following interface: ```typescript export interface WalletContextState { connected: boolean; isLoading: boolean; account: AccountInfo | null; network: NetworkInfo | null; connect(walletName: WalletName): void; disconnect(): void; wallet: WalletInfo | null; wallets?: ReadonlyArray<Wallet | AptosStandardSupportedWallet>; signAndSubmitTransaction(transaction: InputTransactionData): Promise<any>; signTransaction( transactionOrPayload: AnyRawTransaction | Types.TransactionPayload, asFeePayer?: boolean, options?: InputGenerateTransactionOptions ): Promise<AccountAuthenticator>; submitTransaction( transaction: InputSubmitTransactionData ): Promise<PendingTransactionResponse>; signMessage(message: SignMessagePayload): Promise<SignMessageResponse>; signMessageAndVerify(message: SignMessagePayload): Promise<boolean>; changeNetwork(network: Network): Promise<AptosChangeNetworkOutput>; } ``` <details> <summary>Details all function of useWallet()</summary> ### Functions *See [`WalletCore.ts`](https://github.com/aptos-labs/aptos-wallet-adapter/blob/main/packages/wallet-adapter-core/src/WalletCore.ts) in [`wallet-adapter-core`](https://github.com/aptos-labs/aptos-wallet-adapter/tree/main/packages/wallet-adapter-core) for where these functions are implemented.* | Function | Signature | Description | | -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | | `connect` | `connect(walletName: WalletName): void` | Connects to the specified wallet by its name. | | `disconnect` | `disconnect(): void` | Disconnects the currently connected wallet. | | `signTransaction` | `signTransaction(transactionOrPayload: AnyRawTransaction \| Types.TransactionPayload, asFeePayer?: boolean, options?: InputGenerateTransactionOptions): Promise<AccountAuthenticator>` | Signs a transaction with optional parameters for fee payment. | | `submitTransaction` | `submitTransaction(transaction: InputSubmitTransactionData): Promise<PendingTransactionResponse>` | Submits a transaction with the provided transaction data. | | `signAndSubmitTransaction` | `signAndSubmitTransaction(transaction: InputTransactionData): Promise<any>` | Signs and submits a transaction with the given input data. | | `signMessage` | `signMessage(message: SignMessagePayload): Promise<SignMessageResponse>` | Signs a message and returns the signature and other response info. | | `signMessageAndVerify` | `signMessageAndVerify(message: SignMessagePayload): Promise<boolean>` | Signs a message and verifies the signer. | | `changeNetwork` | `changeNetwork(network: Network): Promise<AptosChangeNetworkOutput>` | Requests a change in the connected network. This is not supported by all wallets. | </details> # Digital Asset URL: /devs/tokenStandard/currentStandard/digitalAsset # Digital Asset (DA) Standard The Movement Digital Asset Standard provides a modern, flexible framework for creating and managing Non-Fungible Tokens (NFTs) on Movement. Built on Move Objects, this standard offers enhanced composability, direct transfers, and extensibility that surpasses traditional NFT implementations. <Callout type="info"> The Digital Asset standard is available in the Movement framework at `aptos_token_objects` and represents the current standard for NFT development on Movement. </Callout> ## Overview Movement's Digital Asset standard enables developers to: * **Create Sophisticated NFTs**: Build tokens with custom logic, metadata, and behaviors * **Direct Transfers**: Transfer NFTs without recipient opt-in requirements * **Enhanced Composability**: NFTs can own other NFTs and complex asset structures * **Extensible Design**: Leverage Move Objects for unlimited customization possibilities * **Ecosystem Integration**: Seamless compatibility with Movement's DeFi and gaming protocols ## Core Architecture ### Object-Based Design The DA standard uses Move Objects to represent digital assets with two primary components: ```move module aptos_token_objects::collection { /// Collection metadata and configuration struct Collection has key { creator: address, description: String, name: String, uri: String, mutation_setting: MutationSetting, } } module aptos_token_objects::token { /// Individual token within a collection struct Token has key { collection: Object<Collection>, description: String, name: String, uri: String, mutation_setting: MutationSetting, } } ``` **Architecture Benefits:** * **True Ownership**: NFTs are owned objects, not account resources * **Composability**: Objects can contain other objects for complex structures * **Extensibility**: Add custom resources and functionality via smart contracts * **Gas Efficiency**: Optimized storage and transfer mechanisms ### Movement Framework Structures #### Collections Collections organize related NFTs under a unified framework: | Field | Type | Description | | ------------------ | --------------- | --------------------------------------------------- | | `creator` | address | Address of the collection creator | | `description` | String | Collection description (max 2048 characters) | | `name` | String | Unique collection name under creator | | `uri` | String | URI pointing to collection metadata (max 512 chars) | | `mutation_setting` | MutationSetting | Controls which fields can be modified | #### Tokens Tokens represent individual NFTs within a collection. Each token is a Move Object that contains metadata and maintains a reference to its parent collection. Tokens can be extended with custom resources to add application-specific functionality such as game attributes, DeFi properties, or any other custom data. | Field | Type | Description | | ------------------ | -------------------- | --------------------------------------------------------------------- | | `collection` | `Object<Collection>` | Reference to the parent collection object | | `description` | String | Token description (max 2048 characters) | | `name` | String | Unique token name within the collection | | `uri` | String | URI pointing to off-chain token metadata (max 512 chars) | | `mutation_setting` | MutationSetting | Configuration controlling which fields can be modified after creation | ## Creating Collections on Movement ### Fixed Supply Collections Fixed supply collections have a predetermined maximum number of tokens that can be minted. This is ideal for limited edition NFT drops, exclusive membership tokens, or any collection where scarcity is important. Use `collection::create_fixed_collection` to create a collection with a hard cap on supply. ```move module movement_addr::movement_nft_collection { use aptos_token_objects::collection; use aptos_token_objects::royalty; use std::string; use std::option; use std::signer; /// Movement Gaming NFT Collection struct MovementGamingCollection has key {} /// Create a Movement gaming collection with fixed supply public entry fun create_gaming_collection(creator: &signer) { let royalty_config = royalty::create( 5, // 5% royalty 100, // denominator signer::address_of(creator) // royalty recipient ); collection::create_fixed_collection( creator, string::utf8(b"Exclusive collection of Movement gaming assets featuring unique characters, weapons, and items for the Movement ecosystem"), 1000, // Maximum 1000 NFTs string::utf8(b"Movement Gaming Assets"), option::some(royalty_config), string::utf8(b"https://gaming.movement.xyz/collection/metadata") ); } } ``` <Callout type="warning"> A Collection's maximum supply cannot be changed after creation. </Callout> ### Unlimited Supply Collections Unlimited supply collections have no cap on the number of tokens that can be minted. This is suitable for ongoing NFT series, reward tokens, or collections that need to grow over time. Use `collection::create_unlimited_collection` to create an open-ended collection. ```move module movement_addr::movement_art_collection { use aptos_token_objects::collection; use aptos_token_objects::royalty; use std::string; use std::option; /// Create Movement art collection with unlimited supply public entry fun create_art_collection(creator: &signer) { let royalty_config = royalty::create( 10, // 10% royalty for artists 100, signer::address_of(creator) ); collection::create_unlimited_collection( creator, string::utf8(b"Curated digital art collection showcasing the creativity and innovation of the Movement community"), string::utf8(b"Movement Digital Art"), option::some(royalty_config), string::utf8(b"https://art.movement.xyz/collection") ); } } ``` ### Advanced Collection with Custom Features Since Collections are Move Objects, they can be customized through permission tokens called Refs. These Refs grant the ability to modify specific aspects of the Object after creation. In addition to standard Object Refs, Collections support a specialized MutatorRef that can be obtained by calling `collection::generate_mutator_ref`: ```move module movement_addr::advanced_movement_collection { use aptos_token_objects::collection::{Self, MutatorRef}; use aptos_token_objects::royalty; use aptos_framework::object; use std::string; use std::option; use std::signer; /// Collection with custom mutability struct CustomCollection has key { mutator_ref: MutatorRef, } /// Create collection with mutator ref for future updates public entry fun create_custom_collection(creator: &signer) { let royalty_config = royalty::create(5, 100, signer::address_of(creator)); let constructor_ref = &collection::create_unlimited_collection( creator, string::utf8(b"Movement collection with mutable metadata"), string::utf8(b"Movement Custom Collection"), option::some(royalty_config), string::utf8(b"https://movement.xyz/metadata") ); // Generate mutator ref for later modifications let mutator_ref = collection::generate_mutator_ref(constructor_ref); let collection_signer = &object::generate_signer(constructor_ref); // Store mutator ref for future use move_to(collection_signer, CustomCollection { mutator_ref, }); } /// Update collection description using stored mutator ref public entry fun update_description( creator: &signer, collection: object::Object<collection::Collection>, new_description: string::String ) acquires CustomCollection { let collection_addr = object::object_address(&collection); let custom_collection = borrow_global<CustomCollection>(collection_addr); collection::set_description(&custom_collection.mutator_ref, new_description); } } ``` <Callout type="info"> Refs must be generated at creation time of an Object. The ConstructorRef used to generate other Refs expires as soon as the transaction to create the Object is finished. </Callout> ## Creating Tokens (NFTs) ### Named Tokens Named tokens have deterministic addresses derived from the creator address, collection name, and token name. This makes them predictable and easy to reference without needing to store the token address. Named tokens are ideal when you need to look up tokens by their identifying information rather than storing addresses. Use `token::create_named_token` to create tokens with deterministic addressing. ```move module movement_addr::movement_character_nft { use aptos_token_objects::token; use aptos_token_objects::royalty; use std::string; use std::option; /// Create a Movement character NFT public entry fun mint_character( creator: &signer, character_class: String, rarity: String, power_level: u64 ) { let character_name = string::utf8(b"Movement Warrior #1001"); let description = string::utf8(b"A powerful legendary warrior from the Movement universe with high power level"); let royalty_config = royalty::create(5, 100, signer::address_of(creator)); token::create_named_token( creator, string::utf8(b"Movement Gaming Assets"), description, character_name, option::some(royalty_config), string::utf8(b"https://gaming.movement.xyz/characters/warrior") ); } // Helper function to convert u64 to string (implementation omitted for brevity) fun u64_to_string(value: u64): String { // Implementation would convert u64 to string string::utf8(b"placeholder") } } ``` <Callout type="info"> You can derive the address for named tokens by: * Concatenating the creator address, collection name and token name * Doing a sha256 hash of that new string </Callout> ### Unnamed Tokens with Custom Properties Unnamed tokens receive unique, non-deterministic addresses at creation time. They offer more flexibility for dynamic minting scenarios where predictable addresses aren't required. Unnamed tokens are commonly used with custom properties stored as additional resources on the token object, enabling rich functionality like equipment stats, character progression, or any application-specific data. ```move module movement_addr::movement_equipment_nft { use aptos_token_objects::token::{Self, MutatorRef, BurnRef}; use aptos_token_objects::royalty; use aptos_framework::object::{Self, Object}; use aptos_framework::event; use std::string::{Self, String}; use std::option; use std::signer; /// Equipment NFT with custom properties struct MovementEquipment has key { mutator_ref: MutatorRef, burn_ref: BurnRef, equipment_type: String, rarity: String, stats: EquipmentStats, upgrade_level: u64, durability: u64, } /// Equipment statistics struct EquipmentStats has store, drop { attack: u64, defense: u64, speed: u64, special_ability: String, } #[event] struct EquipmentUpgraded has drop, store { token: address, old_level: u64, new_level: u64, new_stats: EquipmentStats, } /// Mint equipment NFT with custom properties public entry fun mint_equipment( creator: &signer, recipient: address, equipment_type: String, rarity: String, base_stats: EquipmentStats ) { let token_name = string::utf8(b"Movement Legendary Sword"); let description = string::utf8(b"A legendary sword forged in the Movement realm"); let royalty_config = royalty::create(3, 100, signer::address_of(creator)); let constructor_ref = &token::create( creator, string::utf8(b"Movement Gaming Assets"), description, token_name, option::some(royalty_config), string::utf8(b"https://gaming.movement.xyz/equipment/sword") ); // Generate refs for customization let mutator_ref = token::generate_mutator_ref(constructor_ref); let burn_ref = token::generate_burn_ref(constructor_ref); let token_signer = &object::generate_signer(constructor_ref); // Store custom equipment data move_to(token_signer, MovementEquipment { mutator_ref, burn_ref, equipment_type, rarity, stats: base_stats, upgrade_level: 1, durability: 100, }); // Transfer to recipient let token = object::object_from_constructor_ref<token::Token>(constructor_ref); object::transfer(creator, token, recipient); } /// Upgrade equipment NFT public entry fun upgrade_equipment( owner: &signer, token: `Object<token::Token>` ) acquires MovementEquipment { let token_addr = object::object_address(&token); assert!(object::is_owner(token, signer::address_of(owner)), 1); let equipment = borrow_global_mut<MovementEquipment>(token_addr); let old_level = equipment.upgrade_level; // Upgrade stats based on level equipment.upgrade_level = equipment.upgrade_level + 1; equipment.stats.attack = equipment.stats.attack + (equipment.upgrade_level * 5); equipment.stats.defense = equipment.stats.defense + (equipment.upgrade_level * 3); equipment.stats.speed = equipment.stats.speed + (equipment.upgrade_level * 2); // Update token description let new_description = string::utf8(b"A legendary sword (Level 2) forged in the Movement realm"); token::set_description(&equipment.mutator_ref, new_description); event::emit(EquipmentUpgraded { token: token_addr, old_level, new_level: equipment.upgrade_level, new_stats: equipment.stats, }); } // Helper function (implementation omitted for brevity) fun u64_to_string(value: u64): String { string::utf8(b"placeholder") } } ``` ## Token Operations ### Transfer Operations The Digital Asset standard enables direct NFT transfers without requiring recipient opt-in, simplifying the user experience. Transfers are performed using the `object::transfer` function, which moves ownership of the NFT object to the specified recipient address. ```move public entry fun transfer_nft( owner: &signer, nft: `Object<token::Token>`, recipient: address ) { object::transfer(owner, nft, recipient); } ``` ### Batch Operations For applications that need to transfer multiple NFTs in a single transaction, batch operations provide gas efficiency and atomic execution. The following pattern iterates through a list of NFTs and recipients to perform multiple transfers. ```move public entry fun batch_tra
프로젝트로 돌아가기