Ankr: Deploy a Smart Contract on Polygon using Ankr that is backed up to Filebase

Learn how to deploy an app on Polygon using Ankr that is backed up to Filebase.

What is Ankr?

Ankr is an API and blockchain node utility that can be used to create API projects and deploy your own blockchain nodes.

The Ankr API can be used in a variety of different applications, making it useful for project development and application creation. Ankr offers a selection of public API endpoints, so there is no need for an account to get started. To create custom, private apps, check out their guide on creating your own Polygon API endpoint here.

In this guide, we’ll use HardHat and Ankr to create a an example app deployed on the using the Polygon Mumbai blockchain network that is backed up to an IPFS bucket on Filebase.

Prerequisites:

This guide was written and tested using Ubuntu 20.04. Commands and workflow may vary depending on your operating system.

1. First, we need a Filebase IPFS bucket.

To do this, navigate to console.filebase.com. If you don’t have an account already, sign up, then log in.

2. Select ‘Buckets’ from the left side bar menu, or navigate to console.filebase.com/buckets.

Select ‘Create Bucket’ in the top right corner to create a new bucket.

3. Enter a bucket name and choose the IPFS storage network to create the bucket.

Bucket names must be unique across all Filebase users, be between 3 and 63 characters long, and can contain only lowercase characters, numbers, and dashes.

4. Next, download and install S3FS-FUSE on a Linux or macOS system.

5. Set up an Access Key file for use with S3FS-FUSE.

Set up a credentials file for S3FS at ${HOME}/.passwd-s3fs. You will need to save your Filebase Access and Secret keys to this file and give it owner permissions. You can do so with the following commands:

echo ACCESS_KEY_ID:SECRET_ACCESS_KEY > ${HOME}/.passwd-s3fs

chmod 600 ${HOME}/.passwd-s3fs

ACCESS_KEY_ID is your Filebase Access key, and SECRET_ACCESS_KEY is your Filebase Secret key. For more information on Filebase access keys, see here.

6. Mount your bucket.

You can mount a Filebase IPFS bucket with the command:

s3fs mybucket /path/to/mountpoint -o passwd_file=${HOME}/.passwd-s3fs -o url=https://s3.filebase.com

  • mybucket: name of your Filebase bucket

  • /path/to/mountpoint

7. Now, navigate into the mounted Filebase bucket.

cd /path/to/mounted/bucket

8. Next, create a new folder to house your project scripts and navigate inside of it.

mkdir polygon-project

cd polygon-project

9. Initialize your npm workspace:

npm init

Provide any necessary configuration options for your workspace, or accept the default configuration settings for your npm workspace.

10. Install Hardhat into your project:

npm install --save-dev hardhat

11. Start Hardhat with the command:

npx hardhat

Select the ‘Create an empty hardhat.config.js’ option.

12. Next, create two new folders to house our project files:

mkdir contracts

mkdir scripts

  • Contracts will be used for storing our smart contract code files.

  • Scripts will be used for storing script files used to deploy and interact with our contract.

13. Navigate into the contracts folder and create a new file called HelloWorld.sol.

Open this file in your IDE of choice, and enter the following content:

// SPDX-License-Identifier: None

// Specifies the version of Solidity, using semantic versioning.
// Learn more: <https://solidity.readthedocs.io/en/v0.5.10/layout-of-source-files.html#pragma>
pragma solidity >=0.8.9;

// Defines a contract named `HelloWorld`.
// A contract is a collection of functions and data (its state). Once deployed, a contract resides at a specific address on the Ethereum blockchain. Learn more: <https://solidity.readthedocs.io/en/v0.5.10/structure-of-a-contract.html>
contract HelloWorld {

   //Emitted when update function is called
   //Smart contract events are a way for your contract to communicate that something happened on the blockchain to your app front-end, which can be 'listening' for certain events and take action when they happen.
   event UpdatedMessages(string oldStr, string newStr);

   // Declares a state variable `message` of type `string`.
   // State variables are variables whose values are permanently stored in contract storage. The keyword `public` makes variables accessible from outside a contract and creates a function that other contracts or clients can call to access the value.
   string public message;

   // Similar to many class-based object-oriented languages, a constructor is a special function that is only executed upon contract creation.
   // Constructors are used to initialize the contract's data. Learn more:<https://solidity.readthedocs.io/en/v0.5.10/contracts.html#constructors>
   constructor(string memory initMessage) {

      // Accepts a string argument `initMessage` and sets the value into the contract's `message` storage variable).
      message = initMessage;
   }

   // A public function that accepts a string argument and updates the `message` storage variable.
   function update(string memory newMessage) public {
      string memory oldMsg = message;
      message = newMessage;
      emit UpdatedMessages(oldMsg, newMessage);
   }
}

This is a sample Hello World smart contract that creates a sample application using a Hello World function.

14. Next, install the dotenv package into your project directory:

npm install dotenv --save

15. Then, create a .env file.

Note: This .env file will hold your Ankr API URL and your Metamask Private Key. Do not use this method if you are utilizing a public Filebase bucket. This method is only recommended for use with a private Filebase bucket so that your information is secure.

Enter the following content in your .env file:

API_URL = "https://rpc.ankr.com/polygon"
PRIVATE_KEY = "your-metamask-private-key"

This contract uses the Ankr public Polygon endpoint. Learn more about Ankr by checking out their website here.

16. Next, install the Ethers.js library:

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

17. Then, open your hardhat.config.js file. Replace the contents with the following:

/**
* @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: "polygon_mumbai",
   networks: {
      hardhat: {},
      polygon_mumbai: {
         url: API_URL,
         accounts: [`0x${PRIVATE_KEY}`]
      }
   },
}

18. Now it’s time to compile your contract:

npx hardhat compile

19. Now that your contract has been compiled, we need to write a script to deploy the contract onto the Polygon Mumbai network.

Navigate into the scripts directory and create a new file called deploy.js with the following content:

async function main() {
   const HelloWorld = await ethers.getContractFactory("HelloWorld");

   // Start deployment, returning a promise that resolves to a contract object
   const hello_world = await HelloWorld.deploy("Hello World!");   
   console.log("Contract deployed to address:", hello_world.address);
}

main()
  .then(() => process.exit(0))
  .catch(error => {
    console.error(error);
    process.exit(1);
  });

20. Now it’s time to deploy your contract using the command:

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

Congrats! You’ve deployed a simple smart contract onto the Polygon Mumbai network! To get a more detailed idea of what happened behind the scenes, take a look at the Ankr API dashboard for your project. From there, you can see all of the requests made with your API URL, and the associated JSON RPC for each request.

Last updated