i am setting up react with ether.js and smart contract is deployed using hardhat on localhost network. React app is connected to metasmask using
const provider = new ethers.providers.Web3Provider(window.ethereum);
the contract is written below
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "hardhat/console.sol";
contract Greeter {
string private greeting;
constructor(string memory _greeting) {
console.log("Deploying a Greeter with greeting:", _greeting);
greeting = _greeting;
}
function greet() public view returns (string memory) {
return greeting;
}
function setGreeting(string memory _greeting) public {
console.log("Changing greeting from '%s' to '%s'", greeting, _greeting);
greeting = _greeting;
}
}
i deployed this contract using npx hardhat run script.js.In the react code i am fetching contract object using
const erc20=new ethers.Contract(address,obj.abi,signer);
and in the useEffect i am trying to call erc20.greet()
which is giving error in console.
**
(in promise) Error: call revert exception (method="greet()", errorArgs=null, errorName=null, errorSignature=null, reason=null, code=CALL_EXCEPTION, version=abi/5.5.0)
**
You need to make sure these points:
Your Metamask extension is connecting to your hardhat localhost network.
When you run your React app in a browser with the Metamask extension installed, make sure that your Metamask is connecting to your hardhat localhost network (by default, it is localhost:8545). If Metamask is connecting to a different network, you will get that error.
(Note: Because the Metamask extension hides test networks by default, you will need to make it show test networks so that you can see your hardhat localhost network listed.)
Use the correct contract address.
When you start a hardhat local network, hardhat will return a list of accounts like this:
WARNING: These accounts, and their private keys, are publicly known. Any funds sent to them on Mainnet or any other live network WILL BE LOST.
Account #0: 0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266 (10000 ETH)
Private Key: 0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80
Account #1: 0x70997970c51812dc3a010c7d01b50e0d17dc79c8 (10000 ETH)
Private Key: 0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d
...
When you deployed that smart contract using hardhat on localhost network, hardhat will return something like this:
[contract-name] deployed to: [contract-address]
Make sure that you use that [contract-address] as the value of the address argument here:
const erc20=new ethers.Contract(address,obj.abi,signer);
A [contract-address] and an account look quite similar, but they represent two different things. If you use an account instead the [contract-address], you will get the error.
Related
I am getting this error message when trying to interact with my smart contract on my react front end. I am running localhost3000 and which requires metamask to sign in.
Unhandled Rejection (Error): call revert exception (method="symbol()", errorSignature=null, errorArgs=[null], reason=null, code=CALL_EXCEPTION, version=abi/5.0.8)
Logger.makeError
/Users/username/Desktop/final-4/src.ts/index.ts:205
Logger.throwError
/Users/username/Desktop/final-4/src.ts/index.ts:217
Interface.decodeFunctionResult
/Users/username/Desktop/final-4/src.ts/interface.ts:326
323 | eventFragment = this.getEvent(eventFragment);
324 | }
325 | const topics = [];
> 326 | const dataTypes = [];
| ^ 327 | const dataValues = [];
328 | if (!eventFragment.anonymous) {
329 | topics.push(this.getEventTopic(eventFragment));
View compiled
Contract.<anonymous>
/Users/username/Desktop/final-4/src.ts/index.ts:309
fulfilled
http://localhost:3000/static/js/0.chunk.js:5079:24
Also from the source tab in inspect:
Uncaught (in promise) Error: call revert exception (method="symbol()", errorSignature=null, errorArgs=[null], reason=null, code=CALL_EXCEPTION, version=abi/5.0.8)
Uncaught (in promise) Error: call revert exception (method="balanceOf(address)", errorSignature=null, errorArgs=[null], reason=null, code=CALL_EXCEPTION, version=abi/5.0.8)
Here is my directory structure:
client
|--node_modules
|-—public
|—-src
|—-contracts
|—-Address.json
|—-Context.json
|—-ERC20.json
|—-IERC20.json
|—-Migrations.json
|—-PreciousChicken.json
|——SafeMath.json
|—-App.css
|—-App.js
|—-App.test.js
|—-index.css
|—-logo.svg
|—-reportWebVitalls.js
|—-setupTests.js
|—-gitignore
|—-package-lock.json
|—-package.json
|—-yarn.lock
|—-contracts
|—-Migrations.sol
|—-MyPreciousToken
|—-migrations
|—-1_initial_migations.js
|—-2_deploy_contracts.js
|—-node-modules
|—-test
This error (CALL_EXCEPTION) happens when your smart contract is not deployed yet.
Wait the transaction ends:
await contract.deployTransaction.wait()
I got the same error because I was trying to use a contract's Ropsten address instead of it's Mainnet address. Make sure that whatever contract you're using is deployed and is on the correct network.
Connecting a proper test network in the wallet could prevent this issue while you are building a smart contract in the test network.
E.g for me, I had to connect Rinkeby network in the wallet, but actually pointing a main network.
For me the reason was when I redeployed the contract, the contract's json files generated in the build needed to be replaced in my react app as well.
Double check that your contract is deoloyed on what ever test network you are using !
I ran npx hardhat run scripts/deploy.js --network localhost while my testnet was running in a seperate terminal and, it fixed the error.
hope this helps anyone
First make sure your local blockchain network npx hardhat node is running in a separate terminal and access the local network console in a separate terminal npx hardhat console --network localhost.
If the error still pops up for the commands fired in the terminal of local network console, then
The way to resolve the issue is to check the logs presented in the terminal where your local blockchain network is running.
For my case I created the contract instance with wrong address. And every time I did try to execute the functions of the contract instance created with wrong address, for each execution there was a log in the terminal running the local blockchain network as :
WARNING: Calling an account which is not a contract
From: 0xf39fd6e51aad88f......................266
To: 0xf39fd6e51aad88f......................266
Try to deploy the main contract again.
Run the below commands in separate terminals parallelly
npx hardhat node
npx hardhat run scripts/deploy.js --network localhost
I got this error when trying to access an element of a public array that didn't exist. The array had only one element inside so I had to change from index 1 to 0.
const elIndex = ethers.BigNumber.from(0);
await ExampleContract.nfts(elIndex);
```
Trying to Run a Script in Luna Eclipse using IE Driver
and getting the following error:
Exception in thread "main" org.openqa.selenium.remote.UnreachableBrowserException: Could not start a new session. Possible causes are invalid address of the remote server or browser start-up failure. Here is the code trying to Run:
package com.newpack;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
public class SecondClass {
public static void main(String[] args)
{
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability("requireWindowFocus", true);
capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
capabilities.setCapability(InternetExplorerDriver.INITIAL_BROWSER_URL,"https://www.google.co.in");
System.setProperty("webdriver.ie.driver","M:\\workspace\\IEDriver.exe");
WebDriver driver ;
driver = new InternetExplorerDriver(capabilities);
String baseUrl = "https://www.google.co.in";
driver.get(baseUrl);
String expectedTitle = "Google";
String actualTitle = "";
actualTitle = driver.getTitle();
if (actualTitle.contentEquals(expectedTitle)){
System.out.println("Test Passed!");
} else {
System.out.println("Test Failed");
}
driver.close();
System.exit(0);
}
}
try once following steps
Got to
internet options>>Security>>
click on:"Reset all zones to default level"
ensure that the 'Enable protected mode' checkbox is ticked for all the four zones. Like i.e Internet, Local internet, Trusted Sites, Restricted Sites.
Internet Explorer needs to be configured first in order to successfully run a selenium script.
Make sure you complete all the following steps:
Go to Internet Options > Security and enable "Protected Mode" for all the 4 zones: Internet, Local internet, Trusted Sites, Restricted Sites.
Also, click on Custom Level for all 4 zones and reset Recent Custom Settings to same level, say "Medium" or "High".
If this does not work, please update your IEDriverServer from Selenium Official Downloads
Trying to figure out the best way to test PubSub push endpoints locally. We tried with ngrok.io, but you must own the domain in order to whitelist (the tool for doing so is also broken… resulting in an infinite redirect loop). We also tried emulating PubSub locally. I am able to publish and pull, but I cannot get the push subscriptions working. We are using a local Flask webserver like so:
#app.route('/_ah/push-handlers/events', methods=['POST'])
def handle_message():
print request.json
return jsonify({'ok': 1}), 200
The following produces no result:
client = pubsub.Client()
topic = client('events')
topic.create()
subscription = topic.subscription('test_push', push_endpoint='http://localhost:5000/_ah/push-handlers/events')
subscription.create()
topic.publish('{"test": 123}')
It does yell at us when we attempt to create a subscription to an HTTP endpoint (whereas live PubSub will if you do not use HTTPS). Perhaps this is by design? Pull works just fine… Any ideas on how to best develop PubSub push endpoints locally?
Following the latest PubSub library documentation at the time of writing, the following example creates a subscription with a push configuration.
Requirements
I have tested with the following requirements :
Google Cloud SDK 285.0.1 (for PubSub local emulator)
Python 3.8.1
Python packages (requirements.txt) :
flask==1.1.1
google-cloud-pubsub==1.3.1
Run PubSub emulator locally
export PUBSUB_PROJECT_ID=fake-project
gcloud beta emulators pubsub start --project=$PUBSUB_PROJECT_ID
By default, PubSub emulator starts on port 8085.
Project argument can be anything and does not matter.
Flask server
Considering the following server.py :
from flask import Flask, jsonify, request
app = Flask(__name__)
#app.route('/_ah/push-handlers/events', methods=['POST'])
def handle_message():
print(request.json)
return jsonify({'ok': 1}), 200
if __name__ == "__main__":
app.run(port=5000)
Run the server (starts on port 5000) :
python server.py
PubSub example
Considering the following pubsub.py :
import sys
from google.cloud import pubsub_v1
if __name__ == "__main__":
project_id = sys.argv[1]
# 1. create topic (events)
publisher_client = pubsub_v1.PublisherClient()
topic_path = publisher_client.topic_path(project_id, "events")
publisher_client.create_topic(topic_path)
# 2. create subscription (test_push with push_config)
subscriber_client = pubsub_v1.SubscriberClient()
subscription_path = subscriber_client.subscription_path(
project_id, "test_push"
)
subscriber_client.create_subscription(
subscription_path,
topic_path,
push_config={
'push_endpoint': 'http://localhost:5000/_ah/push-handlers/events'
}
)
# 3. publish a test message
publisher_client.publish(
topic_path,
data='{"test": 123}'.encode("utf-8")
)
Finally, run this script :
PUBSUB_EMULATOR_HOST=localhost:8085 \
PUBSUB_PROJECT_ID=fake-project \
python pubsub.py $PUBSUB_PROJECT_ID
Results
Then, you can see the results in Flask server's log :
{'subscription': 'projects/fake-project/subscriptions/test_push', 'message': {'data': 'eyJ0ZXN0IjogMTIzfQ==', 'messageId': '1', 'attributes': {}}}
127.0.0.1 - - [22/Mar/2020 12:11:00] "POST /_ah/push-handlers/events HTTP/1.1" 200 -
Note that you can retrieve the message sent, encoded here in base64 (message.data) :
$ echo "eyJ0ZXN0IjogMTIzfQ==" | base64 -d
{"test": 123}
Of course, you can also do the decoding in Python.
This could be a known bug (fix forthcoming) in the emulator where push endpoints created along with the subscription don't work. The bug only affects the initial push config; modifying the push config for an existing subscription should work. Can you try that?
I failed to get PubSub emulator to work on my local env (fails with various java exceptions). I didn't even get to try various features like push with auth, etc. So I end up using ngrok to expose my local dev server and used the public https URL from ngrok in PubSub subscription.
I had no issue with whitelisting and redirects like described in the Q.
So might be helpful for anyone else.
I am trying to run the guestbook application https://developers.google.com/appengine/docs/java/gettingstarted/creating but getting error:
Error screenshot at the url http://goo.gl/rw0dnR
FATAL ERROR in native method: JDWP No transports initialized, jvmtiError=AGENT_ERROR_TRANSPORT_INIT(197)
ERROR: transport error 202: connect failed: Connection timed out
ERROR: JDWP Transport dt_socket failed to initialize, TRANSPORT_INIT(510)
JDWP exit error AGENT_ERROR_TRANSPORT_INIT(197): No transports initialized [../../../src/share/back/debugInit.c:741]
I tried it on Eclipse. In Eclipse I click Run menu and then "Debug As"->"Web application". The error popup says:
Problem Occurred: 'Launching Guestbook' has encountered a
problem.Cannot connect to VM. (Cannot connect to VM
com.sun.jdi.connect.TransportTimeoutException)
Could anyone help me troubleshhot.
The code is:
package guestbook;
import java.io.IOException;
import javax.servlet.http.*;
public class GuestbookServlet extends HttpServlet {
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/plain");
resp.getWriter().println("Hello, world");
}
}
The code looks fine and it evidently compiles without error. The problem appears to be rather low down in the run time environment of Eclipse, the AppEngine development environment or the Jetty web application server.
I suggest uninstalling and re-installing Eclipse and the AppEngine SDK, or better still try with another computer.
Is another process listening on port 8888? On Windows use netstat -an at a command prompt to check.
You could try another port number. In Eclipse select Run, Debug Configurations..., your project name, Server. Change from 8888 and try again.
To prove that Eclipse is not the problem, temporarily use a fresh copy in a spare directory. Get it from from Eclipse Downloads, selecting "Eclipse IDE for Java EE Developers" and the appropriate 32 bit or 64 bit version. Add both the Google Plugin for Eclipse and App Engine Java SDK using the Eclipse Help -> Install new software... options, working with https://dl.google.com/eclipse/plugin/4.3 as the available software site.
I'm working on a JS based project that runs off GAE and part of the code gets the user's avatar using OAuth from Facebook, Twitter or Google. I'm trying to write tests in Mocha in order to test this but I'm running into some problems.
The code works when I test it in the front end, and the way I envisaged it to work would be to use ZombieJS to run the app on GAE's dev_appserver.py, fire the OAuth functions, fill in the appropriate auth stuff and then complete the test by returning the image URL.
However the first hurdle I've got is that it appears that NodeJS's server is not allowing GAE's server to run on the same IP address. For example:
exec 'dev_appserver.py .', ->
console.log arguments
This returns the error 'Address already in use'. How can I get around this apart from running it on a different machine? Is it possible to tell NodeJS to not reserve the whole IP and just a port? I'm running GAE on 8080 and it works fine when it isn't invoked by NodeJS.
The second problem is ZombieJS. I'm trying to figure out a way I can listen to when new windows are opened and, essentially, tail the console of the browser. I've started two discussions on the Google group but no one has responded yet (https://groups.google.com/forum/?hl=en#!topic/zombie-js/cJklyMbwxRE and https://groups.google.com/forum/?hl=en#!topic/zombie-js/tOhk_lZv5eA)
While the latter isn't as important as I can find ways around it (I hope), the former is the main issue, so I'd greatly appreciate any direction on how to resolve this address conflict.
Here's my NodeJS script:
exec = ( require 'child_process' ).exec
fs = require 'fs'
should = require 'should'
yaml = require 'yaml'
Zombie = require 'zombie'
common = require '../../static/assets/js/common'
url = 'ahmeds.local'
browser = new Zombie()
config = null
consoleCb = 'function consoleSuccess(){console.log("success",arguments)}function consoleFailure(){console.log("failure",arguments)}'
browser.debug = true
browser.silent = false
fs.readFile '../../config.yaml', (error, data) ->
config = yaml.eval data.toString 'ascii'
exec 'cd ../../ && dev_appserver.py -a ' + url + ' .', ->
console.log arguments
# browser.visit config.local.url, ->
browser.visit 'http://' + url + ':8080', ->
browser.evaluate consoleCb
browser.evaluate 'profileImage("facebook",consoleSuccess,consoleFailure)'
console.log browser.window.console.output
I have only limited familiarity with NodeJS, but I just tested running a NodeJS server and App Engine local dev server on the same machine — it works just fine. Without seeing your NodeJS code, I'm guessing you're also trying to run NodeJS on port 8080, and so the App Engine server complains when it's started (8080 is the default, and you noted it's the port you are using).
Try passing --port=8081 (or some other port) to your invocation of dev_appserver.py and it should resolve the conflict.
Nothing in the code you've shown (other than the invocation of dev_appserver) should even be listening on any port (unless zombie implements a "server" for remote debugging or something like that). It looks like the port conflict is coming from somewhere else.
Note that zombie's own Mocha test framework does set up an express server, so if you're using it or code lifted from it, that might be doing it.
What does netstat have to say about who's binding to what port?