avatarKeno Leon

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

9202

Abstract

span></span> contract... txHash:<span class="hljs-number">0xaa0d82eb3228c52fb9f192b69c7a2983e390fefbf5a9bbb5fd14690959ff354d</span> Succesfully deployed Contract with address: <span class="hljs-number">0xe10e9ec821c219ca483c3a48915c3530add08724</span></pre></div><ul><li><b>Calling flipSwitch():</b></li></ul><div id="a47d"><pre><span class="hljs-keyword">var</span> switcher = contractInstance.flipSwitch.call(); <span class="hljs-built_in">console</span>.<span class="hljs-built_in">log</span>(<span class="hljs-string">'switcher state : '</span> + switcher); <span class="hljs-comment">// True</span> <span class="hljs-comment">// switcher was originally false.</span></pre></div><div id="a8e2"><pre>Note: <span class="hljs-keyword">If</span> you want <span class="hljs-keyword">to</span> actually change the switcher <span class="hljs-type">boolean</span> <span class="hljs-keyword">in</span> the contracts <span class="hljs-keyword">storage</span>, you would need <span class="hljs-keyword">to</span> <span class="hljs-keyword">call</span> flipSwitch <span class="hljs-keyword">in</span> a <span class="hljs-keyword">transaction</span>.</pre></div><h2 id="aae7">Enums:</h2><p id="ddc1">Enums are useful when you have a variable that can take one of a series of predefined values ( <a href="https://stackoverflow.com/questions/4709175/what-are-enums-and-why-are-they-useful"><i>see this answer, for java but same principles apply</i></a><i> </i>)</p><ul><li><b>Contract:</b></li></ul><div id="97f3"><pre><span class="hljs-comment">// FILE: enumContract.sol</span></pre></div><div id="df32"><pre><span class="hljs-attribute">pragma</span> solidity ^<span class="hljs-number">0</span>.<span class="hljs-number">4</span>.<span class="hljs-number">0</span>;</pre></div><div id="ba35"><pre>contract <span class="hljs-keyword">enumContract</span> {</pre></div><div id="349d"><pre><span class="hljs-built_in">enum</span> <span class="hljs-keyword">someThings</span> { CHAIR, CAR, TREE, COFFEE } someThings constant favoriteThing <span class="hljs-operator">=</span> someThings.COFFEE;</pre></div><div id="09bd"><pre><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getFavoriteThing</span><span class="hljs-params">()</span> <span class="hljs-title">returns</span> <span class="hljs-params">(<span class="hljs-keyword">uint</span>)</span> </span>{ <span class="hljs-keyword">return</span> <span class="hljs-keyword">uint</span>(favoriteThing); } }</pre></div><div id="3f04"><pre>// Notice <span class="hljs-keyword">the</span> lack <span class="hljs-keyword">of</span> semicolon <span class="hljs-keyword">at</span> <span class="hljs-keyword">the</span> <span class="hljs-function"><span class="hljs-keyword">end</span> <span class="hljs-title">of</span> <span class="hljs-title">the</span> <span class="hljs-title">enum</span> <span class="hljs-title">values</span>.</span></pre></div><ul><li><b>Deploy (skipping full readout) </b>:</li></ul><div id="f704"><pre><span class="hljs-attribute">Deploying</span> contract... <span class="hljs-attribute">txHash</span>:<span class="hljs-number">0</span>x97e9385d936774c044b7ed80499b52e3737e2eb01e191c6e2b7fede2366a0484 <span class="hljs-attribute">Succesfully</span> deployed Contract with address: <span class="hljs-number">0</span>x5d9a2c9e85e6b46466abc42408ab80d46b61d17a</pre></div><ul><li><b>Call function</b></li></ul><div id="bf4e"><pre>FILE : callContract.js ( skipping <span class="hljs-keyword">the</span> header section <span class="hljs-keyword">from</span> now <span class="hljs-keyword">on</span>, <span class="hljs-keyword">but</span> <span class="hljs-keyword">it</span> <span class="hljs-keyword">is</span> <span class="hljs-keyword">the</span> same <span class="hljs-built_in">file</span>, just change <span class="hljs-keyword">the</span> ABI <span class="hljs-keyword">and</span> <span class="hljs-keyword">the</span> contract address. </pre></div><div id="b168"><pre><span class="hljs-attribute">var</span> favoriteThing = contractInstance.getFavoriteThing.call(); <span class="hljs-attribute">console</span>.log('Favorite Thing: (<span class="hljs-number">0</span>:CHAIR, <span class="hljs-number">1</span>:CAR, <span class="hljs-number">2</span>:TREE, <span class="hljs-number">3</span>: COFFEE ) : ' + favoriteThing);</pre></div><div id="100c"><pre>// <span class="hljs-title class_">Favorite</span> <span class="hljs-symbol">Thing:</span> (<span class="hljs-number">0</span><span class="hljs-symbol">:CHAIR</span>, <span class="hljs-number">1</span><span class="hljs-symbol">:CAR</span>, <span class="hljs-number">2</span><span class="hljs-symbol">:TREE</span>, <span class="hljs-number">3</span><span class="hljs-symbol">:COFFEE</span> ) : <span class="hljs-number">3</span></pre></div><div id="0039"><pre>// Notice that enum gives us <span class="hljs-keyword">a</span> <span class="hljs-built_in">number</span> <span class="hljs-keyword">not</span> <span class="hljs-keyword">a</span> <span class="hljs-keyword">string</span>, so <span class="hljs-keyword">it</span> is up <span class="hljs-built_in">to</span> us <span class="hljs-built_in">to</span> interpret <span class="hljs-keyword">it</span> when reading <span class="hljs-keyword">it</span>. It is also <span class="hljs-literal">zero</span> indexed.</pre></div><h2 id="28b2">Reference types :</h2><p id="d002">Reference types (mainly arrays and structs) are more complex types which we’ll discuss next:</p><h2 id="cc8b">Arrays:</h2><p id="feff">Ethereum implementation of the ubiquitous <a href="https://en.wikipedia.org/wiki/Array_data_type">array data type</a> is pretty straightforward with the caveat that one needs to pay attention to the way they are stored, as part of the state (in storage) or in memory ( non peristent), let’s do a simple array contract:</p><div id="68d0"><pre><span class="hljs-comment">// FILE: arrayContract.sol</span>

