To interact with the TON blockchain, you must initialize a TonClient with an HTTP API endpoint. You can use public endpoints for Mainnet or Testnet.
Common workflow:
- Initialize Client: Use
new TonClient({ endpoint: '...' }). - Manage Keys: Use
@ton/crypto to generate mnemonics and private keys. - Open Wallet: Use
WalletContractV4.create to define the wallet and client.open(wallet) to create a contract instance that can interact with the blockchain. - Get Balance: Call
contract.getBalance(). - Transfer Funds: Retrieve the current
seqno via contract.getSeqno(), then use contract.createTransfer with an array of internal messages.
import { TonClient, WalletContractV4, internal } from "@ton/ton";
import { mnemonicNew, mnemonicToPrivateKey } from "@ton/crypto";
// Create Client
const client = new TonClient({
endpoint: 'https://toncenter.com/api/v2/jsonRPC',
});
// Generate new key
const mnemonic = await mnemonicNew();
const keyPair = await mnemonicToPrivateKey(mnemonic);
// Create wallet contract
const wallet = WalletContractV4.create({
workchain: 0, // basechain
publicKey: keyPair.publicKey,
});
const contract = client.open(wallet);
// Get balance
const balance = await contract.getBalance();
// Create a transfer
const seqno = await contract.getSeqno();
const transfer = await contract.createTransfer({
seqno,
secretKey: keyPair.secretKey,
messages: [internal({
value: '1.5',
to: 'EQCD39VS5jcptHL8vMjEXrzGaRcCVYto7HUn4bpAOg8xqB2N',
body: 'Hello world',
})]
});