I just built a calculator on the Ethereum blockchain and thought I’d document what I discovered. This will be a brief post, but should be enough to walk you though the basics.I just built a calculator on the Ethereum blockchain and thought I’d document what I discovered. This will be a brief post, but should be enough to walk you though the basics.
In the spirit on decentralization, I’ll be building my client with nwjs in order to avoid central dependencies. This is a personal preference of mine, so the client will just be a script that you can run from your terminal. It would be simple to build up a GUI around it.
Install Truffle with npm install -g truffle.
Fire up the TestRPC by typing testrpc. Note the accounts that are printed onto the command line.
Each of these accounts have associated private keys that are also listed. You won’t really have to concern yourself with these right now.
Run `truffle init` from whatever directory you want to initialize your project from. This will give you four directories:
- contracts: directory where Truffle expects to find solidity contracts.
- migrations: directory to place scriptable deployment files.
- test: location of test files for testing your application and contracts.
- truffle.js: your main Truffle configuration file.
The contracts/ directory has a few contracts in it already. You might want to use these as a reference in the future, but for now create a file called Math.sol and add the following lines:
This very simple script will fire a Print event when multiply() is complete. We can call this function and capture the results from a client.
This is the code that is actually built into our app (client, webpage, or whatever you’re interested in building).
I included a few notes in comments:
- A: This the part where our client talks to the Truffle framework. When the contract is deployed with
truffle migrate, information from the transaction receipt (address, ABI, etc.) is stored in the
/builddirectory. This line fetches it so we can call the contract again.
- B: This is an event listener. Every time the Print event is fired, we’ll have some data that we can read from the blockchain.
- C: Remember when we started up TestRPC? We were given a list of addresses. Just pick one of those and paste it in the
fromfield. This account will be sending the transaction with
If you did everything correctly, you should get back an object containing a few indices, txHash, and the result of this transaction.