javascript - Web3JS 发送事务
问题描述
我是 Web3 和 Solidity 开发的新手。尝试开发我的第一个 DAPP 只是为了更多地了解这个世界。我正在使用元掩码,并且在浏览器中也没有出现错误。我正在执行发送事务,结果没有在控制台中弹出,但也没有错误。请帮助我改进我的代码并引导我朝着正确的方向前进。
const web3 = new Web3(Web3.givenProvider || "ws://localhost:8545");
async function requestWeb3() {
await window.ethereum.request({ method: "eth_requestAccounts" });
}
requestWeb3();
let account;
const contractABI = [
{
"inputs": [],
"name": "buyAd",
"outputs": [],
"stateMutability": "payable",
"type": "function"
},
{
"inputs": [],
"name": "lastPrice",
"outputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"stateMutability": "view",
"type": "function"
}
]
const contractAddress = "0x933ef849cca1c037c5b335ce5ea1c309a6de6d67";
const contract = new web3.eth.Contract(contractABI, contractAddress);
web3.eth.getAccounts().then(accounts => {
console.log(accounts[0]);
accounts = accounts;
})
const connectBtn = document.getElementById("connect");
connectBtn.addEventListener('click', () => {
console.log('click');
contract.methods.buyAd().send({
from:accounts[0],
to:contractAddress,
value: "1000000000000000000",
data: "0xdf"
}, function (err, result) {
if (err) {
console.log("Error!", err);
return
}
console.log(result);
})
});
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract AdvertisementAuction {
uint public lastPrice = 0;
function buyAd() payable public {
require(msg.value > lastPrice, "This advertisement costs more then the inputed value.");
lastPrice = msg.value;
}
}
解决方案
试试这个脚本:
const Web3 = require("web3");
const ethEnabled = async () => {
if (window.ethereum) {
await window.ethereum.send('eth_requestAccounts');
window.web3 = new Web3(window.ethereum);
return true;
}
return false;
}
我们检查是否window.ethereum
存在,然后window.web3
使用我们自己的 web3 版本创建一个对象,使用 window.ethereum 对象作为输入提供者。在这种情况下,该await window.ethereum.send('eth_requestAccounts')
函数调用弹出 UI 对话框,询问用户是否允许将 dApp 连接到 MetaMask。
它应该有效。让我知道 :)
推荐阅读
- nuxt.js - 在 Nuxt 应用程序的布局中访问 ctx 属性
- python - 有没有办法将色调仅应用于 seaborn 中 PairGrid 的下部
- performance - 什么时候在 Velocity 中评估字符串?
- abap - 将键值映射到结构
- spring-boot - SpringBoot Spring Security 不能将给定的过滤器仅应用于一个路径
- clojure - 如何将 .edn 文件包含为另一个“父”.edn 文件的子集,例如 .xml 文件中的“包含路径”元素?
- shopify - 使用礼品卡在 Shopify 中购买产品时如何禁用其他付款方式?
- asp.net - 如何在 NServiceBus 路由中给出另一个解决方案的路由?
- spring-boot - 获取并解码来自 RestTemplate spring boot 的响应
- c# - Append XML string block save document