Skip to content

Instantly share code, notes, and snippets.

@rafinskipg
Created September 28, 2021 14:05
Show Gist options
  • Save rafinskipg/da57e41125679052e0880f70a88a724a to your computer and use it in GitHub Desktop.
Save rafinskipg/da57e41125679052e0880f70a88a724a to your computer and use it in GitHub Desktop.
signing-security with web3
const web3 = new Web3(context.library.provider);
const thingToSave = {
message: 'Hello world',
owner: address,
};
const hashedData = web3.eth.accounts.hashMessage(
JSON.stringify(thingToSave)
);
try {
const signature = await web3.eth.personal.sign(
hashedData,
address,
null
);
const result = await postData(`/api/something`, {
data: thingToSave,
signature,
});
} catch (e) {
console.log('Error madafacka', e)
}
function isValidMessage(thingToSave) : boolean {
const web3 = new Web3(
new Web3.providers.HttpProvider(process.env.RPC_PROVIDER)
);
const hashedData = web3.eth.accounts.hashMessage(JSON.stringify(thingToSave));
const signingAddress = web3.eth.accounts.recover(hashedData, signature);
if (signingAddress !== thingToSave.owner) {
// DATA IS INVALID, the signer does not equal the address in the message
return false;
}
return true
}
@rafinskipg
Copy link
Author

Hashing the data is optional

@rocioDEV
Copy link

coolio

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment