sourcify

package module
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2024 License: Apache-2.0 Imports: 9 Imported by: 3

README

Build Status Coverage Status License PkgGoDev

Sourcify Go

Sourcify Go is a Golang package that provides tools for interacting with the Sourcify API.

It allows you to access various API endpoints and perform operations such as checking server status, retrieving chains information, obtaining contract information from supported chains and more.

Installation

To use Sourcify in your Go project, you can simply import the package:

import "github.com/unpackdev/sourcify-go"

Usage

Creating a Client

To interact with the Sourcify API, you need to create a client using the NewClient function. You can provide optional configuration options using ClientOption functions. For example, you can specify a custom base URL or a custom HTTP client, set retry configuration in case sourcify servers are temporairly unavailable and set rate limits in order to control the rate at which HTTP requests are sent to the sourcify servers.

client := sourcify.NewClient(
	sourcify.WithHTTPClient(httpClient),
	sourcify.WithBaseURL("https://sourcify.dev/server"),
	sourcify.WithRetryOptions(
		sourcify.WithMaxRetries(3),
		sourcify.WithDelay(2*time.Second),
	),
	sourcify.WithRateLimit(10, 1*time.Second),
)
Calling Raw API Endpoints

Sourcify provides various API endpoints as Method objects. You can call these endpoints using the CallMethod function on the client and do your own method parsers if you wish to.

However, if there are methods that we do not provide yet, you can do something like this to extend package.

customMethod := sourcify.Method{...}

customMethod.SetParams(
	MethodParam{Key: ":chain", Value: chainId},
)

if err := customMethod.Verify(); err != nil {
	return nil, err
}

response, statusCode, err := client.CallMethod(customMethod)
if err != nil {
	return nil, err
}

// Close the io.ReadCloser interface.
// This is important as CallMethod is NOT closing the response body!
// You'll have memory leaks if you don't do this!
defer response.Close()

// Process the response
Supported API Endpoints

Sourcify provides the following API endpoints that you can call that are currently supported by this package:

  • MethodHealth: Check the server status. More information
  • MethodGetChains: Retrieve the chains (networks) added to Sourcify. More information
  • MethodCheckByAddresses: Check if contracts with the desired chain and addresses are verified and in the repository. More information
  • MethodCheckAllByAddresses: Check if contracts with the desired chain and addresses are verified and in the repository. More information
  • MethodGetFileTreeFullOrPartialMatch: Get the file tree with full or partial match for the desired chain and address. More information
  • MethodGetFileTreeFullMatch: Get the file tree with full match for the desired chain and address. More information
  • MethodSourceFilesFullOrPartialMatch: Get the source files with full or partial match for the desired chain and address, including metadata.json. More information
  • MethodSourceFilesFullMatch: Get the source files with full match for the desired chain and address, including metadata.json. More information
  • MethodGetContractAddressesFullOrPartialMatch: Get the verified contract addresses for the chain with full or partial match. More information
  • MethodGetFileFromRepositoryFullMatch: Retrieve statically served files over the server for full match contract. More information
  • MethodGetFileFromRepositoryPartialMatch: Retrieve statically served files over the server for partial match contract. More information

For more information on each endpoint, including the parameters they require and the expected responses, refer to the Sourcify API documentation.

Examples

You can find endpoint examples under the examples directory.

Contributing

Contributions to Sourcify are welcome! If you find any issues or have suggestions for improvements, please open an issue or submit a pull request on GitHub.

License

Sourcify is released under the Apache 2.0 License. See the LICENSE file for more details.

Documentation

Overview

Package sourcify provides tools for interacting with the Sourcify API.

Package sourcify provides a Go client for interacting with the Sourcify API.

The Sourcify API allows developers to fetch metadata and verify contract addresses for sourcify supported smart contracts. This package includes methods for retrieving contract metadata, checking contract verification status by addresses, and accessing compiler information and output details.

To use this package, create a new client using the NewClient function, configure it with optional options, and then call the desired methods to interact with the Sourcify API.

The package also includes various types and structures representing contract metadata, compiler information, output details, and client options. These types can be used to parse and work with the data returned by the API.

