Movement 백서

Movement

원문

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

ctor and pushing one item. ```move use std::vector; let single_element_vec = vector::singleton<u64>(100); // single_element_vec is now [100] ``` ### `destroy_empty` Destroys an empty vector. This is necessary for vectors containing elements that do not have the `drop` ability. If the vector is not empty, the operation will abort. ```move use std::vector; let empty_vec = vector::empty<u64>(); vector::destroy_empty(empty_vec); // This is successful let non_empty_vec = vector[1]; // vector::destroy_empty(non_empty_vec); // This would abort! ``` ## Practical Examples Here are common vector usage patterns: ```move // Managing a list of user addresses fun add_user(users: &mut vector<address>, new_user: address) { if (!vector::contains(users, &new_user)) { vector::push_back(users, new_user); } } // Processing scores fun calculate_average(scores: &vector<u64>): u64 { let sum = 0; let i = 0; let len = vector::length(scores); while (i < len) { sum += *vector::borrow(scores, i); i += 1; }; if (len == 0) { len } else { sum / len } } // Working with byte data fun create_message(): vector<u8> { let message = b"Hello, "; vector::append(&mut message, b"Move!"); message // Returns b"Hello, Move!" } ``` ## Destroying and Copying Vectors The behavior of a `vector<T>` can depend on the abilities of its element type, `T`. ### Dropping Vectors Vectors containing elements that do not have the `drop` ability cannot be implicitly discarded. They must be explicitly destroyed using `vector::destroy_empty`, which aborts if the vector is not empty. ```move fun destroy_any_vector<T>(vec: vector<T>) { vector::destroy_empty(vec); // This is required. } ``` However, if a vector's elements have the `drop` ability, the vector can be dropped without any explicit action, and its contents will be properly destroyed. ```move fun destroy_droppable_vector<T: drop>(vec: vector<T>) { // Valid! No explicit action is needed to destroy the vector. } ``` ### Copying Vectors A `vector<T>` has the `copy` ability if and only if its element type `T` has `copy`. However, even copyable vectors are never implicitly copied. You must use an explicit `copy` instruction. ```move let v1 = vector::singleton<u64>(10); let v2 = copy v1; // An explicit `copy` is required. // let v3 = v1; // This would be a compiler error! ``` This design choice makes expensive copies of large vectors obvious in the code. For more details, see the sections on **type abilities** and **generics**. ## Safety and Performance ### Index Bounds Vector operations check bounds automatically: ```move let numbers = vector[1, 2, 3]; // let item = vector::borrow(&numbers, 5); // Would abort! Index out of bounds ``` ### Memory Management Vectors automatically manage memory: * Elements are automatically cleaned up when the vector is dropped * Efficient resizing as elements are added ## Ownership A `vector<T>` can only be copied if the element type `T` has the copy ability. Move does not allow implicit copies of vectors. You must explicitly perform the copy using either: the copy keyword, or a dereference (\*). ## Summary Vectors in Move are: * **Dynamic collections** that can grow and shrink * **Type-safe** - all elements must be the same type * **Indexed** - access elements by position (0-based) * **Bounds-checked** - operations abort on invalid indices * **Memory-safe** - automatic cleanup and management Common use cases include: * Storing lists of addresses, IDs, or other data * Managing collections that change size during execution * Working with byte data and strings * Building more complex data structures Vectors are essential for most Move programs that need to work with collections of data. # Token Standards URL: /devs/tokenStandard/overview ## Overview Standards define the behavior and structure of essential blockchain features, including tokens, wallets, and on-chain objects. They ensure seamless interoperability between contracts from different developers, enabling assets to maintain consistent appearance, predictable interactions, and universal support across wallets and marketplaces. Movement implements three primary standard categories: * **Move Standards** — Core object model defining data and resource structure * **Asset Standards** — Formal specifications for tokens and NFTs * **Legacy Standards** — Older token systems maintained for backward compatibility *** ## Move Object Model Movement leverages the **Move Object Model** to represent real-world entities on-chain. Rather than creating custom contract layouts for each use case, developers utilize a standardized object-based format. These objects encapsulate resources with strict ownership, transfer, and mutation rules, significantly reducing bugs and enhancing composability. **Key Benefits:** * Provides the foundation for all asset standards (fungible and non-fungible) * Enforces safety guarantees through type system constraints * Eliminates common vulnerabilities associated with ad-hoc implementations *** ## Current Asset Standards The current standards represent the modern approach to token and asset management on Movement. ### Digital Asset (DA) Standard The Digital Asset standard is the recommended framework for non-fungible and semi-fungible assets. **Core Features:** * Tokens implemented as Move Objects * NFTs organized within collections with comprehensive metadata support * Direct transfer capability without recipient opt-in requirements * Composable architecture allowing NFTs to own other NFTs <Callout type="info"> All new NFT projects should implement the DA standard to ensure maximum flexibility and ecosystem compatibility. </Callout> ### Fungible Asset (FA) Standard The Fungible Asset standard provides a comprehensive framework for representing fungible tokens. **Design Principles:** * Type-safe token operations with compile-time guarantees * Automatic recipient storage initialization * Granular control over minting, burning, transfers, and permission management * Enhanced flexibility for diverse applications **Advantages Over Legacy Systems:** FA offers superior expressiveness and adaptability compared to the older Coin standard, making it suitable for use cases ranging from currencies to in-game assets. *** ## Legacy Standards While current standards are recommended for all new development, legacy standards remain supported to ensure backward compatibility with existing applications. ### Token (Legacy) The [Token](https://github.com/movement-network/aptos-core/blob/m1/aptos-move/framework/aptos-token/sources/token.move) standard provides a versatile framework for managing multiple token types within a single implementation. * **Versatile multi-token support** - Handles NFTs, fungibles, and semi-fungibles in a single standard * **Customizable properties** - Offers flexible on-chain property configuration * **Backward compatible** - Remains functional for existing applications ### Coin (Legacy) The [Coin](https://github.com/movement-network/aptos-core/blob/m1/aptos-move/framework/aptos-framework/sources/coin.move) standard offers a straightforward approach to fungible token implementation with high performance and low gas overhead. * **Simple fungible implementation** - Straightforward token standard for fungible assets * **Superseded standard** - Replaced by the more capable Fungible Asset standard * **Continued support** - Still functional for existing deployments # Build URL: /devs/tutorials/build In this guide, we will learn how to build an end-to-end "onchain bio" dApp. We'll start with the Move contract. Then we'll build a React frontend and let wallets connect and register a bio. ## Requirements Make sure to have [Movement CLI](/devs/movementcli) installed. <Callout type="info"> If you are using Aptos CLI - ensure that you are using version 3.5 or lower. </Callout> View an example of the finished dApp [here](https://github.com/movement-network/onchain-bio-dapp). ## Initialize your Environment Initialize your profile for your package development and add Movement as a custom network. Movement is our current blockchain that supports Aptos deployments. ```bash movement init ``` ## Setup Create a new directory and navigate into it: ```bash mkdir my-onchain-bio && cd my-onchain-bio ``` Open a code editor so you can see your dApp's file structure. Here we'll use VS Code: ```bash code . ``` ## Creating and publishing the Onchain Bio smart contract Now that our environment is set up, let's write some code, starting with the Move contract! First, create a move directory and navigate into it: ```bash mkdir move && cd move ``` Then create a move project, containing code for an onchain package: ```bash movement move init --name my_todo_list ``` Your file structure should now look like this: ![folder\_structure](./imgs/structure.webp) ## Creating a Move Module Create a new file named onchain\_bio.move within the sources directory and add the following to that file: ```rust module onchain_bio_addr::onchain_bio { use std::string::{String}; use std::signer; struct Bio has key, store, drop { name: String, bio: String, } #[view] public fun signature() : address { @<address> } public entry fun register(account: &signer, name: String, bio: String) acquires Bio { // Check if a Bio already exists for the account if (exists<Bio>(signer::address_of(account))) { // Remove the existing Bio let _old_Bio = move_from<Bio>(signer::address_of(account)); }; // Create the new Bio let bio = Bio { name, bio, }; // Store the new Bio under the account move_to<Bio>(account, bio); } } ``` Next, let's deploy to testnet! ## Deploying the Module to Movement's Testnetwork First, from within the move directory, initialize your Movement configuration: ```bash movement init ``` When asked for a private key, press Enter to generate a new keypair. Upon successful initialization, you'll see the success message (with your own account instead of the one below): ```json No key given, generating key... Account 0x39883cbc29500a8bf79911ea1469e1c3b58104547a88fb0fbdf17470f80b2a91 doesn't exist, creating it and funding it with 100000000 Octas Account 0x39883cbc29500a8bf79911ea1469e1c3b58104547a88fb0fbdf17470f80b2a91 funded successfully --- Movement CLI is now set up for account 0x39883cbc29500a8bf79911ea1469e1c3b58104547a88fb0fbdf17470f80b2a91 as profile default! Run `movement --help` for more information about commands { "Result": "Success" } ``` Now your move directory will contain a hidden .movement folder containing a config.yaml file. You can view the contents of that file to see your private and public keys. In the line under \[addresses] in Move.toml, add your account address: ```json onchain_bio_addr = "<your-account-address>" ``` After compiling, you'll see a result message formatted like this: ```json { "Result": [ "39883cbc29500a8bf79911ea1469e1c3b58104547a88fb0fbdf17470f80b2a91::onchain_bio" ] } ``` Now you can publish the package: ```bash movement move publish ``` After confirming that the price is okay, your transaction will be submitted to the blockchain. You'll get a result formatted like this, with values associated with your transaction: ```json { "Result": { "transaction_hash": "0x37ea722ad4f1ff0d8d0710965a47354cc903579d38b659d90c4286ddab946151", "gas_used": 1236, "gas_unit_price": 100, "sender": "39883cbc29500a8bf79911ea1469e1c3b58104547a88fb0fbdf17470f80b2a91", "sequence_number": 0, "success": true, "timestamp_us": 1707748417269022, "version": 248, "vm_status": "Executed successfully" } } ``` Congratulations! Your module is now deployed. Let's shift over to the frontend. ## Building a React app for users to register and view their onchain bio Navigate to the root of our project directory: ``` cd .. ``` Create a new React app named `client`: ``` npx create-react-app client --template typescript ``` At the root of your project, you'll have two directories: `client` and `move`. cd into the client directory and run `npm start`. Your app should now be running on [http://localhost:3000](http://localhost:3000), displaying the default React layout. Your apps files are in the `client/src` directory. Replace the code in `Index.tsx` with the following: ```jsx import { PetraWallet } from "petra-plugin-wallet-adapter"; import { AptosWalletAdapterProvider } from "@aptos-labs/wallet-adapter-react"; import React from "react"; import ReactDOM from "react-dom/client"; import App from "./App"; import reportWebVitals from "./reportWebVitals"; import './index.css'; const wallets = [new PetraWallet()]; const root = ReactDOM.createRoot(document.getElementById("root") as HTMLElement); root.render( <React.StrictMode> <AptosWalletAdapterProvider plugins={wallets} autoConnect={true}> <App /> </AptosWalletAdapterProvider> </React.StrictMode>, ); reportWebVitals(); ``` This wraps our app in the `<AptosWalletAdapterProvider /> ` tag so we can connect a wallet. To add support for more wallets, see the [Aptos Wallet Adapter README](https://github.com/aptos-labs/aptos-wallet-adapter#supported-wallet-packages). Now replace your App.tsx code with the following: ```jsx import { WalletSelector } from "@aptos-labs/wallet-adapter-ant-design"; import "@aptos-labs/wallet-adapter-ant-design/dist/index.css"; import { useRef, useState, useEffect } from "react"; import { useWallet, InputTransactionData } from '@aptos-labs/wallet-adapter-react'; import { Movement, MovementConfig, Network } from "@moveindustries/ts-sdk"; import { ONCHAIN_BIO } from "./constants"; import './index.css'; // with custom configuration const movementConfig = new MovementConfig({ network: Network.CUSTOM }); const movement = new Movement(movementConfig); function App() { const { signAndSubmitTransaction, account } = useWallet(); const name = useRef<HTMLInputElement>(null); const bio = useRef<HTMLTextAreaElement>(null); const [accountHasBio, setAccountHasBio] = useState(false); const [currentName, setCurrentName] = useState(null); const [currentBio, setCurrentBio] = useState(null); const fetchBio = async () => { if (!account) { console.log("No account") return []; } try { const bioResource = await movement.getAccountResource( { accountAddress:account?.address, resourceType:`${ONCHAIN_BIO}::onchain_bio::Bio` } ); console.log("Name:", bioResource.name, "Bio:", bioResource.bio); setAccountHasBio(true); if (bioResource) { setCurrentName(bioResource.name); setCurrentBio(bioResource.bio); } else { console.log("no bio") } } catch (e: any) { setAccountHasBio(false); } }; async function registerBio() { if (bio.current !== null && name.current !== null) { const onchainName = name.current.value; const onchainBio = bio.current.value; const transaction: InputTransactionData = { data: { function:`${ONCHAIN_BIO}::onchain_bio::register`, functionArguments:[onchainName, onchainBio] } } try { // sign and submit transaction to chain const response = await signAndSubmitTransaction(transaction); // wait for transaction console.log(`Success! View your transaction at https://explorer.movementnetwork.xyz/txn/${response.hash}?network=bardock+testnet`) await movement.waitForTransaction({transactionHash:response.hash}); fetchBio(); } catch (error: any) { console.log("Error:", error) } } } return ( <> <div className="navbar"> <div className="navbar-text">Your Onchain Bio</div> <div> <WalletSelector /> </div> </div> <div className="center-container"> <div className="row"> <h1>You Onchain Bio</h1> </div> <div className="row"> <h3>Your name:</h3> </div> <div className="row"> <input ref={name} type="text" className="name" placeholder="Enter your name"/> </div> <div className="row"> <h3>Your Bio:</h3> </div> <div className="row"> <textarea ref={bio} className="bio" placeholder="Your onchain bio" /> </div> <div className="row"> <button onClick={registerBio}>Register Bio</button> </div> <div className="row"> <button onClick={fetchBio}>Fetch Bio</button> </div> <div className="row"> <center> <h3>Your Name:</h3> <p>{currentName}</p> </center> </div> <div className="row"> <center> <h3>Your Bio:</h3> <p>{currentBio}</p> </center> </div> </div> </> ); } export default App; ``` Lastly replace the code in the `index.css` ```css :root { font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif; line-height: 1.5; font-weight: 400; font-synthesis: none; text-rendering: optimizeLegibility; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; -webkit-text-size-adjust: 100%; } body { margin: 0; } h1, h3 { margin-bottom: 5px; } h3 { margin-top: 0; } .navbar { display: flex; justify-content: space-between; align-items: center; background-color: #333; color: #fff; padding: 10px 20px; } .navbar-text { font-size: 20px; } .center-container { display: flex; flex-direction: column; align-items: center; height: 100vh; /* Adjust this to control vertical centering */ } .row { display: flex; justify-content: center; } .name { margin-bottom: 10px; width: 200px; } .bio { margin-bottom: 10px; width: 300px; height: 200px; resize: vertical; } ``` Your locally-running app should now look like this: ![app](./imgs/localapp.png) Feel free to style the app however you prefer. ## Using your App To use the dApp, first configure an Aptos wallet to testnet. Head over to the [Movement Faucet](https://faucet.movementnetwork.xyz/) and fund your wallet. Enter a name and bio. Click the Register Bio button. The wallet should pop up for you to sign. After the transaction has been submitted to the blockchain, you'll see your onchain bio information updated: ![apupdate](./imgs/localupdated.png) ## What dApps will you build on Movement? Now you know how to deploy an Aptos dApp for testnet. Check out `onchain_bio.move` logic, try a redeployment by tinkering with it. As a challenge, try modifying the Front End to better display your name and bio! We can't wait to see what dApps you build and deploy to Movement Network! # Deploy URL: /devs/tutorials/deploy 🚀 If you already have a Move module written, you can deploy it to the Movement Network using the Movement CLI or Aptos CLI. For a full guide on how to install the CLI and get your development environment setup, please see our [First Move Module](/devs/firstMoveContract) guide. ## Check Config Ensure your `config.yaml` is configured to the correct network for the profile you are using. This can be found in the `.movement` directory at the root of your project. ``` --- profiles: default: network: Custom private_key: "0xYOUR_PRIVATE_KEY" public_key: "0xYOUR_PRIVATE_KEY" account: "account_address" rest_url: "https://testnet.movementnetwork.xyz/v1" faucet_url: "https://faucet.testnet.movementnetwork.xyz/" ``` ## Add Address to Move.Toml To make compiling, testing, and of course deploying your Move module easier, you can add your address to the `move.toml` file at the root of your Move project. ``` [addresses] default = "YOUR_ADDRESS" ``` ## Deploy to Movement Network Run the following command to deploy your Move module to the Movement Network: ``` movement move publish ``` You'll be prompted to confirm the transaction and spend a small amount of testnet tokens: ``` Do you want to submit this transaction? [Y/n] ``` Type `Y` and press **Enter**. > **Ensure you have sufficient testnet tokens from the faucet before proceeding.** # Move Slayers (On-chain RPG) URL: /devs/tutorials/move_slayers # 🎮 Building an On-Chain RPG with Move: A Complete Educational Guide This guide walks through every line of code in the [`move_slayers`](https://github.com/movement-network/move-slayers) game, explaining how to build an on-chain RPG using the Move language on Movement. ## 📚 What You'll Learn * **Move Language Fundamentals**: Structs, functions
프로젝트로 돌아가기