contracts

package
v1.4.4 Latest Latest
Warning

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

Go to latest
Published: May 22, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package contracts provides smart contract verification and proxy detection.

Index

Constants

View Source
const (
	// EIP-1967 implementation slot: bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)
	StorageSlotEIP1967Implementation = "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc"

	// EIP-1967 beacon slot: bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)
	StorageSlotEIP1967Beacon = "0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50"

	// EIP-1967 admin slot: bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)
	StorageSlotEIP1967Admin = "0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103"

	// OpenZeppelin legacy implementation slot: keccak256("org.zeppelinos.proxy.implementation")
	StorageSlotOpenZeppelinLegacy = "0x7050c9e0f4ca769c69bd3a8ef740bc37934f8e2c036e5a723fd8ee048ed3f8c3"

	// EIP-1822 PROXIABLE slot: keccak256("PROXIABLE")
	StorageSlotEIP1822 = "0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7"

	// Master copy slot (Gnosis Safe): slot 0
	StorageSlotMasterCopy = "0x0"
)

Well-known storage slots for proxy detection.

View Source
const (
	// implementation() selector
	SelectorImplementation = "0x5c60da1b"

	// admin() selector
	SelectorAdmin = "0xf851a440"

	// upgradeTo(address) selector
	SelectorUpgradeTo = "0x3659cfe6"

	// upgradeToAndCall(address,bytes) selector
	SelectorUpgradeToAndCall = "0x4f1ef286"
)

Well-known function selectors.

Variables

View Source
var (
	// Standard EIP-1167: 0x363d3d373d3d3d363d73<address>5af43d82803e903d91602b57fd5bf3
	EIP1167Prefix = []byte{0x36, 0x3d, 0x3d, 0x37, 0x3d, 0x3d, 0x3d, 0x36, 0x3d, 0x73}
	EIP1167Suffix = []byte{0x5a, 0xf4, 0x3d, 0x82, 0x80, 0x3e, 0x90, 0x3d, 0x91, 0x60, 0x2b, 0x57, 0xfd, 0x5b, 0xf3}

	// Variant: 0x3d3d3d3d363d3d37363d73<address>5af43d3d93803e602a57fd5bf3
	EIP1167VariantPrefix = []byte{0x3d, 0x3d, 0x3d, 0x3d, 0x36, 0x3d, 0x3d, 0x37, 0x36, 0x3d, 0x73}
	EIP1167VariantSuffix = []byte{0x5a, 0xf4, 0x3d, 0x3d, 0x93, 0x80, 0x3e, 0x60, 0x2a, 0x57, 0xfd, 0x5b, 0xf3}
)

EIP-1167 minimal proxy bytecode patterns.

Functions

func CombineABIs

func CombineABIs(proxyABI, implABI json.RawMessage) (json.RawMessage, error)

CombineABIs combines proxy and implementation ABIs.

func EncodeCall

func EncodeCall(method MethodSignature, args ...interface{}) (string, error)

EncodeCall encodes a function call.

func ParseABI

func ParseABI(abiJSON json.RawMessage) ([]MethodSignature, []EventSignature, error)

ParseABI extracts method and event signatures from ABI.

Types

type ABIDecoder

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

ABIDecoder decodes function calls and event logs using ABI.

func NewABIDecoder

func NewABIDecoder(abiJSON json.RawMessage) (*ABIDecoder, error)

NewABIDecoder creates a decoder from ABI JSON.

func (*ABIDecoder) DecodeCall

func (d *ABIDecoder) DecodeCall(input string) (*DecodedCall, error)

DecodeCall decodes a function call from input data.

func (*ABIDecoder) DecodeLog

func (d *ABIDecoder) DecodeLog(topics []string, data string) (*DecodedLog, error)

DecodeLog decodes an event log.

type ABIEntry

