tonlib-tlb-derive 0.1.0

Derive macro for tonlib-core TLB types
Documentation

tonlib-tlb-derive - TLB derive macro for tonlib-core

tonlib-tlb-derive provides #[derive(TLB)] for tonlib-core.

Installation

[dependencies]
tonlib-core = "0.25"
tonlib-tlb-derive = "0.1"

Examples

use tonlib_core::{
    cell::{Cell, TonCellError},
    tlb_types::{block::state_init::StateInit, tlb::TLB as Tlb},
    TonHash,
};
use tonlib_tlb_derive::TLB;

#[derive(Debug, Clone, PartialEq, TLB)]
enum AccountState {
    #[tlb(tag = "$00")]
    Uninit,
    #[tlb(tag = "$01")]
    Frozen { state_hash: TonHash },
    #[tlb(tag = "$1")]
    Active(StateInit),
}

fn account_state_example() -> Result<(), TonCellError> {
    let code = Cell::default().to_arc();
    let data = Cell::default().to_arc();
    let value = AccountState::Active(StateInit::new(code, data));

    let cell = <AccountState as Tlb>::to_cell(&value)?;
    let decoded = <AccountState as Tlb>::read(&mut cell.parser())?;
    assert_eq!(decoded, value);
    Ok(())
}

#[derive(Debug, Clone, PartialEq, TLB)]
struct Hooks {
    #[tlb(bit_len = 5)]
    value: u8,
    #[tlb(read_with = "read_hash", skip_write)]
    hash: TonHash,
}

fn read_hash(parser: &mut CellParser) -> Result<TonHash, TonCellError> {
    Ok(parser.cell.cell_hash())
}

fn hooks_example() -> Result<(), TonCellError> {
    let value = Hooks {
        value: 17,
        hash: TonHash::from([0xAA; 32]),
    };

    let cell = value.to_cell().unwrap();
    let decoded = Hooks::read(&mut cell.parser()).unwrap();

    assert_eq!(decoded.value, value.value);
    assert_eq!(decoded.hash, cell.cell_hash());
    Ok(())
}

tonlib-tlb-derive does not ship a dictionary container. TON system types use Hashmap and HashmapE heavily, and ./tests/hashmap.rs shows one clean wrapper pattern: TLBHashmap<const KEY_SIZE, Key, Value>.

Supported attributes

  • #[tlb(tag = "$001")] on structs and enum variants.
  • #[tlb(tag = "#c0ffee")] on structs and enum variants.
  • #[tlb(bit_len = N)] on integer fields.
  • #[tlb(skip)], #[tlb(skip_read)], and #[tlb(skip_write)] on fields.
  • #[tlb(default)] and #[tlb(default_with = "path::to::default")] on skipped-read fields.
  • #[tlb(read_with = "path::to::reader", write_with = "path::to::writer")] on fields.

skip skips both read and write. Skipped reads use Default::default() unless default_with overrides that.

License

MIT