github.com/status-im/status-go@v1.1.0/services/wallet/router/routes/router_graph.go (about) 1 package routes 2 3 import ( 4 "math/big" 5 ) 6 7 type Graph []*Node 8 9 type Node struct { 10 Path *Path 11 Children Graph 12 } 13 14 func newNode(path *Path) *Node { 15 return &Node{Path: path, Children: make(Graph, 0)} 16 } 17 18 func BuildGraph(AmountIn *big.Int, route Route, level int, sourceChainIDs []uint64) Graph { 19 graph := make(Graph, 0) 20 for _, path := range route { 21 found := false 22 for _, chainID := range sourceChainIDs { 23 if chainID == path.FromChain.ChainID { 24 found = true 25 break 26 } 27 } 28 if found { 29 continue 30 } 31 node := newNode(path) 32 33 newRoute := make(Route, 0) 34 for _, p := range route { 35 if path.Equal(p) { 36 continue 37 } 38 newRoute = append(newRoute, p) 39 } 40 41 newAmountIn := new(big.Int).Sub(AmountIn, path.AmountIn.ToInt()) 42 if newAmountIn.Sign() > 0 { 43 newSourceChainIDs := make([]uint64, len(sourceChainIDs)) 44 copy(newSourceChainIDs, sourceChainIDs) 45 newSourceChainIDs = append(newSourceChainIDs, path.FromChain.ChainID) 46 node.Children = BuildGraph(newAmountIn, newRoute, level+1, newSourceChainIDs) 47 48 if len(node.Children) == 0 { 49 continue 50 } 51 } 52 53 graph = append(graph, node) 54 } 55 56 return graph 57 } 58 59 func (n Node) BuildAllRoutes() []Route { 60 res := make([]Route, 0) 61 62 if len(n.Children) == 0 && n.Path != nil { 63 res = append(res, Route{n.Path}) 64 } 65 66 for _, node := range n.Children { 67 for _, route := range node.BuildAllRoutes() { 68 extendedRoute := route 69 if n.Path != nil { 70 extendedRoute = append(Route{n.Path}, route...) 71 } 72 res = append(res, extendedRoute) 73 } 74 } 75 76 return res 77 }