单项合约通信
本页列出了单个已部署合约与区块链上其他合约进行通信的示例。
有关多个已部署合约之间的通信示例,请参阅:多合约通信。
如何进行基本回复
contract Example { receive() { self.reply("Hello, World!".asComment()); // asComment converts a String to a Cell with a comment }}
如何发送简单信息
contract Example { receive() { send(SendParameters{ bounce: true, // default to: sender(), // or another destination address value: ton("0.01"), // attached amount of Tons to send body: "Hello from Tact!".asComment(), // comment (optional) }); }}
如何发送包含全部余额的信息
如果我们需要发送智能合约的全部余额,则应使用 SendRemainingBalance
发送模式。 或者,我们也可以使用 mode:128
,其含义相同。
contract Example { receive() { send(SendParameters{ // bounce = true by default to: sender(), // send the message back to the original sender value: 0, mode: SendRemainingBalance, // or mode: 128 body: "Hello from Tact!".asComment(), // comment (optional) }); }}
如何发送带有余值的信息
如果我们要向同一发件人发送回复,可以使用 SendRemainingValue
模式(即 mode: 64
),除了新信息中最初显示的值外,它还会携带入站信息的所有剩余值。
contract Example { receive() { send(SendParameters{ // bounce = true by default to: sender(), // send the message back to the original sender value: 0, mode: SendRemainingValue, body: "Hello from Tact!".asComment(), // comment (optional) }); }}
通常还需要添加 SendIgnoreErrors
标记,以便忽略在操作阶段处理该消息时出现的任何错误
contract Example { receive() { send(SendParameters{ // bounce = true by default to: sender(), // send the message back to the original sender value: 0, mode: SendRemainingValue | SendIgnoreErrors, // prefer using | over + for the mode body: "Hello from Tact!".asComment(), // comment (optional) }); }}
后一个示例与使用 .reply()
函数相同。
如何发送带有长文本注释的信息
如果我们需要发送一条带有冗长文本注释的信息,我们应该创建一个 String
,由超过 个字符组成。 如果我们需要发送一条带有冗长文本注释的信息,我们应该创建一个 String
,由超过 个字符组成。 为此,我们可以利用 StringBuilder
原始类型及其名为 beginComment()
和 append()
的方法。 在发送之前,我们应该使用 toCell()
方法将字符串转换为cell。 在发送之前,我们应该使用 toCell()
方法将字符串转换为cell。
contract Example { receive() { let comment: StringBuilder = beginComment(); let longString = "..."; // Some string with more than 127 characters. comment.append(longString);
send(SendParameters{ // bounce = true by default to: sender(), value: 0, mode: SendIgnoreErrors, body: comment.toCell(), }); }}