### Install and Initialize TronBox Source: https://tronbox.io/docs/migration/overview Install TronBox globally and initialize a new project. This is similar to Truffle's installation process. ```shell npm install -g tronbox tronbox init ``` -------------------------------- ### Install nvm with wget Source: https://tronbox.io/docs/guides/installation Use wget to download and execute the nvm installation script. This is an alternative to curl for Linux and macOS. ```shell wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.2/install.sh | bash ``` -------------------------------- ### Truffle Configuration Example Source: https://tronbox.io/docs/migration/tronbox-vs-truffle Example Truffle configuration file (truffle-config.js) showing network and compiler settings. ```javascript module.exports = { networks: { development: { host: '127.0.0.1', port: 8545, network_id: '*', gas: 6721975, gasPrice: 20000000000 }, mainnet: { provider: () => new HDWalletProvider(process.env.MNEMONIC, `https://mainnet.infura.io/v3/${process.env.INFURA_KEY}`), network_id: 1, gas: 5500000, gasPrice: 20000000000 } }, compilers: { solc: { version: '0.8.6' } } }; ``` -------------------------------- ### TronBox Configuration Example Source: https://tronbox.io/docs/migration/tronbox-vs-hardhat Example of a TronBox network and compiler configuration. Note the use of `feeLimit`, `fullHost`, and a single `privateKey` for network settings. ```javascript module.exports = { networks: { development: { privateKey: process.env.PRIVATE_KEY, // ⚠️ Single key, not array feeLimit: 1e8, // ⚠️ Resource limit fullHost: 'http://127.0.0.1:9090', // ⚠️ Use `fullHost`, not `url` network_id: '9' }, mainnet: { privateKey: process.env.PRIVATE_KEY, feeLimit: 1e8, fullHost: 'https://api.trongrid.io', // ⚠️ TRON mainnet network_id: '1' } }, compilers: { solc: { version: '0.8.6' // ⚠️ TVM Solidity version } } }; ``` -------------------------------- ### Install @openzeppelin/truffle-upgrades Source: https://tronbox.io/docs/guides/using-upgrades-plugins Install the necessary package for managing upgradable contracts. This command is run in the terminal. ```shell npm install --save-dev @openzeppelin/truffle-upgrades ``` -------------------------------- ### Install TronBox with bun Source: https://tronbox.io/docs Install TronBox globally using bun. Bun is a fast JavaScript runtime and package manager that can be used to install TronBox. ```sh bun install -g tronbox ``` -------------------------------- ### Hardhat Configuration Example Source: https://tronbox.io/docs/migration/tronbox-vs-hardhat Example of a Hardhat network and Solidity compiler configuration. Used for defining network endpoints, accounts, and compiler versions. ```javascript require('@nomicfoundation/hardhat-toolbox'); module.exports = { networks: { localhost: { url: 'http://127.0.0.1:8545', accounts: [process.env.PRIVATE_KEY] }, mainnet: { url: `https://mainnet.infura.io/v3/${process.env.INFURA_KEY}`, accounts: [process.env.PRIVATE_KEY], chainId: 1 } }, solidity: { version: '0.8.6' } }; ``` -------------------------------- ### Install nvm with curl Source: https://tronbox.io/docs/guides/installation Use curl to download and execute the nvm installation script. This is recommended for Linux and macOS to manage Node.js versions. ```shell curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.2/install.sh | bash ``` -------------------------------- ### Start TronBox Runtime Environment (TRE) Source: https://tronbox.io/docs/guides/test-contracts Run this command to start the TRE private blockchain. It exposes port 9090 for interaction. ```shell docker run -it -p 9090:9090 --rm --name tron tronbox/tre ``` -------------------------------- ### Install TronBox with npm Source: https://tronbox.io/docs Install TronBox globally using npm. This command is used to set up the TronBox development environment. ```sh npm install -g tronbox ``` -------------------------------- ### Install TronBox with yarn Source: https://tronbox.io/docs Install TronBox globally using yarn. This command provides another way to manage TronBox installations. ```sh yarn global add tronbox ``` -------------------------------- ### TRE Console Log Output Example Source: https://tronbox.io/docs/guides/debugging-with-TRE This is an example of the log output you can expect in the terminal after running `tronbox migrate` when using `console.log` in your Solidity code. ```solidity Compiling your contracts ... ============================ Compiling ./contracts/Token.sol... Compiling tronbox/console.sol... Writing artifacts to ./build/contracts > Compiled successfully using: - solc: 0.8.6 Using network 'development'. Running migration: 1_initial_migration.js Deploying Token... Token: (base58) TJWQUFE9aZzuugnYsXXKVtJQcUWQNHBY9V (hex) 415da779869e8eac338beaf7cbeda1cdfe412be84f Saving artifacts... Transferring from TJHD16Qq3aWtygQqU4R5UcAGh3hFKxnEwQ to TGjX4QszjhRbyP8k39cGert9pSvkN2sRTA 100 tokens ``` -------------------------------- ### Install Node.js v20 with nvm Source: https://tronbox.io/docs/guides/installation Install a specific version of Node.js, such as v20, using nvm. This ensures compatibility with TronBox. ```shell nvm install 20 ``` -------------------------------- ### Configure Contracts Build Directory Source: https://tronbox.io/docs/reference/configuration Specify a custom directory for compiled contract artifacts. This example sets the output to './output'. ```javascript module.exports = { contracts_build_directory: './output', networks: { nile: { privateKey: process.env.PRIVATE_KEY, feeLimit: 1000 * 1e6, fullHost: 'https://api.nileex.io', network_id: '3' } } }; ``` -------------------------------- ### Install TronBox with pnpm Source: https://tronbox.io/docs Install TronBox globally using pnpm. This is an alternative package manager for installing TronBox. ```sh pnpm add -g tronbox ``` -------------------------------- ### Basic Migration File Example Source: https://tronbox.io/docs/guides/deploy-contracts A simple migration script to deploy a contract. Filenames are prefixed with a number for ordering and suffixed with a description. The numbered prefix is required for tracking successful migrations. ```javascript const MyContract = artifacts.require('MyContract'); module.exports = function (deployer) { deployer.deploy(MyContract); }; ``` -------------------------------- ### JavaScript Test Example with TronBox Source: https://tronbox.io/docs/guides/write-javascript-tests This example demonstrates writing tests for a MetaCoin contract using TronBox's `contract()` function, `artifacts.require()`, and async/await. It covers deploying contracts, checking balances, and sending coins between accounts. ```javascript const MetaCoin = artifacts.require('MetaCoin'); contract('2nd MetaCoin test', async accounts => { it('should put 10000 MetaCoin in the first account', async () => { let instance = await MetaCoin.deployed(); let balance = await instance.getBalance.call(accounts[0]); assert.equal(balance.valueOf(), 10000); }); it('should call a function that depends on a linked library', async () => { let meta = await MetaCoin.deployed(); let outCoinBalance = await meta.getBalance.call(accounts[0]); let metaCoinBalance = Number(outCoinBalance); let outCoinConvertedBalance = await meta.getConvertedBalance.call(accounts[0]); let metaCoinConvertedBalance = Number(outCoinConvertedBalance); assert.equal(metaCoinConvertedBalance, 2 * metaCoinBalance); }); it('should send coin correctly', async () => { // Get initial balances of first and second account. let account_one = accounts[0]; let account_two = accounts[1]; let amount = 10; let instance = await MetaCoin.deployed(); let meta = instance; balance = await meta.getBalance.call(account_one); let account_one_starting_balance = Number(balance); balance = await meta.getBalance.call(account_two); let account_two_starting_balance = Number(balance); await meta.sendCoin(account_two, amount, { from: account_one }); balance = await meta.getBalance.call(account_one); let account_one_ending_balance = Number(balance); balance = await meta.getBalance.call(account_two); let account_two_ending_balance = Number(balance); assert.equal( account_one_ending_balance, account_one_starting_balance - amount, "Amount wasn't correctly taken from the sender" ); assert.equal( account_two_ending_balance, account_two_starting_balance + amount, "Amount wasn't correctly sent to the receiver" ); }); }); ``` -------------------------------- ### Initialize a Bare TronBox Project Source: https://tronbox.io/docs/guides/create-a-project Use `tronbox init` to create a new TronBox project without any pre-included smart contracts or templates. This is useful for starting from scratch. ```shell tronbox init ``` -------------------------------- ### Install NPM Package Source: https://tronbox.io/docs/guides/work-with-npm Install an external library as a project dependency using npm. This makes the package available in your project's `node_modules` directory. ```shell cd my_project && npm install example-tronbox-library ``` -------------------------------- ### Start TronBox Console Source: https://tronbox.io/docs/quickstart Launch the TronBox console to interact with your deployed contracts. The console connects to the specified network, indicated in the prompt. ```shell tronbox console ``` -------------------------------- ### Configure Contracts Build Directory (Relative Path) Source: https://tronbox.io/docs/reference/configuration Use relative paths to specify the contracts build directory. This example points to a directory three levels up and then into 'output'. ```javascript module.exports = { contracts_build_directory: '../../../output', networks: { nile: { privateKey: process.env.PRIVATE_KEY, feeLimit: 1000 * 1e6, fullHost: 'https://api.nileex.io', network_id: '3' } } }; ``` -------------------------------- ### Configure Migrations Directory Source: https://tronbox.io/docs/reference/configuration Set a custom directory for your migration scripts. This example specifies a deeply nested path for migrations. ```javascript module.exports = { migrations_directory: './allMyStuff/someStuff/theMigrationsFolder', networks: { nile: { privateKey: process.env.PRIVATE_KEY, feeLimit: 1000 * 1e6, fullHost: 'https://api.nileex.io', network_id: '3' } } }; ``` -------------------------------- ### TronBox Migration Script Example Source: https://tronbox.io/docs/migration/migrating-from-truffle Migration scripts in TronBox follow the same pattern as Truffle. Ensure your contract artifacts are correctly referenced. ```javascript // migrations/2_deploy_contracts.js (TronBox) const MyContract = artifacts.require('MyContract'); module.exports = function (deployer) { deployer.deploy(MyContract /* constructor arguments */); }; ``` -------------------------------- ### TronBox Test Output Example Source: https://tronbox.io/docs/quickstart This output shows the results of running contract tests, including contract deployment status and test case outcomes. ```shell Using network 'development'. Deploying contracts to development network... Preparing Javascript tests (if any)... Contract: MetaCoin ✔ should verify that there are at least three available accounts ✔ should verify that the contract has been deployed by accounts[0] ✔ should put 10000 MetaCoin in the first account Sleeping for 1 second... Slept. ✔ should call a function that depends on a linked library (1091ms) Sleeping for 3 seconds... Slept. ✔ should send coins from account 0 to 1 (3208ms) 5 passing (4s) ``` -------------------------------- ### Check TronBox version Source: https://tronbox.io/docs/guides/installation Verify that TronBox has been installed correctly by checking its version in the terminal. ```shell tronbox version ``` -------------------------------- ### Deploy Contracts to Local Development Network Source: https://tronbox.io/docs/migration/migrating-from-truffle Start the TronBox development environment (TRE) using Docker, then run `tronbox migrate` to deploy contracts to the local network. ```shell docker run -it -p 9090:9090 --rm --name tron tronbox/tre ``` ```shell tronbox migrate ``` -------------------------------- ### Check nvm version Source: https://tronbox.io/docs/guides/installation Verify that nvm has been installed correctly by checking its version. You may need to restart your terminal. ```shell nvm --version ``` -------------------------------- ### Deploy Beacon Proxy with TronBox Migrations Source: https://tronbox.io/docs/guides/using-upgrades-plugins Deploy a beacon contract and then deploy beacon proxies pointing to it using `deployBeacon` and `deployBeaconProxy`. Set `deployer.trufflePlugin` to `true` before calling these functions. This example deploys a Box contract via a beacon proxy. ```javascript // migrations/NN_deploy_upgradeable_box.js const { deployBeacon, deployBeaconProxy } = require('@openzeppelin/truffle-upgrades'); const Box = artifacts.require('Box'); module.exports = async function (deployer) { try { // Setup tronbox deployer deployer.trufflePlugin = true; const beacon = await deployBeacon(Box, { deployer }); console.info('Beacon deployed', beacon.address); const instance = await deployBeaconProxy(beacon, Box, [42], { deployer }); console.info('Deployed', instance.address); // Call proxy contract const box = await Box.deployed(); const beforeValue = await box.value(); console.info('Value before', beforeValue); // Set new Value await box.setValue(beforeValue + 100n); const afterValue = await box.value(); console.info('Value after', afterValue); } catch (error) { console.error('Beacon: deploy box error', error); } }; ``` -------------------------------- ### Hardhat Test Structure and Assertions Source: https://tronbox.io/docs/migration/tronbox-vs-hardhat Example of a smart contract test suite using Hardhat, Chai for assertions, and Ethers.js for contract interaction. Demonstrates `describe`, `it`, `beforeEach`, and `expect` syntax. ```javascript // Hardhat const { expect } = require('chai'); describe('MyContract', function () { let contract; let owner; beforeEach(async function () { [owner] = await ethers.getSigners(); const MyContract = await ethers.getContractFactory('MyContract'); contract = await MyContract.deploy(); }); it('should work', async function () { expect(await contract.getValue()).to.equal(0); }); }); ``` -------------------------------- ### TronBox Test Execution Output Source: https://tronbox.io/docs/guides/write-javascript-tests This is an example of the output you can expect when running `tronbox test`. It shows the network being used, contract deployment status, and the results of your test suites. ```shell Using network 'development'. Deploying contracts to development network... Preparing Javascript tests (if any תח) Contract: MetaCoin ✔ should put 10000 MetaCoin in the first account ✔ should call a function that depends on a linked library (68ms) ✔ should send coin correctly (137ms) 3 passing (240ms) ``` -------------------------------- ### Update Tests: Replace Web3 with TronWeb Source: https://tronbox.io/docs/migration/migrating-from-truffle Adapt your contract tests by replacing the global `web3` object with `tronWeb` for interacting with the Tron network. This example shows how to fetch TRX balance. ```javascript // test/my_contract.test.js (TronBox) const MyContract = artifacts.require('MyContract'); contract('MyContract', accounts => { it('should work', async () => { const instance = await MyContract.deployed(); // Log account balance (sun) const balance = await tronWeb.trx.getBalance(accounts[0]); console.log('TRX balance (sun):', balance); // Set value via transaction await instance.setValue(42); // Verify state via call const value = await instance.getValue(); assert.equal(value.toString(), '42', 'getValue should return 42 after setValue'); }); }); ``` -------------------------------- ### Specify Custom Contracts Directory Source: https://tronbox.io/docs/reference/configuration Configure the 'contracts_directory' property to point to a custom location for uncompiled contracts. This example also includes a network configuration for Nile. ```javascript module.exports = { contracts_directory: './allMyStuff/someStuff/theContractFolder', networks: { nile: { privateKey: process.env.PRIVATE_KEY, feeLimit: 1000 * 1e6, fullHost: 'https://api.nileex.io', network_id: '3' } } }; ``` -------------------------------- ### Deploy Upgradable Proxy with TronBox Migrations Source: https://tronbox.io/docs/guides/using-upgrades-plugins Use `deployProxy` within TronBox migrations to deploy an upgradable contract instance. Ensure `deployer.trufflePlugin` is set to `true` and the contract is upgrade-safe. This example demonstrates deploying a Box contract and interacting with it. ```javascript // migrations/NN_deploy_upgradeable_box.js const { deployProxy } = require('@openzeppelin/truffle-upgrades'); const Box = artifacts.require('Box'); module.exports = async function (deployer) { try { // Setup tronbox deployer deployer.trufflePlugin = true; const instance = await deployProxy(Box, [42], { deployer }); console.info('Deployed', instance.address); // Call proxy contract const box = await Box.deployed(); const beforeValue = await box.value(); console.info('Value before', beforeValue); // Set new Value await box.setValue(beforeValue + 100n); const afterValue = await box.value(); console.info('Value after', afterValue); } catch (error) { console.error('Transparent: deploy box error', error); } }; ``` -------------------------------- ### MetaCoin Solidity Contract Source: https://tronbox.io/docs/guides/interact-with-contracts A simple example of a coin-like contract written in Solidity. It includes functions for sending coins, checking balances, and retrieving the owner. This contract is not standards-compatible. ```solidity pragma solidity ^0.5.4; import "./ConvertLib.sol"; // This is just a simple example of a coin-like contract. // It is not standards compatible and cannot be expected to talk to other // coin/token contracts. contract MetaCoin { mapping(address => uint) balances; event Transfer(address _from, address _to, uint256 _value); address owner; constructor(uint initialBalance) public { owner = msg.sender; balances[msg.sender] = initialBalance; } function sendCoin(address receiver, uint amount) public returns (bool sufficient) { if (balances[msg.sender] < amount) return false; balances[msg.sender] -= amount; balances[receiver] += amount; emit Transfer(msg.sender, receiver, amount); return true; } function getConvertedBalance(address addr) public view returns (uint){ return ConvertLib.convert(getBalance(addr), 2); } function getBalance(address addr) public view returns (uint) { return balances[addr]; } function getOwner() public view returns (address) { return owner; } } ``` -------------------------------- ### TronBox Test Structure and Assertions Source: https://tronbox.io/docs/migration/tronbox-vs-hardhat Example of a smart contract test suite using TronBox. Uses `contract`, `it`, `beforeEach`, and Node.js `assert` for testing. Note the `artifacts.require` for contract abstraction and the `accounts` parameter. ```javascript // TronBox const MyContract = artifacts.require('MyContract'); contract('MyContract', accounts => { let instance; beforeEach(async () => { instance = await MyContract.new(); }); it('should pass test', async () => { // Test code here const result = await instance.getValue(); assert.equal(result, expectedValue); }); }); ``` -------------------------------- ### Transfer Coins using TronBox Console Source: https://tronbox.io/docs/quickstart Execute a contract function to send coins from one account to another. This example sends 500 metacoin from accounts[0] to accounts[1]. ```javascript MetaCoin.deployed().then(res => res.sendCoin(tronWeb._accounts[1], 500)); ``` -------------------------------- ### Import Contract from NPM Package Source: https://tronbox.io/docs/guides/work-with-npm Import a Solidity contract from an installed NPM package. TronBox automatically resolves paths that do not start with `./` to the `node_modules` directory. ```solidity import "example-tronbox-library/contracts/SimpleNameRegistry.sol"; ``` -------------------------------- ### Create and Navigate to Project Directory Source: https://tronbox.io/docs/guides/create-a-project Use these shell commands to create a new directory for your project and then change into it. ```shell mkdir MetaCoin cd MetaCoin ``` -------------------------------- ### Initialize TronBox Project Source: https://tronbox.io/docs/migration/migrating-from-hardhat Create a new TronBox workspace to scaffold standard folders and project structure. ```shell mkdir my-tron-project cd my-tron-project tronbox init ``` -------------------------------- ### Display TronBox Help Source: https://tronbox.io/docs/reference/command-line-options Shows a list of all available commands and their descriptions. ```shell tronbox help ``` -------------------------------- ### Web3.js Contract Deployment and Interaction Source: https://tronbox.io/docs/migration/tronbox-vs-truffle Demonstrates deploying and interacting with a smart contract using the Web3.js library, including account management. ```javascript const { Web3 } = require('web3'); const web3 = new Web3('http://localhost:8545'); // Add account const account = web3.eth.accounts.privateKeyToAccount(process.env.PRIVATE_KEY); web3.eth.accounts.wallet.add(account); web3.defaultAccount = account.address; // Deploy contract const contract = new web3.eth.Contract(abi); const instance = await contract .deploy({ data: bytecode, arguments: [arg1, arg2] }) .send({ gas: 1500000 }); // Call function const result = await instance.methods.getValue().call(); // Send transaction await instance.methods.setValue(42).send({ gas: 1500000 }); ``` -------------------------------- ### Deploy New Contract Instance Source: https://tronbox.io/docs/reference/contract-abstractions Deploy a new instance of a contract using .new(), passing constructor arguments and optional transaction parameters. Returns a Promise for the new contract abstraction instance. ```javascript MyContract.new(...[arg1, arg2, ...], { tx params }) ``` -------------------------------- ### Get Deployed Contract Instance in Console Source: https://tronbox.io/docs/reference/contract-abstractions In the developer console, use .deployed() to get a contract abstraction instance of the default deployed contract. ```shell tronbox(development)> MyContract.deployed().then(myContract => console.log(myContract)); ``` -------------------------------- ### TronBox Box Hooks Configuration Source: https://tronbox.io/docs/guides/create-a-box Configure commands to be executed automatically after the Box is unpacked. The 'post-unpack' hook is commonly used for installing project dependencies, such as with 'npm install'. ```json { "hooks": { "post-unpack": "npm install" } } ``` -------------------------------- ### Get Contract Storage Range with TRE Source: https://tronbox.io/docs/guides/test-contracts Use debug_storageRangeAt to get the contract storage within a specified range. Requires block number, transaction index, contract address, and storage key range. ```javascript const result = await tronWrap.send('debug_storageRangeAt', [0, 0, contractAddress, '0x01', 1]); console.log(result); ``` -------------------------------- ### Run TronBox Migrations Source: https://tronbox.io/docs/reference/command-line-options Executes migration files to deploy smart contracts. Use `--reset` to rerun all migrations from the beginning. ```shell tronbox migrate [--reset] [--f ] [--to ] [--network ] [--compile-all] [--evm] ``` -------------------------------- ### Unbox MetaCoin Project Template Source: https://tronbox.io/docs/guides/create-a-project Download and set up the MetaCoin project template using the tronbox unbox command. This provides a pre-configured project structure for a token. ```shell tronbox unbox metacoin ``` -------------------------------- ### Reading Contract State: Hardhat vs TronBox Source: https://tronbox.io/docs/migration/tronbox-vs-hardhat Demonstrates reading contract state, showing that the method is the same in both Hardhat and TronBox. ```javascript // Hardhat const value = await contract.getValue(); // TronBox const value = await instance.getValue(); // ✅ Same! ``` -------------------------------- ### Deploy Contracts with Async/Await Source: https://tronbox.io/docs/guides/deploy-contracts Utilize async/await syntax for a cleaner way to manage contract deployment and access deployed instances. This simplifies asynchronous operations in your migration scripts. ```javascript const MyContract = artifacts.require('MyContract'); module.exports = async function (deployer) { // deploy a contract await deployer.deploy(MyContract); //access information about your deployed contract instance const instance = await MyContract.deployed(); }; ``` -------------------------------- ### Get List of Accounts using TronBox Console Source: https://tronbox.io/docs/quickstart Access the list of available accounts managed by TronBox using tronWeb._accounts. ```javascript tronWeb._accounts; ``` -------------------------------- ### TronWeb Contract Deployment and Interaction Source: https://tronbox.io/docs/migration/tronbox-vs-truffle Shows how to deploy and interact with a smart contract using the TronWeb library, highlighting differences in initialization and transaction parameters. ```javascript const { TronWeb } = require('tronweb'); const tronWeb = new TronWeb({ fullHost: 'http://127.0.0.1:9090', privateKey: process.env.PRIVATE_KEY }); // Deploy contract const contract = await tronWeb.contract().new({ abi: abi, bytecode: bytecode, feeLimit: 1e8, parameters: [arg1, arg2] }); // Call function const result = await contract.getValue().call(); // Send transaction await contract.setValue(42).send({ feeLimit: 1e8 }); ``` -------------------------------- ### Import External Package Dependency Source: https://tronbox.io/docs/guides/compile-contracts Import contracts from an external package installed via npm. Specify the package name and the contract file path. ```solidity import 'somepackage/SomeContract.sol'; ``` -------------------------------- ### Create Contract Instance at Address Source: https://tronbox.io/docs/reference/contract-abstractions Use .at(address) to create a contract abstraction instance for a contract already deployed at a specific address. Verifies contract code exists at the address. ```javascript MyContract.at(address) ``` -------------------------------- ### Get Account Information using TronBox Console Source: https://tronbox.io/docs/quickstart Retrieve details about the connected Tron account, including its balance and resource usage, using tronWeb.trx.getAccount(). ```javascript tronWeb.trx.getAccount(); ``` -------------------------------- ### Get Default Deployed Contract Instance Source: https://tronbox.io/docs/reference/contract-abstractions Use .deployed() to retrieve the contract abstraction instance associated with the default deployment address saved in the project. ```javascript MyContract.deployed() ``` -------------------------------- ### Contract Deployment with Truffle and TronBox Source: https://tronbox.io/docs/migration/tronbox-vs-truffle Both Truffle and TronBox use the same syntax for deploying new contract instances with arguments. ```javascript // Truffle const instance = await MyContract.new(arg1, arg2); // TronBox const instance = await MyContract.new(arg1, arg2); // ✅ Same! ``` -------------------------------- ### TronBox Command Structure Source: https://tronbox.io/docs/reference/command-line-options All TronBox commands follow a general structure. Passing no arguments is equivalent to `tronbox help`. ```shell tronbox [options] ``` -------------------------------- ### MyContract.clone(network_id) Source: https://tronbox.io/docs/reference/contract-abstractions Clone a contract abstraction to get another object that uses a different network_id. This is useful if you would like to manage the same contract but on a different network. ```APIDOC ## MyContract.clone(network_id) ### Description Clone a contract abstraction to get another object that uses a different network_id. This is useful if you would like to manage the same contract but on a different network. When using this function, do not forget to set the correct network. ### Parameters #### Path Parameters - **network_id** (number) - Required - The ID of the network to clone the contract for. ### Request Example ```javascript const MyOtherContract = MyContract.clone(3); ``` ### Response #### Success Response (200) - **clonedContract** (object) - A new contract abstraction instance for the specified network. ``` -------------------------------- ### Deploy Contracts with Promises Source: https://tronbox.io/docs/guides/deploy-contracts Use the `.then()` method to chain deployment steps, allowing for sequential contract creation and interaction. This is useful for setting contract data or relationships during migration. ```javascript const A = artifacts.require('A'); const B = artifacts.require('B'); module.exports = async function (deployer) { let a, b; deployer .then(function () { // Create a new version of A return A.new(); }) .then(function (instance) { a = instance; // Get the deployed instance of B return B.deployed(); }) .then(function (instance) { b = instance; // Set the new instance of A's address on B via B's setA() function. return b.setA(a.address); }); }; ``` -------------------------------- ### Check Contract Balance using TronBox Console Source: https://tronbox.io/docs/quickstart Call a contract function to check an account's balance. This example retrieves the balance of the first account (accounts[0]). ```javascript MetaCoin.deployed().then(res => res.getBalance(tronWeb._accounts[0])); ``` -------------------------------- ### Sending Transactions: Hardhat vs TronBox Source: https://tronbox.io/docs/migration/tronbox-vs-hardhat Illustrates sending transactions, noting that the method for setting contract values is identical in Hardhat and TronBox. ```javascript // Hardhat await contract.setValue(42); // TronBox await instance.setValue(42); // ✅ Same! ``` -------------------------------- ### TronWeb Contract Deployment and Interaction Source: https://tronbox.io/docs/migration/tronbox-vs-hardhat Equivalent pattern for deploying and interacting with smart contracts using TronWeb. Highlights differences in initialization, deployment parameters (`feeLimit`), and transaction sending. ```javascript const { TronWeb } = require('tronweb'); const tronWeb = new TronWeb({ fullHost: 'http://127.0.0.1:9090', privateKey: process.env.PRIVATE_KEY }); // Deploy contract const contract = await tronWeb.contract().new({ abi: abi, bytecode: bytecode, feeLimit: 1e8, parameters: [arg1, arg2] }); // Call function const result = await contract.getValue(); // Send transaction await contract.setValue(42); ``` -------------------------------- ### Send MetaCoin Transaction Source: https://tronbox.io/docs/guides/interact-with-contracts Example of sending Meta coins by executing the `sendCoin` function as a transaction. This function modifies the blockchain state. The `from` parameter specifies the sender's address. ```shell tronbox(development)> MetaCoin.deployed().then(res => res.sendCoin(tronWeb._accounts[1], 500, { from: tronWeb._accounts[0] })); ``` -------------------------------- ### Download TronBox Box Source: https://tronbox.io/docs/reference/command-line-options Downloads a pre-built TronBox project (a 'Box') to the current working directory. The box name is required. ```shell tronbox unbox ``` -------------------------------- ### Deploying a Single Contract Source: https://tronbox.io/docs/guides/deploy-contracts Deploy a single contract instance. The contract's address will be set after deployment. ```javascript // Deploy a single contract without constructor arguments deployer.deploy(A); // Deploy a single contract with constructor arguments deployer.deploy(A, arg1, arg2, ...); ``` -------------------------------- ### Configure Solidity Compiler Settings Source: https://tronbox.io/docs/reference/configuration Configure the Solidity compiler (solc) with specific version and optimizer settings. The 'settings' object follows the Solidity compiler's input schema. ```javascript module.exports = { compilers: { solc: { version: '0.8.6', // An object with the same schema as the settings entry in the Input JSON. // See https://docs.soliditylang.org/en/latest/using-the-compiler.html#input-description settings: { optimizer: { enabled: true, runs: 200 }, evmVersion: 'istanbul', viaIR: true } } } }; ``` -------------------------------- ### Configure EVM Networks and Compilers Source: https://tronbox.io/docs/guides/work-with-evm Define network settings and Solidity compiler versions for EVM-compatible chains in `tronbox-evm-config.js`. Ensure TronBox v4.0.0 or later is used. ```javascript module.exports = { networks: { bttc: { privateKey: process.env.PRIVATE_KEY_BTTC, fullHost: 'https://rpc.bt.io', gas: 8500000, // Gas sent with each transaction gasPrice: '500000000000000', // 500,000 gwei (in wei) network_id: '1' }, development: { privateKey: process.env.PRIVATE_KEY_DEV, fullHost: 'http://127.0.0.1:8545', network_id: '*' } }, compilers: { solc: { version: '0.8.7', // An object with the same schema as the settings entry in the Input JSON. // See https://docs.soliditylang.org/en/latest/using-the-compiler.html#input-description settings: { // optimizer: { // enabled: true, // runs: 200 // }, // evmVersion: 'istanbul', // viaIR: true, } } } }; ``` -------------------------------- ### MyContract.defaults([new_defaults]) Source: https://tronbox.io/docs/reference/contract-abstractions Get and optionally set transaction defaults for all instances created from this abstraction. If called without any parameters, it will simply return an object representing current defaults. Passing an object will result in new defaults being set. ```APIDOC ## MyContract.defaults([new_defaults]) ### Description Get and optionally set transaction defaults for all instances created from this abstraction. If called without any parameters, it will simply return an object representing current defaults. Passing an object will result in new defaults being set. ### Parameters #### Request Body - **new_defaults** (object) - Optional - An object representing new default transaction values. - **feeLimit** (number) - Optional - The fee limit for transactions. - **callValue** (number) - Optional - The value to be called in transactions. - **tokenValue** (number) - Optional - The token value for transactions. - **tokenId** (string) - Optional - The token ID for transactions. - **userFeePercentage** (number) - Optional - The user fee percentage. - **originEnergyLimit** (number) - Optional - The origin energy limit. ### Request Example ```javascript MyContract.defaults({ feeLimit: 1000, callValue: 1, tokenValue: 100, tokenId: "1001", userFeePercentage: 1, originEnergyLimit: 50000 }) ``` ### Response #### Success Response (200) - **defaults** (object) - An object representing the current transaction defaults. ``` -------------------------------- ### Deploy a New Contract Source: https://tronbox.io/docs/guides/interact-with-contracts Deploy a new instance of a contract to the network. This function returns the address of the newly deployed contract. ```javascript tronbox(development)> MetaCoin.new(50).then(res => console.log(res.address)) // outputs: // 418912f128b414779e0a21251883b026671706ea6d ``` -------------------------------- ### Link Library by Name and Address Source: https://tronbox.io/docs/reference/contract-abstractions Link a library to a contract by specifying its name and address as strings using .link(name, address). ```javascript MyContract.link(name, address) ``` -------------------------------- ### Contract Deployment: Hardhat vs TronBox Source: https://tronbox.io/docs/migration/tronbox-vs-hardhat Compare contract deployment methods between Hardhat and TronBox. Hardhat uses `ethers.getContractFactory`, while TronBox uses `artifacts.require`. ```javascript // Hardhat const MyContract = await ethers.getContractFactory('MyContract'); const contract = await MyContract.deploy(arg1, arg2); // TronBox const MyContract = artifacts.require('MyContract'); const instance = await MyContract.new(arg1, arg2); ``` -------------------------------- ### Compile Contracts Source: https://tronbox.io/docs/guides/compile-contracts Run this command in your project's root directory to compile all contracts. TronBox will only recompile changed files on subsequent runs. ```shell tronbox compile ``` -------------------------------- ### Contract Abstraction Instance Methods Source: https://tronbox.io/docs/reference/contract-abstractions Contract abstractions provide methods like `at()`, `deployed()`, and `new()` to create instances representing contracts on the TRON network. ```APIDOC ## Contract Abstraction Instance Methods ### Description Each contract abstraction, such as `MyContract`, has the following useful functions for interacting with deployed contracts or deploying new ones. ### `at(address)` Creates a contract abstraction instance of `MyContract` that is deployed at a specific address. It resolves into a contract abstraction instance after ensuring the contract code exists at the specified address. ### `deployed()` Creates a contract abstraction instance of `MyContract` that represents the default address managed by `MyContract`. ### `new(...[arg1, arg2, ...], { tx params })` Deploys a new version of this contract to the network, getting a contract abstraction instance of `MyContract` that represents the newly deployed contract. This function takes constructor parameters and an optional last argument for transaction parameters like `feeLimit` and `userFeePercentage`. ``` -------------------------------- ### Run TronBox Console Source: https://tronbox.io/docs/reference/command-line-options Launches an interactive console with contract abstractions and TronBox commands. Specify a network using `--network `. ```shell tronbox console [--network ] [--evm] ``` -------------------------------- ### Setting Transaction Parameters for Deployment Source: https://tronbox.io/docs/guides/deploy-contracts Specify transaction parameters like 'feeLimit' and 'userFeePercentage' during contract deployment. ```javascript // Set a maximum amount of fee_limit and `userFeePercentage` for the deployment deployer.deploy(A, { fee_limit: 1.1e8, userFeePercentage: 30 }); ``` -------------------------------- ### Compile Smart Contracts with TronBox Source: https://tronbox.io/docs/reference/command-line-options Compiles smart contract source files. By default, only changed contracts are compiled. Use `--all` to compile all contracts. ```shell tronbox compile [--all] [--quiet] [--evm] ``` -------------------------------- ### Execute TronBox Tests Source: https://tronbox.io/docs/guides/write-javascript-tests Run your JavaScript tests using the `tronbox test` command in your terminal. This command compiles your contracts, deploys them to the test network, and executes the tests. ```shell tronbox test ``` -------------------------------- ### Run Specific Test File Source: https://tronbox.io/docs/guides/test-contracts Execute a single test file by providing its path. ```shell tronbox test ./path/to/test/file.js ``` -------------------------------- ### Asynchronous Contract Deployment with Promises Source: https://tronbox.io/docs/guides/deploy-contracts Queue deployment tasks that depend on the completion of previous tasks using Promises. This ensures tasks execute in a specific order. ```javascript deployer.deploy(A).then(function () { return deployer.deploy(B, A.address); }); ``` -------------------------------- ### TronBox Box Commands Configuration Source: https://tronbox.io/docs/guides/create-a-box Define a set of key-value pairs for commands that will be displayed to users after unboxing. These serve as quick instructions for common development tasks. ```json { "commands": { "Compile": "tronbox compile", "Migrate": "tronbox migrate", "Test contracts": "tronbox test", "Test dapp": "npm test", "Run dev server": "npm run start", "Build for production": "npm run build" } } ``` -------------------------------- ### Conditional Deployment Based on Network Source: https://tronbox.io/docs/guides/deploy-contracts Execute deployment steps conditionally based on the target network. The 'network' parameter is passed to the migration function. ```javascript module.exports = function (deployer, network) { if (network == 'nile') { // Do something specific to the network named "nile". } else { // Perform a different step otherwise. } }; ``` -------------------------------- ### Flatten Solidity Files with TronBox Source: https://tronbox.io/docs/reference/command-line-options Combines the source code of multiple Solidity files into a single file. Requires TronBox v3.3.0 or later. ```shell tronbox flatten ``` -------------------------------- ### Deploy Contracts Output Source: https://tronbox.io/docs/migration/migrating-from-hardhat The expected output after running `tronbox migrate` to deploy contracts to the development network. ```shell ➜ my-tron-project tronbox migrate Using network 'development'. Compiling your contracts... =========================== > Everything is up to date, there is nothing to compile. Running migration: 1_initial_migration.js ``` -------------------------------- ### Deploying the Migrations Contract Source: https://tronbox.io/docs/guides/deploy-contracts This migration file deploys the `Migrations` contract, which is a prerequisite for using TronBox's migration system. It should be the first migration script created, typically named `1_initial_migration.js`. ```javascript const Migrations = artifacts.require('Migrations'); module.exports = function (deployer) { deployer.deploy(Migrations); }; ``` -------------------------------- ### Compile All Contracts Source: https://tronbox.io/docs/guides/compile-contracts Use the `--all` option to force TronBox to recompile all contracts, regardless of whether they have changed since the last compilation. ```shell tronbox compile --all ``` -------------------------------- ### Run JavaScript Tests with TronBox Source: https://tronbox.io/docs/reference/command-line-options Executes JavaScript tests. Specify a test file or run all tests in the `test/` directory. Use `--network ` to specify a network. ```shell tronbox test [] [--network ] [--evm] ``` -------------------------------- ### TronBox Configuration Source: https://tronbox.io/docs/migration/migrating-from-hardhat Configure tronbox-config.js by setting networks and the Solidity compiler version. Note the differences in endpoint, accounts, and fee limits compared to Hardhat. ```javascript // tronbox-config.js module.exports = { networks: { // Local development (TronBox TRE / local node) development: { privateKey: 'your-dev-private-key', feeLimit: 1e8, fullHost: 'http://127.0.0.1:9090', network_id: '9' }, // Nile Testnet (recommended for testing) nile: { privateKey: process.env.PRIVATE_KEY, feeLimit: 1e8, fullHost: 'https://nile.trongrid.io', network_id: '3' }, // Mainnet (production) mainnet: { privateKey: process.env.PRIVATE_KEY, feeLimit: 1e8, fullHost: 'https://api.trongrid.io', network_id: '1' } }, compilers: { // TVM Solidity versions solc: { version: '0.8.6', settings: { optimizer: { enabled: true, runs: 200 } } } } }; ``` -------------------------------- ### Link Deployed Library Instance Source: https://tronbox.io/docs/reference/contract-abstractions Link a deployed library instance to a contract using .link(instance). The library's name and address are inferred from the instance. This method can be called multiple times, overwriting previous linkages. ```javascript MyContract.link(instance) ``` -------------------------------- ### Use a Contract at a Specific Address Source: https://tronbox.io/docs/guides/interact-with-contracts Create a contract abstraction for an already deployed contract using its network address. This allows interaction with the existing contract. ```javascript tronbox(development)> MetaCoin.at('418912f128b414779e0a21251883b026671706ea6d') // outputs: // ... // - address: { get: [Function: get], set: [Function: set] } // - getOwner: [Function: f] { call: [Circular *1] }, // - sendCoin: [Function: f] { call: [Circular *2] }, // - getConvertedBalance: [Function: f] { call: [Circular *3] }, // - getBalance: [Function: f] { call: [Circular *4] }, // ... ``` -------------------------------- ### Importing console.sol for Debugging Source: https://tronbox.io/docs/guides/debugging-with-TRE Import the console.sol library to enable console.log functionality in your Solidity contracts when using TRE. This requires TronBox v3.4.0 or later. ```solidity pragma solidity ^0.8.0; import "tronbox/console.sol"; contract Token { mapping(address => uint) balance; event Transfer(address _from, address _to, uint256 _value); constructor() { balance[msg.sender] = 100; } //... ``` -------------------------------- ### Clone Contract Abstraction for Different Network Source: https://tronbox.io/docs/reference/contract-abstractions Create a new contract abstraction instance that targets a different network ID. Ensure the correct network is set for the cloned instance. ```javascript const MyOtherContract = MyContract.clone(3); ```