Truffle call Nodejs problem

Source: Internet
Author: User

Truffle3.0 Integrated Nodejs and complete run-through (with detailed examples, possible errors)
Upgrade to Truffle3.0
If you previously installed the Truffle2.0 version, you need to actively upgrade to Truffle3.0, the syntax of the two is a bit large.

Because Truffle is a command-line tool, you need to update the truffle for global space installations.

$ sudo npm update-g truffle
Note that you need root privileges to run the command, or you may get an error without sufficient access, causing the upgrade to fail.

After the installation is successful, you can view the current version through the version command, as shown in the following typeface to illustrate the success of the upgrade:

$ truffle version
Truffle v3.1.2
Initialize Project
Initializing a project with Truffle3.0
We create a new project directory and initialize the truffle framework within the TRUFFLE3 directory.

$ mkdir truffle3 && CD Truffle3
$ truffle Init
Downloading project ...
Project initialized.

Documentation:http://truffleframework.com/docs

Commands:

Compile:truffle Compile

Migrate:truffle Migrate
Test:truffle Test
We created a new project catalog Truffle3, entered this directory, using the Truffle init command, initialized a new Truffle 3.0 project, the project directory is as follows:

Truffle3-project

Integrated Nodejs
The Truffle console command integrates WEB3, the contract abstraction layer by default. If you want to use the truffle contract in your own NODEJS environment, you need to manually integrate the two modules. Before integration, we need to create a project NPM package management environment, first into the TRUFFLE3 engineering catalog, using NPM init to initialize the project's NPM package management environment:

$ NPM Init
This utility would walk you through creating a Package.json file.
It is covers the most common items, and tries to guess sensible defaults.

See for npm help json definitive documentation in these fields
And exactly what they do.

Use npm install <pkg> --save afterwards to install a package and
Save it as a dependency in the Package.json file.

Press ^c at no time to quit.
Name: (truffle3) trufflefortest
Sorry, name can no longer contain capital letters.
Name: (truffle3) Truffle3
Version: (1.0.0) 1.0.0
Description:this is a sample project for integrate truffle 3.0 with Nodejs.
Entry point: (Truffle.js) main.js
Test Command:truffle3
Git repository:main.js
keywords:truffle3.0
Author:tryblockchain
License: (ISC)
About to write To/users/tryblockchain/develop/blockchain_workspace/truffle3/package.json:

{
"Name": "Truffle3",
"Version": "1.0.0",
"description": "This was a sample project for integrate truffle 3.0 with Nodejs."

"Main": "Main.js",
"Directories": {
"Test": "Test"
},
"Scripts": {
"Test": "Truffle3"
},
"keywords": [
"Truffle3.0"
],
"Author": "Tryblockchain",
"License": "ISC"
}

Is this OK? (yes) Yes
If you do not perform NPM init initialization, the subsequent module installation will report the following error:

$ NPM Install Truffle-contract
/users/tryblockchain
└─┬[email protected]
├─┬[email protected]
│├──[email protected]
│├──[email protected]
│└─┬[email protected]
│├──[email protected] Deduped
│└─┬[email protected]
│└──[email protected]

├──[email protected]
├─┬[email protected]
│└──[email protected]
└─┬[email protected]
└──[email protected] (GIT+HTTPS://GITHUB.COM/DEBRIS/BIGNUMBER.JS.GIT#94D7146671B9719E00A09C29B01A691BC85048C2)

NPM WARN enoent enoent:no such file or directory, open '/users/tryblockchain/package.json '
NPM WARN tryblockchain No Description
NPM WARN tryblockchain No repository field.
NPM WARN tryblockchain No README data
NPM WARN tryblockchain No license field.
Packet-dependent writes to Package.json fail because there is no package management environment. Error NPM WARN enoent enoent:no such file or directory, open '/users/tryblockchain/package.json '. To solve this problem, you need to use NPM init to initialize the current project's package management environment.

Truffle Contract Abstraction Layer operating environment for installation of Nodejs
This tool is provided by truffle, which is used to integrate truffle in Nodejs and browser in a contract abstraction run environment 1.

$ NPM Install Truffle-contract
[Email protected]/users/tryblockchain/develop/blockchain_workspace/truffle3
└─┬[email protected]
├─┬[email protected]
│├──[email protected]
│├──[email protected]
│└─┬[email protected]
│├──[email protected] Deduped
│└─┬[email protected]

│└──[email protected]
├─┬[email protected]
│└─┬[email protected]
│├──[email  Protected] (GIT+HTTPS://GITHUB.COM/DEBRIS/BIGNUMBER.JS.GIT#94D7146671B9719E00A09C29B01A691BC85048C2)
│├──[ Email protected] deduped
│├──[email protected] deduped
│├──[email protected]
│└──[email& Nbsp;protected] deduped
├─┬[email protected]
│└──[email protected]
└─┬[email protected]
├──[email protected] (git+https://github.com/debris/bignumber.js.git# 94D7146671B9719E00A09C29B01A691BC85048C2)
├──[email protected]
├──[email protected]
└──[ Email protected]
Install WEB3 environment required for truffle runtime in Nodejs
$ npm Install web3

    • [Email protected] Node_modules/web3/node_modules/bignumber.js
      [Email protected]/users/tryblockchain/develop/blockchain_workspace/truffle3
      └──[email protected]
      We can install the WEB3 module using NPM install WEB3. If you do not have an integrated WEB3 environment, run the relevant code and may report the following error:

$ node Main.js
/users/tryblockchain/develop/blockchain_workspace/truffle3/main/main.js:4
var Provider = new Web3.providers.HttpProvider ("http://localhost:8545");
^

REFERENCEERROR:WEB3 is not defined
At Object.

pragma solidity ^0.4.4;

Contract test{
function f () returns (string) {
Return "Method F ()";
}
function g () returns (string) {
Return "Method G ()";
}
}

In the above code, we provide two functions, f () and g (). Returns a string description that describes the return result of which function they are.

Add Deploy Configuration
Modify the Migrations/2_deploy_contracts.js as follows:

var convertlib = Artifacts.require ("./convertlib.sol");
var metacoin = Artifacts.require ("./metacoin.sol");
var Test = Artifacts.require ("./test.sol");

Module.exports = function (deployer) {
Deployer.deploy (Convertlib);
Deployer.link (Convertlib, Metacoin);
Deployer.deploy (Metacoin);
Deployer.deploy (Test);
};
The above code mainly adds two lines, a behavior of var Test = Artifacts.require ("./test.sol"); declares a new instance of the contract file and names it as test; add another line of content deployer.deploy (test); Used to deploy the test.

Build contract
Below we use truffle migrate--reset to force recompile and publish all contracts, because the contract porting is lazy compiled, if the discovery has been published, and the release number of the publication will not be published, so use--reset. Be sure to figure out why you use--reset to use this command 2. Before running truffle migrate, you need to confirm that the node is running.

$ Truffle Migrate--reset
Using network ' development '.

Running Migration:1_initial_migration.js

Replacing migrations ...
Migrations:0xdc59c5de4e7b1dcf23f864425a704020e53666b5
Saving successful migration to network ...
Saving artifacts ...
Running Migration:2_deploy_contracts.js
Replacing Convertlib ...
Convertlib:0x19cf958fede2e0f082cbcf5629f1a1344b221bf3
Linking Convertlib to Metacoin
Replacing Metacoin ...
Metacoin:0x39073d502491f57537f999584071691d19cf5f24
Replacing Test ...
Test:0x8ca770415902e5a64ef53062b5ba85626c3dd5dc
Saving successful migration to network ...
Saving artifacts ...
Integrated Truffle3.0 code with NODEJS full demo
var Web3 = require (' web3 ');
var contract = require ("Truffle-contract");

var Provider = new Web3.providers.HttpProvider ("http://localhost:8545");

Using the contract () method of the Truffle-contract package
Be sure to use your own compiled. json file contents
var Test = contract ({
"Contract_name": "Test",
"Abi": [
{
"Constant": false,
"Inputs": [],
"Name": "F",
"Outputs": [
{
"Name": "",
' Type ': ' String '
}
],
"Payable": false,
' type ': ' function '
},
{
"Constant": false,
"Inputs": [],
"Name": "G",
"Outputs": [
{
"Name": "",
' Type ': ' String '
}
],
"Payable": false,
' type ': ' function '
}
],
"Unlinked_binary": " 0x606060405234610000575b6101ff806100196000396000f300606060405263ffffffff60e060020a60003504166326121ff0811461002f578063e21 79b8e146100bc575b610000565b346100005761003c610149565b60408051602080825283518183015283519192839290830191850190808383821561 0082575b80518252602083111561008257601f199092019160209182019101610062565b505050905090810190601f1680156100ae578082038051600 1836020036101000a031916815260200191505b509250505060405180910390f35b346100005761003c61018e565b6040805160208082528351818301 52835191928392908301918501908083838215610082575b80518252602083111561008257601f199092019160209182019101610062565b505050905 090810190601f1680156100ae5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b60408051602081 8101835260009091528151808301909252600a82527f6d6574686f642066282900000000000000000000000000000000000000000000908201525b905 65b604080516020818101835260009091528151808301909252600a82527f6d6574686f64206728290000000000000000000000000000000000000000 0000908201525b905600a165627a7a72305820c238bd4de6aa330fcc88946b9948bc265c7ac1408dc5c8b7ee6e648413ae540f0029 ",
"Networks": {
"1489826524891": {
"Events": {},
"Links": {},
"Address": "0x9db90af99faa32ed14dccfb19326e917efac456b",
"Updated_at": 1489827968151
}
},
"Schema_version": "0.0.5",
"Updated_at": 1489827968151
});

Test.setprovider (provider);

No default address, will error
Unhandledpromiserejectionwarning:unhandled promise rejection (rejection Id:3): Error:invalid address
Be sure to set the address for your own wallet, if you do not know, to view your own client startup, to observe the addresses printed to the console
Test.defaults ({
From: "0X299127D72E28CB92D09F856AAEDEB139D1E7E74A"
});

var instance;
Test.deployed (). Then (function (contractinstance) {
instance = Contractinstance;
return Instance.f.call ();
}). Then (function (Result) {
Console.log (result);
return Instance.g.call ();
}). Then (function (Result) {
Console.log (result);
});

Integration examples in a detailed
Introduction of WEB3
To use truffle in Nodejs, we first introduce web3.

var Web3 = require (' web3 ');
var Provider = new Web3.providers.HttpProvider ("http://localhost:8545");

Omitted extraneous code
Contract initialization
var Test = contract (/ contract JSON/);

Setting Up Connections
Test.setprovider (provider);
In the example above, we first pass var Web3 = require (' web3 '), introduce dependencies, initialize an instance Web3, and set Httpprovider for the instance.

Truffle-contract's contract () method
To initialize the truffle compiled contract in Nodejs, use the contract () method. Please Truffle3.0 compiled. json file, generally in Build/contracts/test.json. Please enclose the contents of this file in parentheses in contract ().

var contract = require ("Truffle-contract");

Please use the contents of the. json file compiled with Truffle3.0
var Test = contract (/ parameter is an JSON object, put in Truffle3.0 generated. json file contents /)
Then use. deployed () or at (/ an address /) to make a call to 1.

Contract () A problem with the JSON definition introduced
If there is a problem with the imported JSON data, you may see the following error:

$ node Main.js
/users/tryblockchain/develop/blockchain_workspace/truffle3/node_modules/truffle-contract/node_modules/web3/lib /web3/contract.js:56
Contract.abi.filter (function (JSON) {

            ^

Typeerror:cannot Read Property ' filter ' of undefined
At Addfunctionstocontract (/users/tryblockchain/develop/blockchain_workspace/truffle3/node_modules/ Truffle-contract/node_modules/web3/li
B/WEB3/CONTRACT.JS:56:17)
At contractfactory.at (/users/tryblockchain/develop/blockchain_workspace/truffle3/node_modules/truffle-contract/ Node_modules/web3/lib/we
B3/contract.js:255:5)
At Trufflecontract.contract (/users/tryblockchain/develop/blockchain_workspace/truffle3/node_modules/ Truffle-contract/contract.js:257:33
)
At New Trufflecontract (/users/tryblockchain/develop/blockchain_workspace/truffle3/node_modules/truffle-contract/ CONTRACT.JS:572:25)
At function.at (/users/tryblockchain/develop/blockchain_workspace/truffle3/node_modules/truffle-contract/ CONTRACT.JS:390:22)
At Object.

Default Account Address
The Truffle-contract framework does not read the default address of Coinbase by default, so it needs to be set as follows:

No default address, will error
Unhandledpromiserejectionwarning:unhandled promise rejection (rejection Id:3): Error:invalid address
Test.defaults ({
From: "0X299127D72E28CB92D09F856AAEDEB139D1E7E74A"
});
Otherwise it will be error unhandledpromiserejectionwarning:unhandled promise rejection (rejection Id:3): Error:invalid address3.

Grammar note
For the new Truffle3.0 syntax, it is important to note that the function is called in a way that follows call Rule 4. For an F () function that does not overwrite the state of the blockchain, use Instance.f.call (); and for a function f () that overwrites the state of the blockchain, use INSTANCE.F (). At the bottom of the implementation call, different gas calculation methods are used.

var instance;
Test.deployed (). Then (function (contractinstance) {
instance = Contractinstance;
return Instance.f.call ();
}). Then (function (Result) {
Console.log (result);
return Instance.g.call ();
}). Then (function (Result) {
Console.log (result);
});
If the status F () is not overwritten for one, using INSTANCE.F () returns the corresponding trade status result.

$ node Main.js
{tx: ' 0X2AC645310278D971E3911E8F880947105F582AA4EAB3D3D66D14C95333391AC9 ',
Receipt

{transactionhash: ' 0x2ac645310278d971e3911e8f880947105f582aa4eab3d3d66d14c95333391ac9 ',
transactionindex:0,
Blockhash: ' 0x69a6788032c7bef12d6d51bc045548fa9edb0665bb0fbcf9cf55d30f9744cd61 ',
Blocknumber:29,
gasused:21803,
cumulativegasused:21803,
Contractaddress:null,
Logs: []},
Logs: []}
{tx: ' 0x65aa2c4da73ef5a17221c26e74b9b329bdc353856564f8d1f49c07f6dcd055ea ',
Receipt
{transactionhash: ' 0x65aa2c4da73ef5a17221c26e74b9b329bdc353856564f8d1f49c07f6dcd055ea ',
transactionindex:0,
Blockhash: ' 0x837ec6a3df2cc4d9a8ccf8d77c14b88a13b0053a5149a74c1a984fe88a70eaa8 ',
Blocknumber:30,
gasused:21825,
cumulativegasused:21825,
Contractaddress:null,
Logs: []},
Logs: []}
Truffle contract's GitHub address and documentation: Https://github.com/trufflesuite/truffle-contract?

    1. Transplant details?

About invalid address error, http://ethereum.stackexchange.com/questions/12957/truffle-invalid-address report this error possible situation:/HTTP Www.bullraider.com/ethereum/tutorials/342-understanding-invalid-address-error-in-dapps-or-geth-console?

A detailed contract interaction?

Truffle call Nodejs problem

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.