[Ethereum] Simplest way to integrate Infura with a Web3/Truffle app

infuratruffleweb3js

I have a Truffle/Web3 app which has this code in app.js (by default) which runs when the page is loaded:

$(document).ready(function () {
  if (typeof web3 !== 'undefined') {
    console.warn('Using web3 detected from external source like Metamask')
    window.web3 = new Web3(web3.currentProvider)
  } else {
    console.warn("No web3 detected. Falling back to http://localhost:8545. You should remove this fallback when you deploy live, as it's inherently insecure. Consider switching to Metamask for development. More info here: http://truffleframework.com/tutorials/truffle-and-metamask")
    window.web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'))
  }

My truffle.js file looks like this:

require('babel-register')

module.exports = {
  networks: {
    "ropsten": {
      host: 'localhost',
      port: 8545,
      network_id: 3, // Ropsten
      gas: 500000
    }
  }
}

I have also signed up to Infura which has given me a "provider URL" like https://ropsten.infura.io/xxxxxxxxxxxxxxxxxxxxx

How should I then properly configure my truffle.js and app.js so I am using Infura? I would like to use Infura for the purpose of showing users who aren't using MetaMask/Parity/Mist data from the blockchain (so the app could still call functions from my contract), while Infura should be ignored if it's detected that the user is using MetaMask/Parity/Mist.

Best Answer

Here's a example of setting an infura provider using truffle-hdwallet-provider with a custom wallet:

const HDWalletProvider = require('truffle-hdwallet-provider')
const fs = require('fs')

const mnemonic = process.env.MNEMONIC

module.exports = {
  networks: {
    development: {
      host: 'localhost',
      port: 8545,
      gas: 4500000,
      gasPrice: 25000000000,
      network_id: '*' 
    },
    kovan: {
      provider: new HDWalletProvider(mnemonic, 'https://kovan.infura.io'),
      network_id: '*',
      gas: 4500000,
      gasPrice: 25000000000
    },
    rinkeby: {
      provider: new HDWalletProvider(mnemonic, 'https://rinkeby.infura.io'),
      network_id: '*',
      gas: 4500000,
      gasPrice: 25000000000
    },
    mainnet: {
      provider: new HDWalletProvider(mnemonic, 'https://mainnet.infura.io'),
      network_id: '*',
      gas: 4500000,
      gasPrice: 25000000000
    }
  }
}

Then just set the network option when deploying:

truffle migrate --reset --network=rinkeby

In the UI, here's how to set the Web3 HTTP provider to infura:

if (typeof web3 !== 'undefined') {
    window.web3 = new Web3(web3.currentProvider)
} else {
    window.web3 = new Web3(new Web3.providers.HttpProvider('https://rinkeby.infura.io:443'))
}
Related Topic