uniswap V2 invalid BigNumber value for JSBI negative value - javascript

Hi I was following uniswapV2 document to perform a trade transaction and I encounter error as follow invalid bignumber value
I got my input amount as 2941991120 and in JSBI form it is -1352976176, which gave me invalid bignumber value bug. Here is my code code screenshot. But I was following exactly what the tutorial says https://uniswap.org/docs/v2/javascript-SDK/trading/
Can anyone tell me where I did wrong ?

The example tells you the value should be converted to hex:
const value = trade.inputAmount.raw // // needs to be converted to e.g. hex
Same for one of the other values. Have you tried this?
If you use a (signed) integer, its sign can be positive/negative (+/-). Whatever value you're sending is deemed to be a negative one, which is unexpected and so the response is telling you.
This exmaple seems to suggest you can do: https://ethereum.stackexchange.com/questions/87983/failed-transaction-error-encountered-during-contract-execution-on-uniswap-rout
...
const amountOutMinHex = ethers.BigNumber.from(amountOutMin.toString()).toHexString();
...

The accepted answer is unnecessarily complex. The JSBI::toString() method takes a radix parameter, so your linked example would simply look like:
trade.minimumAmountOut(slippageTolerance).raw.toString(16);

Related

Convert number in javascript produces NAN

I have a text box whose outcome is in Belgium number format like this
<input type="text" name="valeurCatalogue" kendo-numeric-text-box="" k-culture='"fr-BE"' k-spinners="{{false}}" ng-disabled="isValueCatalogDisabled" ng-model="tarifForm.Vehicle.valeurCatalogue" />
Having put the value as 1525,8 the value gets transformed to 1.525,80 which is correct.
Now if I apply Number(1525,8) I get NAN.How to get the number in javascript?
Please note in debug mode I see the value 1525,8 as string.
The problem here is that javascript uses the american way of expressing numbers (as do most programming languages I've encountered). So, 1,5 is not one and a half as you would expect, rather it's not a valid number. Thus when you try to parse it you get NaN (Not a Number). In javascript, the correct way to write said number would be 1.5. If you have 1525,8 the simple way to do this is replace all commas with dots like this:
const numStr = '1525,8';
const replaced = numStr.replace(/,/, '.');
const num = Number(replaced);
If however, your number is 1.525,8 you need to first remove the dots (str.replace(/\./g, '');).

Int entered verificatiion - Parse Server Cloud Code

I use the new Parse Server, and in the cloud part which is using Javascript I want to check if an integer is specified by a user, in other words I want to check if the Int is null or not. I can do it for strings, but as I see from comments, an int can not be null. Bu I do not want to change all ints in my code to integers. I try the code below, but it is not working, how can I check if there is a number specified by the user or if it is empty?
if (!req.object.get('number'))
Your code should work as long as number isn't zero. To handle that case as well, simply do a type check like this:
if (typeof req.object.get('number') !== 'number').
It seems like you are confusing java and javascript. Javascript does not have ints or integers, only numbers. Javascript variables do not have types and all variables can be null and undefined.

Passing a number to parseFloat() instead of string

In my code, the value of a particular var can originate from any one of a number of different json sources. For some of those sources, the json element concerned will be a string (e.g. "temp": "10.2"), while for other sources the json element will already be a float (e.g. "temp": 10.2).
Does it do any harm (is anything likely to break) if I just pass the json element (from whatever source) through a parseFloat(), even if it's already a float? It seems to work; I'm just thinking about good/bad practice and possible breakage in future or on a different platform.
Thanks.
You should be able to call parseFloat() on a float or a string without any problems. If it is a float already, it's converted to a string first, and then to a float again, so it's a little less efficient, but it shouldn't matter too much.
You should still check the result for NaN, in case there's something unexpected in the data.
The most appropriate method to convert any datatype to a number is to use the Number function:
In a non-constructor context (i.e., without the new operator),
Number can be used to perform a type conversion.
Number("1234") // 1234
Number(1234) // 1234
This method differs from parseFloat in these ways at least:
Number function does not perform "double-conversion" if the input is already a number (ref)
Parse float converts the input to a string then extracts the number (ref)
Number function returns common sense values for most datatypes e.g. Number(true) yields 1
Parse float uses the string value of input so parseFloat(true) tries to parse number from "true" and yields NaN
Number function fails when input string is an invalid number e.g. Number("123abc") yields NaN
Parse float tries to parse as much of a number as possible e.g. parseFloat("123abc") yields 123
If you are sure the value is always a valid number, you should use Number(stringOrNumber).
If you need some additional safety using parseFloat() you could also write your own function which is also performance optimized:
function toFloat(value) {
return typeof value === 'number' ? value : parseFloat(value);
}
I also created a jsPerf test case that shows the performance is >30% better than the plain parseFloat() for a 1:1 ratio between strings and numbers as input values.
Nope there is no problem with passing a number to it
MDN says as long as it can be converted to a number, nothing breaking should happen.
If the first character cannot be converted to a number, parseFloat returns NaN.
As an alternative, you could use the unary operator + which does basically the same thing as parseFloat and also returns NaN if it didn't work.
For instance:
var myFloat = +('10.5');
var myOtherFloat = parseFloat('10.5', 10);
var alreadyAFloat = parseFloat(10.5, 10);
console.log(myFloat === myOtherFloat && myOtherFloat === alreadyAFloat); // true
Wether it's a float or a String using parseFloat() is much safer to avoid all kind of errors.
As you said it will always work, but if you enforce it to be a float you will avoid getting any Exception.
For Example:
Both parseFloat('10.2', 10) and parseFloat(10.2, 10) will work
perfectly and will give you the same result which is 10.2.
Personally I can't see this being a problem what so ever, to be honest I would always use the parsefloat() for one reason, and that is safety. You can never be to sure what may happen, so always predict the worse :D

Angular / Javascript 'rounding' long values?

I have the following JSON:
[{"hashcode": 4830991188237466859},{...}]
I have the following Angular/JS code:
var res = $resource('<something>');
...
res.query({}, function(json) {hashcode = json[0].hashcode;};
...
Surprisingly (to me, I'm no JS expert), I find that something (?) is rounding the value to the precision of 1000 (rounding the last 3 digits). This is a problem, since this is a hash code of something.
If, on the other hand I write the value as a String to the JSON, e.g -
[{"hashcode": "4830991188237466859"},{...}]
this does not happen. But this causes a different problem for me (with JMeter/JSON Path, which extracts the value ["4830991188237466859"] by running my query $.hashcode - which I can't use as a HTTP request parameter (I need to add ?hashcode=... to the query, but I end up with ?hashcode=["..."]
So I appreciate help with:
Understanding who and why -- is rounding my hash, and how to avoid it
Help with JMeter/JSON Path
Thanks!
Each system architecture has a maximum number it can represent. See Number.MAX_VALUE or paste your number into the console. You'll see it happens at the JavaScript level, nothing to do with angular. Since the hash doesn't represent the amount of something, it's perfectly natural for it to be a string. Which leads me to
Nothing wrong with site.com/page?hashcode=4830991188237466859 - it's treated as a string there and you should keep treating it as such.
The javascript Number type is floating point based, and can only represent all integers in the range between -253 and 253. Some integers outside this range are therefore subject to "rounding" as you experience.
In regards to JMeter JSON Path Extractor plugin, the correct JSON Path query for your hashcode will look like
$..hashcode[0]
See Parsing JSON chapter of the guide for XPath to JSON Path mappings and more details.

Javascript checking for float

I've got an app that users input coordinates into.
In the DB and most mapping software they use the decimal notation for lat/lng (eg. 123.1234) rather than the older format: 34N 40' 50.12"
I need to test that a value input into a form is a float, and not a string. But using parseFloat on 34N 40' 50.12" returns 34-- which validates using most tests.
Here's what I'm trying, which is a mashup of a few really clever solutions found here-- but so far I can't get the thing to work properly for all cases. The basic cases I'm testing for are:
123.1234 -- valid
'123.1234' -- valid
34N 40' 50.12" -- invalid
'34N 40' 50.12"' -- invalid
123 --valid
'123' -- valid
Here's a jsfiddle of what I've been trying: http://jsfiddle.net/zfwAj/
Seems I should have posted as an answer
isNaN() should work to filter out those ones jsfiddle.net/QYMRe
Try
/^\d+\.?\d*$/.test( str );
Fiddle here
I suggest this one:
/^-?(\d*\.\d+|\d+(\.\d+)?)$/.test(str)
This accepts negative numbers, and float like (.42)
Fiddle test

Categories

Resources