web3protocol

package module
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Feb 15, 2024 License: MIT Imports: 28 Imported by: 1

README

web3protocol-go

Parse and execute ERC-6860 / ERC-4804 web3:// protocol URLs.

Usage

import "github.com/web3-protocol/web3protocol-go"

config := web3protocol.Config{ ... } // Fill with the example in the configuration section
client := NewClient(&config)

fetchedWeb3Url, err := client.FetchUrl("web3://terraformnavigator.eth/view/1234")

fmt.Println("HTTP return code:", fetchedWeb3Url.HttpCode)
fmt.Printf("HTTP return headers: %+v\n", fetchedWeb3Url.HttpHeaders)

output, err := ioutil.ReadAll(fetchedWeb3Url.Output)
fmt.Println("Output bytes", output)

On top of the result, fetchedWeb3Url contains a lot more details on the processing of the call.

Configuration

Right now, by default, this does not come with chains and domain name definitions; they will need to be provided. Here is an example for a basic Ethereum mainnet + ENS config, using the publicnode.com RPCs :

config := Config {
    Chains: map[int]ChainConfig{
        1: ChainConfig{
            ChainId: 1,
            ShortName: "eth",
            RPC: "https://ethereum.publicnode.com/",
            DomainNameServices: map[DomainNameService]DomainNameServiceChainConfig{
                DomainNameServiceENS: DomainNameServiceChainConfig{
                    Id: DomainNameServiceENS,
                    ResolverAddress: common.HexToAddress("0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"),
                },
            },
        },
    },
    DomainNameServices: map[DomainNameService]DomainNameServiceConfig{
        DomainNameServiceENS: DomainNameServiceConfig{
            Id: DomainNameServiceENS,
            Suffix: "eth",
            DefaultChainId: 1,
        },
    },
}

Supported standards

Implemented features
  • ERC-6860 (draft) : the base web3:// protocol with auto and manual mode, basic ENS support. This updates ERC-4804 (final) with clarifications, small fixes and changes.
  • ERC-6821 (draft) : ENS resolution : support for the contentcontract TXT field to point to a contract in another chain
  • ERC-6944 (draft) / ERC-5219 (final) : New mode offloading some parsing processing on the browser side
  • ERC-7617 (pending): Add chunk support in ERC-6944 resource request mode
  • ERC-7618 (pending): Add Content-encoding handling in ERC-6944 resource request mode
Partially implemented features
  • ERC-7087 (draft) : Auto mode : Add MIME type support (dataURLs not supported yet)

Testing

Web3:// test files are located in their own git repository and are imported as a git submodule. After cloning, please run git submodule init and then git submodule update.

Testing is then launched with go test

Documentation

Index

Constants

View Source
const (
	DomainNameServiceENS  = "ens"
	DomainNameServiceW3NS = "w3ns"
)
View Source
const (
	ResolveModeAuto             = "auto"
	ResolveModeManual           = "manual"
	ResolveModeResourceRequests = "resourceRequest"
)
View Source
const (
	ContractCallModeCalldata = "calldata"
	ContractCallModeMethod   = "method"
)
View Source
const (
	// Expect the whole returned data to be ABI-encoded bytes. Decode.
	ContractReturnProcessingDecodeABIEncodedBytes = "decodeABIEncodedBytes"
	// JSON-encode the raw bytes of the returned data
	ContractReturnProcessingRawBytesJsonEncoded = "jsonEncodeRawBytes"
	// JSON-encode the different return values
	ContractReturnProcessingJsonEncodeValues = "jsonEncodeValues"
	// Expect a string as first return value, parse it as a dataUrl
	// ContractReturnProcessingDataUrl = "dataUrl" // To implement
	// Expect a return following the erc5219 spec, will decode it using this spec
	ContractReturnProcessingDecodeErc5219Request = "decodeErc5219Request"
)

Variables

View Source
var (
	EmptyString  = strings.Repeat("0", 62) + "20" + strings.Repeat("0", 64)
	EmptyAddress = strings.Repeat("0", 64)
)

Functions

func JsonEncodeAbiTypeValue

func JsonEncodeAbiTypeValue(arg abi.Type, value interface{}) (result interface{}, err error)

Used for auto mode returning JSON : For a given ABI type and a value, convert it to a string, with the data formatted according to the spec

func LabelHash

func LabelHash(label string) (hash [32]byte, err error)

LabelHash generates a simple hash for a piece of a name.

func NameHash

func NameHash(name string) (hash [32]byte, err error)

NameHash generates a hash from a name that can be used to look up the name in ENS

func Normalize

func Normalize(input string) (output string, err error)

Normalize normalizes a name according to the ENS rules

Types

type ArgInfo

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

type ChainConfig

type ChainConfig struct {
	ChainId int

	// A mapping of chain "short name" (from https://github.com/ethereum-lists/chains) to their chain id
	// Used by ERC-6821 which relies on ERC-3770 addresses
	ShortName string

	// The RPC URL to use to call the chain
	RPC string

	// A chain-specific config per domain name service. Key is their short name.
	DomainNameServices map[DomainNameService]DomainNameServiceChainConfig
}

type Client

type Client struct {
	Config                    *Config
	DomainNameResolutionCache *localCache
}

func NewClient

func NewClient(config *Config) (client *Client)

*

  • You'll need to instantiate a client to make calls.

func (*Client) FetchContractReturn

func (client *Client) FetchContractReturn(web3Url *Web3URL) (contractReturn []byte, err error)

*

  • Step 2: Make the call to the main contract.

func (*Client) FetchUrl

func (client *Client) FetchUrl(url string) (fetchedUrl FetchedWeb3URL, err error)

*

  • The main function of the package.
  • For a given full web3:// url ("web3://xxxx"), returns a structure containing
  • the bytes output and the HTTP code and headers, as well as plenty of informations on
  • how the processing was done.

func (*Client) ParseUrl

func (client *Client) ParseUrl(url string) (web3Url Web3URL, err error)

*

  • Step 1 : Parse the URL and determine how we are going to call the main contract.

func (*Client) ProcessContractReturn

func (client *Client) ProcessContractReturn(web3Url *Web3URL, contractReturn []byte) (fetchedWeb3Url FetchedWeb3URL, err error)

*

  • Step 3 : Process the data returned by the main contract.

func (*Client) ProcessResourceRequestContractReturn

func (client *Client) ProcessResourceRequestContractReturn(fetchedWeb3Url *FetchedWeb3URL, web3Url *Web3URL, contractReturn []byte) (err error)

Step 3 : We have the contract return, process it

type Config

type Config struct {
	// A config per chain. Key is the chain id
	Chains map[int]ChainConfig

	// A config per domain name service. Key is their short name
	DomainNameServices map[DomainNameService]DomainNameServiceConfig

	// There is an internal domain name resolution cache
	NameAddrCacheDurationInMinutes int
}

The config used by the client to make the web3:// calls

func (*Config) GetChainIdByShortName

func (config *Config) GetChainIdByShortName(shortName string) (result int)

func (*Config) GetDomainNameServiceBySuffix

func (config *Config) GetDomainNameServiceBySuffix(suffix string) (result DomainNameService)

type ContractCallMode

type ContractCallMode string

type ContractReturnProcessing

type ContractReturnProcessing string

type DomainNameService

type DomainNameService string

type DomainNameServiceChainConfig

type DomainNameServiceChainConfig struct {
	Id DomainNameService

	// The URL to the contract of the resolver
	ResolverAddress common.Address
}

Attributes of a domain name service specific to a chain

type DomainNameServiceConfig

type DomainNameServiceConfig struct {
	Id DomainNameService

	// "eth", ...
	Suffix string

	// The default home chain of a domain name service; e.g. 1 for ENS, 333 for W3NS
	DefaultChainId int
}

Attributes of a domain name service

type ErrorWithHttpCode

type ErrorWithHttpCode struct {
	HttpCode int
	Err      string
}

An error type with a HTTP code

func (*ErrorWithHttpCode) Error

func (e *ErrorWithHttpCode) Error() string

type FetchedWeb3URL

type FetchedWeb3URL struct {
	// The web3 URL, parsed
	ParsedUrl *Web3URL

	// The raw data returned by the contract
	ContractReturn []byte

	// The processed output, to be returned by the browser
	Output io.Reader
	// The HTTP code to be returned by the browser
	HttpCode int
	// The HTTP headers to be returned by the browser
	HttpHeaders map[string]string
}

This contains the result of a web3:// URL call : the parsed URL, the raw contract return, and the bytes output, HTTP code and headers for the browser.

type PrefixDecompressionErrorReader added in v0.2.3

type PrefixDecompressionErrorReader struct {
	Reader io.Reader
}

func (*PrefixDecompressionErrorReader) Read added in v0.2.3

func (r *PrefixDecompressionErrorReader) Read(p []byte) (readBytes int, err error)

type QueryParameter

type QueryParameter struct {
	Name  string
	Value string
}

URL.parseQuery does not preserve the order of query attributes This is a version which keep order

type QueryParameters

type QueryParameters []QueryParameter

func ParseQuery

func ParseQuery(query string) (params QueryParameters, err error)

type ResolveMode

type ResolveMode string

type ResourceRequestReader added in v0.2.0

type ResourceRequestReader struct {
	Client         *Client
	FetchedWeb3URL *FetchedWeb3URL
	// Content of the last chunk call
	Chunk        []byte
	Cursor       int
	NextChunkUrl string
}

func (*ResourceRequestReader) Read added in v0.2.0

func (rrr *ResourceRequestReader) Read(p []byte) (readBytes int, err error)

Return the result of the method call Implements ERC-7617: Support for chunking

type Web3URL

type Web3URL struct {
	// The actual url string "web3://...."
	Url string

	// If the host was a domain name, what domain name service was used?
	HostDomainNameResolver DomainNameService
	// Chain of the name resolution service
	HostDomainNameResolverChainId int

	// The contract address (after optional domain name resolution) that is going to be called,
	// and its chain location
	ContractAddress common.Address // actual address
	ChainId         int

	// The ERC-4804 resolve mode
	ResolveMode ResolveMode

	// How do we call the smartcontract
	// 'calldata' : We use a raw calldata
	// 'method': We use the specified method and method parameters
	ContractCallMode ContractCallMode
	// Attributes for ContractCallModeCalldata
	Calldata []byte
	// Attributes for ContractCallModeMethod
	MethodName      string
	MethodArgs      []abi.Type
	MethodArgValues []interface{}

	// How to process the return of the contract. See enum for doc
	ContractReturnProcessing ContractReturnProcessing
	// In case of contractReturnProcessing being decodeABIEncodedBytes,
	// this will set the mime type to return
	DecodedABIEncodedBytesMimeType string
	// In case of ContractReturnProcessing being jsonEncodeValues,
	// this will tell us how to ABI-decode the returned data
	JsonEncodedValueTypes []abi.Type
}

This contains a web3:// URL parsed and ready to call the main smartcontract

func (*Web3URL) ComputeCalldata

func (web3Url *Web3URL) ComputeCalldata() (calldata []byte, err error)

If ContractCallMode is calldata, returned the stored calldata If ContractCallMode is method, compute and return it

Jump to

Keyboard shortcuts

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