What is the equivalent of keccak256 in solidity? - solidity

I am going to get the same value that is produced by keccak256 in solidity.
This is the code in my solidity file and I want to get the same value in the javascript file using ethers or web3.
bytes32 node = keccak256(abi.encodePacked(nodeString));
I got the same value of abi.encodePacked(nodeString)) by using ethers.utils.solidityPack.
const abiEncodedPackedString = ethers.utils.solidityPack(['string'], [nodeString]);
But when I tried ethers.utils.solidityKeccak256, the result wasn't the same as node in solidity.
const nodeInJavascript = ethers.utils.solidityKeccak256(['string], [abiEncodePackedString]);
I have also tried ethers.utils.keccak256(abiEncodePackedString) but I couldn't get the result either.

in web3 I used this and worked:
export const createCourseHash = (courseId, account) => {
const hexCourseId = web3.utils.utf8ToHex(courseId)
const courseHash = web3.utils.soliditySha3(
{ type: "bytes16", value: hexCourseId },
{ type: "address", value: account }
)
return courseHash
}
in ethers, you are passing plain string. try to convert it to hex value. in fact if you check the documentation, they are not passing plain strings:
The value MUST be data, such as:
an Array of numbers
a data hex string (e.g. "0x1234")
a Uint8Array

Related

How to build query as variable (from user Input) in prisma.queryRaw without using queryRawUnsafe

I was trying to query my (postgres) db with a customizable statement built front end.
My resolver gets the built query inside the input param, but when I use the queryRaw method I get this error:
`"\nInvalid `prisma.queryRaw()` invocation:\n\n\n Raw query failed. Code: `42601`. Message: `db error: ERROR: syntax error at or near \"$1\"`"`
Is there a way to build a custom query and pass it like the input variable WITHOUT USING queryRawUnsafe to prisma? (queryRawUnsafe works fine, but well.. it's unsafe XD) Thanks <3
Here is my code.
getCars: (_parent, { input }, { prisma }) => {
if(input){
console.log(input) // --> SELECT * FROM car WHERE car."plate" ILIKE '%123%' //type String
const differentInput = '%123%'
// const result = prisma.$queryRaw`SELECT * FROM car WHERE car."plate" ILIKE '%123%'` // works
// const result = prisma.$queryRaw`SELECT * FROM car WHERE car."plate" ILIKE ${differentInput}` // works
// const result = prisma.$queryRawUnsafe(input) // works
const result = prisma.$queryRaw`${input}` // Doesn`t work
return result
}
// ... Other code
}
prisma.$queryRaw only accepts templated strings, not just strings. You can use the Prisma.sql helper to generate those templated strings to get the expected results. That might look like:
const sql = Prisma.sql`SELECT * FROM car WHERE car."plate" ILIKE '%123%'`
const result = prisma.$queryRaw`${sql}`
The queryRaw documentation mentions Prisma.sql with other examples but doesn't show any examples of what you are trying to do.

How can I save part of a string in an alias using Cypress?

I'm trying to save just a number from a string I get from a paragraph but when I try to asign an alias to it and then check the value it returns undefined. I've tried a few solutions I found but none of those seem to work for me. These are two ways I tried (I tried another one similar to the second one but using split, had same result). The console.log inside of the 'then' doesn't show in the console, and when I try the alias after the code is when I get undefined.
cy.get('p')
.eq(1)
.should('have.text', '/[0-9]+/g')
.as('solNumber')
cy.get('p')
.eq(1)
.invoke('text')
.then((text)=>{
var fullText = text;
var pattern = /[0-9]+/g;
var number = fullText.match(pattern);
console.log(number);
})
.as('solNumber')
Please convert with + operator and return the numeric value if you want numeric type to be stored.
cy.get('p').eq(1)
.invoke('text')
.then(fullText => {
const number = fullText.match(/[0-9]+/);
return +number // text to numeric
})
.as('solNumber')
cy.get('#solNumber')
.should('eq', 42) // numeric type
});
Running your 2nd code on this,
<p>21</p>
<p>42</p>
gives the correct outcome
cy.get('p')
.eq(1)
.invoke('text')
.then((text)=>{
var fullText = text;
var pattern = /[0-9]+/g;
var number = fullText.match(pattern);
console.log(number); // logs 42
})
.as('solNumber')
cy.get('#solNumber')
.should('eq', '42') // passes
So, you need to inspect the DOM, it looks like it's not what you expect.
The first attempt you were passing a jquery element to the .should() and although some chainers change the subject yours did not so it saved the jquery element as solNumber.
The second attempt invokes the .text() which was passed to the .then() it logs the number correctly. However, you did not return anything at the end of the .then() block, therefore, solNumber should hold the entire paragraph.
This should help you out to extract the specific number and save it as an alias.
cy.get('p')
.invoke('text')
.invoke('trim')
.then(paragraph => {
const matcher = /some/
expect(paragraph).to.match(matcher) // check number is there
const indexOfText = paragraph.match(matcher) // get index of match text
return paragraph.substring(indexOfText.index, indexOfText.index + indexOfText[0].length) // return substring
})
.as('savedText')
cy.get('#savedText')
.then(cy.log) // will print out the number you seek