type ABIEntry struct {
	Type            string     `json:"type"`
	Name            string     `json:"name,omitempty"`
	Inputs          []ABIParam `json:"inputs,omitempty"`
	Outputs         []ABIParam `json:"outputs,omitempty"`
	StateMutability string     `json:"stateMutability,omitempty"`
	Anonymous       bool       `json:"anonymous,omitempty"`
	Constant        bool       `json:"constant,omitempty"`
	Payable         bool       `json:"payable,omitempty"`
}

ABIEntry represents a single ABI element.

type ABIParam

type ABIParam struct {
	Name         string     `json:"name"`
	Type         string     `json:"type"`
	Indexed      bool       `json:"indexed,omitempty"`
	Components   []ABIParam `json:"components,omitempty"`
	InternalType string     `json:"internalType,omitempty"`
}

ABIParam represents an ABI parameter.

type BytecodeOutput

type BytecodeOutput struct {
	FunctionDebugData json.RawMessage `json:"functionDebugData,omitempty"`
	Object            string          `json:"object"`
	Opcodes           string          `json:"opcodes,omitempty"`
	SourceMap         string          `json:"sourceMap,omitempty"`
	LinkReferences    json.RawMessage `json:"linkReferences,omitempty"`
}

BytecodeOutput represents compiled bytecode.

type CompilerError

type CompilerError struct {
	Component        string          `json:"component"`
	ErrorCode        string          `json:"errorCode"`
	FormattedMessage string          `json:"formattedMessage"`
	Message          string          `json:"message"`
	Severity         string          `json:"severity"`
	SourceLocation   *SourceLocation `json:"sourceLocation,omitempty"`
	Type             string          `json:"type"`
}

CompilerError from solc.

type CompilerOutput

type CompilerOutput struct {
	Contracts map[string]map[string]ContractOutput `json:"contracts"`
	Sources   map[string]SourceOutput              `json:"sources"`
	Errors    []CompilerError                      `json:"errors,omitempty"`
}

CompilerOutput from solc compilation.

type ContractMethod

type ContractMethod struct {
	Selector    string          `json:"selector"`
	Name        string          `json:"name"`
	Signature   string          `json:"signature"`
	InputTypes  json.RawMessage `json:"inputTypes"`
	OutputTypes json.RawMessage `json:"outputTypes,omitempty"`
}

ContractMethod represents a stored method signature.

type ContractOutput

type ContractOutput struct {
	ABI           json.RawMessage `json:"abi"`
	Metadata      string          `json:"metadata,omitempty"`
	UserDoc       json.RawMessage `json:"userdoc,omitempty"`
	DevDoc        json.RawMessage `json:"devdoc,omitempty"`
	IR            string          `json:"ir,omitempty"`
	StorageLayout json.RawMessage `json:"storageLayout,omitempty"`
	EVM           EVMOutput       `json:"evm"`
}

ContractOutput from compilation.

type ContractStore

type ContractStore interface {
	GetContract(ctx context.Context, address string) (*SmartContract, error)
	SaveContract(ctx context.Context, contract *SmartContract) error
}

ContractStore interface for contract storage.

type DecodedCall

type DecodedCall struct {
	MethodID   string                 `json:"methodId"`
	Name       string                 `json:"name"`
	Signature  string                 `json:"signature"`
	Parameters map[string]interface{} `json:"parameters"`
}

DecodedCall represents a decoded function call.

type DecodedLog

type DecodedLog struct {
	Topic0     string                 `json:"topic0"`
	Name       string                 `json:"name"`
	Signature  string                 `json:"signature"`
	Parameters map[string]interface{} `json:"parameters"`
	Indexed    map[string]interface{} `json:"indexed"`
}

DecodedLog represents a decoded event log.

type EVMOutput

type EVMOutput struct {
	Assembly          string            `json:"assembly,omitempty"`
	LegacyAssembly    json.RawMessage   `json:"legacyAssembly,omitempty"`
	Bytecode          BytecodeOutput    `json:"bytecode"`
	DeployedBytecode  BytecodeOutput    `json:"deployedBytecode"`
	MethodIdentifiers map[string]string `json:"methodIdentifiers,omitempty"`
	GasEstimates      json.RawMessage   `json:"gasEstimates,omitempty"`
}

