Deploying Solidity Smart Contracts to Solana
What is Solana and how can you deploy Solidity smart contracts to it?
Solana is a new blockchain focusing on performance. It supports smart contracts like Ethereum which they call Programs. You can develop those in Rust, but there's also a new project now to compile Solidity to Solana. In other words you can deploy your contracts written in Solidity now to Solana!
And of course the costs of transactions on Solana are a fraction of those in Ethereum. So how does it all work?

Transaction Ordering (Proof of History)
The biggest feature of Solana is its Proof of History (PoH) which is based on a chain of sha256 hashes as proof of time being passed. The idea behind it is that to compute hash300, one has to sequentially calculate first hash1, then hash2 on so on. That's because the hash output cannot be predicted and each intermediate result is automatically the input for the next intermediate result.
The lastest CPU generations are extremely fast at calculating sha256, but again it has to be done sequentially. And that's why one can have certainty there won't be a custom ASIC which is 100x faster.


So when a node receives transactions signed with hash300, it will know those transactions are to be placed after hash200, but before hash400 (assuming 100 hashes as delay). This is quite similar to the concept of Verifiable Delay Functions (VDFs) which are also used for ETH2.0. The one difference lies in proof verification which for VDFs can be done in significantly less complex steps than proof creation, while for PoH requires every single hash to be calculated again. So how can PoH verification be done efficiently?
Luckily PoH proof verification, unlike the PoH proof creation, can be parallelized. The proof will have to contain every intermediate hash where then each intermediate hash calculation can be verified in parallel. This is possible very efficiently on modern GPUs. Of course the downside for this is very large proof sizes and generally high Solana validator hardware requirements. The upside is performance, because it reduces messaging overhead + latency due to providing a predetermined transaction order.
New transactions bundled in a batch and optimistically streamed via UDP from the current leader to all other validators where each validator receives a different data part of the bundle. In the next step validators are sharing the missing sets between each other, all of this happens concurrently, non-stop and streamed resulting in very high performance.
Consensus on Solana (Proof of Stake)
PoH doesn't solve the consensus problem though, for that Solana is using a version of PBFT (Practical Byzantine Fault Tolerance) which is similar to Cosmos' Tendermint consensus algorithm (here's a good video overview about it) called Tower BFT. But since Solana can use the PoH for its blockchain clock, the consensus timeouts of PBFT can be encoded with this directly.
Timeouts for all predecessor PBFT votes double with each new vote. Imagine a scenario where every validator has voted 32 times in the last 12 seconds. The last vote from 12 seconds ago now has a timeout of 2³² slots, or roughly 54 years in PoH time. Or in other words you would have to compute sha256 hashes on a CPU for 54 years to be able to rollback that vote.
Other features of Solana include:
- Turbine — a block propagation protocol
- Gulf Stream — Mempool-less transaction forwarding protocol
- Sealevel — Parallel smart contracts run-time
- Pipelining — a Transaction Processing Unit for validation optimization
- Cloudbreak — Horizontally-Scaled Accounts Database
- Replicators — Distributed ledger store
If you want to learn more, check out Solana's docs, whitepaper and blog posts.
Deploying ERC-20 Token to Solana
Deploying an ERC-20 to Solana from Solidity requires installing all tools and running a deploy script.
1. Installing Solang
The best way to install Solang is using the VS Code extension. It will automatically install the correct solang binary along with the dependencies. Alternatively you can download the binary directly and manually install the dependencies. The VS Code extension will also give you compiling capabilities for Solang, the regular Solidity extension wouldn't be quite accurate due to the differences in the supported features.
To make the extension work properly, you only need to more steps:
1. Make sure to choose Solana as target in the extension settings.

2. Disable the solidity extension for the workspace.

Now let's take an ERC20 contract, the code here is almost a 1:1 copy from Openzeppelin.
You'll also want to initialize the package and install required dependencies:
$ npm init
$ npm install @solana/solidity @solana/web3.js2. Installing Solana Tool Suite
Next up install the Solana test suite. If you're running on Mac OS, it's as simple as running:
$ sh -c "$(curl -sSfL https://release.solana.com/v1.8.5/install)"3. Create the ERC-20 contract
Now let's take an ERC20 contract as ERC20.sol in our package root, the code here is almost a 1:1 copy from Openzeppelin.
4. Compile Solidity -> Solana
Next up install the Solana test suite. If you're running on Mac OS, it's as simple as running:
$ solang ERC20.sol --target solana --output buildThis will produce
build/ERC20.abi: Just as you know from Ethereum, the ABI for our contract is generated.build/bundle.so: New here is the compiled Solana Program.
5. Deploy the ERC-20 contract
Now create the following deploy-erc20.js script:
const { Connection, LAMPORTS_PER_SOL, Keypair } = require('@solana/web3.js')
const { Contract, publicKeyToHex } = require('@solana/solidity')
const { readFileSync } = require('fs')
const ERC20_ABI = JSON.parse(readFileSync('./build/ERC20.abi', 'utf8'))
const BUNDLE_SO = readFileSync('./build/bundle.so')
;(async function () {
console.log('Connecting to your local Solana node ...')
const connection = new Connection(
// works only for localhost at the time of writing
// see https://github.com/solana-labs/solana-solidity.js/issues/8
'http://localhost:8899', // "https://api.devnet.solana.com",
'confirmed'
)
const payer = Keypair.generate()
while (true) {
console.log('Airdropping (from faucet) SOL to a new wallet ...')
await connection.requestAirdrop(payer.publicKey, 1 * LAMPORTS_PER_SOL)
await new Promise((resolve) => setTimeout(resolve, 1000))
if (await connection.getBalance(payer.publicKey)) break
}
const address = publicKeyToHex(payer.publicKey)
const program = Keypair.generate()
const storage = Keypair.generate()
const contract = new Contract(connection, program.publicKey, storage.publicKey, ERC20_ABI, payer)
console.log('Deploying the Solang-compiled ERC20 program ...')
await contract.load(program, BUNDLE_SO)
console.log('Program deployment finished, deploying ERC20 ...')
await contract.deploy('ERC20', ['MyToken', 'MTO', '1000000000000000000'], program, storage, 4096 * 8)
console.log('Contract deployment finished, invoking contract functions ...')
const symbol = await contract.symbol()
const balance = await contract.balanceOf(address)
console.log(`ERC20 contract for ${symbol} deployed!`)
console.log(`Wallet at ${address} has a balance of ${balance}.`)
contract.addEventListener(function (event) {
console.log(`${event.name} event emitted!`)
console.log(
`${event.args[0]} sent ${event.args[2]} tokens to
${event.args[1]}`
)
})
console.log('Sending tokens will emit a "Transfer" event ...')
const recipient = Keypair.generate()
await contract.transfer(publicKeyToHex(recipient.publicKey), '1000000000000000000')
process.exit(0)
})()Here we are making use of
If you are Dapp developer and want to connect a wallet, have a look at Solana wallet adapter instead.
Now we're ready to run your own local Solana chain:
$ solana-test-validator --reset --quietAnd in a separate tab run our script:
$ node deploy-erc20.jsWe just deployed the ERC-20 token to our local Solana chain! 🎉🎉🎉
So what exactly is Solang?
In their own words: With Solang you can compile smart contracts written in Solidity for Solana, Parity Substrate, and Ethereum ewasm. It uses the llvm compiler framework to produce WebAssembly (wasm) or BPF contract code.
How does it compare to projects cloning the EVM like Moonbeam and Evmos? Since EVM cloning keeps all the overhead from running the EVM, the solution with Solang should scale much more efficiently since it's running natively on the chain, but there are some caveats to it:
Solang aims to be compatible with Solidity 0.7, however there are some key differences:
- Libraries are always statically linked into the contract code.
- Solang generates WebAssembly or BPF rather than EVM. This means that the
assembly {}statement using EVM instructions is not supported. - No gas exists for Solana. There is compute budget which may not be exceeded, but there is no charge based on compute units used.
- The gas cannot be set on Solana for external calls.
tx.gaspriceis not available.gasleft()is not available.
block.numbergives the slot number rather than the block height.- You can print output for debugging using print().
selfdestructandtx.originare not available.- Solana addresses are base58 encoded, not hexadecimal. An address literal can be specified with the special syntax
address"<account>".address foo = address"5GBWmgdFAMqm8ZgAHGobqDqX6tjLxJhv53ygjNtaaAn3sjeZ";
- The size of the new account can be specified using space. By default, the new account is created with a size of 1 kilobyte (1024 bytes) plus the size required for any fixed-size fields. When you specify space, this is the space in addition to the fixed-size fields (like strings in the state). So, if you specify space: 0, then there is no space for any dynamicially allocated fields.
contract Hatchling {
string name;
constructor(string id) payable {
require(id != "", "name must be provided");
name = id;
}
}
contract Adult {
function test() public {
Hatchling h = new Hatchling{space: 10240}("luna");
}
}- So is this ready to use?
- I'm not sure if it's production ready, but even if not, it's surely getting there soon.
- Is our compiled ERC-20 contract compatible with other SPL tokens on Solana?
- Also not sure, if you know the answer, please leave a comment.
Solidity Developer
More great blog posts from Markus Waas
How to use ChatGPT with Solidity
Using the Solidity Scholar and other GPT tips
How to integrate Uniswap 4 and create custom hooks
Let's dive into Uniswap v4's new features and integration
How to integrate Wormhole in your smart contracts
Entering a New Era of Blockchain Interoperability
Solidity Deep Dive: New Opcode 'Prevrandao'
All you need to know about the latest opcode addition
How Ethereum scales with Arbitrum Nitro and how to use it
A blockchain on a blockchain deep dive
The Ultimate Merkle Tree Guide in Solidity
Everything you need to know about Merkle trees and their future
The New Decentralized The Graph Network
What are the new features and how to use it
zkSync Guide - The future of Ethereum scaling
How the zero-knowledge tech works and how to use it
Exploring the Openzeppelin CrossChain Functionality
What is the new CrossChain support and how can you use it.
Deploying Solidity Contracts in Hedera
What is Hedera and how can you use it.
Writing ERC-20 Tests in Solidity with Foundry
Blazing fast tests, no more BigNumber.js, only Solidity
ERC-4626: Extending ERC-20 for Interest Management
How the newly finalized standard works and can help you with Defi
Advancing the NFT standard: ERC721-Permit
And how to avoid the two step approve + transferFrom with ERC721-Permit (EIP-4494)
Moonbeam: The EVM of Polkadot
Deploying and onboarding users to Moonbeam or Moonriver
Advanced MultiSwap: How to better arbitrage with Solidity
Making multiple swaps across different decentralized exchanges in a single transaction
Smock 2: The powerful mocking tool for Hardhat
Features of smock v2 and how to use them with examples
How to deploy on Evmos: The first EVM chain on Cosmos
Deploying and onboarding users to Evmos
EIP-2535: A standard for organizing and upgrading a modular smart contract system.
Multi-Facet Proxies for full control over your upgrades
MultiSwap: How to arbitrage with Solidity
Making multiple swaps across different decentralized exchanges in a single transaction
The latest tech for scaling your contracts: Optimism
How the blockchain on a blockchain works and how to use it
Ultimate Performance: The Aurora Layer2 Network
Deploying and onboarding users to the Aurora Network powered by NEAR Protocol
What is ecrecover in Solidity?
A dive into the waters of signatures for smart contracts
How to use Binance Smart Chain in your Dapp
Deploying and onboarding users to the Binance Smart Chain (BSC)
Using the new Uniswap v3 in your contracts
What's new in Uniswap v3 and how to integrate Uniswap v3
What's coming in the London Hardfork?
Looking at all the details of the upcoming fork
Welcome to the Matrix of blockchain
How to get alerted *before* getting hacked and prevent it
The Ultimate Ethereum Mainnet Deployment Guide
All you need to know to deploy to the Ethereum mainnet
SushiSwap Explained!
Looking at the implementation details of SushiSwap
Solidity Fast Track 2: Continue Learning Solidity Fast
Continuing to learn Solidity fast with the advanced basics
What's coming in the Berlin Hardfork?
Looking at all the details of the upcoming fork
Using 1inch ChiGas tokens to reduce transaction costs
What are gas tokens and example usage for Uniswap v2
Openzeppelin Contracts v4 in Review
Taking a look at the new Openzeppelin v4 Release
EIP-3156: Creating a standard for Flash Loans
A new standard for flash loans unifying the interface + wrappers for existing ecosystems
Tornado.cash: A story of anonymity and zk-SNARKs
What is Tornado.cash, how to use it and the future
High Stakes Roulette on Ethereum
Learn by Example: Building a secure High Stakes Roulette
How to implement generalized meta transactions
We'll explore a powerful design for meta transactions based on 0x
Utilizing Bitmaps to dramatically save on Gas
A simple pattern which can save you a lot of money
Using the new Uniswap v2 as oracle in your contracts
How does the Uniswap v2 oracle function and how to integrate with it
Smock: The powerful mocking tool for Hardhat
Features of smock and how to use them with examples
How to build and use ERC-721 tokens in 2021
An intro for devs to the uniquely identifying token standard and its future
Trustless token management with Set Protocol
How to integrate token sets in your contracts
Exploring the new Solidity 0.8 Release
And how to upgrade your contracts to Solidity 0.8
How to build and use ERC-1155 tokens
An intro to the new standard for having many tokens in one
Leveraging the power of Bitcoins with RSK
Learn how RSK works and how to deploy your smart contracts to it
Solidity Fast Track: Learn Solidity Fast
'Learn X in Y minutes' this time with X = Solidity 0.7 and Y = 20
Sourcify: The future of a Decentralized Etherscan
Learn how to use the new Sourcify infrastructure today
Integrating the 0x API into your contracts
How to automatically get the best prices via 0x
How to build and use ERC-777 tokens
An intro to the new upgraded standard for ERC-20 tokens
COMP Governance Explained
How Compound's Decentralized Governance is working under the hood
How to prevent stuck tokens in contracts
And other use cases for the popular EIP-165
Understanding the World of Automated Smart Contract Analyzers
What are the best tools today and how can you use them?
A Long Way To Go: On Gasless Tokens and ERC20-Permit
And how to avoid the two step approve + transferFrom with ERC20-Permit (EIP-2612)!
Smart Contract Testing with Waffle 3
What are the features of Waffle and how to use them.
How to use xDai in your Dapp
Deploying and onboarding users to xDai to avoid the high gas costs
Stack Too Deep
Three words of horror
Integrating the new Chainlink contracts
How to use the new price feeder oracles
TheGraph: Fixing the Web3 data querying
Why we need TheGraph and how to use it
Adding Typescript to Truffle and Buidler
How to use TypeChain to utilize the powers of Typescript in your project
Integrating Balancer in your contracts
What is Balancer and how to use it
Navigating the pitfalls of securely interacting with ERC20 tokens
Figuring out how to securely interact might be harder than you think
Why you should automatically generate interests from user funds
How to integrate Aave and similar systems in your contracts
How to use Polygon (Matic) in your Dapp
Deploying and onboarding users to Polygon to avoid the high gas costs
Migrating from Truffle to Buidler
And why you should probably keep both.
Contract factories and clones
How to deploy contracts within contracts as easily and gas-efficient as possible
How to use IPFS in your Dapp?
Using the interplanetary file system in your frontend and contracts
Downsizing contracts to fight the contract size limit
What can you do to prevent your contracts from getting too large?
Using EXTCODEHASH to secure your systems
How to safely integrate anyone's smart contract
Using the new Uniswap v2 in your contracts
What's new in Uniswap v2 and how to integrate Uniswap v2
Solidity and Truffle Continuous Integration Setup
How to setup Travis or Circle CI for Truffle testing along with useful plugins.
Upcoming Devcon 2021 and other events
The Ethereum Foundation just announced the next Devcon in 2021 in Colombia
The Year of the 20: Creating an ERC20 in 2020
How to use the latest and best tools to create an ERC-20 token contract
How to get a Solidity developer job?
There are many ways to get a Solidity job and it might be easier than you think!
Design Pattern Solidity: Mock contracts for testing
Why you should make fun of your contracts
Kickstart your Dapp frontend development with create-eth-app
An overview on how to use the app and its features
The big picture of Solidity and Blockchain development in 2020
Overview of the most important technologies, services and tools that you need to know
Design Pattern Solidity: Free up unused storage
Why you should clean up after yourself
How to setup Solidity Developer Environment on Windows
What you need to know about developing on Windows
Avoiding out of gas for Truffle tests
How you do not have to worry about gas in tests anymore
Design Pattern Solidity: Stages
How you can design stages in your contract
Web3 1.2.5: Revert reason strings
How to use the new feature
Gaining back control of the internet
How Ocelot is decentralizing cloud computing
Devcon 5 - Review
Impressions from the conference
Devcon 5 - Information, Events, Links, Telegram
What you need to know
Design Pattern Solidity: Off-chain beats on-chain
Why you should do as much as possible off-chain
Design Pattern Solidity: Initialize Contract after Deployment
How to use the Initializable pattern
Consensys Blockchain Jobs Report
What the current blockchain job market looks like
Provable — Randomness Oracle
How the Oraclize random number generator works
Solidity Design Patterns: Multiply before Dividing
Why the correct order matters!
Devcon 5 Applications closing in one week
Devcon 5 Applications closing
Randomness and the Blockchain
How to achieve secure randomness for Solidity smart contracts?