web3js调用已部署智能合约的function

简介与环境

简介

web3.js是以太坊提供的一个Javascript库,它封装了以太坊的JSON RPC API、IPC调用,提供了一系列与以太坊区块链交互的J对象和函数。几乎囊括JSON RP的API,还可以编译和部署智能合约以及调用智能合约等,其中最重要的就是与智能合约交互的JS对象及函数。

开发环境

macos操作系统
nodejs 8.9.4
npm 5.6.0

调用智能合约

首先需要使用Solidity编写智能合约,最简单的合约如下,不与区块发生联系:

pragma solidity ^0.4.2;
 contract hello {
 
     function hello() public {
         
     }
 
     function say() constant public returns (string) {
         return "Hello World!";
     }
 }

注:Solidity在线编译环境地址 点我

编译后会产生很多不同的东西,部分如下:

WEB3DEPLOY

var helloContract = web3.eth.contract([{"constant":true,"inputs":[],"name":"say","outputs":[{"name":"","type":"string"}],"payable":false,"type":"function","stateMutability":"view"},{"inputs":[],"payable":false,"type":"constructor","stateMutability":"nonpayable"}]);
var hello = helloContract.new(
   {
     from: web3.eth.accounts[0], 
     data: '0x6060604052341561000c57fe5b5b5b5b6101598061001e6000396000f30060606040526000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063954ab4b21461003b575bfe5b341561004357fe5b61004b6100d4565b604051808060200182810382528381815181526020019150805190602001908083836000831461009a575b80518252602083111561009a57602082019150602081019050602083039250610076565b505050905090810190601f1680156100c65780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6100dc610119565b604060405190810160405280600c81526020017f48656c6c6f20576f726c6421000000000000000000000000000000000000000081525090505b90565b6020604051908101604052806000815250905600a165627a7a72305820b88ade0e1b40d9f8ffeba3f2bc9aa2ee4a1ae17f03fc52fc568812eb5d96f5ad0029', 
     gas: '4700000'
   }, function (e, contract){
    console.log(e, contract);
    if (typeof contract.address !== 'undefined') {
         console.log('Contract mined! address: ' + contract.address + ' transactionHash: ' + contract.transactionHash);
    }
 })

ABI(后面会用到):

[
    {
        "constant": true,
        "inputs": [],
        "name": "say",
        "outputs": [
            {
                "name": "",
                "type": "string"
            }
        ],
        "payable": false,
        "type": "function",
        "stateMutability": "view"
    },
    {
        "inputs": [],
        "payable": false,
        "type": "constructor",
        "stateMutability": "nonpayable"
    }
]

创建一个test.js,内容如下:

// 引入依赖模块
var express = require("express")
var Web3 = require("web3")
var net = require("net")
var http = require("http")

var web3;
// 创建web3对象并连接到以太坊节点
if (typeof web3 !== 'undefined') {
  web3 = new Web3(web3.currentProvider);
} else {
  // set the provider you want from Web3.providers
  web3 = new Web3(new Web3.providers.HttpProvider("http://192.168.53.60:8545"));
}

// 合约ABI
var abi = [{"constant":true,"inputs":[],"name":"say","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"}];
// 合约地址
var address = "0xf77976c9a552f2934d3694c38fbd057ae803ef45";
// 通过ABI和地址获取已部署的合约对象
var helloContract = new web3.eth.Contract(abi,address);

http.createServer(function (request, response) {
    
    // 调用智能合约方法
    var helloResult = helloContract.methods.say().call().then(function(result){
    console.log("返回值:" + result);
    // 发送 HTTP 头部 
    // HTTP 状态值: 200 : OK
    // 内容类型: text/plain
    response.writeHead(200, {'Content-Type': 'text/plain'});
    
    // 发送响应数据
    response.end(result);
});
    
}).listen(8888);

// 终端打印如下信息
console.log('Server running at http://127.0.0.1:8888/');

启动之前应该先加载test.js所依赖的模块:

$ npm install express  
$ npm install web3  
$ npm install http

运行

    $ node test.js

终端打印出"Server running at http://127.0.0.1:8888" 时即可访问"http://127.0.0.1:8888" ,网页会返回"Hello World"!


https://www.meiwen.com.cn/subject/tkvydftx.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值