Help us shape the future of Go! Take the 2026 Go Developer Survey

tokenterminal

package module
v1.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 4, 2026 License: MIT Imports: 13 Imported by: 0

README

TokenTerminal Golang Client/SDK/Library

TokenTerminal Golang SDK

CI Tests CodeQL Codecov Go Reference Go version License

A production-ready, zero-dependency Go SDK for the Token Terminal API v2.

Features

  • Full API coverage — all 24 endpoints across Assets, Projects, Market Sectors, Metrics, and Datasets
  • Type-safe — typed request models and generic Result[T] response envelopes
  • Partial-success support — preserves errors arrays alongside valid data
  • Retry with backoff — capped exponential backoff with jitter, honoring Retry-After
  • Context-aware — every method accepts context.Context for cancellation and timeouts
  • Concurrent-safe — a single Client is safe to share across goroutines
  • 308 redirect following — handles project/asset rename redirects transparently
  • Structured errors — sentinel errors for errors.Is and rich *APIError for errors.As
  • Zero external dependencies — uses only the Go standard library

Requirements

  • Go 1.21 or later

Installation

go get github.com/tigusigalpa/tokenterminal-go

Quick Start

package main

import (
    "context"
    "fmt"
    "log"
    "os"

    tt "github.com/tigusigalpa/tokenterminal-go"
)

func main() {
    client, err := tt.NewClient(
        os.Getenv("TOKEN_TERMINAL_API_KEY"),
        tt.WithTimeout(15 * 1e9),
        tt.WithRetry(3, 1e9),
    )
    if err != nil {
        log.Fatal(err)
    }

    result, err := client.Projects.List(context.Background())
    if err != nil {
        log.Fatal(err)
    }

    for _, p := range result.Data {
        fmt.Printf("%s (id: %s)\n", p.Name, p.ProjectID)
    }
}

Configuration

Environment Variables
Variable Required Default Description
TOKEN_TERMINAL_API_KEY Yes — Your Token Terminal API key
TOKEN_TERMINAL_BASE_URL No https://api.tokenterminal.com Custom base URL
TOKEN_TERMINAL_TIMEOUT No 30 HTTP timeout in seconds
TOKEN_TERMINAL_MAX_RETRIES No 3 Maximum retry attempts
TOKEN_TERMINAL_RETRY_DELAY No 1 Initial retry delay in seconds
Functional Options
client, err := tokenterminal.NewClient(
    apiKey,
    tokenterminal.WithBaseURL("https://api.tokenterminal.com"),
    tokenterminal.WithHTTPClient(customHTTPClient),
    tokenterminal.WithTimeout(15 * time.Second),
    tokenterminal.WithRetry(3, time.Second),
    tokenterminal.WithUserAgent("my-app/1.0"),
    tokenterminal.WithRetryPOST(), // opt-in POST retries
)
From Environment
client, err := tokenterminal.NewClientFromEnv()

Endpoint Coverage

Domain Method HTTP Route
Assets client.Assets.List GET /v2/assets
Assets client.Assets.Get GET /v2/assets/{asset_id}
Assets client.Assets.HistoricalMetrics GET /v2/assets/{asset_id}/metrics
Assets client.Assets.MetricsBreakdown POST /v2/assets/{asset_id}/metrics-breakdown
Projects client.Projects.List GET /v2/projects
Projects client.Projects.Get GET /v2/projects/{project_id}
Projects client.Projects.Product GET /v2/projects/{project_id}/products/{product_id}
Projects client.Projects.FinancialStatement GET /v2/projects/{project_id}/financial-statement
Projects client.Projects.HistoricalMetrics GET /v2/projects/{project_id}/metrics
Projects client.Projects.ProductHistoricalMetrics GET /v2/projects/{project_id}/products/{product_id}/metrics
Projects client.Projects.MetricAggregations GET /v2/projects/{project_id}/metric-aggregations
Market Sectors client.MarketSectors.List GET /v2/market-sectors
Market Sectors client.MarketSectors.Get GET /v2/market-sectors/{market_sector_id}
Metrics client.Metrics.List GET /v2/metrics
Metrics client.Metrics.Data GET /v2/metrics/{metric_id}
Metrics client.Metrics.Aggregations GET /v2/metric-aggregations
Metrics client.Metrics.Breakdown POST /v2/metric-breakdown
Datasets client.Datasets.List GET /v2/datasets
Datasets client.Datasets.BlockchainComparison GET /v2/datasets/blockchain_comparison
Datasets client.Datasets.CohortAnalysis GET /v2/datasets/cohort_analysis
Datasets client.Datasets.CryptoScreener GET /v2/datasets/crypto_screener
Datasets client.Datasets.InsiderTransactions GET /v2/datasets/insider_transactions
Datasets client.Datasets.ProjectContracts GET /v2/datasets/project_contracts
Datasets client.Datasets.TrendingContracts GET /v2/datasets/trending_contracts

Error Handling

The SDK provides typed sentinel errors for use with errors.Is and a rich *APIError for errors.As:

result, err := client.Projects.List(ctx)
if err != nil {
    switch {
    case errors.Is(err, tt.ErrUnauthorized):
        fmt.Println("Invalid API key")
    case errors.Is(err, tt.ErrRateLimited):
        var apiErr *tt.APIError
        if errors.As(err, &apiErr) {
            fmt.Printf("Rate limited. Retry-After: %s\n", apiErr.RetryAfter)
        }
    case errors.Is(err, tt.ErrNotFound):
        fmt.Println("Not found")
    default:
        var apiErr *tt.APIError
        if errors.As(err, &apiErr) {
            fmt.Printf("API error %d: %s\n", apiErr.StatusCode, apiErr.Message)
        }
    }
}
Sentinel Errors
Error HTTP Status
ErrBadRequest 400
ErrUnauthorized 401
ErrSubscriptionInvalid 402
ErrForbidden 403
ErrNotFound 404
ErrRateLimited 429
ErrAPIError 5xx

Partial Success

Some endpoints return valid data alongside an errors array. The SDK preserves both:

result, err := client.Projects.HistoricalMetrics(ctx, "uniswap", &tt.HistoricalMetricsParams{
    MetricIDs: []string{"fees", "invalid-metric"},
})
if err != nil {
    log.Fatal(err)
}

for _, issue := range result.Errors {
    log.Printf("Partial error: %s %s=%s", issue.Code, issue.Field, issue.Value)
}

Retry Semantics

  • GET requests are retried by default (429, 5xx, transient network errors).
  • POST requests are not retried unless WithRetryPOST() is used.
  • Backoff uses capped exponential delay with jitter.
  • Retry-After header is honored when present.
  • Context cancellation stops all retry waits immediately.

Cache Guidance

Token Terminal recommends caching /projects and /metrics and refreshing daily or weekly. The SDK provides an optional cache adapter point — you can wrap the List methods with your own caching layer. No invisible persistent cache is built in.

Context and Concurrency

Every method accepts context.Context as its first argument. A single Client is safe for concurrent use:

var wg sync.WaitGroup
for _, projectID := range projectIDs {
    wg.Add(1)
    go func(id string) {
        defer wg.Done()
        _, err := client.Projects.Get(ctx, id)
    }(projectID)
}
wg.Wait()

Examples

Example Description Command
Basic List projects and metrics go run examples/basic/main.go
Project Metrics Historical metrics with filters go run examples/project_metrics/main.go
Metric Breakdown POST breakdown with stats go run examples/metric_breakdown/main.go
Datasets Query crypto screener go run examples/datasets/main.go
Error Handling Handle API errors go run examples/error_handling/main.go
Concurrency Concurrent safe calls go run examples/concurrency/main.go

Testing

go test ./... -v
go test -race ./...
gofmt -l .
go vet ./...

All tests use httptest.Server and never call the real Token Terminal API.

API Documentation

License

MIT © Igor Sazonov

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrMissingAPIKey       = errors.New("tokenterminal: API key is required")
	ErrBadRequest          = errors.New("tokenterminal: bad request")
	ErrUnauthorized        = errors.New("tokenterminal: unauthorized")
	ErrSubscriptionInvalid = errors.New("tokenterminal: subscription invalid or payment required")
	ErrForbidden           = errors.New("tokenterminal: forbidden")
	ErrNotFound            = errors.New("tokenterminal: not found")
	ErrRateLimited         = errors.New("tokenterminal: rate limited")
	ErrAPIError            = errors.New("tokenterminal: API error")
)

Sentinel errors for use with errors.Is.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	StatusCode  int
	Code        string
	Message     string
	RetryAfter  string
	RequestURL  string
	BodySnippet string
}

APIError represents a structured error returned by the Token Terminal API. Use errors.As to extract it from a returned error.

func (*APIError) Error

func (e *APIError) Error() string

Error implements the error interface.

func (*APIError) Is

func (e *APIError) Is(target error) bool

Is allows errors.Is matching against sentinel errors.

type AggregateBy

type AggregateBy string

AggregateBy represents the granularity level for metric queries.

const (
	// AggregateByChain aggregates metrics by chain.
	AggregateByChain AggregateBy = "chain"
	// AggregateByProductID aggregates metrics by product ID.
	AggregateByProductID AggregateBy = "product_id"
)

type Asset

type Asset struct {
	AssetID     string         `json:"asset_id"`
	AssetType   *string        `json:"asset_type"`
	Name        string         `json:"name"`
	Symbol      string         `json:"symbol"`
	CoingeckoID *string        `json:"coingecko_id"`
	Addresses   []AssetAddress `json:"addresses"`
	Products    []AssetProduct `json:"products"`
	CreatedAt   string         `json:"created_at"`
	InsertedAt  string         `json:"inserted_at"`
}

Asset represents an asset in the Token Terminal API.

type AssetAddress

type AssetAddress struct {
	ChainID      *string `json:"chain_id"`
	TokenAddress *string `json:"token_address"`
	TokenName    *string `json:"token_name"`
	TokenSymbol  *string `json:"token_symbol"`
}

AssetAddress represents an asset's address on a specific chain.

type AssetBreakdownItem

type AssetBreakdownItem struct {
	AssetID        *string                         `json:"asset_id"`
	DataID         *string                         `json:"data_id"`
	ProductID      *string                         `json:"product_id"`
	ChainID        *string                         `json:"chain_id"`
	MarketSectorID *string                         `json:"market_sector_id"`
	Metrics        map[string]BreakdownMetricStats `json:"metrics"`
}

AssetBreakdownItem represents a row in an asset metrics breakdown response.

type AssetDetail

type AssetDetail struct {
	Asset
	AvailableMetrics []string `json:"available_metrics"`
}

AssetDetail is an Asset with available_metrics field.

type AssetHistoricalMetricsParams

type AssetHistoricalMetricsParams struct {
	MetricID       string
	ChainIDs       []string
	ProductIDs     []string
	Start          *Date
	End            *Date
	AggregateBy    []string
	OrderDirection OrderDirection
	Interval       Interval
}

AssetHistoricalMetricsParams holds parameters for asset historical metrics.

type AssetMetricPoint

type AssetMetricPoint struct {
	Timestamp string `json:"timestamp"`
	AssetID   string `json:"asset_id"`
	MetricID  string `json:"metric_id"`
	Value     string `json:"value"`
}

AssetMetricPoint represents a single historical metric data point for an asset.

type AssetMetricsBreakdownBody

type AssetMetricsBreakdownBody struct {
	MetricIDs       []string `json:"metric_ids"`
	GroupBy         GroupBy  `json:"group_by"`
	Interval        Interval `json:"interval"`
	DataIDs         []string `json:"data_ids,omitempty"`
	ProductIDs      []string `json:"product_ids,omitempty"`
	AssetIDs        []string `json:"asset_ids,omitempty"`
	ChainIDs        []string `json:"chain_ids,omitempty"`
	MarketSectorIDs []string `json:"market_sector_ids,omitempty"`
	IncludeSelf     *bool    `json:"includeSelf,omitempty"`
	Start           *Date    `json:"start,omitempty"`
	End             *Date    `json:"end,omitempty"`
	IgnoreThreshold *bool    `json:"ignore_threshold,omitempty"`
}

AssetMetricsBreakdownBody represents the JSON body for the asset metrics breakdown POST.

type AssetProduct

type AssetProduct struct {
	DataID               string   `json:"data_id"`
	ProductID            string   `json:"product_id"`
	Tags                 []string `json:"tags"`
	RelationToTheProject *string  `json:"relation_to_the_project"`
}

AssetProduct represents a product associated with an asset.

type AssetsService

type AssetsService struct {
	// contains filtered or unexported fields
}

AssetsService provides access to the Token Terminal assets endpoints.

func (*AssetsService) Get

func (s *AssetsService) Get(ctx context.Context, assetID string) (*ResultOne[AssetDetail], error)

Get retrieves details and available metrics for a specific asset. GET /v2/assets/{asset_id}

func (*AssetsService) HistoricalMetrics

func (s *AssetsService) HistoricalMetrics(ctx context.Context, assetID string, params *AssetHistoricalMetricsParams) (*Result[AssetMetricPoint], error)

HistoricalMetrics retrieves historical metrics for an asset. GET /v2/assets/{asset_id}/metrics

func (*AssetsService) List

func (s *AssetsService) List(ctx context.Context, params *ListAssetsParams) (*Result[Asset], error)

List retrieves a list of all assets. GET /v2/assets

func (*AssetsService) MetricsBreakdown

func (s *AssetsService) MetricsBreakdown(ctx context.Context, assetID string, body *AssetMetricsBreakdownBody) (*Result[AssetBreakdownItem], error)

MetricsBreakdown retrieves aggregated breakdown data for asset metrics. POST /v2/assets/{asset_id}/metrics-breakdown

func (*AssetsService) MetricsBreakdownRaw

func (s *AssetsService) MetricsBreakdownRaw(ctx context.Context, assetID string, body *AssetMetricsBreakdownBody) (*Result[json.RawMessage], error)

MetricsBreakdownRaw retrieves the breakdown with raw JSON data for dynamic fields.

type BlockchainComparisonRow

type BlockchainComparisonRow struct {
	ChainID   string          `json:"chain_id"`
	ChainName string          `json:"chain_name"`
	Raw       json.RawMessage `json:"-"`
}

BlockchainComparisonRow represents a row in the blockchain comparison dataset. Dynamic metric columns are preserved in Raw.

func (*BlockchainComparisonRow) UnmarshalJSON

func (r *BlockchainComparisonRow) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the known fields normally while preserving the full raw JSON payload in Raw for access to dynamic metric columns.

type BreakdownMetricStats

type BreakdownMetricStats struct {
	Latest *float64 `json:"latest,omitempty"`
	Avg    *float64 `json:"avg,omitempty"`
	Sum    *float64 `json:"sum,omitempty"`
	Change *float64 `json:"change,omitempty"`
	Trend  *float64 `json:"trend,omitempty"`
}

BreakdownMetricStats represents the aggregated stats for a metric in a breakdown response.

type Client

type Client struct {
	Assets        *AssetsService
	Projects      *ProjectsService
	MarketSectors *MarketSectorsService
	Metrics       *MetricsService
	Datasets      *DatasetsService
	// contains filtered or unexported fields
}

Client is the main Token Terminal API client. A single Client is safe for concurrent use across goroutines.

func NewClient

func NewClient(apiKey string, opts ...Option) (*Client, error)

NewClient creates a new Token Terminal API client with the given API key and optional functional options.

func NewClientFromEnv

func NewClientFromEnv(opts ...Option) (*Client, error)

NewClientFromEnv creates a new client from environment variables. TOKEN_TERMINAL_API_KEY is required; TOKEN_TERMINAL_BASE_URL and TOKEN_TERMINAL_TIMEOUT are optional.

type CohortAnalysisRow

type CohortAnalysisRow struct {
	ProjectName       string  `json:"project_name"`
	ProjectID         string  `json:"project_id"`
	MarketSectorID    string  `json:"market_sector_id"`
	MarketSectorName  string  `json:"market_sector_name"`
	Cohort            string  `json:"cohort"`
	InitialCohortSize float64 `json:"initial_cohort_size"`
	Month0            float64 `json:"month_0"`
	Month1            float64 `json:"month_1"`
	Month2            float64 `json:"month_2"`
	Month3            float64 `json:"month_3"`
	Month4            float64 `json:"month_4"`
	Month5            float64 `json:"month_5"`
	Month6            float64 `json:"month_6"`
	Month7            float64 `json:"month_7"`
	Month8            float64 `json:"month_8"`
	Month9            float64 `json:"month_9"`
	Month10           float64 `json:"month_10"`
	Month11           float64 `json:"month_11"`
}

CohortAnalysisRow represents a row in the cohort analysis dataset.

type CryptoScreenerRow

type CryptoScreenerRow struct {
	ProjectName      string          `json:"project_name"`
	ProjectID        string          `json:"project_id"`
	MarketSectorID   string          `json:"market_sector_id"`
	MarketSectorName string          `json:"market_sector_name"`
	Raw              json.RawMessage `json:"-"`
}

CryptoScreenerRow represents a row in the crypto screener dataset. Dynamic metric columns are preserved in Raw.

func (*CryptoScreenerRow) UnmarshalJSON

func (r *CryptoScreenerRow) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the known fields normally while preserving the full raw JSON payload in Raw for access to dynamic metric columns.

type DatasetInfo

type DatasetInfo struct {
	MartID string `json:"mart_id"`
	Name   string `json:"name"`
}

DatasetInfo represents a dataset in the list endpoint.

type DatasetQuery

type DatasetQuery struct {
	ProjectIDs      []string
	ChainIDs        []string
	MarketSectorIDs []string
	OrderBy         string
	OrderDirection  OrderDirection
	Limit           *int
}

DatasetQuery holds common parameters for dataset queries.

type DatasetsService

type DatasetsService struct {
	// contains filtered or unexported fields
}

DatasetsService provides access to the Token Terminal datasets endpoints.

func (*DatasetsService) BlockchainComparison

func (s *DatasetsService) BlockchainComparison(ctx context.Context, params *DatasetQuery) (*Result[BlockchainComparisonRow], error)

BlockchainComparison retrieves the Blockchain comparison dataset. GET /v2/datasets/blockchain_comparison

func (*DatasetsService) CohortAnalysis

func (s *DatasetsService) CohortAnalysis(ctx context.Context, params *DatasetQuery) (*Result[CohortAnalysisRow], error)

CohortAnalysis retrieves the Cohort analysis dataset. GET /v2/datasets/cohort_analysis

func (*DatasetsService) CryptoScreener

func (s *DatasetsService) CryptoScreener(ctx context.Context, params *DatasetQuery) (*Result[CryptoScreenerRow], error)

CryptoScreener retrieves the Crypto screener dataset. GET /v2/datasets/crypto_screener

func (*DatasetsService) InsiderTransactions

func (s *DatasetsService) InsiderTransactions(ctx context.Context, params *DatasetQuery) (*Result[InsiderTransactionRow], error)

InsiderTransactions retrieves the Insider transactions dataset. GET /v2/datasets/insider_transactions

func (*DatasetsService) List

List retrieves all available datasets. GET /v2/datasets

func (*DatasetsService) ProjectContracts

func (s *DatasetsService) ProjectContracts(ctx context.Context, params *DatasetQuery) (*Result[ProjectContractRow], error)

ProjectContracts retrieves the Project contracts dataset. GET /v2/datasets/project_contracts

func (*DatasetsService) TrendingContracts

func (s *DatasetsService) TrendingContracts(ctx context.Context, params *DatasetQuery) (*Result[TrendingContractRow], error)

TrendingContracts retrieves the Trending contracts dataset. GET /v2/datasets/trending_contracts

type Date

type Date struct {
	time.Time
}

Date is a date-only type that serializes to YYYY-MM-DD for query parameters. Use Date("2025-01-01") to create a value.

func DateVal

func DateVal(s string) Date

DateVal creates a Date from a YYYY-MM-DD string, panicking on error. Intended for use in literals where the format is known to be correct.

func NewDate

func NewDate(s string) (Date, error)

NewDate creates a Date from a YYYY-MM-DD string.

func (Date) IsZero

func (d Date) IsZero() bool

IsZero reports whether the date is the zero value.

func (Date) String

func (d Date) String() string

String returns the date in YYYY-MM-DD format.

type FinancialStatementInterval

type FinancialStatementInterval string

FinancialStatementInterval represents intervals for financial statement queries.

const (
	// FSInterval1m specifies a one-month financial statement interval.
	FSInterval1m FinancialStatementInterval = "1m"
	// FSInterval1y specifies a one-year financial statement interval.
	FSInterval1y FinancialStatementInterval = "1y"
	// FSInterval2y specifies a two-year financial statement interval.
	FSInterval2y FinancialStatementInterval = "2y"
	// FSInterval3y specifies a three-year financial statement interval.
	FSInterval3y FinancialStatementInterval = "3y"
	// FSInterval5y specifies a five-year financial statement interval.
	FSInterval5y FinancialStatementInterval = "5y"
	// FSIntervalMax specifies the maximum financial statement interval.
	FSIntervalMax FinancialStatementInterval = "max"
)

type FinancialStatementParams

type FinancialStatementParams struct {
	TimestampGranularity TimestampGranularity
	Interval             FinancialStatementInterval
}

FinancialStatementParams holds parameters for financial statement queries.

type FinancialStatementRow

type FinancialStatementRow struct {
	Timestamp                string `json:"timestamp"`
	TimestampLabelHeading    string `json:"timestamp_label_heading"`
	TimestampLabelSubheading string `json:"timestamp_label_subheading"`
	TimestampGranularity     string `json:"timestamp_granularity"`
	ProjectName              string `json:"project_name"`
	Section                  string `json:"section"`
	MetricID                 string `json:"metric_id"`
	Value                    string `json:"value"`
	PopChange                string `json:"pop_change"`
	Definition               string `json:"definition"`
}

FinancialStatementRow represents a single row in a financial statement.

type GroupBy

type GroupBy string

GroupBy represents the grouping dimension for breakdown queries.

const (
	// GroupByAssets groups breakdown data by assets.
	GroupByAssets GroupBy = "assets"
	// GroupByProjects groups breakdown data by projects.
	GroupByProjects GroupBy = "projects"
	// GroupByProduct groups breakdown data by products.
	GroupByProduct GroupBy = "product"
	// GroupByChains groups breakdown data by chains.
	GroupByChains GroupBy = "chains"
	// GroupByMarketSector groups breakdown data by market sectors.
	GroupByMarketSector GroupBy = "market-sector"
	// GroupByChainAsset groups breakdown data by chain and asset.
	GroupByChainAsset GroupBy = "chain-asset"
	// GroupByChainProject groups breakdown data by chain and project.
	GroupByChainProject GroupBy = "chain-project"
	// GroupByProductChain groups breakdown data by product and chain.
	GroupByProductChain GroupBy = "product+chain"
	// GroupByChainProduct groups breakdown data by chain and product.
	GroupByChainProduct GroupBy = "chain-product"
	// GroupByChainMarketSector groups breakdown data by chain and market sector.
	GroupByChainMarketSector GroupBy = "chain-market-sector"
)

type HistoricalMetricsParams

type HistoricalMetricsParams struct {
	MetricIDs       []string
	ChainIDs        []string
	ProductIDs      []string
	MarketSectorIDs []string
	AggregateBy     AggregateBy
	Start           *Date
	End             *Date
	OrderDirection  OrderDirection
	AssetsBridged   *bool
}

HistoricalMetricsParams holds parameters for project historical metrics.

type InsiderTransactionRow

type InsiderTransactionRow struct {
	Timestamp                  string   `json:"timestamp"`
	ProjectName                string   `json:"project_name"`
	ProjectID                  string   `json:"project_id"`
	MarketSectorID             string   `json:"market_sector_id"`
	MarketSectorName           string   `json:"market_sector_name"`
	ChainID                    string   `json:"chain_id"`
	ChainName                  string   `json:"chain_name"`
	TokenStandard              string   `json:"token_standard"`
	TokenSymbol                string   `json:"token_symbol"`
	TokenAddress               string   `json:"token_address"`
	InsiderAccountAddress      string   `json:"insider_account_address"`
	InsiderAccountTitle        string   `json:"insider_account_title"`
	CounterpartyAccountAddress string   `json:"counterparty_account_address"`
	CounterpartyAccountTitle   string   `json:"counterparty_account_title"`
	TransactionHash            string   `json:"transaction_hash"`
	TransactionType            string   `json:"transaction_type"`
	TransactionNumber          string   `json:"transaction_number"`
	DexName                    string   `json:"dex_name"`
	ActionType                 string   `json:"action_type"`
	AmountNative               *float64 `json:"amount_native"`
	AmountUSD                  *float64 `json:"amount_usd"`
	FlowUSD                    *float64 `json:"flow_usd"`
	PercentageOfPosition       *float64 `json:"percentage_of_position"`
	PostTransactionPosition    *float64 `json:"post_transaction_position"`
	PositionCreationTimestamp  string   `json:"position_creation_timestamp"`
}

InsiderTransactionRow represents a row in the insider transactions dataset.

type Interval

type Interval string

Interval represents a time interval for data aggregation.

const (
	// Interval24h specifies a 24-hour aggregation interval.
	Interval24h Interval = "24h"
	// Interval7d specifies a seven-day aggregation interval.
	Interval7d Interval = "7d"
	// Interval30d specifies a 30-day aggregation interval.
	Interval30d Interval = "30d"
	// Interval90d specifies a 90-day aggregation interval.
	Interval90d Interval = "90d"
	// Interval180d specifies a 180-day aggregation interval.
	Interval180d Interval = "180d"
	// Interval365d specifies a 365-day aggregation interval.
	Interval365d Interval = "365d"
	// IntervalMax specifies the maximum available aggregation interval.
	IntervalMax Interval = "max"
	// IntervalYTD specifies the year-to-date aggregation interval.
	IntervalYTD Interval = "ytd"
	// Interval4FullQ specifies the trailing four-full-quarter aggregation interval.
	Interval4FullQ Interval = "4fullq"
)

type ListAssetsParams

type ListAssetsParams struct {
	AssetIDs      []string
	AssetTypes    []string
	MarketSectors []string
	Limit         *int
	Offset        *int
}

ListAssetsParams holds parameters for listing assets.

type MarketSector

type MarketSector struct {
	ID   string `json:"id"`
	Name string `json:"name"`
	URL  string `json:"url"`
}

MarketSector represents a market sector in the list endpoint.

type MarketSectorDescription

type MarketSectorDescription struct {
	What string `json:"what"`
	How  string `json:"how"`
}

MarketSectorDescription represents the description of a market sector.

type MarketSectorDetail

type MarketSectorDetail struct {
	MarketSectorID string                  `json:"market_sector_id"`
	Name           string                  `json:"name"`
	Description    MarketSectorDescription `json:"description"`
	Projects       []MarketSectorProject   `json:"projects"`
}

MarketSectorDetail represents detailed market sector data.

type MarketSectorProject

type MarketSectorProject struct {
	ProjectID string `json:"project_id"`
	Name      string `json:"name"`
	URL       string `json:"url"`
}

MarketSectorProject represents a project within a market sector.

type MarketSectorsService

type MarketSectorsService struct {
	// contains filtered or unexported fields
}

MarketSectorsService provides access to the Token Terminal market sectors endpoints.

func (*MarketSectorsService) Get

func (s *MarketSectorsService) Get(ctx context.Context, marketSectorID string) (*ResultOne[MarketSectorDetail], error)

Get retrieves market sector data including its projects. GET /v2/market-sectors/{market_sector_id}

func (*MarketSectorsService) List

List retrieves a list of all market sectors. GET /v2/market-sectors

type MetricAggregation

type MetricAggregation struct {
	ProjectName           string `json:"project_name"`
	ProjectID             string `json:"project_id"`
	MetricID              string `json:"metric_id"`
	MetricAggregationName string `json:"metric_aggregation_name"`
	Value                 string `json:"value"`
}

MetricAggregation represents a metric aggregation for multiple projects.

type MetricAggregationsParams

type MetricAggregationsParams struct {
	ProjectIDs []string
	MetricIDs  []string
}

MetricAggregationsParams holds parameters for the metric aggregations endpoint.

type MetricBreakdownBody

type MetricBreakdownBody struct {
	MetricIDs       []string `json:"metric_ids"`
	Interval        Interval `json:"interval"`
	GroupBy         GroupBy  `json:"group_by"`
	ProjectIDs      []string `json:"project_ids,omitempty"`
	ProductIDs      []string `json:"product_ids,omitempty"`
	ChainIDs        []string `json:"chain_ids,omitempty"`
	MarketSectorIDs []string `json:"market_sector_ids,omitempty"`
	Start           *Date    `json:"start,omitempty"`
	End             *Date    `json:"end,omitempty"`
}

MetricBreakdownBody represents the JSON body for the metric breakdown POST.

type MetricBreakdownItem

type MetricBreakdownItem struct {
	DataID    *string                         `json:"data_id"`
	ChainID   *string                         `json:"chain_id"`
	ProductID *string                         `json:"product_id"`
	Metrics   map[string]BreakdownMetricStats `json:"metrics"`
}

MetricBreakdownItem represents a row in a metric breakdown response.

type MetricDataParams

type MetricDataParams struct {
	ProjectIDs      []string
	ChainIDs        []string
	ProductIDs      []string
	MarketSectorIDs []string
	Start           *Date
	End             *Date
	AssetsBridged   *bool
}

MetricDataParams holds parameters for the metric data endpoint.

type MetricDataPoint

type MetricDataPoint struct {
	Timestamp   string `json:"timestamp"`
	ProjectID   string `json:"project_id"`
	ProjectName string `json:"project_name"`
	MetricID    string `json:"metric_id"`
	Value       string `json:"value"`
}

MetricDataPoint represents a single metric data point for multiple projects.

type MetricDefinition

type MetricDefinition struct {
	MetricID    string `json:"metric_id"`
	MetricName  string `json:"metric_name"`
	Description string `json:"description"`
	URL         string `json:"url"`
}

MetricDefinition represents a metric in the metrics list endpoint.

type MetricsService

type MetricsService struct {
	// contains filtered or unexported fields
}

MetricsService provides access to the Token Terminal metrics endpoints.

func (*MetricsService) Aggregations

Aggregations retrieves metric aggregations for multiple projects. GET /v2/metric-aggregations

func (*MetricsService) Breakdown

Breakdown retrieves metric breakdown aggregation for multiple projects, chains, or products. POST /v2/metric-breakdown

func (*MetricsService) BreakdownRaw

func (s *MetricsService) BreakdownRaw(ctx context.Context, body *MetricBreakdownBody) (*Result[json.RawMessage], error)

BreakdownRaw retrieves the breakdown with raw JSON data for dynamic fields.

func (*MetricsService) Data

func (s *MetricsService) Data(ctx context.Context, metricID string, params *MetricDataParams) (*Result[MetricDataPoint], error)

Data retrieves metric data for multiple projects. GET /v2/metrics/{metric_id}

func (*MetricsService) List

List retrieves a list of all metrics. GET /v2/metrics

type Option

type Option func(*config)

Option is a functional option for configuring the Client.

func WithBaseURL

func WithBaseURL(url string) Option

WithBaseURL sets a custom base URL (useful for testing).

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient sets a custom *http.Client.

func WithRetry

func WithRetry(maxRetries int, delay time.Duration) Option

WithRetry configures the retry behaviour. maxRetries is the maximum number of retry attempts (0 disables retries). delay is the initial backoff delay between retries.

func WithRetryPOST

func WithRetryPOST() Option

WithRetryPOST enables automatic retry for POST requests. By default POST requests are not retried.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the HTTP client timeout.

func WithUserAgent

func WithUserAgent(ua string) Option

WithUserAgent sets a custom User-Agent header.

type OrderDirection

type OrderDirection string

OrderDirection represents the sort order for API responses.

const (
	// OrderAscending specifies ascending sort order.
	OrderAscending OrderDirection = "asc"
	// OrderDescending specifies descending sort order.
	OrderDescending OrderDirection = "desc"
)

type PartialError

type PartialError struct {
	Code      string `json:"code"`
	Field     string `json:"field,omitempty"`
	Value     string `json:"value,omitempty"`
	ProjectID string `json:"project_id,omitempty"`
	MetricID  string `json:"metric_id,omitempty"`
}

PartialError represents a partial-success error returned alongside valid data.

type ProductDetail

type ProductDetail struct {
	Name               string          `json:"name"`
	ProductID          string          `json:"product_id"`
	ProjectID          string          `json:"project_id"`
	Symbol             string          `json:"symbol"`
	MarketSectors      json.RawMessage `json:"market_sectors"`
	Chains             []string        `json:"chains"`
	AggregateByOptions json.RawMessage `json:"aggregate_by_options"`
	MetricAvailability json.RawMessage `json:"metric_availability"`
	MetricDefinitions  json.RawMessage `json:"metric_definitions"`
	MetricSources      json.RawMessage `json:"metric_sources"`
}

ProductDetail represents detailed information about a product within a project.

type ProductHistoricalMetricsParams

type ProductHistoricalMetricsParams struct {
	MetricIDs      []string
	ChainIDs       []string
	Start          *Date
	End            *Date
	AggregateBy    AggregateBy
	OrderDirection OrderDirection
	AssetsBridged  *bool
}

ProductHistoricalMetricsParams holds parameters for product historical metrics.

type ProductMetricPoint

type ProductMetricPoint struct {
	MetricID string  `json:"metric_id"`
	Date     string  `json:"date"`
	Value    float64 `json:"value"`
	ChainID  string  `json:"chain_id,omitempty"`
}

ProductMetricPoint represents a historical metric data point for a product.

type Project

type Project struct {
	Name              string           `json:"name"`
	ProjectID         string           `json:"project_id"`
	CoingeckoID       string           `json:"coingecko_id"`
	Symbol            string           `json:"symbol"`
	URL               string           `json:"url"`
	IsArchived        bool             `json:"is_archived"`
	ArchivedReason    string           `json:"archived_reason"`
	MaintenanceReason string           `json:"maintenance_reason"`
	Products          []ProjectProduct `json:"products"`
}

Project represents a project in the list endpoint.

type ProjectContractRow

type ProjectContractRow struct {
	ProjectID                      string          `json:"project_id"`
	ProjectName                    string          `json:"project_name"`
	MarketSectorID                 string          `json:"market_sector_id"`
	MarketSectorName               string          `json:"market_sector_name"`
	ChainID                        string          `json:"chain_id"`
	ChainName                      string          `json:"chain_name"`
	AccountAddress                 string          `json:"account_address"`
	AccountTitle                   string          `json:"account_title"`
	AccountCreationTimestamp       string          `json:"account_creation_timestamp"`
	GasUsed1dSum                   *float64        `json:"gas_used_1d_sum"`
	TransactionCount1dSum          *float64        `json:"transaction_count_1d_sum"`
	ActiveAddresses1dDistinctCount *float64        `json:"active_addresses_1d_distinct_count"`
	TransactionGas1dAvg            *float64        `json:"transaction_gas_1d_avg"`
	GasMarketShare1dAvg            *float64        `json:"gas_market_share_1d_avg"`
	Inflows1dSum                   *float64        `json:"inflows_1d_sum"`
	Outflows1dSum                  *float64        `json:"outflows_1d_sum"`
	NetFlows1dSum                  *float64        `json:"net_flows_1d_sum"`
	Raw                            json.RawMessage `json:"-"`
}

ProjectContractRow represents a row in the project contracts dataset.

func (*ProjectContractRow) UnmarshalJSON

func (r *ProjectContractRow) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the known fields normally while preserving the full raw JSON payload in Raw for access to dynamic metric columns.

type ProjectDetail

type ProjectDetail struct {
	Name               string                    `json:"name"`
	ProjectID          string                    `json:"project_id"`
	Symbol             string                    `json:"symbol"`
	Description        json.RawMessage           `json:"description"`
	MarketSectors      json.RawMessage           `json:"market_sectors"`
	Chains             []string                  `json:"chains"`
	Links              []ProjectLink             `json:"links"`
	AggregateByOptions json.RawMessage           `json:"aggregate_by_options"`
	MetricAvailability json.RawMessage           `json:"metric_availability"`
	MetricDefinitions  []ProjectMetricDefinition `json:"metric_definitions"`
	MetricSources      []ProjectMetricDefinition `json:"metric_sources"`
}

ProjectDetail represents the detailed project data with metric availability.

type ProjectLink struct {
	Summary string `json:"summary"`
	URL     string `json:"url"`
}

ProjectLink represents a link associated with a project.

type ProjectMetricAggregation

type ProjectMetricAggregation struct {
	ProjectName           string `json:"project_name"`
	ProjectID             string `json:"project_id"`
	MetricID              string `json:"metric_id"`
	MetricAggregationName string `json:"metric_aggregation_name"`
	Value                 string `json:"value"`
}

ProjectMetricAggregation represents a metric aggregation for a project.

type ProjectMetricDefinition

type ProjectMetricDefinition struct {
	MetricID   string `json:"metric_id"`
	Definition string `json:"definition"`
}

ProjectMetricDefinition represents a metric definition for a project.

type ProjectMetricPoint

type ProjectMetricPoint struct {
	Timestamp    string          `json:"timestamp"`
	ProjectName  string          `json:"project_name"`
	ProjectID    string          `json:"project_id"`
	Chain        string          `json:"chain,omitempty"`
	BusinessLine string          `json:"business_line,omitempty"`
	Version      string          `json:"version,omitempty"`
	RawMetrics   json.RawMessage `json:"-"` // dynamic metric keys
}

ProjectMetricPoint represents a historical metric data point for a project.

type ProjectProduct

type ProjectProduct struct {
	ProductID   string `json:"product_id"`
	ProductName string `json:"product_name"`
	Symbol      string `json:"symbol"`
	URL         string `json:"url"`
}

ProjectProduct represents a product within a project listing.

type ProjectsService

type ProjectsService struct {
	// contains filtered or unexported fields
}

ProjectsService provides access to the Token Terminal projects endpoints.

func (*ProjectsService) FinancialStatement

func (s *ProjectsService) FinancialStatement(ctx context.Context, projectID string, params *FinancialStatementParams) (*Result[FinancialStatementRow], error)

FinancialStatement retrieves the financial statement for a project. GET /v2/projects/{project_id}/financial-statement

func (*ProjectsService) Get

func (s *ProjectsService) Get(ctx context.Context, projectID string) (*ResultOne[ProjectDetail], error)

Get retrieves metric availability for a project. GET /v2/projects/{project_id}

func (*ProjectsService) HistoricalMetrics

func (s *ProjectsService) HistoricalMetrics(ctx context.Context, projectID string, params *HistoricalMetricsParams) (*Result[json.RawMessage], error)

HistoricalMetrics retrieves historical metrics for a project. GET /v2/projects/{project_id}/metrics

func (*ProjectsService) List

func (s *ProjectsService) List(ctx context.Context) (*Result[Project], error)

List retrieves a list of all projects. GET /v2/projects

func (*ProjectsService) MetricAggregations

func (s *ProjectsService) MetricAggregations(ctx context.Context, projectID string) (*Result[ProjectMetricAggregation], error)

MetricAggregations retrieves metric aggregations for a project. GET /v2/projects/{project_id}/metric-aggregations

func (*ProjectsService) Product

func (s *ProjectsService) Product(ctx context.Context, projectID, productID string) (*ResultOne[ProductDetail], error)

Product retrieves details for a specific product of a project. GET /v2/projects/{project_id}/products/{product_id}

func (*ProjectsService) ProductHistoricalMetrics

func (s *ProjectsService) ProductHistoricalMetrics(ctx context.Context, projectID, productID string, params *ProductHistoricalMetricsParams) (*Result[json.RawMessage], error)

ProductHistoricalMetrics retrieves historical metrics for a specific product of a project. GET /v2/projects/{project_id}/products/{product_id}/metrics

type ResponseMetadata

type ResponseMetadata struct {
	StatusCode int
	Headers    http.Header
}

ResponseMetadata contains HTTP response metadata.

type Result

type Result[T any] struct {
	Data     []T
	Errors   []PartialError
	Metadata ResponseMetadata
}

Result is a generic envelope that wraps the API response data, optional partial-success errors, and response metadata.

type ResultOne

type ResultOne[T any] struct {
	Data     T
	Errors   []PartialError
	Metadata ResponseMetadata
}

ResultOne is like Result but for single-object responses (non-array data).

type TimestampGranularity

type TimestampGranularity string

TimestampGranularity represents the granularity for financial statements.

const (
	// GranularityYear specifies yearly financial statement timestamps.
	GranularityYear TimestampGranularity = "year"
	// GranularityQuarter specifies quarterly financial statement timestamps.
	GranularityQuarter TimestampGranularity = "quarter"
	// GranularityMonth specifies monthly financial statement timestamps.
	GranularityMonth TimestampGranularity = "month"
	// GranularityWeek specifies weekly financial statement timestamps.
	GranularityWeek TimestampGranularity = "week"
)

type TrendingContractRow

type TrendingContractRow struct {
	ProjectID                string          `json:"project_id"`
	ProjectName              string          `json:"project_name"`
	MarketSectorID           string          `json:"market_sector_id"`
	MarketSectorName         string          `json:"market_sector_name"`
	ChainID                  string          `json:"chain_id"`
	ChainName                string          `json:"chain_name"`
	AccountAddress           string          `json:"account_address"`
	AccountTitle             string          `json:"account_title"`
	AccountCreationTimestamp string          `json:"account_creation_timestamp"`
	Raw                      json.RawMessage `json:"-"`
}

TrendingContractRow represents a row in the trending contracts dataset.

func (*TrendingContractRow) UnmarshalJSON

func (r *TrendingContractRow) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes the known fields normally while preserving the full raw JSON payload in Raw for access to dynamic metric columns.

Directories

Path Synopsis
examples
basic command
concurrency command
datasets command
error_handling command
project_metrics command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL