Проблема с web3js и testrpc

введите описание изображения здесь

И у меня проблема с web3js на testrpc, я не могу создать и установить экземпляр web3. Терминал сказал, что web3 не определен. (ошибка ссылки) Также, когда я пытаюсь выполнить методы в своем контракте, например

var e = Mycontract.deployed();

У меня также есть undefined , и когда я пытаюсь

console.log(e.address);

я установил web3js

  • узел js-версия 6~
  • нпм версия 3~
  • также плохо установлены пудинг, трюфель

Мне нужно установить что-то еще? или переустановить?

truffle(development)> Art.at(Art.address) TruffleContract {  
constructor:     { [Function: TruffleContract]
     _static_methods: 
      { setProvider: [Function: setProvider],
        new: [Function: new],
        at: [Function: at],
        deployed: [Function: deployed],
        defaults: [Function: defaults],
        hasNetwork: [Function: hasNetwork],
        isDeployed: [Function: isDeployed],
        detectNetwork: [Function: detectNetwork],
        setNetwork: [Function: setNetwork],
        resetAddress: [Function: resetAddress],
        link: [Function: link],
        clone: [Function: clone],
        addProp: [Function: addProp],
        toJSON: [Function: toJSON] },
     _properties: 
      { contract_name: [Object],
        abi: [Object],
        network: [Function: network],
        networks: [Function: networks],
        address: [Object],
        links: [Function: links],
        events: [Function: events],
        binary: [Function: binary],
        unlinked_binary: [Object],
        schema_version: [Function: schema_version],
        updated_at: [Function: updated_at] },
     _property_values: {},
     _json: 
      { contract_name: 'Art',
        default_network: undefined,
        abi: [Object],
        unlinked_binary: '0x606060405234610000575b6101d9806100196000396000f300606060405263ffffffff60e060020a6000350416637183616c811461003a57806376dbd1081461008f578063faf924cf146100f4575b610000565b346100005761008d600480803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284375094965061011395505050505050565b005b34610000576100e2600480803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284375094965061012395505050505050565b60408051918252519081900360200190f35b34610000576100e26101a7565b60408051918252519081900360200190f35b61011c81610123565b6000555b50565b60006002826000604051602001526040518082805190602001908083835b602083106101605780518252601f199092019160209182019101610141565b51815160209384036101000a600019018019909216911617905260405191909301945091925050808303816000866161da5a03f1156100005750506040515190505b919050565b600054815600a165627a7a723058205af3325408f62f5b64135ac0e2eac3d1632e79f925249e4ce52266a8f02becdc0029',
        networks: [Object],
        schema_version: '0.0.5',
        updated_at: 1490993477853 },
     setProvider: [Function: bound setProvider],
     new: [Function: bound new],
     at: [Function: bound at],
     deployed: [Function: bound deployed],
     defaults: [Function: bound defaults],
     hasNetwork: [Function: bound hasNetwork],
     isDeployed: [Function: bound isDeployed],
     detectNetwork: [Function: bound detectNetwork],
     setNetwork: [Function: bound setNetwork],
     resetAddress: [Function: bound resetAddress],
     link: [Function: bound link],
     clone: [Function: bound clone],
     addProp: [Function: bound addProp],
     toJSON: [Function: bound toJSON],
     web3: 
      Web3 {
        _requestManager: [Object],
        currentProvider: [Object],
        eth: [Object],
        db: [Object],
        shh: [Object],
        net: [Object],
        personal: [Object],
        bzz: [Object],
        settings: [Object],
        version: [Object],
        providers: [Object],
        _extend: [Object] },
     class_defaults: 
      { from: '0x32f2e046d626c285bf6e60002dd4761209a5d8d2',
        gas: 4712388,
        gasPrice: 100000000000 },
     currentProvider: HttpProvider { host: 'http://localhost:8545', timeout: 0 },
     network_id: '1490993444046' },   abi:     [ { constant: false,
       inputs: [Object],
       name: 'notarize',
       outputs: [],
       payable: false,
       type: 'function' },
     { constant: true,
       inputs: [Object],
       name: 'calculateProof',
       outputs: [Object],
       payable: false,
       type: 'function' },
     { constant: true,
       inputs: [],
       name: 'proof',
       outputs: [Object],
       payable: false,
       type: 'function' } ],   contract:     Contract {
     _eth: 
      Eth {
        _requestManager: [Object],
        getBalance: [Object],
        getStorageAt: [Object],
        getCode: [Object],
        getBlock: [Object],
        getUncle: [Object],
        getCompilers: [Object],
        getBlockTransactionCount: [Object],
        getBlockUncleCount: [Object],
        getTransaction: [Object],
        getTransactionFromBlock: [Object],
        getTransactionReceipt: [Object],
        getTransactionCount: [Object],
        call: [Object],
        estimateGas: [Object],
        sendRawTransaction: [Object],
        sendTransaction: [Object],
        sign: [Object],
        compile: [Object],
        submitWork: [Object],
        getWork: [Object],
        coinbase: [Getter],
        getCoinbase: [Object],
        mining: [Getter],
        getMining: [Object],
        hashrate: [Getter],
        getHashrate: [Object],
        syncing: [Getter],
        getSyncing: [Object],
        gasPrice: [Getter],
        getGasPrice: [Object],
        accounts: [Getter],
        getAccounts: [Object],
        blockNumber: [Getter],
        getBlockNumber: [Object],
        protocolVersion: [Getter],
        getProtocolVersion: [Object],
        iban: [Object],
        sendIBANTransaction: [Function: bound transfer] },
     transactionHash: null,
     address: '0x732e24b2de90ec2e009748a6bf2d379ed1eee072',
     abi: [ [Object], [Object], [Object] ],
     notarize: 
      { [Function: bound ]
        request: [Function: bound ],
        call: [Function: bound ],
        sendTransaction: [Function: bound ],
        estimateGas: [Function: bound ],
        getData: [Function: bound ],
        string: [Circular] },
     calculateProof: 
      { [Function: bound ]
        request: [Function: bound ],
        call: [Function: bound ],
        sendTransaction: [Function: bound ],
        estimateGas: [Function: bound ],
        getData: [Function: bound ],
        string: [Circular] },
     proof: 
      { [Function: bound ]
        request: [Function: bound ],
        call: [Function: bound ],
        sendTransaction: [Function: bound ],
        estimateGas: [Function: bound ],
        getData: [Function: bound ],
        '': [Circular] },
     allEvents: [Function: bound ] },   notarize:     { [Function]
     call: [Function],
     sendTransaction: [Function],
     request: [Function: bound ],
     estimateGas: [Function] },   calculateProof:     { [Function]
     call: [Function],
     sendTransaction: [Function],
     request: [Function: bound ],
     estimateGas: [Function] },   proof:     { [Function]
     call: [Function],
     sendTransaction: [Function],
     request: [Function: bound ],
     estimateGas: [Function] },   sendTransaction: [Function],   send: [Function],   allEvents: [Function: bound ],   address:
'0x732e24b2de90ec2e009748a6bf2d379ed1eee072',   transactionHash: null
} 
truffle(development)>  
(To exit, press ^C again or type .exit)
truffle(development)> var e=Art.deployed 
undefined
truffle(development)> console.log(e.address) 
undefined 
undefined'

Ответы (3)

Вам нужно либо настроить web3 вручную, либо использовать фреймворк, который это делает.

Вот код, чтобы сделать это вручную, с прослушиванием testrpc localhost:8545(по умолчанию)

var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));
web3.isConnected() // should return true if it all worked.

Обратите внимание, что web3 должен быть установлен локально (т.е. в вашем проекте node_modules). Это укусило меня, когда я учился это делать.

спс за ответ. Я установил web3 в свой ptoject (это моя ошибка :), затем вставьте ваш код в Node (я новичок в JS, и также вставьте его в консоль трюфеля). Но также не могу вызывать функции в моем контракте. (Добавлено фото) Пожалуйста, помогите :(
Вы запускали truffle init ? Судя по этому снимку экрана, это не похоже на каталог проекта, который создаст трюфель.
да. а также выполните npm init для локальной установки web3

Вот как это работает для скомпилированного контракта с web3:

var source = 'contract demo {string public name = "Petros"; function changeName(string _newName){name = _newName; } }'; 
var compiled = web3.eth.compile.solidity(source);
var abi = compiled['<stdin>:demo'].info.abiDefinition;

Надеюсь, это поможет вам.

Сначала вы можете проверить, какую версию трюфеля вы используете, набрав:

$ truffer --version

truffle ведет себя по-разному в v2.x и v3.x, в v3.x он не разрешает обещание deployed()автоматически, поэтому, если вы хотите зарегистрировать экземпляр контракта, вы можете сделать:

> var poe = Art.at(Art.address)
> assert.ok(poe.address)      // "address" should be defined
> poe.notarize('Hello World') // try to call the contract function

Во-вторых, убедитесь, что имя контракта совпадает с именем файла исходного кода.

Надеюсь это поможет.

иметь версию 3x и обновить вопрос с вашим ответом. также ундиф;(
@Vladimir Владимир, я обновил код для запуска в консоли трюфелей, взгляните.