Ethereum is turing complete : Any software that is able to run code written by a developer or executed by an end user.

Smart contract : A contract written in code. More specifically, it is an object on the Ethereum blockchain that contains EVM code functions. Will continue running forever. Will self destruct when specified if a kill switch is created inside.

Solidity : High level language for coding and deploying smart contracts.

Ethereum aims at being a globally distributed computer. “World computer”

Why Ethereum ?

“A decentralized platform that runs smart contracts: applications that run exactly as programmed without any possibility of downtime, censorship, fraud, or third-party interference” – Ethereum.org

Generalized platform that allows people to develop on it. Go beyond basic functions whitout having to update the protocol.

Operating system – the world computer

Ethereum vs Bitcoin State

In Bitcoin UTXO’s (unspent transaction output) are what represents the state of the blockchain

In Ethereum the world state is composed of :

  • Nonce + Balance + Storage hash
  • Code hash + Account Storage + Ethereum virtual code

In bitcoin all the info stays on the blockchain

On Ethereum it is a bit different, blockchain state is separated from account state and there is a mapping between them using Patricia trees (Practical Algorithm To Retrieve Information Coded In Alphanumeric)

Bitcoin vs Ethereum in detail

Keep in mind that Ethereum is currently migrating to POS instead of POW (Casper project)

Ethereum Virtual Machine

EVM is the machine that powers and runs the Ethereum platform (often called the operating system). All nodes in the world run the EVM and validate transactions. This is what we refer as to the World Computer. Manages :

  • State
  • Accounts
  • Transactions
  • Gas and Fees

EVM (technical definition) : A virtual machine that executes code. A runtime environment for Smart Contracts. There are multiple implementations of EVMs like Go Ethereum (GoEth), parity.. Enabling us to access the EVM with different programing languages if you want. It is the hearth of Ethereum.

Write Contract code -> Compile contract (Bytecode, assembly) -> EVM

Some portion of EVM is dedicated to the testnet (test network).

Ethereum tooling Ecosystem

  • Etherscan : Search the blockchain for transactions, accounts, smart contracts. Block explorer
  • Metamask : Browser wallet
  • Remix : Online integrated dev environment to create smart contracts
  • web3.js : web3 library to read and interact with the Ethereum blockchain
  • Infura : connection to the ethereum blockchain, access to endpoint URLs (node as a service)
  • Ganache : Local development
  • Truffle : Creating and deploying applications
  • Geth : Download full node, but we can use infura

Introduction to DApps

Decentralized Applications, known as DApps, are the applications that run on the Ethereum Network.

DApps run on decentralized networks powered by a network of computers. Standard Applications run on the computation of centralized networks owned by companies.

Alright time to deploy a small one, head over to https://remix.ethereum.org/

Create a new file called myMessage.sol and copy paste the code below :

pragma solidity ^0.4.24; //tell the compiler which solidity version to use, ^ tells to look the most recent version of solidity starting from this version, without the ^ it would say to use exactly this version

contract Message {
    string myMessage;

    function setMessage(string x) public {
        myMessage = x; 
    }

    function getMessage() public view returns (string) { //Publicly available, only meant to view information, returns a string
        return myMessage;
    }
}

Compile it with the right version

Deploy it using the JavaScript VM. You now have a depoyed Contract and you can set a new message and then retrieve the saved message :

It is important to understand that each interaction with a smart contract is considered as a transaction and is therefore saved on the blockchain and requires a fee to be paid (unless it’s only view 🙂 )

DApp stack example :

  • Local Ethereum Blockchain : Back end data storage
  • Web3 : Javascript Ethereum API
  • Metamask : Web3 provider
  • Remix : In browser IDE
  • Node.js : Javascript runtime environment
  • Smart contract : Code executed on the EVM
  • JS/HTML/CSS : Website front end

Tools introduced by the course that I will not explain as they are quite trivial :

  • Etherscan (Etherscan.io) permits to really search anything you want on the Ethereum blockchain. Including the richest owners ! Including as well the main tokens and the main contracts of those tokens and their code. Etherscan is basically you’re best friend when interacting with the Ethereum blockchain.
  • Metamask, you browser wallet and your best friend to interact with the blockchain and hold your tokens and cryptocurrencies. Metamask is a great tool for getting started with the blockchain. It provides a bridge into the Ethereum ecosystem that you can use to quickly get started with existing applications on the Ethereum network. It also provides this same functionality to users that will want to interact with the DApps that you create.

Main nets and test nets :

  • Mainnet : Production, live ethereum blockchain, proof of work (currently migrating to proof of stake)
  • Ropsten : Test net (proof of work)
  • Kovan : Test net (proof of authority)
  • Rinkeby : Test net (proof of authority)
  • You can easily request a few Ethers on test nets to play around by using faucets (like we did for bitcoin), here is one : https://faucet.metamask.io/

Deploying to test net :

  • And here is my example transaction : https://ropsten.etherscan.io/tx/0x9b77b6d3dbe01768a2fa3ab13582f2e4d3740ffb4e2f43fafdc4ca01cade21c3

Now we can deploy our previous smart contract on the blockchain using our test Ethers on ropsten

I changed the environment to “Injected Web3” now, this tells Remix that you will deploy using your metamask wallet. And in Metamask I connected to the test net, verify under “Injected Web3” that you are indeed using the Ropsten test network if you don’t want to pay real Ethers for deploying a dummy smart contract !

When you click you will be asked to confirm and sign the transaction in your metamask (like in the screenshot above) and when you do the transaction is broadcasted to the network and your smart contract is deployed. You can see in the console the transaction and find it on etherscan. In deployed contracts you can see the the actual address of the new live smart contract !

  • My transaction : https://ropsten.etherscan.io/tx/0xcf65f5045dc1440a0384c54ff81aa42c2d73ad2207b878364e8dc82b0f61079f
  • My contract : https://ropsten.etherscan.io/address/0xbfb81e1742b8bc96ee82a1c3152135f1802837b0

You can’t see the code of your contract, to enable this you need to do the verification of the smart contract in etherscan. Here :

But we don’t care right now. You can test to register a message via your smart contract and then see it on etherscan by selecting the transaction, clicking on “more” and then selecting UTF-8 in “view input as” :

Setting up the API to the network (web3.js) :

We will be using web3.js : Installing web3.js will allow you to read and write data to the Ethereum blockchain and programmatically interact with the Ethereum blockchain. Getting familiar with this tool is a huge part of building decentralized applications. From their site : web3.js is a collection of libraries that allow you to interact with a local or remote ethereum node using HTTP, IPC or WebSocket.

to install web3 :

//Make a new folder for your project
mkdir projectFolder <----don't name this folder web3
cd projectFolder

//Initialize node to create a package.json file and chose defaults
npm init

//Install web3 and save it as a dependency to package.json
npm install web3 --save

//Open node from the terminal 
node

//Require web3 as Web3 variable
var Web3 = require('web3')

//Read the Web3 Variable
Web3

A few useful libraries :

  • Web3 : The main class of anything related Ethereum
  • web3.eth : Allows you to interact with an Ethereum blockchain and Ethereum smart contracts.
  • web3.eth.accounts : Contains functions to generate Ethereum accounts and sign transactions and data.
  • web3.eth.personal : Allows you to interact with the Ethereum node’s accounts
  • web3.utils : Provides utility functions for Ethereum dapps and other web3.js packages

Web3 is the API, now it is installed but we need now to make the connection to the Ethereum blockchain and for this we will use Infura.

Connecting to the Ethereum blockchain (Infura):

By connecting web3 to Infura, you will be able to access the Ethereum main and test networks using the Infura API. You need the connection to make your call go through.

Without a service la infura you would need to use Geth in order to have your local version of the blockchain, which takes a lot of space etc. Infura provides a way to connect to nodes directly without having to setup a local node.

Steps :

  1. Setup an infura account and get the network endpoint they provide
  2. Terminal you connect to Web3
  3. Withing web3 you setup a connection to the endpoint infura provides (1 line of code :))

Infura : Infura allows you to connect to the Ethereum blockchain without running a full node. It’s a lightweight alternative to downloading the entire blockchain to your local device. It makes the connection that allows you to use the functionality provided by web3.

To create an infura account, go to infura.io. And then create a project :

Connect web3 with Infura

Super easy, you copy paste one of the endpoints listed in Keys at infura after chosing the network you want to use and then you open a terminal in your project and :

var Web3 = require('web3')

Set a variable url to a string containing this endpoint url :

