Function execution in Ethereum smart contract using Myetherwallet and Metamask
Learning Ethereum Smart Contract developement is not straightforward. Ethereum smart contract developers face a bunch of issues. One of them is proper function execution.
In this post I highlight function execution in deployed Ethereum smart contract using React UI through Myetherwallet(MEW) and Metamask. This article is not intended for absolute beginners. If you make the first steps in Ethereum smart contract development, I encourage you to read this article(https://medium.com/crypto-currently/build-your-first-smart-contract-fc36a8ff50ca). It covers a variety of topics for beginners.
In my github account (https://github.com/cyberbono3/mintable-erc20-token ) you can view the basic ERC-20 token contract (DecypherCoinContract) and React UI sources in src folder.
Primarily, I address the function execution in Ethereum contract using React UI through MyEtherWallet(MEW). Please open App.js in src folder to view the source code.
First of all, I define the following variables:
1)ETHEREUM_CLIENT is web3 object in Kovan testnet;
2)decypherCoinContractABI represents abstract interface of the contract;
3)decypherCoinContractAddress is the address of the deployed contract in Kovan testnet;
4)decypherCoinContract represents contract instance in Kovan testnetwork.
var decypherCoinContract = ETHEREUM_CLIENT.eth.contract(decypherCoinContractABI).at(decypherCoinContractAddress)
Eessentially, Ethereum is Turing state machine. It is important to distinguish two types of function calls in Ethereum:
1)function calls that does not cause Ethereum state change. For instance, DecypherCoinContract contains totalSupply() property that specifies the total amount of tokens this contract has. Execution of this function does not alter the state of Ethereum and can be accomplished in the following fashion:
var totalSupply =decypherCoinContract.totalSupply.call().
Finally, it is free of charge.
2)functions calls that change Ethereum state. DecypherCoinContract has mintToken() function that aims to append the total amount of tokens. Therefore, this function call leads to Ethereum state change and must be signed by private key. Additionally, you have to pay a certain amount of Ether for its execution. I explain this process in MEW below.
In order to execute mintToken() function you have to :
1)create a raw transaction with the following parameters in Hex format
var rawTx = {
nonce: ETHEREUM_CLIENT.toHex(ETHEREUM_CLIENT.eth.getTransactionCount(‘0xaC24aB7Be05a8d42Ce958B6310990c95E1e69793’)),
gasPrice: ETHEREUM_CLIENT.toHex(20000000000),
gasLimit: ETHEREUM_CLIENT.toHex(60000),
to: decypherCoinContractAddress,
from: ‘0xaC24aB7Be05a8d42Ce958B6310990c95E1e69793’,
value: ‘0x00’,
data: payloadData }, where
a)nonce represents the number of transactions initiated from the particular address. It is used to prevent dupicate transactions;
b)to: contract address;
c) acceptable gasPrice and gasLimit;
d)from: address of contract creator;
e)value is amount of Ether you would like to transfer. In our case it is set to zero.
g)data = decypherCoinContract.mintToken.getData(this.numTokens). I use the method getData to call the function mintToken(this.numTokens) for contract instance decypherCoinContract. As you can see in DecyphetCoinContract.sol from my github repository, the function mintToken appends the new tokens to the contract. For additional security, only owner is allowed to execute it.
function mintToken(uint256 _amountToMint) onlyOwner {
balances[this] += _amountToMint;
totalSupply += _amountToMint;
}
2)sign a raw transaction with your private key
The private key is represented as a buffer in Hex format;
var key = new Buffer(‘private_key’, ‘hex’)
The low level library “ethereumjs-tx” is used to output tx object that is signed by private key.
var tx = new EthTx(rawTx)
tx.sign(key)
3)send the signed transaction to the Kovan testnet
var stx = tx.serialize()
ETHEREUM_CLIENT.eth.sendRawTransaction(‘0x’ + stx.toString(‘hex’), (err, hash) => {
if (err) { console.log(err); return; }
console.log(‘contract creation tx: ‘ + hash)
Perhaps you already noticed the downside of this implementation. Exposure of private key in UI is a big deal. To overcome this issue, it recomended to use another wallet Metamask that represents Chrome extension. Unlike MEW, Metamask uses alternative workflow preventing exposure of private key. Metamask injects web3 object in any page that you are browsing.
To execute arbitary functions in the contract you have to:
- access web3 object from global window, you can use the following Javascript code :
var userEthereumClient;
window.addEventListener(“load”, function() {
userEthereumClient = window.web3;}) - get the contract instance as I described in the beginning of my post
var contract = userEthereumClient.eth.contract(abi).at(address);
Hence, you are able to call various functions, e.g. name
contract.getBasicData(“name”, function(error, data) { console.log(data); });
Through this post, I have explained the basics of function execution in Ethereum smart contract using Myetherwallet and Metamask. So, due to more secure workflow I encourage you to apply Metamask upon your Dapp developement.
I would like to get your feedback. I apologize for my grammar skills in advance:)
Andrei Iv
Your Post Has Been Featured on @Resteemable!
Feature any Steemit post using resteemit.com!
How It Works:
1. Take Any Steemit URL
2. Erase
https://
3. Type
re
Get Featured Instantly � Featured Posts are voted every 2.4hrs
Join the Curation Team Here | Vote Resteemable for Witness