aptos

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Aptos Blockchain & Move Language Expert

Aptos区块链与Move语言专家

Aptos is a Layer 1 blockchain with the Move programming language, designed for safe and scalable smart contracts.
Aptos是采用Move编程语言的Layer 1区块链,专为安全且可扩展的智能合约设计。

When to Use

适用场景

  • Writing Move smart contracts
  • Understanding Move type system (abilities, generics, resources)
  • Using Aptos framework modules (coin, fungible_asset, object)
  • Token standards (Coin, Fungible Asset, Digital Asset/NFT)
  • Gas optimization and testing
  • dApp integration with TypeScript SDK
  • 编写Move智能合约
  • 理解Move类型系统(abilities、泛型、资源)
  • 使用Aptos框架模块(coin、fungible_asset、object)
  • 代币标准(Coin、Fungible Asset、Digital Asset/NFT)
  • Gas优化与测试
  • 基于TypeScript SDK的dApp集成

Move Language Fundamentals

Move语言基础

Abilities - Move's Core Feature

Abilities - Move的核心特性

Every type has abilities that control what you can do with it:
AbilityMeaningExample
copy
Can be duplicatedPrimitives, configs
drop
Can be discardedTemporary data
store
Can be stored in structsMost data types
key
Can be top-level resourceAccount resources
move
// Resource that can be stored globally
struct Balance has key, store {
    coins: u64
}

// Value type that behaves like a primitive
struct Point has copy, drop, store {
    x: u64,
    y: u64
}

// No abilities = must be explicitly handled (hot potato)
struct Receipt {
    amount: u64
}
每种类型都具备abilities,用于控制该类型的可用操作:
能力含义示例
copy
可复制基本类型、配置项
drop
可丢弃临时数据
store
可存储在结构体中大多数数据类型
key
可作为顶级资源账户资源
move
// 可全局存储的资源
struct Balance has key, store {
    coins: u64
}

// 表现类似基本类型的值类型
struct Point has copy, drop, store {
    x: u64,
    y: u64
}

// 无能力 = 必须显式处理(烫手山芋模式)
struct Receipt {
    amount: u64
}

Generics and Phantom Types

泛型与幻影类型

move
// Type parameter with ability constraint
struct Box<T: store> has key {
    value: T
}

// Phantom type - zero runtime cost, type safety only
struct Coin<phantom CoinType> has store {
    value: u64
}

// Different types can't be mixed
let btc: Coin<BTC> = Coin { value: 100 };
let eth: Coin<ETH> = Coin { value: 50 };
// btc + eth → compile error!
move
// 带有能力约束的类型参数
struct Box<T: store> has key {
    value: T
}

// 幻影类型 - 零运行时开销,仅提供类型安全
struct Coin<phantom CoinType> has store {
    value: u64
}

// 不同类型无法混合
let btc: Coin<BTC> = Coin { value: 100 };
let eth: Coin<ETH> = Coin { value: 50 };
// btc + eth → 编译错误!

Global Storage Operations

全局存储操作

move
// Store resource at signer's address
public fun initialize(account: &signer) {
    move_to(account, MyResource { value: 0 });
}

// Read resource (requires acquires annotation)
public fun get_value(addr: address): u64 acquires MyResource {
    borrow_global<MyResource>(addr).value
}

// Modify resource
public fun set_value(addr: address, val: u64) acquires MyResource {
    borrow_global_mut<MyResource>(addr).value = val;
}

// Check existence
public fun exists_at(addr: address): bool {
    exists<MyResource>(addr)
}

// Remove and return resource
public fun destroy(addr: address): MyResource acquires MyResource {
    move_from<MyResource>(addr)
}
move
// 将资源存储在签名者地址下
public fun initialize(account: &signer) {
    move_to(account, MyResource { value: 0 });
}

// 读取资源(需要acquires注解)
public fun get_value(addr: address): u64 acquires MyResource {
    borrow_global<MyResource>(addr).value
}

// 修改资源
public fun set_value(addr: address, val: u64) acquires MyResource {
    borrow_global_mut<MyResource>(addr).value = val;
}

// 检查存在性
public fun exists_at(addr: address): bool {
    exists<MyResource>(addr)
}

// 移除并返回资源
public fun destroy(addr: address): MyResource acquires MyResource {
    move_from<MyResource>(addr)
}

Signer - Authentication

Signer - 身份验证

