-
Notifications
You must be signed in to change notification settings - Fork 3
/
dashapi.js
264 lines (223 loc) · 7.02 KB
/
dashapi.js
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
(function (exports) {
"use strict";
let Dash = {};
//@ts-ignore
exports.DashApi = Dash;
const DUFFS = 100000000;
const DUST = 10000;
const FEE = 1000;
//@ts-ignore
let Dashcore = exports.dashcore || require("./lib/dashcore.js");
let Transaction = Dashcore.Transaction;
Dash.create = function ({
//@ts-ignore TODO
insightApi,
}) {
let dashApi = {};
/**
* Instant Balance is accurate with Instant Send
* @param {String} address
* @returns {Promise<InstantBalance>}
*/
dashApi.getInstantBalance = async function (address) {
let body = await insightApi.getUtxos(address);
let utxos = await getUtxos(body);
let balance = utxos.reduce(function (total, utxo) {
return total + utxo.satoshis;
}, 0);
// because 0.1 + 0.2 = 0.30000000000000004,
// but we would only want 0.30000000
let floatBalance = parseFloat((balance / DUFFS).toFixed(8));
return {
addrStr: address,
balance: floatBalance,
balanceSat: balance,
_utxoCount: utxos.length,
_utxoAmounts: utxos.map(function (utxo) {
return utxo.satoshis;
}),
};
};
/**
* Full Send!
* @param {String} privKey
* @param {String} pub
*/
dashApi.createBalanceTransfer = async function (privKey, pub) {
let pk = new Dashcore.PrivateKey(privKey);
let changeAddr = pk.toPublicKey().toAddress().toString();
let body = await insightApi.getUtxos(changeAddr);
let utxos = await getUtxos(body);
let balance = utxos.reduce(function (total, utxo) {
return total + utxo.satoshis;
}, 0);
//@ts-ignore - no input required, actually
let tmpTx = new Transaction()
//@ts-ignore - allows single value or array
.from(utxos);
tmpTx.to(pub, balance - 1000);
tmpTx.sign(pk);
// TODO getsmartfeeestimate??
// fee = 1duff/byte (2 chars hex is 1 byte)
// +10 to be safe (the tmpTx may be a few bytes off)
let fee = 10 + tmpTx.toString().length / 2;
//@ts-ignore - no input required, actually
let tx = new Transaction()
//@ts-ignore - allows single value or array
.from(utxos);
tx.to(pub, balance - fee);
tx.fee(fee);
tx.sign(pk);
return tx;
};
/**
* Send with change back
* @param {String} privKey
* @param {(String|import('@dashevo/dashcore-lib').Address)} payAddr
* @param {Number} amount
* @param {(String|import('@dashevo/dashcore-lib').Address)} [changeAddr]
*/
dashApi.createPayment = async function (
privKey,
payAddr,
amount,
changeAddr,
) {
let pk = new Dashcore.PrivateKey(privKey);
let utxoAddr = pk.toPublicKey().toAddress().toString();
if (!changeAddr) {
changeAddr = utxoAddr;
}
// TODO make more accurate?
let feePreEstimate = 1000;
let utxos = await getOptimalUtxos(utxoAddr, amount + feePreEstimate);
let balance = getBalance(utxos);
if (!utxos.length) {
throw new Error(`not enough funds available in utxos for ${utxoAddr}`);
}
// (estimate) don't send dust back as change
if (balance - amount <= DUST + FEE) {
amount = balance;
}
//@ts-ignore - no input required, actually
let tmpTx = new Transaction()
//@ts-ignore - allows single value or array
.from(utxos);
tmpTx.to(payAddr, amount);
//@ts-ignore - the JSDoc is wrong in dashcore-lib/lib/transaction/transaction.js
tmpTx.change(changeAddr);
tmpTx.sign(pk);
// TODO getsmartfeeestimate??
// fee = 1duff/byte (2 chars hex is 1 byte)
// +10 to be safe (the tmpTx may be a few bytes off - probably only 4 -
// due to how small numbers are encoded)
let fee = 10 + tmpTx.toString().length / 2;
// (adjusted) don't send dust back as change
if (balance + -amount + -fee <= DUST) {
amount = balance - fee;
}
//@ts-ignore - no input required, actually
let tx = new Transaction()
//@ts-ignore - allows single value or array
.from(utxos);
tx.to(payAddr, amount);
tx.fee(fee);
//@ts-ignore - see above
tx.change(changeAddr);
tx.sign(pk);
return tx;
};
// TODO make more optimal
/**
* @param {String} utxoAddr
* @param {Number} fullAmount - including fee estimate
*/
async function getOptimalUtxos(utxoAddr, fullAmount) {
// get smallest coin larger than transaction
// if that would create dust, donate it as tx fee
let body = await insightApi.getUtxos(utxoAddr);
let utxos = await getUtxos(body);
let balance = getBalance(utxos);
if (balance < fullAmount) {
return [];
}
// from largest to smallest
utxos.sort(function (a, b) {
return b.satoshis - a.satoshis;
});
/** @type Array<CoreUtxo> */
let included = [];
let total = 0;
// try to get just one
utxos.every(function (utxo) {
if (utxo.satoshis > fullAmount) {
included[0] = utxo;
total = utxo.satoshis;
return true;
}
return false;
});
if (total) {
return included;
}
// try to use as few coins as possible
utxos.some(function (utxo) {
included.push(utxo);
total += utxo.satoshis;
return total >= fullAmount;
});
return included;
}
/**
* @param {Array<CoreUtxo>} utxos
*/
function getBalance(utxos) {
return utxos.reduce(function (total, utxo) {
return total + utxo.satoshis;
}, 0);
}
/**
* @param {Array<InsightUtxo>} body
*/
async function getUtxos(body) {
/** @type Array<CoreUtxo> */
let utxos = [];
await body.reduce(async function (promise, utxo) {
await promise;
let data = await insightApi.getTx(utxo.txid);
// TODO the ideal would be the smallest amount that is greater than the required amount
let utxoIndex = -1;
/**
* @template {InsightTxVout} T
* @param {T} vout
* @param {Number} index
* @returns {Boolean}
*/
function findAndSetUtxoIndex(vout, index) {
if (!vout.scriptPubKey?.addresses?.includes(utxo.address)) {
return false;
}
let satoshis = Math.round(parseFloat(vout.value) * DUFFS);
if (utxo.satoshis !== satoshis) {
return false;
}
utxoIndex = index;
return true;
}
data.vout.some(findAndSetUtxoIndex);
utxos.push({
txId: utxo.txid,
outputIndex: utxoIndex,
address: utxo.address,
script: utxo.scriptPubKey,
satoshis: utxo.satoshis,
});
}, Promise.resolve());
return utxos;
}
return dashApi;
};
if ("undefined" !== typeof module) {
module.exports = Dash;
}
})(("undefined" !== typeof module && module.exports) || window);