willow

package module
v0.0.0-...-5d5fcec Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 34 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Willow Go SDK

Official Go SDK for interacting with the Willow network - a decentralized data infrastructure protocol providing blockchain indexing and structured data storage. See What the SDK verifies for what it checks itself.

Installation

go get github.com/willow-network/willow-go

Features

  • Identity Management: DID generation and request signing
  • Data Operations: Store data as signed transactions, read it, query it, and fetch its proofs
  • Subgrove Management: Register and deregister subgroves as signed transactions
  • Token Operations: Query balances and fee schedules
  • GraphQL Indexing: Query indexed blockchain data (answers unverified)
  • File Storage: Upload, download, list, and delete files with chunk Merkle verification
  • File Encryption: XChaCha20-Poly1305 encryption/decryption for private files
  • Light Client: Track a trusted CometBFT header (see Proofs and the light client)
  • GroveDB Proofs: Decode GroveDB proofs and check their envelope (the grovedb package doesn't verify a proof: its hashing isn't grovedb's, and its verify functions are deprecated)

Transaction submission

Transactions submitted through this SDK go to the API server's POST /tx/submit endpoint. The server accepts the JSON-encoded transaction, bincode-encodes it (the chain's on-the-wire format), and forwards to CometBFT's broadcast_tx_sync. APIURL is therefore required whenever you submit a tx; RPCURL is only used for read-only RPC queries (status, block, validators) and may be omitted or pointed at the same endpoint.

BroadcastTxAsync and BroadcastTxCommit were removed from consensus.Client — /tx/submit only exposes sync semantics. Callers that need fire-and-forget or wait-for-commit should layer that on top of BroadcastTxSync + GetTx polling.

Every write is a transaction: the API serves no REST route that writes data, subgroves, DIDs, or permissions. The write methods this SDK builds no transaction for (RegisterDID, Data.Store, Data.Update, Data.Delete, Data.BatchStore, Registration.UpdateSubgrove, GrantPermission, and RevokePermission) send nothing and return an error naming the supported path, for which willow.IsUnsupported(err) is true; they are deprecated.

API responses

Most API routes answer {"success": bool, "data": ..., "error": ...}. The client returns data, decoded into the method's result, and turns success: false into an error carrying the API's message, with a 2xx status or a 4xx one (willow.IsNotFound(err) for a missing key, DID, or subgrove); a 5xx answer is retried, then reported by its status. /health, /graphql, /sql, /files, and /historical/query answer with their result directly. u128 amounts (balances, stakes, fees, supplies) arrive as JSON numbers beyond 64 bits and are read exactly: as consensus.Uint128, or as decimal strings in TokenInfo and FeeSchedule.

