Movement 백서

Movement

원문

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

has store { permissions: u64 } // Only admins can create admin capabilities public fun create_admin_cap(): Capability<AdminRole> { Capability { permissions: 0xFF } } // Role-specific operations public fun admin_only<T>(_cap: &Capability<AdminRole>, data: T): T { data // Only callable with admin capability } } ``` **Key advantages:** * **Zero runtime cost**: No extra storage or computation * **Compile-time safety**: Type errors caught early * **Clear intent**: Types express domain concepts * **Flexible design**: Easy to extend with new "categories" ## Limitations ### Recursive Restrictions Move prevents certain recursive patterns to ensure type system soundness: ```move // Direct recursion not allowed struct Node<T> { value: T, next: Node<T> // ERROR: recursive struct } // Infinite type generation not allowed fun recursive_types<T>() { recursive_types<vector<T>>(); // ERROR: infinite types } ``` ### Type-Level Recursion The compiler conservatively prevents patterns that could generate infinite types, even if they would terminate at runtime: ```move fun controlled_recursion<T>(depth: u64) { if (depth > 0) { controlled_recursion<vector<T>>(depth - 1); // ERROR: still forbidden } } ``` ## Best Practices * Use descriptive type parameter names (`Currency` vs `T`) * Prefer type inference over explicit specification * Use phantom parameters for type-level distinctions * Apply minimal necessary constraints ## Summary Generics enable writing reusable, type-safe code that works across multiple data types: * **Code reuse**: Write once, use with multiple types while maintaining type safety * **Type parameters**: Functions and structs accept placeholders for concrete types * **Constraints**: Specify required abilities for safe operations on unknown types * **Phantom parameters**: Enable type-level programming without affecting abilities * **Unused parameters**: Create type distinctions without runtime overhead * **Type inference**: Compiler automatically determines types in most cases * **Zero runtime cost**: All generic resolution happens at compile time * **Essential for libraries**: Critical for building robust, reusable Move components # Global Storage URL: /devs/move-book/globalStorage # Global Storage Move programs operate on **persistent global storage** - a tree-structured data store that maintains state across transactions. Organized as a forest of trees rooted at account addresses. Global storage serves as Move's database, enabling smart contracts to maintain state, store user data, and coordinate between different program executions. ## Storage Structure Global storage conceptually resembles this structure: ``` GlobalStorage { resources: Map<(address, ResourceType), ResourceValue> modules: Map<(address, ModuleName), ModuleBytecode> } ``` **Organization principles:** * Each **address** acts as a namespace for both resources and modules * **Resources** store data values with the `key` ability * **Modules** contain executable code and type definitions * **Uniqueness** constraint: one resource per type per address ## Storage Operations Move provides five core operations for interacting with global storage: | Operation | Description | Aborts If | | --------------------------------------- | --------------------------------------- | ----------------------- | | `move_to<T>(&signer, T)` | Publish resource under signer's address | Resource already exists | | `move_from<T>(address): T` | Remove and return resource | Resource doesn't exist | | `borrow_global_mut<T>(address): &mut T` | Get mutable reference | Resource doesn't exist | | `borrow_global<T>(address): &T` | Get immutable reference | Resource doesn't exist | | `exists<T>(address): bool` | Check resource existence | Never | **Access control:** * All operations require the resource type `T` to have the `key` ability * Type `T` must be declared in the current module (module privacy) * Operations use `address` or `&signer` to specify the storage location ## Basic Usage Example Here's a simple counter module demonstrating storage operations: ```move module 0x42::counter { use std::signer; struct Counter has key { value: u64 } public fun create(account: &signer, initial: u64) { move_to(account, Counter { value: initial }); } public fun increment(addr: address) acquires Counter { let counter = borrow_global_mut<Counter>(addr); counter.value = counter.value + 1; } public fun get_value(addr: address): u64 acquires Counter { borrow_global<Counter>(addr).value } public fun destroy(account: &signer): u64 acquires Counter { let Counter { value } = move_from<Counter>(signer::address_of(account)); value } } ``` ## The `acquires` Annotation Functions that access global storage must declare which resources they acquire: ```move // Required when function directly accesses global storage public fun read_counter(addr: address): u64 acquires Counter { borrow_global<Counter>(addr).value } // Required when calling functions that acquire resources (same module only) fun increment_twice(addr: address) acquires Counter { increment(addr); // increment() has acquires Counter increment(addr); } ``` **Annotation rules:** Required for direct global storage access: ```move fun get_value(addr: address): u64 acquires Counter { borrow_global<Counter>(addr).value } ``` Required when calling functions with `acquires` (same module only): ```move fun double_increment(addr: address) acquires Counter { increment(addr); // increment() has acquires Counter } ``` Multiple resources and generic resources: ```move fun multi_access(addr: address) acquires Counter, Profile { // Multiple: acquires Counter, Profile } ``` ## Storage Polymorphism Global storage operations work with generic types, enabling powerful design patterns: ```move struct Container<T> has key { data: T } // Store any type T in global storage fun store_data<T: store>(account: &signer, data: T) { move_to<Container<T>>(account, Container { data }); } // Retrieve specific type at runtime fun get_u64_data(addr: address): u64 acquires Container { borrow_global<Container<u64>>(addr).data } ``` **Benefits of storage polymorphism:** * Write generic storage functions once * Type safety maintained at compile time * Enables flexible, reusable storage patterns ## Reference Safety Move prevents dangling references through strict rules and the `acquires` annotation to ensure static reference safety. ### No Returning Global References Functions cannot return references pointing to global storage: ```move // Not allowed - prevents dangling references fun get_counter_ref(addr: address): &Counter { borrow_global<Counter>(addr) // ERROR! } // Allowed - return owned values or local references fun get_counter_value(addr: address): u64 acquires Counter { borrow_global<Counter>(addr).value } ``` ### Acquires Annotation Protection The `acquires` annotation prevents dangling references by tracking resource access: ```move module 0x42::safety { struct T has key { f: u64 } fun borrow_then_remove_bad(a: address) acquires T { let t_ref: &mut T = borrow_global_mut<T>(a); let t = remove_t(a); // ERROR: type system prevents this // t_ref would be dangling! } fun remove_t(a: address): T acquires T { move_from<T>(a) } } ``` ### Reference Lifetime Rules Global references must be used within the same function scope: ```move fun safe_usage(addr: address) acquires Counter { let counter_ref = borrow_global_mut<Counter>(addr); counter_ref.value = 100; // Safe - same scope // Reference automatically expires at function end } ``` These restrictions ensure **static reference safety** - no dangling references, null dereferences, or memory safety violations at compile time. ## Best Practices * Use descriptive struct names with the `key` ability * Leverage module privacy for access control * Use `exists<T>()` to check before accessing resources * Minimize storage operations for better performance ## Summary Global storage provides Move's persistent data layer: * **Tree structure**: Organized as a forest rooted at account addresses * **Core operations**: Five operations (move\_to, move\_from, borrow\_global, borrow\_global\_mut, exists) * **Reference safety**: Strict rules prevent dangling references and memory violations * **Acquires annotation**: Tracks resource access for safe operations * **Storage polymorphism**: Generic storage patterns with compile-time type safety * **State persistence**: Essential for maintaining data across transactions in Move applications # Integer URL: /devs/move-book/integer # Integer Types Move supports unsigned integers of various sizes, from 8-bit to 256-bit. These are the fundamental numeric types for calculations and data storage. ## Integer Types Move provides six integer types: | Type | Size | Range | | ------ | ------- | ------------------------ | | `u8` | 8-bit | 0 to 2<sup>8</sup> - 1 | | `u16` | 16-bit | 0 to 2<sup>16</sup> - 1 | | `u32` | 32-bit | 0 to 2<sup>32</sup> - 1 | | `u64` | 64-bit | 0 to 2<sup>64</sup> - 1 | | `u128` | 128-bit | 0 to 2<sup>128</sup> - 1 | | `u256` | 256-bit | 0 to 2<sup>256</sup> - 1 | ## Integer Literals You can write integer literals in several ways: ### Decimal Literals ```move let small = 42; // Defaults to u64 let tiny = 255u8; // Explicit u8 type let big = 1000u128; // Explicit u128 type ``` ### Hexadecimal Literals ```move let hex_value = 0xFF; // 255 in decimal let hex_u32 = 0xDEADBEEFu32; ``` ### Underscores for Readability ```move let million = 1_000_000; let hex_readable = 0xAB_CD_EF_12u32; ``` ## Type Inference The compiler tries to infer integer types from context: ```move let x = 42; // Inferred as u64 (default) let y: u8 = 42; // Explicitly u8 let z = 42u16; // Explicitly u16 using suffix ``` ## Arithmetic Operations All integer types support basic arithmetic operations. Both operands must be the same type: ```move let a = 10u8; let b = 5u8; let sum = a + b; // 15 let difference = a - b; // 5 let product = a * b; // 50 let quotient = a / b; // 2 let remainder = a % b; // 0 ``` ### Safety Features Move prevents common arithmetic errors: * **Overflow**: Operations that exceed the type's maximum value will abort * **Underflow**: Subtracting to get below zero will abort * **Division by zero**: Will abort the program ```move let max_u8 = 255u8; // let overflow = max_u8 + 1; // This would abort! let zero = 0u8; // let div_by_zero = 10 / zero; // This would abort! ``` ## Comparison Operations Integers can be compared using standard operators: ```move let x = 10; let y = 20; let less = x < y; // true let greater = x > y; // false let less_equal = x <= y; // true let greater_equal = x >= y; // false let equal = x == y; // false let not_equal = x != y; // true ``` ## Type Casting You can convert between integer types using the `as` operator: ```move let small: u8 = 42; let medium: u16 = small as u16; // u8 to u16 let large: u64 = medium as u64; // u16 to u64 ``` ### Safe Casting Casting to a larger type is always safe: ```move let tiny: u8 = 255; let big: u64 = tiny as u64; // Always works ``` ### Unsafe Casting Casting to a smaller type can fail if the value is too large: ```move let big: u64 = 1000; // let small: u8 = big as u8; // Would abort! (1000 > 255) ``` ### Preventing Overflow with Casting Cast to larger types before operations that might overflow: ```move let a: u8 = 200; let b: u8 = 100; // let overflow = a + b; // Would abort! // Safe approach: let safe_sum: u16 = (a as u16) + (b as u16); // 300 ``` ## Practical Examples Here are common integer usage patterns: ```move // Age validation fun is_adult(age: u8): bool { age >= 18 } // Price calculation fun calculate_total(price: u64, quantity: u32): u64 { price * (quantity as u64) } // Range checking fun is_valid_percentage(value: u8): bool { value <= 100 } ``` ## Ownership As with the other scalar values built-in to the language, integer values are implicitly copyable, meaning they can be copied without an explicit instruction such as `copy`. ## Summary Integer types in Move are: * **Unsigned only** - no negative numbers * **Size-specific** - choose the right size for your data * **Safe by default** - operations abort on overflow/underflow * **Castable** - convert between sizes with `as` * **Copyable** - no explicit `copy` needed Choose the smallest type that fits your data to save storage space, but use larger types for calculations to avoid overflow. # Loop URL: /devs/move-book/loop # Loop Move offers multiple constructs for looping: `while`, `loop`, and `for`. These constructs allow you to repeat code execution based on conditions or iterate over ranges and collections. ## While Loops The `while` construct repeats the body (an expression of type unit) until the condition (an expression of type `bool`) evaluates to `false`. ### Basic While Loop Here is an example of a simple while loop that calculates the product of numbers from 1 to n (factorial): ```move fun factorial(n: u64): u64 { let result = 1; let i = 1; while (i <= n) { result *= i; i += 1; }; result } ``` ### Infinite Loops Infinite loops are allowed but should be used with caution due to computational cost: ```move fun foo() { while (true) { } } ``` ## Break Statement The `break` expression can be used to exit a loop before the condition evaluates to `false`. For example, this loop uses `break` to find the first power of 2 that exceeds a given threshold: ```move fun first_power_exceeding(threshold: u64): u64 { let power = 1; let exponent = 0; while (true) { if (power > threshold) break; power *= 2; exponent += 1; }; power } ``` The `break` expression cannot be used outside of a loop. ## Continue Statement The `continue` expression skips the rest of the loop and continues to the next iteration. This loop uses `continue` to count only odd numbers from 1 to n: ```move fun count_odd_numbers(n: u64): u64 { let count = 0; let i = 0; while (i < n) { i += 1; if (i % 2 == 0) continue; count += 1; }; count } ``` The `continue` expression cannot be used outside of a loop. ## The Type of Break and Continue `break` and `continue`, much like `return` and `abort`, can have any type. The following examples illustrate where this flexible typing can be helpful: ```move fun merge_until_duplicate( v1: vector<u8>, v2: vector<u8>, ): vector<u8> { let result = vector::empty(); while (!vector::is_empty(&v1) && !vector::is_empty(&v2)) { let val1 = *vector::borrow(&v1, 0); let val2 = *vector::borrow(&v2, 0); let next_val = if (val1 < val2) vector::remove(&mut v1, 0) else if (val2 < val1) vector::remove(&mut v2, 0) else break; // Here, `break` has type `u8` vector::push_back(&mut result, next_val); }; result } ``` ```move fun collect_valid_strings( lengths: vector<u64>, v1: &vector<vector<u8>>, v2: &vector<vector<u8>> ): vector<vector<u8>> { let len1 = vector::length(v1); let len2 = vector::length(v2); let result = vector::empty(); while (!vector::is_empty(&lengths)) { let target_len = vector::pop_back(&mut lengths); let chosen_vector = if (target_len <= len1) v1 else if (target_len <= len2) v2 else continue; // Here, `continue` has type `&vector<vector<u8>>` vector::push_back(&mut result, *vector::borrow(chosen_vector, target_len - 1)) }; result } ``` ## The Loop Expression The `loop` expression repeats the loop body (an expression with type `()`) until it hits a `break`. Without a `break`, the loop will continue forever: ```move fun infinite_counter() { let counter = 0; loop { counter = counter + 1 } } ``` ### Loop with Break Here is an example that uses `loop` to calculate the greatest common divisor (GCD): ```move fun gcd(a: u64, b: u64): u64 { let x = a; let y = b; loop { if (y == 0) break; let temp = y; y = x % y; x = temp }; x } ``` ### Loop with Continue As you might expect, `continue` can also be used inside a `loop`. Here is an example that counts prime numbers up to n: ```move fun count_primes(n: u64): u64 { let count = 0; let num = 2; loop { if (num > n) break; if (!is_prime(num)) { num = num + 1; continue; }; count = count + 1; num = num + 1 }; count } fun is_prime(n: u64): bool { if (n < 2) return false; let i = 2; while (i * i <= n) { if (n % i == 0) return false; i = i + 1 }; true } ``` ## The Type of While and Loop Move loops are typed expressions. A `while` expression always has type `()`: ```move let () = while (i < 10) { i = i + 1 }; ``` If a `loop` contains a `break`, the expression has type unit `()`: ```move (loop { if (i < 10) i = i + 1 else break }: ()); let () = loop { if (i < 10) i = i + 1 else break }; ``` If `loop` does not have a `break`, `loop` can have any type much like `return`, `abort`, `break`, and `continue`: ```move (loop (): u64); (loop (): address); (loop (): &vector<vector<u8>>); ``` ## For Loops For loops are used to iterate over a range of values, providing a more concise syntax for common iteration patterns. ### Basic For Loop Syntax ```move for (i in 1..n) { // code to be executed } ``` ### Range Iteration For loops can iterate over numeric ranges: ```move fun product_range(start: u64, end: u64): u64 { let product = 1; for (i in start..end) { product *= i; }; product } ``` ### Vector Iteration For loops can iterate over vector indices: ```move fun find_minimum(v: &vector<u64>): u64 { let min_val = *vector::borrow(v, 0); for (i in 1..vector::length(v)) { let current = *vector::borrow(v, i); if (current < min_val) { min_val = current; }; }; min_val } ``` ### For Loop with Break and Continue `break` and `continue` work in for loops just like in while loops: ```move fun find_first_perfect_square(start: u64, end: u64): u64 { for (i in start..end) { let sqrt_i = integer_sqrt(i); if (sqrt_i * sqrt_i != i) continue; return i }; abort 1 // No perfect square found } fun multiply_until_overflow(start: u64, end: u64, threshold: u64): u64 { let product = 1; for (i in start..end) { if (product > threshold / i) break; // Prevent overflow product = product * i; }; product } fun integer_sqrt(n: u64): u64 { if (n == 0) return 0; let x = n; let y = (x + 1) / 2; while (y < x) { x = y; y = (x + n / x) / 2; }; x } ``` ## Practical Examples ### Vector Processing ```move fun find_second_largest_index(v: &vector<u64>): u64 { let largest = 0; let second_largest = 0; let second_idx = 0; for (i in 0..vector::length(v)) { let val = *vector::borrow(v, i); if (val > largest) { second_largest = largest; second_idx = if (largest > 0) i - 1 else 0; largest = val; } else if (val > second_largest && val < largest) { second_largest = val; second_idx = i; }; }; second_idx } ``` ### Nested Loops ```move fun matrix_diagonal_product(matrix: &vector<vector<u64>>): u64 { let product = 1; let size = vector::length(matrix); for (i in 0..size) { let row = vector::borrow(matrix, i); if (i < vector::length(row)) { let diagonal_val = *vector::borrow(row, i); product = product * diagonal_val; }; }; product } ``` ### Fibonacci Calculation ```move fun fibonacci(n: u64): u64 { if (n <= 1) return n; let prev = 0; let curr = 1; for (i in 2..=n) { let next = prev + curr; prev = curr; curr = next; }; curr } ``` ## Performance Considerations 1. **Choose the right loop type**: * Use `for` loops for known ranges * Use `while` loops for condition-based iteration * Use `loop` for infinite loops with explicit breaks 2. **Minimize work inside loops**: ```move // Inefficient: repeated calculation for (i in 0..n) { let expensive_value = expensive_calculation(); process(i, expensive_value); }; // Efficient: calculate once let expensive_value = expensive_calculation(); for (i in 0..n) { process(i, expensive_value); }; ``` 3. **Use early termination** when possible with `break` ## Best Practices 1. **Use descripti
프로젝트로 돌아가기