Как получить доступ к контракту по его адресу (в Mix)

Стройный

Как получить доступ к контракту по его адресу (в Mix)

Я пытаюсь использовать Mix для тестирования нескольких экземпляров одного и того же контракта, поэтому я пытаюсь выбрать контракт по адресу, но пока безуспешно. Это ограничение в Mix или мое непонимание?

Я пытался использовать API web3.js, например, как описано в методах контракта , но получаю только ошибку.

Вот фрагмент кода, который вызывает ошибку...

    var contractAddress = "0xc069cb45291acafdd701e9341e7bf730255abbe1";
var abi = '[{\"constant\":false,\"inputs\":[],\"name\":\"kill\",\"outputs\":[],\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_greeting\",\"type\":\"string\"}],\"name\":\"setgreeting\",\"outputs\":[],\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"greet\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"owned\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"type\":\"function\"},{\"inputs\":[{\"name\":\"_greeting\",\"type\":\"string\"}],\"type\":\"constructor\"}]';
var queryContract = web3.eth.contract(abi);

/*
The next line throws "web3.js - line 2838 - Uncaught TypeError: undefined is not a function"
*/
var LocalContract = queryContract.at(contractAddress);

Это связано с миксом? Я считаю, что с ABI все в порядке.

Вот полная информация. Я позаимствовал контракт приветствия, чтобы исправить свою ошибку. Контракт..

contract mortal {
    /* Define variable owner of the type address*/
    address owner;

    /* this function is executed at initialization and sets the owner of the contract */
    function mortal() { owner = msg.sender; }

    /* Function to recover the funds on the contract */
    function kill() { if (msg.sender == owner) suicide(owner); }
}

contract greeter is mortal {
    /* define variable greeting of the type string */
    string greeting;

    /* this runs when the contract is executed */
    function greeter(string _greeting) public {
        greeting = _greeting;
    }

    /* main function */
    function greet() constant returns (string) {
        return greeting;
    }
    /* set function */
    function setgreeting(string _greeting)  {
        greeting = _greeting;
    }
    /* other function */
    function owned() constant returns (address) {
        return owner;
    }
}

А теперь код...

    <html>
  <head>
    <title>Multiple Contract Test</title>
<script type='text/javascript'>

/*
 Test Set Functions
 */

function getGreetingB() {
    var contractAddress = "0xc069cb45291acafdd701e9341e7bf730255abbe1";
    var abi = '[{\"constant\":false,\"inputs\":[],\"name\":\"kill\",\"outputs\":[],\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_greeting\",\"type\":\"string\"}],\"name\":\"setgreeting\",\"outputs\":[],\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"greet\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"owned\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"type\":\"function\"},{\"inputs\":[{\"name\":\"_greeting\",\"type\":\"string\"}],\"type\":\"constructor\"}]';
    var queryContract = web3.eth.contract(abi);

    /*
    feeble attempts at querying the contract object
    */
    console.log("Logging start");
    //console.log(Object.keys(queryContract));
    console.log(Object.getOwnPropertyNames(queryContract));   // Yields "eth,abi,new"   and NOT "at"
    console.log(Object.getOwnPropertyNames(queryContract.eth));
    console.log("Logging End");

    /*
      Some access from the contract that does work.
      */
    document.getElementById('QueryContractABIReturned').innerText = queryContract.abi;

    /*
    Now lets try to specify exactly which contract to reference.

    The next line throws "web3.js - line 2838 - Uncaught TypeError: undefined is not a function"
    */

    var LocalContract = queryContract.at(contractAddress);




    document.getElementById('QueryContractAddressB').innerText = LocalContract.address;
    document.getElementById('QueryGreetingB').innerText = LocalContract.contract.greet();
    document.getElementById('QueryOwnerB').innerText = LocalContract.contract.owned();

}

function setGreetingB() {
/*
 nothing yet
 */
}


</script>
  </head>
  <body>
    <h3>Duplicate Contract Access Test B</h3>

<div>
    <input value='Fetch Greeting' type='button' onclick='getGreetingB()' />
<table>
    <tr><td>ABI:</td><td><div id='QueryContractABIReturned'></div></td></tr>
    <tr><td>Greeting:</td><td><div id='QueryGreetingB'></div></td></tr>
    <tr><td>Owner Address:</td><td><div id='QueryOwnerB'></div></td></tr>
    <tr><td>Contract Address:</td><td><div id='QueryContractAddressB'></div></td></tr>
</table>
</div>  
<hr>
    <div>
        New Greeting: <input type="string" id="newgreetingB">
        <button onclick="setGreetingB()">Save</button>
    </div>
    </body>
</html>

ародригесдонайр

Чтобы получить экземпляр контракта по его адресу, вы можете сделать:

ПРОЧНОСТЬ

ContractClass contractInstance = ContractClass(contractAddress);

В JS С WEB3

var Web3 = require('web3');
var web3 = new Web3();
var contractClass = web3.eth.contract(contractClassAbi);
var contractInstance = contractClass.at(contractAddress);

В ТВОЕМ СЛУЧАЕ

Вы должны правильно установить и инициализировать web3.js, ошибка исходит от объекта web3, а не от функций, которые вы использовали.

Стройный

Спасибо, я так и подозревал. Но когда я добавляю этот фрагмент кода, я получаю сообщение об ошибке «Uncaught ReferenceError: требование не определено».

Стройный

С ошибкой «Uncaught ReferenceError: требование не определено» он не пройдет дальше первой базы. «требовать» — это функция node.js, не так ли? Я в тупике, как на него ссылаться. Если это работает в Mix в index.html, мне нужно что-то вроде браузера? работает Ubuntu 15.10 в виртуальной машине VirtualBox. Я установил двоичные файлы Эфириума (включая смесь) в соответствии с ethdocs.org/en/latest/ethereum-clients/cpp-ethereum/… Затем я установил node.js, npm, ethereum-console, web3.