0

I have a project where rather than installing modules I have to import web3.js cdn. It's possible to find it here: https://cdn.jsdelivr.net/gh/ethereum/web3.js@1.0.0-beta.34/dist/

In the project there is a specific part integrating the script:

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

However I am slightly confused if this is really web3.js 1.0.0.

According to this source, if the web3 is under 1.0 you initiate contracts as

var MyContract = web3.eth.contract(abiArray, contractAddress);

In web3 1.0 and above instead:

var MyContract = new web3.eth.Contract(abiArray, contractAddress);

I am forced in my syntax to use the one provided for versions below 1.0, yet I am importing web3.js@1.0.0-beta.34.

I decided to print the web3 version using

console.log(web3.version);

and in my console it appears to be 0.20.7.

Keep in mind that I tried other packages (from those that work as most don't lol) and the result is similar (I may get another version such as 0.20.8)

----------------Solution in short:

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

<script>
window.addEventListener('load', function () {
    if (typeof web3 !== 'undefined') {
        console.log('Web3 Detected! ' + web3.currentProvider.constructor.name)
        window.web3 = new Web3(web3.currentProvider);
    } else {
        console.log('No Web3 Detected... using HTTP Provider')
        window.web3 = new Web3(new Web3.providers.HttpProvider("https://rinkeby.infura.io/v3/yourInfuraKey"));
    }
})

</script>
  • From the source it appears to be 1.0.0-beta34. How do you instantiate web3 variable? Perhaps some other dependency is bringing an old version. – Ismael Sep 16 at 4:46
  • I think I know what's the problem. The 0.20.7 version is somehow from metamask. When I go with another browser or incognito on the same page I'm getting web3 not defined, despite using <script src="cdn.jsdelivr.net/gh/ethereum/web3.js@1.0.0-beta.34/dist/…> – Cristian Sep 16 at 19:59
1

Once you have loaded web3.min.js it should have created Web3 (with uppercase). Then you have to instantiate your own instance:

web3 = new Web3("http://ropsten.infura.io/v3/MyOtterToken")
  • Oops I literally forgot this step despite using it multiple times before. Thanks – Cristian Sep 16 at 22:53

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.