Solana web3 js failed to get recent blockhash error 403 - web3js

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.

Related

Error "invalid_grant" after using msal token from msal-react

I need your help with an unreachable error when msal token expire, specifically an invalid_grant error. I have a exception but this error only is showing on console. Thanks you
const refreshToken = async () => {
const request = {
account: account,
scopes: ["https://graph.microsoft.com/User.Read"],
};
try {
const response = await instance.acquireTokenSilent(request);
localStorage.setItem("accessToken", response.accessToken);
setToken(response.accessToken);
} catch (e) {
console.log(e);
const isServerError = e instanceof ServerError;
const isInteractionRequiredError = e instanceof InteractionRequiredAuthError;
const isInvalidGrantError = (e.errorCode === "invalid_grant");
if (isInteractionRequiredError) {
try {
const response = await instance.acquireTokenRedirect(request);
localStorage.setItem("accessToken", response.accessToken);
setToken(response.accessToken);
return;
} catch (e) {
console.log("InteractionRequiredAuthError:" + e);
handleError(e);
}
}
if (isServerError && isInvalidGrantError && !isInteractionRequiredError) {
localStorage.clear();
window.location.reload();
}
}
};
I tried to catch that error but it was not possible

db transactions and mongodb in particular

I have a general question about DB transactions and specifically mongo DB.
Is the following code safe in terms of read and write operations?
import { MongoClient, ObjectId } from "mongodb";
const CONNECTION = "mongodb+srv://...";
const client = new MongoClient(CONNECTION);
const con = await client.connect();
const session = con.startSession();
try {
await session.withTransaction(
async () => {
const _id = new ObjectId("...");
const col = con.db("purchases").collection("collection");
// READ
const purchase = await col.findOne({ _id }) as any;
if (purchase.test) {
// WRITE
await col.updateOne({ _id }, { $set: { test: false } });
}
},
{ readConcern: "majority", writeConcern: { w: "majority" } }
);
} finally {
await session.endSession();
await client.close();
}
I know that I can also achieve this functionality using findOneAndUpdate but I'm interested in the transactions specifically.

Why whenever I type something that does not exist, i got this error?

Whenever I type something that does not exist in the json I got this error:
TypeError: countries.map is not a function
The search functionality works fine until I type in a result that doesn't exist.
const mainUrl = `https://restcountries.eu/rest/v2/`
const all = `${'all'}`
const serachUrl = `${'name/'}`
const Home = () => {
// usesstate to conutries
const [countries, setCountries] = useState([])
// usesstate to query
const [query, setQuery] = useState('')
{
/* // fetch countries */
}
const fetchCountries = async () => {
let url
if (query) {
url = `${mainUrl}${serachUrl}${query}`
} else {
url = `${mainUrl}${all}`
}
try {
const response = await fetch(url)
const data = await response.json()
setCountries(data)
} catch (error) {
console.log(error)
}
}
useEffect(() => {
fetchCountries()
}, [query])
Issue
When you search for something that doesn't exist the API is returning an error object, a 404.
{
"status": 404,
"message": "Not Found"
}
This is stored in countries state and you then attempt to map it, OFC throwing the error.
Solution
Checking that the fetch was successful
A fetch() promise will reject with a TypeError when a network error is
encountered or CORS is misconfigured on the server-side, although this
usually means permission issues or similar — a 404 does not constitute
a network error, for example. An accurate check for a successful
fetch() would include checking that the promise resolved, then
checking that the Response.ok property has a value of true.
The fetch API returns a resolved Promise even for 400 responses. You should check that the request was successful.
const fetchCountries = async () => {
let url;
if (query) {
url = `${mainUrl}${serachUrl}${query}`;
} else {
url = `${mainUrl}${all}`;
}
try {
const response = await fetch(url);
if (!response.ok) { // <-- check OK response
throw new Error("Network response was not ok");
}
const data = await response.json();
setCountries(data);
} catch (error) {
console.log(error);
}
};

React Native Async Axios not responding

I've got JWT logging and I'm trying to get the user by token
export const authTokenLogin = async (token) => {
let extra_url = `jwttokenlogin`;
try {
console.log("Break Point 1");
const response_user = await Axios.post(BASE_URL + extra_url, null, {
params: {
token,
},
});
console.log(response_user.data);
return response_user.data;
} catch (e) {
console.log("Break Point 2");
console.log(e.response.status);
return null;
}
};
all worked fine until few days ago from reason yet to be discovered
now it gets to "Break Point 1" and stock there, not reaching "Break Point 2" or "Break Point 3"
just stock and heat up my phone
I've manage to get the token from
export const authLogin = async (email, password, rememberMe) => {
var formData = new FormData();
formData.append("email", email);
formData.append("password", password);
formData.append("remember_me", rememberMe);
try {
return await Axios.post(BASE_URL + "jwtlogin", formData).then((res) => {
return res.data.data;
});
} catch (e) {
return e.response.status;
}
};
So the server is alive and responding
looking for solution , Thanks

Getting "#ReferenceError: connection is not defined"

I've been using the code from discord.js guide and keep getting this error when I try to make it join
Here's my code:
const Discord = require('discord.js');
const client = new Discord.Client();
const PREFIX = '%';
const request = require('request');
const cheerio = require('cheerio');
var servers = {};
client.on('ready', () => {
console.log('This client is online!');
})
client.on('message', message => {
let args = message.content.substring(PREFIX.length).split(" ");
switch (args[0]) {
case 'image':
var imreq = (args[1])
image(message, imreq);
break;
case 'bruh':
client.on('message', async message => {
// Join the same voice channel of the author of the message
if (message.member.voice.channel) {
const connection = await message.member.voice.channel.join();
}
});
const dispatcher = connection.play('C:\Users\jayja\Downloads\Bruh Sound Effect 2.mp3 ');
dispatcher.on('start', () => {
console.log('audio.mp3 is now playing!');
});
dispatcher.on('finish', () => {
console.log('audio.mp3 has finished playing!');
});
// Always remember to handle errors appropriately!
dispatcher.on('error', console.error);
break;
}
});
function image(message, imreq) {
var options = {
url: "http://results.dogpile.com/serp?qc=images&q=" + imreq,
method: "GET",
headers: {
"Accept": "text/html",
"User-Agent": "Chrome"
}
};
request(options, function(error, response, responseBody) {
if (error) {
return;
}
$ = cheerio.load(responseBody);
var links = $(".image a.link");
var urls = new Array(links.length).fill(0).map((v, i) =>
links.eq(i).attr("href"));
console.log(urls);
if (!urls.length) {
return;
}
// Send result
message.channel.send(urls[Math.floor(Math.random() * urls.length)]);
});
}
client.login(token)
Heres a screenshot of the terminal:
Screenshot
So like I guessed, you don't need to listen to the message event of the client. You already have the message object via the initial command trigger.
if (message.member.voice.channel) {
const connection = await message.member.voice.channel.join();
const dispatcher = connection.play('C:\Users\jayja\Downloads\Bruh Sound Effect 2.mp3 ');
dispatcher.on('start', () => {
console.log('audio.mp3 is now playing!');
});
dispatcher.on('finish', () => {
console.log('audio.mp3 has finished playing!');
});
// Always remember to handle errors appropriately!
dispatcher.on('error', console.error);
}
This should be all you need. You also might find this guide interesting to read.

Resources