erc721

package
v0.0.0-...-2597ab7 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2023 License: MIT Imports: 23 Imported by: 0

Documentation

Overview

Package erc721 provides functionality associated with ERC721 NFTs.

Index

Constants

View Source
const TokenIDParam = "tokenId"

TokenIDParam is the name of the httprouter parameter matched by metadata and image endpoints. Examples of valid paths include:

/metadata/:tokenId
/images/:tokenId
/path/to/metadata/:tokenId/:otherParam/passed/to/user/functions

Variables

This section is empty.

Functions

func AttachServers

func AttachServers(ctx context.Context, mux *http.ServeMux, client *ethclient.Client) error

If the Client is non-nil every server registered with an Address for the Client's chain ID will be bound to the respective Address. See Server documentation for behaviour of the Contract field, which is populated by this step.

func MustRegisterServer

func MustRegisterServer(pathPrefix string, s Server, chainAddrs ChainAddressFunc, ctor Constructor)

MustRegisterServer registers an ERC721 metadata Server to be attached by calls to AttachServers(). It is expected to be called in init() functions, and errors are fatal to the binary.

All MetadataEndpoints and ImageEndpoints will have their Path fields prefixed with pathPrefix. The Server.Contract MUST be nil as it will be bound to the provided Address by calls to AttachServers().

If an Address is provided for a chain ID, AttachServers() will bind to this address, using the Constructor, and populate the Server.Contract field appropriately. The Constructor MAY be nil, in which case a generic IERC721 will be used. See Server documentation for behaviour of the Contract field.

Types

type Attribute

type Attribute struct {
	TraitType   string             `json:"trait_type,omitempty"`
	Value       interface{}        `json:"value"`
	DisplayType OpenSeaDisplayType `json:"display_type,omitempty"`
}

An Attribute is a single attribute in Metadata.

func (*Attribute) String

func (a *Attribute) String() string

String returns a human-readable string of TraitType:Value.

type ChainAddressFunc

type ChainAddressFunc func(uint64) (common.Address, error)

ChainAddressFunc returns contract addresses depending on chain ID

func AsChainAddressFunc

func AsChainAddressFunc(chainAddrs map[uint64]common.Address) ChainAddressFunc

AsChainAddressFunc converts a map to a ChainAddressFunc

type Collection

type Collection map[TokenID]*Metadata

A Collection is a set of Metadata, each associated with a single token ID.

func CollectionFromMetadata

func CollectionFromMetadata(md []*Metadata) Collection

CollectionFromMetadata assumes that each token's ID is its index in the received Metadata slice, returning the respective Collection map.

func (Collection) Rarity

func (coll Collection) Rarity(bucket func(interface{}) string) *Rarity

Rarity computes rarity of each token in the Collection based on information entropy. Every TraitType is considered as a categorical probability distribution with each Value having an associated probability and hence information content. The rarity of a particular token is the sum of information content carried by each of its Attributes, divided by the entropy of the Collection as a whole (see the Rarity struct for rationale).

Notably, the lack of a TraitType is considered as a null-Value Attribute as the absence across the majority of a Collection implies rarity in those tokens that do carry the TraitType.

Non-string Attribute Values are passed to the bucket function. The returned bucket is used in place of original value. It is valid for the bucket function to simply return the string equivalent (e.g. true/false for booleans).

type Constructor

type Constructor func(common.Address, bind.ContractBackend) (Interface, error)

A Constructor binds to an Address, exposing Interface methods. See FromConcreteConstructor if using abigen code.

func FromConcreteConstructor

func FromConcreteConstructor[T Interface](ctor func(common.Address, bind.ContractBackend) (T, error)) Constructor

FromConcreteConstructor generically creates a Constructor from a function that returns a concrete type implementing Interface. It accepts all New*() functions generated by abigen. For example:

FromConcreteConstructor(erc.New.NewIERC721)

type ImageEndpoint

type ImageEndpoint struct {
	Path    string
	Handler ImageHandler
}

An ImageEndpoint is the image equivalent of a MetadataEndpoint.

type ImageHandler

type ImageHandler func(context.Context, Interface, *TokenID, *http.Request, httprouter.Params) (img io.Reader, contentType string, httpCode int, err error)

An ImageHandler is the image equivalent of a MetadataHandler. See MetadataHandler re the Context.

type Interface

type Interface interface {
	OwnerOf(_ *bind.CallOpts, tokenId *big.Int) (common.Address, error)
}

Interface is the ERC721 standard interface, as generated by abigen.

type Metadata

type Metadata struct {
	Name           string       `json:"name,omitempty"`
	Description    string       `json:"description,omitempty"`
	Image          string       `json:"image,omitempty"`
	AnimationURL   string       `json:"animation_url,omitempty"`
	ExternalURL    string       `json:"external_url,omitempty"`
	CollectionName string       `json:"collection_name,omitempty"`
	Attributes     []*Attribute `json:"attributes,omitempty"`
}

Metadata carries a parsed JSON payload from ERC721 metadata, compatible with OpenSea.

func (*Metadata) CloneShallow

func (md *Metadata) CloneShallow() *Metadata

CloneShallow returns a shallow copy of the Metadata to avoid mutating the original. Signing URLs without creating a shallow copy can sometimes break the URL by appending the URL onto itself.

func (*Metadata) Hash

func (md *Metadata) Hash() common.Hash

Hash returns the keccak256 hash of the JSON-encoded Metadata.

func (*Metadata) MarshalJSONTo

func (md *Metadata) MarshalJSONTo(w io.Writer) (int, error)

MarshalJSONTo marshals the Metadata to JSON and writes it to the Writer, returning the number of bytes written and any error that may occur.

func (*Metadata) SignImageURL

func (md *Metadata) SignImageURL(bh *storage.BucketHandle) error

SignImageURL signs the Metadata's Image field with a GCS signed URL.

func (*Metadata) SignedURL

func (md *Metadata) SignedURL(bh *storage.BucketHandle, url string) (string, error)

SignedURL signs the provided GCS URL with a signed URL and returns it. All signed URLs use GCS's v2 signing scheme to be valid for a year (vs v4 signing scheme which has a maximum lifetime of 7 days). When signing, consider passing in a CloneShallow() to avoid mutating the original metadata.

type MetadataEndpoint

type MetadataEndpoint struct {
	Path    string
	Handler MetadataHandler
}

A MetadataEndpoint specifies an HTTP path and associated handler for requests matched to the path. The Path follows the syntax of github.com/julienschmidt/httprouter and uses TokenIDParam to extract the token ID.

type MetadataHandler

type MetadataHandler func(context.Context, Interface, *TokenID, *http.Request, httprouter.Params) (md *Metadata, httpCode int, err error)

A MetadataHandler returns Metadata for a specified TokenID, bound to an ERC721 instance that can be accessed via the Interface. It is typically used in a Server. The Context is always the http.Request.Context to make the API easier to misuse by those requiring a Context but unaware of its availability who might then use context.Background().

func SignedURLImages

func SignedURLImages(ctx context.Context, bucketName string, src MetadataHandler, opts ...option.ClientOption) (MetadataHandler, error)

SignedURLImages wraps the provided MetadataHandler in a new one that sources all images from a GCP Storage signed URL. The bucket name is held constant for all images, while the object is derived from the Image field returned in src().Image.

type OpenSeaDisplayType

type OpenSeaDisplayType int

An OpenSeaDisplayType is an OpenSea-specific metadata concept to control how their UI treats numerical values.

See https://docs.opensea.io/docs/metadata-standards for details.

const (
	DisplayDefault OpenSeaDisplayType = iota
	DisplayNumber
	DisplayBoostNumber
	DisplayBoostPercentage
	DisplayDate
)

Allowable OpenSeaDisplayType values.

func (OpenSeaDisplayType) MarshalJSON

func (t OpenSeaDisplayType) MarshalJSON() ([]byte, error)

MarshalJSON returns the display type as JSON.

func (OpenSeaDisplayType) String

func (t OpenSeaDisplayType) String() string

String returns the display type as a string.

func (*OpenSeaDisplayType) UnmarshalJSON

func (t *OpenSeaDisplayType) UnmarshalJSON(buf []byte) error

