Solidity – Calling Contract Constructor with Arguments

contract-developmentgo-ethereumjavascriptsolidityweb3js

I want to call the constructor of my contract which accepts address as a parameter,

below is the contract code:

pragma solidity ^0.4.4;

    contract Relay {
        address public currentVersion;
        address public owner;

        function Relay(address initAddr){
            currentVersion = initAddr;
            owner = msg.sender;
        }

        function update(address newAddress){
            if(msg.sender != owner) throw;
            currentVersion = newAddress;
        }

        function(){
            if(!currentVersion.delegatecall(msg.data)) throw;
        }
    }

I am trying to call the constructor in this contract from JavaScript using web3.js

below is the code I am using for that

var myContract = new web3.eth.Relay("0x87d8cc2aa5230e5d2f1a54b84366ea433da4bafd",abi, contractAddress, {
    from: web3.eth.coinbase,gasPrice: 200000000 });

but it shows error that

Uncaught TypeError: web3.eth.Relay is not a constructor

If I follow the normal contract object creation method ie.

var contract = web3.eth.contract(abi).at(contractAddress);

it works fine but this one not able to accept any parameter,
Can any one suggest any method to do this.
I have already found some answers about this here and here also but not useful for me.

Best Answer

To create a contract passing parameters to its constructor you can do

helloContract = eth.contract(contractAbi);
hello = helloContract.new(param1, param2, {from:eth.accounts[0], data:contractCode, gas:3000000})

Here contractAbi and contractCode are the result from compiling your contract with solidity compiler.

But I'd suggest to use a framework like embark, truffle or populus. They make much easier to deploy and test contracts.

Related Topic