Documentation
¶
Overview ¶
Package willow — client-side completeness verification.
Mirrors Willow's on-chain completeness anchor so a client can verify that an indexer's served event set for a (subgrove, block) is the complete, untampered filter-matched set the anchor binds — without trusting the indexer. The on-chain events_commitment (a 32-byte keccak hash) is the anchor; the indexer serves the matched-log preimage; the client re-hashes it via CanonicalEventSetHash and compares. VerifyServedEvents trusts the commitment it is given; VerifyBlockCompleteness reads it from an RPC node, which it trusts for it.
Canonical Rust source: willow-network consensus indexed_data_handler::full_block_auth::canonical_event_set_hash.
This file holds the pure, network-free hashing spec (CanonicalEventSetHash / VerifyServedEvents). The end-to-end fetch-and-verify convenience wrapper — VerifyBlockCompleteness, which pulls the on-chain anchor and the indexer's matched-log preimage and calls VerifyServedEvents — lives in completeness_fetch.go so this file stays dependency-free for cross-language vector comparison.
Package willow provides a Go SDK for interacting with the Willow network.
Computed Fields Module ¶
This module provides SDK-layer computation of derived fields from the values a query returns. It enables drop-in compatibility with The Graph's query interfaces by computing derived values (like price ratios) from base data.
Design Philosophy:
- Division and other derived calculations are done client-side
- A derived value is exactly as trustworthy as the values it is computed from; the SDK returns query results unverified
- Same API: queries return the same fields The Graph would return
Package willow — Ethereum state reads served by an indexer.
Counterpart to the indexer's POST /verifiable-rpc/eth/state and /verifiable-rpc/eth/call routes. Walks EIP-1186 MPT proofs locally and exposes a storage-layout helper (ERC-20 balance).
The SDK doesn't verify these reads against Ethereum (see EthOperations).
Package willow — canonical WillowManifest builder.
Mirrors willow_types::consensus::manifest::WillowManifest in the Rust workspace. The consensus validator rejects any manifest_content that doesn't decode into this exact shape, so SDK callers should build their on-chain manifest bytes via SerializeManifest. Each data source is either EVM (Address + Abi + StartBlock + Events) or Solana (ProgramID + StartSlot + Instructions); the family is dispatched at parse time from the Network field.
Package willow provides a Go SDK for interacting with the Willow network.
Index ¶
- Constants
- Variables
- func ApplyComputedFields(record map[string]interface{}, fields ComputedFieldSet) map[string]interface{}
- func BoolPtr(b bool) *bool
- func CanonicalEventSetHash(blockNumber uint64, matchedLogs []Log) [32]byte
- func DecryptFile(ciphertext []byte, key [32]byte, nonce [24]byte) ([]byte, error)
- func EncryptFile(data []byte, key [32]byte) (ciphertext []byte, nonce [24]byte, err error)
- func EvmChainID(chain SupportedChain) (uint64, bool)
- func FormatDataStoreMessage(subgroveID, key, ownerDID string, data []byte, nonce uint64) (string, error)
- func FormatDeleteFileManifestMessage(subgroveID, fileKey, ownerDID string, nonce uint64) (string, error)
- func FormatGrantSubgroveKeyMessage(subgroveID, senderDID string, grant EncryptedKeyGrant, nonce uint64) (string, error)
- func FormatRegisterSubgroveMessage(tx *consensus.RegisterSubgroveTx) (string, error)
- func FormatRotateSubgroveKeyMessage(subgroveID, senderDID string, newEpoch uint32, grants []EncryptedKeyGrant, ...) (string, error)
- func FormatStoreFileManifestMessage(f FileManifestFields) (string, error)
- func FormatTransferMessage(req *TransferRequest, nonce uint64) string
- func FormatUnregisterStorageNodeMessage(nodeDID string, nonce uint64) (string, error)
- func GenerateDID(keyPair *KeyPair) string
- func IsHTTPError(err error) (int, bool)
- func IsNotAuthenticated(err error) bool
- func IsNotFound(err error) bool
- func IsSupportedChain(s string) bool
- func IsUnsupported(err error) bool
- func IsValidationError(err error) bool
- func LegacyRequestMessage(method, path, timestamp string) string
- func NewRequestNonce() (string, error)
- func SerializeManifest(m *WillowManifest) ([]byte, error)
- func SignedRequestMessage(did, publicKeyID, method, pathAndQuery, timestamp, nonce string, body []byte) string
- func ValidateManifest(m *WillowManifest) error
- func Verify(algorithm SignatureAlgorithm, publicKey, message, signature []byte) (bool, error)
- func VerifyServedEvents(commitment [32]byte, blockNumber uint64, matchedLogs []Log) bool
- type AccountNonceState
- type ApiResponse
- type BalanceInfo
- type BatchStoreRequest
- type ChainFamily
- type CheckpointInfo
- type ChunkUploadError
- type Client
- func (c *Client) Close() error
- func (c *Client) FetchEventsCommitment(ctx context.Context, subgroveID string, blockNumber uint64) ([32]byte, error)
- func (c *Client) FetchMatchedLogs(ctx context.Context, subgroveID string, blockNumber uint64) ([]Log, error)
- func (c *Client) GetAccountNonce(ctx context.Context, did string) (*AccountNonceState, error)
- func (c *Client) GetComputedFields(datasetID string) (ComputedFieldSet, bool)
- func (c *Client) GetDID(ctx context.Context, did string) (*DidInfo, error)
- func (c *Client) GetIdentity() *Identity
- func (c *Client) GetLatestAppHash(ctx context.Context) (string, error)
- func (c *Client) GetOrCreateLightClient(ctx context.Context) (*lightclient.LightClient, error)
- func (c *Client) GetRootHash(ctx context.Context) (string, error)
- func (c *Client) GetVerifiedRootHash(ctx context.Context) (string, error)deprecated
- func (c *Client) HasComputedFields(datasetID string) bool
- func (c *Client) HasIdentity() bool
- func (c *Client) HasLightClient() bool
- func (c *Client) Health(ctx context.Context) (*HealthStatus, error)
- func (c *Client) IndexerBaseURL() string
- func (c *Client) LightClient() *lightclient.LightClient
- func (c *Client) NextNonce(ctx context.Context, did string) (uint64, error)
- func (c *Client) RPCEndpoint() string
- func (c *Client) RegisterComputedFields(datasetID string, fields ComputedFieldSet)
- func (c *Client) RegisterDID(ctx context.Context, didDocument *DidDocument) (*DidDocument, error)deprecated
- func (c *Client) RequireAuth() error
- func (c *Client) SetIdentity(identity *Identity)
- func (c *Client) VerifyBlockCompleteness(ctx context.Context, subgroveID string, blockNumber uint64) (bool, error)
- func (c *Client) WaitUntilLanded(ctx context.Context, did string, nonce uint64) error
- type ClientBuilder
- func (b *ClientBuilder) Build() (*Client, error)
- func (b *ClientBuilder) WithAPIKey(key string) *ClientBuilder
- func (b *ClientBuilder) WithHTTPClient(httpClient *http.Client) *ClientBuilder
- func (b *ClientBuilder) WithIndexerURL(indexerURL string) *ClientBuilder
- func (b *ClientBuilder) WithLightClient(lc *lightclient.LightClient) *ClientBuilder
- func (b *ClientBuilder) WithRPCURL(rpcURL string) *ClientBuilder
- func (b *ClientBuilder) WithRetryConfig(config RetryConfig) *ClientBuilder
- func (b *ClientBuilder) WithTimeout(timeout time.Duration) *ClientBuilder
- type ClientOption
- func WithAPIKey(key string) ClientOption
- func WithHTTPClient(httpClient *http.Client) ClientOption
- func WithIndexerURL(indexerURL string) ClientOption
- func WithLightClient(lc *lightclient.LightClient) ClientOption
- func WithRPCURL(rpcURL string) ClientOption
- func WithRetryConfig(config RetryConfig) ClientOption
- func WithTimeout(timeout time.Duration) ClientOption
- type CommitmentFrequency
- type ComputeFunction
- type ComputedFieldDefinition
- type ComputedFieldRegistry
- func (r *ComputedFieldRegistry) Clear()
- func (r *ComputedFieldRegistry) Get(datasetID string) (ComputedFieldSet, bool)
- func (r *ComputedFieldRegistry) Has(datasetID string) bool
- func (r *ComputedFieldRegistry) Register(datasetID string, fields ComputedFieldSet)
- func (r *ComputedFieldRegistry) Unregister(datasetID string) bool
- type ComputedFieldSet
- type DataOperations
- func (d *DataOperations) BatchStore(ctx context.Context, subgroveID string, items []StoreRequest) errordeprecated
- func (d *DataOperations) Delete(ctx context.Context, subgroveID, key string) errordeprecated
- func (d *DataOperations) Get(ctx context.Context, subgroveID, key string) (*DataResponse, error)
- func (d *DataOperations) GetCheckpointStateRoot(ctx context.Context, subgroveID, checkpointID string) (*CheckpointInfo, error)
- func (d *DataOperations) GetProof(ctx context.Context, subgroveID, key string) (*DataProof, error)
- func (d *DataOperations) GetUnverified(ctx context.Context, subgroveID, key string) (*DataResponse, error)
- func (d *DataOperations) Query(ctx context.Context, subgroveID string, query *QueryRequest) (*QueryResponse, error)deprecated
- func (d *DataOperations) QueryHistorical(ctx context.Context, subgroveID, checkpointID string, ...) (*HistoricalQueryResponse, error)
- func (d *DataOperations) QueryHistoricalVerified(ctx context.Context, subgroveID, checkpointID string, ...) (*HistoricalQueryResponse, error)deprecated
- func (d *DataOperations) QueryUnverified(ctx context.Context, subgroveID string, query *QueryRequest) (*QueryResponse, error)
- func (d *DataOperations) Store(ctx context.Context, subgroveID string, data map[string]interface{}) errordeprecated
- func (d *DataOperations) StoreItem(ctx context.Context, subgroveID, key string, data map[string]interface{}, ...) (*WriteResult, error)
- func (d *DataOperations) Update(ctx context.Context, subgroveID, key string, data map[string]interface{}) errordeprecated
- func (d *DataOperations) VerifyProof(ctx context.Context, proof *DataProof) errordeprecated
- type DataProof
- type DataResponse
- type DataSource
- type DevnetTestAccount
- type DidDocument
- type DidInfo
- type EncryptedKeyGrant
- type ErrorType
- type EthCallResult
- type EthOperations
- func (e *EthOperations) Erc20Balance(ctx context.Context, token, holder string, balanceSlot byte, ...) (*big.Int, error)
- func (e *EthOperations) GetCall(ctx context.Context, tx map[string]interface{}, blockNumber uint64) (*EthCallResult, error)
- func (e *EthOperations) GetState(ctx context.Context, address string, slots []string, blockNumber uint64) (*EthStateRead, error)
- type EthProofMode
- type EthStateRead
- type EthStorageSlot
- type EthereumAnchor
- type EvmDataSource
- type FeeSchedule
- type FileEncryption
- type FileListResponse
- type FileManifest
- type FileManifestFields
- type FileOperations
- func (f *FileOperations) Delete(subgroveID, fileKey string, signing *FileSigningOptions) error
- func (f *FileOperations) DeleteContext(ctx context.Context, subgroveID, fileKey string, signing *FileSigningOptions) error
- func (f *FileOperations) Download(subgroveID, fileKey, storageNodeEndpoint string) ([]byte, error)
- func (f *FileOperations) DownloadContext(ctx context.Context, subgroveID, fileKey, storageNodeEndpoint string) ([]byte, error)
- func (f *FileOperations) List(subgroveID string) ([]FileManifest, error)
- func (f *FileOperations) ListContext(ctx context.Context, subgroveID string) ([]FileManifest, error)
- func (f *FileOperations) Metadata(subgroveID, fileKey string) (*FileManifest, error)
- func (f *FileOperations) MetadataContext(ctx context.Context, subgroveID, fileKey string) (*FileManifest, error)
- func (f *FileOperations) UnregisterStorageNode(nodeDID string, signing *FileSigningOptions) error
- func (f *FileOperations) UnregisterStorageNodeContext(ctx context.Context, nodeDID string, signing *FileSigningOptions) error
- func (f *FileOperations) Upload(subgroveID, fileKey, filename string, data []byte, storageNodeEndpoint string, ...) (*FileManifest, error)
- func (f *FileOperations) UploadContext(ctx context.Context, subgroveID, fileKey, filename string, data []byte, ...) (*FileManifest, error)
- type FileSigningOptions
- type GraphQLError
- type GraphQLLocation
- type GraphQLQueryBuilder
- func (b *GraphQLQueryBuilder) Build() *GraphQLRequest
- func (b *GraphQLQueryBuilder) IncludeProof() *GraphQLQueryBuilder
- func (b *GraphQLQueryBuilder) OperationName(name string) *GraphQLQueryBuilder
- func (b *GraphQLQueryBuilder) Variable(name string, value interface{}) *GraphQLQueryBuilder
- func (b *GraphQLQueryBuilder) Variables(vars map[string]interface{}) *GraphQLQueryBuilder
- type GraphQLRequest
- type GraphQLResponse
- type HTTPError
- type HealthStatus
- type HistoricalQueryRequest
- type HistoricalQueryResponse
- type Identity
- func (i *Identity) DID() string
- func (i *Identity) PublicKeyID() string
- func (i *Identity) Sign(message []byte) ([]byte, error)
- func (i *Identity) SignHex(message []byte) (string, error)
- func (i *Identity) SignRequest(method, path string) (map[string]string, error)
- func (i *Identity) SignRequestWithNonce(method, pathAndQuery string, body []byte) (map[string]string, error)
- type IndexDefinition
- type IndexType
- type IndexerInfo
- type Indexers
- type IndexingOperations
- func (i *IndexingOperations) Execute(ctx context.Context, subgroveID, query string, ...) (*GraphQLResponse, error)
- func (i *IndexingOperations) ExecuteWithResult(ctx context.Context, subgroveID, query string, ...) error
- func (i *IndexingOperations) GetIndexer(ctx context.Context, indexerID string) (*IndexerInfo, error)
- func (i *IndexingOperations) GetIndexerStatus(ctx context.Context, indexerID, subgroveID string) (*IndexerInfo, error)deprecated
- func (i *IndexingOperations) GetSubgrove(ctx context.Context, subgroveID string) (*SubgroveInfo, error)
- func (i *IndexingOperations) GraphQLQueryWithSource(ctx context.Context, subgroveID string, req *GraphQLRequest, ...) (*RoutedQueryResult[*GraphQLResponse], error)
- func (i *IndexingOperations) ListIndexers(ctx context.Context) ([]IndexerInfo, error)
- func (i *IndexingOperations) ListSubgroves(ctx context.Context) ([]SubgroveInfo, error)
- func (i *IndexingOperations) Query(ctx context.Context, subgroveID string, req *GraphQLRequest) (*GraphQLResponse, error)deprecated
- func (i *IndexingOperations) QueryUnverified(ctx context.Context, subgroveID string, req *GraphQLRequest) (*GraphQLResponse, error)
- func (i *IndexingOperations) SqlQuery(ctx context.Context, subgroveID, query string, includeProof bool) (*SqlResponse, error)
- func (i *IndexingOperations) SqlQueryWithSource(ctx context.Context, subgroveID, query string, includeProof bool, ...) (*RoutedQueryResult[*SqlResponse], error)
- type InsufficientFundsError
- type KeyPair
- type Log
- type ManifestValidationError
- type MerkleProofData
- type NoIndexersReachableError
- type Permission
- type PrivacyConfig
- type PrivacyOperations
- func (p *PrivacyOperations) GetKeyGrantProof(ctx context.Context, subgroveID, did string) (json.RawMessage, error)
- func (p *PrivacyOperations) GetMyKeyGrant(ctx context.Context, subgroveID string) (*EncryptedKeyGrant, error)
- func (p *PrivacyOperations) GrantSubgroveKey(ctx context.Context, subgroveID string, grant EncryptedKeyGrant, ...) (*WriteResult, error)
- func (p *PrivacyOperations) ListKeyGrantees(ctx context.Context, subgroveID string) ([]string, error)
- func (p *PrivacyOperations) RevokeSubgroveKey(ctx context.Context, subgroveID, revokeeDID string, opts ...WriteOption) (*WriteResult, error)
- func (p *PrivacyOperations) RotateSubgroveKey(ctx context.Context, subgroveID string, newEpoch uint32, ...) (*WriteResult, error)
- type PublicKey
- type QueryBuilder
- func (qb *QueryBuilder) Build() *QueryRequest
- func (qb *QueryBuilder) Contains(field string, value interface{}) *QueryBuilder
- func (qb *QueryBuilder) Equals(field string, value interface{}) *QueryBuilder
- func (qb *QueryBuilder) Filter(field, operator string, value interface{}) *QueryBuilder
- func (qb *QueryBuilder) GreaterThan(field string, value interface{}) *QueryBuilder
- func (qb *QueryBuilder) GreaterThanOrEqual(field string, value interface{}) *QueryBuilder
- func (qb *QueryBuilder) In(field string, values []interface{}) *QueryBuilder
- func (qb *QueryBuilder) IncludeProof() *QueryBuilder
- func (qb *QueryBuilder) LessThan(field string, value interface{}) *QueryBuilder
- func (qb *QueryBuilder) LessThanOrEqual(field string, value interface{}) *QueryBuilder
- func (qb *QueryBuilder) Limit(limit int) *QueryBuilder
- func (qb *QueryBuilder) NotEquals(field string, value interface{}) *QueryBuilder
- func (qb *QueryBuilder) Offset(offset int) *QueryBuilder
- func (qb *QueryBuilder) Search(fields []string, query string) *QueryBuilder
- func (qb *QueryBuilder) SortAsc(field string) *QueryBuilder
- func (qb *QueryBuilder) SortDesc(field string) *QueryBuilder
- type QueryFilter
- type QueryProof
- type QueryRequest
- type QueryResponse
- type QueryResult
- type QuerySearch
- type QuerySort
- type QuerySource
- type RegisterSubgroveRequest
- type RegistrationOperations
- func (r *RegistrationOperations) DeleteSubgrove(ctx context.Context, subgroveID string, opts ...WriteOption) (*WriteResult, error)
- func (r *RegistrationOperations) GetPermissions(ctx context.Context, did string) ([]Permission, error)
- func (r *RegistrationOperations) GetSubgrove(ctx context.Context, subgroveID string) (*SubgroveRegistration, error)
- func (r *RegistrationOperations) GrantPermission(ctx context.Context, permission *Permission) errordeprecated
- func (r *RegistrationOperations) ListSubgroves(ctx context.Context) ([]SubgroveRegistration, error)
- func (r *RegistrationOperations) RegisterSubgrove(ctx context.Context, req *RegisterSubgroveRequest, opts ...WriteOption) (*WriteResult, error)
- func (r *RegistrationOperations) RevokePermission(ctx context.Context, did, subgroveID string) errordeprecated
- func (r *RegistrationOperations) UpdateSubgrove(ctx context.Context, subgroveID string, updates map[string]interface{}) (*SubgroveRegistration, error)deprecated
- type RetryConfig
- type RoutedQueryResult
- type SchemaBuilder
- func (b *SchemaBuilder) ArrayField(name string, itemType string, required bool) *SchemaBuilder
- func (b *SchemaBuilder) BoolField(name string, required bool) *SchemaBuilder
- func (b *SchemaBuilder) Build() *SchemaDefinition
- func (b *SchemaBuilder) Description(desc string) *SchemaBuilder
- func (b *SchemaBuilder) Field(name, fieldType string, required, indexed bool) *SchemaBuilder
- func (b *SchemaBuilder) FloatField(name string, required bool) *SchemaBuilder
- func (b *SchemaBuilder) FullTextIndex(name string, fields []string) *SchemaBuilder
- func (b *SchemaBuilder) HashIndex(name string, fields []string) *SchemaBuilder
- func (b *SchemaBuilder) Index(name string, fields []string, indexType IndexType, unique bool) *SchemaBuilder
- func (b *SchemaBuilder) IntField(name string, required bool) *SchemaBuilder
- func (b *SchemaBuilder) ObjectField(name string, required bool) *SchemaBuilder
- func (b *SchemaBuilder) RangeIndex(name string, fields []string) *SchemaBuilder
- func (b *SchemaBuilder) StringField(name string, required bool) *SchemaBuilder
- func (b *SchemaBuilder) UniqueIndex(name string, fields []string) *SchemaBuilder
- type SchemaDefinition
- type SchemaField
- type ServedBy
- type SignatureAlgorithm
- type SolanaDataSource
- type SqlRequest
- type SqlResponse
- type StateVerifyModedeprecated
- type StoreRequest
- type SubgroveBuilder
- func (b *SubgroveBuilder) AddReader(did string) *SubgroveBuilder
- func (b *SubgroveBuilder) AddWriter(did string) *SubgroveBuilder
- func (b *SubgroveBuilder) Build() *RegisterSubgroveRequest
- func (b *SubgroveBuilder) Description(desc string) *SubgroveBuilder
- func (b *SubgroveBuilder) Owner(did string) *SubgroveBuilder
- func (b *SubgroveBuilder) Readers(dids []string) *SubgroveBuilder
- func (b *SubgroveBuilder) RewardRate(rate uint64) *SubgroveBuilder
- func (b *SubgroveBuilder) Schema(schema SchemaDefinition) *SubgroveBuilder
- func (b *SubgroveBuilder) Writers(dids []string) *SubgroveBuilder
- type SubgroveInfo
- type SubgroveRegistration
- type SubscribeOptions
- type SubscribeSource
- type Subscription
- type SubscriptionPayload
- type Subscriptions
- type SupportedChain
- type TokenInfo
- type TokenOperations
- func (t *TokenOperations) EstimateQueryFee(ctx context.Context) (string, error)
- func (t *TokenOperations) EstimateStorageFee(ctx context.Context, dataSizeBytes uint64) (string, error)
- func (t *TokenOperations) GetBalance(ctx context.Context, did string) (*BalanceInfo, error)
- func (t *TokenOperations) GetFeeSchedule(ctx context.Context) (*FeeSchedule, error)
- func (t *TokenOperations) GetInfo(ctx context.Context) (*TokenInfo, error)
- func (t *TokenOperations) GetMyBalance(ctx context.Context) (*BalanceInfo, error)
- type TransactionError
- type TransferRequest
- type ValidatorHasNoDataError
- type ValidatorInfo
- type ValidatorOperations
- func (v *ValidatorOperations) Get(ctx context.Context, did string) (*ValidatorInfo, error)
- func (v *ValidatorOperations) GetActive(ctx context.Context) ([]ValidatorInfo, error)
- func (v *ValidatorOperations) GetTotalStake(ctx context.Context) (consensus.Uint128, error)
- func (v *ValidatorOperations) List(ctx context.Context) ([]ValidatorInfo, error)
- type ValidatorStatus
- type VerifiedCalldeprecated
- type VerifiedStateReaddeprecated
- type VerifiedStoragedeprecated
- type WillowError
- func NewAPIError(message string) *WillowError
- func NewAuthenticationError(message string) *WillowError
- func NewConfigError(message string) *WillowError
- func NewConsensusError(message string, cause error) *WillowError
- func NewCryptoError(message string, cause error) *WillowError
- func NewLightClientError(message string, cause error) *WillowError
- func NewNetworkError(message string, cause error) *WillowError
- func NewNotFoundError(resource string) *WillowError
- func NewPermissionDeniedError(message string) *WillowError
- func NewProofError(message string) *WillowError
- func NewSerializationError(message string, cause error) *WillowError
- func NewUnsupportedError(message string) *WillowError
- func NewValidationError(message string) *WillowError
- type WillowManifest
- type WriteError
- type WriteOption
- type WriteResult
Constants ¶
const ( // Deprecated: use EthWalkProofs, which walks the proofs against the // answer's own state root; the SDK doesn't verify that root. StateVerifyModeStrict = EthWalkProofs // Deprecated: use EthSkipProofs; no root is anchored to anything trusted. StateVerifyModeAnchorOnly = EthSkipProofs // Deprecated: use EthSkipProofs, which it acts as: no proof is walked. It // keeps its own value, 2, so a switch over the three older modes still // compiles. StateVerifyModeDisabled EthProofMode = 2 )
const ( MaxDataSources = 64 MaxEventsPerSource = 32 MaxNameLen = 64 MaxAbiLen = 64 MaxDescriptionLen = 1024 )
Mirrors MAX_* constants in willow-types.
const ( // NonceWindow is how many nonces above the account nonce the chain // accepts. NonceWindow = 24 // NonceHold is how long a nonce handed out and not seen to land stays // taken once no submission under it is in flight. The node holds a // pending transaction's nonce for 3 blocks or 120 s, whichever ends // first, so 120 s is the conservative bound. NonceHold = 120 * time.Second )
const DefaultCacheTTL = 30 * time.Second
DefaultCacheTTL is how long a successful /indexers response is reused before the SDK re-fetches.
const DefaultChunkSize = 262144 // 256 KB
const ManifestSpecVersion = "1.0.0"
ManifestSpecVersion is the schema version pinned by consensus.
Variables ¶
var ( // ErrNotAuthenticated is returned when an operation requires authentication but no identity is set. ErrNotAuthenticated = errors.New("not authenticated: please call SetIdentity() first") // ErrInvalidSignature is returned when signature verification fails. ErrInvalidSignature = errors.New("invalid signature") // ErrProofVerificationFailed is returned when proof verification fails. ErrProofVerificationFailed = errors.New("proof verification failed") // ErrLightClientNotInitialized is returned when light client operations are attempted without initialization. ErrLightClientNotInitialized = errors.New("light client not initialized") // ErrAnswerTooLarge is the cause of the error for an HTTP answer the SDK // refuses for its size (errors.Is(err, ErrAnswerTooLarge)): longer than // its route's limit, or holding more JSON than the SDK decodes. The // consensus, lightclient, and erc8004 packages' errors match it too. // Ask for less where the request sets an answer's size. ErrAnswerTooLarge = httpbody.ErrTooLarge )
Error types for the Willow SDK.
var DEVNET_TEST_ACCOUNT = DevnetTestAccount{
DID: "did:willow:devnet-test",
PrivateKey: "b5ecc03536f5e039e3c5bc46ad178d7faf80cee5f063016a4f4084e163409b3c",
PublicKey: "c153874d3d284a11e3cb12b524e1a9cc32fef966d56b903c79688a95d5193c8f",
PublicKeyID: "did:willow:devnet-test#key-1",
}
DEVNET_TEST_ACCOUNT is the pre-funded test account for local devnet development. This account has 10,000 WILL tokens pre-allocated in the genesis.
WARNING: Do not use this account in production!
var ErrNonceUsed = errors.New("nonce already used")
ErrNonceUsed is the cause of a *WriteError for a write refused because its nonce is used (errors.Is(err, ErrNonceUsed)): the chain showed it used, so the write wasn't sent (WithNonce), or the answer to its submission said it is already used or at or below the base. The transaction that used the nonce may be this write: an earlier attempt of it, or this attempt itself, which an API can forward to the chain while answering that it was refused. If it is, it landed and was applied or refused in its block. So the SDK never signs the write again under another nonce on its own: read what the write wrote before sending it again, without WithNonce, under a fresh nonce.
var ErrNonceWindowFull = errors.New("nonce window full")
ErrNonceWindowFull is the cause of the error a write returns when every nonce the chain accepts for its DID is used or held by a write in flight (errors.Is(err, ErrNonceWindowFull)). Wait for earlier writes to land (see Client.WaitUntilLanded) and send it again.
var GenericAMMPairFields = ComputedFieldSet{ { Name: "token0Price", Description: "Price of token0 in terms of token1", Dependencies: []string{"reserve0", "reserve1"}, Compute: func(record map[string]interface{}) interface{} { reserve0, ok0 := parseNumeric(record["reserve0"]) reserve1, ok1 := parseNumeric(record["reserve1"]) if !ok0 || !ok1 || reserve0 == 0 { return nil } return reserve1 / reserve0 }, }, { Name: "token1Price", Description: "Price of token1 in terms of token0", Dependencies: []string{"reserve0", "reserve1"}, Compute: func(record map[string]interface{}) interface{} { reserve0, ok0 := parseNumeric(record["reserve0"]) reserve1, ok1 := parseNumeric(record["reserve1"]) if !ok0 || !ok1 || reserve1 == 0 { return nil } return reserve0 / reserve1 }, }, }
GenericAMMPairFields provides generic AMM pair fields (works for Uniswap V2, Sushiswap, etc.).
var GlobalComputedFieldRegistry = NewComputedFieldRegistry()
GlobalComputedFieldRegistry is a global registry instance for convenience.
{ Name: "shareOfPool", Description: "User share of pool (userLPBalance / totalLPSupply)", Dependencies: []string{"userLPBalance", "totalLPSupply"}, Compute: func(record map[string]interface{}) interface{} { userBalance, ok0 := parseNumeric(record["userLPBalance"]) totalSupply, ok1 := parseNumeric(record["totalLPSupply"]) if !ok0 || !ok1 || totalSupply == 0 { return nil } return userBalance / totalSupply }, }, { Name: "userToken0Amount", Description: "User share of token0 (shareOfPool * reserve0)", Dependencies: []string{"userLPBalance", "totalLPSupply", "reserve0"}, Compute: func(record map[string]interface{}) interface{} { userBalance, ok0 := parseNumeric(record["userLPBalance"]) totalSupply, ok1 := parseNumeric(record["totalLPSupply"]) reserve0, ok2 := parseNumeric(record["reserve0"]) if !ok0 || !ok1 || !ok2 || totalSupply == 0 { return nil } return (userBalance / totalSupply) * reserve0 }, }, { Name: "userToken1Amount", Description: "User share of token1 (shareOfPool * reserve1)", Dependencies: []string{"userLPBalance", "totalLPSupply", "reserve1"}, Compute: func(record map[string]interface{}) interface{} { userBalance, ok0 := parseNumeric(record["userLPBalance"]) totalSupply, ok1 := parseNumeric(record["totalLPSupply"]) reserve1, ok2 := parseNumeric(record["reserve1"]) if !ok0 || !ok1 || !ok2 || totalSupply == 0 { return nil } return (userBalance / totalSupply) * reserve1 }, }, }
LPShareFields provides LP share computation fields.
var LendingProtocolFields = ComputedFieldSet{ { Name: "utilizationRate", Description: "Utilization rate (totalBorrows / totalSupply)", Dependencies: []string{"totalBorrows", "totalSupply"}, Compute: func(record map[string]interface{}) interface{} { borrows, ok0 := parseNumeric(record["totalBorrows"]) supply, ok1 := parseNumeric(record["totalSupply"]) if !ok0 || !ok1 || supply == 0 { return nil } return borrows / supply }, }, { Name: "availableLiquidity", Description: "Available liquidity (totalSupply - totalBorrows)", Dependencies: []string{"totalBorrows", "totalSupply"}, Compute: func(record map[string]interface{}) interface{} { borrows, ok0 := parseNumeric(record["totalBorrows"]) supply, ok1 := parseNumeric(record["totalSupply"]) if !ok0 || !ok1 { return nil } return supply - borrows }, }, }
LendingProtocolFields provides computed fields for lending protocols (Aave, Compound, etc.).
var SupportedChains = []SupportedChain{ ChainMainnet, ChainSepolia, ChainHolesky, ChainBsc, ChainOptimism, ChainArbitrumOne, ChainBase, ChainPolygon, ChainSolanaMainnet, }
SupportedChains is the canonical chain set. Adding a chain is a consensus change: bump willow-types first, then mirror here.
var UniswapV2AggregationFields = ComputedFieldSet{ { Name: "dailyVolumeUSD", Description: "Daily volume in USD (dailyVolumeETH * ethPriceUSD)", Dependencies: []string{"dailyVolumeETH", "ethPriceUSD"}, Compute: func(record map[string]interface{}) interface{} { volumeETH, ok0 := parseNumeric(record["dailyVolumeETH"]) ethPrice, ok1 := parseNumeric(record["ethPriceUSD"]) if !ok0 || !ok1 { return nil } return volumeETH * ethPrice }, }, { Name: "totalLiquidityUSD", Description: "Total liquidity in USD (totalLiquidityETH * ethPriceUSD)", Dependencies: []string{"totalLiquidityETH", "ethPriceUSD"}, Compute: func(record map[string]interface{}) interface{} { liquidityETH, ok0 := parseNumeric(record["totalLiquidityETH"]) ethPrice, ok1 := parseNumeric(record["ethPriceUSD"]) if !ok0 || !ok1 { return nil } return liquidityETH * ethPrice }, }, }
UniswapV2AggregationFields provides computed fields for Uniswap V2 daily/hourly data.
var UniswapV2PairFields = ComputedFieldSet{ { Name: "token0Price", Description: "Price of token0 in terms of token1 (reserve1 / reserve0)", Dependencies: []string{"reserve0", "reserve1"}, Compute: func(record map[string]interface{}) interface{} { reserve0, ok0 := parseNumeric(record["reserve0"]) reserve1, ok1 := parseNumeric(record["reserve1"]) if !ok0 || !ok1 { return nil } if reserve0 == 0 { return nil } decimals0 := 18.0 decimals1 := 18.0 if token0, ok := record["token0"].(map[string]interface{}); ok { if d, ok := parseNumeric(token0["decimals"]); ok { decimals0 = d } } if token1, ok := record["token1"].(map[string]interface{}); ok { if d, ok := parseNumeric(token1["decimals"]); ok { decimals1 = d } } decimalAdjustment := math.Pow(10, decimals0-decimals1) return (reserve1 / reserve0) * decimalAdjustment }, }, { Name: "token1Price", Description: "Price of token1 in terms of token0 (reserve0 / reserve1)", Dependencies: []string{"reserve0", "reserve1"}, Compute: func(record map[string]interface{}) interface{} { reserve0, ok0 := parseNumeric(record["reserve0"]) reserve1, ok1 := parseNumeric(record["reserve1"]) if !ok0 || !ok1 { return nil } if reserve1 == 0 { return nil } decimals0 := 18.0 decimals1 := 18.0 if token0, ok := record["token0"].(map[string]interface{}); ok { if d, ok := parseNumeric(token0["decimals"]); ok { decimals0 = d } } if token1, ok := record["token1"].(map[string]interface{}); ok { if d, ok := parseNumeric(token1["decimals"]); ok { decimals1 = d } } decimalAdjustment := math.Pow(10, decimals1-decimals0) return (reserve0 / reserve1) * decimalAdjustment }, }, }
UniswapV2PairFields provides computed fields for Uniswap V2 pairs.
These fields are computed from the pair's reserves, as a query returns them (unverified), to match The Graph's Uniswap V2 subgraph schema.
Fields required:
- reserve0: Token 0 reserve amount
- reserve1: Token 1 reserve amount
- token0.decimals: Token 0 decimals (optional, defaults to 18)
- token1.decimals: Token 1 decimals (optional, defaults to 18)
var UniswapV2TokenFields = ComputedFieldSet{ { Name: "derivedETH", Description: "Price of token in ETH (derived from WETH pair reserves)", Dependencies: []string{}, Compute: func(record map[string]interface{}) interface{} { if isWeth, ok := record["isWeth"].(bool); ok && isWeth { return 1.0 } if symbol, ok := record["symbol"].(string); ok && symbol == "WETH" { return 1.0 } reserve0, ok0 := parseNumeric(record["ethPairReserve0"]) reserve1, ok1 := parseNumeric(record["ethPairReserve1"]) if !ok0 || !ok1 { return nil } token0IsWeth, _ := record["ethPairToken0IsWeth"].(bool) if token0IsWeth { if reserve1 == 0 { return nil } return reserve0 / reserve1 } if reserve0 == 0 { return nil } return reserve1 / reserve0 }, }, }
UniswapV2TokenFields provides computed fields for Uniswap V2 tokens.
These fields compute derived ETH prices from stablecoin pool reserves, as a query returns them (unverified).
Functions ¶
func ApplyComputedFields ¶
func ApplyComputedFields(record map[string]interface{}, fields ComputedFieldSet) map[string]interface{}
ApplyComputedFields applies computed fields to a single record. Returns a new map with computed fields added.
func BoolPtr ¶
BoolPtr is a convenience helper for the Reconnect field.
Usage:
opts := &SubscribeOptions{Reconnect: BoolPtr(false)}
func CanonicalEventSetHash ¶
CanonicalEventSetHash computes the domain-separated keccak-256 commitment over the filter-matched event set in canonical order. All integers are big-endian and the layout is length-prefixed, so no boundary is ambiguous:
"WILLOW_CRYPTO_EVENTS_V1" (23 ASCII bytes, no terminator) blockNumber (u64 big-endian, 8 bytes) len(matchedLogs) (u64 big-endian, 8 bytes) for each log, in order: address (20 bytes) len(topics) (u32 big-endian, 4 bytes) each topic (32 bytes each) len(data) (u32 big-endian, 4 bytes) data (raw bytes)
func DecryptFile ¶
DecryptFile decrypts file data using XChaCha20-Poly1305.
Requires: golang.org/x/crypto/chacha20poly1305
func EncryptFile ¶
EncryptFile encrypts file data using XChaCha20-Poly1305.
Uses XChaCha20-Poly1305 with a 24-byte nonce to match the Rust SDK and consensus layer. Files encrypted with this function are interoperable across all Willow SDKs.
Requires: golang.org/x/crypto/chacha20poly1305
func EvmChainID ¶
func EvmChainID(chain SupportedChain) (uint64, bool)
EvmChainID returns the EIP-155 chain id for EVM-family chains, or (0, false) for non-EVM chains.
func FormatDataStoreMessage ¶
func FormatDataStoreMessage(subgroveID, key, ownerDID string, data []byte, nonce uint64) (string, error)
FormatDataStoreMessage returns the message a StoreData transaction is signed over:
StoreData Subgrove: <subgroveID> Key: <key> Owner: <ownerDID> DataHash: <hex SHA-256 of data> Nonce: <nonce>
data is the exact bytes the transaction carries in its data field (the JSON text as UTF-8).
func FormatDeleteFileManifestMessage ¶
func FormatDeleteFileManifestMessage(subgroveID, fileKey, ownerDID string, nonce uint64) (string, error)
FormatDeleteFileManifestMessage returns the message a DeleteFileManifest transaction is signed over:
DeleteFileManifest Subgrove: <subgroveID> Key: <fileKey> Owner: <ownerDID> Nonce: <nonce>
func FormatGrantSubgroveKeyMessage ¶
func FormatGrantSubgroveKeyMessage(subgroveID, senderDID string, grant EncryptedKeyGrant, nonce uint64) (string, error)
FormatGrantSubgroveKeyMessage returns the message a GrantSubgroveKey transaction is signed over:
GrantSubgroveKey Subgrove: <subgroveID> Sender: <senderDID> Grantee: <grant.GranteeDID> GranteeKey: <grant.GranteePublicKeyID> KeyEpoch: <grant.KeyEpoch> EphemeralKey: <hex grant.EphemeralPublicKey> EncryptedKey: <hex grant.EncryptedKey> GrantedBy: <grant.GrantedBy> GrantedAt: <grant.GrantedAt> Nonce: <nonce>
It refuses a grant whose grantee isn't a DID ("did:willow:" then ASCII letters, digits, '-', or '_', at most 128 bytes), which the chain refuses.
func FormatRegisterSubgroveMessage ¶
func FormatRegisterSubgroveMessage(tx *consensus.RegisterSubgroveTx) (string, error)
FormatRegisterSubgroveMessage returns the message a RegisterSubgrove transaction is signed over:
RegisterSubgrove Subgrove: <SubgroveID> Owner: <OwnerDid> Config: <hex SHA-256 of the transaction's bincode with an empty signature> Nonce: <Nonce>
Config binds every field of the transaction: it hashes consensus.RegisterSubgroveUnsignedBincode of the JSON tx marshals to, which is the JSON sent. Build the message from the transaction as it will be sent (every field but the signature set, the nonce included), then set Signature.
It refuses a BlockchainIndexing registration: consensus.SubgroveBlockchainIndexing doesn't encode the chain's indexing mode, so this SDK signs DataStorage and FileStorage registrations only. A nil Mode is the chain's default DataStorage. It also refuses what the chain refuses in a DataStorage or FileStorage registration: a subgrove id that isn't 1 to 64 ASCII letters, digits, '-', or '_' starting with a letter or digit; admins, writers, or free readers that aren't DIDs ("did:willow:" then ASCII letters, digits, '-', or '_', at most 128 bytes); a schema that doesn't parse as the chain's schema definition (see SchemaDefinition.ChainSchemaJSON) or declares indexes; and, in a private DataStorage registration, an initial owner key grant that isn't key epoch 0 to the owner.
func FormatRotateSubgroveKeyMessage ¶
func FormatRotateSubgroveKeyMessage(subgroveID, senderDID string, newEpoch uint32, grants []EncryptedKeyGrant, nonce uint64) (string, error)
FormatRotateSubgroveKeyMessage returns the message a RotateSubgroveKey transaction is signed over:
RotateSubgroveKey Subgrove: <subgroveID> Sender: <senderDID> NewEpoch: <newEpoch> Grants: <len(grants)> <for each grant, in order, its seven lines Grantee … GrantedAt, as in FormatGrantSubgroveKeyMessage> Nonce: <nonce>
It refuses what the chain refuses: a rotation with no grants, a grant whose KeyEpoch isn't newEpoch, or a grant whose grantee isn't a DID.
func FormatStoreFileManifestMessage ¶
func FormatStoreFileManifestMessage(f FileManifestFields) (string, error)
FormatStoreFileManifestMessage returns the message a StoreFileManifest transaction is signed over:
StoreFileManifest Subgrove: <SubgroveID> Key: <FileKey> Owner: <OwnerDID> Filename: <Filename> ContentType: <ContentType> TotalSize: <TotalSize> ContentHash: <hex ContentHash> ChunkCount: <ChunkCount> ChunkSize: <ChunkSize> ChunkMerkleRoot: <hex ChunkMerkleRoot> Encryption: none | <KeyEpoch>:<hex Nonce> Nonce: <Nonce>
func FormatTransferMessage ¶
func FormatTransferMessage(req *TransferRequest, nonce uint64) string
FormatTransferMessage formats the message to sign for a transfer.
func FormatUnregisterStorageNodeMessage ¶
FormatUnregisterStorageNodeMessage returns the message an UnregisterStorageNode transaction is signed over:
UnregisterStorageNode Node: <nodeDID> Nonce: <nonce>
func GenerateDID ¶
GenerateDID derives a self-certifying Willow DID from a key pair.
The identifier is bound to the public key, so it cannot be chosen:
did = "did:willow:z" + base58btc( SHA3-256( multicodec_prefix || public_key ) )
where SHA3-256 is FIPS-202 (NOT Keccak-256), the multicodec prefix is 0xED01 for Ed25519 and 0xE701 for secp256k1 (hashed over the 33-byte compressed key), and the leading 'z' is the multibase base58btc marker.
Because the id is derived from the key, the on-chain RegisterDid check accepts a registration only for the exact derived id. A freshly generated DID therefore has to be funded (someone transfers at least the registration fee to the derived id) BEFORE the holder registers it; see RegisterDID.
func IsHTTPError ¶
IsHTTPError checks if the error is an HTTP error and returns the status code.
func IsNotAuthenticated ¶
IsNotAuthenticated checks if the error is a not authenticated error.
func IsNotFound ¶
IsNotFound checks if the error is a not found error.
func IsSupportedChain ¶
IsSupportedChain returns true iff s is a canonical chain id.
func IsUnsupported ¶
IsUnsupported checks if the error is an unsupported-operation error.
func IsValidationError ¶
IsValidationError checks if the error is a validation error.
func LegacyRequestMessage ¶
LegacyRequestMessage is the message SignRequest signs: {METHOD}:{PATH}:{TIMESTAMP}, with any query string dropped from path.
func NewRequestNonce ¶
NewRequestNonce returns a fresh nonce for a nonce-signed request: 32 hex characters from 16 random bytes. The server accepts 16 to 128 characters of A-Z a-z 0-9 - _, and each (DID, nonce) only once.
func SerializeManifest ¶
func SerializeManifest(m *WillowManifest) ([]byte, error)
SerializeManifest validates and emits the canonical JSON byte form that goes on-chain via SubgroveMode.BlockchainIndexing.manifest_content.
func SignedRequestMessage ¶
func SignedRequestMessage(did, publicKeyID, method, pathAndQuery, timestamp, nonce string, body []byte) string
SignedRequestMessage is the message a nonce-signed request signs: a version line, then one per line the DID, its key's id, the method, the path and query exactly as sent, the Unix timestamp, the nonce, and the hex SHA-256 of the body (of no bytes, for a request without one).
func ValidateManifest ¶
func ValidateManifest(m *WillowManifest) error
ValidateManifest applies every canonical-schema check. Same rules as WillowManifest::from_bytes + validate() in willow-types.
func Verify ¶
func Verify(algorithm SignatureAlgorithm, publicKey, message, signature []byte) (bool, error)
Verify verifies a signature against a message and public key.
func VerifyServedEvents ¶
VerifyServedEvents reports whether matchedLogs re-hash to the trusted on-chain commitment for blockNumber. A false result means the indexer's served set was tampered with, incomplete, or for the wrong block.
Types ¶
type AccountNonceState ¶
type AccountNonceState struct {
// Base is the account nonce: every nonce at or below it is used.
Base uint64
// Used has bit i set when nonce Base+1+i is used (24 bits). Only the
// ABCI query /store/account_nonce_state/{did} reports it; read from the
// API's /account/{did}/nonce it is 0.
Used uint32
}
AccountNonceState is an account's nonce state as the chain reports it.
func ParseAccountNonceState ¶
func ParseAccountNonceState(value []byte) (AccountNonceState, error)
ParseAccountNonceState reads the value of the ABCI query /store/account_nonce_state/{did}: the base as a big-endian u64, then 3 bytes in which bit i%8 of byte i/8 marks Base+1+i used. 8 bytes is the base alone, and none an account with no transactions.
func (AccountNonceState) IsUsed ¶
func (s AccountNonceState) IsUsed(nonce uint64) bool
IsUsed reports whether the state shows nonce used.
type ApiResponse ¶
type ApiResponse[T any] struct { Success bool `json:"success"` Data T `json:"data,omitempty"` Error string `json:"error,omitempty"` }
ApiResponse represents a generic API response.
type BalanceInfo ¶
type BalanceInfo struct {
DID string `json:"did"`
// Available is the spendable balance.
Available consensus.Uint128 `json:"available"`
// Staked is the amount staked with validators.
Staked consensus.Uint128 `json:"staked"`
// Locked is the amount unbonding.
Locked consensus.Uint128 `json:"locked"`
}
BalanceInfo is a DID's balance, in the smallest token unit (10^-18 WILL).
type BatchStoreRequest ¶
type BatchStoreRequest struct {
Items []StoreRequest `json:"items"`
}
BatchStoreRequest represents a request to store multiple items.
type ChainFamily ¶
type ChainFamily string
ChainFamily indicates the proof / data-source primitives a chain uses.
const ( FamilyEvm ChainFamily = "evm" FamilySolana ChainFamily = "solana" )
func FamilyOf ¶
func FamilyOf(chain SupportedChain) ChainFamily
FamilyOf returns the family a chain belongs to.
type CheckpointInfo ¶
type CheckpointInfo struct {
CheckpointID string `json:"checkpoint_id"`
SubgroveID string `json:"subgrove_id"`
StateRoot string `json:"state_root"` // State root hash (hex)
BlockRange [2]uint64 `json:"block_range"`
IndexerDID string `json:"indexer_did"`
SubmittedAt uint64 `json:"submitted_at"` // Unix timestamp
IsTrusted bool `json:"is_trusted"`
}
CheckpointInfo represents information about a checkpoint.
type ChunkUploadError ¶
type ChunkUploadError struct {
// Manifest is the manifest Upload sent, as it returns it on success.
Manifest *FileManifest
// Submission is the manifest's transaction: its signer, nonce, and hash.
Submission *WriteResult
// Chunk is the index of the chunk the storage node didn't store.
Chunk int
// Err is why: the request's error, or an *HTTPError carrying the
// storage node's status and message.
Err error
}
ChunkUploadError is an Upload whose manifest transaction CheckTx accepted but whose chunk Chunk the storage node didn't store. The manifest is on chain once its transaction lands, which uses its nonce, but the storage node doesn't hold the file whole: chunk Chunk failed, and the chunks after it weren't sent.
func (*ChunkUploadError) Error ¶
func (e *ChunkUploadError) Error() string
Error implements the error interface.
type Client ¶
type Client struct {
// Sub-clients for different operations
Data *DataOperations
Registration *RegistrationOperations
Token *TokenOperations
Validators *ValidatorOperations
Indexing *IndexingOperations
Privacy *PrivacyOperations
Files *FileOperations
// Indexers is the discovery client used by source-routed queries.
// When no indexer URL was configured, it queries GET /indexers on the
// validator (with 30-second cache). When indexerURL is set, it returns
// a synthetic single-entry list.
Indexers *Indexers
// Subscriptions opens graphql-transport-ws WebSocket connections
// against either the validator's /graphql/ws (default) or an
// indexer's, based on SubscribeOptions.Source.
Subscriptions *Subscriptions
// contains filtered or unexported fields
}
Client is the main client for interacting with the Willow network.
func NewClient ¶
func NewClient(apiURL string, opts ...ClientOption) (*Client, error)
NewClient creates a new Willow client with the given API URL and options.
func (*Client) FetchEventsCommitment ¶
func (c *Client) FetchEventsCommitment(ctx context.Context, subgroveID string, blockNumber uint64) ([32]byte, error)
FetchEventsCommitment reads a block's on-chain events_commitment anchor via a CometBFT ABCI store query against the validator RPC endpoint. It returns the 32-byte commitment on success. A non-zero ABCI response code (e.g. no anchor stored for the block) is surfaced as an error: the block is not verifiable.
The commitment is the RPC node's answer, which the SDK trusts: the node answers this query with no proof, so nothing binds it to a verified header. The RPC node is the one WithRPCURL names; without it, the API URL with its :3031 replaced by :26657 (the API's host), or, when the API URL has no :3031, the API URL itself (see RPCEndpoint). An answer about another subgrove or block than the one asked for is an error.
func (*Client) FetchMatchedLogs ¶
func (c *Client) FetchMatchedLogs(ctx context.Context, subgroveID string, blockNumber uint64) ([]Log, error)
FetchMatchedLogs fetches the indexer's canonical filter-matched log set for a block — the events_commitment preimage — and parses it into Log values in the order served. A non-200 response (e.g. 404 when the indexer retained no matched logs, or the block is not finalized) is surfaced as an error: the block is not verifiable from this indexer.
Only indexers serve matched logs, so the client needs an indexer URL (WithIndexerURL).
func (*Client) GetAccountNonce ¶
GetAccountNonce reads did's nonce state. With an RPC URL set (WithRPCURL) it is the base and which of the 24 nonces above it are used, from the ABCI query /store/account_nonce_state/{did}; otherwise, or if that query fails, the base alone, from the API's /account/{did}/nonce.
func (*Client) GetComputedFields ¶
func (c *Client) GetComputedFields(datasetID string) (ComputedFieldSet, bool)
GetComputedFields returns the computed fields for a dataset.
func (*Client) GetDID ¶
GetDID retrieves a DID's on-chain document. Its balance is read with Token.GetBalance.
func (*Client) GetIdentity ¶
GetIdentity returns the current identity.
func (*Client) GetLatestAppHash ¶
GetLatestAppHash returns the app hash of the latest block, as the API reads it from its CometBFT node (/state/root-hash/verified). The SDK doesn't verify it: it is the API's value, not checked against the validators' commit signatures.
func (*Client) GetOrCreateLightClient ¶
func (c *Client) GetOrCreateLightClient(ctx context.Context) (*lightclient.LightClient, error)
GetOrCreateLightClient returns the light client, creating one with trust-on-first-use if needed: it takes the RPC endpoint's latest header as trusted. See the lightclient package for what its VerifyHeader checks; it does not verify commit signatures.
func (*Client) GetRootHash ¶
GetRootHash returns the current root hash from the local node.
func (*Client) HasComputedFields ¶
HasComputedFields checks if computed fields are registered for a dataset.
func (*Client) HasIdentity ¶
HasIdentity returns true if an identity is set on the client.
func (*Client) HasLightClient ¶
HasLightClient returns true if a light client is configured.
func (*Client) Health ¶
func (c *Client) Health(ctx context.Context) (*HealthStatus, error)
Health checks the health of the node. The API answers /health with the status itself, not the success/data envelope.
func (*Client) IndexerBaseURL ¶
IndexerBaseURL returns the indexer URL if configured, otherwise the base API URL. Used to route GraphQL/SQL queries to an indexer node.
func (*Client) LightClient ¶
func (c *Client) LightClient() *lightclient.LightClient
LightClient returns the light client, if configured.
func (*Client) NextNonce ¶
NextNonce hands out a nonce for a transaction signed by did: the lowest in the account's window that the chain doesn't show used and that this client doesn't hold. Take one here for a transaction the client doesn't choose the nonce of (a file write's FileSigningOptions.Nonce), so that no other write from this client takes it while it is in flight. A nonce handed out and never sent is free again after NonceHold; one sent through the client (Files) is held while the submission is in flight and as its outcome says.
It returns an error wrapping ErrNonceWindowFull when every nonce in the window is used or held: wait for earlier writes to land.
func (*Client) RPCEndpoint ¶
RPCEndpoint returns the CometBFT JSON-RPC endpoint used for ABCI store queries. It returns the explicit override from WithRPCURL when set, otherwise derives it from the API URL by swapping the :3031 REST port for :26657.
func (*Client) RegisterComputedFields ¶
func (c *Client) RegisterComputedFields(datasetID string, fields ComputedFieldSet)
RegisterComputedFields registers computed fields for a dataset.
Computed fields are derived values calculated from the values a query returns, which are unverified, enabling drop-in compatibility with The Graph's query interfaces.
Example:
client.RegisterComputedFields("pairs", UniswapV2PairFields)
func (*Client) RegisterDID
deprecated
func (c *Client) RegisterDID(ctx context.Context, didDocument *DidDocument) (*DidDocument, error)
RegisterDID returns an unsupported-operation error and sends nothing.
The API serves no DID registration route: a DID is registered on chain by a RegisterDid transaction sent to POST /tx/submit, which this SDK does not build.
Willow DIDs are self-certifying: the id is derived from the public key (see GenerateDID), not chosen. Because the fee for registration is paid from the derived id's own balance, a new DID must be funded (a token transfer of at least the registration fee to identity.DID()) before it is registered.
Deprecated: RegisterDID always fails, and this SDK has no replacement: it builds no RegisterDid transaction.
func (*Client) RequireAuth ¶
RequireAuth returns an error if the client has no identity set.
func (*Client) SetIdentity ¶
SetIdentity sets the identity used for request signing.
func (*Client) VerifyBlockCompleteness ¶
func (c *Client) VerifyBlockCompleteness(ctx context.Context, subgroveID string, blockNumber uint64) (bool, error)
VerifyBlockCompleteness performs the client-side completeness check for a (subgrove, block): it fetches the events_commitment anchor and the indexer's matched-log preimage, then verifies the latter re-hashes to the former. It returns true only when the served event set is exactly the filter-matched set the commitment binds. The commitment is the RPC node's answer, which the SDK trusts (see FetchEventsCommitment): the check removes trust in the indexer, not in that node. Without WithRPCURL that node is the API's host (the API URL with :3031 replaced by :26657), or the API itself when its URL has no :3031, so the check then trusts the API's operator.
An error is returned when either fetch fails or the block is not verifiable (no on-chain anchor, or the indexer retained no matched logs). A non-nil error with a false result is the not-verifiable case; a nil error with a false result means the served set did not match the anchor (tampered, incomplete, reordered, or wrong block).
func (*Client) WaitUntilLanded ¶
WaitUntilLanded waits until the chain shows did's nonce used, polling its nonce state (see GetAccountNonce) until then or until ctx is done.
A write returns once CheckTx accepts it; send a write that depends on it (an update of a key being stored, a store into a subgrove being registered) only after it lands, since writes in flight may land in any order. A write refused in its block also uses its nonce (every kind the SDK sends except DeregisterSubgrove, whose refusal leaves it unused): read what it wrote, or look the TxHash of its WriteResult up (consensus.Client.GetTx), to know it took effect. For a write whose *WriteError has MayLand set, read what it wrote: the API names no transaction hash for a submission that may have landed. (A CheckTx refusal's hash is on the *TransactionError the WriteError wraps.)
Set an RPC URL (WithRPCURL) when writes run concurrently. Without one only the base is known, and the base advances only over used nonces with no gap below them, so a nonce that landed above a nonce not yet used (a write still pending, or one that never landed) doesn't show as landed: this waits for every earlier nonce of did, and fails at ctx's deadline if one never lands.
type ClientBuilder ¶
type ClientBuilder struct {
// contains filtered or unexported fields
}
ClientBuilder provides a fluent interface for building a Client.
func (*ClientBuilder) Build ¶
func (b *ClientBuilder) Build() (*Client, error)
Build creates the Client with all configured options.
func (*ClientBuilder) WithAPIKey ¶
func (b *ClientBuilder) WithAPIKey(key string) *ClientBuilder
WithAPIKey adds a managed-tier API key to the builder. See WithAPIKey.
func (*ClientBuilder) WithHTTPClient ¶
func (b *ClientBuilder) WithHTTPClient(httpClient *http.Client) *ClientBuilder
WithHTTPClient adds a custom HTTP client option to the builder.
func (*ClientBuilder) WithIndexerURL ¶
func (b *ClientBuilder) WithIndexerURL(indexerURL string) *ClientBuilder
WithIndexerURL adds an indexer URL option to the builder.
func (*ClientBuilder) WithLightClient ¶
func (b *ClientBuilder) WithLightClient(lc *lightclient.LightClient) *ClientBuilder
WithLightClient adds a light client option to the builder.
func (*ClientBuilder) WithRPCURL ¶
func (b *ClientBuilder) WithRPCURL(rpcURL string) *ClientBuilder
WithRPCURL adds a CometBFT JSON-RPC endpoint option to the builder.
func (*ClientBuilder) WithRetryConfig ¶
func (b *ClientBuilder) WithRetryConfig(config RetryConfig) *ClientBuilder
WithRetryConfig adds a retry configuration option to the builder.
func (*ClientBuilder) WithTimeout ¶
func (b *ClientBuilder) WithTimeout(timeout time.Duration) *ClientBuilder
WithTimeout adds a timeout option to the builder.
type ClientOption ¶
ClientOption is a functional option for configuring the Client.
func WithAPIKey ¶
func WithAPIKey(key string) ClientOption
WithAPIKey configures the managed-tier API key. Mint a key at https://dashboard.willow.tech/account. Required for queries and writes against managed api.willow.tech / indexer.willow.tech.
The SDK sends `X-API-Key: <key>` only to the API URL's origin and to the indexer URL's (WithIndexerURL), whatever the order of the options: never to an indexer it discovers from the API's /indexers list, whose endpoint anyone who registers an indexer chooses, nor to the RPC URL or a storage node. To send the key to an indexer, name it with WithIndexerURL. A client passed with WithHTTPClient isn't changed: the SDK uses a copy that carries the key.
func WithHTTPClient ¶
func WithHTTPClient(httpClient *http.Client) ClientOption
WithHTTPClient sets a custom HTTP client.
func WithIndexerURL ¶
func WithIndexerURL(indexerURL string) ClientOption
WithIndexerURL sets an optional indexer node URL. When set, GraphQL and SQL queries are routed to the indexer instead of the validator.
func WithLightClient ¶
func WithLightClient(lc *lightclient.LightClient) ClientOption
WithLightClient sets the light client LightClient and GetOrCreateLightClient return. It tracks CometBFT headers without verifying their commit signatures (see the lightclient package), and no read is verified against it.
func WithRPCURL ¶
func WithRPCURL(rpcURL string) ClientOption
WithRPCURL sets an explicit CometBFT JSON-RPC endpoint (e.g. http://localhost:26657). Used for ABCI store queries such as the completeness anchor and, only when set, the account nonce state (see GetAccountNonce), whose bitmap of used nonces lets writes skip them. When unset, the endpoint is derived from the API URL by swapping the :3031 REST port for :26657, and the nonce state is read from the API (its base alone).
func WithRetryConfig ¶
func WithRetryConfig(config RetryConfig) ClientOption
WithRetryConfig sets the retry configuration.
func WithTimeout ¶
func WithTimeout(timeout time.Duration) ClientOption
WithTimeout sets the HTTP client timeout.
type CommitmentFrequency ¶
type CommitmentFrequency = consensus.CommitmentFrequency
CommitmentFrequency defines how often a provider must publish state root commitments on-chain for a private subgrove (see consensus.CommitmentFrequency).
func NewCommitmentFrequencyEveryNBlocks ¶
func NewCommitmentFrequencyEveryNBlocks(n uint64) CommitmentFrequency
NewCommitmentFrequencyEveryNBlocks returns a CommitmentFrequency that commits every n blocks processed.
func NewCommitmentFrequencyEveryNSeconds ¶
func NewCommitmentFrequencyEveryNSeconds(n uint64) CommitmentFrequency
NewCommitmentFrequencyEveryNSeconds returns a CommitmentFrequency that commits at least every n seconds.
func NewCommitmentFrequencyEveryUpdate ¶
func NewCommitmentFrequencyEveryUpdate() CommitmentFrequency
NewCommitmentFrequencyEveryUpdate returns a CommitmentFrequency that commits after every write/block update (default, strongest freshness).
func NewCommitmentFrequencyNever ¶
func NewCommitmentFrequencyNever() CommitmentFrequency
NewCommitmentFrequencyNever returns a CommitmentFrequency that disables on-chain commitments.
type ComputeFunction ¶
type ComputeFunction func(record map[string]interface{}) interface{}
ComputeFunction is a function that computes a derived value from a record's fields. Returns nil if the computation cannot be performed (e.g., division by zero).
type ComputedFieldDefinition ¶
type ComputedFieldDefinition struct {
// Name is the field name in the output record.
Name string
// Description is a human-readable description of what this field represents.
Description string
// Dependencies are the record's fields this computation depends on.
Dependencies []string
// Compute is the computation function.
Compute ComputeFunction
}
ComputedFieldDefinition defines a single computed field.
type ComputedFieldRegistry ¶
type ComputedFieldRegistry struct {
// contains filtered or unexported fields
}
ComputedFieldRegistry is a registry of computed fields by dataset.
func NewComputedFieldRegistry ¶
func NewComputedFieldRegistry() *ComputedFieldRegistry
NewComputedFieldRegistry creates a new ComputedFieldRegistry.
func (*ComputedFieldRegistry) Clear ¶
func (r *ComputedFieldRegistry) Clear()
Clear removes all registered computed fields.
func (*ComputedFieldRegistry) Get ¶
func (r *ComputedFieldRegistry) Get(datasetID string) (ComputedFieldSet, bool)
Get returns computed fields for a specific dataset.
func (*ComputedFieldRegistry) Has ¶
func (r *ComputedFieldRegistry) Has(datasetID string) bool
Has checks if computed fields are registered for a dataset.
func (*ComputedFieldRegistry) Register ¶
func (r *ComputedFieldRegistry) Register(datasetID string, fields ComputedFieldSet)
Register registers computed fields for a specific dataset.
func (*ComputedFieldRegistry) Unregister ¶
func (r *ComputedFieldRegistry) Unregister(datasetID string) bool
Unregister removes computed fields for a dataset.
type ComputedFieldSet ¶
type ComputedFieldSet []ComputedFieldDefinition
ComputedFieldSet is a set of computed field definitions for a dataset.
type DataOperations ¶
type DataOperations struct {
// contains filtered or unexported fields
}
DataOperations provides methods for data storage and retrieval.
func (*DataOperations) BatchStore
deprecated
func (d *DataOperations) BatchStore(ctx context.Context, subgroveID string, items []StoreRequest) error
BatchStore returns an unsupported-operation error and sends nothing: the API serves no batch write route. Store each item with StoreItem, which sends one StoreData transaction per item under its own nonce; at most 24 can be in flight per identity, so past that wait for earlier ones to land (Client.WaitUntilLanded).
Deprecated: BatchStore always fails; store each item with StoreItem.
func (*DataOperations) Delete
deprecated
func (d *DataOperations) Delete(ctx context.Context, subgroveID, key string) error
Delete returns an unsupported-operation error and sends nothing: the API's REST data routes refuse writes, and data is deleted by a DeleteData transaction, which this SDK does not build.
Deprecated: Delete always fails, and this SDK has no replacement: it builds no DeleteData transaction.
func (*DataOperations) Get ¶
func (d *DataOperations) Get(ctx context.Context, subgroveID, key string) (*DataResponse, error)
Get retrieves the value stored under key.
The API's data route answers with the value alone, without a proof, so Get has nothing to verify. GetProof fetches the key's GroveDB proof.
func (*DataOperations) GetCheckpointStateRoot ¶
func (d *DataOperations) GetCheckpointStateRoot(ctx context.Context, subgroveID, checkpointID string) (*CheckpointInfo, error)
GetCheckpointStateRoot retrieves checkpoint information including state root.
func (*DataOperations) GetProof ¶
GetProof retrieves the GroveDB proof of a key, with the GroveDB path and key it proves and the height of the block whose state it is of.
The proof is of the state after block Height, so its root is the app_hash of the CometBFT header at Height+1. Checking it takes that header verified against the validators' commit signatures and a GroveDB verifier that reproduces the chain's proofs, run at Path; this SDK has neither (see VerifyProof), so GetProof returns the proof unverified.
func (*DataOperations) GetUnverified ¶
func (d *DataOperations) GetUnverified(ctx context.Context, subgroveID, key string) (*DataResponse, error)
GetUnverified retrieves the value stored under key, asking the API for no proof.
func (*DataOperations) Query
deprecated
func (d *DataOperations) Query(ctx context.Context, subgroveID string, query *QueryRequest) (*QueryResponse, error)
Query returns an unsupported-operation error and sends nothing.
A query's proof is of the state after block Height, so its root is the app_hash of the CometBFT header at Height+1. Verifying a query takes that header verified against the validators' commit signatures, the proof's root reproduced, and the returned documents matched to the values the proof proves. This SDK does none of these (see VerifyProof), so it doesn't present a query as verified. QueryUnverified sends the query and returns its documents unverified.
Deprecated: Query always fails; use QueryUnverified, which returns the documents unverified.
func (*DataOperations) QueryHistorical ¶
func (d *DataOperations) QueryHistorical(ctx context.Context, subgroveID, checkpointID string, req *HistoricalQueryRequest) (*HistoricalQueryResponse, error)
QueryHistorical queries historical indexed data from a checkpoint and returns the answer unverified: its StateRoot, Data, and Proof are what the API relays from an indexer, and the SDK checks none of them. The API answers this route with the HistoricalQueryResponse itself, not the success/data envelope.
func (*DataOperations) QueryHistoricalVerified
deprecated
func (d *DataOperations) QueryHistoricalVerified(ctx context.Context, subgroveID, checkpointID string, req *HistoricalQueryRequest) (*HistoricalQueryResponse, error)
QueryHistoricalVerified returns an unsupported-operation error and sends nothing.
Verifying a historical answer takes the checkpoint's state root read from the chain against a CometBFT header verified by the validators' commit signatures, and a proof that binds the answer's data at the asked path and key to that root. The answer carries its own state root, and this SDK verifies no header and has no GroveDB verifier that binds the data, so it doesn't present a historical answer as verified.
Deprecated: the SDK can't verify a historical answer; QueryHistorical returns it unverified.
func (*DataOperations) QueryUnverified ¶
func (d *DataOperations) QueryUnverified(ctx context.Context, subgroveID string, query *QueryRequest) (*QueryResponse, error)
QueryUnverified queries data without a proof (include_proof false) and returns the API's documents as they are. query isn't changed. An answer over 64 MiB is refused: the API sets no maximum Limit (100 documents of up to 512 KiB each, its default page, fit), so ask for fewer documents when a page would be over it.
func (*DataOperations) Store
deprecated
func (*DataOperations) StoreItem ¶
func (d *DataOperations) StoreItem(ctx context.Context, subgroveID, key string, data map[string]interface{}, opts ...WriteOption) (*WriteResult, error)
StoreItem stores data under key by sending a signed StoreData transaction to POST /tx/submit, owned by the client's identity.
data is sent as its JSON text (encoding/json, object keys sorted) carried as bytes, and the signature binds those exact bytes with the subgrove, key, owner, and the transaction's nonce (see FormatDataStoreMessage). The nonce is the lowest free one in the identity's window (see Client.NextNonce), so writes in flight together take distinct nonces; at most 24 can be in flight per identity. StoreItem returns once the chain's CheckTx accepts the transaction, with the nonce and transaction hash; the write is applied, or refused, in its block (see Client.WaitUntilLanded). A failure after the transaction was signed is a *WriteError naming its nonce; to send it again under that nonce, pass WithNonce.
func (*DataOperations) Update
deprecated
func (d *DataOperations) Update(ctx context.Context, subgroveID, key string, data map[string]interface{}) error
Update returns an unsupported-operation error and sends nothing: the API's REST data routes refuse writes, and data is updated by an UpdateData transaction, which this SDK does not build.
Deprecated: Update always fails, and this SDK has no replacement: it builds no UpdateData transaction (the chain refuses a StoreData to a key that holds data).
func (*DataOperations) VerifyProof
deprecated
func (d *DataOperations) VerifyProof(ctx context.Context, proof *DataProof) error
VerifyProof returns an unsupported-operation error.
A proof's root must equal the app_hash of the CometBFT header at proof.Height+1, verified against the validators' commit signatures. This SDK doesn't verify CometBFT headers, and its GroveDB verifier doesn't reproduce the chain's root for every proof, so it doesn't present a proof as verified.
Deprecated: VerifyProof always fails, and this SDK has no replacement: no method in it verifies a proof against the chain. GetProof returns a proof unverified.
type DataProof ¶
type DataProof struct {
Proof []byte `json:"proof"`
// Path is the GroveDB path the proof descends to, and Key the key it
// proves under it.
Path [][]byte `json:"path,omitempty"`
Key []byte `json:"key,omitempty"`
RootHash string `json:"root_hash"`
Height int64 `json:"height"`
VerifiedAt int64 `json:"verified_at"`
}
DataProof represents a proof for data retrieval.
type DataResponse ¶
type DataResponse struct {
Key string `json:"key"`
Data map[string]interface{} `json:"data"`
Proof *DataProof `json:"proof,omitempty"`
}
DataResponse represents the response from a data retrieval operation.
type DataSource ¶
type DataSource interface {
// contains filtered or unexported methods
}
DataSource is one data source in a manifest. Concrete types: EvmDataSource, SolanaDataSource.
type DevnetTestAccount ¶
type DevnetTestAccount struct {
// DID is the decentralized identifier for the test account.
DID string
// PrivateKey is the hex-encoded private key - DO NOT USE IN PRODUCTION.
PrivateKey string
// PublicKey is the hex-encoded public key.
PublicKey string
// PublicKeyID is the key identifier used for authentication.
PublicKeyID string
}
DevnetTestAccount contains the pre-funded test account credentials for local devnet development.
This account is pre-registered and funded in the devnet genesis. Use it for SDK testing and development - DO NOT use in production!
Example usage:
client, _ := willow.NewClient("http://localhost:3031")
identity, _ := willow.DEVNET_TEST_ACCOUNT.ToIdentity()
client.SetIdentity(identity)
func (DevnetTestAccount) ToIdentity ¶
func (d DevnetTestAccount) ToIdentity() (*Identity, error)
ToIdentity converts the test account to an Identity that can be used for authentication.
This creates an Identity with the pre-registered devnet-test DID, not a newly generated DID from the key.
type DidDocument ¶
type DidDocument struct {
ID string `json:"id"`
PublicKeys []PublicKey `json:"public_keys"`
Created int64 `json:"created"`
Updated int64 `json:"updated"`
}
DidDocument represents a DID (Decentralized Identifier) document.
func CreateDidDocument ¶
func CreateDidDocument(keyPair *KeyPair) *DidDocument
CreateDidDocument creates a DID document from a key pair.
type DidInfo ¶
type DidInfo struct {
Did string `json:"did"`
Document *DidDocument `json:"document,omitempty"`
// Balance is never set: GetDID reads only the document.
//
// Deprecated: read the balance with Token.GetBalance.
Balance uint64 `json:"balance"`
// Nonce is never set: GetDID reads only the document.
//
// Deprecated: read the nonce state with Client.GetAccountNonce.
Nonce uint64 `json:"nonce"`
CreatedAt int64 `json:"created_at"`
}
DidInfo is a DID and its on-chain document, as Client.GetDID reads them.
type EncryptedKeyGrant ¶
type EncryptedKeyGrant = consensus.EncryptedKeyGrant
EncryptedKeyGrant represents an encrypted key grant for a subgrove, allowing a specific DID to decrypt the subgrove's data (see consensus.EncryptedKeyGrant).
type ErrorType ¶
type ErrorType string
ErrorType categorizes the type of error.
const ( ErrorTypeNetwork ErrorType = "network" ErrorTypeHTTP ErrorType = "http" ErrorTypeAuthentication ErrorType = "authentication" ErrorTypeValidation ErrorType = "validation" ErrorTypeNotFound ErrorType = "not_found" ErrorTypePermissionDenied ErrorType = "permission_denied" ErrorTypeSerialization ErrorType = "serialization" ErrorTypeCrypto ErrorType = "crypto" ErrorTypeProof ErrorType = "proof" ErrorTypeLightClient ErrorType = "light_client" ErrorTypeConfig ErrorType = "config" ErrorTypeConsensus ErrorType = "consensus" ErrorTypeTransaction ErrorType = "transaction" // ErrorTypeAPI is a request the API answered with success false. ErrorTypeAPI ErrorType = "api" // ErrorTypeUnsupported is an operation the network serves no route or // transaction for, or one this SDK does not build. ErrorTypeUnsupported ErrorType = "unsupported" )
type EthCallResult ¶
type EthCallResult struct {
BlockNumber uint64
BlockHash string
StateRoot string
Result []byte
AccessStateReads []EthStateRead
Mode EthProofMode
}
EthCallResult is an eth_call as an indexer ran it: its result, and the state of every account the call touched, unverified against Ethereum (see EthOperations). No proof binds Result: the SDK doesn't run the call.
type EthOperations ¶
type EthOperations struct {
Mode EthProofMode
// contains filtered or unexported fields
}
EthOperations reads Ethereum state through an indexer.
Nothing it returns is verified against Ethereum. Each answer carries the block's state root, and its MPT proofs bind the account and slot values to that root, but the SDK has no trusted source of Ethereum block headers (it runs no Ethereum light client; the block hash and state root it has are the indexer's), so it can't check that the root is the state root of the block asked for. Treat every result as the indexer's claim. In EthWalkProofs mode (the default) the SDK walks the proofs, so a result is at least consistent with the root the answer names; in EthSkipProofs mode it doesn't.
A zero storage value is proved by the slot's absence from the account's storage trie, and an account that doesn't exist by its absence from the state trie. Such an account reads as nonce and balance zero, every slot asked of it zero, and the storage root and code hash the answer carries: the empty ones, or zero hashes (as geth names them).
In every mode an answer must be about what was asked: a state read's proof must be for the address, block, and slots requested, in order, and a call's state proofs for the block requested, under the answer's state root.
func NewEthOperations ¶
func NewEthOperations(indexerBaseURL string, httpClient *http.Client) *EthOperations
NewEthOperations reads Ethereum state through the indexer at indexerBaseURL with httpClient, or, when it is nil, a client with a 30 s timeout.
func (*EthOperations) Erc20Balance ¶
func (e *EthOperations) Erc20Balance( ctx context.Context, token, holder string, balanceSlot byte, blockNumber uint64, ) (*big.Int, error)
Erc20Balance returns balanceOf(holder) for a token whose balance mapping lives at slot balanceSlot, as the indexer reports it (see EthOperations): the value of the slot GetState asked for. It returns an error when there is no contract at token: its account doesn't exist, or has no code. It can't tell whether balanceSlot is the token's balance mapping: a wrong balanceSlot reads a slot the token never set, which reads as zero.
func (*EthOperations) GetCall ¶
func (e *EthOperations) GetCall( ctx context.Context, tx map[string]interface{}, blockNumber uint64, ) (*EthCallResult, error)
GetCall asks the indexer to run tx at blockNumber and returns the ABI-encoded result it reports, with its state proofs for every account the call touched (see EthOperations). No proof binds the result. It returns an error, rather than the answer, when a state proof isn't for blockNumber, isn't under the answer's state root, or carries a balance or value longer than 32 bytes, or, in EthWalkProofs mode, when a proof doesn't walk or its address isn't 20 bytes or a slot 32 bytes.
func (*EthOperations) GetState ¶
func (e *EthOperations) GetState( ctx context.Context, address string, slots []string, blockNumber uint64, ) (*EthStateRead, error)
GetState reads an account's state, and the storage slots asked for, at blockNumber, as the indexer reports it (see EthOperations). address is 20 bytes of hex; each slot is up to 32 bytes of hex, read as a big-endian number and sent as 32 bytes. It returns an error, rather than the answer, when the answer's proof isn't for that address, block, and those slots in that order, or carries a balance or value longer than 32 bytes, or, in EthWalkProofs mode, when a proof doesn't walk.
type EthProofMode ¶
type EthProofMode int
EthProofMode selects how much of an indexer's Ethereum state answer EthOperations checks. No mode verifies the answer against Ethereum (see EthOperations).
const ( // EthWalkProofs (the default) walks the account proof and every storage // proof against the state root the answer itself carries. EthWalkProofs EthProofMode = iota // EthSkipProofs returns the answer's values without walking its proofs. EthSkipProofs )
type EthStateRead ¶
type EthStateRead struct {
Address string
BlockNumber uint64
BlockHash string
StateRoot string
Nonce uint64
Balance *big.Int
StorageHash string
CodeHash string
Storage []EthStorageSlot
Mode EthProofMode
}
EthStateRead is an account's state (and asked storage slots) at a block, as an indexer's answer carries it, unverified against Ethereum (see EthOperations). Mode says whether its proofs were walked against StateRoot.
type EthStorageSlot ¶
EthStorageSlot is a storage slot's value as an indexer's answer carries it.
type EthereumAnchor ¶
type EthereumAnchor struct {
BlockNumber uint64 `json:"block_number"`
TxHash []byte `json:"tx_hash"`
Contract string `json:"contract"`
}
EthereumAnchor contains Ethereum anchoring information
type EvmDataSource ¶
type EvmDataSource struct {
Name string `json:"name"`
Network SupportedChain `json:"network"`
Address string `json:"address"` // 0x + 40 hex (lowercased on serialize)
Abi string `json:"abi"`
StartBlock uint64 `json:"start_block"`
Events []string `json:"events"`
}
EvmDataSource is one indexed EVM contract within a manifest.
type FeeSchedule ¶
type FeeSchedule struct {
DidRegistration string `json:"did_registration"`
SubgroveRegistration string `json:"subgrove_registration"`
BaseTxCost string `json:"base_tx_cost"`
CostPerByte string `json:"cost_per_byte"`
QueryFee string `json:"query_fee"`
TransferFeePercentage uint32 `json:"transfer_fee_percentage"`
MaxTxSizeBytes uint64 `json:"max_tx_size_bytes"`
MaxDataPayloadBytes uint64 `json:"max_data_payload_bytes"`
}
FeeSchedule represents the fee schedule for operations. Fees are decimal strings of the smallest unit: the API sends them as u128 numbers.
func (*FeeSchedule) UnmarshalJSON ¶
func (f *FeeSchedule) UnmarshalJSON(data []byte) error
UnmarshalJSON reads the fees from JSON numbers (as the API sends them) or decimal strings.
type FileEncryption ¶
FileEncryption is a file manifest's encryption metadata: the subgrove key epoch and the 24-byte XChaCha20-Poly1305 nonce.
type FileListResponse ¶
type FileListResponse struct {
Files []FileManifest `json:"files"`
}
FileListResponse is the response from listing files.
type FileManifest ¶
type FileManifest struct {
FileKey string `json:"file_key"`
Filename string `json:"filename"`
ContentType string `json:"content_type"`
TotalSize uint64 `json:"total_size"`
ContentHash string `json:"content_hash"`
ChunkCount uint32 `json:"chunk_count"`
ChunkSize uint32 `json:"chunk_size"`
ChunkMerkleRoot string `json:"chunk_merkle_root"`
OwnerDID string `json:"owner_did"`
CreatedAt uint64 `json:"created_at"`
UpdatedAt uint64 `json:"updated_at"`
Encrypted bool `json:"encrypted"`
StorageNodes []string `json:"storage_nodes"`
}
FileManifest represents file metadata stored on-chain.
type FileManifestFields ¶
type FileManifestFields struct {
SubgroveID string
FileKey string
OwnerDID string
Filename string
ContentType string
TotalSize uint64
ContentHash [32]byte
ChunkCount uint32
ChunkSize uint32
ChunkMerkleRoot [32]byte
// Encryption is nil for a transaction without encryption metadata.
Encryption *FileEncryption
Nonce uint64
}
FileManifestFields are the fields a StoreFileManifest transaction writes, as it carries them.
type FileOperations ¶
type FileOperations struct {
// contains filtered or unexported fields
}
FileOperations provides file storage operations.
func (*FileOperations) Delete ¶
func (f *FileOperations) Delete(subgroveID, fileKey string, signing *FileSigningOptions) error
Delete deletes a file: it sends a DeleteFileManifest transaction signed with signing, which must name the owner (OwnerDID) and carry a SignFunc; without them Delete sends nothing and returns a validation error. A transaction that fails to submit returns a *WriteError (see FileSigningOptions.Nonce). Its request times out as Upload's do.
func (*FileOperations) DeleteContext ¶
func (f *FileOperations) DeleteContext(ctx context.Context, subgroveID, fileKey string, signing *FileSigningOptions) error
DeleteContext is Delete, stopping when ctx ends.
func (*FileOperations) Download ¶
func (f *FileOperations) Download(subgroveID, fileKey, storageNodeEndpoint string) ([]byte, error)
Download downloads a file from a FileStorage subgrove: the chunks its manifest (see Metadata) names, each the length the manifest makes it, which must hash to the manifest's chunk Merkle root and content hash. It refuses a manifest the chain would refuse for its sizes (no data, more than 1 GiB or 262,144 chunks, or a chunk count its total and chunk sizes don't make) before it asks for any chunk, and a chunk longer than 2 MiB, the most the storage node's upload route takes, as it reads it. Each request it sends times out as Upload's do; see DownloadContext to bound the whole download.
func (*FileOperations) DownloadContext ¶
func (f *FileOperations) DownloadContext(ctx context.Context, subgroveID, fileKey, storageNodeEndpoint string) ([]byte, error)
DownloadContext is Download, stopping when ctx ends.
func (*FileOperations) List ¶
func (f *FileOperations) List(subgroveID string) ([]FileManifest, error)
List returns the first page of a subgrove's files as the API answers it: at most 50, by default. It doesn't read the pages after it. Its request times out as Upload's do.
func (*FileOperations) ListContext ¶
func (f *FileOperations) ListContext(ctx context.Context, subgroveID string) ([]FileManifest, error)
ListContext is List, stopping when ctx ends.
func (*FileOperations) Metadata ¶
func (f *FileOperations) Metadata(subgroveID, fileKey string) (*FileManifest, error)
Metadata gets file manifest metadata from the validator API, which answers with the manifest itself, not the success/data envelope. Its request times out as Upload's do.
func (*FileOperations) MetadataContext ¶
func (f *FileOperations) MetadataContext(ctx context.Context, subgroveID, fileKey string) (*FileManifest, error)
MetadataContext is Metadata, stopping when ctx ends.
func (*FileOperations) UnregisterStorageNode ¶
func (f *FileOperations) UnregisterStorageNode(nodeDID string, signing *FileSigningOptions) error
UnregisterStorageNode submits an UnregisterStorageNode transaction to consensus. The signing options are required for this transaction: SignFunc signs as the node's DID, and Nonce is the transaction's nonce (take it with Client.NextNonce(ctx, nodeDID)). It is signed over FormatUnregisterStorageNodeMessage, which binds the node and the nonce. Without a node DID or a SignFunc it sends nothing and returns a validation error. A transaction that fails to submit returns a *WriteError (see FileSigningOptions.Nonce). Its request times out as Upload's do.
func (*FileOperations) UnregisterStorageNodeContext ¶
func (f *FileOperations) UnregisterStorageNodeContext(ctx context.Context, nodeDID string, signing *FileSigningOptions) error
UnregisterStorageNodeContext is UnregisterStorageNode, stopping when ctx ends.
func (*FileOperations) Upload ¶
func (f *FileOperations) Upload(subgroveID, fileKey, filename string, data []byte, storageNodeEndpoint string, signing *FileSigningOptions) (*FileManifest, error)
Upload uploads a file to a FileStorage subgrove: it sends the file's manifest as a StoreFileManifest transaction signed with signing, then its chunks to the storage node. signing must name the owner (OwnerDID) and carry a SignFunc: without them Upload sends nothing and returns a validation error, as the chain refuses a manifest with no owner or signature. A manifest that fails to submit returns a *WriteError (see FileSigningOptions.Nonce). Once the manifest's transaction is accepted, a chunk the storage node doesn't store (an answer other than 2xx, or a failed request) stops the upload with a *ChunkUploadError, which carries the manifest, its transaction, and the chunk. Each request it sends times out as the client's do, after 30 s if the client's HTTP client has none; see UploadContext to bound the whole upload.
func (*FileOperations) UploadContext ¶
func (f *FileOperations) UploadContext(ctx context.Context, subgroveID, fileKey, filename string, data []byte, storageNodeEndpoint string, signing *FileSigningOptions) (*FileManifest, error)
UploadContext is Upload, stopping when ctx ends.
type FileSigningOptions ¶
type FileSigningOptions struct {
OwnerDID string
PublicKeyID string
SignFunc func(message []byte) (string, error) // returns hex-encoded signature
// Nonce is the transaction's nonce, which the signed message binds. Take
// it with Client.NextNonce(ctx, OwnerDID), so that it is free in the
// account's window and no other write from the client takes it while this
// one is in flight.
//
// A write that fails to submit returns a *WriteError naming the nonce.
// With MayLand set, its submission may have reached the node and may
// still land: to send it again, sign it under the same Nonce, so that
// whichever attempt lands first uses the nonce and the other is refused.
// Signed under a fresh nonce instead, both attempts can run. Once the
// nonce is used (the write landed, applied or refused in its block, or
// its error wraps ErrNonceUsed), read what the write wrote before signing
// it again under a fresh nonce.
Nonce uint64
}
FileSigningOptions provides transaction signing for file operations. When provided, the transaction will include a DID-authenticated signature.
type GraphQLError ¶
type GraphQLError struct {
Message string `json:"message"`
Locations []GraphQLLocation `json:"locations,omitempty"`
Path []interface{} `json:"path,omitempty"`
Extensions map[string]interface{} `json:"extensions,omitempty"`
}
GraphQLError represents a GraphQL error.
type GraphQLLocation ¶
GraphQLLocation represents a location in a GraphQL query.
type GraphQLQueryBuilder ¶
type GraphQLQueryBuilder struct {
// contains filtered or unexported fields
}
GraphQLQueryBuilder provides a fluent interface for building GraphQL queries.
func NewGraphQLQuery ¶
func NewGraphQLQuery(query string) *GraphQLQueryBuilder
NewGraphQLQuery creates a new GraphQL query builder.
func (*GraphQLQueryBuilder) Build ¶
func (b *GraphQLQueryBuilder) Build() *GraphQLRequest
Build returns the constructed GraphQLRequest.
func (*GraphQLQueryBuilder) IncludeProof ¶
func (b *GraphQLQueryBuilder) IncludeProof() *GraphQLQueryBuilder
IncludeProof asks for a proof. QueryUnverified asks for none whatever the request says; GraphQLQueryWithSource asks for one only when it is set, and returns it unverified.
func (*GraphQLQueryBuilder) OperationName ¶
func (b *GraphQLQueryBuilder) OperationName(name string) *GraphQLQueryBuilder
OperationName sets the operation name.
func (*GraphQLQueryBuilder) Variable ¶
func (b *GraphQLQueryBuilder) Variable(name string, value interface{}) *GraphQLQueryBuilder
Variable adds a variable to the query.
func (*GraphQLQueryBuilder) Variables ¶
func (b *GraphQLQueryBuilder) Variables(vars map[string]interface{}) *GraphQLQueryBuilder
Variables sets multiple variables.
type GraphQLRequest ¶
type GraphQLRequest struct {
Query string `json:"query"`
Variables map[string]interface{} `json:"variables,omitempty"`
OperationName string `json:"operation_name,omitempty"`
IncludeProof *bool `json:"include_proof,omitempty"`
}
GraphQLRequest represents a GraphQL query request.
type GraphQLResponse ¶
type GraphQLResponse struct {
Data json.RawMessage `json:"data,omitempty"`
Errors []GraphQLError `json:"errors,omitempty"`
// Proof is the answer's proof object as served, unverified and undecoded;
// an indexer's can be tens of MiB of JSON numbers, so decode it into typed
// fields, not interface{}.
Proof json.RawMessage `json:"proof,omitempty"`
}
GraphQLResponse represents a GraphQL query response.
Proof is the proof object the answer carries, as JSON, unverified (the SDK can't verify it; see IndexingOperations), or nil when it carries none.
func (*GraphQLResponse) UnmarshalJSON ¶
func (r *GraphQLResponse) UnmarshalJSON(b []byte) error
UnmarshalJSON reads a GraphQL answer, leaving Proof nil when the answer's proof is null or absent.
type HTTPError ¶
type HTTPError struct {
WillowError
StatusCode int
}
HTTPError represents an HTTP error with status code.
func NewHTTPError ¶
NewHTTPError creates a new HTTP error.
type HealthStatus ¶
type HealthStatus struct {
Status string `json:"status,omitempty"`
Timestamp string `json:"timestamp,omitempty"`
Checks map[string]interface{} `json:"checks,omitempty"`
Healthy bool `json:"healthy"`
Version string `json:"version"`
NodeID string `json:"node_id"`
Network string `json:"network"`
BlockHeight int64 `json:"block_height"`
SyncStatus string `json:"sync_status"`
}
HealthStatus represents the health status of a node. The API's /health answers with Status ("healthy", "degraded", or "unhealthy"), Timestamp, Version, and Checks; Healthy is set from Status.
type HistoricalQueryRequest ¶
type HistoricalQueryRequest struct {
Path [][]byte `json:"path"` // GroveDB path as byte arrays
Key []byte `json:"key,omitempty"` // Key to query (for single-key queries)
QueryType string `json:"query_type,omitempty"` // Query type: "get", "get_range", "get_path"
IncludeProof bool `json:"include_proof"` // Whether to include proof
}
HistoricalQueryRequest represents a request for historical checkpoint data. It is sent with Path and Key as arrays of byte values, and IncludeProof even when false (the API's default is true).
func (HistoricalQueryRequest) MarshalJSON ¶
func (r HistoricalQueryRequest) MarshalJSON() ([]byte, error)
MarshalJSON writes the request as the API reads it: Path and Key as arrays of byte values (a Vec<u8>), not base64.
type HistoricalQueryResponse ¶
type HistoricalQueryResponse struct {
Success bool `json:"success"`
ProviderDID string `json:"provider_did,omitempty"`
ProviderEndpoint string `json:"provider_endpoint,omitempty"`
StateRoot string `json:"state_root"` // Checkpoint state root, as the answer reports it (unverified)
BlockRange [2]uint64 `json:"block_range"` // Block range covered by the checkpoint
Data interface{} `json:"data"` // Query results from the indexer
Proof string `json:"proof,omitempty"` // Merkle proof (hex-encoded), unverified
CanReindex bool `json:"can_reindex"` // Whether data can be re-indexed
Error string `json:"error,omitempty"` // Error message if any
}
HistoricalQueryResponse represents the response from a historical query.
type Identity ¶
type Identity struct {
KeyPair *KeyPair
DidDocument *DidDocument
}
Identity represents a complete identity with key pair and DID document.
func IdentityFromPrivateKey ¶
func IdentityFromPrivateKey(algorithm SignatureAlgorithm, privateKeyHex string) (*Identity, error)
IdentityFromPrivateKey creates an identity from an existing private key.
func NewIdentity ¶
func NewIdentity(algorithm SignatureAlgorithm) (*Identity, error)
NewIdentity creates a new identity with the specified algorithm.
func (*Identity) PublicKeyID ¶
PublicKeyID returns the public key ID for this identity.
func (*Identity) SignRequest ¶
SignRequest signs a request in the server's older form and returns the authentication headers. The message is {METHOD}:{PATH}:{TIMESTAMP}, where PATH is the path alone: the server verifies the request's path without its query, so any query string in path is left out of the message (see LegacyRequestMessage).
This form proves the DID but carries none of its read rights (a Reader permission or a free-reader entry), and anyone who sees it can replay it for five minutes with any body. The Client signs every request to the API with SignRequestWithNonce instead.
func (*Identity) SignRequestWithNonce ¶
func (i *Identity) SignRequestWithNonce(method, pathAndQuery string, body []byte) (map[string]string, error)
SignRequestWithNonce signs a request with a one-time nonce over the whole request and returns the authentication headers, X-Nonce among them.
pathAndQuery is the request target exactly as the server receives it, query string included; body is the exact bytes sent (nil for none). The timestamp is now, and the server accepts it for 300 seconds. Each signature is accepted once, so sign every attempt of a retried request anew.
Only this form carries the DID's read rights: a Reader permission, or an entry on a priced subgrove's free-reader list.
type IndexDefinition ¶
type IndexDefinition struct {
Name string `json:"name"`
Fields []string `json:"fields"`
Type IndexType `json:"type"`
Unique bool `json:"unique,omitempty"`
}
IndexDefinition defines an index on a schema.
type IndexerInfo ¶
type IndexerInfo struct {
IndexerDID string `json:"indexer_did"`
Subgroves []string `json:"subgroves"`
// StakeAmount is in the smallest token unit (10^-18 WILL).
StakeAmount consensus.Uint128 `json:"stake_amount"`
// Endpoint is the monitoring / health endpoint (historically also used
// for queries).
Endpoint string `json:"endpoint"`
// QueryEndpoint is the preferred endpoint for client query traffic
// (GraphQL/SQL/historical). When empty, callers should fall back to
// Endpoint. See EffectiveQueryEndpoint.
QueryEndpoint string `json:"query_endpoint,omitempty"`
Status string `json:"status"`
PerformanceScore float64 `json:"performance_score"`
LastUpdate uint64 `json:"last_update"`
}
IndexerInfo represents information about an indexer node. Matches the validator's `GET /indexers` response shape.
func (*IndexerInfo) EffectiveQueryEndpoint ¶
func (i *IndexerInfo) EffectiveQueryEndpoint() string
EffectiveQueryEndpoint returns the URL clients should POST GraphQL/SQL queries to. Prefers QueryEndpoint when non-empty; falls back to Endpoint.
type Indexers ¶
type Indexers struct {
// contains filtered or unexported fields
}
Indexers is a discovery client for the validator's GET /indexers endpoint.
When the SDK is constructed with an explicit indexerURL, discovery is bypassed and a synthetic single-entry list is returned so the routing code path stays uniform.
func NewIndexers ¶
NewIndexers constructs a discovery client. Normally called by the WillowClient builder — consumers access it through client.Indexers().
func (*Indexers) ForSubgrove ¶
ForSubgrove returns active indexers serving subgroveID, sorted by PerformanceScore descending (best first).
With an explicit indexerURL override, always returns a single synthetic entry — the routing code doesn't need to special-case this.
func (*Indexers) HasExplicitOverride ¶
HasExplicitOverride reports whether an explicit indexer URL was provided (in which case discovery is skipped).
func (*Indexers) Invalidate ¶
func (d *Indexers) Invalidate()
Invalidate forces the next List to re-fetch from the validator.
type IndexingOperations ¶
type IndexingOperations struct {
// contains filtered or unexported fields
}
IndexingOperations provides methods for blockchain indexing and GraphQL queries.
No GraphQL or SQL answer is verified: the SDK can't bind an indexer's or the API's answer to the chain's state (it verifies no CometBFT header, and no proof ties the answer's rows to a root), so every query method returns the answer as it comes.
func (*IndexingOperations) Execute ¶
func (i *IndexingOperations) Execute(ctx context.Context, subgroveID, query string, variables map[string]interface{}) (*GraphQLResponse, error)
Execute sends a GraphQL query with its variables, unverified: it is QueryUnverified with a request built from them.
func (*IndexingOperations) ExecuteWithResult ¶
func (i *IndexingOperations) ExecuteWithResult(ctx context.Context, subgroveID, query string, variables map[string]interface{}, result interface{}) error
ExecuteWithResult sends a query unverified (see Execute) and unmarshals its data into result.
func (*IndexingOperations) GetIndexer ¶
func (i *IndexingOperations) GetIndexer(ctx context.Context, indexerID string) (*IndexerInfo, error)
GetIndexer retrieves information about a specific indexer.
func (*IndexingOperations) GetIndexerStatus
deprecated
func (i *IndexingOperations) GetIndexerStatus(ctx context.Context, indexerID, subgroveID string) (*IndexerInfo, error)
GetIndexerStatus returns an unsupported-operation error and sends nothing: the API serves no per-subgrove indexer status route. GetIndexer reads an indexer, with the subgroves it serves and its status.
Deprecated: GetIndexerStatus always fails; use GetIndexer.
func (*IndexingOperations) GetSubgrove ¶
func (i *IndexingOperations) GetSubgrove(ctx context.Context, subgroveID string) (*SubgroveInfo, error)
GetSubgrove retrieves information about a specific subgrove.
func (*IndexingOperations) GraphQLQueryWithSource ¶
func (i *IndexingOperations) GraphQLQueryWithSource( ctx context.Context, subgroveID string, req *GraphQLRequest, source QuerySource, ) (*RoutedQueryResult[*GraphQLResponse], error)
GraphQLQueryWithSource executes a GraphQL query with explicit source selection and returns the answer unverified. It asks for no proof (include_proof false) unless req sets IncludeProof; a proof asked for is returned, unverified, as the answer's JSON in GraphQLResponse.Proof. req isn't changed.
Callers choose the backend via QuerySource:
- QuerySourceValidator: the API, which serves the chain-tip state. Returns a *ValidatorHasNoDataError for VerifyOnly subgroves.
- QuerySourceIndexer: historical/analytics via an indexer. Returns a *NoIndexersReachableError if none are reachable.
- QuerySourceAuto (default): indexer if one serves this subgrove, else validator. On indexer failure, falls back to validator with Fallback=true in the returned result, except when an indexer's answer was refused for its size (ErrAnswerTooLarge): that error is returned.
It tries at most the three best-scored indexers serving the subgrove.
func (*IndexingOperations) ListIndexers ¶
func (i *IndexingOperations) ListIndexers(ctx context.Context) ([]IndexerInfo, error)
ListIndexers retrieves all indexers.
func (*IndexingOperations) ListSubgroves ¶
func (i *IndexingOperations) ListSubgroves(ctx context.Context) ([]SubgroveInfo, error)
ListSubgroves retrieves all available subgroves.
func (*IndexingOperations) Query
deprecated
func (i *IndexingOperations) Query(ctx context.Context, subgroveID string, req *GraphQLRequest) (*GraphQLResponse, error)
Query returns an unsupported-operation error and sends nothing.
Verifying a GraphQL answer takes a proof that binds the returned data to a state root, and that root checked against a CometBFT header verified by the validators' commit signatures. The answer's proof doesn't bind its data, and this SDK verifies no header (see the lightclient package), so it doesn't present a GraphQL answer as verified. QueryUnverified sends the query and returns its answer unverified.
Deprecated: Query always fails; use QueryUnverified, which returns the answer unverified.
func (*IndexingOperations) QueryUnverified ¶
func (i *IndexingOperations) QueryUnverified(ctx context.Context, subgroveID string, req *GraphQLRequest) (*GraphQLResponse, error)
QueryUnverified sends a GraphQL query asking for no proof (include_proof false) and returns the answer as it comes, unverified. With an indexer URL set (WithIndexerURL) the query goes to that indexer; otherwise to the API, signed by the client's identity when one is set. req isn't changed.
An indexer that doesn't serve the subgrove answers with empty data, not an error; a DataStorage subgrove is served by the API alone. With an indexer URL set, query one with GraphQLQueryWithSource and QuerySourceValidator.
func (*IndexingOperations) SqlQuery ¶
func (i *IndexingOperations) SqlQuery(ctx context.Context, subgroveID, query string, includeProof bool) (*SqlResponse, error)
SqlQuery executes a SQL query against a subgrove and returns the answer (and, with includeProof, its proof) unverified. An indexer attaches a proof of every row whatever includeProof says. When an indexer URL is configured, the query is routed there.
func (*IndexingOperations) SqlQueryWithSource ¶
func (i *IndexingOperations) SqlQueryWithSource( ctx context.Context, subgroveID, query string, includeProof bool, source QuerySource, ) (*RoutedQueryResult[*SqlResponse], error)
SqlQueryWithSource executes a SQL query with explicit source selection and returns the answer (and any proof it carries) unverified.
See GraphQLQueryWithSource for source semantics.
type InsufficientFundsError ¶
type InsufficientFundsError struct {
TransactionError
Required uint64
Available uint64
}
InsufficientFundsError represents an insufficient funds error.
func NewInsufficientFundsError ¶
func NewInsufficientFundsError(required, available uint64) *InsufficientFundsError
NewInsufficientFundsError creates a new insufficient funds error.
type KeyPair ¶
type KeyPair struct {
Algorithm SignatureAlgorithm
PublicKey []byte
PrivateKey []byte
}
KeyPair represents a cryptographic key pair.
func GenerateKeyPair ¶
func GenerateKeyPair(algorithm SignatureAlgorithm) (*KeyPair, error)
GenerateKeyPair generates a new key pair for the specified algorithm.
func KeyPairFromPrivateKey ¶
func KeyPairFromPrivateKey(algorithm SignatureAlgorithm, privateKeyHex string) (*KeyPair, error)
KeyPairFromPrivateKey creates a KeyPair from an existing private key.
func (*KeyPair) PrivateKeyHex ¶
PrivateKeyHex returns the hex-encoded private key.
func (*KeyPair) PublicKeyHex ¶
PublicKeyHex returns the hex-encoded public key.
type Log ¶
Log is a filter-matched event log as served by the indexer. Only the consensus-derivable, root-bound fields are bound by the commitment.
type ManifestValidationError ¶
ManifestValidationError carries a field path so callers can attribute validation failures.
func (*ManifestValidationError) Error ¶
func (e *ManifestValidationError) Error() string
type MerkleProofData ¶
type MerkleProofData struct {
Key string `json:"key"`
ValueHash []byte `json:"value_hash"`
Siblings [][]byte `json:"siblings"`
Path string `json:"path"`
}
MerkleProofData contains a single Merkle proof
type NoIndexersReachableError ¶
NoIndexersReachableError is returned when QuerySourceIndexer was requested but either no indexer serves the subgrove or every candidate failed. Errs holds each candidate's error, in the order they were tried; errors.Is and errors.As look through them.
func (*NoIndexersReachableError) Error ¶
func (e *NoIndexersReachableError) Error() string
func (*NoIndexersReachableError) Unwrap ¶
func (e *NoIndexersReachableError) Unwrap() []error
Unwrap returns Errs.
type Permission ¶
type Permission struct {
Did string `json:"did"`
SubgroveID string `json:"subgrove_id,omitempty"`
// Role is the subgrove role granted, in lowercase (for example "reader").
Role string `json:"role,omitempty"`
Actions []string `json:"actions"`
GrantedBy string `json:"granted_by"`
GrantedAt int64 `json:"granted_at"`
ExpiresAt *int64 `json:"expires_at,omitempty"`
}
Permission represents a permission entry.
type PrivacyConfig ¶
type PrivacyConfig = consensus.PrivacyConfig
PrivacyConfig contains privacy configuration for a private subgrove (see consensus.PrivacyConfig).
type PrivacyOperations ¶
type PrivacyOperations struct {
// contains filtered or unexported fields
}
PrivacyOperations provides methods for managing private subgroves, including key grant management and key rotation.
func (*PrivacyOperations) GetKeyGrantProof ¶
func (p *PrivacyOperations) GetKeyGrantProof(ctx context.Context, subgroveID, did string) (json.RawMessage, error)
GetKeyGrantProof retrieves the GroveDB Merkle proof for a key grant: the data of the API's answer, {"proof": <hex>, "subgrove_id": ..., "grantee_did": ...}.
func (*PrivacyOperations) GetMyKeyGrant ¶
func (p *PrivacyOperations) GetMyKeyGrant(ctx context.Context, subgroveID string) (*EncryptedKeyGrant, error)
GetMyKeyGrant retrieves the encryption key grant for the authenticated DID, allowing it to decrypt the subgrove's data.
func (*PrivacyOperations) GrantSubgroveKey ¶
func (p *PrivacyOperations) GrantSubgroveKey(ctx context.Context, subgroveID string, grant EncryptedKeyGrant, opts ...WriteOption) (*WriteResult, error)
GrantSubgroveKey broadcasts a GrantSubgroveKey transaction, granting the specified DID access to the subgrove's encryption key. It is signed over FormatGrantSubgroveKeyMessage, which binds every field of the grant and the transaction's nonce (see Client.NextNonce). A grantee that isn't a DID is a validation error, and nothing is sent. It returns once CheckTx accepts the transaction, with the nonce and transaction hash.
func (*PrivacyOperations) ListKeyGrantees ¶
func (p *PrivacyOperations) ListKeyGrantees(ctx context.Context, subgroveID string) ([]string, error)
ListKeyGrantees retrieves the list of DIDs that have been granted access to a subgrove's encryption key. Only the subgrove owner or admin can call this.
func (*PrivacyOperations) RevokeSubgroveKey ¶
func (p *PrivacyOperations) RevokeSubgroveKey(ctx context.Context, subgroveID, revokeeDID string, opts ...WriteOption) (*WriteResult, error)
RevokeSubgroveKey broadcasts a RevokeSubgroveKey transaction, revoking the specified DID's access to the subgrove's encryption key. It is signed over "RevokeSubgroveKey:<subgroveID>:<revokeeDID>:<senderDID>:<nonce>". A subgrove id holding ':', or a revokee that isn't a DID, is a validation error, as the chain refuses it, and nothing is sent. It returns once CheckTx accepts the transaction, with the nonce and transaction hash.
func (*PrivacyOperations) RotateSubgroveKey ¶
func (p *PrivacyOperations) RotateSubgroveKey(ctx context.Context, subgroveID string, newEpoch uint32, newGrants []EncryptedKeyGrant, opts ...WriteOption) (*WriteResult, error)
RotateSubgroveKey broadcasts a RotateSubgroveKey transaction, rotating the subgrove encryption key to a new epoch and re-granting access to the specified DIDs with newly encrypted keys. It is signed over FormatRotateSubgroveKeyMessage, which binds every grant, their order and count, and the transaction's nonce. No grants, a grant whose KeyEpoch isn't newEpoch, or a grant whose grantee isn't a DID is a validation error, as the chain refuses it, and nothing is sent. It returns once CheckTx accepts the transaction, with the nonce and transaction hash.
type PublicKey ¶
type PublicKey struct {
ID string `json:"id"`
Type string `json:"type"`
PublicKeyHex string `json:"public_key_hex,omitempty"`
}
PublicKey represents a public key in a DID document.
type QueryBuilder ¶
type QueryBuilder struct {
// contains filtered or unexported fields
}
QueryBuilder provides a fluent interface for building queries.
func NewQueryBuilder ¶
func NewQueryBuilder() *QueryBuilder
NewQueryBuilder creates a new QueryBuilder.
func (*QueryBuilder) Build ¶
func (qb *QueryBuilder) Build() *QueryRequest
Build returns the constructed QueryRequest.
func (*QueryBuilder) Contains ¶
func (qb *QueryBuilder) Contains(field string, value interface{}) *QueryBuilder
Contains adds a contains filter.
func (*QueryBuilder) Equals ¶
func (qb *QueryBuilder) Equals(field string, value interface{}) *QueryBuilder
Equals adds an equality filter.
func (*QueryBuilder) Filter ¶
func (qb *QueryBuilder) Filter(field, operator string, value interface{}) *QueryBuilder
Filter adds a filter condition.
func (*QueryBuilder) GreaterThan ¶
func (qb *QueryBuilder) GreaterThan(field string, value interface{}) *QueryBuilder
GreaterThan adds a greater-than filter.
func (*QueryBuilder) GreaterThanOrEqual ¶
func (qb *QueryBuilder) GreaterThanOrEqual(field string, value interface{}) *QueryBuilder
GreaterThanOrEqual adds a greater-than-or-equal filter.
func (*QueryBuilder) In ¶
func (qb *QueryBuilder) In(field string, values []interface{}) *QueryBuilder
In adds an in filter.
func (*QueryBuilder) IncludeProof ¶
func (qb *QueryBuilder) IncludeProof() *QueryBuilder
IncludeProof enables proof inclusion.
func (*QueryBuilder) LessThan ¶
func (qb *QueryBuilder) LessThan(field string, value interface{}) *QueryBuilder
LessThan adds a less-than filter.
func (*QueryBuilder) LessThanOrEqual ¶
func (qb *QueryBuilder) LessThanOrEqual(field string, value interface{}) *QueryBuilder
LessThanOrEqual adds a less-than-or-equal filter.
func (*QueryBuilder) Limit ¶
func (qb *QueryBuilder) Limit(limit int) *QueryBuilder
Limit sets the maximum number of results.
func (*QueryBuilder) NotEquals ¶
func (qb *QueryBuilder) NotEquals(field string, value interface{}) *QueryBuilder
NotEquals adds a not-equals filter.
func (*QueryBuilder) Offset ¶
func (qb *QueryBuilder) Offset(offset int) *QueryBuilder
Offset sets the result offset.
func (*QueryBuilder) Search ¶
func (qb *QueryBuilder) Search(fields []string, query string) *QueryBuilder
Search adds a full-text search.
func (*QueryBuilder) SortAsc ¶
func (qb *QueryBuilder) SortAsc(field string) *QueryBuilder
SortAsc adds ascending sort.
func (*QueryBuilder) SortDesc ¶
func (qb *QueryBuilder) SortDesc(field string) *QueryBuilder
SortDesc adds descending sort.
type QueryFilter ¶
type QueryFilter struct {
Field string `json:"field"`
Operator string `json:"operator"`
Value interface{} `json:"value"`
}
QueryFilter represents a filter condition for queries.
type QueryProof ¶
type QueryProof struct {
MerkleProofs []MerkleProofData `json:"merkle_proofs"`
StateRoot []byte `json:"state_root"`
BlockHeight uint64 `json:"block_height"`
EthereumAnchor *EthereumAnchor `json:"ethereum_anchor,omitempty"`
}
QueryProof is the Merkle proof data a SQL answer carries, returned unverified (see IndexingOperations).
type QueryRequest ¶
type QueryRequest struct {
Filters []QueryFilter `json:"filters,omitempty"`
Search *QuerySearch `json:"search,omitempty"`
Sort *QuerySort `json:"sort,omitempty"`
Limit int `json:"limit,omitempty"`
Offset int `json:"offset,omitempty"`
IncludeProof *bool `json:"include_proof,omitempty"`
}
QueryRequest represents a query request.
type QueryResponse ¶
type QueryResponse struct {
Results []QueryResult `json:"results"`
TotalCount int `json:"total_count"`
HasMore bool `json:"has_more"`
Proof []byte `json:"proof,omitempty"`
// Height is the block height the proof was generated at.
Height uint64 `json:"height,omitempty"`
}
QueryResponse represents the response to a query.
func ApplyComputedFieldsToResponse ¶
func ApplyComputedFieldsToResponse(response *QueryResponse, fields ComputedFieldSet) *QueryResponse
ApplyComputedFieldsToResponse applies computed fields to a query response. Returns a new response with computed fields added to all results.
type QueryResult ¶
QueryResult represents a single result from a query. The API's /query answers with the matching documents alone, so Key is empty for its results.
type QuerySearch ¶
QuerySearch represents full-text search options.
type QuerySource ¶
type QuerySource int
QuerySource tells the routing layer where to send a query. Whichever backend answers, the answer is returned unverified.
- QuerySourceValidator: the API, which serves the chain-tip state. Fails fast for VerifyOnly subgroves.
- QuerySourceIndexer: full history + analytics via an indexer.
- QuerySourceAuto (default): indexer if one serves this subgrove, else validator. Sets Fallback=true when it falls back.
const ( QuerySourceAuto QuerySource = iota QuerySourceValidator QuerySourceIndexer )
type RegisterSubgroveRequest ¶
type RegisterSubgroveRequest struct {
SubgroveID string `json:"subgrove_id"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
Schema SchemaDefinition `json:"schema"`
OwnerDid string `json:"owner_did"`
Writers []string `json:"writers,omitempty"`
Readers []string `json:"readers,omitempty"`
RewardRate uint64 `json:"reward_rate,omitempty"`
}
RegisterSubgroveRequest represents a request to register a new subgrove.
type RegistrationOperations ¶
type RegistrationOperations struct {
// contains filtered or unexported fields
}
RegistrationOperations provides methods for subgrove registration.
func (*RegistrationOperations) DeleteSubgrove ¶
func (r *RegistrationOperations) DeleteSubgrove(ctx context.Context, subgroveID string, opts ...WriteOption) (*WriteResult, error)
DeleteSubgrove deregisters a subgrove owned by the client's identity by sending a signed DeregisterSubgrove transaction to POST /tx/submit (see consensus.DeregisterSubgroveSignMessage); the chain refunds its remaining balance to the owner. It returns once CheckTx accepts the transaction, with the nonce and transaction hash.
func (*RegistrationOperations) GetPermissions ¶
func (r *RegistrationOperations) GetPermissions(ctx context.Context, did string) ([]Permission, error)
GetPermissions retrieves permissions for a DID.
func (*RegistrationOperations) GetSubgrove ¶
func (r *RegistrationOperations) GetSubgrove(ctx context.Context, subgroveID string) (*SubgroveRegistration, error)
GetSubgrove retrieves information about a subgrove. The API's /subgroves/{id} answers with the subgrove's id, name, and owner (and its status), so only those fields are set; ListSubgroves carries whole registrations, with the schema, writers, and free readers.
func (*RegistrationOperations) GrantPermission
deprecated
func (r *RegistrationOperations) GrantPermission(ctx context.Context, permission *Permission) error
GrantPermission returns an unsupported-operation error and sends nothing: the API serves no permission write route. A subgrove's permissions (its owner, admins, writers, and readers) are written by its RegisterSubgrove transaction (see RegisterSubgrove).
Deprecated: GrantPermission always fails; name a subgrove's writers and readers when RegisterSubgrove registers it (RegisterSubgroveRequest's Writers and Readers), or its admins in a consensus.RegisterSubgroveTx you build.
func (*RegistrationOperations) ListSubgroves ¶
func (r *RegistrationOperations) ListSubgroves(ctx context.Context) ([]SubgroveRegistration, error)
ListSubgroves lists all subgroves.
func (*RegistrationOperations) RegisterSubgrove ¶
func (r *RegistrationOperations) RegisterSubgrove(ctx context.Context, req *RegisterSubgroveRequest, opts ...WriteOption) (*WriteResult, error)
RegisterSubgrove registers a DataStorage subgrove owned by the client's identity, by sending a signed consensus.RegisterSubgroveTx, tx, to POST /tx/submit in the body {"RegisterSubgrove": tx}, the form /tx/submit takes a transaction in.
The transaction carries req's SubgroveID, Name, and Description, its Schema in the chain's form (SchemaDefinition.ChainSchemaJSON), and a DataStorage mode named Name whose writers are Writers and whose free readers are Readers. Every other field is sent with its default: no admins, funding, TEE requirement, read pricing, privacy, or template. It is signed over FormatRegisterSubgroveMessage, which binds all of them and the nonce (see Client.NextNonce). For another mode or those fields, build a consensus.RegisterSubgroveTx, sign FormatRegisterSubgroveMessage, and send it in the same body with consensus.Client.BroadcastTxSync: BroadcastTxSync(ctx, map[string]interface{}{"RegisterSubgrove": tx}).
OwnerDid, when set, must be the identity's DID, and RewardRate must be 0: a DataStorage registration has no reward rate. SubgroveID must be 1 to 64 ASCII letters, digits, '-', or '_', starting with a letter or digit, Writers and Readers must be DIDs, and the schema must declare no indexes, as the chain requires. It returns once the chain's CheckTx accepts the transaction, with the nonce and transaction hash; the subgrove exists once the transaction lands (see Client.WaitUntilLanded) and is applied in its block. WithNonce sends it again under an earlier attempt's nonce.
func (*RegistrationOperations) RevokePermission
deprecated
func (r *RegistrationOperations) RevokePermission(ctx context.Context, did, subgroveID string) error
RevokePermission returns an unsupported-operation error and sends nothing: the API serves no permission write route. A subgrove's permissions are written by its RegisterSubgrove transaction (see RegisterSubgrove).
Deprecated: RevokePermission always fails, and this SDK has no replacement: a subgrove's permissions are set by the transaction that registers it (see RegisterSubgrove).
func (*RegistrationOperations) UpdateSubgrove
deprecated
func (r *RegistrationOperations) UpdateSubgrove(ctx context.Context, subgroveID string, updates map[string]interface{}) (*SubgroveRegistration, error)
UpdateSubgrove returns an unsupported-operation error and sends nothing: the API serves no subgrove update route. A subgrove is changed by UpdateSubgroveReadPricing, UpdateSubgroveFreeReaders, or ReplaceSubgrove transactions sent to POST /tx/submit, which this SDK does not build.
Deprecated: UpdateSubgrove always fails, and this SDK has no replacement: it builds none of the transactions that change a subgrove.
type RetryConfig ¶
type RetryConfig struct {
MaxRetries int
InitialBackoff time.Duration
MaxBackoff time.Duration
BackoffFactor float64
}
RetryConfig contains configuration for retry behavior.
func DefaultRetryConfig ¶
func DefaultRetryConfig() RetryConfig
DefaultRetryConfig returns the default retry configuration.
type RoutedQueryResult ¶
type RoutedQueryResult[T any] struct { Result T Source ServedBy IndexerDID string // Empty when Source == ServedByValidator Fallback bool // True when Auto routing fell back from indexer to validator }
RoutedQueryResult wraps a query response with routing metadata.
Callers get back both the raw result and an explicit tag identifying which backend served it — useful for UIs that want to display the trust model.
type SchemaBuilder ¶
type SchemaBuilder struct {
// contains filtered or unexported fields
}
SchemaBuilder provides a fluent interface for building schema definitions.
func NewSchemaBuilder ¶
func NewSchemaBuilder(name string) *SchemaBuilder
NewSchemaBuilder creates a new SchemaBuilder.
func (*SchemaBuilder) ArrayField ¶
func (b *SchemaBuilder) ArrayField(name string, itemType string, required bool) *SchemaBuilder
ArrayField adds an array field with item type.
func (*SchemaBuilder) BoolField ¶
func (b *SchemaBuilder) BoolField(name string, required bool) *SchemaBuilder
BoolField adds a boolean field.
func (*SchemaBuilder) Build ¶
func (b *SchemaBuilder) Build() *SchemaDefinition
Build returns the constructed SchemaDefinition.
func (*SchemaBuilder) Description ¶
func (b *SchemaBuilder) Description(desc string) *SchemaBuilder
Description sets the schema description.
func (*SchemaBuilder) Field ¶
func (b *SchemaBuilder) Field(name, fieldType string, required, indexed bool) *SchemaBuilder
Field adds a field to the schema. The chain doesn't support schema indexes, so ChainSchemaJSON (and RegisterSubgrove) refuse a field added with indexed true.
func (*SchemaBuilder) FloatField ¶
func (b *SchemaBuilder) FloatField(name string, required bool) *SchemaBuilder
FloatField adds a float field.
func (*SchemaBuilder) FullTextIndex ¶
func (b *SchemaBuilder) FullTextIndex(name string, fields []string) *SchemaBuilder
FullTextIndex adds a full-text index.
func (*SchemaBuilder) HashIndex ¶
func (b *SchemaBuilder) HashIndex(name string, fields []string) *SchemaBuilder
HashIndex adds a hash index.
func (*SchemaBuilder) Index ¶
func (b *SchemaBuilder) Index(name string, fields []string, indexType IndexType, unique bool) *SchemaBuilder
Index adds an index to the schema. The chain doesn't support schema indexes, so ChainSchemaJSON (and RegisterSubgrove) refuse a schema with one; this and the other index methods describe a schema this SDK can't register.
func (*SchemaBuilder) IntField ¶
func (b *SchemaBuilder) IntField(name string, required bool) *SchemaBuilder
IntField adds an integer field.
func (*SchemaBuilder) ObjectField ¶
func (b *SchemaBuilder) ObjectField(name string, required bool) *SchemaBuilder
ObjectField adds an object field.
func (*SchemaBuilder) RangeIndex ¶
func (b *SchemaBuilder) RangeIndex(name string, fields []string) *SchemaBuilder
RangeIndex adds a range index.
func (*SchemaBuilder) StringField ¶
func (b *SchemaBuilder) StringField(name string, required bool) *SchemaBuilder
StringField adds a string field.
func (*SchemaBuilder) UniqueIndex ¶
func (b *SchemaBuilder) UniqueIndex(name string, fields []string) *SchemaBuilder
UniqueIndex adds a unique index.
type SchemaDefinition ¶
type SchemaDefinition struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Fields []SchemaField `json:"fields"`
Indexes []IndexDefinition `json:"indexes,omitempty"`
}
SchemaDefinition defines the schema for a subgrove.
func (SchemaDefinition) ChainSchemaJSON ¶
func (s SchemaDefinition) ChainSchemaJSON() (string, error)
ChainSchemaJSON returns the schema as the JSON text a RegisterSubgrove transaction carries:
{"version":1,"fields":{"<name>":"<type>",...},"indexes":[],"required_fields":[...]}
Field types map to the chain's: string; int, integer, float, and number to number; bool and boolean to boolean; array and array:<item> to array; object; bytes. Another type is refused. Required fields go in required_fields.
The chain refuses a DataStorage or FileStorage registration whose schema declares indexes, so a schema with an index (Indexes, or a field marked Indexed) is refused. The chain's schema has no name or description; those label the schema in this SDK and are not sent.
func (*SchemaDefinition) UnmarshalJSON ¶
func (s *SchemaDefinition) UnmarshalJSON(data []byte) error
UnmarshalJSON reads a schema in this SDK's form (fields as a list) or in the chain's (fields as a map of name to type, with required_fields), which is how the API lists registered subgroves. Read from the chain's form, fields are sorted by name.
type SchemaField ¶
type SchemaField struct {
Name string `json:"name"`
Type string `json:"type"`
Required bool `json:"required,omitempty"`
Indexed bool `json:"indexed,omitempty"`
}
SchemaField defines a field in a schema.
type SignatureAlgorithm ¶
type SignatureAlgorithm string
SignatureAlgorithm represents the cryptographic algorithm used for signatures.
const ( // Ed25519 is the Ed25519 signature algorithm. Ed25519 SignatureAlgorithm = "Ed25519" // Secp256k1 is the secp256k1 signature algorithm. Secp256k1 SignatureAlgorithm = "secp256k1" )
func (SignatureAlgorithm) KeyType ¶
func (a SignatureAlgorithm) KeyType() string
KeyType returns the DID key type string for this algorithm.
type SolanaDataSource ¶
type SolanaDataSource struct {
Name string `json:"name"`
Network SupportedChain `json:"network"`
ProgramID string `json:"program_id"` // base58-encoded 32-byte pubkey
StartSlot uint64 `json:"start_slot"`
Instructions []string `json:"instructions"` // each 0x + even hex chars (>= 2)
}
SolanaDataSource is one indexed Solana program within a manifest.
type SqlRequest ¶
type SqlRequest struct {
Query string `json:"query"`
IncludeProof *bool `json:"include_proof,omitempty"`
}
SqlRequest represents a SQL query request
type SqlResponse ¶
type SqlResponse struct {
Columns []string `json:"columns"`
Rows [][]interface{} `json:"rows"`
Total *uint64 `json:"total,omitempty"`
Warnings []string `json:"warnings,omitempty"`
Proof *QueryProof `json:"proof,omitempty"`
}
SqlResponse represents the response from a SQL query
type StateVerifyMode
deprecated
type StateVerifyMode = EthProofMode
StateVerifyMode is EthProofMode.
Deprecated: no mode verifies a read against Ethereum; use EthProofMode.
type StoreRequest ¶
type StoreRequest struct {
Key string `json:"key,omitempty"`
Data map[string]interface{} `json:"data"`
}
StoreRequest represents a request to store data.
type SubgroveBuilder ¶
type SubgroveBuilder struct {
// contains filtered or unexported fields
}
SubgroveBuilder provides a fluent interface for building subgrove registrations.
func NewSubgroveBuilder ¶
func NewSubgroveBuilder(subgroveID, name string) *SubgroveBuilder
NewSubgroveBuilder creates a new SubgroveBuilder.
func (*SubgroveBuilder) AddReader ¶
func (b *SubgroveBuilder) AddReader(did string) *SubgroveBuilder
AddReader adds a reader DID.
func (*SubgroveBuilder) AddWriter ¶
func (b *SubgroveBuilder) AddWriter(did string) *SubgroveBuilder
AddWriter adds a writer DID.
func (*SubgroveBuilder) Build ¶
func (b *SubgroveBuilder) Build() *RegisterSubgroveRequest
Build returns the constructed RegisterSubgroveRequest.
func (*SubgroveBuilder) Description ¶
func (b *SubgroveBuilder) Description(desc string) *SubgroveBuilder
Description sets the subgrove description.
func (*SubgroveBuilder) Owner ¶
func (b *SubgroveBuilder) Owner(did string) *SubgroveBuilder
Owner sets the owner DID.
func (*SubgroveBuilder) Readers ¶
func (b *SubgroveBuilder) Readers(dids []string) *SubgroveBuilder
Readers sets the reader DIDs.
func (*SubgroveBuilder) RewardRate ¶
func (b *SubgroveBuilder) RewardRate(rate uint64) *SubgroveBuilder
RewardRate sets the reward rate for indexers.
func (*SubgroveBuilder) Schema ¶
func (b *SubgroveBuilder) Schema(schema SchemaDefinition) *SubgroveBuilder
Schema sets the schema definition.
func (*SubgroveBuilder) Writers ¶
func (b *SubgroveBuilder) Writers(dids []string) *SubgroveBuilder
Writers sets the writer DIDs.
type SubgroveInfo ¶
type SubgroveInfo struct {
SubgroveID string `json:"subgrove_id"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
OwnerDid string `json:"owner_did"`
// Mode is DataStorage or BlockchainIndexing.
Mode string `json:"mode,omitempty"`
// Chain is the canonical id of the chain an indexing subgrove indexes.
Chain string `json:"chain,omitempty"`
IndexerCount int `json:"indexer_count,omitempty"`
Status string `json:"status,omitempty"`
// LatestBlock is the latest indexed source-chain block, 0 before any.
LatestBlock uint64 `json:"latest_block,omitempty"`
// DeploymentBlock is the Willow height the subgrove was registered at.
DeploymentBlock uint64 `json:"deployment_block,omitempty"`
Indexers []string `json:"indexers,omitempty"`
}
SubgroveInfo is a subgrove as the API's /subgroves routes answer. The list (ListSubgroves) carries its registration with Mode, Chain, and IndexerCount; one subgrove (GetSubgrove) carries Status, LatestBlock, DeploymentBlock, Indexers, and Chain.
type SubgroveRegistration ¶
type SubgroveRegistration struct {
SubgroveID string `json:"subgrove_id"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
Schema SchemaDefinition `json:"schema"`
OwnerDid string `json:"owner_did"`
Writers []string `json:"writers,omitempty"`
Readers []string `json:"free_readers,omitempty"`
RewardRate uint64 `json:"reward_rate,omitempty"`
ItemCount uint64 `json:"item_count"`
StorageUsed uint64 `json:"storage_used"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
}
SubgroveRegistration represents a registered subgrove.
type SubscribeOptions ¶
type SubscribeOptions struct {
// Variables passes GraphQL variables into the subscribe payload.
Variables map[string]any
// OperationName sets the GraphQL operation name (when the query
// contains multiple).
OperationName string
// ConnectionPayload is forwarded on the `connection_init` frame
// (e.g., auth tokens).
ConnectionPayload map[string]any
// Source picks which backend to connect to. Defaults to
// SubscribeSourceValidator.
Source SubscribeSource
// Reconnect enables automatic reconnect on unexpected disconnect.
// Nil means the SDK default (reconnect enabled). To opt out
// explicitly, pass BoolPtr(false).
//
// Reconnection is reconnect-only: messages that were in flight when
// the socket dropped are not replayed, and the new connection may
// redeliver events the old one already emitted. Callers that need
// exactly-once should dedupe by a stable field (e.g., block number
// or entity id) themselves.
Reconnect *bool
// MaxReconnectAttempts caps the number of consecutive reconnect
// attempts. Zero means retry forever. The counter resets only after
// a reconnection delivers at least one real payload — this avoids an
// infinite loop against a server that accepts the subscription but
// immediately drops the socket.
MaxReconnectAttempts int
// ReconnectBackoff is the initial reconnect delay; it doubles on
// each consecutive failure up to MaxReconnectBackoff. Zero means
// 500 ms.
ReconnectBackoff time.Duration
// MaxReconnectBackoff caps the reconnect delay. Zero means 30 s.
MaxReconnectBackoff time.Duration
// OnReconnect is called when a reconnect attempt is scheduled.
// attempt is 1-indexed; delay is the backoff we'll sleep before
// trying. Callback errors are ignored.
OnReconnect func(attempt int, delay time.Duration)
}
SubscribeOptions is the optional argument bag for Subscribe.
Auto-reconnect is on by default. To opt out explicitly, set Reconnect to a pointer to false (see BoolPtr). On unexpected disconnect the SDK applies exponential backoff and for SubscribeSourceIndexer re-resolves a different indexer via discovery.
type SubscribeSource ¶
type SubscribeSource int
SubscribeSource tells the SDK which backend to open the subscription WebSocket against.
- SubscribeSourceValidator (default): {apiURL}/graphql/ws, the API's chain-tip events (BlockFinalized), delivered unverified.
- SubscribeSourceIndexer: selected via discovery (or the explicit indexerURL override), for `VerifyOnly` subgroves or caller-driven indexer-side tails.
const ( SubscribeSourceValidator SubscribeSource = iota SubscribeSourceIndexer )
type Subscription ¶
type Subscription struct {
// Events emits server `next` payloads. Closed when the subscription
// ends. Err() after close tells you why.
Events <-chan SubscriptionPayload
// contains filtered or unexported fields
}
Subscription exposes an incoming stream of SubscriptionPayloads via its Events channel. Reconnects are transparent: the channel stays open across transient drops and only closes when the subscription is definitively over (server `complete`, caller Unsubscribe, reconnect disabled + socket drop, or MaxReconnectAttempts exhausted).
func (*Subscription) Done ¶
func (s *Subscription) Done() <-chan struct{}
Done is closed when the subscription has fully terminated.
func (*Subscription) Err ¶
func (s *Subscription) Err() error
Err returns the error that terminated the subscription, or nil if it was a clean completion or Unsubscribe. Safe to call after <-Done().
func (*Subscription) Unsubscribe ¶
func (s *Subscription) Unsubscribe(ctx context.Context) error
Unsubscribe cancels the subscription. The loop will send `complete` to the current server and close the socket on its way out. Safe to call more than once.
type SubscriptionPayload ¶
type SubscriptionPayload struct {
Data map[string]any `json:"data,omitempty"`
Errors any `json:"errors,omitempty"`
}
SubscriptionPayload is a single payload pushed by the server over a `next` frame. Mirrors the graphql-transport-ws wire shape.
type Subscriptions ¶
type Subscriptions struct {
// contains filtered or unexported fields
}
Subscriptions is the subscription client wired into WillowClient.
func NewSubscriptions ¶
func NewSubscriptions(apiURL string, indexers *Indexers, httpClient *http.Client) *Subscriptions
NewSubscriptions creates a subscription client. Normally constructed by NewClient; callers invoke it via Client.Subscriptions.
func (*Subscriptions) Subscribe ¶
func (s *Subscriptions) Subscribe( ctx context.Context, subgroveID, query string, opts *SubscribeOptions, ) (*Subscription, error)
Subscribe opens a GraphQL subscription.
The initial handshake runs synchronously — connection_init → connection_ack → subscribe — so the first-attempt failures surface here. After that the subscription is handed off to a background goroutine that handles reconnects (unless Reconnect is explicitly disabled).
For SubscribeSourceIndexer, discovery happens inside this call on the first attempt. On each reconnect, the previously-used indexer is evicted from the discovery cache so failover to a different indexer is automatic.
type SupportedChain ¶
type SupportedChain string
SupportedChain is a canonical chain identifier accepted by Willow's consensus validator. Order mirrors SupportedChain::ALL in willow-types.
const ( ChainMainnet SupportedChain = "mainnet" ChainSepolia SupportedChain = "sepolia" ChainHolesky SupportedChain = "holesky" ChainBsc SupportedChain = "bsc" ChainOptimism SupportedChain = "optimism" ChainArbitrumOne SupportedChain = "arbitrum-one" ChainBase SupportedChain = "base" ChainPolygon SupportedChain = "polygon" ChainSolanaMainnet SupportedChain = "solana-mainnet" )
func FromEvmChainID ¶
func FromEvmChainID(id uint64) (SupportedChain, bool)
FromEvmChainID maps an EIP-155 chain id to a canonical chain.
type TokenInfo ¶
type TokenInfo struct {
Name string `json:"name"`
Symbol string `json:"symbol"`
Decimals uint8 `json:"decimals"`
GenesisSupply string `json:"genesis_supply"`
MintedSupply string `json:"minted_supply"`
MaxSupply string `json:"max_supply"`
CirculatingSupply string `json:"circulating_supply"`
}
TokenInfo represents information about the WILL token. Supplies are decimal strings of the smallest unit: the API sends them as u128 numbers.
func (*TokenInfo) UnmarshalJSON ¶
UnmarshalJSON reads the supplies from JSON numbers (as the API sends them) or decimal strings.
type TokenOperations ¶
type TokenOperations struct {
// contains filtered or unexported fields
}
TokenOperations provides methods for token-related queries.
func (*TokenOperations) EstimateQueryFee ¶
func (t *TokenOperations) EstimateQueryFee(ctx context.Context) (string, error)
EstimateQueryFee estimates the query fee.
func (*TokenOperations) EstimateStorageFee ¶
func (t *TokenOperations) EstimateStorageFee(ctx context.Context, dataSizeBytes uint64) (string, error)
EstimateStorageFee estimates the storage fee (in WILL base units) for the given data size: cost_per_byte * dataSizeBytes. cost_per_byte is a u128, held as a decimal string because the value can exceed uint64, so the multiplication runs through math/big and the result is returned as a decimal string in the same convention.
func (*TokenOperations) GetBalance ¶
func (t *TokenOperations) GetBalance(ctx context.Context, did string) (*BalanceInfo, error)
GetBalance retrieves the balance for a DID.
func (*TokenOperations) GetFeeSchedule ¶
func (t *TokenOperations) GetFeeSchedule(ctx context.Context) (*FeeSchedule, error)
GetFeeSchedule retrieves the current fee schedule.
func (*TokenOperations) GetInfo ¶
func (t *TokenOperations) GetInfo(ctx context.Context) (*TokenInfo, error)
GetInfo retrieves information about the WILL token.
func (*TokenOperations) GetMyBalance ¶
func (t *TokenOperations) GetMyBalance(ctx context.Context) (*BalanceInfo, error)
GetMyBalance retrieves the balance for the authenticated user.
type TransactionError ¶
type TransactionError struct {
WillowError
TxHash string
ErrorCode int
}
TransactionError represents a transaction-specific error.
func NewTransactionError ¶
func NewTransactionError(message string, txHash string, errorCode int) *TransactionError
NewTransactionError creates a new transaction error.
func (*TransactionError) Error ¶
func (e *TransactionError) Error() string
Error implements the error interface.
type TransferRequest ¶
type TransferRequest struct {
FromDid string `json:"from_did"`
ToDid string `json:"to_did"`
Amount uint64 `json:"amount"`
Memo string `json:"memo,omitempty"`
}
TransferRequest represents a request to transfer tokens.
type ValidatorHasNoDataError ¶
ValidatorHasNoDataError is returned when QuerySourceValidator was requested but the validator has no data for the subgrove (VerifyOnly retention, pruned, or not indexed).
func (*ValidatorHasNoDataError) Error ¶
func (e *ValidatorHasNoDataError) Error() string
type ValidatorInfo ¶
type ValidatorInfo struct {
DID string `json:"did"`
TotalStake consensus.Uint128 `json:"total_stake"`
SelfStake consensus.Uint128 `json:"self_stake"`
Active bool `json:"active"`
Jailed bool `json:"jailed"`
// JailEndTime is the Unix time a jailed validator's jail ends.
JailEndTime *uint64 `json:"jail_end_time,omitempty"`
ConsensusPubkey string `json:"consensus_pubkey,omitempty"`
}
ValidatorInfo is a validator as the API's /validators routes answer: its DID, stakes in the smallest token unit (10^-18 WILL), and state.
func (ValidatorInfo) Status ¶
func (v ValidatorInfo) Status() ValidatorStatus
Status returns the validator's status: jailed, active, or inactive.
type ValidatorOperations ¶
type ValidatorOperations struct {
// contains filtered or unexported fields
}
ValidatorOperations provides methods for validator-related queries.
func (*ValidatorOperations) Get ¶
func (v *ValidatorOperations) Get(ctx context.Context, did string) (*ValidatorInfo, error)
Get retrieves a validator by its DID.
func (*ValidatorOperations) GetActive ¶
func (v *ValidatorOperations) GetActive(ctx context.Context) ([]ValidatorInfo, error)
GetActive retrieves the validators that are active and not jailed.
func (*ValidatorOperations) GetTotalStake ¶
GetTotalStake returns the total stake of the active validators, in the smallest token unit.
func (*ValidatorOperations) List ¶
func (v *ValidatorOperations) List(ctx context.Context) ([]ValidatorInfo, error)
List retrieves the active validators (the API's /validators lists only active, unjailed validators with at least the minimum stake).
type ValidatorStatus ¶
type ValidatorStatus string
ValidatorStatus represents the status of a validator.
const ( ValidatorStatusActive ValidatorStatus = "active" ValidatorStatusInactive ValidatorStatus = "inactive" ValidatorStatusJailed ValidatorStatus = "jailed" )
type VerifiedCall
deprecated
type VerifiedCall = EthCallResult
VerifiedCall is EthCallResult.
Deprecated: the call isn't verified against Ethereum; use EthCallResult.
type VerifiedStateRead
deprecated
type VerifiedStateRead = EthStateRead
VerifiedStateRead is EthStateRead.
Deprecated: the state isn't verified against Ethereum; use EthStateRead.
type VerifiedStorage
deprecated
type VerifiedStorage = EthStorageSlot
VerifiedStorage is EthStorageSlot.
Deprecated: the value isn't verified against Ethereum; use EthStorageSlot.
type WillowError ¶
type WillowError struct {
Type ErrorType
Message string
Cause error
Details map[string]interface{}
}
WillowError represents an error from the Willow SDK.
func NewAPIError ¶
func NewAPIError(message string) *WillowError
NewAPIError creates an error for a request the API answered with success false, carrying the API's message.
func NewAuthenticationError ¶
func NewAuthenticationError(message string) *WillowError
NewAuthenticationError creates a new authentication error.
func NewConfigError ¶
func NewConfigError(message string) *WillowError
NewConfigError creates a new configuration error.
func NewConsensusError ¶
func NewConsensusError(message string, cause error) *WillowError
NewConsensusError creates a new consensus error.
func NewCryptoError ¶
func NewCryptoError(message string, cause error) *WillowError
NewCryptoError creates a new cryptography error.
func NewLightClientError ¶
func NewLightClientError(message string, cause error) *WillowError
NewLightClientError creates a new light client error.
func NewNetworkError ¶
func NewNetworkError(message string, cause error) *WillowError
NewNetworkError creates a new network error.
func NewNotFoundError ¶
func NewNotFoundError(resource string) *WillowError
NewNotFoundError creates a new not found error.
func NewPermissionDeniedError ¶
func NewPermissionDeniedError(message string) *WillowError
NewPermissionDeniedError creates a new permission denied error.
func NewProofError ¶
func NewProofError(message string) *WillowError
NewProofError creates a new proof verification error.
func NewSerializationError ¶
func NewSerializationError(message string, cause error) *WillowError
NewSerializationError creates a new serialization error.
func NewUnsupportedError ¶
func NewUnsupportedError(message string) *WillowError
NewUnsupportedError creates an error for an operation the network serves no route or transaction for, or one this SDK does not build. The message names the supported path.
func NewValidationError ¶
func NewValidationError(message string) *WillowError
NewValidationError creates a new validation error.
func (*WillowError) Error ¶
func (e *WillowError) Error() string
Error implements the error interface.
func (*WillowError) Is ¶
func (e *WillowError) Is(target error) bool
Is checks if the target error matches this error type.
func (*WillowError) Unwrap ¶
func (e *WillowError) Unwrap() error
Unwrap returns the underlying cause of the error.
type WillowManifest ¶
type WillowManifest struct {
SpecVersion string `json:"spec_version"`
Description *string `json:"description,omitempty"`
DataSources []DataSource `json:"data_sources"`
DeferredCompleteness bool `json:"deferred_completeness,omitempty"`
}
WillowManifest is the canonical on-chain manifest shape.
func ParseManifest ¶
func ParseManifest(data []byte) (*WillowManifest, error)
ParseManifest validates and decodes canonical manifest bytes.
type WriteError ¶
WriteError is a write that failed after it was signed under Nonce.
When MayLand is true its submission failed in transit (a network error or a 5xx answer), so it may have reached the node and may still land. To send it again, sign it under the same nonce (WithNonce(Nonce)): whichever attempt lands first uses the nonce and the other is refused, so the write runs at most once. Or wait for the nonce with Client.WaitUntilLanded and read what it wrote: a write sent again under a fresh nonce while the first is valid can run twice. Otherwise the answer said CheckTx refused the write before it reached the mempool, so it will not run, unless the refusal is ErrNonceUsed (see there).
func (*WriteError) Error ¶
func (e *WriteError) Error() string
Error implements the error interface.
func (*WriteError) Unwrap ¶
func (e *WriteError) Unwrap() error
Unwrap returns the submission's error.
type WriteOption ¶
type WriteOption func(*writeOptions)
WriteOption changes how a write method (Data.StoreItem, Registration.RegisterSubgrove, Registration.DeleteSubgrove, and Privacy.GrantSubgroveKey, RevokeSubgroveKey, and RotateSubgroveKey) signs its transaction.
func WithNonce ¶
func WithNonce(nonce uint64) WriteOption
WithNonce signs the write under nonce instead of a nonce the client hands out. Use it to send a write again under the nonce of an earlier attempt that may have landed (the Nonce of a *WriteError with MayLand set): whichever attempt lands first uses the nonce and the other is refused, so the write runs at most once. Send the same write (the same fields) under it.
The client reads the account's nonce state first. If the chain shows the nonce used, it sends nothing and returns a *WriteError wrapping ErrNonceUsed: the earlier attempt (or another transaction under the nonce) landed. A refusal as already used returns the same error; the write isn't signed again under another nonce. A refusal as held by a pending transaction, or another *WriteError with MayLand set (which is also how the API reports CometBFT refusing a transaction identical to one it has already seen), means a transaction under the nonce, most likely the earlier attempt, may be pending: wait for it with WaitUntilLanded. This attempt's outcome never frees the hold the earlier attempt left on the nonce. While a submission under the nonce from this client is in flight (a write that took it, or another sent under it), the write sends nothing and returns a *WriteError (not ErrNonceUsed): send it again once that one returns.
type WriteResult ¶
WriteResult is a write the chain's CheckTx accepted: the DID that signed it, the nonce it was signed under, and its transaction hash. It is applied, or refused, in its block; Client.WaitUntilLanded waits for that.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package erc8004 provides ERC-8004 (Trustless Agents) integration for Willow.
|
Package erc8004 provides ERC-8004 (Trustless Agents) integration for Willow. |
|
examples
|
|
|
basic_usage
command
|
|
|
data_operations
command
|
|
|
graphql_indexing
command
|
|
|
light_client
command
|
|
|
proof_verification
command
|
|
|
registration
command
|
|
|
token_operations
command
|
|
|
Package grovedb decodes GroveDB proofs (the bincode envelope and its Merk operations) and checks the envelope's shape (CheckEnvelope).
|
Package grovedb decodes GroveDB proofs (the bincode envelope and its Merk operations) and checks the envelope's shape (CheckEnvelope). |
|
internal
|
|
|
httpbody
Package httpbody reads HTTP answers under a cap on their size, one per kind of answer, and refuses to decode one that holds more JSON than the SDK decodes.
|
Package httpbody reads HTTP answers under a cap on their size, one per kind of answer, and refuses to decode one that holds more JSON than the SDK decodes. |