UnmarshalJSON parses the JSON buffer into the display type.

type Rarity

type Rarity struct {
	Entropy float64
	Scores  map[TokenID]float64
}

Rarity describes the information-theoretic "rarity" of a Collection.

The concept of "rarity" can be considered as a measure of "surprise" at the occurrence of a particular token's properties, within the context of the Collection from which it is derived. Self-information is a measure of such surprise, and information entropy a measure of the expected value of self-information across a distribution (i.e. across a Collection).

It is trivial to "stuff" a Collection with extra information by merely adding additional properties to all tokens. This is reflected in the Entropy field, measured in bits—all else held equal, a Collection with more token properties will have higher Entropy. However, this information bloat is carried by the tokens themselves, so their individual information-content grows in line with Collection-wide Entropy. The Scores are therefore scaled down by the Entropy to provide unitless "relative surprise", which can be safely compared between Collections.

type Server

type Server struct {
	// BaseURL is the base URL of the server; i.e. everything except the path,
	// which will be overwritten.
	BaseURL *url.URL
	// TokenIDBase, if non-zero, uses a custom base for decoding the token ID,
	// defaulting to base 10.
	TokenIDBase int
	// The Contract, if provided, is used to confirm that tokens exist before
	// responding with metadata or images. Checks use the ownerOf function,
	// which must not revert.
	Contract Interface

	// Metadata and Image are responsible for returning a token's metadata and
	// image, respectively (surprise, surprise!). If Contract is non-nil, the
	// token is guaranteed to exist if Metadata/Image are called. Only 200, 400,
	// 404 and 500 are allowed as HTTP codes, and these will be propagated to
	// the end user. If more than one endpoint is provided for a given type,
	// they are selected based on their Path.
	Metadata []MetadataEndpoint
	Image    []ImageEndpoint
}

A Server handles HTTP routes to serve ERC721 metadata JSON and associated images. If a contract binding is provided, it is checked to ensure that the requested token already exists, thus allowing a Server to be used for delayed reveals.

func (*Server) Handler

func (s *Server) Handler() (http.Handler, error)

Handler returns a Handler, for use with http.ListenAndServe(), that handles all requests for metadata and images. Unless the Handler is specifically needed for non-default uses, prefer s.ListenAndServer().

func (*Server) ListenAndServe

func (s *Server) ListenAndServe(addr string) error

ListenAndServe returns http.ListenAndServe(addr, s.Handler()).

type TokenID

type TokenID [32]byte

A TokenID is a uint256 Solidity tokenId.

func TokenIDFromBig

func TokenIDFromBig(b *big.Int) (*TokenID, error)

TokenIDFromBig returns TokenIDFromUint256(uint256.FromBig(b)), or an error if b overflows 256 bits.

func TokenIDFromHex

func TokenIDFromHex(h string) (*TokenID, error)

TokenIDFromHex returns TokenIDFromUint256(uint256.FromHex(b)), or any error returned by FromHex().

func TokenIDFromInt

func TokenIDFromInt(i int) *TokenID

TokenIDFromInt returns TokenIDFromUint256(uint256.NewInt(uint64(i))).

func TokenIDFromUint256

func TokenIDFromUint256(u *uint256.Int) *TokenID

TokenIDFromUint256 returns the 32-byte buffer underlying u, typed as a TokenID pointer.

func TokenIDFromUint64

func TokenIDFromUint64(u uint64) *TokenID

TokenIDFromUint64 returns TokenIDFromUint256(uint256.NewInt(u)).

func (*TokenID) Big

func (id *TokenID) Big() *big.Int

Big returns id as a big.Int.

func (*TokenID) Cmp

func (id *TokenID) Cmp(oID *TokenID) int

Cmp compares id and oID and returns:

-1 if o <  oID
 0 if o == oID
 1 if o >  oID

func (*TokenID) String

func (id *TokenID) String() string

String returns a decimal text representation of id.

func (*TokenID) Text

func (id *TokenID) Text(base int) string

String returns a string representation of id in the given base.

func (*TokenID) Uint256

func (id *TokenID) Uint256() *uint256.Int

Uint256 returns id as a uint256.Int.

Jump to

Keyboard shortcuts

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