This repository has been archived by the owner on Jan 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 88
/
transaction.ts
99 lines (94 loc) · 2.72 KB
/
transaction.ts
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
import { DecodedMethod, DecodedParam } from 'abi-decoder';
import {
GraphQLEnumType,
GraphQLFieldConfigMap,
GraphQLInt,
GraphQLInterfaceType,
GraphQLObjectType,
GraphQLString,
GraphQLUnionType,
} from 'graphql';
import { Account } from './account';
export const DecodedTransaction = new GraphQLInterfaceType({
name: 'InterpretedTransaction',
resolveType: decoded => decoded.type,
fields: {
contractType: {
name: 'ContractType',
type: GraphQLString,
},
},
});
export const Transaction = new GraphQLObjectType({
name: 'Transaction',
fields: {
hash: { type: GraphQLString },
nonce: { type: GraphQLInt },
blockHash: { type: GraphQLString },
blockNumber: { type: GraphQLInt },
transactionIndex: { type: GraphQLInt },
from: { type: Account },
to: { type: Account },
value: { type: GraphQLString },
gasPrice: { type: GraphQLString },
gas: { type: GraphQLInt },
input: { type: GraphQLString },
decoded: {
type: DecodedTransaction,
resolve: tx => {
if (!tx.input) {
return;
}
/* If we find a decoder for the transaction, we return the result of the ABI decoding
enhanced with a 'type' property with the GraphQL type. */
for (const entry of decoders) {
const decoded = entry.decoder.decodeMethod(tx.input);
if (decoded) {
return { ...decoded, type: entry.type };
}
}
},
},
},
});
const extractParamValue = (params: [DecodedParam], name: string) => {
if (Array.isArray(params) && params.length >= 0) {
const param = params.find(p => name === p.name);
return param && param.value;
}
};
export const Erc20TransactionType = new GraphQLObjectType({
name: 'ERC20Transaction',
interfaces: [DecodedTransaction],
fields: {
contractType: { type: GraphQLString, resolve: () => 'erc20' },
action: {
type: new GraphQLEnumType({
name: 'ERC20Actions',
values: {
approveAndCall: { value: 'approveAndCall' },
approve: { value: 'approve' },
transferFrom: { value: 'transferFrom' },
transfer: { value: 'transfer' },
},
}),
resolve: ({ name }) => name,
},
from: {
type: GraphQLString,
resolve: ({ params }) => extractParamValue(params, 'from'),
},
to: { type: GraphQLString, resolve: ({ params }) => extractParamValue(params, 'to') },
value: { type: GraphQLString, resolve: ({ params }) => extractParamValue(params, 'value') },
},
});
const decoders = [
{
type: Erc20TransactionType,
decoder: (() => {
const decoder = require('abi-decoder');
decoder.addABI(require('../abi/erc20.json'));
return decoder;
})(),
},
];