var url = 'https://ropsten.infura.io/v3/5576598e840b447c92db422fbbbac0be'

Set a variable web3 = to a new instance of Web3 connected to the url.

var web3 = new Web3(url)

Call the variable

web3

You are now connected to the Ethereum network !

Now let’s try it out and get the balance from an adress using your terminal.

Here is an adress : 0x983c1C3C23C4C58fa1F89195CD86803D899A6cc9

Set a variable equal to a string of the address you chose

var address = '0x983c1C3C23C4C58fa1F89195CD86803D899A6cc9'

Use web3 to read the balance of this account and set it to the variable balance.

web3.eth.getBalance(address, (err, bal) => { balance = bal })

 Read the variable balance to the terminal

balance

Here it is :

if you want to see it with the decimals you have to divide it by 10^18, or use a utils function :

web3.utils.fromWei('815572901210764252','ether');

This outputs : 0.815572901210764252

Ethereum Accounts

Ethereum has 2 types of accounts :

  • Externally owned accounts (EOA0s) : used by regular users. it contains : Account balance and transaction count. they can send transactions, initiate smart contracts, transfer value from their wallets.
  • Contract Account (CA’s) : controlled by the code in smart contracts, they hold Account balance, transaction count and smart contract code. they can send transactions, initiate smart contracts, Execute smart contracts, manipulate storage

Externally owned accounts are owned by users with private keys while contract accounts are held by smart contracts. Transaction counts on EOA’s refer to the number of transactions that user made while on CA’s it refers to the number of times it has deployed other smart contracts. Many of the contents of these accounts are the same but contract accounts also hold the code from the deployed contract.

Account state variables :

  • Nonce : number of transactions on the account
  • Account balance : total value of ether available on the account in Wei (1 Ether = 10^18 Wei)
  • Storage hash : root node of the patricia tree
  • Code hash : hash of the code within the smart contract, for EOA it is empty, for CAs it is filled and can’t be changed

To summarize :

EOA :

  • Tied to a private key
  • Doesn’t hold code
  • Maintains ether balance
  • Can send transactions

CA :

  • Has code
  • Maintains ether balance
  • executes code when triggered

Now let’s read the number of transactions on an account

let’s use another method :

web3.eth.getTransactionCount(address [, defaultBlock] [, callback])

with my address :

web3.eth.getTransactionCount("0x983c1C3C23C4C58fa1F89195CD86803D899A6cc9").then(console.log);

56 transactions !

Read a Contract Account

Pick one of the tokens on Etherscan and go the contract and then to the code section and copy the ABI :

I picked the DAI stablecoin contract

Set a variable ABI to the value of the ABI in the contract code.

var abi = PASTE ABI FROM CONTRACT
abi

Well formated abi :

Set the address of the contract to a variable named contractAddress.

var contractAddress = '0x6B175474E89094C44Da98b954EedeAC495271d0F'

Pass the abi and contractAddress into the web3.eth.Contract function and assign it to a varialbe named contract.

var contract = new web3.eth.Contract(abi, contractAddress)

View the details of the contract.

contract

View the methods from the contract :

Call methods for this contract from your terminal :

contract.methods.name().call((err, result) => { console.log(result )})
contract.methods.symbol().call((err, result) => { console.log(result )})
contract.methods.totalSupply().call((err, result) => { console.log(result )})

You just read the name, the symbol and the total supply of the dai smart contract !

Ganache

Ganache gives you a way to set up a local blockchain pre-loaded with accounts and ether. Basically it replaces the need to use the testnet and have to request test ethers to pay for your transaction and you don’t have to wait for confirmations and etherscan for your transactions. Ganache is a local blockchain to be used for your development and testing purposes.

Ganache allows you to set up your own local blockchain. It comes preloaded with 10 accounts, each containing 100 ether. This gives you a way to make test transactions between many accounts without needing to worry about stocking up on test ether or paying for real ether.

Here is where you can get it : https://www.trufflesuite.com/ganache

You can use either the GUI interface or the command line to install it and to run it.

to run Ganache in the terminal :

In case, like me, you could not run the script due to execution policy, you have to change said policy, like this :

  1. Press Win Key + R. A a small window will pop up as shown in the screenshot below.
  2. Type in powershell and press Ctrl+Shift+Enter or press and hold Ctrl+Shift.
  3. Click OK to make PowerShell run as administrator
  4. Type “Set-ExecutionPolicy RemoteSigned”