move
use std::signer;

// Only the account owner can call this
public entry fun transfer(
    sender: &signer,
    recipient: address,
    amount: u64
) acquires Balance {
    let sender_addr = signer::address_of(sender);
    // sender proves ownership of sender_addr
}
move
use std::signer;

// 仅账户所有者可调用此函数
public entry fun transfer(
    sender: &signer,
    recipient: address,
    amount: u64
) acquires Balance {
    let sender_addr = signer::address_of(sender);
    // 发送者证明对sender_addr的所有权
}

Visibility Modifiers

可见性修饰符

move
module example {
    // Private (default) - only within module
    fun internal() { }

    // Public - callable from anywhere
    public fun library_fn() { }

    // Friend - only from declared friend modules
    public(friend) fun restricted() { }

    // Entry - transaction entry point
    public entry fun user_action(account: &signer) { }
}
move
module example {
    // 私有(默认)- 仅模块内可访问
    fun internal() { }

    // 公共 - 可从任意位置调用
    public fun library_fn() { }

    // 友元 - 仅声明的友元模块可访问
    public(friend) fun restricted() { }

    // 入口 - 交易入口点
    public entry fun user_action(account: &signer) { }
}

Aptos Framework (0x1)

Aptos框架(0x1)

Core Modules

核心模块

ModulePurpose
account
Account creation, auth key rotation
coin
Original fungible token standard
fungible_asset
New flexible token standard
object
Object model for composable assets
aptos_coin
Native APT token
timestamp
Block timestamp
event
Event emission
模块用途
account
账户创建、认证密钥轮换
coin
原始可替代代币标准
fungible_asset
新型灵活代币标准
object
用于可组合资产的对象模型
aptos_coin
原生APT代币
timestamp
区块时间戳
event
事件发射

Coin Standard (0x1::coin)

Coin标准(0x1::coin)

move
use aptos_framework::coin;

// Register to receive a coin type
public entry fun register<CoinType>(account: &signer) {
    coin::register<CoinType>(account);
}

// Transfer coins
public entry fun transfer<CoinType>(
    from: &signer,
    to: address,
    amount: u64
) {
    coin::transfer<CoinType>(from, to, amount);
}

// Check balance
public fun balance<CoinType>(addr: address): u64 {
    coin::balance<CoinType>(addr)
}
move
use aptos_framework::coin;

// 注册以接收某类代币
public entry fun register<CoinType>(account: &signer) {
    coin::register<CoinType>(account);
}

// 转移代币
public entry fun transfer<CoinType>(
    from: &signer,
    to: address,
    amount: u64
) {
    coin::transfer<CoinType>(from, to, amount);
}

// 查询余额
public fun balance<CoinType>(addr: address): u64 {
    coin::balance<CoinType>(addr)
}

Fungible Asset Standard (0x1::fungible_asset)

可替代资产标准(0x1::fungible_asset)

Modern, flexible token standard:
move
use aptos_framework::fungible_asset::{Self, FungibleAsset, Metadata};
use aptos_framework::primary_fungible_store;

// Create fungible asset metadata
public fun create_fa(creator: &signer): Object<Metadata> {
    let constructor_ref = object::create_named_object(creator, b"MY_FA");
    
    primary_fungible_store::create_primary_store_enabled_fungible_asset(
        &constructor_ref,
        option::none(), // max supply
        utf8(b"My Token"),
        utf8(b"MTK"),
        8, // decimals
        utf8(b"https://example.com/icon.png"),
        utf8(b"https://example.com"),
    );
    
    object::object_from_constructor_ref(&constructor_ref)
}

// Transfer FA
public entry fun transfer_fa(
    sender: &signer,
    metadata: Object<Metadata>,
    recipient: address,
    amount: u64
) {
    primary_fungible_store::transfer(sender, metadata, recipient, amount);
}
现代化、灵活的代币标准:
move
use aptos_framework::fungible_asset::{Self, FungibleAsset, Metadata};
use aptos_framework::primary_fungible_store;

// 创建可替代资产元数据
public fun create_fa(creator: &signer): Object<Metadata> {
    let constructor_ref = object::create_named_object(creator, b"MY_FA");
    
    primary_fungible_store::create_primary_store_enabled_fungible_asset(
        &constructor_ref,
        option::none(), // 最大供应量
        utf8(b"My Token"),
        utf8(b"MTK"),
        8, // 小数位数
        utf8(b"https://example.com/icon.png"),
        utf8(b"https://example.com"),
    );
    
    object::object_from_constructor_ref(&constructor_ref)
}

// 转移可替代资产
public entry fun transfer_fa(
    sender: &signer,
    metadata: Object<Metadata>,
    recipient: address,
    amount: u64
) {
    primary_fungible_store::transfer(sender, metadata, recipient, amount);
}

Object Model (0x1::object)

对象模型(0x1::object)

Composable, transferable objects:
move
use aptos_framework::object::{Self, Object, ConstructorRef};

struct MyObject has key {
    value: u64
}

// Create object
public fun create(creator: &signer): Object<MyObject> {
    let constructor_ref = object::create_object(signer::address_of(creator));
    let object_signer = object::generate_signer(&constructor_ref);
    
    move_to(&object_signer, MyObject { value: 42 });
    
    object::object_from_constructor_ref(&constructor_ref)
}

// Transfer object
public entry fun transfer_object(
    owner: &signer,
    obj: Object<MyObject>,
    recipient: address
) {
    object::transfer(owner, obj, recipient);
}
可组合、可转移的对象:
move
use aptos_framework::object::{Self, Object, ConstructorRef};

struct MyObject has key {
    value: u64
}

// 创建对象
public fun create(creator: &signer): Object<MyObject> {
    let constructor_ref = object::create_object(signer::address_of(creator));
    let object_signer = object::generate_signer(&constructor_ref);
    
    move_to(&object_signer, MyObject { value: 42 });
    
    object::object_from_constructor_ref(&constructor_ref)
}

// 转移对象
public entry fun transfer_object(
    owner: &signer,
    obj: Object<MyObject>,
    recipient: address
) {
    object::transfer(owner, obj, recipient);
}

Token Standards

代币标准

Digital Asset (NFT) Standard

数字资产(NFT)标准

move
use aptos_token_objects::collection;
use aptos_token_objects::token;

// Create collection
public entry fun create_collection(creator: &signer) {
    collection::create_unlimited_collection(
        creator,
        utf8(b"My Collection Description"),
        utf8(b"My Collection"),
        option::none(), // royalty
        utf8(b"https://example.com/collection"),
    );
}

// Mint token
public entry fun mint_token(creator: &signer, to: address) {
    let token_constructor_ref = token::create(
        creator,
        utf8(b"My Collection"),
        utf8(b"Token description"),
        utf8(b"Token #1"),
        option::none(), // royalty
        utf8(b"https://example.com/token/1"),
    );
    
    let transfer_ref = object::generate_transfer_ref(&token_constructor_ref);
    let linear_transfer_ref = object::generate_linear_transfer_ref(&transfer_ref);
    object::transfer_with_ref(linear_transfer_ref, to);
}
move
use aptos_token_objects::collection;
use aptos_token_objects::token;

// 创建集合
public entry fun create_collection(creator: &signer) {
    collection::create_unlimited_collection(
        creator,
        utf8(b"My Collection Description"),
        utf8(b"My Collection"),
        option::none(), // 版税
        utf8(b"https://example.com/collection"),
    );
}

// 铸造代币
public entry fun mint_token(creator: &signer, to: address) {
    let token_constructor_ref = token::create(
        creator,
        utf8(b"My Collection"),
        utf8(b"Token description"),
        utf8(b"Token #1"),
        option::none(), // 版税
        utf8(b"https://example.com/token/1"),
    );
    
    let transfer_ref = object::generate_transfer_ref(&token_constructor_ref);
    let linear_transfer_ref = object::generate_linear_transfer_ref(&transfer_ref);
    object::transfer_with_ref(linear_transfer_ref, to);
}

Common Patterns

常见模式

Capability Pattern

能力模式

move
struct AdminCap has key, store {}

public fun init_module(deployer: &signer) {
    move_to(deployer, AdminCap {});
}

public entry fun admin_only(admin: &signer) acquires AdminCap {
    assert!(exists<AdminCap>(signer::address_of(admin)), E_NOT_ADMIN);
    // Admin-only logic
}
move
struct AdminCap has key, store {}

public fun init_module(deployer: &signer) {
    move_to(deployer, AdminCap {});
}

public entry fun admin_only(admin: &signer) acquires AdminCap {
    assert!(exists<AdminCap>(signer::address_of(admin)), E_NOT_ADMIN);
    // 仅管理员可执行的逻辑
}

