How to handle Web3 js privateKeyToAccount error? - web3js

How to handle Web3 js privateKeyToAccount error if I pass the wrong private key?
I am using node js v18.
const signer = web3.eth.accounts.privateKeyToAccount("*****");
If i add a try-catch block on it then the signer is not accessible outside the try block.

You need to pass the private key as a string:
prefixed 0x
followed by 64 hex characters (representing the 256bit key)
Example:
const signer = web3.eth.accounts.privateKeyToAccount("0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef");
console.log(signer.address); // 0xFCAd0B19bB29D4674531d6f115237E16AfCE377c

Related

Gametracker Scraper discord.js

So I'm trying to script something that shows how many players are on a Server using gametracker. I found this module. I successfully can log those information in my terminal but i want to display. So when somebody types .info that this information are in the channel.
My Code:
case 'info':
const module = require ('gametracker-scraper')
async function output() {
let info = await module.get('My Link')
message.channel.send('Our Server Info:' + info)
}
output()
The text that is posted in the Channel when you write .info:
Our Server Info: [object Object]
Other scraper alternatives are welcome!
It is outputting "[object Object]" because you're concatenating a string and an object.
If you want to output the actual info, you could loop over the object (with, as an example, a for in loop), like this example:
let infoString = 'Our Server Info:\n';
for (const element in info) {
infoString += `${element}: ${info[element]}\n`;
}
message.channel.send(infoString);
Which would produce something like this:
Our Server Info:
Map: (your map)
Online: (your player count)
// etc...
info is an Object. Trying to concatenate an object with a string will return "[object Object]", unless it has a custom toString() method. You can access primitives from that object (using variable.property or variable["property"]) and it should concatenate properly. Another way, not as readable, is using JSON.stringify(). This will turn the object into a string
message.channel.send('Our Server Info:\n' + JSON.stringify(info))

Expo React Native String to BigInt

I am trying to get unique ID for my device and I get is successfully with Constants.deviceId. However, I need it in 8 bytes (BigInt type). Is it possible somehow?
Device ID in string looks like this: "AAAAAAAA-BBBB-CCCC-DDDD-EEEEFFFFGGGG"
Is it better to use another approach and just generate a random 8 byte number and use it as unique ID for the device?
Can you encode it as base64?
yarn add Base64.
import Base64 from 'Base64';
const encoded = Base64.btoa('AAAAAAAA-BBBB-CCCC-DDDD-EEEEFFFFGGGG');
const decoded = Base64.atob(encoded);
// Should return QUFBQUFBQUEtQkJCQi1DQ0NDLUREREQtRUVFRUZGRkZHR0dH
npm package.
Blog with more info

Upload images to Azure blob from front end (React)

The front end enables people to upload their photos, so i was sending the base64 to the server and working with it initially, but there are problems with firewall which blocks the request which contains base64. As an alternative solution I was trying to upload the image to azure blob get the file name and then send that to the server for processing where I generate a sas token for the blob validation and processing.
This works perfectly fine when I work locally and the front end connection works with #azure/storage-blob
and uploadBrowserData() when I send the arrayBuffer as the param
export const uploadSelfieToBlob = async arrayBuffer => {
try {
const blobURL = `https://${accountName}.blob.core.windows.net${sasString}`;
const blobServiceClient = new BlobServiceClient(blobURL, anonymousCredential);
const containerClient = blobServiceClient.getContainerClient(containerName);
let randomString = Math.random().toString(36).substring(7);
const blobName = `${randomString}_${new Date().getTime()}.jpg`;
const blockBlobClient = containerClient.getBlockBlobClient(blobName);
const uploadBlobResponse = await blockBlobClient.uploadBrowserData(arrayBuffer);
return { blobName, blobId: uploadBlobResponse.requestId };
} catch (error) {
console.log('error when uploading to blob', error);
throw new Error('Error Uploading the selfie to blob');
}
};
When I deploy this is not working, the front is deployed in the EastUs2 location and the local development location is different.
I thought the sasString generated for anonymous access had the timezone option so I generated 2 different one's one for local and one for hosted server with the same location selected.
Failed to send request to https://xxxx.blob.core.windows.net/contanainer-name/26pcie_1582087489288.jpg?sv=2019-02-02&ss=b&srt=c&sp=rwdlac&se=2023-09-11T07:57:29Z&st=2020-02-18T00:57:29Z&spr=https&sig=9IWhXo5i%2B951%2F8%2BTDqIY5MRXbumQasOnY4%2Bju%2BqF3gw%3D
What am I missing any lead would be helpful thanks
First, as mentioned in the comments there was an issue with the CORS Settings because of which you're getting the initial error.
AuthorizationResourceTypeMismatchThis
request is not authorized to perform this operation using this
resource type. RequestId:7ec96c83-101e-0001-4ef1-e63864000000
Time:2020-02-19T06:57:31.2867563Z
I looked up this error code here and then closely looked at your SAS URL.
One thing I noticed in your SAS URL is that you have set the signed resource type (srt) as c (container) and trying to upload the blob. If you look at the description of the kind of operations you can do using srt=c here, you will notice that blob related operations are not supported.
In order to perform blob related operations (like blob upload), you would need to set signed resource type value to o (for object).
Please regenerate your SAS Token and include signed resource type as object (you can also include container and/or service in there as well) and then your request should work. So essentially your srt in your SAS URL should be something like srt=o or srt=co or srt=sco.
I couldn't notice anything wrong with the code you mentioned about, but I have been using a different method to upload files to Azure Blog Storage using React, the method is exactly the same as in this blog article which works perfectly for me.
https://medium.com/#stuarttottle/upload-to-azure-blob-storage-with-react-34f37805fdfc

Encrypting the client side local storage data using Angularjs

I have a client side data storing in the localStorage. For security reasons i want to encrypt the data. Is there any way to encrypt/decrypt the client data(not server data) using Angularjs?
$scope.accountObj = {
isErrorMsg:false,
isReadonly:false,
createAccountErr:false
};
You could use cryptojs library for encrypting/decrypting your data. First you should generate some key to use in encryption process:
var secretKey = 'your-secret-key';
Then you need method to store and claim data:
store : function (key, value) {
var encryptedData = CryptoJS.AES.encrypt(angular.toJson(value), secretKey).toString();
window.localStorage.setItem(key, encryptedData);
},
get : function (key) {
var encryptedData = window.localStorage.getItem(key);
if (!_.isNull(encryptedData))
return angular.fromJson(CryptoJS.AES.decrypt(encryptedValue, secretKey).toString(CryptoJS.enc.Utf8));
return null;
}
The only problem here is that secret key is stored on the client side and it's kind of breaking logics of such encryptions.
These are probably the best out of the box solutions available for cryptography in Javascript until now.
https://www.w3.org/TR/WebCryptoAPI/
https://crypto.stanford.edu/sjcl/
However, you will probably wanna avoid cryptography on the browser if "security" is a concern and seeing as you don't trust the client machine with your localStorage.

proper location for public/private keys in my React development app?

In the dev environment for my React app, I have a set of public/private keys that I need to access an API. I'd like to ideally put these keys into their own file for gitignore purposes, but i'm not having luck with my code as shown below.
my helpers.jsx file is where the API data is called via lightweight AJAX add-on, and I have the actual keys in the require declarations area:
var API_KEY = require('./keys.jsx');
var PRIV_KEY = require('./keys.jsx');
Summarily, my keys.jsx file (stored in the same subfolder as the helpers.jsx) consists of the following:
module.exports = {
API_KEY:'myactualpublickey',
PRIV_KEY:'myactualprivatekey'
};
However, my app does not like this set up, as I get an "Failed to load resource: the server responded with a status of 401 (Unauthorized)” error message and the API call isn't successful because the necessary keys are not included.
When I replace the require('./keys.jsx'); in the helpers.jsx file with the actual keys, the API call works fine.
Any help or guidance would be most appreciated. Thanks.
You're exporting an object with properties called API_KEY and PRIV_KEY, so try this:
var API_KEY = require('./keys.jsx').API_KEY;
var PRIV_KEY = require('./keys.jsx').PRIV_KEY;

Resources