Skip to content

Code Snippets

Setting up a Local Moonbeam Node

Clone moonbeam-tutorials repo:

git clone -b tutorial-v3 https://github.com/PureStake/moonbeam
cd moonbeam

Install substrate and its pre-requisites:

curl https://getsubstrate.io -sSf | bash -s -- --fast

Run initialization script:

./scripts/init.sh

Add Rust to system path:

source $HOME/.cargo/env

Build the standalone node:

cd ./node/standalone
cargo build --release

Run node in dev mode:

./target/release/moonbase-standalone --dev

Purge chain, clean up any old data from running a ‘dev’ node in the past:

./target/release/moonbase-standalone purge-chain --dev

Run node in dev mode suppressing block information but prints errors in console:

./target/release/moonbase-standalone --dev -lerror

Genesis Account

  • Private key: 99B3C12287537E38C90A9219D4CB074A89A16E9CDB20BF85728EBD97C343E342
  • Public address: 0x6Be02d1d3665660d22FF9624b7BE0551ee1Ac91b

MetaMask

Moonbeam Standalone node details:

  • Network Name: Moonbeam Dev
  • New RPC URL: http://127.0.0.1:9933
  • ChainID: 1281
  • Symbol (Optional): DEV

Moonbase Alpha TestNet:

  • Network Name: Moonbase Alpha
  • New RPC URL: https://rpc.testnet.moonbeam.network
  • ChainID: 1287
  • Symbol (Optional): DEV

Remix

ERC-20 contract Open Zeppeling template:

pragma solidity ^0.7.0;

import 'https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.2.0-solc-0.7/contracts/token/ERC20/ERC20.sol';

// This ERC-20 contract mints the specified amount of tokens to the contract creator.
contract MyToken is ERC20 {
  constructor(uint256 initialSupply) ERC20("MyToken", "MYTOK") public {
    _mint(msg.sender, initialSupply);
  }
}

Truffle

Download Moonbeam Truffle box:

git clone https://github.com/PureStake/moonbeam-truffle-box
cd moonbeam-truffle-box

Compile contracts in Truffle:

node_modules/.bin/truffle compile

Deploy contracts in Truffle:

node_modules/.bin/truffle migrate --network <network_name>

Installing NodeJS, npm, Web3 JS Library, and the Solidity Compiler

Install NodeJS and npm:

curl -sL https://deb.nodesource.com/setup_15.x | sudo -E bash -
sudo apt install -y nodejs

Install the Web3 Javascript library with npm:

npm install web3

Install the Solidity Compiler (for versions v0.7.x) with npm:

npm install solc@0.7.0

Signing Transactions with Web3 and JS

The transaction.js file to make transaction:

const Web3 = require('web3');

// Variables definition
const privKey =
   '99b3c12287537e38c90a9219d4cb074a89a16e9cdb20bf85728ebd97c343e342'; // Genesis private key
const addressFrom = '0x6Be02d1d3665660d22FF9624b7BE0551ee1Ac91b';
const addressTo = '0x44236223aB4291b93EEd10E4B511B37a398DEE55'; // Change addressTo
const web3 = new Web3('http://localhost:9933');

// Create transaction
const deploy = async () => {
   console.log(
      `Attempting to make transaction from ${addressFrom} to ${addressTo}`
   );

   const createTransaction = await web3.eth.accounts.signTransaction(
      {
         from: addressFrom,
         to: addressTo,
         value: web3.utils.toWei('100', 'ether'),
         gas: 21000,
      },
      privKey
   );

   // Deploy transaction
   const createReceipt = await web3.eth.sendSignedTransaction(
      createTransaction.rawTransaction
   );
   console.log(
      `Transaction successful with hash: ${createReceipt.transactionHash}`
   );
};

deploy();

The balances.js file to check balances:

const Web3 = require('web3');

// Variables definition
const addressFrom = '0x6Be02d1d3665660d22FF9624b7BE0551ee1Ac91b';
const addressTo = '0x44236223aB4291b93EEd10E4B511B37a398DEE55';
const web3 = new Web3('http://localhost:9933');

// Balance call
const balances = async () => {
   const balanceFrom = web3.utils.fromWei(
      await web3.eth.getBalance(addressFrom),
      'ether'
   );
   const balanceTo = web3.utils.fromWei(
      await web3.eth.getBalance(addressTo),
      'ether'
   );

   console.log(`The balance of ${addressFrom} is: ${balanceFrom} ETH`);
   console.log(`The balance of ${addressTo} is: ${balanceTo} ETH`);
};

balances();

Compiling and Deploying a Smart Contract with Web3 and JS

The Incrementer.sol example contract:

pragma solidity ^0.7.4;

contract Incrementer {
    uint256 public number;

    constructor(uint256 _initialNumber) public {
        number = _initialNumber;
    }

    function increment(uint256 _value) public {
        number = number + _value;
    }

    function reset() public {
        number = 0;
    }
}