Example usage:

client := sourcify.NewClient(
	sourcify.WithHTTPClient(httpClient),
	sourcify.WithBaseURL("https://sourcify.dev/server"),
	sourcify.WithRetryOptions(
		sourcify.WithMaxRetries(3),
		sourcify.WithDelay(2*time.Second),
	),

)

metadata, err := sourcify.GetContractMetadata(client, 1, common.HexToAddress("0x1234567890abcdef"), sourcify.MethodMatchTypeFull)
if err != nil {
  log.Fatal(err)
}
fmt.Println("Contract Metadata:", metadata)

For more information on the Sourcify API and its endpoints, refer to the official documentation:

Index

Constants

View Source
const (
	// MethodParamTypeUri denotes the type of parameter which is part of the URI.
	MethodParamTypeUri MethodParamType = iota // 0

	// MethodParamTypeQueryString denotes the type of parameter which is part of the query string.
	MethodParamTypeQueryString // 1

	// MethodMatchTypeFull denotes the type of match which is full.
	MethodMatchTypeFull MethodMatchType = "full"

	// MethodMatchTypePartial denotes the type of match which is partial.
	MethodMatchTypeAny MethodMatchType = "any"

	// MethodMatchTypePartial denotes the type of match which is partial.
	MethodMatchTypePartial MethodMatchType = "partial"
)

Variables

View Source
var (
	// MethodCheckByAddresses represents the API endpoint for checking by addresses in the Sourcify service.
	// It includes the name, the HTTP method, the URI, and the parameters necessary for the request.
	// Checks if contract with the desired chain and address is verified and in the repository.
	// More information: https://docs.sourcify.dev/docs/api/server/check-by-addresses/
	MethodCheckByAddresses = Method{
		Name:           "Check By Addresses",
		URI:            "/check-by-addresses",
		MoreInfo:       "https://docs.sourcify.dev/docs/api/server/check-by-addresses/",
		Method:         "GET",
		ParamType:      MethodParamTypeQueryString,
		RequiredParams: []string{"addresses", "chainIds"},
		Params: []MethodParam{
			{
				Key:   "addresses",
				Value: []string{},
			},
			{
				Key:   "chainIds",
				Value: []int{},
			},
		},
	}

	// MethodCheckAllByAddresses represents the API endpoint for checking all addresses in the Sourcify service.
	// It includes the name, the HTTP method, the URI, and the parameters necessary for the request.
	// Checks if contract with the desired chain and address is verified and in the repository.
	// More information: https://docs.sourcify.dev/docs/api/server/check-all-by-addresses/
	MethodCheckAllByAddresses = Method{
		Name:           "Check All By Addresses",
		URI:            "/check-all-by-addresses",
		MoreInfo:       "https://docs.sourcify.dev/docs/api/server/check-all-by-addresses/",
		Method:         "GET",
		ParamType:      MethodParamTypeQueryString,
		RequiredParams: []string{"addresses", "chainIds"},
		Params: []MethodParam{
			{
				Key:   "addresses",
				Value: []string{},
			},
			{
				Key:   "chainIds",
				Value: []int{},
			},
		},
	}
)
View Source
var (
	// MethodGetFileFromRepositoryFullMatch represents the API endpoint for retrieving staticly served files over the server for full match contract in the Sourcify service.
	// It includes the name, the HTTP method, the URI, and the parameters necessary for the request.
	// Returns all verified sources from the repository for the desired contract address and chain, including metadata.json. Searches only for full matches.
	// More information: https://docs.sourcify.dev/docs/api/repository/get-file-static/
	MethodGetFileFromRepositoryFullMatch = Method{
		Name:           "Retrieve staticly served files over the server for full match contract",
		URI:            "/repository/contracts/full_match/:chain/:address/:filePath",
		MoreInfo:       "https://docs.sourcify.dev/docs/api/repository/get-file-static/",
		Method:         "GET",
		ParamType:      MethodParamTypeUri,
		RequiredParams: []string{":chain", ":address", ":filePath"},
		Params: []MethodParam{
			{
				Key:   ":chain",
				Value: "",
			},
			{
				Key:   ":address",
				Value: "",
			},
			{
				Key:   ":filePath",
				Value: "",
			},
		},
	}

	// MethodGetFileFromRepositoryPartialMatch represents the API endpoint for retrieving staticly served files over the server for partial match contract in the Sourcify service.
	// It includes the name, the HTTP method, the URI, and the parameters necessary for the request.
	// Returns all verified sources from the repository for the desired contract address and chain, including metadata.json. Searches only for partial matches.
	// More information: https://docs.sourcify.dev/docs/api/repository/get-file-static/
	MethodGetFileFromRepositoryPartialMatch = Method{
		Name:           "Retrieve staticly served files over the server for partial match contract",
		URI:            "/repository/contracts/partial_match/:chain/:address/:filePath",
		MoreInfo:       "https://docs.sourcify.dev/docs/api/repository/get-file-static/",
		Method:         "GET",
		ParamType:      MethodParamTypeUri,
		RequiredParams: []string{":chain", ":address", ":filePath"},
		Params: []MethodParam{
			{
				Key:   ":chain",
				Value: "",
			},
			{
				Key:   ":address",
				Value: "",
			},
			{
				Key:   ":filePath",
				Value: "",
			},
		},
	}
)
View Source
var (
	// MethodSourceFilesFullOrPartialMatch represents the API endpoint for getting the source files with full or partial match in the Sourcify service.
	// It includes the name, the HTTP method, the URI, and the parameters necessary for the request.
	// Returns all verified sources from the repository for the desired contract address and chain, including metadata.json. Searches for full and partial matches.
	// More information: https://docs.sourcify.dev/docs/api/server/get-source-files-all/
	MethodSourceFilesFullOrPartialMatch = Method{
		Name:           "Get source files for the address full or partial match",
		URI:            "/files/any/:chain/:address",
		MoreInfo:       "https://docs.sourcify.dev/docs/api/server/get-source-files-all/",
		Method:         "GET",
		ParamType:      MethodParamTypeUri,
		RequiredParams: []string{":chain", ":address"},
		Params: []MethodParam{
			{
				Key:   ":chain",
				Value: "",
			},
			{
				Key:   ":address",
				Value: "",
			},
		},
	}

	// MethodSourceFilesFullMatch represents the API endpoint for getting the source files with full match in the Sourcify service.
	// It includes the name, the HTTP method, the URI, and the parameters necessary for the request.
	// Returns all verified sources from the repository for the desired contract address and chain, including metadata.json. Searches only for full matches.
	// More information: https://docs.sourcify.dev/docs/api/server/get-source-files-full/
	MethodSourceFilesFullMatch = Method{
		Name:           "Get source files for the address full match",
		URI:            "/files/:chain/:address",
		MoreInfo:       "https://docs.sourcify.dev/docs/api/server/get-source-files-full/",
		Method:         "GET",
		ParamType:      MethodParamTypeUri,
		RequiredParams: []string{":chain", ":address"},
		Params: []MethodParam{
			{
				Key:   ":chain",
				Value: "",
			},
			{
				Key:   ":address",
				Value: "",
			},
		},
	}
)
View Source
var (
	// MethodGetFileTreeFullOrPartialMatch represents the API endpoint for getting the file tree with full or partial match in the Sourcify service.
	// It includes the name, the HTTP method, the URI, and the parameters necessary for the request.
	// Returns repository URLs for every file in the source tree for the desired chain and address. Searches for full and partial matches.
	// More information: https://docs.sourcify.dev/docs/api/server/get-file-tree-all/
	MethodGetFileTreeFullOrPartialMatch = Method{
		Name:           "Get File Tree Full or Partial Match",
		URI:            "/files/tree/any/:chain/:address",
		MoreInfo:       "https://docs.sourcify.dev/docs/api/server/get-file-tree-all/",
		Method:         "GET",
		ParamType:      MethodParamTypeUri,
		RequiredParams: []string{":chain", ":address"},
		Params: []MethodParam{
			{
				Key:   ":chain",
				Value: "",
			},
			{
				Key:   ":address",
				Value: "",
			},
		},
	}

	// MethodGetFileTreeFullMatch represents the API endpoint for getting the file tree with full match in the Sourcify service.
	// It includes the name, the HTTP method, the URI, and the parameters necessary for the request.
	// Returns repository URLs for every file in the source tree for the desired chain and address. Searches only for full matches.
	// More information: https://docs.sourcify.dev/docs/api/server/get-file-tree-full/
	MethodGetFileTreeFullMatch = Method{
		Name:           "Get File Tree Full Match",
		URI:            "/files/tree/:chain/:address",
		MoreInfo:       "https://docs.sourcify.dev/docs/api/server/get-file-tree-full/",
		Method:         "GET",
		ParamType:      MethodParamTypeUri,
		RequiredParams: []string{":chain", ":address"},
		Params: []MethodParam{
			{
				Key:   ":chain",
				Value: "",
			},
			{
				Key:   ":address",
				Value: "",
			},
		},
	}
)
View Source
var (
	// ErrInvalidParamType represents an error when a parameter of an invalid type is encountered.
	ErrInvalidParamType = func(t string) error {
		return fmt.Errorf("encountered a parameter of invalid type: %s", t)
	}
)
View Source
var MethodGetChains = Method{
	Name:           "Retrieve staticly served files over the server for partial match contract",
	URI:            "/chains",
	MoreInfo:       "https://docs.sourcify.dev/docs/api/chains/",
	Method:         "GET",
	ParamType:      MethodParamTypeUri,
	RequiredParams: []string{},
	Params:         []MethodParam{},
}

