Im making a frontend for a Dapp, so after making instances of the smart contracts and setting a provider I try to deploy the contract, get the token balance and display it in on the web page but get the error:
Cannot read property 'deployed' of undefined
in my browser.
Note that my FixedSupplyToken.sol is deployed on test RPC as I can see in the FixedSupplyToken.json file, it has an address. Was thinking this was the issue, but no such luck.
app.js:
// Import libraries we need.
import { default as Web3} from 'web3';
import { default as contract } from 'truffle-contract'
// Import our contract artifacts and turn them into usable abstractions.
import exchange_artifacts from '../../build/contracts/Exchange.json'
import token_artifacts from '../../build/contracts/FixedSupplyToken.json'
var accounts;
var account;
var ExchangeContract = contract(exchange_artifacts);
var TokenContract = contract(token_artifacts);
window.App = {
start: function() {
//bootstrap everything
ExchangeContract = web3.setProvider(web3.currentProvider);
TokenContract = web3.setProvider(web3.currentProvider);
},
//update balance function
updateTokenBalance: function() {
var tokenInstance;
**TokenContract.deployed().then(function (instance) { // getting the Uncaught TypeError: Cannot read property 'deployed' of undefined**
tokenInstance = instance;
return tokenInstance.balanceOf.call(account);
}).then(function (value) {
var balance_element = document.getElementById("balanceTokenInToken");
balance_element.innerHTML = value.valueOf();
}).catch(function (e) {
console.log(e);
App.setStatus("Error getting balance; see log.");
});
},
Even if I uncomment web3.setProvider(web3.currentProvider)
I get the setProvider undefined error.
In the
start
function, you're reassigning theTokenContract
variable.Try changing
to:
Edit based on comment:
The root of the problem is that
web3.setProvider
method returns void orundefined
, so in the statementTokenContract = web3.setProvider(web3.currentProvider);
you are assigningundefined
toTokenContract
, hence the error. Setting the web3 provider and the Truffle contract provider are two different actions. Not sure if there's more code in the//bootstrap everything
but if for some reason you need to set the provider explicitly try changing the code to:The first line, though, shouldn't be necessary if Web3 is configured correctly. I suggest reading this article for this since there's been changes in how this is done: https://medium.com/@awantoch/how-to-connect-web3-js-to-metamask-in-2020-fee2b2edf58a.
The gist of it is: