-
Notifications
You must be signed in to change notification settings - Fork 21
/
engine.go
704 lines (613 loc) · 22.8 KB
/
engine.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
// Copyright (C) 2023 Gobalsky Labs Limited
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package banking
import (
"context"
"errors"
"fmt"
"math/big"
"slices"
"sort"
"strings"
"sync/atomic"
"time"
"code.vegaprotocol.io/vega/core/assets"
"code.vegaprotocol.io/vega/core/broker"
"code.vegaprotocol.io/vega/core/events"
"code.vegaprotocol.io/vega/core/types"
"code.vegaprotocol.io/vega/core/validators"
"code.vegaprotocol.io/vega/libs/num"
"code.vegaprotocol.io/vega/logging"
"code.vegaprotocol.io/vega/protos/vega"
proto "code.vegaprotocol.io/vega/protos/vega"
"github.com/emirpasic/gods/sets/treeset"
"golang.org/x/exp/maps"
)
//go:generate go run github.com/golang/mock/mockgen -destination mocks/mocks.go -package mocks code.vegaprotocol.io/vega/core/banking Assets,Notary,Collateral,Witness,TimeService,EpochService,Topology,MarketActivityTracker,ERC20BridgeView,EthereumEventSource,Parties
var (
ErrWrongAssetTypeUsedInBuiltinAssetChainEvent = errors.New("non builtin asset used for builtin asset chain event")
ErrWrongAssetTypeUsedInERC20ChainEvent = errors.New("non ERC20 for ERC20 chain event")
ErrWrongAssetUsedForERC20Withdraw = errors.New("non erc20 asset used for lock withdraw")
ErrInvalidWithdrawalState = errors.New("invalid withdrawal state")
ErrNotMatchingWithdrawalForReference = errors.New("invalid reference for withdrawal chain event")
ErrWithdrawalNotReady = errors.New("withdrawal not ready")
ErrNotEnoughFundsToTransfer = errors.New("not enough funds to transfer")
)
type Assets interface {
Get(assetID string) (*assets.Asset, error)
Enable(ctx context.Context, assetID string) error
ApplyAssetUpdate(ctx context.Context, assetID string) error
}
// Notary ...
type Notary interface {
StartAggregate(resID string, kind types.NodeSignatureKind, signature []byte)
IsSigned(ctx context.Context, id string, kind types.NodeSignatureKind) ([]types.NodeSignature, bool)
OfferSignatures(kind types.NodeSignatureKind, f func(resources string) []byte)
}
// Collateral engine.
type Collateral interface {
Deposit(ctx context.Context, party, asset string, amount *num.Uint) (*types.LedgerMovement, error)
Withdraw(ctx context.Context, party, asset string, amount *num.Uint) (*types.LedgerMovement, error)
EnableAsset(ctx context.Context, asset types.Asset) error
GetPartyGeneralAccount(party, asset string) (*types.Account, error)
GetPartyVestedRewardAccount(partyID, asset string) (*types.Account, error)
TransferFunds(ctx context.Context,
transfers []*types.Transfer,
accountTypes []types.AccountType,
references []string,
feeTransfers []*types.Transfer,
feeTransfersAccountTypes []types.AccountType,
) ([]*types.LedgerMovement, error)
GovernanceTransferFunds(ctx context.Context, transfers []*types.Transfer, accountTypes []types.AccountType, references []string) ([]*types.LedgerMovement, error)
PropagateAssetUpdate(ctx context.Context, asset types.Asset) error
GetSystemAccountBalance(asset, market string, accountType types.AccountType) (*num.Uint, error)
}
// Witness provide foreign chain resources validations.
type Witness interface {
StartCheck(validators.Resource, func(interface{}, bool), time.Time) error
RestoreResource(validators.Resource, func(interface{}, bool)) error
}
// TimeService provide the time of the vega node using the tm time.
type TimeService interface {
GetTimeNow() time.Time
}
// Epochervice ...
type EpochService interface {
NotifyOnEpoch(f func(context.Context, types.Epoch), r func(context.Context, types.Epoch))
}
// Topology ...
type Topology interface {
IsValidator() bool
}
type MarketActivityTracker interface {
CalculateMetricForIndividuals(ctx context.Context, ds *vega.DispatchStrategy) []*types.PartyContributionScore
CalculateMetricForTeams(ctx context.Context, ds *vega.DispatchStrategy) ([]*types.PartyContributionScore, map[string][]*types.PartyContributionScore)
GetMarketsWithEligibleProposer(asset string, markets []string, payoutAsset string, funder string) []*types.MarketContributionScore
MarkPaidProposer(asset, market, payoutAsset string, marketsInScope []string, funder string)
MarketTrackedForAsset(market, asset string) bool
TeamStatsForMarkets(allMarketsForAssets, onlyTheseMarkets []string) map[string]map[string]*num.Uint
PublishGameMetric(ctx context.Context, dispatchStrategy []*vega.DispatchStrategy, now time.Time)
}
type EthereumEventSource interface {
UpdateContractBlock(string, string, uint64)
}
type Parties interface {
CheckDerivedKeyOwnership(party types.PartyID, derivedKey string) bool
}
const (
pendingState uint32 = iota
okState
rejectedState
)
var defaultValidationDuration = 30 * 24 * time.Hour
type dispatchStrategyCacheEntry struct {
ds *proto.DispatchStrategy
refCount int
}
type Engine struct {
cfg Config
log *logging.Logger
timeService TimeService
broker broker.Interface
col Collateral
witness Witness
notary Notary
assets Assets
top Topology
parties Parties
// assetActions tracks all the asset actions the engine must process on network
// tick.
assetActions map[string]*assetAction
// seenAssetActions keeps track of all asset action the node has seen.
seenAssetActions *treeset.Set
// primaryEthChainID stores the Ethereum Mainnet chain ID. It is used during the
// chain event deduplication phase, to ensure we correctly deduplicate
// chain events that have been seen before the introduce of the second bridge.
primaryEthChainID string
// lastSeenPrimaryEthBlock holds the block height of the latest ERC20 chain
// event, from the primary chain, processed by the engine.
lastSeenPrimaryEthBlock uint64
primaryBridgeState *bridgeState
primaryBridgeView ERC20BridgeView
// lastSeenSecondaryEthBlock holds the block height of the latest ERC20 chain
// event, from the secondary chain, processed by the engine.
lastSeenSecondaryEthBlock uint64
secondaryEthChainID string
secondaryBridgeState *bridgeState
secondaryBridgeView ERC20BridgeView
// map from chain-id -> collateral contract address
bridgeAddresses map[string]string
ethEventSource EthereumEventSource
withdrawals map[string]withdrawalRef
withdrawalCnt *big.Int
deposits map[string]*types.Deposit
currentEpoch uint64
bss *bankingSnapshotState
marketActivityTracker MarketActivityTracker
// transfer fee related stuff
scheduledTransfers map[int64][]scheduledTransfer
transferFeeFactor num.Decimal
minTransferQuantumMultiple num.Decimal
maxQuantumAmount num.Decimal
feeDiscountDecayFraction num.Decimal
feeDiscountMinimumTrackedAmount num.Decimal
// assetID -> partyID -> fee discount
pendingPerAssetAndPartyFeeDiscountUpdates map[string]map[string]*num.Uint
feeDiscountPerPartyAndAsset map[partyAssetKey]*num.Uint
scheduledGovernanceTransfers map[int64][]*types.GovernanceTransfer
recurringGovernanceTransfers []*types.GovernanceTransfer
recurringGovernanceTransfersMap map[string]*types.GovernanceTransfer
// a hash of a dispatch strategy to the dispatch strategy details
hashToStrategy map[string]*dispatchStrategyCacheEntry
// recurring transfers in the order they were created
recurringTransfers []*types.RecurringTransfer
// transfer id to recurringTransfers
recurringTransfersMap map[string]*types.RecurringTransfer
minWithdrawQuantumMultiple num.Decimal
maxGovTransferQunatumMultiplier num.Decimal
maxGovTransferFraction num.Decimal
metricUpdateFrequency time.Duration
nextMetricUpdate time.Time
// transient cache used to market a dispatch strategy as checked for eligibility for this round so we don't check again.
dispatchRequiredCache map[string]bool
}
type withdrawalRef struct {
w *types.Withdrawal
ref *big.Int
}
func New(log *logging.Logger,
cfg Config,
col Collateral,
witness Witness,
tsvc TimeService,
assets Assets,
notary Notary,
broker broker.Interface,
top Topology,
marketActivityTracker MarketActivityTracker,
primaryBridgeView ERC20BridgeView,
secondaryBridgeView ERC20BridgeView,
ethEventSource EthereumEventSource,
parties Parties,
) (e *Engine) {
log = log.Named(namedLogger)
log.SetLevel(cfg.Level.Get())
return &Engine{
cfg: cfg,
log: log,
timeService: tsvc,
broker: broker,
col: col,
witness: witness,
assets: assets,
notary: notary,
top: top,
ethEventSource: ethEventSource,
parties: parties,
assetActions: map[string]*assetAction{},
seenAssetActions: treeset.NewWithStringComparator(),
withdrawals: map[string]withdrawalRef{},
deposits: map[string]*types.Deposit{},
withdrawalCnt: big.NewInt(0),
bss: &bankingSnapshotState{},
scheduledTransfers: map[int64][]scheduledTransfer{},
recurringTransfers: []*types.RecurringTransfer{},
recurringTransfersMap: map[string]*types.RecurringTransfer{},
scheduledGovernanceTransfers: map[int64][]*types.GovernanceTransfer{},
recurringGovernanceTransfers: []*types.GovernanceTransfer{},
recurringGovernanceTransfersMap: map[string]*types.GovernanceTransfer{},
transferFeeFactor: num.DecimalZero(),
minTransferQuantumMultiple: num.DecimalZero(),
minWithdrawQuantumMultiple: num.DecimalZero(),
marketActivityTracker: marketActivityTracker,
nextMetricUpdate: time.Time{},
hashToStrategy: map[string]*dispatchStrategyCacheEntry{},
primaryBridgeState: &bridgeState{
active: true,
},
secondaryBridgeState: &bridgeState{
active: true,
},
bridgeAddresses: map[string]string{},
feeDiscountPerPartyAndAsset: map[partyAssetKey]*num.Uint{},
pendingPerAssetAndPartyFeeDiscountUpdates: map[string]map[string]*num.Uint{},
primaryBridgeView: primaryBridgeView,
secondaryBridgeView: secondaryBridgeView,
dispatchRequiredCache: map[string]bool{},
}
}
func (e *Engine) OnMaxFractionChanged(ctx context.Context, f num.Decimal) error {
e.maxGovTransferFraction = f
return nil
}
func (e *Engine) OnMaxAmountChanged(ctx context.Context, f num.Decimal) error {
e.maxGovTransferQunatumMultiplier = f
return nil
}
func (e *Engine) OnMinWithdrawQuantumMultiple(ctx context.Context, f num.Decimal) error {
e.minWithdrawQuantumMultiple = f
return nil
}
func (e *Engine) OnPrimaryEthChainIDUpdated(chainID, collateralAddress string) {
e.primaryEthChainID = chainID
e.bridgeAddresses[chainID] = collateralAddress
}
func (e *Engine) OnSecondaryEthChainIDUpdated(chainID, collateralAddress string) {
e.secondaryEthChainID = chainID
e.bridgeAddresses[chainID] = collateralAddress
}
// ReloadConf updates the internal configuration.
func (e *Engine) ReloadConf(cfg Config) {
e.log.Info("reloading configuration")
if e.log.GetLevel() != cfg.Level.Get() {
e.log.Info("updating log level",
logging.String("old", e.log.GetLevel().String()),
logging.String("new", cfg.Level.String()),
)
e.log.SetLevel(cfg.Level.Get())
}
e.cfg = cfg
}
func (e *Engine) OnBlockEnd(ctx context.Context, now time.Time) {
if !now.Before(e.nextMetricUpdate) {
e.publishMetricData(ctx, now)
e.nextMetricUpdate = now.Add(e.metricUpdateFrequency)
}
}
// publishMetricData requests the market activity tracker to publish and event
// for each game with the current metric data for each party.
func (e *Engine) publishMetricData(ctx context.Context, now time.Time) {
hashes := make([]string, 0, len(e.hashToStrategy))
for hash := range e.hashToStrategy {
hashes = append(hashes, hash)
}
sort.Strings(hashes)
dss := make([]*vega.DispatchStrategy, 0, len(hashes))
for _, hash := range hashes {
dss = append(dss, e.hashToStrategy[hash].ds)
}
e.marketActivityTracker.PublishGameMetric(ctx, dss, now)
}
func (e *Engine) OnEpoch(ctx context.Context, ep types.Epoch) {
switch ep.Action {
case proto.EpochAction_EPOCH_ACTION_START:
e.currentEpoch = ep.Seq
e.cleanupStaleDispatchStrategies()
case proto.EpochAction_EPOCH_ACTION_END:
e.distributeRecurringTransfers(ctx, e.currentEpoch)
e.distributeRecurringGovernanceTransfers(ctx)
e.applyPendingFeeDiscountsUpdates(ctx)
e.sendTeamsStats(ctx, ep.Seq)
e.dispatchRequiredCache = map[string]bool{}
// as the metrics are going to be published here, we want to progress the next update.
e.nextMetricUpdate = e.timeService.GetTimeNow().Add(e.metricUpdateFrequency)
default:
e.log.Panic("epoch action should never be UNSPECIFIED", logging.String("epoch", ep.String()))
}
}
func (e *Engine) OnTick(ctx context.Context, now time.Time) {
e.processAssetActions(ctx, now)
e.notary.OfferSignatures(types.NodeSignatureKindAssetWithdrawal, e.offerERC20NotarySignatures)
// then process all scheduledTransfers
if err := e.distributeScheduledTransfers(ctx, now); err != nil {
e.log.Error("could not process scheduled transfers",
logging.Error(err),
)
}
// process governance transfers
e.distributeScheduledGovernanceTransfers(ctx, now)
}
func (e *Engine) processAssetActions(ctx context.Context, now time.Time) {
sortedAssetActionKeys := maps.Keys(e.assetActions)
sort.Strings(sortedAssetActionKeys)
for _, key := range sortedAssetActionKeys {
action := e.assetActions[key]
switch action.state.Load() {
case pendingState:
// The verification of the action has not been completed yet, so
// we skip it until it is.
continue
case okState:
if err := e.deduplicateAssetAction(ctx, action); err != nil {
e.log.Warn("an error occurred during asset action deduplication",
logging.Error(err),
logging.String("action", action.String()),
logging.String("tx-hash", action.txHash),
logging.String("chain-id", action.chainID))
break
}
if err := e.finalizeAction(ctx, action, now); err != nil {
e.log.Error("unable to finalize action",
logging.String("action", action.String()),
logging.Error(err))
}
case rejectedState:
e.log.Error("network rejected banking action",
logging.String("action", action.String()))
}
delete(e.assetActions, key)
}
}
func (e *Engine) onCheckDone(i interface{}, valid bool) {
aa, ok := i.(*assetAction)
if !ok {
return
}
newState := rejectedState
if valid {
newState = okState
}
aa.state.Store(newState)
}
func (e *Engine) getWithdrawalFromRef(ref *big.Int) (*types.Withdrawal, error) {
// sort withdraws to check deterministically
withdrawalsK := make([]string, 0, len(e.withdrawals))
for k := range e.withdrawals {
withdrawalsK = append(withdrawalsK, k)
}
sort.Strings(withdrawalsK)
for _, k := range withdrawalsK {
v := e.withdrawals[k]
if v.ref.Cmp(ref) == 0 {
return v.w, nil
}
}
return nil, ErrNotMatchingWithdrawalForReference
}
func (e *Engine) dedupAction(ctx context.Context, aa *assetAction) error {
switch {
case aa.IsBuiltinAssetDeposit():
dep := e.deposits[aa.id]
return e.dedupDeposit(ctx, dep)
case aa.IsERC20Deposit():
dep := e.deposits[aa.id]
return e.dedupDeposit(ctx, dep)
}
// the bridge stop/resume actions don't send events, and the asset listing/updates share the same
// underlying asset ID, so they don't result in duplicates. Only deposits need to be handled.
e.log.Warn("unable to deduplicate asset action",
logging.String("action", aa.String()))
return nil
}
func (e *Engine) finalizeAction(ctx context.Context, aa *assetAction, now time.Time) error {
// tell the evt forwarder tracker about this block height
if addr, ok := e.bridgeAddresses[aa.chainID]; ok {
e.ethEventSource.UpdateContractBlock(addr, aa.chainID, aa.blockHeight)
}
switch {
case aa.IsBuiltinAssetDeposit():
dep := e.deposits[aa.id]
return e.finalizeDeposit(ctx, dep, now)
case aa.IsERC20Deposit():
dep := e.deposits[aa.id]
return e.finalizeDeposit(ctx, dep, now)
case aa.IsERC20AssetList():
return e.finalizeAssetList(ctx, aa.erc20AL.VegaAssetID)
case aa.IsERC20AssetLimitsUpdated():
return e.finalizeAssetLimitsUpdated(ctx, aa.erc20AssetLimitsUpdated.VegaAssetID)
case aa.IsERC20BridgeStopped():
b, err := e.bridgeStateForChainID(aa.chainID)
if err != nil {
return err
}
b.NewBridgeStopped(aa.blockHeight, aa.logIndex)
return nil
case aa.IsERC20BridgeResumed():
b, err := e.bridgeStateForChainID(aa.chainID)
if err != nil {
return err
}
b.NewBridgeResumed(aa.blockHeight, aa.logIndex)
return nil
default:
return ErrUnknownAssetAction
}
}
func (e *Engine) finalizeAssetList(ctx context.Context, assetID string) error {
asset, err := e.assets.Get(assetID)
if err != nil {
e.log.Error("invalid asset id used to finalise asset list",
logging.Error(err),
logging.AssetID(assetID))
return nil
}
if err := e.assets.Enable(ctx, assetID); err != nil {
e.log.Error("unable to enable asset",
logging.Error(err),
logging.AssetID(assetID))
return err
}
return e.col.EnableAsset(ctx, *asset.ToAssetType())
}
func (e *Engine) finalizeAssetLimitsUpdated(ctx context.Context, assetID string) error {
asset, err := e.assets.Get(assetID)
if err != nil {
e.log.Error("invalid asset id used to finalise asset list",
logging.Error(err),
logging.AssetID(assetID))
return nil
}
if err := e.assets.ApplyAssetUpdate(ctx, assetID); err != nil {
e.log.Error("couldn't apply asset update",
logging.Error(err),
logging.AssetID(assetID))
return err
}
return e.col.PropagateAssetUpdate(ctx, *asset.ToAssetType())
}
func (e *Engine) finalizeDeposit(ctx context.Context, d *types.Deposit, now time.Time) error {
defer func() {
e.broker.Send(events.NewDepositEvent(ctx, *d))
// whatever happens, the deposit is in its final state (cancelled or finalized)
delete(e.deposits, d.ID)
}()
res, err := e.col.Deposit(ctx, d.PartyID, d.Asset, d.Amount)
if err != nil {
d.Status = types.DepositStatusCancelled
return err
}
d.Status = types.DepositStatusFinalized
d.CreditDate = now.UnixNano()
e.broker.Send(events.NewLedgerMovements(ctx, []*types.LedgerMovement{res}))
return nil
}
func (e *Engine) dedupDeposit(ctx context.Context, d *types.Deposit) error {
d.Status = types.DepositStatusDuplicateRejected
e.broker.Send(events.NewDepositEvent(ctx, *d))
return nil
}
func (e *Engine) finalizeWithdraw(ctx context.Context, w *types.Withdrawal) error {
// always send the withdrawal event, don't delete it from the map because we
// may still receive events
defer func() {
e.broker.Send(events.NewWithdrawalEvent(ctx, *w))
}()
res, err := e.col.Withdraw(ctx, w.PartyID, w.Asset, w.Amount.Clone())
if err != nil {
w.Status = types.WithdrawalStatusRejected
return err
}
w.Status = types.WithdrawalStatusFinalized
e.broker.Send(events.NewLedgerMovements(ctx, []*types.LedgerMovement{res}))
return nil
}
func (e *Engine) newWithdrawal(
id, partyID, asset string,
amount *num.Uint,
wext *types.WithdrawExt,
) (w *types.Withdrawal, ref *big.Int) {
partyID = strings.TrimPrefix(partyID, "0x")
asset = strings.TrimPrefix(asset, "0x")
now := e.timeService.GetTimeNow()
// reference needs to be an int, deterministic for the contracts
ref = big.NewInt(0).Add(e.withdrawalCnt, big.NewInt(now.Unix()))
e.withdrawalCnt.Add(e.withdrawalCnt, big.NewInt(1))
w = &types.Withdrawal{
ID: id,
Status: types.WithdrawalStatusOpen,
PartyID: partyID,
Asset: asset,
Amount: amount,
Ext: wext,
CreationDate: now.UnixNano(),
Ref: ref.String(),
}
return
}
func (e *Engine) newDeposit(
id, partyID, asset string,
amount *num.Uint,
txHash string,
) *types.Deposit {
partyID = strings.TrimPrefix(partyID, "0x")
asset = strings.TrimPrefix(asset, "0x")
return &types.Deposit{
ID: id,
Status: types.DepositStatusOpen,
PartyID: partyID,
Asset: asset,
Amount: amount,
CreationDate: e.timeService.GetTimeNow().UnixNano(),
TxHash: txHash,
}
}
func (e *Engine) GetDispatchStrategy(hash string) *proto.DispatchStrategy {
ds, ok := e.hashToStrategy[hash]
if !ok {
e.log.Warn("could not find dispatch strategy in banking engine", logging.String("hash", hash))
return nil
}
if ds.refCount == 0 {
return nil
}
return ds.ds
}
// sendTeamsStats sends the teams statistics, which only account for games.
// This is located here not because this is where it should be, but because
// we don't know where to put it, as we need to have access to the dispatch
// strategy.
func (e *Engine) sendTeamsStats(ctx context.Context, seq uint64) {
onlyTheseMarkets := map[string]interface{}{}
allMarketsForAssets := map[string]interface{}{}
for _, ds := range e.hashToStrategy {
if ds.ds.EntityScope == proto.EntityScope_ENTITY_SCOPE_TEAMS {
if len(ds.ds.Markets) != 0 {
// If there is no markets specified, then we need gather data from
// all markets tied to this asset.
allMarketsForAssets[ds.ds.AssetForMetric] = nil
} else {
for _, market := range ds.ds.Markets {
onlyTheseMarkets[market] = nil
}
}
}
}
if len(allMarketsForAssets) == 0 && len(onlyTheseMarkets) == 0 {
return
}
allMarketsForAssetsS := maps.Keys(allMarketsForAssets)
slices.Sort(allMarketsForAssetsS)
onlyTheseMarketsS := maps.Keys(onlyTheseMarkets)
slices.Sort(onlyTheseMarketsS)
teamsStats := e.marketActivityTracker.TeamStatsForMarkets(allMarketsForAssetsS, onlyTheseMarketsS)
if len(teamsStats) > 0 {
e.broker.Send(events.NewTeamsStatsUpdatedEvent(ctx, seq, teamsStats))
}
}
func (e *Engine) bridgeViewForChainID(chainID string) (ERC20BridgeView, error) {
switch chainID {
case e.primaryEthChainID:
return e.primaryBridgeView, nil
case e.secondaryEthChainID:
return e.secondaryBridgeView, nil
default:
return nil, fmt.Errorf("chain id %q is not supported", chainID)
}
}
func (e *Engine) bridgeStateForChainID(chainID string) (*bridgeState, error) {
switch chainID {
case e.primaryEthChainID:
return e.primaryBridgeState, nil
case e.secondaryEthChainID:
return e.secondaryBridgeState, nil
default:
return nil, fmt.Errorf("chain id %q is not supported", chainID)
}
}
func newPendingState() *atomic.Uint32 {
state := &atomic.Uint32{}
state.Store(pendingState)
return state
}