The SDK reads at most a set number of bytes of each HTTP answer (from the API, the CometBFT RPC, an indexer, or a storage node), by route, and refuses a longer one with an error that names the limit. A limit bounds the bytes read, not the memory decoding them takes, which can be tens of times their length (a list of empty JSON objects decoded into maps). So the SDK also counts the JSON in an answer before decoding it, and refuses one that holds more than 2,097,152 units (each string, number, true, false, or null costs one, and each array or object eight) or nests deeper than 512 levels. Measured, an answer under that limit decodes to at most a few hundred MiB besides the bytes of its strings. A number in a byte array (one the SDK decodes into []byte or []int: the byte fields of a SQL answer's top-level proof, which an indexer sends for every row, and of an EthOperations answer) costs a sixteenth; every other number counts in full. A SQL answer with an indexer's proof of each row reaches the 64 MiB byte limit first, at about 9,000 rows with 2 KB proofs. A historical answer's data, bytes as JSON numbers decoded into interface{}, reaches the JSON limit at about 2 MB of those bytes. The byte limits, by route, hold the largest answer the node serves where the node bounds it:

  • 4 MiB: answers of fixed shape or short lists: nonces, balances, token info, fees, validators, indexers, health, /tx/submit, DID documents and permissions, key grants, subgrove information, state roots, file manifests and file-list pages, ERC-8004 answers, and CometBFT's status, commit, validators, and ABCI queries. These answers are a few KB; 4 MiB is the chain's max_tx_bytes.
  • 2 MiB: a file chunk, the most the storage node's upload route takes.
  • 12 MiB: Data.Get, Data.GetProof, and consensus.Client.GetTx, which carry what one transaction holds (at most 4 MiB), a proof in hex and a transaction in base64.
  • 32 MiB: consensus.Client.GetBlock and GetLatestBlock (a block of at most 21 MiB, its transactions in base64).
  • 64 MiB: answers whose size the request sets, which the node doesn't cap: Data.QueryUnverified (a page of 100 documents, the default, of up to 512 KiB each is 50 MiB), Data.QueryHistorical, GraphQL and SQL queries, FetchMatchedLogs, and EthOperations. Ask for less (a lower Limit, fewer slots) when an answer would be over it.

Some answers have no bound on the node and grow with the chain: the lists the API doesn't page (subgroves, validators, indexers, a subgrove's key grants, a DID's permissions) and DID documents can outgrow their limit, and an Ethereum call (GetCall) can touch more state than 64 MiB of proofs carries. Read one entry at a time instead of a list (GetSubgrove, GetIndexer, Validators.Get), and make a call touch less. An answer refused for its size, past its byte limit or the JSON limit, is an error that matches willow.ErrAnswerTooLarge (errors.Is), in every package of the SDK. A routed query under QuerySourceAuto returns that error rather than falling back to the API, which doesn't serve an indexing subgrove's rows.

The HTTP clients the SDK makes time out after 30 s (WithTimeout sets the client's, which Files also uses with the storage node, and consensus.ClientConfig.Timeout the consensus client's), and the light client's after lightclient.Config.RPCTimeout (10 s by default); a client you pass (WithHTTPClient, NewEthOperations) is used as it is, except that Files bounds each request it sends at 30 s when that client has no timeout. Files methods take no context; each has a Context variant (UploadContext, DownloadContext, MetadataContext, ListContext, DeleteContext, UnregisterStorageNodeContext) that stops when its context ends.

Signed transactions

The kinds below are signed over a message of lines joined by \n (no trailing newline): the kind first, then Label: value lines binding every field the transaction writes, the nonce last. Numbers are unsigned decimal and bytes lowercase hex. A signed text field can't hold a line break or invalid UTF-8: the builders return a validation error instead. The nonce in the message is the nonce the transaction carries, so a message is built after the nonce is chosen and a retry under another nonce is signed anew. A write refused in its block after its signature and nonce verify still spends that nonce. (RevokeSubgroveKey and DeregisterSubgrove sign RevokeSubgroveKey:<subgrove>:<revokee>:<sender>:<nonce> and DeregisterSubgrove:<subgrove>:<owner>:<nonce>, which bind every field.)

Kind Builder Lines after the kind
StoreData FormatDataStoreMessage Subgrove, Key, Owner, DataHash (SHA-256 of the data bytes sent), Nonce
StoreFileManifest FormatStoreFileManifestMessage Subgrove, Key, Owner, Filename, ContentType, TotalSize, ContentHash, ChunkCount, ChunkSize, ChunkMerkleRoot, Encryption, Nonce
DeleteFileManifest FormatDeleteFileManifestMessage Subgrove, Key, Owner, Nonce
RegisterSubgrove FormatRegisterSubgroveMessage Subgrove, Owner, Config, Nonce
GrantSubgroveKey FormatGrantSubgroveKeyMessage Subgrove, Sender, the grant's Grantee, GranteeKey, KeyEpoch, EphemeralKey, EncryptedKey, GrantedBy, GrantedAt, Nonce
RotateSubgroveKey FormatRotateSubgroveKeyMessage Subgrove, Sender, NewEpoch, Grants (the count), each grant's seven lines in order, Nonce
UnregisterStorageNode FormatUnregisterStorageNodeMessage Node, Nonce

The chain accepts these forms from its activation height; until then it refuses them, including GrantSubgroveKey and RotateSubgroveKey, which the older forms signed.

A RegisterSubgrove's Config is the hex SHA-256 of the registration's bincode (bincode 1.x: fixed-width little-endian integers, u64 lengths) with an empty signature, so it binds every field: consensus.RegisterSubgroveUnsignedBincode computes it from the exact JSON sent. consensus.RegisterSubgroveTx sends every field, nil lists as [], a nil Mode as the chain's default DataStorage, and other absent options as null, so the chain decodes the values the hash covers. The SDK signs DataStorage and FileStorage registrations; it refuses to sign a BlockchainIndexing one, whose mode its types don't encode, and one the chain would refuse for its subgrove id, its admins, writers, or free readers, its schema, or a private registration's initial owner key grant (see Subgrove Management).

The key-grant builders and flows refuse what the chain refuses: a grant or rotation to a grantee that isn't a DID, a rotation with no grants, and a rotation with a grant whose KeyEpoch isn't the rotation's new epoch (the block refuses that one after CheckTx admits it, and the refusal spends the nonce).

Ed25519 signs the message's UTF-8 bytes. secp256k1 signs their Keccak-256 (low-S; the SDK sends DER, and the chain also accepts 64-byte compact r||s).

Nonces

The chain accepts a nonce in base+1 … base+24 that it hasn't used, where base (the account nonce) advances only over used nonces with no gap below them. The client keeps, per signing DID, the nonces it has handed out that haven't landed (each held while a submission under it is in flight, and for 120 s, the longest the node holds a pending transaction's nonce, after CheckTx accepts it or after it may have reached the node) and the nonces it has seen used, and each write takes the lowest nonce in the window that is neither, under a lock, so writes in flight together take distinct nonces. With WithRPCURL it reads which nonces above the base are used from the ABCI query /store/account_nonce_state/{did}; otherwise it reads the base from the API's /account/{did}/nonce. With all 24 held, a write fails with an error wrapping willow.ErrNonceWindowFull and sends nothing: wait for earlier writes to land.

A write returns a *willow.WriteResult (DID, Nonce, TxHash) once CheckTx accepts it. client.WaitUntilLanded(ctx, did, nonce) waits until the chain shows the nonce used; writes in flight may land in any order, so send a write that depends on another only after the first has landed. A write refused in its block also uses its nonce (every kind the SDK sends except DeregisterSubgrove, whose refusal leaves the nonce unused): read what it wrote, or look its TxHash up with consensus.Client.GetTx, to know it took effect. For a *willow.WriteError with MayLand set, read what the write wrote: the API names no transaction hash for a submission that may have landed. (A CheckTx refusal's hash is on the *willow.TransactionError the WriteError wraps.) client.GetAccountNonce reads the account's nonce state, and client.NextNonce hands out a nonce for a transaction the client doesn't build (a file write's FileSigningOptions.Nonce, or one sent with consensus.Client.BroadcastTxSync).

Set WithRPCURL (the CometBFT RPC endpoint) when writes run concurrently. Without it the client reads only the base, which advances only over used nonces with no gap below them: a write that landed above a nonce not yet used (a write still pending, or one that never landed) doesn't show as landed, so WaitUntilLanded waits for every earlier nonce and fails at the context's deadline if one never lands. The client may also hand that write's nonce out again once its 120 s hold lapses; a write then refused as used under it fails with willow.ErrNonceUsed (see below).

client, err := willow.NewClient("http://localhost:3031",
    willow.WithRPCURL("http://localhost:26657"))

A nonce stays held while a submission under it is in flight, however long that takes. A refusal at CheckTx gives its nonce back, unless it is the node's own error for that nonce saying it is held by a pending transaction (the write fails and the nonce stays held) or already used, or at or below the base (the write fails with willow.ErrNonceUsed and the nonce is marked used). Text a refusal only quotes, such as the expected message a signature mismatch repeats, says nothing about the nonce.

A write whose submission fails in transit (a network error or a 5xx) may still land: its error is a *willow.WriteError with MayLand set, naming the nonce. Send it again under that nonce with willow.WithNonce: whichever attempt lands first uses the nonce and the other is refused, so the write runs at most once.

write, err := client.Data.StoreItem(ctx, "sg", "k", data)
var werr *willow.WriteError
if errors.As(err, &werr) && werr.MayLand {
    write, err = client.Data.StoreItem(ctx, "sg", "k", data, willow.WithNonce(werr.Nonce))
}

File writes (Files.Upload, Delete, and UnregisterStorageNode) return the same *willow.WriteError: send one with MayLand set again signed under the same FileSigningOptions.Nonce.

Under WithNonce the client sends nothing if the chain already shows the nonce used, and doesn't sign the write again under another nonce if it is refused as used; either way the error wraps willow.ErrNonceUsed: the earlier attempt may have landed, so read what it wrote before sending the write again without WithNonce. A refusal as held by a pending transaction, or another MayLand error (also how the API reports CometBFT refusing a transaction identical to one it has already seen), means the earlier attempt may be pending: wait for the nonce. Sending the write again under a fresh nonce while the earlier attempt is valid can run it twice. For the same reason, a write refused as used, with or without WithNonce, fails with willow.ErrNonceUsed and is never signed again under another nonce on its own: the transaction that used the nonce may be this write (an API can forward an attempt to the chain while answering that its nonce is used), so read what it wrote before sending it again.

Quick Start

package main

import (
    "context"
    "fmt"
    "log"

    willow "github.com/willow-network/willow-go"
)

func main() {
    ctx := context.Background()

    // Create a new client
    client, err := willow.NewClient("http://localhost:3031")
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()

    // Generate a new identity
    identity, err := willow.NewIdentity(willow.Ed25519)
    if err != nil {
        log.Fatal(err)
    }

    // Willow DIDs are self-certifying: the id is derived from the public key
    // as did:willow:z<base58btc(SHA3-256(multicodec_prefix || public_key))>.
    // A DID is registered on chain by a RegisterDid transaction, which this
    // SDK does not build; it must be funded first, since the fee is paid from
    // its own balance.
    fmt.Printf("Generated DID: %s\n", identity.DID())

    // Set identity for per-request signing
    client.SetIdentity(identity)

    // The latest block's app hash, as the API's CometBFT node reports it.
    // This is the API's value: the SDK doesn't verify it.
    appHash, err := client.GetLatestAppHash(ctx)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("Latest app hash (unverified):", appHash)
}

Usage Examples

Creating a Client
// Simple client
client, err := willow.NewClient("http://localhost:3031")

// With options
client, err := willow.NewClient("http://localhost:3031",
    willow.WithTimeout(60 * time.Second),
    willow.WithRetryConfig(willow.RetryConfig{
        MaxRetries:     5,
        InitialBackoff: 200 * time.Millisecond,
        MaxBackoff:     10 * time.Second,
        BackoffFactor:  2.0,
    }),
)

// Using builder pattern
client, err := willow.Builder("http://localhost:3031").
    WithTimeout(30 * time.Second).
    Build()

WithAPIKey sets the managed tier's key. The client sends it (as X-API-Key) only to the API URL and to the indexer named with WithIndexerURL: never to an indexer it discovers from the API's /indexers list, whose endpoint whoever registered it chooses, nor to the RPC URL or a storage node. To send the key to an indexer, name it with WithIndexerURL.

Identity Management
// Generate Ed25519 identity
identity, err := willow.NewIdentity(willow.Ed25519)

// Generate secp256k1 identity
identity, err := willow.NewIdentity(willow.Secp256k1)

// Restore from private key
identity, err := willow.IdentityFromPrivateKey(willow.Ed25519, privateKeyHex)

// Read a registered DID's document
info, err := client.GetDID(ctx, identity.DID())

// Set identity for per-request signing
client.SetIdentity(identity)

// Check if identity is set
if client.HasIdentity() {
    fmt.Println("Identity is set, requests will be signed")
}
Request Signing

With an identity set, the client signs each read of subgrove data it sends to the API (GET /data/{sg}/{key}, GET /proof/{sg}/{key}, the key-grant reads under /key-grants and /proof/key-grant, and POST /query, /sql, and /graphql) with a one-time nonce over the whole request. Only this form carries the DID's read rights: a Reader permission on a subgrove, or a place on a priced subgrove's free-reader list. Other requests it signs use the older form below, which the server also accepts in the first 30 s after it restarts, when it refuses nonce-signed requests.

The headers are X-DID, X-Public-Key-ID, X-Signature, X-Timestamp, and X-Nonce. The signature is over eight lines:

willow-request-v2
<DID>
<public key id>
<METHOD>
<path and query, exactly as sent>
<Unix timestamp>
<nonce>
<hex SHA-256 of the body>
  • The server accepts a timestamp up to 300 s old and 30 s ahead of its clock, and each (DID, nonce) once. The client signs each retry with a new nonce.
  • A nonce is 16 to 128 characters of A-Z a-z 0-9 - _. NewRequestNonce makes one of 32 hex characters.
  • Ed25519 signatures are sent as hex. secp256k1 signatures are over the Keccak-256 of the message and are sent as 0x-prefixed hex.
  • Requests sent to an indexer (WithIndexerURL) are not signed this way.

To sign a request you send yourself:

headers, err := identity.SignRequestWithNonce("POST", "/query/my-subgrove", body)

identity.SignRequest(method, path) makes the older {METHOD}:{PATH}:{TIMESTAMP} form, over the path without its query string. It proves the DID but carries none of its read rights, and it can be replayed with any body until the timestamp expires.

Data Operations
// Store an object under a key: a StoreData transaction signed by the
// identity, carrying the object's JSON text as bytes
write, err := client.Data.StoreItem(ctx, "users", "user-123", map[string]interface{}{
    "name":  "Alice",
    "email": "alice@example.com",
})

// Wait for it to land before reading it back
err = client.WaitUntilLanded(ctx, write.DID, write.Nonce)

// Read the stored value (the API's data route carries no proof)
response, err := client.Data.Get(ctx, "users", "user-123")

// Fetch the key's GroveDB proof, with its path, key, and height (unverified)
proof, err := client.Data.GetProof(ctx, "users", "user-123")

StoreItem returns once the chain's CheckTx accepts the transaction; the write is applied, or refused, in its block. Each item is its own transaction under its own nonce, so up to 24 can be in flight per identity; set WithRPCURL when they are, so WaitUntilLanded sees each one land (see Nonces). The SDK doesn't build UpdateData or DeleteData transactions, so Data.Update and Data.Delete return an unsupported error, as do Data.Store (a StoreData needs a key) and Data.BatchStore.

Querying Data
query := willow.NewQueryBuilder().
    Equals("status", "active").
    SortDesc("created_at").
    Limit(10).
    Build()

response, err := client.Data.QueryUnverified(ctx, "users", query)
for _, result := range response.Results {
    fmt.Println(result.Data) // the matching documents, as the API returns them
}

The API's /query applies one equality filter, a sort on one field, a limit, and an offset. The client refuses a query it wouldn't apply (more filters, another operator, full-text search) instead of sending it. Data.Query returns an unsupported error and sends nothing, because the SDK can't verify a query's proof (see Proofs and the light client).

Subgrove Management
// Create a schema using builder
schema := willow.NewSchemaBuilder("User").
    Description("User profile schema").
    StringField("name", true).
    StringField("email", true).
    IntField("age", false).
    Build()

// Register a DataStorage subgrove owned by the identity: a RegisterSubgrove
// transaction signed over FormatRegisterSubgroveMessage
subgroveReq := willow.NewSubgroveBuilder("users", "Users").
    Description("User profiles").
    Schema(*schema).
    Owner(identity.DID()).
    AddWriter(identity.DID()).
    Build()

write, err := client.Registration.RegisterSubgrove(ctx, subgroveReq)

// The subgrove exists once the registration lands
err = client.WaitUntilLanded(ctx, write.DID, write.Nonce)

// Deregister it (a DeregisterSubgrove transaction; the chain refunds its balance)
_, err = client.Registration.DeleteSubgrove(ctx, "users")

The schema is sent in the chain's form (SchemaDefinition.ChainSchemaJSON): a map of field name to type (string, number, boolean, array, object, bytes) and the required fields; its name and description label it in the SDK and are not sent. The chain refuses a DataStorage or FileStorage registration whose subgrove id isn't 1 to 64 ASCII letters, digits, -, or _ starting with a letter or digit; whose admins, writers, or free readers aren't DIDs (did:willow: then ASCII letters, digits, -, or _, at most 128 bytes); whose schema doesn't parse as its schema definition (version a u32, fields a map of name to one of the six types, indexes, and required_fields a list of names; each optional, unknown keys ignored) or declares indexes; and a private DataStorage registration whose InitialOwnerKeyGrant isn't key epoch 0 to the owner. The SDK refuses each before signing with a validation error (an index is one added with the schema builder's index methods, or a field marked indexed). For a FileStorage or private registration, read pricing, admins, or initial funding, build a consensus.RegisterSubgroveTx and sign it (a nil Mode is sent as the chain's default, an empty DataStorage):

tx := &consensus.RegisterSubgroveTx{
    SubgroveID:  "files-1",
    Name:        "Files",
    Schema:      `{"version":1,"fields":{},"indexes":[],"required_fields":[]}`,
    OwnerDid:    identity.DID(),
    Mode: &consensus.SubgroveMode{FileStorage: &consensus.SubgroveFileStorage{
        Name: "Files", MaxFileSize: 100 << 20, ReplicationFactor: 3,
        Writers: []string{identity.DID()},
    }},
    PublicKeyID: identity.PublicKeyID(),
    Nonce:       nonce, // from client.NextNonce(ctx, identity.DID())
}
message, err := willow.FormatRegisterSubgroveMessage(tx)
tx.Signature, err = identity.Sign([]byte(message))
result, err := consensusClient.BroadcastTxSync(ctx, map[string]interface{}{"RegisterSubgrove": tx})
GraphQL Queries
// Execute a GraphQL query; the answer is returned unverified
response, err := client.Indexing.Execute(ctx, "uniswap-v3",
    `query GetSwaps($first: Int!) {
        swaps(first: $first, orderBy: timestamp, orderDirection: desc) {
            id
            timestamp
            amountUSD
            token0 { symbol }
            token1 { symbol }
        }
    }`,
    map[string]interface{}{"first": 10},
)

// Using query builder
query := willow.NewGraphQLQuery(`query Pools($first: Int!) { pools(first: $first) { id } }`).
    Variable("first", 100).
    Build()

response, err = client.Indexing.QueryUnverified(ctx, "uniswap-v3", query)

// Execute and unmarshal the answer's data directly
var result struct {
    Swaps []struct {
        ID        string `json:"id"`
        Timestamp int64  `json:"timestamp"`
    } `json:"swaps"`
}

err = client.Indexing.ExecuteWithResult(ctx, "uniswap-v3",
    `query GetSwaps($first: Int!) { swaps(first: $first) { id timestamp } }`,
    map[string]interface{}{"first": 10},
    &result,
)

Execute, ExecuteWithResult, and QueryUnverified ask for no proof and return the answer as the API (or, with WithIndexerURL, the indexer) sends it. An indexer that doesn't serve the subgrove answers with empty data, not an error, and only the API serves a DataStorage subgrove: with WithIndexerURL set, query one with GraphQLQueryWithSource and willow.QuerySourceValidator. GraphQLQueryWithSource asks for a proof only when the request sets IncludeProof, and returns it unverified, as the answer's JSON, in GraphQLResponse.Proof. Indexing.Query returns an unsupported error and sends nothing, because the SDK can't verify a GraphQL answer (see What the SDK verifies).

Proofs and the light client

A proof the API returns (from Data.GetProof, or with a query) 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, a GroveDB verifier that reproduces the chain's root for the proof, and, for a query, the returned documents matched to the values the proof proves. The SDK doesn't provide these, so Data.Query and Data.VerifyProof return an unsupported error (willow.IsUnsupported) instead of presenting data as verified, and Data.QueryUnverified and Data.GetProof return what the API sends, unverified.

The lightclient package keeps a trusted CometBFT header. Its VerifyHeader checks a later header's chain id, height and time, the trusting period, clock drift, an adjacent header's validator-set hash, and the voting power its commit lists, counted from the validator set the block itself carries; it does not verify the commit signatures, or tie that validator set to the header, so a header anyone can build passes. The result's ChecksPassed says only that those checks passed (Verified, the same value, is deprecated).

import "github.com/willow-network/willow-go/lightclient"

lc, err := lightclient.NewLightClient(lightclient.Config{
    ChainID:            "willow-mainnet",
    ValidatorEndpoints: []string{"http://validator1:26657"},
    TrustingPeriod:     24 * time.Hour,
})

// Pin a header you trust, then read it back
err = lc.InitializeWithTrustedHeader(trustedBlock)
header, err := lc.GetLatestTrustedHeader()
fmt.Println(header.Height, header.AppHash)

lc.GetLatestAppHash returns that header's app hash (GetVerifiedRootHash is a deprecated alias): it is as trustworthy as the header pinned, or the endpoints the light client took it from, not verified against the validators.

What the SDK verifies
  • Nothing read from the chain's state is verified: the SDK verifies no CometBFT header (VerifyHeader doesn't check commit signatures) and has no GroveDB verifier that binds data to the chain's root. So Data.Query, Data.VerifyProof, Data.QueryHistoricalVerified (deprecated), and Indexing.Query return an unsupported error and send nothing, and every other read (Data.Get, Data.QueryUnverified, Data.GetProof, Data.QueryHistorical, GraphQL and SQL queries, GetLatestAppHash) returns what it is sent, unverified.
  • Block completeness: VerifyBlockCompleteness re-hashes an indexer's matched logs and compares them with the block's events commitment. It doesn't trust the indexer, but it trusts the RPC node it reads the commitment from: that ABCI answer carries no proof. That node is the one WithRPCURL names; without it, it is the API's host (the API URL with :3031 replaced by :26657), or the API URL itself when it has no :3031, so the check trusts the API's operator. An answer for another subgrove or block than the one asked for is an error.
  • Ethereum state reads (EthOperations): the indexer's answer carries the block's state root and MPT proofs of the account and slot values under it. The SDK requires the proof to be for the address, block, and slots asked for (in order), and in EthWalkProofs mode (the default) walks it, but it has no trusted source of Ethereum block headers, so it can't check that the root is Ethereum's: every result is the indexer's claim. A zero slot value is proved by the slot's absence from the storage trie, and an account that doesn't exist by its absence from the state trie (it reads as empty). Erc20Balance refuses a token address with no contract (no account, or no code), but can't tell a wrong balance slot, which reads as zero. An eth_call's result is bound by no proof.
  • File downloads: Files.Download checks the chunks against the manifest's chunk Merkle root and content hash, with the manifest as the API sends it, unverified.
Consensus Client
import "github.com/willow-network/willow-go/consensus"

// Create consensus client: BroadcastTxSync sends to the API's /tx/submit,
// so it needs APIURL; RPCURL is for the CometBFT reads (GetTx, GetBlock, ...)
consensusClient := consensus.NewClient(consensus.ClientConfig{
    RPCURL:  "http://localhost:26657",
    APIURL:  "http://localhost:3031",
    Timeout: 30 * time.Second,
})

// Broadcast transaction
tx := consensus.TransferTx{
    FromDid: identity.DID(),
    ToDid:   recipient.DID(),
    Amount:  1000,
    // ... signature fields
}

result, err := consensusClient.BroadcastTxSync(ctx, map[string]interface{}{
    "Transfer": tx,
})

// Look a transaction up by its hash once it is in a block (the hex hash is
// sent to CometBFT as base64 of its bytes): Status is not_found until then,
// and Code and Log are its block's result.
txResult, err := consensusClient.GetTx(ctx, result.TxHash)
Token Operations
// Get token info
info, err := client.Token.GetInfo(ctx)
fmt.Printf("Token: %s (%s)\n", info.Name, info.Symbol)

// Get balance (u128 amounts in the smallest unit, read exactly)
balance, err := client.Token.GetBalance(ctx, identity.DID())
fmt.Printf("Available: %s, staked: %s\n", balance.Available, balance.Staked)

// Get fee schedule
fees, err := client.Token.GetFeeSchedule(ctx)
fmt.Printf("Base TX cost: %s wei\n", fees.BaseTxCost)
fmt.Printf("Cost per byte: %s wei\n", fees.CostPerByte)

// Estimate fees
storageFee, err := client.Token.EstimateStorageFee(ctx, 1024) // 1KB write

Error Handling

response, err := client.Data.Get(ctx, "users", "user-123")
if err != nil {
    // Check error types
    if willow.IsNotFound(err) {
        fmt.Println("User not found")
    } else if willow.IsUnsupported(err) {
        fmt.Println(err) // names the supported path
    } else if willow.IsNotAuthenticated(err) {
        fmt.Println("Please call SetIdentity() first")
    } else if statusCode, ok := willow.IsHTTPError(err); ok {
        fmt.Printf("HTTP error: %d\n", statusCode)
    } else {
        fmt.Printf("Error: %v\n", err)
    }
}

Configuration

Retry Configuration
config := willow.RetryConfig{
    MaxRetries:     3,                   // Maximum retry attempts
    InitialBackoff: 100 * time.Millisecond, // Initial backoff duration
    MaxBackoff:     5 * time.Second,     // Maximum backoff duration
    BackoffFactor:  2.0,                 // Backoff multiplier
}

client, err := willow.NewClient(url, willow.WithRetryConfig(config))

Examples

The SDK includes several examples demonstrating common use cases:

# Basic usage - DID generation, signed requests, storing and reading data
go run ./examples/basic_usage

# Data operations - storing, reading, and querying data, and the writes this
# SDK doesn't build (update, delete), which return an unsupported error
go run ./examples/data_operations

# Light client - a trusted CometBFT header, and what the SDK verifies
go run ./examples/light_client

# Registration - DID generation, listing, reading, and registering subgroves
go run ./examples/registration

# GraphQL indexing - Query indexed blockchain data
go run ./examples/graphql_indexing

# Token operations - Balances, fees, validators
go run ./examples/token_operations

Testing

# Run tests
go test ./...

# Run tests with coverage
go test -cover ./...

License

MIT License - see LICENSE file for details.

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

View Source
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
)
View Source
const (
	MaxDataSources     = 64
	MaxEventsPerSource = 32
	MaxNameLen         = 64
	MaxAbiLen          = 64
	MaxDescriptionLen  = 1024
)

