Helps Claude Code understand Sui blockchain's BCS (Binary Canonical Serialization) encoding, providing usage guidelines and examples for primitive types, composite types, Sui-specific types,...
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.
// 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';
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);
The BCS type system is built on the BcsType<T, I> generic class:
Location: https://github.com/MystenLabs/ts-sdks/tree/main/packages/bcs/src/bcs-type.ts
BcsType is the abstract base class for all BCS types, providing:
Location: https://github.com/MystenLabs/ts-sdks/tree/main/packages/bcs/src/bcs.ts
Factory methods create various BCS types:
For detailed information about primitive types including integers, booleans, and strings, see Primitive Types.
BCS supports the following primitive types:
// 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();
For comprehensive coverage of composite types including structs, enums, vectors, tuples, options, and maps, see Composite Types.
BCS provides the following composite types:
Organize related fields into named structures.
const Person = bcs.struct('Person', {
name: bcs.string(),
age: bcs.u8(),
balance: bcs.u64(),
});
Define variant types with optional associated data.
const Status = bcs.enum('Status', {
Pending: null,
Active: bcs.u64(),
Inactive: bcs.string(),
});
Collections of homogeneous elements.
const NumberVector = bcs.vector(bcs.u32());
Fixed-size collections of heterogeneous elements.
const Pair = bcs.tuple([bcs.string(), bcs.u64()]);
Optional values (Some/None pattern).
const OptionalNumber = bcs.option(bcs.u64());
Key-value mappings.
const StringToNumberMap = bcs.map(bcs.string(), bcs.u32());
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:
32-byte blockchain addresses with validation.
bcs.Address.serialize('0x123...');
References to Sui objects (owned, shared, receiving).
bcs.SuiObjectRef.serialize(objectRef);
bcs.SharedObjectRef.serialize(sharedObjectRef);
Transaction data, kind, and gas configuration.
bcs.TransactionData.serialize(transactionData);
bcs.GasData.serialize(gasData);
Cryptographic types for transaction authorization.
bcs.PublicKey.serialize(publicKeyBytes);
bcs.MultiSig.serialize(multiSigData);
Move programming language type system representations.
bcs.TypeTag.serialize(typeTag);
bcs.StructTag.serialize(structTag);
For comprehensive examples of serialization patterns including basic operations, complex data structures, and recursive types, see Serialization Patterns.
const serialized = bcs.u32().serialize(42);
const hex = serialized.toHex();
const value = bcs.u32().parseFromHex(hex);
Define and serialize hierarchical data structures.
const Account = bcs.struct('Account', {
address: bcs.string(),
balance: bcs.u64(),
transactions: bcs.vector(Transaction),
});
Handle self-referential data structures with lazy evaluation.
const TreeNode = bcs.struct('TreeNode', {
value: bcs.u64(),
children: bcs.lazy(() => bcs.vector(TreeNode)),
});
For detailed examples of type transformations, validation patterns, and chained transformations, see Transformation Support.
Convert between different data representations during serialization/deserialization.
const StringNumber = bcs.string().transform({
input: (val: number) => val.toString(),
output: (val: string) => parseInt(val),
});
Add data validation logic to ensure data integrity.
const PositiveNumber = bcs.u32().transform({
input: (val: number) => {
if (val <= 0) throw new Error('Value must be positive');
return val;
},
output: (val: number) => val,
});
Combine multiple transformations for complex data processing.
const ProcessedString = bcs.string()
.transform({ /* trim */ })
.transform({ /* uppercase */ });
For detailed performance optimization strategies including size prediction, zero-copy operations, and caching, see Performance Considerations.
Estimate serialized size before actual serialization.
const size = schema.serializedSize(data);
Minimize data copying for better performance.
const ByteVectorType = bcs.byteVector();
const serialized = ByteVectorType.serialize(existingBuffer);
Reuse type instances and buffers.
const PersonType = bcs.struct('Person', { /* fields */ });
// Reuse across multiple serializations
For comprehensive examples of BCS integration with Sui transactions including argument serialization, transaction data handling, and object references, see Integration with Transactions.
Serialize custom types for transaction arguments.
const tx = new Transaction();
tx.moveCall({
target: '0x2::example::function',
arguments: [
tx.pure(bcs.U64.serialize(100n)),
tx.pure.address('0xaddress'),
],
});
Serialize complete transaction data for signing and submission.
const serializedTxData = bcs.TransactionData.serialize(transactionData);
Serialize different types of object references.
bcs.ObjectArg.serialize(objectArg);
For detailed guidance on creating custom BCS types, extending existing types, and type registration, see Custom BCS Types.
Implement custom serialization logic for specialized data formats.
const CustomType = new BcsType<MyType, MyInput>({
name: 'CustomType',
read: (reader) => { /* deserialization */ },
write: (value, writer) => { /* serialization */ },
});
Add custom behavior to built-in types using transformations.
const enhancedU32 = bcs.u32().transform({
input: (val) => val * 2,
output: (val) => val / 2,
});
Register application-specific types for reuse.
bcs.registerStructType('User', {
id: 'address',
name: 'string',
age: 'u8',
});
For complete workflow examples including Sui object serialization, transaction validation, and custom type registration, see Workflows.
function validateTransactionData(data: any): boolean {
try {
bcs.TransactionData.serialize(data);
return true;
} catch {
return false;
}
}
function registerAppTypes() {
bcs.registerStructType('User', {
id: 'address',
name: 'string',
age: 'u8',
});
}
For comprehensive best practices covering type safety, performance optimization, compatibility, and security, see Best Practices.
For detailed information on specific topics, refer to the following files in the reference/ directory:
https://github.com/MystenLabs/ts-sdks/tree/main/packages/bcs/src/ and https://github.com/MystenLabs/ts-sdks/tree/main/packages/typescript/src/bcs/https://github.com/MystenLabs/ts-sdks/tree/main/packages/bcs/tests/https://github.com/MystenLabs/ts-sdks/tree/main/packages/bcs/src/types.tsThis 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.