在上面的文章中已经说明了web3与geth的交互,下面将使用web3访问我们已经部署好的代币合约
在nodejs项目下新建一个contract.js 文件
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
是合约的地址,在部署合约中可以看到
myContract.methods.balanceOf('0xa5d4725d9dc3f7e73818936abe151602ad6d26fa').call().then(function(r){
console.log('show the custom account balance:');
console.log(r)
})
myContract.methods.transfer('0xa5d4725d9dc3f7e73818936abe151602ad6d26fa',100).send().then(function(r){
console.log('use the contract to send coin:');
console.log(r)
})
代码略