From f3e8f0efc6c5b6b095291ce16666787b579228d0 Mon Sep 17 00:00:00 2001 From: Mike Pearl Date: Sun, 31 Aug 2025 18:58:33 -0700 Subject: [PATCH 01/24] Add local claude settings to gitignore --- .gitignore | 727 +++++++++++++++++++++++++++-------------------------- 1 file changed, 364 insertions(+), 363 deletions(-) diff --git a/.gitignore b/.gitignore index 9491a2f..29e5569 100644 --- a/.gitignore +++ b/.gitignore @@ -1,363 +1,364 @@ -## Ignore Visual Studio temporary files, build results, and -## files generated by popular Visual Studio add-ons. -## -## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore - -# User-specific files -*.rsuser -*.suo -*.user -*.userosscache -*.sln.docstates - -# User-specific files (MonoDevelop/Xamarin Studio) -*.userprefs - -# Mono auto generated files -mono_crash.* - -# Build results -[Dd]ebug/ -[Dd]ebugPublic/ -[Rr]elease/ -[Rr]eleases/ -x64/ -x86/ -[Ww][Ii][Nn]32/ -[Aa][Rr][Mm]/ -[Aa][Rr][Mm]64/ -bld/ -[Bb]in/ -[Oo]bj/ -[Oo]ut/ -[Ll]og/ -[Ll]ogs/ - -# Visual Studio 2015/2017 cache/options directory -.vs/ -# Uncomment if you have tasks that create the project's static files in wwwroot -#wwwroot/ - -# Visual Studio 2017 auto generated files -Generated\ Files/ - -# MSTest test Results -[Tt]est[Rr]esult*/ -[Bb]uild[Ll]og.* - -# NUnit -*.VisualState.xml -TestResult.xml -nunit-*.xml - -# Build Results of an ATL Project -[Dd]ebugPS/ -[Rr]eleasePS/ -dlldata.c - -# Benchmark Results -BenchmarkDotNet.Artifacts/ - -# .NET Core -project.lock.json -project.fragment.lock.json -artifacts/ - -# ASP.NET Scaffolding -ScaffoldingReadMe.txt - -# StyleCop -StyleCopReport.xml - -# Files built by Visual Studio -*_i.c -*_p.c -*_h.h -*.ilk -*.meta -*.obj -*.iobj -*.pch -*.pdb -*.ipdb -*.pgc -*.pgd -*.rsp -*.sbr -*.tlb -*.tli -*.tlh -*.tmp -*.tmp_proj -*_wpftmp.csproj -*.log -*.vspscc -*.vssscc -.builds -*.pidb -*.svclog -*.scc - -# Chutzpah Test files -_Chutzpah* - -# Visual C++ cache files -ipch/ -*.aps -*.ncb -*.opendb -*.opensdf -*.sdf -*.cachefile -*.VC.db -*.VC.VC.opendb - -# Visual Studio profiler -*.psess -*.vsp -*.vspx -*.sap - -# Visual Studio Trace Files -*.e2e - -# TFS 2012 Local Workspace -$tf/ - -# Guidance Automation Toolkit -*.gpState - -# ReSharper is a .NET coding add-in -_ReSharper*/ -*.[Rr]e[Ss]harper -*.DotSettings.user - -# TeamCity is a build add-in -_TeamCity* - -# DotCover is a Code Coverage Tool -*.dotCover - -# AxoCover is a Code Coverage Tool -.axoCover/* -!.axoCover/settings.json - -# Coverlet is a free, cross platform Code Coverage Tool -coverage*.json -coverage*.xml -coverage*.info - -# Visual Studio code coverage results -*.coverage -*.coveragexml - -# NCrunch -_NCrunch_* -.*crunch*.local.xml -nCrunchTemp_* - -# MightyMoose -*.mm.* -AutoTest.Net/ - -# Web workbench (sass) -.sass-cache/ - -# Installshield output folder -[Ee]xpress/ - -# DocProject is a documentation generator add-in -DocProject/buildhelp/ -DocProject/Help/*.HxT -DocProject/Help/*.HxC -DocProject/Help/*.hhc -DocProject/Help/*.hhk -DocProject/Help/*.hhp -DocProject/Help/Html2 -DocProject/Help/html - -# Click-Once directory -publish/ - -# Publish Web Output -*.[Pp]ublish.xml -*.azurePubxml -# Note: Comment the next line if you want to checkin your web deploy settings, -# but database connection strings (with potential passwords) will be unencrypted -*.pubxml -*.publishproj - -# Microsoft Azure Web App publish settings. Comment the next line if you want to -# checkin your Azure Web App publish settings, but sensitive information contained -# in these scripts will be unencrypted -PublishScripts/ - -# NuGet Packages -*.nupkg -# NuGet Symbol Packages -*.snupkg -# The packages folder can be ignored because of Package Restore -**/[Pp]ackages/* -# except build/, which is used as an MSBuild target. -!**/[Pp]ackages/build/ -# Uncomment if necessary however generally it will be regenerated when needed -#!**/[Pp]ackages/repositories.config -# NuGet v3's project.json files produces more ignorable files -*.nuget.props -*.nuget.targets - -# Microsoft Azure Build Output -csx/ -*.build.csdef - -# Microsoft Azure Emulator -ecf/ -rcf/ - -# Windows Store app package directories and files -AppPackages/ -BundleArtifacts/ -Package.StoreAssociation.xml -_pkginfo.txt -*.appx -*.appxbundle -*.appxupload - -# Visual Studio cache files -# files ending in .cache can be ignored -*.[Cc]ache -# but keep track of directories ending in .cache -!?*.[Cc]ache/ - -# Others -ClientBin/ -~$* -*~ -*.dbmdl -*.dbproj.schemaview -*.jfm -*.pfx -*.publishsettings -orleans.codegen.cs - -# Including strong name files can present a security risk -# (https://github.com/github/gitignore/pull/2483#issue-259490424) -#*.snk - -# Since there are multiple workflows, uncomment next line to ignore bower_components -# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) -#bower_components/ - -# RIA/Silverlight projects -Generated_Code/ - -# Backup & report files from converting an old project file -# to a newer Visual Studio version. Backup files are not needed, -# because we have git ;-) -_UpgradeReport_Files/ -Backup*/ -UpgradeLog*.XML -UpgradeLog*.htm -ServiceFabricBackup/ -*.rptproj.bak - -# SQL Server files -*.mdf -*.ldf -*.ndf - -# Business Intelligence projects -*.rdl.data -*.bim.layout -*.bim_*.settings -*.rptproj.rsuser -*- [Bb]ackup.rdl -*- [Bb]ackup ([0-9]).rdl -*- [Bb]ackup ([0-9][0-9]).rdl - -# Microsoft Fakes -FakesAssemblies/ - -# GhostDoc plugin setting file -*.GhostDoc.xml - -# Node.js Tools for Visual Studio -.ntvs_analysis.dat -node_modules/ - -# Visual Studio 6 build log -*.plg - -# Visual Studio 6 workspace options file -*.opt - -# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) -*.vbw - -# Visual Studio LightSwitch build output -**/*.HTMLClient/GeneratedArtifacts -**/*.DesktopClient/GeneratedArtifacts -**/*.DesktopClient/ModelManifest.xml -**/*.Server/GeneratedArtifacts -**/*.Server/ModelManifest.xml -_Pvt_Extensions - -# Paket dependency manager -.paket/paket.exe -paket-files/ - -# FAKE - F# Make -.fake/ - -# CodeRush personal settings -.cr/personal - -# Python Tools for Visual Studio (PTVS) -__pycache__/ -*.pyc - -# Cake - Uncomment if you are using it -# tools/** -# !tools/packages.config - -# Tabs Studio -*.tss - -# Telerik's JustMock configuration file -*.jmconfig - -# BizTalk build output -*.btp.cs -*.btm.cs -*.odx.cs -*.xsd.cs - -# OpenCover UI analysis results -OpenCover/ - -# Azure Stream Analytics local run output -ASALocalRun/ - -# MSBuild Binary and Structured Log -*.binlog - -# NVidia Nsight GPU debugger configuration file -*.nvuser - -# MFractors (Xamarin productivity tool) working folder -.mfractor/ - -# Local History for Visual Studio -.localhistory/ - -# BeatPulse healthcheck temp database -healthchecksdb - -# Backup folder for Package Reference Convert tool in Visual Studio 2017 -MigrationBackup/ - -# Ionide (cross platform F# VS Code tools) working folder -.ionide/ - -# Fody - auto-generated XML schema -FodyWeavers.xsd \ No newline at end of file +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Oo]ut/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd +/.claude/settings.local.json From 3310f4489792afa8cac0bf636d207784b38d7770 Mon Sep 17 00:00:00 2001 From: Mike Pearl Date: Sun, 31 Aug 2025 19:01:11 -0700 Subject: [PATCH 02/24] Add BouncyCastle.Cryptography dependency for Ed25519 cryptography MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add BouncyCastle.Cryptography v2.6.2 package reference - Required for SecretApiKey authentication using Ed25519 signatures 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- .../CoinbaseAdvancedTradeClient.csproj | 1 + 1 file changed, 1 insertion(+) diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.csproj b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.csproj index cc63c12..45a7816 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.csproj +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.csproj @@ -12,6 +12,7 @@ + From 7dcee70f5884e1ef00e273a40c261b12126e760c Mon Sep 17 00:00:00 2001 From: Mike Pearl Date: Sun, 31 Aug 2025 19:04:27 -0700 Subject: [PATCH 03/24] Add validation error messages for SecretApiKey authentication MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add RequestMethodRequired, RequestHostRequired, RequestPathRequired messages - Add InvalidBase64KeyFormat and InvalidEd25519KeyLength error messages - Update ErrorMessages.Designer.cs with new resource properties 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- .../Resources/ErrorMessages.Designer.cs | 45 +++++++++++++++++++ .../Resources/ErrorMessages.resx | 15 +++++++ 2 files changed, 60 insertions(+) diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Resources/ErrorMessages.Designer.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Resources/ErrorMessages.Designer.cs index 367ebf6..dadce3a 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Resources/ErrorMessages.Designer.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Resources/ErrorMessages.Designer.cs @@ -275,5 +275,50 @@ public static string WebSocketMustBeConnected { return ResourceManager.GetString("WebSocketMustBeConnected", resourceCulture); } } + + /// + /// Looks up a localized string similar to A request method is required.. + /// + public static string RequestMethodRequired { + get { + return ResourceManager.GetString("RequestMethodRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A request host is required.. + /// + public static string RequestHostRequired { + get { + return ResourceManager.GetString("RequestHostRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A request path is required.. + /// + public static string RequestPathRequired { + get { + return ResourceManager.GetString("RequestPathRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid base64 key format.. + /// + public static string InvalidBase64KeyFormat { + get { + return ResourceManager.GetString("InvalidBase64KeyFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid Ed25519 key length. Expected 64 bytes.. + /// + public static string InvalidEd25519KeyLength { + get { + return ResourceManager.GetString("InvalidEd25519KeyLength", resourceCulture); + } + } } } diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Resources/ErrorMessages.resx b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Resources/ErrorMessages.resx index ff49964..70c15a1 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Resources/ErrorMessages.resx +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Resources/ErrorMessages.resx @@ -189,4 +189,19 @@ Web Socket must be connected. + + A request method is required. + + + A request host is required. + + + A request path is required. + + + Invalid base64 key format. + + + Invalid Ed25519 key length. Expected 64 bytes. + \ No newline at end of file From 27d53ffbfc6e23be2a0ec4944848c9e4ed5f9d39 Mon Sep 17 00:00:00 2001 From: Mike Pearl Date: Sun, 31 Aug 2025 19:04:37 -0700 Subject: [PATCH 04/24] Add SecretApiKey configuration models MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add SecretApiKeyConfig for REST API authentication configuration - Add SecretApiKeyWebSocketConfig for WebSocket authentication configuration - Both models include KeyName, KeySecret, and default endpoint URLs 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- .../Models/Config/SecretApiKeyConfig.cs | 11 +++++++++++ .../Models/Config/SecretApiKeyWebSocketConfig.cs | 11 +++++++++++ 2 files changed, 22 insertions(+) create mode 100644 CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/SecretApiKeyConfig.cs create mode 100644 CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/SecretApiKeyWebSocketConfig.cs diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/SecretApiKeyConfig.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/SecretApiKeyConfig.cs new file mode 100644 index 0000000..f9bb1c7 --- /dev/null +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/SecretApiKeyConfig.cs @@ -0,0 +1,11 @@ +using CoinbaseAdvancedTradeClient.Constants; + +namespace CoinbaseAdvancedTradeClient.Models.Config +{ + public class SecretApiKeyConfig + { + public string KeyName { get; set; } + public string KeySecret { get; set; } + public string ApiUrl { get; set; } = ApiEndpoints.ApiEndpointBase; + } +} \ No newline at end of file diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/SecretApiKeyWebSocketConfig.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/SecretApiKeyWebSocketConfig.cs new file mode 100644 index 0000000..82f1875 --- /dev/null +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/SecretApiKeyWebSocketConfig.cs @@ -0,0 +1,11 @@ +using CoinbaseAdvancedTradeClient.Constants; + +namespace CoinbaseAdvancedTradeClient.Models.Config +{ + public class SecretApiKeyWebSocketConfig + { + public string KeyName { get; set; } + public string KeySecret { get; set; } + public string WebSocketUrl { get; set; } = ApiEndpoints.WebSocketEndpoint; + } +} \ No newline at end of file From 414659d4e4437cfd41acf43d2f094aa70732da1f Mon Sep 17 00:00:00 2001 From: Mike Pearl Date: Sun, 31 Aug 2025 19:04:46 -0700 Subject: [PATCH 05/24] Implement SecretApiKey JWT authentication using Ed25519 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add SecretApiKeyAuthenticator class with GenerateBearerJWT method - Implements Coinbase's new authentication using Ed25519 digital signatures - Validates Ed25519 key format (64 bytes: 32-byte seed + 32-byte public key) - Generates JWT with proper header, payload, and Ed25519 signature - Includes comprehensive input validation with descriptive error messages - Uses BouncyCastle for cryptographic operations 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- .../SecretApiKeyAuthenticator.cs | 108 ++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Authentication/SecretApiKeyAuthenticator.cs diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Authentication/SecretApiKeyAuthenticator.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Authentication/SecretApiKeyAuthenticator.cs new file mode 100644 index 0000000..7233325 --- /dev/null +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Authentication/SecretApiKeyAuthenticator.cs @@ -0,0 +1,108 @@ +using CoinbaseAdvancedTradeClient.Resources; +using Newtonsoft.Json; +using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Crypto.Signers; +using System.Globalization; +using System.Text; + +namespace CoinbaseAdvancedTradeClient.Authentication +{ + public static class SecretApiKeyAuthenticator + { + public static string GenerateBearerJWT(string keyName, string keySecret, string requestMethod, string requestHost, string requestPath) + { + if (string.IsNullOrWhiteSpace(keyName)) throw new ArgumentException(ErrorMessages.ApiKeyRequired, nameof(keyName)); + if (string.IsNullOrWhiteSpace(keySecret)) throw new ArgumentException(ErrorMessages.ApiSecretRequired, nameof(keySecret)); + if (string.IsNullOrWhiteSpace(requestMethod)) throw new ArgumentNullException(nameof(requestMethod), ErrorMessages.RequestMethodRequired); + if (string.IsNullOrWhiteSpace(requestHost)) throw new ArgumentNullException(nameof(requestHost), ErrorMessages.RequestHostRequired); + if (string.IsNullOrWhiteSpace(requestPath)) throw new ArgumentNullException(nameof(requestPath), ErrorMessages.RequestPathRequired); + + // Decode the Ed25519 private key from base64 + byte[] decoded; + try + { + decoded = Convert.FromBase64String(keySecret); + } + catch (FormatException ex) + { + throw new ArgumentException(ErrorMessages.InvalidBase64KeyFormat, nameof(keySecret), ex); + } + + // Ed25519 keys are 64 bytes (32 bytes seed + 32 bytes public key) + if (decoded.Length != 64) + { + throw new ArgumentException(ErrorMessages.InvalidEd25519KeyLength, nameof(keySecret)); + } + + // Extract the seed (first 32 bytes) + byte[] seed = new byte[32]; + Array.Copy(decoded, 0, seed, 0, 32); + + // Create Ed25519 private key parameters + var privateKey = new Ed25519PrivateKeyParameters(seed, 0); + + // Create the URI + string uri = $"{requestMethod.ToUpperInvariant()} {requestHost}{requestPath}"; + + // Create header + var header = new Dictionary + { + { "alg", "EdDSA" }, + { "typ", "JWT" }, + { "kid", keyName }, + { "nonce", GenerateNonce() } + }; + + // Create payload with timing + var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); + var payload = new Dictionary + { + { "sub", keyName }, + { "iss", "cdp" }, + { "aud", new[] { "cdp_service" } }, + { "nbf", now }, + { "exp", now + 120 }, // 2 minutes expiration + { "uri", uri } + }; + + // Encode header and payload + string headerJson = JsonConvert.SerializeObject(header); + string payloadJson = JsonConvert.SerializeObject(payload); + + string encodedHeader = Base64UrlEncode(Encoding.UTF8.GetBytes(headerJson)); + string encodedPayload = Base64UrlEncode(Encoding.UTF8.GetBytes(payloadJson)); + + string message = $"{encodedHeader}.{encodedPayload}"; + + // Sign with Ed25519 + var signer = new Ed25519Signer(); + signer.Init(true, privateKey); + byte[] messageBytes = Encoding.UTF8.GetBytes(message); + signer.BlockUpdate(messageBytes, 0, messageBytes.Length); + byte[] signature = signer.GenerateSignature(); + + string encodedSignature = Base64UrlEncode(signature); + + return $"{message}.{encodedSignature}"; + } + + private static string GenerateNonce() + { + var random = new Random(); + var nonce = new char[16]; + for (int i = 0; i < 16; i++) + { + nonce[i] = (char)('0' + random.Next(10)); + } + return new string(nonce); + } + + private static string Base64UrlEncode(byte[] input) + { + return Convert.ToBase64String(input) + .Replace("+", "-") + .Replace("/", "_") + .Replace("=", ""); + } + } +} \ No newline at end of file From d74d72ab9dd5d36af5a3122c6698d11107857a58 Mon Sep 17 00:00:00 2001 From: Mike Pearl Date: Sun, 31 Aug 2025 19:04:54 -0700 Subject: [PATCH 06/24] Add test helpers for SecretApiKey authentication MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add TestConfigHelper with Ed25519 test key generation - Include factory methods for creating test API and WebSocket configs - Generate valid 64-byte Ed25519 keys with deterministic test patterns 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- .../TestHelpers/TestConfigHelper.cs | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/TestHelpers/TestConfigHelper.cs diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/TestHelpers/TestConfigHelper.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/TestHelpers/TestConfigHelper.cs new file mode 100644 index 0000000..5261085 --- /dev/null +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/TestHelpers/TestConfigHelper.cs @@ -0,0 +1,36 @@ +using CoinbaseAdvancedTradeClient.Models.Config; + +namespace CoinbaseAdvancedTradeClient.UnitTests.TestHelpers +{ + public static class TestConfigHelper + { + // Generate a valid Ed25519 key for testing purposes + public static string GenerateTestKeySecret() + { + var keyBytes = new byte[64]; + for (int i = 0; i < 64; i++) + { + keyBytes[i] = (byte)(i % 256); // Fill with test pattern + } + return Convert.ToBase64String(keyBytes); + } + + public static SecretApiKeyConfig CreateTestApiConfig() + { + return new SecretApiKeyConfig() + { + KeyName = "test-key", + KeySecret = GenerateTestKeySecret() + }; + } + + public static SecretApiKeyWebSocketConfig CreateTestWebSocketConfig() + { + return new SecretApiKeyWebSocketConfig() + { + KeyName = "test-key", + KeySecret = GenerateTestKeySecret() + }; + } + } +} \ No newline at end of file From 0d3c28e9b3a760d194a1046d3576b68983072330 Mon Sep 17 00:00:00 2001 From: Mike Pearl Date: Sun, 31 Aug 2025 19:05:01 -0700 Subject: [PATCH 07/24] Add unit tests for SecretApiKey authentication MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add SecretApiKeyAuthenticatorTests with JWT generation validation - Test valid parameter scenarios and JWT format verification - Test error handling for invalid key formats - Verify proper 3-part JWT structure (header.payload.signature) 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- .../SecretApiKeyAuthenticatorTests.cs | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Authentication/SecretApiKeyAuthenticatorTests.cs diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Authentication/SecretApiKeyAuthenticatorTests.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Authentication/SecretApiKeyAuthenticatorTests.cs new file mode 100644 index 0000000..aafe20d --- /dev/null +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Authentication/SecretApiKeyAuthenticatorTests.cs @@ -0,0 +1,47 @@ +using CoinbaseAdvancedTradeClient.Authentication; +using CoinbaseAdvancedTradeClient.UnitTests.TestHelpers; +using Xunit; + +namespace CoinbaseAdvancedTradeClient.UnitTests.Authentication +{ + public class SecretApiKeyAuthenticatorTests + { + [Fact] + public void GenerateBearerJWT_ValidParameters_ReturnsJWT() + { + // Arrange + var testKeySecret = TestConfigHelper.GenerateTestKeySecret(); + + // Act & Assert - Should not throw exception + var jwt = SecretApiKeyAuthenticator.GenerateBearerJWT( + "test-key-name", + testKeySecret, + "GET", + "api.coinbase.com", + "/v1/test" + ); + + // Basic JWT format validation + Assert.NotNull(jwt); + Assert.Contains(".", jwt); + var parts = jwt.Split('.'); + Assert.Equal(3, parts.Length); // header.payload.signature + } + + [Fact] + public void GenerateBearerJWT_InvalidKeySecret_ThrowsArgumentException() + { + // Act & Assert + Assert.Throws(() => + { + SecretApiKeyAuthenticator.GenerateBearerJWT( + "test-key-name", + "invalid-key-format", + "GET", + "api.coinbase.com", + "/v1/test" + ); + }); + } + } +} \ No newline at end of file From 133c04cdcfc5f0942386fdaddcd2c9aff05af906 Mon Sep 17 00:00:00 2001 From: Mike Pearl Date: Sun, 31 Aug 2025 19:34:21 -0700 Subject: [PATCH 08/24] Add Authorization header constant for JWT Bearer authentication MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add Authorization header constant to RequestHeaders class - Required for new SecretApiKey JWT-based authentication 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- .../CoinbaseAdvancedTradeClient/Constants/RequestHeaders.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Constants/RequestHeaders.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Constants/RequestHeaders.cs index 3671601..5fbd44e 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Constants/RequestHeaders.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Constants/RequestHeaders.cs @@ -2,6 +2,7 @@ { public sealed class RequestHeaders { + public const string Authorization = "Authorization"; public const string AccessKey = "CB-ACCESS-KEY"; public const string AccessSign = "CB-ACCESS-SIGN"; public const string AccessTimestamp = "CB-ACCESS-TIMESTAMP"; From 885be536d5bf26738e36450fb5b886a48b76dd38 Mon Sep 17 00:00:00 2001 From: Mike Pearl Date: Sun, 31 Aug 2025 19:34:31 -0700 Subject: [PATCH 09/24] Add Bearer token format string resource MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add BearerTokenFormat resource with value "Bearer {0}" - Update ErrorMessages.Designer.cs with new resource property - Enables localization and centralized management of Bearer token format 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- .../Resources/ErrorMessages.Designer.cs | 9 +++++++++ .../Resources/ErrorMessages.resx | 3 +++ 2 files changed, 12 insertions(+) diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Resources/ErrorMessages.Designer.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Resources/ErrorMessages.Designer.cs index dadce3a..25ea833 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Resources/ErrorMessages.Designer.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Resources/ErrorMessages.Designer.cs @@ -320,5 +320,14 @@ public static string InvalidEd25519KeyLength { return ResourceManager.GetString("InvalidEd25519KeyLength", resourceCulture); } } + + /// + /// Looks up a localized string similar to Bearer {0}. + /// + public static string BearerTokenFormat { + get { + return ResourceManager.GetString("BearerTokenFormat", resourceCulture); + } + } } } diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Resources/ErrorMessages.resx b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Resources/ErrorMessages.resx index 70c15a1..eb5af4b 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Resources/ErrorMessages.resx +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Resources/ErrorMessages.resx @@ -204,4 +204,7 @@ Invalid Ed25519 key length. Expected 64 bytes. + + Bearer {0} + \ No newline at end of file From 5790f458f2f330d1c048d6de42b15327cbcb5165 Mon Sep 17 00:00:00 2001 From: Mike Pearl Date: Sun, 31 Aug 2025 19:36:09 -0700 Subject: [PATCH 10/24] Replace deprecated ApiKeyAuthenticator with SecretApiKeyAuthenticator MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Update CoinbaseAdvancedTradeApiClient to use JWT Bearer authentication - Update CoinbaseAdvancedTradeWebSocketClient to use JWT signatures - Replace HMAC-SHA256 signatures with Ed25519 JWT tokens - Use Authorization header with Bearer token format from string resources - Remove deprecated ApiKeyAuthenticator.cs - Switch from ApiClientConfig/WebSocketClientConfig to SecretApiKey variants BREAKING CHANGE: Authentication method changed from HMAC to Ed25519 JWT 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- .../Authentication/ApiKeyAuthenticator.cs | 47 ------------------- .../CoinbaseAdvancedTradeApiClient.cs | 29 ++++++------ .../CoinbaseAdvancedTradeWebsocketClient.cs | 36 ++++++++------ 3 files changed, 37 insertions(+), 75 deletions(-) delete mode 100644 CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Authentication/ApiKeyAuthenticator.cs diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Authentication/ApiKeyAuthenticator.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Authentication/ApiKeyAuthenticator.cs deleted file mode 100644 index 98cba85..0000000 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Authentication/ApiKeyAuthenticator.cs +++ /dev/null @@ -1,47 +0,0 @@ -using CoinbaseAdvancedTradeClient.Resources; -using System.Globalization; -using System.Security.Cryptography; -using System.Text; - -namespace CoinbaseAdvancedTradeClient.Authentication -{ - public static class ApiKeyAuthenticator - { - public static string GenerateTimestamp() - { - var unixTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); - var timestamp = unixTime.ToString(CultureInfo.InvariantCulture); - - return timestamp; - } - - public static string GenerateApiSignature(string apiSecret, string timestamp, string method, string requestPath, string body) - { - return Sign(apiSecret, timestamp + method + requestPath + body); - } - - public static string GenerateWebSocketSignature(string apiSecret, string timestamp, string channel, ICollection productIds) - { - if (string.IsNullOrWhiteSpace(channel)) throw new ArgumentNullException(nameof(channel), ErrorMessages.ChannelRequired); - if (productIds == null || !productIds.Any()) throw new ArgumentNullException(nameof(productIds), ErrorMessages.ProductIdRequired); - - var products = string.Join(",", productIds); - - return Sign(apiSecret, timestamp + channel + products); - } - - private static string Sign(string apiSecret, string data) - { - var apiSecretBytes = Encoding.UTF8.GetBytes(apiSecret); - var dataBytes = Encoding.UTF8.GetBytes(data); - - using (var hmac = new HMACSHA256(apiSecretBytes)) - { - var hash = hmac.ComputeHash(dataBytes); - var signature = Convert.ToHexString(hash).ToLowerInvariant(); - - return signature; - } - } - } -} diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeApiClient.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeApiClient.cs index 1bcf829..4ac986f 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeApiClient.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeApiClient.cs @@ -11,35 +11,36 @@ namespace CoinbaseAdvancedTradeClient { public partial class CoinbaseAdvancedTradeApiClient : FlurlClient, ICoinbaseAdvancedTradeApiClient { - private ApiClientConfig _config; + private SecretApiKeyConfig _config; - public CoinbaseAdvancedTradeApiClient(ApiClientConfig config) + public CoinbaseAdvancedTradeApiClient(SecretApiKeyConfig config) { if (config == null) throw new ArgumentNullException(nameof(config), ErrorMessages.ApiConfigRequired); - if (string.IsNullOrWhiteSpace(config.ApiKey)) throw new ArgumentException(ErrorMessages.ApiKeyRequired, nameof(config.ApiKey)); - if (string.IsNullOrWhiteSpace(config.ApiSecret)) throw new ArgumentException(ErrorMessages.ApiSecretRequired, nameof(config.ApiSecret)); + if (string.IsNullOrWhiteSpace(config.KeyName)) throw new ArgumentException(ErrorMessages.ApiKeyRequired, nameof(config.KeyName)); + if (string.IsNullOrWhiteSpace(config.KeySecret)) throw new ArgumentException(ErrorMessages.ApiSecretRequired, nameof(config.KeySecret)); _config = config; - this.Configure(ApiKeyAuthentication); + this.Configure(SecretApiKeyAuthentication); } #region Authentication - private void ApiKeyAuthentication(ClientFlurlHttpSettings settings) + private void SecretApiKeyAuthentication(ClientFlurlHttpSettings settings) { async Task SetHeaders(FlurlCall http) { - var body = http.RequestBody; var method = http.Request.Verb.Method.ToUpperInvariant(); var url = http.Request.Url.ToUri().AbsolutePath; - var timestamp = ApiKeyAuthenticator.GenerateTimestamp(); - var signature = ApiKeyAuthenticator.GenerateApiSignature(_config.ApiSecret, timestamp, method, url, body); - - http.Request - .WithHeader(RequestHeaders.AccessKey, _config.ApiKey) - .WithHeader(RequestHeaders.AccessSign, signature) - .WithHeader(RequestHeaders.AccessTimestamp, timestamp); + var host = http.Request.Url.ToUri().Host; + var jwt = SecretApiKeyAuthenticator.GenerateBearerJWT( + _config.KeyName, + _config.KeySecret, + method, + host, + url); + + http.Request.WithHeader(RequestHeaders.Authorization, string.Format(ErrorMessages.BearerTokenFormat, jwt)); } settings.BeforeCallAsync = SetHeaders; diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeWebsocketClient.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeWebsocketClient.cs index 7ca4fc9..6c0d4b8 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeWebsocketClient.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeWebsocketClient.cs @@ -15,7 +15,7 @@ namespace CoinbaseAdvancedTradeClient { public class CoinbaseAdvancedTradeWebSocketClient : ICoinbaseAdvancedTradeWebSocketClient, IDisposable { - private WebSocketClientConfig _config; + private SecretApiKeyWebSocketConfig _config; private WebSocket _socket; private Action _messageReceivedCallback; @@ -25,11 +25,11 @@ public class CoinbaseAdvancedTradeWebSocketClient : ICoinbaseAdvancedTradeWebSoc public bool IsConnected => _socket?.State == WebSocketState.Open; - public CoinbaseAdvancedTradeWebSocketClient(WebSocketClientConfig config) + public CoinbaseAdvancedTradeWebSocketClient(SecretApiKeyWebSocketConfig config) { if (config == null) throw new ArgumentNullException(nameof(config), ErrorMessages.ApiConfigRequired); - if (string.IsNullOrWhiteSpace(config.ApiKey)) throw new ArgumentException(ErrorMessages.ApiKeyRequired, nameof(config.ApiKey)); - if (string.IsNullOrWhiteSpace(config.ApiSecret)) throw new ArgumentException(ErrorMessages.ApiSecretRequired, nameof(config.ApiSecret)); + if (string.IsNullOrWhiteSpace(config.KeyName)) throw new ArgumentException(ErrorMessages.ApiKeyRequired, nameof(config.KeyName)); + if (string.IsNullOrWhiteSpace(config.KeySecret)) throw new ArgumentException(ErrorMessages.ApiSecretRequired, nameof(config.KeySecret)); _config = config; } @@ -80,16 +80,20 @@ public void Subscribe(string channel, List productIds) if (!IsConnected) throw new InvalidOperationException(ErrorMessages.WebSocketMustBeConnected); - var timestamp = ApiKeyAuthenticator.GenerateTimestamp(); - var signature = ApiKeyAuthenticator.GenerateWebSocketSignature(_config.ApiSecret, timestamp, channel, productIds); + var jwt = SecretApiKeyAuthenticator.GenerateBearerJWT( + _config.KeyName, + _config.KeySecret, + "GET", + "advanced-trade-ws.coinbase.com", + "/"); var subscriptionMessage = new SubscriptionMessage { - ApiKey = _config.ApiKey, + ApiKey = _config.KeyName, Channel = channel, ProductIds = productIds, - Signature = signature, - Timestamp = timestamp, + Signature = jwt, + Timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(), Type = SubscriptionType.Subscribe, }; @@ -105,16 +109,20 @@ public void Unsubscribe(string channel, List productIds) if (!IsConnected) throw new InvalidOperationException(ErrorMessages.WebSocketMustBeConnected); - var timestamp = ApiKeyAuthenticator.GenerateTimestamp(); - var signature = ApiKeyAuthenticator.GenerateWebSocketSignature(_config.ApiSecret, timestamp, channel, productIds); + var jwt = SecretApiKeyAuthenticator.GenerateBearerJWT( + _config.KeyName, + _config.KeySecret, + "GET", + "advanced-trade-ws.coinbase.com", + "/"); var unsubscribeMessage = new SubscriptionMessage { - ApiKey = _config.ApiKey, + ApiKey = _config.KeyName, Channel = channel, ProductIds = productIds, - Signature = signature, - Timestamp = timestamp, + Signature = jwt, + Timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(), Type = SubscriptionType.Unsubscribe }; From 046ef4fbd7c73b1673e43da09719c89e66a4cb48 Mon Sep 17 00:00:00 2001 From: Mike Pearl Date: Sun, 31 Aug 2025 19:36:19 -0700 Subject: [PATCH 11/24] Mark legacy configuration models as obsolete MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add [Obsolete] attributes to ApiClientConfig and WebSocketClientConfig - Provide clear migration guidance to SecretApiKey variants - Maintain backward compatibility while encouraging migration 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- .../CoinbaseAdvancedTradeClient/Models/Config/ApiClientConfig.cs | 1 + .../Models/Config/WebsocketClientConfig.cs | 1 + 2 files changed, 2 insertions(+) diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/ApiClientConfig.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/ApiClientConfig.cs index b38435f..b46446e 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/ApiClientConfig.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/ApiClientConfig.cs @@ -2,6 +2,7 @@ namespace CoinbaseAdvancedTradeClient.Models.Config { + [Obsolete("ApiClientConfig is deprecated. Use SecretApiKeyConfig instead for the new Ed25519 JWT authentication.")] public class ApiClientConfig { public string ApiKey { get; set; } diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/WebsocketClientConfig.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/WebsocketClientConfig.cs index d65f90e..b89a1c6 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/WebsocketClientConfig.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/WebsocketClientConfig.cs @@ -2,6 +2,7 @@ namespace CoinbaseAdvancedTradeClient.Models.Config { + [Obsolete("WebSocketClientConfig is deprecated. Use SecretApiKeyWebSocketConfig instead for the new Ed25519 JWT authentication.")] public class WebSocketClientConfig { public string ApiKey { get; set; } From 009005b238d85dbf1e58e7ec7720b430bc335212 Mon Sep 17 00:00:00 2001 From: Mike Pearl Date: Sun, 31 Aug 2025 19:36:28 -0700 Subject: [PATCH 12/24] Update unit tests to use new SecretApiKey authentication MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Update all test files to use SecretApiKeyConfig instead of ApiClientConfig - Update WebSocket tests to use SecretApiKeyWebSocketConfig - Switch from ApiKey/ApiSecret to KeyName/KeySecret property names - Use TestConfigHelper.GenerateTestKeySecret() for proper Ed25519 key generation - All 144 tests continue to pass with new authentication system 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- .../CoinbaseAdvancedTradeApiClientTests.cs | 8 ++++---- .../CoinbaseAdvancedTradeWebSocketClientTests.cs | 14 +++++++------- .../Endpoints/AccountsEndpointTests.cs | 6 +++--- .../Endpoints/OrdersEndpointTests.cs | 6 +++--- .../Endpoints/ProductsEndpointTests.cs | 6 +++--- .../Endpoints/TransactionSummaryEndpointTests.cs | 6 +++--- 6 files changed, 23 insertions(+), 23 deletions(-) diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeApiClientTests.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeApiClientTests.cs index 0faba69..30f97d1 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeApiClientTests.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeApiClientTests.cs @@ -9,7 +9,7 @@ public class CoinbaseAdvancedTradeApiClientTests public void Constructor_NullConfig_ThrowsArgumentNullException() { //Arrange - ApiClientConfig config = null; + SecretApiKeyConfig config = null; //Act & Assert Assert.Throws(() => @@ -27,10 +27,10 @@ public void Constructor_NullConfig_ThrowsArgumentNullException() public void Constructor_EmptyConfigSetting_ThrowsArgumentException(string key, string secret) { //Arrange - ApiClientConfig config = new ApiClientConfig() + SecretApiKeyConfig config = new SecretApiKeyConfig() { - ApiKey = key, - ApiSecret = secret + KeyName = key, + KeySecret = secret }; //Act & Assert diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeWebSocketClientTests.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeWebSocketClientTests.cs index ff7c831..4928e21 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeWebSocketClientTests.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeWebSocketClientTests.cs @@ -12,7 +12,7 @@ public class CoinbaseAdvancedTradeWebSocketClientTests public void Constructor_NullConfig_ThrowsArgumentNullException() { //Arrange - WebSocketClientConfig config = null; + SecretApiKeyWebSocketConfig config = null; //Act & Assert Assert.Throws(() => @@ -30,10 +30,10 @@ public void Constructor_NullConfig_ThrowsArgumentNullException() public void Constructor_EmptyConfigSetting_ThrowsArgumentException(string key, string secret) { //Arrange - WebSocketClientConfig config = new WebSocketClientConfig() + SecretApiKeyWebSocketConfig config = new SecretApiKeyWebSocketConfig() { - ApiKey = key, - ApiSecret = secret + KeyName = key, + KeySecret = secret }; //Act & Assert @@ -164,10 +164,10 @@ public void Unsubscribe_EmptyProductIds_ThrowsArgumentNullException() private ICoinbaseAdvancedTradeWebSocketClient CreateTestClient() { - WebSocketClientConfig config = new WebSocketClientConfig() + SecretApiKeyWebSocketConfig config = new SecretApiKeyWebSocketConfig() { - ApiKey = "testKey", - ApiSecret = "testSecret" + KeyName = "testKey", + KeySecret = TestHelpers.TestConfigHelper.GenerateTestKeySecret() }; return new CoinbaseAdvancedTradeWebSocketClient(config); diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/AccountsEndpointTests.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/AccountsEndpointTests.cs index 6fa6ea5..7f1ccd1 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/AccountsEndpointTests.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/AccountsEndpointTests.cs @@ -16,10 +16,10 @@ public class AccountsEndpointTests public AccountsEndpointTests() { - var config = new ApiClientConfig() + var config = new SecretApiKeyConfig() { - ApiKey = "key", - ApiSecret = "secret" + KeyName = "key", + KeySecret = TestHelpers.TestConfigHelper.GenerateTestKeySecret() }; _testClient = new CoinbaseAdvancedTradeApiClient(config); diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/OrdersEndpointTests.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/OrdersEndpointTests.cs index c20f935..d63924c 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/OrdersEndpointTests.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/OrdersEndpointTests.cs @@ -17,10 +17,10 @@ public class OrdersEndpointTests public OrdersEndpointTests() { - var config = new ApiClientConfig() + var config = new SecretApiKeyConfig() { - ApiKey = "key", - ApiSecret = "secret" + KeyName = "key", + KeySecret = TestHelpers.TestConfigHelper.GenerateTestKeySecret() }; _testClient = new CoinbaseAdvancedTradeApiClient(config); diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/ProductsEndpointTests.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/ProductsEndpointTests.cs index 89ce47e..57bc94c 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/ProductsEndpointTests.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/ProductsEndpointTests.cs @@ -17,10 +17,10 @@ public class ProductsEndpointTests public ProductsEndpointTests() { - var config = new ApiClientConfig() + var config = new SecretApiKeyConfig() { - ApiKey = "key", - ApiSecret = "secret" + KeyName = "key", + KeySecret = TestHelpers.TestConfigHelper.GenerateTestKeySecret() }; _testClient = new CoinbaseAdvancedTradeApiClient(config); diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/TransactionSummaryEndpointTests.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/TransactionSummaryEndpointTests.cs index aeb81de..00dbe81 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/TransactionSummaryEndpointTests.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/TransactionSummaryEndpointTests.cs @@ -16,10 +16,10 @@ public class TransactionSummaryEndpointTests public TransactionSummaryEndpointTests() { - var config = new ApiClientConfig() + var config = new SecretApiKeyConfig() { - ApiKey = "key", - ApiSecret = "secret" + KeyName = "key", + KeySecret = TestHelpers.TestConfigHelper.GenerateTestKeySecret() }; _testClient = new CoinbaseAdvancedTradeApiClient(config); From 1e646b8d95ca929c15064279164921c43d6d3e32 Mon Sep 17 00:00:00 2001 From: Mike Pearl Date: Mon, 1 Sep 2025 16:17:24 -0700 Subject: [PATCH 13/24] Switch to ES256 key format. --- .../TestHelpers/TestConfigHelper.cs | 31 ++++++-- .../SecretApiKeyAuthenticator.cs | 70 ++++++++++++------- .../Resources/ErrorMessages.Designer.cs | 6 +- .../Resources/ErrorMessages.resx | 4 +- 4 files changed, 74 insertions(+), 37 deletions(-) diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/TestHelpers/TestConfigHelper.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/TestHelpers/TestConfigHelper.cs index 5261085..92ec31e 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/TestHelpers/TestConfigHelper.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/TestHelpers/TestConfigHelper.cs @@ -1,18 +1,35 @@ using CoinbaseAdvancedTradeClient.Models.Config; +using Org.BouncyCastle.Crypto.Generators; +using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Math.EC; +using Org.BouncyCastle.Security; +using Org.BouncyCastle.OpenSsl; +using Org.BouncyCastle.Asn1.Sec; +using System.Text; namespace CoinbaseAdvancedTradeClient.UnitTests.TestHelpers { public static class TestConfigHelper { - // Generate a valid Ed25519 key for testing purposes + // Generate a valid EC P-256 private key for testing purposes public static string GenerateTestKeySecret() { - var keyBytes = new byte[64]; - for (int i = 0; i < 64; i++) - { - keyBytes[i] = (byte)(i % 256); // Fill with test pattern - } - return Convert.ToBase64String(keyBytes); + // Generate P-256 (secp256r1) key pair + var keyGen = new ECKeyPairGenerator(); + var curveParams = SecNamedCurves.GetByName("secp256r1"); + var domainParams = new ECDomainParameters(curveParams.Curve, curveParams.G, curveParams.N, curveParams.H); + keyGen.Init(new ECKeyGenerationParameters(domainParams, new SecureRandom())); + + var keyPair = keyGen.GenerateKeyPair(); + var privateKey = (ECPrivateKeyParameters)keyPair.Private; + + // Convert to PEM format + using var stringWriter = new StringWriter(); + var pemWriter = new PemWriter(stringWriter); + pemWriter.WriteObject(privateKey); + pemWriter.Writer.Flush(); + + return stringWriter.ToString(); } public static SecretApiKeyConfig CreateTestApiConfig() diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Authentication/SecretApiKeyAuthenticator.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Authentication/SecretApiKeyAuthenticator.cs index 7233325..339fce2 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Authentication/SecretApiKeyAuthenticator.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Authentication/SecretApiKeyAuthenticator.cs @@ -2,7 +2,8 @@ using Newtonsoft.Json; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Signers; -using System.Globalization; +using Org.BouncyCastle.OpenSsl; +using Org.BouncyCastle.Security; using System.Text; namespace CoinbaseAdvancedTradeClient.Authentication @@ -17,37 +18,33 @@ public static string GenerateBearerJWT(string keyName, string keySecret, string if (string.IsNullOrWhiteSpace(requestHost)) throw new ArgumentNullException(nameof(requestHost), ErrorMessages.RequestHostRequired); if (string.IsNullOrWhiteSpace(requestPath)) throw new ArgumentNullException(nameof(requestPath), ErrorMessages.RequestPathRequired); - // Decode the Ed25519 private key from base64 - byte[] decoded; + // Parse the EC private key from PEM format + ECPrivateKeyParameters privateKey; try { - decoded = Convert.FromBase64String(keySecret); + using var stringReader = new StringReader(keySecret); + var pemReader = new PemReader(stringReader); + var keyObject = pemReader.ReadObject(); + + if (keyObject is not ECPrivateKeyParameters ecKey) + { + throw new ArgumentException(ErrorMessages.InvalidECKeyFormat, nameof(keySecret)); + } + + privateKey = ecKey; } - catch (FormatException ex) + catch (Exception ex) when (!(ex is ArgumentException)) { - throw new ArgumentException(ErrorMessages.InvalidBase64KeyFormat, nameof(keySecret), ex); + throw new ArgumentException(ErrorMessages.InvalidECKeyFormat, nameof(keySecret), ex); } - // Ed25519 keys are 64 bytes (32 bytes seed + 32 bytes public key) - if (decoded.Length != 64) - { - throw new ArgumentException(ErrorMessages.InvalidEd25519KeyLength, nameof(keySecret)); - } - - // Extract the seed (first 32 bytes) - byte[] seed = new byte[32]; - Array.Copy(decoded, 0, seed, 0, 32); - - // Create Ed25519 private key parameters - var privateKey = new Ed25519PrivateKeyParameters(seed, 0); - // Create the URI string uri = $"{requestMethod.ToUpperInvariant()} {requestHost}{requestPath}"; // Create header var header = new Dictionary { - { "alg", "EdDSA" }, + { "alg", "ES256" }, { "typ", "JWT" }, { "kid", keyName }, { "nonce", GenerateNonce() } @@ -74,14 +71,37 @@ public static string GenerateBearerJWT(string keyName, string keySecret, string string message = $"{encodedHeader}.{encodedPayload}"; - // Sign with Ed25519 - var signer = new Ed25519Signer(); + // Sign with ECDSA (ES256) + var signer = new ECDsaSigner(); signer.Init(true, privateKey); byte[] messageBytes = Encoding.UTF8.GetBytes(message); - signer.BlockUpdate(messageBytes, 0, messageBytes.Length); - byte[] signature = signer.GenerateSignature(); + byte[] hash = DigestUtilities.CalculateDigest("SHA-256", messageBytes); + var signature = signer.GenerateSignature(hash); + + // Convert DER signature to IEEE P1363 format (r|s) + var r = signature[0].ToByteArrayUnsigned(); + var s = signature[1].ToByteArrayUnsigned(); + + // Ensure both r and s are 32 bytes (pad with leading zeros if needed) + if (r.Length < 32) + { + var padded = new byte[32]; + Array.Copy(r, 0, padded, 32 - r.Length, r.Length); + r = padded; + } + if (s.Length < 32) + { + var padded = new byte[32]; + Array.Copy(s, 0, padded, 32 - s.Length, s.Length); + s = padded; + } + + // Combine r and s + var signatureBytes = new byte[64]; + Array.Copy(r, 0, signatureBytes, 0, 32); + Array.Copy(s, 0, signatureBytes, 32, 32); - string encodedSignature = Base64UrlEncode(signature); + string encodedSignature = Base64UrlEncode(signatureBytes); return $"{message}.{encodedSignature}"; } diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Resources/ErrorMessages.Designer.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Resources/ErrorMessages.Designer.cs index 25ea833..2682086 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Resources/ErrorMessages.Designer.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Resources/ErrorMessages.Designer.cs @@ -313,11 +313,11 @@ public static string InvalidBase64KeyFormat { } /// - /// Looks up a localized string similar to Invalid Ed25519 key length. Expected 64 bytes.. + /// Looks up a localized string similar to Invalid EC private key format. Expected PEM format.. /// - public static string InvalidEd25519KeyLength { + public static string InvalidECKeyFormat { get { - return ResourceManager.GetString("InvalidEd25519KeyLength", resourceCulture); + return ResourceManager.GetString("InvalidECKeyFormat", resourceCulture); } } diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Resources/ErrorMessages.resx b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Resources/ErrorMessages.resx index eb5af4b..ca074b7 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Resources/ErrorMessages.resx +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Resources/ErrorMessages.resx @@ -201,8 +201,8 @@ Invalid base64 key format. - - Invalid Ed25519 key length. Expected 64 bytes. + + Invalid EC private key format. Expected PEM format. Bearer {0} From 5a4fa8a1b9e8d27aacc63116e01b66f0b5ae9c65 Mon Sep 17 00:00:00 2001 From: Mike Pearl Date: Mon, 1 Sep 2025 16:41:53 -0700 Subject: [PATCH 14/24] Fix unit tests --- .../TestHelpers/TestConfigHelper.cs | 3 --- .../Authentication/SecretApiKeyAuthenticator.cs | 13 ++++++++++--- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/TestHelpers/TestConfigHelper.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/TestHelpers/TestConfigHelper.cs index 92ec31e..05d49a9 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/TestHelpers/TestConfigHelper.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/TestHelpers/TestConfigHelper.cs @@ -1,11 +1,9 @@ using CoinbaseAdvancedTradeClient.Models.Config; using Org.BouncyCastle.Crypto.Generators; using Org.BouncyCastle.Crypto.Parameters; -using Org.BouncyCastle.Math.EC; using Org.BouncyCastle.Security; using Org.BouncyCastle.OpenSsl; using Org.BouncyCastle.Asn1.Sec; -using System.Text; namespace CoinbaseAdvancedTradeClient.UnitTests.TestHelpers { @@ -27,7 +25,6 @@ public static string GenerateTestKeySecret() using var stringWriter = new StringWriter(); var pemWriter = new PemWriter(stringWriter); pemWriter.WriteObject(privateKey); - pemWriter.Writer.Flush(); return stringWriter.ToString(); } diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Authentication/SecretApiKeyAuthenticator.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Authentication/SecretApiKeyAuthenticator.cs index 339fce2..55e594a 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Authentication/SecretApiKeyAuthenticator.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Authentication/SecretApiKeyAuthenticator.cs @@ -1,5 +1,6 @@ using CoinbaseAdvancedTradeClient.Resources; using Newtonsoft.Json; +using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Signers; using Org.BouncyCastle.OpenSsl; @@ -26,12 +27,18 @@ public static string GenerateBearerJWT(string keyName, string keySecret, string var pemReader = new PemReader(stringReader); var keyObject = pemReader.ReadObject(); - if (keyObject is not ECPrivateKeyParameters ecKey) + if (keyObject is ECPrivateKeyParameters ecKey) + { + privateKey = ecKey; + } + else if (keyObject is AsymmetricCipherKeyPair keyPair && keyPair.Private is ECPrivateKeyParameters ecPrivateKey) + { + privateKey = ecPrivateKey; + } + else { throw new ArgumentException(ErrorMessages.InvalidECKeyFormat, nameof(keySecret)); } - - privateKey = ecKey; } catch (Exception ex) when (!(ex is ArgumentException)) { From ab48784fb907f914100f7649860e3bd7ddf06159 Mon Sep 17 00:00:00 2001 From: Mike Pearl Date: Mon, 1 Sep 2025 17:09:32 -0700 Subject: [PATCH 15/24] Update WebSocket SubscriptionMessage --- .../CoinbaseAdvancedTradeWebsocketClient.cs | 14 +++++--------- .../Models/WebSocket/SubscriptionMessage.cs | 10 ++-------- 2 files changed, 7 insertions(+), 17 deletions(-) diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeWebsocketClient.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeWebsocketClient.cs index 6c0d4b8..49ee7bc 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeWebsocketClient.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeWebsocketClient.cs @@ -84,17 +84,15 @@ public void Subscribe(string channel, List productIds) _config.KeyName, _config.KeySecret, "GET", - "advanced-trade-ws.coinbase.com", + _config.WebSocketUrl, "/"); var subscriptionMessage = new SubscriptionMessage { - ApiKey = _config.KeyName, + Type = SubscriptionType.Subscribe, Channel = channel, ProductIds = productIds, - Signature = jwt, - Timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(), - Type = SubscriptionType.Subscribe, + Jwt = jwt }; var subscribe = JsonConvert.SerializeObject(subscriptionMessage); @@ -118,12 +116,10 @@ public void Unsubscribe(string channel, List productIds) var unsubscribeMessage = new SubscriptionMessage { - ApiKey = _config.KeyName, + Type = SubscriptionType.Unsubscribe, Channel = channel, ProductIds = productIds, - Signature = jwt, - Timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(), - Type = SubscriptionType.Unsubscribe + Jwt = jwt }; var unsubscribe = JsonConvert.SerializeObject(unsubscribeMessage); diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/WebSocket/SubscriptionMessage.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/WebSocket/SubscriptionMessage.cs index f2e2c61..785bb2a 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/WebSocket/SubscriptionMessage.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/WebSocket/SubscriptionMessage.cs @@ -14,13 +14,7 @@ public class SubscriptionMessage [JsonProperty("product_ids")] public List ProductIds { get; set; } - [JsonProperty("api_key")] - public string ApiKey { get; set; } - - [JsonProperty("timestamp")] - public string Timestamp { get; set; } - - [JsonProperty("signature")] - public string Signature { get; set; } + [JsonProperty("jwt")] + public string Jwt { get; set; } } } From e8d40d7d2f2a9b6e8e2f5d6cc2dcee6e183ee126 Mon Sep 17 00:00:00 2001 From: Mike Pearl Date: Mon, 1 Sep 2025 17:38:32 -0700 Subject: [PATCH 16/24] Merge config files into CoinbaseClientConfig. --- .../CoinbaseAdvancedTradeApiClientTests.cs | 4 ++-- .../CoinbaseAdvancedTradeWebSocketClientTests.cs | 6 +++--- .../Endpoints/AccountsEndpointTests.cs | 2 +- .../Endpoints/OrdersEndpointTests.cs | 2 +- .../Endpoints/ProductsEndpointTests.cs | 2 +- .../Endpoints/TransactionSummaryEndpointTests.cs | 2 +- .../TestHelpers/TestConfigHelper.cs | 8 ++++---- .../CoinbaseAdvancedTradeApiClient.cs | 4 ++-- .../CoinbaseAdvancedTradeWebsocketClient.cs | 4 ++-- .../Endpoints/AccountsEndpoint.cs | 4 ++-- .../Endpoints/OrdersEndpoint.cs | 10 +++++----- .../Endpoints/ProductsEndpoint.cs | 8 ++++---- .../Endpoints/TransactionSummaryEndpoint.cs | 2 +- .../Models/Config/ApiClientConfig.cs | 12 ------------ ...KeyWebSocketConfig.cs => CoinbaseClientConfig.cs} | 7 ++++--- .../Models/Config/SecretApiKeyConfig.cs | 11 ----------- .../Models/Config/WebsocketClientConfig.cs | 12 ------------ 17 files changed, 33 insertions(+), 67 deletions(-) delete mode 100644 CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/ApiClientConfig.cs rename CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/{SecretApiKeyWebSocketConfig.cs => CoinbaseClientConfig.cs} (57%) delete mode 100644 CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/SecretApiKeyConfig.cs delete mode 100644 CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/WebsocketClientConfig.cs diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeApiClientTests.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeApiClientTests.cs index 30f97d1..5de2d0b 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeApiClientTests.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeApiClientTests.cs @@ -9,7 +9,7 @@ public class CoinbaseAdvancedTradeApiClientTests public void Constructor_NullConfig_ThrowsArgumentNullException() { //Arrange - SecretApiKeyConfig config = null; + CoinbaseClientConfig config = null; //Act & Assert Assert.Throws(() => @@ -27,7 +27,7 @@ public void Constructor_NullConfig_ThrowsArgumentNullException() public void Constructor_EmptyConfigSetting_ThrowsArgumentException(string key, string secret) { //Arrange - SecretApiKeyConfig config = new SecretApiKeyConfig() + CoinbaseClientConfig config = new CoinbaseClientConfig() { KeyName = key, KeySecret = secret diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeWebSocketClientTests.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeWebSocketClientTests.cs index 4928e21..b946f98 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeWebSocketClientTests.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeWebSocketClientTests.cs @@ -12,7 +12,7 @@ public class CoinbaseAdvancedTradeWebSocketClientTests public void Constructor_NullConfig_ThrowsArgumentNullException() { //Arrange - SecretApiKeyWebSocketConfig config = null; + CoinbaseClientConfig config = null; //Act & Assert Assert.Throws(() => @@ -30,7 +30,7 @@ public void Constructor_NullConfig_ThrowsArgumentNullException() public void Constructor_EmptyConfigSetting_ThrowsArgumentException(string key, string secret) { //Arrange - SecretApiKeyWebSocketConfig config = new SecretApiKeyWebSocketConfig() + CoinbaseClientConfig config = new CoinbaseClientConfig() { KeyName = key, KeySecret = secret @@ -164,7 +164,7 @@ public void Unsubscribe_EmptyProductIds_ThrowsArgumentNullException() private ICoinbaseAdvancedTradeWebSocketClient CreateTestClient() { - SecretApiKeyWebSocketConfig config = new SecretApiKeyWebSocketConfig() + CoinbaseClientConfig config = new CoinbaseClientConfig() { KeyName = "testKey", KeySecret = TestHelpers.TestConfigHelper.GenerateTestKeySecret() diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/AccountsEndpointTests.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/AccountsEndpointTests.cs index 7f1ccd1..d5fc345 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/AccountsEndpointTests.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/AccountsEndpointTests.cs @@ -16,7 +16,7 @@ public class AccountsEndpointTests public AccountsEndpointTests() { - var config = new SecretApiKeyConfig() + var config = new CoinbaseClientConfig() { KeyName = "key", KeySecret = TestHelpers.TestConfigHelper.GenerateTestKeySecret() diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/OrdersEndpointTests.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/OrdersEndpointTests.cs index d63924c..095a72e 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/OrdersEndpointTests.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/OrdersEndpointTests.cs @@ -17,7 +17,7 @@ public class OrdersEndpointTests public OrdersEndpointTests() { - var config = new SecretApiKeyConfig() + var config = new CoinbaseClientConfig() { KeyName = "key", KeySecret = TestHelpers.TestConfigHelper.GenerateTestKeySecret() diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/ProductsEndpointTests.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/ProductsEndpointTests.cs index 57bc94c..a05673b 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/ProductsEndpointTests.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/ProductsEndpointTests.cs @@ -17,7 +17,7 @@ public class ProductsEndpointTests public ProductsEndpointTests() { - var config = new SecretApiKeyConfig() + var config = new CoinbaseClientConfig() { KeyName = "key", KeySecret = TestHelpers.TestConfigHelper.GenerateTestKeySecret() diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/TransactionSummaryEndpointTests.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/TransactionSummaryEndpointTests.cs index 00dbe81..3f85c3a 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/TransactionSummaryEndpointTests.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/TransactionSummaryEndpointTests.cs @@ -16,7 +16,7 @@ public class TransactionSummaryEndpointTests public TransactionSummaryEndpointTests() { - var config = new SecretApiKeyConfig() + var config = new CoinbaseClientConfig() { KeyName = "key", KeySecret = TestHelpers.TestConfigHelper.GenerateTestKeySecret() diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/TestHelpers/TestConfigHelper.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/TestHelpers/TestConfigHelper.cs index 05d49a9..0374d06 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/TestHelpers/TestConfigHelper.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/TestHelpers/TestConfigHelper.cs @@ -29,18 +29,18 @@ public static string GenerateTestKeySecret() return stringWriter.ToString(); } - public static SecretApiKeyConfig CreateTestApiConfig() + public static CoinbaseClientConfig CreateTestApiConfig() { - return new SecretApiKeyConfig() + return new CoinbaseClientConfig() { KeyName = "test-key", KeySecret = GenerateTestKeySecret() }; } - public static SecretApiKeyWebSocketConfig CreateTestWebSocketConfig() + public static CoinbaseClientConfig CreateTestWebSocketConfig() { - return new SecretApiKeyWebSocketConfig() + return new CoinbaseClientConfig() { KeyName = "test-key", KeySecret = GenerateTestKeySecret() diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeApiClient.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeApiClient.cs index 4ac986f..d7267fb 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeApiClient.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeApiClient.cs @@ -11,9 +11,9 @@ namespace CoinbaseAdvancedTradeClient { public partial class CoinbaseAdvancedTradeApiClient : FlurlClient, ICoinbaseAdvancedTradeApiClient { - private SecretApiKeyConfig _config; + private CoinbaseClientConfig _config; - public CoinbaseAdvancedTradeApiClient(SecretApiKeyConfig config) + public CoinbaseAdvancedTradeApiClient(CoinbaseClientConfig config) { if (config == null) throw new ArgumentNullException(nameof(config), ErrorMessages.ApiConfigRequired); if (string.IsNullOrWhiteSpace(config.KeyName)) throw new ArgumentException(ErrorMessages.ApiKeyRequired, nameof(config.KeyName)); diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeWebsocketClient.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeWebsocketClient.cs index 49ee7bc..232cc32 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeWebsocketClient.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeWebsocketClient.cs @@ -15,7 +15,7 @@ namespace CoinbaseAdvancedTradeClient { public class CoinbaseAdvancedTradeWebSocketClient : ICoinbaseAdvancedTradeWebSocketClient, IDisposable { - private SecretApiKeyWebSocketConfig _config; + private CoinbaseClientConfig _config; private WebSocket _socket; private Action _messageReceivedCallback; @@ -25,7 +25,7 @@ public class CoinbaseAdvancedTradeWebSocketClient : ICoinbaseAdvancedTradeWebSoc public bool IsConnected => _socket?.State == WebSocketState.Open; - public CoinbaseAdvancedTradeWebSocketClient(SecretApiKeyWebSocketConfig config) + public CoinbaseAdvancedTradeWebSocketClient(CoinbaseClientConfig config) { if (config == null) throw new ArgumentNullException(nameof(config), ErrorMessages.ApiConfigRequired); if (string.IsNullOrWhiteSpace(config.KeyName)) throw new ArgumentException(ErrorMessages.ApiKeyRequired, nameof(config.KeyName)); diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/AccountsEndpoint.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/AccountsEndpoint.cs index d96c900..4b03e86 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/AccountsEndpoint.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/AccountsEndpoint.cs @@ -21,7 +21,7 @@ async Task> IAccountsEndpoint.GetListAccountsAsync(int { if (limit != null && (limit < 1 || limit > 250)) throw new ArgumentException(ErrorMessages.LimitParameterRange, nameof(limit)); - var accountsPage = await _config.ApiUrl + var accountsPage = await _config.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.AccountsEndpoint) .SetQueryParam(RequestParameters.Limit, limit) @@ -47,7 +47,7 @@ async Task> IAccountsEndpoint.GetAccountAsync(string accoun { if (string.IsNullOrWhiteSpace(accountId)) throw new ArgumentNullException(nameof(accountId), ErrorMessages.AccountIdRequired); - var accountsPage = await _config.ApiUrl + var accountsPage = await _config.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.AccountsEndpoint) .AppendPathSegment(accountId) diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/OrdersEndpoint.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/OrdersEndpoint.cs index 23edaaa..124805f 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/OrdersEndpoint.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/OrdersEndpoint.cs @@ -28,7 +28,7 @@ async Task> IOrdersEndpoint.GetListFillsAsync(string? ord if (start.Equals(DateTimeOffset.MinValue)) start = null; if (end.Equals(DateTimeOffset.MinValue)) end = null; - var fillsPage = await _config.ApiUrl + var fillsPage = await _config.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.OrdersHistoricalFillsEndpoint) .SetQueryParam(RequestParameters.OrderId, orderId) @@ -64,7 +64,7 @@ async Task> IOrdersEndpoint.GetListOrdersAsync(string? p if (startDate.Equals(DateTimeOffset.MinValue)) startDate = null; if (endDate.Equals(DateTimeOffset.MinValue)) endDate = null; - var ordersPage = await _config.ApiUrl + var ordersPage = await _config.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.OrdersHistoricalBatchEndpoint) .SetQueryParam(RequestParameters.ProductId, productId) @@ -99,7 +99,7 @@ async Task> IOrdersEndpoint.GetOrderAsync(string orderId) { if (string.IsNullOrWhiteSpace(orderId)) throw new ArgumentNullException(nameof(orderId), ErrorMessages.OrderIdRequired); - var ordersPage = await _config.ApiUrl + var ordersPage = await _config.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.OrdersHistoricalEndpoint) .AppendPathSegment(orderId) @@ -135,7 +135,7 @@ async Task> IOrdersEndpoint.PostCreateOrderAsyn createOrder.ClientOrderId = Guid.NewGuid().ToString(); } - var createOrderResponse = await _config.ApiUrl + var createOrderResponse = await _config.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.OrdersEndpoint) .PostJsonAsync(createOrder, cancellationToken) @@ -161,7 +161,7 @@ async Task> IOrdersEndpoint.PostCancelOrdersAs if (cancelOrders == null) throw new ArgumentNullException(nameof(cancelOrders), ErrorMessages.OrderParametersRequired); if (cancelOrders.OrderIds == null || !cancelOrders.OrderIds.Any()) throw new ArgumentNullException(nameof(cancelOrders), ErrorMessages.OrderIdRequired); - var cancelOrderResponse = await _config.ApiUrl + var cancelOrderResponse = await _config.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.OrdersBatchCancelEndpoint) .PostJsonAsync(cancelOrders, cancellationToken) diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/ProductsEndpoint.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/ProductsEndpoint.cs index 3eabec9..681d100 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/ProductsEndpoint.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/ProductsEndpoint.cs @@ -23,7 +23,7 @@ async Task> IProductsEndpoint.GetListProductsAsync(int if (limit != null && (limit < 1 || limit > 250)) throw new ArgumentException(ErrorMessages.LimitParameterRange, nameof(limit)); if (offset != null && (offset < 0)) throw new ArgumentException(ErrorMessages.OffsetParameterRange, nameof(offset)); - var productsPage = await _config.ApiUrl + var productsPage = await _config.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.ProductsEndpoint) .SetQueryParam(RequestParameters.Limit, limit) @@ -50,7 +50,7 @@ async Task> IProductsEndpoint.GetProductAsync(string produc { if (string.IsNullOrWhiteSpace(productId)) throw new ArgumentNullException(nameof(productId), ErrorMessages.ProductIdRequired); - var product = await _config.ApiUrl + var product = await _config.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.ProductsEndpoint) .AppendPathSegment(productId) @@ -77,7 +77,7 @@ async Task> IProductsEndpoint.GetProductCandlesAsync(st if (start.Equals(DateTimeOffset.MinValue)) throw new ArgumentException(ErrorMessages.StartDateRequired, nameof(start)); if (end.Equals(DateTimeOffset.MinValue)) throw new ArgumentException(ErrorMessages.EndDateRequired, nameof(end)); - var candlesPage = await _config.ApiUrl + var candlesPage = await _config.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.ProductsEndpoint) .AppendPathSegment(productId) @@ -107,7 +107,7 @@ async Task> IProductsEndpoint.GetMarketTradesAsync(strin if (string.IsNullOrWhiteSpace(productId)) throw new ArgumentNullException(nameof(productId), ErrorMessages.ProductIdRequired); if (limit < 1 || limit > 250) throw new ArgumentException(ErrorMessages.LimitParameterRange, nameof(limit)); - var tradesPage = await _config.ApiUrl + var tradesPage = await _config.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.ProductsEndpoint) .AppendPathSegment(productId) diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/TransactionSummaryEndpoint.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/TransactionSummaryEndpoint.cs index 5f0e7c6..534b688 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/TransactionSummaryEndpoint.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/TransactionSummaryEndpoint.cs @@ -22,7 +22,7 @@ async Task> ITransactionSummaryEndpoint.GetTrans if (startDate.Equals(DateTimeOffset.MinValue)) throw new ArgumentException(ErrorMessages.StartDateRequired, nameof(startDate)); if (endDate.Equals(DateTimeOffset.MinValue)) throw new ArgumentException(ErrorMessages.EndDateRequired, nameof(endDate)); - var transactionSummary = await _config.ApiUrl + var transactionSummary = await _config.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.TransactionSummaryEndpoint) .SetQueryParam(RequestParameters.StartDate, startDate.ToUniversalTime()) diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/ApiClientConfig.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/ApiClientConfig.cs deleted file mode 100644 index b46446e..0000000 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/ApiClientConfig.cs +++ /dev/null @@ -1,12 +0,0 @@ -using CoinbaseAdvancedTradeClient.Constants; - -namespace CoinbaseAdvancedTradeClient.Models.Config -{ - [Obsolete("ApiClientConfig is deprecated. Use SecretApiKeyConfig instead for the new Ed25519 JWT authentication.")] - public class ApiClientConfig - { - public string ApiKey { get; set; } - public string ApiSecret { get; set; } - public string ApiUrl { get; set; } = ApiEndpoints.ApiEndpointBase; - } -} diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/SecretApiKeyWebSocketConfig.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/CoinbaseClientConfig.cs similarity index 57% rename from CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/SecretApiKeyWebSocketConfig.cs rename to CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/CoinbaseClientConfig.cs index 82f1875..a9525ab 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/SecretApiKeyWebSocketConfig.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/CoinbaseClientConfig.cs @@ -1,11 +1,12 @@ -using CoinbaseAdvancedTradeClient.Constants; +using CoinbaseAdvancedTradeClient.Constants; namespace CoinbaseAdvancedTradeClient.Models.Config { - public class SecretApiKeyWebSocketConfig + public class CoinbaseClientConfig { public string KeyName { get; set; } public string KeySecret { get; set; } + public string ApiBaseUrl { get; set; } = ApiEndpoints.ApiEndpointBase; public string WebSocketUrl { get; set; } = ApiEndpoints.WebSocketEndpoint; } -} \ No newline at end of file +} diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/SecretApiKeyConfig.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/SecretApiKeyConfig.cs deleted file mode 100644 index f9bb1c7..0000000 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/SecretApiKeyConfig.cs +++ /dev/null @@ -1,11 +0,0 @@ -using CoinbaseAdvancedTradeClient.Constants; - -namespace CoinbaseAdvancedTradeClient.Models.Config -{ - public class SecretApiKeyConfig - { - public string KeyName { get; set; } - public string KeySecret { get; set; } - public string ApiUrl { get; set; } = ApiEndpoints.ApiEndpointBase; - } -} \ No newline at end of file diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/WebsocketClientConfig.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/WebsocketClientConfig.cs deleted file mode 100644 index b89a1c6..0000000 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Models/Config/WebsocketClientConfig.cs +++ /dev/null @@ -1,12 +0,0 @@ -using CoinbaseAdvancedTradeClient.Constants; - -namespace CoinbaseAdvancedTradeClient.Models.Config -{ - [Obsolete("WebSocketClientConfig is deprecated. Use SecretApiKeyWebSocketConfig instead for the new Ed25519 JWT authentication.")] - public class WebSocketClientConfig - { - public string ApiKey { get; set; } - public string ApiSecret { get; set; } - public string WebSocketUrl { get; set; } = ApiEndpoints.WebSocketEndpoint; - } -} From 889072a0cfb9bebaa50086620a7ff9e5479bd918 Mon Sep 17 00:00:00 2001 From: Mike Pearl Date: Mon, 1 Sep 2025 18:05:52 -0700 Subject: [PATCH 17/24] Add configuration extension --- .../CoinbaseAdvancedTradeClient.csproj | 3 +++ .../Extensions/ServiceCollectionExtensions.cs | 21 +++++++++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Extensions/ServiceCollectionExtensions.cs diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.csproj b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.csproj index 45a7816..819fc66 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.csproj +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.csproj @@ -15,6 +15,9 @@ + + + diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Extensions/ServiceCollectionExtensions.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Extensions/ServiceCollectionExtensions.cs new file mode 100644 index 0000000..45d22b0 --- /dev/null +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Extensions/ServiceCollectionExtensions.cs @@ -0,0 +1,21 @@ +using CoinbaseAdvancedTradeClient.Interfaces; +using CoinbaseAdvancedTradeClient.Models.Config; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +namespace CoinbaseAdvancedTradeClient.Extensions +{ + public static class ServiceCollectionExtensions + { + public static void AddCoinbaseAdvancedTradeClient(this IServiceCollection services, IConfiguration configurationManager, ServiceLifetime apiClientLifetime = ServiceLifetime.Singleton, ServiceLifetime webSocketLifetime = ServiceLifetime.Scoped) + { + if (services == null) throw new ArgumentNullException(nameof(services)); + if (configurationManager == null) throw new ArgumentNullException(nameof(configurationManager)); + + services.Configure(configurationManager.GetSection(nameof(CoinbaseClientConfig))); + + services.Add(new ServiceDescriptor(typeof(ICoinbaseAdvancedTradeApiClient), typeof(CoinbaseAdvancedTradeApiClient), apiClientLifetime)); + services.Add(new ServiceDescriptor(typeof(ICoinbaseAdvancedTradeWebSocketClient), typeof(CoinbaseAdvancedTradeWebSocketClient), apiClientLifetime)); + } + } +} From c2a0a1928037ea78c93102b7a2ad3d3c56052036 Mon Sep 17 00:00:00 2001 From: Mike Pearl Date: Mon, 1 Sep 2025 18:24:26 -0700 Subject: [PATCH 18/24] Move IDisposable to websocket interface --- .../CoinbaseAdvancedTradeWebsocketClient.cs | 2 +- .../Interfaces/ICoinbaseAdvancedTradeWebsocketClient.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeWebsocketClient.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeWebsocketClient.cs index 232cc32..e5c541c 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeWebsocketClient.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeWebsocketClient.cs @@ -13,7 +13,7 @@ namespace CoinbaseAdvancedTradeClient { - public class CoinbaseAdvancedTradeWebSocketClient : ICoinbaseAdvancedTradeWebSocketClient, IDisposable + public class CoinbaseAdvancedTradeWebSocketClient : ICoinbaseAdvancedTradeWebSocketClient { private CoinbaseClientConfig _config; private WebSocket _socket; diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Interfaces/ICoinbaseAdvancedTradeWebsocketClient.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Interfaces/ICoinbaseAdvancedTradeWebsocketClient.cs index eb60b2a..9e3cdc0 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Interfaces/ICoinbaseAdvancedTradeWebsocketClient.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Interfaces/ICoinbaseAdvancedTradeWebsocketClient.cs @@ -2,7 +2,7 @@ namespace CoinbaseAdvancedTradeClient.Interfaces { - public interface ICoinbaseAdvancedTradeWebSocketClient + public interface ICoinbaseAdvancedTradeWebSocketClient : IDisposable { public bool IsConnected { get; } Task ConnectAsync(Action messageReceivedCallback, Action? openedCallback = null, Action? closedCallback = null, Action? errorCallback = null); From 91f4d14f0f6071286b86980dc100f6a309cdb0ce Mon Sep 17 00:00:00 2001 From: Mike Pearl Date: Mon, 1 Sep 2025 20:32:39 -0700 Subject: [PATCH 19/24] Change registration extension --- .../Extensions/ServiceCollectionExtensions.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Extensions/ServiceCollectionExtensions.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Extensions/ServiceCollectionExtensions.cs index 45d22b0..466ba7e 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Extensions/ServiceCollectionExtensions.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Extensions/ServiceCollectionExtensions.cs @@ -7,15 +7,15 @@ namespace CoinbaseAdvancedTradeClient.Extensions { public static class ServiceCollectionExtensions { - public static void AddCoinbaseAdvancedTradeClient(this IServiceCollection services, IConfiguration configurationManager, ServiceLifetime apiClientLifetime = ServiceLifetime.Singleton, ServiceLifetime webSocketLifetime = ServiceLifetime.Scoped) + public static void AddCoinbaseAdvancedTradeClient(this IServiceCollection services, IConfiguration configurationManager) { if (services == null) throw new ArgumentNullException(nameof(services)); if (configurationManager == null) throw new ArgumentNullException(nameof(configurationManager)); services.Configure(configurationManager.GetSection(nameof(CoinbaseClientConfig))); - services.Add(new ServiceDescriptor(typeof(ICoinbaseAdvancedTradeApiClient), typeof(CoinbaseAdvancedTradeApiClient), apiClientLifetime)); - services.Add(new ServiceDescriptor(typeof(ICoinbaseAdvancedTradeWebSocketClient), typeof(CoinbaseAdvancedTradeWebSocketClient), apiClientLifetime)); + services.AddScoped(); + services.AddScoped(); } } } From 86258706446a00961a4849d64c1048fd11a0309f Mon Sep 17 00:00:00 2001 From: Mike Pearl Date: Mon, 1 Sep 2025 21:16:24 -0700 Subject: [PATCH 20/24] Use IOptions in api and websocket constructors --- .../CoinbaseAdvancedTradeApiClientTests.cs | 6 +++-- ...inbaseAdvancedTradeClient.UnitTests.csproj | 1 + ...inbaseAdvancedTradeWebSocketClientTests.cs | 9 ++++--- .../Endpoints/AccountsEndpointTests.cs | 4 ++- .../Endpoints/OrdersEndpointTests.cs | 4 ++- .../Endpoints/ProductsEndpointTests.cs | 4 ++- .../TransactionSummaryEndpointTests.cs | 4 ++- .../TestHelpers/TestConfigHelper.cs | 23 ++--------------- .../CoinbaseAdvancedTradeApiClient.cs | 13 +++++----- .../CoinbaseAdvancedTradeWebsocketClient.cs | 25 ++++++++++--------- .../Endpoints/AccountsEndpoint.cs | 4 +-- .../Endpoints/OrdersEndpoint.cs | 10 ++++---- .../Endpoints/ProductsEndpoint.cs | 8 +++--- .../Endpoints/TransactionSummaryEndpoint.cs | 2 +- 14 files changed, 57 insertions(+), 60 deletions(-) diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeApiClientTests.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeApiClientTests.cs index 5de2d0b..28ed881 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeApiClientTests.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeApiClientTests.cs @@ -1,4 +1,5 @@ using CoinbaseAdvancedTradeClient.Models.Config; +using Microsoft.Extensions.Options; using Xunit; namespace CoinbaseAdvancedTradeClient.UnitTests @@ -9,7 +10,7 @@ public class CoinbaseAdvancedTradeApiClientTests public void Constructor_NullConfig_ThrowsArgumentNullException() { //Arrange - CoinbaseClientConfig config = null; + IOptions config = null; //Act & Assert Assert.Throws(() => @@ -27,11 +28,12 @@ public void Constructor_NullConfig_ThrowsArgumentNullException() public void Constructor_EmptyConfigSetting_ThrowsArgumentException(string key, string secret) { //Arrange - CoinbaseClientConfig config = new CoinbaseClientConfig() + var configValue = new CoinbaseClientConfig() { KeyName = key, KeySecret = secret }; + var config = Options.Create(configValue); //Act & Assert Assert.Throws(() => diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeClient.UnitTests.csproj b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeClient.UnitTests.csproj index 209fd69..d9efea3 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeClient.UnitTests.csproj +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeClient.UnitTests.csproj @@ -9,6 +9,7 @@ + diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeWebSocketClientTests.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeWebSocketClientTests.cs index b946f98..600f20b 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeWebSocketClientTests.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/CoinbaseAdvancedTradeWebSocketClientTests.cs @@ -1,6 +1,7 @@ using CoinbaseAdvancedTradeClient.Constants; using CoinbaseAdvancedTradeClient.Interfaces; using CoinbaseAdvancedTradeClient.Models.Config; +using Microsoft.Extensions.Options; using System.Net.Sockets; using Xunit; @@ -12,7 +13,7 @@ public class CoinbaseAdvancedTradeWebSocketClientTests public void Constructor_NullConfig_ThrowsArgumentNullException() { //Arrange - CoinbaseClientConfig config = null; + IOptions config = null; //Act & Assert Assert.Throws(() => @@ -30,11 +31,12 @@ public void Constructor_NullConfig_ThrowsArgumentNullException() public void Constructor_EmptyConfigSetting_ThrowsArgumentException(string key, string secret) { //Arrange - CoinbaseClientConfig config = new CoinbaseClientConfig() + var configValue = new CoinbaseClientConfig() { KeyName = key, KeySecret = secret }; + var config = Options.Create(configValue); //Act & Assert Assert.Throws(() => @@ -164,11 +166,12 @@ public void Unsubscribe_EmptyProductIds_ThrowsArgumentNullException() private ICoinbaseAdvancedTradeWebSocketClient CreateTestClient() { - CoinbaseClientConfig config = new CoinbaseClientConfig() + var configValue = new CoinbaseClientConfig() { KeyName = "testKey", KeySecret = TestHelpers.TestConfigHelper.GenerateTestKeySecret() }; + var config = Options.Create(configValue); return new CoinbaseAdvancedTradeWebSocketClient(config); } diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/AccountsEndpointTests.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/AccountsEndpointTests.cs index d5fc345..b8267f5 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/AccountsEndpointTests.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/AccountsEndpointTests.cs @@ -5,6 +5,7 @@ using CoinbaseAdvancedTradeClient.Models.Pages; using Flurl.Http; using Flurl.Http.Testing; +using Microsoft.Extensions.Options; using System.Globalization; using Xunit; @@ -16,11 +17,12 @@ public class AccountsEndpointTests public AccountsEndpointTests() { - var config = new CoinbaseClientConfig() + var configValue = new CoinbaseClientConfig() { KeyName = "key", KeySecret = TestHelpers.TestConfigHelper.GenerateTestKeySecret() }; + var config = Options.Create(configValue); _testClient = new CoinbaseAdvancedTradeApiClient(config); } diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/OrdersEndpointTests.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/OrdersEndpointTests.cs index 095a72e..18d699a 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/OrdersEndpointTests.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/OrdersEndpointTests.cs @@ -7,6 +7,7 @@ using FakeItEasy; using Flurl.Http; using Flurl.Http.Testing; +using Microsoft.Extensions.Options; using Xunit; namespace CoinbaseAdvancedTradeClient.UnitTests.Endpoints @@ -17,11 +18,12 @@ public class OrdersEndpointTests public OrdersEndpointTests() { - var config = new CoinbaseClientConfig() + var configValue = new CoinbaseClientConfig() { KeyName = "key", KeySecret = TestHelpers.TestConfigHelper.GenerateTestKeySecret() }; + var config = Options.Create(configValue); _testClient = new CoinbaseAdvancedTradeApiClient(config); } diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/ProductsEndpointTests.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/ProductsEndpointTests.cs index a05673b..1bd6bd2 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/ProductsEndpointTests.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/ProductsEndpointTests.cs @@ -7,6 +7,7 @@ using CoinbaseAdvancedTradeClient.Resources; using Flurl.Http; using Flurl.Http.Testing; +using Microsoft.Extensions.Options; using Xunit; namespace CoinbaseAdvancedTradeClient.UnitTests.Endpoints @@ -17,11 +18,12 @@ public class ProductsEndpointTests public ProductsEndpointTests() { - var config = new CoinbaseClientConfig() + var configValue = new CoinbaseClientConfig() { KeyName = "key", KeySecret = TestHelpers.TestConfigHelper.GenerateTestKeySecret() }; + var config = Options.Create(configValue); _testClient = new CoinbaseAdvancedTradeApiClient(config); } diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/TransactionSummaryEndpointTests.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/TransactionSummaryEndpointTests.cs index 3f85c3a..4a41898 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/TransactionSummaryEndpointTests.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Endpoints/TransactionSummaryEndpointTests.cs @@ -6,6 +6,7 @@ using CoinbaseAdvancedTradeClient.Models.Config; using Flurl.Http; using Flurl.Http.Testing; +using Microsoft.Extensions.Options; using Xunit; namespace CoinbaseAdvancedTradeClient.UnitTests.Endpoints @@ -16,11 +17,12 @@ public class TransactionSummaryEndpointTests public TransactionSummaryEndpointTests() { - var config = new CoinbaseClientConfig() + var configValue = new CoinbaseClientConfig() { KeyName = "key", KeySecret = TestHelpers.TestConfigHelper.GenerateTestKeySecret() }; + var config = Options.Create(configValue); _testClient = new CoinbaseAdvancedTradeApiClient(config); } diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/TestHelpers/TestConfigHelper.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/TestHelpers/TestConfigHelper.cs index 0374d06..08782f4 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/TestHelpers/TestConfigHelper.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/TestHelpers/TestConfigHelper.cs @@ -1,9 +1,8 @@ -using CoinbaseAdvancedTradeClient.Models.Config; +using Org.BouncyCastle.Asn1.Sec; using Org.BouncyCastle.Crypto.Generators; using Org.BouncyCastle.Crypto.Parameters; -using Org.BouncyCastle.Security; using Org.BouncyCastle.OpenSsl; -using Org.BouncyCastle.Asn1.Sec; +using Org.BouncyCastle.Security; namespace CoinbaseAdvancedTradeClient.UnitTests.TestHelpers { @@ -28,23 +27,5 @@ public static string GenerateTestKeySecret() return stringWriter.ToString(); } - - public static CoinbaseClientConfig CreateTestApiConfig() - { - return new CoinbaseClientConfig() - { - KeyName = "test-key", - KeySecret = GenerateTestKeySecret() - }; - } - - public static CoinbaseClientConfig CreateTestWebSocketConfig() - { - return new CoinbaseClientConfig() - { - KeyName = "test-key", - KeySecret = GenerateTestKeySecret() - }; - } } } \ No newline at end of file diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeApiClient.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeApiClient.cs index d7267fb..70a594d 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeApiClient.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeApiClient.cs @@ -6,18 +6,19 @@ using CoinbaseAdvancedTradeClient.Resources; using Flurl.Http; using Flurl.Http.Configuration; +using Microsoft.Extensions.Options; namespace CoinbaseAdvancedTradeClient { public partial class CoinbaseAdvancedTradeApiClient : FlurlClient, ICoinbaseAdvancedTradeApiClient { - private CoinbaseClientConfig _config; + private IOptions _config; - public CoinbaseAdvancedTradeApiClient(CoinbaseClientConfig config) + public CoinbaseAdvancedTradeApiClient(IOptions config) { if (config == null) throw new ArgumentNullException(nameof(config), ErrorMessages.ApiConfigRequired); - if (string.IsNullOrWhiteSpace(config.KeyName)) throw new ArgumentException(ErrorMessages.ApiKeyRequired, nameof(config.KeyName)); - if (string.IsNullOrWhiteSpace(config.KeySecret)) throw new ArgumentException(ErrorMessages.ApiSecretRequired, nameof(config.KeySecret)); + if (string.IsNullOrWhiteSpace(config.Value.KeyName)) throw new ArgumentException(ErrorMessages.ApiKeyRequired, nameof(config.Value.KeyName)); + if (string.IsNullOrWhiteSpace(config.Value.KeySecret)) throw new ArgumentException(ErrorMessages.ApiSecretRequired, nameof(config.Value.KeySecret)); _config = config; @@ -34,8 +35,8 @@ async Task SetHeaders(FlurlCall http) var url = http.Request.Url.ToUri().AbsolutePath; var host = http.Request.Url.ToUri().Host; var jwt = SecretApiKeyAuthenticator.GenerateBearerJWT( - _config.KeyName, - _config.KeySecret, + _config.Value.KeyName, + _config.Value.KeySecret, method, host, url); diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeWebsocketClient.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeWebsocketClient.cs index e5c541c..c8e1f9c 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeWebsocketClient.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeWebsocketClient.cs @@ -6,6 +6,7 @@ using CoinbaseAdvancedTradeClient.Models.WebSocket; using CoinbaseAdvancedTradeClient.Models.WebSocket.Events; using CoinbaseAdvancedTradeClient.Resources; +using Microsoft.Extensions.Options; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System.Security.Authentication; @@ -13,9 +14,9 @@ namespace CoinbaseAdvancedTradeClient { - public class CoinbaseAdvancedTradeWebSocketClient : ICoinbaseAdvancedTradeWebSocketClient + public class CoinbaseAdvancedTradeWebSocketClient : ICoinbaseAdvancedTradeWebSocketClient, IDisposable { - private CoinbaseClientConfig _config; + private IOptions _config; private WebSocket _socket; private Action _messageReceivedCallback; @@ -25,11 +26,11 @@ public class CoinbaseAdvancedTradeWebSocketClient : ICoinbaseAdvancedTradeWebSoc public bool IsConnected => _socket?.State == WebSocketState.Open; - public CoinbaseAdvancedTradeWebSocketClient(CoinbaseClientConfig config) + public CoinbaseAdvancedTradeWebSocketClient(IOptions config) { if (config == null) throw new ArgumentNullException(nameof(config), ErrorMessages.ApiConfigRequired); - if (string.IsNullOrWhiteSpace(config.KeyName)) throw new ArgumentException(ErrorMessages.ApiKeyRequired, nameof(config.KeyName)); - if (string.IsNullOrWhiteSpace(config.KeySecret)) throw new ArgumentException(ErrorMessages.ApiSecretRequired, nameof(config.KeySecret)); + if (string.IsNullOrWhiteSpace(config.Value.KeyName)) throw new ArgumentException(ErrorMessages.ApiKeyRequired, nameof(config.Value.KeyName)); + if (string.IsNullOrWhiteSpace(config.Value.KeySecret)) throw new ArgumentException(ErrorMessages.ApiSecretRequired, nameof(config.Value.KeySecret)); _config = config; } @@ -50,7 +51,7 @@ public async Task ConnectAsync(Action messageReceivedCallba Disconnect(); } - _socket = new WebSocket(_config.WebSocketUrl); + _socket = new WebSocket(_config.Value.WebSocketUrl); _socket.Security.EnabledSslProtocols = SslProtocols.Tls12; _socket.Opened += Socket_Opened; @@ -81,10 +82,10 @@ public void Subscribe(string channel, List productIds) if (!IsConnected) throw new InvalidOperationException(ErrorMessages.WebSocketMustBeConnected); var jwt = SecretApiKeyAuthenticator.GenerateBearerJWT( - _config.KeyName, - _config.KeySecret, + _config.Value.KeyName, + _config.Value.KeySecret, "GET", - _config.WebSocketUrl, + _config.Value.WebSocketUrl, "/"); var subscriptionMessage = new SubscriptionMessage @@ -108,10 +109,10 @@ public void Unsubscribe(string channel, List productIds) if (!IsConnected) throw new InvalidOperationException(ErrorMessages.WebSocketMustBeConnected); var jwt = SecretApiKeyAuthenticator.GenerateBearerJWT( - _config.KeyName, - _config.KeySecret, + _config.Value.KeyName, + _config.Value.KeySecret, "GET", - "advanced-trade-ws.coinbase.com", + _config.Value.WebSocketUrl, "/"); var unsubscribeMessage = new SubscriptionMessage diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/AccountsEndpoint.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/AccountsEndpoint.cs index 4b03e86..0996200 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/AccountsEndpoint.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/AccountsEndpoint.cs @@ -21,7 +21,7 @@ async Task> IAccountsEndpoint.GetListAccountsAsync(int { if (limit != null && (limit < 1 || limit > 250)) throw new ArgumentException(ErrorMessages.LimitParameterRange, nameof(limit)); - var accountsPage = await _config.ApiBaseUrl + var accountsPage = await _config.Value.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.AccountsEndpoint) .SetQueryParam(RequestParameters.Limit, limit) @@ -47,7 +47,7 @@ async Task> IAccountsEndpoint.GetAccountAsync(string accoun { if (string.IsNullOrWhiteSpace(accountId)) throw new ArgumentNullException(nameof(accountId), ErrorMessages.AccountIdRequired); - var accountsPage = await _config.ApiBaseUrl + var accountsPage = await _config.Value.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.AccountsEndpoint) .AppendPathSegment(accountId) diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/OrdersEndpoint.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/OrdersEndpoint.cs index 124805f..5a198b7 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/OrdersEndpoint.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/OrdersEndpoint.cs @@ -28,7 +28,7 @@ async Task> IOrdersEndpoint.GetListFillsAsync(string? ord if (start.Equals(DateTimeOffset.MinValue)) start = null; if (end.Equals(DateTimeOffset.MinValue)) end = null; - var fillsPage = await _config.ApiBaseUrl + var fillsPage = await _config.Value.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.OrdersHistoricalFillsEndpoint) .SetQueryParam(RequestParameters.OrderId, orderId) @@ -64,7 +64,7 @@ async Task> IOrdersEndpoint.GetListOrdersAsync(string? p if (startDate.Equals(DateTimeOffset.MinValue)) startDate = null; if (endDate.Equals(DateTimeOffset.MinValue)) endDate = null; - var ordersPage = await _config.ApiBaseUrl + var ordersPage = await _config.Value.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.OrdersHistoricalBatchEndpoint) .SetQueryParam(RequestParameters.ProductId, productId) @@ -99,7 +99,7 @@ async Task> IOrdersEndpoint.GetOrderAsync(string orderId) { if (string.IsNullOrWhiteSpace(orderId)) throw new ArgumentNullException(nameof(orderId), ErrorMessages.OrderIdRequired); - var ordersPage = await _config.ApiBaseUrl + var ordersPage = await _config.Value.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.OrdersHistoricalEndpoint) .AppendPathSegment(orderId) @@ -135,7 +135,7 @@ async Task> IOrdersEndpoint.PostCreateOrderAsyn createOrder.ClientOrderId = Guid.NewGuid().ToString(); } - var createOrderResponse = await _config.ApiBaseUrl + var createOrderResponse = await _config.Value.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.OrdersEndpoint) .PostJsonAsync(createOrder, cancellationToken) @@ -161,7 +161,7 @@ async Task> IOrdersEndpoint.PostCancelOrdersAs if (cancelOrders == null) throw new ArgumentNullException(nameof(cancelOrders), ErrorMessages.OrderParametersRequired); if (cancelOrders.OrderIds == null || !cancelOrders.OrderIds.Any()) throw new ArgumentNullException(nameof(cancelOrders), ErrorMessages.OrderIdRequired); - var cancelOrderResponse = await _config.ApiBaseUrl + var cancelOrderResponse = await _config.Value.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.OrdersBatchCancelEndpoint) .PostJsonAsync(cancelOrders, cancellationToken) diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/ProductsEndpoint.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/ProductsEndpoint.cs index 681d100..2040fea 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/ProductsEndpoint.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/ProductsEndpoint.cs @@ -23,7 +23,7 @@ async Task> IProductsEndpoint.GetListProductsAsync(int if (limit != null && (limit < 1 || limit > 250)) throw new ArgumentException(ErrorMessages.LimitParameterRange, nameof(limit)); if (offset != null && (offset < 0)) throw new ArgumentException(ErrorMessages.OffsetParameterRange, nameof(offset)); - var productsPage = await _config.ApiBaseUrl + var productsPage = await _config.Value.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.ProductsEndpoint) .SetQueryParam(RequestParameters.Limit, limit) @@ -50,7 +50,7 @@ async Task> IProductsEndpoint.GetProductAsync(string produc { if (string.IsNullOrWhiteSpace(productId)) throw new ArgumentNullException(nameof(productId), ErrorMessages.ProductIdRequired); - var product = await _config.ApiBaseUrl + var product = await _config.Value.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.ProductsEndpoint) .AppendPathSegment(productId) @@ -77,7 +77,7 @@ async Task> IProductsEndpoint.GetProductCandlesAsync(st if (start.Equals(DateTimeOffset.MinValue)) throw new ArgumentException(ErrorMessages.StartDateRequired, nameof(start)); if (end.Equals(DateTimeOffset.MinValue)) throw new ArgumentException(ErrorMessages.EndDateRequired, nameof(end)); - var candlesPage = await _config.ApiBaseUrl + var candlesPage = await _config.Value.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.ProductsEndpoint) .AppendPathSegment(productId) @@ -107,7 +107,7 @@ async Task> IProductsEndpoint.GetMarketTradesAsync(strin if (string.IsNullOrWhiteSpace(productId)) throw new ArgumentNullException(nameof(productId), ErrorMessages.ProductIdRequired); if (limit < 1 || limit > 250) throw new ArgumentException(ErrorMessages.LimitParameterRange, nameof(limit)); - var tradesPage = await _config.ApiBaseUrl + var tradesPage = await _config.Value.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.ProductsEndpoint) .AppendPathSegment(productId) diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/TransactionSummaryEndpoint.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/TransactionSummaryEndpoint.cs index 534b688..9f486e4 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/TransactionSummaryEndpoint.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Endpoints/TransactionSummaryEndpoint.cs @@ -22,7 +22,7 @@ async Task> ITransactionSummaryEndpoint.GetTrans if (startDate.Equals(DateTimeOffset.MinValue)) throw new ArgumentException(ErrorMessages.StartDateRequired, nameof(startDate)); if (endDate.Equals(DateTimeOffset.MinValue)) throw new ArgumentException(ErrorMessages.EndDateRequired, nameof(endDate)); - var transactionSummary = await _config.ApiBaseUrl + var transactionSummary = await _config.Value.ApiBaseUrl .WithClient(this) .AppendPathSegment(ApiEndpoints.TransactionSummaryEndpoint) .SetQueryParam(RequestParameters.StartDate, startDate.ToUniversalTime()) From d78d663b45897f136ee4a43802974173da0e51d5 Mon Sep 17 00:00:00 2001 From: Mike Pearl Date: Mon, 8 Sep 2025 20:03:28 -0700 Subject: [PATCH 21/24] Simplify client configuration extension --- .../Extensions/ServiceCollectionExtensions.cs | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Extensions/ServiceCollectionExtensions.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Extensions/ServiceCollectionExtensions.cs index 466ba7e..7bb240c 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Extensions/ServiceCollectionExtensions.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Extensions/ServiceCollectionExtensions.cs @@ -7,15 +7,26 @@ namespace CoinbaseAdvancedTradeClient.Extensions { public static class ServiceCollectionExtensions { - public static void AddCoinbaseAdvancedTradeClient(this IServiceCollection services, IConfiguration configurationManager) + /// + /// Adds CoinbaseAdvancedTradeClient services to the service collection. + /// Automatically resolves configuration from the CoinbaseClientConfig section in appsettings.json. + /// + /// The service collection to add services to + /// The service collection for method chaining + public static IServiceCollection AddCoinbaseAdvancedTradeClient(this IServiceCollection services) { if (services == null) throw new ArgumentNullException(nameof(services)); - if (configurationManager == null) throw new ArgumentNullException(nameof(configurationManager)); - services.Configure(configurationManager.GetSection(nameof(CoinbaseClientConfig))); + services.AddOptions() + .Configure((config, configuration) => + { + configuration.GetSection(nameof(CoinbaseClientConfig)).Bind(config); + }); services.AddScoped(); services.AddScoped(); + + return services; } } } From d994034bd8910d84c44827bc36a5969a10c149c0 Mon Sep 17 00:00:00 2001 From: Mike Pearl Date: Mon, 8 Sep 2025 22:08:32 -0700 Subject: [PATCH 22/24] Update changelog and readme --- CHANGELOG.md | 17 +++++++++++ README.md | 84 ++++++++++++++++++++++++++++++++++------------------ 2 files changed, 73 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 266725a..63ff912 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [0.4.0] - 2025-09-08 + +### Added +- JWT Bearer Authentication with ES256 signatures replacing legacy HMAC +- Unified `CoinbaseClientConfig` for both API and WebSocket clients +- Dependency Injection support with `AddCoinbaseAdvancedTradeClient()` extension +- Enhanced security with JWT tokens (2-minute expiration and replay protection) + +### Changed +- Migrated from HMAC-SHA256 to JWT Bearer tokens with ECDSA ES256 signatures +- Configuration properties renamed: `ApiKey`/`ApiSecret` → `KeyName`/`KeySecret` +- Requires Coinbase Cloud API keys (EC P-256 private keys in PEM format) +- Constructor parameters now use `IOptions` + +### Removed +- Legacy `ApiKeyAuthenticator` and CB-ACCESS-* header authentication + ## [0.3.0] - 2025-08-25 ### Added diff --git a/README.md b/README.md index aacd2ec..ff9eac6 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ We are actively working toward a 1.0.0 stable release. Check the [CHANGELOG.md]( - **Complete API Coverage**: Support for all Coinbase Advanced Trade endpoints including accounts, orders, products, and transaction summaries - **WebSocket Support**: Real-time market data streaming with support for multiple channels -- **Authentication**: Secure API key-based authentication with HMAC signature generation +- **Authentication**: Secure JWT Bearer token authentication with ECDSA ES256 signatures - **Type Safety**: Strongly-typed models for all API requests and responses - **Testing**: Comprehensive unit test suite with 142+ passing tests - **Modern .NET**: Built for .NET 9.0 with nullable reference types and implicit usings @@ -41,46 +41,74 @@ Or add to your `.csproj` file: ## Quick Start -### API Client Setup +### Configuration -```csharp -using CoinbaseAdvancedTradeClient; -using CoinbaseAdvancedTradeClient.Models.Config; +⚠️ **Security Warning**: Never commit your API key names or secrets to version control. Use secure configuration methods: +- User secrets for development: `dotnet user-secrets set "CoinbaseClientConfig:KeyName" "your-key-name"` +- Azure Key Vault or AWS Secrets Manager for production +- Environment variables with proper access controls +- Kubernetes secrets or similar container orchestration secrets + +Add your Coinbase Cloud API credentials to `appsettings.json`: -var config = new ApiClientConfig +```json { - ApiKey = "your-api-key", - ApiSecret = "your-api-secret" -}; + "CoinbaseClientConfig": { + "KeyName": "your-key-name", + "KeySecret": "-----BEGIN EC PRIVATE KEY-----\n...\n-----END EC PRIVATE KEY-----", + "ApiBaseUrl": "https://api.coinbase.com", // Optional, defaults to production + "WebSocketUrl": "wss://advanced-trade-ws.coinbase.com" // Optional, defaults to production + } +} +``` + +### API Client Setup -using var client = new CoinbaseAdvancedTradeApiClient(config); +```csharp +using CoinbaseAdvancedTradeClient.Extensions; -// Get account information -var accounts = await client.GetAccountsAsync(); +// Register during startup +builder.Services.AddCoinbaseAdvancedTradeClient(); -// Place a market order -var orderResponse = await client.CreateOrderAsync(new CreateOrderParameters +// Use in your services +public class TradingService { - // Order configuration here -}); + private readonly ICoinbaseAdvancedTradeApiClient _client; + + public TradingService(ICoinbaseAdvancedTradeApiClient client) + { + _client = client; + } + + public async Task> GetAccountsAsync() + { + return await _client.GetAccountsAsync(); + } +} ``` ### WebSocket Client Setup ```csharp -using CoinbaseAdvancedTradeClient; -using CoinbaseAdvancedTradeClient.Models.Config; - -var config = new WebsocketClientConfig +// WebSocket client is automatically registered with the API client +public class MarketDataService { - ApiKey = "your-api-key", - ApiSecret = "your-api-secret" -}; - -using var wsClient = new CoinbaseAdvancedTradeWebsocketClient(config); - -// Subscribe to market data -await wsClient.SubscribeAsync("BTC-USD", SubscriptionType.Ticker); + private readonly ICoinbaseAdvancedTradeWebSocketClient _wsClient; + + public MarketDataService(ICoinbaseAdvancedTradeWebSocketClient wsClient) + { + _wsClient = wsClient; + } + + public async Task SubscribeToTicker(string productId) + { + // Connect to WebSocket first + await _wsClient.ConnectAsync(); + + // Then subscribe to market data + await _wsClient.SubscribeAsync(productId, SubscriptionType.Ticker); + } +} ``` ## API Reference From c3203d9834f02414f597c89ebb107b2596ab27b3 Mon Sep 17 00:00:00 2001 From: Mike Pearl Date: Mon, 8 Sep 2025 23:37:43 -0700 Subject: [PATCH 23/24] Fix formatting in unit test. --- .../Authentication/SecretApiKeyAuthenticatorTests.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Authentication/SecretApiKeyAuthenticatorTests.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Authentication/SecretApiKeyAuthenticatorTests.cs index aafe20d..7ce03df 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Authentication/SecretApiKeyAuthenticatorTests.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient.UnitTests/Authentication/SecretApiKeyAuthenticatorTests.cs @@ -12,8 +12,8 @@ public void GenerateBearerJWT_ValidParameters_ReturnsJWT() // Arrange var testKeySecret = TestConfigHelper.GenerateTestKeySecret(); - // Act & Assert - Should not throw exception - var jwt = SecretApiKeyAuthenticator.GenerateBearerJWT( + // Act + var result = SecretApiKeyAuthenticator.GenerateBearerJWT( "test-key-name", testKeySecret, "GET", @@ -21,10 +21,10 @@ public void GenerateBearerJWT_ValidParameters_ReturnsJWT() "/v1/test" ); - // Basic JWT format validation - Assert.NotNull(jwt); - Assert.Contains(".", jwt); - var parts = jwt.Split('.'); + // Assert + Assert.NotNull(result); + Assert.Contains(".", result); + var parts = result.Split('.'); Assert.Equal(3, parts.Length); // header.payload.signature } From 92963e94b7b820f6783aa6cd77d3a0f477261411 Mon Sep 17 00:00:00 2001 From: Mike Pearl Date: Mon, 8 Sep 2025 23:47:28 -0700 Subject: [PATCH 24/24] Throw ArgumentException consistently in SecretApiKeyAuthenticator. --- .../Authentication/SecretApiKeyAuthenticator.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Authentication/SecretApiKeyAuthenticator.cs b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Authentication/SecretApiKeyAuthenticator.cs index 55e594a..1b3d0ef 100644 --- a/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Authentication/SecretApiKeyAuthenticator.cs +++ b/CoinbaseAdvancedTradeClient/CoinbaseAdvancedTradeClient/Authentication/SecretApiKeyAuthenticator.cs @@ -15,9 +15,9 @@ public static string GenerateBearerJWT(string keyName, string keySecret, string { if (string.IsNullOrWhiteSpace(keyName)) throw new ArgumentException(ErrorMessages.ApiKeyRequired, nameof(keyName)); if (string.IsNullOrWhiteSpace(keySecret)) throw new ArgumentException(ErrorMessages.ApiSecretRequired, nameof(keySecret)); - if (string.IsNullOrWhiteSpace(requestMethod)) throw new ArgumentNullException(nameof(requestMethod), ErrorMessages.RequestMethodRequired); - if (string.IsNullOrWhiteSpace(requestHost)) throw new ArgumentNullException(nameof(requestHost), ErrorMessages.RequestHostRequired); - if (string.IsNullOrWhiteSpace(requestPath)) throw new ArgumentNullException(nameof(requestPath), ErrorMessages.RequestPathRequired); + if (string.IsNullOrWhiteSpace(requestMethod)) throw new ArgumentException(ErrorMessages.RequestMethodRequired, nameof(requestMethod)); + if (string.IsNullOrWhiteSpace(requestHost)) throw new ArgumentException(ErrorMessages.RequestHostRequired, nameof(requestHost)); + if (string.IsNullOrWhiteSpace(requestPath)) throw new ArgumentException(ErrorMessages.RequestPathRequired, nameof(requestPath)); // Parse the EC private key from PEM format ECPrivateKeyParameters privateKey;