How to use the web3 function in web3

To help you get started, we’ve selected a few web3 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github glowkeeper / Provenator / app / utils / web3Handler.jsx View on Github external
let ethereum = window.ethereum
    this.web3 = window.web3


    if (ethereum) {
      this.web3 = new Web3(ethereum)
      try {
        //console.log('Ethereum')
        await ethereum.enable()
      } catch (error) {
        // User denied account access...
        console.log("Ethereum disabled")
      }
    } else if (this.web3) {
      //console.log('Legacy dapp browsers...')
      this.web3 = new Web3(web3.currentProvider);
    }
    // Non-dapp browsers...
    else {
        //console.log('Non-Ethereum browser detected. You should consider trying MetaMask!')
        let host = '127.0.0.1'
        let port = '8545'
        this.web3 = new Web3(new Web3.providers.HttpProvider('http://' + host + ':' + port))
    }

    setInterval(this._setAccount.bind(this), 3000)
  }
github kleros / tokens-on-trial / src / utils / tcr.js View on Github external
const archon = new Archon(HTTP_PROVIDER, 'https://ipfs.kleros.io')

  const httpProvider = new Web3.providers.HttpProvider(HTTP_PROVIDER)
  const websocketProvider = new Web3.providers.WebsocketProvider(WS_PROVIDER)
  websocketProvider.on('error', () => console.info('WS closed'))
  websocketProvider.on('end', () => console.info('WS closed'))

  let eventsWeb3 = new Web3(websocketProvider)
  let viewWeb3 = new Web3(httpProvider)

  let arbitrableTokenList
  let badgeContracts = {}
  let arbitrator
  let web3
  if (window.ethereum) {
    web3 = new Web3(window.ethereum)

    // If window.web3 is available, also use it for viewing and event subscription.
    viewWeb3 = web3
    eventsWeb3 = web3

    arbitrator = new web3.eth.Contract(Arbitrator.abi, ARBITRATOR_ADDRESS)

    arbitrableTokenList = new web3.eth.Contract(
      ArbitrableTokenList.abi,
      ARBITRABLE_TOKEN_LIST_ADDRESS
    )
    if (badgeTCRs[networkID])
      badgeContracts = badgeTCRs[networkID]
        .map(
          address =>
            new viewWeb3.eth.Contract(ArbitrableAddressList.abi, address)
github blockmason / lndr-mobile / packages / lndr / settlement / index.ts View on Github external
declare const Buffer

import { Platform } from 'react-native'
import { ERC20_Transaction } from 'lndr/erc-20'
import Tx from 'ethereumjs-tx'
import Web3 from 'web3'

export const web3 = new Web3(new Web3.providers.HttpProvider('https://mainnet.infura.io/EoLr1OVfUMDqq3N2KaKA'))
// export const web3 = Platform.OS === 'ios' ? new Web3(new Web3.providers.HttpProvider('http://localhost:8545')) : new Web3(new Web3.providers.HttpProvider('http://10.0.2.2:8545'))

//post to infura using web3js
export const settleWithEth = async (transaction: ERC20_Transaction, privateKey: any) => {

  const privateKeyBuffer = new Buffer(privateKey.privateKey, 'hex')
  const nonce = await web3AsyncWrapper(web3.eth.getTransactionCount(`0x${transaction.to}`))

  const rawTx = {
    nonce: '0x' + nonce,
    gasPrice: '0x' + transaction.gasPrice,
    gasLimit: '0x' + transaction.gas,
    to: '0x' + transaction.to,
    value: '0x1000'
  }
github ethereum / remix / remix-tests / src / testRunner.ts View on Github external
export function runTest(testName, testObject: any, contractDetails: any, opts: any, testCallback: TestCbInterface, resultsCallback: ResultCbInterface) {
    let runList = createRunList(testObject._jsonInterface)

    let passingNum: number = 0
    let failureNum: number = 0
    let timePassed: number = 0
    let web3 = new Web3()

    var userAgent = (typeof (navigator) !== 'undefined') && navigator.userAgent ? navigator.userAgent.toLowerCase() : '-'
    var isBrowser = !(typeof (window) === 'undefined' || userAgent.indexOf(' electron/') > -1)
    if (!isBrowser) {
        let signale = require('signale')
        signale.warn('DO NOT TRY TO ACCESS (IN YOUR SOLIDITY TEST) AN ACCOUNT GREATER THAN THE LENGTH OF THE FOLLOWING ARRAY (' + opts.accounts.length + ') :')
        signale.warn(opts.accounts)
        signale.warn('e.g: the following code won\'t work in the current context:')
        signale.warn('TestsAccounts.getAccount(' + opts.accounts.length + ')')
    }
    const resp: TestResultInterface = {
      type: 'contract',
      value: testName,
      filename: testObject.filename
    }
    testCallback(undefined, resp)
github MyEtherWallet / MyEtherWallet / tests / unit / specs / src / layouts / InterfaceLayout / components / GenerateInfo / GenerateInfo.spec.js View on Github external
beforeEach(() => {
    const network = nodeList['ETH'][ETH_NETWORK_INDEX];
    const hostUrl = url.parse(network.url);
    const newWeb3 = new Web3(
      `${hostUrl.protocol}//${hostUrl.hostname}:${network.port}${
        hostUrl.pathname
      }`
    );

    const wallet = {
      getChecksumAddressString: jest.fn(() => 0),
      getAddressString: function() {
        return '0xDECAF9CD2367cdbb726E904cD6397eDFcAe6068D';
      }
    };

    const getters = {
      wallet: () => {
        return wallet;
      },
github XYOracleNetwork / tool-dapper-react / src / util / web3.js View on Github external
const portisNetwork = Cookies.get(`portisNetwork`)
      const portisAPI = `3b1ca5fed7f439bf72771e64e9442d74`
      console.log(`Creating Portis Privider`, portisNetwork)
      const portisArgs =
        portisNetwork === `development`
          ? {
              apiKey: portisAPI,
              network: portisNetwork,
              providerNodeUrl: localProviderUrl,
            }
          : {
              apiKey: portisAPI,
              network: portisNetwork,
            }
      console.log(`Setting up Portis`)
      const web3js = new Web3(new PortisProvider(portisArgs))
      setWeb3js(web3js)
    }
  }
github celo-org / celo-monorepo / packages / faucet / scripts / transfer-funds.ts View on Github external
async function transferFunds(args: {
  nodeUrl: string
  stableTokenAddress: string
  goldTokenAddress: string
  pk: string
  recipientAddress: string
  dryrun?: boolean
  gold?: string
  dollar?: string
}) {
  const web3 = await new Web3(args.nodeUrl)
  const pk = args.pk
  const to = args.recipientAddress
  const celo = new CeloAdapter(web3, pk, args.stableTokenAddress, args.goldTokenAddress, '')

  const printBalance = async (addr: string) => {
    console.log(`Account: ${addr}`)
    console.log(`USD: ${await celo.getDollarsBalance(addr)}`)
    console.log(`Gold: ${await celo.getGoldBalance(addr)}`)
    console.log('-------------------------------------------')
  }

  console.log('Funder')
  await printBalance(celo.defaultAddress)
  console.log('Recipient')
  await printBalance(to)
github embark-framework / embark / packages / stack / contracts-manager / src / index.js View on Github external
return (async () => {
      if (!this._web3) {
        const provider = await this.events.request2("blockchain:client:provider", "ethereum");
        this._web3 = new Web3(provider);
      }
      return this._web3;
    })();
  }
github status-im / hackathon / submissions / dts / src / providers / ethereum.ts View on Github external
constructor(private logger: Logger) {

        if (typeof web3 !== 'undefined') {
            this.provider = web3.currentProvider;
        } else {
            this.provider = new Web3.providers.HttpProvider(environment.rpcurl);
        }
        
        this.web3 = new Web3(this.provider); //new Web3(provider) 
    }
github kleros / doges-on-trial / src / bootstrap / dapp-api.js View on Github external
import Arbitrator from '../assets/contracts/arbitrator.json'

const env = process.env.NODE_ENV === 'production' ? 'PROD' : 'DEV'
const ETHEREUM_PROVIDER = process.env[`REACT_APP_${env}_ETHEREUM_PROVIDER`]
const ARBITRABLE_PERMISSION_LIST_ADDRESS =
  process.env[`REACT_APP_${env}_ARBITRABLE_PERMISSION_LIST_ADDRESS`]
const IMAGES_BASE_URL = process.env[`REACT_APP_${env}_IMAGES_BASE_URL`]
const IMAGE_UPLOAD_URL = process.env[`REACT_APP_${env}_IMAGE_UPLOAD_URL`]
const PATCH_USER_SETTINGS_URL =
  process.env[`REACT_APP_${env}_PATCH_USER_SETTINGS_URL`]

let web3
const infuraWeb3 = new Web3(new Web3.providers.HttpProvider(ETHEREUM_PROVIDER))
let onlyInfura = false
if (process.env.NODE_ENV === 'test')
  web3 = new Web3(require('ganache-cli').provider())
else if (window.ethereum) web3 = new Web3(window.ethereum)
else if (window.web3 && window.web3.currentProvider)
  web3 = new Web3(window.web3.currentProvider)
else {
  web3 = new Web3(new Web3.providers.HttpProvider(ETHEREUM_PROVIDER))
  onlyInfura = true
}

const network =
  web3.eth &&
  web3.eth.net
    .getId()
    .then(networkID => {
      switch (networkID) {
        case 1:
          return 'main'