diff --git a/client/app/config.go b/client/app/config.go index 732b69fb65..e84fdf4e11 100644 --- a/client/app/config.go +++ b/client/app/config.go @@ -213,7 +213,7 @@ var DefaultConfig = Config{ // ParseCLIConfig parses the command-line arguments into the provided struct // with go-flags tags. If the --help flag has been passed, the struct is // described back to the terminal and the program exits using os.Exit. -func ParseCLIConfig(cfg interface{}) error { +func ParseCLIConfig(cfg any) error { preParser := flags.NewParser(cfg, flags.HelpFlag|flags.PassDoubleDash) _, flagerr := preParser.Parse() @@ -251,7 +251,7 @@ func ResolveCLIConfigPaths(cfg *Config) (appData, configPath string) { // ParseFileConfig parses the INI file into the provided struct with go-flags // tags. The CLI args are then parsed, and take precedence over the file values. -func ParseFileConfig(path string, cfg interface{}) error { +func ParseFileConfig(path string, cfg any) error { parser := flags.NewParser(cfg, flags.Default) err := flags.NewIniParser(parser).ParseFile(path) if err != nil { diff --git a/client/asset/bch/spv.go b/client/asset/bch/spv.go index 44292ce340..8524d1dbe1 100644 --- a/client/asset/bch/spv.go +++ b/client/asset/bch/spv.go @@ -992,32 +992,32 @@ type fileLoggerPlus struct { log dex.Logger } -func (f *fileLoggerPlus) Warnf(format string, params ...interface{}) { +func (f *fileLoggerPlus) Warnf(format string, params ...any) { f.log.Warnf(format, params...) f.Logger.Warnf(format, params...) } -func (f *fileLoggerPlus) Errorf(format string, params ...interface{}) { +func (f *fileLoggerPlus) Errorf(format string, params ...any) { f.log.Errorf(format, params...) f.Logger.Errorf(format, params...) } -func (f *fileLoggerPlus) Criticalf(format string, params ...interface{}) { +func (f *fileLoggerPlus) Criticalf(format string, params ...any) { f.log.Criticalf(format, params...) f.Logger.Criticalf(format, params...) } -func (f *fileLoggerPlus) Warn(v ...interface{}) { +func (f *fileLoggerPlus) Warn(v ...any) { f.log.Warn(v...) f.Logger.Warn(v...) } -func (f *fileLoggerPlus) Error(v ...interface{}) { +func (f *fileLoggerPlus) Error(v ...any) { f.log.Error(v...) f.Logger.Error(v...) } -func (f *fileLoggerPlus) Critical(v ...interface{}) { +func (f *fileLoggerPlus) Critical(v ...any) { f.log.Critical(v...) f.Logger.Critical(v...) } diff --git a/client/asset/btc/btc.go b/client/asset/btc/btc.go index b41a387328..81a016f329 100644 --- a/client/asset/btc/btc.go +++ b/client/asset/btc/btc.go @@ -1083,7 +1083,7 @@ type findRedemptionReq struct { contractHash []byte } -func (req *findRedemptionReq) fail(s string, a ...interface{}) { +func (req *findRedemptionReq) fail(s string, a ...any) { req.success(&findRedemptionResult{err: fmt.Errorf(s, a...)}) } @@ -4517,7 +4517,7 @@ func (btc *intermediaryWallet) tryRedemptionRequests(ctx context.Context, startB undiscovered[req.outPt] = req } - epicFail := func(s string, a ...interface{}) { + epicFail := func(s string, a ...any) { errMsg := fmt.Sprintf(s, a...) for _, req := range reqs { req.fail(errMsg) @@ -5180,7 +5180,7 @@ func (btc *intermediaryWallet) reportNewTip(ctx context.Context, newTip *block) // be determined, as searching just the new tip might result in blocks // being omitted from the search operation. If that happens, cancel all // find redemption requests in queue. - notifyFatalFindRedemptionError := func(s string, a ...interface{}) { + notifyFatalFindRedemptionError := func(s string, a ...any) { for _, req := range reqs { req.fail("tipChange handler - "+s, a...) } @@ -5355,7 +5355,7 @@ func (btc *baseWallet) sendWithReturn(baseTx *wire.MsgTx, addr btcutil.Address, func (btc *baseWallet) signTxAndAddChange(baseTx *wire.MsgTx, addr btcutil.Address, totalIn, totalOut, feeRate uint64) (*wire.MsgTx, *output, uint64, error) { - makeErr := func(s string, a ...interface{}) (*wire.MsgTx, *output, uint64, error) { + makeErr := func(s string, a ...any) (*wire.MsgTx, *output, uint64, error) { return nil, nil, 0, fmt.Errorf(s, a...) } @@ -6351,7 +6351,7 @@ func (btc *baseWallet) scriptHashScript(contract []byte) ([]byte, error) { // CallRPC is a method for making RPC calls directly on an underlying RPC // client. CallRPC is not part of the wallet interface. Its intended use is for // clone wallets to implement custom functionality. -func (btc *baseWallet) CallRPC(method string, args []interface{}, thing interface{}) error { +func (btc *baseWallet) CallRPC(method string, args []any, thing any) error { rpcCl, is := btc.node.(*rpcClient) if !is { return errors.New("wallet is not RPC") diff --git a/client/asset/btc/btc_test.go b/client/asset/btc/btc_test.go index 9440372c0f..a88528197c 100644 --- a/client/asset/btc/btc_test.go +++ b/client/asset/btc/btc_test.go @@ -247,7 +247,7 @@ func (c *testData) bestBlock() (*chainhash.Hash, int64) { return bestHash, bestBlkHeight } -func encodeOrError(thing interface{}, err error) (json.RawMessage, error) { +func encodeOrError(thing any, err error) (json.RawMessage, error) { if err != nil { return nil, err } @@ -718,7 +718,7 @@ func tNewWallet(segwit bool, walletType string) (*intermediaryWallet, *testData, return wallet, data, shutdownAndWait } -func mustMarshal(thing interface{}) []byte { +func mustMarshal(thing any) []byte { b, err := json.Marshal(thing) if err != nil { panic("mustMarshal error: " + err.Error()) @@ -1980,7 +1980,7 @@ func testFundMultiOrder(t *testing.T, segwit bool, walletType string) { if totalNumCoins != len(node.lockedCoins) { t.Fatalf("%s: expected %d locked coins, got %d", test.name, totalNumCoins, len(node.lockedCoins)) } - lockedCoins := make(map[RPCOutpoint]interface{}) + lockedCoins := make(map[RPCOutpoint]any) for _, coin := range node.lockedCoins { lockedCoins[*coin] = true } diff --git a/client/asset/btc/electrum/jsonrpc.go b/client/asset/btc/electrum/jsonrpc.go index 4e7778cd37..3cddd30811 100644 --- a/client/asset/btc/electrum/jsonrpc.go +++ b/client/asset/btc/electrum/jsonrpc.go @@ -10,7 +10,7 @@ import ( "strconv" ) -type positional []interface{} +type positional []any type request struct { Jsonrpc string `json:"jsonrpc"` @@ -43,7 +43,7 @@ type ntfnData struct { Params json.RawMessage `json:"params"` } -func prepareRequest(id uint64, method string, args interface{}) ([]byte, error) { +func prepareRequest(id uint64, method string, args any) ([]byte, error) { // nil args should marshal as [] instead of null. if args == nil { args = []json.RawMessage{} diff --git a/client/asset/btc/electrum/network.go b/client/asset/btc/electrum/network.go index 537159cb67..76ebf57f5f 100644 --- a/client/asset/btc/electrum/network.go +++ b/client/asset/btc/electrum/network.go @@ -26,19 +26,19 @@ import ( ) // Printer is a function with the signature of a logger method. -type Printer func(format string, params ...interface{}) +type Printer func(format string, params ...any) var ( // StdoutPrinter is a DebugLogger that uses fmt.Printf. - StdoutPrinter = Printer(func(format string, params ...interface{}) { + StdoutPrinter = Printer(func(format string, params ...any) { fmt.Printf(format+"\n", params...) // discard the returns }) // StderrPrinter is a DebugLogger that uses fmt.Fprintf(os.Stderr, ...). - StderrPrinter = Printer(func(format string, params ...interface{}) { + StderrPrinter = Printer(func(format string, params ...any) { fmt.Fprintf(os.Stderr, format+"\n", params...) }) - disabledPrinter = Printer(func(string, ...interface{}) {}) + disabledPrinter = Printer(func(string, ...any) {}) ) const pingInterval = 10 * time.Second @@ -356,7 +356,7 @@ func (sc *ServerConn) deleteSubscriptions() { // arguments. args may not be any other basic type. The the response does not // include an error, the result will be unmarshalled into result, unless the // provided result is nil in which case the response payload will be ignored. -func (sc *ServerConn) Request(ctx context.Context, method string, args interface{}, result interface{}) error { +func (sc *ServerConn) Request(ctx context.Context, method string, args any, result any) error { id := sc.nextID() reqMsg, err := prepareRequest(id, method, args) if err != nil { @@ -417,7 +417,7 @@ type ServerFeatures struct { Hosts map[string]map[string]uint32 `json:"hosts"` // e.g. {"host.com": {"tcp_port": 51001, "ssl_port": 51002}}, may be unset! ProtoMax string `json:"protocol_max"` ProtoMin string `json:"protocol_min"` - Pruning interface{} `json:"pruning,omitempty"` // supposedly an integer, but maybe a string or even JSON null + Pruning any `json:"pruning,omitempty"` // supposedly an integer, but maybe a string or even JSON null Version string `json:"server_version"` // server software version, not proto HashFunc string `json:"hash_function"` // e.g. sha256 // Services []string `json:"services,omitempty"` // e.g. ["tcp://host.com:51001", "ssl://host.com:51002"] @@ -450,8 +450,8 @@ func (sc *ServerConn) Peers(ctx context.Context) ([]*PeersResult, error) { // (*WalletClient).GetServers. We might wish to in the future though. // [["ip", "host", ["featA", "featB", ...]], ...] - // [][]interface{}{string, string, []interface{}{string, ...}} - var resp [][]interface{} + // [][]any{string, string, []any{string, ...}} + var resp [][]any err := sc.Request(ctx, "server.peers.subscribe", nil, &resp) // not really a subscription! if err != nil { return nil, err @@ -472,7 +472,7 @@ func (sc *ServerConn) Peers(ctx context.Context) ([]*PeersResult, error) { sc.debug("bad peer hostname: %v (%T)", peer[1], peer[1]) continue } - featsI, ok := peer[2].([]interface{}) + featsI, ok := peer[2].([]any) if !ok { sc.debug("bad peer feature data: %v (%T)", peer[2], peer[2]) continue diff --git a/client/asset/btc/electrum/wallet.go b/client/asset/btc/electrum/wallet.go index 32838922ad..25160dc267 100644 --- a/client/asset/btc/electrum/wallet.go +++ b/client/asset/btc/electrum/wallet.go @@ -62,7 +62,7 @@ func (ec *WalletClient) nextID() uint64 { // should have their fields appropriately tagged for JSON marshalling. The // result is marshaled into result if it is non-nil, otherwise the result is // discarded. -func (ec *WalletClient) Call(ctx context.Context, method string, args interface{}, result interface{}) error { +func (ec *WalletClient) Call(ctx context.Context, method string, args any, result any) error { reqMsg, err := prepareRequest(ec.nextID(), method, args) if err != nil { return err diff --git a/client/asset/btc/rpcclient.go b/client/asset/btc/rpcclient.go index 631d5eddf5..206fe5a894 100644 --- a/client/asset/btc/rpcclient.go +++ b/client/asset/btc/rpcclient.go @@ -94,7 +94,7 @@ type RawRequester interface { // anylist is a list of RPC parameters to be converted to []json.RawMessage and // sent via RawRequest. -type anylist []interface{} +type anylist []any type rpcCore struct { rpcConfig *RPCConfig @@ -1132,11 +1132,11 @@ func (wc *rpcClient) searchBlockForRedemptions(ctx context.Context, reqs map[out // call is used internally to marshal parameters and send requests to the RPC // server via (*rpcclient.Client).RawRequest. If thing is non-nil, the result // will be marshaled into thing. -func (wc *rpcClient) call(method string, args anylist, thing interface{}) error { +func (wc *rpcClient) call(method string, args anylist, thing any) error { return call(wc.ctx, wc.requester(), method, args, thing) } -func call(ctx context.Context, r RawRequester, method string, args anylist, thing interface{}) error { +func call(ctx context.Context, r RawRequester, method string, args anylist, thing any) error { params := make([]json.RawMessage, 0, len(args)) for i := range args { p, err := json.Marshal(args[i]) diff --git a/client/asset/dcr/config.go b/client/asset/dcr/config.go index 8bcfa2e66e..99cc6f4efb 100644 --- a/client/asset/dcr/config.go +++ b/client/asset/dcr/config.go @@ -81,7 +81,7 @@ func loadRPCConfig(settings map[string]string, network dex.Network) (*rpcConfig, // RPCListen or RPCCert in the specified file, default values will be used. If // there is no error, the module-level chainParams variable will be set // appropriately for the network. -func loadConfig(settings map[string]string, network dex.Network, cfg interface{}) (*chaincfg.Params, error) { +func loadConfig(settings map[string]string, network dex.Network, cfg any) (*chaincfg.Params, error) { if err := config.Unmapify(settings, cfg); err != nil { return nil, fmt.Errorf("error parsing config: %w", err) } diff --git a/client/asset/dcr/dcr.go b/client/asset/dcr/dcr.go index cc14cb3139..96622a944e 100644 --- a/client/asset/dcr/dcr.go +++ b/client/asset/dcr/dcr.go @@ -5521,7 +5521,7 @@ func (dcr *ExchangeWallet) monitorPeers(ctx context.Context) { } func (dcr *ExchangeWallet) emitTipChange(height int64) { - var data interface{} + var data any // stakeInfo, err := dcr.wallet.StakeInfo(dcr.ctx) // if err != nil { // dcr.log.Errorf("Error getting stake info for tip change notification data: %v", err) @@ -5671,7 +5671,7 @@ func (dcr *ExchangeWallet) handleTipChange(ctx context.Context, newTipHash *chai // be determined, as searching just the new tip might result in blocks // being omitted from the search operation. If that happens, cancel all // find redemption requests in queue. - notifyFatalFindRedemptionError := func(s string, a ...interface{}) { + notifyFatalFindRedemptionError := func(s string, a ...any) { dcr.fatalFindRedemptionsError(fmt.Errorf("tipChange handler - "+s, a...), contractOutpoints) } diff --git a/client/asset/dcr/dcr_test.go b/client/asset/dcr/dcr_test.go index 0d102a5192..f482b3225e 100644 --- a/client/asset/dcr/dcr_test.go +++ b/client/asset/dcr/dcr_test.go @@ -2479,7 +2479,7 @@ func TestFundMultiOrder(t *testing.T) { if totalNumCoins != len(node.lockedCoins) { t.Fatalf("%s: expected %d locked coins, got %d", test.name, totalNumCoins, len(node.lockedCoins)) } - lockedCoins := make(map[wire.OutPoint]interface{}) + lockedCoins := make(map[wire.OutPoint]any) for _, coin := range node.lockedCoins { lockedCoins[*coin] = true } diff --git a/client/asset/dcr/rpcwallet.go b/client/asset/dcr/rpcwallet.go index ec123f99a1..46284f7328 100644 --- a/client/asset/dcr/rpcwallet.go +++ b/client/asset/dcr/rpcwallet.go @@ -1099,12 +1099,12 @@ func (w *rpcWallet) SetTxFee(ctx context.Context, feePerKB dcrutil.Amount) error // anylist is a list of RPC parameters to be converted to []json.RawMessage and // sent via nodeRawRequest. -type anylist []interface{} +type anylist []any // rpcClientRawRequest is used to marshal parameters and send requests to the // RPC server via rpcClient.RawRequest. If `thing` is non-nil, the result will // be marshaled into `thing`. -func (w *rpcWallet) rpcClientRawRequest(ctx context.Context, method string, args anylist, thing interface{}) error { +func (w *rpcWallet) rpcClientRawRequest(ctx context.Context, method string, args anylist, thing any) error { params := make([]json.RawMessage, 0, len(args)) for i := range args { p, err := json.Marshal(args[i]) diff --git a/client/asset/eth/contractor.go b/client/asset/eth/contractor.go index f00a0ea31f..5deba2a498 100644 --- a/client/asset/eth/contractor.go +++ b/client/asset/eth/contractor.go @@ -243,7 +243,7 @@ func (c *contractorV0) estimateInitGas(ctx context.Context, n int) (uint64, erro } // estimateGas estimates the gas used to interact with the swap contract. -func (c *contractorV0) estimateGas(ctx context.Context, value *big.Int, method string, args ...interface{}) (uint64, error) { +func (c *contractorV0) estimateGas(ctx context.Context, value *big.Int, method string, args ...any) (uint64, error) { data, err := c.abi.Pack(method, args...) if err != nil { return 0, fmt.Errorf("Pack error: %v", err) @@ -422,7 +422,7 @@ func (c *tokenContractorV0) estimateTransferGas(ctx context.Context, amount *big // estimateGas estimates the gas needed for methods on the ERC20 token contract. // For estimating methods on the swap contract, use (contractorV0).estimateGas. -func (c *tokenContractorV0) estimateGas(ctx context.Context, method string, args ...interface{}) (uint64, error) { +func (c *tokenContractorV0) estimateGas(ctx context.Context, method string, args ...any) (uint64, error) { data, err := erc20.ERC20ABI.Pack(method, args...) if err != nil { return 0, fmt.Errorf("token estimateGas Pack error: %v", err) diff --git a/client/asset/eth/eth.go b/client/asset/eth/eth.go index 6c74078569..7cfd2c492b 100644 --- a/client/asset/eth/eth.go +++ b/client/asset/eth/eth.go @@ -1970,7 +1970,7 @@ func (w *ETHWallet) Swap(swaps *asset.Swaps) ([]asset.Receipt, asset.Coin, uint6 return nil, nil, 0, fmt.Errorf("cannot send swap with with zero fee rate") } - fail := func(s string, a ...interface{}) ([]asset.Receipt, asset.Coin, uint64, error) { + fail := func(s string, a ...any) ([]asset.Receipt, asset.Coin, uint64, error) { return nil, nil, 0, fmt.Errorf(s, a...) } @@ -2057,7 +2057,7 @@ func (w *TokenWallet) Swap(swaps *asset.Swaps) ([]asset.Receipt, asset.Coin, uin return nil, nil, 0, fmt.Errorf("cannot send swap with with zero fee rate") } - fail := func(s string, a ...interface{}) ([]asset.Receipt, asset.Coin, uint64, error) { + fail := func(s string, a ...any) ([]asset.Receipt, asset.Coin, uint64, error) { return nil, nil, 0, fmt.Errorf(s, a...) } diff --git a/client/asset/eth/multirpc.go b/client/asset/eth/multirpc.go index 25ca6be463..164ccd5067 100644 --- a/client/asset/eth/multirpc.go +++ b/client/asset/eth/multirpc.go @@ -995,7 +995,7 @@ func allRPCErrorsAreFails(err error) (discard, propagate, fail bool) { return false, false, true } -func errorFilter(err error, matches ...interface{}) bool { +func errorFilter(err error, matches ...any) bool { errStr := err.Error() for _, mi := range matches { var s string diff --git a/client/asset/eth/node.go b/client/asset/eth/node.go index 2bbb8ed1ec..3e4f25ba2f 100644 --- a/client/asset/eth/node.go +++ b/client/asset/eth/node.go @@ -39,7 +39,7 @@ type ethLogger struct { // New returns a new Logger that has this logger's context plus the given // context. -func (el *ethLogger) New(ctx ...interface{}) log.Logger { +func (el *ethLogger) New(ctx ...any) log.Logger { s := "" for _, v := range ctx { if s == "" { @@ -74,8 +74,8 @@ func (el *ethLogger) GetHandler() log.Handler { // Used during setup in geth when a logger is not supplied. Does nothing here. func (el *ethLogger) SetHandler(h log.Handler) {} -func formatEthLog(msg string, ctx ...interface{}) []interface{} { - msgs := []interface{}{msg, " "} +func formatEthLog(msg string, ctx ...any) []any { + msgs := []any{msg, " "} alternator := 0 for _, v := range ctx { deliminator := "=" @@ -89,32 +89,32 @@ func formatEthLog(msg string, ctx ...interface{}) []interface{} { } // Trace logs at Trace level. -func (el *ethLogger) Trace(msg string, ctx ...interface{}) { +func (el *ethLogger) Trace(msg string, ctx ...any) { el.dl.Trace(formatEthLog(msg, ctx...)...) } // Debug logs at debug level. -func (el *ethLogger) Debug(msg string, ctx ...interface{}) { +func (el *ethLogger) Debug(msg string, ctx ...any) { el.dl.Debug(formatEthLog(msg, ctx...)...) } // Info logs at info level. -func (el *ethLogger) Info(msg string, ctx ...interface{}) { +func (el *ethLogger) Info(msg string, ctx ...any) { el.dl.Info(formatEthLog(msg, ctx...)...) } // Warn logs at warn level. -func (el *ethLogger) Warn(msg string, ctx ...interface{}) { +func (el *ethLogger) Warn(msg string, ctx ...any) { el.dl.Warn(formatEthLog(msg, ctx...)...) } // Error logs at error level. -func (el *ethLogger) Error(msg string, ctx ...interface{}) { +func (el *ethLogger) Error(msg string, ctx ...any) { el.dl.Error(formatEthLog(msg, ctx...)...) } // Crit logs at critical level. -func (el *ethLogger) Crit(msg string, ctx ...interface{}) { +func (el *ethLogger) Crit(msg string, ctx ...any) { el.dl.Critical(formatEthLog(msg, ctx...)...) } diff --git a/client/asset/firo/firo.go b/client/asset/firo/firo.go index 3203c990d5..f8b13646f9 100644 --- a/client/asset/firo/firo.go +++ b/client/asset/firo/firo.go @@ -189,7 +189,7 @@ func NewWallet(cfg *asset.WalletConfig, logger dex.Logger, network dex.Network) // rpcCaller is satisfied by ExchangeWalletFullNode (baseWallet), providing // direct RPC requests. type rpcCaller interface { - CallRPC(method string, args []interface{}, thing interface{}) error + CallRPC(method string, args []any, thing any) error } // privKeyForAddress is Firo's dumpprivkey RPC which calls dumpprivkey once @@ -198,7 +198,7 @@ type rpcCaller interface { func privKeyForAddress(c rpcCaller, addr string) (*btcec.PrivateKey, error) { const methodDumpPrivKey = "dumpprivkey" var privkeyStr string - err := c.CallRPC(methodDumpPrivKey, []interface{}{addr}, &privkeyStr) + err := c.CallRPC(methodDumpPrivKey, []any{addr}, &privkeyStr) if err == nil { // really, expect an error... return nil, errors.New("firo dumpprivkey: no authorization challenge") } @@ -213,7 +213,7 @@ func privKeyForAddress(c rpcCaller, addr string) (*btcec.PrivateKey, error) { auth := errStr[i : i+4] /// fmt.Printf("OTA: %s\n", auth) - err = c.CallRPC(methodDumpPrivKey, []interface{}{addr, auth}, &privkeyStr) + err = c.CallRPC(methodDumpPrivKey, []any{addr, auth}, &privkeyStr) if err != nil { return nil, err } diff --git a/client/asset/interface.go b/client/asset/interface.go index 6c233ac6c5..f7e7a2285b 100644 --- a/client/asset/interface.go +++ b/client/asset/interface.go @@ -310,14 +310,14 @@ type WalletInfo struct { // ConfigOption is a wallet configuration option. type ConfigOption struct { - Key string `json:"key"` - DisplayName string `json:"displayname"` - Description string `json:"description"` - DefaultValue interface{} `json:"default"` + Key string `json:"key"` + DisplayName string `json:"displayname"` + Description string `json:"description"` + DefaultValue any `json:"default"` // If MaxValue/MinValue are set to the string "now" for a date config, the // UI will display the current date. - MaxValue interface{} `json:"max"` - MinValue interface{} `json:"min"` + MaxValue any `json:"max"` + MinValue any `json:"min"` Options map[string]*ConfigOption NoEcho bool `json:"noecho"` IsBoolean bool `json:"isboolean"` @@ -1371,22 +1371,22 @@ type MultiOrder struct { // WalletNotification can be any asynchronous information the wallet needs // to convey. -type WalletNotification interface{} +type WalletNotification any // TipChangeNote is the only required wallet notification. All wallets should // emit a TipChangeNote when a state change occurs that might necessitate swap // progression or new balance checks. type TipChangeNote struct { - AssetID uint32 `json:"assetID"` - Tip uint64 `json:"tip"` - Data interface{} `json:"data"` + AssetID uint32 `json:"assetID"` + Tip uint64 `json:"tip"` + Data any `json:"data"` } // CustomWalletNote is any other information the wallet wishes to convey to // the user. type CustomWalletNote struct { - AssetID uint32 `json:"assetID"` - Payload interface{} `json:"payload"` + AssetID uint32 `json:"assetID"` + Payload any `json:"payload"` } // WalletEmitter handles a channel for wallet notifications and provides methods @@ -1415,13 +1415,13 @@ func (e *WalletEmitter) emit(note WalletNotification) { } // Data sends a CustomWalletNote with the specified data payload. -func (e *WalletEmitter) Data(payload interface{}) { +func (e *WalletEmitter) Data(payload any) { e.emit(&CustomWalletNote{AssetID: e.assetID, Payload: payload}) } // TipChange sends a TipChangeNote with optional extra data. -func (e *WalletEmitter) TipChange(tip uint64, datas ...interface{}) { - var data interface{} +func (e *WalletEmitter) TipChange(tip uint64, datas ...any) { + var data any if len(datas) > 0 { data = datas[0] } diff --git a/client/asset/kvdb/kvdb.go b/client/asset/kvdb/kvdb.go index 5bdf998c5f..1b21201314 100644 --- a/client/asset/kvdb/kvdb.go +++ b/client/asset/kvdb/kvdb.go @@ -117,7 +117,7 @@ type badgerLoggerWrapper struct { var _ badger.Logger = (*badgerLoggerWrapper)(nil) // Warningf -> dex.Logger.Warnf -func (log *badgerLoggerWrapper) Warningf(s string, a ...interface{}) { +func (log *badgerLoggerWrapper) Warningf(s string, a ...any) { log.Warnf(s, a...) } diff --git a/client/asset/ltc/spv.go b/client/asset/ltc/spv.go index ce300fd240..ab6b2a23db 100644 --- a/client/asset/ltc/spv.go +++ b/client/asset/ltc/spv.go @@ -1034,32 +1034,32 @@ type fileLoggerPlus struct { log dex.Logger } -func (f *fileLoggerPlus) Warnf(format string, params ...interface{}) { +func (f *fileLoggerPlus) Warnf(format string, params ...any) { f.log.Warnf(format, params...) f.Logger.Warnf(format, params...) } -func (f *fileLoggerPlus) Errorf(format string, params ...interface{}) { +func (f *fileLoggerPlus) Errorf(format string, params ...any) { f.log.Errorf(format, params...) f.Logger.Errorf(format, params...) } -func (f *fileLoggerPlus) Criticalf(format string, params ...interface{}) { +func (f *fileLoggerPlus) Criticalf(format string, params ...any) { f.log.Criticalf(format, params...) f.Logger.Criticalf(format, params...) } -func (f *fileLoggerPlus) Warn(v ...interface{}) { +func (f *fileLoggerPlus) Warn(v ...any) { f.log.Warn(v...) f.Logger.Warn(v...) } -func (f *fileLoggerPlus) Error(v ...interface{}) { +func (f *fileLoggerPlus) Error(v ...any) { f.log.Error(v...) f.Logger.Error(v...) } -func (f *fileLoggerPlus) Critical(v ...interface{}) { +func (f *fileLoggerPlus) Critical(v ...any) { f.log.Critical(v...) f.Logger.Critical(v...) } diff --git a/client/asset/zec/regnet_test.go b/client/asset/zec/regnet_test.go index 17178c8b8e..f61be4de35 100644 --- a/client/asset/zec/regnet_test.go +++ b/client/asset/zec/regnet_test.go @@ -100,7 +100,7 @@ func TestDeserializeTestnetBlocks(t *testing.T) { t.Fatalf("GetBlockHash(%d) error: %v", testnetOverwinterActivationHeight-1, err) } - mustMarshal := func(thing interface{}) json.RawMessage { + mustMarshal := func(thing any) json.RawMessage { b, err := json.Marshal(thing) if err != nil { t.Fatalf("Failed to marshal %T thing: %v", thing, err) diff --git a/client/asset/zec/shielded_rpc.go b/client/asset/zec/shielded_rpc.go index 3d77e61d5e..0ebdb7d73c 100644 --- a/client/asset/zec/shielded_rpc.go +++ b/client/asset/zec/shielded_rpc.go @@ -52,7 +52,7 @@ type zGetAddressForAccountResult struct { // z_getaddressforaccount account ( ["receiver_type", ...] diversifier_index ) func zGetAddressForAccount(c rpcCaller, acctNumber uint32, addrTypes []string) (unified *zGetAddressForAccountResult, err error) { - return unified, c.CallRPC(methodZGetAddressForAccount, []interface{}{acctNumber, addrTypes}, &unified) + return unified, c.CallRPC(methodZGetAddressForAccount, []any{acctNumber, addrTypes}, &unified) } type unifiedReceivers struct { @@ -63,7 +63,7 @@ type unifiedReceivers struct { // z_listunifiedreceivers unified_address func zGetUnifiedReceivers(c rpcCaller, unifiedAddr string) (receivers *unifiedReceivers, err error) { - return receivers, c.CallRPC(methodZListUnifiedReceivers, []interface{}{unifiedAddr}, &receivers) + return receivers, c.CallRPC(methodZListUnifiedReceivers, []any{unifiedAddr}, &receivers) } func zGetBalanceForAccount(c rpcCaller, acct uint32) (uint64, error) { @@ -76,7 +76,7 @@ func zGetBalanceForAccount(c rpcCaller, acct uint32) (uint64, error) { } `json:"orchard"` } `json:"pools"` } - return res.Pools.Orchard.ValueZat, c.CallRPC(methodZGetBalanceForAccount, []interface{}{acct, minConf}, &res) + return res.Pools.Orchard.ValueZat, c.CallRPC(methodZGetBalanceForAccount, []any{acct, minConf}, &res) } type zValidateAddressResult struct { @@ -92,7 +92,7 @@ type zValidateAddressResult struct { // z_validateaddress "address" func zValidateAddress(c rpcCaller, addr string) (res *zValidateAddressResult, err error) { - return res, c.CallRPC(methodZValidateAddress, []interface{}{addr}, &res) + return res, c.CallRPC(methodZValidateAddress, []any{addr}, &res) } type zSendManyRecipient struct { @@ -124,7 +124,7 @@ const ( // z_sendmany "fromaddress" [{"address":... ,"amount":...},...] ( minconf ) ( fee ) ( privacyPolicy ) func zSendMany(c rpcCaller, fromAddress string, recips []*zSendManyRecipient, priv privacyPolicy) (operationID string, err error) { const minConf, fee = 1, 0.00001 - return operationID, c.CallRPC(methodZSendMany, []interface{}{fromAddress, recips, minConf, fee, priv}, &operationID) + return operationID, c.CallRPC(methodZSendMany, []any{fromAddress, recips, minConf, fee, priv}, &operationID) } type operationStatus struct { @@ -159,7 +159,7 @@ const ErrEmptyOpResults = dex.ErrorKind("no z_getoperationstatus results") // z_getoperationresult (["operationid", ... ]) func zGetOperationResult(c rpcCaller, operationID string) (s *operationStatus, err error) { var res []*operationStatus - if err := c.CallRPC(methodZGetOperationResult, []interface{}{[]string{operationID}}, &res); err != nil { + if err := c.CallRPC(methodZGetOperationResult, []any{[]string{operationID}}, &res); err != nil { return nil, err } if len(res) == 0 { diff --git a/client/asset/zec/zec.go b/client/asset/zec/zec.go index 701a9074cc..ec8bf6f50a 100644 --- a/client/asset/zec/zec.go +++ b/client/asset/zec/zec.go @@ -247,7 +247,7 @@ func NewWallet(cfg *asset.WalletConfig, logger dex.Logger, net dex.Network) (ass } type rpcCaller interface { - CallRPC(method string, args []interface{}, thing interface{}) error + CallRPC(method string, args []any, thing any) error } type zecWallet struct { diff --git a/client/comms/wsconn_test.go b/client/comms/wsconn_test.go index d507534b37..6017bf7774 100644 --- a/client/comms/wsconn_test.go +++ b/client/comms/wsconn_test.go @@ -24,7 +24,7 @@ import ( var tLogger = dex.StdOutLogger("conn_TEST", dex.LevelTrace) -func makeRequest(id uint64, route string, msg interface{}) *msgjson.Message { +func makeRequest(id uint64, route string, msg any) *msgjson.Message { req, _ := msgjson.NewRequest(id, route, msg) return req } @@ -62,7 +62,7 @@ func TestWsConn(t *testing.T) { upgrader := websocket.Upgrader{} pingCh := make(chan struct{}) - readPumpCh := make(chan interface{}) + readPumpCh := make(chan any) writePumpCh := make(chan *msgjson.Message) ctx, cancel := context.WithCancel(context.Background()) defer cancel() diff --git a/client/core/account.go b/client/core/account.go index b32b6e5468..96f0a56dac 100644 --- a/client/core/account.go +++ b/client/core/account.go @@ -352,7 +352,7 @@ func (c *Core) UpdateCert(host string, cert []byte) error { // UpdateDEXHost updates the host for a connection to a dex. The dex at oldHost // and newHost must be the same dex, which means that the dex at both hosts use // the same public key. -func (c *Core) UpdateDEXHost(oldHost, newHost string, appPW []byte, certI interface{}) (*Exchange, error) { +func (c *Core) UpdateDEXHost(oldHost, newHost string, appPW []byte, certI any) (*Exchange, error) { if oldHost == newHost { return nil, errors.New("old host and new host are the same") } diff --git a/client/core/core.go b/client/core/core.go index f030536dbc..47e4c34e5e 100644 --- a/client/core/core.go +++ b/client/core/core.go @@ -735,7 +735,7 @@ func (c *Core) tryCancelTrade(dc *dexConnection, tracker *trackedTrade) error { // signAndRequest signs and sends the request, unmarshaling the response into // the provided interface. -func (dc *dexConnection) signAndRequest(signable msgjson.Signable, route string, result interface{}, timeout time.Duration) error { +func (dc *dexConnection) signAndRequest(signable msgjson.Signable, route string, result any, timeout time.Duration) error { if dc.acct.locked() { return fmt.Errorf("cannot sign: %s account locked", dc.acct.host) } @@ -2539,7 +2539,7 @@ func (c *Core) createWalletOrToken(crypter encrypt.Crypter, walletPW []byte, for } } - initErr := func(s string, a ...interface{}) (*xcWallet, error) { + initErr := func(s string, a ...any) (*xcWallet, error) { _ = wallet.Lock(2 * time.Second) // just try, but don't confuse the user with an error wallet.Disconnect() return nil, fmt.Errorf(s, a...) @@ -3766,7 +3766,7 @@ func (c *Core) AutoWalletConfig(assetID uint32, walletType string) (map[string]s // tempDexConnection creates an unauthenticated dexConnection. The caller must // dc.connMaster.Disconnect when done with the connection. -func (c *Core) tempDexConnection(dexAddr string, certI interface{}) (*dexConnection, error) { +func (c *Core) tempDexConnection(dexAddr string, certI any) (*dexConnection, error) { host, err := addrHost(dexAddr) if err != nil { return nil, newError(addressParseErr, "error parsing address: %w", err) @@ -3799,7 +3799,7 @@ func (c *Core) tempDexConnection(dexAddr string, certI interface{}) (*dexConnect // since a DEX connection is already established and the config is accessible // via the User or Exchanges methods. A TLS certificate, certI, can be provided // as either a string filename, or []byte file contents. -func (c *Core) GetDEXConfig(dexAddr string, certI interface{}) (*Exchange, error) { +func (c *Core) GetDEXConfig(dexAddr string, certI any) (*Exchange, error) { dc, err := c.tempDexConnection(dexAddr, certI) if err != nil { return nil, err @@ -3814,7 +3814,7 @@ func (c *Core) GetDEXConfig(dexAddr string, certI interface{}) (*Exchange, error // activity without setting up account keys or communicating account identity // with the DEX. DiscoverAccount, Post Bond or Register (deprecated) may be used // to set up a trading account for this DEX if required. -func (c *Core) AddDEX(dexAddr string, certI interface{}) error { +func (c *Core) AddDEX(dexAddr string, certI any) error { if !c.IsInitialized() { // TODO: Allow adding view-only DEX without init. return fmt.Errorf("cannot register DEX because app has not been initialized") } @@ -4040,7 +4040,7 @@ func (c *Core) upgradeConnection(dc *dexConnection) { // The Tier and BondsPending fields may be consulted to determine if it is still // necessary to PostBond (i.e. Tier == 0 && !BondsPending) before trading. The // Connected field should be consulted first. -func (c *Core) DiscoverAccount(dexAddr string, appPW []byte, certI interface{}) (*Exchange, bool, error) { +func (c *Core) DiscoverAccount(dexAddr string, appPW []byte, certI any) (*Exchange, bool, error) { if !c.IsInitialized() { return nil, false, fmt.Errorf("cannot register DEX because app has not been initialized") } @@ -4117,7 +4117,7 @@ func (c *Core) DiscoverAccount(dexAddr string, appPW []byte, certI interface{}) // pay the registration fee for a certain asset. The dex host is required // because the dex server is used as a fallback to determine the current // fee rate in case the client wallet is unable to do it. -func (c *Core) EstimateRegistrationTxFee(host string, certI interface{}, assetID uint32) (uint64, error) { +func (c *Core) EstimateRegistrationTxFee(host string, certI any, assetID uint32) (uint64, error) { wallet, err := c.connectedWallet(assetID) if err != nil { return 0, err @@ -7528,7 +7528,7 @@ func (c *Core) loadDBTrades(dc *dexConnection) error { // readyToTick will be set to true, even if the funding coins for the order could // not be found or the audit info could not be loaded. func (c *Core) resumeTrade(tracker *trackedTrade, crypter encrypt.Crypter, failed map[uint32]bool, relocks assetMap) bool { - notifyErr := func(tracker *trackedTrade, topic Topic, args ...interface{}) { + notifyErr := func(tracker *trackedTrade, topic Topic, args ...any) { subject, detail := c.formatDetails(topic, args...) c.notify(newOrderNote(topic, subject, detail, db.ErrorLevel, tracker.coreOrderInternal())) } @@ -7848,7 +7848,7 @@ func (c *Core) reReserveFunding(w *xcWallet) { continue } - notifyErr := func(topic Topic, args ...interface{}) { + notifyErr := func(topic Topic, args ...any) { subject, detail := c.formatDetails(topic, args...) c.notify(newOrderNote(topic, subject, detail, db.ErrorLevel, tracker.coreOrderInternal())) } @@ -9528,7 +9528,7 @@ func stampAndSign(privKey *secp256k1.PrivateKey, payload msgjson.Stampable) { // the response into the provided interface. // TODO: Modify to accept a context.Context argument so callers can pass core's // context to break out of the reply wait when Core starts shutting down. -func sendRequest(conn comms.WsConn, route string, request, response interface{}, timeout time.Duration) error { +func sendRequest(conn comms.WsConn, route string, request, response any, timeout time.Duration) error { reqMsg, err := msgjson.NewRequest(conn.NextID(), route, request) if err != nil { return fmt.Errorf("error encoding %q request: %w", route, err) @@ -9670,7 +9670,7 @@ func validateOrderResponse(dc *dexConnection, result *msgjson.OrderResult, ord o // string, it will be treated as a filepath and the raw file contents returned. // if certI is already a []byte, it is presumed to be the raw file contents, and // is returned unmodified. -func parseCert(host string, certI interface{}, net dex.Network) ([]byte, error) { +func parseCert(host string, certI any, net dex.Network) ([]byte, error) { switch c := certI.(type) { case string: if len(c) == 0 { @@ -9915,7 +9915,7 @@ func deleteMatchFn(matchesFileStr string) (perMatchFn func(*db.MetaMatch, bool) return nil, nil, fmt.Errorf("error writing matches CSV: %v", err) } return func(mtch *db.MetaMatch, isSell bool) error { - numToStr := func(n interface{}) string { + numToStr := func(n any) string { return fmt.Sprintf("%d", n) } base, quote := mtch.MetaData.Base, mtch.MetaData.Quote diff --git a/client/core/core_test.go b/client/core/core_test.go index a0a4addb68..95614ec14d 100644 --- a/client/core/core_test.go +++ b/client/core/core_test.go @@ -2012,7 +2012,7 @@ func TestRegister(t *testing.T) { _, err = tCore.Register(form) } - getNotification := func(tag string) interface{} { + getNotification := func(tag string) any { t.Helper() select { case n := <-ch.C: @@ -7567,7 +7567,7 @@ func TestHandlePenaltyMsg(t *testing.T) { tests := []struct { name string key *secp256k1.PrivateKey - payload interface{} + payload any wantErr bool }{{ name: "ok", diff --git a/client/core/errors.go b/client/core/errors.go index eec2acdb80..f5de3a1f8a 100644 --- a/client/core/errors.go +++ b/client/core/errors.go @@ -76,7 +76,7 @@ func (e *Error) Unwrap() error { } // newError is a constructor for a new Error. -func newError(code int, s string, a ...interface{}) error { +func newError(code int, s string, a ...any) error { return &Error{ code: code, err: fmt.Errorf(s, a...), // s may contain a %w verb to wrap an error diff --git a/client/core/exchangeratefetcher.go b/client/core/exchangeratefetcher.go index b7597b8650..011fbf1e48 100644 --- a/client/core/exchangeratefetcher.go +++ b/client/core/exchangeratefetcher.go @@ -231,7 +231,7 @@ func coinpapSlug(symbol, name string) string { return strings.ToLower(strings.ReplaceAll(slug, " ", "-")) } -func getRates(ctx context.Context, url string, thing interface{}) error { +func getRates(ctx context.Context, url string, thing any) error { req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { return err diff --git a/client/core/notification.go b/client/core/notification.go index 388eff0fa4..d47711dc16 100644 --- a/client/core/notification.go +++ b/client/core/notification.go @@ -138,7 +138,7 @@ func (c *Core) AckNotes(ids []dex.Bytes) { } } -func (c *Core) formatDetails(topic Topic, args ...interface{}) (translatedSubject, details string) { +func (c *Core) formatDetails(topic Topic, args ...any) (translatedSubject, details string) { trans, found := c.locale[topic] if !found { c.log.Errorf("No translation found for topic %q", topic) diff --git a/client/core/simnet_trade.go b/client/core/simnet_trade.go index 1cee1d5369..f3d6fab1e3 100644 --- a/client/core/simnet_trade.go +++ b/client/core/simnet_trade.go @@ -96,7 +96,7 @@ type assetConfig struct { id uint32 symbol string conversionFactor uint64 - valFmt func(interface{}) string + valFmt func(any) string isToken bool } @@ -201,8 +201,8 @@ func RunSimulationTest(cfg *SimulationConfig) error { if cfg.RegistrationAsset == cfg.QuoteSymbol { regAsset = quoteID } - valFormatter := func(valFmt func(uint64) string) func(interface{}) string { - return func(vi interface{}) string { + valFormatter := func(valFmt func(uint64) string) func(any) string { + return func(vi any) string { var vu uint64 var negative bool switch vt := vi.(type) { diff --git a/client/core/trade.go b/client/core/trade.go index 177aacdcb9..eeb6f1a8fd 100644 --- a/client/core/trade.go +++ b/client/core/trade.go @@ -265,7 +265,7 @@ type trackedTrade struct { lockTimeTaker time.Duration lockTimeMaker time.Duration notify func(Notification) - formatDetails func(Topic, ...interface{}) (string, string) + formatDetails func(Topic, ...any) (string, string) fromAssetID uint32 // wallets.fromWallet.AssetID options map[string]string // metaData.Options (immutable) for Redeem and Swap redemptionReserves uint64 // metaData.RedemptionReserves (immutable) @@ -292,7 +292,7 @@ type trackedTrade struct { // newTrackedTrade is a constructor for a trackedTrade. func newTrackedTrade(dbOrder *db.MetaOrder, preImg order.Preimage, dc *dexConnection, lockTimeTaker, lockTimeMaker time.Duration, db db.DB, latencyQ *wait.TickerQueue, wallets *walletSet, - coins asset.Coins, notify func(Notification), formatDetails func(Topic, ...interface{}) (string, string)) *trackedTrade { + coins asset.Coins, notify func(Notification), formatDetails func(Topic, ...any) (string, string)) *trackedTrade { fromID := dbOrder.Order.Quote() if dbOrder.Order.Trade().Sell { diff --git a/client/core/types.go b/client/core/types.go index 9fa94d278f..68cedfb329 100644 --- a/client/core/types.go +++ b/client/core/types.go @@ -46,12 +46,12 @@ type errorSet struct { } // newErrorSet constructs an error set with a prefix. -func newErrorSet(s string, a ...interface{}) *errorSet { +func newErrorSet(s string, a ...any) *errorSet { return &errorSet{prefix: fmt.Sprintf(s, a...)} } // add adds the message to the slice as an error and returns the errorSet. -func (set *errorSet) add(s string, a ...interface{}) *errorSet { +func (set *errorSet) add(s string, a ...any) *errorSet { set.errs = append(set.errs, fmt.Errorf(s, a...)) return set } @@ -214,7 +214,7 @@ type PostBondForm struct { // Cert is needed if posting bond to a new DEX. Cert can be a string, which // is interpreted as a filepath, or a []byte, which is interpreted as the // file contents of the certificate. - Cert interface{} `json:"cert"` + Cert any `json:"cert"` } // RegisterForm is information necessary to register an account on a DEX. Old @@ -226,7 +226,7 @@ type RegisterForm struct { Asset *uint32 `json:"assetID,omitempty"` // do not default to 0 // Cert can be a string, which is interpreted as a filepath, or a []byte, // which is interpreted as the file contents of the certificate. - Cert interface{} `json:"cert"` + Cert any `json:"cert"` } // Match represents a match on an order. An order may have many matches. @@ -731,10 +731,10 @@ const ( // BookUpdate is an order book update. type BookUpdate struct { - Action string `json:"action"` - Host string `json:"host"` - MarketID string `json:"marketID"` - Payload interface{} `json:"payload"` + Action string `json:"action"` + Host string `json:"host"` + MarketID string `json:"marketID"` + Payload any `json:"payload"` } type CandlesPayload struct { diff --git a/client/db/test/dbtest.go b/client/db/test/dbtest.go index e030b1b7e1..2824d58e99 100644 --- a/client/db/test/dbtest.go +++ b/client/db/test/dbtest.go @@ -171,7 +171,7 @@ func RandomNotification(maxTime uint64) *db.Notification { type testKiller interface { Helper() - Fatalf(string, ...interface{}) + Fatalf(string, ...any) } // MustCompareMatchAuth ensures the two MatchAuth are identical, calling the diff --git a/client/mm/mm.go b/client/mm/mm.go index 0968780fc1..074e72bc57 100644 --- a/client/mm/mm.go +++ b/client/mm/mm.go @@ -224,7 +224,7 @@ func (m *MarketMaker) loginAndUnlockWallets(pw []byte, cfgs []*BotConfig) error if err != nil { return fmt.Errorf("failed to login: %w", err) } - unlocked := make(map[uint32]interface{}) + unlocked := make(map[uint32]any) for _, cfg := range cfgs { if _, done := unlocked[cfg.BaseAsset]; !done { err := m.core.OpenWallet(cfg.BaseAsset, pw) diff --git a/client/mm/price_oracle.go b/client/mm/price_oracle.go index e989683e8f..7a031a3000 100644 --- a/client/mm/price_oracle.go +++ b/client/mm/price_oracle.go @@ -206,7 +206,7 @@ func coinpapSlug(symbol, name string) string { return strings.ToLower(strings.ReplaceAll(slug, " ", "-")) } -func getRates(ctx context.Context, url string, thing interface{}) error { +func getRates(ctx context.Context, url string, thing any) error { req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { return err diff --git a/client/orderbook/orderbook.go b/client/orderbook/orderbook.go index e43af5b177..9653cb961a 100644 --- a/client/orderbook/orderbook.go +++ b/client/orderbook/orderbook.go @@ -47,7 +47,7 @@ type RemoteOrderBook interface { // CachedOrderNote represents a cached order not entry. type cachedOrderNote struct { Route string - OrderNote interface{} + OrderNote any } // rateSell provides the rate and book side information about an order that is @@ -154,7 +154,7 @@ func (ob *OrderBook) setSeq(seq uint64) { } // cacheOrderNote caches an order note. -func (ob *OrderBook) cacheOrderNote(route string, entry interface{}) error { +func (ob *OrderBook) cacheOrderNote(route string, entry any) error { note := new(cachedOrderNote) switch route { diff --git a/client/rpcserver/handlers.go b/client/rpcserver/handlers.go index c4a6145c4a..b68cd749d2 100644 --- a/client/rpcserver/handlers.go +++ b/client/rpcserver/handlers.go @@ -75,7 +75,7 @@ const ( ) // createResponse creates a msgjson response payload. -func createResponse(op string, res interface{}, resErr *msgjson.Error) *msgjson.ResponsePayload { +func createResponse(op string, res any, resErr *msgjson.Error) *msgjson.ResponsePayload { encodedRes, err := json.Marshal(res) if err != nil { err := fmt.Errorf("unable to marshal data for %s: %w", op, err) @@ -488,9 +488,9 @@ func handlePostBond(s *RPCServer, params *RawParams) *msgjson.ResponsePayload { // handleExchanges handles requests for exchanges. It takes no arguments and // returns a map of exchanges. func handleExchanges(s *RPCServer, _ *RawParams) *msgjson.ResponsePayload { - // Convert something to a map[string]interface{}. - convM := func(in interface{}) map[string]interface{} { - var m map[string]interface{} + // Convert something to a map[string]any. + convM := func(in any) map[string]any { + var m map[string]any b, err := json.Marshal(in) if err != nil { panic(err) diff --git a/client/rpcserver/handlers_test.go b/client/rpcserver/handlers_test.go index b418d29f30..ab94f4b9a0 100644 --- a/client/rpcserver/handlers_test.go +++ b/client/rpcserver/handlers_test.go @@ -28,7 +28,7 @@ func init() { }) } -func verifyResponse(payload *msgjson.ResponsePayload, res interface{}, wantErrCode int) error { +func verifyResponse(payload *msgjson.ResponsePayload, res any, wantErrCode int) error { if wantErrCode != -1 { if payload.Error == nil { return errors.New("no error") @@ -98,7 +98,7 @@ type Dummy struct { func TestCreateResponse(t *testing.T) { tests := []struct { name string - res interface{} + res any resErr *msgjson.Error wantErrCode int }{{ diff --git a/client/rpcserver/rpcserver.go b/client/rpcserver/rpcserver.go index 1bae53355c..4991e5a59d 100644 --- a/client/rpcserver/rpcserver.go +++ b/client/rpcserver/rpcserver.go @@ -62,14 +62,14 @@ type clientCore interface { Cancel(orderID dex.Bytes) error CloseWallet(assetID uint32) error CreateWallet(appPass, walletPass []byte, form *core.WalletForm) error - DiscoverAccount(dexAddr string, pass []byte, certI interface{}) (*core.Exchange, bool, error) + DiscoverAccount(dexAddr string, pass []byte, certI any) (*core.Exchange, bool, error) Exchanges() (exchanges map[string]*core.Exchange) InitializeClient(appPass, seed []byte) error Login(appPass []byte) error Logout() error OpenWallet(assetID uint32, appPass []byte) error ToggleWalletStatus(assetID uint32, disable bool) error - GetDEXConfig(dexAddr string, certI interface{}) (*core.Exchange, error) + GetDEXConfig(dexAddr string, certI any) (*core.Exchange, error) Register(form *core.RegisterForm) (*core.RegisterResult, error) // V0PURGE PostBond(form *core.PostBondForm) (*core.PostBondResult, error) UpdateBondOptions(form *core.BondOptionsForm) error @@ -137,13 +137,13 @@ func genCertPair(certFile, keyFile string, hosts []string) error { // writeJSON marshals the provided interface and writes the bytes to the // ResponseWriter. The response code is assumed to be StatusOK. -func writeJSON(w http.ResponseWriter, thing interface{}) { +func writeJSON(w http.ResponseWriter, thing any) { writeJSONWithStatus(w, thing, http.StatusOK) } // writeJSONWithStatus marshals the provided interface and writes the bytes to // the ResponseWriter with the specified response code. -func writeJSONWithStatus(w http.ResponseWriter, thing interface{}, code int) { +func writeJSONWithStatus(w http.ResponseWriter, thing any, code int) { w.Header().Set("Content-Type", "application/json; charset=utf-8") b, err := json.Marshal(thing) if err != nil { diff --git a/client/rpcserver/rpcserver_test.go b/client/rpcserver/rpcserver_test.go index e15afb4429..c75f63ada6 100644 --- a/client/rpcserver/rpcserver_test.go +++ b/client/rpcserver/rpcserver_test.go @@ -127,7 +127,7 @@ func (c *TCore) ToggleWalletStatus(assetID uint32, disable bool) error { func (c *TCore) RescanWallet(assetID uint32, force bool) error { return c.rescanWalletErr } -func (c *TCore) GetDEXConfig(dexAddr string, certI interface{}) (*core.Exchange, error) { +func (c *TCore) GetDEXConfig(dexAddr string, certI any) (*core.Exchange, error) { return c.dexExchange, c.getDEXConfigErr } func (c *TCore) Register(*core.RegisterForm) (*core.RegisterResult, error) { @@ -157,7 +157,7 @@ func (c *TCore) Send(pw []byte, assetID uint32, value uint64, addr string, subtr func (c *TCore) ExportSeed(pw []byte) ([]byte, error) { return c.exportSeed, c.exportSeedErr } -func (c *TCore) DiscoverAccount(dexAddr string, pass []byte, certI interface{}) (*core.Exchange, bool, error) { +func (c *TCore) DiscoverAccount(dexAddr string, pass []byte, certI any) (*core.Exchange, bool, error) { return c.dexExchange, false, c.discoverAcctErr } func (c *TCore) DeleteArchivedRecords(olderThan *time.Time, matchesFileStr, ordersFileStr string) (int, error) { diff --git a/client/rpcserver/types.go b/client/rpcserver/types.go index 344b41b48c..7ad43bab62 100644 --- a/client/rpcserver/types.go +++ b/client/rpcserver/types.go @@ -110,7 +110,7 @@ type match struct { type discoverAcctForm struct { addr string appPass encode.PassBytes - cert interface{} + cert any } // openWalletForm is information necessary to open a wallet. diff --git a/client/webserver/http.go b/client/webserver/http.go index d132a4130e..a470230f29 100644 --- a/client/webserver/http.go +++ b/client/webserver/http.go @@ -36,7 +36,7 @@ const ( ) // sendTemplate processes the template and sends the result. -func (s *WebServer) sendTemplate(w http.ResponseWriter, tmplID string, data interface{}) { +func (s *WebServer) sendTemplate(w http.ResponseWriter, tmplID string, data any) { page, err := s.html.exec(tmplID, data) if err != nil { log.Errorf("template exec error for %s: %v", tmplID, err) diff --git a/client/webserver/live_test.go b/client/webserver/live_test.go index 6b3de8b132..e98f2374bd 100644 --- a/client/webserver/live_test.go +++ b/client/webserver/live_test.go @@ -605,14 +605,14 @@ func (c *TCore) InitializeClient(pw, seed []byte) error { c.inited = true return nil } -func (c *TCore) GetDEXConfig(host string, certI interface{}) (*core.Exchange, error) { +func (c *TCore) GetDEXConfig(host string, certI any) (*core.Exchange, error) { if xc := tExchanges[host]; xc != nil { return xc, nil } return tExchanges[firstDEX], nil } -func (c *TCore) AddDEX(dexAddr string, certI interface{}) error { +func (c *TCore) AddDEX(dexAddr string, certI any) error { randomDelay() if initErrors { return fmt.Errorf("forced init error") @@ -621,7 +621,7 @@ func (c *TCore) AddDEX(dexAddr string, certI interface{}) error { } // DiscoverAccount - use secondDEX = "thisdexwithalongname.com" to get paid = true. -func (c *TCore) DiscoverAccount(dexAddr string, pw []byte, certI interface{}) (*core.Exchange, bool, error) { +func (c *TCore) DiscoverAccount(dexAddr string, pw []byte, certI any) (*core.Exchange, bool, error) { xc := tExchanges[dexAddr] if xc == nil { xc = tExchanges[firstDEX] @@ -655,7 +655,7 @@ func (c *TCore) PostBond(form *core.PostBondForm) (*core.PostBondResult, error) func (c *TCore) UpdateBondOptions(form *core.BondOptionsForm) error { return nil } -func (c *TCore) EstimateRegistrationTxFee(host string, certI interface{}, assetID uint32) (uint64, error) { +func (c *TCore) EstimateRegistrationTxFee(host string, certI any, assetID uint32) (uint64, error) { xc := tExchanges[host] if xc == nil { xc = tExchanges[firstDEX] @@ -1946,7 +1946,7 @@ func (c *TCore) RecoverWallet(uint32, []byte, bool) error { func (c *TCore) UpdateCert(string, []byte) error { return nil } -func (c *TCore) UpdateDEXHost(string, string, []byte, interface{}) (*core.Exchange, error) { +func (c *TCore) UpdateDEXHost(string, string, []byte, any) (*core.Exchange, error) { return nil, nil } func (c *TCore) WalletRestorationInfo(pw []byte, assetID uint32) ([]*asset.WalletRestoration, error) { diff --git a/client/webserver/template.go b/client/webserver/template.go index 39421fb971..48b8210392 100644 --- a/client/webserver/template.go +++ b/client/webserver/template.go @@ -158,7 +158,7 @@ func (t *templates) buildErr() error { // // DRAFT NOTE: Might consider writing directly to the the buffer here. Could // still set the error code appropriately. -func (t *templates) exec(name string, data interface{}) (string, error) { +func (t *templates) exec(name string, data any) (string, error) { tmpl, found := t.templates[name] if !found { return "", fmt.Errorf("template %q not found", name) diff --git a/client/webserver/webserver.go b/client/webserver/webserver.go index 0873500bf9..739b5f70de 100644 --- a/client/webserver/webserver.go +++ b/client/webserver/webserver.go @@ -115,9 +115,9 @@ type clientCore interface { NewDepositAddress(assetID uint32) (string, error) AutoWalletConfig(assetID uint32, walletType string) (map[string]string, error) User() *core.User - GetDEXConfig(dexAddr string, certI interface{}) (*core.Exchange, error) - AddDEX(dexAddr string, certI interface{}) error - DiscoverAccount(dexAddr string, pass []byte, certI interface{}) (*core.Exchange, bool, error) + GetDEXConfig(dexAddr string, certI any) (*core.Exchange, error) + AddDEX(dexAddr string, certI any) error + DiscoverAccount(dexAddr string, pass []byte, certI any) (*core.Exchange, bool, error) SupportedAssets() map[uint32]*core.SupportedAsset Send(pw []byte, assetID uint32, value uint64, address string, subtract bool) (asset.Coin, error) Trade(pw []byte, form *core.TradeForm) (*core.Order, error) @@ -136,13 +136,13 @@ type clientCore interface { ExportSeed(pw []byte) ([]byte, error) PreOrder(*core.TradeForm) (*core.OrderEstimate, error) WalletLogFilePath(assetID uint32) (string, error) - EstimateRegistrationTxFee(host string, certI interface{}, assetID uint32) (uint64, error) + EstimateRegistrationTxFee(host string, certI any, assetID uint32) (uint64, error) BondsFeeBuffer(assetID uint32) (uint64, error) PreAccelerateOrder(oidB dex.Bytes) (*core.PreAccelerate, error) AccelerateOrder(pw []byte, oidB dex.Bytes, newFeeRate uint64) (string, error) AccelerationEstimate(oidB dex.Bytes, newFeeRate uint64) (uint64, error) UpdateCert(host string, cert []byte) error - UpdateDEXHost(oldHost, newHost string, appPW []byte, certI interface{}) (*core.Exchange, error) + UpdateDEXHost(oldHost, newHost string, appPW []byte, certI any) (*core.Exchange, error) WalletRestorationInfo(pw []byte, assetID uint32) ([]*asset.WalletRestoration, error) ToggleRateSourceStatus(src string, disable bool) error FiatRateSources() map[string]bool @@ -835,7 +835,7 @@ func (s *WebServer) readNotifications(ctx context.Context) { } // readPost unmarshals the request body into the provided interface. -func readPost(w http.ResponseWriter, r *http.Request, thing interface{}) bool { +func readPost(w http.ResponseWriter, r *http.Request, thing any) bool { body, err := io.ReadAll(r.Body) r.Body.Close() if err != nil { @@ -1004,13 +1004,13 @@ func fileServer(r chi.Router, pathPrefix, siteDir, subDir, forceContentType stri // writeJSON marshals the provided interface and writes the bytes to the // ResponseWriter. The response code is assumed to be StatusOK. -func writeJSON(w http.ResponseWriter, thing interface{}, indent bool) { +func writeJSON(w http.ResponseWriter, thing any, indent bool) { writeJSONWithStatus(w, thing, http.StatusOK, indent) } // writeJSON writes marshals the provided interface and writes the bytes to the // ResponseWriter with the specified response code. -func writeJSONWithStatus(w http.ResponseWriter, thing interface{}, code int, indent bool) { +func writeJSONWithStatus(w http.ResponseWriter, thing any, code int, indent bool) { w.Header().Set("Content-Type", "application/json; charset=utf-8") b, err := json.Marshal(thing) if err != nil { @@ -1036,6 +1036,6 @@ type chiLogger struct { dex.Logger } -func (l *chiLogger) Print(v ...interface{}) { +func (l *chiLogger) Print(v ...any) { l.Trace(v...) } diff --git a/client/webserver/webserver_test.go b/client/webserver/webserver_test.go index 944515dfaa..4f18d19689 100644 --- a/client/webserver/webserver_test.go +++ b/client/webserver/webserver_test.go @@ -91,13 +91,13 @@ type TCore struct { func (c *TCore) Network() dex.Network { return dex.Mainnet } func (c *TCore) Exchanges() map[string]*core.Exchange { return nil } func (c *TCore) Exchange(host string) (*core.Exchange, error) { return nil, nil } -func (c *TCore) GetDEXConfig(dexAddr string, certI interface{}) (*core.Exchange, error) { +func (c *TCore) GetDEXConfig(dexAddr string, certI any) (*core.Exchange, error) { return nil, c.getDEXConfigErr // TODO along with test for apiUser / Exchanges() / User() } -func (c *TCore) AddDEX(dexAddr string, certI interface{}) error { +func (c *TCore) AddDEX(dexAddr string, certI any) error { return nil } -func (c *TCore) DiscoverAccount(dexAddr string, pw []byte, certI interface{}) (*core.Exchange, bool, error) { +func (c *TCore) DiscoverAccount(dexAddr string, pw []byte, certI any) (*core.Exchange, bool, error) { return nil, false, nil } func (c *TCore) Register(r *core.RegisterForm) (*core.RegisterResult, error) { return nil, c.regErr } @@ -107,7 +107,7 @@ func (c *TCore) PostBond(r *core.PostBondForm) (*core.PostBondResult, error) { func (c *TCore) UpdateBondOptions(form *core.BondOptionsForm) error { return c.postBondErr } -func (c *TCore) EstimateRegistrationTxFee(host string, certI interface{}, assetID uint32) (uint64, error) { +func (c *TCore) EstimateRegistrationTxFee(host string, certI any, assetID uint32) (uint64, error) { return 0, nil } func (c *TCore) BondsFeeBuffer(assetID uint32) (uint64, error) { @@ -259,7 +259,7 @@ func (c *TCore) RecoverWallet(uint32, []byte, bool) error { func (c *TCore) UpdateCert(string, []byte) error { return nil } -func (c *TCore) UpdateDEXHost(string, string, []byte, interface{}) (*core.Exchange, error) { +func (c *TCore) UpdateDEXHost(string, string, []byte, any) (*core.Exchange, error) { return nil, nil } func (c *TCore) WalletRestorationInfo(pw []byte, assetID uint32) ([]*asset.WalletRestoration, error) { @@ -398,7 +398,7 @@ func newTServer(t *testing.T, start bool) (*WebServer, *TCore, func()) { return s, c, shutdown } -func ensureResponse(t *testing.T, f func(w http.ResponseWriter, r *http.Request), want string, reader *TReader, writer *TWriter, body interface{}, cookies map[string]string) { +func ensureResponse(t *testing.T, f func(w http.ResponseWriter, r *http.Request), want string, reader *TReader, writer *TWriter, body any, cookies map[string]string) { t.Helper() var err error reader.msg, err = json.Marshal(body) @@ -496,7 +496,7 @@ func TestConnectBindError(t *testing.T) { func TestAPIRegister(t *testing.T) { writer := new(TWriter) - var body interface{} + var body any reader := new(TReader) s, tCore, shutdown := newTServer(t, false) defer shutdown() @@ -531,7 +531,7 @@ func TestAPIRegister(t *testing.T) { func TestAPILogin(t *testing.T) { writer := new(TWriter) - var body interface{} + var body any reader := new(TReader) s, tCore, shutdown := newTServer(t, false) defer shutdown() @@ -568,7 +568,7 @@ func TestAPISendAndAPIWithdraw(t *testing.T) { func testAPISendAndAPIWithdraw(t *testing.T, withdraw bool) { writer := new(TWriter) - var body interface{} + var body any reader := new(TReader) s, tCore, shutdown := newTServer(t, false) defer shutdown() @@ -626,7 +626,7 @@ func testAPISendAndAPIWithdraw(t *testing.T, withdraw bool) { func TestAPIInit(t *testing.T) { writer := new(TWriter) - var body interface{} + var body any reader := new(TReader) s, tCore, shutdown := newTServer(t, false) defer shutdown() @@ -661,7 +661,7 @@ func TestAPIInit(t *testing.T) { func TestAPINewWallet(t *testing.T) { writer := new(TWriter) - var body interface{} + var body any reader := new(TReader) s, tCore, shutdown := newTServer(t, false) defer shutdown() @@ -776,7 +776,7 @@ func TestGetOrderIDCtx(t *testing.T) { } // Test some negative paths - for name, v := range map[string]interface{}{ + for name, v := range map[string]any{ "nil": nil, "int": 5, "wrong length": "abc", diff --git a/client/websocket/websocket.go b/client/websocket/websocket.go index 7097bc2c94..1b5dd76793 100644 --- a/client/websocket/websocket.go +++ b/client/websocket/websocket.go @@ -174,7 +174,7 @@ func (s *Server) connect(ctx context.Context, conn ws.Connection, addr string) { } // Notify sends a notification to the websocket client. -func (s *Server) Notify(route string, payload interface{}) { +func (s *Server) Notify(route string, payload any) { msg, err := msgjson.NewNotification(route, payload) if err != nil { s.log.Errorf("%q notification encoding error: %v", route, err) diff --git a/dex/config/config.go b/dex/config/config.go index db8aa49851..39b53ed79d 100644 --- a/dex/config/config.go +++ b/dex/config/config.go @@ -10,14 +10,14 @@ import ( "gopkg.in/ini.v1" ) -func loadINIConfig(cfgPathOrData interface{}) (*ini.File, error) { +func loadINIConfig(cfgPathOrData any) (*ini.File, error) { loadOpts := ini.LoadOptions{Insensitive: true} return ini.LoadSources(loadOpts, cfgPathOrData) } // Parse returns a collection of all key-value options in the provided config // file path or []byte data. -func Parse(cfgPathOrData interface{}) (map[string]string, error) { +func Parse(cfgPathOrData any) (map[string]string, error) { cfgFile, err := loadINIConfig(cfgPathOrData) if err != nil { return nil, err @@ -33,7 +33,7 @@ func Parse(cfgPathOrData interface{}) (map[string]string, error) { // ParseInto parses config options from the provided config file path or []byte // data into the specified interface. -func ParseInto(cfgPathOrData, obj interface{}) error { +func ParseInto(cfgPathOrData, obj any) error { cfgFile, err := loadINIConfig(cfgPathOrData) if err != nil { return err @@ -58,14 +58,14 @@ func Data(settings map[string]string) []byte { // Unmapify parses config options from the provided settings map into the // specified interface. -func Unmapify(settings map[string]string, obj interface{}) error { +func Unmapify(settings map[string]string, obj any) error { cfgData := Data(settings) return ParseInto(cfgData, obj) } // Mapify takes an interface with ini tags, and parses it into // a settings map. obj must be a pointer to a struct. -func Mapify(obj interface{}) (map[string]string, error) { +func Mapify(obj any) (map[string]string, error) { cfg := ini.Empty() err := ini.ReflectFrom(cfg, obj) if err != nil { diff --git a/dex/config/config_test.go b/dex/config/config_test.go index 6c8b31a29e..970078fdfd 100644 --- a/dex/config/config_test.go +++ b/dex/config/config_test.go @@ -58,8 +58,8 @@ func TestConfigParsing(t *testing.T) { type test struct { name string - cfgData interface{} - parsedCfg interface{} + cfgData any + parsedCfg any expect expectations } diff --git a/dex/marshal.go b/dex/marshal.go index 947eb9d56d..389d256ce8 100644 --- a/dex/marshal.go +++ b/dex/marshal.go @@ -26,7 +26,7 @@ func (b Bytes) MarshalJSON() ([]byte, error) { } // Scan implements the sql.Scanner interface. -func (b *Bytes) Scan(src interface{}) error { +func (b *Bytes) Scan(src any) error { switch src := src.(type) { case []byte: // src may be reused, so create a new slice. diff --git a/dex/msgjson/types.go b/dex/msgjson/types.go index b838bc2ded..4555a13c6f 100644 --- a/dex/msgjson/types.go +++ b/dex/msgjson/types.go @@ -288,7 +288,7 @@ func (e Error) String() string { } // NewError is a constructor for an Error. -func NewError(code int, format string, a ...interface{}) *Error { +func NewError(code int, format string, a ...any) *Error { return &Error{ Code: code, Message: fmt.Sprintf(format, a...), @@ -359,7 +359,7 @@ func DecodeMessage(b []byte) (*Message, error) { } // NewRequest is the constructor for a Request-type *Message. -func NewRequest(id uint64, route string, payload interface{}) (*Message, error) { +func NewRequest(id uint64, route string, payload any) (*Message, error) { if id == 0 { return nil, fmt.Errorf("id = 0 not allowed for a request-type message") } @@ -379,7 +379,7 @@ func NewRequest(id uint64, route string, payload interface{}) (*Message, error) } // NewResponse encodes the result and creates a Response-type *Message. -func NewResponse(id uint64, result interface{}, rpcErr *Error) (*Message, error) { +func NewResponse(id uint64, result any, rpcErr *Error) (*Message, error) { if id == 0 { return nil, fmt.Errorf("id = 0 not allowed for response-type message") } @@ -421,7 +421,7 @@ func (msg *Message) Response() (*ResponsePayload, error) { } // NewNotification encodes the payload and creates a Notification-type *Message. -func NewNotification(route string, payload interface{}) (*Message, error) { +func NewNotification(route string, payload any) (*Message, error) { if route == "" { return nil, fmt.Errorf("empty string not allowed for route of notification-type message") } @@ -439,13 +439,13 @@ func NewNotification(route string, payload interface{}) (*Message, error) { // Unmarshal unmarshals the Payload field into the provided interface. Note that // the payload interface must contain a pointer. If it is a pointer to a // pointer, it may become nil for a Message.Payload of []byte("null"). -func (msg *Message) Unmarshal(payload interface{}) error { +func (msg *Message) Unmarshal(payload any) error { return json.Unmarshal(msg.Payload, payload) } // UnmarshalResult is a convenience method for decoding the Result field of a // ResponsePayload. -func (msg *Message) UnmarshalResult(result interface{}) error { +func (msg *Message) UnmarshalResult(result any) error { resp, err := msg.Response() if err != nil { return err diff --git a/dex/networks/erc20/txdata.go b/dex/networks/erc20/txdata.go index a47ea12f19..82a06b1198 100644 --- a/dex/networks/erc20/txdata.go +++ b/dex/networks/erc20/txdata.go @@ -11,7 +11,7 @@ import ( "github.com/ethereum/go-ethereum/common" ) -func parseCallData(method string, data []byte, expArgs int) ([]interface{}, error) { +func parseCallData(method string, data []byte, expArgs int) ([]any, error) { decoded, err := dexeth.ParseCallData(data, ERC20ABI) if err != nil { return nil, fmt.Errorf("unable to parse call data: %v", err) diff --git a/dex/networks/eth/abi.go b/dex/networks/eth/abi.go index 6cd161d985..6a272611d4 100644 --- a/dex/networks/eth/abi.go +++ b/dex/networks/eth/abi.go @@ -37,14 +37,14 @@ type DecodedCallData struct { inputs []decodedArgument Name string - Args []interface{} + Args []any } // decodedArgument is an internal type to represent an argument parsed according // to an ABI method signature. type decodedArgument struct { soltype abi.Argument - value interface{} + value any } // String implements stringer interface, tries to use the underlying value-type diff --git a/dex/networks/eth/abi_test.go b/dex/networks/eth/abi_test.go index 2abbbd0dad..e96cf59868 100644 --- a/dex/networks/eth/abi_test.go +++ b/dex/networks/eth/abi_test.go @@ -29,7 +29,7 @@ import ( "github.com/ethereum/go-ethereum/common" ) -func verify(t *testing.T, jsondata, calldata string, exp []interface{}) { +func verify(t *testing.T, jsondata, calldata string, exp []any) { abispec, err := abi.JSON(strings.NewReader(jsondata)) if err != nil { t.Fatal(err) @@ -58,14 +58,14 @@ func TestNewUnpacker(t *testing.T) { type unpackTest struct { jsondata string calldata string - exp []interface{} + exp []any } testcases := []unpackTest{ { // https://solidity.readthedocs.io/en/develop/abi-spec.html#use-of-dynamic-types `[{"type":"function","name":"f", "inputs":[{"type":"uint256"},{"type":"uint32[]"},{"type":"bytes10"},{"type":"bytes"}]}]`, // 0x123, [0x456, 0x789], "1234567890", "Hello, world!" "8be65246" + "00000000000000000000000000000000000000000000000000000000000001230000000000000000000000000000000000000000000000000000000000000080313233343536373839300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e0000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000004560000000000000000000000000000000000000000000000000000000000000789000000000000000000000000000000000000000000000000000000000000000d48656c6c6f2c20776f726c642100000000000000000000000000000000000000", - []interface{}{ + []any{ big.NewInt(0x123), []uint32{0x456, 0x789}, [10]byte{49, 50, 51, 52, 53, 54, 55, 56, 57, 48}, @@ -75,7 +75,7 @@ func TestNewUnpacker(t *testing.T) { `[{"type":"function","name":"sam","inputs":[{"type":"bytes"},{"type":"bool"},{"type":"uint256[]"}]}]`, // "dave", true and [1,2,3] "a5643bf20000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000464617665000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000003", - []interface{}{ + []any{ []byte{0x64, 0x61, 0x76, 0x65}, true, []*big.Int{big.NewInt(1), big.NewInt(2), big.NewInt(3)}, @@ -83,11 +83,11 @@ func TestNewUnpacker(t *testing.T) { }, { `[{"type":"function","name":"send","inputs":[{"type":"uint256"}]}]`, "a52c101e0000000000000000000000000000000000000000000000000000000000000012", - []interface{}{big.NewInt(0x12)}, + []any{big.NewInt(0x12)}, }, { `[{"type":"function","name":"compareAndApprove","inputs":[{"type":"address"},{"type":"uint256"},{"type":"uint256"}]}]`, "751e107900000000000000000000000000000133700000deadbeef00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001", - []interface{}{ + []any{ common.HexToAddress("0x00000133700000deadbeef000000000000000000"), new(big.Int).SetBytes([]byte{0x00}), big.NewInt(0x1), diff --git a/dex/networks/ltc/block_online_test.go b/dex/networks/ltc/block_online_test.go index 6ba608b61a..8580f3a5d5 100644 --- a/dex/networks/ltc/block_online_test.go +++ b/dex/networks/ltc/block_online_test.go @@ -58,7 +58,7 @@ func TestOnlineDeserializeBlock(t *testing.T) { isTestNet := gbci.Chain == "test" t.Log("Network:", gbci.Chain) - makeParams := func(args ...interface{}) []json.RawMessage { + makeParams := func(args ...any) []json.RawMessage { params := make([]json.RawMessage, 0, len(args)) for i := range args { p, err := json.Marshal(args[i]) diff --git a/dex/order/match.go b/dex/order/match.go index 742d415472..ebae50e0b3 100644 --- a/dex/order/match.go +++ b/dex/order/match.go @@ -44,7 +44,7 @@ func (id MatchID) Value() (driver.Value, error) { } // Scan implements the sql.Scanner interface. -func (id *MatchID) Scan(src interface{}) error { +func (id *MatchID) Scan(src any) error { idB, ok := src.([]byte) if !ok { return fmt.Errorf("cannot convert %T to OrderID", src) diff --git a/dex/order/order.go b/dex/order/order.go index ec0fd1fede..66293e6e84 100644 --- a/dex/order/order.go +++ b/dex/order/order.go @@ -77,7 +77,7 @@ func (oid OrderID) Value() (driver.Value, error) { } // Scan implements the sql.Scanner interface. -func (oid *OrderID) Scan(src interface{}) error { +func (oid *OrderID) Scan(src any) error { switch src := src.(type) { case []byte: copy(oid[:], src) @@ -116,7 +116,7 @@ func (ot OrderType) Value() (driver.Value, error) { } // Scan implements the sql.Scanner interface. -func (ot *OrderType) Scan(src interface{}) error { +func (ot *OrderType) Scan(src any) error { // Use sql.(NullInt32).Scan because it uses the unexported // sql.convertAssignRows to coerce compatible types. v := new(sql.NullInt32) @@ -256,7 +256,7 @@ func (c Commitment) Value() (driver.Value, error) { // Scan implements the sql.Scanner interface. NULL table values are scanned as // the zero-value Commitment. -func (c *Commitment) Scan(src interface{}) error { +func (c *Commitment) Scan(src any) error { switch src := src.(type) { case []byte: copy(c[:], src) @@ -294,7 +294,7 @@ func (pi Preimage) Value() (driver.Value, error) { } // Scan implements the sql.Scanner interface. -func (pi *Preimage) Scan(src interface{}) error { +func (pi *Preimage) Scan(src any) error { switch src := src.(type) { case []byte: copy(pi[:], src) diff --git a/dex/order/test/helpers.go b/dex/order/test/helpers.go index a7f099afe8..9bc47972e3 100644 --- a/dex/order/test/helpers.go +++ b/dex/order/test/helpers.go @@ -322,7 +322,7 @@ func CompareUserMatch(m1, m2 *order.UserMatch) error { type testKiller interface { Helper() - Fatalf(string, ...interface{}) + Fatalf(string, ...any) } // MustComparePrefix compares the Prefix field-by-field and calls the Fatalf diff --git a/dex/testing/loadbot/mantle.go b/dex/testing/loadbot/mantle.go index 3c47880a88..0ba6555e08 100644 --- a/dex/testing/loadbot/mantle.go +++ b/dex/testing/loadbot/mantle.go @@ -186,7 +186,7 @@ func newMantle(name string) (*Mantle, error) { } // fatalError kills the LoadBot by cancelling the global Context. -func (m *Mantle) fatalError(s string, a ...interface{}) { +func (m *Mantle) fatalError(s string, a ...any) { m.log.Criticalf(s, a...) if !ignoreErrors || ctx.Err() != nil { quit() @@ -546,7 +546,7 @@ func (m *Mantle) replenishBalance(w *botWallet, minFunds, maxFunds uint64) { // mustJSON JSON-encodes the thing. If an error is encountered, the error text // is returned instead. -func mustJSON(thing interface{}) string { +func mustJSON(thing any) string { s, err := json.Marshal(thing) if err != nil { return "invalid json: " + err.Error() diff --git a/server/account/account.go b/server/account/account.go index 2dc5c4d49f..3a378521d0 100644 --- a/server/account/account.go +++ b/server/account/account.go @@ -53,7 +53,7 @@ func (aid AccountID) Value() (driver.Value, error) { } // Scan implements the sql.Scanner interface. -func (aid *AccountID) Scan(src interface{}) error { +func (aid *AccountID) Scan(src any) error { switch src := src.(type) { case []byte: copy(aid[:], src) diff --git a/server/admin/api.go b/server/admin/api.go index 3aced67d15..29eb252cdf 100644 --- a/server/admin/api.go +++ b/server/admin/api.go @@ -30,13 +30,13 @@ const ( // writeJSON marshals the provided interface and writes the bytes to the // ResponseWriter. The response code is assumed to be StatusOK. -func writeJSON(w http.ResponseWriter, thing interface{}) { +func writeJSON(w http.ResponseWriter, thing any) { writeJSONWithStatus(w, thing, http.StatusOK) } // writeJSON marshals the provided interface and writes the bytes to the // ResponseWriter with the specified response code. -func writeJSONWithStatus(w http.ResponseWriter, thing interface{}, code int) { +func writeJSONWithStatus(w http.ResponseWriter, thing any, code int) { w.Header().Set("Content-Type", "application/json; charset=utf-8") b, err := json.MarshalIndent(thing, "", " ") if err != nil { diff --git a/server/apidata/apidata.go b/server/apidata/apidata.go index d90d05f38e..fcfa0875c9 100644 --- a/server/apidata/apidata.go +++ b/server/apidata/apidata.go @@ -168,7 +168,7 @@ func (s *DataAPI) ReportEpoch(base, quote uint32, epochIdx uint64, stats *matche } // handleSpots implements comms.HTTPHandler for the /spots endpoint. -func (s *DataAPI) handleSpots(interface{}) (interface{}, error) { +func (s *DataAPI) handleSpots(any) (any, error) { s.spotsMtx.RLock() defer s.spotsMtx.RUnlock() spots := make([]json.RawMessage, 0, len(s.spots)) @@ -179,7 +179,7 @@ func (s *DataAPI) handleSpots(interface{}) (interface{}, error) { } // handleCandles implements comms.HTTPHandler for the /candles endpoints. -func (s *DataAPI) handleCandles(thing interface{}) (interface{}, error) { +func (s *DataAPI) handleCandles(thing any) (any, error) { req, ok := thing.(*msgjson.CandlesRequest) if !ok { return nil, fmt.Errorf("candles request unparseable") @@ -218,7 +218,7 @@ func (s *DataAPI) handleCandles(thing interface{}) (interface{}, error) { } // handleOrderBook implements comms.HTTPHandler for the /orderbook endpoints. -func (s *DataAPI) handleOrderBook(thing interface{}) (interface{}, error) { +func (s *DataAPI) handleOrderBook(thing any) (any, error) { req, ok := thing.(*msgjson.OrderBookSubscription) if !ok { return nil, fmt.Errorf("unparseable orderbook request") diff --git a/server/asset/btc/btc.go b/server/asset/btc/btc.go index cc5710d96d..f46bb9cc72 100644 --- a/server/asset/btc/btc.go +++ b/server/asset/btc/btc.go @@ -1344,7 +1344,7 @@ func (btc *Backend) run(ctx context.Context) { } } - sendErrFmt := func(s string, a ...interface{}) { + sendErrFmt := func(s string, a ...any) { sendErr(fmt.Errorf(s, a...)) } diff --git a/server/asset/btc/btc_test.go b/server/asset/btc/btc_test.go index 25e071c021..ec5a91e181 100644 --- a/server/asset/btc/btc_test.go +++ b/server/asset/btc/btc_test.go @@ -307,7 +307,7 @@ func txOutID(txHash *chainhash.Hash, index uint32) string { return txHash.String() + ":" + strconv.Itoa(int(index)) } -func mustUnmarshal(data []byte, thing interface{}) { +func mustUnmarshal(data []byte, thing any) { if err := json.Unmarshal(data, thing); err != nil { panic(err.Error()) } diff --git a/server/asset/btc/rpcclient.go b/server/asset/btc/rpcclient.go index 2bf1a7c8e4..18b6c43cc2 100644 --- a/server/asset/btc/rpcclient.go +++ b/server/asset/btc/rpcclient.go @@ -231,7 +231,7 @@ type GetBlockVerboseResult struct { } func (rc *RPCClient) GetRawBlock(blockHash *chainhash.Hash) ([]byte, error) { - arg := interface{}(0) + arg := any(0) if rc.booleanGetBlockRPC { arg = false } @@ -285,7 +285,7 @@ func (rc *RPCClient) getBlockWithVerboseHeader(blockHash *chainhash.Hash) (*wire // GetBlockVerbose fetches verbose block data for the block with the given hash. func (rc *RPCClient) GetBlockVerbose(blockHash *chainhash.Hash) (*GetBlockVerboseResult, error) { - arg := interface{}(1) + arg := any(1) if rc.booleanGetBlockRPC { arg = true } @@ -539,18 +539,18 @@ func (rc *RPCClient) RawRequest(method string, params []json.RawMessage) (json.R // Call is used to marshal parameters and send requests to the RPC server via // (*rpcclient.Client).RawRequest. If `thing` is non-nil, the result will be // marshaled into `thing`. -func (rc *RPCClient) Call(method string, args []interface{}, thing interface{}) error { +func (rc *RPCClient) Call(method string, args []any, thing any) error { return rc.call(method, args, thing) } // anylist is a list of RPC parameters to be converted to []json.RawMessage and // sent via RawRequest. -type anylist []interface{} +type anylist []any // call is used internally to marshal parameters and send requests to the RPC // server via (*rpcclient.Client).RawRequest. If `thing` is non-nil, the result // will be marshaled into `thing`. -func (rc *RPCClient) call(method string, args anylist, thing interface{}) error { +func (rc *RPCClient) call(method string, args anylist, thing any) error { params := make([]json.RawMessage, 0, len(args)) for i := range args { p, err := json.Marshal(args[i]) diff --git a/server/asset/common.go b/server/asset/common.go index 2d6ad8451d..182bdedcc0 100644 --- a/server/asset/common.go +++ b/server/asset/common.go @@ -188,7 +188,7 @@ type BlockUpdate struct { type ConnectionError error // NewConnectionError is a constructor for a ConnectionError. -func NewConnectionError(s string, a ...interface{}) ConnectionError { +func NewConnectionError(s string, a ...any) ConnectionError { return ConnectionError(fmt.Errorf(s, a...)) } diff --git a/server/asset/dcr/dcr.go b/server/asset/dcr/dcr.go index b84d5dbcf3..42abf0aca1 100644 --- a/server/asset/dcr/dcr.go +++ b/server/asset/dcr/dcr.go @@ -917,7 +917,7 @@ func (dcr *Backend) run(ctx context.Context) { dcr.signalMtx.Unlock() } - sendErrFmt := func(s string, a ...interface{}) { + sendErrFmt := func(s string, a ...any) { sendErr(fmt.Errorf(s, a...)) } diff --git a/server/asset/eth/rpcclient.go b/server/asset/eth/rpcclient.go index 7d5a92f967..764a218a61 100644 --- a/server/asset/eth/rpcclient.go +++ b/server/asset/eth/rpcclient.go @@ -39,7 +39,7 @@ var ( ) type ContextCaller interface { - CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) error + CallContext(ctx context.Context, result any, method string, args ...any) error } type ethConn struct { diff --git a/server/book/orderpq.go b/server/book/orderpq.go index aa9df2f74e..f2f33b1afb 100644 --- a/server/book/orderpq.go +++ b/server/book/orderpq.go @@ -242,7 +242,7 @@ func (pq *OrderPQ) Swap(i, j int) { // Push an order, which must be a *LimitOrder. Use heap.Push, not this directly. // Push is required for heap.Interface. It is not thread-safe. -func (pq *OrderPQ) Push(ord interface{}) { +func (pq *OrderPQ) Push(ord any) { lo, ok := ord.(*order.LimitOrder) if !ok || lo == nil { fmt.Printf("Failed to push an order: %v", ord) @@ -261,10 +261,10 @@ func (pq *OrderPQ) Push(ord interface{}) { pq.push(entry) } -// Pop will return an interface{} that may be cast to *LimitOrder. Use heap.Pop, +// Pop will return an any that may be cast to *LimitOrder. Use heap.Pop, // Extract*, or Remove*, not this method. Pop is required for heap.Interface. It // is not thread-safe. -func (pq *OrderPQ) Pop() interface{} { +func (pq *OrderPQ) Pop() any { // heap.Pop put the best value at the end and re-heaped without it. Now // actually pop it off the heap's slice. n := pq.Len() diff --git a/server/comms/comms_test.go b/server/comms/comms_test.go index 843d7bda6e..327a294569 100644 --- a/server/comms/comms_test.go +++ b/server/comms/comms_test.go @@ -57,7 +57,7 @@ func giveItASecond(f func() bool) bool { } } -func readChannel(t *testing.T, tag string, c chan interface{}) interface{} { +func readChannel(t *testing.T, tag string, c chan any) any { t.Helper() select { case i := <-c: @@ -228,7 +228,7 @@ func sendToConn(t *testing.T, conn *wsConnStub, method, msg string) { conn.msg <- encMsg } -func sendReplace(t *testing.T, conn *wsConnStub, thing interface{}, old, new string) { +func sendReplace(t *testing.T, conn *wsConnStub, thing any, old, new string) { enc, err := json.Marshal(thing) if err != nil { t.Fatalf("error encoding thing for sendReplace: %v", err) @@ -271,7 +271,7 @@ func TestMain(m *testing.M) { defer shutdown() // Register dummy handlers for the HTTP routes. for _, route := range []string{msgjson.ConfigRoute, msgjson.SpotsRoute, msgjson.CandlesRoute, msgjson.OrderBookRoute} { - RegisterHTTP(route, func(interface{}) (interface{}, error) { return nil, nil }) + RegisterHTTP(route, func(any) (any, error) { return nil, nil }) } UseLogger(tLogger) os.Exit(m.Run()) @@ -328,7 +328,7 @@ func TestClientRequests(t *testing.T) { // Register all methods before sending any requests. // 'getclient' grabs the server's link. - srvChan := make(chan interface{}) + srvChan := make(chan any) Route("getclient", func(c Link, _ *msgjson.Message) *msgjson.Error { client, ok := c.(*wsLink) if !ok { @@ -377,7 +377,7 @@ func TestClientRequests(t *testing.T) { return nil }) var httpSeen uint32 - RegisterHTTP("httproute", func(thing interface{}) (interface{}, error) { + RegisterHTTP("httproute", func(thing any) (any, error) { atomic.StoreUint32(&httpSeen, 1) srvChan <- nil return struct{}{}, nil @@ -546,7 +546,7 @@ func TestClientResponses(t *testing.T) { // Register all methods before sending any requests. // 'getclient' grabs the server's link. - srvChan := make(chan interface{}) + srvChan := make(chan any) Route("grabclient", func(c Link, _ *msgjson.Message) *msgjson.Error { client, ok := c.(*wsLink) if !ok { @@ -712,7 +712,7 @@ func TestOnline(t *testing.T) { return nil }) // The 'banuser' route quarantines the user. - banChan := make(chan interface{}) + banChan := make(chan any) Route("banuser", func(c Link, req *msgjson.Message) *msgjson.Error { rpcErr := msgjson.NewError(msgjson.RPCQuarantineClient, "test quarantine") msg, _ := msgjson.NewResponse(req.ID, nil, rpcErr) @@ -755,7 +755,7 @@ func TestOnline(t *testing.T) { } // A loop to grab responses from the server. - recv := make(chan interface{}) + recv := make(chan any) go func() { for { _, r, err := remoteClient.ReadMessage() diff --git a/server/comms/link.go b/server/comms/link.go index 94d8eb0632..7ba4b03ac0 100644 --- a/server/comms/link.go +++ b/server/comms/link.go @@ -150,7 +150,7 @@ func handleMessage(c *wsLink, msg *msgjson.Message) *msgjson.Error { } // Prepare the thing and unmarshal. - var thing interface{} + var thing any switch msg.Route { case msgjson.CandlesRoute: thing = new(msgjson.CandlesRequest) diff --git a/server/comms/server.go b/server/comms/server.go index fccba94da3..9dcecc636d 100644 --- a/server/comms/server.go +++ b/server/comms/server.go @@ -125,7 +125,7 @@ type MsgHandler func(Link, *msgjson.Message) *msgjson.Error var rpcRoutes = make(map[string]MsgHandler) // HTTPHandler describes a handler for an HTTP route. -type HTTPHandler func(thing interface{}) (interface{}, error) +type HTTPHandler func(thing any) (any, error) // httpRoutes maps HTTP routes to the handlers. var httpRoutes = make(map[string]HTTPHandler) @@ -841,7 +841,7 @@ func routeHandler(route string) func(w http.ResponseWriter, r *http.Request) { // writeJSONWithStatus writes the JSON response with the specified HTTP response // code. -func writeJSONWithStatus(w http.ResponseWriter, thing interface{}, code int) { +func writeJSONWithStatus(w http.ResponseWriter, thing any, code int) { w.Header().Set("Content-Type", "application/json; charset=utf-8") b, err := json.Marshal(thing) if err != nil { diff --git a/server/db/driver.go b/server/db/driver.go index 21c10f8f97..1dca5ef3e7 100644 --- a/server/db/driver.go +++ b/server/db/driver.go @@ -19,7 +19,7 @@ var ( // Driver is the interface required of all DB drivers. Open should create a // DEXArchivist and verify connectivity with the asset's chain server. type Driver interface { - Open(ctx context.Context, cfg interface{}) (DEXArchivist, error) + Open(ctx context.Context, cfg any) (DEXArchivist, error) UseLogger(logger dex.Logger) } @@ -38,7 +38,7 @@ func Register(name string, driver Driver) { } // Open loads the named DB driver with the provided configuration. -func Open(ctx context.Context, name string, cfg interface{}) (DEXArchivist, error) { +func Open(ctx context.Context, name string, cfg any) (DEXArchivist, error) { driversMtx.Lock() drv, ok := drivers[name] driversMtx.Unlock() diff --git a/server/db/driver/pg/epochs.go b/server/db/driver/pg/epochs.go index 50ffc3bbcb..fb003f87a0 100644 --- a/server/db/driver/pg/epochs.go +++ b/server/db/driver/pg/epochs.go @@ -40,7 +40,7 @@ func (oids orderIDs) Value() (driver.Value, error) { } // Scan implements the sql.Scanner interface. -func (oids *orderIDs) Scan(src interface{}) error { +func (oids *orderIDs) Scan(src any) error { var ba pq.ByteaArray err := ba.Scan(src) if err != nil { diff --git a/server/db/driver/pg/matches.go b/server/db/driver/pg/matches.go index b8437a0a49..76be66208a 100644 --- a/server/db/driver/pg/matches.go +++ b/server/db/driver/pg/matches.go @@ -617,7 +617,7 @@ func (a *Archiver) SwapData(mid db.MarketMatchID) (order.MatchStatus, *db.SwapDa // updateMatchStmt executes a SQL statement with the provided arguments, // choosing the market's matches table from the MarketMatchID. Exactly 1 table // row must be updated, otherwise an error is returned. -func (a *Archiver) updateMatchStmt(mid db.MarketMatchID, stmt string, args ...interface{}) error { +func (a *Archiver) updateMatchStmt(mid db.MarketMatchID, stmt string, args ...any) error { marketSchema, err := a.marketSchema(mid.Base, mid.Quote) if err != nil { return err diff --git a/server/db/driver/pg/orders.go b/server/db/driver/pg/orders.go index 710761f693..e9de2db1be 100644 --- a/server/db/driver/pg/orders.go +++ b/server/db/driver/pg/orders.go @@ -42,7 +42,7 @@ func (coins dbCoins) Value() (driver.Value, error) { } // Scan implements the sql.Scanner interface. -func (coins *dbCoins) Scan(src interface{}) error { +func (coins *dbCoins) Scan(src any) error { b := src.([]byte) if len(b) == 0 { *coins = dbCoins{} diff --git a/server/db/driver/pg/pg.go b/server/db/driver/pg/pg.go index 0e1397b9ca..c96246f947 100644 --- a/server/db/driver/pg/pg.go +++ b/server/db/driver/pg/pg.go @@ -18,7 +18,7 @@ import ( type Driver struct{} // Open creates the DB backend, returning a DEXArchivist. -func (d *Driver) Open(ctx context.Context, cfg interface{}) (db.DEXArchivist, error) { +func (d *Driver) Open(ctx context.Context, cfg any) (db.DEXArchivist, error) { switch c := cfg.(type) { case *Config: return NewArchiver(ctx, c) diff --git a/server/db/driver/pg/system.go b/server/db/driver/pg/system.go index fda7dfdc5d..81ac0bc186 100644 --- a/server/db/driver/pg/system.go +++ b/server/db/driver/pg/system.go @@ -59,7 +59,7 @@ func connect(host, port, user, pass, dbName string) (*sql.DB, error) { // https://www.postgresql.org/docs/13/runtime-config-client.html#GUC-CLIENT-MIN-MESSAGES // The default setting is NOTICE, which excludes DEBUG and LOG, but not // INFO since that is sent to the client regardless of the setting. - var printer func(format string, params ...interface{}) + var printer func(format string, params ...any) switch notice.Severity { case pq.Efatal, pq.Epanic: // error caused database session to abort printer = log.Criticalf @@ -103,17 +103,17 @@ func connect(host, port, user, pass, dbName string) (*sql.DB, error) { // sqlExecutor is implemented by both sql.DB and sql.Tx. type sqlExecutor interface { - Exec(query string, args ...interface{}) (sql.Result, error) + Exec(query string, args ...any) (sql.Result, error) } type sqlQueryer interface { - Query(query string, args ...interface{}) (*sql.Rows, error) - QueryRow(query string, args ...interface{}) *sql.Row + Query(query string, args ...any) (*sql.Rows, error) + QueryRow(query string, args ...any) *sql.Row } // sqlExec executes the SQL statement string with any optional arguments, and // returns the number of rows affected. -func sqlExec(db sqlExecutor, stmt string, args ...interface{}) (int64, error) { +func sqlExec(db sqlExecutor, stmt string, args ...any) (int64, error) { res, err := db.Exec(stmt, args...) if err != nil { return 0, err @@ -129,7 +129,7 @@ func sqlExec(db sqlExecutor, stmt string, args ...interface{}) (int64, error) { // sqlExecStmt executes the prepared SQL statement with any optional arguments, // and returns the number of rows affected. -func sqlExecStmt(stmt *sql.Stmt, args ...interface{}) (int64, error) { +func sqlExecStmt(stmt *sql.Stmt, args ...any) (int64, error) { res, err := stmt.Exec(args...) if err != nil { return 0, err diff --git a/server/db/driver/pg/types.go b/server/db/driver/pg/types.go index 04dc2efb53..e126bc74ff 100644 --- a/server/db/driver/pg/types.go +++ b/server/db/driver/pg/types.go @@ -12,7 +12,7 @@ import ( // postgresql type of INT8 (8-byte integer) that scan a value of type int64. type fastUint64 uint64 -func (n *fastUint64) Scan(value interface{}) error { +func (n *fastUint64) Scan(value any) error { if value == nil { *n = 0 return fmt.Errorf("NULL not supported") diff --git a/server/dex/dex.go b/server/dex/dex.go index ecd7a13256..cbbf79f89a 100644 --- a/server/dex/dex.go +++ b/server/dex/dex.go @@ -228,7 +228,7 @@ func marketSubSysName(name string) string { return fmt.Sprintf("Market[%s]", name) } -func (dm *DEX) handleDEXConfig(interface{}) (interface{}, error) { +func (dm *DEX) handleDEXConfig(any) (any, error) { dm.configRespMtx.RLock() defer dm.configRespMtx.RUnlock() return dm.configResp.configEnc, nil @@ -263,7 +263,7 @@ type Bonder interface { // 9. Create and start the comms server. func NewDEX(ctx context.Context, cfg *DexConf) (*DEX, error) { var subsystems []subsystem - startSubSys := func(name string, rc interface{}) (err error) { + startSubSys := func(name string, rc any) (err error) { subsys := subsystem{name: name} switch st := rc.(type) { case dex.Runner: diff --git a/server/market/bookrouter.go b/server/market/bookrouter.go index b577052b2a..090bd4c5e7 100644 --- a/server/market/bookrouter.go +++ b/server/market/bookrouter.go @@ -86,7 +86,7 @@ func (bua updateAction) String() string { // applies. type updateSignal struct { action updateAction - data interface{} // sigData* type + data any // sigData* type } func (us updateSignal) String() string { @@ -369,7 +369,7 @@ out: } // Prepare the book/unbook/epoch note. - var note interface{} + var note any var route string var spot *msgjson.Spot switch sigData := u.data.(type) { @@ -723,7 +723,7 @@ func (r *BookRouter) handlePriceFeeder(conn comms.Link, msg *msgjson.Message) *m } // sendNote sends a notification to the specified subscribers. -func (r *BookRouter) sendNote(route string, subs *subscribers, note interface{}) { +func (r *BookRouter) sendNote(route string, subs *subscribers, note any) { msg, err := msgjson.NewNotification(route, note) if err != nil { log.Errorf("error creating notification-type Message: %v", err) diff --git a/server/market/market_test.go b/server/market/market_test.go index 9ac39198d6..d0b831f1ef 100644 --- a/server/market/market_test.go +++ b/server/market/market_test.go @@ -266,7 +266,7 @@ func randomOrderID() order.OrderID { return id } -func newTestMarket(opts ...interface{}) (*Market, *TArchivist, *TAuth, func(), error) { +func newTestMarket(opts ...any) (*Market, *TArchivist, *TAuth, func(), error) { // The DEX will make MasterCoinLockers for each asset. masterLockerBase := coinlock.NewMasterCoinLocker() bookLockerBase := masterLockerBase.Book() diff --git a/server/swap/swap.go b/server/swap/swap.go index 803ba533c8..419a57b87f 100644 --- a/server/swap/swap.go +++ b/server/swap/swap.go @@ -1261,7 +1261,7 @@ func (s *Swapper) respondError(id uint64, user account.AccountID, code int, errM } // respondSuccess sends a successful response to a user. -func (s *Swapper) respondSuccess(id uint64, user account.AccountID, result interface{}) { +func (s *Swapper) respondSuccess(id uint64, user account.AccountID, result any) { msg, err := msgjson.NewResponse(id, result, nil) if err != nil { log.Errorf("failed to send success: %v", err) diff --git a/server/swap/swap_test.go b/server/swap/swap_test.go index f7d5aa9e10..b7c5e3b8aa 100644 --- a/server/swap/swap_test.go +++ b/server/swap/swap_test.go @@ -261,7 +261,7 @@ func (m *TAuthManager) pushReq(id account.AccountID, req *TRequest) { m.reqs[id] = append([]*TRequest{req}, m.reqs[id]...) } -func (m *TAuthManager) getNtfn(id account.AccountID, route string, payload interface{}) error { +func (m *TAuthManager) getNtfn(id account.AccountID, route string, payload any) error { m.mtx.Lock() defer m.mtx.Unlock() msgs := m.ntfns[id]