EVMOutput contains bytecode and related data.

type EventSignature

type EventSignature struct {
	Topic0    string     `json:"topic0"` // 32-byte topic
	Name      string     `json:"name"`
	Signature string     `json:"signature"`
	Inputs    []ABIParam `json:"inputs"`
}

EventSignature represents an event signature.

type FourByteDB

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

FourByteDB provides 4byte.directory signature lookup.

func NewFourByteDB

func NewFourByteDB() *FourByteDB

NewFourByteDB creates a new 4byte database.

func (*FourByteDB) AddFromABI

func (db *FourByteDB) AddFromABI(abiJSON json.RawMessage) error

AddFromABI adds all function signatures from an ABI.

func (*FourByteDB) AddSignature

func (db *FourByteDB) AddSignature(sig string)

AddSignature adds a function signature.

func (*FourByteDB) LookupSelector

func (db *FourByteDB) LookupSelector(selector string) []string

LookupSelector returns possible signatures for a selector.

type MetadataSettings

type MetadataSettings struct {
	BytecodeHash      string `json:"bytecodeHash,omitempty"`
	UseLiteralContent bool   `json:"useLiteralContent,omitempty"`
}

MetadataSettings for bytecode metadata.

type MethodSignature

type MethodSignature struct {
	Selector  string     `json:"selector"` // 4-byte selector
	Name      string     `json:"name"`
	Signature string     `json:"signature"` // full signature
	Inputs    []ABIParam `json:"inputs"`
	Outputs   []ABIParam `json:"outputs,omitempty"`
}

MethodSignature represents a function signature.

type MultiABIDecoder

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

MultiABIDecoder combines multiple ABIs for decoding.

func NewMultiABIDecoder

func NewMultiABIDecoder(abis ...json.RawMessage) (*MultiABIDecoder, error)

NewMultiABIDecoder creates a decoder from multiple ABIs.

func (*MultiABIDecoder) DecodeCall

func (m *MultiABIDecoder) DecodeCall(input string) (*DecodedCall, error)

DecodeCall tries to decode with all available ABIs.

func (*MultiABIDecoder) DecodeLog

func (m *MultiABIDecoder) DecodeLog(topics []string, data string) (*DecodedLog, error)

DecodeLog tries to decode with all available ABIs.

type OptimizerSettings

type OptimizerSettings struct {
	Enabled bool `json:"enabled"`
	Runs    int  `json:"runs"`
}

OptimizerSettings for compiler optimization.

type ProxyDetector

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

ProxyDetector detects proxy contracts and resolves implementations.

func NewProxyDetector

func NewProxyDetector(rpcEndpoint string) *ProxyDetector

NewProxyDetector creates a new proxy detector.

func (*ProxyDetector) DetectAllProxies

func (d *ProxyDetector) DetectAllProxies(ctx context.Context, addresses []string) (map[string]*ProxyInfo, error)

DetectAllProxies detects proxies for a list of addresses.

func (*ProxyDetector) DetectProxy

func (d *ProxyDetector) DetectProxy(ctx context.Context, address string) (*ProxyInfo, error)

DetectProxy detects if an address is a proxy and returns implementation info.

func (*ProxyDetector) GetImplementationABI

func (d *ProxyDetector) GetImplementationABI(ctx context.Context, proxyInfo *ProxyInfo, store ContractStore) (json.RawMessage, error)

GetImplementationABI fetches the ABI from the implementation contract.

func (*ProxyDetector) ResolveProxyChain

func (d *ProxyDetector) ResolveProxyChain(ctx context.Context, address string, maxDepth int) ([]string, error)

ResolveProxyChain follows proxy chain to find the final implementation.

type ProxyInfo

type ProxyInfo struct {
	IsProxy               bool      `json:"isProxy"`
	ProxyType             ProxyType `json:"proxyType,omitempty"`
	ImplementationAddress string    `json:"implementationAddress,omitempty"`
	BeaconAddress         string    `json:"beaconAddress,omitempty"`
}

ProxyInfo contains proxy detection results.

type ProxyType

type ProxyType string

ProxyType identifies the proxy pattern used by a contract.

const (
	ProxyNone                   ProxyType = ""
	ProxyEIP1967                ProxyType = "eip1967"
	ProxyEIP1967Beacon          ProxyType = "eip1967_beacon"
	ProxyEIP1967OpenZeppelin    ProxyType = "eip1967_oz"
	ProxyEIP1822                ProxyType = "eip1822"
	ProxyEIP1167                ProxyType = "eip1167"
	ProxyMasterCopy             ProxyType = "master_copy"
	ProxyBasicImplementation    ProxyType = "basic_implementation"
	ProxyCloneWithImmutableArgs ProxyType = "clone_with_immutable_args"
	ProxyEIP2535                ProxyType = "eip2535"
	ProxyResolvedDelegate       ProxyType = "resolved_delegate"
)

type SecondarySource

type SecondarySource struct {
	FileName   string `json:"fileName"`
	SourceCode string `json:"sourceCode"`
}

SecondarySource represents additional source files.

type SmartContract

type SmartContract struct {
	Address            string             `json:"address"`
	Name               string             `json:"name"`
	CompilerVersion    string             `json:"compilerVersion"`
	EVMVersion         string             `json:"evmVersion"`
	Optimization       bool               `json:"optimization"`
	OptimizationRuns   int                `json:"optimizationRuns"`
	SourceCode         string             `json:"sourceCode"`
	ABI                json.RawMessage    `json:"abi"`
	Bytecode           string             `json:"bytecode"`
	DeployedBytecode   string             `json:"deployedBytecode"`
	ConstructorArgs    string             `json:"constructorArgs,omitempty"`
	Libraries          map[string]string  `json:"libraries,omitempty"`
	VerificationStatus VerificationStatus `json:"verificationStatus"`
	ProxyType          ProxyType          `json:"proxyType,omitempty"`
	ImplementationAddr string             `json:"implementationAddress,omitempty"`
	FilePath           string             `json:"filePath,omitempty"`
	SecondarySources   []SecondarySource  `json:"secondarySources,omitempty"`
	CompilerSettings   json.RawMessage    `json:"compilerSettings,omitempty"`
	VerifiedAt         time.Time          `json:"verifiedAt"`
	CreatedAt          time.Time          `json:"createdAt"`
	UpdatedAt          time.Time          `json:"updatedAt"`
}

SmartContract represents a verified smart contract.

type SourceLocation

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

SourceLocation in source code.

type SourceOutput

type SourceOutput struct {
	ID  int             `json:"id"`
	AST json.RawMessage `json:"ast,omitempty"`
}

SourceOutput from compilation.

type StandardJSONInput

type StandardJSONInput struct {
	Language string                        `json:"language"`
	Sources  map[string]StandardJSONSource `json:"sources"`
	Settings StandardJSONSettings          `json:"settings"`
}

StandardJSONInput for Solidity standard JSON verification.

type StandardJSONSettings

type StandardJSONSettings struct {
	Optimizer       OptimizerSettings              `json:"optimizer"`
	EVMVersion      string                         `json:"evmVersion,omitempty"`
	Libraries       map[string]map[string]string   `json:"libraries,omitempty"`
	OutputSelection map[string]map[string][]string `json:"outputSelection"`
	Metadata        *MetadataSettings              `json:"metadata,omitempty"`
}

StandardJSONSettings for compiler settings.

type StandardJSONSource

type StandardJSONSource struct {
	Content string   `json:"content,omitempty"`
	URLs    []string `json:"urls,omitempty"`
}

StandardJSONSource represents a source file in standard JSON input.

type Store

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

Store handles database operations for smart contracts.

func NewStore

func NewStore(db *sql.DB) *Store

NewStore creates a new contract store.

func (*Store) GetContract

func (s *Store) GetContract(ctx context.Context, address string) (*SmartContract, error)

