From a2417648d1f45da3c16f0fb89f30776ff4a72f27 Mon Sep 17 00:00:00 2001
From: Novus Nota <68142933+novusnota@users.noreply.github.com>
Date: Mon, 8 Apr 2024 16:30:06 +0200
Subject: [PATCH 01/24] chore: Started the big move
---
pages/_meta.js | 4 +-
pages/language/_meta.js | 20 ---
pages/language/libs/_meta.js | 9 --
pages/language/ref/_meta.js | 8 --
pages/ref/_meta.js | 41 ++++++
.../ref/advanced.mdx => ref/api-advanced.mdx} | 0
pages/ref/api-base.mdx | 11 ++
.../ref/cells.mdx => ref/api-cells.mdx} | 0
.../ref/common.mdx => ref/api-common.mdx} | 127 +-----------------
pages/ref/api-comptime.mdx | 65 +++++++++
pages/ref/api-debug.mdx | 75 +++++++++++
.../ref/math.mdx => ref/api-math.mdx} | 0
.../ref/random.mdx => ref/api-random.mdx} | 0
.../ref/strings.mdx => ref/api-strings.mdx} | 8 +-
pages/{language => ref}/evolution/OTP-001.mdx | 0
pages/{language => ref}/evolution/OTP-002.mdx | 0
pages/{language => ref}/evolution/OTP-003.mdx | 0
pages/{language => ref}/evolution/OTP-004.mdx | 0
pages/{language => ref}/evolution/OTP-005.mdx | 0
pages/{language => ref}/evolution/OTP-006.mdx | 0
pages/{language => ref}/evolution/_meta.js | 0
.../{language => ref}/evolution/overview.mdx | 0
pages/{language => ref}/index.mdx | 0
pages/{language => ref}/spec.mdx | 0
.../standard-libraries.mdx} | 6 +-
.../libs/config.mdx => ref/stdlib-config.mdx} | 0
.../content.mdx => ref/stdlib-content.mdx} | 0
.../libs/deploy.mdx => ref/stdlib-deploy.mdx} | 0
.../libs/dns.mdx => ref/stdlib-dns.mdx} | 0
.../ownable.mdx => ref/stdlib-ownable.mdx} | 0
.../stdlib-stoppable.mdx} | 0
31 files changed, 209 insertions(+), 165 deletions(-)
delete mode 100644 pages/language/_meta.js
delete mode 100644 pages/language/libs/_meta.js
delete mode 100644 pages/language/ref/_meta.js
create mode 100644 pages/ref/_meta.js
rename pages/{language/ref/advanced.mdx => ref/api-advanced.mdx} (100%)
create mode 100644 pages/ref/api-base.mdx
rename pages/{language/ref/cells.mdx => ref/api-cells.mdx} (100%)
rename pages/{language/ref/common.mdx => ref/api-common.mdx} (64%)
create mode 100644 pages/ref/api-comptime.mdx
create mode 100644 pages/ref/api-debug.mdx
rename pages/{language/ref/math.mdx => ref/api-math.mdx} (100%)
rename pages/{language/ref/random.mdx => ref/api-random.mdx} (100%)
rename pages/{language/ref/strings.mdx => ref/api-strings.mdx} (99%)
rename pages/{language => ref}/evolution/OTP-001.mdx (100%)
rename pages/{language => ref}/evolution/OTP-002.mdx (100%)
rename pages/{language => ref}/evolution/OTP-003.mdx (100%)
rename pages/{language => ref}/evolution/OTP-004.mdx (100%)
rename pages/{language => ref}/evolution/OTP-005.mdx (100%)
rename pages/{language => ref}/evolution/OTP-006.mdx (100%)
rename pages/{language => ref}/evolution/_meta.js (100%)
rename pages/{language => ref}/evolution/overview.mdx (100%)
rename pages/{language => ref}/index.mdx (100%)
rename pages/{language => ref}/spec.mdx (100%)
rename pages/{language/libs/overview.mdx => ref/standard-libraries.mdx} (85%)
rename pages/{language/libs/config.mdx => ref/stdlib-config.mdx} (100%)
rename pages/{language/libs/content.mdx => ref/stdlib-content.mdx} (100%)
rename pages/{language/libs/deploy.mdx => ref/stdlib-deploy.mdx} (100%)
rename pages/{language/libs/dns.mdx => ref/stdlib-dns.mdx} (100%)
rename pages/{language/libs/ownable.mdx => ref/stdlib-ownable.mdx} (100%)
rename pages/{language/libs/stoppable.mdx => ref/stdlib-stoppable.mdx} (100%)
diff --git a/pages/_meta.js b/pages/_meta.js
index daf8a929..330d4313 100644
--- a/pages/_meta.js
+++ b/pages/_meta.js
@@ -15,8 +15,8 @@ export default {
title: "Cookbook",
type: 'page',
},
- language: {
- title: "Language",
+ ref: {
+ title: "Reference",
type: 'page',
},
ecosystem: {
diff --git a/pages/language/_meta.js b/pages/language/_meta.js
deleted file mode 100644
index 50a90981..00000000
--- a/pages/language/_meta.js
+++ /dev/null
@@ -1,20 +0,0 @@
-export default {
- index: 'Overview',
- ref: 'Reference',
- libs: 'Libraries',
- spec: 'Specification',
- evolution: 'Evolution',
- '-- Community': {
- type: 'separator',
- },
- 'telegram-link': {
- title: '✈️ Telegram',
- href: 'https://t.me/tactlang',
- newWindow: true
- },
- 'xtwitter-link': {
- title: '🐦 X/Twitter',
- href: 'https://twitter.com/tact_language',
- newWindow: true
- },
-}
\ No newline at end of file
diff --git a/pages/language/libs/_meta.js b/pages/language/libs/_meta.js
deleted file mode 100644
index e01b1cc5..00000000
--- a/pages/language/libs/_meta.js
+++ /dev/null
@@ -1,9 +0,0 @@
-export default {
- overview: 'Overview',
- config: '@stdlib/config',
- content: '@stdlib/content',
- deploy: '@stdlib/deploy',
- dns: '@stdlib/dns',
- ownable: '@stdlib/ownable',
- stoppable: '@stdlib/stoppable'
-}
diff --git a/pages/language/ref/_meta.js b/pages/language/ref/_meta.js
deleted file mode 100644
index cd61e554..00000000
--- a/pages/language/ref/_meta.js
+++ /dev/null
@@ -1,8 +0,0 @@
-export default {
- common: 'Common',
- strings: 'Strings',
- random: 'Random',
- math: 'Math',
- cells: 'Cells, Builders and Slices',
- advanced: 'Advanced',
-}
\ No newline at end of file
diff --git a/pages/ref/_meta.js b/pages/ref/_meta.js
new file mode 100644
index 00000000..1c5d51b4
--- /dev/null
+++ b/pages/ref/_meta.js
@@ -0,0 +1,41 @@
+export default {
+ index: 'Overview',
+ spec: 'Specification',
+ evolution: 'Evolution',
+ '-- API': {
+ type: 'separator',
+ title: 'API Reference',
+ },
+ 'api-base': 'Base trait',
+ 'api-comptime': 'Compile-time',
+ 'api-common': 'Common', // what does it mean???
+ 'api-strings': 'Strings', // text.tact + ...
+ 'api-random': 'Random',
+ 'api-math': 'Math',
+ 'api-cells': 'Cells, Builders and Slices',
+ 'api-advanced': 'Advanced',
+ '-- Stdlib': {
+ type: 'separator',
+ title: 'Standard Libraries',
+ },
+ 'standard-libraries': 'Overview',
+ 'stdlib-config': '@stdlib/config',
+ 'stdlib-content': '@stdlib/content',
+ 'stdlib-deploy': '@stdlib/deploy',
+ 'stdlib-dns': '@stdlib/dns',
+ 'stdlib-ownable': '@stdlib/ownable',
+ 'stdlib-stoppable': '@stdlib/stoppable',
+ '-- Community': {
+ type: 'separator',
+ },
+ 'telegram-link': {
+ title: '✈️ Telegram',
+ href: 'https://t.me/tactlang',
+ newWindow: true
+ },
+ 'xtwitter-link': {
+ title: '🐦 X/Twitter',
+ href: 'https://twitter.com/tact_language',
+ newWindow: true
+ },
+}
diff --git a/pages/language/ref/advanced.mdx b/pages/ref/api-advanced.mdx
similarity index 100%
rename from pages/language/ref/advanced.mdx
rename to pages/ref/api-advanced.mdx
diff --git a/pages/ref/api-base.mdx b/pages/ref/api-base.mdx
new file mode 100644
index 00000000..7963aeef
--- /dev/null
+++ b/pages/ref/api-base.mdx
@@ -0,0 +1,11 @@
+# Base trait
+
+import { Callout } from 'nextra-theme-docs'
+
+Every [contract](/book/contracts) and [trait](/book/types#traits) in Tact implicitly inherits the `Base{:tact}` trait, which contains a number of the most useful [internal functions (methods)](/book/contracts#internal-functions) for any kind of contract.
+
+
+
+ This page is a stub. [Contributions are welcome!](https://github.com/tact-lang/tact-docs/issues)
+
+
diff --git a/pages/language/ref/cells.mdx b/pages/ref/api-cells.mdx
similarity index 100%
rename from pages/language/ref/cells.mdx
rename to pages/ref/api-cells.mdx
diff --git a/pages/language/ref/common.mdx b/pages/ref/api-common.mdx
similarity index 64%
rename from pages/language/ref/common.mdx
rename to pages/ref/api-common.mdx
index 7366ae64..f56de18e 100644
--- a/pages/language/ref/common.mdx
+++ b/pages/ref/api-common.mdx
@@ -2,7 +2,8 @@
import { Callout } from 'nextra-theme-docs'
-List of a basic functions that are available in all smart contracts.
+List of the most commonly used built-in [global static functions](/book/functions#global-static-functions).
+
## sender
@@ -32,21 +33,6 @@ receive() {
-## require
-
-```tact
-fun require(condition: Bool, error: String);
-```
-
-Checks the `condition` and throws an exception with `error` message if the `condition` is `false{:tact}`. Does nothing otherwise.
-
-Usage example:
-
-```tact
-// now() has to return a value greater than 1000, otherwise an error message will be thrown
-require(now() > 1000, "We're in the first 1000 seconds of 1 January 1970!");
-```
-
## now
```tact
@@ -164,23 +150,11 @@ let hereBeDragons: Address = contractAddressExt(0, initPkg.code, initPkg.data);
-## address
-
-```tact
-fun address(s: String): Address;
-```
-
-A compile-time function that converts a [`String{:tact}`][p] with an address into the Address type.
+
-Usage example:
+ For this function to work, the compiler option `debug` has to be set to `true{:tact}` for the current project in the [configuration file](/book/config). Read more about debugging on the dedicated page: [Debugging](/book/debug).
-```tact
-contract Example {
- // Persistent state variables
- addr: Address =
- address("EQCD39VS5jcptHL8vMjEXrzGaRcCVYto7HUn4bpAOg8xqB2N"); // works at compile-time!
-}
-```
+
## emit
@@ -196,97 +170,6 @@ Usage example:
emit("Catch me if you can".asComment()); // asComment() converts a String to a Cell
```
-## cell
-
-```tact
-fun cell(bocBase64: String): Cell;
-```
-
-A compile-time function that embeds a base64-encoded [BoC](https://docs.ton.org/develop/data-formats/cell-boc#bag-of-cells) `bocBase64` as a [`Cell{:tact}`][p] into the contract.
-
-Usage example:
-
-```tact
-// Init package for Wallet V3R1 as a base64-encoded BoC:
-cell("te6cckEBAQEAYgAAwP8AIN0gggFMl7qXMO1E0NcLH+Ck8mCDCNcYINMf0x/TH/gjE7vyY+1E0NMf0x/T/9FRMrryoVFEuvKiBPkBVBBV+RDyo/gAkyDXSpbTB9QC+wDo0QGkyMsfyx/L/8ntVD++buA=");
-```
-
-
-
- **Useful links:**\
- [Bag of Cells in TON Docs](https://docs.ton.org/develop/data-formats/cell-boc#bag-of-cells)
-
-
-
-## ton
-
-```tact
-fun ton(value: String): Int;
-```
-
-A compile-time function that converts the given Toncoins `value` from a human-readable format [`String{:tact}`][p] to the nanoToncoins [`Int{:tact}`][int] format.
-
-Usage example:
-
-```tact
-ton("1"); // 10^9 nanoToncoins, which is equal to one Toncoin
-ton("0.1"); // 10^8 nanoToncoins, which is equal to 0.1 Toncoin
-ton("0.000000001"); // 1 nanoToncoin, which is equal to 10^-9 Toncoins
-```
-
-## dump
-
-```tact
-fun dump(arg);
-```
-
-Prints the argument `arg` to the contract's debug console. Evaluated only if `debug` option is set in the [configuration file](/book/config), otherwise does nothing.
-
-Can be applied to the following list of types and values:
-
-* [`Int{:tact}`][int]
-* [`Bool{:tact}`][bool]
-* [`Builder{:tact}`][p], [`Cell{:tact}`][p] or [`Slice{:tact}`][p]
-* [`String{:tact}`][p] or [`StringBuilder{:tact}`][p]
-* [`map{:tact}`](/book/maps)
-* [Optionals and `null{:tact}` value](/book/optionals)
-* `void`, which is implicitly returned when a function doesn't have return value defined
-
-Usage examples:
-
-```tact
-// Int
-dump(42);
-
-// Bool
-dump(true);
-dump(false);
-
-// Builder, Cell or Slice
-dump(beginCell()); // Builder
-dump(emptyCell()); // Cell
-dump(emptyCell().asSlice()); // Slice
-
-// String or StringBuilder
-dump("Hello, my name is..."); // String
-dump(beginTailString()); // StringBuilder
-
-// Maps
-let m: map = emptyMap();
-m.set(2 + 2, 4);
-dump(m);
-
-// Special values
-dump(null);
-dump(emit("msg".asComment())); // As emit() function doesn't return a value, dump() would print #DEBUG#: void.
-```
-
-
-
- For this function to work, the compiler option `debug` has to be set to `true{:tact}` for the current project in the [configuration file](/book/config). Read more about debugging on the dedicated page: [Debugging](/book/debug).
-
-
-
## context
```tact
diff --git a/pages/ref/api-comptime.mdx b/pages/ref/api-comptime.mdx
new file mode 100644
index 00000000..eae71729
--- /dev/null
+++ b/pages/ref/api-comptime.mdx
@@ -0,0 +1,65 @@
+# Compile-time
+
+import { Callout } from 'nextra-theme-docs'
+
+This page lists all the built-in [global static functions](/book/functions#global-static-functions), which are evaluated at the time of building the Tact project (compile-time).
+
+## address
+
+```tact
+fun address(s: String): Address;
+```
+
+A compile-time function that converts a [`String{:tact}`][p] with an address into the Address type.
+
+Usage example:
+
+```tact
+contract Example {
+ // Persistent state variables
+ addr: Address =
+ address("EQCD39VS5jcptHL8vMjEXrzGaRcCVYto7HUn4bpAOg8xqB2N"); // works at compile-time!
+}
+```
+
+## cell
+
+```tact
+fun cell(bocBase64: String): Cell;
+```
+
+A compile-time function that embeds a base64-encoded [BoC](https://docs.ton.org/develop/data-formats/cell-boc#bag-of-cells) `bocBase64` as a [`Cell{:tact}`][p] into the contract.
+
+Usage example:
+
+```tact
+// Init package for Wallet V3R1 as a base64-encoded BoC:
+cell("te6cckEBAQEAYgAAwP8AIN0gggFMl7qXMO1E0NcLH+Ck8mCDCNcYINMf0x/TH/gjE7vyY+1E0NMf0x/T/9FRMrryoVFEuvKiBPkBVBBV+RDyo/gAkyDXSpbTB9QC+wDo0QGkyMsfyx/L/8ntVD++buA=");
+```
+
+
+
+ **Useful links:**\
+ [Bag of Cells in TON Docs](https://docs.ton.org/develop/data-formats/cell-boc#bag-of-cells)
+
+
+
+## ton
+
+```tact
+fun ton(value: String): Int;
+```
+
+A compile-time function that converts the given Toncoins `value` from a human-readable format [`String{:tact}`][p] to the nanoToncoins [`Int{:tact}`][int] format.
+
+Usage example:
+
+```tact
+ton("1"); // 10^9 nanoToncoins, which is equal to one Toncoin
+ton("0.1"); // 10^8 nanoToncoins, which is equal to 0.1 Toncoin
+ton("0.000000001"); // 1 nanoToncoin, which is equal to 10^-9 Toncoins
+```
+
+[p]: /book/types#primitive-types
+[bool]: /book/types#booleans
+[int]: /book/integers
diff --git a/pages/ref/api-debug.mdx b/pages/ref/api-debug.mdx
new file mode 100644
index 00000000..8f928596
--- /dev/null
+++ b/pages/ref/api-debug.mdx
@@ -0,0 +1,75 @@
+# Debug
+
+import { Callout } from 'nextra-theme-docs'
+
+## require
+
+```tact
+fun require(condition: Bool, error: String);
+```
+
+Checks the `condition` and throws an exception with `error` message if the `condition` is `false{:tact}`. Does nothing otherwise.
+
+Usage example:
+
+```tact
+// now() has to return a value greater than 1000, otherwise an error message will be thrown
+require(now() > 1000, "We're in the first 1000 seconds of 1 January 1970!");
+```
+
+## dump
+
+```tact
+fun dump(arg);
+```
+
+Prints the argument `arg` to the contract's debug console. Evaluated only if `debug` option is set in the [configuration file](/book/config), otherwise does nothing.
+
+Can be applied to the following list of types and values:
+
+* [`Int{:tact}`][int]
+* [`Bool{:tact}`][bool]
+* [`Builder{:tact}`][p], [`Cell{:tact}`][p] or [`Slice{:tact}`][p]
+* [`String{:tact}`][p] or [`StringBuilder{:tact}`][p]
+* [`map{:tact}`](/book/maps)
+* [Optionals and `null{:tact}` value](/book/optionals)
+* `void`, which is implicitly returned when a function doesn't have return value defined
+
+Usage examples:
+
+```tact
+// Int
+dump(42);
+
+// Bool
+dump(true);
+dump(false);
+
+// Builder, Cell or Slice
+dump(beginCell()); // Builder
+dump(emptyCell()); // Cell
+dump(emptyCell().asSlice()); // Slice
+
+// String or StringBuilder
+dump("Hello, my name is..."); // String
+dump(beginTailString()); // StringBuilder
+
+// Maps
+let m: map = emptyMap();
+m.set(2 + 2, 4);
+dump(m);
+
+// Special values
+dump(null);
+dump(emit("msg".asComment())); // As emit() function doesn't return a value, dump() would print #DEBUG#: void.
+```
+
+[p]: /book/types#primitive-types
+[bool]: /book/types#booleans
+[int]: /book/integers
+
+## dumpStack
+## throw
+## nativeThrow
+## nativeThrowWhen
+## nativeThrowUnless
diff --git a/pages/language/ref/math.mdx b/pages/ref/api-math.mdx
similarity index 100%
rename from pages/language/ref/math.mdx
rename to pages/ref/api-math.mdx
diff --git a/pages/language/ref/random.mdx b/pages/ref/api-random.mdx
similarity index 100%
rename from pages/language/ref/random.mdx
rename to pages/ref/api-random.mdx
diff --git a/pages/language/ref/strings.mdx b/pages/ref/api-strings.mdx
similarity index 99%
rename from pages/language/ref/strings.mdx
rename to pages/ref/api-strings.mdx
index fe5814c5..2329c358 100644
--- a/pages/language/ref/strings.mdx
+++ b/pages/ref/api-strings.mdx
@@ -86,19 +86,25 @@ extends fun asSlice(self: String): Slice;
**Dangerously** casts string as slice for future parsing. Use it only if you know what you are doing.
## Slice.asString
+
```tact
extends fun asString(self: Slice): String;
```
+
**Dangerously** casts slice as string. Use it only if you know what you are doing.
## String.fromBase64
+
```tact
extends fun fromBase64(self: String): Slice;
```
+
Decodes base64 string to a slice. NOTE: This method is very limited and can be used only for small strings that fits a single cell.
## Slice.fromBase64
+
```tact
extends fun fromBase64(self: Slice): Slice;
```
-Decodes base64 slice to a slice. Alias for `self.asString().fromBase64()`
\ No newline at end of file
+
+Decodes base64 slice to a slice. Alias for `self.asString().fromBase64()`
diff --git a/pages/language/evolution/OTP-001.mdx b/pages/ref/evolution/OTP-001.mdx
similarity index 100%
rename from pages/language/evolution/OTP-001.mdx
rename to pages/ref/evolution/OTP-001.mdx
diff --git a/pages/language/evolution/OTP-002.mdx b/pages/ref/evolution/OTP-002.mdx
similarity index 100%
rename from pages/language/evolution/OTP-002.mdx
rename to pages/ref/evolution/OTP-002.mdx
diff --git a/pages/language/evolution/OTP-003.mdx b/pages/ref/evolution/OTP-003.mdx
similarity index 100%
rename from pages/language/evolution/OTP-003.mdx
rename to pages/ref/evolution/OTP-003.mdx
diff --git a/pages/language/evolution/OTP-004.mdx b/pages/ref/evolution/OTP-004.mdx
similarity index 100%
rename from pages/language/evolution/OTP-004.mdx
rename to pages/ref/evolution/OTP-004.mdx
diff --git a/pages/language/evolution/OTP-005.mdx b/pages/ref/evolution/OTP-005.mdx
similarity index 100%
rename from pages/language/evolution/OTP-005.mdx
rename to pages/ref/evolution/OTP-005.mdx
diff --git a/pages/language/evolution/OTP-006.mdx b/pages/ref/evolution/OTP-006.mdx
similarity index 100%
rename from pages/language/evolution/OTP-006.mdx
rename to pages/ref/evolution/OTP-006.mdx
diff --git a/pages/language/evolution/_meta.js b/pages/ref/evolution/_meta.js
similarity index 100%
rename from pages/language/evolution/_meta.js
rename to pages/ref/evolution/_meta.js
diff --git a/pages/language/evolution/overview.mdx b/pages/ref/evolution/overview.mdx
similarity index 100%
rename from pages/language/evolution/overview.mdx
rename to pages/ref/evolution/overview.mdx
diff --git a/pages/language/index.mdx b/pages/ref/index.mdx
similarity index 100%
rename from pages/language/index.mdx
rename to pages/ref/index.mdx
diff --git a/pages/language/spec.mdx b/pages/ref/spec.mdx
similarity index 100%
rename from pages/language/spec.mdx
rename to pages/ref/spec.mdx
diff --git a/pages/language/libs/overview.mdx b/pages/ref/standard-libraries.mdx
similarity index 85%
rename from pages/language/libs/overview.mdx
rename to pages/ref/standard-libraries.mdx
index 9666e4ee..1793e594 100644
--- a/pages/language/libs/overview.mdx
+++ b/pages/ref/standard-libraries.mdx
@@ -1,8 +1,8 @@
import { Callout } from 'nextra-theme-docs'
-# Overview
+# Standard libraries overview
-Some standard libraries (also referred to as stdlibs) come bundled with Tact compiler, but aren't automatically included to your project until explicitly made to.
+Some libraries (also referred to as standard libraries or stdlibs) come bundled with Tact compiler, but aren't automatically included to your project until explicitly made to.
To import any standard library, use the `import{:tact}` statement followed by the name of that library in a [string](/language/ref/strings), like so:
@@ -29,4 +29,4 @@ Library | Description
[6]: /language/libs/stoppable
[cell]: /language/ref/cells
[str]: /language/ref/strings
-[dns]: https://docs.ton.org/participate/web3/dns
\ No newline at end of file
+[dns]: https://docs.ton.org/participate/web3/dns
diff --git a/pages/language/libs/config.mdx b/pages/ref/stdlib-config.mdx
similarity index 100%
rename from pages/language/libs/config.mdx
rename to pages/ref/stdlib-config.mdx
diff --git a/pages/language/libs/content.mdx b/pages/ref/stdlib-content.mdx
similarity index 100%
rename from pages/language/libs/content.mdx
rename to pages/ref/stdlib-content.mdx
diff --git a/pages/language/libs/deploy.mdx b/pages/ref/stdlib-deploy.mdx
similarity index 100%
rename from pages/language/libs/deploy.mdx
rename to pages/ref/stdlib-deploy.mdx
diff --git a/pages/language/libs/dns.mdx b/pages/ref/stdlib-dns.mdx
similarity index 100%
rename from pages/language/libs/dns.mdx
rename to pages/ref/stdlib-dns.mdx
diff --git a/pages/language/libs/ownable.mdx b/pages/ref/stdlib-ownable.mdx
similarity index 100%
rename from pages/language/libs/ownable.mdx
rename to pages/ref/stdlib-ownable.mdx
diff --git a/pages/language/libs/stoppable.mdx b/pages/ref/stdlib-stoppable.mdx
similarity index 100%
rename from pages/language/libs/stoppable.mdx
rename to pages/ref/stdlib-stoppable.mdx
From 65fb5d40bfe54f7b4f2e75432ce898d91f9a96c9 Mon Sep 17 00:00:00 2001
From: Novus Nota <68142933+novusnota@users.noreply.github.com>
Date: Mon, 8 Apr 2024 18:58:26 +0200
Subject: [PATCH 02/24] chore: Fix internal linkage
---
pages/book/index.mdx | 4 +--
pages/cookbook/index.mdx | 2 +-
pages/ecosystem/index.mdx | 6 ++--
pages/ref/_meta.js | 2 +-
pages/ref/api-advanced.mdx | 8 +++--
pages/ref/api-common.mdx | 3 +-
pages/ref/api-comptime.mdx | 15 +++++++++
pages/ref/api-math.mdx | 6 ----
pages/ref/evolution/overview.mdx | 16 +++++-----
pages/ref/index.mdx | 28 ++++++++--------
pages/ref/standard-libraries.mdx | 55 +++++++++++++++++++++-----------
pages/ref/stdlib-config.mdx | 16 ++++------
pages/ref/stdlib-content.mdx | 11 ++++---
pages/ref/stdlib-deploy.mdx | 4 +--
pages/ref/stdlib-dns.mdx | 49 +++++++++++-----------------
pages/ref/stdlib-ownable.mdx | 10 +++---
pages/ref/stdlib-stoppable.mdx | 6 ++--
17 files changed, 128 insertions(+), 113 deletions(-)
diff --git a/pages/book/index.mdx b/pages/book/index.mdx
index b116cbfd..af9ed9df 100644
--- a/pages/book/index.mdx
+++ b/pages/book/index.mdx
@@ -1,10 +1,10 @@
-# Book Overview
+# Book overview
import { Cards, Steps } from 'nextra/components'
Welcome to **The Tact Book** section (or just **The Book**), — an introductory book about the Tact language.
-Here are it's main contents:
+Here are its main contents:
diff --git a/pages/cookbook/index.mdx b/pages/cookbook/index.mdx
index 0f1798d5..fe04518c 100644
--- a/pages/cookbook/index.mdx
+++ b/pages/cookbook/index.mdx
@@ -1,4 +1,4 @@
-# Cookbook Overview
+# Cookbook overview
import { Callout, Steps, Cards } from 'nextra/components'
import { OneIcon, FormulaIcon, DiagramIcon, DropperIcon, BoxIcon, IdCardIcon, WarningIcon, StarsIcon, RowsIcon, GearIcon, LightningIcon } from '@components/icons'
diff --git a/pages/ecosystem/index.mdx b/pages/ecosystem/index.mdx
index 01ff105b..0bde8b7a 100644
--- a/pages/ecosystem/index.mdx
+++ b/pages/ecosystem/index.mdx
@@ -1,10 +1,10 @@
-# Overview
+# Ecosystem overview
import { Cards, Steps } from 'nextra/components'
Welcome to the **Ecosystem** section — a bird-eye overview of Tact ecosystem, tools and ways you can start contributing to those!
-Here are it's main contents:
+Here are its main contents:
@@ -20,4 +20,4 @@ Here are it's main contents:
/>
-
\ No newline at end of file
+
diff --git a/pages/ref/_meta.js b/pages/ref/_meta.js
index 1c5d51b4..7e7813d8 100644
--- a/pages/ref/_meta.js
+++ b/pages/ref/_meta.js
@@ -16,7 +16,7 @@ export default {
'api-advanced': 'Advanced',
'-- Stdlib': {
type: 'separator',
- title: 'Standard Libraries',
+ title: 'Standard libraries',
},
'standard-libraries': 'Overview',
'stdlib-config': '@stdlib/config',
diff --git a/pages/ref/api-advanced.mdx b/pages/ref/api-advanced.mdx
index ee777acc..85ed0db9 100644
--- a/pages/ref/api-advanced.mdx
+++ b/pages/ref/api-advanced.mdx
@@ -1,11 +1,13 @@
-# Advanced
+# Miscellaneous
import { Callout } from 'nextra/components'
-Dangerous or unstable features meant to be used by advanced users only.
+Various niche, dangerous or unstable features which can produce unexpected results and are meant to be used by the more experienced users.
+
Proceed with caution.
+
## readForwardFee
@@ -122,4 +124,4 @@ Function `raw_reserve` is roughly equivalent to creating an outbound message car
Currently, `amount` must be a non-negative integer, and `mode` must be in the range 0..15, inclusive.
-
\ No newline at end of file
+
diff --git a/pages/ref/api-common.mdx b/pages/ref/api-common.mdx
index f56de18e..d77efe59 100644
--- a/pages/ref/api-common.mdx
+++ b/pages/ref/api-common.mdx
@@ -4,7 +4,6 @@ import { Callout } from 'nextra-theme-docs'
List of the most commonly used built-in [global static functions](/book/functions#global-static-functions).
-
## sender
```tact
@@ -87,7 +86,7 @@ let meMyselfAndI: Address = myAddress();
fun newAddress(chain: Int, hash: Int): Address;
```
-Creates a new [`Address{:tact}`][p] based on the [`chain` id](https://ton-blockchain.github.io/docs/#/overviews/TON_blockchain_overview) and the [SHA-256](/language/ref/math#sha256) encoded [`hash` value](https://docs.ton.org/learn/overviews/addresses#account-id).
+Creates a new [`Address{:tact}`][p] based on the [`chain` id](https://ton-blockchain.github.io/docs/#/overviews/TON_blockchain_overview) and the [SHA-256](/ref/stdlib-math#sha256) encoded [`hash` value](https://docs.ton.org/learn/overviews/addresses#account-id).
Usage example:
diff --git a/pages/ref/api-comptime.mdx b/pages/ref/api-comptime.mdx
index eae71729..67d8ffc3 100644
--- a/pages/ref/api-comptime.mdx
+++ b/pages/ref/api-comptime.mdx
@@ -60,6 +60,21 @@ ton("0.1"); // 10^8 nanoToncoins, which is equal to 0.1 Toncoin
ton("0.000000001"); // 1 nanoToncoin, which is equal to 10^-9 Toncoins
```
+## pow
+
+```tact
+fun pow(a: Int, b: Int): Int;
+```
+
+A compile-time function that computes the exponent `b` of value `a`. Exponent `b` must be non-negative.
+
+Usage example:
+
+```tact
+pow(2, 3); // raises 2 to the 3rd power, which is 8
+pow(5, 0); // raises 5 to the power 0, which always produces 1
+```
+
[p]: /book/types#primitive-types
[bool]: /book/types#booleans
[int]: /book/integers
diff --git a/pages/ref/api-math.mdx b/pages/ref/api-math.mdx
index 1e1987fc..3eaf644e 100644
--- a/pages/ref/api-math.mdx
+++ b/pages/ref/api-math.mdx
@@ -41,9 +41,3 @@ Computes the maximum of two integers `x` and `y`.
fun abs(x: Int): Int
```
Computes the absolute value of the integer `x`.
-
-## pow
-```tact
-fun pow(a: Int, b: Int): Int
-```
-Computes the exponent `b` of `a`.
\ No newline at end of file
diff --git a/pages/ref/evolution/overview.mdx b/pages/ref/evolution/overview.mdx
index 23716b95..233ed167 100644
--- a/pages/ref/evolution/overview.mdx
+++ b/pages/ref/evolution/overview.mdx
@@ -1,4 +1,4 @@
-# Overview
+# Evolution overview
import { Cards } from 'nextra/components'
@@ -11,32 +11,32 @@ Additionaly, it features TEPs (TON Enhancement Proposals) and the up-to-date cha
@@ -48,4 +48,4 @@ List of [merged TEPs](https://github.com/ton-blockchain/TEPs#merged-teps).
## Changelog
-All notable changes to the main Tact repository are documented in the [CHANGELOG.md](https://github.com/tact-lang/tact/blob/main/CHANGELOG.md).
\ No newline at end of file
+All notable changes to the main Tact repository are documented in the [CHANGELOG.md](https://github.com/tact-lang/tact/blob/main/CHANGELOG.md).
diff --git a/pages/ref/index.mdx b/pages/ref/index.mdx
index 154bb183..3fe0142b 100644
--- a/pages/ref/index.mdx
+++ b/pages/ref/index.mdx
@@ -1,58 +1,58 @@
-# Overview
+# Reference overview
import { Cards, Steps } from 'nextra/components'
Welcome to the **Language** section of Tact documentation — a place for becoming more familiar with the language in much more depth compared to the [Book](/book).
-Here are it's main contents:
+Here are its main contents:
-### Reference
+### API Reference
-[Reference](/language/ref/common) is a comprehensive list of language syntax and semantics. More detailed than the [Book](/book) at the expense of no additional guidance — targeted at more experienced programmers.
+[API Reference](/ref/stdlib-common) gives a comprehensive list of auto-included constructs and provides examples of their usage.
-### Libraries
+### Standard libraries
-[Libraries](/language/libs/overview) sub-section explains how to use the bundled libraries, how to import external code and lists all the contents of the standard library.
+[Standard libraries](/ref/standard-libraries) sub-section explains how to use the bundled libraries, lists all their contents with examples of their usage.
### Specification
-[Specification](/language/spec) page provides full Tact grammar written in Ohm language, which is used in the Tact's compiler. Aimed at more experienced programmers, but generally can still be very handy to quickly grasp all of the possible syntax in the language.
+[Specification](/ref/spec) page provides full Tact grammar written in Ohm language, which is used in the Tact's compiler. Aimed at more experienced programmers, but generally can still be very handy to quickly grasp all of the possible syntax in the language.
### Evolution
-Finally, [Evolution](/language/evolution/overview) sub-section gives insight on important decisions about language semantics, Tact's future and links to the up-to-date changelog of Tact updates.
+Finally, [Evolution](/ref/evolution/overview) sub-section gives insight on important decisions about language semantics, Tact's future and links to the up-to-date changelog of Tact updates.
diff --git a/pages/ref/standard-libraries.mdx b/pages/ref/standard-libraries.mdx
index 1793e594..398a13f7 100644
--- a/pages/ref/standard-libraries.mdx
+++ b/pages/ref/standard-libraries.mdx
@@ -4,29 +4,46 @@ import { Callout } from 'nextra-theme-docs'
Some libraries (also referred to as standard libraries or stdlibs) come bundled with Tact compiler, but aren't automatically included to your project until explicitly made to.
-To import any standard library, use the `import{:tact}` statement followed by the name of that library in a [string](/language/ref/strings), like so:
+To import any standard library, use the [`import{:tact}` keyword](/book/import) followed by the name of that library in a [string][p], like so:
```tact
-import "@stdlib/deploy"; // this would include everything from @stdlib/deploy library into your codebase
+// This would include everything from @stdlib/deploy into your codebase:
+import "@stdlib/deploy";
```
## List of standard libraries: [#list]
-Library | Description | Commonly used APIs
-:--------------------- | :--------------------------------------------------------------- | :-----------------
-[@stdlib/config][1] | Config and elector address retrieval. | `getConfigAddress`, `getElectorAddress`
-[@stdlib/content][2] | Encoding off-chain link [strings][str] to a [Cell][cell]. | `createOffchainContent`
-[@stdlib/deploy][3] | Unified mechanism for deployments. | `Deployable`, `FactoryDeployable`
-[@stdlib/dns][4] | Resolution of [DNS][dns] names. | `DNSResolver`, `dnsInternalVerify`
-[@stdlib/ownable][5] | Traits for ownership management. | `Ownable`, `OwnableTransferable`
-[@stdlib/stoppable][6] | Traits that allow contract stops. Requires [@stdlib/ownable][5]. | `Stoppable`, `Resumable`
-
-[1]: /language/libs/config
-[2]: /language/libs/content
-[3]: /language/libs/deploy
-[4]: /language/libs/dns
-[5]: /language/libs/ownable
-[6]: /language/libs/stoppable
-[cell]: /language/ref/cells
-[str]: /language/ref/strings
+Library | Description | Commonly used APIs
+:----------------------- | :--------------------------------------------------------------- | :-----------------
+[`@stdlib/config`][1] | Config and elector address retrieval. | [`getConfigAddress{:tact}`][gca], [`getElectorAddress{:tact}`][gea]
+[`@stdlib/content`][2] | Encoding off-chain link [strings][p] to a [`Cell{:tact}`][p]. | [`createOffchainContent{:tact}`][coff]
+[`@stdlib/deploy`][3] | Unified mechanism for deployments. | [`Deployable{:tact}`][dep], [`FactoryDeployable{:tact}`][fcd]
+[`@stdlib/dns`][4] | Resolution of [DNS][dns] names. | [`DNSResolver{:tact}`][dnsr], [`dnsInternalVerify{:tact}`][dnsi]
+[`@stdlib/ownable`][5] | Traits for ownership management. | [`Ownable{:tact}`][own], [`OwnableTransferable{:tact}`][ownt]
+[`@stdlib/stoppable`][6] | Traits that allow contract stops. Requires [@stdlib/ownable][5]. | [`Stoppable{:tact}`][stp], [`Resumable{:tact}`][res]
+
+[1]: /ref/stdlib-config
+[gca]: /ref/stdlib-config#getconfigaddress
+[gea]: /ref/stdlib-config#getelectoraddress
+
+[2]: /ref/stdlib-content
+[coff]: /ref/stdlib-content#createoffchaincontent
+
+[3]: /ref/stdlib-deploy
+[dep]: /ref/stdlib-deploy#deployable
+[fcd]: /ref/stdlib-deploy#factorydeployable
+
+[4]: /ref/stdlib-dns
+[dnsr]: /ref/stdlib-dns#dnsresolver
+[dnsi]: /ref/stdlib-dns#dnsinternalverify
+
+[5]: /ref/stdlib-ownable
+[own]: /ref/stdlib-ownable#ownable
+[ownt]: /ref/stdlib-ownable#ownabletransferable
+
+[6]: /ref/stdlib-stoppable
+[stp]: /ref/stdlib-stoppable#stoppable
+[res]: /ref/stdlib-stoppable#resumable
+
+[p]: /book/types#primitive-types
[dns]: https://docs.ton.org/participate/web3/dns
diff --git a/pages/ref/stdlib-config.mdx b/pages/ref/stdlib-config.mdx
index e2716b09..33a1b537 100644
--- a/pages/ref/stdlib-config.mdx
+++ b/pages/ref/stdlib-config.mdx
@@ -12,14 +12,12 @@ import "@stdlib/config";
### getConfigAddress
-Retrives config parameter 0 as an Address.
-
-Signature:
-
```tact
fun getConfigAddress(): Address;
```
+Retrives config parameter 0 as an [`Address{:tact}`][p].
+
Source code:
```tact
@@ -32,14 +30,12 @@ fun getConfigAddress(): Address {
### getElectorAddress
-Retrives config parameter 1 as an Address.
-
-Signature:
-
```tact
fun getElectorAddress(): Address;
```
+Retrives config parameter 1 as an [`Address{:tact}`][p].
+
Source code:
```tact
@@ -52,4 +48,6 @@ fun getElectorAddress(): Address {
## Sources
-* [config.tact](https://github.com/tact-lang/tact/blob/61541b7783098e1af669faccd7d2334c10981c72/stdlib/libs/config.tact)
\ No newline at end of file
+* [config.tact](https://github.com/tact-lang/tact/blob/61541b7783098e1af669faccd7d2334c10981c72/stdlib/libs/config.tact)
+
+[p]: /book/types#primitive-types
diff --git a/pages/ref/stdlib-content.mdx b/pages/ref/stdlib-content.mdx
index 10abd793..ff26b3da 100644
--- a/pages/ref/stdlib-content.mdx
+++ b/pages/ref/stdlib-content.mdx
@@ -1,6 +1,6 @@
# @stdlib/content
-Provides a function for encoding an off-chain link [string](/language/ref/strings) to a [Cell](/language/ref/cells).
+Provides a function for encoding an off-chain link from a [`String{:tact}`][p] to a [`Cell{:tact}`][p].
To use this library, import `@stdlib/content`:
@@ -12,14 +12,12 @@ import "@stdlib/content";
### createOffchainContent
-Encodes an off-chain `link` [string](/language/ref/strings) to a [Cell](/language/ref/cells).
-
-Signature:
-
```tact
fun createOffchainContent(link: String): Cell;
```
+Encodes an off-chain `link` from a [`String{:tact}`][p] to a [`Cell{:tact}`][p].
+
Source code:
```tact
@@ -33,3 +31,6 @@ fun createOffchainContent(link: String): Cell {
## Sources
* [content.tact](https://github.com/tact-lang/tact/blob/61541b7783098e1af669faccd7d2334c10981c72/stdlib/libs/content.tact)
+
+[p]: /book/types#primitive-types
+
diff --git a/pages/ref/stdlib-deploy.mdx b/pages/ref/stdlib-deploy.mdx
index c86758c3..eeeb7aed 100644
--- a/pages/ref/stdlib-deploy.mdx
+++ b/pages/ref/stdlib-deploy.mdx
@@ -39,7 +39,7 @@ message FactoryDeploy {
### Deployable
-Simplest trait `Deployable` that provides a handy unified mechanism for deployments by implementing a simple receiver for the [Deploy](#deploy) message.
+Simplest trait `Deployable{:tact}` that provides a handy unified mechanism for deployments by implementing a simple receiver for the [Deploy](#deploy) message.
All contracts are deployed by sending them a message. While any message can be used for this purpose, best practice is to use the special [Deploy](#deploy) message.
@@ -67,7 +67,7 @@ contract ExampleContract with Deployable {
### FactoryDeployable
-Trait `FactoryDeployable` provides a handy unified mechanism for chained deployments.
+Trait `FactoryDeployable{:tact}` provides a handy unified mechanism for chained deployments.
Source code:
diff --git a/pages/ref/stdlib-dns.mdx b/pages/ref/stdlib-dns.mdx
index 8af9a440..f4812c9c 100644
--- a/pages/ref/stdlib-dns.mdx
+++ b/pages/ref/stdlib-dns.mdx
@@ -23,53 +23,45 @@ struct DNSResolveResult {
### dnsStringToInternal
-Converts a DNS string to a [Slice?](/language/ref/cells).
-
-Signature:
-
```tact
@name(dns_string_to_internal)
native dnsStringToInternal(str: String): Slice?;
```
+Converts a DNS string to a [`Slice{:tact}`][p] or [`null{:tact}`](/book/optionals), if it's impossible.
+
Source code (FunC): [dns.fc#L1](https://github.com/tact-lang/tact/blob/61541b7783098e1af669faccd7d2334c10981c72/stdlib/libs/dns.fc#L1)
### dnsInternalNormalize
-Normalizes the internal DNS representation of the [Slice](/language/ref/cells).
-
-Signature:
-
```tact
@name(dns_internal_normalize)
native dnsInternalNormalize(src: Slice): Slice;
```
+Normalizes the internal DNS representation of the [`Slice{:tact}`][p].
+
Source code (FunC): [dns.fc#L125](https://github.com/tact-lang/tact/blob/61541b7783098e1af669faccd7d2334c10981c72/stdlib/libs/dns.fc#L125)
### dnsInternalVerify
-Verifies the internal DNS representation of the subdomain [Slice](/language/ref/cells).
-
-Signature:
-
```tact
@name(dns_internal_verify)
native dnsInternalVerify(subdomain: Slice): Bool;
```
+Verifies the internal DNS representation of the subdomain [`Slice{:tact}`][p].
+
Source code (FunC): [dns.fc#L81](https://github.com/tact-lang/tact/blob/61541b7783098e1af669faccd7d2334c10981c72/stdlib/libs/dns.fc#L81)
### dnsExtractTopDomainLength
-Calculates length of a top domain in the `subdomain` [Slice](/language/ref/cells).
-
-Signature:
-
```tact
fun dnsExtractTopDomainLength(subdomain: Slice): Int;
```
+Calculates length of a top domain in the `subdomain` [`Slice{:tact}`][p].
+
Source code:
```tact
@@ -90,14 +82,12 @@ fun dnsExtractTopDomainLength(subdomain: Slice): Int {
### dnsExtractTopDomain
-Extracts top domain from a `subdomain` [Slice](/language/ref/cells).
-
-Signature:
-
```tact
fun dnsExtractTopDomain(subdomain: Slice): Slice;
```
+Extracts top domain from a `subdomain` [`Slice{:tact}`][p].
+
Source code:
```tact
@@ -109,14 +99,12 @@ fun dnsExtractTopDomain(subdomain: Slice): Slice {
### dnsResolveNext
-Resolves an `address` Address into a [Cell](/language/ref/cells).
-
-Signature:
-
```tact
fun dnsResolveNext(address: Address): Cell;
```
+Resolves an `address` [`Address{:tact}`][p] into a [`Cell{:tact}`][p].
+
Source code:
```tact
@@ -130,14 +118,12 @@ fun dnsResolveNext(address: Address): Cell {
### dnsResolveWallet
-Resolves a wallet `address` Address into a [Cell](/language/ref/cells).
-
-Signature:
-
```tact
fun dnsResolveWallet(address: Address): Cell;
```
+Resolves a wallet `address` [`Address{:tact}`][p] into a [`Cell{:tact}`][p].
+
Source code:
```tact
@@ -155,8 +141,9 @@ fun dnsResolveWallet(address: Address): Cell {
### DNSResolver
Trait `DNSResolver` provides two helper functions for DNS resolution:
-1. getter `dnsresolve`, which corresponds to it's [FunC variant](https://docs.ton.org/develop/howto/subresolvers#dnsresolve-code).
-2. virtual `doResolveDNS`, which creates a struct [DNSResolveResult](#dnsresolveresult) out of subdomain [Slice](/language/ref/cells) bits.
+
+1. [getter function](/book/functions#getter-functions) `dnsresolve(){:tact}`, which corresponds to its [FunC variant](https://docs.ton.org/develop/howto/subresolvers#dnsresolve-code).
+2. virtual function `doResolveDNS(){:tact}`, which creates a struct [DNSResolveResult](#dnsresolveresult) out of subdomain [`Slice{:tact}`][p] bits.
Source code:
@@ -199,3 +186,5 @@ contract ExampleContract with DNSResolver {
* [dns.tact](https://github.com/tact-lang/tact/blob/61541b7783098e1af669faccd7d2334c10981c72/stdlib/libs/dns.tact)
* [dns.fc](https://github.com/tact-lang/tact/blob/61541b7783098e1af669faccd7d2334c10981c72/stdlib/libs/dns.fc)
+
+[p]: /book/types#primitive-types
diff --git a/pages/ref/stdlib-ownable.mdx b/pages/ref/stdlib-ownable.mdx
index 5ed76358..86a7fdb2 100644
--- a/pages/ref/stdlib-ownable.mdx
+++ b/pages/ref/stdlib-ownable.mdx
@@ -1,6 +1,6 @@
# @stdlib/ownable
-Provides a contract traits for ownable contracts. This is most commonly used trait that is required by most other traits.
+Provides [traits](/book/types#composite-types) for ownable contracts. This is most commonly used trait that is required by most other traits.
To use this library, import `@stdlib/ownable`:
@@ -32,9 +32,9 @@ message ChangeOwnerOk {
### Ownable
-Trait `Ownable` declares an owner (non-editable) of a contract and provides a helper function `requireOwner()` that checks that a message was sent by an owner.
+[Trait](/book/types#composite-types) `Ownable{:tact}` declares an owner (non-editable) of a [contract](/book/contracts) and provides a helper function `requireOwner(){:tact}` that checks that a message was sent by an owner.
-This trait requires a field `owner: Address` to be declared and exposes get-method `owner` to read it from the contract.
+This [trait](/book/types#composite-types) requires a field `owner: Address{:tact}` to be declared and exposes get-method `owner` to read it from the [contract](/book/contracts).
Source code:
@@ -66,9 +66,9 @@ contract ExampleContract with Ownable {
### OwnableTransferable
-`OwnableTransferable` is an extension of an [Ownable](#ownable) that allows to transfer ownership of a contract to another address. It provides a secure handle message [ChangeOwner](#changeowner) that could be called by an owner to transfer ownership.
+`OwnableTransferable{:tact}` is an extension of an [`Ownable{:tact}`](#ownable) that allows to transfer ownership of a contract to another address. It provides a secure handle [Message](/book/structs-and-messages#messages) [`ChangeOwner{:tact}`](#changeowner) that could be called by an owner to transfer ownership.
-If the owner transfer request succeeds, the contract will reply with a [ChangeOwnerOk](#changeownerok) message.
+If the owner transfer request succeeds, the contract will reply with a [`ChangeOwnerOk{:tact}`](#changeownerok) [Message](/book/structs-and-messages#messages).
Source code:
diff --git a/pages/ref/stdlib-stoppable.mdx b/pages/ref/stdlib-stoppable.mdx
index 0cb660a7..9724405e 100644
--- a/pages/ref/stdlib-stoppable.mdx
+++ b/pages/ref/stdlib-stoppable.mdx
@@ -1,6 +1,6 @@
# @stdlib/stoppable
-Provides traits that allow to stop a contract. Useful for emergency or maintenance modes. Requires an [Ownable](/language/libs/ownable#ownable) trait from [@stdlib/ownable](/language/libs/ownable). This trait just manages a single flag `stopped` in the contract and handling stopped state have to be done in the contract itself.
+Provides [traits](/book/types#composite-types) that allow to stop a [contract](/book/contracts). Useful for emergency or maintenance modes. Requires an [`Ownable{:tact}`](/ref/stdlib-ownable#ownable) trait from [`@stdlib/ownable`](/ref/stdlib-ownable). This trait just manages a single flag `stopped` in the contract and handling stopped state have to be done in the contract itself.
To use this library, import `@stdlib/stoppable` and `@stdlib/ownable`:
@@ -13,7 +13,7 @@ import "@stdlib/stoppable";
### Stoppable
-Trait `Stoppable` implements receiver for the message [string](/language/ref/strings) "Stop" that can be sent by owner, implements `stopped` get-method that returns `true` if contract is stopped and provides private (non-getter) functions `requireNotStopped` and `requireStopped`.
+[Trait](/book/types#composite-types) `Stoppable{:tact}` implements receiver for the [Message](/book/structs-and-messages#messages) [string](/book/types#primitive-types) "Stop" that can be sent by owner, implements `stopped` get-method that returns `true{:tact}` if contract is stopped (or `false{:tact}` otherwise) and provides private (non-getter) functions `requireNotStopped(){:tact}` and `requireStopped(){:tact}`.
Source code:
@@ -58,7 +58,7 @@ contract MyContract with Stoppable {
### Resumable
-`Resumable` trait extends [Stoppable](#stoppable) and allows to resume contract execution.
+`Resumable{:tact}` [trait](/book/types#composite-types) extends [`Stoppable{:tact}`](#stoppable) trait and allows to resume [contract](/book/contracts) execution.
Source code:
From ee7fe047e0802d879a37113223a87077731c4eb1 Mon Sep 17 00:00:00 2001
From: Novus Nota <68142933+novusnota@users.noreply.github.com>
Date: Tue, 9 Apr 2024 23:08:30 +0200
Subject: [PATCH 03/24] chore: Update redirects
---
scripts/redirects-generate.js | 114 ++++++++++++++++++++++------------
1 file changed, 73 insertions(+), 41 deletions(-)
diff --git a/scripts/redirects-generate.js b/scripts/redirects-generate.js
index f82d21a1..79616aef 100644
--- a/scripts/redirects-generate.js
+++ b/scripts/redirects-generate.js
@@ -36,7 +36,7 @@ const constructRedirectPage = (href) =>
* Those redirects are essentially a diff of the current structure and the previous one on this commit:
* https://github.com/tact-lang/tact-docs/tree/17176cb5e8bac84163bfa4c7b1bd94c0dc917bea/pages
*
- * @returns {{source: string, subSources: string[] | undefined, destination: string}[]}
+ * @returns {{source: string, subSources?: string[], destination: string, destPrefix?: string, destSuffix?: string}[]}
*/
const getRedirects = () => [
// Language→Guides pages are moved under Book section
@@ -52,7 +52,6 @@ const getRedirects = () => [
// Getting Started is now a part of Book→Guides sub-section
{
source: '/start',
- subSources: undefined,
destination: '/book/guides/getting-started',
},
{
@@ -64,14 +63,12 @@ const getRedirects = () => [
// Language→Guides→Grammar is now under Language section as a Specification page
{
source: '/book/grammar',
- subSources: undefined,
destination: '/language/spec',
},
// Evolution section is moved under Language section
{
source: '/evolution',
- subSources: undefined,
destination: '/language/evolution/overview',
},
{
@@ -83,7 +80,6 @@ const getRedirects = () => [
// Language→Guides→Changelog is merged with the Evolution page
{
source: '/language/guides/changelog',
- subSources: undefined,
destination: '/language/evolution/overview',
},
@@ -97,39 +93,69 @@ const getRedirects = () => [
// Small updates in naming of pages or sub-sections
{
source: '/book/message-modes',
- subSources: undefined,
destination: '/book/message-mode',
},
{
source: '/ecosystem/tools/vs',
- subSources: undefined,
destination: '/ecosystem/tools/vscode',
},
{
source: '/book/ints',
- subSources: undefined,
destination: '/book/integers',
},
{
source: '/book/numbers',
- subSources: undefined,
destination: '/book/integers',
},
{
source: '/book/defining-types',
- subSources: undefined,
destination: '/book/types#composite-types',
},
{
source: '/book/composite-types',
- subSources: undefined,
destination: '/book/types#composite-types',
},
{
source: '/book/cookbook',
- subSources: undefined,
destination: '/cookbook',
},
+
+ // Language→Libs pages are moved under Reference section
+ {
+ source: '/language',
+ destination: '/ref',
+ },
+ {
+ source: '/language/ref',
+ subSources: [
+ 'common', 'strings', 'random', 'math', 'cells', 'advanced'
+ ],
+ destination: '/ref',
+ destPrefix: 'api-', // /ref/api-common, etc.
+ },
+ {
+ source: '/language/libs/overview',
+ destination: '/ref/standard-libraries',
+ },
+ {
+ source: '/language/libs',
+ subSources: [
+ 'config', 'content', 'deploy', 'dns', 'ownable', 'stoppable',
+ ],
+ destination: '/ref',
+ destPrefix: 'stdlib-', // /ref/stdlib-config, etc.
+ },
+ {
+ source: '/language/spec',
+ destination: '/ref/spec',
+ },
+ {
+ source: '/language/evolution',
+ subSources: [
+ 'overview', 'OTP-001', 'OTP-002', 'OTP-003', 'OTP-004', 'OTP-005', 'OTP-006',
+ ],
+ destination: '/ref/evolution',
+ },
];
/**
@@ -139,48 +165,48 @@ const getRedirects = () => [
* @returns bool
*/
const isRegularFile = (filePathWithExt) => {
- if (fs.existsSync(filePathWithExt)
- && !(fs.readFileSync(filePathWithExt, 'utf8').includes('Redirecting...'))) {
- return true;
- }
+ if (fs.existsSync(filePathWithExt)
+ && !(fs.readFileSync(filePathWithExt, 'utf8').includes('Redirecting...'))) {
+ return true;
+ }
- return false;
+ return false;
};
/**
* Creates the redirect file, unless there exists a regular page/file under source path already.
* Returns true if the redirect file was created and false otherwise.
*
- * @param source {string}
- * @param destination {string}
+ * @param source {string} - path to the file
+ * @param destination {string} - link to the new page
* @returns bool
*/
const createRedirectFile = (source, destination) => {
- // full path, minus the extension
- const pathUntilExt = path.join(cwd, '/out', source);
+ // full path, minus the extension
+ const pathUntilExt = path.join(cwd, '/out', source);
- // full path with extension
- const pathWithExt = pathUntilExt + '.html';
+ // full path with extension
+ const pathWithExt = pathUntilExt + '.html';
- // if file exists, but doesn't include the line from the redirect page
- if (isRegularFile(pathWithExt)) {
- console.log(`Warning: such path (${pathWithExt}) already exists in the docs, so redirect from it was NOT created`);
- return false;
- }
+ // if file exists, but doesn't include the line from the redirect page
+ if (isRegularFile(pathWithExt)) {
+ console.log(`Warning: such path (${pathWithExt}) already exists in the docs, so redirect from it was NOT created`);
+ return false;
+ }
- // need to create additional dirs
- if (source.split('/').length > 1) {
- const nestedDir = path.dirname(pathUntilExt);
- // NOTE: debug output
- // console.log(nestedDir, redirect.source);
- fs.mkdirSync(nestedDir, { recursive: true });
- }
+ // need to create additional dirs
+ if (source.split('/').length > 1) {
+ const nestedDir = path.dirname(pathUntilExt);
+ // NOTE: debug output
+ // console.log(nestedDir, redirect.source);
+ fs.mkdirSync(nestedDir, { recursive: true });
+ }
- // create the redirect file
- fs.writeFileSync(pathWithExt, constructRedirectPage(destination));
+ // create the redirect file
+ fs.writeFileSync(pathWithExt, constructRedirectPage(destination));
- // report success
- return true;
+ // report success
+ return true;
};
/* ---------------- */
@@ -218,7 +244,10 @@ let count = 0;
for (const redirect of redirects) {
// 1. have no nested sub-sources
if (redirect.subSources === undefined) {
- if (createRedirectFile(redirect.source, redirect.destination) === true) {
+ if (createRedirectFile(
+ redirect.source,
+ (redirect.destPrefix ?? '') + redirect.destination + (redirect.destSuffix ?? ''),
+ )) {
count += 1;
}
continue;
@@ -226,7 +255,10 @@ for (const redirect of redirects) {
// 2. have some nested structure
for (const subSource of redirect.subSources) {
- if (createRedirectFile(redirect.source + '/' + subSource, redirect.destination + '/' + subSource)) {
+ if (createRedirectFile(
+ redirect.source + '/' + subSource,
+ redirect.destination + '/' + (redirect.destPrefix ?? '') + subSource + (redirect.destSuffix ?? ''),
+ )) {
count += 1;
}
}
From fcff4bc507e547952f6a26a630ca5d64e83047ee Mon Sep 17 00:00:00 2001
From: Novus Nota <68142933+novusnota@users.noreply.github.com>
Date: Mon, 29 Apr 2024 04:39:37 +0200
Subject: [PATCH 04/24] feat: Language->Reference, a big update!
WIP, but almost there.
---
pages/book/config.mdx | 2 +-
pages/book/import.mdx | 6 +-
pages/book/integers.mdx | 2 +-
pages/book/operators.mdx | 4 +-
pages/book/types.mdx | 8 +-
pages/cookbook/misc.mdx | 2 +-
pages/cookbook/random.mdx | 4 +-
pages/cookbook/single-communication.mdx | 2 +-
pages/cookbook/time.mdx | 2 +-
pages/cookbook/type-conversion.mdx | 6 +-
pages/index.mdx | 8 +-
pages/ref/_meta.js | 5 +-
pages/ref/api-advanced.mdx | 42 +--
pages/ref/api-base.mdx | 120 ++++++-
pages/ref/api-cells.mdx | 440 ++++++++++++++++++++----
pages/ref/api-common.mdx | 175 ++++++++--
pages/ref/api-comptime.mdx | 32 +-
pages/ref/api-debug.mdx | 39 +++
pages/ref/api-math.mdx | 81 ++++-
pages/ref/api-random.mdx | 23 +-
pages/ref/api-strings.mdx | 149 ++++++--
pages/ref/standard-libraries.mdx | 4 +-
pages/ref/stdlib-stoppable.mdx | 5 +-
23 files changed, 957 insertions(+), 204 deletions(-)
diff --git a/pages/book/config.mdx b/pages/book/config.mdx
index 209eefdc..4496fbc1 100644
--- a/pages/book/config.mdx
+++ b/pages/book/config.mdx
@@ -15,7 +15,7 @@ Each project is described by the following fields:
Tact support next parameters:
* `debug: true`. Enables debug output of a contract. It is useful for debugging purposes. Enabling this contract would report that it was compiled in debug mode using the `supported_interfaces` method.
-* `masterchain: true`. Enables [masterchain support](/language/guides/masterchain) in the contract.
+* `masterchain: true`. Enables [masterchain support](/book/masterchain) in the contract.
## Example
diff --git a/pages/book/import.mdx b/pages/book/import.mdx
index 7e1e3c76..abfd1eda 100644
--- a/pages/book/import.mdx
+++ b/pages/book/import.mdx
@@ -4,7 +4,7 @@ import { Callout } from 'nextra-theme-docs'
Tact allows you to import Tact and [FunC](https://docs.ton.org/develop/func/overview) code — any given `.tact` or `.fc`/`.func` file can be imported into your project using an `import{:tact}` keyword.
-Additionally, Tact compiler has a versatile set of standard libraries, which come bundled in, but not included right away, see [Language→Libs→Overview](/language/libs/overview).
+Additionally, Tact compiler has a versatile set of standard libraries, which come bundled in, but not included right away, see [Standard libraries overview](/ref/standard-libraries).
NOTE: All imported code is combined together with yours, so it's important to avoid name collisions and always double-check the sources!
@@ -36,7 +36,7 @@ import "./relative/path/to/the/target/func/file.fc";
import "../subfolder/imported/func/file.fc";
```
-But in order to use functions from such file, one has to declare them as `native` functions first. For example, when standard library [@stdlib/dns](/language/libs/dns) uses a `dns.fc` FunC file, it maps FunC functions to Tact ones like so:
+But in order to use functions from such file, one has to declare them as `native` functions first. For example, when standard library [@stdlib/dns](/ref/stdlib-dns) uses a `dns.fc` FunC file, it maps FunC functions to Tact ones like so:
```tact
// FunC code located in a file right next to the current Tact one:
@@ -49,4 +49,4 @@ native dnsStringToInternal(str: String): Slice?;
## Standard libraries
-See [Language→Libs→Overview](/language/libs/overview).
\ No newline at end of file
+See [Standard libraries overview](/ref/standard-libraries).
diff --git a/pages/book/integers.mdx b/pages/book/integers.mdx
index d4e8ef8d..6d749e2e 100644
--- a/pages/book/integers.mdx
+++ b/pages/book/integers.mdx
@@ -46,7 +46,7 @@ Use underscores (`_`) to improve readability: $\mathrm{0b111\_111\_111}$ is equa
For example, arithmetic with dollars requires two decimal places after the dot — those are used for the cents value. But how would we represent the number \$$1.25$ if we're only able to work with integers? The solution is to work with _cents_ directly. This way, \$$1.25$ becomes $125$ cents. We simply memorize that the two rightmost digits represent the numbers after the decimal point.
-Similarly, working with Toncoins requires nine decimal places instead of the two. Therefore, the amount of $1.25$ TON, which can be represented in Tact as [`ton("1.25"){:tact}`](/language/ref/common#ton), is actually the number $1250000000$. We refer to such numbers as _nano-tons_ (or _nanoToncoins_) rather than _cents_.
+Similarly, working with Toncoins requires nine decimal places instead of the two. Therefore, the amount of $1.25$ TON, which can be represented in Tact as [`ton("1.25"){:tact}`](/ref/api-comptime#ton), is actually the number $1250000000$. We refer to such numbers as _nano-tons_ (or _nanoToncoins_) rather than _cents_.
## Serialization
diff --git a/pages/book/operators.mdx b/pages/book/operators.mdx
index e8df5c5c..bae33fe5 100644
--- a/pages/book/operators.mdx
+++ b/pages/book/operators.mdx
@@ -8,7 +8,7 @@ This page lists all the operators in Tact in decreasing order of their [preceden
- Note, that there are no implicit type conversions in Tact, so operators can't be used to, say, add values of different type or compare them in terms of equality without explicitly casting to the same type. That's done with certain functions from the standard library. See [`Int.toString(){:tact}`](/language/ref/strings#inttostring) for an example of such function.
+ Note, that there are no implicit type conversions in Tact, so operators can't be used to, say, add values of different type or compare them in terms of equality without explicitly casting to the same type. That's done with certain functions from the standard library. See [`Int.toString(){:tact}`](/ref/api-strings#inttostring) for an example of such function.
@@ -135,7 +135,7 @@ two % 1; // 1
-1 % -5; // -1
```
-The simplest way to avoid confusion between the two is to prefer using positive values via [`abs(x: Int){:tact}`](/language/ref/math#abs):
+The simplest way to avoid confusion between the two is to prefer using positive values via [`abs(x: Int){:tact}`](/ref/api-math#abs):
```tact
abs(-1) % abs(-5); // 1
diff --git a/pages/book/types.mdx b/pages/book/types.mdx
index ae940ed1..5dffdf6b 100644
--- a/pages/book/types.mdx
+++ b/pages/book/types.mdx
@@ -140,7 +140,7 @@ Read more about them on the dedicated page: [Contracts](/book/contracts).
Tact doesn't support classical class inheritance, but instead introduces the concept of _traits_, which can be viewed as abstract contracts (like abstract classes in popular object-oriented languages). They have the same structure as [contracts](#contracts), but can't [initialize persistent state variables](/book/contracts#init-function), while allowing to override some of their behaviors.
-Example of a trait [`Ownable`](/language/libs/ownable#ownable) from [`@stdlib/ownable`](/language/libs/ownable):
+Example of a trait [`Ownable{:tact}`](/ref/stdlib-ownable#ownable) from [`@stdlib/ownable`](/ref/stdlib-ownable):
```tact
trait Ownable {
@@ -159,14 +159,14 @@ trait Ownable {
}
```
-And the [contract](#contracts) that uses trait [`Ownable`](/language/libs/ownable#ownable):
+And the [contract](#contracts) that uses trait [`Ownable{:tact}`](/ref/stdlib-ownable#ownable):
```tact
contract Treasure with Ownable {
- // persistent state variable, which MUST be defined in the contract
+ // Persistent state variable, which MUST be defined in the contract
owner: Address;
- // constructor function init(), where all the variables are initialized
+ // Constructor function init(), where all the variables are initialized
init(owner: Address) {
self.owner = owner;
}
diff --git a/pages/cookbook/misc.mdx b/pages/cookbook/misc.mdx
index 148c198a..a0960f58 100644
--- a/pages/cookbook/misc.mdx
+++ b/pages/cookbook/misc.mdx
@@ -26,7 +26,7 @@ nativeThrowUnless(39, number == 198);
**Useful links:**\
- [`throw(){:tact}` in Language→Reference](/language/ref/advanced#throw)\
+ [`throw(){:tact}` in API Reference](/ref/api-debug#throw)\
[Errors in Tact-By-Example](https://tact-by-example.org/03-errors)
diff --git a/pages/cookbook/random.mdx b/pages/cookbook/random.mdx
index e0ee66a7..898aa8b2 100644
--- a/pages/cookbook/random.mdx
+++ b/pages/cookbook/random.mdx
@@ -20,8 +20,8 @@ number = random(1, 12);
**Useful links:**\
- [`randomInt(){:tact}` in Language→Reference](/language/ref/random#randomInt)\
- [`random(){:tact}` in Language→Reference](/language/ref/random#random)
+ [`randomInt(){:tact}` in API Reference](/ref/api-random#randomInt)\
+ [`random(){:tact}` in API Reference](/ref/api-random#random)
diff --git a/pages/cookbook/single-communication.mdx b/pages/cookbook/single-communication.mdx
index a9bc7479..9c129390 100644
--- a/pages/cookbook/single-communication.mdx
+++ b/pages/cookbook/single-communication.mdx
@@ -91,7 +91,7 @@ send(SendParameters{
["Sending messages" in the Book](/book/send#send-message)\
["Message `mode`" in the Book](/book/message-mode)
[`StringBuilder{:tact}` in the Book](/book/types#primitive-types)\
- [`Cell{:tact}` in Language→Reference](/language/ref/cells)
+ [`Cell{:tact}` in API Reference](/ref/api-cells)
diff --git a/pages/cookbook/time.mdx b/pages/cookbook/time.mdx
index 813e6cd2..790b60ed 100644
--- a/pages/cookbook/time.mdx
+++ b/pages/cookbook/time.mdx
@@ -19,7 +19,7 @@ if (currentTime > 1672080143) {
**Useful links:**\
- [`now(){:tact}` in Language→Reference](/language/ref/common#now)\
+ [`now(){:tact}` in API Reference](/ref/api-common#now)\
["Current Time" in Tact-By-Example](https://tact-by-example.org/04-current-time)
diff --git a/pages/cookbook/type-conversion.mdx b/pages/cookbook/type-conversion.mdx
index 3299ed19..77a17049 100644
--- a/pages/cookbook/type-conversion.mdx
+++ b/pages/cookbook/type-conversion.mdx
@@ -60,9 +60,9 @@ dump(coinsString); // "0.261119911"
**Useful links:**\
- [`Int.toString(){:tact}` in Language→Reference](/language/ref/strings#inttostring)\
- [`Int.toFloatString(){:tact}` in Language→Reference](/language/ref/strings#inttofloatstring)\
- [`Int.toCoinsString(){:tact}` in Language→Reference](/language/ref/strings#inttocoinsstring)
+ [`Int.toString(){:tact}` in API Reference](/ref/api-strings#inttostring)\
+ [`Int.toFloatString(){:tact}` in API Reference](/ref/api-strings#inttofloatstring)\
+ [`Int.toCoinsString(){:tact}` in API Reference](/ref/api-strings#inttocoinsstring)
diff --git a/pages/index.mdx b/pages/index.mdx
index e61fcbf2..ffc84811 100644
--- a/pages/index.mdx
+++ b/pages/index.mdx
@@ -109,7 +109,7 @@ For custom plugins for your favorite editor and other tooling see the [Tools](/e
Alternatively, take a look at the following broader sections:
* [Book](/book) helps you learn the language step-by-step
* [Cookbook](/cookbook) gives you ready-made recipes of Tact code
-* [Language](/language) provides a complete reference of the standard library, grammar and evolution process
+* [Reference](/ref) provides a complete glossary of the standard library, grammar and evolution process
* Finally, [Ecosystem](/ecosystem) describes "what's out there" in the Tacts' and TONs' ecosystems
@@ -120,13 +120,13 @@ Alternatively, take a look at the following broader sections:
/>
Currently, `amount` must be a non-negative integer, and `mode` must be in the range 0..15, inclusive.
+
+---
+
+TODO: remove
+
+```tact
+@name(raw_reserve)
+native nativeReserve(amount: Int, mode: Int);
+
+const ReserveExact: Int = 0;
+const ReserveAllExcept: Int = 1;
+const ReserveAtMost: Int = 2;
+const ReserveAddOriginalBalance: Int = 4;
+const ReserveInvertSign: Int = 8;
+const ReserveBounceIfActionFail: Int = 16;
+```
diff --git a/pages/ref/api-base.mdx b/pages/ref/api-base.mdx
index 7963aeef..d4034f90 100644
--- a/pages/ref/api-base.mdx
+++ b/pages/ref/api-base.mdx
@@ -2,10 +2,124 @@
import { Callout } from 'nextra-theme-docs'
-Every [contract](/book/contracts) and [trait](/book/types#traits) in Tact implicitly inherits the `Base{:tact}` trait, which contains a number of the most useful [internal functions (methods)](/book/contracts#internal-functions) for any kind of contract.
+Every [contract](/book/contracts) and [trait](/book/types#traits) in Tact implicitly inherits the `Base{:tact}` trait, which contains a number of the most useful [internal functions](/book/contracts#internal-functions) for any kind of contract, and a constant `storageReserve` aimed at advanced users of Tact.
-
+## Constants
- This page is a stub. [Contributions are welcome!](https://github.com/tact-lang/tact-docs/issues)
+### self.storageReserve [#self-storagereserve]
+
+```tact
+virtual const storageReserve: Int = 0;
+```
+
+Usage example:
+
+```tact
+contract AllYourStorageBelongsToUs {
+ // This would change the behaviour of self.reserve() function,
+ // causing it to try reserving this amount of nanoToncoins before
+ // forwarding a message with SendRemainingBalance mode
+ override const storageReserve = ton("0.1");
+}
+```
+
+## Functions
+
+### self.reply [#self-reply]
+
+```tact
+virtual fun reply(body: Cell?);
+```
+
+An alias to calling the [`forward(){:tact}`](#self-forward) function with the following arguments:
+
+```tact
+self.forward(sender(), body, true, null);
+// ↑ ↑ ↑ ↑
+// | | | init: StateInit?
+// | | bounce: Bool
+// | body: Cell?
+// to: Address
+```
+
+Usage example:
+
+```tact
+// This message can bounce back to us!
+self.reply("Beware, this is my reply to you!".asComment());
+```
+
+### self.notify [#self-notify]
+
+```tact
+virtual fun notify(body: Cell?);
+```
+
+An alias to calling the [`forward(){:tact}`](#self-forward) function with the following arguments:
+
+```tact
+self.forward(sender(), body, false, null);
+// ↑ ↑ ↑ ↑
+// | | | init: StateInit?
+// | | bounce: Bool
+// | body: Cell?
+// to: Address
+```
+
+Usage example:
+
+```tact
+// This message won't bounce!
+self.notify("Beware, this is my reply to you!".asComment());
+```
+
+### self.forward [#self-forward]
+
+```tact
+virtual fun forward(to: Address, body: Cell?, bounce: Bool, init: StateInit?);
+```
+
+Sends a bounceable or non-bounceable message to the specified address `to`. Optionally, you may provide a `body` of the message and the [`init` package](/book/expressions#initof).
+
+When [`storageReserve{:tact}`](#self-storagereserve) constant is overwritten to be $> 0$, before sending a message it also tries to reserve the `storageReserve{:tact}` amount of nanoToncoins from the remaining balance before making the send in the [`SendRemainingBalance{:tact}`](https://docs.tact-lang.org/book/message-mode#base-modes) ($128$) mode.
+
+In case reservation attempt fails and in the default case without the attempt, the message is sent with the [`SendRemainingValue{:tact}`](https://docs.tact-lang.org/book/message-mode#base-modes) ($64$) mode instead.
+
+
+
+ Note, that `self.forward(){:tact}` never sends additional Toncoins on top of what's available on the balance.\
+ To be able to send more Toncoins with a single message, use the the [`send(){:tact}`](/ref/api-common#send) function.
+
+Usage example:
+
+```tact
+import "@stdlib/ownable";
+
+message PayoutOk {
+ address: Address;
+ value: Int as coins;
+}
+
+contract Payout with Ownable {
+ completed: Bool;
+ owner: Address;
+
+ init(owner: Address) {
+ self.owner = owner;
+ self.completed = false;
+ }
+
+ // ... some actions there ...
+
+ // Bounced receiver function, which is called when the specified outgoing message bounces back
+ bounced(msg: bounced) {
+ // Reset completed flag if our message bounced
+ self.completed = false;
+
+ // Send a notification that the payout failed using the remaining funds for processing this send
+ self.forward(self.owner, "Payout failed".asComment(), false, null);
+ }
+}
+```
diff --git a/pages/ref/api-cells.mdx b/pages/ref/api-cells.mdx
index 39f48255..ba2a1b72 100644
--- a/pages/ref/api-cells.mdx
+++ b/pages/ref/api-cells.mdx
@@ -1,5 +1,7 @@
# Cells, Builders and Slices
+import { Callout } from 'nextra-theme-docs'
+
Cells is a low level primitive that represents data in TON blockchain. Cell consists of a 1023 bits of data with up to 4 references to another Cells. Cells are read-only and immutable. Builders are immutable structures that can be used to construct Cells. Slices are a way to parse cells.
## beginCell
@@ -8,7 +10,13 @@ Cells is a low level primitive that represents data in TON blockchain. Cell cons
fun beginCell(): Builder
```
-Creates a new empty Builder.
+Creates a new empty [`Builder{:tact}`][p].
+
+Usage example:
+
+```tact
+let fizz: Builder = beginCell();
+```
## Builder.endCell
@@ -16,9 +24,16 @@ Creates a new empty Builder.
extends fun endCell(self: Builder): Cell;
```
-Extension function for the Builder.
+Extension function for the [`Builder{:tact}`][p].
+
+Converts a [`Builder{:tact}`][p] into an ordinary [`Cell{:tact}`][p].
-Converts a Builder into an ordinary Cell.
+Usage example:
+
+```tact
+let b: Builder = beginCell();
+let fizz: Cell = b.endCell();
+```
## Builder.storeUint
@@ -26,9 +41,16 @@ Converts a Builder into an ordinary Cell.
extends fun storeUint(self: Builder, value: Int, bits: Int): Builder;
```
-Extension function for the Builder.
+Extension function for the [`Builder{:tact}`][p].
+
+Stores an unsigned `bits`-bit `value` into the [`Builder{:tact}`][p] for $0 ≤ bits ≤ 256$. Returns modified [`Builder{:tact}`][p].
+
+Usage example:
-Stores an unsigned `bits`-bit Int `value` into the Builder for $0 ≤ bits ≤ 256$. Returns modified Builder.
+```tact
+let b: Builder = beginCell();
+let fizz: Builder = b.storeUint(42, 6);
+```
## Builder.storeInt
@@ -36,9 +58,16 @@ Stores an unsigned `bits`-bit Int `value` into the Builder for $0 ≤ bits ≤ 2
extends fun storeInt(self: Builder, value: Int, bits: Int): Builder;
```
-Extension function for the Builder.
+Extension function for the [`Builder{:tact}`][p].
+
+Stores a signed `bits`-bit `value` into the [`Builder{:tact}`][p] for $0 ≤ bits ≤ 257$. Returns modified [`Builder{:tact}`][p].
-Stores a signed `bits`-bit Int `value` into the Builder for $0 ≤ bits ≤ 257$. Returns modified Builder.
+Usage example:
+
+```tact
+let b: Builder = beginCell();
+let fizz: Builder = b.storeUint(42, 7);
+```
## Builder.storeBool
@@ -46,9 +75,17 @@ Stores a signed `bits`-bit Int `value` into the Builder for $0 ≤ bits ≤ 257$
extends fun storeBool(self: Builder, value: Bool): Builder;
```
-Extension function for the Builder.
+Extension function for the [`Builder{:tact}`][p].
-Stores a Bool `value` into the Builder. Writes `-1` if `value` is `true`, and writes `0` otherwise. Returns modified Builder.
+Stores a [`Bool{:tact}`][bool] `value` into the [`Builder{:tact}`][p]. Writes `-1` if `value` is `true{:tact}`, and writes `0` otherwise. Returns modified [`Builder{:tact}`][p].
+
+Usage example:
+
+```tact
+let b: Builder = beginCell();
+let fizz: Builder = b.storeBool(true); // writes -1
+let buzz: Builder = b.storeBool(false); // writes 0
+```
## Builder.storeSlice
@@ -56,9 +93,17 @@ Stores a Bool `value` into the Builder. Writes `-1` if `value` is `true`, and wr
extends fun storeSlice(self: Builder, cell: Slice): Builder;
```
-Extension function for the Builder.
+Extension function for the [`Builder{:tact}`][p].
+
+Stores a [`Slice{:tact}`][p] `cell` into the [`Builder{:tact}`][p]. Returns modified [`Builder{:tact}`][p].
-Stores a Slice `cell` into the Builder. Returns modified Builder.
+Usage example:
+
+```tact
+let b: Builder = beginCell();
+let s: Slice = emptyCell().asSlice();
+let fizz: Builder = b.storeSlice(s);
+```
## Builder.storeCoins
@@ -66,21 +111,35 @@ Stores a Slice `cell` into the Builder. Returns modified Builder.
extends fun storeCoins(self: Builder, value: Int): Builder;
```
-Extension function for the Builder.
+Extension function for the [`Builder{:tact}`][p].
-Stores (serializes) an integer `value` in the range $0 .. 2^{120} − 1$ into the Builder. The serialization of `value` consists of a 4-bit unsigned big-endian integer $l$, which is the smallest integer $l ≥ 0$, such that `value` $< 2^{8 * l}$, followed by an $8 * l$-bit unsigned big-endian representation of `value`. If `value` does not belong to the supported range, a range check exception is thrown. Returns modified Builder.
+Stores (serializes) an integer `value` in the range $0 .. 2^{120} − 1$ into the [`Builder{:tact}`][p]. The serialization of `value` consists of a 4-bit unsigned big-endian integer $l$, which is the smallest integer $l ≥ 0$, such that `value` $< 2^{8 * l}$, followed by an $8 * l$-bit unsigned big-endian representation of `value`. If `value` does not belong to the supported range, a range check exception is thrown. Returns modified [`Builder{:tact}`][p].
This is the most common way of storing Toncoins.
+Usage example:
+
+```tact
+let b: Builder = beginCell();
+let fizz: Builder = b.storeCoins(42);
+```
+
## Builder.storeAddress
```tact
extends fun storeAddress(self: Builder, address: Address): Builder;
```
-Extension function for the Builder.
+Extension function for the [`Builder{:tact}`][p].
+
+Stores the `address` in the [`Builder{:tact}`][p]. Returns modified [`Builder{:tact}`][p].
+
+Usage example:
-Stores Address `address` in the Builder. Returns modified Builder.
+```tact
+let b: Builder = beginCell();
+let fizz: Builder = b.storeAddress(myAddress());
+```
## Builder.storeRef
@@ -88,9 +147,16 @@ Stores Address `address` in the Builder. Returns modified Builder.
extends fun storeRef(self: Builder, cell: Cell): Builder;
```
-Extension function for the Builder.
+Extension function for the [`Builder{:tact}`][p].
-Stores a reference Cell `cell` into the Builder. Returns modified Builder.
+Stores a reference `cell` into the [`Builder{:tact}`][p]. Returns modified [`Builder{:tact}`][p].
+
+Usage example:
+
+```tact
+let b: Builder = beginCell();
+let fizz: Builder = b.storeRef(emptyCell());
+```
## Builder.refs
@@ -98,9 +164,16 @@ Stores a reference Cell `cell` into the Builder. Returns modified Builder.
extends fun refs(self: Builder): Int;
```
-Extension function for the Builder.
+Extension function for the [`Builder{:tact}`][p].
+
+Returns the number of cell references already stored in the [`Builder{:tact}`][p] as an [`Int{:tact}`][int].
-Returns the number of cell references already stored in the Builder as an Int.
+Usage example:
+
+```tact
+let b: Builder = beginCell();
+let fizz: Int = b.refs();
+```
## Builder.bits
@@ -108,9 +181,16 @@ Returns the number of cell references already stored in the Builder as an Int.
extends fun bits(self: Builder): Int;
```
-Extension function for the Builder.
+Extension function for the [`Builder{:tact}`][p].
+
+Returns the number of data bits already stored in the [`Builder{:tact}`][p] as an [`Int{:tact}`][int].
-Returns the number of data bits already stored in the Builder as an Int.
+Usage example:
+
+```tact
+let b: Builder = beginCell();
+let fizz: Int = b.bits();
+```
## Builder.asSlice
@@ -118,9 +198,16 @@ Returns the number of data bits already stored in the Builder as an Int.
extends fun asSlice(self: Builder): Slice;
```
-Extension function for the Builder.
+Extension function for the [`Builder{:tact}`][p].
+
+Converts the [`Builder{:tact}`][p] to a [`Slice{:tact}`][p]. Alias to `self.endCell().beginParse(){:tact}`.
+
+Usage example:
-Converts the Builder to a Slice. Alias to `self.endCell().beginParse()`.
+```tact
+let b: Builder = beginCell();
+let fizz: Slice = b.asSlice();
+```
## Builder.asCell
@@ -128,9 +215,16 @@ Converts the Builder to a Slice. Alias to `self.endCell().beginParse()`.
extends fun asCell(self: Builder): Cell;
```
-Extension function for the Builder.
+Extension function for the [`Builder{:tact}`][p].
+
+Converts the [`Builder{:tact}`][p] to a [`Cell{:tact}`][p]. Alias to `self.endCell(){:tact}`.
-Converts the Builder to a Cell. Alias to `self.endCell()`.
+Usage example:
+
+```tact
+let b: Builder = beginCell();
+let fizz: Cell = b.asCell();
+```
## Cell.beginParse
@@ -138,9 +232,16 @@ Converts the Builder to a Cell. Alias to `self.endCell()`.
extends fun beginParse(self: Cell): Slice;
```
-Extension function for the Cell.
+Extension function for the [`Cell{:tact}`][p].
+
+Opens the [`Cell{:tact}`][p] for parsing and returns it as a [`Slice{:tact}`][p].
+
+Usage example:
-Opens the Cell for parsing and returns it as a Slice.
+```tact
+let c: Cell = emptyCell();
+let fizz: Slice = c.beginParse();
+```
## Cell.hash
@@ -148,9 +249,16 @@ Opens the Cell for parsing and returns it as a Slice.
extends fun hash(self: Cell): Int;
```
-Extension function for the Cell.
+Extension function for the [`Cell{:tact}`][p].
+
+Calculates hash of the [`Cell{:tact}`][p] as an [`Int{:tact}`][int].
-Calculates hash of the Cell as an Int.
+Usage example:
+
+```tact
+let c: Cell = emptyCell();
+let fizz: Int = c.hash();
+```
## Cell.asSlice
@@ -158,49 +266,84 @@ Calculates hash of the Cell as an Int.
extends fun asSlice(self: Cell): Slice;
```
-Extension function for the Cell.
+Extension function for the [`Cell{:tact}`][p].
-Converts the Cell to a Slice. Alias to `self.beginParse()`.
+Converts the Cell to a [`Slice{:tact}`][p]. Alias to `self.beginParse(){:tact}`.
-## Slice.loadInt
+Usage example:
```tact
-extends mutates fun loadInt(self: Slice, l: Int): Int;
+let c: Cell = emptyCell();
+let fizz: Slice = c.asSlice();
+```
+
+## Slice.loadUint
+
+```tact
+extends mutates fun loadUint(self: Slice, l: Int): Int;
```
-Extension mutation function for the Slice.
+Extension mutation function for the [`Slice{:tact}`][p].
-Loads a signed `l`-bit Int from the Slice.
+Loads an unsigned `l`-bit [`Int{:tact}`][int] from the [`Slice{:tact}`][p].
-## Slice.preloadInt
+Usage example:
```tact
-extends mutates fun preloadInt(self: Slice, l: Int): Int;
+let s: Slice = beginCell().storeInt(42, 7).asSlice();
+let fizz: Int = s.loadUint(7);
```
-Extension mutation function for the Slice.
+## Slice.preloadUint
-Preloads a signed `len`-bit Int from the Slice.
+```tact
+extends mutates fun preloadUint(self: Slice, l: Int): Int;
+```
-## Slice.loadUint
+Extension mutation function for the [`Slice{:tact}`][p].
+
+Preloads an unsigned `l`-bit [`Int{:tact}`][int] from the [`Slice{:tact}`][p].
+
+Usage example:
```tact
-extends mutates fun loadUint(self: Slice, l: Int): Int;
+let s: Slice = beginCell().storeInt(42, 7).asSlice();
+let fizz: Int = s.preloadUint(7);
```
-Extension mutation function for the Slice.
+## Slice.loadInt
-Loads an unsigned `l`-bit Int from the Slice.
+```tact
+extends mutates fun loadInt(self: Slice, l: Int): Int;
+```
-## Slice.preloadUint
+Extension mutation function for the [`Slice{:tact}`][p].
+
+Loads a signed `l`-bit [`Int{:tact}`][int] from the [`Slice{:tact}`][p].
+
+Usage example:
```tact
-extends mutates fun preloadUint(self: Slice, l: Int): Int;
+let s: Slice = beginCell().storeInt(42, 7).asSlice();
+let fizz: Int = s.loadInt(7);
+```
+
+## Slice.preloadInt
+
+```tact
+extends mutates fun preloadInt(self: Slice, l: Int): Int;
```
-Extension mutation function for the Slice.
+Extension mutation function for the [`Slice{:tact}`][p].
+
+Preloads a signed `len`-bit [`Int{:tact}`][int] from the [`Slice{:tact}`][p].
-Preloads an unsigned `l`-bit Int from the Slice.
+Usage example:
+
+```tact
+let s: Slice = beginCell().storeInt(42, 7).asSlice();
+let fizz: Int = s.preloadInt(7);
+```
## Slice.loadBits
@@ -208,9 +351,16 @@ Preloads an unsigned `l`-bit Int from the Slice.
extends mutates fun loadBits(self: Slice, l: Int): Slice;
```
-Extension mutation function for the Slice.
+Extension mutation function for the [`Slice{:tact}`][p].
+
+Loads the first $0 ≤ l ≤ 1023$ bits from the [`Slice{:tact}`][p], and returns it as a separate [`Slice{:tact}`][p].
+
+Usage example:
-Loads the first $0 ≤ l ≤ 1023$ bits from the Slice, and returns it as a separate Slice.
+```tact
+let s: Slice = beginCell().storeInt(42, 7).asSlice();
+let fizz: Slice = s.loadBits(7);
+```
## Slice.preloadBits
@@ -218,9 +368,16 @@ Loads the first $0 ≤ l ≤ 1023$ bits from the Slice, and returns it as a sepa
extends mutates fun preloadBits(self: Slice, l: Int): Slice;
```
-Extension mutation function for the Slice.
+Extension mutation function for the [`Slice{:tact}`][p].
+
+Preloads the first $0 ≤ l ≤ 1023$ bits from the Slice, and returns it as a separate [`Slice{:tact}`][p].
-Preloads the first $0 ≤ l ≤ 1023$ bits from the Slice, and returns it as a separate Slice.
+Usage example:
+
+```tact
+let s: Slice = beginCell().storeInt(42, 7).asSlice();
+let fizz: Slice = s.preloadBits(7);
+```
## Slice.loadCoins
@@ -228,9 +385,16 @@ Preloads the first $0 ≤ l ≤ 1023$ bits from the Slice, and returns it as a s
extends mutates fun loadCoins(self: Slice): Int;
```
-Extension mutation function for the Slice.
+Extension mutation function for the [`Slice{:tact}`][p].
-Loads serialized amount of nanoToncoins (any unsigned integer up to $2^{120} - 1$) as an Int.
+Loads serialized amount of nanoToncoins (any unsigned integer up to $2^{120} - 1$) as an [`Int{:tact}`][int].
+
+Usage example:
+
+```tact
+let s: Slice = beginCell().storeCoins(42).asSlice();
+let fizz: Int = s.loadCoins();
+```
## Slice.loadAddress
@@ -238,9 +402,16 @@ Loads serialized amount of nanoToncoins (any unsigned integer up to $2^{120} - 1
extends mutates fun loadAddress(self: Slice): Address;
```
-Extension mutation function for the Slice.
+Extension mutation function for the [`Slice{:tact}`][p].
+
+Loads an [`Address{:tact}`][p] from the [`Slice{:tact}`][p].
-Loads an Address from the Slice.
+Usage example:
+
+```tact
+let s: Slice = beginCell().storeAddress(myAddress()).asSlice();
+let fizz: Address = s.loadAddress();
+```
## Slice.loadRef
@@ -248,9 +419,16 @@ Loads an Address from the Slice.
extends mutates fun loadRef(self: Slice): Cell;
```
-Extension mutation function for the Slice.
+Extension mutation function for the [`Slice{:tact}`][p].
-Loads the first reference from the Slice as a Cell.
+Loads the first reference from the [`Slice{:tact}`][p] as a [`Cell{:tact}`][p].
+
+Usage example:
+
+```tact
+let s: Slice = beginCell().storeRef(emptyCell()).asSlice();
+let fizz: Cell = s.loadRef();
+```
## Slice.refs
@@ -258,9 +436,16 @@ Loads the first reference from the Slice as a Cell.
extends fun refs(self: Slice): Int;
```
-Extension function for the Slice.
+Extension function for the [`Slice{:tact}`][p].
+
+Returns the number of references in the [`Slice{:tact}`][p] as an [`Int{:tact}`][int].
+
+Usage example:
-Returns the number of references in the Slice as an Int.
+```tact
+let s: Slice = beginCell().storeRef(emptyCell()).asSlice();
+let fizz: Int = s.refs();
+```
## Slice.bits
@@ -268,9 +453,16 @@ Returns the number of references in the Slice as an Int.
extends fun bits(self: Slice): Int;
```
-Extension function for the Slice.
+Extension function for the [`Slice{:tact}`][p].
-Returns the number of data bits in the Slice as an Int.
+Returns the number of data bits in the [`Slice{:tact}`][p] as an [`Int{:tact}`][int].
+
+Usage example:
+
+```tact
+let s: Slice = beginCell().storeRef(emptyCell()).asSlice();
+let fizz: Int = s.bits();
+```
## Slice.empty
@@ -278,9 +470,17 @@ Returns the number of data bits in the Slice as an Int.
extends fun empty(self: Slice): Bool;
```
-Extension function for the Slice.
+Extension function for the [`Slice{:tact}`][p].
+
+Checks whether the [`Slice{:tact}`][p] is empty (i.e., contains no bits of data and no cell references). Returns `true{:tact}` if it's empty, `false{:tact}` otherwise.
-Checks whether the Slice is empty (i.e., contains no bits of data and no cell references). Returns `true` if it's empty, `false` otherwise.
+Usage example:
+
+```tact
+let s: Slice = beginCell().storeRef(emptyCell()).asSlice();
+let fizz: Bool = s.empty(); // false
+let buzz: Bool = beginCell().asSlice().empty(); // true
+```
## Slice.dataEmpty
@@ -288,9 +488,19 @@ Checks whether the Slice is empty (i.e., contains no bits of data and no cell re
extends fun dataEmpty(slice: Slice): Bool;
```
-Extension function for the Slice.
+Extension function for the [`Slice{:tact}`][p].
+
+Checks whether the [`Slice{:tact}`][p] has no bits of data. Returns `true{:tact}` if it has no data, `false{:tact}` otherwise.
+
+Usage example:
+
+```tact
+let s: Slice = beginCell().storeRef(emptyCell()).asSlice();
+let fizz: Bool = s.dataEmpty(); // true
-Checks whether the Slice has no bits of data. Returns `true` if it has no data, `false` otherwise.
+let s2: Slice = beginCell().storeInt(42, 7).asSlice();
+let buzz: Bool = s2.dataEmpty(); // false
+```
## Slice.refsEmpty
@@ -298,9 +508,17 @@ Checks whether the Slice has no bits of data. Returns `true` if it has no data,
extends fun refsEmpty(slice: Slice): Bool;
```
-Extension function for the Slice.
+Extension function for the [`Slice{:tact}`][p].
+
+Checks whether the [`Slice{:tact}`][p] has no references. Returns `true{:tact}` if it has no references, `false{:tact}` otherwise.
-Checks whether the Slice has no references. Returns `true` if it has no references, `false` otherwise.
+Usage example:
+
+```tact
+let s: Slice = beginCell().storeRef(emptyCell()).asSlice();
+let fizz: Bool = s.refsEmpty(); // false
+let buzz: Bool = beginCell().asSlice().refsEmpty(); // true
+```
## Slice.hash
@@ -308,9 +526,16 @@ Checks whether the Slice has no references. Returns `true` if it has no referenc
extends fun hash(self: Slice): Int;
```
-Extension function for the Slice.
+Extension function for the [`Slice{:tact}`][p].
-Calculates hash of the Slice as an Int.
+Calculates hash of the [`Slice{:tact}`][p] as an [`Int{:tact}`][int].
+
+Usage example:
+
+```tact
+let s: Slice = beginCell().asSlice();
+let fizz: Int = s.hash();
+```
## Slice.asCell
@@ -318,9 +543,65 @@ Calculates hash of the Slice as an Int.
extends fun asCell(self: Slice): Cell;
```
-Extension function for the Slice.
+Extension function for the [`Slice{:tact}`][p].
+
+Converts the [`Slice{:tact}`][p] to a [`Cell{:tact}`][p]. Alias to `beginCell().storeSlice(self).endCell(){:tact}`.
+
+Usage example:
+
+```tact
+let s: Slice = beginCell().asSlice();
+let fizz: Cell = s.asCell();
+let buzz: Cell = beginCell().storeSlice(s).endCell();
+
+fizz == buzz; // true
+```
+
+## Address.asSlice
+
+```tact
+extends fun asSlice(self: Address): Slice;
+```
+
+Extension function for the [`Address{:tact}`][p].
+
+Converts the [`Address{:tact}`][p] to a [`Slice{:tact}`][p]. Alias to `beginCell().storeAddress(self).asSlice(){:tact}`.
+
+Usage example:
+
+```tact
+let a: Address = myAddress();
+let fizz: Slice = a.asSlice();
+let buzz: Slice = beginCell().storeAddress(a).asSlice();
+
+fizz == buzz; // true
+```
+
+## Struct.toCell
+
+```tact
+extends fun toCell(self: Struct): Cell;
+```
+
+Extension function for any [Struct][struct].
+
+Converts the [Struct][struct] to a [`Cell{:tact}`][p].
-Converts the Slice to a Cell. Alias to `beginCell().storeSlice(self).endCell()`.
+Usage example:
+
+```tact
+struct GuessCoin {
+ probably: Int as coins;
+ nothing: Int as coins;
+}
+
+fun coinCell(): Cell {
+ let s: GuessCoin = GuessCoin{ probably: 42, nothing: 27 };
+ let fizz: Cell = s.toCell();
+
+ return fizz; // "x{12A11B}"
+}
+```
## emptyCell
@@ -328,4 +609,19 @@ Converts the Slice to a Cell. Alias to `beginCell().storeSlice(self).endCell()`.
fun emptyCell(): Cell;
```
-Creates and returns an empty Cell (without data and references). Alias to `beginCell().endCell()`.
\ No newline at end of file
+Creates and returns an empty [`Cell{:tact}`][p] (without data and references). Alias to `beginCell().endCell(){:tact}`.
+
+Usage example:
+
+```tact
+let fizz: Cell = emptyCell();
+let buzz: Cell = beginCell().endCell();
+
+fizz == buzz; // true
+```
+
+[p]: /book/types#primitive-types
+[bool]: /book/types#booleans
+[int]: /book/integers
+[map]: /book/maps
+[struct]: /book/structs-and-messages#structs
diff --git a/pages/ref/api-common.mdx b/pages/ref/api-common.mdx
index d77efe59..07b286fa 100644
--- a/pages/ref/api-common.mdx
+++ b/pages/ref/api-common.mdx
@@ -4,33 +4,7 @@ import { Callout } from 'nextra-theme-docs'
List of the most commonly used built-in [global static functions](/book/functions#global-static-functions).
-## sender
-
-```tact
-fun sender(): Address;
-```
-
-Returns the [`Address{:tact}`][p] of the sender of the current message.
-
-Usage example:
-
-```tact
-receive() {
- let whoSentMeMessage: Address = sender();
-}
-```
-
-
-
- Behaviour is undefined for [getter functions](/book/contracts#getter-functions), as they cannot have a sender nor they can send messages.
-
-
-
-
-
- In order to reduce gas usage, prefer using this function over calling [`context().sender{:tact}`](#context) when you only need to know the sender of the message.
-
-
+{/* TODO: are they truly most common? Otherwise, they may be called Miscellaneous or Basic */}
## now
@@ -88,6 +62,8 @@ fun newAddress(chain: Int, hash: Int): Address;
Creates a new [`Address{:tact}`][p] based on the [`chain` id](https://ton-blockchain.github.io/docs/#/overviews/TON_blockchain_overview) and the [SHA-256](/ref/stdlib-math#sha256) encoded [`hash` value](https://docs.ton.org/learn/overviews/addresses#account-id).
+{/* TODO: a note, that newAddress can try to resolve constant values in compile-time */}
+
Usage example:
```tact
@@ -169,6 +145,34 @@ Usage example:
emit("Catch me if you can".asComment()); // asComment() converts a String to a Cell
```
+## sender
+
+```tact
+fun sender(): Address;
+```
+
+Returns the [`Address{:tact}`][p] of the sender of the current message.
+
+Usage example:
+
+```tact
+receive() {
+ let whoSentMeMessage: Address = sender();
+}
+```
+
+
+
+ Behaviour is undefined for [getter functions](/book/contracts#getter-functions), as they cannot have a sender nor they can send messages.
+
+
+
+
+
+ In order to reduce gas usage, prefer using this function over calling [`context().sender{:tact}`](#context) when you only need to know the sender of the message.
+
+
+
## context
```tact
@@ -200,3 +204,120 @@ require(ctx.value != 68 + 1, "Invalid amount of nanoToncoins, bye!");
[p]: /book/types#primitive-types
[bool]: /book/types#booleans
[int]: /book/integers
+
+{/* TODO: check and assign proper places
+
+```tact
+@name(send_raw_message)
+native nativeSendMessage(cell: Cell, mode: Int);
+
+const SendRemainingBalance: Int = 128;
+const SendRemainingValue: Int = 64;
+const SendIgnoreErrors: Int = 2;
+const SendPayGasSeparately: Int = 1;
+const SendDestroyIfZero: Int = 32;
+const SendBounceIfActionFail: Int = 16;
+
+struct SendParameters {
+ bounce: Bool = true;
+ to: Address;
+ value: Int;
+ mode: Int = 0;
+ body: Cell? = null;
+ code: Cell? = null;
+ data: Cell? = null;
+}
+
+fun send(params: SendParameters) {
+ let b: Builder = beginCell();
+ b = b.storeInt(1, 2); // internal_message + ihd_disabled
+ b = b.storeBool(params.bounce); // bounce
+ b = b.storeInt(0, 3); // bounced + from
+ b = b.storeAddress(params.to); // To
+ b = b.storeCoins(params.value); // Value
+ b = b.storeInt(0, 1 + 4 + 4 + 64 + 32); // currency_collection + IHR fees + Fwd fees + CreatedLT + CreatedAt
+
+ // Stateinit
+ if (params.code != null || params.data != null) {
+ b = b.storeBool(true); // State init
+
+ // Assemble state init cell
+ let bc: Builder = beginCell();
+ bc = bc.storeBool(false); // SplitDepth
+ bc = bc.storeBool(false); // TickTock
+ if (params.code != null) {
+ bc = bc.storeBool(true); // Code presence
+ bc = bc.storeRef(params.code!!);
+ } else {
+ bc = bc.storeBool(false); // Code presence
+ }
+ if (params.data != null) {
+ bc = bc.storeBool(true); // Data presence
+ bc = bc.storeRef(params.data!!);
+ } else {
+ bc = bc.storeBool(false); // Data presence
+ }
+ bc = bc.storeBool(false); // Library
+
+ b = b.storeBool(true); // Store as ref
+ b = b.storeRef(bc.endCell());
+ } else {
+ b = b.storeBool(false); // No state init
+ }
+
+ // Body
+ let body: Cell? = params.body;
+ if (body != null) {
+ b = b.storeBool(true);
+ b = b.storeRef(body!!);
+ } else {
+ b = b.storeBool(false); // No body
+ }
+
+ // Send
+ let c: Cell = b.endCell();
+ nativeSendMessage(c, params.mode);
+}
+
+inline fun emit(body: Cell) {
+ // ext_out_msg_info$11 src:MsgAddressInt dest:MsgAddressExt created_lt:uint64 created_at:uint32
+ // maybe: stateInit (false) bodyRef: bool (true)
+ let c: Cell = beginCell()
+ .storeUint(15211807202738752817960438464513, 104)
+ .storeRef(body)
+ .endCell();
+ nativeSendMessage(c, 0);
+}
+
+@name(accept_message)
+native acceptMessage();
+
+@name(commit)
+native commit();
+```
+
+```tact
+struct Context {
+ bounced: Bool;
+ sender: Address;
+ value: Int;
+ raw: Slice;
+}
+
+@name(__tact_context_get)
+native context(): Context;
+
+@name(__tact_context_get_sender)
+native sender(): Address;
+
+extends fun readForwardFee(self: Context): Int {
+ let sc: Slice = self.raw;
+ sc.loadAddress(); // Skip destination
+ sc.loadCoins(); // Skip value
+ sc.skipBits(1); // Skip extracurrency collection
+ sc.loadCoins(); // Skip ihr_fee
+ return (sc.loadCoins() * 3) / 2;
+}
+```
+
+*/}
diff --git a/pages/ref/api-comptime.mdx b/pages/ref/api-comptime.mdx
index 67d8ffc3..e065dab2 100644
--- a/pages/ref/api-comptime.mdx
+++ b/pages/ref/api-comptime.mdx
@@ -2,7 +2,7 @@
import { Callout } from 'nextra-theme-docs'
-This page lists all the built-in [global static functions](/book/functions#global-static-functions), which are evaluated at the time of building the Tact project (compile-time).
+This page lists all the built-in [global static functions](/book/functions#global-static-functions), which are evaluated at the time of building the Tact project. These functions are commonly referred to as "compile-time functions".
## address
@@ -10,7 +10,7 @@ This page lists all the built-in [global static functions](/book/functions#globa
fun address(s: String): Address;
```
-A compile-time function that converts a [`String{:tact}`][p] with an address into the Address type.
+A compile-time function that converts a [`String{:tact}`][p] with an address into the [`Address{:tact}`][p] type.
Usage example:
@@ -33,8 +33,12 @@ A compile-time function that embeds a base64-encoded [BoC](https://docs.ton.org/
Usage example:
```tact
-// Init package for Wallet V3R1 as a base64-encoded BoC:
-cell("te6cckEBAQEAYgAAwP8AIN0gggFMl7qXMO1E0NcLH+Ck8mCDCNcYINMf0x/TH/gjE7vyY+1E0NMf0x/T/9FRMrryoVFEuvKiBPkBVBBV+RDyo/gAkyDXSpbTB9QC+wDo0QGkyMsfyx/L/8ntVD++buA=");
+contract Example {
+ // Persistent state variables
+ storedCell: Cell =
+ // Init package for Wallet V3R1 as a base64-encoded BoC
+ cell("te6cckEBAQEAYgAAwP8AIN0gggFMl7qXMO1E0NcLH+Ck8mCDCNcYINMf0x/TH/gjE7vyY+1E0NMf0x/T/9FRMrryoVFEuvKiBPkBVBBV+RDyo/gAkyDXSpbTB9QC+wDo0QGkyMsfyx/L/8ntVD++buA="); // works at compile-time!
+}
```
@@ -55,9 +59,13 @@ A compile-time function that converts the given Toncoins `value` from a human-re
Usage example:
```tact
-ton("1"); // 10^9 nanoToncoins, which is equal to one Toncoin
-ton("0.1"); // 10^8 nanoToncoins, which is equal to 0.1 Toncoin
-ton("0.000000001"); // 1 nanoToncoin, which is equal to 10^-9 Toncoins
+contract Example {
+ // Persistent state variables
+ one: Int = ton("1"); // 10^9 nanoToncoins, which is equal to one Toncoin
+ pointOne: Int = ton("0.1"); // 10^8 nanoToncoins, which is equal to 0.1 Toncoin
+ nano: Int = ton("0.000000001"); // 1 nanoToncoin, which is equal to 10^-9 Toncoins
+ // works at compile-time!
+}
```
## pow
@@ -68,11 +76,17 @@ fun pow(a: Int, b: Int): Int;
A compile-time function that computes the exponent `b` of value `a`. Exponent `b` must be non-negative.
+{/* TODO: a note, that pow can be used for resolving constant values in runtime too! */}
+
Usage example:
```tact
-pow(2, 3); // raises 2 to the 3rd power, which is 8
-pow(5, 0); // raises 5 to the power 0, which always produces 1
+contract Example {
+ // Persistent state variables
+ p23: Int = pow(2, 3); // raises 2 to the 3rd power, which is 8
+ one: Int = pow(5, 0); // raises 5 to the power 0, which always produces 1
+ // works at compile-time!
+}
```
[p]: /book/types#primitive-types
diff --git a/pages/ref/api-debug.mdx b/pages/ref/api-debug.mdx
index 8f928596..60982b34 100644
--- a/pages/ref/api-debug.mdx
+++ b/pages/ref/api-debug.mdx
@@ -2,6 +2,9 @@
import { Callout } from 'nextra-theme-docs'
+{/* TODO: a better description */}
+{/* TODO: usage examples for all functions here */}
+
## require
```tact
@@ -27,6 +30,8 @@ Prints the argument `arg` to the contract's debug console. Evaluated only if `de
Can be applied to the following list of types and values:
+{/* TODO: dump also handles Addresses now */}
+
* [`Int{:tact}`][int]
* [`Bool{:tact}`][bool]
* [`Builder{:tact}`][p], [`Cell{:tact}`][p] or [`Slice{:tact}`][p]
@@ -69,7 +74,41 @@ dump(emit("msg".asComment())); // As emit() function doesn't return a value, dum
[int]: /book/integers
## dumpStack
+
+```tact
+fun dumpStack();
+```
+
+{/* TODO: a better description */}
+
## throw
+
+```tact
+fun throw(code: Int);
+```
+
+Throw an exception with error code equal `code`.
+
## nativeThrow
+
+```tact
+fun nativeThrow(code: Int);
+````
+
+{/* TODO: a better description */}
+
## nativeThrowWhen
+
+```tact
+fun nativeThrowWhen(code: Int, condition: Bool);
+```
+
+Throw an exception with error code equal to `code` when `condition` is equal to `true{:tact}`.
+
## nativeThrowUnless
+
+```tact
+fun nativeThrowUnless(code: Int, condition: Bool);
+```
+
+Throw an exception with error code equal to `code` when `condition` is equal to `false{:tact}`.
diff --git a/pages/ref/api-math.mdx b/pages/ref/api-math.mdx
index 3eaf644e..0c893fcc 100644
--- a/pages/ref/api-math.mdx
+++ b/pages/ref/api-math.mdx
@@ -2,17 +2,25 @@
Various math helper functions.
+{/* TODO: better descriptions */}
+{/* TODO: usage examples */}
+
## checkSignature
+
```tact
fun checkSignature(hash: Int, signature: Slice, public_key: Int): Bool;
```
+
Checks the Ed25519 `signature` of `hash` (a 256-bit unsigned integer, usually computed as the hash of some data) using `public_key` (also represented by a 256-bit unsigned integer). The signature must contain at least 512 data bits; only the first 512 bits are used. If the signature is valid, the result is true; otherwise, it is false.
+
Note that `CHKSIGNU` creates a 256-bit slice with the `hash` and calls `CHKSIGNS`. That is, if hash is computed as the hash of some data, this data is hashed twice, the second hashing occurring inside `CHKSIGNS`.
## checkDataSignature
+
```tact
fun checkDataSignature(data: Slice, signature: Slice, public_key: Int): Bool;
```
+
Checks whether `signature` is a valid Ed25519 signature of the data portion of `data` using `public_key`, similarly to `checkSignature`. If the bit length of `data` is not divisible by eight, it throws a cell underflow exception. The verification of Ed25519 signatures is a standard one, with sha256 used to reduce `data` to the 256-bit number that is actually signed. If the signature is valid, the result is true; otherwise, it is false.
## sha256
@@ -22,22 +30,93 @@ fun sha256(data: Slice): Int;
fun sha256(data: String): Int;
```
-Computes sha256 of byte-string. The result is a 256-bit unsigned integer. Slice or string must have no refs and have number of bits divisible by 8. Passing constant string computes hash in compile time that could be useful for some optimizations.
+Computes SHA-256 hash of a byte-string. The result is a 256-bit unsigned integer. Slice or string must have no refs and have number of bits divisible by 8. Passing constant string computes hash in compile time that could be useful for some optimizations.
## min
+
```tact
fun min(x: Int, y: Int): Int;
```
+
Computes the minimum of two integers `x` and `y`.
## max
+
```tact
fun max(x: Int, y: Int): Int;
```
+
Computes the maximum of two integers `x` and `y`.
## abs
+
```tact
fun abs(x: Int): Int
```
+
Computes the absolute value of the integer `x`.
+
+## log
+
+```tact
+fun log(num: Int, base: Int): Int;
+```
+
+Computes the logarithm on the `num` of `base`.
+
+## log2
+
+```tact
+fun log2(num: Int): Int;
+```
+
+Computes the logarithm on the `num` of base 2.
+
+{/* TODO: check, that all of those are covered:
+
+```tact
+// Prepare random
+
+@name(randomize)
+native nativeRandomize(x: Int);
+
+@name(randomize_lt)
+native nativeRandomizeLt();
+
+@name(__tact_prepare_random)
+native nativePrepareRandom();
+
+// Random
+
+@name(random)
+native nativeRandom(): Int;
+
+@name(rand)
+native nativeRandomInterval(max: Int): Int;
+
+inline fun randomInt(): Int {
+ nativePrepareRandom();
+ return nativeRandom();
+}
+
+inline fun random(min: Int, max: Int): Int {
+ nativePrepareRandom();
+ return min + nativeRandomInterval(max - min);
+}
+
+// Math
+
+@name(min)
+native min(x: Int, y: Int): Int;
+
+@name(max)
+native max(x: Int, y: Int): Int;
+
+@name(abs)
+native abs(x: Int): Int;
+
+@name(now)
+native now(): Int;
+```
+
+*/}
diff --git a/pages/ref/api-random.mdx b/pages/ref/api-random.mdx
index b6ed4d4d..7de3ad6e 100644
--- a/pages/ref/api-random.mdx
+++ b/pages/ref/api-random.mdx
@@ -1,16 +1,33 @@
# Random number generation
-Random number generation in TON smart contracts.
+import { Callout } from 'nextra-theme-docs'
+
+Random number generation for Tact smart contracts.
+
+{/* TODO: usage examples */}
## randomInt
+
```tact
fun randomInt(): Int;
```
-Generates a new pseudo-random unsigned 256-bit integer `x`. The algorithm is as follows: if `r` is the old value of the random seed considered a 32-byte array (by constructing the big-endian representation of an unsigned 256-bit integer), then its `sha512(r)` is computed; the first 32 bytes of this hash are stored as the new value `r'` of the random seed, and the remaining 32 bytes are returned as the next random value `x`.
+
+Generates a new pseudo-random unsigned $256$-bit [`Int{:tact}`][int] value `x`.
+
+The algorithm is as follows: if `r` is the old value of the random seed considered a $32$-byte array (by constructing the big-endian representation of an unsigned $256$-bit [`Int{:tact}`][int]), then its `sha512(r){:tact}` is computed. The first $32$ bytes of this hash are stored as the new value `r'` of the random seed, and the remaining $32$ bytes are returned as the next random value `x`.
## random
+
```tact
fun random(from: Int, to: Int): Int;
```
-Generates a new pseudo-random unsigned integer in the provided semi-closed interval: `from <= x < to` or `from >= x > to`, if both `from` and `to` are negative.
+Generates a new pseudo-random unsigned [`Int{:tact}`][int] value `x` in the provided semi-closed interval: `from` $≤$ `x` $<$ `to` or `from` $≥$ `x` $>$ `to`, if both `from` and `to` are negative.
+
+
+
+ Advanced APIs for working with random numbers are listed on a specialized page: [Advanced APIs](/ref/api-advanced).
+
+
+
+[int]: /book/integers
diff --git a/pages/ref/api-strings.mdx b/pages/ref/api-strings.mdx
index 2329c358..8eb015e8 100644
--- a/pages/ref/api-strings.mdx
+++ b/pages/ref/api-strings.mdx
@@ -1,89 +1,132 @@
-# Strings
+# Strings and StringBuilders
-Strings are a sequence of a characters. Strings are immutable, which means that once a string is created, it cannot be changed. Tact have a limitied support for strings, but you can use them to store text. Strings are also useful as comment messages body.
+import { Callout } from 'nextra-theme-docs'
+
+Strings are immutable sequences of characters, which means that once a [`String{:tact}`][p] is created, it cannot be changed. Strings are useful to store text, and so they can be converted to [`Cell{:tact}`][p] type to be used as message bodies.
+
+To be able to concatenate strings in a gas-efficient way, use a [`StringBuilder{:tact}`][p].
+
+
+
+ Note, that the current support of strings in Tact is very limited as the main focus goes towards other data types, such as [`Cell{:tact}`][p] and [`Int{:tact}`][int].
+
+ {/* TODO: improve description */}
+
+
## beginString
+
```tact
fun beginString(): StringBuilder;
```
-Creates new empty StringBuilder.
+
+Creates and returns an empty [`StringBuilder{:tact}`][p].
+
+Usage example:
+
+```tact
+let fizz: StringBuilder = beginString();
+```
## beginComment
+
```tact
fun beginComment(): StringBuilder;
```
-Creates new empty StringBuilder for comment.
+
+{/* TODO: showcase the differences of beginString, beginComment and beginTailString
+ All of them use a single Cell for encoding, so up to 127 bytes and 7 bits are the limits on storage
+ */}
+
+Creates and returns an empty [`StringBuilder{:tact}`][p] for comment.
## beginTailString
+
```tact
fun beginTailString(): StringBuilder;
```
-Creates new empty StringBuilder for a tailstring. This format is used in various standards like NFT or Jetton.
+
+Creates new empty [`StringBuilder{:tact}`][p] for a tailstring. This format is used in various standards like NFT or Jetton.
## beginStringFromBuilder
+
```tact
fun beginStringFromBuilder(builder: Builder): StringBuilder;
```
-Creates new StringBuilder from existing builder. Useful if you need to serialize string to a cell with some other data.
+
+`b` in source
+
+Creates new [`StringBuilder{:tact}`][p] from existing builder. Useful if you need to serialize string to a cell with some other data.
## StringBuilder.append
+
```tact
extends mutates fun append(self: StringBuilder, s: String);
```
-Append to StringBuilder `self` String `s` and updates it.
+
+Appends to [`StringBuilder{:tact}`][p] `self` String `s` and updates it.
+
+## StringBuilder.concat
+
+```tact
+extends fun concat(self: StringBuilder, s: String): StringBuilder;
+```
+
+Extension function.
+
+Like `StringBuilder.append(){:tact}`, but can be chained. Doesn't mutate the original StringBuilder, but returns the new one.
## StringBuilder.toString
+
```tact
extends fun toString(self: StringBuilder): String;
```
+
Assembles a string from a builder's content.
## StringBuilder.toCell
+
```tact
extends fun toCell(self: StringBuilder): Cell
```
+
Assembles a cell from a builder's content.
## StringBuilder.toSlice
+
```tact
extends fun toSlice(self: StringBuilder): Slice;
```
+
Assembles a cell from builder's content into a slice. Alias to `self.toCell().asSlice()`.
-## Int.toString
-```tact
-extends fun toString(self: Int): String;
-```
-Converts Int value to String
+## String.asSlice
-## Int.toFloatString
```tact
-extends fun toFloatString(self: Int, digits: Int): String
+extends fun asSlice(self: String): Slice;
```
-Converts Fixed Float value that represented as Int to String
-
-Where,
-* `self` significant part of float number as Int number;
-* `digits` is a exponentiation parameter of expression `10^(-digits)` that will be used for computing float number. `digits` required to be `0 <= digits < 77`.
-
-## Int.toCoinsString
-```tact
-extends fun toCoinsString(self: Int): String
-```
-Converts nanoToncoin Int value `self` to String float number of Toncoins and returns it as a result.
+**Dangerously** casts string as slice for future parsing. Use it only if you know what you are doing.
## String.asComment
+
```tact
extends fun asComment(self: String): Cell
```
+
Converts String `self` to comment message body Cell.
-## String.asSlice
+{/* TODO: is it? Alias to beginComment().concat(self).toCell(); */}
+
+## String.fromBase64
+
```tact
-extends fun asSlice(self: String): Slice;
+extends fun fromBase64(self: String): Slice;
```
-**Dangerously** casts string as slice for future parsing. Use it only if you know what you are doing.
+
+Decodes base64 string to a slice. NOTE: This method is very limited and can be used only for small strings that fit in a single cell.
+
+{/* TODO: Alias for asSlice.fromBase64 */}
## Slice.asString
@@ -93,18 +136,56 @@ extends fun asString(self: Slice): String;
**Dangerously** casts slice as string. Use it only if you know what you are doing.
-## String.fromBase64
+{/* TODO: describe what's actually going on using the Cookbook example (type conversions page). */}
+
+## Slice.fromBase64
```tact
-extends fun fromBase64(self: String): Slice;
+extends fun fromBase64(self: Slice): Slice;
```
-Decodes base64 string to a slice. NOTE: This method is very limited and can be used only for small strings that fits a single cell.
+Decodes base64 slice to a slice.
-## Slice.fromBase64
+## Int.toString
```tact
-extends fun fromBase64(self: Slice): Slice;
+extends fun toString(self: Int): String;
+```
+
+Converts Int value to String
+
+## Int.toFloatString
+
+```tact
+extends fun toFloatString(self: Int, digits: Int): String
+```
+
+Converts Fixed Float value that represented as Int to String
+
+Where,
+* `self` significant part of float number as Int number;
+* `digits` is a exponentiation parameter of expression `10^(-digits)` that will be used for computing float number. `digits` required to be `0 <= digits < 77`.
+
+## Int.toCoinsString
+
+```tact
+extends fun toCoinsString(self: Int): String
```
-Decodes base64 slice to a slice. Alias for `self.asString().fromBase64()`
+Converts nanoToncoin Int value `self` to String float number of Toncoins and returns it as a result.
+
+{/* TODO: What does it mean??? Make note that it uses toFloatString(9) */}
+
+## Address.toString
+
+```tact
+extends fun toString(self: Address): String;
+```
+
+Extension function for the [`Address{:tact}`][p].
+
+Converts an [`Address{:tact}`][p] to a String.
+
+[p]: /book/types#primitive-types
+[bool]: /book/types#booleans
+[int]: /book/integers
diff --git a/pages/ref/standard-libraries.mdx b/pages/ref/standard-libraries.mdx
index 398a13f7..acbe7af0 100644
--- a/pages/ref/standard-libraries.mdx
+++ b/pages/ref/standard-libraries.mdx
@@ -1,7 +1,7 @@
-import { Callout } from 'nextra-theme-docs'
-
# Standard libraries overview
+import { Callout } from 'nextra-theme-docs'
+
Some libraries (also referred to as standard libraries or stdlibs) come bundled with Tact compiler, but aren't automatically included to your project until explicitly made to.
To import any standard library, use the [`import{:tact}` keyword](/book/import) followed by the name of that library in a [string][p], like so:
diff --git a/pages/ref/stdlib-stoppable.mdx b/pages/ref/stdlib-stoppable.mdx
index 9724405e..3072a3fb 100644
--- a/pages/ref/stdlib-stoppable.mdx
+++ b/pages/ref/stdlib-stoppable.mdx
@@ -2,11 +2,10 @@
Provides [traits](/book/types#composite-types) that allow to stop a [contract](/book/contracts). Useful for emergency or maintenance modes. Requires an [`Ownable{:tact}`](/ref/stdlib-ownable#ownable) trait from [`@stdlib/ownable`](/ref/stdlib-ownable). This trait just manages a single flag `stopped` in the contract and handling stopped state have to be done in the contract itself.
-To use this library, import `@stdlib/stoppable` and `@stdlib/ownable`:
+To use this library, import `@stdlib/stoppable`:
```tact
-import "@stdlib/ownable";
-import "@stdlib/stoppable";
+import "@stdlib/stoppable"; // this would automatically import @stdlib/ownable too!
```
## Traits
From b4961a7a55f071fe9ff082b2a23e81628d8e5265 Mon Sep 17 00:00:00 2001
From: Novus Nota <68142933+novusnota@users.noreply.github.com>
Date: Sat, 11 May 2024 21:25:45 +0200
Subject: [PATCH 05/24] wip: intermediate commit
---
pages/ref/api-cells.mdx | 27 +++++++++
pages/ref/api-debug.mdx | 2 +-
pages/ref/api-strings.mdx | 122 +++++++++++++++++++++++++++++++-------
3 files changed, 127 insertions(+), 24 deletions(-)
diff --git a/pages/ref/api-cells.mdx b/pages/ref/api-cells.mdx
index ba2a1b72..44145009 100644
--- a/pages/ref/api-cells.mdx
+++ b/pages/ref/api-cells.mdx
@@ -603,6 +603,32 @@ fun coinCell(): Cell {
}
```
+## Message.toCell
+
+```tact
+extends fun toCell(self: Message): Cell;
+```
+
+Extension function for any [Message][message].
+
+Converts the [Message][message] to a [`Cell{:tact}`][p].
+
+Usage example:
+
+```tact
+message GuessCoin {
+ probably: Int as coins;
+ nothing: Int as coins;
+}
+
+fun coinCell(): Cell {
+ let s: GuessCoin = GuessCoin{ probably: 42, nothing: 27 };
+ let fizz: Cell = s.toCell();
+
+ return fizz; // "x{AB37107712A11B}"
+}
+```
+
## emptyCell
```tact
@@ -625,3 +651,4 @@ fizz == buzz; // true
[int]: /book/integers
[map]: /book/maps
[struct]: /book/structs-and-messages#structs
+[message]: /book/structs-and-messages#messages
diff --git a/pages/ref/api-debug.mdx b/pages/ref/api-debug.mdx
index 60982b34..05f6bb08 100644
--- a/pages/ref/api-debug.mdx
+++ b/pages/ref/api-debug.mdx
@@ -36,7 +36,7 @@ Can be applied to the following list of types and values:
* [`Bool{:tact}`][bool]
* [`Builder{:tact}`][p], [`Cell{:tact}`][p] or [`Slice{:tact}`][p]
* [`String{:tact}`][p] or [`StringBuilder{:tact}`][p]
-* [`map{:tact}`](/book/maps)
+* [`map{:tact}`](/book/maps)
* [Optionals and `null{:tact}` value](/book/optionals)
* `void`, which is implicitly returned when a function doesn't have return value defined
diff --git a/pages/ref/api-strings.mdx b/pages/ref/api-strings.mdx
index 8eb015e8..fc6425b8 100644
--- a/pages/ref/api-strings.mdx
+++ b/pages/ref/api-strings.mdx
@@ -6,13 +6,7 @@ Strings are immutable sequences of characters, which means that once a [`String{
To be able to concatenate strings in a gas-efficient way, use a [`StringBuilder{:tact}`][p].
-
-
- Note, that the current support of strings in Tact is very limited as the main focus goes towards other data types, such as [`Cell{:tact}`][p] and [`Int{:tact}`][int].
-
- {/* TODO: improve description */}
-
-
+To use [`String{:tact}`][p] literals directly, see: [String literals](/book/expressions#string-literals).
## beginString
@@ -34,11 +28,13 @@ let fizz: StringBuilder = beginString();
fun beginComment(): StringBuilder;
```
-{/* TODO: showcase the differences of beginString, beginComment and beginTailString
- All of them use a single Cell for encoding, so up to 127 bytes and 7 bits are the limits on storage
- */}
+Creates and returns an empty [`StringBuilder{:tact}`][p] for building a comment string, which prefixes the resulting [`String{:tact}`][p] with four null bytes. This format is used for passing text comments for message bodies.
+
+Usage example:
-Creates and returns an empty [`StringBuilder{:tact}`][p] for comment.
+```tact
+let fizz: StringBuilder = beginComment();
+```
## beginTailString
@@ -46,17 +42,27 @@ Creates and returns an empty [`StringBuilder{:tact}`][p] for comment.
fun beginTailString(): StringBuilder;
```
-Creates new empty [`StringBuilder{:tact}`][p] for a tailstring. This format is used in various standards like NFT or Jetton.
+Creates and returns an empty [`StringBuilder{:tact}`][p] for building a tail string, which prefixes the resulting [`String{:tact}`][p] with a single null byte. This format is used in various standards like NFT or Jetton.
+
+Usage example:
+
+```tact
+let fizz: StringBuilder = beginTailString();
+```
## beginStringFromBuilder
```tact
-fun beginStringFromBuilder(builder: Builder): StringBuilder;
+fun beginStringFromBuilder(b: StringBuilder): StringBuilder;
```
-`b` in source
+Creates and returns a new [`StringBuilder{:tact}`][p] from existing [`StringBuilder{:tact}`][p] `b`. Useful when you need to serialize an existing [`String{:tact}`][p] to a [`Cell{:tact}`][p] with some other data.
+
+Usage example:
-Creates new [`StringBuilder{:tact}`][p] from existing builder. Useful if you need to serialize string to a cell with some other data.
+```tact
+let fizz: StringBuilder = beginStringFromBuilder(beginString());
+```
## StringBuilder.append
@@ -64,7 +70,18 @@ Creates new [`StringBuilder{:tact}`][p] from existing builder. Useful if you nee
extends mutates fun append(self: StringBuilder, s: String);
```
-Appends to [`StringBuilder{:tact}`][p] `self` String `s` and updates it.
+Extension mutation function for the [`StringBuilder{:tact}`][p].
+
+Appends a [`String{:tact}`][p] `s` to the [`StringBuilder{:tact}`][p].
+
+Usage example:
+
+```tact
+let fizz: StringBuilder = beginString();
+fizz.append("oh");
+fizz.append("my");
+fizz.append("Tact!");
+```
## StringBuilder.concat
@@ -72,9 +89,18 @@ Appends to [`StringBuilder{:tact}`][p] `self` String `s` and updates it.
extends fun concat(self: StringBuilder, s: String): StringBuilder;
```
-Extension function.
+Extension function for the [`StringBuilder{:tact}`][p].
+
+Returns a new [`StringBuilder{:tact}`][p] after concatinating it with a [`String{:tact}`][p] `s`. Can be chained, unlike [`StringBuilder.append(){:tact}`](#stringbuilderappend).
+
+Usage example:
-Like `StringBuilder.append(){:tact}`, but can be chained. Doesn't mutate the original StringBuilder, but returns the new one.
+```tact
+let fizz: StringBuilder = beginString()
+ .concat("oh")
+ .concat("my")
+ .concat("Tact!");
+```
## StringBuilder.toString
@@ -82,15 +108,33 @@ Like `StringBuilder.append(){:tact}`, but can be chained. Doesn't mutate the ori
extends fun toString(self: StringBuilder): String;
```
-Assembles a string from a builder's content.
+Extension function for the [`StringBuilder{:tact}`][p].
+
+Returns a built [`String{:tact}`][p] from a [`StringBuilder{:tact}`][p].
+
+Usage example:
+
+```tact
+let fizz: StringBuilder = beginString();
+let buzz: String = fizz.toString();
+```
## StringBuilder.toCell
```tact
-extends fun toCell(self: StringBuilder): Cell
+extends fun toCell(self: StringBuilder): Cell;
```
-Assembles a cell from a builder's content.
+Extension function for the [`StringBuilder{:tact}`][p].
+
+Returns an assembled [`Cell{:tact}`][p] from a [`StringBuilder{:tact}`][p].
+
+Usage example:
+
+```tact
+let fizz: StringBuilder = beginString();
+let buzz: Cell = fizz.toCell();
+```
## StringBuilder.toSlice
@@ -98,7 +142,19 @@ Assembles a cell from a builder's content.
extends fun toSlice(self: StringBuilder): Slice;
```
-Assembles a cell from builder's content into a slice. Alias to `self.toCell().asSlice()`.
+Extension function for the [`StringBuilder{:tact}`][p].
+
+Returns an assembled [`Cell{:tact}`][p] as a [`Slice{:tact}`][p] from a [`StringBuilder{:tact}`][p]. Alias to [`self.toCell().asSlice(){:tact}`](/ref/api-cells#cellasslice).
+
+Usage example:
+
+```tact
+let s: StringBuilder = beginString();
+let fizz: Slice = s.toSlice();
+let buzz: Slice = s.toCell().asSlice();
+
+fizz == buzz; // true
+```
## String.asSlice
@@ -106,7 +162,27 @@ Assembles a cell from builder's content into a slice. Alias to `self.toCell().as
extends fun asSlice(self: String): Slice;
```
-**Dangerously** casts string as slice for future parsing. Use it only if you know what you are doing.
+Extension function for the [`String{:tact}`][p].
+
+Returns a [`Slice{:tact}`][p] from a [`String{:tact}`][p] by trying to pack all of its bytes into a continuous list of [Cells][p], each referencing the next one and opening them all for future parsing.
+
+Note, that there's no indication of how many bytes a particular character could take in the [`Slice{:tact}`][p] or how deep the list of references is going to be, so use this function only if you know what you're doing.
+
+Usage example:
+
+```tact
+let s: String = "123";
+let fizz: Slice = s.toSlice();
+let buzz: Slice = s.toCell().asSlice();
+
+fizz == buzz; // true
+```
+
+
+
+ See the enhanced version of this example in the Cookbook: [How to convert a `String` to an `Int`](/cookbook/type-conversion#how-to-convert-a-string-to-an-int).
+
+
## String.asComment
From 4afd8bf22b5f263ee28d4107f08a28d42c6698fc Mon Sep 17 00:00:00 2001
From: Novus Nota <68142933+novusnota@users.noreply.github.com>
Date: Sun, 12 May 2024 19:24:54 +0200
Subject: [PATCH 06/24] feat: finished api-strings
finally :)
---
pages/ref/api-strings.mdx | 131 ++++++++++++++++++++++++++++++--------
1 file changed, 106 insertions(+), 25 deletions(-)
diff --git a/pages/ref/api-strings.mdx b/pages/ref/api-strings.mdx
index fc6425b8..ef39d98b 100644
--- a/pages/ref/api-strings.mdx
+++ b/pages/ref/api-strings.mdx
@@ -28,7 +28,7 @@ let fizz: StringBuilder = beginString();
fun beginComment(): StringBuilder;
```
-Creates and returns an empty [`StringBuilder{:tact}`][p] for building a comment string, which prefixes the resulting [`String{:tact}`][p] with four null bytes. This format is used for passing text comments for message bodies.
+Creates and returns an empty [`StringBuilder{:tact}`][p] for building a comment string, which prefixes the resulting [`String{:tact}`][p] with four null bytes. This format is used for passing text comments as message bodies.
Usage example:
@@ -164,35 +164,48 @@ extends fun asSlice(self: String): Slice;
Extension function for the [`String{:tact}`][p].
-Returns a [`Slice{:tact}`][p] from a [`String{:tact}`][p] by trying to pack all of its bytes into a continuous list of [Cells][p], each referencing the next one and opening them all for future parsing.
+Returns a [`Slice{:tact}`][p] from a [`String{:tact}`][p] by trying to pack all of its bits into a continuous list of [Cells][p], each referencing the next one and opening them all for future parsing.
Note, that there's no indication of how many bytes a particular character could take in the [`Slice{:tact}`][p] or how deep the list of references is going to be, so use this function only if you know what you're doing.
Usage example:
```tact
-let s: String = "123";
-let fizz: Slice = s.toSlice();
-let buzz: Slice = s.toCell().asSlice();
+let s: String = "It's alive! It's alive!!!";
+let fizz: Slice = s.asSlice();
+let buzz: Slice = s.asSlice().asString().asSlice();
-fizz == buzz; // true
+fizz == buzz; // true, but be careful as it's not always the case
```
- See the enhanced version of this example in the Cookbook: [How to convert a `String` to an `Int`](/cookbook/type-conversion#how-to-convert-a-string-to-an-int).
+ See how `String.asSlice{:tact}` function can be used in practice: [How to convert a `String` to an `Int`](/cookbook/type-conversion#how-to-convert-a-string-to-an-int).
## String.asComment
```tact
-extends fun asComment(self: String): Cell
+extends fun asComment(self: String): Cell;
```
-Converts String `self` to comment message body Cell.
+Extension function for the [`String{:tact}`][p].
+
+Returns a [`Cell{:tact}`][p] from a [`String{:tact}`][p] by prefixing the latter with four null bytes. This format is used for passing text comments as message bodies.
+
+Usage example:
-{/* TODO: is it? Alias to beginComment().concat(self).toCell(); */}
+```tact
+let s: String = "When life gives you lemons, call them 'yellow oranges' and sell them for double the price.";
+let fizz: Cell = s.asComment();
+
+let b: StringBuilder = beginComment();
+b.append(s);
+let buzz: Cell = b.toCell();
+
+fizz == buzz; // true
+```
## String.fromBase64
@@ -200,9 +213,21 @@ Converts String `self` to comment message body Cell.
extends fun fromBase64(self: String): Slice;
```
-Decodes base64 string to a slice. NOTE: This method is very limited and can be used only for small strings that fit in a single cell.
+Extension function for the [`String{:tact}`][p].
+
+Returns a [`Slice{:tact}`][p] out of the decoded [Base64](https://en.wikipedia.org/wiki/Base64) [`String{:tact}`][p]. Alias to `self.asSlice().fromBase64(){:tact}`.
+
+Note, that this function is very limited and can be used only for small strings that fit in a single [`Cell{:tact}`][p] (i.e., strings that contain no more than 1023 bits of data).
-{/* TODO: Alias for asSlice.fromBase64 */}
+Usage example:
+
+```tact
+let s: String = "SGVyZSdzIEpvaG5ueSE=";
+let fizz: Slice = s.fromBase64();
+let buzz: Slice = s.asSlice().fromBase64();
+
+fizz == buzz; // true
+```
## Slice.asString
@@ -210,9 +235,21 @@ Decodes base64 string to a slice. NOTE: This method is very limited and can be u
extends fun asString(self: Slice): String;
```
-**Dangerously** casts slice as string. Use it only if you know what you are doing.
+Extension function for the [`Slice{:tact}`][p].
-{/* TODO: describe what's actually going on using the Cookbook example (type conversions page). */}
+Returns a [`String{:tact}`][p] from a [`Slice{:tact}`][p] by trying to load all of its bits without looking for its references, if any.
+
+Note, that this function doesn't look at the references at all and is truncates its output to 1023 bits, so use it only if you know what you're doing.
+
+Usage example:
+
+```tact
+let s: String = "Keep your Slices close, but your Strings closer.";
+let fizz: String = s;
+let buzz: String = s.asSlice().asString();
+
+fizz == buzz; // true, but be careful as it's not always the case
+```
## Slice.fromBase64
@@ -220,7 +257,18 @@ extends fun asString(self: Slice): String;
extends fun fromBase64(self: Slice): Slice;
```
-Decodes base64 slice to a slice.
+Extension function for the [`Slice{:tact}`][p].
+
+Returns a [`Slice{:tact}`][p] out of the decoded [Base64](https://en.wikipedia.org/wiki/Base64) [`Slice{:tact}`][p].
+
+Note, that this function doesn't load [`Cell{:tact}`][p] references, which makes it limited to only 1023 bits of data.
+
+Usage example:
+
+```tact
+let s: Slice = "SSBhbSBHcm9vdC4=".asSlice();
+let fizz: Slice = s.fromBase64();
+```
## Int.toString
@@ -228,29 +276,55 @@ Decodes base64 slice to a slice.
extends fun toString(self: Int): String;
```
-Converts Int value to String
+Extension function for the [`Int{:tact}`][int].
+
+Returns a [`String{:tact}`][p] from an [`Int{:tact}`][int] value.
+
+Usage example:
+
+```tact
+let fizz: String = (84 - 42).toString();
+```
## Int.toFloatString
```tact
-extends fun toFloatString(self: Int, digits: Int): String
+extends fun toFloatString(self: Int, digits: Int): String;
```
-Converts Fixed Float value that represented as Int to String
+Extension function for the [`Int{:tact}`][int].
+
+Returns a [`String{:tact}`][p] from an [`Int{:tact}`][int] value using a [fixed-point representation](https://en.wikipedia.org/wiki/Fixed-point_arithmetic) of a fractional number, where `self` is a significant part of the number and `digits` is a number of digits in the fractional part.
-Where,
-* `self` significant part of float number as Int number;
-* `digits` is a exponentiation parameter of expression `10^(-digits)` that will be used for computing float number. `digits` required to be `0 <= digits < 77`.
+More precisely, `digits` is an exponentiation parameter of $10^{-\mathrm{digits}}$ expression, which constitutes the represented number. Parameter `digits` is required to be in the range $0 <=$ `digits` $< 77$.
+
+Usage example:
+
+```tact
+let fizz: String = (42).toFloatString(9); // "0.000000042"
+```
## Int.toCoinsString
```tact
-extends fun toCoinsString(self: Int): String
+extends fun toCoinsString(self: Int): String;
```
-Converts nanoToncoin Int value `self` to String float number of Toncoins and returns it as a result.
+Extension function for the [`Int{:tact}`][int].
+
+Returns a [`String{:tact}`][p] from an [`Int{:tact}`][int] value using a [fixed-point representation](https://en.wikipedia.org/wiki/Fixed-point_arithmetic) of a fractional number. Alias to `self.toFloatString(9){:tact}`.
+
+This is used to represent nanoToncoin (nano-ton) [`Int{:tact}`][int] values using strings.
+
+Usage example:
+
+```tact
+let nanotons: Int = 42;
+let fizz: String = nanotons.toCoinsString();
+let buzz: String = nanotons.toFloatString(9);
-{/* TODO: What does it mean??? Make note that it uses toFloatString(9) */}
+fizz == buzz; // true, both store "0.000000042"
+```
## Address.toString
@@ -260,7 +334,14 @@ extends fun toString(self: Address): String;
Extension function for the [`Address{:tact}`][p].
-Converts an [`Address{:tact}`][p] to a String.
+Returns a [`String{:tact}`] from an [`Address{:tact}`][p].
+
+Usage example:
+
+```tact
+let community: Address = address("UQDpXLZKrkHsOuE_C1aS69C697wE568vTnqSeRfBXZfvmVOo");
+let fizz: String = community.toString();
+```
[p]: /book/types#primitive-types
[bool]: /book/types#booleans
From 2e8fa521d63dbb50fc4acf99b6788403253e9157 Mon Sep 17 00:00:00 2001
From: Novus Nota <68142933+novusnota@users.noreply.github.com>
Date: Sun, 12 May 2024 19:29:15 +0200
Subject: [PATCH 07/24] feat: finished api-random
---
pages/ref/api-random.mdx | 18 +++++++++++++-----
1 file changed, 13 insertions(+), 5 deletions(-)
diff --git a/pages/ref/api-random.mdx b/pages/ref/api-random.mdx
index 7de3ad6e..767231c0 100644
--- a/pages/ref/api-random.mdx
+++ b/pages/ref/api-random.mdx
@@ -4,17 +4,19 @@ import { Callout } from 'nextra-theme-docs'
Random number generation for Tact smart contracts.
-{/* TODO: usage examples */}
-
## randomInt
```tact
fun randomInt(): Int;
```
-Generates a new pseudo-random unsigned $256$-bit [`Int{:tact}`][int] value `x`.
+Generates and returns a new pseudo-random unsigned $256$-bit [`Int{:tact}`][int] value `x`.
+
+The algorithm works as follows: if `r` is the old value of the random seed considered a $32$-byte array (by constructing the big-endian representation of an unsigned $256$-bit [`Int{:tact}`][int]), then its `sha512(r){:tact}` is computed. The first $32$ bytes of this hash are stored as the new value `r'` of the random seed, and the remaining $32$ bytes are returned as the next random value `x`.
-The algorithm is as follows: if `r` is the old value of the random seed considered a $32$-byte array (by constructing the big-endian representation of an unsigned $256$-bit [`Int{:tact}`][int]), then its `sha512(r){:tact}` is computed. The first $32$ bytes of this hash are stored as the new value `r'` of the random seed, and the remaining $32$ bytes are returned as the next random value `x`.
+```tact
+let allYourRandomBelongsToUs: Int = randomInt();
+```
## random
@@ -22,7 +24,13 @@ The algorithm is as follows: if `r` is the old value of the random seed consider
fun random(from: Int, to: Int): Int;
```
-Generates a new pseudo-random unsigned [`Int{:tact}`][int] value `x` in the provided semi-closed interval: `from` $≤$ `x` $<$ `to` or `from` $≥$ `x` $>$ `to`, if both `from` and `to` are negative.
+Generates and returns a new pseudo-random unsigned [`Int{:tact}`][int] value `x` in the provided semi-closed interval: `from` $≤$ `x` $<$ `to` or `from` $≥$ `x` $>$ `to`, if both `from` and `to` are negative.
+
+Usage example:
+
+```tact
+let itsAlways42: Int = random(42, 43);
+```
From 6e5aa5e760c7c41b7b0586ecdd00c4cad573e672 Mon Sep 17 00:00:00 2001
From: Novus Nota <68142933+novusnota@users.noreply.github.com>
Date: Mon, 13 May 2024 22:34:09 +0200
Subject: [PATCH 08/24] feat: api-math and couple of more
Left to commit:
* api-common
* api-debug
* api-advanced
Pushing through!
---
pages/ref/api-comptime.mdx | 23 +---
pages/ref/api-math.mdx | 209 ++++++++++++++++++++++++++-------
pages/ref/api-random.mdx | 21 ++--
pages/ref/api-strings.mdx | 2 +-
pages/ref/stdlib-deploy.mdx | 4 +-
pages/ref/stdlib-ownable.mdx | 9 +-
pages/ref/stdlib-stoppable.mdx | 11 +-
7 files changed, 198 insertions(+), 81 deletions(-)
diff --git a/pages/ref/api-comptime.mdx b/pages/ref/api-comptime.mdx
index e065dab2..e0e6b21b 100644
--- a/pages/ref/api-comptime.mdx
+++ b/pages/ref/api-comptime.mdx
@@ -2,7 +2,7 @@
import { Callout } from 'nextra-theme-docs'
-This page lists all the built-in [global static functions](/book/functions#global-static-functions), which are evaluated at the time of building the Tact project. These functions are commonly referred to as "compile-time functions".
+This page lists all the built-in [global static functions](/book/functions#global-static-functions), which are evaluated at the time of building the Tact project and cannot work with non-constant, run-time data. These functions are commonly referred to as "compile-time functions".
## address
@@ -68,27 +68,6 @@ contract Example {
}
```
-## pow
-
-```tact
-fun pow(a: Int, b: Int): Int;
-```
-
-A compile-time function that computes the exponent `b` of value `a`. Exponent `b` must be non-negative.
-
-{/* TODO: a note, that pow can be used for resolving constant values in runtime too! */}
-
-Usage example:
-
-```tact
-contract Example {
- // Persistent state variables
- p23: Int = pow(2, 3); // raises 2 to the 3rd power, which is 8
- one: Int = pow(5, 0); // raises 5 to the power 0, which always produces 1
- // works at compile-time!
-}
-```
-
[p]: /book/types#primitive-types
[bool]: /book/types#booleans
[int]: /book/integers
diff --git a/pages/ref/api-math.mdx b/pages/ref/api-math.mdx
index 0c893fcc..87230490 100644
--- a/pages/ref/api-math.mdx
+++ b/pages/ref/api-math.mdx
@@ -1,9 +1,8 @@
# Math
-Various math helper functions.
+import { Callout } from 'nextra-theme-docs'
-{/* TODO: better descriptions */}
-{/* TODO: usage examples */}
+Various math helper functions.
## checkSignature
@@ -11,9 +10,40 @@ Various math helper functions.
fun checkSignature(hash: Int, signature: Slice, public_key: Int): Bool;
```
-Checks the Ed25519 `signature` of `hash` (a 256-bit unsigned integer, usually computed as the hash of some data) using `public_key` (also represented by a 256-bit unsigned integer). The signature must contain at least 512 data bits; only the first 512 bits are used. If the signature is valid, the result is true; otherwise, it is false.
+Checks the [Ed25519][ed] `signature` of the $256$-bit unsigned [`Int{:tact}`][int] `hash` using a `public_key`, represented by a $256$-bit unsigned [`Int{:tact}`][int] too. The signature must contain at least $512$ bits of data, but only the first $512$ bits are used.
+
+Returns `true{:tact}` if the signature is valid, `false{:tact}` otherwise.
+
+Usage example:
-Note that `CHKSIGNU` creates a 256-bit slice with the `hash` and calls `CHKSIGNS`. That is, if hash is computed as the hash of some data, this data is hashed twice, the second hashing occurring inside `CHKSIGNS`.
+```tact {19-24}
+message ExtMsg {
+ signature: Slice;
+ data: Cell;
+}
+
+contract Showcase {
+ // Persistent state variables
+ pub: Int as uint256; // public key as an 256-bit unsigned Int
+
+ // Constructor function init(), where all the variables are initialized
+ init(pub: Int) {
+ self.pub = pub; // storing the public key upon contract initialization
+ }
+
+ // External message receiver, which accepts message ExtMsg
+ external(msg: ExtMsg) {
+ let hash: Int = beginCell().storeRef(msg.data).endCell().hash();
+ let check: Bool = checkSignature(hash, msg.signature, self.pub);
+ // ---- ------------- --------
+ // ↑ ↑ ↑
+ // | | public_key, stored in our contract
+ // | signature, obtained from the received message
+ // hash, calculated using the data from the received message
+ // ... follow-up logic ...
+ }
+}
+```
## checkDataSignature
@@ -21,7 +51,19 @@ Note that `CHKSIGNU` creates a 256-bit slice with the `hash` and calls `CHKSIGNS
fun checkDataSignature(data: Slice, signature: Slice, public_key: Int): Bool;
```
-Checks whether `signature` is a valid Ed25519 signature of the data portion of `data` using `public_key`, similarly to `checkSignature`. If the bit length of `data` is not divisible by eight, it throws a cell underflow exception. The verification of Ed25519 signatures is a standard one, with sha256 used to reduce `data` to the 256-bit number that is actually signed. If the signature is valid, the result is true; otherwise, it is false.
+Checks the [Ed25519][ed] `signature` of the `data` using a `public_key`, similar to [`checkSignature(){:tact}`](#checksignature). If the bit length of `data` is not divisible by $8$, this functions throws an error with [exit code 9](/book/exit-codes#9): `Cell underflow`. Verification itself is being done indirectly: on a [SHA-256][sha2] hash of the `data`.
+
+Returns `true{:tact}` if the signature is valid, `false{:tact}` otherwise.
+
+Usage example:
+
+```tact
+let data: Slice = ...;
+let signature: Slice = ...;
+let publicKey: Int = ...;
+
+let check: Bool = checkSignature(data, signature, publicKey);
+```
## sha256
@@ -30,7 +72,20 @@ fun sha256(data: Slice): Int;
fun sha256(data: String): Int;
```
-Computes SHA-256 hash of a byte-string. The result is a 256-bit unsigned integer. Slice or string must have no refs and have number of bits divisible by 8. Passing constant string computes hash in compile time that could be useful for some optimizations.
+Computes and returns the [SHA-256](https://en.wikipedia.org/wiki/SHA-2#Hash_standard) hash as an $256$-bit unsigned [`Int{:tact}`][int] from a passed [`Slice{:tact}`][p] or [`String{:tact}`][p] `data`.
+
+In case `data` is a [`String{:tact}`][p] it should have a number of bits divisible by $8$, and in case it's a [`Slice{:tact}`][p] it must **also** have no references (i.e. only up to 1023 bits of data in total).
+
+This function tries to resolve constant string values in [compile-time](/ref/api-comptime) whenever possible.
+
+Usage examples:
+
+```tact
+sha256(beginCell().asSlice());
+sha256("Hello, world!"); // will be resolved in compile-time
+sha256(someVariableElsewhere); // will try to resolve at compile-time,
+ // and fallback to run-time evaluation
+```
## min
@@ -38,7 +93,18 @@ Computes SHA-256 hash of a byte-string. The result is a 256-bit unsigned integer
fun min(x: Int, y: Int): Int;
```
-Computes the minimum of two integers `x` and `y`.
+Computes and returns the [minimum](https://en.wikipedia.org/wiki/Maximum_and_minimum) of two [`Int{:tact}`][int] values `x` and `y`.
+
+Usage examples:
+
+```tact
+min(1, 2); // 1
+min(2, 2); // 2
+min(007, 3); // 3
+min(0x45, 3_0_0); // 69, nice
+// ↑ ↑
+// 69 300
+```
## max
@@ -46,7 +112,18 @@ Computes the minimum of two integers `x` and `y`.
fun max(x: Int, y: Int): Int;
```
-Computes the maximum of two integers `x` and `y`.
+Computes and returns the [maximum](https://en.wikipedia.org/wiki/Maximum_and_minimum) of two [`Int{:tact}`][int] values `x` and `y`.
+
+Usage examples:
+
+```tact
+max(1, 2); // 2
+max(2, 2); // 2
+max(007, 3); // 7
+max(0x45, 3_0_0); // 300
+// ↑ ↑
+// 69 300
+```
## abs
@@ -54,7 +131,15 @@ Computes the maximum of two integers `x` and `y`.
fun abs(x: Int): Int
```
-Computes the absolute value of the integer `x`.
+Computes and returns the [absolute value](https://en.wikipedia.org/wiki/Absolute_value) of the [`Int{:tact}`][int] value `x`.
+
+Usage examples:
+
+```tact
+abs(42); // 42
+abs(-42); // 42
+abs(-(-(-42))); // 42
+```
## log
@@ -62,7 +147,15 @@ Computes the absolute value of the integer `x`.
fun log(num: Int, base: Int): Int;
```
-Computes the logarithm on the `num` of `base`.
+Computes and returns the [logarithm](https://en.wikipedia.org/wiki/Logarithm) of a number `num` to the base `base`.
+
+Usage example:
+
+```tact
+log(1000, 10); // 3, as 10^3 is 1000
+// ↑ ↑ ↑ ↑
+// num base base num
+```
## log2
@@ -70,53 +163,83 @@ Computes the logarithm on the `num` of `base`.
fun log2(num: Int): Int;
```
-Computes the logarithm on the `num` of base 2.
+Similar to `log(){:tact}`, but sets the `base` to $2$.
-{/* TODO: check, that all of those are covered:
+Usage example:
```tact
-// Prepare random
-
-@name(randomize)
-native nativeRandomize(x: Int);
+log2(1024); // 10, as 2^10 is 1024
+// ↑ ↑ ↑
+// num base₂ num
+```
-@name(randomize_lt)
-native nativeRandomizeLt();
+## pow
-@name(__tact_prepare_random)
-native nativePrepareRandom();
+```tact
+fun pow(base: Int, exp: Int): Int;
+```
-// Random
+Computes and returns the [exponentiation](https://en.wikipedia.org/wiki/Exponentiation) involving two numbers: the `base` and the exponent (or _power_) `exp`. Exponent `exp` must be non-negative, otherwise an error with [exit code 5](/book/exit-codes#5) will be thrown: `Integer out of expected range`.
-@name(random)
-native nativeRandom(): Int;
+Note, that this function works both at run-time and at [compile-time](/ref/api-comptime).
-@name(rand)
-native nativeRandomInterval(max: Int): Int;
+Usage example:
-inline fun randomInt(): Int {
- nativePrepareRandom();
- return nativeRandom();
+```tact
+contract Example {
+ // Persistent state variables
+ p23: Int = pow(2, 3); // raises 2 to the 3rd power, which is 8
+ one: Int = pow(5, 0); // raises 5 to the power 0, which always produces 1
+ // works at compile-time!
+
+ // Internal message receiver, which accepts message ExtMsg
+ receive() {
+ pow(self.p23, self.one + 1); // 64, works at run-time too!
+ pow(0, -1); // ERROR! Exit code 5: Integer out of expected range
+ }
}
+```
-inline fun random(min: Int, max: Int): Int {
- nativePrepareRandom();
- return min + nativeRandomInterval(max - min);
-}
+
+
+ List of functions, that only work at compile-time: [API Comptime](/ref/api-comptime).
-// Math
+
-@name(min)
-native min(x: Int, y: Int): Int;
+## pow2
+
+```tact
+fun pow2(exp: Int): Int;
+```
-@name(max)
-native max(x: Int, y: Int): Int;
+Similar to `pow(){:tact}`, but sets the `base` to $2$. Works both at run-time and at [compile-time](/ref/api-comptime).
-@name(abs)
-native abs(x: Int): Int;
+Usage examples:
-@name(now)
-native now(): Int;
+```tact
+contract Example {
+ // Persistent state variables
+ p23: Int = pow2(3); // raises 2 to the 3rd power, which is 8
+ one: Int = pow2(0); // raises 2 to the power 0, which always produces 1
+ // works at compile-time!
+
+ // Internal message receiver, which accepts message ExtMsg
+ receive() {
+ pow2(self.one + 1); // 4, works at run-time too!
+ pow2(-1); // ERROR! Exit code 5: Integer out of expected range
+ }
+}
```
-*/}
+
+
+ List of functions, that only work at compile-time: [API Comptime](/ref/api-comptime).
+
+
+
+[p]: /book/types#primitive-types
+[bool]: /book/types#booleans
+[int]: /book/integers
+
+[ed]: https://en.wikipedia.org/wiki/EdDSA#Ed25519
+[sha-2]: https://en.wikipedia.org/wiki/SHA-2#Hash_standard
diff --git a/pages/ref/api-random.mdx b/pages/ref/api-random.mdx
index 767231c0..92a5dfb7 100644
--- a/pages/ref/api-random.mdx
+++ b/pages/ref/api-random.mdx
@@ -4,32 +4,35 @@ import { Callout } from 'nextra-theme-docs'
Random number generation for Tact smart contracts.
-## randomInt
+## random
```tact
-fun randomInt(): Int;
+fun random(min: Int, max: Int): Int;
```
-Generates and returns a new pseudo-random unsigned $256$-bit [`Int{:tact}`][int] value `x`.
+Generates and returns a new pseudo-random unsigned [`Int{:tact}`][int] value `x` in the provided semi-closed interval: `min` $≤$ `x` $<$ `max` or `min` $≥$ `x` $>$ `max`, if both `min` and `max` are negative. Note, that `max` value is never included in the interval.
-The algorithm works as follows: if `r` is the old value of the random seed considered a $32$-byte array (by constructing the big-endian representation of an unsigned $256$-bit [`Int{:tact}`][int]), then its `sha512(r){:tact}` is computed. The first $32$ bytes of this hash are stored as the new value `r'` of the random seed, and the remaining $32$ bytes are returned as the next random value `x`.
+Usage examples:
```tact
-let allYourRandomBelongsToUs: Int = randomInt();
+random(42, 43); // 42, always
+random(0, 42); // 0-41, but never a 42
```
-## random
+## randomInt
```tact
-fun random(from: Int, to: Int): Int;
+fun randomInt(): Int;
```
-Generates and returns a new pseudo-random unsigned [`Int{:tact}`][int] value `x` in the provided semi-closed interval: `from` $≤$ `x` $<$ `to` or `from` $≥$ `x` $>$ `to`, if both `from` and `to` are negative.
+Generates and returns a new pseudo-random unsigned $256$-bit [`Int{:tact}`][int] value `x`.
+
+The algorithm works as follows: if `r` is the old value of the random seed considered a $32$-byte array (by constructing the big-endian representation of an unsigned $256$-bit [`Int{:tact}`][int]), then its `sha512(r){:tact}` is computed. The first $32$ bytes of this hash are stored as the new value `r'` of the random seed, and the remaining $32$ bytes are returned as the next random value `x`.
Usage example:
```tact
-let itsAlways42: Int = random(42, 43);
+let allYourRandomBelongsToUs: Int = randomInt(); // ???, it's random :)
```
diff --git a/pages/ref/api-strings.mdx b/pages/ref/api-strings.mdx
index ef39d98b..e7d01108 100644
--- a/pages/ref/api-strings.mdx
+++ b/pages/ref/api-strings.mdx
@@ -296,7 +296,7 @@ Extension function for the [`Int{:tact}`][int].
Returns a [`String{:tact}`][p] from an [`Int{:tact}`][int] value using a [fixed-point representation](https://en.wikipedia.org/wiki/Fixed-point_arithmetic) of a fractional number, where `self` is a significant part of the number and `digits` is a number of digits in the fractional part.
-More precisely, `digits` is an exponentiation parameter of $10^{-\mathrm{digits}}$ expression, which constitutes the represented number. Parameter `digits` is required to be in the range $0 <=$ `digits` $< 77$.
+More precisely, `digits` is an exponentiation parameter of $10^{-\mathrm{digits}}$ expression, which gives the represented fractional number when multiplied by the actual [`Int{:tact}`][int] value. Parameter `digits` is required to be in the semi-closed interval: $0 <=$ `digits` $< 77$.
Usage example:
diff --git a/pages/ref/stdlib-deploy.mdx b/pages/ref/stdlib-deploy.mdx
index eeeb7aed..ae51175a 100644
--- a/pages/ref/stdlib-deploy.mdx
+++ b/pages/ref/stdlib-deploy.mdx
@@ -57,7 +57,7 @@ trait Deployable {
Usage example:
-```tact
+```tact /Deployable/
import "@stdlib/deploy";
contract ExampleContract with Deployable {
@@ -81,7 +81,7 @@ trait FactoryDeployable {
Usage example:
-```tact
+```tact /FactoryDeployable/
import "@stdlib/deploy";
contract ExampleContract with FactoryDeployable {
diff --git a/pages/ref/stdlib-ownable.mdx b/pages/ref/stdlib-ownable.mdx
index 86a7fdb2..3ad231b2 100644
--- a/pages/ref/stdlib-ownable.mdx
+++ b/pages/ref/stdlib-ownable.mdx
@@ -42,9 +42,11 @@ Source code:
@interface("org.ton.ownable")
trait Ownable {
owner: Address;
+
fun requireOwner() {
nativeThrowUnless(132, sender() == self.owner);
}
+
get fun owner(): Address {
return self.owner;
}
@@ -53,11 +55,12 @@ trait Ownable {
Usage example:
-```tact
+```tact /Ownable/
import "@stdlib/ownable";
contract ExampleContract with Ownable {
owner: Address;
+
init(owner: Address) {
self.owner = owner;
}
@@ -76,6 +79,7 @@ Source code:
@interface("org.ton.ownable.transferable.v2")
trait OwnableTransferable with Ownable {
owner: Address;
+
receive(msg: ChangeOwner) {
// Check if the sender is the owner
self.requireOwner();
@@ -91,11 +95,12 @@ trait OwnableTransferable with Ownable {
Usage example:
-```tact
+```tact /OwnableTransferable/
import "@stdlib/ownable";
contract ExampleContract with OwnableTransferable {
owner: Address;
+
init(owner: Address) {
self.owner = owner;
}
diff --git a/pages/ref/stdlib-stoppable.mdx b/pages/ref/stdlib-stoppable.mdx
index 3072a3fb..5270557a 100644
--- a/pages/ref/stdlib-stoppable.mdx
+++ b/pages/ref/stdlib-stoppable.mdx
@@ -21,18 +21,22 @@ Source code:
trait Stoppable with Ownable {
stopped: Bool;
owner: Address;
+
fun requireNotStopped() {
require(!self.stopped, "Contract stopped");
}
+
fun requireStopped() {
require(self.stopped, "Contract not stopped");
}
+
receive("Stop") {
self.requireOwner();
self.requireNotStopped();
self.stopped = true;
self.reply("Stopped".asComment());
}
+
get fun stopped(): Bool {
return self.stopped;
}
@@ -41,13 +45,14 @@ trait Stoppable with Ownable {
Usage example:
-```tact
+```tact /Stoppable/
import "@stdlib/ownable";
import "@stdlib/stoppable";
contract MyContract with Stoppable {
owner: Address;
stopped: Bool;
+
init(owner: Address) {
self.owner = owner;
self.stopped = false;
@@ -66,6 +71,7 @@ Source code:
trait Resumable with Stoppable {
stopped: Bool;
owner: Address;
+
receive("Resume") {
self.requireOwner();
self.requireStopped();
@@ -77,13 +83,14 @@ trait Resumable with Stoppable {
Usage example:
-```tact
+```tact /Resumable/
import "@stdlib/ownable";
import "@stdlib/stoppable";
contract MyContract with Resumable {
owner: Address;
stopped: Bool;
+
init(owner: Address) {
self.owner = owner;
self.stopped = false;
From 0362b9de90d976bb70ae372285558aba899a5539 Mon Sep 17 00:00:00 2001
From: Novus Nota <68142933+novusnota@users.noreply.github.com>
Date: Tue, 14 May 2024 02:35:09 +0200
Subject: [PATCH 09/24] feat: api-common
Left:
* api-debug
* api-advanced
---
pages/ref/api-common.mdx | 251 +++++++++++++--------------------------
1 file changed, 83 insertions(+), 168 deletions(-)
diff --git a/pages/ref/api-common.mdx b/pages/ref/api-common.mdx
index 07b286fa..12914b65 100644
--- a/pages/ref/api-common.mdx
+++ b/pages/ref/api-common.mdx
@@ -4,9 +4,9 @@ import { Callout } from 'nextra-theme-docs'
List of the most commonly used built-in [global static functions](/book/functions#global-static-functions).
-{/* TODO: are they truly most common? Otherwise, they may be called Miscellaneous or Basic */}
+## Contextual
-## now
+### now
```tact
fun now(): Int
@@ -20,7 +20,7 @@ Usage example:
let timeOffset: Int = now() + 1000; // thousand seconds from now()
```
-## myBalance
+### myBalance
```tact
fun myBalance(): Int;
@@ -36,11 +36,11 @@ let iNeedADolla: Int = myBalance();
- Note, that [`send(){:tact}` function](/book/send) does not update the contract's balance.
+ Note, that [`send(){:tact}` function](#send) does not update the contract's balance.
-## myAddress
+### myAddress
```tact
fun myAddress(): Address;
@@ -54,69 +54,83 @@ Usage example:
let meMyselfAndI: Address = myAddress();
```
-## newAddress
+### sender
```tact
-fun newAddress(chain: Int, hash: Int): Address;
+fun sender(): Address;
```
-Creates a new [`Address{:tact}`][p] based on the [`chain` id](https://ton-blockchain.github.io/docs/#/overviews/TON_blockchain_overview) and the [SHA-256](/ref/stdlib-math#sha256) encoded [`hash` value](https://docs.ton.org/learn/overviews/addresses#account-id).
-
-{/* TODO: a note, that newAddress can try to resolve constant values in compile-time */}
+Returns the [`Address{:tact}`][p] of the sender of the current message.
Usage example:
```tact
-let oldTonFoundationAddr: Address =
- newAddress(0, 0x83dfd552e63729b472fcbcc8c45ebcc6691702558b68ec7527e1ba403a0f31a8);
- // ↑ ------------------------------------------------------------------
- // | ↑
- // | sha-256 hash of contract's init package (StateInit)
- // chain id: 0 is a workchain, -1 is a masterchain
+receive() {
+ let whoSentMeMessage: Address = sender();
+}
```
- This method throws an error with [exit code 136](/book/exit-codes#136) if `chain` is invalid or with [exit code 137](/book/exit-codes#137) if `chain` points to the masterchain ($-1$) without [masterchain support](/book/masterchain) enabled.
+ Behaviour is undefined for [getter functions](/book/contracts#getter-functions), as they cannot have a sender nor they can send messages.
- **Useful links:**\
- [`chain` (Workchain ID) in TON Docs](https://docs.ton.org/learn/overviews/addresses#workchain-id)\
- [`hash` (Account ID) in TON Docs](https://docs.ton.org/learn/overviews/addresses#account-id)\
- [Contract's init package (`StateInit{:tact}`)](/book/expressions#initof)
+ In order to reduce gas usage, prefer using this function over calling [`context().sender{:tact}`](#context) when you only need to know the sender of the message.
-## contractAddress
+### context
```tact
-fun contractAddress(s: StateInit): Address;
+fun context(): Context;
```
-Computes smart contract's [`Address{:tact}`][p] in a workchain $0$ based on its [`StateInit{:tact}`](/book/expressions#initof).
+Returns `Context{:tact}` [Struct](/book/structs-and-messages#structs), that consists of:
+
+Field | Type | Description
+:------ | :-------------------- | :----------
+bounced | [`Bool{:tact}`][bool] | [Bounced](https://ton.org/docs/learn/overviews/addresses#bounceable-vs-non-bounceable-addresses) flag of the incoming message.
+sender | [`Address{:tact}`][p] | Internal address of the sender on the TON blockchain.
+value | [`Int{:tact}`][int] | Amount of nanoToncoins in a message.
+raw | [`Slice{:tact}`][p] | The reminder of the message as a [`Slice{:tact}`][p].
Usage example:
```tact
-let foundMeSome: Address = contractAddress(initOf SomeContract());
+let ctx: Context = context();
+require(ctx.value != 68 + 1, "Invalid amount of nanoToncoins, bye!");
```
-## contractAddressExt
+
+
+ Note, that if you only need to know who sent the message, use the [`sender(){:tact}`](#sender) function, as it's less gas-expensive.
+
+
+
+## Addressing
+
+### newAddress
```tact
-fun contractAddressExt(chain: Int, code: Cell, data: Cell): Address;
+fun newAddress(chain: Int, hash: Int): Address;
```
-Computes smart contract's [`Address{:tact}`][p] based on the `chain` id, contract's `code` and contract's initial state `data`. Use [`initOf{:tact}`](/book/expressions#initof) expression to obtain initial `code` and initial `data` of a given contract.
+Creates a new [`Address{:tact}`][p] based on the [`chain` id](https://ton-blockchain.github.io/docs/#/overviews/TON_blockchain_overview) and the [SHA-256](/ref/stdlib-math#sha256) encoded [`hash` value](https://docs.ton.org/learn/overviews/addresses#account-id).
+
+This function tries to resolve constant values in [compile-time](/ref/api-comptime) whenever possible.
Usage example:
```tact
-let initPkg: StateInit = initOf SomeContract();
-let hereBeDragons: Address = contractAddressExt(0, initPkg.code, initPkg.data);
+let oldTonFoundationAddr: Address =
+ newAddress(0, 0x83dfd552e63729b472fcbcc8c45ebcc6691702558b68ec7527e1ba403a0f31a8);
+ // ↑ ------------------------------------------------------------------
+ // | ↑
+ // | sha-256 hash of contract's init package (StateInit)
+ // chain id: 0 is a workchain, -1 is a masterchain
```
@@ -127,197 +141,98 @@ let hereBeDragons: Address = contractAddressExt(0, initPkg.code, initPkg.data);
- For this function to work, the compiler option `debug` has to be set to `true{:tact}` for the current project in the [configuration file](/book/config). Read more about debugging on the dedicated page: [Debugging](/book/debug).
+ **Useful links:**\
+ [`chain` (Workchain ID) in TON Docs](https://docs.ton.org/learn/overviews/addresses#workchain-id)\
+ [`hash` (Account ID) in TON Docs](https://docs.ton.org/learn/overviews/addresses#account-id)\
+ [Contract's init package (`StateInit{:tact}`)](/book/expressions#initof)
-## emit
+### contractAddress
```tact
-fun emit(body: Cell);
+fun contractAddress(s: StateInit): Address;
```
-Sends a message `body` to the outer world with the purpose of logging and analyzing it later off-chain. The message does not have a recipient and is gas-efficient compared to alternatives.
+Computes smart contract's [`Address{:tact}`][p] in a workchain $0$ based on its [`StateInit{:tact}`](/book/expressions#initof).
Usage example:
```tact
-emit("Catch me if you can".asComment()); // asComment() converts a String to a Cell
+let foundMeSome: Address = contractAddress(initOf SomeContract());
```
-## sender
+### contractAddressExt
```tact
-fun sender(): Address;
+fun contractAddressExt(chain: Int, code: Cell, data: Cell): Address;
```
-Returns the [`Address{:tact}`][p] of the sender of the current message.
+Computes smart contract's [`Address{:tact}`][p] based on the `chain` id, contract's `code` and contract's initial state `data`. Use [`initOf{:tact}`](/book/expressions#initof) expression to obtain initial `code` and initial `data` of a given contract.
Usage example:
```tact
-receive() {
- let whoSentMeMessage: Address = sender();
-}
+let initPkg: StateInit = initOf SomeContract();
+let hereBeDragons: Address = contractAddressExt(0, initPkg.code, initPkg.data);
```
- Behaviour is undefined for [getter functions](/book/contracts#getter-functions), as they cannot have a sender nor they can send messages.
+ This method throws an error with [exit code 136](/book/exit-codes#136) if `chain` is invalid or with [exit code 137](/book/exit-codes#137) if `chain` points to the masterchain ($-1$) without [masterchain support](/book/masterchain) enabled.
- In order to reduce gas usage, prefer using this function over calling [`context().sender{:tact}`](#context) when you only need to know the sender of the message.
+ For this function to work, the compiler option `debug` has to be set to `true{:tact}` for the current project in the [configuration file](/book/config).\
+ Read more about debugging on the dedicated page: [Debugging](/book/debug).
-## context
+## Communication
+
+### send
```tact
-fun context(): Context;
+fun send(params: SendParameters);
```
-Returns `Context{:tact}` [Struct](/book/structs-and-messages#structs), that consists of:
-
-Field | Type | Description
-:------ | :-------------------- | :----------
-bounced | [`Bool{:tact}`][bool] | [Bounced](https://ton.org/docs/learn/overviews/addresses#bounceable-vs-non-bounceable-addresses) flag of the incoming message.
-sender | [`Address{:tact}`][p] | Internal address of the sender on the TON blockchain.
-value | [`Int{:tact}`][int] | Amount of nanoToncoins in a message.
-raw | [`Slice{:tact}`][p] | The reminder of the message as a [`Slice{:tact}`][p].
+Sends a message using a [`SendParameters{:tact}`](/book/send) [Struct](/book/structs-and-messages#structs).
Usage example:
```tact
-let ctx: Context = context();
-require(ctx.value != 68 + 1, "Invalid amount of nanoToncoins, bye!");
+send(SendParameters{
+ to: sender(), // back to the sender
+ value: 1, // with 1 toncoin
+ // and no message body
+});
```
- Note, that if you only need to know who sent the message, use the [`sender(){:tact}`](#sender) function, as it's less gas-expensive.
+ **Useful links:**\
+ [Sending messages in the Book](/book/send)\
+ [Message `mode` in the Book](/book/message-mode)\
+ [Single-contract communication in the Cookbook](/cookbook/single-communication)
-[p]: /book/types#primitive-types
-[bool]: /book/types#booleans
-[int]: /book/integers
-
-{/* TODO: check and assign proper places
+### emit
```tact
-@name(send_raw_message)
-native nativeSendMessage(cell: Cell, mode: Int);
-
-const SendRemainingBalance: Int = 128;
-const SendRemainingValue: Int = 64;
-const SendIgnoreErrors: Int = 2;
-const SendPayGasSeparately: Int = 1;
-const SendDestroyIfZero: Int = 32;
-const SendBounceIfActionFail: Int = 16;
-
-struct SendParameters {
- bounce: Bool = true;
- to: Address;
- value: Int;
- mode: Int = 0;
- body: Cell? = null;
- code: Cell? = null;
- data: Cell? = null;
-}
-
-fun send(params: SendParameters) {
- let b: Builder = beginCell();
- b = b.storeInt(1, 2); // internal_message + ihd_disabled
- b = b.storeBool(params.bounce); // bounce
- b = b.storeInt(0, 3); // bounced + from
- b = b.storeAddress(params.to); // To
- b = b.storeCoins(params.value); // Value
- b = b.storeInt(0, 1 + 4 + 4 + 64 + 32); // currency_collection + IHR fees + Fwd fees + CreatedLT + CreatedAt
-
- // Stateinit
- if (params.code != null || params.data != null) {
- b = b.storeBool(true); // State init
-
- // Assemble state init cell
- let bc: Builder = beginCell();
- bc = bc.storeBool(false); // SplitDepth
- bc = bc.storeBool(false); // TickTock
- if (params.code != null) {
- bc = bc.storeBool(true); // Code presence
- bc = bc.storeRef(params.code!!);
- } else {
- bc = bc.storeBool(false); // Code presence
- }
- if (params.data != null) {
- bc = bc.storeBool(true); // Data presence
- bc = bc.storeRef(params.data!!);
- } else {
- bc = bc.storeBool(false); // Data presence
- }
- bc = bc.storeBool(false); // Library
-
- b = b.storeBool(true); // Store as ref
- b = b.storeRef(bc.endCell());
- } else {
- b = b.storeBool(false); // No state init
- }
-
- // Body
- let body: Cell? = params.body;
- if (body != null) {
- b = b.storeBool(true);
- b = b.storeRef(body!!);
- } else {
- b = b.storeBool(false); // No body
- }
-
- // Send
- let c: Cell = b.endCell();
- nativeSendMessage(c, params.mode);
-}
-
-inline fun emit(body: Cell) {
- // ext_out_msg_info$11 src:MsgAddressInt dest:MsgAddressExt created_lt:uint64 created_at:uint32
- // maybe: stateInit (false) bodyRef: bool (true)
- let c: Cell = beginCell()
- .storeUint(15211807202738752817960438464513, 104)
- .storeRef(body)
- .endCell();
- nativeSendMessage(c, 0);
-}
-
-@name(accept_message)
-native acceptMessage();
-
-@name(commit)
-native commit();
+fun emit(body: Cell);
```
-```tact
-struct Context {
- bounced: Bool;
- sender: Address;
- value: Int;
- raw: Slice;
-}
-
-@name(__tact_context_get)
-native context(): Context;
+Sends a message `body` to the outer world with the purpose of logging and analyzing it later off-chain. The message does not have a recipient and is gas-efficient compared to using any other message sending function in Tact.
-@name(__tact_context_get_sender)
-native sender(): Address;
+Usage example:
-extends fun readForwardFee(self: Context): Int {
- let sc: Slice = self.raw;
- sc.loadAddress(); // Skip destination
- sc.loadCoins(); // Skip value
- sc.skipBits(1); // Skip extracurrency collection
- sc.loadCoins(); // Skip ihr_fee
- return (sc.loadCoins() * 3) / 2;
-}
+```tact
+emit("Catch me if you can, Mr. Holmes".asComment()); // asComment() converts a String to a Cell
```
-*/}
+[p]: /book/types#primitive-types
+[bool]: /book/types#booleans
+[int]: /book/integers
From b7fa4d10f6c89efc37e0b152de3807a28810da45 Mon Sep 17 00:00:00 2001
From: Novus Nota <68142933+novusnota@users.noreply.github.com>
Date: Tue, 14 May 2024 03:01:06 +0200
Subject: [PATCH 10/24] feat: api-debug
---
pages/ref/api-debug.mdx | 104 ++++++++++++++++++++++++++++++++++------
1 file changed, 90 insertions(+), 14 deletions(-)
diff --git a/pages/ref/api-debug.mdx b/pages/ref/api-debug.mdx
index 05f6bb08..909eac3a 100644
--- a/pages/ref/api-debug.mdx
+++ b/pages/ref/api-debug.mdx
@@ -2,9 +2,6 @@
import { Callout } from 'nextra-theme-docs'
-{/* TODO: a better description */}
-{/* TODO: usage examples for all functions here */}
-
## require
```tact
@@ -30,10 +27,9 @@ Prints the argument `arg` to the contract's debug console. Evaluated only if `de
Can be applied to the following list of types and values:
-{/* TODO: dump also handles Addresses now */}
-
* [`Int{:tact}`][int]
* [`Bool{:tact}`][bool]
+* [`Address{:tact}`][p]
* [`Builder{:tact}`][p], [`Cell{:tact}`][p] or [`Slice{:tact}`][p]
* [`String{:tact}`][p] or [`StringBuilder{:tact}`][p]
* [`map{:tact}`](/book/maps)
@@ -50,6 +46,9 @@ dump(42);
dump(true);
dump(false);
+// Address
+dump(myAddress());
+
// Builder, Cell or Slice
dump(beginCell()); // Builder
dump(emptyCell()); // Cell
@@ -69,17 +68,26 @@ dump(null);
dump(emit("msg".asComment())); // As emit() function doesn't return a value, dump() would print #DEBUG#: void.
```
-[p]: /book/types#primitive-types
-[bool]: /book/types#booleans
-[int]: /book/integers
-
## dumpStack
```tact
fun dumpStack();
```
-{/* TODO: a better description */}
+Prints all the values of [persistent state variables](/book/contracts#variables) to the contract's debug console. Evaluated only if `debug` option is set in the [configuration file](/book/config), otherwise does nothing.
+
+Usage example:
+
+```tact
+contract DumpsterFire {
+ var1: Int = 0;
+ var2: Int = 5;
+
+ receive() {
+ dumpStack(); // would print 0 5
+ }
+}
+```
## throw
@@ -87,7 +95,7 @@ fun dumpStack();
fun throw(code: Int);
```
-Throw an exception with error code equal `code`.
+An alias to [`nativeThrow(){:tact}`](#nativethrow).
## nativeThrow
@@ -95,7 +103,29 @@ Throw an exception with error code equal `code`.
fun nativeThrow(code: Int);
````
-{/* TODO: a better description */}
+Throws an exception with an error code equal to `code`. Execution of the current context stops (the statements after `nativeThrow` won't be executed) and control will be passed to the first [`try...catch{:tact}` block](/book/statements#try-catch) in the call stack. If no `try{:tact}` or `try...catch{:tact}` block exists among caller functions, [TVM](https://docs.ton.org/learn/tvm-instructions/tvm-overview) will terminate the transaction.
+
+Usage examples:
+
+```tact {2,7}
+fun thisWillTerminate() {
+ nativeThrow(42); // throwing with exit code 42
+}
+
+fun butThisDoesnt() {
+ try {
+ nativeThrow(42); // throwing with exit code 42
+ }
+
+ // ... follow-up logic ...
+}
+```
+
+
+
+ Prefer to use `require(){:tact}` over this function as the former comes with more [compile-time](/ref/api-comptime) optimizations and is generally more user-friendly.
+
+
## nativeThrowWhen
@@ -103,7 +133,28 @@ fun nativeThrow(code: Int);
fun nativeThrowWhen(code: Int, condition: Bool);
```
-Throw an exception with error code equal to `code` when `condition` is equal to `true{:tact}`.
+Similar to [`nativeThrow(){:tact}`](#nativethrow), but with throw an exception conditionally, when `condition` is equal to `true{:tact}`. Won't throw otherwise.
+
+Usage examples:
+
+```tact {2,7}
+fun thisWillTerminate() {
+ nativeThrowWhen(42, true); // throwing with exit code 42
+}
+
+fun butThisDoesnt() {
+ try {
+ nativeThrow(42, true); // throwing with exit code 42
+ }
+ // ... follow-up logic ...
+}
+```
+
+
+
+ Prefer to use `require(){:tact}` over this function as the former comes with more [compile-time](/ref/api-comptime) optimizations and is generally more user-friendly.
+
+
## nativeThrowUnless
@@ -111,4 +162,29 @@ Throw an exception with error code equal to `code` when `condition` is equal to
fun nativeThrowUnless(code: Int, condition: Bool);
```
-Throw an exception with error code equal to `code` when `condition` is equal to `false{:tact}`.
+Similar to [`nativeThrow(){:tact}`](#nativethrow), but with throw an exception conditionally, when `condition` is equal to `false{:tact}`. Won't throw otherwise.
+
+Usage examples:
+
+```tact {2,7}
+fun thisWillTerminate() {
+ nativeThrowUnless(42, false); // throwing with exit code 42
+}
+
+fun butThisDoesnt() {
+ try {
+ nativeThrowUnless(42, false); // throwing with exit code 42
+ }
+ // ... follow-up logic ...
+}
+```
+
+
+
+ Prefer to use `require(){:tact}` over this function as the former comes with more [compile-time](/ref/api-comptime) optimizations and is generally more user-friendly.
+
+
+
+[p]: /book/types#primitive-types
+[bool]: /book/types#booleans
+[int]: /book/integers
From 23c5d774581b0a81d3dc6a85ee9c6a9f26ca41da Mon Sep 17 00:00:00 2001
From: Novus Nota <68142933+novusnota@users.noreply.github.com>
Date: Tue, 14 May 2024 04:12:30 +0200
Subject: [PATCH 11/24] feat: api-advanced
---
pages/ref/api-advanced.mdx | 198 +++++++++++++++++++++++++++++-------
pages/ref/stdlib-config.mdx | 4 +-
2 files changed, 165 insertions(+), 37 deletions(-)
diff --git a/pages/ref/api-advanced.mdx b/pages/ref/api-advanced.mdx
index e586c4cc..a0625341 100644
--- a/pages/ref/api-advanced.mdx
+++ b/pages/ref/api-advanced.mdx
@@ -16,7 +16,15 @@ Various niche, dangerous or unstable features which can produce unexpected resul
extends fun readForwardFee(self: Context): Int
```
-Read and compute forward fee from the `Context{:tact}` and return it as `Int{:tact}` value in nanoToncoins (nano-tons).
+Extension function for the [`Context{:tact}`](/ref/api-common#context).
+
+Reads forward fee and returns it as [`Int{:tact}`][int] value in nanoToncoins (nano-tons).
+
+Usage example:
+
+```tact
+let fwdFee: Int = context().readForwardFee();
+```
## getConfigParam
@@ -24,7 +32,83 @@ Read and compute forward fee from the `Context{:tact}` and return it as `Int{:ta
fun getConfigParam(id: Int): Cell?;
```
-Load network configuration parameter from the blockchain.
+Loads network configuration parameter from the blockchain.
+
+Usage example:
+
+```tact
+let iDemand: Cell = getConfigParam(0)!!;
+```
+
+
+
+ A standard library [`@stdlib/config`](/ref/stdlib-config) provides two related helper functions:\
+ [`getConfigAddress(){:tact}`](/ref/stdlib-config#getconfigaddress) for retrieving config [`Address{:tact}`][p]\
+ [`getElectorAddress(){:tact}`](/ref/stdlib-config#getconfigaddress) for retrieving elector [`Address{:tact}`][p]
+
+
+
+## acceptMessage
+
+```tact
+fun acceptMessage();
+```
+
+Agrees to buy some gas to finish the current transaction. This action is required to process external messages, which bring no value (hence no gas) with themselves.
+
+Usage example:
+
+```tact {10}
+contract Timeout {
+ timeout: Int;
+
+ init() {
+ self.timeout = now() + 5 * 60; // 5 minutes from now
+ }
+
+ external("timeout") {
+ if (now() > self.timeout) {
+ acceptMessage(); // start accepting external messages once timeout went out
+ }
+ }
+}
+```
+
+
+
+ For more details, see: [Accept Message Effects in TON Docs](https://docs.ton.org/develop/smart-contracts/guidelines/accept).
+
+
+
+## commit
+
+```tact
+fun commit();
+```
+
+Commits the current state of [registers](https://docs.ton.org/learn/tvm-instructions/tvm-overview#control-registers) `c4` ("persistent data") and `c5` ("actions"), so that the current execution is considered "successful" with the saved values even if an exception in compute phase is thrown later.
+
+Usage example:
+
+```tact {1}
+commit(); // now, transaction is considered "successful"
+throw(42); // and this won't fail it
+```
+
+## nativePrepareRandom
+
+```tact
+fun nativePrepareRandom();
+```
+
+Prepares a random number generator by using [`nativeRandomizeLt(){:tact}`](#nativerandomizelt). Automatically called by [`randomInt(){:tact}`](/ref/api-random#randomint) and [`random(){:tact}`](/ref/api-random#random) functions.
+
+Usage example:
+
+```tact
+nativePrepareRandom(); // prepare the RNG
+// ... do your random things ...
+```
## nativeRandomize
@@ -32,7 +116,14 @@ Load network configuration parameter from the blockchain.
fun nativeRandomize(x: Int);
```
-Randomize the random number generator with the specified seed `x`.
+Randomizes the pseudo-random number generator with the specified seed `x`.
+
+Usage example:
+
+```tact
+nativeRandomize(); // now, random numbers are less predictable
+let idk: Int = randomInt(); // ???, it's random!
+```
## nativeRandomizeLt
@@ -40,24 +131,28 @@ Randomize the random number generator with the specified seed `x`.
fun nativeRandomizeLt();
```
-Randomize the random number generator with the current logical time.
+Randomizes the random number generator with the current [logical time](https://docs.ton.org/develop/smart-contracts/guidelines/message-delivery-guarantees#what-is-a-logical-time).
-## nativePrepareRandom
+Usage example:
```tact
-fun nativePrepareRandom();
+nativeRandomizeLt(); // now, random numbers are impredictable!
+let idk: Int = randomInt(); // ???, it's random!
```
-This function prepares random number generator by calling [nativeRandomizeLt](#nativeRandomizeLt) once and called internally by [random](#random) and [randomInt](#randomInt) functions.
-
## nativeRandom
```tact
fun nativeRandom(): Int;
```
-You shouldn't use this function directly, use [random](#random) and [randomInt](#randomInt) functions instead.\
-This function generates 256-bit random number just like [randomInt](#randomInt) function, but random generator is not initialized by [nativePrepareRandom](#nativePrepareRandom) function.
+Generates and returns an $256$-bit random number just like [`randomInt(){:tact}`](/ref/api-random#randomint), but doesn't initialize the random generator with [`nativePrepareRandom(){:tact}`](#nativepreparerandom) beforehand.
+
+
+
+ Don't use this function directly, and prefer using [`randomInt(){:tact}`](/ref/api-random#randomint) instead.
+
+
## nativeRandomInterval
@@ -65,8 +160,27 @@ This function generates 256-bit random number just like [randomInt](#randomInt)
fun nativeRandomInterval(max: Int): Int;
```
-You shouldn't use this function directly, use [random](#random) and [randomInt](#randomInt) functions instead.\
-This function generates random number in the range from 0 to `max`. This call doesn't prepare initialization by [nativePrepareRandom](#nativePrepareRandom) function.
+Generates and returns a $256$-bit random number in the range from $0$ to `max` similar to [`random(){:tact}`](/ref/api-random#random), but doesn't initialize the random generator with [`nativePrepareRandom(){:tact}`](#nativepreparerandom) beforehand.
+
+
+
+ Don't use this function directly, and prefer using [`random(){:tact}`](/ref/api-random#random) instead.
+
+
+
+## nativeSendMessage
+
+```tact
+fun nativeSendMessage(cell: Cell, mode: Int);
+```
+
+Sends the message by specifying the complete `cell` and the [message `mode`](/book/message-mode).
+
+
+
+ Prefer using a much more common and user-friendly [`send(){:tact}`](/ref/api-common#send) function unless you have a complex logic that can't be expressed otherwise.
+
+
## nativeReserve
@@ -83,37 +197,51 @@ raw_reserve(int amount, int mode) impure asm "RAWRESERVE";
```
The function takes two arguments:
-* `amount`: The number of nanotoncoins to reserve.
+* `amount`: The number of nanoToncoins to reserve.
* `mode`: Determines the reservation behavior.
-The resulting `mode` value can have the following base modes:
-* $0$: Reserve exactly amount nanotoncoins.
-* $1$ or $3$: Reserve all but amount nanotoncoins.
-* $2$: Reserve at most amount nanotoncoins.
-
-Additionally, the resulting `mode` can have the following optional flags added:
-* $+2$: If the specified amount cannot be reserved, reserve the remaining balance instead of failing.
-* $+4$: Increase amount by the original balance of the current account (before the compute phase), including all extra currencies.
-* $+8$: Negate the amount before performing further actions.
+Function `raw_reserve` is roughly equivalent to creating an outbound message carrying the specified `amount` of nanoToncoins (or `b` $-$ `amount` nanoToncoins, where `b` is the remaining balance) to oneself. This ensures that subsequent output actions cannot spend more money than the remainder.
-Function `raw_reserve` is roughly equivalent to creating an outbound message carrying the specified `amount` of nanoToncoins (or `b`-amount nanoToncoins, where `b` is the remaining balance) to oneself. This ensures that subsequent output actions cannot spend more money than the remainder.
+It's possible to use raw [`Int{:tact}`][int] values and manually provide them for the `mode`, but for your convenience there's a set of constants which you may use to construct the compound `mode` with ease. Take a look at the following tables for more information on base modes and optional flags.
- Currently, `amount` must be a non-negative integer, and `mode` must be in the range 0..15, inclusive.
+
+ Currently, `amount` must be a non-negative integer, and `mode` must be in the range $0..31$, inclusive.
+
----
+### Base modes [#nativereserve-base-modes]
-TODO: remove
+The resulting `mode` value can have the following base modes:
-```tact
-@name(raw_reserve)
-native nativeReserve(amount: Int, mode: Int);
+Mode value | Constant name | Description
+---------: | :---------------------------- | -----------
+$0$ | `ReserveExact{:tact}` | Reserves exactly the specified `amount` of nanoToncoins.
+$1$ | `ReserveAllExcept{:tact}` | Reserves all, but the specified `amount` of nanoToncoins.
+$2$ | `ReserveAtMost{:tact}` | Reserves at most the specified `amount` of nanoToncoins.
+
+### Optional flags [#nativereserve-optional-flags]
+
+Additionally, the resulting `mode` can have the following optional flags added:
-const ReserveExact: Int = 0;
-const ReserveAllExcept: Int = 1;
-const ReserveAtMost: Int = 2;
-const ReserveAddOriginalBalance: Int = 4;
-const ReserveInvertSign: Int = 8;
-const ReserveBounceIfActionFail: Int = 16;
+Flag value | Constant name | Description
+---------: | :--------------------------------- | -----------
+$+4$ | `ReserveAddOriginalBalance{:tact}` | Increases the `amount` by the original balance of the current accounr (before the compute phase), including all extra currencies.
+$+8$ | `ReserveInvertSign{:tact}` | Negates the `amount` value before performing the reservation.
+$+16$ | `ReserveBounceIfActionFail{:tact}` | Bounces the transaction if reservation fails.
+
+### Combining modes with flags [#nativereserve-combining-modes-with-flags]
+
+To make the [`Int{:tact}`][int] value for `mode` parameter, you just have to combine base modes with optional flags by applying the [`bitwise OR{:tact}`](/book/operators#binary-bitwise-or) operation:
+
+```tact
+nativeReserve(ton("0.1"), ReserveExact | ReserveBounceIfActionFail);
+// ---------- ----------------------------------------
+// ↑ ↑
+// | mode, which would bounce the transaction if exact reservation would fail
+// amount of nanoToncoins to reserve
```
+
+[p]: /book/types#primitive-types
+[bool]: /book/types#booleans
+[int]: /book/integers
diff --git a/pages/ref/stdlib-config.mdx b/pages/ref/stdlib-config.mdx
index 33a1b537..a40071be 100644
--- a/pages/ref/stdlib-config.mdx
+++ b/pages/ref/stdlib-config.mdx
@@ -16,7 +16,7 @@ import "@stdlib/config";
fun getConfigAddress(): Address;
```
-Retrives config parameter 0 as an [`Address{:tact}`][p].
+Retrives config parameter $0$ as an [`Address{:tact}`][p].
Source code:
@@ -34,7 +34,7 @@ fun getConfigAddress(): Address {
fun getElectorAddress(): Address;
```
-Retrives config parameter 1 as an [`Address{:tact}`][p].
+Retrives config parameter $1$ as an [`Address{:tact}`][p].
Source code:
From 431fd407c9d5403e128d2828b817faf821a0799e Mon Sep 17 00:00:00 2001
From: Novus Nota <68142933+novusnota@users.noreply.github.com>
Date: Tue, 14 May 2024 17:16:16 +0200
Subject: [PATCH 12/24] chore: Apply basic suggestions from code review
Co-authored-by: Anton Trunov
---
pages/ref/api-advanced.mdx | 2 +-
pages/ref/api-cells.mdx | 12 ++++++------
pages/ref/api-random.mdx | 2 +-
3 files changed, 8 insertions(+), 8 deletions(-)
diff --git a/pages/ref/api-advanced.mdx b/pages/ref/api-advanced.mdx
index a0625341..813631f3 100644
--- a/pages/ref/api-advanced.mdx
+++ b/pages/ref/api-advanced.mdx
@@ -226,7 +226,7 @@ Additionally, the resulting `mode` can have the following optional flags added:
Flag value | Constant name | Description
---------: | :--------------------------------- | -----------
-$+4$ | `ReserveAddOriginalBalance{:tact}` | Increases the `amount` by the original balance of the current accounr (before the compute phase), including all extra currencies.
+$+4$ | `ReserveAddOriginalBalance{:tact}` | Increases the `amount` by the original balance of the current account (before the compute phase), including all extra currencies.
$+8$ | `ReserveInvertSign{:tact}` | Negates the `amount` value before performing the reservation.
$+16$ | `ReserveBounceIfActionFail{:tact}` | Bounces the transaction if reservation fails.
diff --git a/pages/ref/api-cells.mdx b/pages/ref/api-cells.mdx
index 44145009..547fbdad 100644
--- a/pages/ref/api-cells.mdx
+++ b/pages/ref/api-cells.mdx
@@ -297,10 +297,10 @@ let fizz: Int = s.loadUint(7);
## Slice.preloadUint
```tact
-extends mutates fun preloadUint(self: Slice, l: Int): Int;
+extends fun preloadUint(self: Slice, l: Int): Int;
```
-Extension mutation function for the [`Slice{:tact}`][p].
+Extension function for the [`Slice{:tact}`][p].
Preloads an unsigned `l`-bit [`Int{:tact}`][int] from the [`Slice{:tact}`][p].
@@ -331,10 +331,10 @@ let fizz: Int = s.loadInt(7);
## Slice.preloadInt
```tact
-extends mutates fun preloadInt(self: Slice, l: Int): Int;
+extends fun preloadInt(self: Slice, l: Int): Int;
```
-Extension mutation function for the [`Slice{:tact}`][p].
+Extension function for the [`Slice{:tact}`][p].
Preloads a signed `len`-bit [`Int{:tact}`][int] from the [`Slice{:tact}`][p].
@@ -365,10 +365,10 @@ let fizz: Slice = s.loadBits(7);
## Slice.preloadBits
```tact
-extends mutates fun preloadBits(self: Slice, l: Int): Slice;
+extends fun preloadBits(self: Slice, l: Int): Slice;
```
-Extension mutation function for the [`Slice{:tact}`][p].
+Extension function for the [`Slice{:tact}`][p].
Preloads the first $0 ≤ l ≤ 1023$ bits from the Slice, and returns it as a separate [`Slice{:tact}`][p].
diff --git a/pages/ref/api-random.mdx b/pages/ref/api-random.mdx
index 92a5dfb7..8bfa0524 100644
--- a/pages/ref/api-random.mdx
+++ b/pages/ref/api-random.mdx
@@ -37,7 +37,7 @@ let allYourRandomBelongsToUs: Int = randomInt(); // ???, it's random :)
- Advanced APIs for working with random numbers are listed on a specialized page: [Advanced APIs](/ref/api-advanced).
+ Advanced functions for working with random numbers are listed on a specialized page: [Advanced APIs](/ref/api-advanced).
From 109ac8674fdb62ba94a7416c6721e3f67b497a41 Mon Sep 17 00:00:00 2001
From: Novus Nota <68142933+novusnota@users.noreply.github.com>
Date: Tue, 14 May 2024 17:32:18 +0200
Subject: [PATCH 13/24] chore: forward fee
---
pages/ref/api-advanced.mdx | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/pages/ref/api-advanced.mdx b/pages/ref/api-advanced.mdx
index 813631f3..b7203da3 100644
--- a/pages/ref/api-advanced.mdx
+++ b/pages/ref/api-advanced.mdx
@@ -18,7 +18,7 @@ extends fun readForwardFee(self: Context): Int
Extension function for the [`Context{:tact}`](/ref/api-common#context).
-Reads forward fee and returns it as [`Int{:tact}`][int] value in nanoToncoins (nano-tons).
+Reads [forward fee](https://docs.ton.org/develop/smart-contracts/guidelines/processing) and returns it as [`Int{:tact}`][int] value in nanoToncoins (nano-tons).
Usage example:
From 3ad336a2c89cf4c578880c04fc6a19fd8089f5b0 Mon Sep 17 00:00:00 2001
From: Novus Nota <68142933+novusnota@users.noreply.github.com>
Date: Wed, 15 May 2024 16:54:32 +0200
Subject: [PATCH 14/24] chore: couple fixes
---
pages/ref/api-advanced.mdx | 4 +++-
pages/ref/api-cells.mdx | 10 +++++-----
2 files changed, 8 insertions(+), 6 deletions(-)
diff --git a/pages/ref/api-advanced.mdx b/pages/ref/api-advanced.mdx
index b7203da3..43fa5f04 100644
--- a/pages/ref/api-advanced.mdx
+++ b/pages/ref/api-advanced.mdx
@@ -136,7 +136,9 @@ Randomizes the random number generator with the current [logical time](https://d
Usage example:
```tact
-nativeRandomizeLt(); // now, random numbers are impredictable!
+nativeRandomizeLt(); // now, random numbers are unpredictable for users,
+ // but still may be affected by validators or collators
+ // as they determine the seed of the current block.
let idk: Int = randomInt(); // ???, it's random!
```
diff --git a/pages/ref/api-cells.mdx b/pages/ref/api-cells.mdx
index 547fbdad..0861ce6e 100644
--- a/pages/ref/api-cells.mdx
+++ b/pages/ref/api-cells.mdx
@@ -172,7 +172,7 @@ Usage example:
```tact
let b: Builder = beginCell();
-let fizz: Int = b.refs();
+let fizz: Int = b.refs(); // 0
```
## Builder.bits
@@ -189,7 +189,7 @@ Usage example:
```tact
let b: Builder = beginCell();
-let fizz: Int = b.bits();
+let fizz: Int = b.bits(); // 0
```
## Builder.asSlice
@@ -302,7 +302,7 @@ extends fun preloadUint(self: Slice, l: Int): Int;
Extension function for the [`Slice{:tact}`][p].
-Preloads an unsigned `l`-bit [`Int{:tact}`][int] from the [`Slice{:tact}`][p].
+Preloads an unsigned `l`-bit [`Int{:tact}`][int] from the [`Slice{:tact}`][p] without changing its data.
Usage example:
@@ -336,7 +336,7 @@ extends fun preloadInt(self: Slice, l: Int): Int;
Extension function for the [`Slice{:tact}`][p].
-Preloads a signed `len`-bit [`Int{:tact}`][int] from the [`Slice{:tact}`][p].
+Preloads a signed `len`-bit [`Int{:tact}`][int] from the [`Slice{:tact}`][p] without changing its data.
Usage example:
@@ -370,7 +370,7 @@ extends fun preloadBits(self: Slice, l: Int): Slice;
Extension function for the [`Slice{:tact}`][p].
-Preloads the first $0 ≤ l ≤ 1023$ bits from the Slice, and returns it as a separate [`Slice{:tact}`][p].
+Preloads the first $0 ≤ l ≤ 1023$ bits from the Slice, and returns it as a separate [`Slice{:tact}`][p] without changing its data.
Usage example:
From 21fd8e02a7b111faa403c6defbac0ec710685031 Mon Sep 17 00:00:00 2001
From: Novus Nota <68142933+novusnota@users.noreply.github.com>
Date: Wed, 15 May 2024 17:12:14 +0200
Subject: [PATCH 15/24] chore: "API Reference" is now called "Core library" for
clarity
---
pages/cookbook/misc.mdx | 2 +-
pages/cookbook/random.mdx | 4 ++--
pages/cookbook/single-communication.mdx | 2 +-
pages/cookbook/time.mdx | 2 +-
pages/cookbook/type-conversion.mdx | 6 ++---
pages/ref/_meta.js | 22 +++++++++----------
.../{api-advanced.mdx => core-advanced.mdx} | 0
pages/ref/{api-base.mdx => core-base.mdx} | 0
pages/ref/{api-cells.mdx => core-cells.mdx} | 0
pages/ref/{api-common.mdx => core-common.mdx} | 0
.../{api-comptime.mdx => core-comptime.mdx} | 0
pages/ref/{api-debug.mdx => core-debug.mdx} | 0
pages/ref/{api-math.mdx => core-math.mdx} | 0
pages/ref/{api-random.mdx => core-random.mdx} | 0
.../ref/{api-strings.mdx => core-strings.mdx} | 0
pages/ref/index.mdx | 10 ++++-----
16 files changed, 24 insertions(+), 24 deletions(-)
rename pages/ref/{api-advanced.mdx => core-advanced.mdx} (100%)
rename pages/ref/{api-base.mdx => core-base.mdx} (100%)
rename pages/ref/{api-cells.mdx => core-cells.mdx} (100%)
rename pages/ref/{api-common.mdx => core-common.mdx} (100%)
rename pages/ref/{api-comptime.mdx => core-comptime.mdx} (100%)
rename pages/ref/{api-debug.mdx => core-debug.mdx} (100%)
rename pages/ref/{api-math.mdx => core-math.mdx} (100%)
rename pages/ref/{api-random.mdx => core-random.mdx} (100%)
rename pages/ref/{api-strings.mdx => core-strings.mdx} (100%)
diff --git a/pages/cookbook/misc.mdx b/pages/cookbook/misc.mdx
index a0960f58..d2922c36 100644
--- a/pages/cookbook/misc.mdx
+++ b/pages/cookbook/misc.mdx
@@ -26,7 +26,7 @@ nativeThrowUnless(39, number == 198);
**Useful links:**\
- [`throw(){:tact}` in API Reference](/ref/api-debug#throw)\
+ [`throw(){:tact}` in Core library](/ref/core-debug#throw)\
[Errors in Tact-By-Example](https://tact-by-example.org/03-errors)
diff --git a/pages/cookbook/random.mdx b/pages/cookbook/random.mdx
index 898aa8b2..ee538b46 100644
--- a/pages/cookbook/random.mdx
+++ b/pages/cookbook/random.mdx
@@ -20,8 +20,8 @@ number = random(1, 12);
**Useful links:**\
- [`randomInt(){:tact}` in API Reference](/ref/api-random#randomInt)\
- [`random(){:tact}` in API Reference](/ref/api-random#random)
+ [`randomInt(){:tact}` in Core library](/ref/core-random#randomInt)\
+ [`random(){:tact}` in Core library](/ref/core-random#random)
diff --git a/pages/cookbook/single-communication.mdx b/pages/cookbook/single-communication.mdx
index 9063958e..6755b1c9 100644
--- a/pages/cookbook/single-communication.mdx
+++ b/pages/cookbook/single-communication.mdx
@@ -91,7 +91,7 @@ send(SendParameters{
["Sending messages" in the Book](/book/send#send-message)\
["Message `mode`" in the Book](/book/message-mode)
[`StringBuilder{:tact}` in the Book](/book/types#primitive-types)\
- [`Cell{:tact}` in API Reference](/ref/api-cells)
+ [`Cell{:tact}` in Core library](/ref/core-cells)
diff --git a/pages/cookbook/time.mdx b/pages/cookbook/time.mdx
index 790b60ed..be01dcb6 100644
--- a/pages/cookbook/time.mdx
+++ b/pages/cookbook/time.mdx
@@ -19,7 +19,7 @@ if (currentTime > 1672080143) {
**Useful links:**\
- [`now(){:tact}` in API Reference](/ref/api-common#now)\
+ [`now(){:tact}` in Core library](/ref/core-common#now)\
["Current Time" in Tact-By-Example](https://tact-by-example.org/04-current-time)
diff --git a/pages/cookbook/type-conversion.mdx b/pages/cookbook/type-conversion.mdx
index 77a17049..174216a6 100644
--- a/pages/cookbook/type-conversion.mdx
+++ b/pages/cookbook/type-conversion.mdx
@@ -60,9 +60,9 @@ dump(coinsString); // "0.261119911"
**Useful links:**\
- [`Int.toString(){:tact}` in API Reference](/ref/api-strings#inttostring)\
- [`Int.toFloatString(){:tact}` in API Reference](/ref/api-strings#inttofloatstring)\
- [`Int.toCoinsString(){:tact}` in API Reference](/ref/api-strings#inttocoinsstring)
+ [`Int.toString(){:tact}` in Core library](/ref/core-strings#inttostring)\
+ [`Int.toFloatString(){:tact}` in Core library](/ref/core-strings#inttofloatstring)\
+ [`Int.toCoinsString(){:tact}` in Core library](/ref/core-strings#inttocoinsstring)
diff --git a/pages/ref/_meta.js b/pages/ref/_meta.js
index 432e3015..9ba1719e 100644
--- a/pages/ref/_meta.js
+++ b/pages/ref/_meta.js
@@ -2,19 +2,19 @@ export default {
index: 'Overview',
spec: 'Specification',
evolution: 'Evolution',
- '-- API': {
+ '-- Core library': {
type: 'separator',
- title: 'API Reference',
+ title: 'Core library',
},
- 'api-base': 'Base trait',
- 'api-common': 'Common',
- 'api-comptime': 'Compile-time',
- 'api-debug': 'Debug',
- 'api-random': 'Random',
- 'api-math': 'Math',
- 'api-strings': 'Strings and StringBuilders',
- 'api-cells': 'Cells, Builders and Slices',
- 'api-advanced': 'Advanced',
+ 'core-base': 'Base trait',
+ 'core-common': 'Common',
+ 'core-comptime': 'Compile-time',
+ 'core-debug': 'Debug',
+ 'core-random': 'Random',
+ 'core-math': 'Math',
+ 'core-strings': 'Strings and StringBuilders',
+ 'core-cells': 'Cells, Builders and Slices',
+ 'core-advanced': 'Advanced',
'-- Stdlib': {
type: 'separator',
title: 'Standard libraries',
diff --git a/pages/ref/api-advanced.mdx b/pages/ref/core-advanced.mdx
similarity index 100%
rename from pages/ref/api-advanced.mdx
rename to pages/ref/core-advanced.mdx
diff --git a/pages/ref/api-base.mdx b/pages/ref/core-base.mdx
similarity index 100%
rename from pages/ref/api-base.mdx
rename to pages/ref/core-base.mdx
diff --git a/pages/ref/api-cells.mdx b/pages/ref/core-cells.mdx
similarity index 100%
rename from pages/ref/api-cells.mdx
rename to pages/ref/core-cells.mdx
diff --git a/pages/ref/api-common.mdx b/pages/ref/core-common.mdx
similarity index 100%
rename from pages/ref/api-common.mdx
rename to pages/ref/core-common.mdx
diff --git a/pages/ref/api-comptime.mdx b/pages/ref/core-comptime.mdx
similarity index 100%
rename from pages/ref/api-comptime.mdx
rename to pages/ref/core-comptime.mdx
diff --git a/pages/ref/api-debug.mdx b/pages/ref/core-debug.mdx
similarity index 100%
rename from pages/ref/api-debug.mdx
rename to pages/ref/core-debug.mdx
diff --git a/pages/ref/api-math.mdx b/pages/ref/core-math.mdx
similarity index 100%
rename from pages/ref/api-math.mdx
rename to pages/ref/core-math.mdx
diff --git a/pages/ref/api-random.mdx b/pages/ref/core-random.mdx
similarity index 100%
rename from pages/ref/api-random.mdx
rename to pages/ref/core-random.mdx
diff --git a/pages/ref/api-strings.mdx b/pages/ref/core-strings.mdx
similarity index 100%
rename from pages/ref/api-strings.mdx
rename to pages/ref/core-strings.mdx
diff --git a/pages/ref/index.mdx b/pages/ref/index.mdx
index 3fe0142b..829c9f94 100644
--- a/pages/ref/index.mdx
+++ b/pages/ref/index.mdx
@@ -2,21 +2,21 @@
import { Cards, Steps } from 'nextra/components'
-Welcome to the **Language** section of Tact documentation — a place for becoming more familiar with the language in much more depth compared to the [Book](/book).
+Welcome to the **Reference** section of Tact documentation — a place for discovering the Tact's standard library, grammar specification and evolution process.
Here are its main contents:
-### API Reference
+### Core library
-[API Reference](/ref/stdlib-common) gives a comprehensive list of auto-included constructs and provides examples of their usage.
+[Core library](/ref/core-base) gives a comprehensive list of auto-included functions, traits and other constructs with examples of their usage.
From 4e40dafb8fc4e45934946309720f0b2d5e3a958c Mon Sep 17 00:00:00 2001
From: Novus Nota <68142933+novusnota@users.noreply.github.com>
Date: Thu, 16 May 2024 20:54:54 +0200
Subject: [PATCH 16/24] fix: explain `require()` better
---
pages/ref/core-debug.mdx | 48 ++++++++++++++++++++++------------------
1 file changed, 26 insertions(+), 22 deletions(-)
diff --git a/pages/ref/core-debug.mdx b/pages/ref/core-debug.mdx
index 909eac3a..961c6b77 100644
--- a/pages/ref/core-debug.mdx
+++ b/pages/ref/core-debug.mdx
@@ -2,6 +2,14 @@
import { Callout } from 'nextra-theme-docs'
+List of functions commonly used for debugging smart contracts in Tact.
+
+
+
+ Read more about debugging on the dedicated page: [Debugging](/book/debug).
+
+
+
## require
```tact
@@ -10,11 +18,25 @@ fun require(condition: Bool, error: String);
Checks the `condition` and throws an exception with `error` message if the `condition` is `false{:tact}`. Does nothing otherwise.
-Usage example:
+
+
+ Note, that as of this moment, `require(){:tact}` generates its own non-standard exit codes. However, they're all outside of the common range $0 - 255$ reserved for TVM and Tact contract errors, which makes it possible to distinguish errors from `require(){:tact}` and any other standard [exit codes](/book/exit-codes).
+
+
+
+Usage examples:
```tact
// now() has to return a value greater than 1000, otherwise an error message will be thrown
require(now() > 1000, "We're in the first 1000 seconds of 1 January 1970!");
+
+try {
+ // The following will never be true, so this require would always throw
+ require(now() < -1, "Time is an illusion. Lunchtime doubly so.");
+} catch (e) {
+ // e will be outside of range 0-255
+ dump(e);
+}
```
## dump
@@ -78,7 +100,7 @@ Prints all the values of [persistent state variables](/book/contracts#variables)
Usage example:
-```tact
+```tact {6}
contract DumpsterFire {
var1: Int = 0;
var2: Int = 5;
@@ -121,19 +143,13 @@ fun butThisDoesnt() {
}
```
-
-
- Prefer to use `require(){:tact}` over this function as the former comes with more [compile-time](/ref/api-comptime) optimizations and is generally more user-friendly.
-
-
-
## nativeThrowWhen
```tact
fun nativeThrowWhen(code: Int, condition: Bool);
```
-Similar to [`nativeThrow(){:tact}`](#nativethrow), but with throw an exception conditionally, when `condition` is equal to `true{:tact}`. Won't throw otherwise.
+Similar to [`nativeThrow(){:tact}`](#nativethrow), but throws an exception conditionally, when `condition` is equal to `true{:tact}`. Doesn't throw otherwise.
Usage examples:
@@ -150,19 +166,13 @@ fun butThisDoesnt() {
}
```
-
-
- Prefer to use `require(){:tact}` over this function as the former comes with more [compile-time](/ref/api-comptime) optimizations and is generally more user-friendly.
-
-
-
## nativeThrowUnless
```tact
fun nativeThrowUnless(code: Int, condition: Bool);
```
-Similar to [`nativeThrow(){:tact}`](#nativethrow), but with throw an exception conditionally, when `condition` is equal to `false{:tact}`. Won't throw otherwise.
+Similar to [`nativeThrow(){:tact}`](#nativethrow), but throws an exception conditionally, when `condition` is equal to `false{:tact}`. Doesn't throw otherwise.
Usage examples:
@@ -179,12 +189,6 @@ fun butThisDoesnt() {
}
```
-
-
- Prefer to use `require(){:tact}` over this function as the former comes with more [compile-time](/ref/api-comptime) optimizations and is generally more user-friendly.
-
-
-
[p]: /book/types#primitive-types
[bool]: /book/types#booleans
[int]: /book/integers
From 3949cfa0e2e4d4a4bbae81f93c6da80d44c02c3c Mon Sep 17 00:00:00 2001
From: Novus Nota <68142933+novusnota@users.noreply.github.com>
Date: Thu, 16 May 2024 23:40:38 +0200
Subject: [PATCH 17/24] fix: core-math stuff
---
pages/ref/core-math.mdx | 34 ++++++++++++++++++++++++++++++++--
1 file changed, 32 insertions(+), 2 deletions(-)
diff --git a/pages/ref/core-math.mdx b/pages/ref/core-math.mdx
index 87230490..ebf6faa9 100644
--- a/pages/ref/core-math.mdx
+++ b/pages/ref/core-math.mdx
@@ -147,16 +147,28 @@ abs(-(-(-42))); // 42
fun log(num: Int, base: Int): Int;
```
-Computes and returns the [logarithm](https://en.wikipedia.org/wiki/Logarithm) of a number `num` to the base `base`.
+Computes and returns the [logarithm](https://en.wikipedia.org/wiki/Logarithm) of a number `num` to the base `base`. Results are [rounded down](https://en.wikipedia.org/wiki/Rounding#Rounding_down). Passing negative `num` always gives $0$ as the result, while passing negative `base` gives $-1$ when it is close enough to zero and there's enough gas for calculations, otherwise throws an error with [exit code -14](/book/exit-codes): `Out of gas`.
-Usage example:
+Usage examples:
```tact
log(1000, 10); // 3, as 10^3 is 1000
// ↑ ↑ ↑ ↑
// num base base num
+
+log(1001, 10); // 3
+log(999, 10); // 2
+log(-1000, 10); // 0, because of the negative num
+log(1024, 2); // 10
+log(1024, -2); // -1, because of the negative base
```
+
+
+ Note, that if you only need to obtain logarithms to the base $2$, use the [`log2(){:tact}`](#log2) function, as it's less gas-consuming.
+
+
+
## log2
```tact
@@ -173,6 +185,12 @@ log2(1024); // 10, as 2^10 is 1024
// num base₂ num
```
+
+
+ In order to reduce gas usage, prefer using this function over calling [`log(){:tact}`](#log) when you only need to obtain logarithms to the base $2$.
+
+
+
## pow
```tact
@@ -200,6 +218,12 @@ contract Example {
}
```
+
+
+ Note, that if you only need to obtain powers of $2$, use the [`pow2(){:tact}`](#pow2) function, as it's less gas-consuming.
+
+
+
List of functions, that only work at compile-time: [API Comptime](/ref/api-comptime).
@@ -231,6 +255,12 @@ contract Example {
}
```
+
+
+ In order to reduce gas usage, prefer using this function over calling [`pow(){:tact}`](#pow) when you only need to obtain powers of $2$.
+
+
+
List of functions, that only work at compile-time: [API Comptime](/ref/api-comptime).
From f81c12fd828e6707b9776cce6c56c59866a4a068 Mon Sep 17 00:00:00 2001
From: Novus Nota <68142933+novusnota@users.noreply.github.com>
Date: Fri, 17 May 2024 13:13:30 +0200
Subject: [PATCH 18/24] chore: "more gas-efficient" over "less gas-consuming"
---
pages/ref/core-debug.mdx | 2 +-
pages/ref/core-math.mdx | 4 ++--
2 files changed, 3 insertions(+), 3 deletions(-)
diff --git a/pages/ref/core-debug.mdx b/pages/ref/core-debug.mdx
index 961c6b77..3c980280 100644
--- a/pages/ref/core-debug.mdx
+++ b/pages/ref/core-debug.mdx
@@ -20,7 +20,7 @@ Checks the `condition` and throws an exception with `error` message if the `cond
- Note, that as of this moment, `require(){:tact}` generates its own non-standard exit codes. However, they're all outside of the common range $0 - 255$ reserved for TVM and Tact contract errors, which makes it possible to distinguish errors from `require(){:tact}` and any other standard [exit codes](/book/exit-codes).
+ Note, that as of this moment, `require(){:tact}` generates its own non-standard exit codes. However, they're all outside of the common range $0 - 255$ reserved for TVM and Tact contract errors, which makes it possible to distinguish exit codes from `require(){:tact}` and any other [standard exit codes](/book/exit-codes).
diff --git a/pages/ref/core-math.mdx b/pages/ref/core-math.mdx
index ebf6faa9..3fdf63f6 100644
--- a/pages/ref/core-math.mdx
+++ b/pages/ref/core-math.mdx
@@ -165,7 +165,7 @@ log(1024, -2); // -1, because of the negative base
- Note, that if you only need to obtain logarithms to the base $2$, use the [`log2(){:tact}`](#log2) function, as it's less gas-consuming.
+ Note, that if you only need to obtain logarithms to the base $2$, use the [`log2(){:tact}`](#log2) function, as it's more gas-efficient.
@@ -220,7 +220,7 @@ contract Example {
- Note, that if you only need to obtain powers of $2$, use the [`pow2(){:tact}`](#pow2) function, as it's less gas-consuming.
+ Note, that if you only need to obtain powers of $2$, use the [`pow2(){:tact}`](#pow2) function, as it's more gas-efficient.
From 80450f77679f4e4d31aff11eedeaea50832f7af0 Mon Sep 17 00:00:00 2001
From: Novus Nota <68142933+novusnota@users.noreply.github.com>
Date: Fri, 17 May 2024 13:31:28 +0200
Subject: [PATCH 19/24] chore: correct the bug
---
pages/ref/core-math.mdx | 14 +++++++++-----
1 file changed, 9 insertions(+), 5 deletions(-)
diff --git a/pages/ref/core-math.mdx b/pages/ref/core-math.mdx
index 3fdf63f6..41f51444 100644
--- a/pages/ref/core-math.mdx
+++ b/pages/ref/core-math.mdx
@@ -147,7 +147,7 @@ abs(-(-(-42))); // 42
fun log(num: Int, base: Int): Int;
```
-Computes and returns the [logarithm](https://en.wikipedia.org/wiki/Logarithm) of a number `num` to the base `base`. Results are [rounded down](https://en.wikipedia.org/wiki/Rounding#Rounding_down). Passing negative `num` always gives $0$ as the result, while passing negative `base` gives $-1$ when it is close enough to zero and there's enough gas for calculations, otherwise throws an error with [exit code -14](/book/exit-codes): `Out of gas`.
+Computes and returns the [logarithm](https://en.wikipedia.org/wiki/Logarithm) of a number `num` $> 0$ to the base `base` $≥ 1$. Results are [rounded down](https://en.wikipedia.org/wiki/Rounding#Rounding_down). Passing a non-positive `num` value or a `base` less than $1$ throws an error with [exit code 5](/book/exit-codes#5): `Integer out of expected range`.
Usage examples:
@@ -158,9 +158,13 @@ log(1000, 10); // 3, as 10^3 is 1000
log(1001, 10); // 3
log(999, 10); // 2
-log(-1000, 10); // 0, because of the negative num
+try {
+ log(-1000, 10); // throws exit code 5 because of the non-positive num
+}
log(1024, 2); // 10
-log(1024, -2); // -1, because of the negative base
+try {
+ log(1024, -2); // throws exit code 5 because of the base less than 1
+}
```
@@ -175,7 +179,7 @@ log(1024, -2); // -1, because of the negative base
fun log2(num: Int): Int;
```
-Similar to `log(){:tact}`, but sets the `base` to $2$.
+Similar to [`log(){:tact}`](#log), but sets the `base` to $2$.
Usage example:
@@ -236,7 +240,7 @@ contract Example {
fun pow2(exp: Int): Int;
```
-Similar to `pow(){:tact}`, but sets the `base` to $2$. Works both at run-time and at [compile-time](/ref/api-comptime).
+Similar to [`pow(){:tact}`](#pow), but sets the `base` to $2$. Works both at run-time and at [compile-time](/ref/api-comptime).
Usage examples:
From 68c039b608d79d8cc900d400ca3360ea5d8d435a Mon Sep 17 00:00:00 2001
From: Novus Nota <68142933+novusnota@users.noreply.github.com>
Date: Fri, 17 May 2024 13:58:49 +0200
Subject: [PATCH 20/24] chore: placed less used functions lower
---
pages/ref/core-math.mdx | 166 ++++++++++++++++++++--------------------
1 file changed, 83 insertions(+), 83 deletions(-)
diff --git a/pages/ref/core-math.mdx b/pages/ref/core-math.mdx
index 41f51444..3a8f32df 100644
--- a/pages/ref/core-math.mdx
+++ b/pages/ref/core-math.mdx
@@ -4,89 +4,6 @@ import { Callout } from 'nextra-theme-docs'
Various math helper functions.
-## checkSignature
-
-```tact
-fun checkSignature(hash: Int, signature: Slice, public_key: Int): Bool;
-```
-
-Checks the [Ed25519][ed] `signature` of the $256$-bit unsigned [`Int{:tact}`][int] `hash` using a `public_key`, represented by a $256$-bit unsigned [`Int{:tact}`][int] too. The signature must contain at least $512$ bits of data, but only the first $512$ bits are used.
-
-Returns `true{:tact}` if the signature is valid, `false{:tact}` otherwise.
-
-Usage example:
-
-```tact {19-24}
-message ExtMsg {
- signature: Slice;
- data: Cell;
-}
-
-contract Showcase {
- // Persistent state variables
- pub: Int as uint256; // public key as an 256-bit unsigned Int
-
- // Constructor function init(), where all the variables are initialized
- init(pub: Int) {
- self.pub = pub; // storing the public key upon contract initialization
- }
-
- // External message receiver, which accepts message ExtMsg
- external(msg: ExtMsg) {
- let hash: Int = beginCell().storeRef(msg.data).endCell().hash();
- let check: Bool = checkSignature(hash, msg.signature, self.pub);
- // ---- ------------- --------
- // ↑ ↑ ↑
- // | | public_key, stored in our contract
- // | signature, obtained from the received message
- // hash, calculated using the data from the received message
- // ... follow-up logic ...
- }
-}
-```
-
-## checkDataSignature
-
-```tact
-fun checkDataSignature(data: Slice, signature: Slice, public_key: Int): Bool;
-```
-
-Checks the [Ed25519][ed] `signature` of the `data` using a `public_key`, similar to [`checkSignature(){:tact}`](#checksignature). If the bit length of `data` is not divisible by $8$, this functions throws an error with [exit code 9](/book/exit-codes#9): `Cell underflow`. Verification itself is being done indirectly: on a [SHA-256][sha2] hash of the `data`.
-
-Returns `true{:tact}` if the signature is valid, `false{:tact}` otherwise.
-
-Usage example:
-
-```tact
-let data: Slice = ...;
-let signature: Slice = ...;
-let publicKey: Int = ...;
-
-let check: Bool = checkSignature(data, signature, publicKey);
-```
-
-## sha256
-
-```tact
-fun sha256(data: Slice): Int;
-fun sha256(data: String): Int;
-```
-
-Computes and returns the [SHA-256](https://en.wikipedia.org/wiki/SHA-2#Hash_standard) hash as an $256$-bit unsigned [`Int{:tact}`][int] from a passed [`Slice{:tact}`][p] or [`String{:tact}`][p] `data`.
-
-In case `data` is a [`String{:tact}`][p] it should have a number of bits divisible by $8$, and in case it's a [`Slice{:tact}`][p] it must **also** have no references (i.e. only up to 1023 bits of data in total).
-
-This function tries to resolve constant string values in [compile-time](/ref/api-comptime) whenever possible.
-
-Usage examples:
-
-```tact
-sha256(beginCell().asSlice());
-sha256("Hello, world!"); // will be resolved in compile-time
-sha256(someVariableElsewhere); // will try to resolve at compile-time,
- // and fallback to run-time evaluation
-```
-
## min
```tact
@@ -271,6 +188,89 @@ contract Example {
+## checkSignature
+
+```tact
+fun checkSignature(hash: Int, signature: Slice, public_key: Int): Bool;
+```
+
+Checks the [Ed25519][ed] `signature` of the $256$-bit unsigned [`Int{:tact}`][int] `hash` using a `public_key`, represented by a $256$-bit unsigned [`Int{:tact}`][int] too. The signature must contain at least $512$ bits of data, but only the first $512$ bits are used.
+
+Returns `true{:tact}` if the signature is valid, `false{:tact}` otherwise.
+
+Usage example:
+
+```tact {19-24}
+message ExtMsg {
+ signature: Slice;
+ data: Cell;
+}
+
+contract Showcase {
+ // Persistent state variables
+ pub: Int as uint256; // public key as an 256-bit unsigned Int
+
+ // Constructor function init(), where all the variables are initialized
+ init(pub: Int) {
+ self.pub = pub; // storing the public key upon contract initialization
+ }
+
+ // External message receiver, which accepts message ExtMsg
+ external(msg: ExtMsg) {
+ let hash: Int = beginCell().storeRef(msg.data).endCell().hash();
+ let check: Bool = checkSignature(hash, msg.signature, self.pub);
+ // ---- ------------- --------
+ // ↑ ↑ ↑
+ // | | public_key, stored in our contract
+ // | signature, obtained from the received message
+ // hash, calculated using the data from the received message
+ // ... follow-up logic ...
+ }
+}
+```
+
+## checkDataSignature
+
+```tact
+fun checkDataSignature(data: Slice, signature: Slice, public_key: Int): Bool;
+```
+
+Checks the [Ed25519][ed] `signature` of the `data` using a `public_key`, similar to [`checkSignature(){:tact}`](#checksignature). If the bit length of `data` is not divisible by $8$, this functions throws an error with [exit code 9](/book/exit-codes#9): `Cell underflow`. Verification itself is being done indirectly: on a [SHA-256][sha2] hash of the `data`.
+
+Returns `true{:tact}` if the signature is valid, `false{:tact}` otherwise.
+
+Usage example:
+
+```tact
+let data: Slice = ...;
+let signature: Slice = ...;
+let publicKey: Int = ...;
+
+let check: Bool = checkSignature(data, signature, publicKey);
+```
+
+## sha256
+
+```tact
+fun sha256(data: Slice): Int;
+fun sha256(data: String): Int;
+```
+
+Computes and returns the [SHA-256](https://en.wikipedia.org/wiki/SHA-2#Hash_standard) hash as an $256$-bit unsigned [`Int{:tact}`][int] from a passed [`Slice{:tact}`][p] or [`String{:tact}`][p] `data`.
+
+In case `data` is a [`String{:tact}`][p] it should have a number of bits divisible by $8$, and in case it's a [`Slice{:tact}`][p] it must **also** have no references (i.e. only up to 1023 bits of data in total).
+
+This function tries to resolve constant string values in [compile-time](/ref/api-comptime) whenever possible.
+
+Usage examples:
+
+```tact
+sha256(beginCell().asSlice());
+sha256("Hello, world!"); // will be resolved in compile-time
+sha256(someVariableElsewhere); // will try to resolve at compile-time,
+ // and fallback to run-time evaluation
+```
+
[p]: /book/types#primitive-types
[bool]: /book/types#booleans
[int]: /book/integers
From b9bd0aca32557f71c853284e2401980ed1ee010e Mon Sep 17 00:00:00 2001
From: Novus Nota <68142933+novusnota@users.noreply.github.com>
Date: Fri, 17 May 2024 14:21:32 +0200
Subject: [PATCH 21/24] chore: more about the context and emit
---
pages/ref/core-common.mdx | 42 +++++++++++++++++++++++++++++----------
1 file changed, 31 insertions(+), 11 deletions(-)
diff --git a/pages/ref/core-common.mdx b/pages/ref/core-common.mdx
index 12914b65..cfb95a5d 100644
--- a/pages/ref/core-common.mdx
+++ b/pages/ref/core-common.mdx
@@ -90,12 +90,12 @@ fun context(): Context;
Returns `Context{:tact}` [Struct](/book/structs-and-messages#structs), that consists of:
-Field | Type | Description
-:------ | :-------------------- | :----------
-bounced | [`Bool{:tact}`][bool] | [Bounced](https://ton.org/docs/learn/overviews/addresses#bounceable-vs-non-bounceable-addresses) flag of the incoming message.
-sender | [`Address{:tact}`][p] | Internal address of the sender on the TON blockchain.
-value | [`Int{:tact}`][int] | Amount of nanoToncoins in a message.
-raw | [`Slice{:tact}`][p] | The reminder of the message as a [`Slice{:tact}`][p].
+Field | Type | Description
+:-------- | :-------------------- | :----------
+`bounced` | [`Bool{:tact}`][bool] | [Bounced](https://ton.org/docs/learn/overviews/addresses#bounceable-vs-non-bounceable-addresses) flag of the incoming message.
+`sender` | [`Address{:tact}`][p] | Internal address of the sender on the TON blockchain.
+`value` | [`Int{:tact}`][int] | Amount of nanoToncoins in a message.
+`raw` | [`Slice{:tact}`][p] | The remainder of the message as a [`Slice{:tact}`][p]. It follows [internal message layout](https://docs.ton.org/develop/smart-contracts/messages#message-layout) of TON starting from the destination [`Address{:tact}`][p] (`dest:MsgAddressInt ` in [TL-B notation](https://docs.ton.org/develop/data-formats/tl-b-language)).
Usage example:
@@ -106,7 +106,7 @@ require(ctx.value != 68 + 1, "Invalid amount of nanoToncoins, bye!");
- Note, that if you only need to know who sent the message, use the [`sender(){:tact}`](#sender) function, as it's less gas-expensive.
+ Note, that if you only need to know who sent the message, use the [`sender(){:tact}`](#sender) function, as it's less gas-consuming.
@@ -204,9 +204,9 @@ Usage example:
```tact
send(SendParameters{
- to: sender(), // back to the sender
- value: 1, // with 1 toncoin
- // and no message body
+ to: sender(), // back to the sender,
+ value: ton("1"), // with 1 toncoin,
+ // and no message body
});
```
@@ -225,7 +225,7 @@ send(SendParameters{
fun emit(body: Cell);
```
-Sends a message `body` to the outer world with the purpose of logging and analyzing it later off-chain. The message does not have a recipient and is gas-efficient compared to using any other message sending function in Tact.
+Sends a message `body` to the outer world with the purpose of logging and analyzing it later off-chain. The message does not have a recipient and is gas-efficient compared to using any other message sending functions of Tact.
Usage example:
@@ -233,6 +233,26 @@ Usage example:
emit("Catch me if you can, Mr. Holmes".asComment()); // asComment() converts a String to a Cell
```
+
+
+ To analyze `emit(){:tact}` calls, one has to look at [external messages](http://localhost:3000/book/external) produced by the contract. For example, when deploying in [Sandbox](https://github.com/ton-org/sandbox), you may call `emit(){:tact}` from a [receiver function](/book/contracts#receiver-functions) and then observe the list of sent external messages:
+
+ ```typescript {9-10}
+ it('emits', async () => {
+ const res = await simpleCounter.send(
+ deployer.getSender(),
+ { value: toNano('0.05') },
+ 'emit_receiver',
+ );
+
+ console.log("Address of our contract: " + simpleCounter.address);
+ console.log(res.externals); // ← here one would see results of emit() calls,
+ // and all external messages in general
+ });
+ ```
+
+
+
[p]: /book/types#primitive-types
[bool]: /book/types#booleans
[int]: /book/integers
From 92dcd713aa1abae5ae84d3b7d2756bd18bd71599 Mon Sep 17 00:00:00 2001
From: Novus Nota <68142933+novusnota@users.noreply.github.com>
Date: Fri, 17 May 2024 21:56:21 +0200
Subject: [PATCH 22/24] chore: almost nothing throws for core-string
---
pages/ref/core-strings.mdx | 10 +++++-----
1 file changed, 5 insertions(+), 5 deletions(-)
diff --git a/pages/ref/core-strings.mdx b/pages/ref/core-strings.mdx
index e7d01108..df9a9e83 100644
--- a/pages/ref/core-strings.mdx
+++ b/pages/ref/core-strings.mdx
@@ -217,7 +217,7 @@ Extension function for the [`String{:tact}`][p].
Returns a [`Slice{:tact}`][p] out of the decoded [Base64](https://en.wikipedia.org/wiki/Base64) [`String{:tact}`][p]. Alias to `self.asSlice().fromBase64(){:tact}`.
-Note, that this function is very limited and can be used only for small strings that fit in a single [`Cell{:tact}`][p] (i.e., strings that contain no more than 1023 bits of data).
+Note, that this function is limited and only takes the first $1023$ bits of data from the given [`String{:tact}`][p], without throwing an exception when the [`String{:tact}`][p] is larger (i.e. contains more than $1023$ bits of data).
Usage example:
@@ -239,7 +239,7 @@ Extension function for the [`Slice{:tact}`][p].
Returns a [`String{:tact}`][p] from a [`Slice{:tact}`][p] by trying to load all of its bits without looking for its references, if any.
-Note, that this function doesn't look at the references at all and is truncates its output to 1023 bits, so use it only if you know what you're doing.
+Note, that this function doesn't look at the references at all and is truncates its output to $1023$ bits, so use it only if you know what you're doing.
Usage example:
@@ -259,9 +259,9 @@ extends fun fromBase64(self: Slice): Slice;
Extension function for the [`Slice{:tact}`][p].
-Returns a [`Slice{:tact}`][p] out of the decoded [Base64](https://en.wikipedia.org/wiki/Base64) [`Slice{:tact}`][p].
+Returns a new [`Slice{:tact}`][p] out of the decoded [Base64](https://en.wikipedia.org/wiki/Base64) [`Slice{:tact}`][p].
-Note, that this function doesn't load [`Cell{:tact}`][p] references, which makes it limited to only 1023 bits of data.
+Note, that this function is limited and only takes the first $1023$ bits of data from the given [`Slice{:tact}`][p], without throwing an exception if the [`Slice{:tact}`][p] has more data (i.e., when it has any references).
Usage example:
@@ -296,7 +296,7 @@ Extension function for the [`Int{:tact}`][int].
Returns a [`String{:tact}`][p] from an [`Int{:tact}`][int] value using a [fixed-point representation](https://en.wikipedia.org/wiki/Fixed-point_arithmetic) of a fractional number, where `self` is a significant part of the number and `digits` is a number of digits in the fractional part.
-More precisely, `digits` is an exponentiation parameter of $10^{-\mathrm{digits}}$ expression, which gives the represented fractional number when multiplied by the actual [`Int{:tact}`][int] value. Parameter `digits` is required to be in the semi-closed interval: $0 <=$ `digits` $< 77$.
+More precisely, `digits` is an exponentiation parameter of $10^{-\mathrm{digits}}$ expression, which gives the represented fractional number when multiplied by the actual [`Int{:tact}`][int] value. Parameter `digits` is required to be in the semi-closed interval: $0 <=$ `digits` $< 78$, otherwise an exception with [exit code 134](/book/exit-codes#134) will be thrown: `Invalid argument`.
Usage example:
From 92203b0973dc3dba014064ce8fa4716cdab8e4eb Mon Sep 17 00:00:00 2001
From: Novus Nota <68142933+novusnota@users.noreply.github.com>
Date: Mon, 20 May 2024 12:29:43 +0200
Subject: [PATCH 23/24] feat: done!
---
pages/ref/core-cells.mdx | 186 +++++++++++++++++++++++++++++++++------
1 file changed, 159 insertions(+), 27 deletions(-)
diff --git a/pages/ref/core-cells.mdx b/pages/ref/core-cells.mdx
index 0861ce6e..38a04e1a 100644
--- a/pages/ref/core-cells.mdx
+++ b/pages/ref/core-cells.mdx
@@ -4,6 +4,14 @@ import { Callout } from 'nextra-theme-docs'
Cells is a low level primitive that represents data in TON blockchain. Cell consists of a 1023 bits of data with up to 4 references to another Cells. Cells are read-only and immutable. Builders are immutable structures that can be used to construct Cells. Slices are a way to parse cells.
+
+
+ Be very careful when constructing and parsing cells, and always make sure to document their desired layout: a strict order of values and types for serialization and deserialization.
+
+ To do so, advanced users are recommended to use [Type Language - Binary (`TL-B`) schemes](https://docs.ton.org/develop/data-formats/tl-b-language).
+
+
+
## beginCell
```tact
@@ -43,7 +51,9 @@ extends fun storeUint(self: Builder, value: Int, bits: Int): Builder;
Extension function for the [`Builder{:tact}`][p].
-Stores an unsigned `bits`-bit `value` into the [`Builder{:tact}`][p] for $0 ≤ bits ≤ 256$. Returns modified [`Builder{:tact}`][p].
+Stores an unsigned `bits`-bit `value` into the copy of the [`Builder{:tact}`][p] for $0 ≤$ `bits` $≤ 256$. Returns that copy.
+
+Attempts to store a negative `value` or provide an unsufficient or out-of-bounds `bits` number throw an exception with [exit code 5](/book/exit-codes#5): `Integer out of expected range`.
Usage example:
@@ -60,7 +70,9 @@ extends fun storeInt(self: Builder, value: Int, bits: Int): Builder;
Extension function for the [`Builder{:tact}`][p].
-Stores a signed `bits`-bit `value` into the [`Builder{:tact}`][p] for $0 ≤ bits ≤ 257$. Returns modified [`Builder{:tact}`][p].
+Stores a signed `bits`-bit `value` into the copy of the [`Builder{:tact}`][p] for $0 ≤$ `bits` $≤ 257$. Returns that copy.
+
+Attempts to provide an unsufficient or out-of-bounds `bits` number throw an exception with [exit code 5](/book/exit-codes#5): `Integer out of expected range`.
Usage example:
@@ -77,7 +89,7 @@ extends fun storeBool(self: Builder, value: Bool): Builder;
Extension function for the [`Builder{:tact}`][p].
-Stores a [`Bool{:tact}`][bool] `value` into the [`Builder{:tact}`][p]. Writes `-1` if `value` is `true{:tact}`, and writes `0` otherwise. Returns modified [`Builder{:tact}`][p].
+Stores a [`Bool{:tact}`][bool] `value` into the copy of the [`Builder{:tact}`][p]. Writes $-1$ if `value` is `true{:tact}`, and writes $0$ otherwise. Returns that copy of the [`Builder{:tact}`][p].
Usage example:
@@ -95,7 +107,7 @@ extends fun storeSlice(self: Builder, cell: Slice): Builder;
Extension function for the [`Builder{:tact}`][p].
-Stores a [`Slice{:tact}`][p] `cell` into the [`Builder{:tact}`][p]. Returns modified [`Builder{:tact}`][p].
+Stores a [`Slice{:tact}`][p] `cell` into the copy of the [`Builder{:tact}`][p]. Returns that copy.
Usage example:
@@ -113,9 +125,11 @@ extends fun storeCoins(self: Builder, value: Int): Builder;
Extension function for the [`Builder{:tact}`][p].
-Stores (serializes) an integer `value` in the range $0 .. 2^{120} − 1$ into the [`Builder{:tact}`][p]. The serialization of `value` consists of a 4-bit unsigned big-endian integer $l$, which is the smallest integer $l ≥ 0$, such that `value` $< 2^{8 * l}$, followed by an $8 * l$-bit unsigned big-endian representation of `value`. If `value` does not belong to the supported range, a range check exception is thrown. Returns modified [`Builder{:tact}`][p].
+Stores (serializes) an unsigned [`Int{:tact}`][int] `value` in the range $0 .. 2^{120} − 1$ into the copy of the [`Builder{:tact}`][p]. The serialization of `value` consists of a 4-bit unsigned big-endian integer $l$, which is the smallest integer $l ≥ 0$, such that `value` $< 2^{8 * l}$, followed by an $8 * l$-bit unsigned big-endian representation of `value`. If `value` does not belong to the supported range, a range check exception is thrown. Returns that copy of the [`Builder{:tact}`][p].
+
+Attempts to store an out-of-bounds `value` throw an exception with [exit code 5](/book/exit-codes#5): `Integer out of expected range`.
-This is the most common way of storing Toncoins.
+This is the most common way of storing nanoToncoins.
Usage example:
@@ -132,7 +146,7 @@ extends fun storeAddress(self: Builder, address: Address): Builder;
Extension function for the [`Builder{:tact}`][p].
-Stores the `address` in the [`Builder{:tact}`][p]. Returns modified [`Builder{:tact}`][p].
+Stores the `address` in the copy of the [`Builder{:tact}`][p]. Returns that copy.
Usage example:
@@ -149,7 +163,9 @@ extends fun storeRef(self: Builder, cell: Cell): Builder;
Extension function for the [`Builder{:tact}`][p].
-Stores a reference `cell` into the [`Builder{:tact}`][p]. Returns modified [`Builder{:tact}`][p].
+Stores a reference `cell` into the copy of the [`Builder{:tact}`][p]. Returns that copy.
+
+As a single [`Cell{:tact}`][p] can store up to $4$ references, attempts to store more throw an exception with [exit code 8](/book/exit-codes#8): `Cell overflow`.
Usage example:
@@ -200,7 +216,7 @@ extends fun asSlice(self: Builder): Slice;
Extension function for the [`Builder{:tact}`][p].
-Converts the [`Builder{:tact}`][p] to a [`Slice{:tact}`][p]. Alias to `self.endCell().beginParse(){:tact}`.
+Converts the [`Builder{:tact}`][p] to a [`Slice{:tact}`][p] and returns it. Alias to `self.endCell().beginParse(){:tact}`.
Usage example:
@@ -217,7 +233,7 @@ extends fun asCell(self: Builder): Cell;
Extension function for the [`Builder{:tact}`][p].
-Converts the [`Builder{:tact}`][p] to a [`Cell{:tact}`][p]. Alias to `self.endCell(){:tact}`.
+Converts the [`Builder{:tact}`][p] to a [`Cell{:tact}`][p] and returns it. Alias to `self.endCell(){:tact}`.
Usage example:
@@ -251,7 +267,7 @@ extends fun hash(self: Cell): Int;
Extension function for the [`Cell{:tact}`][p].
-Calculates hash of the [`Cell{:tact}`][p] as an [`Int{:tact}`][int].
+Calculates and returns a hash of the [`Cell{:tact}`][p] as an [`Int{:tact}`][int].
Usage example:
@@ -268,7 +284,7 @@ extends fun asSlice(self: Cell): Slice;
Extension function for the [`Cell{:tact}`][p].
-Converts the Cell to a [`Slice{:tact}`][p]. Alias to `self.beginParse(){:tact}`.
+Converts the Cell to a [`Slice{:tact}`][p] and returns it. Alias to `self.beginParse(){:tact}`.
Usage example:
@@ -285,7 +301,11 @@ extends mutates fun loadUint(self: Slice, l: Int): Int;
Extension mutation function for the [`Slice{:tact}`][p].
-Loads an unsigned `l`-bit [`Int{:tact}`][int] from the [`Slice{:tact}`][p].
+Loads and returns an unsigned `l`-bit [`Int{:tact}`][int] from the [`Slice{:tact}`][p] for $0 ≤$ `l` $≤ 256$.
+
+Attempts to specify an out-of-bounds `l` value throw an exception with [exit code 5](/book/exit-codes#5): `Integer out of expected range`.
+
+Attempts to load more data than [`Slice{:tact}`][p] contains throw an exception with [exit code 9](/book/exit-codes#9): `Cell underflow`.
Usage example:
@@ -302,7 +322,11 @@ extends fun preloadUint(self: Slice, l: Int): Int;
Extension function for the [`Slice{:tact}`][p].
-Preloads an unsigned `l`-bit [`Int{:tact}`][int] from the [`Slice{:tact}`][p] without changing its data.
+Preloads and returns an unsigned `l`-bit [`Int{:tact}`][int] from the [`Slice{:tact}`][p] for $0 ≤$ `l` $≤ 256$. Doesn't modify the [`Slice{:tact}`][p].
+
+Attempts to specify an out-of-bounds `l` value throw an exception with [exit code 5](/book/exit-codes#5): `Integer out of expected range`.
+
+Attempts to preload more data than [`Slice{:tact}`][p] contains throw an exception with [exit code 9](/book/exit-codes#9): `Cell underflow`.
Usage example:
@@ -319,7 +343,11 @@ extends mutates fun loadInt(self: Slice, l: Int): Int;
Extension mutation function for the [`Slice{:tact}`][p].
-Loads a signed `l`-bit [`Int{:tact}`][int] from the [`Slice{:tact}`][p].
+Loads and returns a signed `l`-bit [`Int{:tact}`][int] from the [`Slice{:tact}`][p] for $0 ≤$ `l` $≤ 257$.
+
+Attempts to specify an out-of-bounds `l` value throw an exception with [exit code 5](/book/exit-codes#5): `Integer out of expected range`.
+
+Attempts to load more data than [`Slice{:tact}`][p] contains throw an exception with [exit code 9](/book/exit-codes#9): `Cell underflow`.
Usage example:
@@ -336,7 +364,11 @@ extends fun preloadInt(self: Slice, l: Int): Int;
Extension function for the [`Slice{:tact}`][p].
-Preloads a signed `len`-bit [`Int{:tact}`][int] from the [`Slice{:tact}`][p] without changing its data.
+Preloads and returns a signed `l`-bit [`Int{:tact}`][int] from the [`Slice{:tact}`][p] for $0 ≤$ `l` $≤ 257$. Doesn't modify the [`Slice{:tact}`][p].
+
+Attempts to specify an out-of-bounds `l` value throw an exception with [exit code 5](/book/exit-codes#5): `Integer out of expected range`.
+
+Attempts to preload more data than [`Slice{:tact}`][p] contains throw an exception with [exit code 9](/book/exit-codes#9): `Cell underflow`.
Usage example:
@@ -353,7 +385,11 @@ extends mutates fun loadBits(self: Slice, l: Int): Slice;
Extension mutation function for the [`Slice{:tact}`][p].
-Loads the first $0 ≤ l ≤ 1023$ bits from the [`Slice{:tact}`][p], and returns it as a separate [`Slice{:tact}`][p].
+Loads $0 ≤$ `l` $≤ 1023$ bits from the [`Slice{:tact}`][p], and returns them as a separate [`Slice{:tact}`][p].
+
+Attempts to specify an out-of-bounds `l` value throw an exception with [exit code 5](/book/exit-codes#5): `Integer out of expected range`.
+
+Attempts to load more data than [`Slice{:tact}`][p] contains throw an exception with [exit code 9](/book/exit-codes#9): `Cell underflow`.
Usage example:
@@ -370,7 +406,11 @@ extends fun preloadBits(self: Slice, l: Int): Slice;
Extension function for the [`Slice{:tact}`][p].
-Preloads the first $0 ≤ l ≤ 1023$ bits from the Slice, and returns it as a separate [`Slice{:tact}`][p] without changing its data.
+Preloads $0 ≤$ `l` $≤ 1023$ bits from the [`Slice{:tact}`][p], and returns them as a separate [`Slice{:tact}`][p]. Doesn't modify the original [`Slice{:tact}`][p].
+
+Attempts to specify an out-of-bounds `l` value throw an exception with [exit code 5](/book/exit-codes#5): `Integer out of expected range`.
+
+Attempts to preload more data than [`Slice{:tact}`][p] contains throw an exception with [exit code 9](/book/exit-codes#9): `Cell underflow`.
Usage example:
@@ -379,6 +419,34 @@ let s: Slice = beginCell().storeInt(42, 7).asSlice();
let fizz: Slice = s.preloadBits(7);
```
+## Slice.skipBits
+
+```tact
+extends mutates fun skipBits(self: Slice, l: Int): Slice;
+```
+
+Extension mutation function for the [`Slice{:tact}`][p].
+
+Loads all but the first $0 ≤$ `l` $≤ 1023$ bits from the [`Slice{:tact}`][p], and returns them as a separate [`Slice{:tact}`][p].
+
+Attempts to specify an out-of-bounds `l` value throw an exception with [exit code 5](/book/exit-codes#5): `Integer out of expected range`.
+
+Attempts to load more data than [`Slice{:tact}`][p] contains throw an exception with [exit code 9](/book/exit-codes#9): `Cell underflow`.
+
+Usage example:
+
+```tact
+let s: Slice = beginCell().storeInt(42, 7).asSlice();
+s.skipBits(5); // all but first 5 bits
+let fizz: Slice = s.loadBits(1); // load only 1 bit
+```
+
+
+
+ At the moment, one cannot store the results of this function in a variable, because its a wrapper over native FunC function and its return type isn't compatible with Tact yet.
+
+
+
## Slice.loadCoins
```tact
@@ -387,7 +455,11 @@ extends mutates fun loadCoins(self: Slice): Int;
Extension mutation function for the [`Slice{:tact}`][p].
-Loads serialized amount of nanoToncoins (any unsigned integer up to $2^{120} - 1$) as an [`Int{:tact}`][int].
+Loads and returns [serialized](#builderstorecoins) an unsigned [`Int{:tact}`][int] value in the range $0 .. 2^{120} - 1$ from the [`Slice{:tact}`][p]. This values usually represents the amount in nanoToncoins.
+
+Attempts to load such [`Int{:tact}`][int] when [`Slice{:tact}`][p] doesn't contain it throw an exception with [exit code 8](/book/exit-codes#8): `Cell overflow`.
+
+Attempts to load more data than [`Slice{:tact}`][p] contains throw an exception with [exit code 9](/book/exit-codes#9): `Cell underflow`.
Usage example:
@@ -404,7 +476,11 @@ extends mutates fun loadAddress(self: Slice): Address;
Extension mutation function for the [`Slice{:tact}`][p].
-Loads an [`Address{:tact}`][p] from the [`Slice{:tact}`][p].
+Loads and returns an [`Address{:tact}`][p] from the [`Slice{:tact}`][p].
+
+Attempts to load such [`Address{:tact}`][p] when [`Slice{:tact}`][p] doesn't contain it throw an exception with [exit code 8](/book/exit-codes#8): `Cell overflow`.
+
+Attempts to load more data than [`Slice{:tact}`][p] contains throw an exception with [exit code 9](/book/exit-codes#9): `Cell underflow`.
Usage example:
@@ -421,13 +497,24 @@ extends mutates fun loadRef(self: Slice): Cell;
Extension mutation function for the [`Slice{:tact}`][p].
-Loads the first reference from the [`Slice{:tact}`][p] as a [`Cell{:tact}`][p].
+Loads the next reference from the [`Slice{:tact}`][p] as a [`Cell{:tact}`][p].
-Usage example:
+Attempts to load such reference [`Cell{:tact}`][p] when [`Slice{:tact}`][p] doesn't contain it throw an exception with [exit code 8](/book/exit-codes#8): `Cell overflow`.
+
+Attempts to load more data than [`Slice{:tact}`][p] contains throw an exception with [exit code 9](/book/exit-codes#9): `Cell underflow`.
+
+Usage examples:
```tact
let s: Slice = beginCell().storeRef(emptyCell()).asSlice();
let fizz: Cell = s.loadRef();
+
+let s: Slice = beginCell()
+ .storeRef(emptyCell())
+ .storeRef(emptyCell())
+ .asSlice();
+let ref1: Cell = s.loadRef();
+let ref2: Cell = s.loadRef();
```
## Slice.refs
@@ -482,6 +569,12 @@ let fizz: Bool = s.empty(); // false
let buzz: Bool = beginCell().asSlice().empty(); // true
```
+
+
+ Unlike [`Slice.endParse(){:tact}`](#sliceendparse), this function doesn't throw any exceptions even when the [`Slice{:tact}`][p] is empty.
+
+
+
## Slice.dataEmpty
```tact
@@ -520,6 +613,28 @@ let fizz: Bool = s.refsEmpty(); // false
let buzz: Bool = beginCell().asSlice().refsEmpty(); // true
```
+## Slice.endParse
+
+```tact
+extends fun endParse(self: Slice);
+```
+
+Extension function for the [`Slice{:tact}`][p].
+
+Checks whether the [`Slice{:tact}`][p] is empty (i.e., contains no bits of data and no cell references). If it's not, throws an exception with [exit code 9](/book/exit-codes#9): `Cell underflow`.
+
+Usage examples:
+
+```tact {2,6}
+let emptyOne: Slice = emptySlice();
+emptyOne.endParse(); // nothing, as it's empty
+
+let paul: Slice = "Fear is the mind-killer".asSlice();
+try {
+ paul.endParse(); // throws exit code 9
+}
+```
+
## Slice.hash
```tact
@@ -528,7 +643,7 @@ extends fun hash(self: Slice): Int;
Extension function for the [`Slice{:tact}`][p].
-Calculates hash of the [`Slice{:tact}`][p] as an [`Int{:tact}`][int].
+Calculates and returns a hash of the [`Slice{:tact}`][p] as an [`Int{:tact}`][int].
Usage example:
@@ -545,7 +660,7 @@ extends fun asCell(self: Slice): Cell;
Extension function for the [`Slice{:tact}`][p].
-Converts the [`Slice{:tact}`][p] to a [`Cell{:tact}`][p]. Alias to `beginCell().storeSlice(self).endCell(){:tact}`.
+Converts the [`Slice{:tact}`][p] to a [`Cell{:tact}`][p] and returns it. Alias to `beginCell().storeSlice(self).endCell(){:tact}`.
Usage example:
@@ -565,7 +680,7 @@ extends fun asSlice(self: Address): Slice;
Extension function for the [`Address{:tact}`][p].
-Converts the [`Address{:tact}`][p] to a [`Slice{:tact}`][p]. Alias to `beginCell().storeAddress(self).asSlice(){:tact}`.
+Converts the [`Address{:tact}`][p] to a [`Slice{:tact}`][p] and returns it. Alias to `beginCell().storeAddress(self).asSlice(){:tact}`.
Usage example:
@@ -585,7 +700,7 @@ extends fun toCell(self: Struct): Cell;
Extension function for any [Struct][struct].
-Converts the [Struct][struct] to a [`Cell{:tact}`][p].
+Converts the [Struct][struct] to a [`Cell{:tact}`][p] and returns it.
Usage example:
@@ -611,7 +726,7 @@ extends fun toCell(self: Message): Cell;
Extension function for any [Message][message].
-Converts the [Message][message] to a [`Cell{:tact}`][p].
+Converts the [Message][message] to a [`Cell{:tact}`][p] and returns it.
Usage example:
@@ -646,6 +761,23 @@ let buzz: Cell = beginCell().endCell();
fizz == buzz; // true
```
+## emptySlice
+
+```tact
+fun emptySlice(): Slice;
+```
+
+Creates and returns an empty [`Slice{:tact}`][p] (without data and references). Alias to `emptyCell().asSlice(){:tact}`.
+
+Usage example:
+
+```tact
+let fizz: Slice = emptySlice();
+let buzz: Slice = emptyCell().asSlice();
+
+fizz == buzz; // true
+```
+
[p]: /book/types#primitive-types
[bool]: /book/types#booleans
[int]: /book/integers
From b1eb045928a52c4233a5ea9fe08674b7c7e93f51 Mon Sep 17 00:00:00 2001
From: Novus Nota <68142933+novusnota@users.noreply.github.com>
Date: Mon, 20 May 2024 12:56:51 +0200
Subject: [PATCH 24/24] fix: clarify
---
pages/ref/core-cells.mdx | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/pages/ref/core-cells.mdx b/pages/ref/core-cells.mdx
index 38a04e1a..63849919 100644
--- a/pages/ref/core-cells.mdx
+++ b/pages/ref/core-cells.mdx
@@ -427,7 +427,7 @@ extends mutates fun skipBits(self: Slice, l: Int): Slice;
Extension mutation function for the [`Slice{:tact}`][p].
-Loads all but the first $0 ≤$ `l` $≤ 1023$ bits from the [`Slice{:tact}`][p], and returns them as a separate [`Slice{:tact}`][p].
+Loads all but the first $0 ≤$ `l` $≤ 1023$ bits from the [`Slice{:tact}`][p], and returns skipped bits in a separate [`Slice{:tact}`][p].
Attempts to specify an out-of-bounds `l` value throw an exception with [exit code 5](/book/exit-codes#5): `Integer out of expected range`.