Movement 백서

Movement

원문

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

e between mainnet or testnet versions ## Package Development Workflow ### Project Setup ```bash # Create new package movement move init my_project cd my_project # Add dependencies to Move.toml # Implement modules in sources/ # Add tests in tests/ # Compile and test movement move compile movement move test ``` ### Compilation Options ```bash # Fetch dependencies only movement move compile --fetch-deps-only # Skip git dependency updates movement move compile --skip-fetch-latest-git-deps # Override standard library version movement move compile --override-std testnet # Set optimization level movement move compile --optimize default # Specify named addresses movement move compile --named-addresses protocol=0x123 ``` ## Best Practices * Use clear, descriptive package names * Organize related modules in the same package * Pin specific git revisions for production dependencies * Use dev-addresses for testing and development * Specify optimization levels appropriate for your use case * Use `--save-metadata` for debugging and analysis ## Summary Move packages provide structured code organization with standardized directory layouts, dependency management through Move.toml manifests, and parameterized named addresses for flexible deployment. The build system generates bytecode, documentation, and source maps, while Move.lock ensures reproducible builds. Packages enable modular development, code reuse, and professional project management in the Move ecosystem. # References URL: /devs/move-book/references # References Move has two types of references: **immutable** `&` and **mutable** `&mut`. References allow you to borrow values without taking ownership, enabling safe access and modification of data. ## What are References? References are "borrows" that provide temporary access to a value without transferring ownership. Think of them as safe pointers that the compiler tracks to prevent memory errors. | Type | Symbol | Purpose | | ----------------------- | ----------- | ------------------------------------------------------------ | | Immutable reference | `&T` | Read-only access to value of type `T` | | Mutable reference | `&mut T` | Read and write access to value of type `T` | | Field reference | `&e.f` | Create an immutable reference to field f of struct e. | | Mutable field reference | `&mut e.f` | Create a mutable reference to field f of struct e. | | Freeze | `freeze(e)` | Convert the mutable reference e into an immutable reference. | <Callout type="info"> **Key Concept**: References are ephemeral - they exist only during program execution and cannot be stored in structs or global storage. </Callout> ## Creating References ### Basic Reference Creation ```move fun basic_references() { let x = 42u64; let x_ref: &u64 = &x; // Immutable reference let x_mut_ref: &mut u64 = &mut x; // Mutable reference } ``` ### Field References The `&e.f` and `&mut e.f` operators can be used both to create a new reference into a struct or to extend an existing reference: ```move struct S has drop { f: u64 } fun field_references() { let s = S { f: 10 }; let f_ref1: &u64 = &s.f; // works let s_ref: &S = &s; let f_ref2: &u64 = &s_ref.f; // also works } ``` ### Multiple Field Access A reference expression with multiple fields works as long as both structs are in the same module: ```move struct A has drop { b: B } struct B has drop { c: u64 } fun f(a: &A): &u64 { &a.b.c } ``` ### References to References Finally, note that references to references are not allowed: ```move fun invalid_references() { let x = 7; let y: &u64 = &x; let z: &&u64 = &y; // will not compile } ``` ## Reading and Writing Through References Both mutable and immutable references can be read to produce a copy of the referenced value. Only mutable references can be written. A write `*x = v` discards the value previously stored in `x` and updates it with `v`. Both operations use the C-like `*` syntax. However, note that a read is an expression, whereas a write is a mutation that must occur on the left hand side of an equals. | Syntax | Type | Description | | ---------- | ----------------------------------- | ---------------------------------- | | `*e` | `T` where `e` is `&T` or `&mut T` | Read the value pointed to by `e` | | `*e1 = e2` | `()` where `e1: &mut T` and `e2: T` | Update the value in `e1` with `e2` | ### Reading Through References ```move fun reading_example() { let x = 42u64; let x_ref = &x; let value: u64 = *x_ref; // Read the value (creates a copy) assert!(value == 42, 0); } ``` ### Writing Through References ```move fun writing_example() { let x = 42u64; let x_ref = &mut x; *x_ref = 100; // Write new value assert!(x == 100, 0); } ``` ### Ability Requirements In order for a reference to be read, the underlying type must have the `copy` ability as reading the reference creates a new copy of the value. This rule prevents the copying of resource values: ```move struct Coin has store { value: u64 } fun copy_resource_via_ref_bad(c: Coin) { let c_ref = &c; let counterfeit: Coin = *c_ref; // local `c_ref` of type `Coin` does not have the `copy` ability // pay(c); // pay(counterfeit); } ``` Dually: in order for a reference to be written to, the underlying type must have the `drop` ability as writing to the reference will discard (or "drop") the old value. This rule prevents the destruction of resource values: ```move fun destroy_resource_via_ref_bad(ten_coins: Coin, c: Coin) { let ref = &mut ten_coins; *ref = c; // local `ref` of type `Coin` does not have the `drop` ability } ``` ## Freeze Inference A mutable reference can be used in a context where an immutable reference is expected: ```move fun freeze_example() { let x = 7; let y: &u64 = &mut x; } ``` This works because the under the hood, the compiler inserts `freeze` instructions where they are needed. Here are a few more examples of freeze inference in action: ```move fun takes_immut_returns_immut(x: &u64): &u64 { x } // freeze inference on return value fun takes_mut_returns_immut(x: &mut u64): &u64 { x } fun expression_examples() { let x = 0; let y = 0; takes_immut_returns_immut(&x); // no inference takes_immut_returns_immut(&mut x); // inferred freeze(&mut x) takes_mut_returns_immut(&mut x); // no inference assert!(&x == &mut y, 42); // inferred freeze(&mut y) } fun assignment_examples() { let x = 0; let y = 0; let imm_ref: &u64 = &x; imm_ref = &x; // no inference imm_ref = &mut y; // inferred freeze(&mut y) } ``` ## Subtyping With this freeze inference, the Move type checker can view `&mut T` as a subtype of `&T`. As shown above, this means that anywhere for any expression where a `&T` value is used, a `&mut T` value can also be used. This terminology is used in error messages to concisely indicate that a `&mut T` was needed where a `&T` was supplied. For example: ```move module 0x42::example { fun read_and_assign(store: &mut u64, new_value: &u64) { *store = *new_value } fun subtype_examples() { let x: &u64 = &0; let y: &mut u64 = &mut 1; x = &mut 1; // valid y = &2; // invalid! read_and_assign(y, x); // valid read_and_assign(x, y); // invalid! } } ``` The invalid assignments will yield error messages indicating subtype mismatches: ``` error: ┌── example.move:12:9 ─── │ 12 │ y = &2; // invalid! │ ^ Invalid assignment to local 'y' · 12 │ y = &2; // invalid! │ -- The type: '&{integer}' · 9 │ let y: &mut u64 = &mut 1; │ -------- Is not a subtype of: '&mut u64' ``` <Callout type="info"> **Note**: The only other types currently that have subtyping are tuples. </Callout> ## Ownership Both mutable and immutable references can always be copied and extended even if there are existing copies or extensions of the same reference: ```move struct S { f: u64 } fun reference_copies(s: &mut S) { let s_copy1 = s; // ok let s_extension = &mut s.f; // also ok let s_copy2 = s; // still ok // ... } ``` This might be surprising for programmers familiar with Rust's ownership system, which would reject the code above. Move's type system is more permissive in its treatment of copies, but equally strict in ensuring unique ownership of mutable references before writes. ## Storage Limitations References and tuples are the only types that cannot be stored as a field value of structs, which also means that they cannot exist in global storage. All references created during program execution will be destroyed when a Move program terminates; they are entirely ephemeral. This invariant is also true for values of types without the `store` ability, but note that references and tuples go a step further by never being allowed in structs in the first place. ```move struct Container { // value_ref: &u64, // Error: references cannot be stored value: u64, // OK: store the value directly } ``` <Callout type="warning"> **Important**: References are ephemeral and exist only during program execution. </Callout> ## Common Use Cases ### Function Parameters ```move fun process_data(data: &vector<u8>) { // Read-only access to vector without taking ownership let length = vector::length(data); } fun modify_data(data: &mut vector<u8>) { // Can modify the vector vector::push_back(data, 42); } ``` ### Struct Field Access ```move struct Account { balance: u64 } fun check_balance(account: &Account): u64 { account.balance // Access field through reference } fun deposit(account: &mut Account, amount: u64) { account.balance = account.balance + amount; } ``` ## Summary References in Move provide: * **Safe borrowing** without ownership transfer * **Two types**: immutable `&T` for reading, mutable `&mut T` for reading and writing * **Automatic conversions** from mutable to immutable references when needed * **Ephemeral nature** - exist only during execution, cannot be stored * **Resource safety** by enforcing ability requirements References are essential for efficient data access without transferring ownership in Move. # Scripts URL: /devs/move-book/scripts # Scripts Scripts in Move are executable entry points similar to a `main` function in conventional programming languages. They serve as ephemeral code snippets that orchestrate interactions with published modules and facilitate updates to global storage. ## Overview Scripts are **not published** to global storage, making them temporary execution units that primarily invoke functions from published modules. They provide a way to execute Move code without permanently storing it on the blockchain. ## Script Structure A script follows a specific structural pattern that must be adhered to: ```move script { <use>* <constants>* fun <identifier><[type parameters: constraint]*>([identifier: type]*) <function_body> } ``` ### Structure Requirements The script block must follow this exact order: 1. **Use declarations** - All import statements must come first 2. **Constants** - Any constant definitions follow the imports 3. **Main function** - A single function declaration that serves as the entry point ### Main Function Characteristics * Can have **any name** (doesn't need to be called `main`) * Must be the **only function** in the script block * Can accept **any number of arguments** * **Must not return a value** ## Example Here's a complete example demonstrating all components of a valid script: ```move script { // Import use std::debug::print; // A constant const CONST: u8 = 0; // Main function (entry point) fun main(value: u64) { let result = value + (CONST as u64); print(&result); } } ``` ## What's NOT ALLOWED in Scripts The following code demonstrates elements that are **forbidden** in scripts and would cause compilation errors: ```move // This is INVALID in a script - for illustration only script { // Imports are ALLOWED use std::debug::print; // Friend declarations are NOT ALLOWED friend 0x1::otherModule; // Struct definitions are NOT ALLOWED public struct Struct {} // Additional function definitions are NOT ALLOWED fun function(_: &Struct) { /* function body */ } // Constants are ALLOWED const CONST: u8 = 0; // Only ONE main function is ALLOWED fun main() { print(&CONST); } } ``` ## Limitations Scripts have intentionally limited capabilities to maintain security and clarity: * Cannot declare `friend` functions * Cannot define `struct` types * Cannot directly access global storage * Can only invoke functions from published modules ## Use Cases Scripts are primarily used for: * **Transaction execution** - Orchestrating complex operations across multiple modules * **Testing and debugging** - Running temporary code without publishing # Signer URL: /devs/move-book/signer # Signer Type `signer` is a built-in Move resource type that represents a capability allowing the holder to act on behalf of a particular address. It's a fundamental security primitive that ensures only authenticated users can perform operations on their accounts. ## What is a Signer? A `signer` is conceptually similar to a cryptographic signature or authentication token: ```move // Conceptual representation (actual implementation is native) struct signer has drop { a: address } ``` <Callout type="info"> **Key Concept**: A `signer` proves that the holder has the authority to act on behalf of a specific address, similar to how a Unix UID represents an authenticated user. </Callout> ## Signer vs Address Understanding the difference between `signer` and `address` is crucial: | Type | Creation | Purpose | Security | | --------- | ------------------------ | --------------------- | -------------------------- | | `address` | Can be created by anyone | Represents a location | No authentication required | | `signer` | Only created by the VM | Proves authentication | Cannot be forged | ### Address Creation Anyone can create any address value without special permission: ```move fun address_examples() { let a1 = @0x1; let a2 = @0x2; let a3 = @0xABCD; // ... any address can be created } ``` ### Signer Creation However, signer values are special because they cannot be created via literals or instructions--only by the Move VM. Before the VM runs a script with parameters of type signer, it will automatically create signer values and pass them into the script: ```move script { use std::signer; fun main(s: signer) { assert!(signer::address_of(&s) == @0x42, 0); } } ``` <Callout type="warning"> **Security**: This function will abort if sent from any address other than `0x42`, providing authentication. </Callout> ## Using Signers in Functions Functions can accept signers as parameters to perform authenticated operations: ```move use std::signer; public entry fun create_account(account: &signer) { let addr = signer::address_of(account); // Only the account owner can call this for their address // ... account creation logic } ``` <Callout type="info"> **Multi-Signer Support**: Functions can accept multiple signers when operations require multiple parties to authenticate. </Callout> ## Signer Operators The `std::signer` standard library provides utility functions: | Function | Signature | Description | | ---------------- | --------------------- | ------------------------------------------ | | `address_of` | `(&signer): address` | Returns the address wrapped by the signer | | `borrow_address` | `(&signer): &address` | Returns a reference to the wrapped address | ### Using Signer Functions ```move use std::signer; public fun example_usage(account: &signer) { // Get the address from a signer let addr: address = signer::address_of(account); // Get a reference to the address let addr_ref: &address = signer::borrow_address(account); // Use the address for operations assert!(addr == @0x123, 0); } ``` ## Global Storage Operations The `signer` is required for publishing resources to global storage: ```move use std::signer; struct UserProfile has key { name: vector<u8>, } public fun create_profile(account: &signer, name: vector<u8>) { let profile = UserProfile { name }; // move_to requires a signer to ensure only the account owner // can publish resources under their address move_to(account, profile); } ``` <Callout type="info"> **Security Guarantee**: Only the authenticated user can publish resources under their address using `move_to<T>(&signer, T)`. </Callout> ## Ownership and Abilities Unlike simple scalar values, signer values are **not copyable**: ```move public fun ownership_example(s: &signer) { // Signers are NOT copyable // let s_copy = *s; // Error: signer does not have copy ability // Must use references to pass signers around let addr = signer::address_of(s); // OK: borrowing } ``` <Callout type="warning"> **Important**: Always use references (`&signer`) when passing signers to functions since they cannot be copied. </Callout> ## Summary The `signer` type in Move provides: * **Authentication** - proves the holder can act for a specific address * **Security** - cannot be forged, only created by the VM * **Access Control** - required for publishing resources and state changes * **Multi-party Operations** - enables atomic transactions requiring multiple signers * **Non-copyable** - must be passed by reference to maintain security Signers are essential for secure Move programming, ensuring that only authenticated users can perform operations on their accounts and resources. # Structs and Resources URL: /devs/move-book/structsAndResources # Structs and Resources Structs are custom data types that contain typed fields and form the foundation of Move's type system. They can hold any non-reference values, including other structs, and are essential for modeling both simple data and complex data structures. Move structs have unique **ownership semantics** by default: * **Linear**: Values cannot be copied - they must be explicitly moved or transferred * **Ephemeral**: Values cannot be dropped - they must be consumed or destructured * **Private**: Values cannot be stored in global storage without explicit abilities When structs have these default properties, we call them **resources** - perfect for representing valuable assets like tokens, NFTs, or account balances where duplication or accidental loss would be problematic. You can grant structs **abilities** (`copy`, `drop`, `store`, `key`) to relax these restrictions and enable different behaviors based on your use case. ## Defining Structs Structs are declared within modules using the `struct` keyword. Each struct defines a custom type with named, typed fields that can hold data: ```move module 0x2::game { struct Player { level: u64, active: bool } // struct with fields struct Team {} // empty struct struct Match { player: Player, } // nested struct (trailing comma allowed) } ``` **Key rules for struct definitions:** * Must be declared inside a module * Can contain zero or more typed fields * Fields can be primitive types, other structs, or generic types * Trailing commas are permitted for better code formatting ### Recursive Structs Move prevents recursive struct definitions to ensure memory safety and avoid infinite data structures: ```move struct Node { next: Node } // ERROR: cyclic data struct Tree { left: Tree } // ERROR: cyclic data ``` **Why this restriction exists:** * Prevents infinite memory allocation * Ensures predictable struct sizes at compile time * Maintains Move's safety guarantees ### Struct Abilities Abilities control what operations are permitted on struct values. By default, structs have **no abilities**, making them resources. You can grant specific abilities using the `has` keyword: ```move module 0x2::game { struct Player has copy, drop { level: u64, active: bool } // copyable and droppable struct Token has store { amount: u64 } // storable only struct Account has key { balance: u64 } // global storage capable struct Resource { value: u64 } // no abilities (pure resource) } ``` **The four abilitie
프로젝트로 돌아가기