This post will be divided in to following concept
1- Trying to undestand blockchain and its terminology
2- Trying to install Truffle suite in windows. Install Ganache to have UI for our test server to check all the transection we will be doing in our local Truffle test server. By the way both truffle and Ganache gives us the local server for testing smart contract in Ethereum platform but Truffle gives us the additional functioanlity like IDE, compilation, migrate to other environment and in build address to perform operation using easy commands.
3- We will create a simple Truffle project and a simple Contract using Solidity language
4- We will do the unit testing of the same for better code testing.
5- we will test our code/smart contract from
‘- local
‘- using metamask wallet.
‘- using web component
6- upload our smartcontract on test blockchain i.e. rinkeby test env and fetch from front end
7- Explain etherem EVM machine i.e. swarm (it is distrubed data storage), Whisper(it is communication protocol used by the block to talk each other), blockchain.[Whisper and Swarm are a decentralized communication protocol and a decentralized storage platform respectively, being developed by Ethereum developers. Whisper is a decentralized communication protocol, whereas Swarm is a decentralized filesystem.
Whisper lets nodes in the network communicate with each other. ] Upload the FE files on swarm and test blockchain i.e. rinkeby test env and fetch from front end exposed in php project or node projects.
8- We will check how we can use the ganache for checking the trasection we are doing.
9- We will check how we can use the drizzle for developing F.E.
10-Understanding MSCODE plugin for trugglesuite and integrate our project in mscode and perform all the operation i.e. developing, testing, debugging, running, migrating.
11- Best pracise i..e how to write clean and secure contract in ethereum and do unit testing for the smart contract we had written
I agree this is sequence of blogpost but trust me if you follow religiously you will be able to understand the web3 concept blockchain, smart contract, dicentralize, Dapps, cryptopgraphy, hashing, miners, minning, consense algorithum like PoW, PoD, PoS and PoC (work, stack, capacity, done)
Lets start our journey
1- Trying to undestand blockchain and its terminology
In this section i would suggest you to please refer to my old blog pages this will give you extensive understanding of this new technology concepts.
Please refer in sequence wise for getting best knowledge on the same.
http://siddharathadhumale.blogspot.com/2019/09/block-chain-concepts.html
http://siddharathadhumale.blogspot.com/2019/09/how-to-create-blockchain-using-ethereum.html
http://siddharathadhumale.blogspot.com/2019/09/accessing-ethereum-files-using-web.html
http://siddharathadhumale.blogspot.com/2019/09/calling-ethereum-contract-using-web3.html
Above all four link will give you basic concept of Blockchain and its terminology along with this you will also know how it is easy to create your own smart contract in solidity language and deploy using solidity IDE and tools.
2- Trying to install Truffle suite in windows. Install Ganache to have UI for our test server to check all the transection we will be doing in our
In above section-1 we have shown you the simple way to create your own smart contract using solidity IDE and solidity language. But in this section we will talk about a new test environment + IDE tool that is widely used in market for creating smart contract for private/public permission and permissionless blockchain. It is called Truffle.
As per site it is Sweet Tools for Smart Contracts and it gets developers from idea to dapp as comfortably as possible. IT is combination of following three tools.
1- TRUFFLE :-SMART CONTRACTS MADE SWEETER
A world class development environment, testing framework and asset pipeline for blockchains using the Ethereum Virtual Machine (EVM), aiming to make life as a developer easier.
https://trufflesuite.com/docs/truffle/
2- Ganache:-ONE CLICK BLOCKCHAIN
A personal blockchain for Ethereum development you can use to deploy contracts, develop your applications, and run tests. It is available as both a desktop application as well as a command-line tool (formerly known as the TestRPC). Ganache is available for Windows, Mac, and Linux.
https://trufflesuite.com/docs/ganache/
3- drizzle:-FRESH CHAIN-DATA FOR FRONT-ENDS
A collection of front-end libraries that make writing dapp front-ends easier and more predictable. The core of Drizzle is based on a Redux store, so you have access to the spectacular development tools around Redux. We take care of synchronizing your contract data, transaction data and more.
https://trufflesuite.com/docs/drizzle/
Truffle and Ganache gives us the local server for testing smart contract in Ethereum platform but Truffle gives us the additional functioanlity like IDE, compilation, migrate to other environment and in build address to perform operation using easy commands.
For more details please refer to the official site of trufflesuite.com
As we are using windows we are going to show how you how to install Truffle suite in windows and also install Ganache in windows .
For now we will not talk about drizzle that will be taken into consideration in later part.
2- Install Truffle suite and Ganache in windows.
To install truffle make sure you have npm and for npm we should have Node installed. You can install node from below site.
During installation if you want to install chocolatey then click below option
Once node and chocolatey is install you can verify the same using below commands.
Note:- if you already have chocolatey it will give warning and exist and will not update your local chocolatey. To upgrade it using belwo command.
PS C:\Windows\system32> choco upgrade chocolatey
Now let try to install Truffle in our windows using below commands
npm install -g truffle
Now lets install Ganache also using below npm command
1 | npm install ganache --global |
Start the Ganache cli and check it is working using below command
ganache-cli
Other alternatives to install Ganache are
Alternative 1:- to use the source code to build and run
You can download a ganache source and build it by yourself by Cloning this repo https://github.com/trufflesuite/ganache
and then run below comamnd
npm install
npm start
Alternative 2:- is to download the windows version of Ganache from belwo site
https://trufflesuite.com/ganache/
https://github.com/trufflesuite/ganache-ui/releases/download/v2.5.4/Ganache-2.5.4-win-x64.appx
extract this files using any unzip software and go inside Apps folder and execute Ganache.exe and you will see below screen.
C:\Ganache-2.5.4-win-x64\app\Ganache
Alternative 3:-can be download the Ganache ui source from the
https://github.com/trufflesuite/ganache-ui
https://github.com/trufflesuite/ganache-ui.git
and run following command
c:\ganache-ui>npm i windows-build-tools
c:\ganache-ui>npm install
c:\ganache-ui>npm dev run
Alternative 4:- which i prefer the most is to use the exe file from the below location
https://github.com/trufflesuite/ganache-ui/releases
Then go to tag
https://github.com/trufflesuite/ganache-ui/tags
https://github.com/trufflesuite/ganache-ui/releases/tag/v2.5.4
Then execute Ganecha.exe and install the Ganeche ui on your windows. This work for me :).
Check you are able to see all the hostname in setting option of Ganache.
Generally as i said eariler both Truffle and Ganache is Test server but advantage of Ganache is it has ui. So we can configure our Truffle to Ganache in such a manner that when we start Truffle it will use Ganache Test server/ test data and we can easily see the ui or change in the ether value of the transections from truffle smart contract to ganache data.
3- We will create a simple Truffle project and a simple Contract using Solidity language
We will divide this assignment into three part
Part 1- We will build simple smart contract which will give us contract like deposite , withdraw and check the current balance.
Part 2- we will have the option to transfer the money from sender to receiver.
Part 3- we will add approval from the approver before sending the money to the receiver from sender.
Lets do the Part 1- We will build simple smart contract which will give us contract like deposite , withdraw and check the current balance.
For this we are going to refer our old example where in we have created a bank.sol file that gives all the smartcontract that had discussed.
https://shdhumale.wordpress.com/2019/09/17/how-to-create-blockchain-using-ethereum-code/
https://shdhumale.wordpress.com/2019/09/18/accessing-ethereum-files-using-web-application/
Lets begin the journey first we will check we have truffle installed.
now execute belwo command.
truffle init
C:\truffle-project>truffle init
Starting init…
Copying project files to C:\truffle-project
Init successful, sweet!
Try our scaffold commands to get started:
$ truffle create contract YourContractName # scaffold a contract
$ truffle create test YourTestName # scaffold a test
Once this operation is completed, you’ll now have a project structure with the following items:
contracts/: Directory for Solidity contracts i.e. all our .sol files
migrations/: Directory for scriptable deployment files i.e. all our .js files
test/: Directory for test files for testing your application and contracts
truffle.js: Truffle configuration file
Now lets open this file. You can use any IDE I am using VSCode because in future example we are going to show you how to use the VSCODE truffle plugin for creation, compilation and deployment of the Ethereum project.
Note:- lets try to add our truffle plugin in vscode at this moment only. we are going to use it in future.
search for truffle in extension and add all the extension you see their.
after installation you will see colour word and proper intendation for sol files
Now let copy of simle .sol file from
https://shdhumale.wordpress.com/2019/09/17/how-to-create-blockchain-using-ethereum-code/
Create a new file Bank.sol
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | 1- Bank.sol pragma solidity >=0.4.22 <0.9.0; //Main class that will be used to perform operation on our block. contract MyBank { //This is variable used for storing our balanceValue int balanceValue; //build constructor constructor() { //initialise the variable balanceValue = 1; } //As getBalance is not manupulating the value it is used to show the data on the screen and use view returns(int) function getBalanceValue() public view returns(int) { //return the current value of balanceValue return balanceValue; } function withdrawMyBalance(int amount) public { balanceValue = balanceValue - amount; } function depositeMyBalance(int amount) public { balanceValue = balanceValue + amount; } } |
change truffle-config.js and uncomment this line
1 2 3 4 5 | development: { host: "127.0.0.1", // Localhost (default: none) port: 9545, // Standard Ethereum port (default: none) network_id: "*", // Any network (default: none) } |
now we need either truffle client to be ready by using Truffle inbuild client or Ganache to be ready
truffle client can be made ready with this command
C:\truffle-project>truffle develop
if you get this error
C:\Users\Siddhartha>truffle develop
ExtendableError: Could not find suitable configuration file.
at Function.detect (C:\Users\Siddhartha\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\config\dist\index.js:139:1)
at Object.module.exports as run
at runCommand (C:\Users\Siddhartha\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\core\lib\command-utils.js:184:1)
Truffle v5.5.23 (core: 5.5.23)
Node v18.6.0
execute belwo command
1 2 3 4 5 6 7 | # <img draggable="false" role="img" class="emoji" alt="" src="https://s0.wp.com/wp-content/mu-plugins/wpcom-smileys/twemoji/2/svg/1f447.svg">️ macOS, Linux or Windows Git Bash export NODE_OPTIONS=--openssl-legacy-provider # ---------------------------------------------------- # <img draggable="false" role="img" class="emoji" alt="" src="https://s0.wp.com/wp-content/mu-plugins/wpcom-smileys/twemoji/2/svg/1f447.svg">️ Windows CMD set NODE_OPTIONS=--openssl-legacy-provider |
Then finally you will be able to run below command
C:\to_delete\truffle>set NODE_OPTIONS=–openssl-legacy-provider
C:\to_delete\truffle>truffle develop
Truffle Develop started at http://127.0.0.1:9545/
Accounts:
(0) 0x8dcbce91c32a557965dcc0233d50a67bcf2f634e
(1) 0x6178be104e0c2226fadc044fb1478ccb4a98cfc5
(2) 0xe02e1e860bb17a2988e0f0b6713f976222e0a1ed
(3) 0xc014ef83d52438c825f333c610e2d5949719a265
(4) 0x7891d21e363703138e01a38e15a5711dc1199be0
(5) 0x5dfc603b55d12e75309b8d1c01e17e3a6fab46db
(6) 0xc75334b6d4a3c6f231bd51892726c09331e2a608
(7) 0x9dd211705d1c3277da479774422356d829075634
(8) 0xaf7cfe15c5dd849b157854304a045b689100d2bd
(9) 0xa428fabd73fe88c9c6372f0eee5e0dbde014476d
Private Keys:
(0) 0996e71f27788b4db01909b543938c76d6ab0c9cc5d159b96072937d136df7c4
(1) 70cecdeb6200d34179e8a66bbf2e82c9426a0c950a6a2047cf15e9f59826faeb
(2) 6a4f7cf48d894909fff5424f06cb3e8077d1594f5357ed994bde1f2b69b302dd
(3) 0837873c8b60b57a50fc1164cf9111d9d016d6803bf069e8e3843bb921ec47ad
(4) c3c91f6bc5d438cb5bb446ca73deb6562616e2e5f963e3076f959f9099ded248
(5) 3a82d2d625271d0f909001ffcfc410d9e603b1bc8b58091d34ccac85fc5860ea
(6) bc89ba192ae0730d1225284a5905d9f947721c032e63756f12cbbec9624853d7
(7) f974195dc2b7b1f4fd3e08fa08c37d9c3a29c6986a80656246b0efbdb1009561
(8) f7db5db05ef39f05a01bfec13a42e96f08118523b5d3dafa5112e7d3cb19ea0e
(9) 6a2c50c6a2b6d4ccc4df9628bcd9457f24d2bdc7c5c982a655da848cdabf2d0b
Mnemonic: couple wagon fatal gallery muffin skate discover rich speed deliver design notice
Important : This mnemonic was created for you by Truffle. It is not secure.
Ensure you do not use it on production blockchains, or else you risk losing funds.
truffle(develop)>
Other option is
Finaly execute this command in sequence
C:\truffle-project>truffle compile
Compiling your contracts…
Compiling .\contracts\Migrations.sol
Compiling .\contracts\MyBank.sol
Artifacts written to C:\truffle-project\build\contracts
Compiled successfully using:
- solc: 0.8.15+commit.e14f2714.Emscripten.clang
we need to create a file 2_initial_bank.js
const MyBank = artifacts.require(“MyBank”);
module.exports = function (deployer) {
deployer.deploy(MyBank);
};
Note:- here MyBank is the name of the Smart contract not name of the files we had created i.e. MyBank.sol.
It is not MyBank.sol file but the contract name in this file MyBank.sol i.e.
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
//Main class that will be used to perform operation on our block.
contract MyBank
{
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | C:\truffle-project>truffle migrate development Compiling your contracts... =========================== > Compiling .\contracts\Migrations.sol > Compiling .\contracts\MyBank.sol > Artifacts written to C:\truffle-project\build\contracts > Compiled successfully using: - solc: 0.8.15+commit.e14f2714.Emscripten.clang Starting migrations... ====================== > Network name: 'development' > Network id: 5777 > Block gas limit: 6721975 (0x6691b7) 1_initial_migration.js ====================== Deploying 'Migrations' ---------------------- > transaction hash: 0xbf1d81a8daeca02b32cedcea0d87ad669180493bb8bd80e27e0bfc957a11b612 > Blocks: 0 Seconds: 0 > contract address: 0xC81CFbD1FdC7C7490d4CC0eb455acbD442e4362e > block number: 1 > block timestamp: 1658753234 > account: 0x8dcBCe91c32a557965dcC0233D50A67Bcf2F634E > balance: 99.99915573025 > gas used: 250154 (0x3d12a) > gas price: 3.375 gwei > value sent: 0 ETH > total cost: 0.00084426975 ETH > Saving migration to chain. > Saving artifacts ------------------------------------- > Total cost: 0.00084426975 ETH 2_initial_bank.js ================= Deploying 'MyBank' ------------------ > transaction hash: 0xc1189af95f2cd811f5ae2a33bfbe94f729ea8e0d1d91ccd0ab8bfd86714372ad > Blocks: 0 Seconds: 0 > contract address: 0x432B44746e1eaC57Be96BB5EaD03A8B89Fe897cf > block number: 3 > block timestamp: 1658753237 > account: 0x8dcBCe91c32a557965dcC0233D50A67Bcf2F634E > balance: 99.998252180842768921 > gas used: 236990 (0x39dbe) > gas price: 3.178366198 gwei > value sent: 0 ETH > total cost: 0.00075324100526402 ETH > Saving migration to chain. > Saving artifacts ------------------------------------- > Total cost: 0.00075324100526402 ETH Summary ======= > Total deployments: 2 > Final cost: 0.00159751075526402 ETH C:\truffle-project>truffle console truffle(development)> let instance = await MyBank.deployed() undefined truffle(development)> instance.depositeMyBalance(2) { tx: '0x73c42a152b2032500a632abfdb47f912ecc4024cd45f9aefde95e1fbfa3290ab', receipt: { transactionHash: '0x73c42a152b2032500a632abfdb47f912ecc4024cd45f9aefde95e1fbfa3290ab', transactionIndex: 0, blockNumber: 5, blockHash: '0x2a82656f5a1794cd45613151301057da822f1897a4c054d8e9eec5a759c27c7e', from: '0x8dcbce91c32a557965dcc0233d50a67bcf2f634e', to: '0x432b44746e1eac57be96bb5ead03a8b89fe897cf', cumulativeGasUsed: 26899, gasUsed: 26899, contractAddress: null, logs: [], logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', status: true, effectiveGasPrice: 3025248329, type: '0x2', rawLogs: [] }, logs: [] } truffle(development)> instance.getBalanceValue() BN { negative: 0, words: [ 3, <1 empty item> ], length: 1, red: null } truffle(development)> instance.withdrawMyBalance(1) truffle(development)> instance.withdrawMyBalance(1) { tx: '0x669b7dbd4b2ba6b03f088dd6a67bc0644e00b81fd5ca8b2ad0fb92c8a0c0ec23', receipt: { transactionHash: '0x669b7dbd4b2ba6b03f088dd6a67bc0644e00b81fd5ca8b2ad0fb92c8a0c0ec23', transactionIndex: 0, blockNumber: 6, blockHash: '0x1cfed298d3517aa929610df3b642251a9106728f38bee7821fba8e973a897392', from: '0x8dcbce91c32a557965dcc0233d50a67bcf2f634e', to: '0x432b44746e1eac57be96bb5ead03a8b89fe897cf', cumulativeGasUsed: 26855, gasUsed: 26855, contractAddress: null, logs: [], logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', status: true, effectiveGasPrice: 2960117754, type: '0x2', rawLogs: [] }, logs: [] } truffle(development)> instance.getBalanceValue() BN { negative: 0, words: [ 2, <1 empty item> ], length: 1, red: null } |
This all above operation we had done taking truffle inbuild client now lets use the Ganace Test server
start the Ganache using command ganache-cli
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | C:\Users\Siddhartha>ganache-cli ganache v7.3.2 (@ganache/cli: 0.4.2, @ganache/core: 0.4.2) Starting RPC server Available Accounts ================== (0) 0x9D04c4598dfa2a66CF0B60aDF146a541c083b857 (1000 ETH) (1) 0x40cC7D5040884FD245668651F10fdAd4d762EDD7 (1000 ETH) (2) 0xbEf0BF9339566401d694b84A7aE700f67532640c (1000 ETH) (3) 0xa3081c5c6d69907200E283140fEc39574060d4F8 (1000 ETH) (4) 0xcD1fe2f91c132acCF4743791B6e61A650c9A4970 (1000 ETH) (5) 0x0Ecd557F51519d1C494C66eC565758f702DaED3F (1000 ETH) (6) 0x25da84202C4F0BDcafED17e2eC41DBee1Cca7223 (1000 ETH) (7) 0xb0Ce2dEb4d6784e62D68b383B9f0216E44f57a95 (1000 ETH) (8) 0x7A96B5977E795A12A15498153100b967821ad753 (1000 ETH) (9) 0xd4eB3Cd44a3fC901f88B7d0931C53e0918D40374 (1000 ETH) Private Keys ================== (0) 0x9bf95fe0a48a57e812529fdd8caa5e9a371a84a7442502fb20cc69ec042261c9 (1) 0xf88a6468d2b2a4f53e7a5f7038ded3bd47b65be9b635d1be18e2bb529e01061a (2) 0xc2922643ac3f4f8662745b01c26e186da91f372b3cb4adaf268c55c0db9abc0d (3) 0x33743307e71c645aed5adc7fc6632baa2d4367d29c323a78b31da1dfab4791c1 (4) 0x2bdc35cc4f0bb85bc52b74aa681167e39319c9b938af55b305ef7e8f0ff685c5 (5) 0x79ba1a2ea4e0107abf0efa67ae60821f0bb968431eec7354fea2df99ed412903 (6) 0x70f5e1c978c1589e285a290e70f99bd7649dc72f42e3eef562e8ef1b25083bf5 (7) 0x74fbfafc19cee41edfb4c901e4801883683f0bcfdb2d940d26f2d7d6a2150481 (8) 0x973f39c3357656b428ca82d95803061fd37265f8bea2952f2f7fad256c54ce0c (9) 0x9d2f9d3d0b309fcf37908a5be6280de8179a9a4739d1b1caff268ed076171f2d HD Wallet ================== Mnemonic: name copy young explain again sword evidence onion gun spoon odor stable Base HD Path: m/44'/60'/0'/0/{account_index} Default Gas Price ================== 2000000000 BlockGas Limit ================== 30000000 Call Gas Limit ================== 50000000 Chain Id ================== 1337 RPC Listening on 127.0.0.1:8545 |
As you see now the test server is started at 8545 we need to make changes in truffle-config.js
networks: {
development: {
host: “127.0.0.1”, // Localhost (default: none)
port: 8545, // Standard Ethereum port (default: none)
network_id: “*”, // Any network (default: none)
}
}
now lets again use the same above command sequence wise and check if our smart contract is working or not.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | C:\truffle-project>truffle compile C:\truffle-project>truffle migrate development C:\truffle-project>truffle console C:\truffle-project>truffle console truffle(development)> let instance = await MyBank.deployed() undefined truffle(development)> instance.getBalanceValue() BN { negative: 0, words: [ 1, <1 empty item> ], length: 1, red: null } truffle(development)> instance.depositeMyBalance(2) { tx: '0x5a408113794de23aec11dac4b69099980a388b24ef49a9b8056ff3ee308098fa', receipt: { transactionHash: '0x5a408113794de23aec11dac4b69099980a388b24ef49a9b8056ff3ee308098fa', transactionIndex: 0, blockNumber: 5, blockHash: '0xcd5c3c8eb84372bfd01b8a37e7a3cd9e19a938237ce5864cce24a9c828677fa5', from: '0x9d04c4598dfa2a66cf0b60adf146a541c083b857', to: '0xbd78cda6ca0471df65a9457aa8762f83ff94a47d', cumulativeGasUsed: 26899, gasUsed: 26899, contractAddress: null, logs: [], logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', status: true, effectiveGasPrice: 3015658101, type: '0x2', rawLogs: [] }, logs: [] } truffle(development)> instance.getBalanceValue() BN { negative: 0, words: [ 3, <1 empty item> ], length: 1, red: null } truffle(development)> |
Now you can see either we use the Truffle inbuild test server using truffle development or Ganache Test server using ganache-cli.
we get cmd prompt. For our whole tutorial we are going to use Ganache UI. so lets start that now so that we can see the trasectio live update on the ui.
As you can see our Ganace ui start on the port 7545 so we will make changes in the truffle-config.js as given below.
Now again execute below command and see if we are able to perform all our smart contract operation locally.
C:\truffle-project>truffle compile
C:\truffle-project>truffle migrate development
C:\truffle-project>truffle console
as soon as we do the operation like below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | C:\truffle-project>truffle console truffle(development)> let instance = await MyBank.deployed() undefined truffle(development)> instance.getBalanceValue() BN { negative: 0, words: [ 1, <1 empty item> ], length: 1, red: null } truffle(development)> instance.depositeMyBalance(2) { tx: '0x010dcc9e18ca31e49ba10ea83f449c3573c9a04fc67d3391f669aed70280a899', receipt: { transactionHash: '0x010dcc9e18ca31e49ba10ea83f449c3573c9a04fc67d3391f669aed70280a899', transactionIndex: 0, blockHash: '0x834b65966ce99978f4bc51088d759c1f7589c95dd37ddb868b36028e423a1fc5', blockNumber: 5, from: '0x4daa8112cd942e90a7e092c5403090c47f37056e', to: '0x5e14065324d37375ade29f13c26b7eaeef065bd5', gasUsed: 27699, cumulativeGasUsed: 27699, contractAddress: null, logs: [], status: true, logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', rawLogs: [] }, logs: [] } |
for this transection tx: ‘0x010dcc9e18ca31e49ba10ea83f449c3573c9a04fc67d3391f669aed70280a899’, we see entry in Ganache ui
go for block and go for trasection
Hurrey we have done following things till now
1- Created truffle project
2- Create our own smart contract MyBank.sol class with name like depositeMyBalance, getBalanceValue etc
3- We had used inbuild truffle test server then we used Ganache-cli and then we used finally Ganache UI.
4- Finally we had tested our Smart contaract locally.
Now lets do our Part 2- we will have the option to transfer the money from sender to receiver.
Let creat a simple contract
1- SendMoney
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; //Main class that will be used to perform operation on our block. contract SendMoney { address public receiver = 0x12B6564a59001e96Ca3Fe426C013250329FcD487; function sendAmount() external payable { payable(receiver).transfer(1); } } |
above simple constract will transfer money from sender to receiver account lets test it.
Step 1- Start the Ganache UI. check in truffle-config.js is configured to our Ganache ui listening on 7545 port.
Step 2- create migration js file as shown below
3_initial_sendmoney.js
1 2 3 4 5 | const SendMoney = artifacts.require("SendMoney"); module.exports = function (deployer) { deployer.deploy(SendMoney); }; |
step 2- Excute belwo command in sequnce
C:\truffle-project>truffle compile
Migrate your project on the local Truffle using below command
C:\truffle-project>truffle migrate development
Now lets transfer the money to this receiver address 0x6B39c13d692098414FB49A89efDa79F88199200B
Note:- You can also use remix site for testing your smart contracts https://remix.ethereum.org/
Part 3- we will add approval from the approver before sending the money to the receiver from sender.
Lets creat a new .sol files as shown below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | // SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; //Main class that will be used to perform operation on our block. contract SendMoneyApproval { address public sender; address public receiver; address public approver = 0x25C0F7Fc38B0d54ea69D93b676338e10122e161c; function deposit(address _sender, address _receiver) external payable { sender = _sender; receiver = _receiver; } function approve() external { (receiver).transfer(1); } // function sendAmount() external payable { // payable(receiver).transfer(1); // } } |
Create corresponding 4_initial_sendmoneyapprover.js for migration of this contract on truffle or ganache etc env.
4_initial_sendmoneyapprover.js
1 2 3 4 5 | const SendMoneyApproval = artifacts.require("SendMoneyApproval"); module.exports = function (deployer) { deployer.deploy(SendMoneyApproval); }; |
Finally perform below command.
C:\truffle-project>truffle compile
1 2 3 4 5 6 7 8 9 10 11 12 | C:\truffle-project>truffle compile Compiling your contracts... =========================== > Compiling .\contracts\Migrations.sol > Compiling .\contracts\MyBank.sol > Compiling .\contracts\SendMoney.sol > Compiling .\contracts\SendMoney.sol > Compiling .\contracts\SendMoneyApproval.sol > Artifacts written to C:\truffle-project\build\contracts > Compiled successfully using: - solc: 0.8.15+commit.e14f2714.Emscripten.clang |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | C:\truffle-project>truffle migrate development Compiling your contracts... =========================== > Compiling .\contracts\Migrations.sol > Compiling .\contracts\MyBank.sol > Compiling .\contracts\SendMoney.sol > Compiling .\contracts\SendMoneyApproval.sol > Artifacts written to C:\truffle-project\build\contracts > Compiled successfully using: - solc: 0.8.15+commit.e14f2714.Emscripten.clang Starting migrations... ====================== > Network name: 'development' > Network id: 5777 > Block gas limit: 6721975 (0x6691b7) 4_initial_sendmoneyapprover.js ============================== Deploying 'SendMoneyApproval' ----------------------------- > transaction hash: 0x59f4e89af360d81061c46744221c5bbf3e6d8e065e57f9a5043200d4ba260941 > Blocks: 0 Seconds: 0 > contract address: 0x8Fe29eB52EFB594c120Ff3B9d9586bFab0ce79b4 > block number: 45 > block timestamp: 1658910469 > account: 0x12B6564a59001e96Ca3Fe426C013250329FcD487 > balance: 67.943808980000000002 > gas used: 263387 (0x404db) > gas price: 20 gwei > value sent: 0 ETH > total cost: 0.00526774 ETH > Saving migration to chain. > Saving artifacts ------------------------------------- > Total cost: 0.00526774 ETH Summary ======= > Total deployments: 1 > Final cost: 0.00526774 ETH |
Lets now test with using Remix site
4- We will do the unit testing of the same for better code testing.
now lets right test file to check if we are able to test our created files.
Create a file inside test folder named as sendmoneyapprover.js
1- sendmoneyapprover.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | const SendMoneyApproval = artifacts.require('../../contracts/SendMoneyApproval.sol'); contract('SendMoneyApproval', function(accounts) { it('deploying and initiates contract', async function() { const contract = await SendMoneyApproval.deployed(); const approver = await contract.approver.call(); assert.equal(approver, 0x25C0F7Fc38B0d54ea69D93b676338e10122e161c, "approvers don't match"); }); it('takes a deposit', async function () { const contract = await SendMoneyApproval.deployed(); await contract.deposit(accounts[0], { value: 1e+18, from: accounts[1] }); assert.equal(web3.eth.getBalance(contract.address), 1e+18, "amount did not match"); }); it('makes the transaction when approved, approver: ' + accounts[2], async function () { const contract = await SendMoneyApproval.deployed(); await contract.deposit(accounts[0], { value: 1e+18, from: accounts[1] }); await contract.approve({ from: accounts[2] }); assert.equal(web3.eth.getBalance(contract.address), 0, "didn't transfer ether"); }); }); |
5- we will test our code/smart contract from
‘5.1- local – Already done above where in we started the Ganache ui and executed all smart contract from node prompt or using Remix sites.
‘5.2- using metamask wallet.
‘5.3- using web component
Lets now 5.2- using metamask wallet.
Make sure to refer my old blog where in i had explain how to install Metamask (which is web wallet for performing operation on our contract) on chorme
Lets not configure our meta mask for our application now. This means now we will configure Ganache Test server with out Meta mask.
Now import the accound using private key.
We had added all our three sender, receiver and approver account. Lets name them properly.
lets first check our contract using remix site and Metamask wallet.
Lets connect with our sender user as shown below.
Now client on deply button
Now add our sender and receiver address in belwo fields
0x27A3BC0d4791159A0B9FFd7EE77d181F1Cc6E32A, 0x564ea453aF24eb26304dCe63fCF862985eBf1cB9
and click deposite
Now lets check we have all our values coming proper which we have set in contract by clicking on approver, sender and receiver.
Now lets click on the approve button to transfer the money
sender value is
recevier values is
‘5.3- using web component
Now lets check out smart contract using web application.
For that we should write a web files that will be exposed as web application and that will consume our contract.
web3.js is the best component that is used widely to do that. we are going to use the same.
we are using simple bootstrap and jquery for look and feel and actions in our html.
Make a web folder in truffle and add this files to it.
We will have a simple html that will ask for
sender address:- Text field for sender address.
receiver address:- Text field for receiver address.
Approver address:- Text field for Approver address.
Send Amount:- The amount we want the sender to send to receiver.
Submit:- to submit the transfer from sender to receiver.
Get balance:- Button that will show the current balance value of the ether on the receiver end.
Get approver:- This will show the address of approver.
get Approve Transection:- this will show the approved transections.
Please copy the below files in your web folder and also web3.js from https://www.cdnpkg.com/web3/file/web3.min.js/
1- index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 | <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <title>Siddhu Dapp Application</title> </head> <body> <h1>Siddhu dapp used to send money through contract.</h1> <form id="contract-form"> <div class="form-group"> <label for="Sender Address">Sender Address</label> <input value="" type="text" class="form-control" id="fromAddress" required="true"> <small id="fromAddressHelp" class="form-text text-muted">Enter your wallet address. Note: you will need to approve this with your private key.</small> </div> <div class="form-group"> <label for="Receiver Address">Receiver Address</label> <input value="" type="text" class="form-control" id="toAddress" aria-describedby="toAddressHelp" placeholder="Enter the receipient address" required="true"> <small id="toAddressHelp" class="form-text text-muted">Enter the wallet address of the recipient.</small> </div> <div class="form-group"> <label for="Approver Address">Approver Address</label> <input value="" type="text" class="form-control" id="approverAddress" aria-describedby="approverAddressHelp" placeholder="Enter the Approver address" required="true"> <small id="approverAddressHelp" class="form-text text-muted">Enter the wallet Approver address.</small> </div> <div class="form-group"> <label for="Amount">Send Amount</label> <input value="" type="text" class="form-control" id="amount" aria-describedby="amountHelp" placeholder="Amount to send in ETH from Sender Address to Receiver Address" required="true"> <small id="amountHelp" class="form-text text-muted">How much you want to send in ETH.</small> </div> <button type="submit" class="btn btn-primary">Submit Transection</button> <div id="deposit-result">Click the Submit button to deposit your ETH to the contract.</div> </form> <hr> <h2>Current Balance:</h2> <form id="get-balance-form"> <button type="submit" class="btn btn-primary">Get Balance</button> <div id="the-balance">Click Button to get the current Receiver contract balance.</div> </form> <h2>Get Approver Address:</h2> <form id="approver-form"> <button type="submit" class="btn btn-primary">Get Approver</button> <div id="approver-display">Click Button to get the address of the approver.</div> </form> <h2>Show Successful Transection ID:</h2> <form id="approve-form"> <button type="submit" class="btn btn-primary">Approve Transaction</button> <div id="approval-display">Click the button to approve the transaction.</div> </form> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="web3.min.js"></script> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <script> var contractAddress = '0x9D2792649811FbB3A89D7A65Edc98f5b885884df'; if ( typeof web3 != 'undefined') { //this web3 is for Metamask as it provide by default web3 object/provider to connect console.log("Got Metamask Provider:"); web3 = new Web3(web3.currentProvider); } else { //this web3 is to connect to directly to our Ganace UI and do the transection from html files. console.log("Using Local Provider:"); web3 = new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:7545")); } var version = web3.version; console.log("using web3 version: " + version); $('#contract-form').submit(function() { event.preventDefault(); var fromAddress = $('#fromAddress').val(); var toAddress = $('#toAddress').val(); var approverAddress = $('#approverAddress').val(); var amount = $('#amount').val(); if (web3.utils.isAddress(fromAddress) != true) { alert('Enter proper ethereum address for the sender address'); return; } if (web3.utils.isAddress(toAddress) != true) { alert('Enter proper ethereum address for the recipient address'); return; } if (web3.utils.isAddress(approverAddress) != true) { alert('Enter proper ethereum Approver address for the recipient address'); return; } if (amount <= 0) { alert('Amount shoule be greated 0 ETH.'); return; } }); $('#get-balance-form').submit(function() { event.preventDefault(); web3.eth.getApprover(contractAddress, function(error, result) { if (error) { console.log('error: ' + error); } else { console.log('balance:' + result); $('#the-balance').html('<b>Current Balance:</b> ' + web3.utils.fromWei(result)); } }); }); </script> </body> </html> |
Note above contact address can be taken from Ganache ui
var contractAddress = ‘0x9D2792649811FbB3A89D7A65Edc98f5b885884df’;
Now click on the GetBalance and you will get the amount.
We had added valitaion for fromAddress and toAddress
Now lets add functionality to our button to call our Smart contract.
As you know we have added a new field Approver and in our old contract we had made it hard coded so lets change our contract to get it from the user input.
SendMoneyWithApproval.sol
1 |
Let test it using Remix site.
Now as our deposite function need sendaddress, receiveraddress, approveraddress and amount send below values
0x79bB4BE13df4A79b7E53AA39789Cc9632C7386eC,0xB9538429c220E280E6140e957842Bf35966E9C62,0x0Fea34BCe3448c9BDE53E4250A09A93AF4c24673,3
In our above SendMoneyWithApproval.sol approve code is not working so we had made some changes as given below
SendMoneyWithApproval.sol
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | // SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; contract SendMoneyWithApproval { address public sender; address payable public receiver; address public approver; uint public amount; //function() external payable { } function deposit(address _sender, address payable _receiver, address _approver, uint _amount) public payable { sender = _sender; receiver = _receiver; approver = _approver; amount = _amount; } function getBalance() public view returns(uint) { return (receiver).balance; } function viewApprover() external view returns(address) { return(approver); } function approve() public payable returns (bool){ receiver.transfer(amount * (1 ether)); return true; } // function sendAmount() external payable { // payable(receiver).transfer(1); // } } |
0x84B4DcE1facC8E8297A372cA33aF450F58B42E74,0x36b102a55bD646dc933BBc84742F962D253b17B9,0x78a33491430712b6caA6Ca1df424F3F293A4991e,2
You can see 2 ehter is deducted from Sender and added to reciever in Ganache UI.
Now lets upload this contract on our Truffle server for testing.
Create a migration script
5_initial_sendmoneywithapprover.js
1 2 3 4 5 | const SendMoneyWithApproval = artifacts.require("SendMoneyWithApproval"); module.exports = function (deployer) { deployer.deploy(SendMoneyWithApproval); }; |
Before upload make some changes in your contract
1- SendMoneyWithApproval.sol
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | // SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; //Main class that will be used to perform operation on our block. contract SendMoneyWithApproval { address public sender; address payable public receiver; address public approver; uint public amount = 0; //function() external payable { } function deposit(address _sender, address payable _receiver, address _approver, uint _amount) public payable { sender = _sender; receiver = _receiver; approver = _approver; amount = _amount; } function getBalance() public view returns(uint) { return (receiver).balance; } function viewApprover() external view returns(address) { return(approver); } function approve() public payable returns (bool){ receiver.transfer(amount * (1 ether)); return true; } // function sendAmount() external payable { // payable(receiver).transfer(1); // } } C:\truffle-project>truffle compile Compiling your contracts... =========================== > Compiling .\contracts\Migrations.sol > Compiling .\contracts\MyBank.sol > Compiling .\contracts\SendMoney.sol > Compiling .\contracts\SendMoneyApproval.sol > Compiling .\contracts\SendMoneyWithApproval.sol > Compiling .\contracts\SendMoneyWithApproval.sol > Artifacts written to C:\truffle-project\build\contracts > Compiled successfully using: - solc: 0.8.15+commit.e14f2714.Emscripten.clang |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 | C:\truffle-project>truffle migrate development Compiling your contracts... =========================== > Compiling .\contracts\Migrations.sol > Compiling .\contracts\MyBank.sol > Compiling .\contracts\SendMoney.sol > Compiling .\contracts\SendMoneyApproval.sol > Compiling .\contracts\SendMoneyWithApproval.sol > Artifacts written to C:\truffle-project\build\contracts > Compiled successfully using: - solc: 0.8.15+commit.e14f2714.Emscripten.clang Starting migrations... ====================== > Network name: 'development' > Network id: 5777 > Block gas limit: 6721975 (0x6691b7) 1_initial_migration.js ====================== Replacing 'Migrations' ---------------------- > transaction hash: 0x1ed66dbac70b46ef5d4172db0222cfc00dafc699caae9456fa0605777ea238ca > Blocks: 0 Seconds: 0 > contract address: 0xdDE76405106B14f2E13F66576b5A9423f4710900 > block number: 14 > block timestamp: 1658996523 > account: 0x79bB4BE13df4A79b7E53AA39789Cc9632C7386eC > balance: 98.96162078 > gas used: 248854 (0x3cc16) > gas price: 20 gwei > value sent: 0 ETH > total cost: 0.00497708 ETH > Saving migration to chain. > Saving artifacts ------------------------------------- > Total cost: 0.00497708 ETH 2_initial_bank.js ================= Replacing 'MyBank' ------------------ > transaction hash: 0x46a42afd9837b372c4daf18d9b3d2da1b0008fbb62a9e9de0700205fb49e6360 > Blocks: 0 Seconds: 0 > contract address: 0x3E3d62449dDA16A96C34B6860872c8c2b44A4A56 > block number: 16 > block timestamp: 1658996523 > account: 0x79bB4BE13df4A79b7E53AA39789Cc9632C7386eC > balance: 98.95607272 > gas used: 234890 (0x3958a) > gas price: 20 gwei > value sent: 0 ETH > total cost: 0.0046978 ETH > Saving migration to chain. > Saving artifacts ------------------------------------- > Total cost: 0.0046978 ETH 3_initial_sendmoney.js ====================== Replacing 'SendMoney' --------------------- > transaction hash: 0xda6792bb739800b98b6336fdac356ac4f056ab7d035b4f82af5888fd94ab70d4 > Blocks: 0 Seconds: 0 > contract address: 0xbb363b80C06795C7cdBe153Df500729e67Bf4d10 > block number: 18 > block timestamp: 1658996524 > account: 0x79bB4BE13df4A79b7E53AA39789Cc9632C7386eC > balance: 98.95234198 > gas used: 159024 (0x26d30) > gas price: 20 gwei > value sent: 0 ETH > total cost: 0.00318048 ETH > Saving migration to chain. > Saving artifacts ------------------------------------- > Total cost: 0.00318048 ETH 4_initial_sendmoneyapprover.js ============================== Replacing 'SendMoneyApproval' ----------------------------- > transaction hash: 0xef786c54bdf9054ced1604dd7ceef092a69a8dd60387f77993be1ccece11b78b > Blocks: 0 Seconds: 0 > contract address: 0x3d15Edb50640Ed98149D883da41B5B1be303C65c > block number: 20 > block timestamp: 1658996525 > account: 0x79bB4BE13df4A79b7E53AA39789Cc9632C7386eC > balance: 98.94652398 > gas used: 263387 (0x404db) > gas price: 20 gwei > value sent: 0 ETH > total cost: 0.00526774 ETH > Saving migration to chain. > Saving artifacts ------------------------------------- > Total cost: 0.00526774 ETH 5_initial_sendmoneywithapprover.js ================================== Deploying 'SendMoneyWithApproval' --------------------------------- > transaction hash: 0x36f1a759f77287127f0a0c5e32c3ff39b1d38a3a8ec3f584c1c7892465543ca6 > Blocks: 0 Seconds: 0 > contract address: 0x76f6A869820CD0751005dF503Df601d4044f4bCa > block number: 22 > block timestamp: 1658996526 > account: 0x79bB4BE13df4A79b7E53AA39789Cc9632C7386eC > balance: 98.93905732 > gas used: 345820 (0x546dc) > gas price: 20 gwei > value sent: 0 ETH > total cost: 0.0069164 ETH > Saving migration to chain. > Saving artifacts ------------------------------------- > Total cost: 0.0069164 ETH Summary ======= > Total deployments: 5 > Final cost: 0.0250395 ETH |
For that we need to connect to Smart contact and for that we need contarct ABI. This can be taken using following ways
1- Froms site ether scan.
2- From Remix.
3- Best way i prefer from the build folder of truffle.
Lets take the third options.
When you execute the truffle compile and truffle migrate command inside build folder you will be able to see yourfilename.json file.
As shown below in build folder open SendMoneyWithApproval.json and get the abi from there.
now add this contractAbi.js in our html files.
1 | <script src="contractAbi.js"></script> |
and modify the code as below
1- index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 | <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <title>Siddhu Dapp Application</title> </head> <body> <h1>Siddhu dapp used to send money through contract.</h1> <form id="contract-form"> <div class="form-group"> <label for="Sender Address">Sender Address</label> <input value="0x93F28454e5145d32a7c38B85Bc08AF26812075FC" type="text" class="form-control" id="fromAddress" aria-describedby="fromAddressHelp" placeholder="Enter the Sender address" required="true"> <small id="fromAddressHelp" class="form-text text-muted">Enter your wallet address. Note: you will need to approve this with your private key.</small> </div> <div class="form-group"> <label for="Receiver Address">Receiver Address</label> <input value="0x85CABfb4cA4608b6C3689D18f3519B9Ef83a98f5" type="text" class="form-control" id="toAddress" aria-describedby="toAddressHelp" placeholder="Enter the receipient address" required="true"> <small id="toAddressHelp" class="form-text text-muted">Enter the wallet address of the recipient.</small> </div> <div class="form-group"> <label for="Approver Address">Approver Address</label> <input value="0xbFFCB6204efaF568e682017c86385077C0A8864d" type="text" class="form-control" id="approverAddress" aria-describedby="approverAddressHelp" placeholder="Enter the Approver address" required="true"> <small id="approverAddressHelp" class="form-text text-muted">Enter the wallet Approver address.</small> </div> <div class="form-group"> <label for="Amount">Send Amount</label> <input value="2" type="text" class="form-control" id="amount" aria-describedby="amountHelp" placeholder="Amount to send in ETH from Sender Address to Receiver Address" required="true"> <small id="amountHelp" class="form-text text-muted">How much you want to send in ETH.</small> </div> <button type="submit" class="btn btn-primary">Submit Transection</button> <div id="deposit-result">Click the Submit button to deposit your ETH to the contract.</div> </form> <hr> <h2>Current Balance:</h2> <form id="get-balance-form"> <button type="submit" class="btn btn-primary">Get Balance</button> <div id="the-balance">Click Button to get the current Receiver contract balance.</div> </form> <h2>Get Approver Address:</h2> <form id="approver-form"> <button type="submit" class="btn btn-primary">Get Approver</button> <div id="approver-display">Click Button to get the address of the approver.</div> </form> <h2>Show Successful Transection ID:</h2> <form id="approve-form"> <button type="submit" class="btn btn-primary">Approve Transaction</button> <div id="approval-display">Click the button to approve the transaction.</div> </form> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="web3.min.js"></script> <script src="contractAbi.js"></script> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <script> var contractAddress = '0x9D2792649811FbB3A89D7A65Edc98f5b885884df'; if ( typeof web3 != 'undefined') { //this web3 is for Metamask as it provide by default web3 object/provider to connect console.log("Got Metamask Provider:"); web3 = new Web3(web3.currentProvider); } else { //this web3 is to connect to directly to our Ganace UI and do the transection from html files. console.log("Using Local Provider:"); web3 = new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:7545")); } var version = web3.version; console.log("using web3 version: " + version); var sendMoneyWithApprover = new web3.eth.Contract(abi, contractAddress); console.log(sendMoneyWithApprover); $('#contract-form').submit(function() { event.preventDefault(); var fromAddress = $('#fromAddress').val(); console.log("fromAddress:"+fromAddress); var toAddress = $('#toAddress').val(); console.log("toAddress:"+toAddress); var approverAddress = $('#approverAddress').val(); console.log("approverAddress:"+approverAddress); var amount = $('#amount').val(); if (web3.utils.isAddress(fromAddress) != true) { alert('Enter proper ethereum address for the sender address'); return; } if (web3.utils.isAddress(toAddress) != true) { alert('Enter proper ethereum address for the recipient address'); return; } if (web3.utils.isAddress(approverAddress) != true) { alert('Enter proper ethereum Approver address for the recipient address'); return; } if (amount <= 0) { alert('Amount should be greated than 0 ETH.'); return; } //This is for calling deposite funtion sendMoneyWithApprover.methods.deposit(fromAddress, toAddress, approverAddress, amount).send({from: fromAddress, gas: 100000, value: web3.utils.toWei(amount,'ether')}, function(error, result) { if (error) { console.log('error: ' + error); $('#deposit-result').html('Error occured in deposite methods: ' + error); } else { $('#deposit-result').html('Success transection and result of the TX: <b>' + result + '</b>'); } }) }); //This is for calling GetBalance $('#get-balance-form').submit(function() { event.preventDefault(); web3.eth.getBalance(contractAddress, function(error, result) { if (error) { console.log('error: ' + error); } else { console.log('balance:' + result); $('#the-balance').html('<b>Current Balance:</b> ' + web3.utils.fromWei(result)); } }); }); // $('#get-balance-form').submit(function() { // event.preventDefault(); // sendMoneyWithApprover.methods.getBalance().send({from: toAddress.value, gas: 100000}, // function(error, result) { // if (error) { // console.log('error: ' + error); // } else { // console.log('balance:' + result); // $('#the-balance').html('<b>Current Balance:</b> ' + web3.utils.fromWei(result)); // } // }); // }); //This is for caling viewApprover $('#approver-form').submit(function() { event.preventDefault(); var submitApproverAddress= approverAddress.value; sendMoneyWithApprover.methods.viewApprover().send({from: approverAddress.value, gas: 100000}, function(error, result) { if (error) { console.log('error: ' + error); } else { console.log('result: ' + JSON.stringify(result)); $('#approver-display').html('Approver Address: <b>' + result + '</b>'); } }); }); //this is for calling Approve transection $('#approve-form').submit(function() { event.preventDefault(); sendMoneyWithApprover.methods.approve().send({from: approverAddress.value, gas: 100000}, function(error, result) { if (error) { console.log('error: ' + error); } else { console.log('result: ' + JSON.stringify(result)); $('#approval-display').html('Transaction Approved. TX: <b>' + result + '</b>'); } }); }); </script> </body> </html> |
Now lets open our local html file in browser and fill all the required data and click on submit button
Now lets expposed our code on php server and consume it as a localhost and finally configure it with metamask wallet and we will deploy our smartcontract on Truffle using (truffle migrate development)
PHP (our html file ) + Smart contract on Truffle (Truffle Migrate development) + Meta mask as wallet
make sure you have php installed in your functions
go to belwo folder where our all html and abh files are kept and run this command.
C:\truffle-project\web>php -S localhost:8000c
Now lets connect our localhost:8000 site to our meta mask as shown below.
Now sumbit the transection
Now change the user to Approver as our two next operatoin getApprover and Approve depends on approval of Approver address.
Finally we had made a web base application that interact with our smart contract and perform transfer operation.
Now we will move our contract on the real Etherium Test network like Rinkeby Test network and performing the live operations.
For that we need to use any etherium client software so that on installtion of that client software we will be able to make our laptop/machine as etherium node and can be able to connect the real desired Etherium network like Rinkeby Test. There are many Ehereun client S/W available we are going to us GETH.
So in short the next step is going to be to install an Ethereum client. What this is going to do is this is going to run a node of Ethereum, as well as the EVM on your machine, and that way you can sync it up to a testnet or the mainnet and this is what’s going to allow you to migrate your smart contracts to these different networks.Probably the most popular Ethereum client is Go Ethereum, otherwise called Geth. By this way we can allow our contract to migrate to these different networks.
GETH :- https://geth.ethereum.org/
This is also known as Go Ethereum written in GO Languge.
you can download the required version from here
https://geth.ethereum.org/downloads/
As mine is windows we are using geth-windows-amd64-1.10.21-67109427.exe
Install the GETH on windows and now set the account as shown below.
This will connecting to the Ethereum main network. And it’s syncing up with the main network.
So now that we’ve got geth installed and up and running, let’s look at how we can connect to it if we do wanna deploy our smart contract to the Ropsten test network and out to the main network.
To depoy on the test network we shoule point our geth to the test network on which we want our contract to be deployed it’s going to put everything and sync everything up against the testnet.
If you look at the Command Line Options for Go Ethereum or Geth https://github.com/ethereum/go-ethereum and https://geth.ethereum.org/docs/interface/command-line-options you will find that we have a network ID in which case, you specify an identifier for a network or you can flag testnet or Rinkeby, depending on which testnet you want to use. We’re going to go ahead and use the rinkeby you can also try for ropston testnet, which seems to be the most popular, and that we’re going to use the testnet flag. So let’s go ahead and go to our Command Line interface, and let’s first create an account, so we’re going to say geth –testnet account new. We’re going to type in our passphrase, and then, we get our address.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | c:\truffle-project>geth --rinkeby account new INFO [08-02|20:43:05.193] Maximum peer count ETH=50 LES=0 total=50 Your new account is locked with a password. Please give a password. Do not forget this password. Password: Repeat password: Your new key was generated Public address of the key: 0x041EF4Dad2cB70E47Fd8cB88Ae4de2f157Ca5bB7 Path of the secret key file: C:\Users\Siddhartha\AppData\Local\Ethereum\rinkeby\keystore\UTC--2022-08-02T15-13-15.280820300Z--041ef4dad2cb70e47fd8cb88ae4de2f157ca5bb7 - You can share your public address with anyone. Others need it to interact with you. - You must NEVER share the secret key with anyone! The key controls access to your funds! - You must BACKUP your key file! Without the key, it's impossible to access account funds! - You must REMEMBER your password! Without the password, it's impossible to decrypt the key! |
Now that we’ve got this, we can go ahead and fire up Geth. We want to have it sync to the rinkeby testnet, so we’ll type in geth –rinkeby, and then, we’ll type in –fast, which will speed up the sync because it’s not going to do a full node sync. It’s going to do essentially some summaries so that we don’t have to download the entire blockchain. It’ll be much faster. We’re going to specify to use 1024 cache, depending on what your available RAM is. Make sure you have enough RAM, or it can end up using a swap drive which won’t speed things up at all, and then, we’re going to turn on remote procedure calls so that we can log in and do some command line, and we’re going to expose a few APIs, specifically eth, net, web3, and personal.
1 | geth --rinkeby --fast --cache 1024 --datadir C:\Users\Siddhartha\AppData\Local\Ethereum\rinkeby --allow-insecure-unlock --http |
Just a note, if you’re using newer versions of Geth, they’ve deprecated the fast flag, and you should use syncmode equals fast instead moving forwar
1 | c:\truffle-project>geth --rinkeby --syncmode light --cache 1024 --datadir C:\Users\Siddhartha\AppData\Local\Ethereum\rinkeby --allow-insecure-unlock --http |
So what this will do is this will start firing up our test network, and eventually, it’s going to connect to one of the Ethereum node and it’s going to start syncing the blockchain.
While it’s doing this, let’s go ahead and get some ether populated into our address. As we know at anytime wherever we do a write procedure using the Ethereum network, it’s going to cost gas, so we need to have ether in an account.
As you in past post of blockchain i had already earned Eth for Rinkeby test system i am going to use the same for my transection.
Same way for my this current address i need to have some Eth.
I had used the simple trick. I had created an user by Importing the private key from the location Path of the secret key file: C:\Users\Siddhartha\AppData\Local\Ethereum\rinkeby\keystore\UTC–2022-08-02T15-13-15.280820300Z–041ef4dad2cb70e47fd8cb88ae4de2f157ca5bb7
and transfer 2 Eth from my Account1 to this user as shown below.
So while it’s syncing, let’s go ahead and add a new configuration into our truffle file. I’m going to go in my truffle.js file, and if you remember, I had one network in here to begin with. I’m going to go ahead and add another one for the rinkeby network. So I have development. network id for rinkeby is 4.
rinkeby: {
host: “127.0.0.1”,
port: 8545,
network_id: 4,
gas: 2900000
}
Now as you can see i had sync with rinksby test.now we will attach to the Geth server using command lines . Open the new command line and type below command.
1 | c:\truffle-project>geth --rinkeby --datadir C:\Users\Siddhartha\AppData\Local\Ethereum\rinkeby attach ipc:\\.\pipe\geth.ipc |
now type eth.syncing and check you get the response as false else if you get below response it means sync is still running and your mahine node is not upto date. So wait till it is completed.
1 2 3 | > eth.syncing false > |
Now I want to unlock my account using below command
personal.unlockAccount(eth.accounts[0])
So it’s going to ask for my passphrase enter your password.
1 2 3 4 5 | > personal.unlockAccount(eth.accounts[0]) Unlock account 0x041ef4dad2cb70e47fd8cb88ae4de2f157ca5bb7 Passphrase: true > |
Now, I can check the balance using below command
web3.eth.getBalance(“0x041ef4dad2cb70e47fd8cb88ae4de2f157ca5bb7”)
I156
It shows us the 0 eth so lets first add some ether to my accont now.
go to this site https://rinkebyfaucet.com/ and enter our address.
https://rinkeby.etherscan.io/address/0x041ef4dad2cb70e47fd8cb88ae4de2f157ca5bb7
After the transfer of the money chech again
1 2 3 | > web3.eth.getBalance("0x041ef4dad2cb70e47fd8cb88ae4de2f157ca5bb7") 100000000000000000 > |
Now lets deploy our contract on the rinkeby network using belwo command.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | truffle migrate --network rinkeby c:\truffle-project>truffle migrate rinkeby Compiling your contracts... =========================== > Compiling .\contracts\Migrations.sol > Compiling .\contracts\MyBank.sol > Compiling .\contracts\SendMoney.sol > Compiling .\contracts\SendMoneyApproval.sol > Compiling .\contracts\SendMoneyWithApproval.sol > Artifacts written to c:\truffle-project\build\contracts > Compiled successfully using: - solc: 0.8.15+commit.e14f2714.Emscripten.clang Network up to date. c:\truffle-project> |
Now lets try to migrate the contract to network rinkeby using below command.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 | c:\truffle-project>truffle migrate --network rinkeby PS C:\truffle-project> truffle migrate --network rinkeby Compiling your contracts... =========================== > Compiling .\contracts\Migrations.sol > Compiling .\contracts\MyBank.sol > Compiling .\contracts\SendMoney.sol > Compiling .\contracts\SendMoneyApproval.sol > Compiling .\contracts\SendMoneyWithApproval.sol > Artifacts written to C:\truffle-project\build\contracts > Compiled successfully using: - solc: 0.8.15+commit.e14f2714.Emscripten.clang Migrations dry-run (simulation) =============================== > Network name: 'rinkeby-fork' > Network id: 4 > Block gas limit: 29970705 (0x1c95111) 1_initial_migration.js ====================== Deploying 'Migrations' ---------------------- > block number: 11138179 > block timestamp: 1659535327 > account: 0x1868fd2095D338e643e54Cc08f1390e43C8c4d08 > balance: 0.099374614996497844 > gas used: 250154 (0x3d12a) > gas price: 2.500000014 gwei > value sent: 0 ETH > total cost: 0.000625385003502156 ETH ------------------------------------- > Total cost: 0.000625385003502156 ETH 2_initial_bank.js ================= Deploying 'MyBank' ------------------ > block number: 11138181 > block timestamp: 1659535327 > account: 0x1868fd2095D338e643e54Cc08f1390e43C8c4d08 > balance: 0.098667357493057095 > gas used: 236990 (0x39dbe) > gas price: 2.500000012 gwei > value sent: 0 ETH > total cost: 0.00059247500284388 ETH ------------------------------------- > Total cost: 0.00059247500284388 ETH 3_initial_sendmoney.js ====================== Deploying 'SendMoney' --------------------- > block number: 11138183 > block timestamp: 1659535327 > account: 0x1868fd2095D338e643e54Cc08f1390e43C8c4d08 > balance: 0.098194514991136912 > gas used: 160324 (0x27244) > gas price: 2.50000001 gwei > value sent: 0 ETH > total cost: 0.00040081000160324 ETH ------------------------------------- > Total cost: 0.00040081000160324 ETH 4_initial_sendmoneyapprover.js ============================== Deploying 'SendMoneyApproval' ----------------------------- > block number: 11138185 > block timestamp: 1659535328 > account: 0x1868fd2095D338e643e54Cc08f1390e43C8c4d08 > balance: 0.097460764988760099 > gas used: 264687 (0x409ef) > gas price: 2.500000008 gwei > value sent: 0 ETH > total cost: 0.000661717502117496 ETH ------------------------------------- > Total cost: 0.000661717502117496 ETH 5_initial_sendmoneywithapprover.js ================================== Deploying 'SendMoneyWithApproval' --------------------------------- > block number: 11138187 > block timestamp: 1659535328 > account: 0x1868fd2095D338e643e54Cc08f1390e43C8c4d08 > balance: 0.096377402485293339 > gas used: 404532 (0x62c34) > gas price: 2.500000008 gwei > value sent: 0 ETH > total cost: 0.001011330003236256 ETH ------------------------------------- > Total cost: 0.001011330003236256 ETH Summary ======= > Total deployments: 5 > Final cost: 0.003291717513303028 ETH Starting migrations... ====================== > Network name: 'rinkeby' > Network id: 4 > Block gas limit: 29970705 (0x1c95111) 1_initial_migration.js ====================== Deploying 'Migrations' ---------------------- *** Deployment Failed *** "Migrations" -- Returned error: authentication needed: password or unlock -- Reason given: Custom error (could not decode).. Exiting: Review successful transactions manually by checking the transaction hashes above on Etherscan. Error: *** Deployment Failed *** "Migrations" -- Returned error: authentication needed: password or unlock -- Reason given: Custom error (could not decode).. at C:\Users\Siddhartha\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\deployer\src\deployment.js:331:1 at processTicksAndRejections (node:internal/process/task_queues:95:5) at Migration._deploy (C:\Users\Siddhartha\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\migrate\Migration.js:68:1) at Migration._load (C:\Users\Siddhartha\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\migrate\Migration.js:54:1) at Migration.run (C:\Users\Siddhartha\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\migrate\Migration.js:202:1) at Object.runMigrations (C:\Users\Siddhartha\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\migrate\index.js:142:1) at Object.runFrom (C:\Users\Siddhartha\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\migrate\index.js:107:1) at Object.run (C:\Users\Siddhartha\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\migrate\index.js:91:1) at module.exports (C:\Users\Siddhartha\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\core\lib\commands\migrate\runMigrations.js:10:1) at Object.module.exports [as run] (C:\Users\Siddhartha\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\core\lib\commands\migrate\run.js:39:1) at runCommand (C:\Users\Siddhartha\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\core\lib\command-utils.js:184:1) Truffle v5.5.23 (core: 5.5.23) Node v18.6.0 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | Note:- If you try to upload the contract when you did not have any eth added to your accougt then you will get below error. c:\truffle-project>truffle migrate --network rinkeby Compiling your contracts... =========================== > Compiling .\contracts\Migrations.sol > Compiling .\contracts\MyBank.sol > Compiling .\contracts\SendMoney.sol > Compiling .\contracts\SendMoneyApproval.sol > Compiling .\contracts\SendMoneyWithApproval.sol > Artifacts written to c:\truffle-project\build\contracts > Compiled successfully using: - solc: 0.8.15+commit.e14f2714.Emscripten.clang Migrations dry-run (simulation) =============================== > Network name: 'rinkeby-fork' > Network id: 4 > Block gas limit: 4700000 (0x47b760) 1_initial_migration.js ====================== Deploying 'Migrations' ---------------------- *** Deployment Failed *** "Migrations" could not deploy due to insufficient funds * Account: 0x1868fd2095D338e643e54Cc08f1390e43C8c4d08 * Balance: 0 wei * Message: insufficient funds for gas * price + value -- Reason given: Custom error (could not decode). * Try: + Using an adequately funded account + If you are using a local Geth node, verify that your node is synced. Exiting: Review successful transactions manually by checking the transaction hashes above on Etherscan. Error: *** Deployment Failed *** "Migrations" could not deploy due to insufficient funds * Account: 0x1868fd2095D338e643e54Cc08f1390e43C8c4d08 * Balance: 0 wei * Message: insufficient funds for gas * price + value -- Reason given: Custom error (could not decode). * Try: + Using an adequately funded account + If you are using a local Geth node, verify that your node is synced. at C:\Users\Siddhartha\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\deployer\src\deployment.js:331:1 at processTicksAndRejections (node:internal/process/task_queues:95:5) at Migration._deploy (C:\Users\Siddhartha\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\migrate\Migration.js:68:1) at Migration._load (C:\Users\Siddhartha\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\migrate\Migration.js:54:1) at Migration.run (C:\Users\Siddhartha\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\migrate\Migration.js:202:1) at Object.runMigrations (C:\Users\Siddhartha\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\migrate\index.js:142:1) at Object.runFrom (C:\Users\Siddhartha\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\migrate\index.js:107:1) at Object.run (C:\Users\Siddhartha\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\migrate\index.js:91:1) at module.exports (C:\Users\Siddhartha\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\core\lib\commands\migrate\runMigrations.js:10:1) at module.exports (C:\Users\Siddhartha\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\core\lib\commands\migrate\setUpDryRunEnvironmentThenRunMigrations.js:37:1) at Object.module.exports [as run] (C:\Users\Siddhartha\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\core\lib\commands\migrate\run.js:33:1) at runCommand (C:\Users\Siddhartha\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\core\lib\command-utils.js:184:1) Truffle v5.5.23 (core: 5.5.23) Node v18.6.0 c:\truffle-project> Now as you see above our depoyement fail it indicate that we did not unlock our account for longer time this can be done using belwo command web3.personal.unlockAccount(web3.personal.listAccounts[0],"password",15000); |
and also change the truffle-config.js
1 2 3 4 5 6 7 | rinkeby: { host: "127.0.0.1", port: 8545, network_id: 4, gas: 2900000, from: "0x1868fd2095d338e643e54cc08f1390e43c8c4d08" } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 | Now as you see our all the smart contract is deployed properly on rinkeby test network. PS C:\truffle-project> truffle migrate --network rinkeby Compiling your contracts... =========================== > Compiling .\contracts\Migrations.sol > Compiling .\contracts\MyBank.sol > Compiling .\contracts\SendMoney.sol > Compiling .\contracts\SendMoneyApproval.sol > Compiling .\contracts\SendMoneyWithApproval.sol > Artifacts written to C:\truffle-project\build\contracts > Compiled successfully using: - solc: 0.8.15+commit.e14f2714.Emscripten.clang Migrations dry-run (simulation) =============================== > Network name: 'rinkeby-fork' > Network id: 4 > Block gas limit: 30000000 (0x1c9c380) 1_initial_migration.js ====================== Deploying 'Migrations' ---------------------- > block number: 11138306 > block timestamp: 1659537239 > account: 0x1868fd2095D338e643e54Cc08f1390e43C8c4d08 > balance: 0.09937461499624769 > gas used: 250154 (0x3d12a) > gas price: 2.500000015 gwei > value sent: 0 ETH > total cost: 0.00062538500375231 ETH ------------------------------------- > Total cost: 0.00062538500375231 ETH 2_initial_bank.js ================= Deploying 'MyBank' ------------------ > block number: 11138308 > block timestamp: 1659537240 > account: 0x1868fd2095D338e643e54Cc08f1390e43C8c4d08 > balance: 0.098667357492524038 > gas used: 236990 (0x39dbe) > gas price: 2.500000013 gwei > value sent: 0 ETH > total cost: 0.00059247500308087 ETH ------------------------------------- > Total cost: 0.00059247500308087 ETH 3_initial_sendmoney.js ====================== Deploying 'SendMoney' --------------------- > block number: 11138310 > block timestamp: 1659537240 > account: 0x1868fd2095D338e643e54Cc08f1390e43C8c4d08 > balance: 0.098194514990414718 > gas used: 160324 (0x27244) > gas price: 2.500000011 gwei > value sent: 0 ETH > total cost: 0.000400810001763564 ETH ------------------------------------- > Total cost: 0.000400810001763564 ETH 4_initial_sendmoneyapprover.js ============================== Deploying 'SendMoneyApproval' ----------------------------- > block number: 11138312 > block timestamp: 1659537240 > account: 0x1868fd2095D338e643e54Cc08f1390e43C8c4d08 > balance: 0.097460764987744405 > gas used: 264687 (0x409ef) > gas price: 2.500000009 gwei > value sent: 0 ETH > total cost: 0.000661717502382183 ETH ------------------------------------- > Total cost: 0.000661717502382183 ETH 5_initial_sendmoneywithapprover.js ================================== Deploying 'SendMoneyWithApproval' --------------------------------- > block number: 11138314 > block timestamp: 1659537241 > account: 0x1868fd2095D338e643e54Cc08f1390e43C8c4d08 > balance: 0.096377402484277645 > gas used: 404532 (0x62c34) > gas price: 2.500000008 gwei > value sent: 0 ETH > total cost: 0.001011330003236256 ETH ------------------------------------- > Total cost: 0.001011330003236256 ETH Summary ======= > Total deployments: 5 > Final cost: 0.003291717514215183 ETH Starting migrations... ====================== > Network name: 'rinkeby' > Network id: 4 > Block gas limit: 30000000 (0x1c9c380) 1_initial_migration.js ====================== Deploying 'Migrations' ---------------------- > transaction hash: 0x343a9490d73295c87cfc3e7734d4a1aa5ad790b6abe26d1d18d75b268820f46e > Blocks: 1 Seconds: 4 > contract address: 0x8e5120cC2e9B8D5bb9dD54EC904E5599219b121B > block number: 11138310 > block timestamp: 1659537243 > account: 0x1868fd2095D338e643e54Cc08f1390e43C8c4d08 > balance: 0.099374614995747382 > gas used: 250154 (0x3d12a) > gas price: 2.500000017 gwei > value sent: 0 ETH > total cost: 0.000625385004252618 ETH > Saving migration to chain. > Saving artifacts ------------------------------------- > Total cost: 0.000625385004252618 ETH 2_initial_bank.js ================= Deploying 'MyBank' ------------------ > transaction hash: 0x53ae63bbd67d5db5ce2b53b8b8b355fb53fbbc06a3b1ebd67db6445498feb79d > Blocks: 1 Seconds: 12 > contract address: 0x306872A51A39C778D8Ab798FF27A5c87B87401a4 > block number: 11138312 > block timestamp: 1659537274 > account: 0x1868fd2095D338e643e54Cc08f1390e43C8c4d08 > balance: 0.098667357490938031 > gas used: 236990 (0x39dbe) > gas price: 2.500000017 gwei > value sent: 0 ETH > total cost: 0.00059247500402883 ETH > Saving migration to chain. > Saving artifacts ------------------------------------- > Total cost: 0.00059247500402883 ETH 3_initial_sendmoney.js ====================== Deploying 'SendMoney' --------------------- > transaction hash: 0xafe681577bf55094683cb1063333bb65bb2f0207bd2e2b5a1558ce7820a02bcd > Blocks: 0 Seconds: 12 > contract address: 0xAF1B2c67bE7dC5aB712590CdC5DC352d772Cb1BB > block number: 11138314 > block timestamp: 1659537304 > account: 0x1868fd2095D338e643e54Cc08f1390e43C8c4d08 > balance: 0.098194514987373241 > gas used: 160324 (0x27244) > gas price: 2.500000019 gwei > value sent: 0 ETH > total cost: 0.000400810003046156 ETH > Saving migration to chain. > Saving artifacts ------------------------------------- > Total cost: 0.000400810003046156 ETH 4_initial_sendmoneyapprover.js ============================== Deploying 'SendMoneyApproval' ----------------------------- > transaction hash: 0x055dc068efaedfb1142d18f9b2b6e66936f4e6a6bfddf12596fde5b7dfa0571b > Blocks: 0 Seconds: 12 > contract address: 0x0B76eBF3cB137f764fa763c639C88F7dB2a160f8 > block number: 11138316 > block timestamp: 1659537334 > account: 0x1868fd2095D338e643e54Cc08f1390e43C8c4d08 > balance: 0.097460764982354928 > gas used: 264687 (0x409ef) > gas price: 2.500000017 gwei > value sent: 0 ETH > total cost: 0.000661717504499679 ETH > Saving migration to chain. > Saving artifacts ------------------------------------- > Total cost: 0.000661717504499679 ETH 5_initial_sendmoneywithapprover.js ================================== Deploying 'SendMoneyWithApproval' --------------------------------- > transaction hash: 0x293b8bd197bcbce7c843d2ba5f30974876626cfbe17330585baffad479f21fe0 > Blocks: 0 Seconds: 12 > contract address: 0x7CbEd17ccAcfd4Fc2E5D73D6cC7F325FD6CFCDEB > block number: 11138318 > block timestamp: 1659537365 > account: 0x1868fd2095D338e643e54Cc08f1390e43C8c4d08 > balance: 0.096377402475421408 > gas used: 404532 (0x62c34) > gas price: 2.500000016 gwei > value sent: 0 ETH > total cost: 0.001011330006472512 ETH > Saving migration to chain. > Saving artifacts ------------------------------------- > Total cost: 0.001011330006472512 ETH Summary ======= > Total deployments: 5 > Final cost: 0.003291717522299795 ETH PS C:\truffle-project> |
Now that we have our smart contract deployed publicly and we have a distributed backend to our app. But in order to access this through our web UI, we either need to have the assets locally or we have to deploy them to a web server, both of which take away the key advantage of having a decentralized app. Fortunately, Ethereum comes with an option to deploy our files on the blockchain, it’s called Swarm. The beauty of Swarm is it comes with Geth.
So lets do that now First thing we need to start up Swarm. In order to start Swarm, we need to have an account set up.
So Swarm is enabled at a command line by nature of having Geth running. So just like other things in the Ethereum network, we do it through an Ethereum account.
we are gonna go to Geth, we will create account new and then we will write a password. we will use this address for connecting and starting the swarm.
PS C:\truffle-project> geth account new
INFO [08-03|20:13:34.330] Maximum peer count ETH=50 LES=0 total=50
Your new account is locked with a password. Please give a password. Do not forget this password.
Password:
Repeat password:
Your new key was generated
Public address of the key: 0xc64462a2f077e13F005e24B3b934E3d03631c567
Path of the secret key file: C:\Users\Siddhartha\AppData\Local\Ethereum\keystore\UTC–2022-08-03T14-43-39.680006900Z–c64462a2f077e13f005e24b3b934e3d03631c567
- You can share your public address with anyone. Others need it to interact with you.
- You must NEVER share the secret key with anyone! The key controls access to your funds!
- You must BACKUP your key file! Without the key, it’s impossible to access account funds!
- You must REMEMBER your password! Without the password, it’s impossible to decrypt the key!
PS C:\truffle-project>
Now, one of the things we are going to do is we will turn off the Ethereum naming service. It’s like a domain name service that’s set up just for Ethereum. we don’t have it all configured, so we just not gonna turn it on. And then we gonna set my B-Z-Z account which is my Swarm account to my private key.
first we need to install swarm in our machine refer to the below sites
Make sure you have GO installed and set in your PATH and then execute below command.
https://github.com/ethersphere/swarm
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | c:\swarm>go get -d github.com/ethersphere/swarm PS C:\swarm> go get -d github.com/ethersphere/swarm go: downloading github.com/ethersphere/swarm v0.5.8 go: downloading github.com/ethereum/go-ethereum v1.9.2 go: downloading github.com/rnsdomains/rns-go-lib v0.0.0-20191114120302-3505575b0b8f go: downloading golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4 go: downloading github.com/elastic/gosigar v0.0.0-20180330100440-37f05ff46ffa go: downloading github.com/golang/snappy v0.0.1 go: downloading golang.org/x/sync v0.0.0-20190423024810-112230192c58 go: downloading github.com/opentracing/opentracing-go v1.1.0 go: downloading github.com/pborman/uuid v0.0.0-20170112150404-1b00554d8222 go: downloading github.com/rs/cors v0.0.0-20160617231935-a62a804a8a00 go: downloading github.com/deckarep/golang-set v0.0.0-20180603214616-504e848d77ea go: downloading github.com/gorilla/websocket v1.4.0 go: downloading gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce go: downloading bazil.org/fuse v0.0.0-20160811212531-371fbbdaa898 go: downloading golang.org/x/net v0.0.0-20190724013045-ca1201d0de80 go: downloading github.com/hashicorp/golang-lru v0.5.3 go: downloading github.com/syndtr/goleveldb v0.0.0-20190318030020-c3a204f8e965 go: downloading github.com/tilinna/clock v1.0.2 go: downloading github.com/uber/jaeger-client-go v0.0.0-20180607151842-f7e0d4744fa6 go: downloading github.com/caarlos0/env v3.5.0+incompatible go: downloading github.com/rjeczalik/notify v0.9.1 go: downloading github.com/btcsuite/btcd v0.0.0-20171128150713-2e60448ffcc6 go: downloading github.com/go-stack/stack v1.8.0 go: downloading golang.org/x/sys v0.0.0-20190804053845-51ab0e2deafa go: downloading github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d go: downloading github.com/aristanetworks/goarista v0.0.0-20170210015632-ea17b1a17847 go: downloading github.com/huin/goupnp v0.0.0-20161224104101-679507af18f3 go: downloading github.com/jackpal/go-nat-pmp v0.0.0-20160603034137-1fa385a6f458 go: downloading github.com/prometheus/tsdb v0.10.0 go: downloading github.com/rs/xhandler v0.0.0-20170707052532-1eb70cf1520d go: downloading github.com/mattn/go-colorable v0.1.2 go: downloading github.com/peterh/liner v0.0.0-20190123174540-a2c9a5303de7 go: downloading github.com/robertkrimen/otto v0.0.0-20170205013659-6a77b7cbc37d go: downloading github.com/ethersphere/go-sw3 v0.2.1 go: downloading github.com/uber/jaeger-lib v0.0.0-20180615202729-a51202d6f4a7 go: downloading github.com/davecgh/go-spew v1.1.1 go: downloading github.com/tyler-smith/go-bip39 v0.0.0-20181017060643-dbb3b84ba2ef go: downloading github.com/allegro/bigcache v0.0.0-20190218064605-e24eb225f156 go: downloading github.com/steakknife/bloomfilter v0.0.0-20180922174646-6819c0d2a570 go: downloading github.com/go-ole/go-ole v1.2.4 go: downloading github.com/gballet/go-libpcsclite v0.0.0-20190528105824-2fd9b619dd3c go: downloading github.com/status-im/keycard-go v0.0.0-20190316090335-8537d3370df4 go: downloading github.com/wsddn/go-ecdh v0.0.0-20161211032359-48726bab9208 go: downloading golang.org/x/text v0.3.2 go: downloading github.com/golang/protobuf v1.3.2 go: downloading github.com/karalabe/usb v0.0.0-20190819132248-550797b1cad8 go: downloading github.com/olekukonko/tablewriter v0.0.0-20190409134802-7e037d187b0c go: downloading github.com/fjl/memsize v0.0.0-20180418122429-ca190fb6ffbc go: downloading github.com/mattn/go-isatty v0.0.8 go: downloading gopkg.in/urfave/cli.v1 v1.20.0 go: downloading github.com/fatih/color v1.7.0 go: downloading github.com/mattn/go-runewidth v0.0.6 go: downloading github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd go: downloading github.com/edsrzf/mmap-go v0.0.0-20160512033002-935e0e8a636c go: downloading github.com/steakknife/hamming v0.0.0-20180906055917-c99c65617cd3 go: downloading gopkg.in/sourcemap.v1 v1.0.5 go: downloading github.com/uber/jaeger-client-go v1.6.0 go: downloading github.com/uber/jaeger-lib v1.5.0 |
c:\swarm>go install github.com/ethersphere/swarm/cmd/swarm@latest
Go to your web folder and execute belwo command.
check swarm is installed using below command
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | PS C:\truffle-project\web> swarm --version swarm.exe version 0.5.8-unstable swarm.exe --bzzaccount 0xc64462a2f077e13F005e24B3b934E3d03631c567 --ens-api \\.\pipe\geth.ipc PS C:\truffle-project\web> swarm.exe --bzzaccount 0xc64462a2f077e13F005e24B3b934E3d03631c567 --ens-api \\.\pipe\geth.ipc INFO [08-03|20:53:08.451] Maximum peer count ETH=50 LES=0 total=50 Unlocking swarm account 0xc64462a2f077e13F005e24B3b934E3d03631c567 [1/3] Passphrase: INFO [08-03|20:53:14.630] Starting peer-to-peer node instance=swarm/v0.5.8/windows-amd64/go1.16.2 INFO [08-03|20:53:14.767] connecting to ENS API url=\\\\.\\pipe\\geth.ipc INFO [08-03|20:53:15.127] New local node record seq=1 id=c86ad3ed92dcb0b3 ip=127.0.0.1 udp=30399 tcp=30399 INFO [08-03|20:53:15.135] Updated bzz local addr oaddr=ebc1186207ab22cf67bce2923c4aa8008da9a7ab57b5aea064262d7d5f334a35 uaddr=enode://72b943a60be89ea73eb61aaf6581b6496066ef0486cfe9a6324fc134723a40e6d3299b23a03c26534f683344e32580ba4d9375c4a05fcfd30bed22903b0ee128@127.0.0.1:30399 INFO [08-03|20:53:15.150] Starting bzz service INFO [08-03|20:53:15.152] Starting hive baseaddr=ebc11862 INFO [08-03|20:53:15.136] Started P2P networking self=enode://72b943a60be89ea73eb61aaf6581b6496066ef0486cfe9a6324fc134723a40e6d3299b23a03c26534f683344e32580ba4d9375c4a05fcfd30bed22903b0ee128@127.0.0.1:30399 INFO [08-03|20:53:15.163] Detected an existing store. trying to load peers INFO [08-03|20:53:15.171] hive ebc11862: no persisted peers found INFO [08-03|20:53:15.174] Swarm network started bzzaddr=ebc1186207ab22cf67bce2923c4aa8008da9a7ab57b5aea064262d7d5f334a35 INFO [08-03|20:53:15.182] bzzeth starting... INFO [08-03|20:53:15.184] Starting outbox INFO [08-03|20:53:15.186] Started Pss INFO [08-03|20:53:15.189] Loaded EC keys pubkey=0423f6d07b7fe22816853a5223cefd9026d42ed3decadc83a6caccc8ea04fa21e5085edccfbd6f4552e10c3537aff15595191ccbfca527fd9b9ba60a4e4ccc67d6 secp256=0223f6d07b7fe22816853a5223cefd9026d42ed3decadc83a6caccc8ea04fa21e5 INFO [08-03|20:53:15.204] starting bzz-retrieve INFO [08-03|20:53:15.204] Starting Swarm HTTP proxy port=8500 INFO [08-03|20:53:15.209] IPC endpoint opened url=\\\\.\\pipe\\bzzd.ipc |
we’re up and running with Swarm. So the next thing we need to do is I need to go to my web directory which I’m at which is in web in my desktop, that’s where I’m storing it and I’m going to go ahead and upload everything using belwo screen
Now lets configure our Metamask for this user and perform our operations.
when u to access the site it will give error as our contractaddress is not perfect
The above error will go if you use belwo command to upload the file on the swarm
1 | c:\truffle-project\web>swarm --recursive up ./ |
Discuss about the truffle dashboard command
truffle(development)> truffle dashboard
Truffle Dashboard running at http://localhost:24012
DashboardProvider RPC endpoint running at http://localhost:24012/rpc
To disconnect
So in short we had done following things in this blog
1- we use the frame work of truffle to create a project and used VS Code as code editor.
2- we integrate Ganache UI for test server and integrate it with truffle.
3- We created a smart contract on solidity
4- we tested it on Remix site
4- we tested it on local truffle configured on Ganache Test server data.
5- we tested it on Remix site using Ganache UI as test server.
6- We tested our smart contract on Remix site using Ganache UI as test server and metamask as wallet.(ask for permission to confirm any transection to execute and debit the respective amount from our wallets).
6- we created UI simple html and with the help of web3.js interact with our smart contract exposed on truffle with Ganache ui test server data locally (means not deployed our html on any server localhost direcly opened it on browser and test it for claling smart contract).
7- We exposed our simple ui html on local host using php server and contacted our smart contract deployed/migrated on Truffle using Metamast as wallets
8- Then we instlled geth client and made our machine as an ethereum node so that we can upload our contract on Test ehereum block chain.
8- Finally we deployed our smart contract on test env along with ui on swarm and consumed it using browser.
you can get the contract on below git hub location
remix contract code
https://github.com/shdhumale/remix-backup-at-11h49min-2022-8-2.git
truffle contract and web code (whole Project)
No comments:
Post a Comment