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博客

展示图

发起交易
完成交易

后记

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

相关推荐
jason_yang几秒前
这5年在掘金的感想
前端·javascript·vue.js
独自破碎E2 分钟前
【前序+中序】重建二叉树
java·开发语言
萧曵 丶6 分钟前
Spring 全套高频面试题(由浅到深 完整版)
java·后端·spring
武子康7 分钟前
大数据-213 Python 手写 K-Means 聚类实战(鸢尾花 Iris 数据集):从距离函数到迭代收敛与坑点
大数据·后端·机器学习
神奇小汤圆9 分钟前
MySQL大事务的Recovery优化
后端
2301_7657151414 分钟前
C语言轮子制造
c语言·开发语言·制造
魔术师卡颂15 分钟前
提问量暴跌 80% ,Stack Overflow 却赚翻了?
前端·后端·ai编程
量子炒饭大师17 分钟前
【C++入门】Cyber骇客的同名异梦——【C++重载函数】(与C的函数差异)
c语言·开发语言·c++·函数重载
charlie11451419120 分钟前
现代嵌入式C++教程:if constexpr——把编译期分支写得像写注释 —— 工程味实战指南
开发语言·c++·笔记·学习·嵌入式·现代c++
冰暮流星22 分钟前
javascript如何转换为字符串与布尔型
java·开发语言·javascript