avatarKeno Leon

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

12007

Abstract

">at</span>(<span class="hljs-string">"0x8caaa1f263ff14d0276ff1a1a6ed15c51159d6e0"</span>); <span class="hljs-built_in">var</span> receiverAddress = '<span class="hljs-number">0x00Ce6C92856A657979E7728005DBc9acD002Eb09</span>';</pre></div><div id="128e"><pre><span class="hljs-comment">// Dry run to estimate Gas:</span></pre></div><div id="b58f"><pre><span class="hljs-built_in">var</span> callData = <span class="hljs-built_in">contract</span>.transfer.getData(receiverAddress, <span class="hljs-number">2000</span>);</pre></div><div id="8011"><pre><span class="hljs-keyword">var</span> gasEstimate = web3.eth.<span class="hljs-title function_ invoke__">estimateGas</span>({ <span class="hljs-attr">from</span>: web3.eth.coinbase, <span class="hljs-attr">to</span>: <span class="hljs-string">"0x8caaa1f263ff14d0276ff1a1a6ed15c51159d6e0"</span>, <span class="hljs-attr">data</span>: callData });</pre></div><div id="2265"><pre>var gasPrice <span class="hljs-operator">=</span> web3.eth.gasPrice<span class="hljs-comment">;</span></pre></div><div id="c0f1"><pre><span class="hljs-built_in">console</span>.<span class="hljs-built_in">log</span>(<span class="hljs-string">'gas Price: '</span> + gasPrice); <span class="hljs-built_in">console</span>.<span class="hljs-built_in">log</span>(<span class="hljs-string">'Estimated Transaction gas: '</span> + gasEstimate);</pre></div><div id="6d2c"><pre><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'unlocking Coinbase account'</span>); <span class="hljs-keyword">const</span> password = <span class="hljs-string">"your_password"</span>; <span class="hljs-keyword">try</span> { web3.<span class="hljs-property">personal</span>.<span class="hljs-title function_">unlockAccount</span>(web3.<span class="hljs-property">eth</span>.<span class="hljs-property">coinbase</span>, password); } <span class="hljs-keyword">catch</span>(e) { <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(e); <span class="hljs-keyword">return</span>; }</pre></div><div id="7701"><pre><span class="hljs-built_in">console</span>.<span class="hljs-built_in">log</span> (<span class="hljs-string">'sending Transaction to the contract'</span>);</pre></div><div id="72cb"><pre><span class="hljs-comment">// For Real this time: </span></pre></div><div id="a815"><pre>const <span class="hljs-attr">transaction</span> <span class="hljs-operator">=</span> <span class="hljs-punctuation">{</span> <span class="hljs-symbol"> from:</span> web3.eth.coinbase, <span class="hljs-symbol"> gas:</span> gasEstimate + <span class="hljs-number">1</span>, <span class="hljs-symbol"> gasPrice:</span> gasPrice + <span class="hljs-number">1</span> <span class="hljs-punctuation">}</span></pre></div><div id="9458"><pre>contract.transfer.sendTransaction(receiverAddress, <span class="hljs-number">2000</span>, transaction, <span class="hljs-keyword">function</span>(<span class="hljs-params">err, txHash</span>) { <span class="hljs-keyword">if</span> (err != <span class="hljs-literal">null</span>) { <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"Error while sending transaction: "</span> + err); } <span class="hljs-keyword">else</span>{ <span class="hljs-built_in">console</span>.<span class="hljs-built_in">log</span>(<span class="hljs-string">"Transaction Sent here's you txHash: "</span> + txHash); } });</pre></div><p id="0eeb"><b><i>Note:</i></b><i> I am using a new way of estimating gas by <a href="https://ethereum.stackexchange.com/questions/9249/how-to-estimate-the-cost-to-call-a-smart-contract-method"><b>using getData, read more here.</b></a></i></p><div id="187e"><pre>...Transaction Sent here's you txHash: 0x8d0a0c35c45bb39d6d386b9d<span class="hljs-number">2321</span>6b85ad7bf86d237ab6e1acc58fcdc<span class="hljs-number">613377</span>7</pre></div><p id="281d">And so, If I query my accounts I should now see 8,000 in the original one and 2,000 on the other ( <i>receiverAddress </i>) account :</p><figure id="bd28"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*CR28kp5_GWUuJXtHiBOyTA.jpeg"><figcaption></figcaption></figure><p id="5e6b">Programmatically you can query with <b><i>balanceOf</i></b> which we already covered, but the important part is that we now have created a token that can have an initial supply ( which is sent to the creator address) and we can then transfer from one account to others.</p><p id="e39f"><b>Better Tokens : </b>While you could use the minimal Token as the basis for your project, the good people at Ethereum have made available a more complex standard token which we will cover in depth in the next part of these notes( part 7). The usage of this standard token requires us to learn more solidity, mainly inheritance, so we’ll be looking at the basics of it next:</p><h2 id="658a">Inheritance in Solidity</h2><p id="817a">Inheritance allows certain behaviors and properties to be passed down from a parent object to child objects, classes or in the case of solidity contracts, In general inheritance aims to organize, simplify and reuse code. Let’s start with a basic example:</p><div id="7eea"><pre><span class="hljs-comment">// FILE: inheritContract.sol</span></pre></div><div id="cb41"><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="e20d"><pre>contract animalContract { <span class="hljs-keyword">function</span> <span class="hljs-title function_">doSomething</span><span class="hljs-params">()</span> <span class="hljs-title function_">returns</span> <span class="hljs-params">(bytes32)</span> { <span class="hljs-keyword">return</span> <span class="hljs-string">"eat, sleep"</span>; } }</pre></div><div id="ac76"><pre><span class="hljs-built_in">contract</span> catContract <span class="hljs-built_in">is</span> animalContract{} </pre></div><p id="d6c2">In this example, catContract inherits the method doSomething from animalContract. We simply define this relationship by the word <b>is.</b></p><ul><li><b>Compile:</b></li></ul><div id="701f"><pre><span class="hljs-comment">// abridged from compilerMK2.js:</span></pre></div><div id="9440"><pre><span class="hljs-built_in">let</span> input = fs.readFileSync(<span class="hljs-built_in">dir</span> + <span class="hljs-string">'/inheritContract.sol'</span>);</pre></div><div id="0beb"><pre><span class="hljs-keyword">const</span> bytecode = output.contracts[<span class="hljs-string">':catContract'</span>].bytecode; <span class="hljs-keyword">const</span> abi = output.contracts[<span class="hljs-string">':catContract'</span>].<span class="hljs-keyword">interface</span>;</pre></div><div id="5bb0"><pre>fs.writeFileSync(<span class="hljs-built_in">dir</span> + <span class="hljs-string">"/catContract.json"</span>, abi)</pre></div><div id="42f6"><pre><span class="hljs-attribute">txHash</span>:<span class="hljs-number">0</span>x8b138df59cd99becd2b7966f43309f1bc0d1f067e5ec4aa5ce1845abe1204d1a <span class="hljs-attribute">Successfully</span> deployed Contract with address: <span class="hljs-number">0</span>xed1c09d2cc09098c1597b0864156be258852a506</pre></div><p id="6b99">Notice that we are feeding our compiler the .sol file first (inheritContract.sol) , but then we are specifying the catContract as both bytecode and abi.</p><ul><li><b>Calling:</b> ( note the use of toAscii to convert to string as well as the shorter syntax for contract creation)</li></ul><div id="2710"><pre>FILE : <span class="hljs-type">callContractMK2.js</span>:</pre></div><div id="c52e"><pre><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Setting up...'</span>); <span class="hljs-keyword">const</span> solc = <span class="hljs-built_in">require</span> (<span class="hljs-string">'solc'</span>); <span class="hljs-keyword">const</span> <span class="hljs-title class_">Web3</span> = <span class="hljs-built_in">require</span> (<span class="hljs-string">'web3'</span>); <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">'Reading abi'</span>); <span class="hljs-keyword">const</span> contractABI = <span class="hljs-built_in">require</span>(<span class="hljs-string">"./catContract.json"</span>);</pre></div><div id="1594"><pre><span class="hljs-built_in">console</span>.<span class="hljs-built_in">log</span>(<span class="hljs-string">'Connecting'</span>); const web3 = <span class="hljs-keyword">new</span> Web3(<span class="hljs-keyword">new</span> Web3.providers.HttpProvider(<span class="hljs-string">"http://localhost:8545"</span>)); <span class="hljs-built_in">console</span>.<span class="hljs-built_in">log</span>(<span class="hljs-string">'Creating contract instance'</span>); <span class="hljs-keyword">var</span> contract = web3.eth.contract(contractABI).at(<span class="hljs-string">"0xed1c09d2cc09098c1597b0864156be258852a506"</span>); <span class="hljs-built_in">console</span>.<span class="hljs-built_in">log</span> (<span class="hljs-string">'calling contract'</span>);</pre></div><div id="c355"><pre>var <span class="hljs-keyword">does</span> = contract.doSomething.call(); console.<span class="hljs-built_in">log</span>('Cat <span class="hljs-keyword">does</span> : ' + web3.toAscii(<span class="hljs-keyword">does</span>));</pre></div><div id="a169"><pre><span class="hljs-comment">//calling contract</span> <span class="hljs-comment">//Cat does : eat, sleep</span></pre></div><p id="2cf3">This is of course a minimal example, but should give you and idea of how inheritance works, and why it would be useful; for instance: we could have a few more animal contracts (<i>dogContract, birdContract, etc</i>) and instead of writing the method <i>doSomething</i> for each one we would just inherit from animalContract saving us from writing the method.</p><h2 id="a302">Abstract Contracts:</h2><p id="08be">Another feature of inheritance is that of templating or setting guidelines and formats in code, for instance, here the sub contracts need to implement some methods, the parent contract just defines the mold or template.</p><div id="aaae"><pre><span class="hljs-comment">//FILE: abstractContract.sol</span></pre></div><div id="53f7"><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="e5ec"><pre>contract animalContract { <span class="hljs-keyword">function</span> <span class="hljs-title function_">doSomething</span><span class="hljs-params">()</span> <span class="hljs-title function_">returns</span> <span class="hljs-params">(bytes32)</span>; }</pre></div><div id="0006"><pre>contract dogContract <span class="hljs-keyword">is</span> animalContract { <span class="hljs-keyword">function</span> <span class="hljs-title function_">doSomething</span><span class="hljs-params">()</span> <span class="hljs-title function_">returns</span> <span class="hljs-params">(bytes32)</span>{ <span class="hljs-keyword">return</span> <span class="hljs-string">"eat, sleep, woofs"</span>; } }</pre></div><div id="08e4"><pre>contract catContract <span class="hljs-keyword">is</span> animalContract { <span class="hljs-keyword">function</span> <span class="hljs-title function_">doSomething</span><span class="hljs-params">()</span> <span class="hljs-title function_">returns</span> <span class="hljs-params">(bytes32)</span>{ <span class="hljs-keyword">return</span> <span class="hljs-string">"eat, sleep, meows"</span>; } }</pre></div><p id="4ea8">Here the method on the parent (<i>animalContract.doSomething()</i>) doesn’t explicitly return what the subContracts do (<i>dogContract and catContract </i>), but rather is l

