Exception in fetchPairData() : call revert exception in method getReserves() - node.js

I am trying to call the "fetchPairData" function (https://uniswap.org/docs/v2/SDK/fetcher/) but I am getting the following error.
Error: call revert exception (method="getReserves()", errorSignature=null, errorArgs=[null], reason=null, code=CALL_EXCEPTION, version=abi/5.1.2)
at Logger.makeError (C:\Users\*\Desktop\ProyectoTransaccion\v2\node_modules\#ethersproject\logger\lib\index.js:180:21)
at Logger.throwError (C:\Users\*\Desktop\ProyectoTransaccion\v2\node_modules\#ethersproject\logger\lib\index.js:189:20)
at Interface.decodeFunctionResult (C:\Users\*\Desktop\ProyectoTransaccion\v2\node_modules\#ethersproject\abi\lib\interface.js:289:23)
at Contract.<anonymous> (C:\Users\*\Desktop\ProyectoTransaccion\v2\node_modules\#ethersproject\contracts\lib\index.js:329:56)
at step (C:\Users\*\Desktop\ProyectoTransaccion\v2\node_modules\#ethersproject\contracts\lib\index.js:48:23)
at Object.next (C:\Users\*\Desktop\ProyectoTransaccion\v2\node_modules\#ethersproject\contracts\lib\index.js:29:53)
at fulfilled (C:\Users\*\Desktop\ProyectoTransaccion\v2\node_modules\#ethersproject\contracts\lib\index.js:20:58)
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
reason: null,
code: 'CALL_EXCEPTION',
method: 'getReserves()',
errorSignature: null,
errorArgs: [ null ],
address: '0x80f836E71a6C92acebf6A49ad39038609c780070',
args: [],
transaction: {
data: '0x0902f1ac',
to: '0x80f836E71a6C92acebf6A49ad39038609c780070'
}
}
Relevant code:
const {ChainId, Token, TokenAmount, Fetcher, Pair, Route, Trade, TradeType, Percent} = require('#pancakeswap-libs/sdk');
const INPUT_TOKEN = new Token(ChainId.MAINNET,InputTokenAddr, 18);
const OUTPUT_TOKEN = new Token(ChainId.MAINNET, OutputTokenAddr, 18);
try {
pair = await Fetcher.fetchPairData(INPUT_TOKEN, OUTPUT_TOKEN, provider);
} catch (ex)
{
console.log("Debug.INPUT_TOKEN: " + JSON.stringify(INPUT_TOKEN));
console.log("Debug.OUTPUT_TOKEN: " + JSON.stringify(OUTPUT_TOKEN));
console.log("Debug.provider: " + JSON.stringify(provider));
console.log(ex)
pair = null;
}
Debug:
Debug.INPUT_TOKEN: {"decimals":18,"chainId":56,"address":"0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"}
Debug.OUTPUT_TOKEN: {"decimals":18,"chainId":56,"address":"0xe9e7CEA3DedcA5984780Bafc599bD69ADd087D56"}
Debug.provider: {"_isProvider":true,"_events":[],"_emitted":{"block":-2},"formatter":{"formats":{"transaction":{},"transactionRequest":{},"receiptLog":{},"receipt":{},"block":{},"blockWithTransactions":{},"filter":{},"filterLog":{}}},"anyNetwork":false,"_networkPromise":{},"_maxInternalBlockNumber":-1024,"_lastBlockNumber":-2,"_pollingInterval":4000,"_fastQueryDate":0,"connection":{"url":"https://bsc-dataseed.binance.org/"},"_nextId":45,"_eventLoopCache":{"detectNetwork":null,"eth_chainId":null},"_network":{"chainId":56,"name":"unknown"}}
I have verified that the swap works correctly in the pancakeswap web interface. It does not indicate route on the web, so it seems that it is a direct swap.
With other tokens the call returns what is expected. For example with the pair WBNB, BUSD.
I found for this error on another site with this comment
I faced the same issue and the problem was that I was trying to fetch
price for a pool that did not exist.
The pool exists. It has liquidity and it is also direct, it does not require a route.

The call revert exception happens when
the client doesn't receive a response
(no contract deployed on the address)
or when the contract code performs a revert.
pragma solidity ^0.8;
contract MyContract {
function foo() external view {
revert();
}
}
(Can also be when you're calling an undefined function and there's no fallback() in the contract)
Your question doesn't specify on which network you tried to perform the call, but there's no contract on the failing address on both mainnet and testnet.
So either your client app is trying to call this non-existing contract directly, or some contract in the chain of calls is trying to call it.
transaction: {
data: '0x0902f1ac',
to: '0x80f836E71a6C92acebf6A49ad39038609c780070'
}

me also facing the same issue for some tokens but i'm sure there is some issue in our end because some tokens have different routes for swapping. If token have different routes not direct swap that tokens will get same error.enter image description here

Related

Solace can't SEND while in WaitingForDNS

I'm trying send a message on a topic queue but the API returns
OperationError: Cannot perform operation SEND while in state WaitingForDNS
The URL can be pinged and it resolves to an IP address. I feel this message is misleading.
FWIW, I'm using Solace's Javascript API calling it from my Typescript code.
Below is code snippet. I've tried to remove irrelevant items such as the console logging. In short, it tests for a session already having been created, and if not, creates it using the Solace factory, then sets some event handlers which I think are irrelevant to this item
so I didn't include them. Because I don't catch any errors at connect() time, I presume it connected. Then when I try to send(), it suddenly is still waiting on the DNS. Or, at least, the error implies this.
class TopicPublisher {
private getSession() {
if (this.session == null) {
try {
this.log('Creating session for url=' + this.hosturl+' vpn='+this.vpn+' username='+this.username);
this.session = this.solace.SolclientFactory.createSession({
// solace.SessionProperties
url: this.hosturl,
vpnName: this.vpn,
userName: this.username,
password: this.pass,
});
// Set session event handlers
try {
this.session.connect();
} catch(error : any) {
this.log('Could not make connection to existing session. Error: '+error.toString());
this.session = null;
}
} catch (error: any) {
this.log(error.toString());
}
}
return this.session;
}
public publish(messageContent: any) {
var solaceMessage = this.getSolaceMessage(messageContent);
this.log('Publishing message "' + messageContent + '" to topic "' + this.topicName + '"...');
try {
// *************************
// This is where SEND fails
// *************************
this.getSession().send(solaceMessage);
this.log('Message published.');
} catch (error: any) {
this.log(error.toString());
}
};
}
An OperationError is thrown when you are attempting to execute a command on the session before it's actually up. What you can do here is only return this.session on session.on(solace.SessionEventCode.UP_NOTICE)
You can also see more info on this in the API docs and check out the note in the docs
Note: Before the session's state transitions to 'connected', a client
application cannot use the session; any attempt to call functions will
throw solace.OperationError.

TypeError : storage.getItem() is not a function - node-persist module

I'm using the node-persist module to persist some data. Have implemented the same using the below documentation
https://www.npmjs.com/package/node-persist/v/1.0.1
Version - "node-persist": "^3.1.0"
Below is my code
const storage = require('node-persist');
class NetworkClass {
public getNetworkIdentity = async (): Promise<any> => {
//My Business logic goes here
// Here I receive the identity with its expiry
await storage.init({ ttl: 3600 });
await storage.setItem('networkIdentity', JSON.stringify({
identity: "XXXXX"
}));
}
public getNetworkIdentity = async () => {
let myIdentity = storage.getItem("networkIdentity")
return myIdentity
}
}
Using this I can see the file getting created inside a node-persist folder in my source structure, it also has value. But while fetching it using storage.getItem()
I'm getting the below exception :
TypeError : storage.getItem() is not a function
Also I'm facing one problem
After the completion of first request, even when storage.setItem() is done successfully, when the seconds request comes I see the persistent file being deleted already. And I don't find the data related to networkIdentity
Updates:
While iterating over multiple requests, I see that the persistent file is still there with the data that is set, but when I try to read it using await storage.getItem() or await storage.data() no data is being fetched and I get the exception again as storage.getItem() is not a function, although the storage file is still present.

Twilio Programmable Chat getChannelByUniqueName throws "Forbidden" Error

After creating a channel in my backend service, I am trying to join the channel in my react frontend in an useEffect hook like this:
const initChat = async () => {
const chatClient = await Client.create(props.token);
const channel = await chatClient.getChannelByUniqueName(props.room);
if (channel) {
if (channel.status !== "joined") {
chatClient.on("channelJoined", () => {
registerChannelListeners(channel);
});
await channel.join();
} else {
registerChannelListeners(channel);
}
setChannel(channel);
setMessages((await channel?.getMessages()).items);
}
};
}
When initially navigating to the page, the error
upstream.js?a850:136 Uncaught (in promise) Error: Forbidden
at Upstream.actualSend (upstream.js?a850:136)
gets thrown sporadically.
On reloading the page, everything works fine.
The problematic line seems to be:
const channel = await chatClient.getChannelByUniqueName(props.room);
As no further code gets executed. token and room are both assigned with valid values.
In the decoded socket messages, this error message is sent from twilio:
{"method":"reply"...,"http_status":{"code":403,"status":"Forbidden"}}
{"status":403,"message":"User not member of channel","code":50400}
although both participants are invited via the backend with this function:
inviteParticipantToChannel(participant: Participant, channelSid: string) {
this.logger.log(
`Inviting paricipant ${participant.getIdentifier()} to channel ${channelSid}`,
);
return this.twilioClient.chat
.services(process.env.TWILIO_CHAT_SERVICE_ID)
.channels(channelSid)
.invites.create({ identity: participant.getIdentifier() });
}
Is there more that I need to do to enable the participant to find/join the channel?
Have you tried setting a short timeout? The channel resource at twilio might need some time.

Call a smart contract function using INFURA

I can not understand how I can prepare the transaction, sign it and then send it using INFURA. I expect to get something wrong with the NodeJS code I posted. Can anyone kindly help me solve this problem?
Note: I am able to send the transaction on my smart contract, but the EVM reverts the execution.
Part of the Smart Contract (Solidity) (the function that I want to call):
function testFunction() public pure returns (string memory) {
return "testSuccess";
}
The function used in NodeJS:
const printRequestTransaction = async (gcodeHash) => {
log(`Preparing a transaction to register that the gcode has been sent`.yellow);
// With every new transaction send using a specific wallet address, it needed to increase a nonce which is tied to the sender wallet
let nonce = await web3.eth.getTransactionCount(web3.eth.defaultAccount);
// Fetch the current transaction gas prices from https://ethgasstation.info/
let gasPrices = await getCurrentGasPrices();
// Build a new transaction object and sign it locally
let details = {
"to": process.env.SMART_CONTRACT_ADDRESS,
//"value": web3.utils.toHex(web3.utils.toWei(amountToSend.toString(), 'ether')),
"gas": 210000,
"gasPrice": gasPrices.low * 1000000000, // converts the gwei price to wei
"nonce": nonce,
//"data": gcodeHash,
"function": "testFunction",
"chainId": 3 // EIP 155 chainId - mainnet: 1, ropsten: 3, rinkeby: 4 (https://ethereum.stackexchange.com/questions/17051/how-to-select-a-network-id-or-is-there-a-list-of-network-ids/17101#17101)
};
const transaction = new EthereumTx(details);
// This is where the transaction is authorized on Local PC behalf. The private key is what unlocks Local PC wallet.
transaction.sign(Buffer.from(process.env.WALLET_PRIVATE_KEY, 'hex'));
// Compress the transaction info down into a transportable object
const serializedTransaction = transaction.serialize();
// The Web3 library is able to automatically determine the "from" address based on Local PC private key
// Submit the raw transaction details to the provider configured above (INFURA)
const transactionHash = await web3.eth.sendSignedTransaction('0x' + serializedTransaction.toString('hex')).then(function (receipt) {
log(`result of the invokation: ${receipt})`.red);
return receipt.transactionHash;
}).catch((err) => {
log(`error occurred: ${err})`.red);
});
//const transactionHash = "exampleHash";
_transactionHash = transactionHash;
// Now it is known the transaction ID, so let's build the public Etherscan url where the transaction details can be viewed.
const url = `https://ropsten.etherscan.io/tx/${transactionHash}`;
log(url.cyan);
log(`Note: please allow for 30 seconds before transaction appears on Etherscan`.yellow)
};
Output:
error occurred: Error: Transaction has been reverted by the EVM:
{
"blockHash": "0x6205c1b8ce2fde3693e85843dce684ff11472e9df01fd850bc99e5771b3262d5",
"blockNumber": 5024524,
"contractAddress": null,
"cumulativeGasUsed": "0x50170f",
"from": "0x8882528C7104e146E0500203C353C09922575385",
"gasUsed": "0x5236",
"logs": [],
"logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"status": "0x0",
"to": "0x1732089F6F6EeFA942871707c5AE1909B60774EB",
"transactionHash": "0xf748c9a6bdb19e776db4d8a9802d2bf5f8b588158da387029529249aca00a499",
"transactionIndex": 1
})
I would like to pay particular attention to the let details = {...}; object for which I am not very sure it is correct, I have a little confusion about this.

Using 2FA for password reset

My application uses Asp.Net Identity and sends a Two Factor code to my Auth app on login. This is pretty standard (as there lots of examples on the net) and uses the SendCode() method. My understanding is that the 'magic' is done by this line:
// Generate the token and send it
if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider))
{
View("Error");
}
My requirement is to ensure the user goes through the same process of 2FA when they want to change their password after they have logged in.
My issue is that when the code to send the 2FA code is executed:
if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider))
{
View("Error");
}
I receive the error 'UserID not found':
Server Error in '/MSPortal' Application.
UserId not found.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: UserId not found.
Source Error:
Line 555:
Line 556: // Generate the token and send it
Line 557: if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider))
Line 558: {
Line 559: return View("Error");
I know SendTwoFactorCodeAsync() calls GetVerifiedUserIdAsync() but my understanding is that the user is verified now that I have already logged in using 2FA.
Does anyone know why I would be getting this error?
Thanks.
I've worked around this by overriding SendTwoFactorCodeAsync() in IdentityConfig.cs. In this override, I first call GetVerifiedUserIdAsync() as per usual but then if that is 0 I get the User's ID from the Current HttpContext.
I am not stating this is the best way but it's what I have done thus far and its got me moving ahead in my aim of having 2FA for login, change password and forgot password.
The code (likely to go through some refactoring if I get feedback) is:
public override async Task<bool> SendTwoFactorCodeAsync(string provider)
{
int userId = 0;
try
{
userId = await GetVerifiedUserIdAsync();
if (userId == 0)
{
userId = Convert.ToInt32(HttpContext.Current.User.Identity.GetUserId());
}
if (userId == 0)
return false;
}
catch
{
return false;
}
var token = await UserManager.GenerateTwoFactorTokenAsync(userId, provider);
// See IdentityConfig.cs to plug in Email/SMS services to actually send the code
await UserManager.NotifyTwoFactorTokenAsync(userId, provider, token);
return true;
//return base.SendTwoFactorCodeAsync(provider);
}

Resources