[区块链笔记11] web3.js实用代码段

检查环境web3环境

window.addEventListener('load', function() {
	if (typeof web3 !== 'undefined') {
		web3 = new Web3(web3.currentProvider);
		if (web3.currentProvider.isMetaMask == true) {
			//metamask可用
		} else {
			//非metamask环境
		}
	} else {
		//需要安装metamask
	}
})

检查网络环境

web3.version.getNetwork((err, netId) => {
	switch (netId) {
		case '1': 	//mainnet
		break
		case '2':	//deprecated morden test network
		break
		case '3': 	//ropsten test network 
		break
		case '4': 	//Rinkeby test network
		break
		default:
			console.log('This is an unknown network.');
	}
});

获取账户信息

//0.20.x版本
''

	ethereum.enable();
	if (typeof web3 !== 'undefined') {
		web3 = new Web3(web3.currentProvider);
	} else {
		web3 = new Web3(new Web3.providers.HttpProvider('http:127.0.0.1:7545'));
		console.log('web3 local provider:' + web3);
	}
	var accounts = web3.eth.accounts;
	console.log('accounts[0]: ' + accounts);
	web3.eth.getAccounts(function callback1(err1, result) {
		web3.eth.getBalance(result[0], function callback2(err2, value) {
			$('#info').html(value);
		})
	})



//1.x.x版本
''

	ethereum.enable();
	if (typeof web3 !== 'undefined') {
		web3 = new Web3(web3.currentProvider);
	} else {
		web3 = new Web3(new Web3.providers.HttpProvider('http:127.0.0.1:7545'));
		console.log('web3 local provider:' + web3);
	}
	web3.eth.getAccounts()
		.then((res) => web3.eth.getBalance(res[0]))
		.then((value) => $('#info').html(value));

部署合约

var infoContract  = web3.eth.contract(ABI);
var info = infoContract.at("address")//这部分代码可以通过remix获取
infoContract.new({
	from: mySenderAddress,
	data:bytecode,
	gas:gasEstimate
});

调用合约

info.getInfo(function(err, result) {

})

info.setInfo(name, age, function(err, result) {
	
})

发送交易

//检查钱包
web3.eth.getAccounts(function(err, accounts) {
	//检查accounts内容
})
//自动指定gas
var message = {from: fromAccount, to:toAccount, value:web3.toWei(amount, 'ether'),
				gas:gas, gasPrice:gasPrice};

//使用默认账号
web3.eth.defaultAccount = fromAccount;
var message = {to:toAccount, value:web3.toWei(amount, 'ether')};



web3.eth.sendTransaction(message, (err, res) => {
	var output = "";
	if (!err) {
		output += res;
	} else {
		output = "Error";
	}
	document.getElementById('transactionResponse').innerHTML = "Transaction response " + output + "
"
});

监听事件

合约中设置事件 event EventName(uint param);
合约中触发事件 emit EventName(10);

pragma solidity ^0.4.23;

contract InfoContract {
    string name;
    uint age;
    
    event doneEvent(string name, uint age);
    
    function setInfo(string _name, uint _age) public {
        name = _name;
        age = _age;
        emit doneEvent(name, age);
    }
    
    function getInfo() public view returns (string, uint) {
        return (name, age);
    }
}
var infoEvent = info.doneEvent();
infoEvent.watch(function(error, result) {
	if (!error) {
		//$('#loader').hide();
		$('#info').html(result.args.name + '(' + result.args.age + ' years old)');
	} else {
		//$('#loader').hide();
		$('#info').hmtl('Error:' + error);
	}
})

最后这个监听事件的地方出了一点问题,就是var infoEvent = info.doneEvent();这行代码中,js的console里说donEvent不是一个函数。搞了半天都没搞好
后来从谷歌换成了火狐就好了。

你可能感兴趣的:(区块链)