标签: web3js

如何在 web3.js 中正确使用恢复原因以在 UI 中显示有意义的错误消息

我想使用 web3.js 向用户显示恢复原因,例如,在用户尝试铸造已经铸造的 erc721 令牌的情况下。我正在使用 try catch 块并查看错误消息,但我想隔离错误消息以向用户显示有意义的原因。提前致谢。

ethereum web3js decentralized-applications

7
推荐指数
2
解决办法
6511
查看次数

如何获取ERC-721 tokenID?

我创建了一个部署在 ropston 网络上的 ERC-721 合约。使用合约我正在创建 NFT,它完全运行良好。

现在,对于转账部分,我需要获取任何 NFT 的 tokenID 并将其转账到其他地址,但每当我从 etherscan 或使用 web3 获取交易详细信息时,我都无法获取 tokenID。

我想将 tokenID 存储在数据库中,以便在转移到其他地址时可以使用它。

在此输入图像描述

我已经圈出了上图中所需的确切 tokenID。

我正在使用以下代码:

window.ethereum
    .request({
        method: 'eth_sendTransaction',
        params: [
            {
                from: fromAddress,
                to: contractAddress,
                gas: '50000',
                data: nftContract.methods.transferFrom(fromAddress, toAddress, tokenNumber).encodeABI()
            },
        ],
    })
Run Code Online (Sandbox Code Playgroud)

我只想在NFT创建时获取tokenID并将其存储到数据库中以供参考并执行业务逻辑。

function mintNFT(address recipient, string memory tokenURI)
        public onlyOwner
        returns (uint256)
    {
        _tokenIds.increment();

        uint256 newItemId = _tokenIds.current();
        _mint(recipient, newItemId);
        _setTokenURI(newItemId, tokenURI);

        return newItemId;
    }
Run Code Online (Sandbox Code Playgroud)

以上是负责创建 NFT 的 Solidity 函数。

javascript ethereum solidity web3js

7
推荐指数
2
解决办法
2万
查看次数

错误:返回错误:方法 eth_sendTransaction 不存在

我正在尝试使用以下代码将 erc20 代币从合约地址转移到 ETH 地址:

var _from = "from Address";
var contAddress = "contract address";
var _to = "to address";

var _Amount = '50';
var txnObject = {
    "from": _from,
    "to": _to,
    "value": web3.utils.toWei(_Amount, 'ether'),
    // "gas": 21000,         (optional)
    // "gasPrice": 4500000,  (optional)
    // "data": 'For testing' (optional)
    // "nonce": 10           (optional)
}

web3.eth.sendTransaction(txnObject, function (error, result) {
    if (error) {
        console.log("Transaction error", error);
    }
    else {
        var txn_hash = result; //Get transaction hash
        //$('#Tx').text(txn_hash);
        alert(txn_hash);
    }
});
Run Code Online (Sandbox Code Playgroud)

但我收到此错误:

交易错误 …

javascript ethereum web3js erc20

7
推荐指数
1
解决办法
9834
查看次数

MetaMask 与 Coinbase 钱包冲突

我正在尝试从我的 dapp 连接到元掩码。按照文档:https ://docs.metamask.io/guide/getting-started.html#connecting-to-metamask

但是当我调用eth_requestAccounts方法时,它也会打开 coinbase 弹出窗口。

如何解决这个问题?有什么建议么?

ethereum.request({ method: 'eth_requestAccounts' });
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

coinbase-api ethereum web3js metamask

7
推荐指数
1
解决办法
3286
查看次数

使用 web3 从网站断开钱包

我正在使用 web3 使用以下方法连接到元掩码

await window.ethereum.request({ method: 'eth_requestAccounts' });
var address = await window.ethereum.request({ method: 'eth_accounts' });
Run Code Online (Sandbox Code Playgroud)

但是当我刷新屏幕时它仍然显示为已连接,我无法在 web3 中找到任何方法将其与 pancackeswap 等网站断开连接

reactjs blockchain web3js metamask

