-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
tx.go
723 lines (626 loc) · 27.8 KB
/
tx.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
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
package core
import (
b64 "encoding/base64"
"encoding/hex"
"fmt"
"math/big"
"reflect"
"strings"
"time"
"unsafe"
"github.com/DefiantLabs/cosmos-tax-cli/block-sdk/modules/auction"
"github.com/DefiantLabs/cosmos-tax-cli/config"
"github.com/DefiantLabs/cosmos-tax-cli/cosmos/modules/authz"
"github.com/DefiantLabs/cosmos-tax-cli/cosmos/modules/bank"
"github.com/DefiantLabs/cosmos-tax-cli/cosmos/modules/distribution"
"github.com/DefiantLabs/cosmos-tax-cli/cosmos/modules/gov"
"github.com/DefiantLabs/cosmos-tax-cli/cosmos/modules/ibc"
"github.com/DefiantLabs/cosmos-tax-cli/cosmos/modules/slashing"
"github.com/DefiantLabs/cosmos-tax-cli/cosmos/modules/staking"
txtypes "github.com/DefiantLabs/cosmos-tax-cli/cosmos/modules/tx"
"github.com/DefiantLabs/cosmos-tax-cli/cosmos/modules/vesting"
"github.com/DefiantLabs/cosmos-tax-cli/cosmwasm"
"github.com/DefiantLabs/cosmos-tax-cli/cosmwasm/modules/wasm"
dbTypes "github.com/DefiantLabs/cosmos-tax-cli/db"
"github.com/DefiantLabs/cosmos-tax-cli/osmosis"
"github.com/DefiantLabs/cosmos-tax-cli/osmosis/modules/gamm"
"github.com/DefiantLabs/cosmos-tax-cli/osmosis/modules/incentives"
"github.com/DefiantLabs/cosmos-tax-cli/osmosis/modules/lockup"
"github.com/DefiantLabs/cosmos-tax-cli/osmosis/modules/protorev"
"github.com/DefiantLabs/cosmos-tax-cli/osmosis/modules/smartaccount"
"github.com/DefiantLabs/cosmos-tax-cli/osmosis/modules/superfluid"
"github.com/DefiantLabs/cosmos-tax-cli/osmosis/modules/tokenfactory"
"github.com/DefiantLabs/cosmos-tax-cli/osmosis/modules/valsetpref"
"github.com/DefiantLabs/cosmos-tax-cli/tendermint/modules/liquidity"
"github.com/DefiantLabs/cosmos-tax-cli/util"
"github.com/DefiantLabs/lens/client"
coretypes "github.com/cometbft/cometbft/rpc/core/types"
"github.com/cosmos/cosmos-sdk/crypto/keys/multisig"
cryptoTypes "github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/types"
cosmosTx "github.com/cosmos/cosmos-sdk/types/tx"
"gorm.io/gorm"
sdkMath "cosmossdk.io/math"
indexerEvents "github.com/DefiantLabs/cosmos-tax-cli/cosmos/events"
)
// Unmarshal JSON to a particular type. There can be more than one handler for each type.
var messageTypeHandler = map[string][]func() txtypes.CosmosMessage{
bank.MsgSend: {func() txtypes.CosmosMessage { return &bank.WrapperMsgSend{} }},
bank.MsgMultiSend: {func() txtypes.CosmosMessage { return &bank.WrapperMsgMultiSend{} }},
distribution.MsgWithdrawDelegatorReward: {func() txtypes.CosmosMessage { return &distribution.WrapperMsgWithdrawDelegatorReward{} }},
distribution.MsgWithdrawValidatorCommission: {func() txtypes.CosmosMessage { return &distribution.WrapperMsgWithdrawValidatorCommission{} }},
distribution.MsgFundCommunityPool: {func() txtypes.CosmosMessage { return &distribution.WrapperMsgFundCommunityPool{} }},
gov.MsgDeposit: {func() txtypes.CosmosMessage { return &gov.WrapperMsgDeposit{} }},
gov.MsgSubmitProposal: {func() txtypes.CosmosMessage { return &gov.WrapperMsgSubmitProposal{} }},
gov.MsgDepositV1: {func() txtypes.CosmosMessage { return &gov.WrapperMsgDepositV1{} }},
gov.MsgSubmitProposalV1: {func() txtypes.CosmosMessage { return &gov.WrapperMsgSubmitProposalV1{} }},
staking.MsgDelegate: {func() txtypes.CosmosMessage { return &staking.WrapperMsgDelegate{} }},
staking.MsgUndelegate: {func() txtypes.CosmosMessage { return &staking.WrapperMsgUndelegate{} }},
staking.MsgBeginRedelegate: {func() txtypes.CosmosMessage { return &staking.WrapperMsgBeginRedelegate{} }},
ibc.MsgRecvPacket: {func() txtypes.CosmosMessage { return &ibc.WrapperMsgRecvPacket{} }},
ibc.MsgAcknowledgement: {func() txtypes.CosmosMessage { return &ibc.WrapperMsgAcknowledgement{} }},
// Support is not fully built out for this message parser
// auction.MsgAuctionBid: {func() txtypes.CosmosMessage { return &auction.WrapperMsgAuctionBid{} }},
}
// These messages are ignored for tax purposes.
// Fees will still be tracked, there is just not need to parse the msg body.
var messageTypeIgnorer = map[string]interface{}{
/////////////////////////////////
/////// Nontaxable Events ///////
/////////////////////////////////
// Authz module actions are not taxable
authz.MsgExec: nil,
authz.MsgGrant: nil,
authz.MsgRevoke: nil,
// block-sdk auction module parameter updates are not taxable
auction.MsgUpdateParams: nil,
auction.MsgAuctionBid: nil,
// Making a config change is not taxable
distribution.MsgSetWithdrawAddress: nil,
// Making a stableswap config change is not taxable
gamm.MsgStableSwapAdjustScalingFactors: nil,
// Voting is not taxable
gov.MsgVote: nil,
gov.MsgVoteWeighted: nil,
gov.MsgVoteV1: nil,
gov.MsgVoteWeightedV1: nil,
// The IBC msgs below do not create taxable events
ibc.MsgTransfer: nil,
ibc.MsgUpdateClient: nil,
ibc.MsgTimeout: nil,
ibc.MsgTimeoutOnClose: nil,
ibc.MsgCreateClient: nil,
ibc.MsgConnectionOpenTry: nil,
ibc.MsgConnectionOpenConfirm: nil,
ibc.MsgChannelOpenTry: nil,
ibc.MsgChannelOpenConfirm: nil,
ibc.MsgConnectionOpenInit: nil,
ibc.MsgConnectionOpenAck: nil,
ibc.MsgChannelOpenInit: nil,
ibc.MsgChannelOpenAck: nil,
ibc.MsgChannelCloseConfirm: nil,
ibc.MsgChannelCloseInit: nil,
ibc.MsgSubmitMisbehaviour: nil,
// Interchain accounts are being explored for taxable types
ibc.InterchainAccountsMsgRegisterInterchainAccount: nil,
ibc.InterchainAccountsMsgSendTX: nil,
// Creating and modifying gauges does not create taxable events
incentives.MsgCreateGauge: nil,
incentives.MsgAddToGauge: nil,
// Locking/unlocking is not taxable
lockup.MsgBeginUnlocking: nil,
lockup.MsgLockTokens: nil,
lockup.MsgBeginUnlockingAll: nil,
lockup.MsgUnlockPeriodLock: nil,
lockup.MsgUnlockTokens: nil,
lockup.MsgSetRewardReceiverAddress: nil,
// Protorev taxable events are handled in epoch BeginBlock events
protorev.MsgSetDeveloperAccount: nil,
// Unjailing and updating params is not taxable
slashing.MsgUnjail: nil,
slashing.MsgUpdateParams: nil,
// Smart accounts are being explored
smartaccount.MsgAddAuthenticator: nil,
smartaccount.MsgRemoveAuthenticator: nil,
// Creating and editing validator is not taxable
staking.MsgCreateValidator: nil,
staking.MsgEditValidator: nil,
staking.MsgCancelUnbondingDelegation: nil, // No rewards are withdrawn when cancelling an unbonding delegation
// Delegating and Locking are not taxable
superfluid.MsgSuperfluidDelegate: nil,
superfluid.MsgSuperfluidUndelegate: nil,
superfluid.MsgSuperfluidUnbondLock: nil,
superfluid.MsgLockAndSuperfluidDelegate: nil,
superfluid.MsgUnPoolWhitelistedPool: nil,
superfluid.MsgUnlockAndMigrateSharesToFullRangeConcentratedPosition: nil,
superfluid.MsgSuperfluidUndelegateAndUnbondLock: nil,
superfluid.MsgCreateFullRangePositionAndSuperfluidDelegate: nil,
superfluid.MsgAddToConcentratedLiquiditySuperfluidPosition: nil,
superfluid.MsgUnbondConvertAndStake: nil,
// Setting validator pref is not taxable
valsetpref.MsgSetValidatorSetPreference: nil,
// Create account is not taxable
vesting.MsgCreateVestingAccount: nil,
// Tendermint Liquidity messages are actually executed in batches during periodic EndBlocker events
// We ignore the Message types since the actual taxable events happen later, and the messages can fail/be refunded
liquidity.MsgCreatePool: nil,
liquidity.MsgDepositWithinBatch: nil,
liquidity.MsgWithdrawWithinBatch: nil,
liquidity.MsgSwapWithinBatch: nil,
// These tokenfactory module messages dont create taxable events
tokenfactory.MsgCreateDenom: nil,
tokenfactory.MsgSetBeforeSendHook: nil,
tokenfactory.MsgSetDenomMetadata: nil,
tokenfactory.MsgChangeAdmin: nil,
////////////////////////////////////////////////////
/////// Possible Taxable Events, future work ///////
////////////////////////////////////////////////////
// CosmWasm
wasm.MsgInstantiateContract: nil,
wasm.MsgInstantiateContract2: nil,
wasm.MsgStoreCode: nil,
wasm.MsgMigrateContract: nil,
wasm.MsgUpdateAdmin: nil,
wasm.MsgClearAdmin: nil,
wasm.MsgUpdateInstantiationAdmin: nil,
wasm.MsgUpdateParams: nil,
wasm.MsgSudoContract: nil,
wasm.MsgPinCodes: nil,
wasm.MsgUnpinCodes: nil,
wasm.MsgStoreAndInstantiateContract: nil,
wasm.MsgRemoveCodeUploadParamsAddresses: nil,
wasm.MsgAddCodeUploadParamsAddresses: nil,
wasm.MsgStoreAndMigrateContract: nil,
}
// Merge the chain specific message type handlers into the core message type handler map.
// Chain specific handlers will be registered BEFORE any generic handlers.
func ChainSpecificMessageTypeHandlerBootstrap(chainID string, lensClient *client.ChainClient) {
var customContractAddressHandlers []wasm.ContractExecutionMessageHandler
var chainSpecificMessageTpeHandler map[string][]func() txtypes.CosmosMessage
if chainID == osmosis.ChainID {
chainSpecificMessageTpeHandler = osmosis.MessageTypeHandler
}
for key, value := range chainSpecificMessageTpeHandler {
if list, ok := messageTypeHandler[key]; ok {
messageTypeHandler[key] = append(value, list...)
} else {
messageTypeHandler[key] = value
}
}
cosmWasmHandlers, err := cosmwasm.GetCosmWasmMessageTypeHandlers(customContractAddressHandlers, lensClient)
if err != nil {
config.Log.Fatal("Error getting CosmWasm message type handlers.", err)
}
for key, value := range cosmWasmHandlers {
if list, ok := messageTypeHandler[key]; ok {
messageTypeHandler[key] = append(value, list...)
} else {
messageTypeHandler[key] = value
}
}
}
// ParseCosmosMessageJSON - Parse a SINGLE Cosmos Message into the appropriate type.
func ParseCosmosMessage(message types.Msg, log txtypes.LogMessage) (txtypes.CosmosMessage, string, error) {
var ok bool
var err error
var msgHandler txtypes.CosmosMessage
var handlerList []func() txtypes.CosmosMessage
// Figure out what type of Message this is based on the '@type' field that is included
// in every Cosmos Message (can be seen in raw JSON for any cosmos transaction).
cosmosMessage := txtypes.Message{}
cosmosMessage.Type = types.MsgTypeURL(message)
// So far we only parsed the '@type' field. Now we get a struct for that specific type.
if handlerList, ok = messageTypeHandler[cosmosMessage.Type]; !ok {
return nil, cosmosMessage.Type, txtypes.ErrUnknownMessage
}
for _, handlerFunc := range handlerList {
// Unmarshal the rest of the JSON now that we know the specific type.
// Note that depending on the type, it may or may not care about logs.
msgHandler = handlerFunc()
err = msgHandler.HandleMsg(cosmosMessage.Type, message, &log)
// We're finished when a working handler is found
if err == nil {
break
}
}
return msgHandler, cosmosMessage.Type, err
}
func toAttributes(attrs []types.Attribute) []txtypes.Attribute {
list := []txtypes.Attribute{}
for _, attr := range attrs {
lma := txtypes.Attribute{Key: attr.Key, Value: attr.Value}
list = append(list, lma)
}
return list
}
func toEvents(msgEvents types.StringEvents) (list []txtypes.LogMessageEvent) {
for _, evt := range msgEvents {
lme := txtypes.LogMessageEvent{Type: evt.Type, Attributes: toAttributes(evt.Attributes)}
list = append(list, lme)
}
return list
}
func getUnexportedField(field reflect.Value) interface{} {
return reflect.NewAt(field.Type(), unsafe.Pointer(field.UnsafeAddr())).Elem().Interface()
}
func ProcessRPCBlockByHeightTXs(db *gorm.DB, cl *client.ChainClient, blockResults *coretypes.ResultBlock, resultBlockRes *coretypes.ResultBlockResults) ([]dbTypes.TxDBWrapper, *time.Time, error) {
if len(blockResults.Block.Txs) != len(resultBlockRes.TxsResults) {
config.Log.Fatalf("blockResults & resultBlockRes: different length")
}
blockTime := &blockResults.Block.Time
blockTimeStr := blockTime.Format(time.RFC3339)
currTxDbWrappers := make([]dbTypes.TxDBWrapper, len(blockResults.Block.Txs))
for txIdx, tendermintTx := range blockResults.Block.Txs {
txResult := resultBlockRes.TxsResults[txIdx]
// Indexer types only used by the indexer app (similar to the cosmos types)
var indexerMergedTx txtypes.MergedTx
var indexerTx txtypes.IndexerTx
var txBody txtypes.Body
var currMessages []types.Msg
var currLogMsgs []txtypes.LogMessage
txDecoder := cl.Codec.TxConfig.TxDecoder()
txBasic, err := txDecoder(tendermintTx)
if err != nil {
return nil, blockTime, fmt.Errorf("ProcessRPCBlockByHeightTXs: TX cannot be parsed from block %v. Err: %v", blockResults.Block.Height, err)
}
// This is a hack, but as far as I can tell necessary. "wrapper" struct is private in Cosmos SDK.
field := reflect.ValueOf(txBasic).Elem().FieldByName("tx")
iTx := getUnexportedField(field)
txFull := iTx.(*cosmosTx.Tx)
logs := types.ABCIMessageLogs{}
// Failed TXs do not have proper JSON in the .Log field, causing ParseABCILogs to fail to unmarshal the logs
// We can entirely ignore failed TXs in downstream parsers, because according to the Cosmos specification, a single failed message in a TX fails the whole TX
if txResult.Code == 0 {
logs, err = types.ParseABCILogs(txResult.Log)
if err != nil {
logs, err = indexerEvents.ParseTxEventsToMessageIndexEvents(len(txFull.Body.Messages), txResult.Events)
}
} else {
err = nil
}
if err != nil {
return nil, blockTime, fmt.Errorf("logs could not be parsed")
}
// Get the Messages and Message Logs
for msgIdx, currMsg := range txFull.GetMsgs() {
if currMsg != nil {
currMessages = append(currMessages, currMsg)
msgEvents := types.StringEvents{}
if txResult.Code == 0 {
msgEvents = logs[msgIdx].Events
}
currTxLog := txtypes.LogMessage{
MessageIndex: msgIdx,
Events: toEvents(msgEvents),
}
currLogMsgs = append(currLogMsgs, currTxLog)
} else {
return nil, blockTime, fmt.Errorf("tx message could not be processed")
}
}
txBody.Messages = currMessages
indexerTx.Body = txBody
txHash := tendermintTx.Hash()
indexerTxResp := txtypes.Response{
TxHash: b64.StdEncoding.EncodeToString(txHash),
Height: fmt.Sprintf("%d", blockResults.Block.Height),
TimeStamp: blockTimeStr,
RawLog: txResult.Log,
Log: currLogMsgs,
Code: txResult.Code,
}
indexerTx.AuthInfo = *txFull.AuthInfo
txSigners, _, err := txFull.GetSigners(cl.Codec.Marshaler)
if err != nil {
return nil, blockTime, fmt.Errorf("error getting signers: %v", err)
}
for _, signer := range txSigners {
indexerTx.Signers = append(indexerTx.Signers, signer)
}
indexerMergedTx.TxResponse = indexerTxResp
indexerMergedTx.Tx = indexerTx
indexerMergedTx.Tx.AuthInfo = *txFull.AuthInfo
processedTx, _, err := ProcessTx(cl, db, indexerMergedTx)
if err != nil {
return currTxDbWrappers, blockTime, err
}
if len(indexerTx.Signers) > 0 {
processedTx.SignerAddress = dbTypes.Address{Address: indexerTx.Signers[0].String()}
} else {
return currTxDbWrappers, blockTime, fmt.Errorf("tx signers could not be processed, no signers found")
}
currTxDbWrappers[txIdx] = processedTx
}
return currTxDbWrappers, blockTime, nil
}
// ProcessRPCTXs - Given an RPC response, build out the more specific data used by the parser.
func ProcessRPCTXs(db *gorm.DB, cl *client.ChainClient, txEventResp *cosmosTx.GetTxsEventResponse) ([]dbTypes.TxDBWrapper, *time.Time, error) {
currTxDbWrappers := make([]dbTypes.TxDBWrapper, len(txEventResp.Txs))
var blockTime *time.Time
for txIdx := range txEventResp.Txs {
// Indexer types only used by the indexer app (similar to the cosmos types)
var indexerMergedTx txtypes.MergedTx
var indexerTx txtypes.IndexerTx
var txBody txtypes.Body
var currMessages []types.Msg
var currLogMsgs []txtypes.LogMessage
currTx := txEventResp.Txs[txIdx]
currTxResp := txEventResp.TxResponses[txIdx]
if len(currTxResp.Logs) == 0 && len(currTxResp.Events) != 0 {
parsedLogs, err := indexerEvents.ParseTxEventsToMessageIndexEvents(len(currTx.Body.Messages), currTxResp.Events)
if err != nil {
config.Log.Errorf("Error parsing events to message index events to normalize: %v", err)
return nil, blockTime, err
}
currTxResp.Logs = parsedLogs
}
// Get the Messages and Message Logs
for msgIdx := range currTx.Body.Messages {
currMsg := currTx.Body.Messages[msgIdx].GetCachedValue()
if currMsg != nil {
msg := currMsg.(types.Msg)
currMessages = append(currMessages, msg)
if len(currTxResp.Logs) >= msgIdx+1 {
msgEvents := currTxResp.Logs[msgIdx].Events
currTxLog := txtypes.LogMessage{
MessageIndex: msgIdx,
Events: toEvents(msgEvents),
}
currLogMsgs = append(currLogMsgs, currTxLog)
}
} else {
return nil, blockTime, fmt.Errorf("tx message could not be processed. CachedValue is not present. TX Hash: %s, Msg type: %s, Msg index: %d, Code: %d",
currTxResp.TxHash,
currTx.Body.Messages[msgIdx].TypeUrl,
msgIdx,
currTxResp.Code,
)
}
}
txBody.Messages = currMessages
indexerTx.Body = txBody
indexerTxResp := txtypes.Response{
TxHash: currTxResp.TxHash,
Height: fmt.Sprintf("%d", currTxResp.Height),
TimeStamp: currTxResp.Timestamp,
RawLog: currTxResp.RawLog,
Log: currLogMsgs,
Code: currTxResp.Code,
}
indexerTx.AuthInfo = *currTx.AuthInfo
txSigners, _, err := currTx.GetSigners(cl.Codec.Marshaler)
if err != nil {
return nil, blockTime, fmt.Errorf("error getting signers: %v", err)
}
for _, signer := range txSigners {
indexerTx.Signers = append(indexerTx.Signers, signer)
}
indexerMergedTx.TxResponse = indexerTxResp
indexerMergedTx.Tx = indexerTx
indexerMergedTx.Tx.AuthInfo = *currTx.AuthInfo
processedTx, txTime, err := ProcessTx(cl, db, indexerMergedTx)
if err != nil {
return currTxDbWrappers, blockTime, err
}
if blockTime == nil {
blockTime = &txTime
}
if len(indexerTx.Signers) > 0 {
processedTx.SignerAddress = dbTypes.Address{Address: indexerTx.Signers[0].String()}
} else {
return currTxDbWrappers, blockTime, fmt.Errorf("tx signers could not be processed, no signers found")
}
currTxDbWrappers[txIdx] = processedTx
}
return currTxDbWrappers, blockTime, nil
}
var allSwaps = []gamm.ArbitrageTx{}
func AnalyzeSwaps() {
earliestTime := time.Now()
latestTime := time.Now()
profit := 0.0
fmt.Printf("%d total uosmo arbitrage swaps\n", len(allSwaps))
for _, swap := range allSwaps {
if swap.TokenOut.Denom == "uosmo" && swap.TokenIn.Denom == "uosmo" {
amount := swap.TokenOut.Amount.Sub(swap.TokenIn.Amount)
if amount.GT(sdkMath.ZeroInt()) {
txProfit := amount.ToLegacyDec().Quo(sdkMath.LegacyNewDec(1000000)).MustFloat64()
profit += txProfit
}
if swap.BlockTime.Before(earliestTime) {
earliestTime = swap.BlockTime
}
if swap.BlockTime.After(latestTime) {
latestTime = swap.BlockTime
}
}
}
fmt.Printf("Profit (OSMO): %.10f, days: %f\n", profit, latestTime.Sub(earliestTime).Hours()/24)
}
func ProcessTx(cl *client.ChainClient, db *gorm.DB, tx txtypes.MergedTx) (txDBWapper dbTypes.TxDBWrapper, txTime time.Time, err error) {
txTime, err = time.Parse(time.RFC3339, tx.TxResponse.TimeStamp)
if err != nil {
config.Log.Error("Error parsing tx timestamp.", err)
return txDBWapper, txTime, err
}
code := tx.TxResponse.Code
var messages []dbTypes.MessageDBWrapper
// non-zero code means the Tx was unsuccessful. We will still need to account for fees in both cases though.
if code == 0 {
for messageIndex, message := range tx.Tx.Body.Messages {
var currMessage dbTypes.Message
var currMessageType dbTypes.MessageType
currMessage.MessageIndex = messageIndex
// Get the message log that corresponds to the current message
var currMessageDBWrapper dbTypes.MessageDBWrapper
messageLog := txtypes.GetMessageLogForIndex(tx.TxResponse.Log, messageIndex)
cosmosMessage, msgType, err := ParseCosmosMessage(message, *messageLog)
if err != nil {
currMessageType.MessageType = msgType
currMessage.MessageType = currMessageType
currMessageDBWrapper.Message = currMessage
if err != txtypes.ErrUnknownMessage {
// What should we do here? This is an actual error during parsing
config.Log.Error(fmt.Sprintf("[Block: %v] ParseCosmosMessage failed for msg of type '%v'.", tx.TxResponse.Height, msgType), err)
config.Log.Error(fmt.Sprint(messageLog))
config.Log.Error(tx.TxResponse.TxHash)
config.Log.Error("Issue parsing a cosmos msg that we DO have a parser for! PLEASE INVESTIGATE")
return txDBWapper, txTime, fmt.Errorf("error parsing message we have a parser for: '%v'", msgType)
}
// if this msg isn't include in our list of those we are explicitly ignoring, do something about it.
// we have decided to throw the error back up the call stack, which will prevent any indexing from happening on this block and add this to the failed block table
if _, ok := messageTypeIgnorer[msgType]; !ok {
config.Log.Error(fmt.Sprintf("[Block: %v] ParseCosmosMessage failed for msg of type '%v'. Missing parser and ignore list entry.", tx.TxResponse.Height, msgType))
return txDBWapper, txTime, fmt.Errorf("missing parser and ignore list entry for msg type '%v'", msgType)
}
} else {
config.Log.Debug(fmt.Sprintf("[Block: %v] Cosmos message of known type: %s", tx.TxResponse.Height, cosmosMessage))
currMessageType.MessageType = cosmosMessage.GetType()
currMessage.MessageType = currMessageType
currMessageDBWrapper.Message = currMessage
relevantData := cosmosMessage.ParseRelevantData()
if len(relevantData) > 0 {
taxableTxs := make([]dbTypes.TaxableTxDBWrapper, len(relevantData))
for i, v := range relevantData {
if v.AmountSent != nil {
taxableTxs[i].TaxableTx.AmountSent = util.ToNumeric(v.AmountSent)
}
if v.AmountReceived != nil {
taxableTxs[i].TaxableTx.AmountReceived = util.ToNumeric(v.AmountReceived)
}
if v.DenominationSent != "" {
denomSent, err := getDenom(v.DenominationSent)
if err != nil {
// attempt to add missing denoms to the database
config.Log.Warnf("Denom lookup failed. Will be inserted as UNKNOWN. Denom Sent: %v. Err: %v", denomSent.Base, err)
denomSent, err = dbTypes.AddUnknownDenom(db, denomSent.Base)
if err != nil {
config.Log.Error(fmt.Sprintf("There was an error adding a missing denom. Denom sent: %v", denomSent.Base), err)
return txDBWapper, txTime, err
}
}
taxableTxs[i].TaxableTx.DenominationSent = denomSent
}
if v.DenominationReceived != "" {
denomReceived, err := getDenom(v.DenominationReceived)
if err != nil {
// attempt to add missing denoms to the database
config.Log.Warnf("Denom lookup failed. Will be inserted as UNKNOWN. Denom Received: %v. Err: %v", denomReceived.Base, err)
denomReceived, err = dbTypes.AddUnknownDenom(db, denomReceived.Base)
if err != nil {
config.Log.Error(fmt.Sprintf("There was an error adding a missing denom. Denom received: %v", denomReceived.Base), err)
return txDBWapper, txTime, err
}
}
taxableTxs[i].TaxableTx.DenominationReceived = denomReceived
}
taxableTxs[i].SenderAddress = dbTypes.Address{Address: strings.ToLower(v.SenderAddress)}
taxableTxs[i].ReceiverAddress = dbTypes.Address{Address: strings.ToLower(v.ReceiverAddress)}
}
currMessageDBWrapper.TaxableTxs = taxableTxs
} else {
currMessageDBWrapper.TaxableTxs = []dbTypes.TaxableTxDBWrapper{}
}
}
if msgSwapExactIn, ok := cosmosMessage.(*gamm.WrapperMsgSwapExactAmountIn); ok {
newSwap := gamm.ArbitrageTx{TokenIn: msgSwapExactIn.TokenIn, TokenOut: msgSwapExactIn.TokenOut, BlockTime: txTime}
allSwaps = append(allSwaps, newSwap)
}
messages = append(messages, currMessageDBWrapper)
}
}
fees, err := ProcessFees(cl, db, tx.Tx.AuthInfo, tx.Tx.Signers)
if err != nil {
return txDBWapper, txTime, err
}
txDBWapper.Tx = dbTypes.Tx{Hash: tx.TxResponse.TxHash, Fees: fees, Code: code}
txDBWapper.Messages = messages
return txDBWapper, txTime, nil
}
// ProcessFees returns a comma delimited list of fee amount/denoms
func ProcessFees(cl *client.ChainClient, db *gorm.DB, authInfo cosmosTx.AuthInfo, signers []types.AccAddress) ([]dbTypes.Fee, error) {
feeCoins := authInfo.Fee.Amount
payer := authInfo.Fee.GetPayer()
fees := []dbTypes.Fee{}
for _, coin := range feeCoins {
zeroFee := big.NewInt(0)
// There are chains like Osmosis that do not require TX fees for certain TXs
if zeroFee.Cmp(coin.Amount.BigInt()) != 0 {
amount := util.ToNumeric(coin.Amount.BigInt())
denom, err := dbTypes.GetDenomForBase(coin.Denom)
if err != nil {
// attempt to add missing denoms to the database
config.Log.Warnf("Denom lookup failed. Will be inserted as UNKNOWN. Denom Received: %v. Err: %v", coin.Denom, err)
denom, err = dbTypes.AddUnknownDenom(db, coin.Denom)
if err != nil {
config.Log.Error(fmt.Sprintf("There was an error adding a missing denom. Denom: %v", coin.Denom), err)
return nil, err
}
}
payerAddr := dbTypes.Address{}
if payer != "" {
payerAddr.Address = payer
} else {
if authInfo.SignerInfos[0].PublicKey == nil && len(signers) > 0 {
payerAddr.Address = signers[0].String()
} else {
var pubKey cryptoTypes.PubKey
pubKeyType, err := cl.Codec.InterfaceRegistry.Resolve(authInfo.SignerInfos[0].PublicKey.TypeUrl)
if err != nil {
return nil, err
}
err = cl.Codec.InterfaceRegistry.UnpackAny(authInfo.SignerInfos[0].PublicKey, &pubKeyType)
if err != nil {
return nil, err
}
multisigKey, ok := pubKeyType.(*multisig.LegacyAminoPubKey)
if ok {
pubKey = multisigKey.GetPubKeys()[0]
} else {
pubKey = pubKeyType.(cryptoTypes.PubKey)
}
hexPub := hex.EncodeToString(pubKey.Bytes())
bechAddr, err := ParseSignerAddress(hexPub, "")
if err != nil {
config.Log.Error(fmt.Sprintf("Error parsing signer address '%v' for tx.", hexPub), err)
} else {
payerAddr.Address = bechAddr
}
}
}
fees = append(fees, dbTypes.Fee{Amount: amount, Denomination: denom, PayerAddress: payerAddr})
}
}
return fees, nil
}
// getDenom handles denom processing for both IBC denoms and native denoms.
// If the denom begins with ibc/ we know this is an IBC denom trace, and it's not guaranteed there is an entry in
// the Denom table.
func getDenom(denom string) (dbTypes.Denom, error) {
var (
denomSent dbTypes.Denom
err error
)
// if this is an ibc denom trace, get the ibc denom then use the base denom to get the Denom from the db
if strings.HasPrefix(denom, "ibc/") {
ibcDenom, err := dbTypes.GetIBCDenom(denom)
if err != nil {
config.Log.Warnf("IBC Denom lookup failed for %s, err: %v", denom, err)
} else {
denomSent, err = dbTypes.GetDenomForBase(ibcDenom.BaseDenom)
if err != nil {
config.Log.Warnf("Denom lookup failed for IBC base denom %s, err: %v", ibcDenom.BaseDenom, err)
return dbTypes.Denom{Base: ibcDenom.BaseDenom}, err
}
}
}
// if this is not an ibc denom trace or there was an issue querying the ibc denom trace in the other table,
// attempt to look up this denom in the regular Denom table
if denomSent.Base == "" {
denomSent, err = dbTypes.GetDenomForBase(denom)
if err != nil {
return dbTypes.Denom{Base: denom}, err
}
}
return denomSent, nil
}