Stage 3: Token Interface¶
Now you will connect your web application to your newly created Token
contract!
Important
Now you should transition back to your Sublime text editor to begin editing your application code.
All of the application development will take place within the src/App.js
file.
Please begin by opening this file which may be done so simply by double-clicking on it in the left file tree under the src
folder.
Note you may also close the other files you may still have open test_buy.js
or 2_deploy_contracts.js
.
Time to start wiring it up!
- Import the web3 library,
src/app.js
#line 5
import Web3 from 'web3';
- Import the token build artifacts into the application, app.js#line 14
import tokenArtifacts from './build/contracts/Token.json';
- Create a web3 connection to the local Ethereum node(ganache), app.js#line 26
this.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
- Detect the current network id that is connected, app.js#line 28-30
Note
This needs to be after the
this.web3 = ...
line above and within thecomponentDidMount(){}
function
i.e.
async componentDidMount() { this.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545")); this.web3.version.getNetwork(async (err, netId) => { }); }this.web3.version.getNetwork(async (err, netId) => { });
- Extract the recently deploy token address from the build artifacts, app.js#line 29
Important
This must be placed within the callback of the above
getNetwork
function call wherenetId
is available!i.e.
this.web3.version.getNetwork(async (err, netId) => { const tokenAddress = tokenArtifacts.networks[netId].address; });const tokenAddress = tokenArtifacts.networks[netId].address;
- Create a client side reference to the contract and save it in the application’s state, app.js#line 30-32
Important
This must be placed within the callback of the above
getNetwork
function call wherenetId
is available!i.e.
this.web3.version.getNetwork(async (err, netId) => { const tokenAddress = tokenArtifacts.networks[netId].address; const token = this.web3.eth.contract(tokenArtifacts.abi).at(tokenAddress); this.setState({ token }); console.log(token); });const token = this.web3.eth.contract(tokenArtifacts.abi).at(tokenAddress); this.setState({ token }); console.log(token);
- Refresh your chrome browser and open up the developer console
This can be accomplished by right-clicking anywhere in the chrome browser and in the dropdown selecting inspect
or inspect element
or by utilizing the shortcut: ctrl+shift+i
.
View in the developer console the token instance is now present
- Example output:
Contract {_eth: Eth, transactionHash: null, address: "0xd58c6b5e848d70fd94693a370045968c0bc762a7", abi: Array[20]}