Skip to content

Instantly share code, notes, and snippets.

@HOllarves
Last active February 6, 2019 10:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HOllarves/eae12358929e0e5bfd65d89f4cbc6207 to your computer and use it in GitHub Desktop.
Save HOllarves/eae12358929e0e5bfd65d89f4cbc6207 to your computer and use it in GitHub Desktop.
BCOIN bitcoin handler
const eventListeners = async (walletClient, nodeClient) => {
const db = require("mongoose")
const IncomingTx = require("../models/IncomingTx")
await walletClient.open()
await nodeClient.open()
/**
* This event is fired everytime a new
* block is published in the blockchain
*/
nodeClient.bind("chain connect", async () => {
const unconfirmedTxs = await IncomingTx.find({ confirmed: false })
if (unconfirmedTxs && unconfirmedTxs.length > 0) {
for (let i = 0; i < unconfirmedTxs.length; i++) {
const utx = unconfirmedTxs[i]
const tx = await walletClient.getTX("primary", utx.txId)
if (tx.confirmations >= 4) {
try {
await commitTransaction(utx)
} catch (e) {
throw new Error(e)
}
}
}
}
})
/**
* We initialize event binding on "connect" event
*/
walletClient.on("connect", () => {
walletClient.all()
})
/**
* Transactions event binding.
* Everytime a new transaction is broadcasted to one of our addesses
* it will return the id of the wallet (primary by default) and the
* transaction details
*/
walletClient.bind("tx", async (id, details) => {
const outputs = details.outputs
const ourOutput = outputs.filter(val => { return val.path !== null })[0]
if (ourOutput) {
const value = ourOutput.value
const userId = "auth0|" + ourOutput.path.name
const txId = details.hash
try {
const newIncomingTx = new IncomingTx({ userId, value, txId })
await newIncomingTx.save()
} catch (e) {
throw new Error(e)
}
}
})
}
module.exports = { eventListeners }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment