Skip to main content
Dynamic fields allow you to add fields to objects after they’ve been created, enabling flexible data structures and efficient storage patterns. Unlike static fields declared in the struct definition, dynamic fields can have names determined at runtime.

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

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: For storing any value with store ability
  • dynamic_object_field: Specifically for storing objects (structs with key)
Dynamic object fields allow the child object to be accessed independently in some cases and provide better type safety for object storage.

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:
The 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

Advantages:
  • Simple and direct
  • Type-safe at compile time
  • Lower gas cost for small objects
Disadvantages:
  • Object becomes inaccessible when wrapped
  • Requires unwrapping to access
  • Fixed at compile time
Best for:
  • Temporarily hiding objects
  • Composition patterns
  • Fixed relationships

Error Handling

Always check field existence before adding to avoid EFieldAlreadyExists. Use exists_ or exists_with_type to verify.

Advanced: Optional Removal

Testing Dynamic Fields

From the examples:

Best Practices

  • Direct fields: For required, fixed data
  • Wrapping: For temporary encapsulation
  • Dynamic fields: For optional, extensible data
Instead of raw bytes, use custom types for field names:
Dynamic fields cost storage. Remove them when no longer needed:
Remember that deleting a parent with dynamic fields will make those fields inaccessible:

Objects

Understand Sui’s object model

Object Storage

Learn how objects are stored

Collections

Use built-in collection types