How can I parse user input decimals based on the current locale in React Native, using a dot or comma for the decimal separator?

I have a number input that pops up a "numeric" text input in React Native.
In many locales this brings up a numeric pad with a comma for decimal separation, instead of a dot. This results in inputs like "100,1" instead of "100.1".
JavaScript's Number(value) only works with dot decimals, not commas. How can I determine the user's current format in order to properly parse the input?
This function will parse a decimal input based on the current locale, using react-native-localize:
import { getNumberFormatSettings } from "react-native-localize";
export function parseLocaleNumber(stringNumber: string) {
const { decimalSeparator, groupingSeparator } = getNumberFormatSettings();
return Number(
stringNumber
.replace(new RegExp(`\\${groupingSeparator}`, "g"), "")
.replace(new RegExp(`\\${decimalSeparator}`), "."),
);
}
For good measure, this complementary function provides toFixed functionality based on locale:
export function toFixedLocale(value: number, numDigits: number) {
const standardFixedString = value.toFixed(numDigits);
const { decimalSeparator } = getNumberFormatSettings();
if (decimalSeparator === ",") {
return standardFixedString.replace(".", ",");
} else {
return standardFixedString; // Locale matches JavaScript default
}
}
(parseLocaleNumber based on https://stackoverflow.com/a/42213804/152711)

Using symbols in JSX and React Native

I would like to use this symbol in my React Native project.
I tried using the Unicode encoding like this:
var arrow = "U+0279C";
And in the JSX:
<Text>
{arrow}
</Text>
However, this just displays the encoding literally: U+0279C.
So any idea how can I use a symbol in JSX?
You should use the HTML code for the symbol.
<Text>
➜
</Text>
As described in notes below.. (important, quotes don't seem to work)...
Just to clarify: <Text>➜</Text> will work, but <Text>{ '➜' }</Text> will not.
Use this functions for symbols in this format: & # 1 7 4 ;
/**
* replaces /$#d\+/ symbol with actual symbols in the given string
*
* Returns given string with symbol code replaced with actual symbol
*
* #param {string} name
*/
export function convertSymbolsFromCode(name = '') {
let final = null;
if (name) {
const val = name.match(/&#\d+;/) ? name.match(/&#\d+;/)[0] : false; // need to check whether it is an actual symbol code
if (val) {
const num = val.match(/\d+;/) ? val.match(/\d+;/)[0] : false; // if symbol, then get numeric code
if (num) {
final = num.replace(/;/g, '');
}
}
if (final) {
name = name.replace(/&#\d+;/g, String.fromCharCode(final));
}
}
return name;
}
USAGE
<Text>
{convertSymbolsFromCode(this.state.unicode)}
</Text>
The provided answer did not work for me, since I was dynamically retrieving unicode hex codes from an API. I had to pass them as JavaScript into the react-native jsx code.
The following answer worked for me:
Concatenate unicode and variable
I used String.fromCodePoint(parseInt(unicode, 16)) and it worked.
Example:
const unicode = unicodeHexValueFromApi //This value equals "05D2"
return(<Text>{String.fromCodePoint(parseInt(unicode, 16))}</Text>)
<Text>{"Any character"}</Text>
This worked for me.

setQueryParameters error parameters format

I have this ionic service but when i pass the parameters in set Queryparametrs function it wont work.
var sample = function(title,description,adress,country,userid)
{
var req = new WLResourceRequest("/adapters/eventAdapter/addEvent", WLResourceRequest.POST);
req.setQueryParameters("params", "['"+title+","+description+","+adress+","+country+","+userid+"']");
return req.send().then(function(res) {
........
}, function(bad) {
.......
});
}
any help ?
If your content (title, description, etc) contains any invalid json characters, it could be that the string you generated is invalid.
As you guessed correctly, using JSON.stringify is the safer option.
var params = [title, description, adress, country, state, userid];
req.setQueryParameters("params",JSON.stringify(params));
Also, your request is using POST, and so it is expected to use form parameters instead of query parameters:
req.sendFormParameters({"params":JSON.stringify(params)})