简介与环境
简介
web3.js 是以太坊提供的一个 JavaScript 库,它封装了以太坊的 JSON RPC API、IPC 调用,提供了一系列与以太坊区块链交互的对象和函数。
几乎囊括 JSON RPC 的 API,还可以编译和部署智能合约以及调用智能合约等,其中最重要的就是与智能合约交互的 JS 对象及函数。
开发环境
macOS 操作系统
Node.js 8.9.4
npm 5.6.0
调用智能合约
首先需要使用 Solidity 编写智能合约,最简单的合约如下,不与区块发生联系:
1 | pragma solidity ^0.4.2; |
注:Solidity 在线编译环境 地址
编译后会产生很多不同的东西,部分如下:
WEB3DEPLOY:
1
2
3
4
5
6
7
8
9
10
11
12var helloContract = web3.eth.contract([{"constant":true,"inputs":[],"name":"say","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function","stateMutability":"view"},{"inputs":[],"payable":false,"type":"constructor","stateMutability":"nonpayable"}]);
var hello = helloContract.new(
{
from: web3.eth.accounts[0],
data: '0x6060604052341561000c57fe5b5b5b5b6101598061001e6000396000f30060606040526000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063954ab4b21461003b575bfe5b341561004357fe5b61004b6100d4565b604051808060200182810382528381815181526020019150805190602001908083836000831461009a575b80518252602083111561009a57602082019150602081019050602083039250610076565b505050905090810190601f1680156100c65780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6100dc610119565b604060405190810160405280600c81526020017f48656c6c6f20576f726c6421000000000000000000000000000000000000000081525090505b90565b6020604051908101604052806000815250905600a165627a7a72305820b88ade0e1b40d9f8ffeba3f2bc9aa2ee4a1ae17f03fc52fc568812eb5d96f5ad0029',
gas: '4700000'
}, function (e, contract){
console.log(e, contract);
if (typeof contract.address !== 'undefined') {
console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash);
}
})
ABI(后面会用到):
1 | [ |
创建一个 test.js,内容如下:
1 | // 引入依赖模块 |
启动之前应该先加载 test.js 所依赖的模块:
1 | $ npm install express |
运行
1 | $ node test.js |
终端打印出”Server running at http://127.0.0.1:8888"时即可访问"http://127.0.0.1:8888",网页会返回"Hello World”!