这里直接上代码:
首先,在写代码之前,我们需要先下载web3.js库:
npm install web3
之后进行wbe3.js的引用:
<script src="/node_modules/web3/dist/web3.min.js">//这里换成你自己的路径</script>
这里是前端代码:
<h1>Simple DApp</h1>
<label for="dataInput">Enter a number:</label>
<input type="number" id="dataInput" placeholder="Enter a number">
<button onclick="setNumber()">Set Number</button>
<button onclick="getNumber()">Get Number</button>
<p>Stored Number: <span id="storedNumber">0</span></p>
// 替换为你的合约 ABI 和地址
const abi = [
{
"inputs": [
{
"internalType": "uint256",
"name": "initialValue",
"type": "uint256"
}
],
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"inputs": [],
"name": "get",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
{
"internalType": "uint256",
"name": "x",
"type": "uint256"
}
],
"name": "set",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "storedData",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
}
];
const contractAddress = '0x63dD7E97c2ba8cF2038A65B0fCF477B67b065CF8'; // 替换为你的合约地址
const web3 = new Web3(window.ethereum);
// 创建 Web3 实例
if (typeof window.ethereum !== 'undefined') {
// 请求用户授权连接
window.ethereum.request({ method: 'eth_requestAccounts' });
} else {
console.error('MetaMask not installed');
}
// 创建合约实例
const contract = new web3.eth.Contract(abi, contractAddress);
async function setNumber() {
const number = document.getElementById('dataInput').value;
const accounts = await web3.eth.requestAccounts();
contract.methods.set(number).send({ from: accounts[0] }, (error, transactionHash) => {
if (!error) {
console.log('Transaction hash:', transactionHash);
} else {
console.error(error);
}
});
}
async function getNumber() {
const result = await contract.methods.get().call();
document.getElementById('storedNumber').innerText = result;
}
这里是合约代码:
contract SimpleStorage {
uint256 public storedData;
// 构造函数,初始化存储数据
constructor(uint256 initialValue) {
storedData = initialValue;
}
// 设置存储数据
function set(uint256 x) public {
storedData = x;
}
// 获取存储数据
function get() public view returns (uint256) {
return storedData;
}
这些就是所有的代码。
如果有什么问题可以在评论区提出。
标签:function,const,name,如何,uint256,DAPP,简单,web3,type From: https://blog.csdn.net/2401_83221104/article/details/145093938