sui-bcs
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseBCS (Binary Canonical Serialization) Skill
BCS(Binary Canonical Serialization)技能文档
Overview
概述
BCS (Binary Canonical Serialization) is a binary serialization format designed for the Move programming language and widely used in the Sui blockchain ecosystem. The Sui TypeScript SDK provides a type-safe, efficient serialization system that supports primitive types, composite types, and Sui-specific types.
BCS(Binary Canonical Serialization,标准二进制序列化)是为Move编程语言设计的二进制序列化格式,在Sui区块链生态中被广泛使用。Sui TypeScript SDK提供了一个类型安全、高效的序列化系统,支持基本类型、复合类型以及Sui专属类型。
Quick Start
快速开始
Installation and Import
安装与导入
typescript
// Import BCS from @mysten/sui (includes Sui-specific types)
import { bcs } from '@mysten/sui/bcs';
// Or import base BCS from @mysten/bcs
import { bcs } from '@mysten/bcs';typescript
// 从@mysten/sui导入包含Sui专属类型的BCS
import { bcs } from '@mysten/sui/bcs';
// 或从@mysten/bcs导入基础BCS
import { bcs } from '@mysten/bcs';Basic Serialization Examples
基础序列化示例
typescript
import { bcs } from '@mysten/sui/bcs';
// Serialize primitive types
const u32Bytes = bcs.u32().serialize(42).toBytes();
const stringBytes = bcs.string().serialize("hello").toBytes();
// Deserialize
const value = bcs.u32().parse(u32Bytes);
const text = bcs.string().parse(stringBytes);
// Use Sui-specific types
const addressBytes = bcs.Address.serialize('0x0000...0000');
const address = bcs.Address.parse(addressBytes);typescript
import { bcs } from '@mysten/sui/bcs';
// 序列化基本类型
const u32Bytes = bcs.u32().serialize(42).toBytes();
const stringBytes = bcs.string().serialize("hello").toBytes();
// 反序列化
const value = bcs.u32().parse(u32Bytes);
const text = bcs.string().parse(stringBytes);
// 使用Sui专属类型
const addressBytes = bcs.Address.serialize('0x0000...0000');
const address = bcs.Address.parse(addressBytes);Core Components
核心组件
BCS Type System
BCS类型系统
The BCS type system is built on the generic class:
BcsType<T, I>- Type safety: Compile-time and runtime type checking
- Transformation support: Input/output type transformations
- Lazy evaluation: Supports recursive type definitions
- Validation: Runtime data validation
BCS类型系统基于泛型类构建:
BcsType<T, I>- 类型安全:编译时与运行时类型检查
- 转换支持:输入/输出类型转换
- 延迟求值:支持递归类型定义
- 验证:运行时数据验证
BcsType Base Class
BcsType基类
Location:
https://github.com/MystenLabs/ts-sdks/tree/main/packages/bcs/src/bcs-type.tsBcsType- Serialization/deserialization operations
- Type validation and transformation
- Base encoding support (Base58, Base64, Hex)
- Serialized size calculation
位置:
https://github.com/MystenLabs/ts-sdks/tree/main/packages/bcs/src/bcs-type.tsBcsType- 序列化/反序列化操作
- 类型验证与转换
- 基础编码支持(Base58、Base64、Hex)
- 序列化大小计算
BCS Factory Methods
BCS工厂方法
Location:
https://github.com/MystenLabs/ts-sdks/tree/main/packages/bcs/src/bcs.tsFactory methods create various BCS types:
- Primitive types: u8, u16, u32, u64, u128, u256, bool, string
- Composite types: struct, enum, tuple, vector, map, option
- Special types: Fixed arrays, byte vectors, LEB128 encoding
位置:
https://github.com/MystenLabs/ts-sdks/tree/main/packages/bcs/src/bcs.ts工厂方法用于创建各类BCS类型:
- 基本类型:u8, u16, u32, u64, u128, u256, bool, string
- 复合类型:struct, enum, tuple, vector, map, option
- 特殊类型:固定数组、字节向量、LEB128编码
Reader/Writer Components
读取器/写入器组件
- BcsReader: Reads from binary data
- BcsWriter: Writes to binary data
- SerializedBcs: Wrapper for serialized data, provides encoding methods
- BcsReader:读取二进制数据
- BcsWriter:写入二进制数据
- SerializedBcs:序列化数据的包装类,提供编码方法
Primitive Types
基本类型
For detailed information about primitive types including integers, booleans, and strings, see Primitive Types.
BCS supports the following primitive types:
- Integer types: u8, u16, u32, u64, u128, u256, uleb128 (variable-length)
- Boolean type: bool
- String type: UTF-8 encoded strings with LEB128 length prefix
关于整数、布尔值和字符串等基本类型的详细信息,请参阅基本类型。
BCS支持以下基本类型:
- 整数类型:u8, u16, u32, u64, u128, u256, uleb128(可变长度)
- 布尔类型:bool
- 字符串类型:带LEB128长度前缀的UTF-8编码字符串
Basic Usage
基本用法
typescript
// Integer serialization
const u32Bytes = bcs.u32().serialize(42).toBytes();
// Boolean serialization
const boolBytes = bcs.bool().serialize(true).toBytes();
// String serialization
const stringBytes = bcs.string().serialize("Hello").toBytes();typescript
// 整数序列化
const u32Bytes = bcs.u32().serialize(42).toBytes();
// 布尔值序列化
const boolBytes = bcs.bool().serialize(true).toBytes();
// 字符串序列化
const stringBytes = bcs.string().serialize("Hello").toBytes();Composite Types
复合类型
For comprehensive coverage of composite types including structs, enums, vectors, tuples, options, and maps, see Composite Types.
BCS provides the following composite types:
关于结构体、枚举、向量、元组、可选类型和映射等复合类型的全面介绍,请参阅复合类型。
BCS提供以下复合类型:
Struct
结构体
Organize related fields into named structures.
typescript
const Person = bcs.struct('Person', {
name: bcs.string(),
age: bcs.u8(),
balance: bcs.u64(),
});将相关字段组织为命名结构。
typescript
const Person = bcs.struct('Person', {
name: bcs.string(),
age: bcs.u8(),
balance: bcs.u64(),
});Enum
枚举
Define variant types with optional associated data.
typescript
const Status = bcs.enum('Status', {
Pending: null,
Active: bcs.u64(),
Inactive: bcs.string(),
});定义带可选关联数据的变体类型。
typescript
const Status = bcs.enum('Status', {
Pending: null,
Active: bcs.u64(),
Inactive: bcs.string(),
});Vector
向量
Collections of homogeneous elements.
typescript
const NumberVector = bcs.vector(bcs.u32());同类型元素的集合。
typescript
const NumberVector = bcs.vector(bcs.u32());Tuple
元组
Fixed-size collections of heterogeneous elements.
typescript
const Pair = bcs.tuple([bcs.string(), bcs.u64()]);固定大小的异构元素集合。
typescript
const Pair = bcs.tuple([bcs.string(), bcs.u64()]);Option
可选类型
Optional values (Some/None pattern).
typescript
const OptionalNumber = bcs.option(bcs.u64());可选值(Some/None模式)。
typescript
const OptionalNumber = bcs.option(bcs.u64());Map
映射
Key-value mappings.
typescript
const StringToNumberMap = bcs.map(bcs.string(), bcs.u32());键值对映射。
typescript
const StringToNumberMap = bcs.map(bcs.string(), bcs.u32());Sui-Specific Types
Sui专属类型
For detailed information about Sui blockchain-specific types including addresses, object references, transaction types, and Move types, see Sui-Specific Types.
Sui extends the base BCS with blockchain-specific types:
关于Sui区块链专属类型(包括地址、对象引用、交易类型和Move类型)的详细信息,请参阅Sui专属类型。
Sui在基础BCS之上扩展了区块链专属类型:
Address Type
地址类型
32-byte blockchain addresses with validation.
typescript
bcs.Address.serialize('0x123...');带验证的32字节区块链地址。
typescript
bcs.Address.serialize('0x123...');Object Reference Types
对象引用类型
References to Sui objects (owned, shared, receiving).
typescript
bcs.SuiObjectRef.serialize(objectRef);
bcs.SharedObjectRef.serialize(sharedObjectRef);指向Sui对象的引用(自有、共享、接收中)。
typescript
bcs.SuiObjectRef.serialize(objectRef);
bcs.SharedObjectRef.serialize(sharedObjectRef);Transaction-Related Types
交易相关类型
Transaction data, kind, and gas configuration.
typescript
bcs.TransactionData.serialize(transactionData);
bcs.GasData.serialize(gasData);交易数据、类型和Gas配置。
typescript
bcs.TransactionData.serialize(transactionData);
bcs.GasData.serialize(gasData);Key and Signature Types
密钥与签名类型
Cryptographic types for transaction authorization.
typescript
bcs.PublicKey.serialize(publicKeyBytes);
bcs.MultiSig.serialize(multiSigData);用于交易授权的密码学类型。
typescript
bcs.PublicKey.serialize(publicKeyBytes);
bcs.MultiSig.serialize(multiSigData);Move Types
Move类型
Move programming language type system representations.
typescript
bcs.TypeTag.serialize(typeTag);
bcs.StructTag.serialize(structTag);Move编程语言类型系统的表示。
typescript
bcs.TypeTag.serialize(typeTag);
bcs.StructTag.serialize(structTag);Serialization Patterns
序列化模式
For comprehensive examples of serialization patterns including basic operations, complex data structures, and recursive types, see Serialization Patterns.
关于基础操作、复杂数据结构和递归类型等序列化模式的全面示例,请参阅序列化模式。
Basic Patterns
基础模式
- Direct serialization to bytes
- Encoding to hex, base64, base58
- Parsing from encoded strings
typescript
const serialized = bcs.u32().serialize(42);
const hex = serialized.toHex();
const value = bcs.u32().parseFromHex(hex);- 直接序列化为字节
- 编码为十六进制、base64、base58
- 从编码字符串解析
typescript
const serialized = bcs.u32().serialize(42);
const hex = serialized.toHex();
const value = bcs.u32().parseFromHex(hex);Complex Structures
复杂结构
Define and serialize hierarchical data structures.
typescript
const Account = bcs.struct('Account', {
address: bcs.string(),
balance: bcs.u64(),
transactions: bcs.vector(Transaction),
});定义并序列化分层数据结构。
typescript
const Account = bcs.struct('Account', {
address: bcs.string(),
balance: bcs.u64(),
transactions: bcs.vector(Transaction),
});Recursive Types
递归类型
Handle self-referential data structures with lazy evaluation.
typescript
const TreeNode = bcs.struct('TreeNode', {
value: bcs.u64(),
children: bcs.lazy(() => bcs.vector(TreeNode)),
});通过延迟求值处理自引用数据结构。
typescript
const TreeNode = bcs.struct('TreeNode', {
value: bcs.u64(),
children: bcs.lazy(() => bcs.vector(TreeNode)),
});Transformation Support
转换支持
For detailed examples of type transformations, validation patterns, and chained transformations, see Transformation Support.
关于类型转换、验证模式和链式转换的详细示例,请参阅转换支持。
Type Transformations
类型转换
Convert between different data representations during serialization/deserialization.
typescript
const StringNumber = bcs.string().transform({
input: (val: number) => val.toString(),
output: (val: string) => parseInt(val),
});在序列化/反序列化期间在不同数据表示之间转换。
typescript
const StringNumber = bcs.string().transform({
input: (val: number) => val.toString(),
output: (val: string) => parseInt(val),
});Validation Transformations
验证转换
Add data validation logic to ensure data integrity.
typescript
const PositiveNumber = bcs.u32().transform({
input: (val: number) => {
if (val <= 0) throw new Error('Value must be positive');
return val;
},
output: (val: number) => val,
});添加数据验证逻辑以确保数据完整性。
typescript
const PositiveNumber = bcs.u32().transform({
input: (val: number) => {
if (val <= 0) throw new Error('Value must be positive');
return val;
},
output: (val: number) => val,
});Chained Transformations
链式转换
Combine multiple transformations for complex data processing.
typescript
const ProcessedString = bcs.string()
.transform({ /* trim */ })
.transform({ /* uppercase */ });组合多个转换以处理复杂数据。
typescript
const ProcessedString = bcs.string()
.transform({ /* 修剪 */ })
.transform({ /* 大写 */ });Performance Considerations
性能考量
For detailed performance optimization strategies including size prediction, zero-copy operations, and caching, see Performance Considerations.
关于大小预测、零拷贝操作和缓存等性能优化策略的详细信息,请参阅性能考量。
Size Prediction
大小预测
Estimate serialized size before actual serialization.
typescript
const size = schema.serializedSize(data);在实际序列化前估算序列化大小。
typescript
const size = schema.serializedSize(data);Zero-Copy Operations
零拷贝操作
Minimize data copying for better performance.
typescript
const ByteVectorType = bcs.byteVector();
const serialized = ByteVectorType.serialize(existingBuffer);最小化数据拷贝以提升性能。
typescript
const ByteVectorType = bcs.byteVector();
const serialized = ByteVectorType.serialize(existingBuffer);Cache Optimization
缓存优化
Reuse type instances and buffers.
typescript
const PersonType = bcs.struct('Person', { /* fields */ });
// Reuse across multiple serializations复用类型实例和缓冲区。
typescript
const PersonType = bcs.struct('Person', { /* 字段 */ });
// 在多次序列化中复用Integration with Transactions
与交易的集成
For comprehensive examples of BCS integration with Sui transactions including argument serialization, transaction data handling, and object references, see Integration with Transactions.
关于BCS与Sui交易集成的全面示例(包括参数序列化、交易数据处理和对象引用),请参阅与交易的集成。
Using BCS in Transactions
在交易中使用BCS
Serialize custom types for transaction arguments.
typescript
const tx = new Transaction();
tx.moveCall({
target: '0x2::example::function',
arguments: [
tx.pure(bcs.U64.serialize(100n)),
tx.pure.address('0xaddress'),
],
});序列化自定义类型作为交易参数。
typescript
const tx = new Transaction();
tx.moveCall({
target: '0x2::example::function',
arguments: [
tx.pure(bcs.U64.serialize(100n)),
tx.pure.address('0xaddress'),
],
});Transaction Data Serialization
交易数据序列化
Serialize complete transaction data for signing and submission.
typescript
const serializedTxData = bcs.TransactionData.serialize(transactionData);序列化完整交易数据以用于签名和提交。
typescript
const serializedTxData = bcs.TransactionData.serialize(transactionData);Object Argument Types
对象参数类型
Serialize different types of object references.
typescript
bcs.ObjectArg.serialize(objectArg);序列化不同类型的对象引用。
typescript
bcs.ObjectArg.serialize(objectArg);Custom BCS Types
自定义BCS类型
For detailed guidance on creating custom BCS types, extending existing types, and type registration, see Custom BCS Types.
关于创建自定义BCS类型、扩展现有类型和类型注册的详细指南,请参阅自定义BCS类型。
Creating Custom Types
创建自定义类型
Implement custom serialization logic for specialized data formats.
typescript
const CustomType = new BcsType<MyType, MyInput>({
name: 'CustomType',
read: (reader) => { /* deserialization */ },
write: (value, writer) => { /* serialization */ },
});为特殊数据格式实现自定义序列化逻辑。
typescript
const CustomType = new BcsType<MyType, MyInput>({
name: 'CustomType',
read: (reader) => { /* 反序列化 */ },
write: (value, writer) => { /* 序列化 */ },
});Extending Existing Types
扩展现有类型
Add custom behavior to built-in types using transformations.
typescript
const enhancedU32 = bcs.u32().transform({
input: (val) => val * 2,
output: (val) => val / 2,
});使用转换为内置类型添加自定义行为。
typescript
const enhancedU32 = bcs.u32().transform({
input: (val) => val * 2,
output: (val) => val / 2,
});Type Registration
类型注册
Register application-specific types for reuse.
typescript
bcs.registerStructType('User', {
id: 'address',
name: 'string',
age: 'u8',
});注册应用专属类型以供复用。
typescript
bcs.registerStructType('User', {
id: 'address',
name: 'string',
age: 'u8',
});Workflows
工作流
For complete workflow examples including Sui object serialization, transaction validation, and custom type registration, see Workflows.
关于Sui对象序列化、交易验证和自定义类型注册等完整工作流示例,请参阅工作流。
Common Workflows
常见工作流
- Sui Object Serialization: Serialize and deserialize blockchain objects
- Transaction Data Validation: Validate transaction formats using BCS
- Custom Type Registration: Register application-specific types
- Batch Processing: Process multiple operations efficiently
- Error Handling: Graceful error recovery patterns
- Sui对象序列化:序列化和反序列化区块链对象
- 交易数据验证:使用BCS验证交易格式
- 自定义类型注册:注册应用专属类型
- 批量处理:高效处理多个操作
- 错误处理:优雅的错误恢复模式
Example: Transaction Validation
示例:交易验证
typescript
function validateTransactionData(data: any): boolean {
try {
bcs.TransactionData.serialize(data);
return true;
} catch {
return false;
}
}typescript
function validateTransactionData(data: any): boolean {
try {
bcs.TransactionData.serialize(data);
return true;
} catch {
return false;
}
}Example: Type Registration
示例:类型注册
typescript
function registerAppTypes() {
bcs.registerStructType('User', {
id: 'address',
name: 'string',
age: 'u8',
});
}typescript
function registerAppTypes() {
bcs.registerStructType('User', {
id: 'address',
name: 'string',
age: 'u8',
});
}Best Practices
最佳实践
For comprehensive best practices covering type safety, performance optimization, compatibility, and security, see Best Practices.
关于类型安全、性能优化、兼容性和安全性的全面最佳实践,请参阅最佳实践。
Key Recommendations
核心建议
- Type Safety: Use TypeScript interfaces and runtime validation
- Performance: Reuse type instances and predict sizes
- Compatibility: Add version fields and maintain backward compatibility
- Security: Validate input and enforce size limits
- Documentation: Document schemas and provide usage examples
- 类型安全:使用TypeScript接口和运行时验证
- 性能:复用类型实例并预测大小
- 兼容性:添加版本字段并保持向后兼容
- 安全性:验证输入并强制执行大小限制
- 文档:记录模式并提供使用示例
Essential Practices
关键实践
- Always validate external input before serialization
- Use TypeScript for compile-time type checking
- Implement proper error handling and recovery
- Test serialization/deserialization round trips
- Document data formats and versioning strategies
- 序列化前始终验证外部输入
- 使用TypeScript进行编译时类型检查
- 实现适当的错误处理与恢复
- 测试序列化/反序列化往返过程
- 记录数据格式与版本控制策略
Reference Files
参考文件
For detailed information on specific topics, refer to the following files in the directory:
reference/- Primitive Types: Integer, boolean, and string types
- Composite Types: Structs, enums, vectors, tuples, options, and maps
- Sui-Specific Types: Addresses, object references, transaction types, and Move types
- Serialization Patterns: Basic and complex serialization patterns, recursive types
- Transformation Support: Type transformations, validation, and chained transformations
- Performance Considerations: Size prediction, zero-copy operations, caching, and optimization
- Integration with Transactions: BCS usage in Sui transactions, argument serialization
- Custom BCS Types: Creating custom types, extending existing types, type registration
- Workflows: Complete workflow examples and patterns
- Best Practices: Type safety, performance, compatibility, and security guidelines
如需特定主题的详细信息,请参阅目录中的以下文件:
reference/- 基本类型:整数、布尔值和字符串类型
- 复合类型:结构体、枚举、向量、元组、可选类型和映射
- Sui专属类型:地址、对象引用、交易类型和Move类型
- 序列化模式:基础与复杂序列化模式、递归类型
- 转换支持:类型转换、验证和链式转换
- 性能考量:大小预测、零拷贝操作、缓存与优化
- 与交易的集成:BCS在Sui交易中的使用、参数序列化
- 自定义BCS类型:创建自定义类型、扩展现有类型、类型注册
- 工作流:完整工作流示例与模式
- 最佳实践:类型安全、性能、兼容性与安全指南
Related Skills
相关技能
- sui-transaction-building: Understand BCS usage in transaction building
- sui-keypair-cryptography: Understand BCS serialization of public keys and signatures
- sui-transaction-building:了解交易构建中的BCS使用
- sui-keypair-cryptography:了解公钥与签名的BCS序列化
References
参考资料
- Official documentation: https://sdk.mystenlabs.com/bcs
- Source code: and
https://github.com/MystenLabs/ts-sdks/tree/main/packages/bcs/src/https://github.com/MystenLabs/ts-sdks/tree/main/packages/typescript/src/bcs/ - Test cases:
https://github.com/MystenLabs/ts-sdks/tree/main/packages/bcs/tests/ - TypeScript type definitions:
https://github.com/MystenLabs/ts-sdks/tree/main/packages/bcs/src/types.ts
This skill helps Claude Code understand Sui BCS serialization, providing practical code examples and usage guidelines. When users need to handle Sui blockchain data serialization, referencing this skill can provide accurate TypeScript code and best practices.
- 官方文档:https://sdk.mystenlabs.com/bcs
- 源代码:和
https://github.com/MystenLabs/ts-sdks/tree/main/packages/bcs/src/https://github.com/MystenLabs/ts-sdks/tree/main/packages/typescript/src/bcs/ - 测试用例:
https://github.com/MystenLabs/ts-sdks/tree/main/packages/bcs/tests/ - TypeScript类型定义:
https://github.com/MystenLabs/ts-sdks/tree/main/packages/bcs/src/types.ts
本技能帮助Claude Code理解Sui BCS序列化,提供实用代码示例与使用指南。当用户需要处理Sui区块链数据序列化时,参考本技能可获取准确的TypeScript代码与最佳实践。