Movement 백서

Movement

원문

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

f txn_hash: # Read the message after setting it await client.get_message() else: print("\nTo interact with smart contracts, please set MODULE_ADDRESS in your .env file") if __name__ == "__main__": asyncio.run(main()) ``` ## Next Steps Now that you understand the basics of using the Python SDK with Movement: * **Explore More Functions**: The SDK supports many more operations like multi-signature transactions, token transfers, and complex smart contract interactions * **Error Handling**: Implement robust error handling for production applications * **Testing**: Write comprehensive tests for your smart contract interactions * **Security**: Never hardcode private keys in production code - use secure key management solutions ## Additional Resources * [Movement Network Documentation](/) * [Your First Move Contract Tutorial](/devs/firstMoveContract) This completes the Python SDK tutorial for interacting with the Movement network. The SDK provides a powerful and flexible way to build Python applications that interact with Movement smart contracts. # Rust SDK URL: /devs/interactonchain/rustSDK Aptos provides an official lightly supported Rust SDK in the Aptos-core GitHub repository. To use the Rust SDK, add the following dependency and patches on the git repo directly in your Cargo.toml, like this: ```toml [dependencies] aptos-sdk = { git = "https://github.com/aptos-labs/aptos-core", branch = "devnet" } [patch.crates-io] merlin = { git = "https://github.com/aptos-labs/merlin" } x25519-dalek = { git = "https://github.com/aptos-labs/x25519-dalek", branch = "zeroize_v1" } ``` You must also create a `.cargo/config.toml` file with this content: ```toml [build] rustflags = ["--cfg", "tokio_unstable"] ``` ## Usage Full example availables [here](https://github.com/aptos-labs/aptos-core/blob/main/sdk/examples/transfer-coin.rs). Network endpoints should be replaced with the appropriate [Movement endpoints](/devs/networkEndpoints). # TypeScript SDK URL: /devs/interactonchain/tsSdk # Movement TypeScript SDK <Callout type="info" className="py-6"> This Movement TS SDK repo is forked from [github.com/aptos-labs](https://github.com/aptos-labs) prior to the date on which the Aptos Foundation implemented its Innovation-Enabling Source Code License in substitution for the prior Apache License, Version 2.0 governing this repository. Move Industries continues to maintain, develop, modify, and distribute this repository solely under the Apache License, Version 2.0, as existed at the time of the fork and without application of the license instituted by the Aptos Foundation. </Callout> The [Movement TypeScript SDK](https://github.com/MoveIndustries/ts-sdk) allows you to interact with the Movement Network. The guide below will walk you through the process of setting up the SDK and interacting with the chain. ## Installation ```bash tab="npm" npm install @moveindustries/ts-sdk ``` ```bash tab="pnpm" pnpm add @moveindustries/ts-sdk ``` ```bash tab="yarn" yarn add @moveindustries/ts-sdk ``` ```bash tab="bun" bun add @moveindustries/ts-sdk ``` ## Imports To get started with the SDK, import the necessary components: ```javascript const { Account, Movement, MovementConfig, Network, Ed25519PrivateKey } = require("@moveindustries/ts-sdk"); ``` ## Configuration Configure the SDK to connect to the Movement Bardock Testnet (Please refer to [Network Endpoints](/devs/networkEndpoints) for more endpoints): ```javascript const config = new MovementConfig({ network: Network.CUSTOM, fullnode: 'https://testnet.movementnetwork.xyz/v1', faucet: 'https://faucet.testnet.movementnetwork.xyz/', }); // Initialize the Movement client const movement = new Movement(config); ``` ## Interacting with the Chain ### Account Setup ```javascript // Create an account from a private key const privateKey = new Ed25519PrivateKey("YOUR_PRIVATE_KEY") const account = Account.fromPrivateKey({ privateKey }) ``` ### Reading Data ```javascript // Example of reading data using view function const viewPayload = { function: "0x1::message::get_message", functionArguments: [accountAddress] }; const result = await movement.view({ payload: viewPayload }); ``` ### Sending Transactions ```javascript // Build the transaction const transaction = await movement.transaction.build.simple({ sender: accountAddress, data: { function: "0x1::message::set_message", functionArguments: ["Hello Movement!"] }, }); // Sign the transaction const signature = movement.transaction.sign({ signer: account, transaction }); // Submit the transaction const committedTxn = await movement.transaction.submit.simple({ transaction, senderAuthenticator: signature, }); // Wait for transaction completion const response = await movement.waitForTransaction({ transactionHash: committedTxn.hash }); ``` <Callout type="info"> Remember to replace `YOUR_PRIVATE_KEY` with your actual private key and never share or commit private keys to version control. </Callout> ## Example Code The Code below is based on the [Your First Move Contract tutorial](/devs/firstMoveContract). ```javascript const { Account, Movement, MovementConfig, Network, Ed25519PrivateKey } = require("@moveindustries/ts-sdk"); // Define the custom network configuration const config = new MovementConfig({ network: Network.CUSTOM, fullnode: 'https://testnet.movementnetwork.xyz/v1', faucet: 'https://faucet.testnet.movementnetwork.xyz/', }); // Define the module address and functions const MODULE_ADDRESS = ""; const SET_MESSAGE_FUNCTION = `${MODULE_ADDRESS}::message::set_message`; const GET_MESSAGE_FUNCTION = `${MODULE_ADDRESS}::message::get_message`; const PRIVATE_KEY = "YOUR_PRIVATE_KEY"; // Replace with your private key const MESSAGE = "gmove"; const setMessage = async () => { // Setup the client const movement = new Movement(config); // Create an account from the provided private key console.log("creating") const privateKey = new Ed25519PrivateKey(PRIVATE_KEY) const account = Account.fromPrivateKey({ privateKey }) const accountAddress = account.accountAddress console.log(`address: ${account.accountAddress}`) console.log(`Using account: ${accountAddress}`); // Build the transaction payload const payload = { function: SET_MESSAGE_FUNCTION, type_arguments: [], arguments: [MESSAGE], }; console.log("\n=== Reading Message ===\n"); const viewPayload = { function: GET_MESSAGE_FUNCTION, functionArguments: [accountAddress] } try { const message = await movement.view({ payload: viewPayload }); console.log("Message:", message); } catch (error) { console.error("Error reading message:", error); } // Submit the transaction console.log("\n=== Submitting Transaction ===\n"); const transaction = await movement.transaction.build.simple({ sender: accountAddress, data: { function: SET_MESSAGE_FUNCTION, functionArguments: [MESSAGE] }, }); // Sign the transaction const signature = movement.transaction.sign({ signer: account, transaction }); // Submit the transaction to chain const committedTxn = await movement.transaction.submit.simple({ transaction, senderAuthenticator: signature, }); console.log(`Submitted transaction: ${committedTxn.hash}`); const response = await movement.waitForTransaction({ transactionHash: committedTxn.hash }); console.log({ response }) // Read the message after it has been set console.log("\n=== Reading Message ===\n"); const newMessage = await movement.view({ payload: viewPayload }); console.log("Message:", newMessage); }; setMessage().catch((err) => { console.error("Error setting message:", err); }); ``` # Address URL: /devs/move-book/address # Address Type The `address` type represents unique identifiers for accounts and modules in Move. Think of addresses as unique locations where code and data can be stored. ## What is an Address? An address is a 256-bit identifier that serves as a unique location in the blockchain: * **Accounts**: Store resources and data * **Modules**: Store code and functions * **Packages**: Collections of modules at the same address ## Address Literals Addresses are written with the `@` symbol followed by a hexadecimal number: ```move let user_address = @0x1; let contract_address = @0x42; let long_address = @0xDEADBEEF; ``` ### Short and Long Form Move accepts both short and long address formats: ```move // Short form (Move pads with zeros) let addr1 = @0x1; // Same as @0x0000...0001 let addr2 = @0x42; // Same as @0x0000...0042 // Long form (explicit) let addr3 = @0x0000000000000000000000000000000000000000000000000000000000000001; ``` ## Named Addresses Instead of using hex numbers, you can use named addresses for better readability: ```move // In Move.toml or package configuration // std = "0x1" // my_package = "0x42" let std_addr = @std; // Refers to 0x1 let my_addr = @my_package; // Refers to 0x42 ``` ## Address Usage ### In Expressions When using addresses as values, always use the `@` prefix: ```move fun get_user_address(): address { @0x123 } let user = @0x456; ``` ### In Module Declarations When declaring modules, omit the `@` prefix: ```move module 0x42::my_module { // Module code here } // Or with named addresses module my_package::my_module { // Module code here } ``` ## Address Properties Addresses in Move are **opaque**, meaning: * You cannot create them from integers * You cannot perform arithmetic on them * You cannot modify them directly * They can only be compared for equality ```move let addr1 = @0x1; let addr2 = @0x2; // Valid operations let same = addr1 == addr1; // true let different = addr1 != addr2; // true // Invalid operations (won't compile) // let sum = addr1 + addr2; // ERROR! // let addr3 = addr1 * 2; // ERROR! ``` ## Practical Examples Here are common ways to use addresses: ```move // Check if an address owns a resource fun has_account(addr: address): bool { // Implementation would check global storage true // Simplified } // Compare addresses fun is_admin(user: address): bool { user == @0x1 // Check if user is admin address } // Store addresses in data structures struct UserInfo has key { owner: address, balance: u64, } ``` ## Global Storage Operations The primary purpose of `address` values is to interact with global storage. They are used with the following operations: * `exists<T>` * `borrow_global<T>` * `borrow_global_mut<T>` * `move_from<T>` Note that the `move_to<T>` operation does not use an `address` but instead requires a `signer`. ## Ownership As with the other scalar values built-in to the language, address values are implicitly copyable, meaning they can be copied without an explicit instruction such as `copy`. ## Summary Addresses in Move: * **Identify locations** for accounts and modules * **Use `@` prefix** when used as values * **Support named aliases** for better readability * **Are opaque** - no arithmetic operations allowed * **Are copyable** - no explicit `copy` needed * **Enable access** to global storage and resources Addresses are fundamental to Move's security model, ensuring that resources and modules have clear ownership and access patterns. # Assertion and Abortion URL: /devs/move-book/assertionAndAbortion # Assertion and Abortion `return` and `abort` are two control flow constructs that end execution: one for the current function and one for the entire transaction. While `return` exits the current function, `abort` halts execution and reverts all changes made to global state by the current transaction. ## Abort `abort` is an expression that takes one argument: an abort code of type `u64`. For example: ```move abort 42 ``` The `abort` expression halts execution of the current function and reverts all changes made to global state by the current transaction. There is no mechanism for "catching" or otherwise handling an abort. ### Transaction Semantics In Move, transactions are all-or-nothing, meaning any changes to global storage are made all at once only if the transaction succeeds. Because of this transactional commitment of changes, after an abort there is no need to worry about backing out changes. While this approach is lacking in flexibility, it is incredibly simple and predictable. Similar to `return`, `abort` is useful for exiting control flow when some condition cannot be met. ### Basic Usage Example In this example, the function will withdraw funds from an account, but will abort early if there are insufficient funds: ```move fun withdraw_funds(balance: &mut u64, amount: u64): u64 { if (*balance < amount) abort 42; *balance = *balance - amount; amount } #[test] public fun test_withdraw_funds() { let balance = 100u64; let safe_withdrawn = withdraw_funds(&mut balance, 50u64); // This will not abort let withdrawn = withdraw_funds(&mut balance, 225u64); // This will abort } ``` ### Complex Control Flow Example This is even more useful deep inside a control-flow construct. For example, this function validates that all ages in a list are within legal limits and aborts otherwise: ```move use std::vector; fun validate_ages(ages: &vector<u8>, max_age: u8) { let i = 0; let n = vector::length(ages); while (i < n) { let age = *vector::borrow(ages, i); if (age > max_age) abort 42; i = i + 1; } } ``` ## Assert `assert` is a builtin, macro-like operation provided by the Move compiler. It takes two arguments: a condition of type `bool` and a code of type `u64`: ```move assert!(condition: bool, code: u64) ``` Since the operation is a macro, it must be invoked with the `!`. This is to convey that the arguments to `assert` are call-by-expression. In other words, `assert` is not a normal function and does not exist at the bytecode level. It is replaced inside the compiler with: ```move if (condition) () else abort code ``` ### Assert vs Abort `assert` is more commonly used than just `abort` by itself. The abort examples above can be rewritten using `assert`: ```move fun withdraw_funds(balance: &mut u64, amount: u64): u64 { assert!(*balance >= amount, 42); // Now uses 'assert' *balance = *balance - amount; amount } ``` And: ```move use std::vector; fun validate_ages(ages: &vector<u8>, max_age: u8) { let i = 0; let n = vector::length(ages); while (i < n) { let age = *vector::borrow(ages, i); assert!(age <= max_age, 42); // Now uses 'assert' i = i + 1; } } ``` ### Lazy Evaluation Note that because the operation is replaced with an if-else, the argument for the code is not always evaluated. For example: ```move assert!(true, 1 / 0) ``` Will not result in an arithmetic error, it is equivalent to: ```move if (true) () else (1 / 0) ``` So the arithmetic expression is never evaluated! ## Abort Codes in the Move VM When using `abort`, it is important to understand how the `u64` code will be used by the VM. Normally, after successful execution, the Move VM produces a change-set for the changes made to global storage (added/removed resources, updates to existing resources, etc). If an abort is reached, the VM will instead indicate an error. Included in that error will be two pieces of information: * The module that produced the abort (address and name) * The abort code ### Example Error Information ```move module 0x2::bank { public fun transfer_funds() { abort 42 } } ``` ```move script { fun failed_transfer() { 0x2::bank::transfer_funds() } } ``` If a transaction, such as the script `failed_transfer` above, calls `0x2::bank::transfer_funds`, the VM would produce an error that indicated the module `0x2::bank` and the code `42`. ## Using Constants for Error Codes This can be useful for having multiple aborts being grouped together inside a module. It's a best practice to use constants to define error codes: ```move module 0x42::account { const INSUFFICIENT_BALANCE: u64 = 0; const INVALID_AMOUNT: u64 = 1; const ACCOUNT_FROZEN: u64 = 2; struct Account has key { balance: u64, is_frozen: bool, } public fun transfer(from: &mut Account, to: &mut Account, amount: u64) { assert!(!from.is_frozen, ACCOUNT_FROZEN); assert!(!to.is_frozen, ACCOUNT_FROZEN); assert!(amount > 0, INVALID_AMOUNT); assert!(from.balance >= amount, INSUFFICIENT_BALANCE); from.balance = from.balance - amount; to.balance = to.balance + amount; } public fun withdraw(account: &mut Account, amount: u64): u64 { assert!(!account.is_frozen, ACCOUNT_FROZEN); assert!(amount > 0, INVALID_AMOUNT); assert!(account.balance >= amount, INSUFFICIENT_BALANCE); account.balance = account.balance - amount; amount } } ``` ### Benefits of Using Constants Using constants for error codes provides several advantages: * **Readability**: Code is more self-documenting * **Maintainability**: Easy to update error codes in one place * **Consistency**: Prevents duplicate or conflicting error codes * **Documentation**: Constants can be documented with comments ## Type Flexibility The `abort` expression can have any type since it breaks normal control flow and never needs to evaluate to an actual value: ```move let account: address = abort 0; // This will abort with error code 0 // Useful in branching scenarios let account_status = if (balance >= 1000) b"premium" else if (balance > 0) b"active" else abort 42; // Has type `vector<u8>` ``` ## Best Practices * Use **named constants** for error codes * Prefer `assert!` over manual `if-abort` patterns * Keep error codes **unique** within modules * **Document** error conditions clearly ## Summary Move's `abort` and `assert!` provide robust error handling for transaction safety: * **`abort`** immediately halts execution and reverts all transaction changes * **`assert!`** offers cleaner syntax for conditional aborts * **Error codes** help identify specific failure points in the VM * **Constants** make error codes maintainable and self-documenting * All aborts are **transaction-level** - there's no partial failure recovery Use these constructs to enforce invariants and handle exceptional conditions while maintaining Move's transactional guarantees. # Boolean URL: /devs/move-book/bool # Boolean Type The `bool` type represents boolean values in Move - either `true` or `false`. Booleans are essential for making decisions and controlling program flow. ## Boolean Literals There are only two boolean values in Move: ```move let is_active = true; let is_complete = false; ``` The compiler can always infer the `bool` type, so explicit type annotations are optional: ```move let flag: bool = true; // Explicit type let flag = true; // Type inferred ``` ## Logical Operations Move supports three logical operations for booleans: ### AND (`&&`) Returns `true` only if both operands are `true`: ```move let result = true && true; // true let result = true && false; // false let result = false && true; // false ``` ### OR (`||`) Returns `true` if at least one operand is `true`: ```move let result = true || false; // true let result = false || true; // true let result = false || false; // false ``` ### NOT (`!`) Inverts the boolean value: ```move let result = !true; // false let result = !false; // true ``` ## Short-Circuit Evaluation Logical operators use short-circuit evaluation: * `&&` stops evaluating if the first operand is `false` * `||` stops evaluating if the first operand is `true` ```move let x = 5; let result = (x > 10) && (x < 20); // Second condition not checked ``` ## Comparison Operations Booleans are often created from comparison operations: ```move let age = 25; let is_adult = age >= 18; // true let is_senior = age >= 65; // false let is_young_adult = age >= 18 && age <= 30; // true ``` ## Control Flow Usage Booleans are primarily used in control flow statements: ```move let score = 85; let passed = score >= 60; if (passed) { // Execute if true } else { // Execute if false } ``` ## Practical Examples Here are some common boolean usage patterns: ```move fun check_eligibility(age: u8, has_license: bool): bool
프로젝트로 돌아가기