Created
August 3, 2018 07:47
-
-
Save shingonu/9b19671294f0d733b98dd0f44c73a1b7 to your computer and use it in GitHub Desktop.
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
| api.post('/swapper/:address', async (req, res, next) => { | |
| const abiPath = path.join(__dirname, '..', '..', 'contracts', 'HanwhaTokenSwapper.json'); | |
| const abi = JSON.parse(fs.readFileSync(abiPath).toString()).abi; | |
| const contract = new web3.eth.Contract(abi, req.params.address); | |
| const from = process.env.OPERATOR_ADDRESS; | |
| let nonce; | |
| try { | |
| nonce = await web3.eth.getTransactionCount(from); | |
| } catch (err) { | |
| return res.status(400).json({ | |
| code: 1, | |
| message: err.message, | |
| }); | |
| } | |
| const privateKey = new Buffer(process.env.OPERATOR_PRIVATE_KEY, 'hex'); | |
| const method = req.body.method; | |
| const bytecode = getBytecode(web3, abi, method, req.body.params); | |
| const values = Object.values(req.body.params); | |
| let gas; | |
| try { | |
| gas = | |
| await contract.methods[method](...values).estimateGas({ | |
| from: from, | |
| }); | |
| } catch (err) { | |
| return res.status(400).json({ | |
| code: 1, | |
| message: err.message, | |
| }); | |
| } | |
| const rawTx = { | |
| nonce: nonce, | |
| chainId: await web3.eth.net.getId(), | |
| to: req.params.address, | |
| data: bytecode, | |
| gasPrice: '22e9', | |
| gas: parseInt(gas * 1.2), | |
| }; | |
| const tx = new Tx(rawTx); | |
| tx.sign(privateKey); | |
| const serializedTx = tx.serialize().toString('hex'); | |
| try { | |
| web3.eth.sendSignedTransaction('0x' + serializedTx) | |
| .on('receipt', receipt => { | |
| return res.status(200).json({ | |
| code: 0, | |
| message: 'success', | |
| response: { | |
| txhash: receipt.transactionHash, | |
| } | |
| }); | |
| }) | |
| .on('error', error => { | |
| return res.status(400).json({ | |
| code: 1, | |
| message: error.message, | |
| }); | |
| }); | |
| } catch (err) { | |
| return res.status(400).json({ | |
| code: 1, | |
| message: err.message, | |
| }); | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment