forked from webaverse/ethereum-bot
-
Notifications
You must be signed in to change notification settings - Fork 1
/
discordbot.js
3461 lines (3151 loc) · 191 KB
/
discordbot.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
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const path = require('path');
const url = require('url');
const http = require('http');
const https = require('https');
const crypto = require('crypto');
const {randomBytes} = crypto;
const mime = require('mime');
const Discord = require('discord.js');
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 prettyBytes = require('pretty-bytes');
const OpenAI = require('openai-api');
const {encodeSecret, decodeSecret} = require('./encryption.js');
const { discordApiToken, tradeMnemonic, treasuryMnemonic, infuraProjectId, genesisNftStartId, genesisNftEndId, encryptionMnemonic, openAiKey } =
require('fs').existsSync('./config.json') ? require('./config.json') : {
tradeMnemonic: process.env.tradeMnemonic,
treasuryMnemonic: process.env.treasuryMnemonic,
discordApiToken: process.env.discordApiToken,
infuraProjectId: process.env.infuraProjectId,
genesisNftStartId: process.env.genesisNftStartId,
genesisNftEndId: process.env.genesisNftEndId,
encryptionMnemonic: process.env.encryptionMnemonic
}
const dBugUserIds = [
'284377201233887233', // avaer
'465586113835433984',
'559354703746564096',
];
OpenAI.prototype._send_request = (sendRequest => async function(url, method, opts = {}) {
let camelToUnderscore = (key) => {
let result = key.replace(/([A-Z])/g, " $1");
return result.split(' ').join('_').toLowerCase();
}
// console.log('got req', url, method, opts);
const data = {};
for (const key in opts) {
data[camelToUnderscore(key)] = opts[key];
}
const rs = await new Promise((accept, reject) => {
const req = https.request(url, {
method,
headers: {
'Authorization': `Bearer ${this._api_key}`,
'Content-Type': 'application/json'
}
}, res => {
res.setEncoding('utf8');
accept(res);
});
req.end(Object.keys(data).length ? JSON.stringify(data) : '');
req.on('error', reject);
});
return rs;
})(OpenAI.prototype._send_request);
const openai = new OpenAI(openAiKey);
const _openAiCodex = async (message, prompt, stop, blob = false) => {
if (dBugUserIds.includes(message.author.id)) {
const m = await message.channel.send('(¬‿¬ ) . . . d-bugging . . .');
const maxTokens = 4096;
const gptRes = await openai.complete({
engine: 'davinci-codex',
prompt,
stop,
temperature: 0,
max_tokens: maxTokens - prompt.length,
stream: true,
/* stream: false,
prompt: o.prompt, // 'this is a test',
maxTokens: o.maxTokens, // 5,
temperature: o.temperature, // 0.9,
topP: o.topP, // 1,
presencePenalty: o.presencePenalty, // 0,
frequencyPenalty: o.frequencyPenalty, // 0,
bestOf: o.bestOf, // 1,
n: o.n, // 1,
stop: o.stop, // ['\n'] */
});
let fullS = '';
let done = false;
const _updateMessage = (() => {
let running = false;
let queued = false;
const _recurse = async () => {
if (!blob) {
if (!running) {
running = true;
await m.edit('```' + fullS + '```' + (done ? '\n( ‾́ ◡ ‾́ )' : ''));
running = false;
if (queued) {
queued = false;
_recurse();
}
} else {
queued = true;
}
} else {
if (done) {
await m.delete();
const buffer = Buffer.from(fullS, 'utf8');
const attachment = new Discord.MessageAttachment(buffer, 'code.js');
const m2 = await message.channel.send(`(人^▽')~ ☆`, attachment);
}
}
};
return _recurse;
})();
gptRes.on('data', s => {
try {
if (!s.startsWith(`data: [DONE]`)) {
s = s
.replace(/^data: /, '')
.replace(/\n[\s\S]*$/m, '');
console.log('got', {s});
const j = JSON.parse(s);
const {choices} = j;
const {text} = choices[0];
process.stdout.write(text);
fullS += text;
fullS = fullS
.replace(/^\s+/, '')
.replace(/```+/g, '`');
if (fullS) {
_updateMessage();
}
} else {
console.log();
done = true;
_updateMessage();
}
} catch(err) {
console.log('got error', err);
}
});
/* gptRes.on('end', () => {
console.log('end');
}); */
// message.channel.send('```' + gptResponse.data.replace(/```/g, '`') + '```');
} else {
message.channel.send('no d-bug detected for user id ' + message.author.id);
}
};
// isCollaborator
// only collaborator can set
// only collaborator or owner can get
const { jsonParse } = require('./utilities.js');
const {usersTableName, prefix, storageHost, previewHost, previewExt, treasurerRoleName} = require('./constants.js');
const embedColor = '#000000';
const _commandToValue = ([name, args, description]) =>
['.' + name, args.join(' '), '-', description].join(' ');
const _commandToDescription = ([name, args, description]) =>
'```css\n' +
['.' + name, args.join(' '), '-', description].join(' ') +
'```';
const _commandsToValue = commands =>
'```css\n' +
commands.map(command => _commandToValue(command)).join('\n') +
'```';
const helpFields = [
{
name: 'Info',
shortname: 'info',
commands: [
['status', [], 'show account details'],
['balance', ['[@user|0xaddr]?'], 'show FT balance'],
['inventory', ['[@user|0xaddr]?', '[page]?'], 'show NFTs'],
['address', ['[@user]?'], 'print address'],
['key', ['[@user]?'], 'private key (DM)'],
['login', [], 'login link (DM)'],
['play', [], 'play link (DM)'],
['realm', ['[num]'], 'play link to realm [1-5] (DM)'],
],
},
{
name: 'Tokens',
shortname: 'tokens',
commands: [
['inspect', ['[id]'], 'inspect token details'],
['send', ['[@user|0xaddr|treasury]', '[amount]'], 'send [amount] of SILK to user/address'],
['transfer', ['[@user|0xaddr|treasury]', '[id]', '[quantity]?'], 'send NFT'],
['preview', ['[id]'], 'preview NFT [id]; .gif for gif'],
['wget', ['[id]'], 'get NFT [id] in DM'],
['get', ['[id]', '[key]'], 'get metadata for NFT'],
['set', ['[id]', '[key]', '[value]'], 'set metadata for NFT'],
['collab', ['[@user|0xaddr]', '[tokenId]'], 'add collaborator for [tokenId]'],
['uncollab', ['[@user|0xaddr]', '[tokenId]'], 'remove collaborator for [tokenId]'],
],
},
{
name: 'Account',
shortname: 'account',
commands: [
['name', ['[newname]'], 'set name to [name]'],
['monetizationpointer', ['[mp]'], 'set monetization pointer'],
['avatar', ['[id]'], 'set avatar'],
['loadout', ['[num]', '[id]'], 'set loadout NFT [1-8] to [id]'],
['homespace', ['[id]'], 'set NFT as home space'],
['redeem', [], 'redeem NFT roles'],
],
},
{
name: 'Minting',
shortname: 'minting',
commands: [
['mint', ['[count]?'], 'mint NFTs from file drag n drop'],
['mint', ['[count]?', '[url]'], 'mint NFTs from [url]'],
['update', ['[id] (upload comment)'], 'update nft content'],
],
},
{
name: 'Packing',
shortname: 'packing',
commands: [
['packs', ['[@user|nftid]'], 'check packed NFT balances'],
['pack', ['[nftid]', '[amount]'], 'pack [amount] FT into [nftid]'],
['unpack', ['[nftid]', '[amount]'], 'unpack [amount] FT from [nftid]'],
],
},
{
name: 'Trade',
shortname: 'trade',
commands: [
['trade', ['[@user|0xaddr]'], 'start a trade with'],
['addnft', ['[tradeid]', '[nftid]'], 'add NFT to trade [tradeid]'],
['removenft', ['[tradeid]', '[index]'], 'remove NFT [index] from trade [tradeid]'],
['addft', ['[tradeid]','[amount]'], 'add FT to trade [tradeid]'],
],
},
{
name: 'Store',
shortname: 'store',
commands: [
['store', ['[@user]?'], 'show store'],
['sell', ['[nftid]', '[price]'], 'sell [nftid] for [price]'],
['unsell', ['[saleid]'], 'unlist [saleid]'],
['buy', ['[saleid]'], 'buy [saleid]'],
],
},
{
name: 'Land',
shortname: 'land',
commands: [
['parcels', [], 'list owned parcels'],
['deploy', ['[parcelId]', '[nftId]'], 'deploy [nftId] to [parcelId]'],
['landcollab', ['[@user|0xaddr]', '[parcelId]'], 'add collaborator to [parcelId]'],
],
},
{
name: 'Secure commands (DM the bot)',
shortname: 'secure',
commands: [
['key', ['[new mnemonic]'], 'set private key'],
['key', ['reset'], 'generate new private key'],
['gets/.sets', [''], 'encrypted get/set'],
],
},
{
name: 'Help',
shortname: 'help',
commands: [
['help', ['[topic]'], 'show help on a topic (info, tokens, account, minting, packing, trade, store, land, secure)'],
],
},
].map(o => {
o.value = _commandsToValue(o.commands);
return o;
});
const _findCommand = commandName => {
let command = null;
for (const helpField of helpFields) {
for (const c of helpField.commands) {
const [name, args, description] = c;
if (name === commandName) {
command = c;
break;
}
}
if (command !== null) {
break;
}
}
return command;
};
// encryption/decryption of unlocks
const _parseWords = s => {
const words = [];
const r = /\S+/g;
let match;
while (match = r.exec(s)) {
words.push(match);
}
return words;
};
const unlockableKey = 'unlockable';
// locals
const trades = [];
const helps = [];
const inventories = [];
let nextTradeId = 0;
exports.createDiscordClient = (web3, contracts, getStores, runSidechainTransaction, ddb, treasuryAddress, abis, addresses) => {
if (discordApiToken === undefined || discordApiToken === "" || discordApiToken === null)
return console.warn("*** WARNING: Discord API token is not defined");
const client = new Discord.Client();
client.on('ready', async function () {
console.log(`the client becomes ready to start`);
console.log(`I am ready! Logged in as ${client.user.tag}!`);
console.log(`Bot has started, with ${client.users.size} users, in ${client.channels.size} channels of ${client.guilds.size} guilds.`);
// console.log('got', client.guilds.cache.get(guildId).members.cache);
client.user.setPresence({
status: 'online',
activity: {
name: 'Webaverse.com',
type: 'PLAYING',
url: 'https://webaverse.com'
}
});
client.on('messageReactionAdd', async (reaction, user) => {
const { data, message, emoji } = reaction;
// console.log('emoji identifier', message, data, emoji);
if (user.id !== client.user.id && emoji.identifier === '%E2%9D%8C') { // x
if (message.channel.type === 'dm') {
message.delete();
} else {
let helpIndex, trade, index, inventoryIndex;
if ((helpIndex = helps.findIndex(help => help.id === message.id)) !== -1) {
const help = helps[helpIndex];
if (help.requester.id === user.id) {
help.delete();
helps.splice(helpIndex, 1);
}
} else if ((trade = trades.find(trade => trade.id === message.id)) && (index = trade.userIds.indexOf(user.id)) !== -1) {
trade.cancel();
trades.splice(trades.indexOf(trade), 1);
}
}
} else if (user.id !== client.user.id && emoji.identifier === '%E2%9C%85') { // white check mark
const trade = trades.find(trade => trade.id === message.id);
if (trade) {
const index = trade.userIds.indexOf(user.id);
if (index >= 0) {
trade.confirmations[index] = true;
trade.render();
if (trade.confirmations.every(confirmation => !!confirmation)) {
if (trade.confirmations2.every(confirmation => !!confirmation)) {
trade.finish();
trades.splice(trades.indexOf(trade), 1);
} else {
trade.react('💞');
}
}
}
}
} else if (user.id !== client.user.id && emoji.identifier === '%F0%9F%92%9E') { // rotating hearts
const trade = trades.find(trade => trade.id === message.id);
if (trade) {
const index = trade.userIds.indexOf(user.id);
if (index >= 0) {
trade.confirmations2[index] = true;
trade.render();
if (trade.confirmations.every(confirmation => !!confirmation) && trade.confirmations2.every(confirmation => !!confirmation)) {
trade.finish();
trades.splice(trades.indexOf(trade), 1);
}
}
}
} else if (user.id !== client.user.id && emoji.identifier === '%E2%97%80%EF%B8%8F') { // left arrow ◀️
if ((inventoryIndex = inventories.findIndex(i => i.id === message.id)) !== -1) {
const inventory = inventories[inventoryIndex];
if (inventory.requester.id === user.id) {
inventory.left();
}
}
} else if (user.id !== client.user.id && emoji.identifier === '%E2%96%B6%EF%B8%8F') { // right arrow ▶️
if ((inventoryIndex = inventories.findIndex(i => i.id === message.id)) !== -1) {
const inventory = inventories[inventoryIndex];
if (inventory.requester.id === user.id) {
inventory.right();
}
}
}
});
client.on('messageReactionRemove', async (reaction, user) => {
const { data, message, emoji } = reaction;
if (user.id !== client.user.id && emoji.identifier === '%E2%9C%85') { // white check mark
let trade, index;
if ((trade = trades.find(trade => trade.id === message.id)) && (index = trade.userIds.indexOf(user.id)) !== -1) {
trade.confirmations[index] = false;
trade.render();
const doneReactions = trade.reactions.cache.filter(reaction => reaction.emoji.identifier === '%F0%9F%92%9E');
// console.log('got done reactions', Array.from(doneReactions.values()).length);
try {
for (const reaction of doneReactions.values()) {
const users = Array.from(reaction.users.cache.values());
console.log('got reaction users', users.map(u => u.id));
for (const user of users) {
await reaction.users.remove(user.id);
}
}
} catch (error) {
console.error('Failed to remove reactions.', error.stack);
}
}
} else if (user.id !== client.user.id && emoji.identifier === '%E2%97%80%EF%B8%8F') { // left arrow ◀️
if ((inventoryIndex = inventories.findIndex(i => i.id === message.id)) !== -1) {
const inventory = inventories[inventoryIndex];
if (inventory.requester.id === user.id) {
inventory.left();
}
}
} else if (user.id !== client.user.id && emoji.identifier === '%E2%96%B6%EF%B8%8F') { // right arrow ▶️
if ((inventoryIndex = inventories.findIndex(i => i.id === message.id)) !== -1) {
const inventory = inventories[inventoryIndex];
if (inventory.requester.id === user.id) {
inventory.right();
}
}
}
});
client.on('message', async message => {
if (!message.author.bot) {
const _getUser = async (id = message.author.id) => {
const tokenItem = await ddb.getItem({
TableName: usersTableName,
Key: {
email: { S: id + '.discordtoken' },
}
}).promise();
let mnemonic = (tokenItem.Item && tokenItem.Item.mnemonic) ? tokenItem.Item.mnemonic.S : null;
return { mnemonic };
};
const _genKey = async (id = message.author.id) => {
const mnemonic = bip39.generateMnemonic();
await ddb.putItem({
TableName: usersTableName,
Item: {
email: { S: id + '.discordtoken' },
mnemonic: { S: mnemonic },
}
}).promise();
return { mnemonic };
};
if (message.channel.type === 'text') {
// console.log('got message', message);
const _getPage = () => {
let page = parseInt(split[1], 10);
if (!isNaN(page)) {
split[2] = split[1];
split[1] = '';
} else {
page = parseInt(split[2], 10);
if (isNaN(page)) {
page = 1;
}
}
return page;
};
const _items = (contractName, page) => async getEntries => {
let address, userLabel, userName;
const _loadFromUserId = async userId => {
const spec = await _getUser(userId);
let mnemonic = spec.mnemonic;
if (!mnemonic) {
const spec = await _genKey(userId);
mnemonic = spec.mnemonic;
}
const wallet = hdkey.fromMasterSeed(bip39.mnemonicToSeedSync(mnemonic)).derivePath(`m/44'/60'/0'/0/0`).getWallet();
address = wallet.getAddressString();
userLabel = '<@!' + userId + '>';
const o = await Promise.all([
contracts.Account.methods.getMetadata(address, 'name').call(),
contracts.Account.methods.getMetadata(address, 'avatarPreview').call(),
]);
userName = o[0];
avatarPreview = o[1];
};
const _loadFromAddress = async a => {
address = a;
userLabel = a;
userName = a;
avatarPreview = await contracts.Account.methods.getMetadata(address, 'avatarPreview').call();
};
const _loadFromTreasury = async () => {
const wallet = hdkey.fromMasterSeed(bip39.mnemonicToSeedSync(treasuryMnemonic)).derivePath(`m/44'/60'/0'/0/0`).getWallet();
address = wallet.getAddressString();
userLabel = 'treasury';
userName = userLabel;
avatarPreview = await contracts.Account.methods.getMetadata(address, 'avatarPreview').call();
};
if (split.length >= 2 && (match = split[1].match(/<@!?([0-9]+)>/))) {
await _loadFromUserId(match[1]);
} else if (split.length >= 2 && (match = split[1].match(/^(0x[0-9a-f]+)$/i))) {
await _loadFromAddress(match[1]);
} else if (split.length >= 2 && split[1] === 'treasury') {
await _loadFromTreasury();
} else {
await _loadFromUserId(message.author.id);
}
const nftBalance = await contracts[contractName].methods.balanceOf(address).call();
const maxEntriesPerPage = 10;
const numPages = Math.max(Math.ceil(nftBalance / maxEntriesPerPage), 1);
page = Math.min(Math.max(page, 1), numPages);
const startIndex = (page - 1) * maxEntriesPerPage;
const endIndex = Math.min(page * maxEntriesPerPage, nftBalance);
const entries = await getEntries(address, startIndex, endIndex);
return {
userLabel,
userName,
avatarPreview,
numPages,
entries,
};
};
/* if (/grease/.test(message.content)) {
message.author.send('i am NOT grease?!!!!');
} */
const s = message.content;
const words = _parseWords(s);
const split = words.map(word => word[0]);
// console.log('got split', { words, split, s, first: split[0] });
const isHelp = split.length > 1 && split[split.length - 1] === '-h';
if (isHelp) {
const commandName = split[0].slice(1);
const command = _findCommand(commandName);
if (command) {
const [name, args, description] = command;
const exampleEmbed = new Discord.MessageEmbed()
.setColor(embedColor)
.setTitle('Webaverse Help')
.setURL(`https://docs.webaverse.com/`)
// .setAuthor('Some name', 'https://i.imgur.com/wSTFkRM.png', 'https://discord.js.org')
// .setDescription(description || 'This person is a noob without a description.')
// .setThumbnail(avatarPreview)
// .addField('Inline field title', 'Some value here', true)
// .setImage(avatarPreview)
// .setTimestamp()
// .setFooter('.help for help', 'https://app.webaverse.com/assets/logo-flat.svg');
.addFields([
{
name,
value: _commandToDescription(command),
},
]);
const m = await message.channel.send(exampleEmbed);
// m.react('❌');
// m.requester = message.author;
// helps.push(m);
} else {
console.warn('invalid command name', commandName);
}
} else {
if (split[0] === prefix + 'help') {
const name = split[1];
const exampleEmbed = new Discord.MessageEmbed()
.setColor(embedColor)
.setTitle('Webaverse Help')
.setURL(`https://docs.webaverse.com/`)
// .setAuthor('Some name', 'https://i.imgur.com/wSTFkRM.png', 'https://discord.js.org')
// .setDescription(description || 'This person is a noob without a description.')
// .setThumbnail(avatarPreview)
// .addField('Inline field title', 'Some value here', true)
// .setImage(avatarPreview)
// .setTimestamp()
// .setFooter('.help for help', 'https://app.webaverse.com/assets/logo-flat.svg');
if (!name) {
exampleEmbed.addFields(helpFields);
} else {
const command = _findCommand(name);
if (command) {
exampleEmbed.addFields([
{
name,
value: _commandToDescription(command),
},
]);
} else {
const helpField = helpFields.find(hf => hf.shortname === name) || helpFields.find(hf => hf.shortname === 'help');
exampleEmbed.addFields([
helpField,
]);
}
}
const m = await message.channel.send(exampleEmbed);
m.react('❌');
m.requester = message.author;
helps.push(m);
} else if (split[0] === prefix + 'status') {
let userId, mnemonic;
if (split.length >= 2 && (match = split[1].match(/<@!?([0-9]+)>/))) {
userId = match[1];
} else {
userId = message.author.id;
}
const spec = await _getUser(userId);
mnemonic = spec.mnemonic;
if (!mnemonic) {
const spec = await _genKey(userId);
mnemonic = spec.mnemonic;
}
const wallet = hdkey.fromMasterSeed(bip39.mnemonicToSeedSync(mnemonic)).derivePath(`m/44'/60'/0'/0/0`).getWallet();
const address = wallet.getAddressString();
const [
name,
description,
avatarId,
homeSpaceId,
monetizationPointer,
avatarPreview,
] = await Promise.all([
contracts.Account.methods.getMetadata(address, 'name').call(),
contracts.Account.methods.getMetadata(address, 'description').call(),
contracts.Account.methods.getMetadata(address, 'avatarId').call(),
contracts.Account.methods.getMetadata(address, 'homeSpaceId').call(),
contracts.Account.methods.getMetadata(address, 'monetizationPointer').call(),
contracts.Account.methods.getMetadata(address, 'avatarPreview').call(),
]);
const exampleEmbed = new Discord.MessageEmbed()
.setColor(embedColor)
.setTitle(name)
.setURL(`https://webaverse.com/creators/${address}`)
// .setAuthor('Some name', 'https://i.imgur.com/wSTFkRM.png', 'https://discord.js.org')
.setDescription(description || 'This person is a noob without a description.')
.setThumbnail(avatarPreview)
.addFields(
{ name: 'avatar id', value: avatarId || '<none>' },
{ name: 'homespace id', value: homeSpaceId || '<none>' },
{ name: 'monetization pointer', value: monetizationPointer || '<none>' },
)
// .addField('Inline field title', 'Some value here', true)
.setImage(avatarPreview)
.setTimestamp()
.setFooter('.help for help', 'https://app.webaverse.com/assets/logo-flat.svg');
const m = await message.channel.send(exampleEmbed);
m.react('❌');
m.requester = message.author;
helps.push(m);
// message.channel.send('<@!' + message.author.id + '>: ' + `\`\`\`Name: ${name}\nAvatar: ${avatarId}\nHome Space: ${homeSpaceId}\nMonetization Pointer: ${monetizationPointer}\n\`\`\``);
} else if (split[0] === prefix + 'inspect' && !isNaN(split[1])) {
const tokenId = parseInt(split[1], 10);
const token = await contracts.NFT.methods.tokenByIdFull(tokenId).call();
// console.log('got token', token);
const minterAddress = token.minter.toLowerCase();
const [
unlockable,
minterName,
minterAvatarPreview,
] = await Promise.all([
(async () => {
const key = unlockableKey;
const value = await contracts.NFT.methods.getMetadata(token.hash, key).call();
return !!value;
})(),
contracts.Account.methods.getMetadata(minterAddress, 'name').call(),
contracts.Account.methods.getMetadata(minterAddress, 'avatarPreview').call(),
]);
const editionNumber = 1; // XXX hack
const collaborators = [token.owner]; // XXX hack
const sizeString = prettyBytes(100 * 1024); // XXX hack
const resolutionString = `${1024}x${768}`; // XXX hack
const itemPreview = `https://preview.webaverse.com/${token.hash}.${token.ext}/preview.png`;
const exampleEmbed = new Discord.MessageEmbed()
.setColor(embedColor)
.setTitle(token.name)
.setURL(`https://webaverse.com/assets/${token.id}`)
.setAuthor(minterName || 'Anonymous', minterAvatarPreview, `https://webaverse.com/creators/${minterAddress}`)
.setDescription(token.description || 'What a mysterious item.')
.setThumbnail(itemPreview)
.addFields(
{ name: 'content hash', value: token.hash },
{ name: 'edition number', value: editionNumber + ' (est.)' },
{ name: 'edition size', value: token.totalSupply + '' },
{ name: 'file type', value: token.ext },
{ name: 'file size', value: sizeString + ' (est.)' },
{ name: 'file resolution', value: resolutionString + ' (est.)' },
{ name: 'collaborators', value: collaborators.join(', ') + ' (est.)' },
{ name: 'has unlockable?', value: unlockable ? 'yes' : 'no' },
)
// .addField('Inline field title', 'Some value here', true)
.setImage(itemPreview)
.setTimestamp()
.setFooter('.help for help', 'https://app.webaverse.com/assets/logo-flat.svg');
const m = await message.channel.send(exampleEmbed);
m.react('❌');
m.requester = message.author;
helps.push(m);
} else if (split[0] === prefix + 'name') {
let { mnemonic } = await _getUser();
if (!mnemonic) {
const spec = await _genKey();
mnemonic = spec.mnemonic;
}
if (split[1]) {
let name = split[1];
if (/['"]{2}/.test(name)) {
name = '';
}
const wallet = hdkey.fromMasterSeed(bip39.mnemonicToSeedSync(mnemonic)).derivePath(`m/44'/60'/0'/0/0`).getWallet();
const address = wallet.getAddressString();
const result = await runSidechainTransaction(mnemonic)('Account', 'setMetadata', address, 'name', name);
message.channel.send('<@!' + message.author.id + '>: set name to ' + JSON.stringify(name));
} else {
const wallet = hdkey.fromMasterSeed(bip39.mnemonicToSeedSync(mnemonic)).derivePath(`m/44'/60'/0'/0/0`).getWallet();
const address = wallet.getAddressString();
const name = await contracts.Account.methods.getMetadata(address, 'name').call();
message.channel.send('<@!' + message.author.id + '>: name is ' + JSON.stringify(name));
}
} else if (split[0] === prefix + 'monetizationpointer') {
let { mnemonic } = await _getUser();
if (!mnemonic) {
const spec = await _genKey();
mnemonic = spec.mnemonic;
}
if (split[1]) {
const monetizationPointer = split[1];
const wallet = hdkey.fromMasterSeed(bip39.mnemonicToSeedSync(mnemonic)).derivePath(`m/44'/60'/0'/0/0`).getWallet();
const address = wallet.getAddressString();
const result = await runSidechainTransaction(mnemonic)('Account', 'setMetadata', address, 'monetizationPointer', monetizationPointer);
message.channel.send('<@!' + message.author.id + '>: set monetization pointer to ' + JSON.stringify(monetizationPointer));
} else {
const wallet = hdkey.fromMasterSeed(bip39.mnemonicToSeedSync(mnemonic)).derivePath(`m/44'/60'/0'/0/0`).getWallet();
const address = wallet.getAddressString();
const monetizationPointer = await contracts.Account.methods.getMetadata(address, 'monetizationPointer').call();
message.channel.send('<@!' + message.author.id + '>: monetization pointer is ' + JSON.stringify(monetizationPointer));
}
} else if (split[0] === prefix + 'avatar') {
const contentId = split[1];
const id = parseInt(contentId, 10);
let { mnemonic } = await _getUser();
if (!mnemonic) {
const spec = await _genKey();
mnemonic = spec.mnemonic;
}
const wallet = hdkey.fromMasterSeed(bip39.mnemonicToSeedSync(mnemonic)).derivePath(`m/44'/60'/0'/0/0`).getWallet();
const address = wallet.getAddressString();
if (!isNaN(id)) {
const hash = await contracts.NFT.methods.getHash(id).call();
const [
name,
ext,
] = await Promise.all([
contracts.NFT.methods.getMetadata(hash, 'name').call(),
contracts.NFT.methods.getMetadata(hash, 'ext').call(),
]);
// const avatarUrl = `${storageHost}/${hash.slice(2)}${ext ? ('.' + ext) : ''}`;
// const avatarFileName = avatarUrl.replace(/.*\/([^\/]+)$/, '$1');
const avatarPreview = `${previewHost}/${hash}${ext ? ('.' + ext) : ''}/preview.${previewExt}`;
await runSidechainTransaction(mnemonic)('Account', 'setMetadata', address, 'avatarId', id + '');
await runSidechainTransaction(mnemonic)('Account', 'setMetadata', address, 'avatarName', name);
await runSidechainTransaction(mnemonic)('Account', 'setMetadata', address, 'avatarExt', ext);
await runSidechainTransaction(mnemonic)('Account', 'setMetadata', address, 'avatarPreview', avatarPreview);
message.channel.send('<@!' + message.author.id + '>: set avatar to ' + JSON.stringify(id));
} else if (contentId) {
const name = path.basename(contentId);
const ext = path.extname(contentId).slice(1);
const avatarPreview = `https://preview.webaverse.com/[${contentId}]/preview.jpg`;
await runSidechainTransaction(mnemonic)('Account', 'setMetadata', address, 'avatarId', contentId);
await runSidechainTransaction(mnemonic)('Account', 'setMetadata', address, 'avatarName', name);
await runSidechainTransaction(mnemonic)('Account', 'setMetadata', address, 'avatarExt', ext);
await runSidechainTransaction(mnemonic)('Account', 'setMetadata', address, 'avatarPreview', avatarPreview);
message.channel.send('<@!' + message.author.id + '>: set avatar to ' + JSON.stringify(contentId));
} else {
const wallet = hdkey.fromMasterSeed(bip39.mnemonicToSeedSync(mnemonic)).derivePath(`m/44'/60'/0'/0/0`).getWallet();
const address = wallet.getAddressString();
const avatarId = await contracts.Account.methods.getMetadata(address, 'avatarId').call();
message.channel.send('<@!' + message.author.id + '>: avatar is ' + JSON.stringify(avatarId));
}
} else if (split[0] === prefix + 'loadout') {
let { mnemonic } = await _getUser();
if (!mnemonic) {
const spec = await _genKey();
mnemonic = spec.mnemonic;
}
const index = parseInt(split[1], 10);
const contentId = split[2];
const id = parseInt(contentId, 10);
async function getLoadout(address) {
const loadoutString = await contracts.Account.methods.getMetadata(address, 'loadout').call();
let loadout = jsonParse(loadoutString);
if (!Array.isArray(loadout)) {
loadout = [];
}
while (loadout.length < 8) {
loadout.push(null);
}
return loadout;
}
if (index >= 1 && index <= 8) {
let { mnemonic } = await _getUser();
if (!mnemonic) {
const spec = await _genKey();
mnemonic = spec.mnemonic;
}
const wallet = hdkey.fromMasterSeed(bip39.mnemonicToSeedSync(mnemonic)).derivePath(`m/44'/60'/0'/0/0`).getWallet();
const address = wallet.getAddressString();
if (!isNaN(id)) {
const hash = await contracts.NFT.methods.getHash(id).call();
const [
name,
ext,
] = await Promise.all([
contracts.NFT.methods.getMetadata(hash, 'name').call(),
contracts.NFT.methods.getMetadata(hash, 'ext').call(),
]);
const itemPreview = `${previewHost}/${hash}${ext ? ('.' + ext) : ''}/preview.${previewExt}`;
const loadout = await getLoadout(address);
loadout.splice(index - 1, 1, [
id + '',
name,
ext,
itemPreview
]);
await runSidechainTransaction(mnemonic)('Account', 'setMetadata', address, 'loadout', JSON.stringify(loadout));
message.channel.send('<@!' + message.author.id + '>: updated loadout');
} else {
const o = url.parse(contentId);
const match = o.path.match(/\/([^\/]+)$/);
const fileName = match ? match[1] : '';
const ext = path.extname(fileName).slice(1);
const name = ext ? fileName.slice(0, -(ext.length + 1)) : fileName;
if (ext) {
const itemPreview = `${previewHost}/[${contentId}]/preview.${previewExt}`;
const loadout = await getLoadout(address);
loadout.splice(index - 1, 1, [
contentId,
name,
ext,
itemPreview
]);
await runSidechainTransaction(mnemonic)('Account', 'setMetadata', address, 'loadout', JSON.stringify(loadout));
message.channel.send('<@!' + message.author.id + '>: updated loadout');
} else {
message.channel.send('<@!' + message.author.id + '>: content id is not `[number|URL with extension]`: ' + contentId);
}
}
} else {
const wallet = hdkey.fromMasterSeed(bip39.mnemonicToSeedSync(mnemonic)).derivePath(`m/44'/60'/0'/0/0`).getWallet();
const address = wallet.getAddressString();
const loadout = await getLoadout(address);
message.channel.send('<@!' + message.author.id + '>: loadout:\n```' + loadout.map((item, index) => `${index + 1}: ${item !== null ? (`[${item[0]}] ${item[1]} ${item[2]}`) : 'empty'}`).join('\n') + '```');
}
} else if (split[0] === prefix + 'homespace') {
let { mnemonic } = await _getUser();
if (!mnemonic) {
const spec = await _genKey();
mnemonic = spec.mnemonic;
}
const id = parseInt(split[1], 10);
if (!isNaN(id)) {
let { mnemonic } = await _getUser();
if (!mnemonic) {
const spec = await _genKey();
mnemonic = spec.mnemonic;
}
const wallet = hdkey.fromMasterSeed(bip39.mnemonicToSeedSync(mnemonic)).derivePath(`m/44'/60'/0'/0/0`).getWallet();
const address = wallet.getAddressString();
const hash = await contracts.NFT.methods.getHash(id).call();
const [
name,
ext,
] = await Promise.all([
contracts.NFT.methods.getMetadata(hash, 'name').call(),
contracts.NFT.methods.getMetadata(hash, 'ext').call(),
]);
// const homeSpaceUrl = `${storageHost}/${hash.slice(2)}${ext ? ('.' + ext) : ''}`;
// const homeSpaceFileName = homeSpaceUrl.replace(/.*\/([^\/]+)$/, '$1');
const homeSpacePreview = `${previewHost}/${hash}${ext ? ('.' + ext) : ''}/preview.${previewExt}`;
await runSidechainTransaction(mnemonic)('Account', 'setMetadata', address, 'homeSpaceId', id + '');
await runSidechainTransaction(mnemonic)('Account', 'setMetadata', address, 'homeSpaceName', name);
await runSidechainTransaction(mnemonic)('Account', 'setMetadata', address, 'homeSpaceExt', ext);
await runSidechainTransaction(mnemonic)('Account', 'setMetadata', address, 'homeSpacePreview', homeSpacePreview);
message.channel.send('<@!' + message.author.id + '>: set home space to ' + id);
} else {
const wallet = hdkey.fromMasterSeed(bip39.mnemonicToSeedSync(mnemonic)).derivePath(`m/44'/60'/0'/0/0`).getWallet();
const address = wallet.getAddressString();
const homeSpaceUrl = await contracts.Account.methods.getMetadata(address, 'homeSpaceUrl').call();
message.channel.send('<@!' + message.author.id + '>: home space is ' + JSON.stringify(homeSpaceUrl));
}
} else if (split[0] === prefix + 'redeem') {
let { mnemonic } = await _getUser();
if (!mnemonic) {
const spec = await _genKey();
mnemonic = spec.mnemonic;
}
const wallet = hdkey.fromMasterSeed(bip39.mnemonicToSeedSync(mnemonic)).derivePath(`m/44'/60'/0'/0/0`).getWallet();
const address = wallet.getAddressString();
const rinkebyWeb3 = new Web3(new Web3.providers.HttpProvider(`https://rinkeby.infura.io/v3/${infuraProjectId}`));
const signature = await contracts.Account.methods.getMetadata(address, 'mainnetAddress').call();
let mainnetAddress;
if (signature !== '') {
mainnetAddress = await rinkebyWeb3.eth.accounts.recover("Connecting mainnet address.", signature);
} else {
message.channel.send('<@!' + message.author.id + '>: no role redeemed.');
return;
}
let roleRedeemed = null;
const mainnetNft = new rinkebyWeb3.eth.Contract(abis['NFT'], addresses['mainnet']['NFT']);
const nftMainnetBalance = await mainnetNft.methods.balanceOf(mainnetAddress).call();
const mainnetPromises = Array(nftMainnetBalance);
for (let i = 0; i < nftMainnetBalance; i++) {
const token = await mainnetNft.methods.tokenOfOwnerByIndexFull(mainnetAddress, i).call();
mainnetPromises[i] = token;
if (token.id >= genesisNftStartId && token.id <= genesisNftEndId) {
const genesisRole = message.guild.roles.cache.find(role => role.name === "Genesis");
if (!message.member.roles.cache.has(genesisRole.id)) {