Skip to main content

Comment syntax

Identifiers

  • An identifier starts with and continue with .
  • Characters such as ? or : are invalid, so names like found? or op::increase are not allowed.
  • Identifiers such as cell or slice are valid.
Example:
It is similar to how number is a valid identifier in TypeScript. FunC vs Tolk In FunC, almost any character can be part of an identifier. For example, 2+2 without spaces is treated as a single identifier, and a variable can be declared with such a name. In Tolk, spaces are not required. 2+2 is 4, not an identifier. Identifiers can only contain alphanumeric characters. 2+2 evaluates to 4, and 3+~x is interpreted as 3 + (~x), and so on. Backticks can be used to enclose an identifier, allowing any symbols to be included. This feature is intended primarily for code generation, where keywords may need to appear as identifiers.

Impure by default, no function call elimination

FunC has an impure function specifier. When absent, a function is treated as pure. If its result is unused, its call is deleted by the compiler. For example, functions that do not return a value, such as those that throw an exception on a mismatch, are removed. This issue is spoiled by FunC not validating the function body, allowing impure operations to be executed within pure functions. In Tolk, all functions are impure by default. A function can be marked as pure using an annotation. In pure functions, impure operations such as throwing exceptions, modifying globals, or calling non-pure functions are disallowed.

Function syntax updates

  • fun keyword
  • Types of variables — on the right:
  • Modifiers such as inline — with @ annotations:
  • forall — this way:
  • asm implementation — same as in FunC, but properly aligned:
  • There is also a @deprecated attribute, not affecting compilation but for developers and IDE.

get instead of method_id

In FunC, method_id without arguments declares a get method. In Tolk, a direct get syntax is used: For method_id(xxx) — uncommon in practice but valid — Tolk uses an annotation:

Parameter types are required, local types are optional

Parameter types are mandatory, but the return type is optional when it can be inferred. If omitted, it’s auto-inferred:
Local variable types are optional:
Default values for parameters are supported:

Variables cannot be redeclared in the same scope

As a consequence, partial reassignment is not allowed:
This is not an issue for methods like loadUint(). In FunC, such methods returned a modified object, so a pattern like var (cs, int value) = cs.load_int(32) is common. In Tolk, such methods mutate the object: var value = cs.loadInt(32), so redeclaration is rarely needed:

String postfixes removed, compile-time functions added

Tolk removes FunC-style string postfixes like "..."c and replaces them with compile-time functions. These functions are:
  • compile-time only
  • for constant strings only
  • usable in constant initialization
The naming highlights that these functions arrived from string postfixes and operate on string values. At runtime, there are no strings, only slices.

Trailing comma support

Tolk supports trailing commas in the following contexts:
  • tensors
  • tuples
  • function calls
  • function parameters
Note that (5) is not a tensor. It’s the integer 5 in parentheses. With a trailing comma (5,) it’s still (5).

Optional semicolon for the last statement in a block

In Tolk, the semicolon after the final statement in a block can be omitted. While semicolons are still required between statements, the trailing semicolon on the last statement is now optional.

ton(”…”) function for readable Toncoin amounts

The function ton() only accepts constant values. For example, ton(some_var) is invalid. Its type is coins, not int, although it’s treated as a regular int by the TVM. Arithmetic operations on coins degrade to int — for example, cost << 1 or cost + ton("0.02") are both valid.

Type system changes

In Tolk v0.7, the type system was rewritten from scratch. To introduce booleans, fixed-width integers, nullability, structures, and generics, Tolk required a static type system similar to TypeScript or Rust. The types are:
  • int, bool, cell, slice, builder, untyped tuple
  • typed tuple [T1, T2, ...]
  • tensor (T1, T2, ...)
  • callables (TArgs) -> TResult
  • nullable types T?, compile-time null safety
  • union types T1 | T2 | ..., handled with pattern matching
  • coins and function ton("0.05")
  • int32, uint64, and other fixed-width integers — int at TVM — details
  • bytesN and bitsN — similar to intN — backed by slices at TVM
  • address — internal (standard) address, still a slice at TVM
  • any_address — internal/external/none
  • void — more canonical to be named unit, but void is more reliable
  • self, to make chainable methods, described below; it’s not a type, it can only occur instead of return type of a function
  • never — an always-throwing function returns never, for example; an impossible type is also never
  • structures and generics
