solc

package module
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Mar 28, 2024 License: Apache-2.0 Imports: 19 Imported by: 5

README

Build Status Security Status Coverage Status Go Report Card License PkgGoDev

Solc-Switch: A Concurrent Solidity Manager & Compiler in Go

solc-switch is your partner in streamlining the Solidity development process. Built with Go, it's designed to let developers seamlessly switch between different Solidity compiler versions, ensuring optimal compatibility and a frictionless development experience.

While solc-switch is lightweight, fast, and intuitive, it's primarily tailored for APIs and other integration tools. If you're on the hunt for a CLI-based solution, consider exploring solc-select.

Under the Hood: Execution Mechanics

solc-switch makes use of the os/exec package to carry out compilation commands. This method is direct and gets the job done, but it's worth mentioning that it may not always be the best fit for every situation. I've thought about leveraging CGO to directly incorporate the C++ code of the Solidity compiler. But when I considered the challenges of handling over 100 Solidity releases and the nuances of build time, it became clear that this route might be a bit too ambitious and not necessarily beneficial. My main aim is to strike a balance between efficiency, ease of maintenance, and user experience.

Highlighted Features

  • Speedy Downloads: Parallel downloading of multiple Solidity compiler versions ensures you're not waiting around.
  • Smooth Version Switching: Navigate between different Solidity compiler versions without a hitch.
  • Always in the Loop: With automatic updates, always have access to the latest releases from the official Solidity GitHub repository.
  • Broad Compatibility: Crafted with MacOS and Linux in mind, and potentially adaptable for Windows.

📢 Note for Windows Enthusiasts: Testing on a Windows environment hasn't been done yet. If you're a Windows user, your feedback on its functionality would be invaluable. If you're passionate about contributing, your PRs are more than welcome!

Documentation

For a comprehensive overview of solc-switch, its functions, and detailed usage instructions, please refer to the official documentation.

Installation

To use solc-switch in your project, you don't need a separate installation. Simply import it directly:

import "github.com/0x19/solc-switch"
Setting Up Environment Variable

Before you start, ensure you've set up the required environment variable for the GitHub personal access token:

export SOLC_SWITCH_GITHUB_TOKEN="{your_github_token_here}"

Replace {your_github_token_here} with your actual GitHub personal access token. If you don't have one, you can create it by following the instructions here.

It is used to fetch the latest Solidity compiler releases from the official Solidity GitHub repository. If you don't set it up, you'll get an rate limit error quite quickly.

Example Usage

Below is a simple example demonstrating how to use solc-switch to compile a Solidity smart contract:

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/0x19/solc-switch"
	"github.com/davecgh/go-spew/spew"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

func main() {
	// Sample Solidity contract for demonstration purposes
	sourceCode := `
	// SPDX-License-Identifier: MIT
	pragma solidity ^0.8.0;

	contract SimpleStorage {
		uint256 private storedData;

		function set(uint256 x) public {
			storedData = x;
		}

		function get() public view returns (uint256) {
			return storedData;
		}
	}
	`

	// Create a context with cancellation capabilities
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// Initialize a development logger for solc-switch
	logger, err := solc.GetDevelopmentLogger(zapcore.ErrorLevel)
	if err != nil {
		panic(err)
	}
	zap.ReplaceGlobals(logger)

	// Create a default configuration for solc-switch
	solcConfig, err := solc.NewDefaultConfig()
	if err != nil {
		panic(err)
	}

	// Initialize the solc-switch manager with the provided configuration
	solcManager, err := solc.New(ctx, solcConfig)
	if err != nil {
		panic(err)
	}

	// Increase the default HTTP client timeout to ensure successful fetching of compiler versions
	solcConfig.SetHttpClientTimeout(60 * time.Second)

	// Sync with the official Solidity GitHub repository to ensure the latest compiler versions are available locally
	if err := solcManager.Sync(); err != nil {
		panic(err)
	}

	// Revert the HTTP client timeout to a shorter duration post-sync
	solcConfig.SetHttpClientTimeout(10 * time.Second)

	// Create a default compiler configuration targeting Solidity version "0.8.0"
	compilerConfig, err := solc.NewDefaultCompilerConfig("0.8.0")
	if err != nil {
		panic(err)
	}

	// Start the timer to measure the compilation time
	startTime := time.Now()

	// Compile the provided Solidity source code using the specified compiler configuration
	results, err := solcManager.Compile(ctx, sourceCode, compilerConfig)
	if err != nil {
		panic(err)
	}

	// Calculate the time taken for the compilation
	timeTaken := time.Since(startTime)

	// Display the compilation results for review
	spew.Dump(results)

	// Print the time taken for the compilation
	fmt.Printf("Time took: %s\n", timeTaken)
}

Compilation Results
  • Requested Compiler Version: 0.8.0
  • Compiler Version: 0.8.0+commit.c7dfd78e.Linux.g++
  • Contract Name: SimpleStorage
(*solc.CompilerResults)(0xc0002faa80)({
 RequestedVersion: (string) (len=5) "0.8.0",
 CompilerVersion: (string) (len=31) "0.8.0+commit.c7dfd78e.Linux.g++",
 Bytecode: (string) (len=670) "608060405234801561001057600080fd5b5061012f806100206000396000f3fe6080604052348015600f57600080fd5b506004361060325760003560e01c806360fe47b11460375780636d4ce63c14604f575b600080fd5b604d600480360381019060499190608f565b6069565b005b60556073565b6040516060919060c2565b60405180910390f35b8060008190555050565b60008054905090565b60008135905060898160e5565b92915050565b60006020828403121560a057600080fd5b600060ac84828501607c565b91505092915050565b60bc8160db565b82525050565b600060208201905060d5600083018460b5565b92915050565b6000819050919050565b60ec8160db565b811460f657600080fd5b5056fea26469706673582212202155718f049537eeb007a6f90d13320064bd4989f47c4ff85c9042cc2257550164736f6c63430008000033",
 ABI: (string) (len=280) "[{\"inputs\":[],\"name\":\"get\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"set\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]",
 ContractName: (string) (len=13) "SimpleStorage",
 Errors: ([]string) <nil>,
 Warnings: ([]string) <nil>
})
Compilation Time
Time took: 3.309062ms

Contributing

We welcome contributions from the community! Whether it's bug reports, feature requests, or code contributions, your involvement is highly appreciated.

  • Reporting Bugs: Before creating a bug report, please check if the issue has already been reported in the Issues section. If not, create a new one with a clear description and steps to reproduce the issue.
  • Feature Requests: If you have an idea to enhance the tool, feel free to share it in the Issues section.
  • Code Contributions: If you wish to contribute code, please fork the repository, make your changes, and submit a pull request.

License

solc-switch is licensed under the Apache License 2.0. You can read the full license here.

Documentation

Overview

Package solc provides utilities for managing and interacting with the Solidity compiler.

Package solc provides utilities for working with the Solidity compiler (solc).

Package solc provides utilities for managing and interacting with the Solidity compiler.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetDevelopmentLogger

func GetDevelopmentLogger(level zapcore.Level) (*zap.Logger, error)

GetDevelopmentLogger creates and returns a new development logger using the zap library. The development logger is optimized for development and debugging, providing more detailed logs. The log level can be set using the provided level parameter.

func GetProductionLogger

func GetProductionLogger(level zapcore.Level) (*zap.Logger, error)

GetProductionLogger creates and returns a new production logger using the zap library. The production logger is optimized for performance and is suitable for use in production environments. The log level can be set using the provided level parameter.

Types

type Asset

type Asset struct {
	// URL is the API URL for this asset.
	URL string `json:"url"`
	// ID is the unique identifier for this asset.
	ID int `json:"id"`
	// NodeID is the unique node identifier for this asset.
	NodeID string `json:"node_id"`
	// Name is the name of the asset.
	Name string `json:"name"`
	// Label is an optional label for the asset.
	Label string `json:"label"`
	// Uploader is the user who uploaded this asset.
	Uploader Author `json:"uploader"`
	// ContentType is the MIME type of the asset.
	ContentType string `json:"content_type"`
	// State is the state of the asset (e.g., "uploaded").
	State string `json:"state"`
	// Size is the size of the asset in bytes.
	Size int `json:"size"`
	// DownloadCount is the number of times this asset has been downloaded.
	DownloadCount int `json:"download_count"`
	// CreatedAt is the timestamp when this asset was created.
	CreatedAt string `json:"created_at"`
	// UpdatedAt is the timestamp when this asset was last updated.
	UpdatedAt string `json:"updated_at"`
	// BrowserDownloadURL is the URL to download the asset.
	BrowserDownloadURL string `json:"browser_download_url"`
}

Asset represents a downloadable asset associated with a release.

type Author

type Author struct {
	// Login is the username of the author.
	Login string `json:"login"`
	// ID is the unique identifier for the author.
	ID int `json:"id"`
	// NodeID is the unique node identifier for the author.
	NodeID string `json:"node_id"`
	// AvatarURL is the URL to the author's avatar.
	AvatarURL string `json:"avatar_url"`
	// URL is the API URL for the author.
	URL string `json:"url"`
	// HTMLURL is the web URL for the author's profile.
	HTMLURL string `json:"html_url"`
	// FollowersURL is the URL to fetch the author's followers.
	FollowersURL string `json:"followers_url"`
	// FollowingURL is the URL to see who the author is following.
	FollowingURL string `json:"following_url"`
	// GistsURL is the URL to see the author's gists.
	GistsURL string `json:"gists_url"`
	// StarredURL is the URL to see what repositories the author has starred.
	StarredURL string `json:"starred_url"`
	// SubscriptionsURL is the URL to see the author's subscriptions.
	SubscriptionsURL string `json:"subscriptions_url"`
	// OrganizationsURL is the URL to see the organizations the author belongs to.
	OrganizationsURL string `json:"organizations_url"`
	// ReposURL is the URL to see the author's repositories.
	ReposURL string `json:"repos_url"`
	// EventsURL is the URL to see the author's events.
	EventsURL string `json:"events_url"`
	// ReceivedEventsURL is the URL to see events received by the author.
	ReceivedEventsURL string `json:"received_events_url"`
	// Type indicates the type of the user (e.g., "User" or "Organization").
	Type string `json:"type"`
	// SiteAdmin indicates if the author is a site administrator.
	SiteAdmin bool `json:"site_admin"`
}

Author represents the user who published a release or uploaded an asset.

type CompilationError added in v1.0.1

type CompilationError struct {
	Component      string                         `json:"component"`
	Formatted      string                         `json:"formatted_message"`
	Message        string                         `json:"message"`
	Severity       string                         `json:"severity"`
	Type           string                         `json:"type"`
	SourceLocation CompilationErrorSourceLocation `json:"sourceLocation"`
}

CompilationError represents a compilation error.

type CompilationErrorSourceLocation added in v1.0.3

type CompilationErrorSourceLocation struct {
	File  string `json:"file"`
	Start int    `json:"start"`
	End   int    `json:"end"`
}

type Compiler

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

Compiler represents a Solidity compiler instance.

func NewCompiler

func NewCompiler(ctx context.Context, solc *Solc, config *CompilerConfig, source string) (*Compiler, error)

NewCompiler creates a new Compiler instance with the given context, configuration, and source. It returns an error if the provided configuration, solc instance, or source is invalid.

func (*Compiler) Compile

func (v *Compiler) Compile() (*CompilerResults, error)

Compile compiles the Solidity sources using the configured compiler version and arguments. It returns the compilation results or an error if the compilation fails.

func (*Compiler) GetCompilerVersion

func (v *Compiler) GetCompilerVersion() string

GetCompilerVersion returns the currently set version of the solc compiler.

func (*Compiler) GetContext

func (v *Compiler) GetContext() context.Context

GetContext returns the context associated with the compiler.

func (*Compiler) GetSources

func (v *Compiler) GetSources() string

GetSources returns the Solidity sources associated with the compiler.

func (*Compiler) SetCompilerVersion

func (v *Compiler) SetCompilerVersion(version string)

SetCompilerVersion sets the version of the solc compiler to use.

type CompilerConfig

type CompilerConfig struct {
	CompilerVersion string              // The version of the compiler to use.
	EntrySourceName string              // The name of the entry source file.
	Arguments       []string            // Arguments to pass to the solc tool.
	JsonConfig      *CompilerJsonConfig // The json config to pass to the solc tool.
}

CompilerConfig represents the compiler configuration for the solc binaries.

func NewCompilerConfigFromJSON added in v1.0.1

func NewCompilerConfigFromJSON(compilerVersion string, entrySourceName string, config *CompilerJsonConfig) (*CompilerConfig, error)

NewDefaultCompilerConfig creates and returns a default CompilerConfiguration for compiler to use with provided JSON settings.

func NewDefaultCompilerConfig

func NewDefaultCompilerConfig(compilerVersion string) (*CompilerConfig, error)

NewDefaultCompilerConfig creates and returns a default CompilerConfiguration for compiler to use.

func (*CompilerConfig) AppendArguments

func (c *CompilerConfig) AppendArguments(args ...string)

AppendArguments appends new arguments to the existing set of arguments.

func (*CompilerConfig) GetArguments

func (c *CompilerConfig) GetArguments() []string

GetArguments returns the arguments to be passed to the solc tool.

func (*CompilerConfig) GetCompilerVersion

func (c *CompilerConfig) GetCompilerVersion() string

GetCompilerVersion returns the currently set version of the solc compiler.

func (*CompilerConfig) GetEntrySourceName added in v1.0.1

func (c *CompilerConfig) GetEntrySourceName() string

GetEntrySourceName returns the name of the entry source file.

func (*CompilerConfig) GetJsonConfig added in v1.0.1

func (c *CompilerConfig) GetJsonConfig() *CompilerJsonConfig

GetJsonConfig returns the json config to pass to the solc tool.

func (*CompilerConfig) SanitizeArguments

func (c *CompilerConfig) SanitizeArguments(args []string) ([]string, error)

SanitizeArguments sanitizes the provided arguments against a list of allowed arguments. Returns an error if any of the provided arguments are not in the allowed list.

func (*CompilerConfig) SetArguments

func (c *CompilerConfig) SetArguments(args []string)

SetArguments sets the arguments to be passed to the solc tool.

func (*CompilerConfig) SetCompilerVersion

func (c *CompilerConfig) SetCompilerVersion(version string)

SetCompilerVersion sets the version of the solc compiler to use.

func (*CompilerConfig) SetEntrySourceName added in v1.0.1

func (c *CompilerConfig) SetEntrySourceName(name string)

SetEntrySourceName sets the name of the entry source file.

func (*CompilerConfig) SetJsonConfig added in v1.0.1

func (c *CompilerConfig) SetJsonConfig(config *CompilerJsonConfig)

SetJsonConfig sets the json config to pass to the solc tool.

func (*CompilerConfig) Validate

func (c *CompilerConfig) Validate() error

Validate checks if the current CompilerConfiguration's arguments are valid. It ensures that all required arguments are present.

type CompilerJsonConfig added in v1.0.1

type CompilerJsonConfig struct {
	Language string            `json:"language"` // Specifies the language version (e.g., "Solidity").
	Sources  map[string]Source `json:"sources"`  // Map of source file names to their content.
	Settings Settings          `json:"settings"` // Compiler settings.
}

CompilerJsonConfig represents the JSON configuration for the Solidity compiler.

func (*CompilerJsonConfig) ToJSON added in v1.0.1

func (c *CompilerJsonConfig) ToJSON() ([]byte, error)

ToJSON converts the CompilerJsonConfig to its JSON representation. It returns the JSON byte array or an error if the conversion fails.

type CompilerResult added in v1.0.2

type CompilerResult struct {
	IsEntryContract  bool               `json:"is_entry_contract"`
	RequestedVersion string             `json:"requested_version"`
	CompilerVersion  string             `json:"compiler_version"`
	ContractName     string             `json:"contract_name"`
	Bytecode         string             `json:"bytecode"`
	DeployedBytecode string             `json:"deployedBytecode"`
	ABI              string             `json:"abi"`
	Opcodes          string             `json:"opcodes"`
	Metadata         string             `json:"metadata"`
	Errors           []CompilationError `json:"errors"`
}

CompilerResults represents the results of a solc compilation.

func (*CompilerResult) GetABI added in v1.0.2

func (v *CompilerResult) GetABI() string

GetABI returns the compiled contract's ABI (Application Binary Interface) in JSON format.

func (*CompilerResult) GetBytecode added in v1.0.2

func (v *CompilerResult) GetBytecode() string

GetBytecode returns the compiled contract's bytecode.

func (*CompilerResult) GetCompilerVersion added in v1.0.2

func (v *CompilerResult) GetCompilerVersion() string

GetCompilerVersion returns the actual compiler version used for compilation.

func (*CompilerResult) GetContractName added in v1.0.2

func (v *CompilerResult) GetContractName() string

GetContractName returns the name of the compiled contract.

func (*CompilerResult) GetDeployedBytecode added in v1.0.2

func (v *CompilerResult) GetDeployedBytecode() string

GetDeployedBytecode returns the compiled contract's deployed bytecode.

func (*CompilerResult) GetErrors added in v1.0.2

func (v *CompilerResult) GetErrors() []CompilationError

GetErrors returns the compilation errors.

func (*CompilerResult) GetMetadata added in v1.0.2

func (v *CompilerResult) GetMetadata() string

GetMetadata returns the compiled contract's metadata.

func (*CompilerResult) GetOpcodes added in v1.0.2

func (v *CompilerResult) GetOpcodes() string

GetOpcodes returns the compiled contract's opcodes.

func (*CompilerResult) GetRequestedVersion added in v1.0.2

func (v *CompilerResult) GetRequestedVersion() string

GetRequestedVersion returns the requested compiler version used for compilation.

func (*CompilerResult) HasErrors added in v1.0.2

func (v *CompilerResult) HasErrors() bool

HasErrors returns true if there are compilation errors.

func (*CompilerResult) IsEntry added in v1.0.2

func (v *CompilerResult) IsEntry() bool

IsEntry returns true if the compiled contract is the entry contract.

type CompilerResults

type CompilerResults struct {
	Results []*CompilerResult `json:"results"`
}

func (*CompilerResults) GetEntryContract added in v1.0.2

func (cr *CompilerResults) GetEntryContract() *CompilerResult

func (*CompilerResults) GetResults added in v1.0.2

func (cr *CompilerResults) GetResults() []*CompilerResult

type Config

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

Config represents the configuration settings for solc-switch.

func NewDefaultConfig

func NewDefaultConfig() (*Config, error)

NewDefaultConfig initializes a new Config with default settings.

func (*Config) GetHttpClientTimeout

func (c *Config) GetHttpClientTimeout() time.Duration

GetHttpClientTimeout returns the timeout duration set for the HTTP client.

func (*Config) GetReleasesPath

func (c *Config) GetReleasesPath() string

GetReleasesPath returns the path where releases are stored.

func (*Config) GetReleasesUrl

func (c *Config) GetReleasesUrl() string

GetReleasesUrl returns the URL from which releases are fetched.

func (*Config) SetHttpClientTimeout

func (c *Config) SetHttpClientTimeout(timeout time.Duration)

SetHttpClientTimeout sets the timeout duration for the HTTP client.

func (*Config) SetReleasesPath

func (c *Config) SetReleasesPath(path string) error

SetReleasesPath sets the path for the releases.

func (*Config) Validate

func (c *Config) Validate() error

Validate checks the validity of the configuration settings.

type Distribution

type Distribution string

Distribution represents the type of operating system.

const (
	// Windows denotes the Microsoft Windows operating system.
	Windows Distribution = "windows"

	// MacOS denotes the Apple macOS operating system.
	MacOS Distribution = "darwin"

	// Linux denotes the Linux operating system.
	Linux Distribution = "linux"

	// Unknown denotes an unrecognized or unknown operating system.
	Unknown Distribution = "unknown"
)

func (Distribution) String

func (d Distribution) String() string

String returns the string representation of the Distribution. Possible return values include: - "windows" for Windows. - "macos" for MacOS. - "linux" for Linux. - "unknown" for unrecognized or unknown distributions.

type Optimizer added in v1.0.1

type Optimizer struct {
	Enabled bool `json:"enabled"` // Indicates whether the optimizer is enabled.
	Runs    int  `json:"runs"`    // Specifies the number of optimization runs.
}

Optimizer represents the configuration for the Solidity compiler's optimizer.

type Reactions

type Reactions struct {
	// URL is the API URL for these reactions.
	URL string `json:"url"`
	// TotalCount is the total number of reactions.
	TotalCount int `json:"total_count"`
	// PlusOne is the number of "+1" reactions.
	PlusOne int `json:"+1"`
	// MinusOne is the number of "-1" reactions.
	MinusOne int `json:"-1"`
	// Laugh is the number of "laugh" reactions.
	Laugh int `json:"laugh"`
	// Hooray is the number of "hooray" reactions.
	Hooray int `json:"hooray"`
	// Confused is the number of "confused" reactions.
	Confused int `json:"confused"`
	// Heart is the number of "heart" reactions.
	Heart int `json:"heart"`
	// Rocket is the number of "rocket" reactions.
	Rocket int `json:"rocket"`
	// Eyes is the number of "eyes" reactions.
	Eyes int `json:"eyes"`
}

Reactions represents the reactions to a release.

type Settings added in v1.0.1

type Settings struct {
	Optimizer       Optimizer                      `json:"optimizer"`            // Configuration for the optimizer.
	EVMVersion      string                         `json:"evmVersion,omitempty"` // The version of the Ethereum Virtual Machine to target. Optional.
	Remappings      []string                       `json:"remappings,omitempty"` // List of remappings for library addresses. Optional.
	OutputSelection map[string]map[string][]string `json:"outputSelection"`      // Specifies the type of information to output (e.g., ABI, AST).
}

Settings defines the configuration settings for the Solidity compiler.

type Solc

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

Solc represents the main structure for interacting with the Solidity compiler. It holds the configuration, context, and other necessary components to perform operations like compilation.

func New

func New(ctx context.Context, config *Config) (*Solc, error)

New initializes and returns a new instance of the Solc structure.

func (*Solc) Compile

func (s *Solc) Compile(ctx context.Context, source string, config *CompilerConfig) (*CompilerResults, error)

Compile compiles the provided Solidity source code using the specified compiler configuration.

func (*Solc) GetBinary

func (s *Solc) GetBinary(version string) (string, error)

GetBinary returns the path to the binary of the specified version.

Parameters: - version: A string representing the desired Solidity version.

Returns: - A string representing the path to the binary. - An error if there's any issue during the fetch process or if the binary is not found.

func (*Solc) GetCachedReleases

func (s *Solc) GetCachedReleases() []Version

GetCachedReleases returns the cached releases from memory.

func (*Solc) GetConfig

func (s *Solc) GetConfig() *Config

GetConfig retrieves the configuration associated with the Solc instance.

func (*Solc) GetContext

func (s *Solc) GetContext() context.Context

GetContext retrieves the context associated with the Solc instance.

func (*Solc) GetDistribution

func (s *Solc) GetDistribution() Distribution

GetDistribution determines the operating system type on which the code is running. It returns one of the predefined Distribution constants: Windows, MacOS, Linux, or Unknown.

func (*Solc) GetDistributionForAsset

func (s *Solc) GetDistributionForAsset() string

GetDistributionForAsset determines the appropriate asset name based on the operating system. This is useful for fetching the correct compiler binaries or assets. Possible return values include: - "solc-windows" for Windows. - "solc-macos" for MacOS. - "solc-static-linux" for Linux. - "unknown" for unrecognized or unknown distributions.

func (*Solc) GetHTTPClient

func (s *Solc) GetHTTPClient() *http.Client

GetHTTPClient retrieves the HTTP client associated with the Solc instance.

func (*Solc) GetLatestRelease

func (s *Solc) GetLatestRelease() (*Version, error)

GetLatestRelease reads the memory cache or local releases.json file and returns the latest Solidity version.

func (*Solc) GetLocalReleases

func (s *Solc) GetLocalReleases() ([]Version, error)

GetLocalReleases fetches the Solidity versions saved locally in releases.json.

func (*Solc) GetLocalReleasesPath

func (s *Solc) GetLocalReleasesPath() string

GetLocalReleasesPath returns the path to the local releases.json file.

func (*Solc) GetRelease

