# Smart Contracts in a private ethereum network. 1. Start a private network. [Refer this](https://hackmd.io/@QsgLdP1nRmuG8sgkiX2P5g/ryDvWF3e5) 2. Create a simple smart contract using solidity. ``` pragma solidity >=0.1.0; contract Counter{ uint public val; constructor () public{ //constructor val = 0; } function increase() public{ val++; //set the value } function get() public view returns (uint){ return val; // get the value } } ``` 3. Compile it using solc(terminal) / remix(online Compiler) to get ABI and BinaryCode. 4.Deploy the smart contract into the private network. * ##### Using geth. [Refer this](https://blockchain.oodles.io/dev-blog/publishing-a-smart-contract-on-geth-console/) 1. Open a js console of the running node `geth attach http://127.0.0.1.8545` 2. Run the following code in js console. ```javascript contractInterface = eth.contract(contractABI) //creates a contract interface contractTxn = contractInterface.new({ from : eth.accounts[0], data : contractHex }) //check in the logs of the network if txn has been successful. // unlock the account using personal.unlockAccount(addr) incase of error txnReceipt = eth.getTransactionReceipt(contractTxn.transactionHash) contractAddr = txnReceipt.contractAddress //Store this address ``` 5. Interacting with smart contract from js app. ```nodejs const Web3 = require('web3') const web3 = new Web3('http://localhost:8545') const public_key = #PUBLIC_KEY const private_key = #PRIVATE_KEY //(not password). web3.eth.accounts.wallet.add({ // Inorder to send signed transactions. privateKey : private_key, address : public_key }) const contract_addr = #HEX_ADDRESS_OF_THE_SMART_CONTRACT const contract_abi = #CONTRACT_ABI const contract = new web3.eth.Contract(contract_abi,contract_addr) //change value contract.methods.increase().send({from:public_key,gas:1000000},(err,res)=>{ // console.log(res); //send method signs the transaction. }) // get value contract.methods.get().call({from:public_key,gas:10000000},(err,res)=>{ console.log(res) // In this case state is not changing. }) ``` 6. We need to pay to change the state of Smart Contract. Links: [web3-doc](https://web3js.readthedocs.io/en/v1.7.0/), [deploying-smart-contract](https://blockchain.oodles.io/dev-blog/publishing-a-smart-contract-on-geth-console/), [updating-smart-contract](https://ethereum.stackexchange.com/questions/122593/how-do-i-change-smart-contract-state-with-web3-js), [private-key](https://ethereum.stackexchange.com/questions/37182/how-to-get-private-through-utc-files-in-keystore)