-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathworkspace.js
1223 lines (1103 loc) · 46 KB
/
workspace.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
'use strict';
const {
Model,
Sequelize,
QueryTypes,
} = require('sequelize');
const { sanitize, slugify } = require('../lib/utils');
const { enqueue } = require('../lib/queue');
const { ProviderConnector } = require('../lib/rpc');
const logger = require('../lib/logger');
const { getMaxBlockForSyncReset } = require('../lib/env');
const Analytics = require('../lib/analytics');
const Op = Sequelize.Op;
const INTEGRATION_FIELD_MAPPING = {
'alchemy': 'alchemyIntegrationEnabled'
};
module.exports = (sequelize, DataTypes) => {
class Workspace extends Model {
static associate(models) {
Workspace.belongsTo(models.User, { foreignKey: 'userId', as: 'user' });
Workspace.hasOne(models.IntegrityCheck, { foreignKey: 'workspaceId', as: 'integrityCheck' });
Workspace.hasOne(models.RpcHealthCheck, { foreignKey: 'workspaceId', as: 'rpcHealthCheck' });
Workspace.hasOne(models.Explorer, { foreignKey: 'workspaceId', as: 'explorer' });
Workspace.hasMany(models.CustomField, { foreignKey: 'workspaceId', as: 'custom_fields' });
Workspace.hasMany(models.Block, { foreignKey: 'workspaceId', as: 'blocks' });
Workspace.hasMany(models.Transaction, { foreignKey: 'workspaceId', as: 'transactions' });
Workspace.hasMany(models.TransactionReceipt, { foreignKey: 'workspaceId', as: 'receipts' });
Workspace.hasMany(models.TransactionLog, { foreignKey: 'workspaceId', as: 'logs' });
Workspace.hasMany(models.Contract, { foreignKey: 'workspaceId', as: 'contracts' });
Workspace.hasMany(models.Account, { foreignKey: 'workspaceId', as: 'accounts' });
Workspace.hasMany(models.TokenBalanceChange, { foreignKey: 'workspaceId', as: 'tokenBalanceChanges' });
Workspace.hasMany(models.TokenTransfer, { foreignKey: 'workspaceId', as: 'tokenTransfers' });
}
static findPublicWorkspaceById(id) {
return Workspace.findOne({
where: {
public: true,
id: id
}
});
}
static findByUserIdAndName(userId, name) {
return Workspace.findOne({
where: {
userId: userId,
name: name
}
});
}
getProvider() {
return new ProviderConnector(this.rpcServer);
}
async safeDelete() {
const blocks = await this.getBlocks({ limit: getMaxBlockForSyncReset() });
if (blocks.length == getMaxBlockForSyncReset())
throw new Error('Please reset this workspace before deleting it.');
const explorer = await this.getExplorer();
if (explorer)
throw new Error(`This workspace has an explorer associated to it. Please delete it or change its associated workspace first.`);
const transaction = await sequelize.transaction();
try {
const user = await this.getUser();
if (user.currentWorkspaceId == this.id) {
const workspaces = (await user.getWorkspaces()).filter(w => w.id != this.id);
const currentWorkspaceId = workspaces.length ? workspaces[0].id : null;
await user.update({ currentWorkspaceId });
}
await this.reset(null, transaction);
await sequelize.models.CustomField.destroy({ where: { workspaceId: this.id }}, { transaction });
await this.destroy({ transaction });
await transaction.commit();
} catch(error) {
await transaction.rollback();
throw error;
}
}
async getContractByAddress(address) {
if (!address) throw new Error('Missing parameter');
const contracts = await this.getContracts({
where: { address }
});
return contracts[0];
}
findBlockGaps(lowerBound, upperBound) {
if (lowerBound === undefined || lowerBound === null || upperBound === undefined || upperBound === null)
throw new Error('Missing parameter');
return sequelize.query(`
SELECT * FROM (
SELECT
LAG(MAX("number")) OVER (order by group_id) + 1 AS "blockStart",
MIN("number") - 1 AS "blockEnd"
FROM (
SELECT
"workspaceId", "number",
"number" - row_number() OVER (ORDER BY "number") as group_id
FROM blocks
WHERE "workspaceId" = :workspaceId
AND number >= :lowerBound
AND number <= :upperBound
) s
GROUP BY group_id
) q
WHERE "blockStart" IS NOT NULL;
`, {
replacements: {
workspaceId: this.id,
lowerBound: lowerBound,
upperBound: upperBound
},
type: QueryTypes.SELECT
});
}
async safeCreateOrUpdateRpcHealthCheck(isReachable) {
if (isReachable === null || isReachable === undefined)
throw new Error('Missing parameter');
const rpcHealthCheck = await this.getRpcHealthCheck();
if (rpcHealthCheck) {
// This is necessary otherwise Sequelize won't update the value with no other changes
rpcHealthCheck.changed('updatedAt', true);
// If rpc is reachable we reset failed attempts as well
const fields = isReachable ? { isReachable, failedAttempts: 0, updatedAt: new Date() } : { isReachable, updatedAt: new Date() }
return rpcHealthCheck.update(fields);
}
else
return this.createRpcHealthCheck({ isReachable });
}
async safeCreateOrUpdateIntegrityCheck({ blockId, status }) {
if (!blockId && !status) throw new Error('Missing parameter');
const integrityCheck = await this.getIntegrityCheck();
if (integrityCheck)
return integrityCheck.update(sanitize({ blockId, status }));
else
return this.createIntegrityCheck(sanitize({ blockId, status }));
}
async getCustomTransactionFunction() {
const custom_field = await sequelize.models.CustomField.findOne({
where: {
workspaceId: this.id,
location: 'transaction'
}
});
return custom_field ? custom_field.function : null;
}
async getExpiredBlocks(ttlInMinutes = 15) {
const blocks = await sequelize.query(`
SELECT id FROM blocks
WHERE (
SELECT COUNT(*) FROM transactions
WHERE "blockNumber" = blocks.number
AND "workspaceId" = :workspaceId
) <> "transactionsCount"
AND "createdAt" <= NOW() - interval '${ttlInMinutes} minute'
AND "workspaceId" = :workspaceId;
`, {
model: sequelize.models.Block,
replacements: { workspaceId: this.id }
});
return blocks;
}
getFilteredAddressTokenTransfers(address, page = 1, itemsPerPage = 10, orderBy = 'id', order = 'DESC') {
if (!address) throw new Error('Missing parameter');
let sanitizedOrderBy;
switch(orderBy) {
case 'timestamp':
case 'transactionHash':
case 'blockNumber':
sanitizedOrderBy = ['transaction', orderBy];
break;
case 'amount':
sanitizedOrderBy = [sequelize.cast(sequelize.col('"TokenTransfer".amount'), 'numeric')];
break;
default:
sanitizedOrderBy = [orderBy];
break;
}
return this.getTokenTransfers({
where: {
[Op.or]: [
{ src: address.toLowerCase() },
{ dst: address.toLowerCase() }
]
},
include: [
{
model: sequelize.models.Transaction,
as: 'transaction',
attributes: ['hash', 'blockNumber', 'timestamp']
},
{
model: sequelize.models.Contract,
as: 'contract',
attributes: ['id', 'patterns', 'tokenName', 'tokenSymbol', 'tokenDecimals', 'abi']
}
],
attributes: ['id', 'src', 'dst', 'token', [sequelize.cast(sequelize.col('"TokenTransfer".amount'), 'numeric'), 'amount']],
offset: (page - 1) * itemsPerPage,
limit: itemsPerPage,
order: [[...sanitizedOrderBy, order]]
})
}
countAddressTokenTransfers(address) {
if (!address) throw new Error('Missing parameter');
return this.countTokenTransfers({
where: {
[Op.or]: [
{ src: address.toLowerCase() },
{ dst: address.toLowerCase() }
]
}
});
}
countAddressSentTransactions(address) {
if (!address) throw new Error('Missing parameter');
return this.countTransactions({
where: { from: address.toLowerCase() }
});
}
countAddressReceivedTransactions(address) {
if (!address) throw new Error('Missing parameter');
return this.countTransactions({
where: { to: address.toLowerCase() }
});
}
countAddressSentErc20TokenTransfers(address) {
if (!address) throw new Error('Missing parameter');
return this.countTokenTransfers({
where: {
src: address.toLowerCase(),
tokenId: null
}
});
}
countAddressReceivedErc20TokenTransfers(address) {
if (!address) throw new Error('Missing parameter');
return this.countTokenTransfers({
where: {
dst: address.toLowerCase(),
tokenId: null
}
});
}
async getTransactionVolume() {
const [transactions,] = await sequelize.query(`
SELECT timestamp, count
FROM transaction_volume_14d
WHERE "workspaceId" = :workspaceId
ORDER BY timestamp ASC
`, {
replacements: { workspaceId: this.id }
});
return transactions;
}
async findActiveWallets() {
const [wallets,] = await sequelize.query(`
SELECT DISTINCT "from" AS address
FROM transactions
WHERE "workspaceId" = :workspaceId
`, {
replacements: { workspaceId: this.id }
});
return wallets;
}
async getWalletVolume() {
const [wallets,] = await sequelize.query(`
SELECT timestamp, count
FROM wallet_volume_14d
WHERE "workspaceId" = :workspaceId
ORDER BY timestamp
`, {
replacements: { workspaceId: this.id }
});
return wallets;
}
async safeFindLatestTokenBalances(address, tokenPatterns = []) {
if (!address) return [];
const allowedTokenPatterns = tokenPatterns.filter(p => ['erc20', 'erc721'].indexOf(p) > -1);
let tokenFilter = {
[Op.and]: sequelize.where(
sequelize.col("tokenContract.workspaceId"),
Op.eq,
sequelize.col("TokenBalanceChange.workspaceId")
),
[Op.and]: sequelize.where(
sequelize.col("tokenContract.address"),
Op.eq,
sequelize.col("TokenBalanceChange.token")
)
};
if (allowedTokenPatterns.length) {
tokenFilter = { patterns: { [Op.contains]: allowedTokenPatterns }, ...tokenFilter };
}
const tokenBalanceChanges = await this.getTokenBalanceChanges({
where: {
address: address.toLowerCase()
},
order: [['token'], ['transaction', 'blockNumber', 'DESC']],
include: [
{
model: sequelize.models.Contract,
attributes: ['name', 'tokenName', 'tokenSymbol', 'tokenDecimals', 'address', 'workspaceId'],
as: 'tokenContract',
where: tokenFilter,
required: !!allowedTokenPatterns.length
},
{
model: sequelize.models.Transaction,
attributes: ['blockNumber'],
as: 'transaction'
}
]
});
const result = {};
tokenBalanceChanges.forEach(item => {
if (!result[item.token] || result[item.token] && item.blockNumber > result[item.token].blockNumber)
result[item.token] = item.toJSON();
});
return Object.values(result);
}
getFilteredAccounts(page = 1, itemsPerPage = 10, orderBy = 'address', order = 'DESC') {
if (page == -1)
return this.getAccounts({
order: [[orderBy, order]],
attributes: ['workspaceId', 'address', 'balance', 'privateKey']
});
else
return this.getAccounts({
offset: (page - 1) * itemsPerPage,
limit: itemsPerPage,
order: [[orderBy, order]],
attributes: ['workspaceId', 'address', 'balance', 'privateKey']
});
}
getFilteredContracts(page = 1, itemsPerPage = 10, orderBy = 'timestamp', order = 'DESC', pattern = null) {
const allowedPattern = ['erc20', 'erc721'].indexOf(pattern) > -1 ? pattern : null;
const where = allowedPattern ? { patterns: { [Op.contains]: [allowedPattern] } } : {};
return this.getContracts({
where: where,
offset: (page - 1) * itemsPerPage,
limit: itemsPerPage,
order: [[orderBy, order]],
attributes: ['address', 'name', 'timestamp', 'patterns', 'workspaceId', 'tokenName', 'tokenSymbol', 'tokenTotalSupply'],
include: {
model: sequelize.models.ContractVerification,
as: 'verification',
attributes: ['createdAt']
}
});
}
getFilteredBlocks(page = 1, itemsPerPage = 10, order = 'DESC', orderBy = 'number') {
return this.getBlocks({
offset: (page - 1) * itemsPerPage,
limit: itemsPerPage,
order: [[orderBy, order]]
});
}
countTransactionsSince(since = 0) {
return this.countTransactions({
where: {
timestamp: { [Op.gte]: since }
}
});
}
getFilteredTransactions(page = 1, itemsPerPage = 10, order = 'DESC', orderBy = 'blockNumber', address) {
const where = address ? { [Op.or]: [{ to: address.toLowerCase() }, { from: address.toLowerCase() }] } : {};
return this.getTransactions({
where: where,
offset: (page - 1) * itemsPerPage,
limit: itemsPerPage,
order: [[orderBy, order]],
attributes: ['blockNumber', 'from', 'gasPrice', 'hash', 'methodDetails', 'data', 'timestamp', 'to', 'value', 'workspaceId', 'state'],
include: [
{
model: sequelize.models.TransactionReceipt,
attributes: ['gasUsed', 'status', 'contractAddress', [sequelize.json('raw.root'), 'root'], 'gasUsed', 'cumulativeGasUsed', [sequelize.json('raw.effectiveGasPrice'), 'effectiveGasPrice']],
as: 'receipt',
include: [
{
model: sequelize.models.TransactionLog,
attributes: ['address', 'data', 'logIndex', 'topics'],
as: 'logs'
}
]
},
{
model: sequelize.models.Contract,
attributes: ['abi'],
as: 'contract'
}
]
});
}
async canCreateContract() {
if (this.public)
return true;
const user = await this.getUser();
if (user.isPremium)
return true;
const contractCount = await this.countContracts();
return contractCount < 10;
}
async safeCreatePartialBlock(block) {
return sequelize.transaction(async sequelizeTransaction => {
const transactions = block.transactions.map(transaction => {
return sanitize({
workspaceId: this.id,
blockHash: transaction.blockHash,
blockNumber: transaction.blockNumber,
creates: transaction.creates,
data: transaction.data || transaction.input,
parsedError: transaction.parsedError,
rawError: transaction.rawError,
from: transaction.from,
gasLimit: transaction.gasLimit || block.gasLimit,
gasPrice: transaction.gasPrice,
hash: transaction.hash,
methodLabel: transaction.methodLabel,
methodName: transaction.methodName,
methodSignature: transaction.methodSignature,
nonce: transaction.nonce,
r: transaction.r,
s: transaction.s,
timestamp: block.timestamp,
to: transaction.to,
transactionIndex: transaction.transactionIndex !== undefined && transaction.transactionIndex !== null ? transaction.transactionIndex : transaction.index,
type_: transaction.type,
v: transaction.v,
value: transaction.value,
state: 'syncing',
raw: transaction
});
});
return this.createBlock(sanitize({
baseFeePerGas: block.baseFeePerGas,
difficulty: block.difficulty,
extraData: block.extraData,
gasLimit: block.gasLimit,
gasUsed: block.gasUsed,
hash: block.hash,
miner: block.miner,
nonce: block.nonce,
number: block.number,
parentHash: block.parentHash,
timestamp: block.timestamp,
transactionsCount: block.transactions ? block.transactions.length : 0,
state: 'ready',
raw: block,
transactions
}), {
include: [ sequelize.models.Block.associations.transactions ],
transaction: sequelizeTransaction
});
});
}
/*
It's all or nothing, we make sure we synchronize all the block info, ie:
- Block
- Transactions
- Receipt
- Logs
It takes longer, but we avoid inconsistencies, such as a block not displaying all transactions
*/
async safeCreateFullBlock(data) {
try {
return await sequelize.transaction(async sequelizeTransaction => {
const block = data.block;
const transactions = data.transactions;
if (block.transactions.length != transactions.length)
throw new Error('Missing transactions in block.');
const [, [storedBlock]] = await sequelize.models.Block.update(
{ state: 'ready' },
{
where: {
workspaceId: this.id,
number: block.number
},
individualHooks: true,
returning: true,
transaction: sequelizeTransaction
}
);
for (let i = 0; i < transactions.length; i++) {
const transaction = transactions[i];
const [, [storedTx]] = await sequelize.models.Transaction.update(
{ state: 'ready' },
{
where: {
workspaceId: this.id,
hash: transaction.hash
},
individualHooks: true,
returning: true,
transaction: sequelizeTransaction
}
);
const receipt = transaction.receipt;
if (!receipt)
throw new Error('Missing transaction receipt.');
const storedReceipt = await storedTx.createReceipt(sanitize({
workspaceId: storedTx.workspaceId,
blockHash: receipt.blockHash,
blockNumber: receipt.blockNumber,
byzantium: receipt.byzantium,
confirmations: receipt.confirmations,
contractAddress: receipt.contractAddress,
cumulativeGasUsed: receipt.cumulativeGasUsed,
from: receipt.from,
gasUsed: receipt.gasUsed,
logsBloom: receipt.logsBloom,
status: receipt.status,
to: receipt.to,
transactionHash: receipt.transactionHash || receipt.hash || storedTx.hash,
transactionIndex: receipt.transactionIndex || receipt.index,
type: receipt.type,
raw: receipt
}), { transaction: sequelizeTransaction });
for (let i = 0; i < receipt.logs.length; i++) {
const log = receipt.logs[i];
try {
await storedReceipt.createLog(sanitize({
workspaceId: storedTx.workspaceId,
address: log.address,
blockHash: log.blockHash,
blockNumber: log.blockNumber,
data: log.data,
logIndex: log.logIndex,
topics: log.topics,
transactionHash: log.transactionHash,
transactionIndex: log.transactionIndex,
raw: log
}), { transaction: sequelizeTransaction });
} catch(error) {
logger.error(error.message, { location: 'models.workspaces.safeCreateFullBlock', error: error, data });
await storedReceipt.createLog(sanitize({
workspaceId: storedTx.workspaceId,
raw: log
}), { transaction: sequelizeTransaction });
}
}
const explorer = await this.getExplorer();
if (explorer) {
const stripeSubscription = await explorer.getStripeSubscription();
if (stripeSubscription)
await stripeSubscription.increment('transactionQuota', { transaction: sequelizeTransaction });
}
}
return storedBlock;
});
} catch(error) {
await this.safeDestroyPartialBlock(data.block.number);
throw error;
}
}
async safeDestroyPartialBlock(blockNumber) {
const [block] = await this.getBlocks({ where: { workspaceId: this.id, number: blockNumber }});
// No need to throw an error if the block we are trying to destroy does not exist or is not partial
if (!block || block.state !== 'syncing') return;
return block.revertIfPartial();
}
safeCreateBlock(block) {
return this.createBlock(sanitize({
baseFeePerGas: block.baseFeePerGas,
difficulty: block.difficulty,
extraData: block.extraData,
gasLimit: block.gasLimit,
gasUsed: block.gasUsed,
hash: block.hash,
miner: block.miner,
nonce: block.nonce,
number: block.number,
parentHash: block.parentHash,
timestamp: block.timestamp,
transactionsCount: block.transactions ? block.transactions.length : 0,
raw: block
}));
}
async safeCreateTransaction(transaction, blockId) {
return sequelize.transaction(async (sequelizeTransaction) => {
const storedTx = await this.createTransaction(sanitize({
blockHash: transaction.blockHash,
blockNumber: transaction.blockNumber,
blockId: blockId,
creates: transaction.creates,
data: transaction.data,
parsedError: transaction.parsedError,
rawError: transaction.rawError,
from: transaction.from,
gasLimit: transaction.gasLimit,
gasPrice: transaction.gasPrice,
hash: transaction.hash,
methodLabel: transaction.methodLabel,
methodName: transaction.methodName,
methodSignature: transaction.methodSignature,
nonce: transaction.nonce,
r: transaction.r,
s: transaction.s,
timestamp: transaction.timestamp,
to: transaction.to,
transactionIndex: transaction.transactionIndex !== undefined && transaction.transactionIndex !== null ? transaction.transactionIndex : transaction.index,
type_: transaction.type,
v: transaction.v,
value: transaction.value,
raw: transaction
}), { transaction: sequelizeTransaction });
const receipt = transaction.receipt;
if (receipt) {
const storedReceipt = await storedTx.createReceipt(sanitize({
workspaceId: storedTx.workspaceId,
blockHash: receipt.blockHash,
blockNumber: receipt.blockNumber,
byzantium: receipt.byzantium,
confirmations: receipt.confirmations,
contractAddress: receipt.contractAddress,
cumulativeGasUsed: receipt.cumulativeGasUsed,
from: receipt.from,
gasUsed: receipt.gasUsed,
logsBloom: receipt.logsBloom,
status: receipt.status,
to: receipt.to,
transactionHash: receipt.transactionHash || receipt.hash || storedTx.hash,
transactionIndex: receipt.transactionIndex !== undefined && receipt.transactionIndex !== null ? receipt.transactionIndex : receipt.index,
type_: receipt.type,
raw: receipt
}), { transaction: sequelizeTransaction });
for (let i = 0; i < receipt.logs.length; i++) {
const log = receipt.logs[i];
try {
await storedReceipt.createLog(sanitize({
workspaceId: storedTx.workspaceId,
address: log.address,
blockHash: log.blockHash,
blockNumber: log.blockNumber,
data: log.data,
logIndex: log.logIndex,
topics: log.topics,
transactionHash: log.transactionHash,
transactionIndex: log.transactionIndex,
raw: log
}), { transaction: sequelizeTransaction });
} catch(error) {
logger.error(error.message, { location: 'models.workspaces.safeCreateTransaction', error: error, transaction: transaction });
await storedReceipt.createLog(sanitize({
workspaceId: storedTx.workspaceId,
raw: log
}), { transaction: sequelizeTransaction });
}
}
}
return storedTx;
});
}
async safeCreateOrUpdateContract(contract, transaction) {
const contracts = await this.getContracts({ where: { address: contract.address.toLowerCase() }});
const existingContract = contracts[0];
const newContract = sanitize({
hashedBytecode: contract.hashedBytecode,
abi: contract.abi,
address: contract.address,
name: contract.name,
imported: contract.imported,
patterns: contract.patterns,
processed: contract.processed,
proxy: contract.proxy,
timestamp: contract.timestamp,
tokenDecimals: contract.tokenDecimals,
tokenName: contract.tokenName,
tokenSymbol: contract.tokenSymbol,
tokenTotalSupply: contract.tokenTotalSupply,
watchedPaths: contract.watchedPaths,
has721Metadata: contract.has721Metadata,
has721Enumerable: contract.has721Enumerable,
ast: contract.ast,
bytecode: contract.bytecode,
asm: contract.asm
});
if (existingContract)
return existingContract.update(newContract, { transaction })
else
return this.createContract(newContract, { transaction });
}
async safeCreateOrUpdateAccount(account) {
const accounts = await this.getAccounts({ where: { address: account.address.toLowerCase() }});
const existingAccount = accounts[0];
const newAccount = sanitize({
address: account.address,
balance: account.balance,
privateKey: account.privateKey
});
if (existingAccount)
return existingAccount.update(newAccount);
else
return this.createAccount(newAccount);
}
findContractsByText(text) {
return this.getContracts({
attributes: ['id', 'address', 'name', 'tokenName', 'tokenSymbol', 'patterns'],
where: {
[Op.or]: [
{ name: { [Op.iLike]: `%${text}%` } },
{ tokenName: { [Op.iLike]: `%${text}%` } },
{ tokenSymbol: { [Op.iLike]: `%${text}%` } },
]
},
include: {
model: sequelize.models.ContractVerification,
as: 'verification',
attributes: ['createdAt']
}
})
}
async findBlockByHash(hash) {
const blocks = await this.getBlocks({
where: {
hash: hash
}
});
return blocks.length ? blocks[0] : null;
}
async findTransaction(hash) {
const transactions = await this.getTransactions({
where: {
hash: hash
},
attributes: ['id', 'blockNumber', 'data', 'parsedError', 'rawError', 'from', 'formattedBalanceChanges', 'gasLimit', 'gasPrice', 'hash', 'timestamp', 'to', 'value', 'storage', 'workspaceId', 'raw', 'state',
[Sequelize.literal(`
(SELECT COUNT(*)::int
FROM token_transfers AS token_transfers
WHERE token_transfers."transactionId" = "Transaction".id)
`), 'tokenTransferCount']
],
order: [
[sequelize.literal('"traceSteps".'), 'id', 'asc']
],
include: [
{
model: sequelize.models.TransactionReceipt,
attributes: ['gasUsed', 'status', 'contractAddress', [sequelize.json('raw.root'), 'root'], 'cumulativeGasUsed', 'raw', [sequelize.json('raw.effectiveGasPrice'), 'effectiveGasPrice']],
as: 'receipt',
include: [
{
model: sequelize.models.TransactionLog,
attributes: ['address', 'data', 'logIndex', 'topics', 'raw'],
as: 'logs'
}
]
},
{
model: sequelize.models.TransactionTraceStep,
attributes: ['address', 'contractHashedBytecode', 'depth', 'input', 'op', 'returnData', 'workspaceId', 'id', 'value'],
as: 'traceSteps',
include: [
{
model: sequelize.models.Contract,
attributes: ['abi', 'address' , 'name', 'tokenDecimals', 'tokenName', 'tokenSymbol', 'workspaceId'],
include: [
{
model: sequelize.models.Contract,
attributes: ['name', 'tokenName', 'tokenSymbol', 'tokenDecimals', 'abi', 'address', 'workspaceId'],
as: 'proxyContract',
where: {
[Op.and]: sequelize.where(
sequelize.col("traceSteps->contract.workspaceId"),
Op.eq,
sequelize.col("traceSteps->contract->proxyContract.workspaceId")
),
},
required: false
},
{
model: sequelize.models.ContractVerification,
attributes: ['createdAt'],
as: 'verification'
}
],
as: 'contract'
}
]
},
{
model: sequelize.models.TokenBalanceChange,
attributes: ['token', 'address', 'currentBalance', 'previousBalance', 'diff', 'transactionId'],
as: 'tokenBalanceChanges'
},
{
model: sequelize.models.Block,
attributes: ['gasLimit', 'timestamp'],
as: 'block'
},
{
model: sequelize.models.Contract,
attributes: ['abi', 'address', 'name', 'tokenDecimals', 'tokenName', 'tokenSymbol', 'workspaceId'],
as: 'contract'
}
]
});
return transactions.length ? transactions[0] : null;
}
async findBlockByNumber(number, withTransactions = false) {
const include = withTransactions ? [{
model: sequelize.models.Transaction,
attributes: ['id', 'from', 'to', 'hash'],
as: 'transactions'
}] : [];
const blocks = await this.getBlocks({
where: {
number: number
},
include: include
});
return blocks[0];
}
async findContractById(contractId) {
const contracts = await this.getContracts({
where: {
id: contractId
}
});
return contracts[0];
}
async findContractByAddress(address) {
const contracts = await this.getContracts({
where: {
address: address.toLowerCase()
},
include: [
{
model: sequelize.models.Contract,
attributes: ['name', 'tokenName', 'tokenSymbol', 'tokenDecimals', 'abi', 'address'],
as: 'proxyContract',
required: false,
where: {
[Op.and]: sequelize.where(
sequelize.col("Contract.workspaceId"),
Op.eq,
sequelize.col("proxyContract.workspaceId")
)
}
},
{
model: sequelize.models.Transaction,
attributes: ['blockNumber', 'hash'],
as: 'creationTransaction',
},
{
model: sequelize.models.ContractVerification,
as: 'verification',
include: [
{
model: sequelize.models.ContractSource,
as: 'sources'
}
]
}
]
});
return contracts[0];
}
async findContractByHashedBytecode(hashedBytecode) {
const contracts = await this.getContracts({
where: {
hashedBytecode: hashedBytecode
}
});
return contracts[0];
}
addIntegration(integration) {
if (!INTEGRATION_FIELD_MAPPING[integration])
throw '[workspace.addIntegration] Unknown integration';
return this.update({
[INTEGRATION_FIELD_MAPPING[integration]]: true
});
}
removeIntegration(integration) {
if (!INTEGRATION_FIELD_MAPPING[integration])
throw '[workspace.removeIntegration] Unknown integration';
return this.update({
[INTEGRATION_FIELD_MAPPING[integration]]: false
});
}
async updateSettings(data) {
if (data.name) {
const existing = await sequelize.models.Workspace.findOne({
where: {
userId: this.userId,
name: data.name,
id: {
[Op.not]: this.id
}
}
});
if (existing)
throw new Error('You already have a workspace with this name.');
}
return sequelize.transaction(async (transaction) => {
if (data.rpcServer && data.networkId) {
const explorer = await this.getExplorer();
if (explorer)
await explorer.update({ rpcServer: data.rpcServer, chainId: data.networkId }, { transaction });
}
return this.update(sanitize({
name: data.name,
statusPageEnabled: data.statusPageEnabled,
chain: data.chain,