用web3.js与智能合约交互(修改版)

首先放上官方API:https://web3js.readthedocs.io/en/1.0/index.html

工具:Truffle v4.0.4  
ganache-1.1.0-beta(ui界面版)
nodejs 8.9.4
npm 5.6.0   
web3 1.0.0

思路:

1、先用truffle创建一个以太坊智能合约项目,部署在ganache测试网络。

2、用npm创建另外一个项目,使用web3和智能合约交互

创建truffle项目:

1、mkdir truffle_test & cd truffle test

2、初始化:truffle init

3、编写智能合约,在contracts文件夹下新建智能合约:Data.sol:(功能:存、取一个字符串)

 
  1. pragma solidity ^0.4.17;

  2.  
  3. contract Data{

  4.  
  5. string public data;

  6.  
  7. function Data()public{

  8. data = "init data";

  9. }

  10. function setData(string str) public payable{

  11. data = str;

  12. }

  13.  
  14. function getData() public view returns (string) {

  15. return data;

  16. }

  17. }

4、编译:truffle compile

5、部署在测试网络上

(1)打开ganache

(2)修改migrations文件夹下的部署配置

 
  1. var Migrations = artifacts.require("./Migrations.sol");

  2. var Data = artifacts.require("./Data.sol");

  3.  
  4. module.exports = function(deployer) {

  5. deployer.deploy(Migrations);

  6. deployer.deploy(Data);

  7. };

(3)修改truffle.js配置文件,添加连接网络信息:

 
  1. module.exports = {

  2. networks: {

  3. development: {

  4. host: "localhost",

  5. port: 7545,

  6. network_id: "*"

  7. }

  8. }

  9. };

(4)执行truffle migrate(如果执行失败,可以试试truffle migrate --reset)

现在truffle项目已经做好,接下来使用web3和智能合约进行交互。

 

web3与智能合约交互

添加web3到项目中:

1、mkdir web3test & cd web3test

2、初始化 npm init

3、下载web3.js到项目中:

npm install web3 --save

以上命令会将web3.js下载到web3test/node_modules目录下,其中--save参数会web3.js添加到package.json配置文件中。

4、创建web3对象

要使用web3.js与区块链交互,需要先创建web3对象,然后连接到以太坊节点。
在web3test目录下新建index.js文件,在其中输入以下代码:

 
  1. var Web3 = require("web3");

  2. var web3 = new Web3();

  3. web3.setProvider(new Web3.providers.HttpProvider("http://localhost:7545"));

5、获取已部署的智能合约实例

 
  1. var abi = [{"constant":true,"inputs":[],"name":"getData","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"str","type":"string"}],"name":"setData","outputs":[],"payable":true,"stateMutability":"payable","type":"function"},{"constant":true,"inputs":[],"name":"data","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"}];

  2. var address = '0x345ca3e014aaf5dca488057592ee47305d9b3e10';

  3. var data = new web3.eth.Contract(abi,address);

 

合约地址取得:

 

truffle的智能合约项目部署,使用下面的命令:"truffle migrate",这个命令会执行所有migrations目录下的js文件。使用 "truffle migrate --reset"命令,则会重新执行所有脚本的部署。

如果要部署到指定的网络,可以使用"truffle migrate --network live"命令。

执行完“truffle migrate --reset”后,build/Data.json 里会在最后出现 address地址;

 

其中abi是truffle项目中build目录下Data.json文件中的abi,复制过来即可。address是合约部署的地址。通过abi和合约地址就可以获取合约的实例data。下面就可以通过data来调用合约里面的内容了。

6、调用合约函数

 
  1. data.methods.getData().call(null,function(error, result){

  2. console.log("the data:"+result);

  3. });

  4.  
  5. data.methods.setData("hello blockchain").send({from: '0x627306090abaB3A6e1400e9345bC60c78a8BEf57'}).on('transactionHash', function(hash){

  6. console.log("hash:", hash);

  7. data.methods.getData().call(null,function(error, result){

  8. console.log("the data:"+result);

  9. });

  10. });

call()和send()的作用可以从官方文档中查看。send里面的from是发送交易的地址,这里我写的是ganache中第0个账户的地址。

以上的执行结果是:

the data:init data
the data:hello blockchain
hash: 0x86a8674614c5ac4772cdf3aba6bf2786d366460bb524e49b8012b5dbe89b64dd

参考文章:http://dophin459.coding.me/posts/9cc80f82/

好的,以下是一个简单的前端web3应用程序,用于与上面编写的ERC20智能合约交互: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Web3 App</title> <script src="https://cdn.jsdelivr.net/npm/web3@1.3.5/dist/web3.min.js"></script> </head> <body> <h1>Web3 App</h1> <p>Account: <span id="account"></span></p> <p>Balance: <span id="balance"></span> ERC20 tokens</p> <input id="to" type="text" placeholder="Recipient address"> <input id="value" type="text" placeholder="Amount"> <button onclick="transfer()">Transfer</button> <script> window.addEventListener('load', async () => { if (typeof window.ethereum !== 'undefined') { await window.ethereum.enable(); const web3 = new Web3(window.ethereum); const contractAddress = 'CONTRACT_ADDRESS'; const contractAbi = [{ 'constant': true, 'inputs': [{'name': '', 'type': 'address'}], 'name': 'balanceOf', 'outputs': [{'name': '', 'type': 'uint256'}], 'payable': false, 'stateMutability': 'view', 'type': 'function' }, { 'constant': true, 'inputs': [], 'name': 'name', 'outputs': [{'name': '', 'type': 'string'}], 'payable': false, 'stateMutability': 'view', 'type': 'function' }, { 'constant': false, 'inputs': [{'name': '_to', 'type': 'address'}, {'name': '_value', 'type': 'uint256'}], 'name': 'transfer', 'outputs': [{'name': 'success', 'type': 'bool'}], 'payable': false, 'stateMutability': 'nonpayable', 'type': 'function' }, { 'constant': true, 'inputs': [], 'name': 'symbol', 'outputs': [{'name': '', 'type': 'string'}], 'payable': false, 'stateMutability': 'view', 'type': 'function' }, { 'constant': false, 'inputs': [{'name': '_spender', 'type': 'address'}, {'name': '_value', 'type': 'uint256'}], 'name': 'approve', 'outputs': [{'name': 'success', 'type': 'bool'}], 'payable': false, 'stateMutability': 'nonpayable', 'type': 'function' }, { 'constant': true, 'inputs': [{'name': '', 'type': 'address'}, {'name': '', 'type': 'address'}], 'name': 'allowance', 'outputs': [{'name': '', 'type': 'uint256'}], 'payable': false, 'stateMutability': 'view', 'type': 'function' }, { 'constant': false, 'inputs': [{'name': '_from', 'type': 'address'}, {'name': '_to', 'type': 'address'}, { 'name': '_value', 'type': 'uint256' }], 'name': 'transferFrom', 'outputs': [{'name': 'success', 'type': 'bool'}], 'payable': false, 'stateMutability': 'nonpayable', 'type': 'function' }, { 'inputs': [{'name': '_name', 'type': 'string'}, {'name': '_symbol', 'type': 'string'}, { 'name': '_totalSupply', 'type': 'uint256' }], 'payable': false, 'stateMutability': 'nonpayable', 'type': 'constructor' }, { 'anonymous': false, 'inputs': [{'indexed': true, 'name': '_from', 'type': 'address'}, { 'indexed': true, 'name': '_to', 'type': 'address' }, {'indexed': false, 'name': '_value', 'type': 'uint256'}], 'name': 'Transfer', 'type': 'event' }, { 'anonymous': false, 'inputs': [{'indexed': true, 'name': '_owner', 'type': 'address'}, { 'indexed': true, 'name': '_spender', 'type': 'address' }, {'indexed': false, 'name': '_value', 'type': 'uint256'}], 'name': 'Approval', 'type': 'event' }]; const contract = new web3.eth.Contract(contractAbi, contractAddress); const accounts = await web3.eth.getAccounts(); const account = accounts[0]; document.getElementById('account').textContent = account; const balance = await contract.methods.balanceOf(account).call(); document.getElementById('balance').textContent = balance; transfer = async () => { const to = document.getElementById('to').value; const value = document.getElementById('value').value; await contract.methods.transfer(to, value).send({from: account}); location.reload(); }; } else { alert('Please install MetaMask to use this dApp!'); } }); </script> </body> </html> ``` 在这个应用程序中,我们使用了web3.js库来与以太坊网络交互,首先需要检查MetaMask是否已安装并启用。然后,我们使用智能合约地址和ABI创建了一个智能合约实例,以便可以与合约交互。我们还获取了当前用户的帐户和智能合约中该帐户的余额,并将其显示在页面上。最后,我们定义了一个转移函数,该函数在用户输入收件人地址和金额后,调用智能合约的“transfer”函数来发送代币,并重新加载页面以更新余额。 请注意,在这个示例中,你需要将“CONTRACT_ADDRESS”替换为你部署的ERC20智能合约的地址。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值