0xProject / 0x-monorepo

0x protocol monorepo - includes our smart contracts and many developer tools
Other
1.41k stars 466 forks source link

Unable to create order via infura #204

Closed nitika-goel closed 6 years ago

nitika-goel commented 6 years ago

Hi, moving from Issue #133 as I'm unable to reopen the same. I'm still unable to solve this. Intend to use infura as I cannot run a local geth node. Here is the code I am using:

const Web3 = require('web3');
const Accounts=require('web3-eth-accounts');
const HookedWeb3Provider=require("hooked-web3-provider");
const ZeroEx = require('0x.js').ZeroEx;
const BigNumber = require('bignumber.js');
const KOVAN_ENDPOINT='https://kovan.infura.io/';

(async () => {
    var web3=new Web3(new Web3.providers.HttpProvider(KOVAN_ENDPOINT));
    var accounts =new Accounts(KOVAN_ENDPOINT);
    // Creating a new Account
    var logAcc=web3.eth.accounts.privateKeyToAccount("528d53be9f33de80d68b148aac930b9ab757d798ef251bcbdcfd94b95961144a");
    console.log(logAcc);

   var zeroEx = new ZeroEx(web3.currentProvider);    // Number of decimals to use (for ETH and ZRX)
    const DECIMALS = 18;     // Addresses
    const NULL_ADDRESS = ZeroEx.NULL_ADDRESS;  
    console.log("Null address is "+NULL_ADDRESS);  // Ethereum Null address
    const WETH_ADDRESS = await zeroEx.etherToken.getContractAddressAsync();  
    console.log("ETH token address is "+ WETH_ADDRESS);    // The wrapped ETH token contract
    const ZRX_ADDRESS  = await zeroEx.exchange.getZRXTokenAddressAsync(); 
    console.log("ZeroEx Address is "+ ZRX_ADDRESS)  // The ZRX token contract
    const EXCHANGE_ADDRESS   = await zeroEx.exchange.getContractAddressAsync();  // The Exchange.sol address (0x exchange smart contract)
    console.log("Exchange address is "+ EXCHANGE_ADDRESS);
     var account =  await zeroEx.getAvailableAddressesAsync();
     console.log(account);
})().catch(console.log);

I have created an account with a private key and am able to sign the order hash with web3.eth.accounts.sign() but in that case my vrs signatures generated do not match.

I intend to use the standard ZeroEx functions but the function zeroEx.getAvailableAddressesAsync() returns null value even though my web3 object has accounts json associated with it.

Can you please provide a sample of using your standard method with infura ?

fabioberger commented 6 years ago

@nitika-goel, you cannot simply use new Web3.providers.HttpProvider(KOVAN_ENDPOINT) as your provider since the infura node does not have your Ethereum address on file. You need to use providerEngine to create a provider that forwards requests specific to your accounts to a signer you can use, and all other requests to the Infura node. An example of such a subprovider can be found here.

To get started though, I would use TestRPC since we have an article on how to get started with it.

nitika-goel commented 6 years ago

Thanks @fabioberger . I did try using the providerengine but somehow the code breaks whenever I access any of the ZeroEx methods.

I am successfully able to create an order and sign it through metamask but I do not intend to do it that way as I need the entire process to be automated without the signer popup. Also, I need to integrate with this with a project running on Kovan and hence do not intend to use testrpc.

Following is the code I am using. It breaks after printing the nulladdress. I might be missing something really small. Could you please help me with it.

const Web3 = require('web3');
const Accounts=require('web3-eth-accounts');
const ZeroEx = require('0x.js').ZeroEx;
const BigNumber = require('bignumber.js');
const lightwallet= require('eth-lightwallet');
const Transaction = require('ethereumjs-tx');
const ProviderEngine = require("web3-provider-engine");
const Web3Subprovider = require("web3-provider-engine/subproviders/web3.js");
const HookedWalletProvider = require('web3-provider-engine/subproviders/hooked-wallet.js');
const CacheSubprovider = require('web3-provider-engine/subproviders/cache.js');
const FixtureSubprovider = require('web3-provider-engine/subproviders/fixture.js');
const FilterSubprovider = require('web3-provider-engine/subproviders/filters.js');
const VmSubprovider = require('web3-provider-engine/subproviders/vm.js');
const HookedWalletSubprovider = require("hooked-web3-provider");
const NonceSubprovider = require('web3-provider-engine/subproviders/nonce-tracker.js');
const RpcSubprovider = require('web3-provider-engine/subproviders/rpc.js');
const injectMetrics = require('web3-provider-engine/test/util/inject-metrics');
const KOVAN_ENDPOINT='https://kovan.infura.io/';