The type system obeys the following rules:
  • Variable types can be specified manually or are inferred from declarations, and never change after being declared.
  • Function parameters must be strictly typed.
  • Function return types, if unspecified, are inferred from return statements similar to TypeScript. In the case of recursion, direct or indirect, the return type must be explicitly declared.
  • Generic functions are supported.

Clear and readable type mismatch errors

In FunC, type mismatch errors are hard to interpret:
In Tolk, errors are human-readable:

bool type, casting boolVar as int

At the TVM level, bool is represented as -1 or 0, but in the type system, bool and int are distinct types.
  • Comparison operators == / >= /... return bool.
  • Logical operators && || return bool.
  • Constants true and false have the bool type. Many standard library functions now return bool, not int:
  • Operator !x supports both int and bool.
  • if conditions and similar statements accept both int values that are not equal to zero and bool.
  • Logical operators && and || accept both bool and int, preserving compatibility with constructs like a && b where a and b are nonzero integers.
  • Arithmetic operators are restricted to integers. Only bitwise and logical operations are allowed for bool.
Logical operators && and ||, which are absent in FunC, use the if/else asm representation. In the future, for optimization, they could be automatically replaced with & or | when safe to do so, for example, a > 0 && a < 10. To manually optimize gas consumption, & and | can be used for bool, but they are not short-circuited.
  • bool can be cast to int using as operator:
There are no runtime transformations. bool is guaranteed to be -1 or 0 at the TVM level, so this is a type-only cast. Such casts are rarely necessary, except for tricky bitwise optimizations.

Generic functions and instantiations like f<int>(…)

Tolk introduces properly made generic functions. The syntax reminds mainstream languages:
A generic parameter T may represent any type, including complex ones:
Function types are also supported:
Although the generic type T is usually inferred from the arguments, there are edge cases where T cannot be inferred because it does not depend on them.
To make this valid, T must be specified externally:
  • For asm functions, T must occupy exactly one stack slot.
  • For user-defined functions, T may represent any structure.
  • Otherwise, the asm body cannot handle it properly.

Anonymous functions (lambdas)

Use lambdas — function expressions without capturing outer variables. Pass as callbacks, assign to variables, or return them.
Regular functions require explicit parameter types; lambda parameter types may be omitted when they can be inferred:
From the type system point of view, a function (and a lambda) has a special type (...ArgsT) -> ReturnT.
As first-class functions, lambdas can even be returned:
While lambdas are not common in smart contracts, they become useful in general purpose tools. They can easily be combined with generics of any level, nested into each other, and so on. Note that lambdas are not closures: capturing outer variables not supported.
Capturing variables is nearly impossible to implement on a stack machine, just like inheritance (conceptually equivalent).

#include → import

In Tolk, symbols from another file cannot be used without explicitly importing it — import what is used. All standard library functions are available by default. Downloading the stdlib and including it manually #include "stdlib.fc" is unnecessary. See embedded stdlib. There is a global naming scope. If the same symbol is declared in multiple files, it results in an error. import brings all file-level symbols into scope. The export keyword is reserved for future use.

#pragma → compiler options

In FunC, experimental features such as allow-post-modifications were enabled with #pragma directives inside .fc files, which caused inconsistencies across files. These flags are compiler options, not file-level pragmas. In Tolk, all pragmas were removed. allow-post-modification and compute-asm-ltr are merged into Tolk sources and behave as if they were always enabled in FunC. Instead of pragmas, experimental behavior is set through compiler options. There is one experimental option: remove-unused-functions, which excludes unused symbols from the Fift output. #pragma version xxx is replaced with tolk xxx, no >=, only strict versioning. If the version does not match, Tolk shows a warning.

Late symbols resolution and AST representation

In FunC, as in C, a function cannot be accessed before its declaration:
To avoid an error, a forward declaration is required because symbol resolution occurs during the parsing process. Tolk compiler separates parsing and symbol resolution into two distinct steps. The code above is valid, since symbols are resolved after parsing. This required introducing an intermediate AST representation, which is absent in FunC. The AST enables future language extensions and semantic code analysis.

null keyword

Creating null values and checking variables for null is now straightforward.

throw and assert keywords

