We are going to create a Smart Contract .
--
We are going to create a Smart Contract using truffle:
This contract will hold an associative array of addresses and integers. Each address will be associated with a number of tokens that expresses if the user identified by this address is able to use a specific service (tokens > 0) or not (tokens == 0).
Step 1 : Install truffle
It is a development framework for Ethereum. There are many others, but we will use Truffle in this tutorial, to develop and deploy our smart contract.
npm install -g truffle
Step 2 : Create Project
- Make a folder “SmartToken”.
- run “truffle init” cmd on that folder.
- you will see three folders are created inside that folder i.e contracts, migrations, test and one node js file i.e truffle.js
- inside contracts folder we will create contract by default three files will be there they are also a contract but here we will create that contract in the name of “ smart-token.sol “ .contract is written in solidity language.
“pragma solidity ^0.4.0;
contract SmartToken {
mapping(address => uint) tokens;
event OnValueChanged(address indexed _from, uint _value);
function depositToken(address recipient, uint value) returns (bool success) {
tokens[recipient] += value;
OnValueChanged(recipient, tokens[recipient]);
return true;
}
function withdrawToken(address recipient, uint value) returns (bool success) {
if ((tokens[recipient] — value) < 0) {
tokens[recipient] = 0;
} else {
tokens[recipient] -= value;
}
OnValueChanged(recipient, tokens[recipient]);
return true;
}
function getTokens(address recipient) constant returns (uint value) {
return tokens[recipient];
}
}“
This contract has three functions:
- depositToken: add some tokens to a specific address
- withdrawToken: withdraw some token from a specific address
- getTokens: retrieve the number of tokens available for a specific address
Step 4 : Prepare for deployment:
Before deploying the Smart Contract, you have to adjust several files in your project.
Replace the content of “migrations/2_deploy_contracts.js” with the following content in order to deploy our “SmartToken” Smart Contract:
“
var SmartToken = artifacts.require(“./smartToken.sol”);
module.exports = function(deployer) {
deployer.deploy(SmartToken);
};
“
module.exports = {
networks: {
development: {
host: “localhost”,
port: 8042,
network_id: “*” // Match any network id
}
}
};
and in truffle.js file
“
now start mining from miner cmd prompt.
and in another tab run following commands
- truffle compile
- truffle migrate {it will deploy contracts}
- truffle console
- inside truffle console —” smartToken.address” → “JSON.stringify(SmartToken.abi)”
- run it on localhost:5000
Note : http://truffleframework.com/docs
through this tutorial you can go deep into truffle.