Skip to main content

Crate talus_sui_move_codegen

Crate talus_sui_move_codegen 

Source
Expand description

§talus-sui-move-codegen

Generate typed Rust bindings for a Move package on Sui.

This crate solves one problem: turn Move package metadata fetched from Sui into Rust source code compatible with the Talus Sui Move crates:

  • talus-sui-move: Rust representations of Move types (MoveType, MoveStruct, abilities)
  • talus-sui-move-call: CallSpec + typed argument traits (ToCallArg, ObjectArg<T>)
  • talus-sui-move-ptb: build a Sui programmable transaction (PTB) from CallSpec
  • talus-sui-move-runtime: runtime with a cursor for the Read → Tx → Commit mental model and object handles that update after commits
  • talus-sui-move-codegen (this crate): generate the bindings (types + call builders)

§Problem

Interacting with Move from Rust is repetitive and easy to get subtly wrong:

  • you must spell (package, module, function) identifiers correctly
  • you must build correct TypeTags for generic type arguments
  • you must encode pure values with BCS and pass objects with the right input kind
  • you want the Move signature reflected in the Rust function signature (especially for object inputs and &mut)

This crate removes the repetition by generating a small amount of Rust code from the chain’s own metadata.

§How it works (deterministic pipeline)

The pipeline is intentionally split in two:

  1. Source (network): fetch package metadata once and normalize it into an IR that supports Serde (NormalizedPackage).
  2. Render (offline): render Rust source from that IR.

Because the IR is serializable as JSON, you can commit it and render again deterministically in CI without needing network access.

§Optional source parameter names

Sui package metadata contains function parameter types but not their source names. IR built from network data therefore uses deterministic names such as arg0 and arg1 by default.

Callers that own matching Move source can overlay parameter names before saving or rendering the IR:

use talus_sui_move_codegen::{apply_function_parameter_names_from_sources, fetch_package, GrpcClient};
use sui_sdk_types::Address;

let mut client = GrpcClient::new(GrpcClient::MAINNET_FULLNODE)?;
let package_id: Address = "0x2".parse()?;
let mut package = fetch_package(&mut client, package_id).await?;

apply_function_parameter_names_from_sources(&mut package, "path/to/package/sources")?;

The overlay changes names only. Package identity, function signatures, types, and abilities remain derived from network data. The source is trusted metadata and is not verified against published bytecode. Source and network parameter counts must match. Rust rendering preserves source spelling in Move documentation and converts reserved Rust identifiers safely in generated APIs.

§What gets generated

