Movement 백서

Movement

원문

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

{ age >= 18 && has_license } fun is_even(number: u64): bool { number % 2 == 0 } fun is_in_range(value: u64, min: u64, max: u64): bool { value >= min && value <= max } ``` ## Ownership As with the other scalar values built-in to the language, boolean values are implicitly copyable, meaning they can be copied without an explicit instruction such as `copy`. ## Summary Booleans are simple but powerful: * Only two values: `true` and `false` * Support logical operations: `&&`, `||`, `!` * Use short-circuit evaluation for efficiency * Essential for control flow and decision making * Automatically copyable (no explicit `copy` needed) # Coding Conventions URL: /devs/move-book/codingCovention # Coding Conventions Move coding conventions promote consistency, readability, and maintainability across projects. These guidelines help teams collaborate effectively and make codebases easier to understand and maintain. **Key principles:** * **Consistency**: Uniform naming and formatting across all code * **Clarity**: Names should clearly express intent and purpose * **Maintainability**: Code should be easy to read and modify * **Community alignment**: Follow established Move ecosystem patterns While these are recommendations rather than strict requirements, following them helps create more professional and maintainable Move code that integrates well with the broader ecosystem. ## Naming Conventions ### Modules Use **lower\_snake\_case** for module names: ```move module 0x42::fixed_point32 { // Module implementation } module 0x42::token_registry { // Module implementation } ``` **Guidelines:** * Use descriptive names that indicate the module's purpose * Prefer full words over abbreviations * Keep names concise but clear ### Types and Structs Use **PascalCase** for custom types and structs: ```move module 0x42::defi { struct LiquidityPool has key { token_a: u64, token_b: u64, } struct UserAccount has key { balance: u64, role_id: RoleId, } struct RoleId has copy, drop { value: u8 } } ``` **Guidelines:** * Start with uppercase letter * Use descriptive names that indicate the data's purpose * Native types (u64, bool, address) remain lowercase ### Functions Use **lower\_snake\_case** for function names: ```move module 0x42::utils { public fun create_account(owner: &signer): Account { // Function implementation } public fun destroy_empty_container<T>(container: Container<T>) { // Function implementation } fun calculate_interest_rate(principal: u64, time: u64): u64 { // Function implementation } } ``` **Guidelines:** * Use verbs that describe what the function does * Be specific about the action performed * Avoid abbreviations unless they're widely understood ### Constants Use different conventions based on the constant's purpose: ```move module 0x42::errors { // Error codes: E + PascalCase const EInsufficientBalance: u64 = 1; const EInvalidPermission: u64 = 2; const EResourceNotFound: u64 = 3; // Non-error values: UPPER_SNAKE_CASE const MAX_SUPPLY: u64 = 1_000_000; const MIN_STAKE_AMOUNT: u64 = 100; const DEFAULT_FEE_RATE: u64 = 25; // 0.25% } ``` **Guidelines:** * **Error codes**: Start with `E` followed by PascalCase description * **Configuration values**: Use UPPER\_SNAKE\_CASE * Include comments for non-obvious values ### Generic Type Parameters Use descriptive names that indicate the parameter's role: ```move module 0x42::containers { struct Vault<Asset> has key { contents: Asset } struct Pair<TokenA, TokenB> has store { first: TokenA, second: TokenB, } // Single generic can use T when context is clear struct Box<T> has copy, drop { value: T } } ``` **Guidelines:** * Use descriptive names for domain-specific generics (`Asset`, `Currency`) * Use `T` only when the type is truly generic * For multiple generics, use meaningful names (`TokenA`, `TokenB`) ## File Naming ### Module Files File names should match the module name exactly: ``` // File: fixed_point32.move module 0x42::fixed_point32 { ... } // File: token_registry.move module 0x42::token_registry { ... } ``` ### Script Files Use **lower\_snake\_case** matching the main function: ``` // File: create_account.move script { fun create_account(account: signer) { ... } } // File: transfer_tokens.move script { fun transfer_tokens(from: signer, to: address, amount: u64) { ... } } ``` ### Mixed Files For files containing multiple modules or scripts, use descriptive **lower\_snake\_case**: ``` // File: defi_utils.move - contains multiple related modules module 0x42::liquidity_pool { ... } module 0x42::swap_router { ... } module 0x42::price_oracle { ... } ``` ## Code Organization ### Module Structure Organize module contents in a consistent order: ```move module 0x42::token { // 1. Imports use std::signer; use std::vector; // 2. Friend declarations (if any) friend 0x42::token_registry; // 3. Constants const MAX_SUPPLY: u64 = 1_000_000; const EInsufficientBalance: u64 = 1; // 4. Structs struct Token has key { supply: u64, decimals: u8, } // 5. Functions (public first, then private) public fun create_token(creator: &signer): Token { ... } fun validate_amount(amount: u64): bool { ... } } ``` ## Best Practices * Choose names that express intent clearly * Use consistent terminology throughout the project * Group related functionality together * Keep modules focused on a single responsibility ## Summary Move coding conventions promote consistency and readability through: * **Naming patterns**: lower\_snake\_case for modules and functions, PascalCase for types, UPPER\_SNAKE\_CASE for constants * **Generic naming**: Use descriptive names for generics * **File organization**: File names should match module names * **Code structure**: Organize code with clear structure * **Benefits**: Creates professional, maintainable code that integrates well with the Move ecosystem # Conditional URL: /devs/move-book/conditional # Conditional Conditionals are fundamental control flow constructs that allow programs to make decisions based on runtime values. An `if` expression specifies that some code should only be evaluated if a certain condition is true. ## Basic If Expression The simplest form of a conditional expression: ```move if (temperature > 30) is_hot = true ``` The condition must be an expression of type `bool`. If the condition evaluates to `true`, the expression following the condition is executed. ## If-Else Expression An `if` expression can optionally include an `else` clause to specify another expression to evaluate when the condition is false: ```move if (speed <= 60) speed = speed + 5 else speed = 60 ``` Either the "true" branch or the "false" branch will be evaluated, but not both. Either branch can be a single expression or an expression block. ## Conditional Expressions with Values The conditional expressions may produce values so that the `if` expression has a result: ```move let price = if (quantity < 10) quantity * 5 else quantity * 4; ``` This allows conditionals to be used in assignments and other expressions where a value is expected. ## Type Compatibility The expressions in the true and false branches must have compatible types: ```move // width and height must be u64 integers let larger_dimension: u64 = if (width > height) width else height; ``` ### Type Errors Branches with incompatible types will result in compilation errors: ```move // ERROR! branches different types let result = if (is_valid < 10) 10u8 else 100u64; // ERROR! branches different types, as default false-branch is () not u64 if (score >= 10) score; ``` ## Default Else Clause If the `else` clause is not specified, the false branch defaults to the unit value `()`. The following are equivalent: ```move if (is_ready) start_process // implied default: else () if (is_ready) start_process else () ``` This means that when no `else` clause is provided, the `if` expression returns the unit type `()` when the condition is false. ## Expression Blocks Commonly, `if` expressions are used in conjunction with expression blocks for more complex logic: ```move let total_cost = if (items > 5) items * 8 else items * 10; if (total_cost < 50) { shipping_fee = 5; tax_rate = 8; } else if (total_cost >= 50 && total_cost < 100) { shipping_fee = 0; tax_rate = 10; } ``` ## Nested Conditionals You can chain multiple conditions using `else if`: ```move let shipping_method = if (weight <= 1) { b"standard" } else if (weight <= 5) { b"express" } else if (weight <= 20) { b"freight" } else { b"special_handling" }; ``` ## Practical Examples ### Temperature Control ```move fun adjust_temperature(current: u64, target: u64): u64 { if (current < target) { current + 2 } else if (current > target) { current - 2 } else { current } } ``` ## Complex Conditions Conditionals can use complex boolean expressions with logical operators: ```move fun can_access_system(role: u8, is_active: bool, has_permission: bool): bool { if (role >= 2 && is_active && has_permission) { true } else { false } } ``` ## Performance Considerations Due to short-circuit evaluation in logical operators, structure conditions efficiently: ```move // Efficient: check simple condition first if (is_online && complex_validation()) { // process request } // Less efficient: complex check might run unnecessarily if (complex_validation() && is_online) { // process request } ``` ## Grammar The formal grammar for conditional expressions: ``` if-expression → if ( expression ) expression else-clause? else-clause → else expression ``` ## Best Practices * **Use meaningful conditions** - Make boolean expressions clear and readable * **Consistent return types** - Ensure both branches return compatible types * **Avoid deep nesting** - Use `else if` chains instead of deeply nested conditionals * **Structure conditions efficiently** - Put simple checks before complex ones ## Summary Move's conditional expressions provide: * **Decision making** based on boolean conditions * **Value production** through if-else expressions * **Type safety** with compile-time branch compatibility checks * **Flexible syntax** supporting both simple and complex logic Conditionals are essential for implementing business logic, validation, and control flow in Move programs. # Constants URL: /devs/move-book/constants # Constants Constants in Move are immutable named values that are defined at the module or script level. They provide a way to give meaningful names to static values that are used throughout your code, improving readability and maintainability. Constants are evaluated at compile time and stored in the module's bytecode, with their values being copied each time they are used. ## Declaration Syntax Constants are declared using the `const` keyword followed by a name, type annotation, and value: ```move const <NAME>: <type> = <expression>; ``` ### Naming Convention Constants must follow specific naming rules: * Must be in **SCREAMING\_SNAKE\_CASE** (all uppercase with underscores) * Must start with a letter `A-Z` * Can contain letters, digits, and underscores after the first character ```move // Valid constant names const MAX_SUPPLY: u64 = 1000000; const DEFAULT_FEE_RATE: u8 = 5; const ADMIN_ADDRESS: address = @0x1; const ERROR_INSUFFICIENT_BALANCE: u64 = 1001; // Invalid constant names // const maxSupply: u64 = 1000000; // Error: not SCREAMING_SNAKE_CASE // const 1ST_CONSTANT: u64 = 100; // Error: starts with digit ``` ## Supported Types Constants are limited to primitive types and `vector<u8>` (byte strings): ```move // Primitive types const IS_ENABLED: bool = true; const SAMPLE_U8: u8 = 200; const SAMPLE_U16: u16 = 1000; const SAMPLE_U32: u32 = 1000000; const SAMPLE_U64: u64 = 1000000; const SAMPLE_U128: u128 = 1000000; const SAMPLE_U256: u256 = 1000000; // Address type const TREASURY_ADDRESS: address = @0xCAFE; const ZERO_ADDRESS: address = @0x0; // Vector<u8> (byte strings) const APP_NAME: vector<u8> = b"MyDApp"; const VERSION: vector<u8> = b"1.0.0"; const EMPTY_BYTES: vector<u8> = b""; ``` ## Visibility and Scope Constants have **module-level visibility** only - they cannot be made public and are only accessible within the module where they are declared: ```move module 0x1::my_module { const PRIVATE_CONSTANT: u64 = 100; public fun get_constant(): u64 { PRIVATE_CONSTANT // Can access within same module } } module 0x1::other_module { use 0x1::my_module; public fun test() { // let x = PRIVATE_CONSTANT; // Error: not accessible let x = my_module::get_constant(); // Must use public function } } ``` ## Constant Expressions Constants can be initialized with simple expressions involving literals and other constants: ```move const BASE_RATE: u64 = 100; const MULTIPLIER: u64 = 2; const CALCULATED_RATE: u64 = BASE_RATE * MULTIPLIER; // 200 const IS_TESTNET: bool = true; const IS_MAINNET: bool = !IS_TESTNET; // false // Mathematical expressions const SECONDS_PER_MINUTE: u64 = 60; const MINUTES_PER_HOUR: u64 = 60; const SECONDS_PER_HOUR: u64 = SECONDS_PER_MINUTE * MINUTES_PER_HOUR; // 3600 // Address expressions const BASE_ADDRESS: address = @0x1; ``` ## Practical Usage Patterns ### Error Codes Constants are commonly used for error codes to make error handling more readable: ```move module 0x1::token { const ERROR_INSUFFICIENT_BALANCE: u64 = 1001; const ERROR_INVALID_RECIPIENT: u64 = 1002; const ERROR_TRANSFER_TO_SELF: u64 = 1003; const ERROR_AMOUNT_TOO_LARGE: u64 = 1004; public fun transfer(from: address, to: address, amount: u64) { assert!(from != to, ERROR_TRANSFER_TO_SELF); assert!(amount > 0, ERROR_INVALID_AMOUNT); // Transfer logic... } } ``` ### Configuration Values Use constants for configuration that shouldn't change during execution: ```move module 0x1::defi_protocol { const MAX_LOAN_TO_VALUE_RATIO: u8 = 80; // 80% const LIQUIDATION_THRESHOLD: u8 = 85; // 85% const MINIMUM_COLLATERAL: u64 = 1000; // Minimum collateral amount const FEE_DENOMINATOR: u64 = 10000; // For percentage calculations public fun calculate_fee(amount: u64, fee_rate: u64): u64 { (amount * fee_rate) / FEE_DENOMINATOR } } ``` ### Resource Limits Define limits and constraints as constants: ```move module 0x1::nft_collection { const MAX_SUPPLY: u64 = 10000; const MAX_MINT_PER_TRANSACTION: u8 = 10; const MINT_PRICE: u64 = 1000000; // 0.01 MOVE in octas struct Collection has key { total_minted: u64, } public fun mint_nft(account: &signer, quantity: u8) { assert!(quantity <= MAX_MINT_PER_TRANSACTION, ERROR_EXCEEDS_MINT_LIMIT); // Minting logic... } } ``` ### String Constants Use byte vector constants for string-like data: ```move module 0x1::metadata { const COLLECTION_NAME: vector<u8> = b"Awesome NFT Collection"; const COLLECTION_DESCRIPTION: vector<u8> = b"A collection of unique digital assets"; const BASE_URI: vector<u8> = b"https://api.example.com/metadata/"; public fun get_collection_name(): vector<u8> { COLLECTION_NAME } } ``` ## Advanced Patterns ### Bitflags and Permissions Use constants to define permission flags: ```move module 0x1::permissions { const PERMISSION_READ: u8 = 1; // 0001 const PERMISSION_WRITE: u8 = 2; // 0010 const PERMISSION_EXECUTE: u8 = 4; // 0100 const PERMISSION_ADMIN: u8 = 8; // 1000 const PERMISSION_ALL: u8 = PERMISSION_READ | PERMISSION_WRITE | PERMISSION_EXECUTE | PERMISSION_ADMIN; public fun has_permission(user_permissions: u8, required: u8): bool { (user_permissions & required) == required } } ``` ### Time Constants Define time-related constants for clarity: ```move module 0x1::timelock { const SECONDS_PER_DAY: u64 = 86400; const LOCK_DURATION_DAYS: u64 = 7; const LOCK_DURATION_SECONDS: u64 = LOCK_DURATION_DAYS * SECONDS_PER_DAY; public fun create_timelock(unlock_time: u64): u64 { unlock_time + LOCK_DURATION_SECONDS } } ``` ## Best Practices ### 1. Use Descriptive Names ```move // Good const MAX_TRANSACTION_SIZE: u64 = 1024; const DEFAULT_SLIPPAGE_TOLERANCE: u8 = 50; // 0.5% // Avoid const MAX_SIZE: u64 = 1024; const TOLERANCE: u8 = 50; ``` ### 2. Group Related Constants ```move module 0x1::trading { // Fee constants const TRADING_FEE_RATE: u64 = 30; // 0.3% const WITHDRAWAL_FEE_RATE: u64 = 10; // 0.1% const FEE_DENOMINATOR: u64 = 10000; // Limit constants const MIN_TRADE_AMOUNT: u64 = 1000; const MAX_TRADE_AMOUNT: u64 = 1000000000; // Time constants const COOLDOWN_PERIOD: u64 = 3600; // 1 hour } ``` ### 3. Document Complex Constants ```move module 0x1::math { // Represents 1.0 in fixed-point arithmetic with 8 decimal places const FIXED_POINT_SCALING: u64 = 100000000; // Maximum safe value to prevent overflow in multiplication const MAX_SAFE_MULTIPLIER: u64 = 18446744073709551615 / FIXED_POINT_SCALING; } ``` ## Ownership Constants have **copy semantics** - their values are copied each time they are used. This means: * No ownership transfer occurs when using constants * Constants can be used multiple times without restriction * The original constant value remains unchanged ```move const SHARED_VALUE: u64 = 100; public fun example() { let x = SHARED_VALUE; // Value is copied let y = SHARED_VALUE; // Value is copied again // Both x and y have independent copies of 100 } ``` ## Summary Constants in Move provide: * **Immutable named values** that improve code readability * **Compile-time evaluation** for better performance * **Module-level scope** for encapsulation * **Type safety** with explicit type annotations * **Copy semantics** for safe reuse Use constants for: * Error codes and status values * Configuration parameters * Mathematical constants * Resource limits and constraints * String-like data (as `vector<u8>`) Constants are essential for writing maintainable Move code by replacing magic numbers and strings with meaningful, self-documenting names. # Equality And Logical Operator URL: /devs/move-book/equalityAndLogicalOperator # Equality Move supports two equality operations: `==` (equal) and `!=` (not equal). These operators allow you to compare values and determine whether they are the same or different. ## Operations | Syntax | Operation | Description | | ------ | --------- | --------------------------------------------------------------------------- | | `==` | equal | Returns `true` if the two operands have the same value, `false` otherwise | | `!=` | not equal | Returns `true` if the two operands have different values, `false` otherwise | ## Basic Usage Both equality operations work with primitive types and user-defined types: ```move // Primitive types 0 == 0; // `true` 1u128 == 2u128; // `false` b"hello" != x"00"; // `true` ``` ## Typing Requirements Both the equal (`==`) and not-equal (`!=`) operations only work if both operands are the same type: ```move 1u8 == 1u128; // ERROR! // ^^^^^ cannot use `u128` with an operator which expects a value of type `u8` b"" != 0; // ERROR! // ^ cannot use `integer` with an operator which expects a value of type `vector<u8>` ``` ## User-Defined Types Equality and non-equality also work over user-defined types: ```move module 0x42::example { struct S has copy, drop { f: u64, s: vector<u8> } fun always_true(): bool { let s = S { f: 0, s: b"" }; // parens are not needed but added for clarity in this example (copy s) == s } fun always_false(): bool { let s = S { f: 0, s: b"" }; // parens are not needed but added for clarity in this example (copy s) != s } } ``` ## Typing with References When comparing references, the type of the reference (immutable or mutable) does not matter. You can compare an immutable `&` reference with a mutable `&mut` reference of the same underlying type: ```move let i = &0; let m = &mut 1; i == m; // `false` m == i; // `false` m == m; // `true` i == i; // `true` ``` This is equivalent to applying an explicit `freeze` to each mutable reference where needed: ```move let i =
프로젝트로 돌아가기