Mirrors MAX_* constants in willow-types.

View Source
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
)
View Source
const DefaultCacheTTL = 30 * time.Second

DefaultCacheTTL is how long a successful /indexers response is reused before the SDK re-fetches.

View Source
const DefaultChunkSize = 262144 // 256 KB
View Source
const ManifestSpecVersion = "1.0.0"

ManifestSpecVersion is the schema version pinned by consensus.

Variables

View Source
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.

View Source
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!

View Source
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.

View Source
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.

View Source
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.).

View Source
var GlobalComputedFieldRegistry = NewComputedFieldRegistry()

GlobalComputedFieldRegistry is a global registry instance for convenience.

View Source
var LPShareFields = ComputedFieldSet{
	{
		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.

View Source
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.).

SupportedChains is the canonical chain set. Adding a chain is a consensus change: bump willow-types first, then mirror here.

View Source
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.

View Source
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)
View Source
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

func BoolPtr(b bool) *bool

BoolPtr is a convenience helper for the Reconnect field.

Usage:

opts := &SubscribeOptions{Reconnect: BoolPtr(false)}

func CanonicalEventSetHash

func CanonicalEventSetHash(blockNumber uint64, matchedLogs []Log) [32]byte

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

func DecryptFile(ciphertext []byte, key [32]byte, nonce [24]byte) ([]byte, error)

DecryptFile decrypts file data using XChaCha20-Poly1305.

Requires: golang.org/x/crypto/chacha20poly1305

func EncryptFile

func EncryptFile(data []byte, key [32]byte) (ciphertext []byte, nonce [24]byte, err error)

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

func FormatUnregisterStorageNodeMessage(nodeDID string, nonce uint64) (string, error)

FormatUnregisterStorageNodeMessage returns the message an UnregisterStorageNode transaction is signed over:

UnregisterStorageNode
Node: <nodeDID>
Nonce: <nonce>

func GenerateDID

func GenerateDID(keyPair *KeyPair) string

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

func IsHTTPError(err error) (int, bool)

IsHTTPError checks if the error is an HTTP error and returns the status code.

func IsNotAuthenticated

func IsNotAuthenticated(err error) bool

IsNotAuthenticated checks if the error is a not authenticated error.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound checks if the error is a not found error.

func IsSupportedChain

func IsSupportedChain(s string) bool

IsSupportedChain returns true iff s is a canonical chain id.

func IsUnsupported

func IsUnsupported(err error) bool

IsUnsupported checks if the error is an unsupported-operation error.

func IsValidationError

func IsValidationError(err error) bool

IsValidationError checks if the error is a validation error.

func LegacyRequestMessage

func LegacyRequestMessage(method, path, timestamp string) string

LegacyRequestMessage is the message SignRequest signs: {METHOD}:{PATH}:{TIMESTAMP}, with any query string dropped from path.

func NewRequestNonce

func NewRequestNonce() (string, error)

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

func VerifyServedEvents(commitment [32]byte, blockNumber uint64, matchedLogs []Log) bool

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.

func (*ChunkUploadError) Unwrap

func (e *ChunkUploadError) Unwrap() error

Unwrap returns Err.

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) Close

func (c *Client) Close() error

Close closes the client and releases resources.

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

func (c *Client) GetAccountNonce(ctx context.Context, did string) (*AccountNonceState, error)

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

func (c *Client) GetDID(ctx context.Context, did string) (*DidInfo, error)

GetDID retrieves a DID's on-chain document. Its balance is read with Token.GetBalance.

func (*Client) GetIdentity

func (c *Client) GetIdentity() *Identity

GetIdentity returns the current identity.

func (*Client) GetLatestAppHash

func (c *Client) GetLatestAppHash(ctx context.Context) (string, error)

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

func (c *Client) GetRootHash(ctx context.Context) (string, error)

GetRootHash returns the current root hash from the local node.

func (*Client) GetVerifiedRootHash deprecated

func (c *Client) GetVerifiedRootHash(ctx context.Context) (string, error)

GetVerifiedRootHash returns GetLatestAppHash: the API's value, which the SDK doesn't verify.

Deprecated: the hash isn't verified; use GetLatestAppHash.

func (*Client) HasComputedFields

func (c *Client) HasComputedFields(datasetID string) bool

HasComputedFields checks if computed fields are registered for a dataset.

func (*Client) HasIdentity

func (c *Client) HasIdentity() bool

HasIdentity returns true if an identity is set on the client.

func (*Client) HasLightClient

func (c *Client) HasLightClient() bool

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

func (c *Client) IndexerBaseURL() string

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

func (c *Client) NextNonce(ctx context.Context, did string) (uint64, error)

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

func (c *Client) RPCEndpoint() string

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

func (c *Client) RequireAuth() error

RequireAuth returns an error if the client has no identity set.

func (*Client) SetIdentity

func (c *Client) SetIdentity(identity *Identity)

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

func (c *Client) WaitUntilLanded(ctx context.Context, did string, nonce uint64) error

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 Builder

func Builder(apiURL string) *ClientBuilder

Builder creates a new ClientBuilder.

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

type ClientOption func(*Client) error

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

func (d *DataOperations) GetProof(ctx context.Context, subgroveID, key string) (*DataProof, error)

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 (d *DataOperations) Store(ctx context.Context, subgroveID string, data map[string]interface{}) error

Store returns an unsupported-operation error and sends nothing: data is written by a StoreData transaction, which needs a key. Use StoreItem.

Deprecated: Store always fails; use StoreItem.

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

type EthStorageSlot struct {
	Slot  string
	Value *big.Int
}

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

type FileEncryption struct {
	KeyEpoch uint64
	Nonce    [24]byte
}

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

type GraphQLLocation struct {
	Line   int `json:"line"`
	Column int `json:"column"`
}

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

func NewHTTPError(statusCode int, message string) *HTTPError

NewHTTPError creates a new HTTP error.

func (*HTTPError) Error

func (e *HTTPError) Error() string

Error implements the error interface.

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) DID

func (i *Identity) DID() string

DID returns the DID string for this identity.

func (*Identity) PublicKeyID

func (i *Identity) PublicKeyID() string

PublicKeyID returns the public key ID for this identity.

func (*Identity) Sign

func (i *Identity) Sign(message []byte) ([]byte, error)

Sign signs a message with this identity.

func (*Identity) SignHex

func (i *Identity) SignHex(message []byte) (string, error)

SignHex signs a message and returns the hex-encoded signature.

func (*Identity) SignRequest

func (i *Identity) SignRequest(method, path string) (map[string]string, error)

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 IndexType

type IndexType string

IndexType represents the type of index.

const (
	IndexTypeHash     IndexType = "hash"
	IndexTypeRange    IndexType = "range"
	IndexTypeFullText IndexType = "fulltext"
	IndexTypeInverted IndexType = "inverted"
)

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

func NewIndexers(httpClient *http.Client, apiURL, indexerURL string) *Indexers

NewIndexers constructs a discovery client. Normally called by the WillowClient builder — consumers access it through client.Indexers().

func (*Indexers) Evict

func (d *Indexers) Evict(indexerDID string)

Evict drops a specific indexer from the cache (e.g., after a 5xx).

func (*Indexers) ForSubgrove

func (d *Indexers) ForSubgrove(ctx context.Context, subgroveID string) ([]IndexerInfo, error)

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

func (d *Indexers) HasExplicitOverride() bool

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.

func (*Indexers) List

func (d *Indexers) List(ctx context.Context) ([]IndexerInfo, error)

List returns all registered indexers, cached for cacheTTL.

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

func (kp *KeyPair) PrivateKeyHex() string

PrivateKeyHex returns the hex-encoded private key.

func (*KeyPair) PublicKeyHex

func (kp *KeyPair) PublicKeyHex() string

PublicKeyHex returns the hex-encoded public key.

func (*KeyPair) Sign

func (kp *KeyPair) Sign(message []byte) ([]byte, error)

Sign signs a message with the key pair.

type Log

type Log struct {
	Address [20]byte // contract address
	Topics  [][32]byte
	Data    []byte
}

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

type ManifestValidationError struct {
	Message string
	Field   string
}

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

type NoIndexersReachableError struct {
	SubgroveID string
	Details    string
	Errs       []error
}

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

type QueryResult struct {
	Key  string                 `json:"key"`
	Data map[string]interface{} `json:"data"`
}

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

type QuerySearch struct {
	Fields []string `json:"fields"`
	Query  string   `json:"query"`
}

QuerySearch represents full-text search options.

type QuerySort

type QuerySort struct {
	Field     string `json:"field"`
	Ascending bool   `json:"ascending"`
}

QuerySort represents sorting options for queries.

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

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 ServedBy

type ServedBy int

ServedBy tells the caller which backend actually served a query.

const (
	ServedByValidator ServedBy = iota
	ServedByIndexer
)

func (ServedBy) String

func (s ServedBy) String() string

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

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

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

func (t *TokenInfo) UnmarshalJSON(data []byte) error

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

type ValidatorHasNoDataError struct {
	SubgroveID string
	Reason     string
}

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

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

func (v *ValidatorOperations) GetTotalStake(ctx context.Context) (consensus.Uint128, error)

GetTotalStake returns the total stake of the active validators, in the smallest token unit.

func (*ValidatorOperations) List

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

type WriteError struct {
	DID     string
	Nonce   uint64
	MayLand bool
	Err     error
}

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

type WriteResult struct {
	DID    string
	Nonce  uint64
	TxHash string
}

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.

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
light_client command
registration 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.

Jump to

Keyboard shortcuts

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