First put the official api:https://web3js.readthedocs.io/en/1.0/index.html tool: Truffle v4.0.4
Ganache-1.1.0-beta (UI interface Version)
Nodejs 8.9.4
NPM 5.6.0
WEB3 1.0.0
Ideas:
1, first use truffle to create an intelligent contract project, deployed in the Ganache test network.
2, with NPM to create another project, using WEB3 and intelligent contract interaction
To create a truffle project:
1, mkdir truffle_test & CD Truffle test
2. Initialization: Truffle init
3, the preparation of intelligent contracts, in the Contracts folder under the new smart contract: Data.sol: (function: Save, take a string)
pragma solidity ^0.4.17;
Contract data{
string public Data;
function data () public{
data = "init data";
}
function SetData (string str) public payable{
data = str;
}
function GetData () public view Returns (String) {return
data;
}
}
4, compile: truffle compile
5, deployed on the test network
(1) Open ganache
(2) Modify the deployment configuration under the Migrations folder
var migrations = Artifacts.require ("./migrations.sol");
var Data = Artifacts.require ("./data.sol");
Module.exports = function (deployer) {
deployer.deploy (migrations);
Deployer.deploy (Data);
(3) Modify Truffle.js configuration file, add Connection Network information:
Module.exports = {
networks: {
development: {
host: "localhost",
port:7545,
network_id: "*"
}
}
};
(4) Perform truffle migrate (if execution fails, try truffle migrate--reset)
Now that the truffle project is ready, the next step is to interact with the WEB3 and the smart contract.
WEB3 and Intelligent Contract interaction
Add WEB3 to Project:
1. mkdir Web3test & CD Web3test
2. Initializing NPM Init
3, download Web3.js to the project:
NPM Install WEB3--save
The above command downloads web3.js to the Web3test/node_modules directory, where the--save parameters are web3.js added to the Package.json configuration file.
4. Create WEB3 objects
To interact with a block chain using web3.js, you need to create a Web3 object and then connect to the Ethernet square node.
Create a new Index.js file in the Web3test directory, where you enter the following code:
var Web3 = require ("web3");
var web3 = new Web3 ();
Web3.setprovider (New Web3.providers.HttpProvider ("http://localhost:7545"));
5. Get a deployed Smart contract instance
var abi = [{' Constant ': true, ' inputs ': [], ' name ': ' GetData ', ' outputs ': [{' Name ': ' ', ' ' type ': ' ' ', ' ' ' ' ' ', ' ' statemutability ': ' View ', ' type ': ' function '},{' constant ': false, ' inputs ': [{' name ': ' str ', ' type ': ' String '}], ' name ' : "SetData", "outputs": [], "payable": True, "statemutability": "Payable", "type": "function"},{"constant": true, "inputs ': [], ' name ': ' Data ', ' outputs ': [{' Name ': ' ', ' type ': ' String '}], ' payable ': false, ' statemutability ': ' View ', ' type ': ' function "},{" inputs: [], "payable": false, "statemutability": "Nonpayable", "type": "Constructor"}];
var address = ' 0x345ca3e014aaf5dca488057592ee47305d9b3e10 ';
var data = new Web3.eth.Contract (abi,address);
Where the ABI is the truffle project in the build directory in the Data.json file in the ABI, copied over. Address is the location of the contract deployment. The contract's instance data can be obtained through the ABI and the contract address. The following data can be used to invoke the contents of the contract.
6. Call contract function
Data.methods.getData (). Call (Null,function (error, result) {
Console.log ("The Data:" +result);
});
Data.methods.setData ("Hello Blockchain"). Send ({from: ' 0x627306090abab3a6e1400e9345bc60c78a8bef57 '}). On (' Transactionhash ', function (hash) {
console.log ("hash:", hash);
Data.methods.getData (). Call (Null,function (error, result) {
Console.log ("The Data:" +result);});
The role of Call () and send () can be viewed from the official document. Send's from is the address of the transaction, where I write the address of the No. 0 account in ganache.
The results of the above implementation are:
The Data:init data
The Data:hello Blockchain
Hash:0x86a8674614c5ac4772cdf3aba6bf2786d366460bb524e49b8012b5dbe89b64dd
Reference article: http://dophin459.coding.me/posts/9cc80f82/
================== Advanced: web3+ipfs=========================
Ideas:
Because there is a cost to storing data into a block chain, it is not necessary to upload a large amount of data. The data can be stored on the IPFs to get a hash value, the hash stored in the block chain, greatly reducing the amount of storage.
1, storage data: From the local access to files, uploaded to the IPFs above, get the file hash value, the hash value stored in the block chain
2, take data: from the block chain to get hash value, according to hash from the IPFs read data, save in the local
Project Flow:
mkdir Test_eth_ipfs & CD Test_eth_ipfs
Truffle project Creation As in the example above, you can do it again.
Or continue the operation in the TEST_ETH_IPFS directory:
1, NPM Init
2, Import the Web3 interface (using the web30.20.1 version, because in the use of version 1.0 is some errors have been not to come out, simply or with the 0.20 version of it)
NPM Install web3@0.20.1--save
3, Import IPFs interface
NPM Install Ipfs-api--save
4, create a IPFs operation of the JS file, easy to operate below
Const IPFSAPI = require (' Ipfs-api ');
Const IPFS = IPFSAPI ({host: ' localhost ', port: ' 5001 ', protocal: ' http '});
Exports.add = function (buffer) {return
new Promise (function (resolve, reject) {
try {
Ipfs.add buffer, function (err, files) {
if (err | | typeof files = = ' undefined ') {
reject (err);
} else{
Resolve (Files[0].hash);
}
})
} catch (e) {
reject (e);
}}
)
}
Exports.get = function (hash) {return
new Promise (function (resolve, reject) {
try {
ipfs.get (hash, function (err, files) {
if (err | | typeof files = = ' undefined ') {
reject (err);
} else{
Resolve (files[0].content);
}
})
} catch (e) {
reject (e);
}}
)
}
5, create Index.js file, realize intelligent contract and WEB3+IPFS interaction
var ipfsfile = require ("./ipfsfile");
var fs = require (' FS ');
var data = Artifacts.require ("Dataoperator");
var contract = require (' truffle-contract ');
var Web3 = require (' web3 ');
var web3 = new Web3 ();
var Provider = new Web3.providers.HttpProvider (' http://localhost:7545 ');
Web3.setprovider (provider);
Let Addpath = './storage/add/file1 ';
Let GetPath = './storage/get/file2 ';
Let buff = Fs.readfilesync (Addpath);
var Contractjson = Json.parse (Fs.readfilesync ("./build/contracts/dataoperator.json"));
var Contract_abi = Contractjson.abi;
var data = contract (Contractjson);
Data.setprovider (provider);
var data_instance;
var eth_accounts;
Web3.eth.getAccounts (function (err, accounts) {if (err) {Console.log (err);
} eth_accounts = accounts;
Data.deployed (). Then (function (instance) {data_instance = instance;
}). Then (function () {return ipfsfile.add (buff);
}). Then (function (hash) {Console.log (' hash1 ', hash);
Data_instance.setdata (Hash,{from:eth_accounts[0]}); }). Then (function () {return data_instance.getdata ();
}). Then (function (hash) {Console.log (' hash2 ', hash);
return Ipfsfile.get (hash);
}). Then (function (data_info) {Fs.writefilesync (GetPath, data_info);
Console.log (' Data_info: ', data_info.tostring (' utf-8 '));
). catch (function (err) {Console.log (err);
})
})
6. Operation:
IPFs Daemon (start IPFs)
Node Index
Two identical hash values are output in the console, and a file like the one in/storage/set will appear in/storage/get