What are Dynamic Fields?
From the framework documentation:Dynamic Field Structure
Dynamic fields are stored as separate objects with a special structure:Each dynamic field is stored as a separate object whose ID is deterministically derived from the parent object’s ID, the field name, and its type.
Basic Operations
Adding Dynamic Fields
Reading Dynamic Fields
- Immutable Borrow
- Mutable Borrow
Removing Dynamic Fields
Checking Field Existence
Practical Example
Here’s a complete example from the Sui examples:Dynamic Object Fields
Sui provides a variant specifically for storing objects as dynamic fields:Dynamic Field vs Dynamic Object Field
Dynamic Field vs Dynamic Object Field
dynamic_field: For storing any value withstoreabilitydynamic_object_field: Specifically for storing objects (structs withkey)
Use Cases
Collections
Build hash maps, sets, and other collections
Extensibility
Add optional metadata without modifying the base struct
Efficient Storage
Store large amounts of data without hitting object size limits
Heterogeneous Data
Store different types in a single collection
Building a Table
Dynamic fields are the foundation for Sui’s Table type:Table type uses dynamic fields internally to store key-value pairs efficiently.
Object Wrapping
Object wrapping is a different pattern where objects are stored directly in struct fields:Wrapping vs Dynamic Fields
- Object Wrapping
- Dynamic Fields
Advantages:
- Simple and direct
- Type-safe at compile time
- Lower gas cost for small objects
- Object becomes inaccessible when wrapped
- Requires unwrapping to access
- Fixed at compile time
- Temporarily hiding objects
- Composition patterns
- Fixed relationships
Error Handling
Advanced: Optional Removal
Testing Dynamic Fields
From the examples:Best Practices
Choose the right storage pattern
Choose the right storage pattern
- Direct fields: For required, fixed data
- Wrapping: For temporary encapsulation
- Dynamic fields: For optional, extensible data
Use type-safe field names
Use type-safe field names
Instead of raw bytes, use custom types for field names:
Clean up unused fields
Clean up unused fields
Dynamic fields cost storage. Remove them when no longer needed:
Handle deletion carefully
Handle deletion carefully
Remember that deleting a parent with dynamic fields will make those fields inaccessible:
Related Topics
Objects
Understand Sui’s object model
Object Storage
Learn how objects are stored
Collections
Use built-in collection types