GetContract retrieves a contract by address.

func (*Store) GetContractABI

func (s *Store) GetContractABI(ctx context.Context, address string) (json.RawMessage, error)

GetContractABI retrieves just the ABI for a contract.

func (*Store) GetProxyInfo

func (s *Store) GetProxyInfo(ctx context.Context, proxyAddress string) (*ProxyInfo, error)

GetProxyInfo retrieves proxy information.

func (*Store) GetStats

func (s *Store) GetStats(ctx context.Context) (map[string]interface{}, error)

GetStats returns contract verification statistics.

func (*Store) InitSchema

func (s *Store) InitSchema() error

InitSchema creates the database tables for smart contracts.

func (*Store) ListVerifiedContracts

func (s *Store) ListVerifiedContracts(ctx context.Context, limit, offset int) ([]*SmartContract, error)

ListVerifiedContracts lists all verified contracts.

func (*Store) LookupEvent

func (s *Store) LookupEvent(ctx context.Context, topic0 string) (*EventSignature, error)

LookupEvent finds an event signature by topic0.

func (*Store) LookupMethod

func (s *Store) LookupMethod(ctx context.Context, selector string) (*MethodSignature, error)

LookupMethod finds a method signature by selector.

func (*Store) RecordVerificationAttempt

func (s *Store) RecordVerificationAttempt(ctx context.Context, address, compilerVersion string, success bool, errorMsg string) error

RecordVerificationAttempt records a verification attempt.

func (*Store) SaveContract

func (s *Store) SaveContract(ctx context.Context, contract *SmartContract) error

SaveContract saves a verified contract.

func (*Store) SaveProxyInfo

func (s *Store) SaveProxyInfo(ctx context.Context, proxyAddress string, info *ProxyInfo) error

SaveProxyInfo saves proxy detection results.

func (*Store) SearchContracts

func (s *Store) SearchContracts(ctx context.Context, query string, limit int) ([]*SmartContract, error)

SearchContracts searches contracts by name or address.

type VerificationRequest

type VerificationRequest struct {
	Address          string            `json:"address"`
	Name             string            `json:"name"`
	CompilerVersion  string            `json:"compilerVersion"`
	EVMVersion       string            `json:"evmVersion,omitempty"`
	Optimization     bool              `json:"optimization"`
	OptimizationRuns int               `json:"optimizationRuns"`
	SourceCode       string            `json:"sourceCode"`
	ConstructorArgs  string            `json:"constructorArgs,omitempty"`
	Libraries        map[string]string `json:"libraries,omitempty"`
}

VerificationRequest for contract verification.

type VerificationStatus

type VerificationStatus string

VerificationStatus represents contract verification state.

const (
	StatusUnverified VerificationStatus = "unverified"
	StatusVerified   VerificationStatus = "verified"
	StatusPartial    VerificationStatus = "partial"
	StatusFailed     VerificationStatus = "failed"
)

type Verifier

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

Verifier handles smart contract verification.

func NewVerifier

func NewVerifier(cfg VerifierConfig) *Verifier

NewVerifier creates a new contract verifier.

func (*Verifier) GetCompilerVersions

func (v *Verifier) GetCompilerVersions(ctx context.Context) ([]string, error)

GetCompilerVersions returns available compiler versions.

func (*Verifier) VerifyContract

func (v *Verifier) VerifyContract(ctx context.Context, req VerificationRequest) (*SmartContract, error)

VerifyContract verifies a smart contract using source code.

func (*Verifier) VerifyWithStandardJSON

func (v *Verifier) VerifyWithStandardJSON(ctx context.Context, address, name, compilerVersion string, jsonInput StandardJSONInput) (*SmartContract, error)

VerifyWithStandardJSON verifies using Solidity standard JSON input.

type VerifierConfig

type VerifierConfig struct {
	RPCEndpoint string
	SolcDir     string
	SolcListURL string
}

VerifierConfig for Verifier initialization.

Jump to

Keyboard shortcuts

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