(async () => {
    var engine=new ProviderEngine();
    var web3=new Web3(engine);
//    console.log(logAcc.address);
     engine.addProvider(new FixtureSubprovider({
                        web3_clientVersion: 'ProviderEngine/v0.0.0/javascript',
                        net_listening: true,
                        eth_hashrate: '0x00',
                        eth_mining: false,
                        eth_syncing: true
                    }));
      engine.addProvider(new CacheSubprovider());

                            // filters
                            engine.addProvider(new FilterSubprovider());

                            // pending nonce
                            engine.addProvider(new NonceSubprovider());

                            // vm
                            engine.addProvider(new VmSubprovider());

     var providerA = injectMetrics(new HookedWalletProvider({
        getAccounts: function(cb){
          cb(null, ["0x7f4d8f26d33FDF092f713979FEc2753F9f14C331"])
        },
        signTransaction: function(txParams, cb){
          var tx = new Transaction(txParams)
          tx.sign(privateKey)
          var rawTx = '0x'+tx.serialize().toString('hex')
          cb(null, rawTx)
        },
      }));
    engine.addProvider(providerA);

        engine.addProvider(new RpcSubprovider({
          rpcUrl: 'https://kovan.infura.io/',
        }))

        // log new blocks
        engine.on('block', function(block){
          console.log('================================')
          console.log('BLOCK CHANGED:', '#'+block.number.toString('hex'), '0x'+block.hash.toString('hex'))
          console.log('================================')
        })

        // network connectivity error
        engine.on('error', function(err){
          // report connectivity errors
          console.error(err.stack)
        })

        // start polling for blocks
        engine.start();

    var zeroEx = new ZeroEx(web3.currentProvider);
    // Number of decimals to use (for ETH and ZRX)
    const DECIMALS = 18; 
    // Addresses
    const NULL_ADDRESS = ZeroEx.NULL_ADDRESS;  
    console.log("Null address is "+NULL_ADDRESS); 

    const WETH_ADDRESS = await zeroEx.etherToken.getContractAddressAsync();  
    console.log("ETH token address is "+ WETH_ADDRESS);    // The wrapped ETH token contract
    const ZRX_ADDRESS  = await zeroEx.exchange.getZRXTokenAddressAsync(); 
    console.log("ZeroEx Address is "+ ZRX_ADDRESS)       // The ZRX token contract
    const EXCHANGE_ADDRESS   = await zeroEx.exchange.getContractAddressAsync();  // The Exchange.sol address (0x exchange smart contract)
    console.log("Exchange address is "+ EXCHANGE_ADDRESS);

 //    console.log("WEB get accounts " +web3.eth.getAccounts());
    // // list of accounts
     var account =  await zeroEx.getAvailableAddressesAsync();
     console.log(account);

})().catch(console.log);
LogvinovLeon commented 6 years ago

What's the error message?

nitika-goel commented 6 years ago

There is no error message. It just breaks the execution.

fabioberger commented 6 years ago

Breaks or hangs? If it is hanging, that is because of https://github.com/ethereum/web3.js/issues/844. The solution is to import 0x.js and anything else that has web3 as a dependency after importing all ProviderEngine packages.

haidoan commented 6 years ago

@nitika-goel I have successfully signed with web3-provider-engine and @0xproject/subproviders here is snippet code for kovan infura(with out meta mask) , hope it helps // import lib

var PrivateKeyWalletSubprovider = require('@0xproject/subproviders').PrivateKeyWalletSubprovider var ProviderEngine = require('web3-provider-engine') var RpcSubprovider = require('web3-provider-engine/subproviders/rpc.js') var Web3Wrapper = require('@0xproject/web3-wrapper').Web3Wrapper

// usage

engine = new ProviderEngine() engine.addProvider(new PrivateKeyWalletSubprovider(mainAccount.privateKey)) engine.addProvider(new RpcSubprovider({ rpcUrl: NET_WORK_INFURA })) engine.start() configs = { networkId: 42 } web3Wrapper = new Web3Wrapper(engine) zeroEx = new ZeroEx(engine, configs)

now sign as normal.