6
推荐指数
1
解决办法
3871
查看次数

Web3js在Vue3组合api项目中导入失败

我用 . 创建了一个全新的项目npm init vite bar -- --template vue。我已经完成了npm install web3,我可以看到我package-lock.json包含这个包。我的node_modules目录还包括web3模块。

然后我将这一行添加到main.js

import { createApp } from 'vue'
import App from './App.vue'
import Web3 from 'web3'   <-- This line


createApp(App).mount('#app')
Run Code Online (Sandbox Code Playgroud)

我收到以下错误: 未捕获的引用错误:进程未定义

我不明白这是怎么回事。我对使用还很陌生npm,所以我不太确定要谷歌什么。错误来自node_modules/web3/lib/index.jsnode_modules/web3-core/lib/index.jsnode_modules/web3-core-requestmanager/lib/index.js、 最后node_modules/util/util.js。我怀疑这与以下之一有关:

  1. 我正在使用Vue 3
  2. 我正在使用 Vue 3 组合 API
  3. 我正在使用 Vue 3 Composition API SFC<script setup>标签(但我导入了它,main.js所以我不认为是这个)
  4. web3js在 Typescript 中,我的 Vue3 项目没有为 Typescript …

vue.js web3js vuejs3 vite

6
推荐指数
1
解决办法
5900
查看次数

使用 web3js 获取 uniswap 和 sushiswap 交易所上的代币价格,而无需使用他们的 api

我想使用 web.js 获取 uniswap 和 sushiswap 交易所的代币价格

我是加密开发世界的新手,所以请尽可能详细地说明,如果可能的话,一个例子将是我的救星。
这是我能拍出的最好的镜头...但不知道如何获得V3_pool_ABI价值

const JSBI = require('jsbi');
const Web3 = require('web3');

(async () => {
  const web3 = new Web3(new Web3.providers.HttpProvider('https://mainnet.infura.io/v3/d5658a9beace4cd98d2c1216cf66b56a'));
  
  var factoryV3 = new web3.eth.Contract(
    [{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint24","name":"fee","type":"uint24"},{"indexed":true,"internalType":"int24","name":"tickSpacing","type":"int24"}],"name":"FeeAmountEnabled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"oldOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnerChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"token0","type":"address"},{"indexed":true,"internalType":"address","name":"token1","type":"address"},{"indexed":true,"internalType":"uint24","name":"fee","type":"uint24"},{"indexed":false,"internalType":"int24","name":"tickSpacing","type":"int24"},{"indexed":false,"internalType":"address","name":"pool","type":"address"}],"name":"PoolCreated","type":"event"},{"inputs":[{"internalType":"address","name":"tokenA","type":"address"},{"internalType":"address","name":"tokenB","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"}],"name":"createPool","outputs":[{"internalType":"address","name":"pool","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"}],"name":"enableFeeAmount","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint24","name":"","type":"uint24"}],"name":"feeAmountTickSpacing","outputs":[{"internalType":"int24","name":"","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint24","name":"","type":"uint24"}],"name":"getPool","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"parameters","outputs":[{"internalType":"address","name":"factory","type":"address"},{"internalType":"address","name":"token0","type":"address"},{"internalType":"address","name":"token1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickSpacing","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_owner","type":"address"}],"name":"setOwner","outputs":[],"stateMutability":"nonpayable","type":"function"}], 
    '0x1F98431c8aD98523631AE4a59f267346ea31F984'
  );
  var pool_address = await factoryV3.methods.getPool('0x6b175474e89094c44da98b954eedeac495271d0f', '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', 3000).call();
  var pool_1 = new web3.eth.Contract(V3_pool_ABI, pool_address);
  var pool_balance = await pool_1.methods.slot0.call().call();
  var sqrtPriceX96 = pool_balance[0];
  var number_1 =JSBI.BigInt(sqrtPriceX96 *sqrtPriceX96* (1e18)/(1e18)/JSBI.BigInt(2) ** (JSBI.BigInt(192)));
})();
Run Code Online (Sandbox Code Playgroud)