Given a NormalizedPackage (either fetched from gRPC or loaded from JSON), this crate can render:

  • CALL_PACKAGE / TYPE_PACKAGE constants for generated calls and type identity
  • call_package() / type_package() / with_packages(...) helpers for scoped package address overrides
  • type_package_for(...) / with_package_context(...) helpers for exact datatype origins
  • One Rust module per Move module (or a flat layout via RenderOptions::flatten)
  • Move datatypes as Rust types (structs use #[talus_sui_move::move_struct] via talus-sui-move’s derive feature)
  • Move functions as generated *_target functions
  • Optional typed Rust functions that return talus_sui_move_call::CallSpec
  • (optional) A TxExt trait implemented for talus_sui_move_runtime::Tx (enable with RenderOptions::emit_tx_ext)

Those generated call builders can be used directly with:

  • talus-sui-move-ptb can consume CallSpec to build a ProgrammableTransaction
  • talus-sui-move-runtime can consume CallSpec via its tx builder (or talus_sui_move_runtime::tx!)

Use with_packages when generated calls target one deployment package while type tags retain the package that defines the Move types:

bindings::with_packages(localnet_package, localnet_package, || {
    bindings::m::f(10);
});

An upgraded package can contain datatypes that originate in different package versions. Calls must target the current package, while each type tag must retain the package where that datatype was first defined. Generated call builders resolve their target through call_package(), and each generated datatype resolves its type identity through type_package_for(module, datatype). Use with_package_context to scope both lookups to one release:

let initial_package = Address::from_static("0xa1");
let upgraded_package = Address::from_static("0xa2");
let current_package = Address::from_static("0xa3");
let origins = BTreeMap::from([(
    "agent".to_owned(),
    BTreeMap::from([
        ("Agent".to_owned(), initial_package),
        ("AgentStateV2".to_owned(), upgraded_package),
    ]),
)]);

let (call_package, agent_type_package, state_v2_type_package) =
    bindings::with_package_context(current_package, initial_package, &origins, || {
        (
            bindings::call_package(),
            bindings::type_package_for("agent", "Agent"),
            bindings::type_package_for("agent", "AgentStateV2"),
        )
    });

assert_eq!(call_package, current_package);
assert_eq!(agent_type_package, initial_package);
assert_eq!(state_v2_type_package, upgraded_package);

§Example: render from an IR in memory

use std::collections::BTreeMap;
use talus_sui_move_codegen::ir::*;
use talus_sui_move_codegen::render::{render_package, RenderOptions};

let pkg = NormalizedPackage {
    storage_id: "0x1".into(),
    original_id: None,
    version: 0,
    modules: BTreeMap::from([(
        "m".into(),
        NormalizedModule {
            name: "m".into(),
            datatypes: vec![Datatype {
                type_name: TypeName {
                    address: "0x1".into(),
                    module: "m".into(),
                    name: "S".into(),
                },
                module: "m".into(),
                name: "S".into(),
                abilities: vec![Ability::Store],
                type_parameters: vec![],
                kind: DatatypeKind::Struct {
                    fields: vec![Field {
                        name: "value".into(),
                        position: 0,
                        ty: TypeRef::U64,
                    }],
                },
            }],
            functions: vec![Function {
                name: "f".into(),
                visibility: Visibility::Public,
                is_entry: true,
                type_parameters: vec![],
                parameters: vec![FunctionParam {
                    name: "arg0".into(),
                    ty: TypeRef::U64,
                }],
                return_types: vec![],
            }],
        },
    )]),
};

let code = render_package(&pkg, &RenderOptions::default());
assert!(code.contains("pub const CALL_PACKAGE"));
assert!(code.contains("pub struct S"));
assert!(code.contains("pub fn f"));

§Example: object args + TxContext omission

Move functions often take objects by & / &mut, and also take a &mut TxContext. In the generated Rust API:

  • any parameter whose type has the Move key ability becomes &impl ObjectArg<T> (or &mut ... if the Move signature is &mut)
  • for &mut object parameters, the generated builder uses CallSpec::push_arg_mut so shared objects are marked mutable in the transaction input when needed
  • any TxContext parameter is omitted (higher layers supply it when building the transaction)
use std::collections::BTreeMap;
use talus_sui_move_codegen::ir::*;
use talus_sui_move_codegen::render::{render_package, RenderOptions};

let pkg = NormalizedPackage {
    storage_id: "0x1".into(),
    original_id: None,
    version: 0,
    modules: BTreeMap::from([(
        "m".into(),
        NormalizedModule {
            name: "m".into(),
            datatypes: vec![Datatype {
                type_name: TypeName {
                    address: "0x1".into(),
                    module: "m".into(),
                    name: "Obj".into(),
                },
                module: "m".into(),
                name: "Obj".into(),
                abilities: vec![Ability::Key, Ability::Store],
                type_parameters: vec![],
                kind: DatatypeKind::Struct {
                    fields: vec![Field {
                        name: "id".into(),
                        position: 0,
                        ty: TypeRef::Datatype {
                            type_name: TypeName::parse("0x2::object::UID").unwrap(),
                            type_arguments: vec![],
                        },
                    }],
                },
            }],
            functions: vec![Function {
                name: "mutate".into(),
                visibility: Visibility::Public,
                is_entry: true,
                type_parameters: vec![],
                parameters: vec![
                    FunctionParam {
                        name: "arg0".into(),
                        ty: TypeRef::Ref {
                            mutable: true,
                            inner: Box::new(TypeRef::Datatype {
                                type_name: TypeName::parse("0x1::m::Obj").unwrap(),
                                type_arguments: vec![],
                            }),
                        },
                    },
                    FunctionParam {
                        name: "arg1".into(),
                        ty: TypeRef::Ref {
                            mutable: true,
                            inner: Box::new(TypeRef::Datatype {
                                type_name: TypeName::parse("0x2::tx_context::TxContext").unwrap(),
                                type_arguments: vec![],
                            }),
                        },
                    },
                ],
                return_types: vec![],
            }],
        },
    )]),
};

let code = render_package(&pkg, &RenderOptions::default());
let start = code.find("pub fn mutate(").unwrap();
let sig_end = start + code[start..].find('{').unwrap();
let sig = &code[start..sig_end];

assert!(sig.contains("arg0: &mut impl sm_call::ObjectArg<Obj>"));
assert!(!sig.contains("TxContext"));
assert!(code.contains("push_arg_mut(arg0)"));

§Optional: runtime Tx extension trait

If you want a slightly more ergonomic “append a call” API on top of talus-sui-move-runtime, you can ask codegen to emit a TxExt trait implemented for talus_sui_move_runtime::Tx.

The generated methods do not submit the transaction; they only call Tx::call(...). This keeps the Read → Tx → Commit boundary explicit.

use std::collections::BTreeMap;
use talus_sui_move_codegen::ir::*;
use talus_sui_move_codegen::render::{render_package, RenderOptions};

let pkg = NormalizedPackage {
    storage_id: "0x1".into(),
    original_id: None,
    version: 0,
    modules: BTreeMap::from([(
        "m".into(),
        NormalizedModule {
            name: "m".into(),
            datatypes: vec![Datatype {
                type_name: TypeName::parse("0x1::m::Obj").unwrap(),
                module: "m".into(),
                name: "Obj".into(),
                abilities: vec![Ability::Key, Ability::Store],
                type_parameters: vec![],
                kind: DatatypeKind::Struct {
                    fields: vec![Field {
                        name: "id".into(),
                        position: 0,
                        ty: TypeRef::Datatype {
                            type_name: TypeName::parse("0x2::object::UID").unwrap(),
                            type_arguments: vec![],
                        },
                    }],
                },
            }],
            functions: vec![Function {
                name: "mutate".into(),
                visibility: Visibility::Public,
                is_entry: true,
                type_parameters: vec![],
                parameters: vec![
                    FunctionParam {
                        name: "arg0".into(),
                        ty: TypeRef::Ref {
                            mutable: true,
                            inner: Box::new(TypeRef::Datatype {
                                type_name: TypeName::parse("0x1::m::Obj").unwrap(),
                                type_arguments: vec![],
                            }),
                        },
                    },
                    FunctionParam {
                        name: "ctx".into(),
                        ty: TypeRef::Ref {
                            mutable: true,
                            inner: Box::new(TypeRef::Datatype {
                                type_name: TypeName::parse("0x2::tx_context::TxContext").unwrap(),
                                type_arguments: vec![],
                            }),
                        },
                    },
                ],
                return_types: vec![],
            }],
        },
    )]),
};

let opts = RenderOptions {
    emit_tx_ext: true,
    ..RenderOptions::default()
};
let code = render_package(&pkg, &opts);
assert!(code.contains("pub trait TxExt"));
assert!(code.contains("fn m__mutate"));

§Example: generic type params and ability bounds

Move generic constraints become Rust where bounds using talus-sui-move’s marker traits. For example, T: store becomes T0: MoveType + HasStore.

use std::collections::BTreeMap;
use talus_sui_move_codegen::ir::*;
use talus_sui_move_codegen::render::{render_package, RenderOptions};

let pkg = NormalizedPackage {
    storage_id: "0x1".into(),
    original_id: None,
    version: 0,
    modules: BTreeMap::from([(
        "m".into(),
        NormalizedModule {
            name: "m".into(),
            datatypes: vec![],
            functions: vec![Function {
                name: "id".into(),
                visibility: Visibility::Public,
                is_entry: true,
                type_parameters: vec![TypeParameter {
                    constraints: vec![Ability::Store],
                    is_phantom: false,
                }],
                parameters: vec![FunctionParam {
                    name: "arg0".into(),
                    ty: TypeRef::Vector(Box::new(TypeRef::TypeParameter(0))),
                }],
                return_types: vec![],
            }],
        },
    )]),
};

let code = render_package(&pkg, &RenderOptions::default());
let start = code.find("pub fn id<T0>(").unwrap();
let sig_end = start + code[start..].find('{').unwrap();
let sig = &code[start..sig_end];

assert!(sig.contains("pub fn id<T0>(arg0: Vec<T0>)"));
assert!(sig.contains("where"));
assert!(sig.contains("T0: sm::MoveType + sm::HasStore"));
assert!(code.contains("target.push_type_arg::<T0>();"));

§Example: fetch over gRPC

use talus_sui_move_codegen::{fetch_package, GrpcClient};
use sui_sdk_types::Address;

let mut client = GrpcClient::new(GrpcClient::MAINNET_FULLNODE)?;
let package_id: Address = "0x2".parse()?;

let pkg = fetch_package(&mut client, package_id).await?;
let json = pkg.to_json_string()?;
println!("{} bytes", json.len());

To keep builds deterministic, fetch metadata once and commit it as JSON, then render from JSON:

  1. Fetch and save NormalizedPackage JSON (separate; not in build.rs)
  2. Render Rust bindings from that JSON during builds or before generation

This avoids putting network access in CI/build scripts.

§Type resolution across packages

The renderer only treats primitive Move types and datatypes from the package being rendered as intrinsic. Framework and dependency types are still ordinary package declarations, so register their generated Rust bindings explicitly:

use talus_sui_move_codegen::fetch_package;
use talus_sui_move_codegen::render::{render_package, RenderOptions};
use talus_sui_move_codegen::GrpcClient;
use sui_sdk_types::Address;

let mut client = GrpcClient::new(GrpcClient::MAINNET_FULLNODE)?;

let framework = fetch_package(&mut client, "0x2".parse::<Address>()?).await?;
let app = fetch_package(&mut client, "0x123".parse::<Address>()?).await?;

let opts = RenderOptions::default().with_external_package(&framework, "sui_framework");
let code = render_package(&app, &opts);

Without an external binding, an external datatype renders as a compile_error!. That keeps missing dependency bindings explicit instead of silently reintroducing handwritten framework mirrors into talus-sui-move.

§Using the generated code

The rendered Rust is meant to live in its own crate or module. At minimum, the generated code expects these crates in the consumer’s Cargo.toml:

[dependencies]
talus-sui-move = "=0.3.0"
talus-sui-move-derive = "=0.3.0"
talus-sui-move-call = "=0.3.0"

If you want to execute calls, add higher layers (talus-sui-move-ptb, talus-sui-move-runtime) in the same consumer crate.

RenderOptions::use_aliases only affects verbosity in the emitted source (it adds use talus_sui_move as sm; use talus_sui_move_call as sm_call;). It does not change which crates are required. See README.md for the crate level overview.

Modules§

ir
Normalized package IR compatible with Serde. A small IR for Move package metadata that is compatible with Serde.
render
Render normalized metadata into Rust source. Render crate::ir::NormalizedPackage into Rust source code.

Enums§

Error
Errors from sourcing or normalizing package metadata.
SourceNameError
Errors from recovering function parameter names from Move sources.

Functions§

apply_function_parameter_names_from_sources
Apply recovered source parameter names to synthesized argN names in a normalized package.
fetch_package
Fetch a Move package over gRPC and normalize it into NormalizedPackage.
function_parameter_names_from_sources
Recover function parameter names from all .move files under a package sources/ directory.

Type Aliases§

GrpcClient
Sui gRPC client used by package metadata fetching.