const showAccount = document.querySelector('.showAccount');
const showBalance = document.querySelector('.showBalance');
const Web3 = require("web3");
getAccount();
getBalance();
getAccount returns the wallet id
async function getAccount() {
const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
const account = accounts[0];
showAccount.innerHTML = account;
}
getBalance returns undefined instead of the amount of Ether from Metamask
async function getBalance() {
const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
const account = accounts[0];
showBalance.innerHTML = account.balance;
}
Maybe someone knows a good API for retrieving more values than just these two with examples or got a nice video to learn from.
I found the properties for my accounts object: here
I customized your code and now it displays the amount of Ether from the Account:
const showAccount = document.querySelector('.showAccount');
const showBalance = document.querySelector('.showBalance');
getAccount();
loadBalance();
async function getAccount() {
const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
const account = accounts[0];
showAccount.innerHTML = account;
}
function loadBalance(){
web3Provider = null;
contracts = {};
account = '0x0';
const Web3 = require("web3");
const ethEnabled = async () => {
if (window.ethereum) {
await window.ethereum.send('eth_requestAccounts');
window.web3 = new Web3(window.ethereum);
return true;
}
}
if (typeof web3 !== 'undefined') {
// If a web3 instance is already provided by Meta Mask.
web3Provider = web3.currentProvider;
web3 = new Web3(web3.currentProvider);
} else {
// Specify default instance if no web3 instance provided
web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
web3 = new Web3(App.web3Provider);
}
$.getJSON("Market.json", function (market) {
console.log("initializing Market contract")
// Instantiate a new truffle contract from the artifact
contracts.Market = TruffleContract(market);
// Connect provider to interact with contract
contracts.Market.setProvider(web3Provider);
});
$.getJSON("Users.json", function (users) {
console.log("initializing User contract")
// Instantiate a new truffle contract from the artifact
contracts.Users = TruffleContract(users);
// Connect provider to interact with contract
contracts.Users.setProvider(App.web3Provider);
});
var marketInstance;
var userInstance;
var loader = $("#loader");
var content = $("#content");
//loader.show();
content.show();
// Load account data
console.log("loading account data")
var currentAccount;
web3.eth.getCoinbase(function (err, account) {
if (err === null) {
console.log("Your Account: " + account)
account = account;
currentAccount = account;
web3.eth.getBalance(account, function(err, balance) {
if (err === null) { //Note:set id="accountBalance" in your html page
$("#accountBalance").text(web3.fromWei(balance, "ether") + " ETH");
}
});
}
});
}
Related
reading through this resource, https://docs.metamask.io/guide/provider-migration.html#summary-of-breaking-changes, it seems it is still possible to interact with a contract using window.ethereum,
eg (taken from the above link)
const transactionHash = await ethereum.request({
method: 'eth_sendTransaction',
params: [
{
to: '0x...',
'from': '0x...',
value: '0x...',
// And so on...
},
],
});
but I cannot figure out how to connect to the contract.
What do Ireplace this with?
contract = await new window.web3.eth.Contract(ABI,ADDRESS);
I am using the web3 library via this resource
https://cdn.jsdelivr.net/npm/web3#latest/dist/web3.min.js
my simple script is below;
var account = null;
var contract = null;
const ABI = "the abi is here"
const ADDRESS = "contract address is here";
async function asyncCall() {
console.log('async');
if (window.ethereum) {
try {
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
account = accounts[0];
document.getElementById('wallet-address').textContent = account;
// this is the bit i'm stuck on currently
contract = await new window.web3.eth.Contract(ABI,ADDRESS);
//
var mintButton = document.getElementById('mint');
mintButton.addEventListener("click", function(){
console.log('minting');
contract.methods.mint(account).send({from:account,value:"100"});
});
var totalsupply = await contract.methods.totalsupply().call();
document.getElementById('ttt').textContent = totalsupply;
} catch (error) {
if (error.code === 4001) {
console.log('User rejected request');
}
console.log(error);
}
}
}
asyncCall();
So instead of using window.web3 since Metamask no longer injects it into webpages, you can do this before making the call to get the contract:
const Web3 = require('web3');
// Create Web3 instance
const web3 = new Web3(window.ethereum); // Where window.etherem is your provider.
You can then get your contract by calling:
const contract = new web3.eth.Contract(ABI, ADDRESS);
try this:
let provider = window.ethereum;
if (provider) {
await provider.request({ method: "eth_requestAccounts" });
this.web3 = new Web3(provider);
this.contract = new this.web3.eth.Contract(abi_v2, address);
}
I have a problem calling a read only function from my frontend. When I try to call it metamask ask me to pay gas fee
and the output of this transaction doesn't have any sense.
The solidity smart contract: https://rinkeby.etherscan.io/address/0xcf781c136ce1534d00db67c4ec488a6c4e01bbef
This is the solidity function : viewregistro
function compile_registro (string memory new_reg) public returns (bool registration){
registro[ultima] = new_reg;
ultima = ultima +1;
registration = true;
return registration;
}
function viewregistro(uint where) public view returns (string memory here){
here = registro[where];
return here;
}
This is the javascript code:
const enable = async () =>{
await window.ethereum.enable();
provider = new ethers.providers.Web3Provider(window.ethereum);
signer = await provider.getSigner();
address = await signer.getAddress();
console.log(provider);
return provider, signer, address
}
const contractConnection2 = async () => {
rank = new ethers.Contract( address_, rankingabi_ ,signer);
console.log(rank);
return rank;
}
const addmember = async() => {
rank.compile_registro("pluto");
}
i have issue on web3.eth.defaultAccount = web3.eth.getAccounts();
below is the code. it said Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'getAccounts')
the version of my web3 is "^1.3".
var contract = "";
if (typeof web3 !== 'undefined') {
console.log('inside web3')
Web3 = new Web3 (Web3.currentProvider);
} else {
console.log('else web3');
var web3 = new Web3(new Web3.providers.HttpProvider(provider));
}
window.ethereum.enable()
.then(function (accounts) {
console.log(accounts[0]);
web3.eth.defaultAccount = web3.eth.getAccounts();
var contractabi = web3.eth.contract([ABI])
function must be async
window.addEventListener("load", async () => {
// Modern dapp browsers...
if (window.ethereum) {
const web3 = new Web3(window.ethereum);
try {
// Request account access if needed
await window.ethereum.enable();
// Acccounts now exposed
resolve(web3);
} catch (error) {
reject(error);
}
}
try this to fit your case
if possible send me the complete implementation of this code, or you can add this
class App extends Component {
async UNSAFE_componentWillMount() {
await this.loadWeb3();
await this.loadBlockchainData();
}
async loadWeb3() {
if (window.ethereum) {
window.web3 = new Web3(window.ethereum);
await window.ethereum.enable();
} else if (window.web3) {
window.web3 = new Web3(window.web3.currentProvider);
} else {
window.alert('No ethereum broswer detected! You can check out MetaMask!');
}
}
async loadBlockchainData() {
const web3 = window.web3;
const account = await web3.eth.getAccounts();
this.setState({ account: account[0] });
const networkId = await web3.eth.net.getId();
}
}
please use async function to interact with web3 and await the response
I everyone, I'm trying to call a function called 'safeMint' on an ERC721 contract deployed on Rinkeby testnet but I'm getting this error:
Error: resolver or addr is not configured for ENS name (argument="name", value="", code=INVALID_ARGUMENT, version=contracts/5.5.0)
This is the code I'm using to call the function
const mintNFT = async () => {
const {ethereum} = window;
if(isMetaMaskInstalled) {
try {
const abi = require('../contracts/Animals.json').abi;
console.log(abi);
const accounts = await ethereum.request({ method: 'eth_accounts' });
setAccount(accounts[0]);
const web3Provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = web3Provider.getSigner();
const contractWrite = new ethers.Contract('0x53Ea14980c8326E93a9F72889171c1e03d4aD6Ce', abi, signer);
let trx = await contractWrite.safeMint(account, props.cidOfJsonInIpfs);
console.log(trx);
} catch(err) {
console.log(err);
}
}
}
I've tried to print the parameters passed but they seem to be right, what am I doing wrong?
I solved it with the following code
const mintNFT = async () => {
const {ethereum} = window;
if(isMetaMaskInstalled) {
try {
const abi = require('../contracts/Animals.json').abi;
console.log(abi);
const accounts = await ethereum.request({ method: 'eth_accounts' });
const web3Provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = web3Provider.getSigner(accounts[0]);
console.log(signer._address)
const contractWrite = new ethers.Contract('0x53Ea14980c8326E93a9F72889171c1e03d4aD6Ce', abi, signer);
let trx = await contractWrite.safeMint(accounts[0], `https://gateway.pinata.cloud/ipfs/${props.cidOfFile}`);
let receipt = await trx.wait();
console.log(receipt);
} catch(err) {
console.log(err);
}
}
What I was missing: I was using setState function to set the 'account' state variable with the first account of metamask, instead, I started using account[0] directly and it worked!
I will accept this as solution in 2 days
const NetworkToUse = process.env.REACT_APP_NETWORK;
const mnemonicWalletSubprovider = new MnemonicWalletSubprovider({
mnemonic: process.env.REACT_APP_MNEMONIC,
});
const infuraRpcSubprovider = new RPCSubprovider({
rpcUrl: `https://${NetworkToUse}.infura.io/v3/${process.env.REACT_APP_INFURA_KEY}`,
});
const providerEngine = new Web3ProviderEngine();
if (window.ethereum) {
providerEngine.addProvider(new SignerSubprovider(window.ethereum));
}
// providerEngine.addProvider(mnemonicWalletSubprovider);
providerEngine.addProvider(infuraRpcSubprovider);
providerEngine.start();
const seaport = new OpenSeaPort(
providerEngine,
{
networkName: NetworkToUse === "mainnet" ? Network.Main : Network.Rinkeby,
apiKey: process.env.REACT_APP_API_KEY,
},
(arg) => {
console.log("From OpenSeaPort CB:");
console.log(arg);
}
);
const placeBidMetaMask = async (order) => {
setIsProcessing(true);
if (typeof window.ethereum === "undefined") {
setError("Please make sure you have MetaMask installed!");
return;
}
if (!bidPrice || bidPrice < asset.price) {
setError("Insufficient Funds!");
return;
}
const { tokenId, tokenAddress } = order.asset;
try {
const [userAccount] = await window.ethereum.request({
method: "eth_requestAccounts",
});
const offer = await seaport.createBuyOrder({
asset: {
tokenId,
tokenAddress,
schemaName: asset.details.assetContract.schemaName,
},
accountAddress: userAccount,
startAmount: bidPrice,
});
console.log(offer);
setMessage("Buy Order Created");
} catch (err) {
setError(err.message);
console.log(err.message);
} finally {
setIsProcessing(false);
}
};
I am using metamask as wellet for bidding
Hi, I am using above code to place bid on opensea It is working but, I am using my personal MNEMONIC
But, in real time i can't get this from users meta mask wallet.
Is there any alternate way to place the bid.
I am using metamask as wellet for bidding
Hi, I am using above code to place bid on opensea It is working but, I am using my personal MNEMONIC
But, in real time i can't get this from users meta mask wallet.
Is there any alternate way to place the bid.