Tolk simplifies exception handling. While FunC provides throw(), throw_if(), throw_arg_if(), and the corresponding unless forms, Tolk offers two primitives: throw and assert: The !condition is valid, as logical NOT is supported. A verbose form assert(condition, excNo) is also available:
Tolk swaps catch arguments: catch (excNo, arg), both of which are optional since arg is usually empty.

do … until → do … while

The !condition is valid, as logical NOT is supported.

Operator precedence aligned with C++ and JavaScript

In FunC, the code if (slices_equal() & status == 1) is parsed as if ((slices_equal() & status) == 1). This causes errors in real-world contracts. In Tolk, & has a lower priority, identical to C++ and JavaScript. Tolk generates errors on potentially incorrect operator usage to prevent such mistakes:
Produces a compilation error:
Code should be rewritten as:
Tolk detects a common mistake in bitshift operators: a << 8 + 1 is equivalent to a << 9, which may be unexpected.
Operators ~% ^% /% ~/= ^/= ~%= ^%= ~>>= ^>>= are no longer supported.

Immutable variables declared with val

Like in Kotlin, var declares mutable variables and val declares immutable variables, optionally specifying a type. FunC has no equivalent of val.
Function parameters are mutable within the function, but arguments are passed by value and remain unchanged. This behavior matches FunC.
In Tolk, functions can declare mutate parameters. It’s a generalization of FunC ~ tilde functions.

Deprecated command-line options removed

Command-line flags such as -A and -P are removed. The default usage:
  • Use -v to print the version and exit.
  • Use -h to list all available flags.
Only one input file can be specified. Additional files must be imported.

stdlib functions renamed to clear names, camelCase style

All standard library functions now use longer, descriptive names in camelCase style. The former stdlib.fc was split into multiple files, including common.tolk and tvm-dicts.tolk. See the full comparison: Tolk vs FunC: standard library.

stdlib is now embedded, not downloaded from GitHub

In Tolk, the standard library is part of the distribution. It is inseparable, as maintaining the language, compiler, and standard library together is required for proper release management. The compiler automatically locates the standard library. If Tolk is installed using an apt package, stdlib sources are downloaded and stored on disk, so the compiler locates them by system paths. When using the WASM wrapper, stdlib is provided by tolk-js. The standard library is split into multiple files:
  • common.tolk for most common functions,
  • gas-payments.tolk for gas calculations,
  • tvm-dicts.tolk, and others.
Functions from common.tolk are available and implicitly imported by the compiler. Other files must be explicitly imported.
The rule import what is used applies to @stdlib/... files as well, with the only exception of common.tolk. IDE plugins automatically detect the stdlib folder and insert required imports while typing.

Logical operators && ||, logical not !

In FunC, only bitwise operators ~ & | ^ exist. Using them as logical operators leads to errors because their behavior is different: Tolk supports logical operators. They behave as expected, as shown in the right column.. && and || may produce suboptimal Fift code, but the effect is negligible. Use them as in other languages. Keywords ifnot and elseifnot are removed because logical NOT is now available. For optimization, Tolk compiler generates IFNOTJMP. The elseif keyword is replaced by the standard else if. A boolean true transformed as int is -1, not 1. This reflects TVM representation.

Indexed access tensorVar.0 and tupleVar.0

Use tensorVar.{i} to access i-th component of a tensor. Modifying it changes the tensor.
Use tupleVar.{i} to access the i-th element of a tuple, uses INDEX internally. Modifying it changes the tuple, SETINDEX internally.
It also works for untyped tuples, though the compiler does not guarantee index correctness.
  • Supports nesting var.{i}.{j}
  • Supports nested tensors, nested tuples, and tuples inside tensors
  • Supports mutate and global variables

Type address

In TVM, all binary data is represented as a slice. The same applies to addresses: even though TL-B describes the MsgAddress, at the TVM level, it’s just a slice. Thus, in FunC’s standard library, loadAddress returns slice and storeAddress accepts slice. Tolk introduces a dedicated address type meaning “internal address”. It remains a TVM slice at runtime, but differs from an abstract slice in terms of the type system:
  1. Integrated with auto-serialization: the compiler knows how to pack and unpack it using LDSTDADDR and STSTDADDR.
  2. Comparable: operators == and != supported for addresses.
  1. Introspectable: address.getWorkchain() and address.getWorkchainAndHash().
Passing a slice instead leads to an error:
There is also a type any_address to store internal, external, or none address. Embedding a const address into a contract Use the built-in address() function. In FunC, this was done using the postfix "..."a, which returned a slice.
Casting slice to address and vice versa A raw slice that represents an address can be cast using the as operator. This occurs when an address is manually constructed in a builder using its binary representation:
A reversed cast is also valid: someAddr as slice. Different types of addresses There are different types of addresses. The most frequently used is an internal address — the address of a smart contract. But also, there are external and none addresses. In a binary TL-B representation:
  • 10 (internal prefix) + 0 (anycast, always 0) + workchain (8 bits) + hash (256 bits) — that’s EQ...: it’s 267 bits
  • 01 (external prefix) + len (9 bits) + len bits — external addresses
  • 00 (none prefix) — address none, 2 bits
address is “internal only” (90% use cases). address? (nullable) is “internal/none” (9% use cases). any_address is “internal/external/none” (1% use cases). Remember that address is “workchain + hash”. Validate untrusted input:

Type aliases type NewName = <existing type>

Tolk supports type aliases, like in TypeScript and Rust. An alias creates a new name for an existing type and remains fully interchangeable with it.

Nullable types T?, null safety, smart casts, operator !

Tolk supports nullable types: int?, cell?, and T? in general, including tensors. Non-nullable types, such as int and cell, cannot hold null values. The compiler enforces null safety: nullable types cannot be accessed without a null check. Checks are applied through smart casts. Smart casts exist only at compile time and do not affect gas or stack usage.
When a variable’s type is not declared, it is inferred from the initial assignment and never changes:
Variables that may hold null must be explicitly declared as nullable:
Smart casts handle nullable types automatically, enabling code such as:
Smart casts do not apply to global variables; they operate only on local variables. The ! operator in Tolk provides a compile-time non-null assertion, similar to ! in TypeScript and !!in Kotlin. It bypasses the compiler’s check for variables that are guaranteed to be non-null.
Functions that always throw can be declared with the return type never:
The never type occurs implicitly when a condition is impossible to satisfy:
Encountering never in compilation errors usually indicates a warning in the preceding code. Non-atomic nullable types are supported, e.g., (int, int)?, (int?, int?)?, or ()?. A special value presence stack slot is added automatically. It stores 0 for null values and -1 for non-null values.
Nullability improves type safety and reliability. Nullable types prevent runtime errors by enforcing explicit handling of optional values.

Union types T1 | T2 | …, operators match, is, !is

Union types allow a variable to hold multiple types, similar to TypeScript.
Nullable types T? are equivalent to T | null. Union types support intersection properties. For example, B | C can be passed and assigned to A | B | C | D. The only way to handle union types in code is through pattern matching:
Example:
The match must cover all union cases and can be used as an expression.
Syntax details:
  • Commas are optional inside {} but required in expressions.
  • A trailing comma is allowed.
  • No semicolon is required after match when used as a statement.
  • For match-expressions, an arm that terminates has the type never.
Variable declaration inside match is allowed:
At the TVM level, union types are stored as tagged unions, similar to enums in Rust:
  • Each type is assigned a unique type ID, stored alongside the value.
  • The union occupies N + 1 stack slots, where N is the maximum size of any type in the union.
  • A nullable type T? is a union with null (type ID = 0). Atomic types like int? use a single stack slot.
Union types can also be tested using is. Smart casts behave as follows:

Pattern matching for expressions (switch-like behavior)

match can be used with constant expressions, similar to switch:
Rules:
  • Only constant expressions are allowed on the left-hand side, e.g.,1, SOME_CONST, 2 + 3.
  • Branches may include return or throw.
  • else is required for expression form and optional for statement form.

Structures

Similar to TypeScript, but executed at the TVM level.
  • A struct is a named tensor.
  • Point is equivalent to (int, int) at the TVM level.
  • Field access p.x corresponds to tensor element access t.0 for reading and writing.
There is no bytecode overhead; tensors can be replaced with structured types. Fields can be separated by newlines, which is recommended, or by ; or ,,. Both of which are valid, similar to TypeScript. When creating an object, either StructName { ... } or { ... } can be used if the type is clear from context, such as return type or assignment:
Default values for fields are supported:
Structs can include methods as extension functions. Fields support the following modifiers:
  • private — accessible only within methods.
  • readonly — immutable after object creation.