Connect Ganache to Web3

We do exactly like before with infura, but we don’t use the infura endpoint but rather the ganache RPC server. done !

Step 1: Run Ganache

Step 3: Create and change into a directory

mkdir projectFolder -- <----don't name this folder web3
cd projectFolder

Step 4: Initialize an instance of npm

npm init -y
npm install web3 --save

Step 5: Start node in terminal

node

Step 6: Require web3 into node

var Web3 = require('web3')

Step 7: Set the web3 variable to an instance of Web3 on your URL

var web3 = new Web3('HTTP://127.0.0.1:7545') -- // 8545 if you are using ganache-cli

Step 8: Call this web3 variable to read information to your terminal

web3

Step 9: Test the connection by reading the list of accounts

web3.eth.getAccounts().then(accounts => console.log(accounts));

Connect Web3 to Ganache from an IDE

Easy, create a folder in your favorite IDE (I use VS code) and then install npm and web3 as a dependency :

npm init
npm install web3 --save

Then create an index.js file there and add inside :

var Web3 = require('web3')
var url = 'HTTP://127.0.0.1:7545' // 8545 if using ganache-cli
var web3 = new Web3(url)
web3.eth.getAccounts().then(accounts => console.log(accounts));

run node index.js to execute the code, voila :

Create Ethereum Transactions

Transaction Fields

  • Nonce : Transaction count from the senders account
  • Gas price : Price per unit of gas you are willing to pay for executing the code in your smart contract
  • gas limit : Specifies the max number of computational steps the transaction is allowed.
  • Value : The amount of Ether you want to send.
  • Data, init : Information used to record the creation and execution of smart contracts.

Create a Transaction

ensure you have installed both dependencies to your npm initialization

npm install ethereumjs-tx --save
npm install web3 --save
/*##########################

CONFIGURATION
##########################*/

// -- Step 1: Set up the appropriate configuration 
var Web3 = require("web3") 
var EthereumTransaction = require("ethereumjs-tx").Transaction 
var web3 = new Web3('HTTP://127.0.0.1:7545')

// -- Step 2: Set the sending and receiving addresses for the transaction. 
var sendingAddress = '0x74649f71d91461f5Afd51aeBCB8323f1C123926B' 
var receivingAddress = '0x9018f48653E93bEc93acF7d395478463A0Ce38E5'

// -- Step 3: Check the balances of each address 
web3.eth.getBalance(sendingAddress).then(console.log) 
web3.eth.getBalance(receivingAddress).then(console.log)

/*##########################

CREATE A TRANSACTION
##########################*/

// -- Step 4: Set up the transaction using the transaction variables as shown 
var rawTransaction = { 
    nonce: 1, 
    to: receivingAddress, 
    gasPrice: 20000000, 
    gasLimit: 30000, 
    value: 10000000000000000000, 
    data: web3.utils.toHex("") }

// -- Step 5: View the raw transaction 
console.log(rawTransaction)


// -- Step 6: Check the new account balances (they should be the same) 

web3.eth.getBalance(sendingAddress).then(console.log) 
web3.eth.getBalance(receivingAddress).then(console.log)

// Note: They haven't changed because they need to be signed...

/*##########################

Sign the Transaction
##########################*/

// -- Step 7: Sign the transaction with the Hex value of the private key of the sender 
var privateKeySender = '4ca9bdb23d6b357b41ecdaa77c4b839ba073abfab954b12c0e476a76138e6a52' 
var privateKeySenderHex = new Buffer.from(privateKeySender,'hex')
var transaction = new EthereumTransaction(rawTransaction) 
transaction.sign(privateKeySenderHex)

/*#########################################

Send the transaction to the network
#########################################*/

// -- Step 8: Send the serialized signed transaction to the Ethereum network. 
var serializedTransaction = transaction.serialize(); 
web3.eth.sendSignedTransaction(serializedTransaction);

I had to change a little bit the code as apparently ethereumjs-tx has changed and the syntax is slightly different but I made it work

  • I booked one transaction that transfer a small amount from one of my Ganache wallets to another one (nonce = 0 )
  • And then I booked a bigger transaction that transfered 10 ETH from 1 account to another, the code above is the second transaction so here the nonce is 1 (as it has to increment each time there is a transaction on the sending account)

