6.DApp-用Web3实现前端与智能合约的交互

题记

用Web3实现前端与智能合约的交互,以下是操作流程和代码。

准备ganache环境

文章地址:4.DApp-MetaMask怎么连接本地Ganache-CSDN博客

准备智能合约

文章地址: 2.DApp-编写和运行solidity智能合约-CSDN博客

编写index.html文件

<!DOCTYPE html>

<html>

<head>

<title>Name Contract Demo</title>

<!--导入web3库-->

<script src="https://cdn.jsdelivr.net/npm/web3@1.5.2/dist/web3.min.js"></script>

<script>

// 检查Metamask是否已安装

if (typeof window.ethereum !== 'undefined') {

console.log('Metamask已安装');

}

// 设置Web3.js提供者为Metamask

const provider = window.ethereum;

const web3 = new Web3(provider);

// 请求Metamask连接到以太坊网络

provider.request({ method: 'eth_requestAccounts' })

.then(() => {

console.log('Metamask已连接到以太坊网络');

})

.catch((err) => {

console.error('无法连接到以太坊网络', err);

});

function setName() {

// 合约地址

const contractAddress = '0x32FDC4E86421143b1c27dE49542Bc8ECE2B162a0';

// 合约ABI

const contractABI = [

{

"inputs": [

{

"internalType": "string",

"name": "_name",

"type": "string"

}

],

"name": "setName",

"outputs": [],

"stateMutability": "nonpayable",

"type": "function"

},

{

"inputs": [],

"name": "getName",

"outputs": [

{

"internalType": "string",

"name": "",

"type": "string"

}

],

"stateMutability": "view",

"type": "function"

}

];

const contract = new web3.eth.Contract(contractABI, contractAddress);

const name = document.getElementById('name').value;

// 替换为您的账户地址web3.eth.defaultAccount

const fromAddress = '0x4e8eB4d1C203929074A3372F3703E556820fEA57';

//contract.methods.setName(name).send({from: fromAddress})

contract.methods.setName(name).send({from: fromAddress})

.on('transactionHash', function(hash){

console.log('Transaction Hash:', hash);

})

.on('receipt', function(receipt){

console.log('Transaction Receipt:', receipt);

})

.on('error', function(error){

console.error('Error:', error);

});

}

function getName() {

// 合约地址

const contractAddress = '0x32FDC4E86421143b1c27dE49542Bc8ECE2B162a0';

// 合约ABI

const contractABI = [

{

"inputs": [

{

"internalType": "string",

"name": "_name",

"type": "string"

}

],

"name": "setName",

"outputs": [],

"stateMutability": "nonpayable",

"type": "function"

},

{

"inputs": [],

"name": "getName",

"outputs": [

{

"internalType": "string",

"name": "",

"type": "string"

}

],

"stateMutability": "view",

"type": "function"

}

];

const contract = new web3.eth.Contract(contractABI, contractAddress);

contract.methods.getName().call()

.then(function(result) {

console.log('Name:', result);

document.getElementById('nameValue').innerText = result;

})

.catch(function(error) {

console.error('Error:', error);

});

}

</script>

</head>

<body>

<h1>设置姓名</h1>

<label for="name">姓名:</label>

<input type="text" id="name">

<button οnclick="setName()">设置姓名</button>

<br>

<button οnclick="getName()">得到姓名</button>

<br>

<span id="nameValue"></span>

</body>

</html>