Generic structs and aliases

Generic structs and type aliases exist only at the type level and incur no runtime cost.
Example usage:
For generic types, type arguments must be specified when using them:
For generic functions, the compiler can automatically infer type arguments from a call:
Demo: Response<TResult, TError>:

Methods: for any types, including structures

Methods are declared as extension functions, similar to Kotlin. A method that accepts the first self parameter acts as an instance method; without self, it is a static method.
Methods can be defined for any type, including aliases, unions, and built-in types:
Methods work with asm, as self is treated like a regular variable:
By default, self is immutable, preventing modification or calls to mutating methods. To make self mutable, declare mutate self explicitly:
Methods for generic structs can be created without specifying <T>. The compiler interprets unknown symbols in the receiver type as generic arguments during the parsing process.
Example:
Similarly, any unknown symbol, typically T, can be used to define a method that accepts any type:
When multiple methods match a call to someObj.method(), the compiler selects the most specific one:
A generic function can be assigned to a variable, but type arguments must be specified explicitly.

Enums

Properties:
  • Similar to TypeScript and C++ enums
  • Distinct type, not int
  • Checked during deserialization
  • Exhaustive in match
Enum syntax Enum members can be separated by , , ;, or a newline, similar to struct fields. Values can be specified manually; unspecified members are auto-calculated.
Enums are distinct types, not integers Color.Red is Color, not int, although it holds the value 0 at runtime.
Since enums are types, they can be:
  • Used as variable and parameters
  • Extended with methods an enum
  • Used in struct fields, unions, generics, and other type contexts
Enums are integers under the hood At the TVM level, an enum such as Color is represented as int. Casting between the enum and int is allowed:
  • Color.Blue as int evaluates to 2
  • 2 as Color evaluates to Color.Blue
Using as can produce invalid enum values. This is undefined behavior: for example, 100 as Color is syntactically valid, but program behavior is unpredictable after this point During deserialization using fromCell(), the compiler performs checks to ensure that encoded integers correspond to valid enum values. Enums in Tolk differ from Rust. In Rust, each enum member can have a distinct structure. In Tolk, union types provide that capability, so enums are integer constants. match for enums is exhaustive Pattern matching on enums requires coverage of all cases:
All enum cases must be covered, or else can be used to handle remaining values:
The == operator can be used to compare integers and addresses:
The expression someColor is Color.Red is invalid syntax. The is operator is used for type checks. Given var union: Color | A, u is Color is valid. Use == to compare enum values. Enums are allowed in throw and assert
Enums and serialization Enums can be packed to and unpacked from cells like intN or uintN, where N is:
  • Specified manually, e.g., enum Role: int8 { ... }
  • Calculated automatically as the minimal N to fit all values
The serialization type can be specified manually:
Or it will be calculated automatically. For Role above, uint2 is sufficient to fit values 0, 1, 2:
During deserialization, the input value is checked for correctness. For enum Role: int8 with values 0, 1, 2, any input<0 or input>2 triggers exception 5, integer out of range. This check applies to both value ranges and manually specified enum values:

Auto-detect and inline functions

Tolk can inline functions at the compiler level without using PROCINLINE as defined by Fift.
is compiled to:
The compiler automatically determines which functions to inline.
  • @inline attribute forces inlining.
  • @noinline prevents a function from being inlined.
  • @inline_ref preserves an inline reference, suitable for rarely executed paths.
Compiler inlining:
  • Efficient for stack manipulation.
  • Supports arguments of any stack width.
  • Works with any functions or methods, except:
    • Recursive functions
    • Functions containing return statements in the middle
  • Supports mutate and self.
Simple getters, such as fun Point.getX(self) { return self.x }, do not require stack reordering. Small functions can be extracted without runtime cost. The compiler handles inlining; no inlining is deferred to Fift. How does auto-inline work?
  • Simple, small functions are always inlined
  • Functions called only once are always inlined
For every function, the compiler calculates a weight, a heuristic AST-based metric, and the usages count.
  • If weight < THRESHOLD, the function is always inlined
  • If usages == 1, the function is always inlined
  • Otherwise, an empirical formula determines inlining
The @inline annotation can be applied to large functions when all usages correspond to hot paths. Inlining can also be disabled with @inline_ref, even for functions called once. For example, in unlikely execution paths. For optimization, use gas benchmarks and experiment with inlining and branch reordering. What can NOT be auto-inlined? A function is NOT inlined, even if marked with @inline, in the following cases:
  • The function contains return in the middle. Multiple return points are unsupported for inlining.
  • The function participates in a recursive call chain f -> g -> f.
  • The function is used as a non-call. For example, when a reference is taken: val callback = f.

No tilde ~ methods, mutate keyword instead

In FunC, both .methods() and ~methods() exist. In Tolk, only the dot syntax is used, and methods are called as .method(). Tolk follows expected behavior:
For details, see Mutability in Tolk.

Auto-packing to/from cells/builders/slices

Any struct can be automatically packed into a cell or unpacked from one:

Universal createMessage: avoid manual cells composition

No need for manual beginCell().storeUint(...).storeRef(...) boilerplate — describe the message in a literal and the compiler handles packing.

map<K,V> instead of low-level TVM dictionaries

Tolk introduces map<K, V>:
  • A generic type map<K, V> — any serializable keys and values.
  • The compiler automatically generates asm instructions and performs (de)serialization on demand.
  • Natural syntax for iterating forwards, backwards, or starting from a specified key.
  • Zero overhead compared to low-level approach.
Demo: set, exists, get, etc.
m.get(key) returns not an “optional value”, but isFound + loadValue()
  • m.get(key) returns a struct, NOT V?.
  • m.mustGet(key) returns V and throws if the key is missing.
Why “isFound” but not “optional value”?
  • Gas consumption; zero overhead.
  • Nullable values can be supported, such as map<int32, address?> or map<K, Point?>.
  • Returning V?, makes it impossible to distinguish between “key exists but value is null” and “key does not exist”.
Iterating forward and backward There is no syntax like foreach. Iteration follows this pattern:
  • define the starting key: r = m.findFirst() or r = m.findLast()
  • while r.isFound:
    • use r.getKey() and r.loadValue()
    • move the cursor: r = m.iterateNext(r) or r = m.iteratePrev(r)
Example: iterate all keys forward
Example: iterate from key<=2 backward
Iteration over maps uses existing syntax. Use while (r.isFound), not while (r == null). As with m.get(key), existence is checked through isFound.
The reason is the same — zero overhead and no hidden runtime instructions or stack manipulations. Use m.isEmpty(), not m == null. Since map is a dedicated type, it must be checked with isEmpty(), because m == null does not work. Suppose a wrapper over dictionaries is implemented:
Given var m: MyMap, calling m.isEmpty() works. The expression m == null is invalid. The compiler issues the following warning:
The same rule applies to built-in maps. When transitioning code from low-level dicts to high-level maps, pay attention to compiler warnings in the console. A nullable map is valid: var m: map<...>?. This variable can be null and not null. When not null, it can contain an empty map or a non-empty map. The expression m == null only makes sense for nullable maps. Allowed types for K and V All the following key and value types are valid:
Some types are NOT allowed. General rules:
  • Keys must be fixed-width and contain zero references
    • Valid: int32, uint64, address, bits256, Point
    • Invalid: int, coins, cell
  • Values must be serializable
    • Valid: int32, coins, AnyStruct, Cell<AnyStruct>
    • Invalid: int, builder
In practice, keys are typically intN, uintN, or address. Values can be any serializable type. At the TVM level, keys can be numbers or slices. Complex keys, such as Point, are automatically serialized and deserialized by the compiler.
If a key is a struct with a single intN field, it behaves like a number.

Available methods for maps

JetBrains IDE and VS Code provide method suggestions. Most methods are self-explanatory.
  • createEmptyMap<K, V>(): map<K, V>
Returns an empty typed map. Equivalent to PUSHNULL since TVM NULL represents an empty map.
  • createMapFromLowLevelDict<K, V>(d: dict): map<K, V>
Converts a low-level TVM dictionary to a typed map. Accepts an optional cell and returns the same optional cell. Incorrect key and value types cause failure at map.get or similar methods.
  • m.toLowLevelDict(): dict
Converts a high-level map to a low-level TVM dictionary. Returns the same optional cell.
  • m.isEmpty(): bool
Checks whether a map is empty. Use m.isEmpty() instead of m == null.
  • m.exists(key: K): bool
Checks whether a key exists in a map.
  • m.get(key: K): MapLookupResult<V>
Gets an element by key. Returns isFound = false if key does not exist.
  • m.mustGet(key: K, throwIfNotFound: int = 9): V
Gets an element by key and throws if it does not exist.
  • m.set(key: K, value: V): self
Sets an element by key. Since it returns self, calls may be chained.
  • m.setAndGetPrevious(key: K, value: V): MapLookupResult<V>
Sets an element and returns the previous element. If no previous element, isFound = false.
  • m.replaceIfExists(key: K, value: V): bool
Sets an element only if the key exists. Returns whether an element was replaced.
  • m.replaceAndGetPrevious(key: K, value: V): MapLookupResult<V>
Sets an element only if the key exists and returns the previous element.
  • m.addIfNotExists(key: K, value: V): bool
Sets an element only if the key does not exist. Returns true if added.
  • m.addOrGetExisting(key: K, value: V): MapLookupResult<V>
Sets an element only if the key does not exist. If exists, returns an old value.
  • m.delete(key: K): bool
Deletes an element by key. Returns true if deleted.
  • m.deleteAndGetDeleted(key: K): MapLookupResult<V>
Deletes an element by key and returns the deleted element. If not found, isFound = false.
  • m.findFirst(): MapEntry<K, V>
Finds the first (minimal) element. For integer keys, returns minimal integer. For addresses or complex keys, represented as slices, returns lexicographically smallest key. Returns isFound = false for an empty map.
  • m.findLast(): MapEntry<K, V>
Finds the last (maximal) element. For integer keys, returns maximal integer. For addresses or complex keys (represented as slices), returns lexicographically largest key. Returns isFound = false for an empty map.
  • m.findKeyGreater(pivotKey: K): MapEntry<K, V>
Finds an element with key greater than pivotKey.
  • m.findKeyGreaterOrEqual(pivotKey: K): MapEntry<K, V>
Finds an element with key greater than or equal to pivotKey.
  • m.findKeyLess(pivotKey: K): MapEntry<K, V>
Finds an element with key less than pivotKey.
  • m.findKeyLessOrEqual(pivotKey: K): MapEntry<K, V>
Finds an element with key less than or equal to pivotKey.
  • m.iterateNext(current: MapEntry<K, V>): MapEntry<K, V>
Iterates over a map in ascending order.
  • m.iteratePrev(current: MapEntry<K, V>): MapEntry<K, V>
Iterates over a map in descending order. Augmented hashmaps and prefix dictionaries These structures are rarely used and are not part of the type system.
  • Prefix dictionaries: import @stdlib/tvm-dicts and use assembly functions.
  • Augmented hashmaps and Merkle proofs: implement interaction manually.

Modern onInternalMessage

In Tolk, msg_cell does not require manual parsing to retrieve sender_address or fwd_fee. Fields are accessed directly:
The legacy approach of accepting 4 parameters, as recv_internal, works but is less efficient. InMessage fields are directly mapped to TVM-11 instructions. Recommended pattern:
  1. Define each message as a struct, typically including a 32-bit opcode.
  2. Define a union of all allowed messages.
  3. Use val msg = lazy MyUnion.fromSlice(in.body).
  4. Match on msg, handling each branch and possibly an else.
Avoid manually extracting fwd_fee or other fields at the start of the function. Access them on demand through the in.smth.
Separate onBouncedMessage In FunC, msg_cell required parsing, reading 4-bit flags, and testing flags & 1 to detect a bounced message. In Tolk, bounced messages are handled through a separate entry point:
The compiler automatically routes bounced messages:
If onBouncedMessage is not declared, bounced messages are filtered out:
Bounced body is either “first 256 bits” or “the entire body” When you use createMessage, its parameter bounce is an enum:
  • BounceMode.NoBounce
  • BounceMode.Only256BitsOfBodyin.bouncedBody will be “0xFFFFFFFF” + first 256 bits of original body (cheapest)
  • BounceMode.RichBounce — parse in.bouncedBody with RichBounceBody.fromSlice
  • BounceMode.RichBounceOnlyRootCell — same, but originalBody will contain only a root cell

Next steps

Explore the Tolk vs FunC benchmarks —real Jetton, NFT, and Wallet contracts migrated from FunC with the same logic. Use the FunC-to-Tolk converter for incremental migration. Run npm create ton@latest to experiment.