Posts

Showing posts from October, 2017

Solidity Hash of Structs (Testing hash uniqueness)

So ive been informed by one of my Advisee ( Rain de Castro )  that when hashing a Struct in Solidity, the hash is the same for 2 data that is different. So i did a few tests with the following Code pragma solidity ^0.4.0; contract testHashAresh{ //Declare a struct similar to C++ struct Person{ string fullName; string number; } mapping (bytes32 => Person) allPersons; function returnHash(string _name, string _time) constant returns (bytes32,bytes32) { Person memory p = Person(_name, _time); bytes32 hash2 = sha256(p); bytes32 hash = sha256(_name, _time); return (hash2, hash); } } True enough The returned value for a data "Aresh","555" 0: bytes32: 0xac9c046be90fd91b4a31b9d04bb937659e885264dd8e6b8a7c9e79b806ef3ead 1: bytes32: 0x5ffc903b2aee670ea38ec2c35a8c5b8ac04754cf77536dd89d4d9985c4fd110f while the data for "Armin","555" is 0: bytes32

Creating Decentralized Apps Part 2

In this post i will be using javascript to call a contract deployed using Remix IDE and ethereum-js Test RPC(nodeJs) The contract being deployed is pragma solidity ^0.4.0; contract NumberGetNextNumberAresh{ uint index; function getNumber() returns (uint) { index = index + 1; return index; } function myConstantMethod(string a) constant returns (string d) { return a; } function myConstantNumber() constant returns (uint) { return index; } } To get the ABI or  "Interface ABI"   Follow this POST for the "Contract Address" Follow this POST After Deploying you should now be ready to create a UI (interface with html) The html will contain javascript as well <html> <head> <title>Smart Contract Ethereum</title> </head> <body> <fieldset> <button onclick="send()">Send Data</button> <button onclick="

Send Ether using Javascript and Html

In this post i will be using an html file and javascript to send Ether from one account to another account. the Ideal scenario is "Donations". From one account to another account(Author/Organization). In this process i will make use of Metamask and Web3 and Ropsten Test Net. An Event listener waits for the load of the website and checks if its Web3 Compatible, before proceeding. For the Chrome browser to be Web3 Compatible, it needs to have Metamask installed. Note: You cant run this on your computer as an Html File  Due to browser security restrictions . you will need a web server such as Apache or IIS . <html> <head> <title>Smart Contract Ethereum Aresh</title> </head> <body> <fieldset> <label> Ether: <input type="text" id="amount"></input> </label> <button onclick="sendmoney()">Donate to Aresh</button> <div id="response"&g

"Highscore Contract" Example

Keep a highscore of a certain game with the assumption that the game name is unique pragma solidity ^0.4.0; contract GameHighScoreAresh{ struct GameHighScore{ string username;//the name of the user who got the highscore (unique) uint score; //the score acquired string dateOfScore; //date of highscore string game; //name of the game uint8 flag; } struct gameName { string name; uint highscore; string username; bool isData; } mapping (bytes32 => gameName) ListOfGames; mapping (bytes32 => GameHighScore) TableOfHighScore; function GameHighScoreAresh() public{ } function AddUserHighScore(string _username, uint _score, string _game) public { GameHighScore memory currentHighScore = GameHighScore(_username, _score, "_dateofScore", _game, 1); bytes32 hash = keccak256(_username, _score, "_dateofScore", _game, 1);

"Donation Contract" Example

Image
So in this Post i will be writing a Donation Contract. The idea is, The Creator Creates the contract. another person wants to Donate a certain amount of Ether to the Creator. Warning: Tests done with Remix, i can be the creator and send ether to myself without deduction of my own ether. (Im not sure why it allows this.) ideally if i dont have enough ether, it has to revert back, but it doesnt.  (Please help me by commenting Below) pragma solidity ^0.4.0; contract DonationAresh { address creator; //this is Aresh function DonationAresh() public{ creator = msg.sender; } //fall back function that gets an amount of ether and sends to Creator function () payable public{ safeMoney(msg.value); } //send the amount to the creator function safeMoney(uint amountRaised) private{ creator.send(amountRaised); } } So from the Remix IDE there are 5 Accounts. im using the first account as the Creator of the Contract

Creating Decentralized Apps Part 1

Image
In order to create decentralized Apps such as Web applications, Websites, Mobile Apps. we need a way to interact with the blockchain. Solidity Language is merely for creating a programmable interface that runs on the blockchain So in order for us to interact with the Ethereum network (also called a node) we need to use a Client implementation.  There are many client implementations written in languages such as C++,Go,Python, Java,Haskell etc. Once you have a node using one of the clients, you can sync with the blockchain, create wallets and send and receive real ether. So there are 2 well known client implementations. 1. Test RPC - Node.js based Ethereum client for testing and development 2. Geth - Command line interface written in GO language for running a full Ethereum node Source: https://karl.tech/intro-guide-to-ethereum-testnets/ TestRPC is a lightweight Ethereum nodes used for small scale local testnets. Geth is heavyweight Ethereum nodes used for large scale networ

Basic "Inventory Management Contract" Example

in this post i will be creating a Basic Inventory Management Contract Inventory management is the management of inventory and stock. As an element of supply chain managemen t, inventory management includes aspects such as controlling and overseeing ordering inventory, storage of inventory, and controlling the amount of product for sale. So here are the basics of the inventory system that i will be adding to the contract 1. Add a product to the Inventory (Only Creator) 2. Remove a product from the Inventory (Only Creator) 3. Replenish Products in the inventory (Only Creator) 4. allow anyone to order a product pragma solidity ^0.4.0; contract InventoryAresh{ struct Product{ string sku; //always unique to the product string itemName; string itemDescription; uint qty; //available qty uint thresholdQty; //minimum qty before reorder string location; UoM UnitOfMeasure; Status status; bool isValue;

Testing using MetaMask Part 2 "Executing the Contract"

Image
Before writing any javascript code we first need to deploy the contract after deploying we will need 2 things 1. The Contract address 2. The Contract ABI In the next post i will be showing how to use the "web3 Deploy" to get the Contract Address. On the Remix - Solidity IDE. Make sure you are on the "Compile" Tab. Click on the "Details" Button for a popup. scroll down to see the "Interface ABI". (Not needed if you are using Remix IDE) Deploy the contract using the "Web3 Deploy" to get the Contract Address  (Not needed if you are using Remix IDE) Make sure you have Remix IDE open with MetaMask. You will notice the Account Number and number of Ether match. Make sure you have selected "Injected Web3"  Click the "Create" to see a popup Window Requesting for the Transaction. Click "Submit" to Accept the transaction. You will need to wait a minimum of 15 Seconds. In my case i waited

Testing using MetaMask Part 1 "Getting Ether"

Image
Download MetaMask On Chrome Browser Accept The "Privacy Notice" Accept The "Terms of Use" Give it a "Password" you wont forget Copy the "Vault" Created to an external text file and save it Select the "Ropsten Test Network" You currently have Zero Ether. Click "Buy" Click the "Ropsten Test Faucet" to open the website Click the "Request 1 Ether from Faucet" and wait for a few seconds Verify from your MetaMask that you have the 1 Ether. Whenever you run out of test ether, you can always request again using the same process

"User Contract" Example

Image
In this example, i will be using a persons detail and creating a signature (hash value) from it. the hash value will be unique to each user given the assumption that there are no 2 people with the same details except TWINS. Things learned: The Ethereum Virtual Machine has three areas where it can store items.  “memory”, this is used to hold temporary values. It is erased between (external) function calls and is cheaper to use. pragma solidity ^0.4.0; contract UserAresh{ //Declare a struct similar to C++ struct Info{ string firstname; string lastname; string maiden; bytes32 birthday; } //Events event Log(string firstname, string lastname); //Create a mapping array mapping(bytes32 => Info) UserList; //whos the Creator. The Value is the Hex value of the account that consumes GAS/ETHER address creator; //this is a constructor, notice it has the same name as the Contract name function U

"To Do List Contract" Example Version 2

Image
In this example im making use of a mapping of bytes. This works similar to creating an array. A mapping is used to structure value types, such as booleans, integers, addresses, and structs. It consists of two main parts: a  _KeyType  and a  _ValueType ; they appear in the following syntax: mapping (_KeyType => _ValueType) mapName pragma solidity ^0.4.0; contract ToDoAreshFlexible{ //Declare a struct similar to C++ holding details of a single ToDo Item struct Item{ string task; uint priority; } //Create a mapping array mapping(bytes32 => Item) ToDoList; //this is a constructor, notice it has the same name as the Contract name function ToDoAreshFlexible() public { } //Adds an item to the list using PUSH function AddToDo(string _task, uint _priority) public { //sha3" has been deprecated in favour of "keccak256" bytes32 hash = keccak256(_task); ToDoList[hash] = I

"Phone Book Contract" Example Version 4

Image
In my previous post, any account could add and delete from the contract. so in this post i will be using "Modifiers" to check that only the creator of the contract can add and remove data but any one can view the phonebook Modifiers can be used to change the body of a function. Modifiers  let you wrap additional functionality to a method, so they're kind of like the decorator pattern in OOP. pragma solidity ^0.4.0; contract PhoneBookAresh{ //Declare a struct similar to C++ struct Person{ string fullName; string number; } //Events event Log(string name, string number); //An Array of structs similar to C++ (flexible storage) and index start at 0 Person[] MyPhoneBook; //whos phonebook it is. The Value is the Hex value of the account address creator; //this is a constructor, notice it has the same name as the Contract name function PhoneBookAresh() public { creator = msg.sender;

"Phone Book Contract" Example Version 3

In this version im making use of the following 1. Delete an item using an index from the array 2. Log the action using an "Event" Events are dispatched signals the smart contracts can fire. DApps, or anything connected to Ethereum JSON-RPC API, can listen to these events and act accordingly. Event can be indexed, so that the event history is searchable later. pragma solidity ^0.4.0; contract PhoneBookAresh{ //Declare a struct similar to C++ struct Person{ string fullName; string number; } //Events event Log(string name, string number); //An Array of structs similar to C++ (flexible storage) and index start at 0 Person[] MyPhoneBook; //whos phonebook it is. The Value is the Hex value of the account address creator; //this is a constructor, notice it has the same name as the Contract name function PhoneBookAresh() public { creator = msg.sender; } //Adds an item to the Pho

"Phone Book Contract" Example Version 2

In this version of the phone book, i am making use of a function to verify if the name exists before adding it to the array what ive learned from this is: 1. Throw vs Revert 2. View vs Pure pragma solidity ^0.4.0; contract PhoneBookAresh{ //Declare a struct similar to C++ struct Person{ string fullName; string number; } //An Array of structs similar to C++ (flexible storage) and index start at 0 Person[] MyPhoneBook; //whos phonebook it is. The Value is the Hex value of the account address creator; //this is a constructor, notice it has the same name as the Contract name function PhoneBookAresh() public { creator = msg.sender; } //Adds an item to the Phonebook using PUSH function AddPhone(string _fullName, string _number) public { //if name doesnt exist. still uses GAS to go thru the loop if (CheckName(_fullName) == false) { MyPhoneBook.push(Person(_f

"Phone Book Contract" Example

In this example ive learned the following concepts. The use of a loop The use of an if conditional statement The Creator of the contract is the same as the account holding Ether String comparison requires utility functions. You can also use the "import" keyword to import external solidity contracts. but i kept getting errors on Remix. Basic usage for "import" import "github.com/Arachnid/solidity-stringutils/strings.sol"; pragma solidity ^0.4.0; contract PhoneBookAresh{ //Declare a struct similar to C++ struct Person{ string fullName; string number; } //An Array of structs similar to C++ (flexible storage) and index start at 0 Person[] MyPhoneBook; //whos phonebook it is. The Value is the Hex value of the account address creator; //this is a constructor, notice it has the same name as the Contract name function PhoneBookAresh() public { creator = msg.sender; }

"To Do List Contract" With Remix

Image
For this Post, i am using Remix to see the result of the contract. pragma solidity ^0.4.0; contract ToDoAreshFlexible{ //Declare a struct similar to C++ holding details of a single ToDo Item struct Item{ string task; uint priority; } //An Array of structs similar to C++ (flexible storage) and index start at 0 Item[] ToDoList; //this is a constructor, notice it has the same name as the Contract name function ToDoAreshFlexible() public { } //Adds an item to the list using PUSH function AddToDo(string _task, uint _priority) public { ToDoList.push(Item(_task,_priority)); } //returns a single item given an index since it requires more gas to iterate thru //returning multiple Items, both task and priority with a single call function getToDoList(uint _index) public returns(string, uint ){ return (ToDoList[_index].task, ToDoList[_index].priority); } function GetTa

Returning Multiple Values for the "To Do List Contract" Example

In this post i learned how to add items to a fixed array . on this post i extended this contract by making use of a flexible array size . in both posts, i was only returning the task and no the priority. In this post i will be returning multiple values pragma solidity ^0.4.0; contract ToDoAreshFlexible{ //Declare a struct similar to C++ holding details of a single ToDo Item struct Item{ string task; uint priority; } //An Array of structs similar to C++ (flexible storage) and index start at 0 Item[] ToDoList; //this is a constructor, notice it has the same name as the Contract name function ToDoAreshFlexible() public { } //Adds an item to the list using PUSH function AddToDo(string _task, uint _priority) public { ToDoList.push(Item(_task,_priority)); } //returns a single item given an index since it requires more gas to iterate thru //returning multiple Items, both task and priorit

Non fixed Number of Items for a "To Do List Contract" Example

In this example i will be using an array in storage compared to the Previous Post of a Fixed Number of items in the Array pragma solidity ^0.4.0; contract ToDoAreshFlexible{ //Declare a struct similar to C++ holding details of a single ToDo Item struct Item{ string task; uint priority; } //An Array of structs similar to C++ (flexible storage) and index start at 0 Item[] ToDoList; //this is a constructor, notice it has the same name as the Contract name function ToDoAreshFlexible() public { } //Adds an item to the list using PUSH function AddToDo(string _task, uint _priority) public { ToDoList.push(Item(_task,_priority)); } //returns a single item given an index since it requires more gas to iterate thru function getToDoList(uint _index) public returns(string ){ return ToDoList[_index].task; } }

Fixed Number of Items for a "To Do List Contract" Example

So in this post, i have a "To Do List" with constant number of items pragma solidity ^0.4.0; contract ToDoAreshConstant{ //Declare a struct similar to C++ holding details of a single ToDo Item struct Item{ string task; uint priority; } uint CurrentItem; //An Array of structs similar to C++ with 10 items (reserves storage) and index start at 0 Item[10] ToDoList; //this is a constructor, notice it has the same name as the Contract name function ToDoAreshConstant() public { CurrentItem = 0; //Assign to zero when contract is created. } //Adds an item to the list and increments the position of the index function AddToDo(string _task, uint _priority) public { ToDoList[CurrentItem] = Item(_task,_priority); CurrentItem++; } //returns a single item given an index since it requires more gas to iterate thru function getToDoList(uint _index) public returns(string ){

The Language of Ethereum Smart Contracts

This Post will be updated Constantly as i progress SOURCE: https://solidity.readthedocs.io/en/develop/ The language to create Ethereum Smart Contracts is "Solidity" There are many integrations for solidity, i will be using Remix mostly as it does not require any additional installations and can run on the latest Chrome Browser Available Solidity Integrations Remix Browser-based IDE with integrated compiler and Solidity runtime environment without server-side components. Geth  For running Ethereum nodes, i will be using Geth https://github.com/ethereum/go-ethereum/wiki/geth as the command line interface. Some advantages with geth, is it allows interaction between the smart contract and creation of a private block-chain network for testing. Capabilities By installing and running  geth , you can take part in the ethereum frontier live network and mine real ether transfer funds between addresses create contracts and send transactions explore blo

Describing the syntax of Solidity using BNF

SOURCE: https://github.com/ethereum/solidity/blob/develop/docs/grammar.txt SourceUnit = (PragmaDirective | ImportDirective | ContractDefinition)* // Pragma actually parses anything up to the trailing ';' to be fully forward-compatible. PragmaDirective = 'pragma' Identifier ([^;]+) ';' ImportDirective = 'import' StringLiteral ('as' Identifier)? ';' | 'import' ('*' | Identifier) ('as' Identifier)? 'from' StringLiteral ';' | 'import' '{' Identifier ('as' Identifier)? ( ',' Identifier ('as' Identifier)? )* '}' 'from' StringLiteral ';' ContractDefinition = ( 'contract' | 'library' | 'interface' ) Identifier ( 'is' InheritanceSpecifier (',' InheritanceSpecifier )* )? '{' ContractPart* '}' ContractPart = StateVariableDecla