bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 33쪽 중 10쪽
&0;
let m = &mut 1;
i == freeze(m); // `false`
freeze(m) == i; // `false`
m == m; // `true`
i == i; // `true`
```
However, the underlying type must still be the same:
```move
let i = &0;
let s = &b"";
i == s; // ERROR!
// ^ expected an argument of type '&u64'
```
## Drop Ability Restrictions
Both `==` and `!=` consume the value when comparing them. As a result, the type system enforces that the type must have the `drop` ability. Without the `drop` ability, ownership must be transferred by the end of the function, and such values can only be explicitly destroyed within their declaring module.
```move
module 0x42::example {
struct Coin has store { value: u64 }
fun invalid(c1: Coin, c2: Coin) {
c1 == c2 // ERROR!
// ^^ local `c2` of type `Coin` does not have the `drop` ability
}
}
```
## Working with Resources
A programmer can always borrow the value first instead of directly comparing the value, since reference types have the `drop` ability:
```move
module 0x42::compare_without_copy {
struct Coin has store { value: u64 }
fun swap_if_equal(c1: Coin, c2: Coin): (Coin, Coin) {
let are_equal = &c1 == &c2; // valid
if (are_equal) (c2, c1) else (c1, c2)
}
}
```
## Avoiding Extra Copies
While you can compare any value whose type has `drop`, you should often compare by reference to avoid expensive copies:
**Inefficient approach:**
```move
let v1: vector<u8> = function_that_returns_vector();
let v2: vector<u8> = function_that_returns_vector();
assert!(copy v1 == copy v2, 42);
// ^^^^ ^^^^
use_two_vectors(v1, v2);
let s1: Foo = function_that_returns_large_struct();
let s2: Foo = function_that_returns_large_struct();
assert!(copy s1 == copy s2, 42);
// ^^^^ ^^^^
use_two_foos(s1, s2);
```
**Efficient approach:**
```move
let v1: vector<u8> = function_that_returns_vector();
let v2: vector<u8> = function_that_returns_vector();
assert!(&v1 == &v2, 42);
// ^ ^
use_two_vectors(v1, v2);
let s1: Foo = function_that_returns_large_struct();
let s2: Foo = function_that_returns_large_struct();
assert!(&s1 == &s2, 42);
// ^ ^
use_two_foos(s1, s2);
```
The efficiency of the `==` operation itself remains the same, but the copies are removed, making the program more efficient overall.
# Logical Operators
Move supports two logical operators: `&&` (logical and) and `||` (logical or). These operators work with boolean values and provide short-circuit evaluation.
## Operations
| Syntax | Operation | Description |
| ------ | ----------- | ------------------------------------------------------------------- |
| `&&` | logical and | Returns `true` if both operands are `true`, `false` otherwise |
| `\|\|` | logical or | Returns `true` if at least one operand is `true`, `false` otherwise |
## Basic Usage
Both logical operators work exclusively with `bool` type operands:
```move
true && true; // `true`
true && false; // `false`
false && true; // `false`
false && false; // `false`
true || true; // `true`
true || false; // `true`
false || true; // `true`
false || false; // `false`
```
## Short-Circuit Evaluation
Both `&&` and `||` use short-circuit evaluation, meaning the second operand is only evaluated if necessary:
### Logical AND (`&&`)
With `&&`, if the first operand is `false`, the second operand is not evaluated since the result will always be `false`:
```move
fun example_and() {
let x = false && expensive_function(); // expensive_function() is NOT called
let y = true && expensive_function(); // expensive_function() IS called
}
```
### Logical OR (`||`)
With `||`, if the first operand is `true`, the second operand is not evaluated since the result will always be `true`:
```move
fun example_or() {
let x = true || expensive_function(); // expensive_function() is NOT called
let y = false || expensive_function(); // expensive_function() IS called
}
```
## Typing Requirements
Both operands must be of type `bool`. Using non-boolean types will result in a type error:
```move
1 && 2; // error: cannot use `integer` with an operator which expects a value of type `bool`
true && 0; // error: cannot use `integer` with an operator which expects a value of type `bool`
false || "hello"; // error: cannot use `vector<u8>` with an operator which expects a value of type `bool`
```
## Practical Examples
Logical operators are commonly used in conditional statements and assertions:
```move
fun validate_user(age: u64, has_permission: bool): bool {
// User must be 18 or older AND have permission
age >= 18 && has_permission
}
fun can_access(is_admin: bool, is_owner: bool, has_key: bool): bool {
// Access granted if user is admin OR owner OR has key
is_admin || is_owner || has_key
}
fun complex_condition(x: u64, y: u64, flag: bool): bool {
// Complex logical expression
(x > 10 && y < 5) || (flag && x == y)
}
```
## Combining with Equality
Logical operators are often combined with equality operations:
```move
fun check_range(value: u64, min: u64, max: u64): bool {
value >= min && value <= max
}
fun is_valid_coordinate(x: u64, y: u64): bool {
(x >= 0 && x <= 100) && (y >= 0 && y <= 100)
}
fun different_values(a: u64, b: u64, c: u64): bool {
a != b && b != c && a != c
}
```
## Performance Considerations
Due to short-circuit evaluation, place the most likely to fail (for `&&`) or succeed (for `||`) conditions first:
```move
// Efficient: cheap check first
fun efficient_check(expensive_condition: bool, cheap_value: u64): bool {
cheap_value > 0 && expensive_condition
}
// Less efficient: expensive check might run unnecessarily
fun less_efficient_check(expensive_condition: bool, cheap_value: u64): bool {
expensive_condition && cheap_value > 0
}
```
## Operator Precedence
Logical operators have specific precedence rules. `&&` has higher precedence than `||`:
```move
// This expression: a || b && c
// Is evaluated as: a || (b && c)
// NOT as: (a || b) && c
let result = true || false && false; // `true` (not `false`)
```
Use parentheses for clarity when combining operators:
```move
let clear_intent = (a || b) && c; // Explicit grouping
let also_clear = a || (b && c); // Explicit grouping
```
## Summary
Move's comparison and logical operators enable safe value comparison and boolean logic:
* **Equality**: `==` and `!=` compare values of identical types; require `drop` ability
* **Logical**: `&&` and `||` work with `bool` types and use short-circuit evaluation
* **Type Safety**: Strict type matching prevents runtime errors
* **Performance**: Use references to avoid expensive copies; leverage short-circuiting
* **Precedence**: `&&` binds tighter than `||`; use parentheses for clarity
These operators are essential for conditional logic and control flow in Move programs.
# Friends
URL: /devs/move-book/friends
# Friends
The friend system allows modules to grant trusted access to specific other modules. Friend modules can call functions with `public(friend)` visibility, creating controlled inter-module relationships without exposing functionality publicly.
This system enables building modular architectures where related modules can collaborate while maintaining encapsulation from external access.
## Friend Declaration
Modules declare friends using `friend` statements to grant access to `public(friend)` functions. Friend declarations can reference modules by their full name or through aliases.
**Syntax:**
```
friend <module_address>::<module_name>;
friend <module_alias>;
```
### Full Module Name Declaration
Use the complete module path including address when declaring friends:
```move
module 0x42::core {
friend 0x42::utils; // Grant friend access to utils module
friend 0x42::helpers; // Grant friend access to helpers module
public(friend) fun internal_operation(): u64 {
42
}
}
```
### Module Alias Declaration
Import modules with `use` statements, then reference them by alias in friend declarations:
```move
module 0x42::core {
use 0x42::utils; // Import utils module
use 0x42::helpers as h; // Import helpers with alias 'h'
friend utils; // Declare friend using module name
friend h; // Declare friend using alias
public(friend) fun internal_operation(): u64 {
42
}
}
```
**Declaration rules:**
* Friend declarations must be at module scope (not within functions)
* Multiple friends can be declared to form a friend list
* Recommended to place friend declarations near the top for readability
## Usage Example
Here's how friend modules interact:
```move
module 0x42::vault {
friend 0x42::admin;
struct Vault has key, drop {
balance: u64
}
// Only admin module can call this
public(friend) fun emergency_withdraw(vault: &mut Vault): u64 {
let amount = vault.balance;
vault.balance = 0;
amount
}
// Public function - anyone can call
public fun get_balance(vault: &Vault): u64 {
vault.balance
}
public fun deposit(vault: &mut Vault, amount: u64) {
vault.balance += amount;
}
public(friend) fun create_vault(initial_amount: u64): Vault {
Vault { balance: initial_amount }
}
}
module 0x42::admin {
use 0x42::vault::{Self};
public fun perform_emergency_withdrawal(): u64 {
let vault = vault::create_vault(20);
vault::emergency_withdraw(&mut vault)
}
}
```
## Declaration Rules
The friend system enforces several important constraints:
### No Self-Declaration
Modules cannot declare themselves as friends:
```move
module 0x42::example {
friend Self; // ERROR: Cannot declare self as friend
friend 0x42::example; // ERROR: Cannot declare self as friend
}
```
### Same Address Requirement
Friend modules must be within the same account address:
```move
module 0x42::core {
friend 0x43::external; // ERROR: Different address
}
```
### No Circular Dependencies
Friend relationships cannot create dependency cycles:
```move
module 0x42::a {
use 0x42::c;
friend 0x42::b; // a uses c, friends b
}
module 0x42::b {
friend 0x42::c; // ERROR: Creates cycle (a->c, a friends b, b friends c)
}
```
### No Duplicates
Each module can only be declared as a friend once:
```move
module 0x42::core {
use 0x42::utils as u;
friend 0x42::utils;
friend u; // ERROR: Duplicate friend declaration
}
```
## Summary
The friend system provides controlled access between modules:
* **Purpose**: Allows modules to grant selective access to `public(friend)` functions
* **Access control**: Enables fine-grained control over which modules can call specific functions
* **Declaration rules**: Must prevent self-declaration, circular dependencies, and duplicate declarations
* **Same address requirement**: Friend modules must be within the same account address
* **Use cases**: Ideal for creating trusted relationships between related modules in a package
# Functions
URL: /devs/move-book/functions
# Functions
Functions are the fundamental building blocks of Move programs, enabling code organization, reusability, and modularity. Move supports both **module functions** (reusable across transactions) and **script functions** (single-use transaction entry points).
**Key characteristics:**
* **Statically typed**: All parameters and return types must be explicitly declared
* **Module-scoped**: Functions belong to specific modules and follow visibility rules
* **Resource-aware**: Special annotations for global storage access
## Function Declaration
Functions use the `fun` keyword followed by a structured declaration syntax that ensures type safety and clear interfaces:
**Syntax structure:**
```
fun <identifier><[type_parameters: constraint],*>([identifier: type],*): <return_type> <acquires [identifier],*> <function_body>
```
**Complete example:**
```move
fun process_transaction<T: store>(amount: u64, data: T): (bool, T) acquires Account {
// function body
(true, data)
}
```
## Visibility and Access Control
Move enforces strict **module-level encapsulation** through visibility modifiers, ensuring controlled access to functionality:
**Visibility levels:**
* **Private (default)**: Only callable within the defining module
* **Public**: Callable from any module or script
* **Public(friend)**: Callable only from explicitly trusted modules
* **Entry**: Can serve as transaction entry points
```move
module 0x42::defi_pool {
fun calculate_fees(): u64 { 100 }
fun get_pool_fees(): u64 { calculate_fees() } // valid - same module
}
module 0x42::trading_bot {
fun estimate_costs(): u64 {
0x42::defi_pool::calculate_fees() // ERROR!
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 'calculate_fees' is private to '0x42::defi_pool'
}
}
```
```move
script {
fun calls_m_foo(): u64 {
0x42::defi_pool::calculate_fees() // ERROR!
// ^^^^^^^^^^^^ 'foo' is internal to '0x42::m'
}
}
```
To allow access from other modules or from scripts, the function must be declared `public` or `public(friend)`.
### Public Functions
**Public functions** allow access to the function from any module or script. As shown in the following example, a public function can be called by:
* other functions defined in the same module,
* functions defined in another module, or
* the function defined in a script.
```move
module 0x42::defi_pool {
public fun get_pool_balance(): u64 { 1000000 }
fun internal_calculation(): u64 { get_pool_balance() } // valid - same module
}
module 0x42::trading_bot {
fun check_liquidity(): u64 {
0x42::defi_pool::get_pool_balance() // valid - public access
}
}
```
```move
script {
fun calls_m_foo(): u64 {
0x42::m::foo() // valid
}
}
```
### Public(friend) Visibility
The `public(friend)` visibility modifier provides controlled access between trusted modules. It's more restrictive than `public` but more permissive than private visibility.
**Access rules for `public(friend)` functions:**
* Functions within the same module can call them
* Functions in explicitly declared friend modules can call them
* Functions in non-friend modules cannot call them
* Script functions cannot call them (scripts cannot be declared as friends)
```move
module 0x42::vault_core {
friend 0x42::vault_manager; // friend declaration
public(friend) fun access_vault_funds(): u64 { 50000 }
fun internal_operation(): u64 { access_vault_funds() } // valid - same module
}
module 0x42::vault_manager {
fun manage_funds(): u64 {
0x42::vault_core::access_vault_funds() // valid - trusted friend
}
}
module 0x42::external_user {
fun try_access(): u64 {
0x42::vault_core::access_vault_funds() // ERROR!
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 'access_vault_funds' can only be called from a 'friend' of module '0x42::vault_core'
}
}
```
```move
script {
fun calls_m_foo(): u64 {
0x42::m::foo() // ERROR!
// ^^^^^^^^^^^^ 'foo' can only be called from a 'friend' of module '0x42::m'
}
}
```
### Entry Functions
**Entry functions** serve as transaction entry points, enabling direct invocation from external clients while maintaining Move's safety guarantees:
**Entry function characteristics:**
* **Transaction entry points**: Can be called directly by transactions
* **Client interfaces**: Primary way external applications interact with modules
* **Flexible visibility**: Can be public, private, or friend-restricted
* **Still callable internally**: Other Move functions can invoke them
**Design benefits:**
* **Clear interfaces**: Explicitly marks functions intended for external use
* **Security boundaries**: Helps identify transaction entry points
* **Composability**: Entry functions can call other functions normally
```move
module 0x42::nft_marketplace {
public entry fun create_listing(price: u64): u64 { price }
fun internal_setup(): u64 { create_listing(100) } // valid - internal call
}
module 0x42::auction_house {
fun start_auction(): u64 {
0x42::nft_marketplace::create_listing(500) // valid - cross-module call
}
}
module 0x42::trading_platform {
public entry fun launch_sale(): u64 {
0x42::nft_marketplace::create_listing(1000) // valid - entry calling entry
}
}
```
```move
script {
fun calls_m_foo(): u64 {
0x42::m::foo() // valid!
}
}
```
**Private entry functions** provide transaction entry points while maintaining module privacy:
```move
module 0x42::admin_panel {
entry fun system_initialize(): u64 { 42 } // private entry - transaction accessible but not cross-module
}
module 0x42::user_interface {
fun setup_system(): u64 {
0x42::admin_panel::system_initialize() // ERROR!
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 'system_initialize' is private to '0x42::admin_panel'
}
}
```
<Callout type="info">
**Key insight**: Entry functions can be private, allowing transaction access while preventing cross-module calls.
</Callout>
## Function Naming
Move enforces specific naming conventions for functions to ensure consistency and readability:
**Naming rules:**
* **First character**: Letters (a-z, A-Z) only
* **Subsequent characters**: Letters, digits (0-9), underscores (\_)
* **Convention**: snake\_case is strongly recommended
* **Restrictions**: Cannot start with underscore or digit
```move
// Valid function names
fun process_payment() {}
fun calculateFees() {} // valid but not recommended (prefer snake_case)
fun handle_nft_transfer() {}
fun get_balance_v2() {}
// Invalid function names
fun _private_func() {} // ERROR: cannot start with underscore
fun 2nd_attempt() {} // ERROR: cannot start with digit
fun process-payment() {} // ERROR: hyphens not allowed
```
**Best practices:**
* Use descriptive, action-oriented names
* Follow snake\_case convention consistently
* Avoid abbreviations that reduce clarity
* Consider the function's purpose in naming
## Generic Functions
**Generic functions** enable code reuse across different types while maintaining type safety through parameterized types:
**Generic syntax:**
* **Type parameters**: Declared in angle brackets `<T, U>`
* **Constraints**: Optional ability requirements `<T: copy + drop>`
* **Usage**: Type parameters can be used in parameters, return types, and function body
```move
// Simple generic function
fun swap<T>(x: T, y: T): (T, T) { (y, x) }
// Generic with constraints
fun duplicate_and_store<T: copy + store>(item: T): (T, T) {
(copy item, item)
}
// Multiple type parameters
fun process_pair<Asset: store, Metadata: copy + drop>(
asset: Asset,
meta: Metadata
): (Asset, Metadata) {
(asset, copy meta)
}
```
## Function Parameters
**Parameters** define the inputs a function accepts, with explicit type annotations ensuring type safety:
**Parameter syntax:**
* **Format**: `name: type`
* **Multiple parameters**: Comma-separated list
* **Type annotations**: Always required (no type inference)
* **Ownership**: Parameters transfer ownership unless borrowed
```move
// Single parameter
fun calculate_fee(amount: u64): u64 { amount / 100 }
// Multiple parameters with different types
fun create_trade(trader: address, amount: u64, active: bool): Trade {
Trade { trader, amount, active }
}
// Reference parameters (borrowing)
fun read_balance(account: &Account): u64 {
account.balance
}
// Mutable reference parameters
fun update_balance(account: &mut Account, new_balance: u64) {
account.balance = new_balance;
}
```
**Parameter-less functions** are common for constructors and getters:
```move
module 0x42::token_factory {
struct TokenConfig { decimals: u8, max_supply: u64 }
// Constructor with no parameters
fun default_config(): TokenConfig {
TokenConfig { decimals: 8, max_supply: 1000000 }
}
// Getter with no parameters
fun get_current_timestamp(): u64 {
// implementation
1234567890
}
}
```
## Global Storage Access
**Acquires annotations** ensure safe access to global storage by explicitly declaring which resources a function will access:
**Global storage operations requiring acquires:**
* `move_from<T>(address)`: Moving resource from global storage
* `borrow_global<T>(address)`: Immutable borrow from global storage
* `borrow_global_mut<T>(address)`: Mutable borrow from global storage
```move
module 0x42::liquidity_pool {
struct Pool has key { reserves: u64, fees_collected: u64 }
public fun initialize_pool(admin: &signer, initial_reserves: u64)프로젝트로 돌아가기