首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Web3JS发送事务

Web3JS发送事务
EN

Stack Overflow用户
提问于 2021-07-10 12:59:47
回答 1查看 321关注 0票数 0

我是一个非常新的Web3和可靠开发人员。尝试在我的第一个DAPP上工作,只是为了更多地了解这个世界。我正在使用metamask,并且在浏览器中也没有收到任何错误。我正在做一个发送事务,结果没有在控制台中弹出,但也没有错误。请帮助我改进我的代码,并引导我朝着正确的方向前进。

代码语言:javascript
复制
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);
        
    })
});
代码语言:javascript
复制
// 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;
    }
    
}
EN

回答 1

Stack Overflow用户

发布于 2021-07-11 23:42:07

尝试使用此脚本:

代码语言:javascript
复制
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是否存在,然后使用我们自己的web3版本创建一个window.web3对象,使用window.ethereum对象作为输入提供程序。在本例中,await window.ethereum.send('eth_requestAccounts')函数调用弹出式UI对话框,询问用户是否允许将dApp连接到MetaMask。

它应该是有效的。让我知道:)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68324845

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档