> ## Documentation Index
> Fetch the complete documentation index at: https://docs.grantex.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Go SDK

> Official Go SDK for the Grantex delegated authorization protocol

## Installation

Published release: **`github.com/mishrasanjeev/grantex-go@v0.4.3`**. The tag
and public Go proxy resolve to the reviewed merge commit; the downloaded
module passed `go test ./...` and `go vet ./...`.

```bash theme={null}
go get github.com/mishrasanjeev/grantex-go@v0.4.3
```

The unpinned `go get github.com/mishrasanjeev/grantex-go` command follows Go's
module-version resolution. Keep the exact version above in reproducible builds.
See [Release Status](/release-status) before upgrading.

## Requirements

* **Go 1.26.1+**, matching this module's `go.mod` directive

Version `v0.4.0` adds `client.WebAuthn.CreateEnrollmentSession` for
principal-authenticated hosted passkey registration and
`client.Anomalies.GetResponsePolicy` / `SetResponsePolicy` for the
account-level irregularity response mode. Both server capabilities are
default-off for self-hosted deployments and require explicit operator rollout;
both are enabled on the Grantex-hosted service.

Version `v0.4.1` adds typed `WebAuthnGrantEvidence` references to grant and
verification responses and the updated VC WebAuthn attestation. It does not
enable hosted server flags or add custom assertion UI helper methods.

## Configuration

Version `v0.4.2` adds `client.Grants.Verify` and opt-in
`VerifyOptions.CurrentAuthority`, `ExpectedPrincipalID` and `ExpectedAgentDID`.
The callback must query the trusted issuer on each operation and fail closed
on inactive, unavailable or inconsistent authority. Local signature checks
alone do not prove current revocation. See [SDK execution authority](/guides/sdk-execution-authority).

```go theme={null}
import grantex "github.com/mishrasanjeev/grantex-go"

// Default configuration (reads GRANTEX_API_KEY is not used here — pass key directly)
client := grantex.NewClient("your-api-key")

// With options
client := grantex.NewClient("your-api-key",
    grantex.WithBaseURL("https://your-instance.example.com"),
    grantex.WithTimeout(60 * time.Second),
    grantex.WithHTTPClient(customHTTPClient),
)
```

| Option | Default | Description |
| - | - | - |
| `WithBaseURL(url)` | `https://api.grantex.dev` | API base URL |
| `WithTimeout(d)` | `30s` | HTTP request timeout |
| `WithHTTPClient(c)` | `http.DefaultClient` | Custom `*http.Client` |

Version `v0.3.0` adds typed EVM payment responses and authenticated principal/agent
reservation reconciliation for [Base USDC custody](/guides/base-usdc-custody).
It retains bounded refresh lost-response recovery from `v0.2.1` and the corrected
Agent/Audit contracts and ES256 DPoP wallet clients from `v0.2.0`. It does not add
an automatic x402 HTTP payment-and-retry wrapper; applications must implement
their merchant HTTP flow.

## Quick Start

```go theme={null}
package main

import (
    "context"
    "fmt"
    "log"

    grantex "github.com/mishrasanjeev/grantex-go"
)

func main() {
    ctx := context.Background()
    client := grantex.NewClient("your-api-key")

    // 1. Register an agent
    agent, err := client.Agents.Register(ctx, grantex.RegisterAgentParams{
        Name:        "Email Assistant",
        Description: "Reads and sends emails on behalf of users",
        Scopes:      []string{"read:email", "send:email"},
    })
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Agent registered: %s (DID: %s)\n", agent.ID, agent.DID)

    // 2. Create authorization request
    authReq, err := client.Authorize(ctx, grantex.AuthorizeParams{
        AgentID:     agent.ID,
        PrincipalID: "user-123",
        Scopes:      []string{"read:email", "send:email"},
    })
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Consent URL: %s\n", authReq.ConsentURL)

    // 3. Exchange authorization code for token (after user consents)
    tokenResp, err := client.Tokens.Exchange(ctx, grantex.ExchangeTokenParams{
        Code:    "authorization-code-from-callback",
        AgentID: agent.ID,
    })
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Grant token: %s\n", tokenResp.GrantToken)

    // 4. Verify the token
    verified, err := client.Tokens.Verify(ctx, tokenResp.GrantToken)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Token valid: %v, scopes: %v\n", verified.Valid, verified.Scopes)
}
```

## Available Resources

| Service | Description |
| - | - |
| `client.Agents` | Register, list, update, delete agents |
| `client.Tokens` | Exchange, refresh, verify, revoke tokens |
| `client.Grants` | List, revoke, delegate grants |
| `client.Audit` | Log and query audit entries |
| `client.Webhooks` | Manage webhook endpoints |
| `client.Billing` | Subscription and checkout management |
| `client.Policies` | Access policy CRUD |
| `client.Compliance` | Compliance reports and evidence packs |
| `client.Anomalies` | Anomaly detection and management |
| `client.SCIM` | SCIM 2.0 user provisioning |
| `client.SSO` | SSO configuration |
| `client.PrincipalSessions` | End-user dashboard sessions |
| `client.Passports` | Issue, list, get, and revoke MPP agent passports |
| `client.Vault` | Store, list, get, delete, and exchange service credentials |
| `client.Budgets` | Per-grant spending budgets and transactions |
| `client.Events` | SSE event streaming |
| `client.Usage` | Usage metering and history |
| `client.Domains` | Custom domain verification |
| `client.WebAuthn` | FIDO2/WebAuthn passkey management |
| `client.Credentials` | Verifiable Credentials and SD-JWT |
| `client.Commerce` | Commerce V1/OACP merchant discovery, catalog, checkout, webhooks, and ops |
| `client.DPDP` | DPDP Act 2023 records — consent, grievances, erasure, exports |
| `client.WalletSpendPolicies` | Developer-level layered wallet policy |

Use `NewPrincipalPrepaidWalletClient` for human wallet, assignment, reload,
policy, approval, activity, and stop operations. Use
`NewAgentPrepaidWalletClient` with `GenerateDPoPKey` for assigned-wallet listing,
payment authorization, and reload requests. Both constructors reject remote
plain-HTTP wallet endpoints; check their returned errors. See [Agent Wallet
Governance](/guides/agent-wallet-governance).

## Standalone Functions

| Function | Description |
| - | - |
| `grantex.VerifyGrantToken()` | Local JWT verification with a JWKS fetch per standalone call |
| `grantex.GeneratePKCE()` | Generate PKCE S256 challenge pair |
| `grantex.VerifyWebhookSignature()` | Verify HMAC-SHA256 webhook signatures |
| `grantex.Signup()` | Register a new developer (no API key needed) |

## Error Handling

```go theme={null}
agent, err := client.Agents.Get(ctx, "agent-id")
if err != nil {
    switch e := err.(type) {
    case *grantex.AuthError:
        fmt.Printf("Authentication failed: %d\n", e.StatusCode)
    case *grantex.APIError:
        fmt.Printf("API error %d: %s (code: %s)\n", e.StatusCode, e.Message, e.Code)
    case *grantex.NetworkError:
        fmt.Printf("Network error: %s\n", e.Message)
    default:
        fmt.Printf("Unexpected error: %v\n", err)
    }
}
```

## Ownership

Grantex is owned by Orchestrum Technologies LLP. Inventor and owner: Sanjeev Kumar. Ownership contact: [sanjeev@orchestrum.in](mailto:sanjeev@orchestrum.in) or [mishra.sanjeev@gmail.com](mailto:mishra.sanjeev@gmail.com).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.