@ton-community/tlb-codegen v2.0.0-beta.0
TLB Generator
This package allows you to generate Typescript code for serializing and deserializing structures according to the TLB scheme provided.
Here you can find documentation for creating TLB schemes, and more advanced article is here.
This package uses TLB-Parser to get AST of the scheme.
Installation
npm install @ton-community/tlb-codegenUsage
CLI
Create a file with TLB scheme according to the documentation. This is an example of such a file (call it example.tlb):
t$_ x:# y:(uint 5) = A;Then do:
npx tlb example.tlbIt will create a file called example.ts with the following code:
export interface A {
readonly kind: 'A';
readonly x: number;
readonly y: number;
}
export function loadA(slice: Slice): A {
let x: number = slice.loadUint(32);
let y: number = slice.loadUint(5);
return {
kind: 'A',
x: x,
y: y,
}
}
export function storeA(a: A): (builder: Builder) => void {
return ((builder: Builder) => {
builder.storeUint(a.x, 32);
builder.storeUint(a.y, 5);
})
}You also can set an output file with -o option: npx tlb -o other_file.ts example.tlb.
One of the examples where you can see various abilities of the tool is block.tlb. The generation result for it is here.
Node JS
Also you can use the tool from inside JS or TS code.
import { generateCode } from "@ton-community/tlb-codegen"
generateCode('example.tlb', 'example.ts', "typescript")Integration with @ton/core
It is integrated with @ton/core in a way it uses several built-in types from there.
Built-in types supported are:
Bool->boolean(loaded withloadBoolean, stored withstoreBit)MsgAddressInt->Address(loaded withloadAddress, stored withstoreAddress)MsgAddressExt->ExternalAddress | null(loaded withloadMaybeExternalAddress, stored withstoreAddress)MsgAddress->Address | ExternalAddress | null(loaded withloadAddressAny, stored withstoreAddress)VarUInteger->bigint(loaded withloadVarUintBig, stored withstoreVarUint)VarInteger->bigint(loaded withloadVarIntBig, stored withstoreVarInt)Bit->boolean(loaded withloadBit, stored withstoreBit)Grams->bigint(loaded withloadCoins, stored withstoreCoins)HashmapE n Value->Dictionary<bigint, Value>(orDictionary<number, Value>if n <= 64) (loaded withDictionary.load, stored withstoreDict)HashmapAugE n Value Extra->Dictionary<bigint, {value: Value, extra: Extra}>(ornumberinstead ofbigintifn <= 64) (loaded withDictionary.load, stored withstoreDict)
Please note that the tricky thing here with
HashmapAugEis that inTLBscheme extra is stored not only with values, but in intermediate nodes as well. HoweverDictionaryin @ton/core doesn't store the intermediate nodes. That is whyHashmapAugEcan be correctly loaded by the generated code, but storing is incorrect.Please note that
BinTreeis not supported yet. In the future it will be supported as built-in typeBinTreefrom @ton/core.
License
This package is released under the MIT License.