html 复制代码
<!DOCTYPE html>
<html>
<head>
    <title>Name Contract Demo</title>
    <!--导入web3库-->
    <script src="https://cdn.jsdelivr.net/npm/web3@1.5.2/dist/web3.min.js"></script>
    <script>
    // 检查Metamask是否已安装
    if (typeof window.ethereum !== 'undefined') {
    console.log('Metamask已安装');
    }
  
    // 设置Web3.js提供者为Metamask
    const provider = window.ethereum;
    const web3 = new Web3(provider);
  
    // 请求Metamask连接到以太坊网络
    provider.request({ method: 'eth_requestAccounts' })
    .then(() => {
      console.log('Metamask已连接到以太坊网络');
    })
    .catch((err) => {
      console.error('无法连接到以太坊网络', err);
    });
  
    function setName() {
    // 合约地址
    const contractAddress = '0x32FDC4E86421143b1c27dE49542Bc8ECE2B162a0'; 
    // 合约ABI
    const contractABI = [
	{
		"inputs": [
			{
				"internalType": "string",
				"name": "_name",
				"type": "string"
			}
		],
		"name": "setName",
		"outputs": [],
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "getName",
		"outputs": [
			{
				"internalType": "string",
				"name": "",
				"type": "string"
			}
		],
		"stateMutability": "view",
		"type": "function"
	}
    ]; 
    const contract = new web3.eth.Contract(contractABI, contractAddress);
    const name = document.getElementById('name').value;
    // 替换为您的账户地址web3.eth.defaultAccount
    const fromAddress = '0x4e8eB4d1C203929074A3372F3703E556820fEA57'; 
    //contract.methods.setName(name).send({from: fromAddress})

    contract.methods.setName(name).send({from: fromAddress})
    .on('transactionHash', function(hash){
        console.log('Transaction Hash:', hash);
    })
    .on('receipt', function(receipt){
        console.log('Transaction Receipt:', receipt);
    })
    .on('error', function(error){
        console.error('Error:', error);
    });
    }

    function getName() {
    // 合约地址
    const contractAddress = '0x32FDC4E86421143b1c27dE49542Bc8ECE2B162a0'; 
    // 合约ABI
    const contractABI = [
	{
		"inputs": [
			{
				"internalType": "string",
				"name": "_name",
				"type": "string"
			}
		],
		"name": "setName",
		"outputs": [],
		"stateMutability": "nonpayable",
		"type": "function"
	},
	{
		"inputs": [],
		"name": "getName",
		"outputs": [
			{
				"internalType": "string",
				"name": "",
				"type": "string"
			}
		],
		"stateMutability": "view",
		"type": "function"
	}
    ]; 
    const contract = new web3.eth.Contract(contractABI, contractAddress);
    contract.methods.getName().call()
    .then(function(result) {
        console.log('Name:', result);
        document.getElementById('nameValue').innerText = result;
    })
    .catch(function(error) {
        console.error('Error:', error);
    });
    }
    </script>
</head>
<body>
    <h1>设置姓名</h1>
    <label for="name">姓名:</label>
    <input type="text" id="name">
    <button onclick="setName()">设置姓名</button>
    <br>
    <button onclick="getName()">得到姓名</button>
    <br>
    <span id="nameValue"></span>
</body>
</html>

执行程序

使用vscode的Live Server打开网页

参考这篇文章的执行方法:1.Vue-在独立页面实现Vue的增删改查-CSDN博客

展示图

发起交易
完成交易

后记

觉得有用可以点赞或收藏!

相关推荐
栗子~~6 分钟前
基于 Hardhat 区块链 + MetaMask 钱包 开发的极简去中心化应用(DApp)demo
去中心化·区块链
云栖梦泽7 分钟前
易语言开发从入门到精通:进阶篇·网络爬虫与数据采集分析系统深度实战
开发语言
Victor35610 分钟前
MongoDB(39)如何使用聚合进行过滤?
后端
lsx20240617 分钟前
XSLT `<sort>` 元素详解
开发语言
_olone19 分钟前
牛客每日一题:显生之宙(Java)
java·开发语言·算法·牛客
Sirens.21 分钟前
Java 包装类、泛型与类型擦除
java·开发语言·javac
Victor35621 分钟前
MongoDB(38)如何使用聚合进行投影?
后端
小光学长37 分钟前
基于ssm的膳食健康管理系统e6whl4q7(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
java·开发语言·数据库·学习·ssm
无心水41 分钟前
【常见错误】2、Java并发编程避坑指南:从加锁失效到死锁,10个案例教你正确使用锁
java·开发语言·python
青衫码上行42 分钟前
【项目开发日记 | Java架构】第一天
java·开发语言·spring cloud