Passing wallet argument in ethers Contract function - ethereum

I am trying to create an instance of a contract on ethers.
const example = new ethers.Contract(CONTRACT_ADDRESS, contractABI, signer);
I am using a wallet directly instead of getting a signer through metamask ( I am aware of the risks)
Here is my "signer":
const signer = new ethers.Wallet("PRIVATE_KEY");
When i try to execute the code I get:
ethers-5.5.4.esm.min.js:1 Uncaught (in promise) Error: invalid address or ENS name (argument="name", value={"_isSigner":true,"address":"0x92388d12744B418eFac8370B266D31fd9C.....","provider":null}, code=INVALID_ARGUMENT, version=contracts/5.5.0)
Do I have a syntax error? or is this not the correct way to pass a wallet as a signer

I think you might miss your provider there, you'll need to add provider object like this
const url = "RPC Node URL"
const provider = new ethers.providers.JsonRpcProvider(url);
const signer = new ethers.Wallet("PRIVATE_KEY", provider);
Use the right RPC Node network to interact with the right blockchain. You can either use public or private RPC, but for production it is recommended to use private services.

You did not connect to the signer. From docs
// this creates a new contract address
new ethers.Contract( address , abi , signerOrProvider )
// Returns a new instance of the Contract, but connected to providerOrSigner.
contract.connect( providerOrSigner ) ⇒ Contractsource
In your code:
example.connect(signer)

Related

Ethers.js metamask request limit exceeded

I’m trying to connect to contracts on BSC, it worked fine for half a year, now it’s starting to give errors, it’s with contract.on, when reading something from the contract it works fine
To connect the provider and the signer to work with contracts, I used the default entry for connecting to the metamask from the ethers.js documentation:
const provider = new ethers.providers.Web3Provider(window.ethereum); const signer = provider.getSigner();
started getting errorenter image description here
tried doing this:
await window.ethereum.enable() const provider = new ethers.providers.Web3Provider(window.ethereum); const signer = provider.getSigner();
I also tried to connect via rps, but it didn’t happen at all what I needed:
export const provider = new ethers.providers.JsonRpcProvider(settings.bsc.rpcNodeUrl); export const wallet = new ethers.Wallet(settings.wallet.privateKey, provider) export const signer = wallet.connect(provider);
You need to get a paid RPC node.
Binance has cut down the APIs and limits of free nodes.
Even better run your own node.

Cannot switch signers with ethers.js for a contract interaction using Hardhat

Hardhat specifies that to use a different account for contract interactions you should use the connect() method, passing it a Signer, as such:
const [owner, addr1] = await ethers.getSigners();
/* ... */
await greeter.connect(addr1).setGreeting("Hello!");
Where greeter is the contract instance.
However, when I use a Signer as they specify to, I get the following error:
Error: invalid address or ENS name (argument="name", value="<SignerWithAddress 0x59F...34C>", code=INVALID_ARGUMENT, version=contracts/5.6.0)
The internet says to use an address, such as this issue suggesting to use something like addr1.address. But when I do, the following error results:
VoidSigner cannot sign transactions (operation="signTransaction", code=UNSUPPORTED_OPERATION, version=abstract-signer/5.6.0)
How can I switch signers/accounts when making contract calls with ethers.js and Hardhat?
The error you get is because you are not passing in the full address object.
Specifically, I get your exact error when I do this:
This does not work, but reproduces your error:
[deployer, account1] = await ethers.getSigners();
address1 = account1.address;
/* ... */
await greeter.connect(address1).setGreeting("Hello!");
This works, however:
[deployer, account1] = await ethers.getSigners();
/* ... */
await greeter.connect(account1).setGreeting("Hello!");
Notice that we do not call ".address" on account1 in the second example.

How do I solve the Smart Contract error "returned values aren't valid"?

I am trying to read basic information from a smart contract using web3.js (GRAPH Token):
https://etherscan.io/address/0xc944e90c64b2c07662a292be6244bdf05cda44a7#code
This is my super simple react web3.js setup:
import Web3 from 'web3';
...
useEffect(() => {
const start = async () => {
const web3 = new Web3('https://bsc-dataseed1.binance.org:443')
const abi = [{"inputs":[{"internalType":"uint256","name":"_initialSupply","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"}],"name":"MinterAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"}],"name":"MinterRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"}],"name":"NewOwnership","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"}],"name":"NewPendingOwnership","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[],"name":"acceptOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_account","type":"address"}],"name":"addMinter","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"burn","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"burnFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"subtractedValue","type":"uint256"}],"name":"decreaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"governor","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"addedValue","type":"uint256"}],"name":"increaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_account","type":"address"}],"name":"isMinter","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_to","type":"address"},{"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"mint","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pendingGovernor","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address","name":"_spender","type":"address"},{"internalType":"uint256","name":"_value","type":"uint256"},{"internalType":"uint256","name":"_deadline","type":"uint256"},{"internalType":"uint8","name":"_v","type":"uint8"},{"internalType":"bytes32","name":"_r","type":"bytes32"},{"internalType":"bytes32","name":"_s","type":"bytes32"}],"name":"permit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_account","type":"address"}],"name":"removeMinter","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"renounceMinter","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_newGovernor","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"}]
const address = '0xc944E90C64B2c07662A292be6244BDf05Cda44a7'
const contract = new web3.eth.Contract(abi, address)
console.log(contract);
const i = await contract.methods.getName().call()
console.log(i); // => ERROR
}
start()
}, [])
And it throws error:
Error: Returned values aren't valid, did it run Out of Gas? You might also see this error if you are not using the correct ABI for the contract you are retrieving data from, requesting data from a block number that does not exist, or querying a node which is not fully synced.
This is a known and misleading error which usually means that the address or the contract abi is invalid but I verified it is correct.
I researched this error for two days but didn't manage to solve this issue... any suggestions?
You're trying to interact with an Ethereum contract, using a BSC (Binance Smart Chain) Web3 provider (in your case https://bsc-dataseed1.binance.org:443). This results in trying to call the getName() function on the BSC address (which doesn't contain any contract).
Ethereum and BSC are different networks, unrelated to each other.
Solution: Use an Ethereum mainnet provider (for example Infura is widely used).

Error: personal_unlockAccount method not implemented

I'm testing with nethereum(.Net integration library for Ethereum) trying to unlock account API on testrpc with following code:
var ipcClient = ClientFactory.GetClient();
var web3 = new Web3(ipcClient);
// Unlock the caller's account with the given password
var unlockResult = await web3.Personal.UnlockAccount.SendRequestAsync(publicKey, password, _accountUnlockTime);
return unlockResult;
I have executed testrpc on powershell, and have 10 default accounts created by testrpc, and want to unlock on of them.
calling this method i get following exception:
Error: RPC method personal_unlockAccount not supported.
Testrpc does not have the capability to unlock accounts, this is specific of a client like Geth.

Fetching access token from refresh token using Java

I got the refresh token and access token from the authorization code by using the sample program given here https://developers.google.com/drive/credentials#retrieve_oauth_20_credentials
But there is no sample program to get the access token from refresh token i.e., when we dont have authorization code. Any pointers? Is there any way to Instantiate a drive service object using only refresh token and access token?
The DrEdit Java sample has an example on how to retrieve stored Credentials from the Google App Engine Datastore.
If using another type of credentials store, you can use the following code to instantiate new OAuth 2.0 Credentials using stored tokens:
GoogleCredential credentials = new GoogleCredential.Builder()
.setClientSecrets(CLIENT_ID, CLIENT_SECRET)
.setJsonFactory(jsonFactory).setTransport(transport).build()
.setRefreshToken("<REFRESH_TOKEN>").setAccessToken("<ACCESS_TOKEN>");
EDIT: Corrected a typo in the code.
Try this code. This is a mix solution from Alain + https://cloud.google.com/bigquery/authorization. this worked for me.
GoogleCredential credential = createCredentialWithRefreshToken(
HTTP_TRANSPORT, JSON_FACTORY, new TokenResponse().setRefreshToken(refreshToken));
credential.refreshToken();
String newAccessToken = credential.getAccessToken();
public static GoogleCredential createCredentialWithRefreshToken(HttpTransport transport,
JsonFactory jsonFactory, TokenResponse tokenResponse) {
return new GoogleCredential.Builder().setTransport(transport)
.setJsonFactory(jsonFactory)
.setClientSecrets(CLIENT_ID, CLIENT_SECRET)
.build()
.setFromTokenResponse(tokenResponse);
}
Just to explain my experience.
Had the same problem (access token to null) the problem was that I had been tested without sending setAccessType ("offline") and from the account access was allowed access.
Then I put on my code setAccessType ("offline") code but still refresh token to null.
My solution was to revoke permission from the account I want to access (https://accounts.google.com/b/0/IssuedAuthSubTokens?hl=en). In the next test I grant it.
Follow this example:
private static void getAccessTokenFromRefreshToken() throws IOException {
GoogleCredential credentials = new GoogleCredential.Builder()
.setClientSecrets(CLIENT_ID, CLIENT_SECRET)
.setJsonFactory(JSON_FACTORY).setTransport(httpTransport).build()
.setRefreshToken(REFRESH_TOKEN);
String accessToken = credentials.getAccessToken();
System.out.println("Access token before: " + accessToken);
credentials.refreshToken();
accessToken = credentials.getAccessToken();
System.out.println("Access token after: " + accessToken);
}
Output:
Access token before: null
Access token after: ya29.u4HC22-Avc0aaDC0g0zj1jhz2yjsJrm8qm0hU2eVeBrf6DKj3CcHDQ42KARH4y_d364-b