<span class="hljs-keyword">pragma</span> solidity ^<span class="hljs-number">0.4</span><span class="hljs-number">.0</span>;</pre></div><div id="ba07"><pre>contract <span class="hljs-built_in">array</span>Contract {</pre></div><div id="967e"><pre>uint<span class="hljs-comment">[]</span> someNumbers = <span class="hljs-comment">[10,13,14]</span>;</pre></div><div id="b291"><pre><span class="hljs-keyword">function</span> <span class="hljs-title">getArray</span>() constant returns (uint) { <span class="hljs-keyword">return</span> <span class="hljs-type">someNumbers[1]</span>; // should <span class="hljs-keyword">return</span> <span class="hljs-number">13</span> }</pre></div><div id="68c0"><pre>}</pre></div><ul><li><b>Deploying:</b></li></ul><div id="22ba"><pre><span class="hljs-attribute">Deploying</span> contract... <span class="hljs-attribute">txHash</span>:<span class="hljs-number">0</span>x30a1cdc7742b57e6efda75a9214f7c78bef38bfa389228b19f21606fda706dd0 <span class="hljs-attribute">Succesfully</span> deployed Contract with address: <span class="hljs-number">0</span>x97b9892deb69a94b428da3c590c7ca793341493c</pre></div><ul><li><b>Calling:</b></li></ul><div id="c14c"><pre><span class="hljs-keyword">var</span> getArr = contractInstance.getArray.call(); <span class="hljs-built_in">console</span>.<span class="hljs-built_in">log</span>(<span class="hljs-string">'getArray : '</span> + getArr);</pre></div><div id="db9f"><pre><span class="hljs-comment">// getArray : 13</span></pre></div><p id="b62b">I won’t go too far into arrays for now as they become more complex to define when used as variable storage. Instead I’ll focus on 2 of the more useful types: structs and mapping which complement arrays:</p><h2 id="f889">Structs:</h2><p id="9f77">Structs can be considered as a grouping of variables ( <i>Object literals without methods if you are coming from JS</i> ) which in essence give you a new type, they make sense <a href="https://ethereum.stackexchange.com/questions/11637/benefit-to-using-structs/11639">if a set of variables can describe another variable with multiple instances</a> ,here’s an example:</p><div id="735e"><pre><span class="hljs-comment">// FILE: structContract.sol</span></pre></div><div id="3cf4"><pre><span class="hljs-attribute">pragma</span> solidity ^<span class="hljs-number">0</span>.<span class="hljs-number">4</span>.<span class="hljs-number">0</span>;</pre></div><div id="c198"><pre>contract <span class="hljs-keyword">structContract</span> {</pre></div><div id="d639"><pre>struct Stuff { address addr<span class="hljs-comment">;</span> uint[] someNumbers<span class="hljs-comment">;</span> }</pre></div><div id="9e22"><pre>Stuff myStuff<span class="hljs-comment">;</span> Stuff otherPeoplesStuff<span class="hljs-comment">;</span></pre></div><div id="e471"><pre><span class="hljs-keyword">function</span> <span class="hljs-title function_">structContract</span><span class="hljs-params">()</span>{ myStuff.addr = msg.sender; myStuff.someNumbers = [<span class="hljs-number">20</span>,<span class="hljs-number">30</span>,<span class="hljs-number">40</span>]; otherPeoplesStuff.addr = msg.sender; otherPeoplesStuff.someNumbers = [<span class="hljs-number">22</sp

Options

an>,<span class="hljs-number">33</span>,<span class="hljs-number">44</span>]; }</pre></div><div id="51aa"><pre><span class="hljs-keyword">function</span> <span class="hljs-title">getMyStuff</span>() returns (address, uint){ <span class="hljs-keyword">return</span> <span class="hljs-type">(myStuff.addr,</span> myStuff.someNumbers[<span class="hljs-number">1</span>]); }</pre></div><div id="ed84"><pre><span class="hljs-keyword">function</span> <span class="hljs-title">getOthersStuff</span>() returns (address, uint){ <span class="hljs-keyword">return</span> <span class="hljs-type">(otherPeoplesStuff.addr,</span> otherPeoplesStuff.someNumbers[<span class="hljs-number">0</span>]); }</pre></div><div id="3e5c"><pre>}</pre></div><p id="fed6">Explanation: <b>struct Stuff </b>defines a new <i>Stuff type</i> that has an address and an array with numbers, we then inititate 2 variables ( <b><i>myStuff</i></b><i> and <b>otherPeoplesStuff</b></i> ) using our newly created type . In our constructor (<i>structContract()</i>)<b> </b>we initiate these variables structs, and finally we can reference them with dot notation for our getter functions.</p><ul><li><b>Deploying:</b></li></ul><div id="09cd"><pre><span class="hljs-attribute">Deploying</span> contract... <span class="hljs-attribute">txHash</span>:<span class="hljs-number">0</span>x234615b084288719dd20f05829ffc28e8ece866acf070049956fa76819780182 <span class="hljs-attribute">Succesfully</span> deployed Contract with address: <span class="hljs-number">0</span>x8170478d82c63ddf1786157e7ab329e0925dc94f</pre></div><ul><li><b>Calling:</b></li></ul><div id="d652"><pre><span class="hljs-keyword">var</span> myStuff = contractInstance.getMyStuff.call(); <span class="hljs-built_in">console</span>.<span class="hljs-built_in">log</span>(<span class="hljs-string">'myStuff : '</span> + myStuff);</pre></div><div id="4d00"><pre><span class="hljs-keyword">var</span> othersStuff = contractInstance.getOthersStuff.call(); <span class="hljs-built_in">console</span>.<span class="hljs-built_in">log</span>(<span class="hljs-string">'othersStuff : '</span> + othersStuff);</pre></div><div id="06a9"><pre><span class="hljs-comment">// myStuff : 0x001301ad1556fd419cf8970b174fe9af34267eb8,30</span> <span class="hljs-comment">// othersStuff : 0x001301ad1556fd419cf8970b174fe9af34267eb8,22</span></pre></div><h2 id="4276">Mappings:</h2><p id="87c1">Mappings in solidity are roughly equivalent to <a href="https://ethereum.stackexchange.com/questions/7713/how-does-mapping-work">hash tables</a> ( <i>or associative arrays in Javascript</i>), mappings have this structure:</p><div id="cdcd"><pre><span class="hljs-keyword">From</span> the Docs:</pre></div><div id="365e"><pre><span class="hljs-function"><span class="hljs-title">mapping</span><span class="hljs-params">(_KeyType => _ValueType)</span></span> mapName</pre></div><div id="65d8"><pre>Here _KeyType can be almost <span class="hljs-keyword">any</span> type except <span class="hljs-keyword">for</span> <span class="hljs-keyword">a</span> mapping, <span class="hljs-keyword">a</span> dynamically sized array, <span class="hljs-keyword">a</span> contract, <span class="hljs-keyword">an</span> enum <span class="hljs-keyword">and</span> <span class="hljs-keyword">a</span> struct._ValueType can actually be <span class="hljs-keyword">any</span> type, including mappings.</pre></div><div id="43b7"><pre>Keys can <span class="hljs-keyword">be </span>integers, strings, <span class="hljs-keyword">or </span><span class="hljs-keyword">addresses, </span>values can <span class="hljs-keyword">be </span>any other type.</pre></div><p id="6990">Let’s write a contract with mappings:</p><div id="578c"><pre><span class="hljs-comment">// FILE mappingContract.sol</span></pre></div><div id="8d72"><pre><span class="hljs-attribute">pragma</span> solidity ^<span class="hljs-number">0</span>.<span class="hljs-number">4</span>.<span class="hljs-number">0</span>;</pre></div><div id="6535"><pre>contract <span class="hljs-keyword">mappingContract</span> {</pre></div><div id="d454"><pre>mapping(<span class="hljs-keyword">uint</span> => <span class="hljs-keyword">uint</span>[]) luckyNumbers;</pre></div><div id="b259"><pre>function mappingContract(){ luckyNumbers<span class="hljs-comment">[1]</span> = <span class="hljs-comment">[10,20,30]</span>; luckyNumbers<span class="hljs-comment">[2]</span> = <span class="hljs-comment">[11,22,33]</span>; }</pre></div><div id="71ad"><pre><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getLucky</span><span class="hljs-params">(<span class="hljs-keyword">uint</span> luckyKey)</span> <span class="hljs-title">constant</span> <span class="hljs-title">returns</span> <span class="hljs-params">(<span class="hljs-keyword">uint</span>[])</span></span>{ <span class="hljs-keyword">return</span> luckyNumbers[luckyKey]; }</pre></div><div id="b292"><pre>}</pre></div><ul><li><b>Deploying:</b></li></ul><div id="ab2c"><pre><span class="hljs-attribute">Deploying</span> contract... <span class="hljs-attribute">txHash</span>:<span class="hljs-number">0</span>xac9b15597dbb2dc9e931c50fd8d55b8866c623f63d3d10a4e1e77ce4fbcdb737 <span class="hljs-attribute">Successfully</span> deployed Contract with address: <span class="hljs-number">0</span>x1e5f7deadf846ae2f8402c2e3d1cc38ae556ef8e</pre></div><ul><li><b>Calling:</b></li></ul><div id="7b14"><pre><span class="hljs-keyword">var</span> luckyNumbers1 = contractInstance.getLucky.call(<span class="hljs-number">1</span>); <span class="hljs-built_in">console</span>.<span class="hljs-built_in">log</span>(<span class="hljs-string">'Lucky Numbers 1 : '</span> + luckyNumbers1);</pre></div><div id="8373"><pre><span class="hljs-keyword">var</span> luckyNumbers2 = contractInstance.getLucky.call(<span class="hljs-number">2</span>); <span class="hljs-built_in">console</span>.<span class="hljs-built_in">log</span>(<span class="hljs-string">'Lucky Numbers 2 : '</span> + luckyNumbers2);</pre></div><div id="536b"><pre><span class="hljs-comment">// Lucky Numbers 1 : 10,20,30</span> <span class="hljs-comment">// Lucky Numbers 2 : 11,22,33</span></pre></div><p id="022e">This is by no means a complete guide or overview of types and the solidity language; there is still some ground to cover, yet I believe we have enough knowledge to tackle making our own crypto currency in the form of a token smart contract (finally !) , which will cover in next section (booo!) , for now let’s take a breather and recap:</p><ul><li><a href="https://readmedium.com/ethereum-tokens-smart-contracts-f04cb9bb9431"><b>Notes Part 1 : Setting up </b></a><b>:</b> Getting a wallet/client , connecting to a test Ethereum blockchain and getting some test ether.</li><li><a href="https://readmedium.com/ethereum-tokens-smart-contracts-a263b43d4c54"><b>Notes Part 2: web3.js/node</b></a><b> : </b>Interacting with the blockchain through web3.js and node for more convenience and ease of development.</li><li><a href="https://readmedium.com/ethereum-tokens-smart-contracts-3346b62d2a0"><b>Notes Part 3: Solidity</b> </a>: 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.</li><li><a href="https://readmedium.com/ethereum-tokens-smart-contracts-39848cca0c79"><b>Notes Part 4: Smart Contracts:</b></a><b> </b>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.</li><li><b>Notes Part 5: Smarter Contracts ( This post ) : </b>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.</li></ul><figure id="63bb"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*mtIpI9lIZdbye5giXJKB5Q.jpeg"><figcaption></figcaption></figure><div id="1c93"><pre><span class="hljs-built_in">Now</span> in book form !</pre></div><div id="568a"><pre>If you are looking <span class="hljs-keyword">for</span> <span class="hljs-keyword">an</span> introduction <span class="hljs-built_in">to</span> Ethereum, Solidity <span class="hljs-keyword">and</span> Smart Contracts these notes were edited <span class="hljs-keyword">into</span> <span class="hljs-keyword">a</span> convenient book <span class="hljs-keyword">for</span> you !</pre></div><div id="4ce9"><pre><span class="hljs-symbol">Available</span> in ebook <span class="hljs-keyword">and</span> paperback here:</pre></div><div id="73c2"><pre>https:<span class="hljs-regexp">//</span>www.amazon.com<span class="hljs-regexp">/dp/</span>B078CQ8L7V </pre></div><p id="68a6">Cheers !</p><p id="2735">Keno</p><p id="c98a"><b>About the Author :</b></p><p id="14ec"><i>Born Eugenio Noyola Leon (Keno) I am a Designer,Web Developer/programmer, Artist and Inventor, currently living in Mexico City, you can find me at <a href="http://www.k3no.com">www.k3no.com</a></i></p></article></body>

