app.js

First, create a js/ directory inside the src/ directory, and then create an empty file named app.js.

At the top of the file, create the variables we'll need later:

App = {
web3Provider: null,
contracts: {},
account: '0x0',
loading: false,
tokenPrice: 0,
tokensSold: 0,
tokensAvailable: 500000,
...

Next, define the main initialization function:

 init: function() {
return App.initWeb3();
},

This calls our web3 initialization function:

initWeb3: function() {
if (typeof web3 !== 'undefined') {
App.web3Provider = web3.currentProvider;
web3 = new Web3(web3.currentProvider);
} else {
App.web3Provider = new Web3.providers.HttpProvider('http://localhost:8545');
web3 = new Web3(App.web3Provider);
}
return App.initContracts();
},

This is a standard pattern for setting the web3 provider. The if clause checks whether a provider has been injected into the current page, which will be true if the user is using MetaMask. If web3 is undefined, the else clause sets an alternative, which, in this case is a client running locally on port 8545. This could be Ganache, or an Ethereum client, such as Geth, connected to a public or private network. We will assume that anyone wanting to participate in our ICO has an appropriate provider.

Next, we get references to both the deployed contracts, and output their addresses to the console for debugging purposes:

 initContracts: function() {
$.getJSON("PacktTokenSale.json", function(packtTokenSale) {
App.contracts.PacktTokenSale = TruffleContract(packtTokenSale);
App.contracts.PacktTokenSale.setProvider(App.web3Provider);
App.contracts.PacktTokenSale.deployed().then(function(packtTokenSale) {
console.log("Dapp Token Sale Address:", packtTokenSale.address);
});
}).done(function() {
$.getJSON("PacktToken.json", function(packtToken) {
App.contracts.PacktToken = TruffleContract(packtToken);
App.contracts.PacktToken.setProvider(App.web3Provider);
App.contracts.PacktToken.deployed().then(function(packtToken) {
console.log("Dapp Token Address:", packtToken.address);
});

App.listenForEvents();
return App.render();
});
});
},

The next part has the job of listening for Sell events from the deployed contracts, and re-rendering the page when they are received:

 listenForEvents: function() {
App.contracts.PacktTokenSale.deployed().then(function(instance) {
instance.Sell({}, {
fromBlock: 0,
toBlock: 'latest',
}).watch(function(error, event) {
console.log("event triggered", event);
App.render();
});
});
},

The next part is more involved, and is responsible for reading the values from the deployed contracts and rendering them as the user interface. With reference to the ID values set in index.html, the code should be self-explanatory. Of interest is the message output while the data is being loaded, and how this is controlled using the loader variable:

  render: function() {
if (App.loading) {
return;
}
App.loading = true;

const loader = $('#contentLoader');
const content = $('#content');

loader.show();
content.hide();

web3.eth.getCoinbase(function(err, account) {
if (err === null) {
App.account = account;
$('#accountAddress').html(account);
}
});

App.contracts.PacktTokenSale.deployed().then(function(instance) {
packtTokenSaleInstance = instance;
return packtTokenSaleInstance.tokenPrice();
}).then(function(tokenPrice) {
App.tokenPrice = tokenPrice;
$('#tokenPrice').html(web3.fromWei(App.tokenPrice, "ether").toNumber());
return packtTokenSaleInstance.tokensSold();
}).then(function(tokensSold) {
App.tokensSold = tokensSold.toNumber();
$('#tokensSold').html(App.tokensSold);
$('#tokensAvailable').html(App.tokensAvailable);

var progress = (Math.ceil(App.tokensSold) / App.tokensAvailable) * 100;
$('#progress').css('width', progress + '%');

App.contracts.PacktToken.deployed().then(function(instance) {
packtTokenInstance = instance;
return packtTokenInstance.balanceOf(App.account);
}).then(function(balance) {
$('#tokenBalance').html(balance.toNumber());
return packtTokenInstance.name();
}).then(function(name) {
$('#tokenName').html(name);
return packtTokenInstance.symbol();
}).then(function(symbol) {
$('#tokenSymbol').html(symbol);
App.loading = false;
loader.hide();
content.show();
});
});
},

The final part of the code is the function called by the HTML's onSubmit handler, buyTokens(). This calls the associated function in the token sale contract:

  buyTokens: function() {
$('#content').hide();
$('#contentLoader').show();
const numberOfTokens = $('#numberOfTokens').val();
App.contracts.PacktTokenSale.deployed().then(function(instance) {
return instance.buyTokens(numberOfTokens, {
from: App.account,
value: numberOfTokens * App.tokenPrice,
});
}).then(function(result) {
console.log(result);
$('form').trigger('reset');
});
}

Combining the preceding with a call to App.init() at the bottom of the file gives the following overall code:

App = {
web3Provider: null,
contracts: {},
account: '0x0',
loading: false,
tokenPrice: 0,
tokensSold: 0,
tokensAvailable: 500000,

init: function() {
return App.initWeb3();
},

initWeb3: function() {
if (typeof web3 !== 'undefined') {
App.web3Provider = web3.currentProvider;
web3 = new Web3(web3.currentProvider);
} else {
App.web3Provider =
new Web3.providers.HttpProvider('http://localhost:7545');
web3 = new Web3(App.web3Provider);
}
return App.initContracts();
},

initContracts: function() {
$.getJSON("PacktTokenSale.json", function(packtTokenSale) {
App.contracts.PacktTokenSale = TruffleContract(packtTokenSale);
App.contracts.PacktTokenSale.setProvider(App.web3Provider);
App.contracts.PacktTokenSale.deployed().then(function(packtTokenSale) {
console.log("Dapp Token Sale Address:", packtTokenSale.address);
});
}).done(function() {
$.getJSON("PacktToken.json", function(packtToken) {
App.contracts.PacktToken = TruffleContract(packtToken);
App.contracts.PacktToken.setProvider(App.web3Provider);
App.contracts.PacktToken.deployed().then(function(packtToken) {
console.log("Dapp Token Address:", packtToken.address);
});

App.listenForEvents();
return App.render();
});
});
},

listenForEvents: function() {
App.contracts.PacktTokenSale.deployed().then(function(instance) {
instance.Sell({}, {
fromBlock: 0,
toBlock: 'latest',
}).watch(function(error, event) {
console.log("event triggered", event);
App.render();
});
});
},

render: function() {
if (App.loading) {
return;
}
App.loading = true;

const loader = $('#contentLoader');
const content = $('#content');

loader.show();
content.hide();

web3.eth.getCoinbase(function(err, account) {
if (err === null) {
App.account = account;
$('#accountAddress').html(account);
}
});

App.contracts.PacktTokenSale.deployed().then(function(instance) {
packtTokenSaleInstance = instance;
return packtTokenSaleInstance.tokenPrice();
}).then(function(tokenPrice) {
App.tokenPrice = tokenPrice;
$('#tokenPrice').html(web3.fromWei(App.tokenPrice, "ether").toNumber());
return packtTokenSaleInstance.tokensSold();
}).then(function(tokensSold) {
App.tokensSold = tokensSold.toNumber();
$('#tokensSold').html(App.tokensSold);
$('#tokensAvailable').html(App.tokensAvailable);

var progress = (Math.ceil(App.tokensSold) / App.tokensAvailable) * 100;
$('#progress').css('width', progress + '%');

App.contracts.PacktToken.deployed().then(function(instance) {
packtTokenInstance = instance;
return packtTokenInstance.balanceOf(App.account);
}).then(function(balance) {
$('#tokenBalance').html(balance.toNumber());
return packtTokenInstance.name();
}).then(function(name) {
$('#tokenName').html(name);
return packtTokenInstance.symbol();
}).then(function(symbol) {
$('#tokenSymbol').html(symbol);
App.loading = false;
loader.hide();
content.show();
});
});
},

buyTokens: function() {
$('#content').hide();
$('#contentLoader').show();
const numberOfTokens = $('#numberOfTokens').val();
App.contracts.PacktTokenSale.deployed().then(function(instance) {
return instance.buyTokens(numberOfTokens, {
from: App.account,
value: numberOfTokens * App.tokenPrice,
});
}).then(function(result) {
console.log(result);
$('form').trigger('reset');
});
}
};

App.init();
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset