Let’s imagine for a moment you’re an explorer, standing at the edge of a vast, snow-capped mountain range. It’s vast, full of unknowns, and yet, full of limitless possibilities. Sounds daunting?
Well, that’s similar to stepping into the world of Avalanche smart contracts. Just like scaling a mountain, getting to grips with Avalanche smart contracts might seem intimidating at first.
Yet, it’s an exciting adventure waiting for those ready to explore the future of decentralized applications (DApps).
Using this guide, you will discover the crevices and slopes of creating and deploying smart contracts on the Avalanche blockchain.
We’ll get into Solidity programming, Truffle tooling, and Ethereum Virtual Machine intricacies. Buckle up, your journey starts here!
Contents
- 1 Introducing Avalanche: Unleashing Power in the Decentralized World
- 2 Unleashing Avalanche’s Key Features
- 3 Developing and Deploying Smart Contracts on Avalanche
- 3.1 Essential Tools for the Job
- 3.2 Setting Up the Workspace
- 3.2.1 1. Launching a Local Avalanche Network
- 3.2.2 2. Truffle Directory Creation and Dependency Installation
- 3.2.3 3. Tailoring Your truffle-config.js
- 3.2.4 4. Introducing Storage.sol
- 3.2.5 5. Creating a New Migration
- 3.2.6 6. Composing Contracts Using Truffle
- 3.2.7 7. Your C-Chain Accounts
- 3.2.8 8. Let’s Get Those Migrations Running
- 3.2.9 9. Contract Engagement Time
- 4 Crafting the Blockchain Future with Webisoft’s Avalanche Services
- 5 Final Words
Introducing Avalanche: Unleashing Power in the Decentralized World
Imagine an ecosystem that’s not just secure, adaptable, and expandable, but also specifically designed for developing decentralized applications.
This is the vision brought to life by Ava Labs’ founder and Cornell University’s computer science professor, Emin Gün Sirer, and it’s known as Avalanche.
As one of the fastest and most interoperable platforms in the blockchain universe, Avalanche makes creating tailor-made applications on the blockchain a reality for anyone. The lifeblood of this ecosystem is its native token – AVAX.
Threefold Blockchain Magic
The strength of Avalanche lies in its unique design – a trinity of inbuilt blockchains, each engineered for a distinct function. Here’s the breakdown:
Exchange Chain (X-Chain)
This component serves as a hub for creating, trading, and managing assets and their transactions.
Platform Chain (P-Chain)
With its main job being the coordination of validators and the management and creation of subnets, the P-Chain plays a vital role in Avalanche’s ecosystem.
Contract Chain (C-Chain)
But what’s a blockchain ecosystem without smart contracts? Enter the C-Chain, an embodiment of the Ethereum Virtual Machine that’s designed for creating smart contracts.
Since our focus is on Avalanche smart contracts, let’s delve a little deeper into the C-Chain.
The Power of the Contract Chain
The Contract Chain lets you develop Ethereum-fit smart contracts as well as stand as the go-to blockchain for Avalanche smart contracts.
With superior throughput, affordable gas pricing, quick transaction confirmation times, and increased speed, the C-Chain stands out from the Ethereum Virtual Machine.
All of these perks stem from its utilization of the Proof-of-Stake consensus mechanism, underpinned by the Snowman consensus protocol.
Unleashing Avalanche’s Key Features
Let’s unwrap some of the essential elements that make Avalanche shine.
Scalability
Avalanche is a powerhouse, managing an impressive 4500 transactions per second, making it an extraordinarily scalable, robust, and efficient protocol.
Speed
In a race of blockchain ecosystems, Avalanche takes the gold medal, staking its claim as the fastest smart contract platform, gauged by its time-to-finality.
Security
Forget the 51% standard – Avalanche takes security to another level. Its powerful protocol guarantees robust security that is considerably more substantial.
Interoperability and Flexibility
Avalanche’s architecture is built to welcome a plethora of blockchain assets, with AVAX acting as a security measure and a unit of exchange, marking Avalanche as a universal and versatile ecosystem.
Sustainability
Bidding adieu to the energy-intensive proof-of-work consensus mechanism, Avalanche embraces the proof-of-stake consensus mechanism.
It’s a move that ensures a sustainable, less energy-consuming platform, making Avalanche a green choice in the blockchain world.
Developing and Deploying Smart Contracts on Avalanche
Building and launching a smart contract on Avalanche may seem intimidating, but fear not! I’m here to walk you through the process. And don’t worry, it’s not as tough as you might think.
We’re going to use Solidity, a language specifically designed for implementing smart contracts, so it’s perfect for our needs.
Essential Tools for the Job
To shape your smart contracts for Avalanche, you can use a wide variety of tools such as Hardhat, Remix, and more. For our purposes though, we’ll focus on using Truffle in combination with Avalanche’s C-chain blockchain.
Why Truffle? You can write, compile, manage migrations, generate artifacts, and even interact with contracts that have already been deployed using this tool.
Setting Up the Workspace
Before we dive into the nitty-gritty of creating smart contracts, we need to ensure our workspace is properly set up. Here are the key elements we’ll need:
Avalanche Network Runner: This tool lets you run a localized Avalanche network
NodeJS (Version 8.9.4 or later)
Truffle: You can get it by running “npm install -g truffle”
1. Launching a Local Avalanche Network
Starting with the Avalanche Network Runner, it’s an excellent tool that enables us to run a localized Avalanche network, which we can interact with in real-time. Let’s kick things off by running a 5-node Avalanche network.
cd /path/to/avalanche-network-runner
# start a five node staking network
./go run examples/local/fivenodenetwork/main.go
Keep it running as long as you want, and when you’re done, just hit CTRL + C.
2. Truffle Directory Creation and Dependency Installation
Once our network is up and running, let’s open a fresh terminal tab and focus on setting up our “Truffle” directory and installing dependencies. This is the space where you’ll be doing most of your work.
cd /path/to/directory
After deciding where you want your Truffle workspace, generate a new path and christen it “Truffle.”
mkdir truffle; cd truffle
Now it’s time to install the essential tools, using “npm”, get web3.js, a library which acts as a bridge between the AvalancheJS and Ethereum Virtual Machine (EVM) for swapping chains.
npm install web3 avalanche -s
Web3 will provide us with an HTTP server, which is a channel for web3 to engage using the EVM. Let’s finish off our truffle project by building a boilerplate.
truffle init
Remember when you construct your own development network, it automatically deposits funds into some static accounts. For these addresses, we’ll employ @truffle/hdwallet-provider to generate accounts.
npm install @truffle/hdwallet-provider
3. Tailoring Your truffle-config.js
Once you initiate Truffle, it’s going to create a file named “truffle-config.js”. This file needs your attention now. We’re going to inject some code into this to make it work for us.
const Web3 = require(“web3”);
const HDWalletProvider = require(“@truffle/hdwallet-provider”);
const protocol = “http”;
const ip = “localhost”;
const port = 9650;
Web3.providers.HttpProvider.prototype.sendAsync = Web3.providers.HttpProvider.prototype.send;
const provider = new Web3.providers.HttpProvider(
${protocol}://${ip}:${port}/ext/bc/C/rpc
);
const privateKeys = [
“0x56289e99c94b6912bfc12adc093c9b51124f0dc54ac7a766b2bc5ccf558d8027”,
“0x7b4198529994b0dc604278c99d153cfd069d594753d471171a1d102a10438e07”,
“0x15614556be13730e9e8d6eacc1603143e7b96987429df8726384c2ec4502ef6e”,
“0x31b571bf6894a248831ff937bb49f7754509fe93bbd2517c9c73c4144c0e97dc”,
“0x6934bef917e01692b789da754a0eae31a8536eb465e7bff752ea291dad88c675”,
“0xe700bdbdbc279b808b1ec45f8c2370e4616d3a02c336e68d85d4668e08f53cff”,
“0xbbc2865b76ba28016bc2255c7504d000e046ae01934b04c694592a6276988630”,
“0xcdbfd34f687ced8c6968854f8a99ae47712c4f4183b78dcc4a903d1bfe8cbf60”,
“0x86f78c5416151fe3546dece84fda4b4b1e36089f2dbc48496faf3a950f16157c”,
“0x750839e9dbbd2a0910efe40f50b2f3b2f2f59f5580bb4b83bd8c1201cf9a010a”,
];
module.exports = {
networks: {
development: {
provider: () => {
return new HDWalletProvider({
privateKeys: privateKeys,
providerOrUrl: provider,
});
},
network_id: “*”,
gas: 3000000,
gasPrice: 225000000000,
},
},
};
Remember, if you’re thinking about sending API calls to an alternative AvalancheGo node, it’s possible to tweak the “protocol”, “port”, and “ip”. Keep in mind that the “gas” and “gasPrice” are adjusted to align with the Avalanche C-chain parameters.
4. Introducing Storage.sol
Let’s create a fresh file named “Storage.sol” within the “contracts” directory and populate it with some specific code.
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
/**
* @title Storage
* @dev Store & retrieve value in a variable
*/
contract Storage {
uint256 number;
/**
* @dev Store value in variable
* @param num value to store
*/
function store(uint256 num) public {
number = num;
}
/**
* @dev Return value
* @return value of ‘number’
*/
function retrieve() public view returns (uint256){
return number;
}
}
This “Storage” file serves as the smart contract for Solidity, enabling us to record a number onto a blockchain via a function called “store” and later retrieve that number with a “retrieve” function.
5. Creating a New Migration
Our next move is to append some more code into a fresh file. This one’s called “2_deploy_contracts.js” and resides in the directory of “migrations”.
It’s in charge of managing the deployment of our smart contract “Storage” into the blockchain.
const Storage = artifacts.require(“Storage”);
module.exports = function (deployer) {
deployer.deploy(Storage);
};
6. Composing Contracts Using Truffle
Every time you make changes to “Storage.sol”, you must compile it with Truffle.
truffle compile
Here’s what you need to watch out for:
Compiling your contracts…
===========================
> Compiling ./contracts/Migrations.sol
> Compiling ./contracts/Storage.sol
> Artifacts written to /path/to/build/contracts
> Compiled successfully using:
– solc: 0.5.16+commit.9c3226ce.Emscripten.clang
7. Your C-Chain Accounts
Truffle tends to lean on the first account it can find on your C-chain client as the sender (“from” address) at the time you’re deploying your smart contracts to the C-chain.
Just make sure that this default account is already pre-loaded with some AVAX.
Truffle Accounts
You can inspect the accounts that Truffle brings in by using the truffle console.
To open the console of truffle, follow these steps:
truffle console –network development
If you encounter an error message stating that the API call was rejected due to the chain not being fully bootstrapped, you’ll need to sit tight till the chain is prepared and ready for use. This shouldn’t take long.
While you’re inside the truffle console, here’s what you can do:
truffle(development)> accounts
[
‘0x8db97C7cEcE249c2b98bDC0226Cc4C2A57BF52FC’,
‘0x9632a79656af553F58738B0FB750320158495942’,
‘0x55ee05dF718f1a5C1441e76190EB1a19eE2C9430’,
‘0x4Cf2eD3665F6bFA95cE6A11CFDb7A2EF5FC1C7E4’,
‘0x0B891dB1901D4875056896f28B6665083935C7A8’,
‘0x01F253bE2EBF0bd64649FA468bF7b95ca933BDe2’,
‘0x78A23300E04FB5d5D2820E23cc679738982e1fd5’,
‘0x3C7daE394BBf8e9EE1359ad14C1C47003bD06293’,
‘0x61e0B3CD93F36847Abbd5d40d6F00a8eC6f3cfFB’,
‘0x0Fa8EA536Be85F32724D57A37758761B86416123’
]
If you’re keen to check the balance, simply type in the below command:
truffle(development)> await web3.eth.getBalance(accounts[0])
‘50000000000000000000000000’
truffle(development)> await web3.eth.getBalance(accounts[1])
‘0’
You’ll notice that “accounts[0]” (your default account) has a balance, whereas “accounts[1]” is empty.
Funding Your Accounts
For the purpose of funding your list of “accounts”, there’s a handy script that you can download and use with the below command:
wget -nd -m https://raw.githubusercontent.com/ava-labs/avalanche-docs/master/scripts/fund-cchain-addresses.js
To execute the script, enter the given code:
truffle exec fund-cchain-addresses.js –network development
This script will distribute 1000 AVAX into every one of your “accounts”. After you’ve executed the script without a hitch, you can verify the balances with:
truffle(development)> await web3.eth.getBalance(accounts[0]);
‘50000001000000000000000000’
truffle(development)> await web3.eth.getBalance(accounts[1]);
‘1000000000000000000’
Connecting with Personal APIs
Your node accounts link with private APIs. “Web3” includes several functions that utilize this API, like “web3.eth.personal.unlockAccount”, “web3.eth.personal.newAccount”, and so on.
This API, however, isn’t active by default. You can only enable it via “C-chain”/”Coreth” configurations. The current Avalanche Network Runner doesn’t allow you to enable this API.
Thus, these features can only be accessed if you manually launch your network with the “internal-private-personal” API switched on via the “eth-apis” flag.
8. Let’s Get Those Migrations Running
We’re all set! It’s time to run the migrations and launch your “Storage” contract. Here’s how you do it:
truffle(development)> migrate –network development
After running the migrations, you’ll notice this:
Compiling your contracts…
===========================
> Everything is up to date, there is nothing to compile.
Migrations dry-run (simulation)
===============================
> Network name: ‘development-fork’
> Network id: 1
> Block gas limit: 99804786 (0x5f2e672)
1_initial_migration.js
======================
Deploying ‘Migrations’
———————-
> block number: 4
> block timestamp: 1607734632
> account: 0x34Cb796d4D6A3e7F41c4465C65b9056Fe2D3B8fD
> balance: 1000.91683679
> gas used: 176943 (0x2b32f)
> gas price: 225 gwei
> value sent: 0 ETH
> total cost: 0.08316321 ETH
————————————-
> Total cost: 0.08316321 ETH
2_deploy_contracts.js
=====================
Deploying ‘Storage’
——————-
> block number: 6
> block timestamp: 1607734633
> account: 0x34Cb796d4D6A3e7F41c4465C65b9056Fe2D3B8fD
> balance: 1000.8587791
> gas used: 96189 (0x177bd)
> gas price: 225 gwei
> value sent: 0 ETH
> total cost: 0.04520883 ETH
————————————-
> Total cost: 0.04520883 ETH
Summary
=======
> Total deployments: 2
> Final cost: 0.13542204 ETH
If you skipped the step to create your account over the C-chain, you’ll likely encounter this error:
Error: Expected parameter ‘from’ not passed to function.
Likewise, if you didn’t make sure to pre-fund the account, you might see an error like this:
Error: *** Deployment Failed ***
“Migrations” could not deploy due to insufficient funds
* Account: 0x090172CD36e9f4906Af17B2C36D662E69f162282
* Balance: 0 wei
* Message: sender doesn’t have enough funds to send tx. The upfront cost is: 1410000000000000000 and the sender’s account only has: 0
* Try:
+ Using an adequately funded account
9. Contract Engagement Time
Congratulations! Your “Storage” contract is live and ready. Now, we’ll record a number there and retrieve it. This involves heading back to the console of Truffle:
Now, let’s get a hold of the deployed contract “Storage”:
truffle(development)> let instance = await Storage.deployed()
This action will return the following:
undefined
The creation of a blockchain number
Now that you’ve got a hold of the “Storage” contract, you can use its “store” method to put a number onto the blockchain.
truffle(development)> instance.store(1234)
You’ll be dealing with code that looks a bit like this:
{
tx: ‘0x10afbc5e0b9fa0c1ef1d9ec3cdd673e7947bd8760b22b8cdfe08f27f3a93ef1e’,
receipt: {
blockHash: ‘0x8bacbce7c9d835db524bb856288e3a73a6afbe49ab34abd8cd8826db0240eb21’,
blockNumber: 9,
contractAddress: null,
cumulativeGasUsed: 26458,
from: ‘0x34cb796d4d6a3e7f41c4465c65b9056fe2d3b8fd’,
gasUsed: 26458,
logs: [],
logsBloom: ‘0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000’,
status: true,
to: ‘0x0d507b0467baef742f9cc0e671eddbdf6df41d33’,
transactionHash: ‘0x10afbc5e0b9fa0c1ef1d9ec3cdd673e7947bd8760b22b8cdfe08f27f3a93ef1e’,
transactionIndex: 0,
rawLogs: []
},
logs: []
}
Blockchain Number Reading
To retrieve the number you stored on the blockchain, you can call the “retrieve” function on the contract “Storage” instance.
truffle(development)> let i = await instance.retrieve()
You should expect to see this:
undefined
Your “retrieve” call will yield a “BN” (big number). If you want to view the actual value, use its “.toNumber” function:
truffle(development)> i.toNumber()
Voila! Your original blockchain number is now visible.
1234
It’s quite a journey, isn’t it? But remember, practice makes perfect. Keep going!
Crafting the Blockchain Future with Webisoft’s Avalanche Services
Looking for innovative ways to unlock new business growth possibilities with the power of blockchain? Webisoft has you covered.
We’re all about offering a spectrum of blockchain development services tailored to startups and companies eager to harness this revolutionary technology.
Whether it’s Avalanche, or any other top-notch blockchain system, our developers deliver nothing short of top-notch solutions that align with your vision.
Bespoke Blockchain Solutions
Avalanche subnets’ virtual machines are our playground for developing bespoke public and private blockchains.
Our services include setting up a node for the main network, developing subnets and virtual machines, and adding validation.
With Webisoft, get ready for a tailored blockchain experience.
Unveiling dApps Potential
Our talented pool of developers have a knack for constructing DeFi dApps that are fit with Ethereum.
Their technical acumen means you get polished dApps that enable trading of everything from traditional equities and commodities to alternative assets.
Creating Smart Contracts with Solidity
Keeping our fingers on the pulse of Avalanche advancements and new integrations is second nature to our team.
This proactive approach allows us to craft and execute solidity-matched smart contracts on Avalanche with finesse.
Our services encompass all the stages of smart contract development including audits, architecture design, and implementation.
NFT Solutions – The Digital Frontier
The Webisoft blockchain wizards are adept at curating NFT solutions. We’re talking wallet integration, development of NFT marketplace, intuitive UI design, secure NFT storage solutions, and feature integrations for businesses rooted in blockchain.
Leveraging state-of-the-art blockchain technologies, such as Avalanche, we construct and launch robust NFT solutions.
Wallet Development – The Key to Asset Management
Looking for a personalized, user-centric, and secure wallet for managing funds on the Avalanche network? Look no further.
Our developers can whip up a custom Avalanche wallet that enables seamless receipt, asset transfer, and swapping.
Final Words
Our expedition through the mountainous landscape of Avalanche smart contracts comes to a close. Along the way, we encountered a variety of tools and methods.
We used Solidity for contract creation, Truffle for deployment and interaction, and learned to handle different errors like a pro.
You’ve set up your local Avalanche network, and interacted with your smart contract using the Ethereum Virtual Machine.
More importantly, you’ve successfully scaled the challenging heights of deploying and interacting with smart contracts on the Avalanche blockchain.
Remember, each journey enhances your understanding and skills in the rapidly evolving field of blockchain technology.
Let this adventure be a stepping-stone for more advanced explorations into the breathtaking world of blockchain.
Safe travels on your continued journey!Unleash the power of blockchain and transform your business with Webisoft.
Our expert developers are eager to provide top-tier Avalanche solutions, from custom dApps to NFT marketplace developments. Don’t let the blockchain revolution pass you by – connect with Webisoft today!