Ethereum, tokens & smart contracts.

Notes on getting started Part 5. Smarter Contracts

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

It feels like we are halfway up the Ethereum mountain, in this part I would like to go a bit deeper into contracts with slightly more advance features we will need later.

Constructors

A constructor (which is common in other languages) simply initializes a contract with some value,operation or set of operations, let’s say we want to store the address of the contract originator ( that’s us), we would do something like this:

FILE: constructorContract.sol
pragma solidity ^0.4.0;
contract constructorContract {
address father;
function constructorContract() {
  father = msg.sender;
 }
function whosyourfather() constant returns (address) {
      return father;
  }
}

A little extra explanation is in order:

  • function constructorContract() is a our constructor function and will only run once in the life of the contract.
  • We first define a new type of storage: Address Type, and then we initialize the contract with msg.sender which is the address of the first sender or creator, let’s deploy and then call this contract :
Readout only, deployed using our trusty compiler from past notes:
Setting up...
Reading contract Source...
Compiling...
saving ABI
ABI Saved
gasEstimate: 110760 + 50000
gasPrice: 20000000000
unlocking Coinbase account
Deploying contract...
txHash:0x077ef8e4e3e6eb9dcfee00d6bacf45e8da612921209d8476ebf46b74eafc3dc9
Successfully deployed Contract with address: 0xc80ef52d06866cbdebb2a709d075d2508ea0c5d5

