如何ETH以太坊智能合约做一个简单的DAPP
Posted 安志强tim
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何ETH以太坊智能合约做一个简单的DAPP相关的知识,希望对你有一定的参考价值。
目标:
1、使用etherjs
2、链接MetaMask钱包
3、查询链状态、账号状态、转账、调用合同读函数、调用合同写函数
环境:
1、kovan以太坊测试链上发布合约。合约地址:0xB6b0ab2e6205212FD2A4017bD0A4710b11EA55eb
2、nodejs lite-server web服务器测试。
3、安装Google chrome metamask钱包
智能合约代码:InfoContract.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
contract InfoContract
string public fName = "azq";
uint public age= 47;
function setInfo(string memory _fName,uint _age) public returns(bool)
fName = _fName;
age = _age;
return true;
function getInfo() public view returns(string memory,uint)
return(fName,age);
代码实例:index.html
<!DOCTYPE html>
<html>
<head>
<script src="/myscript.js"></script>
</head>
<script src="https://cdn.ethers.io/lib/ethers-5.2.umd.min.js"
type="text/javascript">
</script>
<!-- <script src="https://cdn.ethers.io/lib/ethers-5.2.esm.min.js"
type="text/javascript">
</script> -->
<!-- <script type="module">
import ethers from "https://cdn.ethers.io/lib/ethers-5.2.esm.min.js";
</script> -->
<body onload="f1()">
<h2>区块链查询</h2>
<h3>网络id:<span id="chainId"></span></h3>
<h3>ens地址:<span id="ensAddress"></span></h3>
<h3>网络名:<span id="chainname"></span></h3>
<h3>区块数:<span id="blockNumber"></span></h3>
<form action="" name="myform">
<input type="text" id = "inputChainId" value=1>
</form>
<br>
<button class="queryChain" onclick="queryChain()">查询区块链</button>
<h2>查询账户余额</h2>
<h3>区块数:<span class= "blockNumber"></span></h3>
<h3>账户余额:<span id="balance"></span></h3>
<h3>格式化余额:<span id="formatBalance"></span></h3>
<form action="" name="myform">
<input type="text" id = "inputCount" value="0xFdF04BcFA232E8D2fBacBb0fb95B092273e8acF8">
</form>
<br>
<!-- <button id = "button" onclick="f1()">连接钱包</button> -->
<button class="buttonclass" onclick="queryCount()">查询账户</button>
<h2>获取当前账号</h2>
<h2>Account: <span class="showAccount"></span></h2>
<button class="enableEthereumButton">获取当前账号</button>
<h2>转账</h2>
<form action="" name="myform">
<span>地址:</span><input type="text" id ="inputAddress" value="0x1895626b720Ca74B9F265334aCE49F790Eea4dA1">
<span>金额:</span><input type="text" id ="inputNumber" value = 0>
</form>
<button class="buttonclass" onclick="transFunction()">确认转账</button>
<h2>调用合同写函数</h2>
<form action="" name="myform">
<span>姓名:</span><input type="text" id ="inputName" value="">
<span>年龄:</span><input type="text" id ="inputAge" value = 0>
</form>
<button class="buttonclass" onclick="writeContractFunction()">调用</button>
<h2>调用kovan合同只读函数getinfo</h2>
<h3>kovan链合同地址<br>0xB6b0ab2e6205212FD2A4017bD0A4710b11EA55eb<br>的getinfo函数返回值:<span id= "getInforeturns"></span></h3>
<button class="buttonclass" onclick="queryContractFunction()">调用</button>
<script>
async function queryCount()
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
strCount = document.getElementById("inputCount").value;
balance = await provider.getBalance(strCount);
document.getElementById("balance").innerHTML = balance;
blockNumber = await provider.getBlockNumber();
document.querySelector(".blockNumber").innerHTML = blockNumber;
formatBalance = ethers.utils.formatEther(balance);
document.getElementById("formatBalance").innerHTML = formatBalance;
async function queryContractFunction()
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
// const tx = signer.sendTransaction(
// to: "0x1895626b720Ca74B9F265334aCE49F790Eea4dA1",
// value: ethers.utils.parseEther("0.002")
// );
// 币安测试链智能合约地址
//const infoAddress = "0x1B307050d688adabE14414C43f4825D1ab751878";
// kavan智能合约地址
//0x6426E8dEF3651af00BBAe83C35538a5d94171306
//0x982F1399D6bDcf700bf995BE2d2a4394a8D273E6
//0xB6b0ab2e6205212FD2A4017bD0A4710b11EA55eb
const infoAddress = "0xB6b0ab2e6205212FD2A4017bD0A4710b11EA55eb";
const infoAbi =
[
"inputs": [],
"name": "getInfo",
"outputs": [
"internalType": "string",
"name": "",
"type": "string"
,
"internalType": "uint256",
"name": "",
"type": "uint256"
],
"stateMutability": "view",
"type": "function"
,
"inputs": [
"internalType": "string",
"name": "_fName",
"type": "string"
,
"internalType": "uint256",
"name": "_age",
"type": "uint256"
],
"name": "setInfo",
"outputs": [
"internalType": "bool",
"name": "",
"type": "bool"
],
"stateMutability": "nonpayable",
"type": "function"
];
const infoContract = new ethers.Contract(infoAddress, infoAbi, provider);
ddd = await infoContract.getInfo();
document.getElementById("getInforeturns").innerHTML = ddd;
async function writeContractFunction()
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
// const tx = signer.sendTransaction(
// to: "0x1895626b720Ca74B9F265334aCE49F790Eea4dA1",
// value: ethers.utils.parseEther("0.002")
// );
// 币安测试链智能合约地址
//const infoAddress = "0x1B307050d688adabE14414C43f4825D1ab751878";
// kavan智能合约地址
//0x6426E8dEF3651af00BBAe83C35538a5d94171306
//0x982F1399D6bDcf700bf995BE2d2a4394a8D273E6
//0xB6b0ab2e6205212FD2A4017bD0A4710b11EA55eb
const infoAddress = "0xB6b0ab2e6205212FD2A4017bD0A4710b11EA55eb";
const infoAbi =
[
"inputs": [],
"name": "getInfo",
"outputs": [
"internalType": "string",
"name": "",
"type": "string"
,
"internalType": "uint256",
"name": "",
"type": "uint256"
],
"stateMutability": "view",
"type": "function"
,
"inputs": [
"internalType": "string",
"name": "_fName",
"type": "string"
,
"internalType": "uint256",
"name": "_age",
"type": "uint256"
],
"name": "setInfo",
"outputs": [
"internalType": "bool",
"name": "",
"type": "bool"
],
"stateMutability": "nonpayable",
"type": "function"
];
const infoContract = new ethers.Contract(infoAddress, infoAbi, provider);
const strName = document.getElementById("inputName").value;
const numAge = document.getElementById("inputAge").value;
let infoWithSigner = infoContract.connect(signer);
tx = infoWithSigner.setInfo(strName,numAge);
async function transFunction()
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
// 币安测试链智能合约地址
//const infoAddress = "0x1B307050d688adabE14414C43f4825D1ab751878";
// kavan智能合约地址
//0x6426E8dEF3651af00BBAe83C35538a5d94171306
//0x982F1399D6bDcf700bf995BE2d2a4394a8D273E6
//0xB6b0ab2e6205212FD2A4017bD0A4710b11EA55eb
const infoAddress = "0xB6b0ab2e6205212FD2A4017bD0A4710b11EA55eb";
const infoAbi =
[
"inputs": [],
"name": "getInfo",
"outputs": [
"internalType": "string",
"name": "",
"type": "string"
,
"internalType": "uint256",
"name": "",
"type": "uint256"
],
"stateMutability": "view",
"type": "function"
,
"inputs": [
"internalType": "string",
"name": "_fName",
"type": "string"
,
"internalType": "uint256",
"name": "_age",
"type": "uint256"
],
"name": "setInfo",
"outputs": [
"internalType": "bool",
"name": "",
"type": "bool"
],
"stateMutability": "nonpayable",
"type": "function"
];
const infoContract = new ethers.Contract(infoAddress, infoAbi, provider);
const strAddress = document.getElementById("inputAddress").value;
const sumNumber = document.getElementById("inputNumber").value;
const tx = signer.sendTransaction(
to: strAddress,
value: ethers.utils.parseEther(sumNumber)
);
async function writeContractFunction()
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
// const tx = signer.sendTransaction(
// to: "0x1895626b720Ca74B9F265334aCE49F790Eea4dA1",
// value: ethers.utils.parseEther("0.002")
// );
// 币安测试链智能合约地址
//const infoAddress = "0x1B307050d688adabE14414C43f4825D1ab751878";
// kavan智能合约地址
//0x6426E8dEF3651af00BBAe83C35538a5d94171306
//0x982F1399D6bDcf700bf995BE2d2a4394a8D273E6
//0xB6b0ab2e6205212FD2A4017bD0A4710b11EA55eb
const infoAddress = "0xB6b0ab2e6205212FD2A4017bD0A4710b11EA55eb";
const infoAbi =
[
"inputs": [],
"name": "getInfo",
"outputs": [
"internalType": "string",
"name": "",
"type": "string"
,
"internalType": "uint256",
"name": "",
"type": "uint256"
],
"stateMutability": "view",
"type": "function"
,
"inputs": [
"internalType": "string",
"name": "_fName",
"type": "string"
,
"internalType": "uint256",
"name": "_age",
"type": "uint256"
],
"name": "setInfo",
"outputs": [
"internalType": "bool",
"name": "",
"type": "bool"
],
"stateMutability": "nonpayable",
"type": "function"
];
const infoContract = new ethers.Contract(infoAddress, infoAbi, provider);
const strName = document.getElementById("inputName").value;
const numAge = document.getElementById("inputAge").value;
let infoWithSigner = infoContract.connect(signer);
tx = infoWithSigner.setInfo(strName,numAge);
async function queryChain()
//window.alert("bbbbb");
//balance = await provider.getBalance("ethers.eth")
//const provider = new ethers.providers.JsonRpcProvider(window.ethers);
const provider = new ethers.providers.Web3Provider(window.ethereum);
//window.alert("provider");
const signer = provider.getSigner();
blockNumber = await provider.getBlockNumber();
let strChainId = document.getElementById("inputChainId").value;
strNetwork = ethers.providers.getNetwork(Number(strChainId));
document.getElementById("chainId").innerHTML = strNetwork.chainId;
document.getElementById("ensAddress").innerHTML = strNetwork.ensAddress;
document.getElementById("chainname").innerHTML = strNetwork.name;
document.getElementById("blockNumber").innerHTML = blockNumber;
</script>
</body>
</html>
js代码:myscript.js
function f1()
//document.getElementById("demo").innerHTML = "hahaha";
//检测Metamask钱包
if (typeof window.ethereum !== 'undefined')
console.log('MetaMask is installed!');
//window.alert("MetaMask is installed!")
else
//window.alert("Please install MetaMask")
// if (ethereum.isMetaMask)
// window.alert("MetaMask is installed2!")
//
const ethereumButton = document.querySelector('.enableEthereumButton');
const showAccount = document.querySelector('.showAccount');
const showbutton = document.querySelector('.buttonclass');
//const showbutton = document.querySelector('.buttonclass');
showbutton.addEventListener('click', () =>
//showbutton.innerHTML = "已经链接";
);
ethereumButton.addEventListener('click', () =>
getAccount();
);
async function getAccount()
const accounts = await ethereum.request( method: 'eth_requestAccounts' );
//const balance = await ethereum.request(method: 'eth_balance');
ethereum.on('accountsChanged', function (accounts)
// Time to reload your interface with accounts[0]!
window.alert("log0");
);
const account = accounts[0];
showAccount.innerHTML = account ;
以上是关于如何ETH以太坊智能合约做一个简单的DAPP的主要内容,如果未能解决你的问题,请参考以下文章
Web3与智能合约:开发一个简单的DApp并部署到以太坊测试网(Solidity+Hardhat+React)① 环境搭建
以太坊是什么,智能合约,编程语言:Solidity,DApp: 去中心化的应用程序,Truffle