MethodGetChains represents the API endpoint for getting the chains (networks) added to Sourcify in the Sourcify service. It includes the name, the HTTP method, the URI, and the parameters necessary for the request. Returns the chains (networks) added to Sourcify. Contains both supported, unsupported, monitored, and unmonitored chains. More information: https://docs.sourcify.dev/docs/api/chains/

View Source
var (
	// MethodGetContractAddressesFullOrPartialMatch represents the API endpoint for getting the contract addresses with full or partial match in the Sourcify service.
	// It includes the name, the HTTP method, the URI, and the parameters necessary for the request.
	// Returns all verified sources from the repository for the desired contract address and chain, including metadata.json. Searches only for full matches.
	// More information: https://docs.sourcify.dev/docs/api/server/get-contract-addresses-all/
	MethodGetContractAddressesFullOrPartialMatch = Method{
		Name:           "Get verified contract addresses for the chain full or partial match",
		URI:            "/files/contracts/:chain",
		MoreInfo:       "https://docs.sourcify.dev/docs/api/server/get-contract-addresses-all/",
		Method:         "GET",
		ParamType:      MethodParamTypeUri,
		RequiredParams: []string{":chain"},
		Params:         []MethodParam{},
	}
)
View Source
var MethodHealth = Method{
	Name:           "Show Server Status",
	URI:            "/health",
	MoreInfo:       "https://docs.sourcify.dev/docs/api/health/",
	Method:         "GET",
	ParamType:      MethodParamTypeUri,
	RequiredParams: []string{},
	Params:         []MethodParam{},
}

MethodHealth represents the API endpoint for checking the server status in the Sourcify service. It includes the name, the HTTP method, the URI, and the parameters necessary for the request. Ping the server and see if it is alive and ready for requests. More information: https://docs.sourcify.dev/docs/api/health/

Functions

func GetContractMetadataAsBytes

func GetContractMetadataAsBytes(client *Client, chainId int, contract common.Address, matchType MethodMatchType) ([]byte, error)

GetContractMetadataAsBytes retrieves the metadata of a smart contract as a byte slice. The client parameter is a pointer to a Client instance used to make the API call. The chainId parameter is the ID of the blockchain network where the smart contract resides. The contract parameter is the address of the smart contract. The matchType parameter determines the type of method matching to use when retrieving the contract metadata. It returns a byte slice containing the contract metadata, or an error if there was an issue sending the request, decoding the response, or if an invalid matchType was provided.

The MethodMatchType enum is used to determine the type of method matching to use: - MethodMatchTypeFull: Use full method matching. This will only return a match if the entire method signature matches. - MethodMatchTypePartial: Use partial method matching. This will return a match if any part of the method signature matches. - MethodMatchTypeAny: This match type is not implemented and will return an error.

This function will send a request to the API endpoint specified in the client parameter, using the method determined by the matchType parameter. The method will be set with the chainId, contract address, and file path parameters. If the method fails verification, an error will be returned. If the API call is successful, the response body will be read and returned as a byte slice. If the status code of the response is not 200 OK, an error will be returned.

func GetHealth

func GetHealth(client *Client) (bool, error)

GetHealth checks the server status by calling the MethodHealth endpoint using the provided client. It returns a boolean indicating if the server is healthy and an error if any occurred during the request.

Types

type Abi

type Abi struct {
	Inputs          []any          `json:"inputs"`          // Input parameters of the functions
	StateMutability string         `json:"stateMutability"` // State of mutability of the functions
	Type            string         `json:"type"`            // Type of the ABI entry
	Anonymous       bool           `json:"anonymous"`       // Whether the function is anonymous
	Name            string         `json:"name"`            // Name of the function
	Outputs         []OutputDetail `json:"outputs"`         // Output parameters of the functions
}

Abi holds the Application Binary Interface (ABI) of the compiled code.

type Chain

type Chain struct {
	Name                 string              `json:"name"`
	Chain                string              `json:"chain"`
	Icon                 string              `json:"icon,omitempty"`
	Features             []ChainFeature      `json:"features,omitempty"`
	Faucets              []any               `json:"faucets"`
	NativeCurrency       ChainNativeCurrency `json:"nativeCurrency"`
	InfoURL              string              `json:"infoURL"`
	ShortName            string              `json:"shortName"`
	ChainID              int                 `json:"chainId"`
	NetworkID            int                 `json:"networkId"`
	Slip44               int                 `json:"slip44,omitempty"`
	Ens                  ChainEns            `json:"ens,omitempty"`
	Explorers            []ChainExplorer     `json:"explorers,omitempty"`
	Supported            bool                `json:"supported"`
	Monitored            bool                `json:"monitored"`
	ContractFetchAddress string              `json:"contractFetchAddress,omitempty"`
	RPC                  []string            `json:"rpc"`
	EtherscanAPI         string              `json:"etherscanAPI,omitempty"`
	Title                string              `json:"title,omitempty"`
	TxRegex              string              `json:"txRegex,omitempty"`
	RedFlags             []string            `json:"redFlags,omitempty"`
	Status               string              `json:"status,omitempty"`
	Parent               ChainParent         `json:"parent,omitempty"`
	GraphQLFetchAddress  string              `json:"graphQLFetchAddress,omitempty"`
}

Chain represents a chain (network) added to Sourcify.

func GetChains

func GetChains(client *Client) ([]Chain, error)

GetChains gets the chains (networks) added to Sourcify by calling the MethodGetChains endpoint using the provided client. It returns the chains and an error if any occurred during the request.

type ChainEns

type ChainEns struct {
	Registry string `json:"registry"`
}

ChainEns represents the ENS (Ethereum Name Service) configuration of a chain.

type ChainExplorer

type ChainExplorer struct {
	Name     string `json:"name"`
	URL      string `json:"url"`
	Standard string `json:"standard"`
}

ChainExplorer represents an explorer configuration for a chain.

type ChainFeature

type ChainFeature struct {
	Name string `json:"name"`
}

ChainFeature represents a feature of a chain.

type ChainNativeCurrency

type ChainNativeCurrency struct {
	Name     string `json:"name"`
	Symbol   string `json:"symbol"`
	Decimals int    `json:"decimals"`
}

ChainNativeCurrency represents the native currency of a chain.

type ChainParent

type ChainParent struct {
	Type    string `json:"type"`
	Chain   string `json:"chain"`
	Bridges []struct {
		URL string `json:"url"`
	} `json:"bridges"`
}

ChainParent represents the parent chain information for a chain.

type CheckContractAddress

type CheckContractAddress struct {
	Address  common.Address `json:"address"`  // The contract address.
	Status   string         `json:"status"`   // The status of the contract.
	ChainIDs []string       `json:"chainIds"` // The chain ID.
}

