Send a transaction using web3js1.0: Error: Invalid JSON RPC response: "" - web3js

When I send a transaction to ethereum testnet rinkeby by infura node using web3js interface, I met the error "Error: Invalid JSON RPC responseļ¼š""". This is my source code :
let Web3 = require("web3");
if(typeof web3 !== 'undefined') {
web3 = new Web3(web3.currentProvider);
} else {
web3 = new Web3(new Web3.providers.HttpProvider("https://rinkeby.infura.io/v3/2f85c22a29994320b52da33bec96968d"));
}
let abi = "/abi/"
let address = "";
let contract = new web3.eth.Contract(abi, address);
contract.methods.set("JJJJJJJJJ").send({from: '0x1062024529684b1890b2fa5964334d8db7da2512'},function(err, txHash) {
if(err) {
console.log("err: " + err);
} else {
console.log(txHash);
}
});

Usually web3 initialization will take few mins, so please use await, async method for web3 initialization.
For example:
async function abc() {
web3 = await new Web3(new Web3.providers.HttpProvider("https://rinkeby.infura.io/v3/2f85c22a29994320b52da33bec96968d"));
}

Related

Solana web3 js failed to get recent blockhash error 403

I am trying to implement sendtransaction for phantom In my application.
here's my code:
sendTransaction(amount, depositWallet) { (async () => {
try {
const resp = await window.solana.connect();
this.wallet = resp;
this.signInTransactionAndSendMoney(amount, depositWallet);
console.log(amount, depositWallet)
} catch (err) {
console.log(err);
}
})();
},
signInTransactionAndSendMoney(amount, depositWallet) {
(async () => {
try {
const network = "https://api.mainnet-beta.solana.com";
const connection = new solanaWeb3.Connection(network);
const candidate = amount * solanaWeb3.LAMPORTS_PER_SOL;
const destPubkey = new solanaWeb3.PublicKey(depositWallet);
const instruction = solanaWeb3.SystemProgram.transfer({
fromPubkey: this.wallet.publicKey,
toPubkey: destPubkey,
lamports: candidate,
});
const trans = await this.setWalletTransaction(instruction, connection);
const signature = await this.signAndSendTransaction(this.wallet, trans, connection);
} catch (err) {
console.log(err);
}
})();
},
async setWalletTransaction(instruction, connection) {
const transaction = new solanaWeb3.Transaction();
transaction.add(instruction);
transaction.feePayer = this.wallet.publicKey;
const hash = await connection.getLatestBlockhash();
console.log(hash)
transaction.recentBlockhash = hash.blockhash;
return transaction;
},
async signAndSendTransaction(wallet, transaction, connection) {
// Sign transaction, broadcast, and confirm
const { signature } = await window.solana.signAndSendTransaction(transaction);
await connection.confirmTransaction(signature);
return signature;
},
but when im trying to send the transaction I get an error
Error: failed to get recent blockhash: Error: 403 : {"jsonrpc":"2.0","error":{"code": 403, "message":"Access forbidden, contact your app developer or support#rpcpool.com."}, "id": "001d039f-ad38-4942-a379-5db2f7951ebf" }
Changed to quicknode rpc url solved the problem.

Web3 error when trying to call contract methods

