Receive messages
TON is a distributed blockchain which means that communication between contracts is done by sending and receiving messages. The most common type of message is the internal message - a message sent from one contract (or a wallet) to another.
Receive internal messages
To receive a message of the required type, you need to declare a receiver function, for example, receive("increment")
. This notation means the declaration of a receiver function that will be called when a text with the value "increment"
is sent to the contract. The function body can modify the state of the contract and send messages to other contracts. It is impossible to call a receiver directly. If you need to reuse some logic you can declare a function and call it from the receiver.
There are several receiver functions. All receiver functions are processed in the order they are listed below:
receive()
- called when an empty message is sent to the contractreceive("message")
- called when a text message with a specific comment is sent to the contractreceive(str: String)
- called when an arbitrary text message is sent to the contractreceive(msg: MyMessage)
- called when a binary message of typeMyMessage
is sent to the contractreceive(msg: Slice)
- called when binary message of unknown type is sent to the contract
message MyMessage {
value: Int;
}
contract MyContract {
receive() {
// ...
}
receive("message") {
// ...
}
receive(str: String) {
// ...
}
receive(msg: MyMessage) {
// ...
}
receive(msg: Slice) {
// ...
}
}
Naming a parameter of the receiver function with an underscore _
makes its value considered unused and discarded. This is useful when you don't need to inspect the message received and you only want it to convey a specific opcode:
message(42) UniverseCalls {}
contract Example {
receive(_: UniverseCalls) {
// Got a Message with opcode 42
}
}