And the result:

Gas and Fees

Gas is needed to incentivize miners to pick up and validate transactions. It’s a small fee paid for the cost of each bit of code executed to complete a smart contract. While the gas is specific to execution costs, it can be converted to its equivalent value in ether and given to the miner as reward for their effort. Gas price = what you are willing to pay per unit of gas to execute the code or your transaction, Gas limit : maximum of gas price you are willing to pay. the nore you pay the faster your transaction will be integrated into a block.

Ethereum stats :

You can check various metrics concerning Ethereum here : https://ethstats.net/

A few terms :

  • Best block : The highest block number of the longest valid chain, said differently it is heavy with cumulative difficulty
  • Uncles : Orphaned blocks and unlike other blockchains, in Ethereum they are included and rewarded. The dashboard displays current block uncle count and that from last 50 blocks
  • Last block : The time since the last mined block in seconds
  • Average block : Average time between two block (excl. uncles) – should display 15 seconds unless the network is really slow
  • Difficulty : Also known as the mining difficulty to find a new block.

And here are a few additional functions to get some metrics through web3 :

/*##########################

METRICS
##########################*/
web3.eth.getGasPrice().then(console.log); //Get gas price
web3.eth.getUncle(500, 0).then(console.log); //get uncle
web3.eth.getBlockTransactionCount("0xe751259390762c5f60f1393b620bbf8dd37825e60c445d5649d15367e044dbe1").then(console.log);//Get Block Transaction Count

Deploy to Your Local Blockchain

Alright this was tricky as I had to disable the brave shield in remix and then change the URL or remix to http instead of https in order to manage to connect it to my local blockchain but it worked.

Int he deployment section simply chose Web3 Provider as the environment, then chose port 7545 instead of 8545 if you want to use Ganache GUI. It will automatically select your first wallet in your local blockchain.

You click on Deploy and.. voila :

And here is an additional instruction to get the number of transaction from an account :

web3.eth.getTransactionCount("0x74649f71d91461f5Afd51aeBCB8323f1C123926B").then(console.log);//Get Account Transaction Count

Push Smart Contract Data to a Website

Alright I created a new folder, npm init to get a project and then installed web3 as a dependendy.

I then create an index.html file :

<!DOCTYPE html>
<html lang="en">

<head>
    <!--<meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">-->
    <title>Deploy a Remix Contract</title>

    <!--<link rel="stylesheet" type="text/css" href="main.css">-->

    <script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js/dist/web3.min.js"></script>
</head>

<body>
    <div>
        <h1>Deploy a Remix Contract</h1>
    </div>

    <script>

        // Connect a the web3 provider
        if (typeof web3 !== 'undefined') {
            web3 = new Web3(web3.currentProvider);
        } else {
            web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:7545"));
        }

        // Set a default account
        web3.eth.defaultAccount = web3.eth.accounts[0];

        // Get the contract address
        var RemixContract = new web3.eth.Contract([
	{
		"constant": false,
		"inputs": [
			{
				"name": "x",
				"type": "string"
			}
		],
		"name": "setMessage",
		"outputs": [],
		"payable": false,
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"constant": true,
		"inputs": [],
		"name": "getMessage",
		"outputs": [
			{
				"name": "",
				"type": "string"
			}
		],
		"payable": false,
		"stateMutability": "view",
		"type": "function"
	}
],'0x0117437a70562C98A5c7ba1699d24653da51B028');

        // Get the contract abi
        //var myMessage = RemixContract.at('0x0117437a70562C98A5c7ba1699d24653da51B028');

        console.log(RemixContract.options.jsonInterface);

    </script>
</body>

</html>

in the web3.eth.Contract I simply copy pasted the ABI from the contract in remix and then the address of the smart contract. Then I print the Interface to the console. Double click on your index.html and then hit F12 :

Ethereum Secret Messenger with a Front end

This time we will construct a front as well, as usual :

npm init
npm install ethereumjs-tx --save
npm install web3 --save

Then we create and index.html :

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Deploy a Remix Contract</title>

    <link rel="stylesheet" type="text/css" href="main.css">

    <script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js/dist/web3.min.js"></script>
</head>