Options

eft to them to implement the method.</p><h2 id="9818">Interfaces:</h2><p id="2325">It is also possible to define another type of inheritance in the form of interfaces, they are very similar to abstract contracts, the difference being that they (<a href="http://solidity.readthedocs.io/en/develop/contracts.html#interfaces"><i>from the docs</i></a>) :</p><ol><li>Cannot inherit other contracts or interfaces.</li><li>Cannot define constructor.</li><li>Cannot define variables.</li><li>Cannot define structs.</li><li>Cannot define enums.</li></ol><p id="b16e"><b>Example:</b></p><div id="72db"><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="42be"><pre><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">animalContract</span> </span>{ <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">doSomething</span>(<span class="hljs-params"></span>) <span class="hljs-title">returns</span> (<span class="hljs-params">bytes32</span>)</span>; <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isAlive</span>(<span class="hljs-params"></span>) <span class="hljs-title">returns</span> (<span class="hljs-params"><span class="hljs-keyword">bool</span></span>)</span>; }</pre></div><div id="0a95"><pre>contract dogContract <span class="hljs-keyword">is</span> animalContract { <span class="hljs-keyword">function</span> <span class="hljs-title function_">doSomething</span><span class="hljs-params">()</span> <span class="hljs-title function_">returns</span> <span class="hljs-params">(bytes32)</span>{ <span class="hljs-keyword">return</span> <span class="hljs-string">"eat, sleep, woofs"</span>; } <span class="hljs-keyword">function</span> <span class="hljs-title function_">isAlive</span><span class="hljs-params">()</span> <span class="hljs-title function_">returns</span> <span class="hljs-params">(bool)</span>{ <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>; }</pre></div><div id="2fba"><pre>}</pre></div><div id="1ffe"><pre>contract catContract <span class="hljs-keyword">is</span> animalContract { <span class="hljs-keyword">function</span> <span class="hljs-title function_">doSomething</span><span class="hljs-params">()</span> <span class="hljs-title function_">returns</span> <span class="hljs-params">(bytes32)</span>{ <span class="hljs-keyword">return</span> <span class="hljs-string">"eat, sleep, meows"</span>; } <span class="hljs-keyword">function</span> <span class="hljs-title function_">isAlive</span><span class="hljs-params">()</span> <span class="hljs-title function_">returns</span> <span class="hljs-params">(bool)</span>{ <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>; } }</pre></div><p id="77c0">I like to think of these type of inheritance as a form of map, or like a fellow solidity programmer told me, Imagine if your animalContract had 500 characteristics and more than 20 people were developing, so it is used to help others understand what and how methods should be implemented.</p><h2 id="c430">Few extra odds & ends:</h2><p id="df86">Before moving onto the erc20 contract there are still a few things that I’d like to cover that might come in handy:</p><ul><li><a href="http://solidity.readthedocs.io/en/develop/contracts.html#visibility-and-getters"><b>Visibility :</b></a></li></ul><p id="a388">You can specify your functions and variables visibility as follows:</p><div id="d397"><pre><span class="hljs-keyword">external: </span>Can <span class="hljs-keyword">be </span>called <span class="hljs-keyword">by </span>other contracts.</pre></div><div id="e80d"><pre>public: (Default) Can be called internally or via messages. Public <span class="hljs-keyword">state</span> variables automatically create a getter.</pre></div><div id="23d8"><pre><span class="hljs-type">internal</span>:Visible <span class="hljs-keyword">within</span> contract <span class="hljs-keyword">and</span> derived contracts.</pre></div><div id="e31f"><pre><span class="hljs-keyword">private</span>: Only visible <span class="hljs-keyword">within</span> contract, not derived ones. </pre></div><div id="8601"><pre><span class="hljs-keyword">Note</span>: These visibility settings only affect <span class="hljs-keyword">contract</span> to <span class="hljs-keyword">contract</span> visibility.</pre></div><div id="8402"><pre>Temporary <span class="hljs-literal">warning</span>: You can also <span class="hljs-keyword">use</span> the dreaded this <span class="hljs-keyword">to</span> override behavior,but I would avoid it <span class="hljs-keyword">for</span> now unless you know exactly what this <span class="hljs-keyword">is</span>, <span class="hljs-keyword">to</span> complicate matters more, this can refer <span class="hljs-keyword">to</span> a <span class="hljs-keyword">function</span> <span class="hljs-keyword">or</span> a <span class="hljs-keyword">variable</span> depending <span class="hljs-keyword">on</span> <span class="hljs-keyword">context</span>.</pre></div><p id="673b">Like inheritance declaring visibility is mostly for human convenience and organizational purposes; additionally, it is an important security feature along with type declaration, in practical terms this is the sort of thing you need to be looking out for:</p><div id="5257"><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="caea"><pre>contract numbers { uint number1 <span class="hljs-operator">=</span> <span class="hljs-number">1</span><span class="hljs-comment">;</span> uint public number2 <span class="hljs-operator">=</span> <span class="hljs-number">2</span><span class="hljs-comment">;</span> uint private number3 <span class="hljs-operator">=</span> <span class="hljs-number">3</span><span class="hljs-comment">;</span> uint internal number4 <span class="hljs-operator">=</span> <span class="hljs-number">4</span><span class="hljs-comment">;</span> }</pre></div><div id="27bb"><pre>contract myNumber <span class="hljs-keyword">is</span> numbers{ <span class="hljs-keyword">function</span> <span class="hljs-title">listNumber</span>() returns (uint){ // <span class="hljs-keyword">return</span> <span class="hljs-type">number1</span>; // <span class="hljs-number">1</span> // <span class="hljs-keyword">return</span> number2; // <span class="hljs-number">2</span> // <span class="hljs-keyword">return</span> number3; unexpected identifier // <span class="hljs-keyword">return</span> number4; // <span class="hljs-number">4</span> } }</pre></div><p id="0515">Additionally, it is good to know that you can access public variables via the automagically generated getter:</p><div id="f8ee"><pre>contract myNumber <span class="hljs-keyword">is</span> numbers{ <span class="hljs-keyword">function</span> <span class="hljs-title function_">listNumber</span><span class="hljs-params">()</span> <span class="hljs-title function_">returns</span> <span class="hljs-params">(uint)</span>{ <span class="hljs-keyword">return</span> numbers.number1; <span class="hljs-comment">// 1</span> } }</pre></div><p id="d6d4">Even more convenient, this transaltes to external calls when using public:</p><div id="7626"><pre>Compiling <span class="hljs-string">":myNumber"</span><span class="hljs-params">...</span> Successfully deployed Contract <span class="hljs-keyword">with</span> address: <span class="hljs-number">0x016e8ffa71c1a4e60109615318854aec1b9490ff</span></pre></div><div id="12b3"><pre><span class="hljs-comment">// call contract:</span></pre></div><div id="b426"><pre><span class="hljs-comment">// From uint public number2 = 2; </span></pre></div><div id="c2f6"><pre><span class="hljs-keyword">var</span> ListNumber = contract.number2(); <span class="hljs-built_in">console</span>.<span class="hljs-built_in">log</span>(<span class="hljs-string">'Listing Number : '</span> + ListNumber);</pre></div><div id="27cc"><pre><span class="hljs-comment">// calling contract</span> <span class="hljs-comment">// Listing Number : 2</span></pre></div><h2 id="1aad">Expression & control structures.</h2><p id="e323">I haven’t mentioned much if anything about expressions in solidity,if you have some programming experience a lot of it might be familiar, I encourage you to review the docs for an overview and fill in the blanks depending on what seems new to you, I’ll note them as we encounter them in next part, but for now let’s 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><a href="https://readmedium.com/ethereum-tokens-smart-contracts-678dbb3faddd"><b>Notes Part 5: Smarter Contracts:</b></a><b> </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><li><b>Notes Part 6: Tokens & Inheritance: (This post): </b>We made our first Token and interacted with it by transfering some of it from one account to another, we also briefly covered inheritance which will come in handy in next part where we will check out a more complex Token example.</li></ul><figure id="a8ee"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*mtIpI9lIZdbye5giXJKB5Q.jpeg"><figcaption></figcaption></figure><div id="3422"><pre>Now <span class="hljs-keyword">a</span> book ! I <span class="hljs-keyword">repeat</span> buy <span class="hljs-keyword">the</span> book ! 😎</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">and</span> revised <span class="hljs-keyword">into</span> <span class="hljs-keyword">a</span> convenient book <span class="hljs-keyword">with</span> easy <span class="hljs-built_in">to</span> run code included !</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="1c93">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 6. Tokens & Inheritance

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.

Smart contracts along with Ethereum's VM make an environment suitable for all kinds of applications, while we seem to just be starting, digital tokens are a complex,interesting and perhaps even inevitable or obvious one, tokens have sprouted a multimillion dollar industry and represent a new form of funding via ICOS (Initial Coin Offerings), so now that we know enough solidity to make contracts, let’s dive into tokens.

In essence a token is a crypto currency that rides on top of Ethereums VM, let’s start by making a minimal one, deploying in the testnet and interacting with it.

Ethereum’s guide presents us with this one (I just changed the name to minimalToken):

// FILE : minimalToken.sol
pragma solidity ^0.4.0;
contract minimalToken {
/* This creates an array with all balances */
    mapping (address => uint256) public balanceOf;
/* Initializes contract with initial supply tokens to the creator of the contract */
    function minimalToken(uint256 initialSupply) {
        balanceOf[msg.sender] = initialSupply;
    }
/* Send coins */
    function transfer(address _to, uint256 _value) {
        require(balanceOf[msg.sender] >= _value);           
// Check if the sender has enough
        require(balanceOf[_to] + _value >= balanceOf[_to]); 
// Check for overflows
        balanceOf[msg.sender] -= _value;                    
// Subtract from the sender
        balanceOf[_to] += _value;                          
// Add the same to the recipient
    }
}

To be honest I don’t get what you can and can’t do with this one, but that’s why we are here, so let’s try deploying and interacting with it:

Note: As per out constructor we need to initialize the number of minimalTokens we have, so when deploying our contract we need to add that as a parameter:
const contractInstance = contract.new(10000, {
    data: '0x' + bytecode,
    from: web3.eth.coinbase,
    gasPrice: gasPrice + 1,
    gas: gasEstimate + 1000000
}
Deploying contract...
txHash:0xdaad8e547848a6e04daeeb808aa328b309ea56bf1e8bcbe5a0ae4186f0893472
Successfully deployed Contract with address: 0x8caaa1f263ff14d0276ff1a1a6ed15c51159d6e0

So if all went well we now should have created a new token on Kovan’s blockchain with a supply of 10,000 which we conveniently gave ourselves.

Importing tokens into parity was also a big question I had, it is really simple, to open our parity wallet and start watching a contract ( you might need to enable the option in settings ) Go to thecontracts tabd and add your contract address, the JSON abi we’ve been saving and other simple details, (note that we haven’t given our token a name ot Ticker symbol yet), if all went well you should now see a screen like this one and you can query the token for your address:

So now that we have a minimal token out there, let’s try interacting with it programmatically , let’s start by querying the balance of our address:

console.log('Setting up...');
const solc = require ('solc');
const Web3 = require ('web3');
console.log('Reading abi');
const contractABI = require("./minimalToken.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("0x8caaa1f263ff14d0276ff1a1a6ed15c51159d6e0");
console.log ('calling contract');
var tokenBalance = contractInstance.balanceOf(web3.eth.coinbase);
 console.log('Your tokens balance is :' + tokenBalance);
// Your tokens balance is :10000

The first interesting thing is that even though we never specified a getter function for balances, we can simply query the contract for it with : balanceOf(address), the secret is in the public property of our mapping ( check the contract file ). Ethereum’s VM creates a getter every time you create a public variable,neat.

  • Transferring:

The minimal contract we deployed has but one state changing function: transfer( address,amount), so now we shall try it out by transfering some of our precious tokens to another address :

FILE: callContractTransaction.js
console.log('Setting up...');
const solc = require ('solc');
const Web3 = require ('web3');
console.log('Reading abi');
const contractABI = require("./minimalToken.json");
console.log('Connecting');
const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
console.log('Creating contract instance');
// Note the condensed contractInstance:
var contract = web3.eth.contract(contractABI).at("0x8caaa1f263ff14d0276ff1a1a6ed15c51159d6e0");
var receiverAddress = '0x00Ce6C92856A657979E7728005DBc9acD002Eb09';
// Dry run to estimate Gas:
var callData = contract.transfer.getData(receiverAddress, 2000);
var gasEstimate = web3.eth.estimateGas({
    from: web3.eth.coinbase,
    to: "0x8caaa1f263ff14d0276ff1a1a6ed15c51159d6e0",
    data: callData
});
var gasPrice = web3.eth.gasPrice;
console.log('gas Price: ' + gasPrice);
console.log('Estimated Transaction gas: ' + gasEstimate);
console.log('unlocking Coinbase account');
const password = "your_password";
try {
  web3.personal.unlockAccount(web3.eth.coinbase, password);
} catch(e) {
  console.log(e);
  return;
}
console.log ('sending Transaction to the contract');
// For Real this time: 
const transaction = {
  from: web3.eth.coinbase,
  gas: gasEstimate + 1,
  gasPrice: gasPrice + 1
}
contract.transfer.sendTransaction(receiverAddress, 2000, transaction, function(err, txHash) {
  if (err != null) {
         console.error("Error while sending transaction: " + err);
       }
       else{
         console.log("Transaction Sent here's you  txHash: " + txHash);
       }
});

Note: I am using a new way of estimating gas by using getData, read more here.

...Transaction Sent here's you  txHash:
0x8d0a0c35c45bb39d6d386b9d23216b85ad7bf86d237ab6e1acc58fcdc6133777

And so, If I query my accounts I should now see 8,000 in the original one and 2,000 on the other ( receiverAddress ) account :

Programmatically you can query with balanceOf which we already covered, but the important part is that we now have created a token that can have an initial supply ( which is sent to the creator address) and we can then transfer from one account to others.

Better Tokens : While you could use the minimal Token as the basis for your project, the good people at Ethereum have made available a more complex standard token which we will cover in depth in the next part of these notes( part 7). The usage of this standard token requires us to learn more solidity, mainly inheritance, so we’ll be looking at the basics of it next:

Inheritance in Solidity

Inheritance allows certain behaviors and properties to be passed down from a parent object to child objects, classes or in the case of solidity contracts, In general inheritance aims to organize, simplify and reuse code. Let’s start with a basic example:

// FILE: inheritContract.sol
pragma solidity ^0.4.0;
contract animalContract {
  function doSomething() returns (bytes32) {
    return "eat, sleep";
  }
}
contract catContract is animalContract{}

In this example, catContract inherits the method doSomething from animalContract. We simply define this relationship by the word is.

  • Compile:
// abridged from compilerMK2.js:
let input = fs.readFileSync(dir + '/inheritContract.sol');
const bytecode = output.contracts[':catContract'].bytecode;
const abi = output.contracts[':catContract'].interface;
fs.writeFileSync(dir + "/catContract.json", abi)
txHash:0x8b138df59cd99becd2b7966f43309f1bc0d1f067e5ec4aa5ce1845abe1204d1a
Successfully deployed Contract with address: 0xed1c09d2cc09098c1597b0864156be258852a506

Notice that we are feeding our compiler the .sol file first (inheritContract.sol) , but then we are specifying the catContract as both bytecode and abi.

  • Calling: ( note the use of toAscii to convert to string as well as the shorter syntax for contract creation)
FILE : callContractMK2.js:
console.log('Setting up...');
const solc = require ('solc');
const Web3 = require ('web3');
console.log('Reading abi');
const contractABI = require("./catContract.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("0xed1c09d2cc09098c1597b0864156be258852a506");
console.log ('calling contract');
var does = contract.doSomething.call();
 console.log('Cat does : ' +  web3.toAscii(does));
//calling contract
//Cat does : eat, sleep

This is of course a minimal example, but should give you and idea of how inheritance works, and why it would be useful; for instance: we could have a few more animal contracts (dogContract, birdContract, etc) and instead of writing the method doSomething for each one we would just inherit from animalContract saving us from writing the method.

Abstract Contracts:

Another feature of inheritance is that of templating or setting guidelines and formats in code, for instance, here the sub contracts need to implement some methods, the parent contract just defines the mold or template.

//FILE: abstractContract.sol
pragma solidity ^0.4.0;
contract animalContract {
  function doSomething() returns (bytes32);
}
contract dogContract is animalContract {
  function doSomething() returns (bytes32){
    return "eat, sleep, woofs";
  }
}
contract catContract is animalContract {
  function doSomething() returns (bytes32){
    return "eat, sleep, meows";
  }
}

Here the method on the parent (animalContract.doSomething()) doesn’t explicitly return what the subContracts do (dogContract and catContract ), but rather is left to them to implement the method.

Interfaces:

It is also possible to define another type of inheritance in the form of interfaces, they are very similar to abstract contracts, the difference being that they (from the docs) :

  1. Cannot inherit other contracts or interfaces.
  2. Cannot define constructor.
  3. Cannot define variables.
  4. Cannot define structs.
  5. Cannot define enums.

Example:

pragma solidity ^0.4.0;
interface animalContract {
  function doSomething() returns (bytes32);
  function isAlive() returns (bool);
}
contract dogContract is animalContract {
  function doSomething() returns (bytes32){
    return "eat, sleep, woofs";
  }
  function isAlive() returns (bool){
    return true;
  }
}
contract catContract is animalContract {
  function doSomething() returns (bytes32){
    return "eat, sleep, meows";
  }
  function isAlive() returns (bool){
    return true;
  }
}

I like to think of these type of inheritance as a form of map, or like a fellow solidity programmer told me, Imagine if your animalContract had 500 characteristics and more than 20 people were developing, so it is used to help others understand what and how methods should be implemented.

Few extra odds & ends:

Before moving onto the erc20 contract there are still a few things that I’d like to cover that might come in handy:

You can specify your functions and variables visibility as follows:

external: Can be called by other contracts.
public: (Default) Can be called internally or via messages. Public state variables automatically create a getter.
internal:Visible within contract and derived contracts.
private: Only visible within contract, not derived ones. 
Note: These visibility settings only affect contract to contract visibility.
Temporary warning: You can also use the dreaded this to override behavior,but I would avoid it for now unless you know exactly what this is, to complicate matters more, this can refer to a function or a variable depending on context.

Like inheritance declaring visibility is mostly for human convenience and organizational purposes; additionally, it is an important security feature along with type declaration, in practical terms this is the sort of thing you need to be looking out for:

pragma solidity ^0.4.0;
contract numbers {
    uint number1 = 1;
    uint public number2 = 2;
    uint private number3 = 3;
    uint internal number4 = 4;
  }
contract myNumber is numbers{
  function listNumber() returns (uint){
          // return number1; // 1
          // return number2; // 2
          // return number3;  unexpected identifier
          // return number4; // 4
  }
}

Additionally, it is good to know that you can access public variables via the automagically generated getter:

contract myNumber is numbers{
  function listNumber() returns (uint){
     return numbers.number1; // 1
  }
}

Even more convenient, this transaltes to external calls when using public:

Compiling ":myNumber"...
Successfully deployed Contract with address: 0x016e8ffa71c1a4e60109615318854aec1b9490ff
// call contract:
// From uint public number2 = 2; 
var ListNumber = contract.number2();
console.log('Listing Number : ' + ListNumber);
// calling contract
// Listing Number : 2

Expression & control structures.

I haven’t mentioned much if anything about expressions in solidity,if you have some programming experience a lot of it might be familiar, I encourage you to review the docs for an overview and fill in the blanks depending on what seems new to you, I’ll note them as we encounter them in next part, but for now let’s 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: 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: (This post): We made our first Token and interacted with it by transfering some of it from one account to another, we also briefly covered inheritance which will come in handy in next part where we will check out a more complex Token example.
Now a book ! I repeat buy the book ! 😎
If you are looking for an introduction to Ethereum, Solidity and Smart Contracts these notes were edited and revised into a convenient book with easy to run code included !
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
Cryptocurrency
Solidity
Smart Contracts
Token Sale
Recommended from ReadMedium