Image for post
Image for post

Ethereum, tokens & smart contracts.

Notes on getting started : Part 11. Some intermediate considerations.

Previous notes in case you are just joining us:Part 1. Setting up.
Part 2. Web3.js/node.
Part 3. Solidity.
Part 4. Smart Contracts.
Part 5. Smarter Contracts.
Part 6. Tokens & Inheritance.
Part 7. ERC20 Token Standard.
Part 8. Crowdfunding and ICOs.
Part 9. Dapps & MetaMask.
Part 10. Remix, Truffle, TestRPC.

Working with solidity function parameters in web3

For more complex contracts, sending and receiving parameters/arguments to your contract methods can be hard to grasp at first, let’s try with a set/get array contract:

pragma solidity ^0.4.0;contract SetGetArray { uint[] someNumbers; function getArray() public constant returns (uint[]) {
return someNumbers;
}
function setArray(uint[] setNumbers) public { someNumbers = setNumbers; }}txHash:0x1cc74caab5c64c493a67cf8e3a8de656ba0db1d6f59c634e3c68e27a41afe7bf
Successfully deployed Contract with address: 0x1e1300614978efe2bf5c4b532daef69441314205
// File Setter.jsconsole.log('Setting up...');
const solc = require ('solc');
const Web3 = require ('web3');
console.log('Reading abi');
const contractABI = require("./SetGetArray.json");
console.log('Connecting');
const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
console.log('Creating contract instance');
var contract = web3.eth.contract(contractABI).at("0x1e1300614978efe2bf5c4b532daef69441314205");
var receiverAddress = '0x1e1300614978efe2bf5c4b532daef69441314205';
var setNumbers = [5,2,4,1];
var setData = contract.setArray.getData(setNumbers);
// console.log(setData);var gasEstimate = web3.eth.estimateGas({
from: web3.eth.coinbase,
to: receiverAddress,
data: setData
});
var gasPrice = web3.eth.gasPrice;console.log('gas Price: ' + gasPrice);
console.log('Estimated Transaction gas: ' + gasEstimate);
console.log('unlocking Coinbase account');
const password = "yourPassword";
try {
web3.personal.unlockAccount(web3.eth.coinbase, password);
} catch(e) {
console.log(e);
return;
}
console.log ('sending Transaction to the contract');const transaction = {
from: web3.eth.coinbase,
to:receiverAddress,
value: '0x00',
gas: gasEstimate + 1,
gasPrice: gasPrice + 1,
data: setData
}
web3.eth.sendTransaction( transaction, function(err, txHash) {
if (err != null) {
console.error("Error while sending transaction: " + err);
}
else{
console.log("Transaction Sent here's you txHash: " + txHash);
}
});
// Transaction Sent here's you txHash:
// 0x591ab8bf4b1fe6a81721d6ecab3b99b85248cd4302134c5a5674d9421a8612f6
// File Caller.jsconsole.log('Setting up...');
const solc = require ('solc');
const Web3 = require ('web3');
console.log('Reading abi');
const contractABI = require("./SetGetArray.json");
console.log('Connecting');
const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
console.log('Creating contract instance');
var contract = web3.eth.contract(contractABI).at("0x1e1300614978efe2bf5c4b532daef69441314205");
console.log ('calling contract');
var getArray = contract.getArray();
console.log('Get Array : ' + getArray);
// Get Array : 5,2,4,1
//
getArray[2] = 4
See: https://ethereum.stackexchange.com/questions/8362/passing-an-array-as-a-parameter-from-javascrpt-web3-to-a-solidity-function for further discussion.

Error handling: assert, require,revert,throw.

pragma solidity ^0.4.0;contract ErrorHandler {    uint hundred = 100;
uint ten = 10;
uint[] testvals = [0,1,2,3];
function testAssert() public view returns (uint) {
assert(hundred > ten);
return testvals[1];
}

function testRequire() public view returns (uint) {
require(hundred > ten);
return testvals[2];
}
}
Revert & Throw:When a transaction reverts, the state goes back to it’s original state, and ideally returns unused gas, you can also use it ( although it might be bad design beyond testing) to force the condition, throw; is the now deprecated version of revert(), but you might still see it here and there.

Can you kill a contract ?

In one word, no, contracts once added to the blockchain will remain there until the blockchain exists,what if you want to discontinue a contract ? you have a couple of options, change the internals so the contact no longer works, this would unfortunately make it into a black hole contract where Ether sent to it will remain there ( see the black hole contract in part 8.) but there is also another way, by adding a kill function ( experiment with it before deploying to mainnet to make sure it does what you want) :

function kill() {
if (msg.sender == creator)
suicide(creator);
}
// kills this contract and sends remaining funds back to creator

How to update a contract ?

So you have a token or other type of contract released in the blockchain, what if you discover a bug, want to add features or upgrade it, are you stuck with it forever? Well yes and no, the first thing you need to do is plan ahead and include some way to update your contract or reroute it or stop it should a bug be discovered, there is not a single way, some require the use of interfaces, while others depend on a Relay to forward calls, which in turn becomes problematic due to complexities in calling a contract from another contract, There is also storage and gas considerations, oh boy. I personally think that unless you are building something very complex, in which case I would question the need of a smart contract, you should refine your logic to account for updates and upgrades, consider the following case:

pragma solidity ^0.4.0;contract season1 {string color = "Purple Haze"; function seasonColor() view public returns(string) {
return color;
}
}// calling season1 seasonColor... Purple Haze.
pragma solidity ^0.4.0;contract season2 {string color = "Gunmetal Pink"; function seasonColor() view public returns(string) {
return color;
}
}// calling season2 seasonColor... Gunmetal Pink.
pragma solidity ^0.4.0;contract seasons {  string color;
address owner;

function seasons() public {
owner = msg.sender;

}
function seasonColor() view public returns(string) {
return color;
}

function setSeasonColor(string newSeasonColor) public{
require(msg.sender == owner);
color = newSeasonColor;
}
}

Contract to contract interaction.

Like updating contracts, contract to contract interactions can either be a simple but limited affair or a complex situation, let’s explore a couple of ways contracts can interact between themselves.

pragma solidity ^0.4.0;contract TransferableEther{address owner;function TransferableEther() public{
owner = msg.sender;
}
function transferEther(address forwardAddress, uint amount) public {
require(msg.sender == owner);
forwardAddress.transfer(amount);
}function () public payable {}}// Deployed Contract: 0x522f9a0ccd60d46bcb143f16ba39425b408112c9
Image for post
Image for post
So who pays? Whoever submits the transaction, in this case it would be the contracts owner (K3NOKOVAN), even though this account didn't receive any eth.
pragma solidity ^0.4.0;contract Base {

uint number = 72;

function getNumber() view public returns (uint){
return number;
}

}
pragma solidity ^0.4.0;import "./Base.sol";contract A {

function getNumberAddress(address keyAddress) public constant returns (uint) {
Base baseInstance = Base(keyAddress);
return baseInstance.getNumber();
}
}
Image for post
Image for post
contractInstance.call(bytes4(keccak256("method()")) 

Look down the road traveled :

  • Notes Part 1 : Setting up : Getting a wallet/client , connecting to a test Ethereum blockchain and getting some test ether.
  • Notes Part 2: web3.js/node : Interacting with the blockchain through web3.js and node for more convenience and ease of development.
  • Notes Part 3: Solidity : Installing solidity (Ethereums contract writing language ) , Creating a very basic contract, compiling it, deploying it to the blockchain ( the test one) and interacting with it.
  • Notes Part 4: Smart Contracts : We modified our simple contract so we could store and retrieve information (making it smart), in the process we also covered how to watch the blockchain and contracts and finally we took a look at gas and how to estimate it.
  • Notes Part 5: Smarter Contracts: In order to allow contracts more complex behavior (make them smarter) , we need to delve a bit deeper into contract creation via constructors and a few more complex types which we will use in making a token contract.
  • Notes Part 6: Tokens & Inheritance : We made our first Token and interacted with it by transferring some of it from one account to another, we also briefly covered inheritance which is used in more complex contracts.
  • Notes Part 7: ERC20 Token Standard : We made and deployed an erc20 token which can be considered the parting standard for working sub currencies. We examined the code and talked about transfers in between tokens.
  • Notes Part 8: Crowdfunding and ICOs : We explored the subject of crowdfunding via smart contracts in the form of ICOs and the exchange of ether for tokens, we made contracts that can receive ether, collect ether and can be used for exchanging ether and creating an unlimited supply of tokens.
  • Notes Part 9: Dapps & MetaMask : We looked into what a Dapp is and where we are in terms of development ( very early), we then introduced MetaMask which helps make Dapps accessible in the browser , we looked at various ways to interact with MetaMask via Javascript and we integrated them into a fully fledged test Dapp that uses our previously made token smart contract, we also touched on the future of Dapps and server implementations.
  • Notes part 10: Remix/Truffle/TestRPC: A look into Ethereums current tooling ecosystem, Remix, which allows you to quickly validate contracts online, TestRPC which recreates an offline blockchain in your computer, and Truffle, which has a bit of a learning curve in exchange for complex testing and deploying options.
  • Notes part 11: Some intermediate considerations (This post): Using some of the previous foundational knowledge I went over a few intermediate considerations, working with function parameters & web3, error handling, killing a contract, updating a contract (or not) and contract to contract interactions.
Image for post
Image for post
✨✨ Buy the Book ! ✨✨If you are looking for an introduction to Ethereum, Solidity and Smart Contracts these notes were edited and revised into a book, a super convenient way for you to get started!Available in ebook and paperback:https://www.amazon.com/dp/B078CQ8L7V    🙏 🙏 😊 🙏 🙏

Written by

AI, Software Developer, Designer : www.k3no.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store