And so, if everything went well, we should be able to call our whosyourfather() function and get the creators address:

FILE: callContract.js
console.log('Setting up...');
const solc = require ('solc');
const Web3 = require ('web3');
console.log('Reading abi');
const contractABI = require("./constructorContract.json");
console.log('Connecting');
const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
console.log('Creating contract instance');
const contract = web3.eth.contract(contractABI);
var contractInstance = contract.at("0xc80ef52d06866cbdebb2a709d075d2508ea0c5d5");
console.log ('calling contract');
var returner = contractInstance.whosyourfather.call();
console.log('This contracts father is :' + returner);
//This contracts father is :0x001301ad1556fd419cf8970b174fe9af34267eb8

The above address corresponds to the address I first created a few notes ago and will remain that way forever… contract I am your father.

Types

A lot of the functionality of smart contracts comes from the specific types solidity supports,which in essence allow contracts to go beyond simple storage and behavior, so let’s check out a few of the more interesting ones….

I Recommend you read the full Solidity Docs on Types, you will also be consulting it from time to time.

Value Types :

Passed by value, for instance the handy boolean:

// FILE: booleanContract.sol
pragma solidity ^0.4.0;
contract booleanContract {
bool switcher;
function flipSwitch() constant returns (bool) {
      switcher = !switcher;
      return switcher;
  }
}
  • Compiler Readout :
