Unable to use web3.eth.accounts.wallet.encrypt - javascript

I am trying to create a metamask like a wallet using web3. I am using React for the front end.
I am able to create a wallet but I am getting an error for encrypt function.
Following is the code I am using inside a React Component:-
handleClick = async (event) => {
try {
event.preventDefault();
const web3 = new Web3();
const account = web3.eth.accounts.create();
console.log(account);
const wallet = web3.eth.accounts.wallet.create();
wallet.defaultKeyName = this.state.accountName;
wallet.add(account.privateKey);
console.log(wallet);
const encryptedWallet = web3.eth.accounts.wallet.encrypt(this.state.password);
console.log(encryptedWallet);
}
catch (error) {
console.log(error);
}
}
Following is the error:-
TypeError: "list" argument must be an Array of Buffers
at Function.concat (index.js:399)
at Accounts.push../node_modules/web3-eth-accounts/src/index.js.Accounts.encrypt (index.js:431)
at Object.encrypt (index.js:111)
at index.js:548
at Array.map (<anonymous>)
at Wallet.push../node_modules/web3-eth-accounts/src/index.js.Wallet.encrypt (index.js:547)
at CreateWallet.handleClick (CreateWallet.js:46)
at HTMLUnknownElement.callCallback (react-dom.development.js:188)
at Object.invokeGuardedCallbackDev (react-dom.development.js:237)
at invokeGuardedCallback (react-dom.development.js:292)
at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:306)
at executeDispatch (react-dom.development.js:389)
at executeDispatchesInOrder (react-dom.development.js:414)
at executeDispatchesAndRelease (react-dom.development.js:3278)
at executeDispatchesAndReleaseTopLevel (react-dom.development.js:3287)
at forEachAccumulated (react-dom.development.js:3259)
at runEventsInBatch (react-dom.development.js:3304)
at runExtractedPluginEventsInBatch (react-dom.development.js:3514)
at handleTopLevel (react-dom.development.js:3558)
at batchedEventUpdates$1 (react-dom.development.js:21871)
at batchedEventUpdates (react-dom.development.js:795)
at dispatchEventForLegacyPluginEventSystem (react-dom.development.js:3568)
at attemptToDispatchEvent (react-dom.development.js:4267)
at dispatchEvent (react-dom.development.js:4189)
at unstable_runWithPriority (scheduler.development.js:653)
at runWithPriority$1 (react-dom.development.js:11039)
at discreteUpdates$1 (react-dom.development.js:21887)
at discreteUpdates (react-dom.development.js:806)
at dispatchDiscreteEvent (react-dom.development.js:4168)
Complete code is available at https://github.com/samarth9201/crypto-wallet.git.
I don't know if I am using it the incorrect way.

Related

React component with async array not updating [duplicate]

This question already has answers here:
Why am i getting and empty array when fetching an api with react hooks?
(4 answers)
Closed 13 days ago.
I have a component that gets an array of objects from a database using an async - await function. When the function gets the data and sets the array to a State variable, the component doesn't seem to update and I get errors about being unable to read properties. The data is being retrieved from the database correctly because I can console.log it. What am I doing wrong?
export default function LevelLeaderboard ({ level }) {
const [leaderboardData, setLeaderboardData] = useState([])
useEffect(()=>{
getLeaderBoardData(level)
.then((data)=>{
console.log(data)
setLeaderboardData(data)
})
},[level]);
return (
<div id="level" className="level-leaderboard">
<ul>
<li>{leaderboardData[0]['name']}</li>
</ul>
</div>
)
}
Error:
LevelLeaderboard.js:19 Uncaught TypeError: Cannot read properties of undefined (reading '0')
at LevelLeaderboard (LevelLeaderboard.js:19:1)
at renderWithHooks (react-dom.development.js:16305:1)
at mountIndeterminateComponent (react-dom.development.js:20074:1)
at beginWork (react-dom.development.js:21587:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1)
at invokeGuardedCallback (react-dom.development.js:4277:1)
at beginWork$1 (react-dom.development.js:27451:1)
at performUnitOfWork (react-dom.development.js:26557:1)
at workLoopSync (react-dom.development.js:26466:1)
Here's the async function:
export async function getLeaderBoardData(level, handleData){
const querySnapshot = await getDocs(collection(leaderboard, level));
let tempArr = [];
querySnapshot.forEach((doc) => {
tempArr.push(doc.data())
});
return tempArr;
}
You should add a conditional rendering to
<li>{leaderboardData[0]['name']}</li>
something like:
{leaderboardData.length >= 1 && <li>{leaderboardData[0]['name']}</li>}
since the array 'leaderboardData' its empty when component first render

