0

I am trying to connect to web3 1.0 through a web browser, I dont see much documentation for 1.0 though. This script says im connected but I think its the previous version as anytime I try and run a 1.0 function I get the function is undefined -

<script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js@1.0.0-beta.34/dist/web3.min.js"></script>

<script>

function initweb3 () {
web3 = new Web3(new Web3.providers.HttpProvider("https://mainnet.infura.io/v3/My Api Key"));        
}

window.addEventListener('load',initweb3);

if(web3.isConnected()) {
    alert("Web3 Connected!");
} else {
    alert("Web3 Not Conected");
}

var abi = JSON.parse('[{"MY ABI"}]')

var AK = new web3.eth.contract(abi);

// Set Contract Address
AK.options.address = "Contract Address";

AK.methods.balanceOf("Address to get balance of").call().then(function(balance) { 
alert("Balance is " + balance.toString()) });

This Throws

 Uncaught TypeError: Cannot set property 'address' of undefined

It works fine when I run locally so I think its not connecting to version 1.0

1

I see that you found out a solution apparently. However the code proposed in the description of the problem is not correct and could have led to your error:

var AK = new web3.eth.contract(...)

Should actually be

var AK = new web3.eth.Contract(...)

Note the uppercase, which is necessary since you're actually instanciating a class here. This could have led to the undefined issue you faced. Furthermore, you can simplify your code (remove one line) by loading the contract at address directly:

var AK = new web3.eth.Contract(ABI, address)

This saves you one line. See the full documentation here.

  • yes you are correct, the lower case was for the older version and uppercase is needed for 1.0, I fixed this in my script but forgot to update it here.. Great catch! – Ryan D Oct 28 '18 at 20:43
0

It works now

<script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js@1.0.0-beta.34/dist/web3.min.js"></script>

var web3 = new Web3();
if(web3.setProvider(new Web3.providers.HttpProvider('https://mainnet.infura.io/v3/MY API KEY'))){
web3.eth.net.isListening();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.