Ankr Docs
Search…
How to Create a Simple Project with Truffle
Truffle is a development environment, testing framework and asset pipeline for blockchains using the Ethereum Virtual Machine (EVM
This guide walks you through setting up a simple project with Truffle

Prerequisites

Truffle also requires that you have a running Ethereum client which supports standard JSON RPC API (which is nearly all of them).
See Choosing an Ethereum Client (External Link)

1. Setting up

1. Install Truffle

Truffle allows you to compile, debug, test and deploy smart contracts.
1
npm install -g truffle
Copied!

2. Install webpack

Webpack is a static module bundler for modern JavaScript applications.
1
npm install -g webpack
Copied!

2. Create a Project

To use most Truffle commands, you need to run them against an existing Truffle project. So the first step is to create a bare metal Truffle project.
1 Create a new directory for your Truffle project:
1
mkdir Truffle-project
2
cd Truffle-project2.
Copied!
2 Set up the truffle project
1
truffle unbox webpack
Copied!
Once completed, you'll have a project structure with the following items:
  • app/ : Directory for UI Front end files
  • contracts/: Directory for Solidity contracts
  • migrations/: Directory for scriptable deployment files
  • test/: Directory for test files for testing your application and contracts
  • truffle-config.js: Truffle configuration file

3. Create a Contract

Contracts are written in Solidity, all files containing contracts will have a file extension of .sol
  1. 1.
    Create a new .sol file in the contracts folder.
Example contract file
1
pragma solidity >=0.4.21 <0.7.0;
2
3
contract newContract{
4
function multiply(uint a) returns(uint d){
5
return a * 7;
6
}
7
}
Copied!

4. Set up Contract Deployment

These files are responsible for staging your deployment tasks. They are written under the assumption that your deployment needs will change over time.
2. Create a new file in the migrations folder A simple migration file looks like this:
Filename: 2_deploy_contracts.js
**NOTE: **
The filename is prefixed with a number and is suffixed by a description.
The numbered prefix is required in order to determine the order in which to run migrations as well as to record whether the migration ran successfully.
The suffix is purely for human readability and comprehension. Your migration function also may be async in order to use the await keyword to await your deployments.
Example migration file
1
const newContract = artifacts.require("newContract");
2
module.exports = async function(deployer) {
3
await deployer.deploy(newContract);
4
};
Copied!

5. Create a wallet to sign transactions

Set up a HD Wallet-enabled Web3 provider. Use it to sign transactions for addresses derived from a 12-word mnemonic. Install truffle-hdwallet-provider and babel-register using npm
1
npm init
2
3
npm install babel-register truffle-hdwallet-provider --save
Copied!

6. Create an API on Ankr

Follow the **Getting Started **section to **Create an API **and get your API keys.
You can view your successfully created APIs inside app.ankr.com, as well as the: * Project name of each API, * Network type of the API, * Maximum number of API requests per day, * The display of the API upgrade plan (please refer to the upgrade plan) * Status of the API.

7. Configure your Truffle Project

Modify the truffle-config.js file to configure your truffle project. It's seeded with some common settings for different networks and features like migrations, compilation and testing.
Example configuration file
1
/**
2
* Use this file to configure your truffle project. It's seeded with some
3
* common settings for different networks and features like migrations,
4
* compilation and testing. Uncomment the ones you need or modify
5
* them to suit your project as necessary.
6
*
7
* More information about configuration can be found at:
8
*
9
* truffleframework.com/docs/advanced/configuration
10
*
11
* To deploy via Infura you'll need a wallet provider (like truffle-hdwallet-provider)
12
* to sign your transactions before they're sent to a remote public node. Infura accounts
13
* are available for free at: infura.io/register.
14
*
15
* You'll also need a mnemonic - the twelve word phrase the wallet uses to generate
16
* public/private key pairs. If you're publishing your code to GitHub make sure you load this
17
* phrase from a file you've .gitignored so it doesn't accidentally become public.
18
*
19
*/
20
21
// const HDWallet = require('truffle-hdwallet-provider');
22
// const infuraKey = "fj4jll3k.....";
23
//
24
// const fs = require('fs');
25
// const mnemonic = fs.readFileSync(".secret").toString().trim();
26
27
const fs = require('fs');
28
const mnemonic = fs.readFileSync(".secret").toString().trim(); //.secret Mnemonic Phrase
29
var HDWalletProvider = require("truffle-hdwallet-provider");
30
require('babel-register')
31
32
module.exports = {
33
/**
34
* Networks define how you connect to your ethereum client and let you set the
35
* defaults web3 uses to send transactions. If you don't specify one truffle
36
* will spin up a development blockchain for you on port 9545 when you
37
* run `develop` or `test`. You can ask a truffle command to use a specific
38
* network from the command line, e.g
39
*
40
* $ truffle test --network <network-name>
41
*/
42
43
networks: {
44
// Useful for testing. The `development` name is special - truffle uses it by default
45
// if it's defined here and no other network is specified at the command line.
46
// You should run a client (like ganache-cli, geth or parity) in a separate terminal
47
// tab if you use this network and you must also set the `host`, `port` and `network_id`
48
// options below to some value.
49
//
50
// development: {
51
// host: "127.0.0.1", // Localhost (default: none)
52
// port: 8545, // Standard Ethereum port (default: none)
53
// network_id: "*", // Any network (default: none)
54
// },
55
56
// develop: {
57
// port: 8545
58
// },
59
60
networkName: {
61
provider: () => new HDWalletProvider(mnemonic, `https://apis.ankr.com/xxxxx/xxxxx/eth/archive/main`),
62
network_id: 1, // network's Chain id
63
gas: 4612388, // Chain has a lower block limit than mainnet
64
confirmations: 2, // # of confs to wait between deployments. (default: 0)
65
timeoutBlocks: 200, // # of blocks before a deployment times out (minimum/default: 50)
66
skipDryRun: true, // Skip dry run before migrations? (default: false for public nets )
67
},
68
69
// Another network with more advanced options...
70
// advanced: {
71
// port: 8777, // Custom port
72
// network_id: 1342, // Custom network
73
// gas: 8500000, // Gas sent with each transaction (default: ~6700000)
74
// gasPrice: 20000000000, // 20 gwei (in wei) (default: 100 gwei)
75
// from: <address>, // Account to send txs from (default: accounts[0])
76
// websockets: true // Enable EventEmitter interface for web3 (default: false)
77
// },
78
79
// Useful for deploying to a public network.
80
// NB: It's important to wrap the provider as a function.
81
// ropsten: {
82
// provider: () => new HDWalletProvider(mnemonic, `https://ropsten.infura.io/v3/YOUR-PROJECT-ID`),
83
// network_id: 3, // Ropsten's id
84
// gas: 5500000, // Ropsten has a lower block limit than mainnet
85
// confirmations: 2, // # of confs to wait between deployments. (default: 0)
86
// timeoutBlocks: 200, // # of blocks before a deployment times out (minimum/default: 50)
87
// skipDryRun: true // Skip dry run before migrations? (default: false for public nets )
88
// },
89
90
// Useful for private networks
91
// private: {
92
// provider: () => new HDWalletProvider(mnemonic, `https://network.io`),
93
// network_id: 2111, // This network is yours, in the cloud.
94
// production: true // Treats this network as if it was a public net. (default: false)
95
// }
96
},
97
98
// Set default mocha options here, use special reporters etc.
99
mocha: {
100
// timeout: 100000
101
},
102
103
// Configure your compilers
104
compilers: {
105
solc: {
106
// version: "0.5.1", // Fetch exact version from solc-bin (default: truffle's version)
107
// docker: true, // Use "0.5.1" you've installed locally with docker (default: false)
108
// settings: { // See the solidity docs for advice about optimization and evmVersion
109
// optimizer: {
110
// enabled: false,
111
// runs: 200
112
// },
113
// evmVersion: "byzantium"
114
// }
115
}
116
}
117
}
Copied!

8. Compile the contract

To compile a Truffle project, change to the root of the directory where the project is located and then type the following into a terminal:
1
truffle compile
Copied!
Upon first run, all contracts will be compiled. Upon subsequent runs, Truffle will compile only the contracts that have been changed since the last compile. If you'd like to override this behavior, run the above command with the --all option.

9. Deploy to network

1
truffle migrate --network networkName
Copied!
Last modified 5d ago