-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.js
More file actions
172 lines (158 loc) · 4.59 KB
/
lib.js
File metadata and controls
172 lines (158 loc) · 4.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
require('dotenv').config();
const fetch = require('node-fetch');
const mutinyNetUrl = process.env.MUTINYNET_URL ?? "https://mutinynet.com/api"
const newUTXOThreshold = process.env.NEW_UTXO_THRESHOLD ?? 900 // experimental feature and possible address reuse (bad practice, but might be nice for dev envs)
const pollingInterval = process.env.POLLING_INTERVAL ?? 3000 // 3 seconds
async function getCurrentBlockTip() {
const url = `${mutinyNetUrl}/blocks/tip/height`
const resp = await fetch(url);
const tip = await resp.json();
// console.log("tip", tip);
return tip
}
async function getLastUtxo(address) {
try {
const url = `${mutinyNetUrl}/address/${address}/utxo`
const resp = await fetch(url);
const json = await resp.json()
const lastUtxo = json[json.length - 1]
return lastUtxo
} catch (e){
return undefined
}
}
async function isConfirmed(lastUtxo) {
try {
const confirmed = lastUtxo.status.confirmed === true
if (confirmed) {
return true
}
} catch (e) {
return false
}
return false
}
async function isPaid(lastUtxo, amount) {
try {
const paid = lastUtxo.value >= amount
return paid
} catch(e){
return false
}
}
async function isPaymentConfirmed(lastUtxo) {
try {
const confirmations = process.env.CONFIRMATIONS // 0 for zero conf
const confirmationBlock = lastUtxo.status.block_height
const tip = await getCurrentBlockTip()
const confirmationCount = tip - confirmationBlock
if (confirmationCount >= confirmations) return true
} catch (e){
console.error(e)
}
return false
}
async function isNewUTXO(lastUtxo) {
try {
const tip = await getCurrentBlockTip()
const isNewUTXO = tip - lastUtxo.status.block_height <= newUTXOThreshold
return isNewUTXO
} catch(e){
return false
}
}
async function getTxnHex(txid) {
const url = `${mutinyNetUrl}/tx/${txid}/hex`
const resp = await fetch(url);
const txnHex = await resp.text()
return txnHex
}
async function buildBlockHookResponse({
address,
network = "testnet",
confirmations,
metadata
}) {
const lastUtxo = await getLastUtxo(address)
const txid = lastUtxo.txid
const txnHex = await getTxnHex(txid)
let timestamp = lastUtxo?.status?.block_time * 1000 // convert to milliseconds
if (isNaN(timestamp) || !timestamp){
timestamp = new Date().getTime()
}
const blockhookResp = {
address,
txid,
"hex": txnHex,
network,
confirmations,
timestamp,
metadata
};
return blockhookResp
}
async function sendWebhook(blockhookResp,) {
try {
const resp = await fetch(blockhookResp.webhook, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(blockhookResp),
});
console.log(`Sent webhook for ${blockhookResp.address} with ${blockhookResp.confirmations} confirmations`)
} catch (e) {
console.error("webhook error", e)
}
}
function addressWatcher({
address,
network,
confirmations,
metadata,
amount,
webhook
}) {
return new Promise((resolve, reject) => {
const intervalId = setInterval(async () => {
try {
const lastUtxo = await getLastUtxo(address);
const confirmed = await isConfirmed(lastUtxo);
const paid = await isPaid(lastUtxo, amount);
const newUTXO = await isNewUTXO(lastUtxo);
if (lastUtxo && address) {
const confirmationBlock = lastUtxo?.status?.block_height
const tip = await getCurrentBlockTip()
const confirmationCount = tip - confirmationBlock
const blockhooksResp = await buildBlockHookResponse({
address,
network,
confirmations: confirmationCount ? confirmationCount : 0,
metadata,
amount,
});
blockhooksResp.webhook = webhook
// console.log("paid! send webhook", blockhooksResp);
await sendWebhook(blockhooksResp)
resolve(blockhooksResp);
// stop the watchers for confirmed payment
const paymentConfirmed = await isPaymentConfirmed(lastUtxo);
if (paymentConfirmed && confirmationCount >= 6) {
console.log(`Payment Confirmed! Clearing watcher for ${address} with ${confirmationCount} confs`)
clearInterval(intervalId);
}
} else {
console.log(`mempool watching address ${address}, no activity yet`);
}
} catch (error) {
console.error('An error occurred:', error);
clearInterval(intervalId);
reject(error);
}
}, pollingInterval);
});
}
module.exports = {
addressWatcher,
buildBlockHookResponse,
}