Building Crypto Intelligence with Go: A Deep Dive into the nansen-go Library

go dev.to

The world of blockchain analytics is vast, complex, and often overwhelming. Developers building crypto applications, trading bots, or analytical dashboards constantly face the challenge of extracting meaningful intelligence from raw onchain data. Enter Nansen AI, a platform renowned for its proprietary data labeling, Smart Money analytics, and comprehensive multi-chain coverage 1. While Nansen provides a powerful API, integrating it cleanly into a Go backend requires a well-designed client. This is where nansen-go shines.

In this review, we will explore nansen-go (available at github.com/tigusigalpa/nansen-go), an elegant, dependency-free Go client for the Nansen AI API. We will examine its design philosophy, key features, and how it simplifies the process of building crypto intelligence applications in Go.

The Philosophy of nansen-go: Idiomatic and Unobtrusive

When evaluating a third-party API client, developers often look for a balance between abstraction and control. A good client should handle the boilerplate of HTTP requests, authentication, and error handling without hiding the underlying API or forcing the developer into unnatural patterns. The creator of nansen-go, Igor Sazonov, has clearly embraced this philosophy.

The repository's README states that the library "tries to stay out of your way" 2. This is not just a marketing tagline; it is reflected in the core design choices of the package.

Zero Dependencies

One of the most striking features of nansen-go is its complete lack of third-party dependencies. The entire library is built exclusively on the Go standard library 2.

"Nothing to vendor. The whole thing is built on the standard library. go get it and you're done — no dependency tree to audit." 2

In an era where a simple API client can pull in dozens of transitive dependencies, this is a breath of fresh air. For enterprise applications or security-conscious projects, minimizing the dependency footprint is crucial. It reduces the attack surface, simplifies auditing, and ensures that the client won't conflict with other packages in your project.

Contexts Everywhere

Idiomatic Go code relies heavily on context.Context for managing timeouts, cancellation, and request-scoped values. nansen-go adheres strictly to this convention. Every API call in the library takes a context.Context as its first argument 2. This ensures that developers have fine-grained control over the lifecycle of their requests, making it easy to integrate the client into robust, production-ready systems where timeouts and graceful degradation are essential.

Key Features and Ergonomics

Beyond its architectural philosophy, nansen-go offers a range of features designed to make interacting with the Nansen API as smooth as possible.

Configuration via Functional Options

Instead of relying on massive configuration structs, nansen-go utilizes the functional options pattern for initialization 2. This allows developers to pass only the configuration parameters they need, while sensible defaults handle the rest.

client, err := nansen.New(os.Getenv("NANSEN_API_KEY"),
    nansen.WithTimeout(30*time.Second),
    nansen.WithRetry(3, 500*time.Millisecond, 5*time.Second),
)
Enter fullscreen mode Exit fullscreen mode

Options like WithBaseURL, WithHTTPClient, WithTimeout, and WithRetry provide the flexibility needed to adapt the client to various environments, from local testing to high-throughput production deployments 2.

Concurrency and Safety

Go's concurrency model is one of its strongest selling points, and nansen-go is built to leverage it. The client is designed to be safe for concurrent use across multiple goroutines 2.

"Safe to share. Create one client and hand it to as many goroutines as you like. No locks, no fuss." 2

This means you can instantiate a single nansen.Client at application startup and inject it into your HTTP handlers, background workers, or data pipelines without worrying about race conditions or managing connection pools manually.

Type Safety and Pointer Semantics

The Nansen API expects specific JSON payloads, and nansen-go ensures that your requests are strictly typed. Chains, sort fields, trader types, and labels are defined as real constants in the library 2.

Furthermore, optional request fields are implemented as pointers 2. This is a critical detail in Go, where the zero value of a type (like false for a boolean or 0 for an integer) can sometimes be indistinguishable from an omitted field when marshaling to JSON. By using pointers, nansen-go guarantees that optional fields are only sent when explicitly provided. To alleviate the verbosity of creating pointers to primitive types, the library includes handy helper functions like nansen.StringPtr(), nansen.IntPtr(), and nansen.Float64Ptr() 2.

Advanced Error Handling and Retries

Interacting with any remote API involves handling failures gracefully. Nansen API rate limits and transient network errors are inevitable, and nansen-go provides robust mechanisms to deal with them.

Inspectable Errors

When an API call fails, nansen-go returns an *nansen.APIError. This custom error type provides deep visibility into the failure, exposing the HTTP status code, the error message, the raw response body, and crucial rate-limit headers 2.

Because the library integrates seamlessly with Go's errors.Is and errors.As functions, developers can easily branch their logic based on the specific type of error encountered. The library provides built-in sentinels like nansen.ErrRateLimited, nansen.ErrUnauthorized, and nansen.ErrNotFound for quick checks 2.

Built-in Exponential Backoff

Perhaps the most valuable feature for production use is the built-in retry mechanism. By opting in with nansen.WithRetry(), developers enable automatic retries with exponential backoff 2. The client intelligently handles:

  • 429 Too Many Requests: It pauses execution based on the Retry-After or RateLimit-Reset headers returned by the Nansen API 2.

  • Transient 5xx Errors: It retries server-side errors that are likely to resolve themselves quickly 2.

  • Network Flakiness: It attempts to recover from temporary connection drops, provided the request context hasn't expired 2.

Crucially, the retry logic respects the overall timeout budget set by the developer, ensuring that retries never block indefinitely 2.

Mapping the Nansen Ecosystem

The Nansen API is expansive, offering data on Smart Money movements, token flows, portfolio holdings, and historical trends. nansen-go organizes this vast surface area into logical services attached to the main client object 2.

Service Namespace Description Example Endpoints
client.SmartMoney Access netflows, holdings, and DEX trades of highly profitable entities. /api/v1/smart-money/netflow
client.TokenGodMode Utilize the token screener, flow intelligence, and buyer/seller analysis. /api/v1/token-screener
client.Profiler Retrieve current balances and DEX trade history for specific addresses. /api/v1/profiler/address/current-balance
client.Portfolio Analyze DeFi holdings and overall portfolio composition. /api/v1/portfolio/defi-holdings
client.Historical Access backtesting endpoints for historical token flows and balances. /api/v1beta1/tgm/historical-token-flow-summary

This modular approach makes the client highly discoverable. Developers can rely on their IDE's autocomplete to explore the available endpoints within a specific domain, rather than sifting through a monolithic list of functions.

Getting Started and Examples

To help developers hit the ground running, the repository includes a dedicated examples directory containing complete, runnable programs 2. These examples cover common use cases such as:

  • Using the token screener with complex filters and sorting mechanisms.

  • Profiling specific addresses to retrieve balances and trade history.

  • Analyzing Smart Money netflows and DEX trades.

Running these examples is as simple as setting the NANSEN_API_KEY environment variable and executing go run 2.

Conclusion

The nansen-go library is a masterclass in designing a Go API client. By adhering strictly to idiomatic Go principles—such as zero dependencies, context propagation, functional options, and strong typing—it provides a robust and developer-friendly interface to the Nansen AI platform.

For developers looking to integrate high-quality onchain analytics into their Go applications, nansen-go abstracts away the complexity of HTTP communication, error handling, and rate limiting, allowing them to focus on what truly matters: building powerful, data-driven crypto products. It is a tool that truly "stays out of your way" while delivering immense value.


References

Source: dev.to

arrow_back Back to Tutorials