Skip to content

Commit

Permalink
Cleanup pass.
Browse files Browse the repository at this point in the history
  • Loading branch information
Patricio Napoli committed Oct 10, 2022
1 parent 632561c commit f0a4d2e
Show file tree
Hide file tree
Showing 10 changed files with 58 additions and 51 deletions.
10 changes: 5 additions & 5 deletions cmd/bazaar/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,19 +21,19 @@ func main() {
console.PrintArt()
log.Printf("launching Bazaar on epoch ms %d", utils.GetMillis())

cfg := config.NewConfig()
cfg := config.New()

client := chain.NewEthClient(cfg)

tkns := tokens.GetTokens(cfg)
paths, swaps := pairs.NewPaths(cfg, tkns)
tkns := tokens.New(cfg)
paths, swaps := pairs.New(cfg, tkns)

log.Printf("attempting arbitrage on entry coin: ")
wethJson, _ := utils.ToPrettyJSON(tkns[cfg.WETHAddr])
fmt.Println(string(wethJson))

wd := watchdog.NewWatchdog(cfg, client, swaps)
arb := arbiter.NewArbiter(cfg, client, paths)
wd := watchdog.New(cfg, client, swaps)
arb := arbiter.New(cfg, client, paths)

var wg sync.WaitGroup
keep := true
Expand Down
32 changes: 16 additions & 16 deletions cmd/bazaar/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func TestReduceBigInt(t *testing.T) {
}

func TestNewConfig(t *testing.T) {
cfg := config.NewConfig()
cfg := config.New()
cfg.APIKey = ""

expected := string(ReadFile(t, "test/expected/config.json"))
Expand All @@ -47,7 +47,7 @@ func TestNewConfig(t *testing.T) {
}

func TestNewEthClient(t *testing.T) {
cfg := config.NewConfig()
cfg := config.New()

eth := chain.NewEthClient(cfg)

Expand All @@ -58,62 +58,62 @@ func TestNewEthClient(t *testing.T) {
}

func TestGetTokens(t *testing.T) {
cfg := config.NewConfig()
cfg := config.New()
cfg.TokensFile = "test/fixtures/tokens.json"

tkns := tokens.GetTokens(cfg)
tkns := tokens.New(cfg)

AssertExpectedJSON(t, tkns, "test/expected/tokens.json")
}

func TestNewPaths(t *testing.T) {
cfg := config.NewConfig()
cfg := config.New()
cfg.TokensFile = "test/fixtures/tokens.json"
cfg.PairsFile = "test/fixtures/pairs.json"

tkns := tokens.GetTokens(cfg)
tkns := tokens.New(cfg)

paths, swaps := pairs.NewPaths(cfg, tkns)
paths, swaps := pairs.New(cfg, tkns)

AssertExpectedJSON(t, paths, "test/expected/paths.json")
AssertExpectedJSON(t, swaps, "test/expected/swaps.json")
}

func TestNewWatchdog(t *testing.T) {
cfg := config.NewConfig()
cfg := config.New()
cfg.TokensFile = "test/fixtures/tokens.json"
cfg.PairsFile = "test/fixtures/pairs.json"
cfg.RatePrecision = 5

tkns := tokens.GetTokens(cfg)
_, swaps := pairs.NewPaths(cfg, tkns)
tkns := tokens.New(cfg)
_, swaps := pairs.New(cfg, tkns)

eth := chain.NewEthClient(cfg)

wd := watchdog.NewWatchdog(cfg, eth, swaps)
wd := watchdog.New(cfg, eth, swaps)
wd.Start()

AssertExpectedJSON(t, swaps, "test/expected/swaps_wd.json")
}

func TestNewArbiter(t *testing.T) {
cfg := config.NewConfig()
cfg := config.New()
cfg.TokensFile = "test/fixtures/tokens.json"
cfg.PairsFile = "test/fixtures/pairs.json"
cfg.OutputFilename = "output/output_test.json"
cfg.PrettyPrintOutput = false
cfg.RatePrecision = 6
cfg.IncludeFees = false

tkns := tokens.GetTokens(cfg)
paths, swaps := pairs.NewPaths(cfg, tkns)
tkns := tokens.New(cfg)
paths, swaps := pairs.New(cfg, tkns)

eth := chain.NewEthClient(cfg)

wd := watchdog.NewWatchdog(cfg, eth, swaps)
wd := watchdog.New(cfg, eth, swaps)
wd.Start()

arb := arbiter.NewArbiter(cfg, eth, paths)
arb := arbiter.New(cfg, eth, paths)
arb.Start()

out := ReadFile(t, cfg.OutputFilename)
Expand Down
28 changes: 19 additions & 9 deletions pkg/arbiter/arbiter.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,9 @@ type Arbiter struct {
Config config.Config
}

// NewArbiter creates an arbitration node graph structure, that's capable of easily
// New creates an arbitration node graph structure, that's capable of easily
// traversing it and finding potential market arbitration paths.
func NewArbiter(cfg config.Config, client chain.EthClient, paths []pairs.Path) Arbiter {
func New(cfg config.Config, client chain.EthClient, paths []pairs.Path) Arbiter {
// These are excluded because they do not belong to Uniswap or Sushiswap,
// furthermore, it appears that they have been disabled and reserves have not
// been rebalanced, leading to non-valid exchange rates, since they are not
Expand Down Expand Up @@ -117,7 +117,7 @@ func (arb *Arbiter) Start() {

// Splitting this operation in many go threads yielded bad results
// Threads benefit when the CPU computation of the unit surpasses
// that of the thread scheduling
// that of the thread scheduling load and context switches
for _, rn := range arb.RootNodes {

for _, node := range rn.Children {
Expand All @@ -126,7 +126,7 @@ func (arb *Arbiter) Start() {
Path: make([]*SwapNode, 0),
}
arbs := make([]Arbitration, 0)
arb.exploreArbitrationGraph(&arbs, &currArbitration, node)
arb.findPaths(&arbs, &currArbitration, node)

for _, a := range arbs {
pathLength := float64(len(a.Path))
Expand All @@ -149,7 +149,8 @@ func (arb *Arbiter) Start() {
writePathsToFile(arb.Config, pathGroups, arb.Config.OutputFilename)
}

func (arb *Arbiter) exploreArbitrationGraph(arbs *[]Arbitration, currArb *Arbitration, node *SwapNode) {
func (arb *Arbiter) findPaths(arbs *[]Arbitration, currArb *Arbitration, node *SwapNode) {
// Check what token we are swapping to
if node.Target.Address == node.Swap.Token0.Address {
exch := currArb.Balance * node.Swap.Rate1to0
if node.Swap.Token0Reserve < exch {
Expand All @@ -170,19 +171,20 @@ func (arb *Arbiter) exploreArbitrationGraph(arbs *[]Arbitration, currArb *Arbitr

balanceBefore := currArb.Balance
for i, n := range node.Children {
// Refuse to hop to itself or to same target
// Refuse to hop to itself or to same target token.
if n.Swap.Address == node.Swap.Address || n.Target.Address == node.Target.Address {
continue
}

// Check for second token swap in same Target, and it's not the final one.
if i > 0 && n.Target.Address != arb.Config.WETHAddr {
newPath := currArb.Path[:len(currArb.Path)-1]
currArb = &Arbitration{
Balance: balanceBefore,
Path: newPath,
}
}
arb.exploreArbitrationGraph(arbs, currArb, n)
arb.findPaths(arbs, currArb, n)
}

if len(node.Children) == 0 {
Expand All @@ -195,7 +197,12 @@ func writePathsToFile(cfg config.Config, paths []Arbitration, filename string) {
if err != nil {
log.Panicf("unable to create arbitration log file: %v", err)
}
defer file.Close()
defer func(file *os.File) {
err := file.Close()
if err != nil {
log.Printf("failed when closing file %s", filename)
}
}(file)

var bytes []byte

Expand All @@ -206,5 +213,8 @@ func writePathsToFile(cfg config.Config, paths []Arbitration, filename string) {
}

log.Printf("writing arbitration output to %s", filename)
fmt.Fprintf(file, "%s", string(bytes))
_, err = fmt.Fprintf(file, "%s", string(bytes))
if err != nil {
log.Printf("failed when writing file %s", filename)
}
}
File renamed without changes.
4 changes: 2 additions & 2 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ type Config struct {
RatePrecision uint
}

// NewConfig creates a configuration struct from environment vars.
func NewConfig() Config {
// New creates a configuration struct from environment vars.
func New() Config {
log.Printf("loading config from env vars")

c := Config{
Expand Down
14 changes: 7 additions & 7 deletions pkg/pairs/pairs.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"github.com/PatricioNapoli/bazaar/pkg/config"
"github.com/PatricioNapoli/bazaar/pkg/tokens"
"github.com/PatricioNapoli/bazaar/pkg/utils"

"log"
"sort"
)
Expand All @@ -27,9 +28,9 @@ type Path struct {
TokenSwaps []TokenSwap
}

// NewPaths builds a sane struct representation parse from
// New builds a sane struct representation parse from
// the provided swaps file, this improves later processing.
func NewPaths(cfg config.Config, tokenMap map[string]tokens.Token) ([]Path, []*Swap) {
func New(cfg config.Config, tokenMap map[string]tokens.Token) ([]Path, []*Swap) {
log.Printf("loading pairs info in %s", cfg.PairsFile)

f, err := utils.ReadFile(cfg.PairsFile)
Expand All @@ -54,8 +55,9 @@ func NewPaths(cfg config.Config, tokenMap map[string]tokens.Token) ([]Path, []*S
for i, tswap := range rootPathC {

tswapC := tswap.([]interface{})
ts := TokenSwap{}
ts.Token = tokenMap[tswapC[0].(string)]
ts := TokenSwap{
Token: tokenMap[tswapC[0].(string)],
}

for _, swap := range tswapC[1].([]interface{}) {

Expand All @@ -79,9 +81,7 @@ func NewPaths(cfg config.Config, tokenMap map[string]tokens.Token) ([]Path, []*S
rp.TokenSwaps = append(rp.TokenSwaps, ts)
}

if len(rp.TokenSwaps) != 0 {
paths = append(paths, rp)
}
paths = append(paths, rp)
}

return paths, swaps
Expand Down
4 changes: 2 additions & 2 deletions pkg/tokens/tokens.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ type Tokens struct {
tokens map[string]Token
}

// GetTokens loads a tokens file into an indexed map through token's address.
func GetTokens(cfg config.Config) map[string]Token {
// New loads a tokens file into an indexed map through token's address.
func New(cfg config.Config) map[string]Token {
log.Printf("loading token info in %s", cfg.TokensFile)

f, err := utils.ReadFile(cfg.TokensFile)
Expand Down
8 changes: 0 additions & 8 deletions pkg/utils/float.go

This file was deleted.

5 changes: 5 additions & 0 deletions pkg/utils/bigint.go → pkg/utils/math.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,8 @@ func ReduceBigInt(n *big.Int, decimals int) float64 {
final, _ := flt.Float64()
return final
}

func RoundFloat(val float64, precision uint) float64 {
ratio := math.Pow(10, float64(precision))
return math.Round(val*ratio) / ratio
}
4 changes: 2 additions & 2 deletions pkg/watchdog/watchdog.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ type Watchdog struct {
Config config.Config
}

// NewWatchdog creates a token reserves watchdog that
// New creates a token reserves watchdog that
// maintains rates updated to their latest exchange when started
// using the provided contract address.
func NewWatchdog(cfg config.Config, client chain.EthClient, swaps []*pairs.Swap) Watchdog {
func New(cfg config.Config, client chain.EthClient, swaps []*pairs.Swap) Watchdog {
addresses := make([]common.Address, len(swaps))

for i, swp := range swaps {
Expand Down

0 comments on commit f0a4d2e

Please sign in to comment.