I encounter the following error while trying to run a dapp made using React, Truffle & Ganache. I'm also using web3 version 1.7.1. The problem is that the code enters in a catch(error) sequence of a try/catch and then displays what it is intended correctly. Why is this happening and why does the following error appears?
index.js:1 TypeError: Cannot read properties of undefined (reading 'methods')
at HomePage.componentDidMount
What the code should do: Display something like "Address is: 0x0D05b3220E9cC7A90623fc506cEB64Ab885FD6C6"
What the code does: It shows me the prompt "Failed to load web3, accounts, or contract. Check console for details" AND THEN "Address is: 0x0D05b3220E9cC7A90623fc506cEB64Ab885FD6C6"
The code is the following:
import React, { Component } from "react";
import MySmartContract from "../contracts/MySmartContract.json";
import getWeb3 from "../getWeb3";
//Importing components
class HomePage extends Component {
constructor(props) {
super(props);
this.state = {
ContractInstance: undefined,
account: null,
web3: null,
isOwner: false
}
}
componentDidMount = async () => {
// For refreshing the page a single time
// so that web3 and instance is loaded every time
if (!window.location.hash) {
window.location = window.location + '#loaded';
window.location.reload();
}
try {
// Get network provider and web3 instance.
const web3 = await getWeb3();
// Use web3 to get the user's accounts.
const accounts = await web3.eth.getAccounts();
// Get the contract instance.
const networkId = await web3.eth.net.getId();
const deployedNetwork = MySmartContract.networks[networkId];
const instance = new web3.eth.Contract(
MySmartContract.abi,
deployedNetwork && deployedNetwork.address,
);
// Set web3, accounts, and contract to the state, and then proceed with an
// example of interacting with the contract's methods.
this.setState({ ContractInstance: instance, web3: web3, account: accounts[0] });
const owner = await this.state.ContractInstance.methods.getOwnerAddress().call();
if (this.state.account === owner) {
this.setState({ isOwner: true });
}
} catch (error) {
// Catch any errors for any of the above operations.
alert(
`Failed to load web3, accounts, or contract. Check console for details.`,
);
console.error(error);
}
};
render() {
if (!this.state.web3) {
return (
<h1>
Loading Web3, accounts and contract...
</h1>
)
}
return (
<div><h1>Address is: {this.state.account}</h1></div>
)
}
}
export default HomePage;
The content of getWeb3.js is the following:
import Web3 from "web3";
const getWeb3 = () =>
new Promise((resolve, reject) => {
// Wait for loading completion to avoid race conditions with web3 injection timing.
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();
// Accounts now exposed
resolve(web3);
} catch (error) {
reject(error);
}
}
// Legacy dapp browsers...
else if (window.web3) {
// Use Mist/MetaMask's provider.
const web3 = window.web3;
console.log("Injected web3 detected.");
resolve(web3);
}
// Fallback to localhost; use dev console port by default...
else {
const provider = new Web3.providers.HttpProvider(
"http://127.0.0.1:8545"
);
const web3 = new Web3(provider);
console.log("No web3 instance injected, using Local web3.");
resolve(web3);
}
});
});
export default getWeb3;
This code seems to be wrong!
this.setState({ ContractInstance: instance, web3: web3, account: accounts[0] });
const owner = await this.state.ContractInstance.methods.getOwnerAddress().call();
You should not try to use state value as soon as you set up.
So you need to call your function in the second line like this:
const owner = await instance.methods.getOwnerAddress().call();
Injected connector code sample
const ConnectToInjected = async () => {
let provider = null;
if (typeof window.ethereum !== 'undefined') {
provider = window.ethereum;
try {
await provider.request({ method: 'eth_requestAccounts' })
} catch (error) {
throw new Error("User Rejected");
}
} else if (window.web3) {
provider = window.web3.currentProvider;
} else if (window.celo) {
provider = window.celo;
} else {
throw new Error("No Web3 Provider found");
}
return provider;
};
export default ConnectToInjected;
Usage:
const provider = await ConnectToInjected();
// Open metamask
await provider.request({ method: 'eth_requestAccounts' });
const web3 = new Web3(provider)

Accessing AsyncStorage react native