The compile.js file that compiles the contract:

const path = require('path');
const fs = require('fs');
const solc = require('solc');

// Compile contract
const contractPath = path.resolve(__dirname, 'Incrementer.sol');
const source = fs.readFileSync(contractPath, 'utf8');
const input = {
   language: 'Solidity',
   sources: {
      'Incrementer.sol': {
         content: source,
      },
   },
   settings: {
      outputSelection: {
         '*': {
            '*': ['*'],
         },
      },
   },
};
const tempFile = JSON.parse(solc.compile(JSON.stringify(input)));
const contractFile = tempFile.contracts['Incrementer.sol']['Incrementer'];
module.exports = contractFile;

The deploy.js file that deploys the contract:

const Web3 = require('web3');
const contractFile = require('./compile');

// Initialization
const bytecode = contractFile.evm.bytecode.object;
const abi = contractFile.abi;
const privKey =
   '99B3C12287537E38C90A9219D4CB074A89A16E9CDB20BF85728EBD97C343E342'; // Genesis private key
const address = '0x6Be02d1d3665660d22FF9624b7BE0551ee1Ac91b';
const web3 = new Web3('http://localhost:9933');

// Deploy contract
const deploy = async () => {
   console.log(`Attempting to deploy from account: ${address}`);

   const incrementer = new web3.eth.Contract(abi);

   const incrementerTx = incrementer.deploy({
      data: bytecode,
      arguments: [5],
   });

   const createTransaction = await web3.eth.accounts.signTransaction(
      {
         from: address,
         data: incrementerTx.encodeABI(),
         gas: await incrementerTx.estimateGas(),
      },
      privKey
   );

   const createReceipt = await web3.eth.sendSignedTransaction(
      createTransaction.rawTransaction
   );
   console.log(`Contract deployed at address ${createReceipt.contractAddress}`);
};

deploy();

The get.js file to interact with the contract:

const Web3 = require('web3');
const { abi } = require('./compile');

// Initialization
const web3 = new Web3('http://localhost:9933');
const contractAddress = '0xC2Bf5F29a4384b1aB0C063e1c666f02121B6084a';

// Contract Call
const incrementer = new web3.eth.Contract(abi, contractAddress);
const get = async () => {
   console.log(`Making a call to contract at address ${contractAddress}`);
   const data = await incrementer.methods.number().call();
   console.log(`The current number stored is: ${data}`);
};

get();

The increment.js file to interact with the contract:

const Web3 = require('web3');
const { abi } = require('./compile');

// Initialization
const privKey =
   '99B3C12287537E38C90A9219D4CB074A89A16E9CDB20BF85728EBD97C343E342'; // Genesis private key
const address = '0x6Be02d1d3665660d22FF9624b7BE0551ee1Ac91b';
const web3 = new Web3('http://localhost:9933');
const contractAddress = '0xC2Bf5F29a4384b1aB0C063e1c666f02121B6084a';
const _value = 3;

// Contract Tx
const incrementer = new web3.eth.Contract(abi, contractAddress);
const incrementTx = incrementer.methods.increment(_value);

const increment = async () => {
   console.log(
      `Calling the increment by ${_value} function in contract at address ${contractAddress}`
   );
   const createTransaction = await web3.eth.accounts.signTransaction(
      {
         from: address,
         to: contractAddress,
         data: incrementTx.encodeABI(),
         gas: await incrementTx.estimateGas(),
      },
      privKey
   );

   const createReceipt = await web3.eth.sendSignedTransaction(
      createTransaction.rawTransaction
   );
   console.log(`Tx successfull with hash: ${createReceipt.transactionHash}`);
};

increment();

The reset.js file to interact with the contract:

const Web3 = require('web3');
const { abi } = require('./compile');

// Initialization
const privKey =
   '99B3C12287537E38C90A9219D4CB074A89A16E9CDB20BF85728EBD97C343E342'; // Genesis private key
const address = '0x6Be02d1d3665660d22FF9624b7BE0551ee1Ac91b';
const web3 = new Web3('http://localhost:9933');
const contractAddress = '0xC2Bf5F29a4384b1aB0C063e1c666f02121B6084a';

// Contract Tx
const incrementer = new web3.eth.Contract(abi, contractAddress);
const resetTx = incrementer.methods.reset();

const reset = async () => {
   console.log(
      `Calling the reset function in contract at address ${contractAddress}`
   );
   const createTransaction = await web3.eth.accounts.signTransaction(
      {
         from: address,
         to: contractAddress,
         data: resetTx.encodeABI(),
         gas: '40000',
      },
      privKey
   );

   const createReceipt = await web3.eth.sendSignedTransaction(
      createTransaction.rawTransaction
   );
   console.log(`Tx successfull with hash: ${createReceipt.transactionHash}`);
};

reset();