CheckContractAddress represents the contract address and associated chain IDs and statuses.

func CheckContractByAddresses

func CheckContractByAddresses(client *Client, addresses []string, chainIds []int, matchType MethodMatchType) ([]*CheckContractAddress, error)

CheckContractByAddresses retrieves the available verified contract addresses for the given chain ID.

type CheckContractAddressMore

type CheckContractAddressMore struct {
	Address common.Address                 `json:"address"`  // The contract address.
	Info    []CheckContractAddressMoreInfo `json:"chainIds"` // The chain ID.
}

CheckContractAddressMore represents the contract address and associated chain IDs and statuses.

type CheckContractAddressMoreInfo

type CheckContractAddressMoreInfo struct {
	Status  string `json:"status"`  // The status of the contract.
	ChainID string `json:"chainId"` // The chain ID.
}

CheckContractAddressMoreInfo represents the contract address and associated chain IDs and statuses.

type Client

type Client struct {
	BaseURL      string       // The base URL of the Sourcify API.
	HTTPClient   *http.Client // The HTTP client to use for making requests.
	RetryOptions RetryOptions // The retry options for the client.
	RateLimiter  *RateLimiter // The rate limiter for the client.
}

func NewClient

func NewClient(options ...ClientOption) *Client

NewClient initializes a new Sourcify client with optional configurations. By default, it uses the Sourcify API's base URL (https://sourcify.dev/server), the default http.Client, and no retry options.

func (*Client) CallMethod

func (c *Client) CallMethod(method Method) (io.ReadCloser, int, error)

CallMethod calls the specified method function with the provided parameters. It returns the response body as a byte slice and an error if any.

type ClientOption

type ClientOption func(*Client)

func WithBaseURL

func WithBaseURL(baseURL string) ClientOption

WithBaseURL allows you to provide your own base URL for the Sourcify client.

func WithHTTPClient

func WithHTTPClient(client *http.Client) ClientOption

WithHTTPClient allows you to provide your own http.Client for the Sourcify client.

func WithRateLimit

func WithRateLimit(max int, duration time.Duration) ClientOption

WithRateLimit allows you to configure rate limits for the Sourcify client.

func WithRetryOptions

func WithRetryOptions(options ...RetryOption) ClientOption

WithRetryOptions allows you to configure retry settings for the Sourcify client.

type CompilationTarget

type CompilationTarget map[string]string

CompilationTarget holds the details of the compilation target.

type Compiler

type Compiler struct {
	Version string `json:"version"` // Compiler version
}

Compiler provides information about the compiler used for the smart contract.

type DevMethod

type DevMethod struct {
	Details string `json:"details"` // Details about the method
}

DevMethod contains information about a method in the developer documentation.

type Devdoc

type Devdoc struct {
	DevMethods map[string]DevMethod `json:"methods"` // Mapping of function signatures to their documentation
}

Devdoc provides details about the developer documentation.

type FileTree

type FileTree struct {
	Status string   `json:"status"`
	Files  []string `json:"files"`
}

FileTree represents the file tree response from the Sourcify service.

func GetContractFiles

func GetContractFiles(client *Client, chainId int, contract common.Address, matchType MethodMatchType) (*FileTree, error)

GetContractFiles retrieves the repository URLs for every file in the source tree for the given chain ID and contract address. The matchType parameter determines whether to search for full matches, partial matches, or any matches. It returns the FileTree object containing the status and file URLs, or an error if any.

type Libraries

type Libraries struct {
}

Libraries represent the libraries used in the source code.

type Metadata

type Metadata struct {
	Compiler Compiler `json:"compiler"` // Compiler contains information about the compiler used.
	Language string   `json:"language"` // Language of the source code
	Output   Output   `json:"output"`   // Output represents details of the compiled code.
	Settings Settings `json:"settings"` // Settings represent the compiler settings used.
	Sources  Sources  `json:"sources"`  // Sources represents the details of the source code.
	Version  int      `json:"version"`  // Version of the metadata.
}

Metadata represents the top-level structure for compiler metadata for Ethereum smart contracts.

func GetContractMetadata

func GetContractMetadata(client *Client, chainId int, contract common.Address, matchType MethodMatchType) (*Metadata, error)

GetContractMetadata fetches the metadata of a contract from a given client, chain ID, contract address, and match type. It returns a Metadata object and an error, if any. This function is primarily used to fetch and parse metadata from smart contracts.

type MetadataDetail

type MetadataDetail struct {
	BytecodeHash string `json:"bytecodeHash"` // Hash of the bytecode
}

MetadataDetail provides additional metadata.

type Method

type Method struct {
	Name           string
	Method         string
	URI            string
	MoreInfo       string
	ParamType      MethodParamType
	RequiredParams []string
	Params         []MethodParam
}

Method represents an API endpoint in the Sourcify service. It includes the name, the HTTP method, the URI, and any necessary parameters for requests to this endpoint.

func (Method) GetParams

func (e Method) GetParams() []MethodParam

GetParams returns a slice of the parameters for the API endpoint.

func (Method) GetQueryParams

func (e Method) GetQueryParams() url.Values

GetQueryParams returns the query parameters for the API endpoint as a url.Values object.

func (Method) ParseUri

func (e Method) ParseUri() (string, error)

ParseUri constructs a URL for the API endpoint, including any necessary query parameters or URI replacements. It can handle parameters of type string, int, []string, and []int. For []string and []int, the individual elements are joined with commas for the query string. Other types of parameters will trigger an error.

func (*Method) SetParams

func (e *Method) SetParams(params ...MethodParam)

SetParams allows setting parameters for the API endpoint using a variadic list of MethodParam values.

func (Method) String

func (m Method) String() string

String returns a string representation of the Method struct.

func (Method) Verify

func (e Method) Verify() error

Verify checks if all the required parameters for the API endpoint are provided. It returns an error if any of the required parameters is missing.

type MethodMatchType

type MethodMatchType string

type MethodParam

type MethodParam struct {
	Key   string
	Value interface{}
}

MethodParam represents a parameter key-value pair.

func (MethodParam) String

func (p MethodParam) String() string

String returns a string representation of the MethodParam.

type MethodParamType

type MethodParamType int

func (MethodParamType) String

func (t MethodParamType) String() string

String returns a string representation of the MethodParamType.

type Optimizer

type Optimizer struct {
	Enabled bool `json:"enabled"` // Whether the optimizer was enabled
	Runs    int  `json:"runs"`    // Number of runs for the optimizer
}

Optimizer contains details about the compiler optimization settings.

type Output

type Output struct {
	Abi     []Abi   `json:"abi"`     // Abi represents the Application Binary Interface (ABI) of the compiled code.
	Devdoc  Devdoc  `json:"devdoc"`  // Devdoc represents the developer documentation.
	Userdoc Userdoc `json:"userdoc"` // Userdoc represents the user documentation.
}

Output contains details about the output of the compiled code.

type OutputDetail

type OutputDetail struct {
	InternalType string `json:"internalType"` // Internal type of the parameter
	Name         string `json:"name"`         // Name of the parameter
	Type         string `json:"type"`         // Type of the parameter
}

OutputDetail holds information about the output parameters of the functions.

type RateLimiter

type RateLimiter struct {
	// Max is the maximum number of actions that can be performed per 'Duration'.
	Max int
	// Duration is the time duration for which 'Max' number of actions can be performed.
	Duration time.Duration
	// contains filtered or unexported fields
}

RateLimiter represents a rate limiter that controls the rate of actions using the token bucket algorithm. It provides a mechanism to prevent an HTTP client from exceeding a certain rate of requests. The Max field represents the maximum number of actions that can be performed per 'Duration'. The Duration field represents the time duration for which 'Max' number of actions can be performed. These fields together determine the capacity of the token bucket and the rate at which tokens are added to the bucket. The bucket field is a channel that models the token bucket. A token is consumed from the bucket each time an action is taken. The capacity of the bucket determines the maximum burstiness of the actions, while the rate at which tokens are added to the bucket determines the sustainable average rate of actions.

func NewRateLimiter