Hello I am new to react Native and I would like to access the user id that was stored to react Native storage so that I can pass it to the WebSocket connection but it is not returning the id
here is my sample code
import { io } from "socket.io-client/dist/socket.io";
import env from "../utils/env";
import AsyncStorage from "#react-native-async-storage/async-storage";
const getUserData = async () => {
try {
const value = await AsyncStorage.getItem("UserData");
if (value !== null) {
return value;
}
} catch (e) {
// remove error
}
console.log("Done.");
};
getUserData().then((res) => {
let response = JSON.parse(res);
console.log(response._id);
});
let socket = io(`${env.DEV_SERVER_URL}`, {
transports: ["websocket"],
query: `mobileId=${getUserData().then((res) =>{
let response = JSON.parse(res);
return response._id
})}`,
});
export default socket;
const storeData = async (data) =>{
await AsyncStorage.setItem('UserData', JSON.stringify(UserData));
}
try this to store your data you might have forgot to stringify your object before storing it

Walletconnect not firing App in mobile but redirect

i can't figured out why when i call a method with provider, walletconnect keeps redirecting me in https://link.trustwallet.com instead of open me the app to approve the transaction. I've wrote the code for metamask and walletconnect and i used ethersjs to handle the provider.
Here's code for connection
const getBlockchain = (typew) =>
new Promise(async (resolve) => {
var provider;
if(typew == "metamask"){
/* #ts-ignore */
if(window.ethereum) {
/* #ts-ignore */
await window.ethereum.enable();
/* #ts-ignore */
provider = new ethers.providers.Web3Provider(window.ethereum);
}
}
if(typew == "walletconnect"){
providerEth = new WalletConnectProvider({
chainId: 56,
rpc: {
56: "https://bsc-dataseed.binance.org",
}
});
await providerEth.enable();
provider = new ethers.providers.Web3Provider(providerEth);
provider.off("disconnect");
provider.on("disconnect", () => {
closeBlockhain();
})
}
if(provider !== undefined){
const signer = provider.getSigner();
/* #ts-ignore */
const signerAddress:any = await signer.getAddress();
const contract = new Contract(
Contract.networks[56].address,
Contract.abi,
signer
);
const contract_two = new Contract(
Contract_two.networks[56].address,
Contract_two.abi,
signer
);
configConnections = {
connected: true,
provider,
contract,
contract_two,
signerAddress: signerAddress
}
resolve(configConnections);
}
resolve(configConnections);
});
Here's the code for method
let test = await configConnections.contract.awardItem(ethers.utils.formatBytes32String("1"),res.data.hash);
Can't explain to myself why if i open the app on mobile and try to call method, the browser redirects me on other page not on the TrustWallet or Metamask App.
Thank you.

web3 react contract interaction

I am having some issues when calling a contract via form with React and Web3 component.
In my contract, I have a public function called GetDomainInfo which takes the domain as a parameter. You can view the contract here: https://ropsten.etherscan.io/address/0x756ad7f7c22e7c04a845bd8a138e455a1bc95f6f
The problem is that my components gets the form value, but when use it in a contract, gives the error:
Uncaught TypeError: Cannot read property 'GetDomainInfo' of undefined
Code:
GetInfo = (event) => {
event.preventDefault();
console.log(this.state.value);
const response = this.state.rouDomains.method.GetDomainInfo(this.state.value).send({from: this.state.account})
.once('receipt', (receipt) => {
console.log("receipt: ", receipt);
console.log(response);
})
}
The data arrives in console.log(this.state.value), I can see it.
EDIT: rouDomains is the async load data from web3.
async loadData() {
const web3 = new Web3(Web3.givenProvider || "http://localhost:8545");
const network = await web3.eth.net.getNetworkType();
this.setState({network});
//Fetch account
const accounts = await web3.eth.getAccounts();
this.setState({ account: accounts[0]});
//Load the contract
const rouDomains = new web3.eth.Contract(ROU_TLD, ROU_TLD_ADDRESS);
this.setState({ rouDomains });
console.log("ROU: ", rouDomains);
}
The answer was that I forgot a 's' for method in the below:
const response = this.state.rouDomains.method.GetDomainInfo(this.state.value).send({from: this.state.account})
const response = this.state.rouDomains.methods.GetDomainInfo(this.state.value).send({from: this.state.account})
Stupid rookie mistake :)

Resources