以太坊智能合约代币应用开发(5)-web3调用智能代币合约

一、概述

在上面的文章中已经说明了web3与geth的交互,下面将使用web3访问我们已经部署好的代币合约

二、应用实践

1、新建文件

在nodejs项目下新建一个contract.js 文件

2、创建合约实例

Web3 = require("web3")
var web3 = new Web3(Web3.givenProvider||'http://127.0.0.1:8545');
web3.setProvider('http://127.0.0.1:8545');
var myContract = new web3.eth.Contract([
	{
		"constant": true,
		"inputs": [
			{
				"name": "",
				"type": "address"
			}
		],
		"name": "balanceOf",
		"outputs": [
			{
				"name": "",
				"type": "uint256"
			}
		],
		"payable": false,
		"stateMutability": "view",
		"type": "function"
	},
	{
		"constant": false,
		"inputs": [
			{
				"name": "_to",
				"type": "address"
			},
			{
				"name": "_value",
				"type": "uint256"
			}
		],
		"name": "transfer",
		"outputs": [],
		"payable": false,
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"constant": false,
		"inputs": [
			{
				"name": "addr",
				"type": "address"
			}
		],
		"name": "getBalance",
		"outputs": [
			{
				"name": "",
				"type": "uint256"
			}
		],
		"payable": false,
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"inputs": [
			{
				"name": "initialSupply",
				"type": "uint256"
			}
		],
		"payable": false,
		"stateMutability": "nonpayable",
		"type": "constructor"
	}
], '0x7b05b7bca697f821e94de75f62005c13b66f4575', {
    from: '0xa5d4725d9dc3f7e73818936abe151602ad6d26fa', // default from address
    gasPrice: '20000000000' // default gas price in wei, 20 gwei in this case
});

上面的代码使用abi与合约地址构建了只能合约实例

其中

0x7b05b7bca697f821e94de75f62005c13b66f4575

是合约的地址,在部署合约中可以看到

3、调用合约的balanceof方法查看账户余额

myContract.methods.balanceOf('0xa5d4725d9dc3f7e73818936abe151602ad6d26fa').call().then(function(r){
	console.log('show the custom account balance:');
	console.log(r)
})

4、使用智能合约发起交易

myContract.methods.transfer('0xa5d4725d9dc3f7e73818936abe151602ad6d26fa',100).send().then(function(r){
	console.log('use the contract to send coin:');
	console.log(r)
})

5、再次查询双方的合约余额

代码略


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