func NewRateLimiter(max int, duration time.Duration) *RateLimiter

NewRateLimiter creates a new rate limiter. The rate limiter uses the token bucket algorithm to control the rate of actions. It initially creates a bucket of capacity 'Max' and then adds a token to the bucket every 'Duration'. It allows a maximum of 'Max' actions to be performed per 'Duration'. If an action is attempted when the bucket is empty, the action blocks until a token is added to the bucket. This blocking behaviour ensures that the rate of actions does not exceed the specified rate.

Parameters: max - The maximum number of actions that can be performed per 'duration'. It is the capacity of the token bucket. duration - The time duration for which 'max' number of actions can be performed.

Returns: A pointer to the created RateLimiter.

func (*RateLimiter) Wait

func (r *RateLimiter) Wait()

Wait is used to perform an action with rate limiting. If the token bucket (i.e., 'bucket' field of RateLimiter) is empty, Wait blocks until a token is added to the bucket. If a token is available in the bucket, Wait consumes the token and returns immediately, allowing the action to be performed.

type RetryOption

type RetryOption func(*RetryOptions)

RetryOption sets a configuration option for retry settings.

func WithDelay

func WithDelay(delay time.Duration) RetryOption

WithDelay sets the delay between retries.

func WithMaxRetries

func WithMaxRetries(maxRetries int) RetryOption

WithMaxRetries sets the maximum number of retries.

type RetryOptions

type RetryOptions struct {
	MaxRetries int           // The maximum number of retries.
	Delay      time.Duration // The delay between retries.
}

RetryOptions represents options for configuring retry settings.

type Settings

type Settings struct {
	CompilationTarget CompilationTarget `json:"compilationTarget"` // CompilationTarget represents the compilation target details.
	EvmVersion        string            `json:"evmVersion"`        // EVM version used
	Libraries         Libraries         `json:"libraries"`         // Libraries used in the source code
	Metadata          MetadataDetail    `json:"metadata"`          // MetadataDetail represents additional metadata.
	Optimizer         Optimizer         `json:"optimizer"`         // Optimizer represents the compiler optimization details.
	Remappings        []any             `json:"remappings"`        // Remappings used in the source code
}

Settings includes details about the compiler settings used.

type SourceCode

type SourceCode struct {
	Name    string `json:"name"`
	Path    string `json:"path"`
	Content string `json:"content"`
}

SourceCode represents the source code details for a file.

type SourceCodes

type SourceCodes struct {
	Status string       `json:"status"`
	Code   []SourceCode `json:"files"`
}

SourceCodes represents the source code details for multiple files.

func GetContractSourceCode

func GetContractSourceCode(client *Client, chainId int, contract common.Address, matchType MethodMatchType) (*SourceCodes, error)

GetContractSourceCode retrieves the source code files for a contract with the given chain ID and address, based on the match type. It makes an API request to the Sourcify service and returns the source code details as a SourceCodes object.

type SourceDetails

type SourceDetails struct {
	Keccak256 string   `json:"keccak256"` // Hash of the source code
	License   string   `json:"license"`   // License of the source code
	Urls      []string `json:"urls"`      // URLs of the source code
}

SourceDetails holds the details of the main contract source code.

type Sources

type Sources map[string]SourceDetails

Sources provides details about the source code.

type Userdoc

type Userdoc struct {
	Methods map[string]DevMethod `json:"methods"` // Mapping of function signatures to their documentation
}

Userdoc provides information about the user documentation.

type VerifiedContractAddresses

type VerifiedContractAddresses struct {
	Full    []common.Address `json:"full"`
	Partial []common.Address `json:"partial"`
}

VerifiedContractAddresses represents the structure for the verified contract addresses response.

func GetAvailableContractAddresses

func GetAvailableContractAddresses(client *Client, chainId int) (*VerifiedContractAddresses, error)

GetAvailableContractAddresses retrieves the available verified contract addresses for the given chain ID.

Directories

Path Synopsis
Package examples provides example code snippets demonstrating the usage of the Sourcify Go client.
Package examples provides example code snippets demonstrating the usage of the Sourcify Go client.

Jump to

Keyboard shortcuts

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