<body>
    <div>
        <h1>Ethereum Secret Messenger</h1>
        <hr>

        <label for="message">This site writes a secret message to the Ethereum
            blockchain!</label>
        <input id="userInput" type="text">

        <button id="setMessageButton">Set secret message</button>
    </div>

    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>

    <script>

        // Connect a the web3 provider
        if (typeof web3 !== 'undefined') {
            web3 = new Web3(web3.currentProvider);
        } else {
            web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:7545"));
        }

        // Set a default account
        web3.eth.defaultAccount = web3.eth.accounts[0];

        // create an instance of the contract with the abi, the contract address and an an address of the sender
        var RemixContract = new web3.eth.Contract([
	{
		"constant": false,
		"inputs": [
			{
				"name": "x",
				"type": "string"
			}
		],
		"name": "setMessage",
		"outputs": [],
		"payable": false,
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"constant": true,
		"inputs": [],
		"name": "getMessage",
		"outputs": [
			{
				"name": "",
				"type": "string"
			}
		],
		"payable": false,
		"stateMutability": "view",
		"type": "function"
	}
],'0x0117437a70562C98A5c7ba1699d24653da51B028',{from: '0x74649f71d91461f5Afd51aeBCB8323f1C123926B'});
        
        // create an instance of the methode you want to call
		var msgObject = RemixContract.methods.setMessage("Hello");

        $("#setMessageButton").click(function () {
            //call the function
            msgObject.send(function (err, res) {
				if (!err) {
					console.log(res);
				} else {
					console.log(err);
				}});
            console.log($("#userInput").val())
        });

    </script>
</body>

</html>

and a main.css :

body {
    background-color:#F0F0F0;
    padding: 2em;
    font-family: 'Raleway','Source Sans Pro', 'Arial';
}

label {
    display:block;
    margin-bottom:10px;
}
input {
    padding:10px;
    width: 50%;
    margin-bottom: 1em;
}

button {
    margin: 2em 0;
    padding: 1em 4em;
    display:block;
    background-color: #00BCD4 
}

#setMessageButton {
    padding:1em;
    background-color:#fff;
    margin: 1em 0;
    background-color: #00BCD4;
    color: #fff 
}

And now when we start the front end we have a button, let’s log a few things in the blockchain :

Again, it was a pain to modify the code to make it work with latest version of js. But whatever, good debugging exercise !

Here is the documentation : https://web3js.readthedocs.io/en/v1.2.0/web3-eth-contract.html#id12

 Ethereum secret message, but this time with Metamask !

In the previous section we were sending the transaction locally. This time we will use metamask ! The code in the course is heavily outdated so I had to do several additional things. First of all I had to install lite server and the extension in VS code as well. then to start the application simply right click in the html file and then select “open with live server”.

Then I separated the hmtl code from the .js just to be more clear. And finally I also imported the private key of the first account from ganache into my metamask to be able to sign transactions with it.

Here is the code :

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Deploy a Remix Contract</title>

    <link rel="stylesheet" type="text/css" href="main.css">

    <script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js/dist/web3.min.js"></script>
</head>

<body>
    <div>
        <h1>Ethereum Secret Messenger</h1>
        <hr>

        <label for="message">This site writes a secret message to the Ethereum
            blockchain!</label>
        <input id="userInput" type="text">

        <button id="setMessageButton">Set secret message</button>
    </div>

    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>

    <script src="app.js"></script>
</body>

</html>
// Connect a the web3 provider
async function init() {
    // Modern Dapp browsers (like Brave)
    if (window.ethereum) {
        web3 = new Web3(window.ethereum);
        try {
            // Request account access
            async () => { await window.ethereum.enable() }
        } catch (error) {
            // User denied account access...
            console.error("User denied account access")
        }
    }
};
init();

if(window.addEventListener) {
    window.addEventListener('load',ethereum.enable()); //without this it was not working for some reason
}

// Get the contract address
var RemixContract = new web3.eth.Contract([
    {
        "constant": false,
        "inputs": [
            {
                "name": "x",
                "type": "string"
            }
        ],
        "name": "setMessage",
        "outputs": [],
        "payable": false,
        "stateMutability": "nonpayable",
        "type": "function"
    },
    {
        "constant": true,
        "inputs": [],
        "name": "getMessage",
        "outputs": [
            {
                "name": "",
                "type": "string"
            }
        ],
        "payable": false,
        "stateMutability": "view",
        "type": "function"
    }
],
    '0x849Dd94b6fE5c00212963e98F4E5eD92201Bee23',//contract address 
    {
        from: '0xA3B52D80555416b16CCE59348B0D90345A51039A',//your address 
        gasPrice: '1000000',
        gas: '1048576'
    }
);

RemixContract.defaultAccount = '0xA3B52D80555416b16CCE59348B0D90345A51039A'; //your address 
// console.log(RemixContract);

$("#setMessageButton").click(function () {
    let message = $("#userInput").val();
    RemixContract.methods.setMessage(message)
        .send({ from: RemixContract.defaultAccount },
            (err, result) => { message = result });
    console.log($("#userInput").val())
});

And in Ganache :

Deploying the smart contract to the test network and interacting with it through metamask

First you have to to change your remix back to the https version to be able to connect to ropsten. so just load it back. Then you have to redeploy the smart contract on the testnet, simply connect to ropsten with your metamask and deploy the contract there. Here is mine :

https://ropsten.etherscan.io/address/0x7e40798541F557C9d77350Ef7a362D8617691D79

Then simply change the contract address in the code to your new address on Ropsten. Don’t worry about infura, no need to do anything there as you are transacting anyway through your metamask which is connected to ropsten.

the .js :

// Connect a the web3 provider

async function init() {
    // Modern Dapp browsers (like Brave)
    if (window.ethereum) {
        web3 = new Web3(window.ethereum);
        try {
            // Request account access
            async () => { await window.ethereum.enable() }
        } catch (error) {
            // User denied account access...
            console.error("User denied account access")
        }
    }
};
init();

if(window.addEventListener) {
    window.addEventListener('load',ethereum.enable()); //without this it was not working for some reason
}


// Get the contract address
var RemixContract = new web3.eth.Contract([
    {
        "constant": false,
        "inputs": [
            {
                "name": "x",
                "type": "string"
            }
        ],
        "name": "setMessage",
        "outputs": [],
        "payable": false,
        "stateMutability": "nonpayable",
        "type": "function"
    },
    {
        "constant": true,
        "inputs": [],
        "name": "getMessage",
        "outputs": [
            {
                "name": "",
                "type": "string"
            }
        ],
        "payable": false,
        "stateMutability": "view",
        "type": "function"
    }
],
    '0x7e40798541F557C9d77350Ef7a362D8617691D79',//contract address 
    {
        from: '0x983c1C3C23C4C58fa1F89195CD86803D899A6cc9'//your address 
        //gasPrice: '1000000',
        //gas: '1048576'
    }
);

RemixContract.defaultAccount = '0x983c1C3C23C4C58fa1F89195CD86803D899A6cc9'; //your address 
// console.log(RemixContract);

$("#setMessageButton").click(function () {
    let message = $("#userInput").val();
    RemixContract.methods.setMessage(message)
        .send({ from: RemixContract.defaultAccount },
            (err, result) => { message = result });
    console.log($("#userInput").val())
});

You then deploy again your index.html with lite server and record a new word, sign it with your metamask and done, your transaction is on the testnet and you sent it through your front end application !

proof :

Improve the Deployment Process with Truffle

Truffle replaces Remix.

https://www.trufflesuite.com/ : The Truffle Suite gets developers from idea to dapp as comfortably as possible

Step 1: Install Truffle


npm install truffle -g

Step 2: Set up a project directory


mkdir myProject
cd myProject

Step 3: Initialize Truffle


truffle init

This will create a development framework in your project folder :

In the truffle-config.js file you can setup the connection of your project, here it is local. In the terminal type “truffle” to have the list of available commands. Good now let’s jump into the truffle console :

truffle console

Step 1: Enter the truffle console


truffle console

Step 2: Compile your contract


A test contract has been created when you initialized truffle. You can compile this contract using the following command.

compile

Step 3: Migrate Your Contract


Once compiled, the contract will need to be migrated. You can do this by running the following command.

migrate

This is similar to the process you did earlier where you were pasting the ABI from remix into your editor. Once your migration is complete, you can view the contract ABI in a newly created build folder.

Full Ethereum Nodes

  1. Install and interact with the Geth CLI : https://geth.ethereum.org/downloads/
  2. Install and Interact with Geth with a GUI : https://github.com/ethereum/mist/releases

Brax

Dude in his 30s starting his digital notepad