forked from omgnetwork/js-starter-kit
/
token-ring.js
364 lines (296 loc) · 14.7 KB
/
token-ring.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
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
const RING_TOKEN_CONTRACT_ADDRESS = '0x20050f92b21db9a6fd4a16362fc2dfb3307a2155'
const RING_TOKEN_VALUE = '1'
const RING_SIZE = 500
const RING_TOKEN_TOTAL = 5000
const RING_ETH_MULTIPLIER = 1000
const TX_RUNS = 18000
const REFRESH_RATE = 3000
const TX_COOL_DOWN = 100 // Set to 1000 for a ring size of 50 (or 50,000 / RING_SIZE) to avoid utxo errors
// The following is a bad idea - do not host your seed publicly!!!
const RING_VAULT_PASSWORD = ''
let RING_VAULT_SEED = ''
const coolDown = (milliseconds) => {
return new Promise(resolve => setTimeout(resolve, milliseconds))
}
function createRingVault () {
if(!RING_VAULT_SEED) {
RING_VAULT_SEED = prompt("Please enter your seed phrase", "<seed phrase>")
}
lightwallet.keystore.createVault({
password: RING_VAULT_PASSWORD,
seedPhrase: RING_VAULT_SEED,
hdPathString: "m/0'/0'/0'"
}, function (err, keystore) {
if (err) {
console.error(err)
return
}
globalKeystore = keystore
const web3Provider = new HookedWeb3Provider({
host: WEB3_PROVIDER_URL,
transaction_signer: globalKeystore
})
web3.setProvider(web3Provider)
rootChain = new RootChain(web3, PLASMA_CONTRACT_ADDRESS)
childChain = new ChildChain(WATCHER_URL, CHILDCHAIN_URL)
document.getElementById('RingTokenContractAddress').innerHTML = '<div>' + RING_TOKEN_CONTRACT_ADDRESS + '</div>'
globalKeystore.keyFromPassword(RING_VAULT_PASSWORD, function (err, pwDerivedKey) {
if (err) {
console.error(err)
return
}
// Generate the first 5 addresses in the wallet
globalKeystore.generateNewAddress(pwDerivedKey, RING_SIZE)
showRingBalances()
})
})
}
async function showRingBalances () {
var addresses = globalKeystore.getAddresses()
console.log('RING_TOKEN_TOTAL: ' + RING_TOKEN_TOTAL + ', RING: ' + await getBalanceOfToken(addresses[0], RING_TOKEN_CONTRACT_ADDRESS) + ', RING_ETH_TOTAL: ' + (RING_TOKEN_TOTAL * RING_ETH_MULTIPLIER) + ', ETH: ' + await getBalanceOfToken(addresses[0], OmgUtil.transaction.ETH_CURRENCY))
if((await getBalanceOfToken(addresses[0], RING_TOKEN_CONTRACT_ADDRESS) == RING_TOKEN_TOTAL) || (await getBalanceOfToken(addresses[0], OmgUtil.transaction.ETH_CURRENCY) == (RING_TOKEN_TOTAL * RING_ETH_MULTIPLIER))) {
document.getElementById('distributeButton').style.display = 'block'
}
else {
document.getElementById('distributeButton').style.display = 'none'
}
document.getElementById('RingChildchainBalance').innerHTML = ''
for(let addressIndex in addresses) {
//console.log('Index: ' + addressIndex + ' Address: ' + addresses[addressIndex])
document.getElementById('RingChildchainBalance').innerHTML += '<div>' + addressIndex + ': ' + addresses[addressIndex] + ': ' + await getBalanceOfToken(addresses[addressIndex], RING_TOKEN_CONTRACT_ADDRESS) + ' RING, ' + await getBalanceOfToken(addresses[addressIndex], OmgUtil.transaction.ETH_CURRENCY) + ' wei ETH</div>'
}
}
async function redistributeEth() {
document.getElementById('rotateButton').style.display = 'none'
var rotations = 0
while(rotations < TX_RUNS) {
//console.log(rotations + ' ' + (rotations % RING_SIZE) + ' ' + Date.now())
document.getElementById('CurrentState').innerHTML = 'Timestamp: ' + Date.now() + ' -=- Rotation: ' + rotations + ' of ' + TX_RUNS + ' -=- Index: ' + (rotations % RING_SIZE) + ' of ' + RING_SIZE + ' -=- Cool Down: ' + TX_COOL_DOWN + 'ms'
var rotateFromAddr = globalKeystore.getAddresses()[rotations % RING_SIZE]
var rotateToAddr = globalKeystore.getAddresses()[(rotations + 1) % RING_SIZE]
var surplus = await getBalanceOfToken(rotateFromAddr, OmgUtil.transaction.ETH_CURRENCY) - ((RING_TOKEN_TOTAL * RING_ETH_MULTIPLIER) / RING_SIZE)
//console.log('rotation: ' + rotations + ' index: ' + (rotations % RING_SIZE) + ' from: ' + rotateFromAddr + ' to: ' + rotateToAddr + ' surplus: ' + surplus + ' timestamp: ' + Date.now())
if(surplus > 0) {
var txCreationLog = document.getElementById('TxCreationLog').innerHTML
document.getElementById('TxCreationLog').innerHTML = '<div>' + Date.now() + ': r: ' + rotations + ' i: ' + (rotations % RING_SIZE) + ' from: ' + shortenAddress(rotateFromAddr) + ' to: ' + shortenAddress(rotateToAddr) + ' surplus: ' + surplus + '</div>' + txCreationLog
if(surplus < ((RING_TOKEN_TOTAL * RING_ETH_MULTIPLIER) / RING_SIZE)){
await rotateEth(rotateFromAddr, rotateToAddr, surplus, rotations)
}
else
{
await rotateEth(rotateFromAddr, rotateToAddr, ((RING_TOKEN_TOTAL * RING_ETH_MULTIPLIER) / RING_SIZE), rotations)
}
}
await coolDown(TX_COOL_DOWN)
if(rotations % REFRESH_RATE == REFRESH_RATE - 1)
{
showRingBalances()
}
rotations++
}
showRingBalances()
document.getElementById('rotateButton').style.display = 'block'
document.getElementById('CurrentState').innerHTML = 'Not running...'
}
async function rotateEth (tokenFrom, tokenTo, tokenValue, rotationCount) {
var fromAddr = tokenFrom
var toAddr = tokenTo
var tokenContract = OmgUtil.transaction.ETH_CURRENCY
var value = tokenValue
const utxos = await childChain.getUtxos(fromAddr)
const utxosToSpend = selectUtxos(utxos, value, tokenContract)
if (!utxosToSpend) {
console.log('No utxo big enough to cover the amount ' + value)
return
}
const txBody = {
inputs: utxosToSpend,
outputs: [{
owner: toAddr,
currency: tokenContract,
amount: Number(value)
}]
}
if (new BigNumber(utxosToSpend[0].amount).gt(new BigNumber(value))) {
// Need to add a 'change' output
const CHANGE_AMOUNT = new BigNumber(utxosToSpend[0].amount).minus(new BigNumber(value))
txBody.outputs.push({
owner: fromAddr,
currency: tokenContract,
amount: CHANGE_AMOUNT
})
}
// Create the unsigned transaction
const unsignedTx = childChain.createTransaction(txBody)
const password = RING_VAULT_PASSWORD
// Sign it
globalKeystore.keyFromPassword(password, async function (err, pwDerivedKey) {
if (err) {
console.error(err)
return
}
// Decrypt the private key
const privateKey = globalKeystore.exportPrivateKey(fromAddr, pwDerivedKey)
console.log(privateKey) // Bad idea!!!
// Sign the transaction with the private key
const signatures = await childChain.signTransaction(unsignedTx, [privateKey])
// Build the signed transaction
const signedTx = await childChain.buildSignedTransaction(unsignedTx, signatures)
// Submit the signed transaction to the childchain
const result = await childChain.submitTransaction(signedTx)
console.log(`Submitted transaction: ${JSON.stringify(result)}`)
var txSubmissionLog = document.getElementById('TxSubmissionLog').innerHTML
document.getElementById('TxSubmissionLog').innerHTML = '<div>' + Date.now() + ': r: ' + rotationCount + ' ' + shortenAddressInString(JSON.stringify(result)) + '</div>' + txSubmissionLog
})
}
async function redistributeTokens() {
document.getElementById('rotateButton').style.display = 'none'
var rotations = 0
while(rotations < TX_RUNS) {
//console.log(rotations + ' ' + (rotations % RING_SIZE) + ' ' + Date.now())
document.getElementById('CurrentState').innerHTML = 'Timestamp: ' + Date.now() + ' -=- Rotation: ' + rotations + ' of ' + TX_RUNS + ' -=- Index: ' + (rotations % RING_SIZE) + ' of ' + RING_SIZE + ' -=- Cool Down: ' + TX_COOL_DOWN + 'ms'
var rotateFromAddr = globalKeystore.getAddresses()[rotations % RING_SIZE]
var rotateToAddr = globalKeystore.getAddresses()[(rotations + 1) % RING_SIZE]
var surplus = await getBalanceOfToken(rotateFromAddr, RING_TOKEN_CONTRACT_ADDRESS) - (RING_TOKEN_TOTAL / RING_SIZE)
//console.log('rotation: ' + rotations + ' index: ' + (rotations % RING_SIZE) + ' from: ' + rotateFromAddr + ' to: ' + rotateToAddr + ' surplus: ' + surplus + ' timestamp: ' + Date.now())
if(surplus > 0) {
var txCreationLog = document.getElementById('TxCreationLog').innerHTML
document.getElementById('TxCreationLog').innerHTML = '<div>' + Date.now() + ': r: ' + rotations + ': i: ' + (rotations % RING_SIZE) + ' from: ' + shortenAddress(rotateFromAddr) + ' to: ' + shortenAddress(rotateToAddr) + ' surplus: ' + surplus + '</div>' + txCreationLog
if(surplus < (RING_TOKEN_TOTAL / RING_SIZE)) {
await rotateToken(rotateFromAddr, rotateToAddr, surplus)
}
else
{
await rotateToken(rotateFromAddr, rotateToAddr, (RING_TOKEN_TOTAL / RING_SIZE), rotations)
}
}
await coolDown(TX_COOL_DOWN)
if(rotations % REFRESH_RATE == REFRESH_RATE - 1)
{
showRingBalances()
}
rotations++
}
showRingBalances()
document.getElementById('rotateButton').style.display = 'block'
document.getElementById('CurrentState').innerHTML = 'Not running...'
}
async function rotateTokens() {
document.getElementById('rotateButton').style.display = 'none'
var rotations = 0
while(rotations < TX_RUNS) {
//console.log(rotations + ' ' + (rotations % 5) + ' ' + Date.now())
document.getElementById('CurrentState').innerHTML = 'Timestamp: ' + Date.now() + ' -=- Rotation: ' + rotations + ' of ' + TX_RUNS + ' -=- Index: ' + (rotations % RING_SIZE) + ' of ' + RING_SIZE + ' -=- Cool Down: ' + TX_COOL_DOWN + 'ms'
var rotateFromAddr = globalKeystore.getAddresses()[rotations % RING_SIZE]
var rotateToAddr = globalKeystore.getAddresses()[(rotations + 1) % RING_SIZE]
//console.log('rotation: ' + rotations + ' index: ' + (rotations % 5) + ' from: ' + rotateFromAddr + ' to: ' + rotateToAddr + ' timestamp: ' + Date.now())
var txCreationLog = document.getElementById('TxCreationLog').innerHTML
document.getElementById('TxCreationLog').innerHTML = '<div>' + Date.now() + ': r: ' + rotations + ' i: ' + (rotations % RING_SIZE) + ' from: ' + shortenAddress(rotateFromAddr) + ' to: ' + shortenAddress(rotateToAddr) + '</div>' + txCreationLog
await rotateToken(rotateFromAddr, rotateToAddr, RING_TOKEN_VALUE, rotations)
await coolDown(TX_COOL_DOWN)
if(rotations % REFRESH_RATE == REFRESH_RATE - 1)
{
showRingBalances()
}
rotations++
}
showRingBalances()
document.getElementById('rotateButton').style.display = 'block'
document.getElementById('CurrentState').innerHTML = 'Not running...'
}
async function rotateToken(tokenFrom, tokenTo, tokenValue, rotationCount) {
var fromAddr = tokenFrom
var toAddr = tokenTo
var tokenContract = RING_TOKEN_CONTRACT_ADDRESS
var value = tokenValue
const utxos = await childChain.getUtxos(fromAddr)
//console.log('utxos: ' + JSON.stringify(utxos))
const utxosToSpend = await selectUtxos(utxos, value, tokenContract)
if (!utxosToSpend) {
console.log('The ring is currently out of tokens. Please contact the ring operator.')
return
}
//console.log('utxosToSpend: ' + JSON.stringify(utxosToSpend))
var utxosForFee = await selectUtxos(utxos, 1, OmgUtil.transaction.ETH_CURRENCY)
if (!utxosForFee) {
console.log('No utxo with ETH to act as dummy fee. Please send at least 1 wei ETH to each ring address.')
return
}
//console.log('utxosForFee: ' + JSON.stringify(utxosForFee))
utxosToSpend.push(utxosForFee[0])
const txBody = {
inputs: utxosToSpend,
outputs: [{
owner: toAddr,
currency: tokenContract,
amount: Number(value)
}]
}
txBody.outputs.push({
owner: fromAddr,
currency: OmgUtil.transaction.ETH_CURRENCY,
amount: utxosForFee[0].amount
})
if (new BigNumber(utxosToSpend[0].amount).gt(new BigNumber(value))) {
// Need to add a 'change' output
const CHANGE_AMOUNT = new BigNumber(utxosToSpend[0].amount).minus(new BigNumber(value))
txBody.outputs.push({
owner: fromAddr,
currency: tokenContract,
amount: CHANGE_AMOUNT
})
}
//console.log('txBody: ' + JSON.stringify(txBody))
// Create the unsigned transaction
const unsignedTx = await childChain.createTransaction(txBody)
const password = RING_VAULT_PASSWORD
// Sign it
await globalKeystore.keyFromPassword(password, async function (err, pwDerivedKey) {
if (err) {
console.error(err)
return
}
// Decrypt the private key
const privateKey = globalKeystore.exportPrivateKey(fromAddr, pwDerivedKey)
// console.log(privateKey) // Bad idea!!!
// Sign the transaction with the private key
const signatures = await childChain.signTransaction(unsignedTx, [privateKey, privateKey])
// Build the signed transaction
const signedTx = await childChain.buildSignedTransaction(unsignedTx, signatures)
// Submit the signed transaction to the childchain
const result = await childChain.submitTransaction(signedTx)
console.log(rotationCount + `: Submitted transaction: ${JSON.stringify(result)}`)
var txSubmissionLog = document.getElementById('TxSubmissionLog').innerHTML
document.getElementById('TxSubmissionLog').innerHTML = '<div>' + Date.now() + ': r: ' + rotationCount + ' ' + shortenAddressInString(JSON.stringify(result)) + '</div>' + txSubmissionLog
})
}
async function clearLogs() {
document.getElementById('TxCreationLog').innerHTML = ''
document.getElementById('TxSubmissionLog').innerHTML = ''
}
async function distributeTokens() {
if(await getBalanceOfToken(addresses[0], RING_TOKEN_CONTRACT_ADDRESS) == RING_TOKEN_TOTAL) {
// Need to split UTXOs...
/*
document.getElementById('distributeButton').style.display = 'none'
var distributions = 1
while(distributions < RING_SIZE) {
//console.log(rotations + ' ' + (rotations % 5) + ' ' + Date.now())
document.getElementById('CurrentState').innerHTML = 'Timestamp: ' + Date.now() + ' -=- Rotation: ' + rotations + ' of ' + TX_RUNS + ' -=- Index: ' + (rotations % RING_SIZE) + ' of ' + RING_SIZE + ' -=- Cool Down: ' + TX_COOL_DOWN + 'ms'
var rotateFromAddr = globalKeystore.getAddresses()[rotations % RING_SIZE]
var rotateToAddr = globalKeystore.getAddresses()[(rotations + 1) % RING_SIZE]
//console.log('rotation: ' + rotations + ' index: ' + (rotations % 5) + ' from: ' + rotateFromAddr + ' to: ' + rotateToAddr + ' timestamp: ' + Date.now())
var txCreationLog = document.getElementById('TxCreationLog').innerHTML
document.getElementById('TxCreationLog').innerHTML = '<div>' + Date.now() + ': r: ' + rotations + ' i: ' + (rotations % RING_SIZE) + ' from: ' + shortenAddress(rotateFromAddr) + ' to: ' + shortenAddress(rotateToAddr) + '</div>' + txCreationLog
await rotateToken(rotateFromAddr, rotateToAddr, RING_TOKEN_VALUE, rotations)
await coolDown(TX_COOL_DOWN)
distributions++
}
showRingBalances()
document.getElementById('CurrentState').innerHTML = 'Not running...'
*/
}
else {
alert('Expected ' + RING_TOKEN_TOTAL + 'RING tokens but found ' + await getBalanceOfToken(addresses[0], RING_TOKEN_CONTRACT_ADDRESS) + '!')
}
}