github.com/status-im/status-go@v1.1.0/services/wallet/common/utils.go (about)

     1  package common
     2  
     3  import (
     4  	"context"
     5  	"math/big"
     6  	"reflect"
     7  
     8  	gethParams "github.com/ethereum/go-ethereum/params"
     9  	"github.com/status-im/status-go/params"
    10  )
    11  
    12  // ShouldCancel returns true if the context has been cancelled and task should be aborted
    13  func ShouldCancel(ctx context.Context) bool {
    14  	select {
    15  	case <-ctx.Done():
    16  		return true
    17  	default:
    18  	}
    19  	return false
    20  }
    21  
    22  func NetworksToChainIDs(networks []*params.Network) []uint64 {
    23  	chainIDs := make([]uint64, 0)
    24  	for _, network := range networks {
    25  		chainIDs = append(chainIDs, network.ChainID)
    26  	}
    27  
    28  	return chainIDs
    29  }
    30  
    31  func ArrayContainsElement[T comparable](el T, arr []T) bool {
    32  	for _, e := range arr {
    33  		if e == el {
    34  			return true
    35  		}
    36  	}
    37  	return false
    38  }
    39  
    40  func IsSingleChainOperation(fromChains []*params.Network, toChains []*params.Network) bool {
    41  	return len(fromChains) == 1 &&
    42  		len(toChains) == 1 &&
    43  		fromChains[0].ChainID == toChains[0].ChainID
    44  }
    45  
    46  // CopyMapGeneric creates a copy of any map, if the deepCopyValue function is provided, it will be used to copy values.
    47  func CopyMapGeneric(original interface{}, deepCopyValueFn func(interface{}) interface{}) interface{} {
    48  	originalVal := reflect.ValueOf(original)
    49  	if originalVal.Kind() != reflect.Map {
    50  		return nil
    51  	}
    52  
    53  	newMap := reflect.MakeMap(originalVal.Type())
    54  	for iter := originalVal.MapRange(); iter.Next(); {
    55  		if deepCopyValueFn != nil {
    56  			newMap.SetMapIndex(iter.Key(), reflect.ValueOf(deepCopyValueFn(iter.Value().Interface())))
    57  		} else {
    58  			newMap.SetMapIndex(iter.Key(), iter.Value())
    59  		}
    60  	}
    61  
    62  	return newMap.Interface()
    63  }
    64  
    65  func GweiToEth(val *big.Float) *big.Float {
    66  	return new(big.Float).Quo(val, big.NewFloat(1000000000))
    67  }
    68  
    69  func WeiToGwei(val *big.Int) *big.Float {
    70  	result := new(big.Float)
    71  	result.SetInt(val)
    72  
    73  	unit := new(big.Int)
    74  	unit.SetInt64(gethParams.GWei)
    75  
    76  	return result.Quo(result, new(big.Float).SetInt(unit))
    77  }