Welcome Good Sir to  Compiler Mk2 Setting up...
Reading contract Source...
Compiling...
saving ABI
ABI Saved
gasEstimate: 96783
gasPrice: 21000000000
unlocking Coinbase account
Deploying contract...
txHash:0xaa0d82eb3228c52fb9f192b69c7a2983e390fefbf5a9bbb5fd14690959ff354d
Succesfully deployed Contract with address: 0xe10e9ec821c219ca483c3a48915c3530add08724
  • Calling flipSwitch():
var switcher = contractInstance.flipSwitch.call();
console.log('switcher state : ' + switcher); // True
// switcher was originally false.
Note: If you want to actually change the switcher boolean in the contracts storage, you would need to call flipSwitch in a transaction.

Enums:

Enums are useful when you have a variable that can take one of a series of predefined values ( see this answer, for java but same principles apply )

  • Contract:
// FILE: enumContract.sol
pragma solidity ^0.4.0;
contract enumContract {
enum someThings { CHAIR, CAR, TREE, COFFEE }
  someThings constant favoriteThing = someThings.COFFEE;
function getFavoriteThing() returns (uint) {
        return uint(favoriteThing);
    }
}
// Notice the lack of semicolon at the end of the enum values.
  • Deploy (skipping full readout) :
Deploying contract...
txHash:0x97e9385d936774c044b7ed80499b52e3737e2eb01e191c6e2b7fede2366a0484
Succesfully deployed Contract with address: 0x5d9a2c9e85e6b46466abc42408ab80d46b61d17a
  • Call function
