Created
June 16, 2019 06:11
-
-
Save artiya4u/3882d6a299f24c8d7904c4da567799e4 to your computer and use it in GitHub Desktop.
This file contains 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
const express = require('express'); | |
const Web3 = require('web3'); | |
const {bufferToHex} = require('ethereumjs-util'); | |
const HDWalletProvider = require('truffle-hdwallet-provider'); | |
const providerWithMnemonic = (mnemonic, rpcEndpoint) => | |
new HDWalletProvider(mnemonic, rpcEndpoint); | |
const infuraProvider = network => providerWithMnemonic( | |
process.env.MNEMONIC || '', | |
process.env.RPC_URL || `https://${network}.infura.io/${process.env.INFURA_API_KEY}`, | |
); | |
const router = express.Router(); | |
router.post('/', async (req, res, next) => { | |
try { | |
const user = req.body; | |
const provider = infuraProvider(user.network); | |
let w3 = new Web3(provider); | |
let contractAddress = ''; | |
if (user.network === 'mainnet') { | |
contractAddress = '0xaacf5eca66aecc1ef36e7283b665aa9aac59a10f'; | |
} else if (user.network === 'rinkeby') { | |
contractAddress = '0xf7e1c58873b97961c8e58c261f66499c50b34f1b'; | |
} | |
let issuer = w3.eth.accounts.recover( | |
w3.utils.soliditySha3(contractAddress, user.code), | |
user.signature | |
).toLowerCase(); | |
if (issuer !== provider.address) { | |
res.status(400); | |
return res.send({'status': 'error', 'message': 'Invalid code or signature'}); | |
} | |
let privateKey = bufferToHex(provider.wallet._privKey); | |
let hash = w3.utils.soliditySha3(contractAddress, user.address, user.code); | |
let redeemSignature = w3.eth.accounts.sign(hash, privateKey); | |
let result = { | |
'status': 'ok', | |
'redeemer': user.address, | |
'code': user.code, | |
'redeemSignature': redeemSignature.signature, | |
}; | |
res.send(result); | |
} catch (e) { | |
console.error(e); | |
res.status(500); | |
return res.send({'status': 'no', 'message': e.message}); | |
} | |
}); | |
module.exports = router; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment