forked from webaverse/ethereum-bot
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
209 lines (183 loc) · 6.39 KB
/
index.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
const dns = require('dns');
const AWS = require('aws-sdk');
const fetch = require('node-fetch');
const Web3 = require('web3');
const bip39 = require('bip39');
const { Transaction } = require('@ethereumjs/tx');
const { default: Common } = require('@ethereumjs/common');
const { hdkey } = require('ethereumjs-wallet');
const { accessKeyId, secretAccessKey, treasuryMnemonic } =
require('fs').existsSync('./config.json') ? require('./config.json') : {
accessKeyId: process.env.accessKeyId,
secretAccessKey: process.env.secretAccessKey,
treasuryMnemonic: process.env.treasuryMnemonic
}
const { ethereumHost } = require('./constants.js');
const { makePromise } = require('./utilities.js');
const { devMode } = require("./devmode.js");
const { createDiscordClient } = require('./discordbot.js');
const { createTwitterClient } = require('./twitterBot.js');
Error.stackTraceLimit = 300;
const isMainnet = true;
// If dev mode is true, skip trying any AWS or Web3 calls
if (devMode) {
console.warn("*** Warning: Important config variables not set");
console.warn("*** Bot will start in dev mode");
}
let awsConfig, ddb, treasuryWallet, treasuryAddress = null;
if (!devMode) {
awsConfig = new AWS.Config({
credentials: new AWS.Credentials({
accessKeyId,
secretAccessKey,
}),
region: 'us-west-1',
});
ddb = new AWS.DynamoDB(awsConfig);
treasuryWallet = hdkey.fromMasterSeed(bip39.mnemonicToSeedSync(treasuryMnemonic)).derivePath(`m/44'/60'/0'/0/0`).getWallet();
treasuryAddress = treasuryWallet.getAddressString();
}
(async () => {
const ethereumHostAddress = await new Promise((accept, reject) => {
dns.resolve4(ethereumHost, (err, addresses) => {
if (!err) {
if (addresses.length > 0) {
accept(addresses[0]);
} else {
reject(new Error('no addresses resolved for ' + ethereumHostname));
}
} else {
reject(err);
}
});
});
const gethNodeUrl = `http://${ethereumHostAddress}`;
const web3 = new Web3(new Web3.providers.HttpProvider(gethNodeUrl + ':' + (isMainnet ? '8545' : '8546')));
web3.eth.transactionConfirmationBlocks = 1;
const fullAddresses = await fetch('https://contracts.webaverse.com/config/addresses.js')
.then(res => res.text())
.then(s => JSON.parse(s.replace(/^\s*export\s*default\s*/, '')));
const addresses = fullAddresses[isMainnet ? 'mainnetsidechain' : 'rinkebysidechain'];
const abis = await fetch('https://contracts.webaverse.com/config/abi.js')
.then(res => res.text())
.then(s => JSON.parse(s.replace(/^\s*export\s*default\s*/, '')));
const contracts = await (async () => {
console.log('got addresses', addresses);
const result = {};
[
'Account',
'FT',
'NFT',
'FTProxy',
'NFTProxy',
'Trade',
'LAND',
'LANDProxy',
].forEach(contractName => {
result[contractName] = new web3.eth.Contract(abis[contractName], addresses[contractName]);
});
return result;
})();
const getStores = async () => {
const numStores = await contracts.Trade.methods.numStores().call();
const booths = [];
for (let i = 0; i < numStores; i++) {
const store = await contracts.Trade.methods.getStoreByIndex(i + 1).call();
if (store.live) {
const id = parseInt(store.id, 10);
const seller = store.seller.toLowerCase();
const tokenId = parseInt(store.tokenId, 10);
const price = new web3.utils.BN(store.price);
const entry = {
id,
seller,
tokenId,
price,
};
let booth = booths.find(booth => booth.seller === seller);
if (!booth) {
booth = {
seller,
entries: [],
};
booths.push(booth);
}
booth.entries.push(entry);
}
}
return booths;
};
const txQueues = [];
const runSidechainTransaction = mnemonic => {
const wallet = hdkey.fromMasterSeed(bip39.mnemonicToSeedSync(mnemonic)).derivePath(`m/44'/60'/0'/0/0`).getWallet();
const address = wallet.getAddressString();
const fn = async (contractName, method, ...args) => {
let entry = txQueues[address];
if (!entry) {
entry = {
running: false,
cbs: [],
};
txQueues[address] = entry;
}
if (!entry.running) {
entry.running = true;
try {
const txData = contracts[contractName].methods[method](...args);
const data = txData.encodeABI();
let gasPrice = await web3.eth.getGasPrice();
gasPrice = parseInt(gasPrice, 10);
const privateKey = wallet.getPrivateKeyString();
const nonce = await web3.eth.getTransactionCount(address);
const privateKeyBytes = Uint8Array.from(web3.utils.hexToBytes(privateKey));
let tx = Transaction.fromTxData({
to: contracts[contractName]._address,
nonce: '0x' + new web3.utils.BN(nonce).toString(16),
gasPrice: '0x' + new web3.utils.BN(gasPrice).toString(16),
gasLimit: '0x' + new web3.utils.BN(8000000).toString(16),
data,
}, {
common: Common.forCustomChain(
'mainnet',
{
name: 'geth',
networkId: 1,
chainId: isMainnet ? 1338 : 1337,
},
'petersburg',
),
}).sign(privateKeyBytes);
const rawTx = '0x' + tx.serialize().toString('hex');
const receipt = await web3.eth.sendSignedTransaction(rawTx);
return receipt;
} finally {
entry.running = false;
if (entry.cbs.length > 0) {
entry.cbs.shift()();
}
}
} else {
const p = makePromise();
entry.cbs.push(async () => {
try {
const result = await fn(contractName, method, ...args);
p.accept(result);
} catch (err) {
p.reject(err);
}
});
return await p;
}
};
return fn;
};
createDiscordClient(web3, contracts, getStores, runSidechainTransaction, ddb, treasuryAddress, abis, fullAddresses);
// await createTwitterClient(web3, contracts, getStores, runSidechainTransaction, ddb, treasuryAddress);
console.log("Bot started successfully");
})();
process.on('uncaughtException', err => {
console.warn(err);
});
process.on('unhandledRejection', err => {
console.warn(err);
});