func (s *Solc) GetRelease(tagName string) (*Version, error)

GetRelease reads the memory cache or local releases.json file and returns the Solidity version matching the given tag name.

func (*Solc) GetReleasesSimplified

func (s *Solc) GetReleasesSimplified() ([]VersionInfo, error)

GetReleasesSimplified fetches the Solidity versions saved locally in releases.json and returns a simplified version info.

func (*Solc) IsSynced added in v1.0.2

func (s *Solc) IsSynced() bool

IsSynced checks if the local cache is synced with the remote releases.

func (*Solc) LastSyncTime

func (s *Solc) LastSyncTime() time.Time

LastSyncTime retrieves the last time the Solc instance was synced.

func (*Solc) RemoveBinary

func (s *Solc) RemoveBinary(version string) error

RemoveBinary removes the binary file of the specified version.

func (*Solc) Sync

func (s *Solc) Sync() error

Sync fetches the available Solidity versions from GitHub, saves them to releases.json, reloads the local cache, and downloads all the binaries for the distribution for future use.

func (*Solc) SyncBinaries

func (s *Solc) SyncBinaries(versions []Version, limitVersion string) error

SyncBinaries downloads all the binaries for the specified versions in parallel.

func (*Solc) SyncOne

func (s *Solc) SyncOne(version *Version) error

SyncOne fetches a specific Solidity version from GitHub, saves it to releases.json, reloads the local cache, and downloads the binary for the distribution for future use.

func (*Solc) SyncReleases

func (s *Solc) SyncReleases() ([]Version, error)

SyncReleases fetches the available Solidity versions from GitHub, saves them to releases.json, and reloads the local cache.

type Source added in v1.0.1

type Source struct {
	Content string `json:"content"` // The content of the Solidity source file.
}

Source represents the content of a Solidity source file.

type Version

type Version struct {
	// URL is the API URL for this release.
	URL string `json:"url"`
	// AssetsURL is the URL to fetch the assets for this release.
	AssetsURL string `json:"assets_url"`
	// UploadURL is the URL to upload assets for this release.
	UploadURL string `json:"upload_url"`
	// HTMLURL is the web URL for this release.
	HTMLURL string `json:"html_url"`
	// ID is the unique identifier for this release.
	ID int `json:"id"`
	// NodeID is the unique node identifier for this release.
	NodeID string `json:"node_id"`
	// TagName is the git tag associated with this release.
	TagName string `json:"tag_name"`
	// TargetCommitish is the commit this release is associated with.
	TargetCommitish string `json:"target_commitish"`
	// Name is the name of the release.
	Name string `json:"name"`
	// Draft indicates if this release is a draft.
	Draft bool `json:"draft"`
	// Prerelease indicates if this release is a pre-release.
	Prerelease bool `json:"prerelease"`
	// CreatedAt is the timestamp when this release was created.
	CreatedAt string `json:"created_at"`
	// PublishedAt is the timestamp when this release was published.
	PublishedAt string `json:"published_at"`
	// Assets is a list of assets associated with this release.
	Assets []Asset `json:"assets"`
	// TarballURL is the URL to download the tarball archive of this release.
	TarballURL string `json:"tarball_url"`
	// ZipballURL is the URL to download the zip archive of this release.
	ZipballURL string `json:"zipball_url"`
	// Body is the release notes for this release.
	Body string `json:"body"`
	// Reactions contains the reactions for this release.
	Reactions Reactions `json:"reactions"`
	// Author is the user who published this release.
	Author Author `json:"author"`
}

Version represents the structure of a Solidity version. It contains details about a specific release version of Solidity.

func (*Version) GetVersionInfo

func (v *Version) GetVersionInfo(latestVersionTag string) VersionInfo

GetVersionInfo returns a VersionInfo struct containing the version's tag name and an indication if it's the latest version.

type VersionInfo

type VersionInfo struct {
	TagName      string `json:"tag_name"`
	IsLatest     bool   `json:"is_latest"`
	IsPrerelease bool   `json:"is_prerelease"`
}

VersionInfo represents a simplified structure containing only the version tag name and an indication if it's the latest/prerelease version.

Jump to

Keyboard shortcuts

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