forked from webaverse/api-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
account-manager.js
94 lines (85 loc) · 2.32 KB
/
account-manager.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
const AWS = require('aws-sdk');
const blockchain = require('./blockchain.js');
let config = require('fs').existsSync('./config.json') ? require('./config.json') : null;
const accessKeyId = process.env.accessKeyId || config.accessKeyId;
const secretAccessKey = process.env.secretAccessKey || config.secretAccessKey;
const awsConfig = new AWS.Config({
credentials: new AWS.Credentials({
accessKeyId,
secretAccessKey,
}),
region: 'us-west-1',
});
const ddb = new AWS.DynamoDB(awsConfig);
const tableName = 'users';
const keyName = 'test-users.cache';
const _makePromise = () => {
let accept, reject;
const p = new Promise((a, r) => {
accept = a;
reject = r;
});
p.accept = accept;
p.reject = reject;
return p;
};
const MAX_CACHED_USERS = 5;
class AccountManager {
constructor() {
this.users = [];
this.queue = [];
this.load();
}
async load() {
const tokenItem = await ddb.getItem({
TableName: tableName,
Key: {
email: {S: keyName},
}
}).promise();
this.users = tokenItem.Item ? JSON.parse(tokenItem.Item.users.S) : [];
// console.log('got old', this.users);
const _save = async () => {
await ddb.putItem({
TableName: tableName,
Item: {
email: {S: keyName},
users: {S: JSON.stringify(this.users)},
}
}).promise();
};
const _flush = async () => {
while (this.queue.length > 0 && this.users.length > 0) {
this.queue.shift()(this.users.shift());
}
await _save();
};
await _flush();
const _recurse = async () => {
while (this.users.length < MAX_CACHED_USERS) {
const mnemonic = blockchain.makeMnemonic();
const userKeys = await blockchain.genKeys(mnemonic);
const address = await blockchain.createAccount(userKeys, {
bake: true,
});
userKeys.mnemonic = mnemonic;
userKeys.address = address;
this.users.push(userKeys);
await _flush();
}
setTimeout(_recurse, 1000);
};
setTimeout(_recurse, 1000);
}
async getAccount() {
if (this.users.length > 0) {
return this.users.shift();
} else {
const p = _makePromise();
this.queue.push(p.accept);
return await p;
}
}
}
const accountManager = new AccountManager();
module.exports = accountManager;