-
Notifications
You must be signed in to change notification settings - Fork 17
/
transfer_report.go
326 lines (282 loc) · 10.7 KB
/
transfer_report.go
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
package report
import (
"context"
"encoding/csv"
"fmt"
"math/big"
"os"
"regexp"
"strings"
"time"
"github.com/shopspring/decimal"
"github.com/wormhole-foundation/wormhole-explorer/common/domain"
"github.com/wormhole-foundation/wormhole-explorer/common/prices"
sdk "github.com/wormhole-foundation/wormhole/sdk/vaa"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.uber.org/zap"
)
type TransferReportJob struct {
database *mongo.Database
pageSize int64
logger *zap.Logger
getPriceByTime GetPriceByTimeFn
outputPath string
tokenProvider *domain.TokenProvider
}
type transactionResult struct {
ID string `bson:"_id" json:"vaaId"`
SourceChain sdk.ChainID `bson:"sourceChain" json:"sourceChain"`
EmitterAddress string `bson:"emitterAddress" json:"emitterAddress"`
Sequence string `bson:"sequence" json:"sequence"`
VaaHash string `bson:"vaaHash" json:"vaaHash"`
SourceTxHash string `bson:"sourceTxHash" json:"sourceTxHash"`
DestinationChain sdk.ChainID `bson:"destinationChain" json:"destinationChain"`
DestinationTxHash string `bson:"destinationTxHash" json:"destinationTxHash"`
TokenChain sdk.ChainID `bson:"tokenChain" json:"tokenChain"`
TokenAddress string `bson:"tokenAddress" json:"tokenAddress"`
TokenAddressHexa string `bson:"tokenAddressHexa" json:"tokenAddressHexa"`
Amount string `bson:"amount" json:"amount"`
SourceSenderAddress string `bson:"sourceWallet" json:"sourceSenderAddress"`
DestinationAddress string `bson:"destinationWallet" json:"destinationAddress"`
Fee string `bson:"fee" json:"fee"`
Timestamp time.Time `bson:"timestamp" json:"timestamp"`
AppIds []string `bson:"appIds" json:"appIds"`
PortalPayloadType int `bson:"portalPayloadType" json:"portalPayloadType"`
SemanticDestinationAddress string `bson:"semanticDestinationAddress" json:"semanticDestinationAddress"`
}
type GetPriceByTimeFn func(ctx context.Context, coingeckoID string, day time.Time) (decimal.Decimal, error)
// NewTransferReportJob creates a new transfer report job.
func NewTransferReportJob(database *mongo.Database, pageSize int64, getPriceByTime GetPriceByTimeFn, outputPath string, tokenProvider *domain.TokenProvider, logger *zap.Logger) *TransferReportJob {
return &TransferReportJob{database: database, pageSize: pageSize, getPriceByTime: getPriceByTime, outputPath: outputPath, tokenProvider: tokenProvider, logger: logger}
}
// Run runs the transfer report job.
func (j *TransferReportJob) Run(ctx context.Context) error {
file, err := os.Create(j.outputPath)
if err != nil {
return err
}
writer := csv.NewWriter(file)
_ = j.writeHeader(writer)
defer file.Close()
//start backfilling
page := int64(0)
for {
j.logger.Info("Processing page", zap.Int64("page", page))
trxs, err := j.findTransactionsByPage(ctx, page, j.pageSize)
if err != nil {
j.logger.Error("Failed to get transactions", zap.Error(err))
break
}
if len(trxs) == 0 {
j.logger.Info("Empty page", zap.Int64("page", page))
break
}
for _, t := range trxs {
log := j.logger.With(zap.String("id", t.ID))
log.Debug("Processing transaction")
if t.TokenAddressHexa == "" {
j.writeRecord(t, t.Amount, nil, nil, writer)
continue
}
tokenAddress, err := sdk.StringToAddress(t.TokenAddressHexa)
if err != nil {
log.Error("Failed to get transactions",
zap.String("tokenAddressHexa", t.TokenAddressHexa),
zap.Error(err))
continue
}
m, ok := j.tokenProvider.GetTokenByAddress(sdk.ChainID(t.TokenChain), tokenAddress.String())
if ok {
tokenPrice, err := j.getPriceByTime(ctx, m.CoingeckoID, t.Timestamp)
if err != nil {
log.Error("Failed to get token price",
zap.String("coingeckoId", m.CoingeckoID),
zap.String("timestamp", t.Timestamp.UTC().Format(time.RFC3339)),
zap.Error(err))
continue
}
if t.Amount == "" {
j.writeRecord(t, t.Amount, nil, nil, writer)
continue
}
amount := new(big.Int)
amount, ok := amount.SetString(t.Amount, 10)
if !ok {
log.Error("amount is not a number",
zap.String("amount", t.Amount),
)
j.writeRecord(t, "", nil, nil, writer)
continue
}
priceUSD := prices.CalculatePriceUSD(tokenPrice, amount, m.Decimals)
j.writeRecord(t, t.Amount, m, &priceUSD, writer)
} else {
j.writeRecord(t, t.Amount, nil, nil, writer)
}
}
writer.Flush()
page++
}
return nil
}
func (j *TransferReportJob) writeRecord(trx transactionResult, fAmount string, m *domain.TokenMetadata, priceUSD *decimal.Decimal, file *csv.Writer) error {
var notionalUSD, decimals, symbol, coingeckoID, tokenAddress string
if m != nil {
decimals = fmt.Sprintf("%d", m.Decimals)
symbol = m.Symbol.String()
coingeckoID = m.CoingeckoID
}
if priceUSD != nil {
notionalUSD = priceUSD.Truncate(10).String()
}
tokenAddress = trx.TokenAddress
if !regexp.MustCompile(`^[A-Za-z0-9]*$`).MatchString(tokenAddress) {
tokenAddress, _ = domain.TranslateEmitterAddress(trx.TokenChain, trx.TokenAddressHexa)
}
var record []string
record = append(record, trx.ID)
record = append(record, trx.VaaHash)
record = append(record, chainIDToCsv(trx.SourceChain))
record = append(record, trx.EmitterAddress)
record = append(record, trx.Sequence)
record = append(record, trx.Timestamp.Format(time.RFC3339))
record = append(record, trx.SourceTxHash)
record = append(record, trx.SourceSenderAddress)
record = append(record, chainIDToCsv(trx.DestinationChain))
record = append(record, trx.DestinationAddress)
record = append(record, trx.DestinationTxHash)
record = append(record, portalPayloadTypeToCsv(trx.PortalPayloadType))
record = append(record, appIdsToCsv(trx.AppIds))
record = append(record, chainIDToCsv(trx.TokenChain))
record = append(record, tokenAddress)
record = append(record, fAmount)
record = append(record, decimals)
record = append(record, notionalUSD)
record = append(record, trx.Fee)
record = append(record, coingeckoID)
record = append(record, symbol)
return file.Write(record)
}
func (*TransferReportJob) writeHeader(writer *csv.Writer) error {
var record []string
record = append(record, "vaaId")
record = append(record, "vaaHash")
record = append(record, "sourceChain")
record = append(record, "emitterAddress")
record = append(record, "sequence")
record = append(record, "timestamp")
record = append(record, "sourceTxHash")
record = append(record, "sourceSenderAddress")
record = append(record, "destinationChain")
record = append(record, "destinationAddress")
record = append(record, "destinationTxHash")
record = append(record, "portalPayloadType")
record = append(record, "appIds")
record = append(record, "tokenChain")
record = append(record, "tokenAddress")
record = append(record, "amount")
record = append(record, "decimals")
record = append(record, "notionalUSD")
record = append(record, "fee")
record = append(record, "coinGeckoId")
record = append(record, "symbol")
return writer.Write(record)
}
func (j *TransferReportJob) findTransactionsByPage(ctx context.Context, page, pageSize int64) ([]transactionResult, error) {
vaas := j.database.Collection("vaas")
skip := page * pageSize
// Build the aggregation pipeline
var pipeline mongo.Pipeline
pipeline = append(pipeline, bson.D{
{Key: "$sort", Value: bson.D{
bson.E{Key: "timestamp", Value: -1},
bson.E{Key: "_id", Value: -1},
}},
})
pipeline = append(pipeline, bson.D{
{Key: "$lookup", Value: bson.D{
{Key: "from", Value: "parsedVaa"},
{Key: "localField", Value: "_id"},
{Key: "foreignField", Value: "_id"},
{Key: "as", Value: "parsedVaa"},
}},
})
pipeline = append(pipeline, bson.D{
{Key: "$lookup", Value: bson.D{
{Key: "from", Value: "globalTransactions"},
{Key: "localField", Value: "_id"},
{Key: "foreignField", Value: "_id"},
{Key: "as", Value: "globalTransactions"},
}},
})
// Skip initial results
pipeline = append(pipeline, bson.D{
{Key: "$skip", Value: skip},
})
// Limit size of results
pipeline = append(pipeline, bson.D{
{Key: "$limit", Value: pageSize},
})
// add nested fields
pipeline = append(pipeline, bson.D{
{Key: "$addFields", Value: bson.D{
{Key: "standardizedProperties", Value: bson.M{"$arrayElemAt": []interface{}{"$parsedVaa.rawStandardizedProperties", 0}}},
{Key: "globalTransactions", Value: bson.M{"$arrayElemAt": []interface{}{"$globalTransactions", 0}}},
{Key: "appIds", Value: bson.M{"$arrayElemAt": []interface{}{"$parsedVaa.appIds", 0}}},
{Key: "parsedPayload", Value: bson.M{"$arrayElemAt": []interface{}{"$parsedVaa.parsedPayload", 0}}},
}},
})
pipeline = append(pipeline, bson.D{
{Key: "$project", Value: bson.D{
{Key: "appIds", Value: "$appIds"},
{Key: "sourceChain", Value: "$emitterChain"},
{Key: "emitterAddress", Value: "$emitterAddr"},
{Key: "sequence", Value: "$sequence"},
{Key: "vaaHash", Value: "$txHash"},
{Key: "destinationChain", Value: "$standardizedProperties.toChain"},
{Key: "tokenChain", Value: "$standardizedProperties.tokenChain"},
{Key: "tokenAddress", Value: "$standardizedProperties.tokenAddress"},
{Key: "amount", Value: "$standardizedProperties.amount"},
{Key: "sourceWallet", Value: "$globalTransactions.originTx.from"},
{Key: "sourceTxHash", Value: "$globalTransactions.originTx.nativeTxHash"},
{Key: "destinationTxHash", Value: "$globalTransactions.destinationTx.txHash"},
{Key: "destinationWallet", Value: "$standardizedProperties.toAddress"},
{Key: "fee", Value: "$standardizedProperties.fee"},
{Key: "timestamp", Value: "$timestamp"},
{Key: "tokenAddressHexa", Value: "$parsedPayload.tokenAddress"},
{Key: "portalPayloadType", Value: "$parsedPayload.payloadType"},
}}})
// Execute the aggregation pipeline
cur, err := vaas.Aggregate(ctx, pipeline)
if err != nil {
j.logger.Error("failed execute aggregation pipeline", zap.Error(err))
return nil, err
}
// Read results from cursor
var documents []transactionResult
err = cur.All(ctx, &documents)
if err != nil {
j.logger.Error("failed to decode cursor", zap.Error(err))
return nil, err
}
return documents, nil
}
func chainIDToCsv(chainID sdk.ChainID) string {
if chainID.String() == sdk.ChainIDUnset.String() {
return ""
}
return fmt.Sprintf("%d", int16(chainID))
}
func appIdsToCsv(appIds []string) string {
if len(appIds) == 0 {
return ""
}
return strings.Join(appIds, "|")
}
func portalPayloadTypeToCsv(portalPayloadType int) string {
if portalPayloadType == 0 {
return ""
}
return fmt.Sprintf("%d", portalPayloadType)
}