bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 33쪽 중 13쪽
ve loop variables** - `i`, `j`, `k` for simple counters, meaningful names for complex logic
2. **Avoid infinite loops** unless specifically needed
3. **Use `for` loops for ranges** - more readable than manual while loop counters
4. **Consider vector iteration patterns** - use appropriate vector functions when possible
5. **Handle edge cases** - empty vectors, zero ranges, etc.
## Common Patterns
### Accumulator Pattern
```move
fun sum_of_squares(v: &vector<u64>): u64 {
let sum = 0;
for (i in 0..vector::length(v)) {
let val = *vector::borrow(v, i);
sum = sum + (val * val);
};
sum
}
```
### Search Pattern
```move
fun find_last_occurrence(v: &vector<u64>, target: u64): u64 {
let last_index = vector::length(v); // Use length as "not found" indicator
for (i in 0..vector::length(v)) {
if (*vector::borrow(v, i) == target) {
last_index = i;
};
};
last_index
}
```
### Filter Pattern
```move
fun filter_multiples_of_three(v: &vector<u64>): vector<u64> {
let result = vector::empty();
for (i in 0..vector::length(v)) {
let val = *vector::borrow(v, i);
if (val % 3 == 0 && val > 0) {
vector::push_back(&mut result, val);
};
};
result
}
```
## Summary
Move provides three loop constructs for repetitive execution and iteration:
* **`while`**: Condition-based loops that repeat while a boolean condition is true
* **`loop`**: Infinite loops that require explicit `break` statements to exit
* **`for`**: Range-based iteration over numeric ranges with `start..end` syntax
* **Control flow**: Use `break` to exit loops early and `continue` to skip to next iteration
* **Performance**: Choose the right loop type and minimize work inside loop bodies
Loops enable efficient iteration patterns while maintaining Move's safety guarantees.
# Modules
URL: /devs/move-book/modules
# Modules
Modules are the fundamental building blocks of on-chain logic. They act as libraries that define structs (data types) and functions (behaviors) that operate on those structs.
Structs describe the schema of Move’s global storage, determining how data is organized and stored on-chain, while module functions define the rules and permissions for creating, reading, and updating that data.
## Key Characteristics of Modules:
* **Encapsulation**: Modules group related structs and functions together
* **Reusability**: Modules can be imported and used by other modules
* **Security**: Modules enforce access control and data privacy
* **Global Storage**: Modules define how data is stored on the blockchain
## Syntax of Modules
Modules are defined using the module keyword, followed by the address and identifier of the module. Modules can be declared using named addresses.
Named addresses are declared at the source language level in Move syntax and replaced at the bytecode level with the actual address.
```move
module <address>::<identifier> {
(<use> | <friend> | <type> | <function> | <constant>)*
}
```
**Module members include:**
* **use**: Import declarations (`use <address>::<identifier>`)
* **friend**: Friend module declarations (`friend <address>::<identifier>`)
* **struct**: Type definitions (`struct <name> { ... }`)
* **function**: Function definitions (`fun <name>(<parameters>) -> <return_type> { ... }`)
* **const**: Constant declarations (`const <name>: <type> = <value>`)
The module members can be defined at the source code level in this way:
```move
module test::MyModule {
// import
use std::debug::print;
// friend
friend 0x1::otherModule;
// a struct
struct Struct {}
// function
fun function(_: &Struct) { /* function body */ }
// a constant
const CONST: u8 = 0;
}
```
## Example of Modules
Let's create a simple module that defines a struct and a function to create an instance of that struct.
```move
module test::MyModule {
use std::debug::print;
struct MyStruct {
field: u64
}
fun create_my_struct(field: u64): MyStruct {
let my_struct = MyStruct { field }
print(&my_struct);
my_struct
}
}
```
In this example, we define a module named `MyModule` using the named address `test`. The module contains:
* A struct named `MyStruct` with a single field of type `u64`
* A function named `create_my_struct` that takes a `u64` parameter and returns an instance of `MyStruct`
> **Note:** During compilation, the named address `test` is replaced with a real address (like `0x1` in the example below).
```move
module 0x1::MyModule {
use std::debug::print;
struct MyStruct {
field: u64
}
fun create_my_struct(field: u64): MyStruct {
let my_struct = MyStruct { field }
print(&my_struct);
my_struct
}
}
```
## Module Naming Conventions
Module names must adhere to the following rules:
* Must start with a letter (`a-z` or `A-Z`)
* After the first character, can contain underscores (`_`), letters (`a-z`, `A-Z`), or digits (`0-9`)
* Cannot be Move keywords (e.g., `move`, `public`, `fun`, etc.)
## Module Addresses
Modules are published at specific addresses on the blockchain. There are two ways to specify addresses:
### Named Addresses
Used during development for readability:
```move
module my_project::token {
// module content
}
```
### Literal Addresses
The actual hexadecimal addresses used on-chain:
```move
module 0x1::token {
// module content
}
```
<Callout type="info">
Named addresses must be configured in your `Move.toml` file to map to actual addresses during compilation.
</Callout>
## Module Publication
Once a module is published to an address:
* All its public functions and structs become available to other modules
* The module's bytecode is stored permanently on the blockchain
* Gas fees are required for publication
# Options
URL: /devs/move-book/options
# Options
The `Option<T>` type defines a generic option that represents a value of type `T` that may, or may not, be present. It defined in the standard library and provides a type-safe way to handle optional values.
```move
/// Generic type abstraction of a value that may, or may not, be present.
/// Can contain a value of either resource or copyable kind.
struct Option<T>;
```
## Option Variants
The Option type has two conceptual variants:
* **Some**: Contains a value of type `T`
* **None**: Represents the absence of a value
These variants provide a type-safe way to handle optional data without relying on null pointers or special sentinel values.
## Why Use Option?
Consider an application that takes user input where some fields are required and others are optional. For example, a user's middle name is optional.
While we could use an empty string to represent the absence of a middle name, it would require extra checks to differentiate between an empty string and a missing middle name. Instead, we can use the Option type:
```move
module book::user_registry;
use std::string::String;
use std::option::Option;
/// A struct representing a user record.
public struct User has drop {
first_name: String,
middle_name: Option<String>,
last_name: String,
}
/// Create a new `User` struct with the given fields.
public fun register(
first_name: String,
middle_name: Option<String>,
last_name: String,
): User {
User { first_name, middle_name, last_name }
}
```
In this example, the `middle_name` field is of type `Option<String>`. This makes the optional nature of the field clear and type-safe.
## Creating Option Values
### Creating Empty Options
Use `option::none<T>()` to create an empty Option that can contain a value of type `T`:
```move
let empty_name: Option<vector<u8>> = option::none();
let empty_age: Option<u8> = option::none();
let empty_address: Option<address> = option::none();
```
### Creating Non-Empty Options
Use `option::some<T>(value)` to create an Option containing a value:
```move
let name_opt = option::some(b"Alice");
let age_opt = option::some(25u8);
let address_opt = option::some(@0x1);
```
## Option Operations
### Checking Option State
```move
let opt = option::some(b"Alice");
let empty: Option<u64> = option::none();
// Check if option contains a value
assert!(option::is_some(&opt) == true);
assert!(option::is_some(&empty) == false);
// Check if option is empty
assert!(option::is_none(&opt) == false);
assert!(option::is_none(&empty) == true);
```
### Borrowing Values
Return references to the value inside the option:
```move
let opt = option::some(b"Alice");
// Borrow immutable reference (aborts if empty)
let name_ref = option::borrow(&opt);
assert!(*name_ref == b"Alice");
// Borrow with default reference (never aborts)
let default_name = b"Unknown";
let name_or_default = option::borrow_with_default(&opt, &default_name);
// Borrow mutable reference (aborts if empty)
let opt = option::some(100u64);
let value_ref = option::borrow_mut(&mut opt);
*value_ref
```
### Extracting and Destroying Values
```move
let opt = option::some(b"Alice");
// Extract value, leaving option empty (aborts if empty)
let inner = option::extract(&opt);
assert!(inner == b"Alice");
assert!(option::is_none(&opt));
// Destroy and return value (aborts if empty)
let opt2 = option::some(42u64);
let value = option::destroy_some(opt2);
assert!(value == 42);
// Destroy with default (requires copyable type)
let opt3: Option<u64> = option::none();
let value_or_default = option::destroy_with_default(opt3, 100);
assert!(value_or_default == 100);
// Destroy empty option (aborts if contains value)
let empty_opt: Option<u64> = option::none();
option::destroy_none(empty_opt);
```
### Advanced Operations
```move
// Get value with default (requires copyable type)
let opt: Option<u64> = option::some(42);
let value = option::get_with_default(&opt, 100);
assert!(value == 42);
let empty_opt: Option<u64> = option::none();
let default_value = option::get_with_default(&empty_opt, 100);
assert!(default_value == 100);
// Fill empty option with value (aborts if already contains value)
let empty_opt: Option<u64> = option::none();
option::fill(&empty_opt, 42);
assert!(option::is_some(&empty_opt));
// Swap value in option (aborts if empty)
let opt = option::some(100u64);
let old_value = option::swap(&opt, 200);
assert!(old_value == 100);
assert!(*option::borrow(&opt) == 200);
// Check if option contains specific value
let opt = option::some(42u64);
assert!(option::contains(&opt, &42) == true);
assert!(option::contains(&opt, &100) == false);
```
## Common Usage Patterns
### Safe Value Access with Default
```move
public fun get_user_display_name(user: &User): vector<u8> {
if (option::is_some(&user.middle_name)) {
let middle = option::borrow(&user.middle_name);
// Construct full name with middle name
b"Full name with middle"
} else {
// Construct name without middle name
b"Name without middle"
}
}
```
### Option in Function Parameters
```move
public fun create_user_with_optional_email(
name: vector<u8>,
email: Option<vector<u8>>
): User {
User { name, email, verified: false }
}
// Usage
let user1 = create_user_with_optional_email(
b"Alice",
option::some(b"alice@example.com")
);
let user2 = create_user_with_optional_email(
b"Bob",
option::none()
);
```
### Option in Return Values
```move
public fun find_user_by_id(users: &vector<User>, id: u64): Option<User> {
let i = 0;
let len = vector::length(users);
while (i < len) {
let user = vector::borrow(users, i);
if (user.id == id) {
return option::some(*user)
};
i = i + 1;
};
option::none()
}
```
## Practical Examples
### Configuration with Defaults
```move
module app::config {
public struct Config has key {
max_users: Option<u64>,
timeout: Option<u64>,
}
public fun get_max_users_or_default(config: &Config): u64 {
option::get_with_default(&config.max_users, 1000)
}
public fun get_timeout_or_default(config: &Config): u64 {
option::get_with_default(&config.timeout, 30)
}
}
```
### Safe Mathematical Operations
```move
module app::math {
public fun safe_divide(a: u64, b: u64): Option<u64> {
if (b == 0) {
option::none()
} else {
option::some(a / b)
}
}
public fun safe_sqrt(x: u64): Option<u64> {
// Simplified square root that only works for perfect squares
let i = 0;
while (i * i <= x) {
if (i * i == x) {
return option::some(i)
};
i = i + 1;
};
option::none()
}
}
```
## Best Practices
### 1. Use Option for Truly Optional Data
```move
// Good: Optional fields that may genuinely be absent
public struct User {
name: vector<u8>,
email: Option<vector<u8>>, // Optional
phone: Option<vector<u8>>, // Optional
}
// Avoid: Using Option for required data
public struct User {
name: Option<vector<u8>>, // Don't do this if name is required
}
```
### 2. Prefer get\_with\_default for Copyable Types
```move
// Good: Use get_with_default for simple defaults
public fun get_retry_count(config: &Config): u8 {
option::get_with_default(&config.retry_count, 3)
}
// Less ideal: Manual checking
public fun get_retry_count_manual(config: &Config): u8 {
if (option::is_some(&config.retry_count)) {
*option::borrow(&config.retry_count)
} else {
3
}
}
```
### 3. Handle Resource Types Carefully
```move
// For resource types, you cannot use get_with_default
public fun process_resource_option(opt: Option<SomeResource>): SomeResource {
if (option::is_some(&opt)) {
option::extract(&opt)
} else {
// Must create new resource, cannot use default
create_new_resource()
}
}
```
## Ownership
Option values follow standard Move ownership rules:
* **Copy**: If `T` has `copy`, then `Option<T>` has `copy`
* **Drop**: If `T` has `drop`, then `Option<T>` has `drop`
* **Store**: Option always has `store` ability
```move
let opt1 = option::some(10u64); // u64 has copy
let opt2 = copy opt1; // Can copy because u64 has copy
let opt3 = option::some(vector[1, 2, 3]); // vector doesn't have copy
// let opt4 = copy opt3; // Error: cannot copy
let opt4 = opt3; // Must move
```
**Important**: Some operations like `get_with_default` and `destroy_with_default` require the element type `T` to have the `copy` ability.
## Summary
The Option type in Move provides:
* **Type-safe handling** of values that may or may not be present
* **Resource-aware operations** that work with both copyable and resource types
* **Comprehensive API** for creating, checking, borrowing, and destroying options
* **Explicit null handling** without null pointer errors
Key operations:
* **Creation**: `none()`, `some()`
* **Checking**: `is_some()`, `is_none()`, `contains()`
* **Access**: `borrow()`, `borrow_mut()`, `borrow_with_default()`
* **Extraction**: `extract()`, `get_with_default()`, `swap()`
* **Destruction**: `destroy_some()`, `destroy_none()`, `destroy_with_default()`
Use Option for:
* Optional struct fields
* Function parameters that may be omitted
* Return values from operations that may fail
* Configuration settings with defaults
* Safe handling of potentially absent data
The Option type is essential for writing robust Move code that handles the absence of values safely and explicitly.
# Packages
URL: /devs/move-book/package
# Packages
Move packages provide a structured system for organizing code, managing dependencies, and sharing reusable components across projects. The package system enables modular development with clear dependency relationships and parameterized addresses.
**Key capabilities:**
* **Code organization**: Structure modules and scripts in a standardized layout
* **Dependency management**: Import and version external packages
* **Address parameterization**: Configure named addresses for different environments
* **Build artifacts**: Generate bytecode, documentation, and source maps
* **Reusability**: Share packages across multiple projects
Packages are fundamental to professional Move development, enabling teams to build maintainable, modular applications with clear separation of concerns.
## Package Structure
### Directory Layout
A Move package follows a standardized directory structure:
```
my_defi_project/
├── Move.toml # Package manifest (required)
├── sources/ # Move modules (required)
│ ├── token.move
│ └── pool.move
├── tests/ # Unit tests (optional)
│ └── token_tests.move
├── scripts/ # Move scripts (optional)
│ └── mint_script.move
├── examples/ # Example code (optional)
│ └── basic_usage.move
└── doc_templates/ # Documentation templates (optional)
```
**Directory purposes:**
* **sources/**: Contains the main Move modules and scripts
* **tests/**: Test modules included only in test mode
* **examples/**: Tutorial and development code (dev/test mode only)
* **doc\_templates/**: Templates for generated documentation
## Package Manifest (Move.toml)
### Basic Configuration
The `Move.toml` file defines package metadata and dependencies:
```toml
[package]
name = "hello_blockchain"
version = "1.0.0"
authors = []
[addresses]
hello_blockchain = "0xc48ec9d15e56d71e035333c7d1d7c3c80d66210a940f6583d63a63608a274ab1"
[dev-addresses]
[dependencies.AptosFramework]
git = "https://github.com/movement-network/aptos-core.git"
rev = "movement"
subdir = "aptos-move/framework/aptos-framework"
[dev-dependencies]
```
**Configuration sections:**
* **\[package]**: Basic metadata like name, version, and authors
* **\[addresses]**: Named address declarations and assignments
* **\[dependencies]**: External package dependencies
* **\[dev-dependencies]**: Development-only dependencies
### Dependency Types
```toml
[dependencies.AptosFramework]
git = "https://github.com/movement-network/aptos-core.git"
rev = "movement"
subdir = "aptos-move/framework/aptos-framework"
# Local dependency
[dependencies.Utils]
local = "../shared-utils"
[dev-dependencies.TestHelpers]
local = "../test-utils"
```
**Dependency options:**
* **git**: Remote Git repository with revision and subdirectory
* **local**: Path to local package directory
* **rev**: Specific commit or branch to use
* **subdir**: Subdirectory within the repository
## Named Addresses
### Address Declaration
Named addresses provide flexible address management across environments:
```move
// In Move.toml
[addresses]
protocol = "_" # Unassigned - can be set by importing packages
treasury = "0xTREAS" # Fixed - always this specific address
// In Move code
module protocol::vault {
struct Treasury has key {
balance: u64
}
public fun get_treasury_address(): address {
@treasury
}
}
```
### Address Configuration
Packages can configure addresses for different environments:
```toml
[addresses]
hello_blockchain = "0xc48ec9d15e56d71e035333c7d1d7c3c80d66210a940f6583d63a63608a274ab1"
protocol = "0x1234567890abcdef"
[dev-addresses]
protocol = "0xDEV123"
treasury = "0xDEVTREAS"
```
**Address configuration:**
* **\[addresses]**: Production addresses used in normal builds
* **\[dev-addresses]**: Development addresses used with `--dev` flag
* **Named addresses**: Can be overridden via CLI with `--named-addresses`
## Build System
### Compilation Process
```bash
# Compile the package
movement move compile
# Compile in development mode
movement move compile --dev
# Fetch dependencies only
movement move compile --fetch-deps-only
# Save metadata during compilation
movement move compile --save-metadata
```
### Build Artifacts
The build process generates organized artifacts:
```
build/
├── BuildInfo.yaml
├── bytecode_modules/
│ ├── dependencies/
│ │ └── MoveStdlib/
│ │ └── *.mv
│ └── *.mv
├── source_maps/
│ └── *.mvsm
└── docs/
└── *.md
```
**Artifact types:**
* **bytecode\_modules/**: Compiled Move bytecode (.mv files)
* **source\_maps/**: Debug information (.mvsm files)
* **docs/**: Generated documentation
* **BuildInfo.yaml**: Build metadata and configuration
### Compilation Features
Movement's compilation system provides advanced features:
* **Dependency management**: Automatic fetching and version resolution
* **Optimization levels**: None, default, or extra optimization
* **Bytecode versioning**: Specify target bytecode version
* **Development mode**: Use dev-addresses and dev-dependencies with `--dev`
* **Metadata generation**: Save compilation metadata for debugging
* **Standard library overrides**: Choos프로젝트로 돌아가기