How to use Swap method of watch Package

Best Ginkgo code snippet using watch.Swap

listener.go

Source:listener.go Github

copy

Full Screen

...15 Repay *repay16 ReserveUpdate *reserveUpdate17 CollateralDisabled *collateralDisabled18 CollateralEnabled *collateralEnabled19 Swap *swap20 Withdraw *withdraw21}22func NewListener() *Listener {23 return &Listener{24 Borrow: &borrow{Incoming: make(chan *contracts.LendingPoolBorrow)},25 Deposit: &deposit{Incoming: make(chan *contracts.LendingPoolDeposit)},26 FlashLoan: &flashLoan{Incoming: make(chan *contracts.LendingPoolFlashLoan)},27 Liquidation: &liquidation{Incoming: make(chan *contracts.LendingPoolLiquidationCall)},28 Rebalance: &rebalance{Incoming: make(chan *contracts.LendingPoolRebalanceStableBorrowRate)},29 Repay: &repay{Incoming: make(chan *contracts.LendingPoolRepay)},30 ReserveUpdate: &reserveUpdate{Incoming: make(chan *contracts.LendingPoolReserveDataUpdated)},31 CollateralDisabled: &collateralDisabled{Incoming: make(chan *contracts.LendingPoolReserveUsedAsCollateralDisabled)},32 CollateralEnabled: &collateralEnabled{Incoming: make(chan *contracts.LendingPoolReserveUsedAsCollateralEnabled)},33 Swap: &swap{Incoming: make(chan *contracts.LendingPoolSwap)},34 Withdraw: &withdraw{Incoming: make(chan *contracts.LendingPoolWithdraw)},35 }36}37func (l *Listener) initiateSubscriptions(cli *ethclient.Client, lendingPool *contracts.LendingPool) error {38 var err error39 // Subscribe to lending pool events.40 if l.Borrow.Sub, err = lendingPool.WatchBorrow(nil, l.Borrow.Incoming, nil, nil, nil); err != nil {41 return err42 }43 if l.Deposit.Sub, err = lendingPool.WatchDeposit(nil, l.Deposit.Incoming, nil, nil, nil); err != nil {44 return err45 }46 if l.FlashLoan.Sub, err = lendingPool.WatchFlashLoan(nil, l.FlashLoan.Incoming, nil, nil, nil); err != nil {47 return err48 }49 if l.Liquidation.Sub, err = lendingPool.WatchLiquidationCall(nil, l.Liquidation.Incoming, nil, nil, nil); err != nil {50 return err51 }52 if l.Rebalance.Sub, err = lendingPool.WatchRebalanceStableBorrowRate(nil, l.Rebalance.Incoming, nil, nil); err != nil {53 return err54 }55 if l.Repay.Sub, err = lendingPool.WatchRepay(nil, l.Repay.Incoming, nil, nil, nil); err != nil {56 return err57 }58 if l.ReserveUpdate.Sub, err = lendingPool.WatchReserveDataUpdated(nil, l.ReserveUpdate.Incoming, nil); err != nil {59 return err60 }61 if l.CollateralDisabled.Sub, err = lendingPool.WatchReserveUsedAsCollateralDisabled(nil, l.CollateralDisabled.Incoming, nil, nil); err != nil {62 return err63 }64 if l.CollateralEnabled.Sub, err = lendingPool.WatchReserveUsedAsCollateralEnabled(nil, l.CollateralEnabled.Incoming, nil, nil); err != nil {65 return err66 }67 if l.Swap.Sub, err = lendingPool.WatchSwap(nil, l.Swap.Incoming, nil, nil); err != nil {68 return err69 }70 if l.Withdraw.Sub, err = lendingPool.WatchWithdraw(nil, l.Withdraw.Incoming, nil, nil, nil); err != nil {71 return err72 }73 l.SubsOn = true74 return nil75}76// Unsubscribe from all subscriptions.77func (l *Listener) Cleanup() {78 l.Borrow.Sub.Unsubscribe()79 l.Deposit.Sub.Unsubscribe()80 l.FlashLoan.Sub.Unsubscribe()81 l.Liquidation.Sub.Unsubscribe()82 l.Rebalance.Sub.Unsubscribe()83 l.Repay.Sub.Unsubscribe()84 l.ReserveUpdate.Sub.Unsubscribe()85 l.CollateralDisabled.Sub.Unsubscribe()86 l.CollateralEnabled.Sub.Unsubscribe()87 l.Swap.Sub.Unsubscribe()88 l.Withdraw.Sub.Unsubscribe()89}90// Runs loop for listening to events and stores users in database.91func (l *Listener) Listen(92 e chan<- error,93 cli *ethclient.Client,94 db *leveldb.DB,95 lendingPool *contracts.LendingPool,96) {97 if err := l.initiateSubscriptions(cli, lendingPool); err != nil {98 e <- fmt.Errorf("failed to initiate subscriptions: %w", err)99 return100 }101 go func() {102 if err := l.listenSubError(); err != nil {103 e <- fmt.Errorf("subscription error: %w", err)104 return105 }106 }()107 fmt.Println("Listening for events...")108 for {109 select {110 case borrow := <-l.Borrow.Incoming:111 handleBorrow(db, borrow)112 case deposit := <-l.Deposit.Incoming:113 handleDeposit(db, deposit)114 case flashLoan := <-l.FlashLoan.Incoming:115 handleFlashLoan(db, flashLoan)116 case liquidation := <-l.Liquidation.Incoming:117 handleLiquidation(db, liquidation)118 case rebalance := <-l.Rebalance.Incoming:119 handleRebalance(db, rebalance)120 case repay := <-l.Repay.Incoming:121 handleRepay(db, repay)122 case reserveUpdate := <-l.ReserveUpdate.Incoming:123 handleReserveUpdate(reserveUpdate)124 case collateralDisabled := <-l.CollateralDisabled.Incoming:125 handleCollateralDisabled(db, collateralDisabled)126 case collateralEnabled := <-l.CollateralEnabled.Incoming:127 handleCollateralEnabled(db, collateralEnabled)128 case swap := <-l.Swap.Incoming:129 handleSwap(db, swap)130 case withdraw := <-l.Withdraw.Incoming:131 handleWithdraw(db, withdraw)132 }133 }134}135// Returns subscription error.136func (l *Listener) listenSubError() error {137 // Unblocks if an error occurs.138 select {139 case err := <-l.Borrow.Sub.Err():140 return err141 case err := <-l.Deposit.Sub.Err():142 return err143 case err := <-l.FlashLoan.Sub.Err():144 return err145 case err := <-l.Liquidation.Sub.Err():146 return err147 case err := <-l.Rebalance.Sub.Err():148 return err149 case err := <-l.Repay.Sub.Err():150 return err151 case err := <-l.ReserveUpdate.Sub.Err():152 return err153 case err := <-l.CollateralDisabled.Sub.Err():154 return err155 case err := <-l.CollateralEnabled.Sub.Err():156 return err157 case err := <-l.Swap.Sub.Err():158 return err159 case err := <-l.Withdraw.Sub.Err():160 return err161 }162}...

Full Screen

Full Screen

watch_tower.go

Source:watch_tower.go Github

copy

Full Screen

...11// WatchTower -12type WatchTower struct {13 tracker *tools.Tracker14 operations map[tools.OperationID]chain.Operation15 swaps map[chain.Hex]*Swap16 needRedeem bool17 needRefund bool18 retryCount uint19 stopped bool20 wg sync.WaitGroup21}22// NewWatchTower -23func NewWatchTower(cfg Config) (*WatchTower, error) {24 opts := []tools.TrackerOption{25 tools.WithLogLevel(zerolog.InfoLevel),26 }27 if cfg.Restore {28 opts = append(opts, tools.WithRestore())29 }30 track, err := tools.NewTracker(cfg.General.Chains, opts...)31 if err != nil {32 return nil, err33 }34 wt := &WatchTower{35 tracker: track,36 retryCount: cfg.RetryCountOnFailedTx,37 operations: make(map[tools.OperationID]chain.Operation),38 swaps: make(map[chain.Hex]*Swap),39 }40 if wt.retryCount == 0 {41 wt.retryCount = 342 }43 for i := range cfg.Types {44 switch cfg.Types[i] {45 case "redeem":46 wt.needRedeem = true47 case "refund":48 wt.needRefund = true49 }50 }51 return wt, nil52}53const minus30Minutes = -30 * time.Minute54// Run -55func (wt *WatchTower) Run(ctx context.Context, restore bool) error {56 wt.wg.Add(1)57 go wt.listen(ctx)58 if err := wt.tracker.Start(ctx); err != nil {59 return err60 }61 return nil62}63// Close -64func (wt *WatchTower) Close() error {65 wt.stopped = true66 wt.wg.Wait()67 if err := wt.tracker.Close(); err != nil {68 return err69 }70 return nil71}72func (wt *WatchTower) listen(ctx context.Context) {73 defer wt.wg.Done()74 ticker := time.NewTicker(time.Second * 30)75 defer ticker.Stop()76 for {77 select {78 case <-ctx.Done():79 return80 // Tracker81 case swap := <-wt.tracker.StatusChanged():82 swap.Log(log.Info()).Msg("swap info")83 s, ok := wt.swaps[swap.HashedSecret]84 if !ok {85 s = &Swap{swap, 0}86 wt.swaps[swap.HashedSecret] = s87 } else {88 s.merge(swap)89 }90 if err := wt.onSwap(ctx, s); err != nil {91 log.Err(err).Msg("onSwap")92 }93 case operation := <-wt.tracker.Operations():94 if err := wt.onOperation(ctx, operation); err != nil {95 log.Err(err).Msg("onOperation")96 }97 // Manager channels98 case <-ticker.C:99 wt.checkNextActionTime(ctx)100 }101 }102}103func (wt *WatchTower) onSwap(ctx context.Context, swap *Swap) error {104 if swap.RetryCount >= wt.retryCount {105 delete(wt.swaps, swap.HashedSecret)106 log.Info().Str("hashed_secret", swap.HashedSecret.String()).Msg("swap retry count transaction exceeded")107 return nil108 }109 switch swap.Status {110 case tools.StatusRedeemedOnce:111 if wt.needRedeem {112 if err := wt.redeem(ctx, swap); err != nil {113 return err114 }115 }116 case tools.StatusRefundedOnce:117 case tools.StatusRedeemed, tools.StatusRefunded:118 delete(wt.swaps, swap.HashedSecret)119 default:120 }121 return nil122}123func (wt *WatchTower) checkNextActionTime(ctx context.Context) {124 if !wt.needRefund && !wt.needRedeem {125 return126 }127 for hashedSecret, swap := range wt.swaps {128 if wt.stopped {129 return130 }131 if wt.needRedeem && swap.Status == tools.StatusRedeemedOnce {132 if err := wt.redeem(ctx, swap); err != nil {133 log.Err(err).Msg("redeem")134 }135 }136 if wt.needRefund {137 if swap.IsUnknown() {138 continue139 }140 if swap.RefundTime.UTC().Before(time.Now().UTC()) {141 if err := wt.refund(ctx, swap); err != nil {142 log.Err(err).Msg("refund")143 continue144 }145 delete(wt.swaps, hashedSecret)146 }147 }148 }149}150func (wt *WatchTower) redeem(ctx context.Context, swap *Swap) error {151 utcNow := time.Now().UTC()152 if leg := swap.Leg(); leg != nil && utcNow.Before(swap.RefundTime.UTC()) {153 if swap.RewardForRedeem.IsPositive() {154 swap.RetryCount++155 return wt.tracker.Redeem(ctx, swap.Swap, *leg)156 }157 if swap.RewardForRedeem.IsZero() && utcNow.After(swap.RefundTime.Add(minus30Minutes).UTC()) {158 log.Info().Msg("WatchTower starts redeem for swap with zero reward")159 swap.RetryCount++160 return wt.tracker.Redeem(ctx, swap.Swap, *leg)161 }162 }163 return nil164}165func (wt *WatchTower) refund(ctx context.Context, swap *Swap) error {166 if leg := swap.Leg(); leg != nil {167 swap.RetryCount++168 return wt.tracker.Refund(ctx, swap.Swap, *leg)169 }170 if swap.Acceptor.Status == tools.StatusInitiated && swap.Initiator.Status == tools.StatusInitiated {171 swap.RetryCount++172 if err := wt.tracker.Refund(ctx, swap.Swap, swap.Initiator); err != nil {173 return err174 }175 return wt.tracker.Refund(ctx, swap.Swap, swap.Acceptor)176 }177 return nil178}179func (wt *WatchTower) onOperation(ctx context.Context, operation chain.Operation) error {180 id := tools.OperationID{181 Hash: operation.Hash,182 Chain: operation.ChainType,183 }184 switch operation.Status {185 case chain.Pending:186 wt.operations[id] = operation187 log.Info().Str("blockchain", operation.ChainType.String()).Str("hash", operation.Hash).Str("status", operation.Status.String()).Str("hashed_secret", operation.HashedSecret.String()).Msg("transaction")188 case chain.Applied:189 if old, ok := wt.operations[id]; ok {190 log.Info().Str("blockchain", operation.ChainType.String()).Str("hash", operation.Hash).Str("status", operation.Status.String()).Str("hashed_secret", old.HashedSecret.String()).Msg("transaction")191 delete(wt.operations, id)192 }193 case chain.Failed:194 if old, ok := wt.operations[id]; ok {195 log.Info().Str("blockchain", operation.ChainType.String()).Str("hash", operation.Hash).Str("status", operation.Status.String()).Str("hashed_secret", old.HashedSecret.String()).Msg("transaction")196 delete(wt.operations, id)197 if swap, ok := wt.swaps[old.HashedSecret]; ok {198 return wt.onSwap(ctx, swap)199 }200 }201 }202 return nil203}...

Full Screen

Full Screen

start.go

Source:start.go Github

copy

Full Screen

...9 watchEventDelay = time.Duration(5) * time.Second10)11func (e *Engine) Start() {12 // ERC72113 go e.run(e.manageERC721OngoingRequest, watchSwapEventDelay)14 go e.run(e.manageERC721ConfirmedSwap, watchSwapEventDelay)15 go e.run(e.manageERC721TxCreatedSwap, watchSwapEventDelay)16 go e.run(e.manageERC721TxSentSwap, watchSwapEventDelay)17 // ERC115518 go e.run(e.manageERC1155OngoingRequest, watchSwapEventDelay)19 go e.run(e.manageERC1155ConfirmedSwap, watchSwapEventDelay)20 go e.run(e.manageERC1155TxCreatedSwap, watchSwapEventDelay)21 go e.run(e.manageERC1155TxSentSwap, watchSwapEventDelay)22}23func (e *Engine) run(fn func(), delay time.Duration) {24 fnName := runtime.FuncForPC(reflect.ValueOf(fn).Pointer()).Name()25 if delay.Seconds() == 0 {26 delay = watchEventDelay27 }28 for {29 time.Sleep(watchEventDelay)30 if e.deps.Recorder[e.chainID()].LatestBlockCached() == nil {31 util.Logger.Infof("[Engine.run][%s]: no latest block cache found for chain id %s", fnName, e.chainID())32 continue33 }34 fn()35 }...

Full Screen

Full Screen

Swap

Using AI Code Generation

copy

Full Screen

1import (2type watch struct {3}4func (w *watch) set(h, m, s int) {5}6func (w *watch) String() string {7 return fmt.Sprintf("%02d:%02d:%02d", w.hour, w.minute, w.second)8}9func (w *watch) Swap() {10}11func main() {12 w := watch{}13 w.set(1, 2, 3)14 fmt.Println(w)15 w.Swap()16 fmt.Println(w)17}

Full Screen

Full Screen

Swap

Using AI Code Generation

copy

Full Screen

1import (2type Watch struct {3}4func (w *Watch) Swap(brand string) {5}6func main() {7 watch := Watch{brand: "Fossil"}8 watch.Swap("Casio")9 time.Sleep(5 * time.Second)10}

Full Screen

Full Screen

Swap

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 opts := []selenium.ServiceOption{}4 svc, err := selenium.NewChromeDriverService("C:\\chromedriver.exe", 9515, opts...)5 if err != nil {6 log.Fatal(err)7 }8 defer svc.Stop()9 caps := selenium.Capabilities{"browserName": "chrome"}10 caps.AddChrome(chrome.Capabilities{11 Args: []string{12 },13 })14 if err != nil {15 log.Fatal(err)16 }17 defer wd.Quit()18 log.Fatal(err)19 }20 if err := wd.WaitWithTimeout(selenium.Condition{21 Fn: func(wd selenium.WebDriver) (bool, error) {22 el, err := wd.FindElement(selenium.ByCSSSelector, "#code")23 if err != nil {24 }25 return el.Displayed()26 },27 }, 10*time.Second); err != nil {28 log.Fatal(err)29 }30 codeBox, err := wd.FindElement(selenium.ByCSSSelector, "#code")31 if err != nil {32 log.Fatal(err)33 }34 if err := codeBox.SendKeys("package main35import \"fmt\"36func main() {37 fmt.Println(\"Hello, playground\")38}"); err != nil {39 log.Fatal(err)40 }41 runButton, err := wd.FindElement(selenium.ByCSSSelector, "#run")42 if err != nil {43 log.Fatal(err)44 }45 if err := runButton.Click(); err

Full Screen

Full Screen

Swap

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 watch1 := Watch{Brand: "Rolex", Price: 1000.00}4 watch2 := Watch{Brand: "Casio", Price: 50.00}5 fmt.Println(watch1, watch2)6 watch1.Swap(&watch2)7 fmt.Println(watch1, watch2)8}9import (10func main() {11 watch1 := Watch{Brand: "Rolex", Price: 1000.00}12 watch2 := Watch{Brand: "Casio", Price: 50.00}13 fmt.Println(watch1, watch2)14 watch1.Swap(watch2)15 fmt.Println(watch1, watch2)16}17import (18func main() {19 watch1 := Watch{Brand: "Rolex", Price: 1000.00}20 watch2 := Watch{Brand: "Casio", Price: 50.00}21 fmt.Println(watch1, watch2)22 watch1.Swap(&watch1)23 fmt.Println(watch1, watch2)24}25import (26func main() {27 watch1 := Watch{Brand: "Rolex", Price: 1000.00}28 watch2 := Watch{Brand: "Casio", Price: 50.00}29 fmt.Println(watch1, watch2)30 watch1.Swap(watch1)31 fmt.Println(watch1, watch2)32}

Full Screen

Full Screen

Swap

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 watch := Watch{hour: 9, minute: 30, second: 0}4 fmt.Println(watch)5 watch.Swap()6 fmt.Println(watch)7}8import (9func (w *Watch) Swap() {10 t := time.Date(0, 0, 0, w.hour, w.minute, w.second, 0, time.UTC)11 t = t.Add(12 * time.Hour)12 w.hour, w.minute, w.second = t.Clock()13}14import (15type Watch struct {16}17func (w Watch) String() string {18 return fmt.Sprintf("%02d:%02d:%02d", w.hour, w.minute, w.second)19}

Full Screen

Full Screen

Swap

Using AI Code Generation

copy

Full Screen

1import "fmt"2func main() {3watch1 := watch{"Fossil", 100, "red"}4watch2 := watch{"Casio", 150, "black"}5fmt.Println("Before Swap")6fmt.Println(watch1)7fmt.Println(watch2)8watch1.Swap(&watch2)9fmt.Println("After Swap")10fmt.Println(watch1)11fmt.Println(watch2)12}13{Fossil 100 red}14{Casio 150 black}15{Casio 150 black}16{Fossil 100 red}17import "fmt"18func main() {19watch1 := watch{"Fossil", 100, "red"}20watch2 := watch{"Casio", 150, "black"}21fmt.Println("Before Swap")22fmt.Println(watch1)23fmt.Println(watch2)24watch1.Swap(watch2)25fmt.Println("After Swap")26fmt.Println(watch1)27fmt.Println(watch2)28}29{Fossil 100 red}30{Casio 150 black}31{Fossil 100 red}32{Casio 150 black}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful