Smart Contract Series

Deploy Smart Contract on Binance Smart Chain(BSC) Testnet

How to deploy smart contract on Binance Smart Chain(BSC) Testnet using Hardhat

Chikku George
BLOCK6

--

Binance Smart Chain

BSC chain works in parallel with Binance chain. It enables the creation of smart contracts for tokens on Binance chain. It is based on the Proof of Stake consensus mechanism.

Hardhat

Hardhat is a development environment where we can compile, run, deploy, debug and test our smart contracts.

Now let’s setup our project!

Step 1: Add BSC Testnet to your Metamask and get some fake BNB

Credit: Author
Credit: Author

BSC Testnet Details:

RPC URL: https://bsctestapi.terminet.io/rpc

Chain ID: 97

Currency Symbol: tBNB

Alternative RPC URLs can find at chainlist.

Get fake BNB from BNB Testnet Faucet.

Step 2: Initialize the project

npm init

It will create a new package.json file which you can edit accordingly.

{  
"name": "my-bsc-testnet",
"version": "1.0.0",
"description": "",
"main": "index.js",
"engines": {
"node": "12.19.0"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon index.js"
},
"keywords": [],
"author": "",
"license": "ISC"
}

Step 3: Write smart contract

Create a folder contracts/ and create a new file called MyBSCTestnet.sol.

Make sure to install OpenZeppelin library as we are extending classes from OpenZeppelin Contracts library. npm install @openzeppelin/contracts.

Copy the following code to your smart contract file.

// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;
import “@openzeppelin/contracts/token/ERC721/ERC721.sol”;
import “@openzeppelin/contracts/utils/Counters.sol”;
import “@openzeppelin/contracts/access/Ownable.sol”;
contract MyBSCTestnet is ERC721, Ownable {
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
using Strings for uint256;
mapping(uint256 => string) private _tokenURIs;
string private _baseURIextended;
constructor() ERC721(“MyBSCTestnet”, “MyBSCTestnet”) {}
function setBaseURI(string memory baseURI_) external onlyOwner {
_baseURIextended = baseURI_;
}
function _setTokenURI(uint256 tokenId, string memory _tokenURI)
internal
virtual
{
require(
_exists(tokenId),
“ERC721Metadata: URI set of nonexistent token”
);
_tokenURIs[tokenId] = _tokenURI;
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseURIextended;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
“ERC721Metadata: URI query for nonexistent token”
); string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
if (bytes(base).length == 0) {
return _tokenURI;
}
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return string(abi.encodePacked(base, tokenId.toString()));
}
function mintNFT(address recipient, string memory _tokenURI)
public onlyOwner
returns (uint256)
{
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(recipient, newItemId);
_setTokenURI(newItemId, _tokenURI);
return newItemId;
}
}

Step 4: Install Hardhat & Ethers.js

npm install --save-dev hardhat 
npm install --save-dev @nomiclabs/hardhat-ethers 'ethers@^5.0.0'

Step 5: Create Hardhat project

npx hardhat

You will get a prompt like below and select “create an empty hardhat.config.js”. It will create an empty hardhat.config.js file in your project folder.

888    888                      888 888               888
888 888 888 888 888
888 888 888 888 888
8888888888 8888b. 888d888 .d88888 88888b. 8888b. 888888
888 888 "88b 888P" d88" 888 888 "88b "88b 888
888 888 .d888888 888 888 888 888 888 .d888888 888
888 888 888 888 888 Y88b 888 888 888 888 888 Y88b.
888 888 "Y888888 888 "Y88888 888 888 "Y888888 "Y888Welcome to Hardhat v2.8.0? What do you want to do? ...
Create a basic sample project
Create an advanced sample project
Create an advanced sample project that uses TypeScript
> Create an empty hardhat.config.js
Quit

Step 6: Update hardhat.config.js

/**
* @type import(‘hardhat/config’).HardhatUserConfig
*/
require(“dotenv”).config();
require(“@nomiclabs/hardhat-ethers”);
const { API_URL, PRIVATE_KEY } = process.env;
module.exports = {
solidity: "0.8.9",
defaultNetwork: "bsc",
networks: {
hardhat: {},
bsc: {
url: API_URL,
accounts: [`0x${PRIVATE_KEY}`],
}
}
};

Make sure your .env file contains API_URL and PRIVATE_KEY. Your .env file should look like below:

API_URL = https://rpc.sepolia.online
PRIVATE_KEY = 'Metamask Private Key'
For other RPC URLs, you can refer to chainlist

Step 7: Compile smart contract

npx hardhat compile

Step 8: Write deploy script

Create another folder called scripts/ and create a new file called deploy.js and add the following content to it.

async function main() {  
const MyBSCTestnet = await ethers.getContractFactory("MyBSCTestnet");
const MyBSCTestnetContract = await MyBSCTestnet.deploy();
console.log("Contract deployed to address:", MyBSCTestnetContract.address);
}
main().then(() =>
process.exit(0)
).catch((error) => {
console.log(error);
process.exit(1);
});

Step 9: Deploy smart contract

npx hardhat run scripts/deploy.js --network bsc

You will get a console output like below:

Contract deployed to address: 0xf4db788182019C688565b7d3DF85F0355d4f047f

Now you can verify the deployed contract address on bsc testnet block explorer. The transaction will look something like below:

Credit: Author

Great!

You have successfully deployed your smart contract on BSC Testnet.

Happy DEPLOYing:)

Contents distributed by Learn.Block6.tech

👉 Discord — Live Talks

👉 Twitter — Latest articles

👉 LinkTr.ee

--

--

Chikku George
BLOCK6
Writer for

Software Engineer | ReactJs | NodeJs | Blockchain Enthusiast