Movement 백서

Movement

원문

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

{ move_to(admin, Pool { reserves: initial_reserves, fees_collected: 0 }) } public fun withdraw_reserves(pool_address: address): u64 acquires Pool { let Pool { reserves, fees_collected: _ } = move_from(pool_address); reserves } public fun get_pool_info(pool_address: address): (u64, u64) acquires Pool { let pool = borrow_global<Pool>(pool_address); (pool.reserves, pool.fees_collected) } public fun add_fees(pool_address: address, fee_amount: u64) acquires Pool { let pool = borrow_global_mut<Pool>(pool_address); pool.fees_collected = pool.fees_collected + fee_amount; } } ``` ### Transitive Acquires **Transitive acquires** occur when a function calls another function that accesses global storage. The calling function must also declare the acquires: **Key rules:** * **Same module**: Must declare acquires for transitive calls within the module * **Cross-module**: No acquires needed when calling functions from other modules * **Reason**: Cross-module resource access is impossible, so no reference safety issues ```move module 0x42::staking_pool { struct StakeInfo has key { amount: u64, rewards: u64 } public fun create_stake(staker: &signer, amount: u64) { move_to(staker, StakeInfo { amount, rewards: 0 }) } public fun claim_rewards(staker_addr: address): u64 acquires StakeInfo { let stake = borrow_global_mut<StakeInfo>(staker_addr); let rewards = stake.rewards; stake.rewards = 0; rewards } // Transitive acquires - must declare StakeInfo because it calls claim_rewards public fun compound_rewards(staker_addr: address) acquires StakeInfo { let rewards = claim_rewards(staker_addr); // calls function that acquires StakeInfo let stake = borrow_global_mut<StakeInfo>(staker_addr); stake.amount = stake.amount + rewards; } } ``` ```move module 0x42::rewards_distributor { fun distribute_rewards(staker_addr: address): u64 { 0x42::staking_pool::claim_rewards(staker_addr) // no acquires needed - cross-module } } ``` ### Multiple Acquires **Multiple acquires** allow functions to access several different resource types from global storage: **Syntax**: List all acquired resources separated by commas **Use cases**: Functions that coordinate between multiple resource types ```move module 0x42::defi_protocol { use std::vector; struct UserAccount has key { balance: u64, locked: u64 } struct RewardPool has key { total_rewards: u64, participants: vector<address> } struct GovernanceVotes has key { votes: u64, proposals: vector<u64> } // Function accessing multiple resource types public fun participate_in_governance<T: store>( user_addr: address, vote_weight: u64, proposal_id: u64, ) acquires UserAccount, RewardPool, GovernanceVotes { // Access user account let account = borrow_global_mut<UserAccount>(user_addr); assert!(account.balance >= vote_weight, 1); account.locked = account.locked + vote_weight; // Update reward pool let pool = borrow_global_mut<RewardPool>(user_addr); if (!vector::contains(&pool.participants, &user_addr)) { vector::push_back(&mut pool.participants, user_addr); }; // Record governance vote let votes = borrow_global_mut<GovernanceVotes>(user_addr); votes.votes = votes.votes + vote_weight; vector::push_back(&mut votes.proposals, proposal_id); } } ``` ## Return Types **Return types** specify what values a function produces, ensuring type safety and clear interfaces: **Basic return type syntax:** ```move fun calculate_interest(): u64 { 500 } fun get_user_name(): vector<u8> { b"Alice" } fun is_valid(): bool { true } ``` ### Multiple Return Values **Tuple returns** enable functions to produce multiple values simultaneously: ```move // Trading pair information fun get_trading_pair(): (u64, u64, bool) { (1000, 2000, true) // (price, volume, active) } // User account details fun get_account_info(addr: address): (vector<u8>, u64, bool) { (b"trader_123", 50000, true) // (username, balance, verified) } // Coordinate pair fun get_position(): (u64, u64) { (100, 200) // (x, y) } ``` **Destructuring multiple returns:** ```move fun use_multiple_returns() { let (price, volume, active) = get_trading_pair(); let (name, balance, _) = get_account_info(@0x123); // ignore verified status } ``` ### Unit Return Type **Unit type `()`** represents "no meaningful return value" - used for functions that perform actions rather than compute values: ```move fun just_unit(): () { () } fun just_unit() { () } fun just_unit() { } ``` ### Script Function Return Type Script functions must have a return type of unit `()`: ```move script { fun transfer_tokens() { // transaction logic // must return () - no other return type allowed } fun initialize_account() { // setup logic // implicitly returns () } } ``` As mentioned in the tuples section, these tuple "values" are virtual and do not exist at runtime. So for a function that returns unit `()`, it will not be returning any value at all during execution. ## Function Body **Function bodies** contain the implementation logic using expression blocks where the final expression becomes the return value: ```move fun calculate_fee(amount: u64): u64 { let base_fee = 10; let percentage_fee = amount / 100; base_fee + percentage_fee // this expression is returned } fun process_payment(sender: address, amount: u64): bool { let sender_balance = get_balance(sender); if (sender_balance >= amount) { deduct_balance(sender, amount); true // return success } else { false // return failure } } ``` **Expression block characteristics:** * **Sequential execution**: Statements execute in order * **Final expression**: Last expression becomes the return value * **No explicit return needed**: Final expression is automatically returned * **Type consistency**: Final expression must match declared return type ## Native Functions **Native functions** are implemented in the Move VM rather than in Move code, providing access to system-level operations: **Characteristics of native functions:** * **VM implementation**: Body provided by the virtual machine, not Move code * **Standard library**: Most natives are in `std` modules * **No custom natives**: Developers cannot create new native functions **Common native functions:** ```move module std::vector { native public fun empty<Element>(): vector<Element>; // ... } ``` ## Calling Functions When calling a function, the name can be specified either through an alias or fully qualified: ```move module 0x42::math { public fun get_pi(): u64 { 314 } } ``` ```move script { use 0x42::example::{Self, zero}; fun call_zero() { // With the `use` above all of these calls are equivalent 0x42::example::zero(); example::zero(); zero(); } } ``` ### Function Arguments **Arguments** must be provided for every parameter when calling functions, with strict type matching: ```move module 0x42::trading_engine { public fun get_base_fee(): u64 { 25 } public fun apply_discount(fee: u64): u64 { fee * 90 / 100 } public fun calculate_total(principal: u64, fee: u64): u64 { principal + fee } public fun create_order(trader: address, amount: u64, price: u64): bool { true } } ``` **Calling with correct arguments:** ```move script { use 0x42::trading_engine; fun execute_trades() { // No parameters let base_fee = trading_engine::get_base_fee(); // Single parameter let discounted_fee = trading_engine::apply_discount(base_fee); // Multiple parameters let total_cost = trading_engine::calculate_total(1000, discounted_fee); // Complex parameter types let success = trading_engine::create_order(@0x123, 500, 2000); } } ``` **Argument requirements:** * **Exact count**: Must provide argument for every parameter * **Type matching**: Arguments must match parameter types exactly * **Order matters**: Arguments passed in parameter declaration order ### Generic Type Arguments **Type arguments** for generic functions can be explicitly specified or automatically inferred: ```move module 0x42::container_utils { public fun create_empty<T>(): vector<T> { vector::empty<T>() } public fun swap<T>(x: T, y: T): (T, T) { (y, x) } public fun first_element<T: copy>(v: &vector<T>): T { *vector::borrow(v, 0) } } ``` **Type argument usage:** ```move script { use 0x42::container_utils; fun demonstrate_generics() { // Explicit type arguments let empty_u64_vec = container_utils::create_empty<u64>(); let empty_bool_vec = container_utils::create_empty<bool>(); // Type inference (compiler determines types) let (b, a) = container_utils::swap(100u64, 200u64); // infers T = u64 let (second, first) = container_utils::swap(true, false); // infers T = bool // Mixed approach let numbers = vector[1, 2, 3]; let first_num = container_utils::first_element<u64>(&numbers); } } ``` **When to use explicit type arguments:** * **Ambiguous contexts**: When compiler cannot infer the type * **Clarity**: When explicit types improve code readability * **Empty containers**: When creating empty generic containers ## Return Value Mechanics **Return values** are produced by the final expression in a function's body, enabling both simple and complex computations: **Simple return example:** ```move fun calculate_tax(amount: u64): u64 { amount * 8 / 100 // final expression becomes return value } ``` **Complex return with intermediate calculations:** ```move fun calculate_compound_yield(principal: u64, rate: u64, periods: u64): u64 { let rate_per_period = rate / periods; let compound_factor = 100 + rate_per_period; let final_amount = principal * compound_factor / 100; final_amount // this final expression is returned } ``` **Conditional returns:** ```move fun determine_fee_tier(volume: u64): u64 { if (volume >= 1000000) { 5 // premium tier } else if (volume >= 100000) { 10 // standard tier } else { 25 // basic tier } // the if-else expression result is returned } ``` ### Explicit Return Statements **Explicit returns** provide early exit from functions, especially useful in complex control flow: **Basic explicit return:** ```move fun validate_amount(amount: u64): u64 { if (amount == 0) return 0; // early exit amount * 105 / 100 // normal calculation } ``` These two functions are equivalent. In this slightly more involved example, the function subtracts two `u64` values, but returns early with 0 if the second value is too large: ```move fun safe_sub(x: u64, y: u64): u64 { if (y > x) return 0; x - y } ``` Note that the body of this function could also have been written as `if (y > x) 0 else x - y`. However `return` really shines is in exiting deep within other control flow constructs. In this example, the function iterates through a vector to find the index of a given value: ```move use std::vector; use std::option::{Self, Option}; fun index_of<T>(v: &vector<T>, target: &T): Option<u64> { let i = 0; let n = vector::length(v); while (i < n) { if (vector::borrow(v, i) == target) return option::some(i); i = i + 1 }; option::none() } ``` Using `return` without an argument is shorthand for `return ()`. That is, the following two functions are equivalent: ```move fun foo() { return } fun foo() { return () } ``` ## Function Visibility Summary | Visibility | Callable From | Use Case | Example | | ---------------- | ----------------------- | ----------------- | -------------------------------------- | | (default) | Same module only | Internal helpers | `fun calculate_internal_fee()` | | `public` | Any module or script | Public APIs | `public fun get_balance()` | | `public(friend)` | Same module + friends | Controlled access | `public(friend) fun admin_operation()` | | `entry` | Transaction entry point | Main functions | `entry fun create_account()` | ## Summary Functions are the primary building blocks for organizing and reusing code in Move: * **Declaration**: Use `fun` keyword with parameters, return types, and optional `acquires` annotations * **Visibility**: Control access with `public`, `public(friend)`, or `entry` modifiers * **Safety**: `acquires` annotations ensure safe global storage access * **Flexibility**: Support generics, multiple return values, and early returns * **Patterns**: Common patterns include constructors, accessors, mutators, and utilities Functions enable modular, safe, and reusable code organization in Move programs. # Generics URL: /devs/move-book/generics # Generics Generics enable defining functions and structs that work with multiple data types while maintaining type safety. This feature, also known as **parametric polymorphism**, allows you to write reusable code that operates on any type satisfying specified constraints. **Key benefits:** * **Code reuse**: Write once, use with multiple types * **Type safety**: Compile-time type checking prevents runtime errors * **Library development**: Essential for building flexible, reusable components Generics are extensively used in Move's standard library (like `vector<T>`) and are crucial for building type-safe, reusable smart contract components. ## Type Parameters Both functions and structs can accept type parameters enclosed in angle brackets `<...>`. These parameters act as placeholders for concrete types that will be specified later. ### Generic Functions Type parameters are placed after the function name and before the parameter list: ```move module 0x42::utils { // Generic identity function - works with any type fun id<T>(x: T): T { x } // Generic swap function fun swap<T>(x: T, y: T): (T, T) { (y, x) } } ``` ### Generic Structs Type parameters follow the struct name and can be used in field definitions: ```move module 0x42::containers { struct Box<T> has copy, drop { value: T } struct Pair<T1, T2> has copy, drop { first: T1, second: T2, } } ``` ## Using Generics ### Function Calls You can explicitly specify type arguments or let Move's type inference determine them: ```move fun example() { // Explicit type specification let x = id<bool>(true); // Type inference (preferred when possible) let y = id(42u64); // T inferred as u64 } ``` ### Struct Construction Similar to functions, type arguments can be explicit or inferred: ```move fun create_containers() { // Explicit types let box = Box<u64> { value: 100 }; // Type inference let pair = Pair { first: true, second: 42 }; // Pair<bool, u64> } ``` ## Type Inference Move's compiler automatically infers types in most cases, reducing verbosity while maintaining safety: ```move fun inference_examples() { let numbers = vector[1, 2, 3]; // vector<u64> inferred vector::push_back(&mut numbers, 4); // T inferred from usage } ``` **When manual annotation is required:** * Functions with type parameters only in return positions * Ambiguous contexts where multiple types are possible ## Phantom Type Parameters Phantom type parameters solve a critical problem with ability derivation in generic structs. When a struct has generic parameters, it can only have abilities that **all** its type parameters possess - even if those parameters aren't actually used in the struct fields. ### The Problem Consider this currency system without phantom parameters: ```move module 0x42::currency { struct Currency1 {} // No abilities struct Currency2 {} // No abilities // This struct wants 'store' ability struct Coin<Currency> has store { value: u64 } } ``` **Issue**: Even though `Currency1` and `Currency2` are never used in `Coin`'s fields, the struct `Coin<Currency1>` **cannot** have the `store` ability because `Currency1` lacks it. This prevents storing coins in global storage! ### The Solution: Phantom Parameters Phantom parameters are excluded from ability derivation, solving this problem: ```move module 0x42::currency { struct Currency1 {} // Still no abilities needed struct Currency2 {} // phantom means Currency doesn't affect abilities struct Coin<phantom Currency> has store { value: u64 } public fun mint<Currency>(amount: u64): Coin<Currency> { Coin { value: amount } // Now Coin<Currency1> has 'store'! } } ``` ### Declaration Rules Phantom parameters can only appear in "phantom positions": ```move // Valid: T1 not used at all struct S1<phantom T1, T2> { f: u64 } // Valid: T1 only used as phantom argument struct S2<phantom T1, T2> { f: S1<T1, T2> } // Invalid: T used in non-phantom position struct S3<phantom T> { f: T } // Invalid: T used as argument to non-phantom parameter struct S4<phantom T> { f: vector<T> } ``` **Key benefits:** * **Ability independence**: Phantom parameters don't affect struct abilities * **Type safety**: Different phantom arguments create distinct types * **Zero runtime cost**: No storage or computation overhead ## Constraints By default, generic type parameters have **no abilities**, making the type system very conservative. Constraints allow you to specify what abilities unknown types must have, enabling safe operations that would otherwise be forbidden. ### Why Constraints Are Needed Without constraints, generic functions are severely limited: ```move fun unsafe_consume<T>(x: T) { // error! x does not have 'drop' } fun unsafe_double<T>(x: T) { (copy x, x) // error! x does not have 'copy' } ``` ### Declaring Constraints Constraints specify required abilities using the `:` syntax: ```move // Single constraint fun consume<T: drop>(x: T) { // valid! // x will be dropped automatically } // Multiple constraints fun double<T: copy>(x: T) { (copy x, x) // valid! } // All four abilities T: copy + drop + store + key ``` ### Constraint Verification Constraints are checked at **call sites**, not definitions: ```move struct R {} fun foo() { let r = R {}; consume<R>(r); // ^ error! R does not have 'drop' } fun foo(): (R, R) { let r = R {}; double<R>(r) // ^ error! R does not have 'copy' } ``` ### Practical Examples ```move module 0x42::safe_operations { // Safe resource cleanup fun cleanup<T: drop>(items: vector<T>) { // All items automatically dropped } // Safe value duplication fun backup<T: copy>(original: T): (T, T) { (copy original, original) } // Safe global storage struct Container<T: store> has key { contents: T } } ``` ## Unused Type Parameters Move allows type parameters that don't appear in struct fields, enabling powerful **type-level programming**. These "unused" parameters provide compile-time type distinctions without runtime overhead. ### Type-Level Distinctions Unused parameters create different types that are structurally identical but logically distinct: ```move module 0x42::currency_system { // Currency specifier types (empty structs) struct USD {} struct EUR {} struct BTC {} // Generic coin - Currency parameter is "unused" struct Coin<Currency> has store { value: u64 // Currency doesn't appear here! } // Each currency creates a distinct type public fun mint_usd(value: u64): Coin<USD> { Coin { value } } public fun mint_eur(value: u64): Coin<EUR> { Coin { value } } // Type safety: can't mix currencies! public fun exchange_usd_to_eur(usd: Coin<USD>): Coin<EUR> { let Coin { value } = usd; Coin<EUR> { value: value * 85 / 100 } // 85% exchange rate } } ``` ### Benefits of Unused Parameters **Type Safety**: Prevents mixing incompatible values: ```move fun example() { let dollars = mint_usd(100); let euros = mint_eur(85); // Compile error: type mismatch! // exchange_usd_to_eur(euros); // EUR ≠ USD // Correct usage let converted = exchange_usd_to_eur(dollars); } ``` **Generic Programming**: Write code that works with any currency: ```move // Generic function works with any currency public fun get_value<Currency>(coin: &Coin<Currency>): u64 { coin.value } // Specific function for USD only public fun get_usd_value(coin: &Coin<USD>): u64 { coin.value } ``` ### Real-World Applications ```move module 0x42::access_control { // Permission types struct AdminRole {} struct UserRole {} struct GuestRole {} // Capability with role-based access struct Capability<Role>
프로젝트로 돌아가기