跳到主要内容

Writing to the network

In the previous section, you learned how to read data from the TON Blockchain. Now, let's explore how to write data to it.

Introduction

This guide will walk you through writing data from the TON Blockchain. You'll learn how to:

  • Make transaction
  • Transfer TON/NFT

Setup environment

First, visit installation pages and install NodeJS and npm for your OS. Check that installation is correct by running those commands:

node -v
npm -v

Version of node and npm should be at least v20 and v10 correspondingly.

Project setup

Let's set up our project structure:

  1. Create a new directory for your project
  2. Initialize a Node.js project
  3. Install required dependencies

Run these commands in your terminal:

mkdir writing-to-ton && cd writing-to-ton # create new directory and cd to it
npm init -y # initialize Node.js project
npm install typescript ts-node @ton/ton @ton/core @ton/crypto #install required dependecies
npx tsc --init # initialize typesctipt

To run scripts, use the following command:

npx ts-node script.ts

Sending TON

The simplest interaction between two accounts in TON Blockchain is a TON transfer. The process involves preparing and signing a transaction, and then sending it to the blockchain.

A common transfer would look like this:



警告

Unlike in the Reading from the Network section, a Toncenter API key is mandatory in the following examples. It may be retrieved using following guide.

Implementation

Create a new file 1-send-ton.ts:

1-send-ton.ts
import { mnemonicToWalletKey } from "@ton/crypto";
import { comment, internal, toNano, TonClient, WalletContractV3R2, WalletContractV4, WalletContractV5R1 } from "@ton/ton";
import { SendMode } from "@ton/core";

async function main() {
// Initializing tonClient for sending messages to blockchain
const tonClient = new TonClient({
endpoint: 'https://testnet.toncenter.com/api/v2/jsonRPC',
apiKey: 'YOUR_API_KEY', //acquire it from: https://t.me/toncenter
});

// Using mnemonic to derive public and private keys
// ATTENTION! Replace on your own mnemonic 24-word phrase that you get from wallet app!
const mnemonic = "swarm trumpet innocent empty faculty banner picnic unique major taste cigar slogan health neither diary monster jar scale multiply result biology champion genuine outside".split(' ');
const { publicKey, secretKey } = await mnemonicToWalletKey(mnemonic);

// Creating wallet depending on version (v5r1 or v4 or V3R2), uncomment which version do you have
const walletContract = WalletContractV5R1.create({ walletId: { networkGlobalId: -3 }, publicKey }); // networkGlobalId: -3 for testnet, -239 for mainnet
//const walletContract = WalletContractV4.create({ workchain: 0, publicKey });
//const walletContract = WalletContractV3R2.create({ workchain: 0, publicKey });

// Opening wallet with tonClient, which allows to send messages to blockchain
const wallet = tonClient.open(walletContract);

// Retrieving seqno used for replay protection
const seqno = await wallet.getSeqno();

// Sending transfer
await wallet.sendTransfer({
seqno,
secretKey,
messages: [internal({
to: wallet.address, // Transfer will be made to the same wallet address
body: comment('Hello from wallet!'), // Transfer will contain comment
value: toNano(0.05), // Amount of TON, attached to transfer
})],
sendMode: SendMode.PAY_GAS_SEPARATELY | SendMode.IGNORE_ERRORS,
});
}

main();

Using API_KEY in this case allows to have access to TON functionality by itself through endpoint. By running those script we authntificate to our wallet through public/private key pair generated through mnemonic phrase and, after preparing a transaction, send it TON, resulting in message that wallet sends to itself with 'Hello from wallet!' message.

Advanced Level

In most scenarios, SendMode.PAY_GAS_SEPARATELY | SendMode.IGNORE_ERRORS will work, but if you want a deeper understanding, continue reading in the message modes cookbook.

Run this example using following command:

npx ts-node 1-send-ton.ts

Expected result

Navigate to Tonviewer and paste your address into search bar. You should see TON transfer with 'Hello from wallet!' comment.

Sending NFTs

Non-fungible tokens (NFTs) are assets like a piece of art, digital content, or video that have been tokenized via a blockchain. In TON, NFTs are represented via a collection of smart contracts:

  • NFT Collection: stores information about the NFT collection.
  • NFT Item: stores information about the NFT item that the user owns.

To send NFT we should first acquire one. The easiest way to do that is to create and deploy your own NFT through TON Tools. Note that owner addresses of your NFT must be your wallet address to be able to perform operations on it.

Basic operation of NFT standard in TON is transfer. What is actually performed is changing adress of owner in NFT storage to new owner, which is address of another contract that is able to perform operations with NFT Item now.

提示

See Actors and roles to get more conceptual description.

Implementation

Create a new file 2-send-nft.ts:

2-send-nft.ts
import { mnemonicToWalletKey } from "@ton/crypto";
import { Address, beginCell, comment, internal, toNano, TonClient, WalletContractV5R1 } from "@ton/ton";
import { SendMode } from "@ton/core";


async function main() {
const tonClient = new TonClient({
endpoint: 'https://testnet.toncenter.com/api/v2/jsonRPC',
apiKey: 'YOUR_API_KEY', //acquire it from: https://t.me/toncenter
});

// Using mnemonic to derive public and private keys
// ATTENTION! Replace on your own mnemonic 24-word phrase that you get from wallet app!
const mnemonic = "swarm trumpet innocent empty faculty banner picnic unique major taste cigar slogan health neither diary monster jar scale multiply result biology champion genuine outside".split(' ');
// Remember that it should be mnemonic of the wallet that you have made an owner of NFT

const { publicKey, secretKey } = await mnemonicToWalletKey(mnemonic);
const walletContract = WalletContractV5R1.create({ walletId: { networkGlobalId: -3 }, publicKey });
const wallet = tonClient.open(walletContract);
const seqno = await wallet.getSeqno();

const nftTransferBody = beginCell()
.storeUint(0x5fcc3d14, 32) // opcode for nft transfer
.storeUint(0, 64) // query id
.storeAddress(wallet.address) // address to transfer ownership to
.storeAddress(wallet.address) // response destination
.storeBit(0) // no custom payload
.storeCoins(1) // forward amount - if >0, will send notification message
.storeMaybeRef(comment('Hello from NFT!'))
.endCell();

//The one that you have acquired from https://ton-collection-edit.vercel.app/deploy-nft-single
const nftAddress = Address.parse('YOUR_NFT_ADDRESS');
// Sending NFT transfer
await wallet.sendTransfer({
seqno,
secretKey,
messages: [internal({
to: nftAddress,
body: nftTransferBody,
value: toNano(0.05),
})],
sendMode: SendMode.PAY_GAS_SEPARATELY | SendMode.IGNORE_ERRORS,
});
}
main();

Run this example using following command:

npx ts-node 2-send-nft.ts

Expected result

Navigate to Tonviewer and paste your address into search bar. You should see NFT transfer with 'Hello from NFT!' comment.

Was this article useful?