I have deployed my ERC721 contract to Rinkeby TestNet. The contract has been deployed successfully. I unable to invoke transactions with MetaMask. Spent the whole day looking to resolve this issue. Found some answers stating it the issue with localhosted files or the web3.js doesn't work with MetaMask.
<script>
if (typeof web3 != 'undefined') {
web3 = new Web3(web3.currentProvider) // what Metamask injected
console.log("existing web3: provider " + typeof web3);
} else {
// Instantiate and set Ganache as your provider
web3 = new Web3(new Web3.providers.HttpProvider("https://rinkeby.infura.io/v3/api-key"));
console.log("new provider " + web3);
web3.eth.defaultAccount = web3.eth.accounts[0]
}
// The interface definition for your smart contract (the ABI)
var StarNotary = web3.eth.contract(
[contract-abi]
)
const starNotary = StarNotary.at('0x7cfAD6E80D992599d989166aABf536b21215544C')
function claimStar() {
web3.eth.getAccounts(function(error, accounts) {
if (error) {
hotsnackbar(false, error);
return
}
Uncaught Error: invalid address
at u (web3.min.js:1)
at inputTransactionFormatter (web3.min.js:1)
at web3.min.js:1
at Array.map ()
at i.formatInput (web3.min.js:1)
at i.toPayload (web3.min.js:1)
at _.e [as sendTransaction] (web3.min.js:1)
at c.sendTransaction (web3.min.js:1)
at index.html:589
at web3.min.js:1
Here is a complete demo which includes the introductory steps like authorizing the MetaMask contract and more.
https://fulldecent.github.io/spend-ERC20-create-ERC721/
Here is the particular code I think you will be interested in:
https://github.com/fulldecent/spend-ERC20-create-ERC721/blob/master/docs/index.html#L102-L114
if (window.ethereum) {
window.web3 = new Web3(ethereum);
$('#need-metamask').hide();
} else {
console.log('Non-Ethereum browser detected. Install MetaMask.');
return;
}
window.web3.version.getNetwork((err, netId) => {
if (netId == "3") {
$('#need-ropsten').hide();
}
});
https://github.com/fulldecent/spend-ERC20-create-ERC721/blob/master/docs/index.html#L121-L127
try {
await ethereum.enable();
$('#need-enable').hide();
} catch (error) {
console.log("ERROR: Enable account access and reload.");
return;
}
I too got the same problem while working on a DApp with Rinkeby testnet with Metamask.
When i had my web3.js file as below
import Web3 from 'web3';
let web3;
if (typeof window !== 'undefined' && typeof window.web3 !== 'undefined') {
// We are in the browser and metamask is running.
web3 = new Web3(window.web3.currentProvider);
} else {
// We are on the server *OR* the user is not running metamask
const provider = new Web3.providers.HttpProvider(
'Infura API key'
);
web3 = new Web3(provider);
//window.web3.currentProvider.enable();
}
export default web3;
and when i run
npm start or npm run dev ( depends on your start script)
The browser was throwing error saying "uncaught error: No 'from' address specified "
When i opened up the browser console and did web.currentProvider it threw the same error.
So one thing got clear that Metamask is not making contact with browser.
What i did is
I kept the Browser on with Metamask logged in.
And changed the web3.js to while the server running on command prompt and saved the file.
import Web3 from 'web3';
let web3;
if (typeof window !== 'undefined' && typeof window.web3 !== 'undefined') {
// We are in the browser and metamask is running.
//Note: change to window.web3.currentProvider.enable()
web3 = new Web3(window.web3.currentProvider.enable());
} else {
// We are on the server *OR* the user is not running metamask
const provider = new Web3.providers.HttpProvider(
'Infura API'
);
web3 = new Web3(provider);
//window.web3.currentProvider.enable();
}
export default web3;
As soon as you save the file
The Metamask throws you an prompt saying it want to make connection from your account.
Click yes.
and remove the .enable() from the above code and save your code.
This can be a temporary solution, but yes it works!
web3.js file
import Web3 from 'web3';
let provider;
// if on server or browser
if (typeof window !== 'undefined' && typeof window.web3 !== 'undefined') {
// we are in browser and metamask present
provider = window.web3.currentProvider;
}
else {
// we are on server OR metamask not present
provider = new Web3.providers.HttpProvider(
'https://rinkeby.infura.io/v3/API_KEY'
);
}
const web3 = new Web3(provider);
export default web3;
Do not put new Web3() in the if-blocks itself. After hosting (locally or on server) open metamask Settings -> Connections and add your site to give access to metamask.
Worked perfectly for me after spending days behind metamask and web3 errors!
Related
I'm trying to create a clone using OpenZeppelin Clones library. However, it seems that hardhat is not able to recognize the created clone contracts address.
The same code works on Remix, so does this have something to with Hardhat? NOTE: I have tried using Ganache as well, however it reverts with the same error.
Here is my factory contract:
contract WhoopyFactory {
address immutable implementationContract;
address[] public allClones;
event NewClone(address indexed _instance);
mapping(address => address) public whoopyList;
constructor() {
implementationContract = address (new Whoopy());
}
function createClone(address _whoopyCreator) payable external returns(address) { address clone = Clones.clone(implementationContract); Whoopy(clone).initialize(_whoopyCreator);
emit NewClone(clone);
return clone;
}
And here is the test I am running:
describe("Whoopy + WhoopyFactory", function () {
it("Initialises contract correctly", async function () {
const provider = new ethers.providers.JsonRpcProvider("HTTP://127.0.0.1:7545")
const deployer = provider.getSigner(0);
const player = provider.getSigner(1);
Whoopy = await ethers.getContractFactory("Whoopy")
whoopy = await Whoopy.deploy()
await whoopy.deployed()
WhoopyFactory = await ethers.getContractFactory("WhoopyFactory")
wf = await WhoopyFactory.deploy()
await wf.deployed()
wf.connect(player)
const tx = await wf.createClone("0x70997970C51812dc3A010C7d01b50e0d17dc79C8")
console.log(tx)
const txReceipt = await tx.wait(1)
console.log(txReceipt)
This is the error which reverts:
Error: Transaction reverted: function call to a non-contract account
at Whoopy.initialize (contracts/Whoopy.sol:117)
at <UnrecognizedContract>.<unknown> (0x9f1ac54bef0dd2f6f3462ea0fa94fc62300d3a8e)
As I said before, this code works correctly on Remix. Hope someone can point me in the right direction. Thanks in advance!
From what I understood, you are deploying a smart contract on Ganache, you can use hardhat's own local chain, by doing yarn chain, or npx hardhat node, and change the port to 8545.
You can make it more simpler by replacing the following
const provider = new ethers.providers.JsonRpcProvider("HTTP://127.0.0.1:7545")
const deployer = provider.getSigner(0);
const player = provider.getSigner(1);
with
const accounts = await hre.ethers.getSigners();
const deployer = accounts[0];
const player = accounts[1];
and while deploying use npx hardhat test --network localhost
Here is my contract
https://kovan.etherscan.io/address/0x9c08fb4e6666a796ef1ade3f58cb0a3e3f469e7c#code
I was trying to call the function in the contract by web3 ,for example:
//address and abi are copied from url above
let contractAddr = contract.address
let contractAbi = contract.abi
let web3 = new Web3(new Web3.providers.WebsocketProvider('wss://mainnet.infura.io/ws'))
if (typeof web3 !== 'undefined') {
web3 = new Web3(web3.currentProvider)
} else {
console.log('we need MetaMask')
}
let myContract = new web3.eth.Contract(contractAbi, contractAddr)
myContract.methods.name().call().then(console.log).catch(console.log)
I got this:
Error: ERROR: The returned value is not a convertible string:
However, if I copy the contract to
https://remix.ethereum.org/#optimize=true&version=soljson-v0.4.24+commit.e67f0147.js
and use ganache. Then my code would be:
//address and abi are copied from url above
let contractAddr = contract.address
let contractAbi = contract.abi
let url = contract.url //http://127.0.0.1:7545 provided by ganache
let web3
if (typeof web3 !== 'undefined') {
// web3 = new Web3(web3.currentProvider)
} else {
web3 = new Web3(new Web3.providers.HttpProvider(url))
}
let myContract = new web3.eth.Contract(contractAbi, contractAddr)
myContract.methods.name().call().then(console.log).catch(console.log)
In this case , I will get the right result 'MOMO'.
I would think infura works like ganache and I have tried other infura urls , but all failed.
I have metaMask in my chrome extension and use we web3#^1.0.0-beta.33.
How can I call the function in
https://kovan.etherscan.io/address/0x9c08fb4e6666a796ef1ade3f58cb0a3e3f469e7c#code
just like I call it in
https://remix.ethereum.org/#optimize=true&version=soljson-v0.4.24+commit.e67f0147.js
by ganache.
It looks like you're connected to mainnet instead of kovan:
let web3 = new Web3(new Web3.providers.WebsocketProvider('wss://mainnet.infura.io/ws'))
That should read:
let web3 = new Web3(new Web3.providers.WebsocketProvider('wss://kovan.infura.io/ws'))
I have recently ran into a bit of an issue with a solidity contract I created and am trying to deploy and interact with inside of the Remix IDE. The function I have written to return the address of the contract manager is as so
function getManager() public view returns(address){
return manager;
}
The way the contract manager is set is as so
function Contest() public {
manager = msg.sender;
}
I have created two JavaScript compile and deploy scripts which I run inside of my terminal. The deploy script is written as this
const HDWalletProvider = require('truffle-hdwallet-provider');
const Web3 = require('web3');
const {interface, bytecode} = require('./compile.js');
const provider = new HDWalletProvider(
'MetaMask Mnemonic',
'Infura endpoint key'
);
const web3 = new Web3(provider);
const deploy = async () => {
const accounts = await web3.eth.getAccounts();
console.log('deploying from ', accounts[0]);
const ABI = interface;
const deployedContract = await new web3.eth.Contract(JSON.parse(ABI))
.deploy({data: bytecode})
.send({
gas: '1000000',
from: accounts[0]
});
console.log('contract deployed to', deployedContract.options.address);
}
deploy();
Once my contract is deployed I receive the deployed address (something like 0xbc0370FbC085FAf053b418e6ff62F26ED2C7Dee1) and then I go over to the Remix IDE where I put in the address and use the Injected web3 option. However when I call the "getManager" function it returns an address of 0x0000000000000000000000000000000000000000 and I can't seem to get it to return the address of the manager. This method was working once before and I cannot seem to figure out why it's not working any longer.
I am using web3.js v1.0 with solidity ^0.4.17 with Ganache v1.1.0. I am trying to call a send transaction and it fails with the error message below.
Returned error: Error: Error: [ethjs-query] while formatting outputs
from RPC 'undefined' for method 'sendRawTransaction' Error:
[ethjs-format] hex string 'undefined' must be an alphanumeric 66 utf8
byte hex (chars: a-fA-F) string, is 0 bytes
MyContract.sol
function createStarCard(string name, uint price) public {
require(msg.sender == owner);
uint starCardId = starCards.push(StarCard(name, price));
starCardIdToOwner[starCardId] = owner;
}
App.js
createStarCard = ({ name, price }) => {
window.web3.eth.getAccounts().then((accounts) => {
this.state.ContractInstance.methods.createStarCard(name, price).send({
from: accounts[0],
gas: 300000,
}).then((receipt) => {
console.log(receipt)
}).catch((err) => {
console.log(err.message) <-- Caught error message
})
})
}
Google search results with the error message pointed me to the following issues, but they weren't helpful in my case:
https://github.com/MetaMask/metamask-extension/issues/1870
https://ethereum.stackexchange.com/questions/23679/callback-contain-no-result-error-error-ethjs-query-while-formatting-outputs
Update: sharing my constructor for App.js
constructor(props) {
super(props)
if (typeof window.web3 !== 'undefined') {
this.web3Provider = window.web3.currentProvider;
} else {
console.log("Use Ganache web3")
this.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
}
window.web3 = new Web3(this.web3Provider);
const contractAddress = "0x1bdaf0cd259887258bc13a92c0a6da92698644c0"
const ContractInstance = new window.web3.eth.Contract(Abi, contractAddress);
this.state = {
ContractInstance,
}
}
It looks like the problem is with the Ganache mac app. I solved this by using ganache-cli instead.
I solved this by reinstalling Metamask.
I'm trying to make my OpenShift Node.js app working, but the WS connection is not working. Client error is: connection refused.
Client side factory service:
var dataStream = $websocket(localStorageService.get('wsUrl'))
dataStream.onMessage(function(message) {
var call = JSON.parse(message.data)
if (fnMap[call.fn]) {
fnMap[call.fn](call.event, call.data)
}
})
dataStream.onError(function(err) {
console.log(err)
})
dataStream.onClose(function(event){
console.log('event: ' + JSON.stringify(event))
})
var fnMap = {
"broadcastResult": function(event, data) {
$rootScope.$broadcast(event, data)
}
}
var methods = {
callFn: function(paramJSON) {
dataStream.send(JSON.stringify(paramJSON));
}
}
return methods
I'm trying to connect on the following URL: ws://myapp-myname.rhcloud.com:8000
Could you please help?
Thank you in advance,
Csaba
First, you may want to make sure the websocket library, ws, is installed by declaring it in the dependencies section of your package.json and then doing another git push.
Otherwise, try the example provided in the openshift blog: https://blog.openshift.com/paas-websockets/
Specifically:
var websocket = new WebSocket("ws://myapp-myname.rhcloud.com:8000");
websocket.onopen = function(event) {
// The connection was opened
console.log(event)
};
websocket.onclose = function(event) {
// The connection was closed
console.log(event)
};
websocket.onmessage = function(event) {
// New message arrived
message = event.data
console.log(event)
};
websocket.onerror = function(event) {
// There was an error with your WebSocket
console.log(event)
};
The above at least might help point you toward a specific part of your code that's not working. Or, if the example isn't even working, it could be possibly something wrong with your cartridge, and you could try reaching out to RedHat's support.