-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathutils.js
More file actions
484 lines (419 loc) · 16.8 KB
/
Copy pathutils.js
File metadata and controls
484 lines (419 loc) · 16.8 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
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
const steem = require('steem');
require('dotenv').config();
// ----------------------------------------------
// blockchain data functions
// ----------------------------------------------
// get dynamic global properties from blockchain
function getDynamicGlobalProperties() {
return new Promise((resolve, reject) => {
steem.api.getDynamicGlobalProperties((err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
}
// send unsigned transaction to blockchain
function sendTransaction(transaction, privateKey) {
return new Promise((resolve, reject) => {
steem.broadcast.send(transaction, privateKey, (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
}
// broadcast signed transaction to blockchain
function broadcastTransaction(signedTransaction) {
return new Promise((resolve, reject) => {
steem.api.broadcastTransaction(signedTransaction, (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
}
// get account data from blockchain
function getAccount(account) {
return new Promise((resolve, reject) => {
steem.api.getAccounts([account], (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
}
// get order book from internal market
function getOrderBook() {
return new Promise((resolve, reject) => {
steem.api.getOrderBook(30, (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
}
// ----------------------------------------------
// blockchain data helper functions
// ----------------------------------------------
// get account metadata from blockchain
async function getJsonMetadata(accountName) {
const [account] = await getAccount(accountName)
let json_metadata = {};
try {
json_metadata = JSON.parse(account.posting_json_metadata)
} catch (error) {
console.log(error)
}
return json_metadata;
}
// get account balance from blockchain
async function getBalances(accountName) {
const [account] = await getAccount(accountName)
const sbdBalance = parseFloat(account['sbd_balance'].split(' ')[0]);
const steemBalance = parseFloat(account['balance'].split(' ')[0]);
return { sbdBalance, steemBalance };
}
// ----------------------------------------------
// transaction helper functions
// ----------------------------------------------
// get blank transaction object for new transaction
async function getBlankTransaction() {
const expireTime = 1000 * 3000;
const globalProps = await getDynamicGlobalProperties();
const ref_block_num = globalProps.head_block_number & 0xFFFF;
const ref_block_prefix = Buffer.from(globalProps.head_block_id, 'hex').readUInt32LE(4);
return {
ref_block_num,
ref_block_prefix,
expiration: new Date(Date.now() + expireTime).toISOString().slice(0, -5),
operations: [],
extensions: []
};
}
// check if transaction is valid for the purpose of selling and burning
function transactionIsValid(operations) {
// transfer: max 3 operations allowed
// burn: max 2 operations allowed
// transfer: transfer to market account, to null and transfer back to dao account
// burn: transfer to null account and sell SBD
if (operations.length > 3 ||
(process.env.PROCESS_TYPE === 'burn' && operations.length > 2)
) {
return false;
}
switch (process.env.PROCESS_TYPE) {
case 'transfer':
// allowed are only transfer operations
// and to accounts specified in allowedAccounts
const allowedAccounts = [process.env.SEND_TO, 'steem.dao', 'null'];
return operations.every(operation =>
operation[0] === 'transfer' &&
allowedAccounts.includes(operation[1].to)
);
case 'burn':
// allowed are only transfer to null and limit_order_create operations
return operations.every(operation =>
operation[0] === 'limit_order_create' ||
(operation[0] === 'transfer' && operation[1].to === 'null')
);
}
}
// check if transaction is expired
function transactionIsExpired(transaction) {
return new Date(transaction.expiration) < new Date();
}
//----------------------------------------------
// operations helper functions
//----------------------------------------------
// get operations for all processes
async function getOperations() {
let ops = [];
const { sbdBalance, steemBalance } = await getBalances(process.env.MULTISIG_ACCOUNT);
switch (process.env.PROCESS_TYPE) {
case 'transfer':
if (sbdBalance > 0) {
const {sbdToMarket, sbdToNull, sbdToDao} = getSbdAmountsForTransferProcess(sbdBalance);
if (sbdToMarket > 0) {
// transfer AMOUNT_SBD_TO_MARKET to market account
ops.push(getTransferOperation(
sbdToMarket,
'SBD',
process.env.MULTISIG_ACCOUNT,
process.env.SEND_TO,
'DAO amount for selling and burning')
)
}
if (sbdToNull > 0) {
// transfer AMOUNT_SBD_TO_NULL to null account
ops.push(getTransferOperation(
sbdToNull,
'SBD',
process.env.MULTISIG_ACCOUNT,
'null',
'DAO amount for direct burning')
)
}
if (sbdToDao > 0) {
// transfer remaining amount back to dao
ops.push(getTransferOperation(
sbdToDao,
'SBD',
process.env.MULTISIG_ACCOUNT,
'steem.dao',
'DAO amount not used for selling and burning (return to DAO)')
)
}
}
break;
case 'burn':
if (steemBalance > 0) {
// transfer all STEEM to null
ops.push(getTransferOperation(
steemBalance,
'STEEM',
process.env.MULTISIG_ACCOUNT,
'null',
'Burning STEEM from sold DAO funds')
)
}
if (sbdBalance > 0) {
// try to sell all SBD on internal market
const {steemToBuy, sbdToSell} = await getAmountsForOrderOperation(sbdBalance);
ops.push(getOrderOperation(
process.env.MULTISIG_ACCOUNT,
Math.min(sbdBalance, sbdToSell),
steemToBuy)
)
}
break;
}
if (ops.length === 0) {
throw new Error('No operations generated (sbd and steem balance is 0)');
}
return ops;
}
// get account update operation
function getAccountUpdateOperation(accountName, posting_json_metadata) {
return [
'account_update2',
{
'account': accountName,
'json_metadata': '',
'posting_json_metadata': posting_json_metadata
}
];
}
// get transfer operation
function getTransferOperation(amount, unit, from, to, memo = '') {
return [
'transfer',
{
'amount': amount.toFixed(3) + ' ' + unit.toUpperCase(),
'from': from,
'memo': memo,
'to': to
}
];
}
// get order operation
function getOrderOperation(account, sbdToSell, steemToBuy) {
// create unique order id from timestamp
const orderId = Math.floor(Date.now() / 1000);
const expireTime = 1000 * 3000;
return [
'limit_order_create',
{
'owner': account,
'orderid': orderId,
'amount_to_sell': sbdToSell.toFixed(3) + ' SBD',
'min_to_receive': steemToBuy.toFixed(3) + ' STEEM',
'fill_or_kill': false,
'expiration': new Date(Date.now() + expireTime).toISOString().slice(0, -5)
}
];
}
// get STEEM / SBD amounts for order operation
async function getAmountsForOrderOperation(sbdToSell) {
const orderBook = await getOrderBook();
if (!orderBook || orderBook.asks.length === 0) {
throw new Error('Order book asks missing or empty');
}
let sbdAvailableInt = 0;
let i = 0;
let real_price = '';
// to avoid sweeping the order book:
// if not enough SBD in order bool sell only a share of available SBD
const maxShareForSell = 3 / 4;
// SBD and STEEM amounts are stored as integers
const precision = 3;
let sbdToSellInt = Math.floor(sbdToSell * 10 ** precision);
// get STEEM amount to sell all SBD
// loop over all asks until enough SBD are available
// last real_price is the price to sell all SBD
while (sbdAvailableInt < sbdToSellInt && i < orderBook.asks.length) {
sbdAvailableInt += orderBook.asks[i].sbd;
real_price = orderBook.asks[i].real_price;
i++;
}
if (sbdAvailableInt < sbdToSellInt) {
sbdToSellInt = Math.floor(sbdAvailableInt * maxShareForSell);
}
if (!real_price) {
throw new Error('Could not determine price from order book');
}
// console.log('real_price:', real_price);
let price = parseFloat(real_price);
// add a markup to sale in any case (0.5%)
price *= 1.005;
// console.log('price:', price);
const steemToBuyInt = Math.floor(sbdToSellInt / price);
const steemToBuy = steemToBuyInt / 10 ** precision;
const sbdToSellUsed = sbdToSellInt / 10 ** precision;
return { steemToBuy, sbdToSell: sbdToSellUsed };
}
// get shares of SBD balance for transfer process
// 1: SBD to market
// 2: SBD to null
// 3: SBD back to dao
function getSbdAmountsForTransferProcess(sbdBalance) {
// calculate with integers
const precision = 3;
const factor = 10 ** precision;
// helpers to convert float to int and back
const toInt = (n) => Math.floor(n * factor);
const toFloat = (i) => Number((i / factor).toFixed(precision));
const envSbdToMarketInt = toInt(parseFloat(process.env.AMOUNT_SBD_TO_MARKET));
if (Number.isNaN(envSbdToMarketInt)) {
throw new Error('env variable AMOUNT_SBD_TO_MARKET is missing or not a number');
}
const envSbdToNullInt = toInt(parseFloat(process.env.AMOUNT_SBD_TO_NULL));
if (Number.isNaN(envSbdToNullInt)) {
throw new Error('env variable AMOUNT_SBD_TO_NULL is missing or not a number');
}
const sbdBalanceInt = toInt(sbdBalance);
let sbdUnusedInt = sbdBalanceInt;
// first priority: AMOUNT_SBD_TO_MARKET
const sbdToMarketInt = Math.min(sbdBalanceInt, envSbdToMarketInt);
sbdUnusedInt -= sbdToMarketInt;
// second priority: AMOUNT_SBD_TO_NULL
const sbdToNullInt = Math.min(sbdUnusedInt, envSbdToNullInt);
sbdUnusedInt -= sbdToNullInt;
// remaining SBD back to dao
const sbdToDaoInt = Math.max(0, sbdUnusedInt);
return {
sbdToMarket: toFloat(sbdToMarketInt),
sbdToNull: toFloat(sbdToNullInt),
sbdToDao: toFloat(sbdToDaoInt)
};
}
//----------------------------------------------
// multisig chaining functions
//----------------------------------------------
// get account name of previous account in multisig chain
function getPreviousAccountName(context) {
return context.accountIndex > 0 ? context.multisigAccounts[context.accountIndex - 1] : null;
}
// get transaction stored in json_metadata from previous or second last account
async function getPreviousTransaction(context) {
const { accountIndex, metadataKey } = context;
let previousAccountName = getPreviousAccountName(context);
let previous_json_metadata = await getJsonMetadata(previousAccountName);
if (!previous_json_metadata[metadataKey]) {
// console.log(`No transaction data found in '${previousAccountName}'`);
throw new Error(`No transaction data found in '${previousAccountName}'`);
}
let previousTx = JSON.parse(previous_json_metadata[metadataKey])
// if transaction is expired, get transaction from second last account - if exists
if (accountIndex > 1 && transactionIsExpired(previousTx)) {
console.log(`Transaction from '${previousAccountName}' expired, get transaction from second last account`);
previousAccountName = getPreviousAccountName({ ...context, accountIndex: accountIndex - 1 });
previous_json_metadata = await getJsonMetadata(previousAccountName);
previousTx = JSON.parse(previous_json_metadata[metadataKey])
}
if (!transactionIsValid(previousTx.operations)) {
// console.log(`Transaction data from '${previousAccountName}' mismatch`);
throw new Error(`Transaction from '${previousAccountName}' invalid\noperations: '${JSON.stringify(previousTx.operations)}'`);
}
if (transactionIsExpired(previousTx)) {
// console.log(`Transaction from '${previousAccountName}' expired, no more transactions to get`);
throw new Error(`Transactions from '${previousAccountName}' expired\nexpiration: '${previousTx.expiration}'`);
}
return previousTx;
}
// ----------------------------------------------
// transaction processing functions
// ----------------------------------------------
// create transaction for the first account in multisig chain (multisigAccount)
function createPublishTx(context) {
return new Promise(async (resolve, reject) => {
try {
const { accountName, metadataKey } = context;
// create transaction with necessary operations
let transaction = await getBlankTransaction();
transaction.operations = await getOperations();
const signedTransaction = steem.auth.signTransaction(transaction, [process.env.ACTIVE_KEY]);
// add signed transaction to account metadata
let json_metadata = await getJsonMetadata(accountName);
json_metadata[metadataKey] = JSON.stringify(signedTransaction)
// update account metadata with signed transaction
const ops = [
getAccountUpdateOperation(accountName, JSON.stringify(json_metadata))
];
let finalTx = { operations: ops, extensions: [] };
const tx = await sendTransaction(finalTx, { posting: process.env.POSTING_KEY })
resolve(tx)
} catch (error) {
reject(error)
}
})
}
// sign previous transaction for all accounts in multisig chain except the first and last account
async function signPublishTx(context) {
return new Promise(async (resolve, reject) => {
try {
const { accountName, metadataKey } = context;
// get transaction from previous or second last account and sign it
const previousTx = await getPreviousTransaction(context);
const signedTransaction = steem.auth.signTransaction(previousTx, [process.env.ACTIVE_KEY]);
// add signed transaction to account metadata
let json_metadata = await getJsonMetadata(accountName);
json_metadata[metadataKey] = JSON.stringify(signedTransaction)
// update account metadata with signed transaction
const ops = [
getAccountUpdateOperation(accountName, JSON.stringify(json_metadata))
];
let finalTx = { operations: ops, extensions: [] };
const tx = await sendTransaction(finalTx, { posting: process.env.POSTING_KEY })
resolve(tx)
} catch (error) {
reject(error)
}
})
}
// sign previous transaction for the last account in multisig chain and broadcast it to blockchain
async function signSendTx(context) {
return new Promise(async (resolve, reject) => {
try {
// get transaction from previous or second last account and sign it
const previousTx = await getPreviousTransaction(context);
const signedTransaction = steem.auth.signTransaction(previousTx, [process.env.ACTIVE_KEY]);
// broadcast signed transaction
const tx = await broadcastTransaction(signedTransaction)
resolve(tx)
} catch (error) {
reject(error)
}
})
}
module.exports = { createPublishTx, signPublishTx, signSendTx }