FILE : callContract.js ( skipping the header section from now on, but it is the same file, just change the ABI and the contract address.
var favoriteThing = contractInstance.getFavoriteThing.call();
console.log('Favorite Thing: (0:CHAIR, 1:CAR, 2:TREE, 3: COFFEE ) : ' + favoriteThing);
// Favorite Thing: (0:CHAIR, 1:CAR, 2:TREE, 3:COFFEE ) : 3
// Notice that enum gives us a number not a string, so it is up to us to interpret it when reading it. It is also zero indexed.

Reference types :

Reference types (mainly arrays and structs) are more complex types which we’ll discuss next:

Arrays:

Ethereum implementation of the ubiquitous array data type is pretty straightforward with the caveat that one needs to pay attention to the way they are stored, as part of the state (in storage) or in memory ( non peristent), let’s do a simple array contract:

// FILE: arrayContract.sol
 
pragma solidity ^0.4.0;
contract arrayContract {
uint[] someNumbers = [10,13,14];
function getArray() constant returns (uint) {
        return someNumbers[1]; // should return 13
  }
}
  • Deploying:
Deploying contract...
txHash:0x30a1cdc7742b57e6efda75a9214f7c78bef38bfa389228b19f21606fda706dd0
Succesfully deployed Contract with address: 0x97b9892deb69a94b428da3c590c7ca793341493c
  • Calling:
var getArr = contractInstance.getArray.call();
console.log('getArray : ' + getArr);
// getArray : 13

I won’t go too far into arrays for now as they become more complex to define when used as variable storage. Instead I’ll focus on 2 of the more useful types: structs and mapping which complement arrays:

Structs:

Structs can be considered as a grouping of variables ( Object literals without methods if you are coming from JS ) which in essence give you a new type, they make sense if a set of variables can describe another variable with multiple instances ,here’s an example:

// FILE: structContract.sol
pragma solidity ^0.4.0;
contract structContract {
struct Stuff {
          address addr;
          uint[] someNumbers;
      }
Stuff myStuff;
Stuff otherPeoplesStuff;
function structContract(){
    myStuff.addr = msg.sender;
    myStuff.someNumbers = [20,30,40];
    otherPeoplesStuff.addr = msg.sender;
    otherPeoplesStuff.someNumbers = [22,33,44];
  }
function getMyStuff() returns (address, uint){
  return (myStuff.addr, myStuff.someNumbers[1]);
 }
function getOthersStuff() returns (address, uint){
    return (otherPeoplesStuff.addr, otherPeoplesStuff.someNumbers[0]);
  }
}

Explanation: struct Stuff defines a new Stuff type that has an address and an array with numbers, we then inititate 2 variables ( myStuff and otherPeoplesStuff ) using our newly created type . In our constructor (structContract()) we initiate these variables structs, and finally we can reference them with dot notation for our getter functions.

  • Deploying:
Deploying contract...
txHash:0x234615b084288719dd20f05829ffc28e8ece866acf070049956fa76819780182
Succesfully deployed Contract with address: 0x8170478d82c63ddf1786157e7ab329e0925dc94f
  • Calling:
var myStuff = contractInstance.getMyStuff.call();
console.log('myStuff : ' + myStuff);
var othersStuff = contractInstance.getOthersStuff.call();
console.log('othersStuff : ' + othersStuff);
// myStuff : 0x001301ad1556fd419cf8970b174fe9af34267eb8,30
// othersStuff : 0x001301ad1556fd419cf8970b174fe9af34267eb8,22

Mappings:

Mappings in solidity are roughly equivalent to hash tables ( or associative arrays in Javascript), mappings have this structure:

From the Docs:
mapping(_KeyType => _ValueType) mapName
Here _KeyType can be almost any type except for a mapping, a dynamically sized array, a contract, an enum and a struct._ValueType can actually be any type, including mappings.
Keys can be integers, strings, or addresses, values can be any other type.

Let’s write a contract with mappings:

// FILE mappingContract.sol
pragma solidity ^0.4.0;
contract mappingContract {
mapping(uint => uint[]) luckyNumbers;
function mappingContract(){
    luckyNumbers[1] =  [10,20,30];
    luckyNumbers[2] = [11,22,33];
  }
function getLucky(uint luckyKey) constant returns (uint[]){
    return luckyNumbers[luckyKey];
  }
}
  • Deploying:
Deploying contract...
txHash:0xac9b15597dbb2dc9e931c50fd8d55b8866c623f63d3d10a4e1e77ce4fbcdb737
Successfully deployed Contract with address: 0x1e5f7deadf846ae2f8402c2e3d1cc38ae556ef8e
  • Calling:
var luckyNumbers1 = contractInstance.getLucky.call(1);
console.log('Lucky Numbers 1  : ' + luckyNumbers1);
var luckyNumbers2 = contractInstance.getLucky.call(2);
console.log('Lucky Numbers 2 : ' + luckyNumbers2);
// Lucky Numbers 1 : 10,20,30
// Lucky Numbers 2 : 11,22,33

This is by no means a complete guide or overview of types and the solidity language; there is still some ground to cover, yet I believe we have enough knowledge to tackle making our own crypto currency in the form of a token smart contract (finally !) , which will cover in next section (booo!) , for now let’s take a breather and recap:

  • 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 ( This post ) : 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.
Now in book form !
If you are looking for an introduction to Ethereum, Solidity and Smart Contracts these notes were edited into a convenient  book for you !
Available in ebook and paperback here:
https://www.amazon.com/dp/B078CQ8L7V

Cheers !

Keno

About the Author :

Born Eugenio Noyola Leon (Keno) I am a Designer,Web Developer/programmer, Artist and Inventor, currently living in Mexico City, you can find me at www.k3no.com

Ethereum
Solidity
Cryptocurrency
Web3
Blockchain
Recommended from ReadMedium