The Open Network (TON) is a decentralized and open platform comprising several components, including TON Blockchain, TON DNS, TON Storage, and TON Sites. Originally developed by the Telegram team, TON aims to provide fast, secure, and user-friendly decentralized services. Its core protocol, TON Blockchain, connects the underlying infrastructure to form the greater TON Ecosystem.
TON is focused on achieving widespread cross-chain interoperability within a highly scalable and secure framework. Designed as a distributed supercomputer or “superserver,” TON provides various products and services to contribute to developing the decentralized vision for the new internet. This makes it well-suited for a wide range of decentralized applications.
One of the unique features of TON smart contracts is that they can receive messages and do some action based on it; we’ll leverage this in the smart contract we’ll develop.
This tutorial will guide you through creating, building, testing, deploying, and interacting with a simple storage contract on the TON blockchain. We’ll use the Blueprint SDK.
The Blueprint SDK is an essential tool for developers working with the TON blockchain. It provides a comprehensive suite of tools and libraries that simplify the process of writing, testing, and deploying smart contracts.
Start for free and get your app to production levels immediately. No credit card required. You can sign up with your GitHub, X, Google, or Microsoft account.
This will be an introductory project where we use the Blueprint SDK to develop, test, and deploy a simple storage-style smart contract where we can save a number and increment a counter.
The smart contract is written in the TACT language, TON’s smart contract language, and is comparable to Solidity for EVM-based chains.
Let’s create a new TON project and run the initialization command in a new directory.
Copy
npm create ton@latest
Select an empty project in TACT.
When you create a new project using the Blueprint SDK, the directory structure is organized to help you efficiently manage your smart contract development process. Here’s a brief overview of the main directories and their purposes:
build/: This directory contains the compiled artifacts of your smart contracts. After you run the build command, the output files will be stored here, including the compiled contract bytecode and other related artifacts.
contracts/: This is where you write your smart contracts. All .tact files containing the contract code are placed in this directory. For instance, the SimpleStorage contract will reside here.
scripts/: This directory is used for deployment and interaction scripts. These scripts facilitate deploying your contracts to the TON blockchain and interacting with them. For example, scripts to deploy the contract or fetch data from the contract will be placed here.
tests/: This directory holds the test files for your smart contracts. Here, you can write tests to ensure your contracts behave as expected. The default test script verifies contract deployment, and you can extend it to test additional functionalities.
wrappers/: This directory contains the TypeScript wrappers generated for your contracts. These wrappers provide a convenient way to interact with your contracts in a type-safe manner from your scripts and tests.
Now, we are ready to start developing the contract. You’ll find a .tact contract in the contracts directory, paste the following code in it.
Copy
import "@stdlib/deploy";// Allows the contract to receive a custom object of type "Save" specifying the number to save in the contract.message Save { amount: Int as uint32;}// This is an example of a simple storage contract. It has a function that increments the saved number by one when the function is called.contract SimpleContract with Deployable { // Declare variables // Variables structure: name: type id: Int as uint32; // This is an ID for contract deployment savedNumber: Int as uint32; counter: Int as uint32; // init is similar to a contructor in Solidity init(id: Int) { // Init the id assed from the contructor self.id = id; // Initialize the variables to zero when the contract is deployed self.savedNumber = 0; self.counter = 0; } // TON contracts can recevie messages // This function makes an action when a specific message is recevied // In this case, when the contract recevies the message "add 1" will increment the counter variable by 1 receive("add 1"){ self.counter = self.counter + 1; } // This allows the contract to recevie objects, in this case of type "Save" // Save a value in the contract receive(msg: Save){ self.savedNumber = msg.amount; } // Getter function to read the variable get fun Number(): Int { // Int is the type of value returned return self.savedNumber; } // Getter function to read the counter variable get fun Counter(): Int { // Int is the type of value returned return self.counter; } // Getter function for the ID get fun Id(): Int { return self.id; }}
The contract imports necessary modules using import "@stdlib/deploy";.
A custom message type Save is declared, which contains an amount field of type Int (aliased as uint32).
Copy
import "@stdlib/deploy";message Save { amount: Int as uint32;}
Contract Declaration
The SimpleContract is declared with the Deployable trait, allowing it to be deployed on the blockchain.
The contract contains three variables: id, savedNumber, and counter, all of type Int (aliased as uint32).
Copy
contract SimpleContract with Deployable { id: Int as uint32; savedNumber: Int as uint32; counter: Int as uint32;
Initialization
The init function acts as a constructor and initializes the contract with an id. We need to give a custom ID because the smart contract address will be determined during deployment based on the code and initial status.
The variables savedNumber and counter are set to zero upon deployment.
The contract includes getter functions to retrieve the values of savedNumber, counter, and id.
Copy
get fun Number(): Int { return self.savedNumber; } get fun Counter(): Int { return self.counter; } get fun Id(): Int { return self.id; }
The SimpleContract is a straightforward example of a storage contract on the TON blockchain. It demonstrates basic functionalities such as initializing variables, handling messages to perform specific actions, and providing getter functions to retrieve stored values. In the next sections, we will build, test, deploy, and interact with this contract using the Blueprint SDK.
Once the contract compiles, we can test it; the test file is in the tests directory. The default test script verifies that the contract deploys correctly.
Let’s edit it to also check that the counter and the save features work. Paste the following code.
Copy
import { Blockchain, SandboxContract, TreasuryContract } from '@ton/sandbox';import { toNano } from '@ton/core';import { SimpleContract } from '../wrappers/SimpleContract';import '@ton/test-utils';// On TON we can test by creating a virtual chaindescribe('SimpleContract', () => { let blockchain: Blockchain; // Init a virtual chain let deployer: SandboxContract<TreasuryContract>; let simpleContract: SandboxContract<SimpleContract>; // Init the smart contract instance const contractId = 1648n; // Id for deployment that will be passed in the contructor. Random value in this example beforeEach(async () => { blockchain = await Blockchain.create(); simpleContract = blockchain.openContract(await SimpleContract.fromInit(contractId)); // Init the deployer. It comes with 1M TON tokens deployer = await blockchain.treasury('deployer'); const deployResult = await simpleContract.send( deployer.getSender(), { value: toNano('0.05'), // Value to send to the contract }, { $$type: 'Deploy', // This because the contract inherits the Deployable trait. queryId: 0n, }, ); // Here is the test. In this case it tests that the contract is deployed correctly. expect(deployResult.transactions).toHaveTransaction({ from: deployer.address, to: simpleContract.address, deploy: true, success: true, }); }); it('should deploy', async () => { // the check is done inside beforeEach // blockchain and simpleContract are ready to use console.log('Deploying contract...'); const conttactId = await simpleContract.getId(); console.log(`Fetched ID during deployment: ${conttactId}`); }); it('should increase', async () => { console.log('Testing increase by 1 function...'); const counterBefore = await simpleContract.getCounter(); console.log('counterBefore - ', counterBefore); await simpleContract.send( deployer.getSender(), { value: toNano('0.02'), }, 'add 1', // The message the contract expects ); const counterAfter = await simpleContract.getCounter(); console.log('counterAfter - ', counterAfter); // Check it incremented the value expect(counterBefore).toBeLessThan(counterAfter); }); it('should save the amount', async () => { console.log('Testing increase by given value function...'); const numeberBefore = await simpleContract.getNumber(); const amount = 10n; console.log(`Value to save: ${amount}`); console.log(`Number saved before: ${numeberBefore}`); await simpleContract.send( deployer.getSender(), { value: toNano('0.02'), }, { $$type: 'Save', // This time it's an object and not just text amount: amount, }, ); const numberAfter = await simpleContract.getNumber(); console.log(`Number saved after: ${numberAfter}`); });});
Here is a quick breakdown, the test and interaction scripts are written in TypeScript. The idea is that the test file spins up a virtual chain to run the tests on with let blockchain: Blockchain; // Init a virtual chain.
Imports
Import necessary modules and utilities from the TON Sandbox, core libraries, and the SimpleContract wrapper.
Copy
import { Blockchain, SandboxContract, TreasuryContract } from '@ton/sandbox';import { toNano } from '@ton/core';import { SimpleContract } from '../wrappers/SimpleContract';import '@ton/test-utils';
Describe Block
Define the test suite for the SimpleContract. Inside the describe block, we initialize variables for the blockchain, deployer, and contract instances.
Copy
describe('SimpleContract', () => { let blockchain: Blockchain; // Init a virtual chain let deployer: SandboxContract<TreasuryContract>; let simpleContract: SandboxContract<SimpleContract>; // Init the smart contract instance const contractId = 1648n; // Id for deployment that will be passed in the constructor. Random value in this example
beforeEach Hook
This hook runs before each test. It sets up the blockchain environment, initializes the contract, and deploys it using a deployer with 1M TON tokens available. The deployment is then verified to ensure the contract is deployed successfully.
Copy
beforeEach(async () => { blockchain = await Blockchain.create(); simpleContract = blockchain.openContract(await SimpleContract.fromInit(contractId)); // Init the deployer. It comes with 1M TON tokens deployer = await blockchain.treasury('deployer'); const deployResult = await simpleContract.send( deployer.getSender(), { value: toNano('0.05'), // Value to send to the contract }, { $$type: 'Deploy', // This because the contract inherits the Deployable trait. queryId: 0n, }, ); // Here is the test. In this case it tests that the contract is deployed correctly. expect(deployResult.transactions).toHaveTransaction({ from: deployer.address, to: simpleContract.address, deploy: true, success: true, }); });
Test: should deploy
This test checks if the contract is deployed correctly by fetching the contract ID. The actual deployment check is handled in the beforeEach hook.
Copy
it('should deploy', async () => { // the check is done inside beforeEach // blockchain and simpleContract are ready to use console.log('Deploying contract...'); const contractId = await simpleContract.getId(); console.log(`Fetched ID during deployment: ${contractId}`); });
Test: should increase
This test verifies the functionality of the add 1 message. It retrieves the counter value before and after sending the message and checks if it has increased.
Copy
it('should increase', async () => { console.log('Testing increase by 1 function...'); const counterBefore = await simpleContract.getCounter(); console.log('counterBefore - ', counterBefore); await simpleContract.send( deployer.getSender(), { value: toNano('0.02'), }, 'add 1', // The message the contract expects ); const counterAfter = await simpleContract.getCounter(); console.log('counterAfter - ', counterAfter); // Check it incremented the value expect(counterBefore).toBeLessThan(counterAfter); });
Test: should save the amount
This test checks the functionality of saving a specified amount in the contract. It sends a Save message and verifies if the savedNumber variable is updated correctly.
The Blueprint SDK allows you to deploy contracts to the mainnet or testenet and it provides endpoints out of the box, but in this case we want to use the Chainstack endpoint we deployed since performs better and it’s more reliable. We can add it in a configuration file, in the project’s root create a new file named blueprint.config.ts and paste the code.
Now that the custom endpoint is configured, edit the deploy script inscripts to include the contract ID; in this case, the ID is a random value, but you might change it based on the resulting address that will give you.
Copy
import { toNano } from '@ton/core';import { SimpleContract } from '../wrappers/SimpleContract';import { NetworkProvider } from '@ton/blueprint';export async function run(provider: NetworkProvider) { // Edit this ID const contractId = 1648n; const simpleContract = provider.open(await SimpleContract.fromInit(contractId)); await simpleContract.send( provider.sender(), { value: toNano('0.5'), }, { $$type: 'Deploy', queryId: 0n, }, ); // Deploy contract await provider.waitForDeploy(simpleContract.address); console.log(`Deployed at address ${simpleContract.address}`); // run methods on `simpleContract`}
Blueprint allows various deployment options; in this case, we’ll use the CLI and the run command directly.
First, add environment variables from the terminal if you want to use the mnemonic phrase to use your wallet; you can also use Tonkeeper and the app from your phone (more secure).
Run the run command and follow the instructions, we used the mnemonic deployment in this case.
Copy
npx blueprint run
Example result:
Copy
Using file: deploySimpleContract? Which network do you want to use? testnet? Which wallet are you using? MnemonicConnected to wallet at address: EQDrNXDLYKstXHj5xV6_md1nYvvrb6y6v4bFyTZReZ-vFYdxSent transactionContract deployed at address EQDVoYZ96Gtc-nQM0U4-rj0mporVOTlSpmB64Tn6HJax98VNYou can view it at https://testnet.tonscan.org/address/EQDVoYZ96Gtc-nQM0U4-rj0mporVOTlSpmB64Tn6HJax98VNDeployed at address EQDVoYZ96Gtc-nQM0U4-rj0mporVOTlSpmB64Tn6HJax98VN
Read data from the contract. Make a new file in the scripts direcotry named getCounter.ts:
Copy
import { SimpleContract } from '../wrappers/SimpleContract';import { NetworkProvider } from '@ton/blueprint';export async function run(provider: NetworkProvider) { const contractId = 1648n; // Random in this case const simpleContract = provider.open(await SimpleContract.fromInit(contractId)); const id = await simpleContract.getId(); const savedNumber = await simpleContract.getNumber(); const counter = await simpleContract.getCounter(); console.log(`Fethching smart contract data...`); console.log(`Contract ID: ${id}`); console.log(`Current saved number: ${savedNumber}`); console.log(`Current counter: ${counter}`);}
Run it with the same run command and follow the instructions:
Copy
npx blueprint run
Result:
Copy
? Choose file to use? Choose file to use getCounter? Which network do you want to use?? Which network do you want to use? testnet? Which wallet are you using?? Which wallet are you using? MnemonicConnected to wallet at address: EQDrNXDLYKstXHj5xV6_md1nYvvrb6y6v4bFyTZReZ-vFYdxFethching smart contract data...Contract ID: 1648Current counter: 0
Now use the wallet to send a transaction, including the message “Save” and some TON token to save the value.
Make a new script in scripts named addValue:
Copy
import { toNano } from '@ton/core';import { SimpleContract } from '../wrappers/SimpleContract';import { NetworkProvider } from '@ton/blueprint';export async function run(provider: NetworkProvider) { const contractId = 1648n; const simpleContract = provider.open(await SimpleContract.fromInit(contractId)); const id = await simpleContract.getId(); const counter = await simpleContract.getNumber(); console.log(`Sending increasing value...`); console.log(`Contract ID: ${id}`); console.log(`Current counter: ${counter}`); // Call the Add function and add 7 await simpleContract.send(provider.sender(), { value: toNano('0.02') }, { $$type: 'Save', amount: 7n });}
Follow the same process with the run command, then once the transaction is validated, you can run the get script to fetch the updated value.