how do i get rid of axios error uncaught (in promise)?

I am facing the error that uncaught(in promise) in console, its axios related error, I here pasted the code userSearch.jsx file code, where error showing at the end of function's last bracket ? at the end of function's last bracket, I am getting cross sign, why ? and what's the real error?
import { useState, useContext } from "react";
import GithubContext from "../../context/github/GithubContext";
import AlertContext from "../../context/alert/AlertContext";
import { searchUsers } from "../../context/github/GithubActions";
function UserSearch() {
const [text, setText] = useState('')
const { users, dispatch } = useContext(GithubContext)
const { setAlert } = useContext(AlertContext)
const handleChange = (e) => setText(e.target.value)
const handleSubmit = async (e) => {
e.preventDefault()
if (text === '') {
setAlert('Please enter something', 'error')
} else {
dispatch({ type: 'SET_LOADING' })
const users = await searchUsers(text)
dispatch({ type: 'GET_USERS', payload: users })
setText('')
}
}
return (
<div className='grid grid-cols-1 xl:grid-cols-2 lg:grid-cols-2 md:grid-cols-2 mb-8 gap-8'>
<div>
<form onSubmit={handleSubmit}>
<div className='form-control'>
<div className='relative'>
<input
type='text'
className='w-full pr-40 bg-gray-200 input input-lg text-black'
placeholder='Search'
value={text}
onChange={handleChange}
/>
<button
type='submit'
className='absolute top-0 right-0 rounded-l-none w-36 btn btn-lg'
>
Go
</button>
</div>
</div>
</form>
</div>
{users.length > 0 && (
<div>
<button
onClick={() => dispatch({ type: "CLEAR_USERS" })}
className='btn btn-ghost btn-lg'
>
Clear
</button>
</div>
)}
</div>
);
}
export default UserSearch;
ERROR SHOWING IN CONSOLE
GET https://api.github.com/search/users?q=brad 401
dispatchXhrRequest # xhr.js:220
xhrAdapter # xhr.js:16
dispatchRequest # dispatchRequest.js:58
request # Axios.js:109
Axios.<computed> # Axios.js:131
wrap # bind.js:9
searchUsers # GithubActions.js:16
handleSubmit # UserSearch.jsx:21
callCallback # react-dom.development.js:4164
invokeGuardedCallbackDev # react-dom.development.js:4213
invokeGuardedCallback # react-dom.development.js:4277
invokeGuardedCallbackAndCatchFirstError # react-dom.development.js:4291
executeDispatch # react-dom.development.js:9041
processDispatchQueueItemsInOrder # react-dom.development.js:9073
processDispatchQueue # react-dom.development.js:9086
dispatchEventsForPlugins # react-dom.development.js:9097
(anonymous) # react-dom.development.js:9288
batchedUpdates$1 # react-dom.development.js:26140
batchedUpdates # react-dom.development.js:3991
dispatchEventForPluginEventSystem # react-dom.development.js:9287
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay # react-dom.development.js:6465
dispatchEvent # react-dom.development.js:6457
dispatchDiscreteEvent # react-dom.development.js:6430
UserSearch.jsx:26 //ITS ERROR SHOWING BY THE END OF FUCNTION'S LAST BRACKET, ITS SHOWING CROSS SIGN ERROR AT THE END OF OF BRACKET
Uncaught (in promise) AxiosError {message: 'Request failed with status code 401', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
handleSubmit # UserSearch.jsx:26
await in handleSubmit (async)
callCallback # react-dom.development.js:4164
invokeGuardedCallbackDev # react-dom.development.js:4213
invokeGuardedCallback # react-dom.development.js:4277
invokeGuardedCallbackAndCatchFirstError # react-dom.development.js:4291
executeDispatch # react-dom.development.js:9041
processDispatchQueueItemsInOrder # react-dom.development.js:9073
processDispatchQueue # react-dom.development.js:9086
dispatchEventsForPlugins # react-dom.development.js:9097
(anonymous) # react-dom.development.js:9288
batchedUpdates$1 # react-dom.development.js:26140
batchedUpdates # react-dom.development.js:3991
dispatchEventForPluginEventSystem # react-dom.development.js:9287
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay # react-dom.development.js:6465
dispatchEvent # react-dom.development.js:6457
dispatchDiscreteEvent # react-dom.development.js:6430
GithubAction.js file where axios is added
import axios from 'axios'
const GITHUB_URL = process.env.REACT_APP_GITHUB_URL
const GITHUB_TOKEN = process.env.REACT_APP_GITHUB_TOKEN
const github = axios.create({
baseURL: GITHUB_URL,
headers: { Authorization: `token ${GITHUB_TOKEN}` },
})
// Get search results
export const searchUsers = async (text) => {
const params = new URLSearchParams({
q: text,
})
const response = await github.get(`/search/users?${params}`)
return response.data.items
}
// Get user and repos
export const getUserAndRepos = async (login) => {
const [user, repos] = await Promise.all([
github.get(`/users/${login}`),
github.get(`/users/${login}/repos`),
])
return { user: user.data, repos: repos.data }
}
The first line of your Error console GET https://api.github.com/search/users?q=brad 401 has the error code 401, which indicates the user is unauthorized, hence GitHub is rejecting your API request. Probably the token is incorrect or expired.
The second error related to Axios,
Uncaught (in promise) AxiosError {message: 'Request failed with status code 401', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
This happens because the API call to GitHub fails with a 401 error code and you have not implemented any error handling mechanism in your code to properly catch the errors and process them.
In UserSearch.jsx modify the handleSubmit function to use try-catch block
const handleSubmit = async (e) => {
e.preventDefault();
try {
if (text === "") {
setAlert("Please enter something", "error");
} else {
dispatch({ type: "SET_LOADING" });
const users = await searchUsers(text);
dispatch({ type: "GET_USERS", payload: users });
setText("");
}
} catch (error) {
console.log(error.response.data.error)
}
}
This happens because the API call to GitHub fails with a 401 error
code and you have not implemented any error handling mechanism in your
code to properly catch the errors and process theme.
I was facing same issue when I read this answer and I went back to check my code to realize that, while I was returning a value in
doSomething
.catch(error) { reject(false) }
I wasn't receiving it in the caller function's catch block as such
doSomethingCaller
.catch(error) { }
Once you write some error handling code, it stops displaying the error.

Amplify AppSync Subscription Uncaught (in promise)

I am trying to use AWS amplify GraphQL subscription like below,
import Amplify,{ API, Storage, graphqlOperation } from "aws-amplify";
import awsmobile from "../../aws-exports";
Amplify.configure(awsmobile);
...
const notiSubscription = API.graphql(graphqlOperation(onCreateNotification)).subscribe({
next: (todoData) => {
console.log(todoData);
},
});
...
onCreateNotification Graphql is,
subscription OnCreateNotification {
onCreateNotification {
id
}}
Below is the error I get,
AWSAppSyncProvider.ts:204 Uncaught (in promise) undefined
rejected # AWSAppSyncProvider.ts:204
Promise.then (async)
step # AWSAppSyncProvider.ts:204
(anonymous) # AWSAppSyncProvider.ts:204
push../node_modules/#aws-amplify/pubsub/lib-esm/Providers/AWSAppSyncRealTimeProvider.js.__awaiter # AWSAppSyncProvider.ts:204
AWSAppSyncRealTimeProvider._startSubscriptionWithAWSAppSyncRealTime # AWSAppSyncRealTimeProvider.ts:227
(anonymous) # AWSAppSyncRealTimeProvider.ts:185
Subscription # Observable.js:197
subscribe # Observable.js:279
(anonymous) # PubSub.ts:171
...
Please help me out in this, also my config is
"aws_project_region": "us-east-1",
"aws_appsync_graphqlEndpoint": "https://xxx.appsync-api.us-east-1.amazonaws.com/graphql",
"aws_appsync_region": "us-east-1",
"aws_appsync_authenticationType": "AMAZON_COGNITO_USER_POOLS",
"aws_appsync_apiKey": "xxxx",
You need to intialize the subscription in a useEffect() hook and then unsubscribe from the subscription.
useEffect(() => {
const subscription = API.graphql(graphqlOperation(onCreateNotification))
.subscribe({
next: todoData => {
console.log(todoData);
}
})
return () => subscription.unsubscribe()
}, [])

Error when trying to upload images to Firebase storage

I am trying to create an app which allow the user to upload an image and display it in the page with React and Firebase.
this is the part of the code that responsible for the issue:
the image variable is coming from from the state
const [image, setImage] = useState("");
const [caption, setCaption] = useState("");
const [progress, setProgress] = useState(0)
function handleChange (e){
if (e.target.files[0]){
setImage(e.target.files[0]);
}
}
function handleUpload(){
const uploadTask = storage.ref('images/${image.name}').put(image)
uploadTask.on(
"state_changed",
(snapshot) => {
const progress = Math.round(
(snapshot.bytesTransferred / snapshot.totalBytes) * 100
);
setProgress(progress);
},
(error) => {
console.log(error);
alert(error.message);
},
() => {
storage
.ref("images")
.child(image.name)
.getDownloadURL()
.then(url => {
db.collection("posts").add({
timestamp: db.FieldValue.serverTimestamp(),
caption : caption,
imgUrl: url,
userName: username
})
setProgress(0);
setCaption("");
setImage(null);
})
}
)
}
and this error get logged in the console :
Uncaught
FirebaseStorageError {code_: "storage/invalid-argument", message_: "Firebase Storage: Invalid argument in `put` at index 0: Expected Blob or File.", serverResponse_: null, name_: "FirebaseError"}code_: "storage/invalid-argument"message_: "Firebase Storage: Invalid argument in `put` at index 0: Expected Blob or File."name_: "FirebaseError"serverResponse_: nullcode: (...)message: (...)name: (...)serverResponse: (...)__proto__: Object
rethrowCaughtError # react-dom.development.js:328
runEventsInBatch # react-dom.development.js:3336
runExtractedPluginEventsInBatch # react-dom.development.js:3537
handleTopLevel # react-dom.development.js:3581
batchedEventUpdates$1 # react-dom.development.js:21729
batchedEventUpdates # react-dom.development.js:798
dispatchEventForLegacyPluginEventSystem # react-dom.development.js:3591
attemptToDispatchEvent # react-dom.development.js:4311
dispatchEvent # react-dom.development.js:4232
unstable_runWithPriority # scheduler.development.js:659
runWithPriority$1 # react-dom.development.js:11077
discreteUpdates$1 # react-dom.development.js:21746
discreteUpdates # react-dom.development.js:811
dispatchDiscreteEvent # react-dom.development.js:4211
I have tried to change put(image) to put(blob) but it did not work
The line:
const uploadTask = storage.ref('images/${image.name}').put(image)
Has an error, it should be using the symbol ` (backquote/backtick) instead of using single quotes ':
const uploadTask = storage.ref(`images/${image.name}`).put(image)
otherwise you will create a reference to the literal string images/${image.name} instead of image/value_of_variable_image.jpg more about Template literals can be found here
You haven't still showed us what's the content of the image variable, I can see from the code that you're calling a setState inside a function that appears to be a callback, but I'm not seeing from where are you calling, you can do it from a input like this:
<input type="file" onChange={handleChange} />
If you're already using it like that, I recommend to add console.log(image) outside of a function in order debug what's the content of the variable before sending it to put(). Just as a reference the output from the console.log(image) should be an instance of the File javascript API

React and redux useEffect on async function with dispatch

I'm getting an error in my console when I run my code.
uncaught TypeError: func.apply is not a function
at HTMLUnknownElement.callCallback (react-dom.development.js:188)
at Object.invokeGuardedCallbackDev (react-dom.development.js:237)
at invokeGuardedCallback (react-dom.development.js:292)
at safelyCallDestroy (react-dom.development.js:19650)
at react-dom.development.js:20123
at unstable_runWithPriority (scheduler.development.js:653)
at runWithPriority$1 (react-dom.development.js:11061)
at commitUnmount (react-dom.development.js:20116)
at unmountHostComponents (react-dom.development.js:20497)
at commitDeletion (react-dom.development.js:20533)
at commitMutationEffects (react-dom.development.js:22813)
at HTMLUnknownElement.callCallback (react-dom.development.js:188)
at Object.invokeGuardedCallbackDev (react-dom.development.js:237)
at invokeGuardedCallback (react-dom.development.js:292)
at commitRootImpl (react-dom.development.js:22540)
at unstable_runWithPriority (scheduler.development.js:653)
at runWithPriority$1 (react-dom.development.js:11061)
at commitRoot (react-dom.development.js:22412)
at finishSyncRender (react-dom.development.js:21838)
at performSyncWorkOnRoot (react-dom.development.js:21824)
at react-dom.development.js:11111
at unstable_runWithPriority (scheduler.development.js:653)
at runWithPriority$1 (react-dom.development.js:11061)
at flushSyncCallbackQueueImpl (react-dom.development.js:11106)
at flushSyncCallbackQueue (react-dom.development.js:11094)
at discreteUpdates$1 (react-dom.development.js:21924)
at discreteUpdates (react-dom.development.js:1071)
at dispatchDiscreteEvent (react-dom.development.js:4168)
callCallback # react-dom.development.js:188
invokeGuardedCallbackDev # react-dom.development.js:237
invokeGuardedCallback # react-dom.development.js:292
safelyCallDestroy # react-dom.development.js:19650
(anonymous) # react-dom.development.js:20123
unstable_runWithPriority # scheduler.development.js:653
runWithPriority$1 # react-dom.development.js:11061
commitUnmount # react-dom.development.js:20116
unmountHostComponents # react-dom.development.js:20497
commitDeletion # react-dom.development.js:20533
commitMutationEffects # react-dom.development.js:22813
callCallback # react-dom.development.js:188
invokeGuardedCallbackDev # react-dom.development.js:237
invokeGuardedCallback # react-dom.development.js:292
commitRootImpl # react-dom.development.js:22540
unstable_runWithPriority # scheduler.development.js:653
runWithPriority$1 # react-dom.development.js:11061
commitRoot # react-dom.development.js:22412
finishSyncRender # react-dom.development.js:21838
performSyncWorkOnRoot # react-dom.development.js:21824
(anonymous) # react-dom.development.js:11111
unstable_runWithPriority # scheduler.development.js:653
runWithPriority$1 # react-dom.development.js:11061
flushSyncCallbackQueueImpl # react-dom.development.js:11106
flushSyncCallbackQueue # react-dom.development.js:11094
discreteUpdates$1 # react-dom.development.js:21924
discreteUpdates # react-dom.development.js:1071
dispatchDiscreteEvent # react-dom.development.js:4168
When I click certain buttons that redirect the client-side, the client-side goes to this blank screen and I have to refresh it. When I refresh the app, it works as required and goes to the correct place with the correct states (behaves as it should). When I googled this error I found that it is caused due to an async function being used in the useEffect hook. However, the suggested fixes would work as I am using dispatch for this async function and not sure how to work around this.
here is the function
export const getCurrentProfile = () => async dispatch => {
try {
const res = await axios.get("/api/profile/me");
dispatch({ type: GET_PROFILE, payload: res.data });
} catch (err) {
dispatch({
type: PROFILE_ERROR,
payload: { msg: err.response.statusText, status: err.response.status }
});
}
};
here is the snippet of code I use useEffect in
import { connect } from "react-redux";
import { getCurrentProfile } from "../../actions/profile";
...
const Dashboard = ({
getCurrentProfile,
auth: { user },
profile: { profile, loading }
}) => {
useEffect(() => {
getCurrentProfile();
}, []);
...
export default connect(mapStateToProps, { getCurrentProfile })(Dashboard);

Categories

Resources