-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreturnAllNanoToFaucet.js
More file actions
243 lines (213 loc) · 6.48 KB
/
returnAllNanoToFaucet.js
File metadata and controls
243 lines (213 loc) · 6.48 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
const AWS = require('aws-sdk');
const nano_client = require('@nanobox/nano-client');
require('dotenv').config();
const FAUCET_PUBLIC_KEY = process.env.FAUCET_PUBLIC_KEY,
FAUCET_PRIVATE_KEY = process.env.FAUCET_PRIVATE_KEY,
FAUCET_ADDRESS = process.env.FAUCET_ADDRESS;
const DDB_WALLET_TABLE_NAME = 'TryNanoWallets';
const c = new nano_client.NanoClient({
url: 'https://proxy.powernode.cc/proxy',
});
const ddb = new AWS.DynamoDB({
region: 'us-west-1',
});
/**
* Entry-point for the ReturnAllNanoToFaucet AWS Lambda function.
*
* @param {APIGatewayProxyEvent} event CloudWatch Event object
* @returns {HttpResponse} Http response object
*/
exports.handler = async (event) => {
try {
console.log(`event: ${JSON.stringify(event)}`);
const error = validateState();
if (error) {
return response(500, { error: error });
}
// Get Faucet account info to check things like the current balance
const accountInfo = await c.updateWalletAccount({
address: FAUCET_ADDRESS,
publicKey: FAUCET_PUBLIC_KEY,
privateKey: FAUCET_PRIVATE_KEY,
});
if (!accountInfo) {
return response(500, { error: `unable to retrieve faucet account info` });
}
const previousFaucetBalance = accountInfo.balance.asString;
// Try to return all non-zero nano balances back to the TryNano faucet
const returnToFaucetRes = await returnAllNanoToFaucet();
if (returnToFaucetRes.error) {
return response(500, {
error: returnToFaucetRes.error,
});
}
// Confirm any pending faucet transactions so the balance is fully up to date
const receiveRes = await receivePendingFaucetTransactions();
if (receiveRes.error) {
return response(500, {
error: receiveRes.error,
});
}
const res = response(200, {
walletCount: returnToFaucetRes.walletCount,
previousFaucetBalance: previousFaucetBalance,
updatedFaucetBalance: receiveRes.updatedFaucetBalance,
resolvedCount: receiveRes.resolvedCount,
});
// Show the final response in the logs
console.log(`response: ${JSON.stringify(res)}`);
return res;
} catch (err) {
console.log(`caught error: ${err.message}`);
return response(500, { error: err.message });
}
};
/**
* Gets all non-zero balance nano accounts that haven't been used for at least 1 hour,
* and sends all their nano to the TryNano faucet.
*
* @returns Wallet count if successful, error if not successful
*/
async function returnAllNanoToFaucet() {
const res = await ddb
.scan({
TableName: DDB_WALLET_TABLE_NAME,
ProjectionExpression:
'walletID, publicKey, privateKey, balance, returnToFaucetEpoch',
FilterExpression: 'returnToFaucetEpoch < :t AND balance > :z',
ExpressionAttributeValues: {
':t': { N: Date.now().toString() },
':z': { N: '0' },
},
})
.promise();
console.log(`ddb scan result: ${JSON.stringify(res)}`);
if (!res.Items) {
return {
error: 'database scan results were not defined',
};
}
const sendNanoFromWallets = async () => {
console.log('Start sending nano');
await asyncForEach(res.Items, async (item) => {
const wallet = AWS.DynamoDB.Converter.unmarshall(item);
const accountInfo = await c.updateWalletAccount({
address: wallet.walletID,
publicKey: wallet.publicKey,
privateKey: wallet.privateKey,
});
console.log(
`Returning nano for accountInfo: ${JSON.stringify(accountInfo)}`
);
if (accountInfo.balance.asNumber === 0) {
console.log("Can't send 0 nano, updating balance to 0 and skipping...");
await updateNanoBalanceInDB(
accountInfo.address,
accountInfo.balance.asString
);
} else {
// now send all the nano in this wallet to the faucet
const sendRes = await c.sendMax(accountInfo, FAUCET_ADDRESS);
if (!sendRes) {
return {
error: 'send operation returned undefined',
};
}
const updatedBalance = sendRes.balance.asString;
// finally, update the wallet balance in the database
await updateNanoBalanceInDB(accountInfo.address, updatedBalance);
}
});
console.log('Done sending nano');
};
// run async/await on a loop to wait for all wallets to send their nano
await sendNanoFromWallets();
return {
walletCount: res.Count,
};
}
/**
* Updates the balance for a TryNano wallet in DynamoDB.
*
* @param {string} address the address of the nano account
* @param {string} updatedBalance the updated wallet balance
*/
async function updateNanoBalanceInDB(address, updatedBalance) {
await ddb
.updateItem({
TableName: DDB_WALLET_TABLE_NAME,
Key: {
walletID: {
S: address,
},
},
UpdateExpression: 'SET balance = :u',
ExpressionAttributeValues: {
':u': {
N: updatedBalance,
},
},
ReturnValues: 'UPDATED_NEW',
})
.promise();
}
/**
* Receives any pending transactions for the TryNano faucet
*
* @returns The updated faucet balance, and the number of resolved pending transactions
*/
async function receivePendingFaucetTransactions() {
const res = await c.update({
address: FAUCET_ADDRESS,
publicKey: FAUCET_PUBLIC_KEY,
privateKey: FAUCET_PRIVATE_KEY,
});
if (res.error) {
return {
error: res.error,
};
}
return {
updatedFaucetBalance: res.account.balance.asString,
resolvedCount: res.resolvedCount,
};
}
/**
* Constructs an HttpResponse object.
*
* @param {HttpStatus} code HTTP response status code
* @param {Object} body response body
* @returns {HttpResponse} HTTP response object
*/
function response(code, body) {
return {
statusCode: code,
body: body,
};
}
/**
* An async/await friendly foreach function.
*
* @param {*} array list to loop over
* @param {*} callback code to run on each list item
*/
async function asyncForEach(array, callback) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array);
}
}
/**
* Ensures all required environment variables are present.
*
* @returns {string} Error message
*/
function validateState() {
if (!FAUCET_ADDRESS) {
return 'FAUCET_ADDRESS key missing from .env - you must fix';
} else if (!FAUCET_PUBLIC_KEY) {
return 'FAUCET_PUBLIC_KEY key missing from .env - you must fix';
} else if (!FAUCET_PRIVATE_KEY) {
return 'FAUCET_PRIVATE_KEY key missing from .env - you must fix';
}
return null;
}