太坊インテリジェント契約コインアプリケーション開発(4)-web 3クライアントとgethノードのインタラクション


一、概説
dappとイーサ坊のインタラクションを開発するには多くの方法があり、ここではweb 3とgethインタラクションを使用し、web 3はイーサ坊政府が提供するjsのクライアントインタラクションツールである.nodejsプロジェクトで参照してもよいし、htmlにweb 3を導入してもよい.jsはインタラクティブですが、この方法は安全性が悪いので使用することをお勧めしません.web3.jsの最もよく使われるシーンはやはりnodejsの中でサーバー側のプログラミングを行って、expressなどのフレームワークと結びつけて各種の形式の応用とwebインタフェースを書き出して伝統的なappに使用することができます
二、環境準備
1、npmを使用してweb 3をグローバルにインストールする
sudo npm install web3 -g

2、基礎的なnpmプロジェクトを新規作成する
mkdir web3
cd web3
npm init
npm install

3、入口ファイルの編集
npm initコマンドを実行する際には、プロジェクトのバージョン、エントリファイルなどの設定が必要であり、設定に従って新しいエントリファイルを作成するデフォルトはindexである.js.次のコマンドを使用してindexを実行できます.js
nodejs index.js

インタラクティブモードでjsを実行し、nodejsを直接実行することもできます.
三、インタラクティブな実践
1、web 3設定providerを導入する
Web3 = require("web3")
var web3 = new Web3(Web3.givenProvider||'http://127.0.0.1:8545');
web3.setProvider('http://127.0.0.1:8545');

2、バージョン番号の照会
console.log('list web3 version:');
console.log(web3.version)

3、クエリーサポートモジュール
console.log('list all the modules:'+Web3.modules);
getdetail(Web3.modules)

4、クエリー補助関数
console.log('list utils:'+web3.utils);
getdetail(web3.utils)

5、デフォルトアカウントの照会
console.log('default Account:')
console.log(web3.eth.defaultAccount)

6、gas費用の照会
web3.eth.getGasPrice().then(function(r){
	console.log('display the gasprice base on the last block:');
	console.log(r)
})

7、口座照会リスト
web3.eth.getAccounts().then(function(r){
	console.log('display all the accounts:');
	console.log(r)
})

8、新規口座
web3.eth.personal.newAccount('sunbaolong').then(function(r){
	console.log('create a new account')
	console.log(r)
})

9、口座のロック解除
web3.eth.personal.unlockAccount('0xa5d4725d9dc3f7e73818936abe151602ad6d26fa', "sunbaolong").then(function(r){
	console.log('unlock account')
	console.log(r)
})

10、口座のロック解除
web3.eth.sendTransaction({
    from: '0xa5d4725d9dc3f7e73818936abe151602ad6d26fa',
    to: '0x09f90ceff015e0610a9b9b7d0e3f7c498e0b0f06',
    value: '300'
}).then(function(r){
   console.log('transaction is send');
   console.log(r)
});
その他の機能はご自身で実践してください