javascript ethereum web3js erc20

6
推荐指数
1
解决办法
6771
查看次数

收到错误“未知”类型的参数不可分配给“错误 | 类型”的参数 无效的'

我对打字稿相当陌生,所以我收到一个错误,指出“未知”类型的参数不能分配给“错误 | 类型”的参数。null',我不明白为什么我会得到这个。我该如何解决这个问题?

export function subscribeToAccount(
  web3: Web3,
  callback: (error: Error | null, account: string | null) => any
) {
  const id = setInterval(async () => {
    try {
      const accounts = await web3.eth.getAccounts();
      callback(null, accounts[0]);
    } catch (error) {
      callback(error, null);
    }
  }, 1000);

  return () => {
    clearInterval(id);
  };
}

Run Code Online (Sandbox Code Playgroud)

typescript reactjs web3js

6
推荐指数
1
解决办法
1万
查看次数

如何通过 javascript 代码将元数据 json 上传到 IPFS 以及如何通过前端以编程方式生成此 URL

我已经开始研究如何使用 Solidity 和 IPFS 铸造 NFT。

项目流程为:

  1. 安装IPFS
  2. 通过IPFS上传资产照片并获取其哈希值
  3. metadata.json使用上面的哈希创建一个文件
{
  "name": "NFT",
  "description": "This image shows the true nature of NFT.",
  "image": "https://ipfs.io/ipfs/QmUnMkaEB5FBMDhjPsEtLyHr4ShSAoHUrwqVryCeuMosNr"
}
Run Code Online (Sandbox Code Playgroud)

4:将此json文件上传到IPFS并获取其哈希url

https://ipfs.io/ipfs/QmNSKewexhgY4rYwPoxPgNFN7BSjeiLXJif9q5FjeCrsmg
Run Code Online (Sandbox Code Playgroud)

5:创建solidity具有铸币功能的智能合约。使用 Polygon Mumbai 网络(使用 MATIC 令牌)进行部署。

 // SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
 
import "https://github.com/0xcert/ethereum-erc721/src/contracts/tokens/nf-token-metadata.sol";
import "https://github.com/0xcert/ethereum-erc721/src/contracts/ownership/ownable.sol";
 
contract newNFT is NFTokenMetadata, Ownable {
  constructor() {
    nftName = "Synth NFT";
    nftSymbol = "SYN";
  }

  function mint(address _to, uint256 _tokenId, string calldata _uri) external onlyOwner {
    super._mint(_to, _tokenId);
    super._setTokenUri(_tokenId, _uri);
  }
}
Run Code Online (Sandbox Code Playgroud)

6:部署智能合约后,NFT …

javascript solidity web3js

6
推荐指数
1
解决办法
7450
查看次数

未捕获的类型错误:https.Agent 不是构造函数

我正在使用react开发一个dapp,当我尝试使用HTTPS或HTTP的RPC实例化web3时出现错误。

错误如下:

未捕获的类型错误:https.Agent 不是构造函数

经过一些研究,我已经能够验证该错误来自 web3-providers-http 模块。

预期行为 当我配置 Metamask 提供程序 (window.ethereum) 时,一切正常。因为我可以进行写入和读取事务,在区块链上没有问题。我希望它能够正常工作,没有错误,并且可以进行交易。

重现步骤

var Web3 = require('web3');
var provider = 'https://mainnet.infura.io/v3/<PROJECT-ID>';
var web3Provider = new Web3.providers.HttpProvider(provider);
var web3 = new Web3(web3Provider);
web3.eth.getBlockNumber().then((result) => {
  console.log("Latest Ethereum Block is ",result);
});
Run Code Online (Sandbox Code Playgroud)

Web3.js 版本 1.7.4

维特版本3.0.0

环境 操作系统:macOs 11.5.2 浏览器:Chrome、Firefox Node.js 版本:v12.22.0 NPM 版本:7.7.6

javascript reactjs web3js vite

6
推荐指数
1
解决办法
3450
查看次数