Last active
April 8, 2018 22:13
-
-
Save MagRelo/55df20f6c9e82f4bc3e7b881738881e6 to your computer and use it in GitHub Desktop.
Sign a message using Web3 and send it to the server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Web3 from 'web3' | |
// Setup a message with instructions for the server. | |
const messageData = [ | |
{ | |
name: ‘Contents’, | |
type: ‘string’, | |
value: 'extra! extra! read all about it!' | |
} | |
] | |
// create instance of Web3 from the web3 object provided by the browser | |
const web3 = new Web3(window.web3.currentProvider) | |
// get the user's account | |
web3.eth.getAccounts().then(accounts => { | |
const userAccount = accounts[0] | |
// Sign the message. | |
// This will trigger a popup where the user can review the | |
// message. If they confirm the popup, the message will be signed using | |
// their private key and the callback will be called. | |
web3.currentProvider.sendAsync({ | |
method: ‘eth_signTypedData’, | |
params: [messageData, userAccount], | |
from: userAccount, | |
}, function (err, result) { | |
// result.result is the signature | |
console.log('Signature:', result.result) | |
// send the message and signature to server as normal http request | |
return fetch('/api/vote', { | |
method: "POST", | |
headers: { | |
"Content-Type": "application/json" | |
}, | |
body: JSON.stringify({ | |
messageData: messageData, | |
signature: result.result | |
}) | |
}).then(response => { | |
console.log('sent to server.') | |
}) | |
}) | |
}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment