NO IMAGE

一、概述

在上面的文章中已經說明了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、再次查詢雙方的合約餘額

程式碼略