Resource Account

资源账户

move
use aptos_framework::resource_account;

// Create resource account for deterministic addresses
public fun create_resource_account(creator: &signer): signer {
    let (resource_signer, _cap) = resource_account::create_resource_account(
        creator,
        b"seed"
    );
    resource_signer
}
move
use aptos_framework::resource_account;

// 创建资源账户以获取确定性地址
public fun create_resource_account(creator: &signer): signer {
    let (resource_signer, _cap) = resource_account::create_resource_account(
        creator,
        b"seed"
    );
    resource_signer
}

Events

事件

move
use aptos_framework::event;

#[event]
struct TransferEvent has drop, store {
    from: address,
    to: address,
    amount: u64,
}

public fun emit_transfer(from: address, to: address, amount: u64) {
    event::emit(TransferEvent { from, to, amount });
}
move
use aptos_framework::event;

#[event]
struct TransferEvent has drop, store {
    from: address,
    to: address,
    amount: u64,
}

public fun emit_transfer(from: address, to: address, amount: u64) {
    event::emit(TransferEvent { from, to, amount });
}

Testing

测试

move
#[test]
fun test_basic() {
    let x = 1 + 1;
    assert!(x == 2, 0);
}

#[test(account = @0x123)]
fun test_with_signer(account: &signer) {
    let addr = signer::address_of(account);
    assert!(addr == @0x123, 0);
}

#[test]
#[expected_failure(abort_code = E_NOT_FOUND)]
fun test_expected_failure() {
    abort E_NOT_FOUND
}
move
#[test]
fun test_basic() {
    let x = 1 + 1;
    assert!(x == 2, 0);
}

#[test(account = @0x123)]
fun test_with_signer(account: &signer) {
    let addr = signer::address_of(account);
    assert!(addr == @0x123, 0);
}

#[test]
#[expected_failure(abort_code = E_NOT_FOUND)]
fun test_expected_failure() {
    abort E_NOT_FOUND
}

CLI Commands

CLI命令

bash
undefined
bash
undefined

Initialize project

初始化项目

aptos init
aptos init

Compile

编译

aptos move compile
aptos move compile

Test

测试

aptos move test
aptos move test

Publish

发布

aptos move publish --profile mainnet
aptos move publish --profile mainnet

Run function

执行函数

aptos move run --function-id 'addr::module::function'
undefined
aptos move run --function-id 'addr::module::function'
undefined

Gas Optimization

Gas优化

  • Use
    inline
    for small frequently-called functions
  • Prefer
    Table
    over
    vector
    for large collections
  • Minimize storage operations (most expensive)
  • Use
    SmartTable
    for parallel execution
  • Batch operations when possible
  • 对小型高频调用函数使用
    inline
  • 大型集合优先使用
    Table
    而非
    vector
  • 尽量减少存储操作(开销最高)
  • 并行执行时使用
    SmartTable
  • 尽可能批量操作

TypeScript SDK

TypeScript SDK

typescript
import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";

const config = new AptosConfig({ network: Network.MAINNET });
const aptos = new Aptos(config);

// Query account balance
const balance = await aptos.getAccountAPTAmount({
    accountAddress: "0x1"
});

// Submit transaction
const txn = await aptos.transaction.build.simple({
    sender: account.accountAddress,
    data: {
        function: "0x1::coin::transfer",
        typeArguments: ["0x1::aptos_coin::AptosCoin"],
        functionArguments: [recipientAddress, amount],
    },
});

const result = await aptos.signAndSubmitTransaction({
    signer: account,
    transaction: txn,
});
typescript
import { Aptos, AptosConfig, Network } from "@aptos-labs/ts-sdk";

const config = new AptosConfig({ network: Network.MAINNET });
const aptos = new Aptos(config);

// 查询账户余额
const balance = await aptos.getAccountAPTAmount({
    accountAddress: "0x1"
});

// 提交交易
const txn = await aptos.transaction.build.simple({
    sender: account.accountAddress,
    data: {
        function: "0x1::coin::transfer",
        typeArguments: ["0x1::aptos_coin::AptosCoin"],
        functionArguments: [recipientAddress, amount],
    },
});

const result = await aptos.signAndSubmitTransaction({
    signer: account,
    transaction: txn,
});

Resources

参考资源