tapsdk

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2026 License: MIT Imports: 46 Imported by: 0

README

tap-sdk

Build Taproot Assets applications

Go Reference CI MIT Licensed

tap-sdk is the application SDK for Taproot Assets. It wraps a running tapd node with a typed, developer-facing API for issuing, receiving, sending, proving, burning, and discovering assets.

The SDK intentionally does not mirror tapd one-to-one. It exposes the asset model developers usually want:

  • AssetRef as the stable handle for assets across wallet, issuer, proof, burn, balance, event, and universe flows.
  • Asset, Collection, and Issuance as distinct business concepts.
  • High-level Wallet, Issuer, and Universe surfaces for common workflows.
  • Direct grpc and rest transport packages for connection setup and advanced RPC-shaped access.

The Go package is the first implementation. The API model is designed to be portable to TypeScript, Rust, Python, Kotlin, and Swift bindings over time.

Install

go get github.com/lightninglabs/tap-sdk@v0.3.0

Add the protobuf replacement required by the LND and tapd RPC packages to your application module (Go does not inherit dependency replacements):

go mod edit -replace=google.golang.org/protobuf=github.com/lightninglabs/protobuf-go-hex-display@v1.34.2-hex-display
go mod tidy

Compatibility

tap-sdk tapd / Taproot Assets lnd Go
v0.3.x, main v0.8.5 or newer v0.21.4-beta 1.26.0+
v0.2.x v0.8.3 v0.21.3-beta 1.26.0+
v0.1.x v0.8.0 or newer v0.21.0-beta or newer 1.25.10+

The v0.3.x line requires tapd v0.8.5 or newer. See Compatibility for upgrade details.

The SDK remains pre-v1; public APIs may change between minor releases.

Quick Start

package main

import (
	"context"
	"log"

	tapsdk "github.com/lightninglabs/tap-sdk"
	tapgrpc "github.com/lightninglabs/tap-sdk/grpc"
)

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

	client, err := tapgrpc.NewClient(&tapgrpc.Config{
		Host:     "localhost:10029",
		Network:  tapsdk.NetworkRegtest,
		TLS:      tapgrpc.TLSFromPath("/path/to/tls.cert"),
		Macaroon: tapsdk.MacaroonFromPath("/path/to/admin.macaroon"),
	})
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	wallet := tapsdk.NewWallet(client, tapsdk.NetworkRegtest)
	issuer := wallet.NewIssuer()

	token, err := issuer.CreateFungible(ctx, tapsdk.FungibleAssetSpec{
		Name:   "example-token",
		Amount: 1_000_000,
	})
	if err != nil {
		log.Fatal(err)
	}

	balance, err := wallet.GetBalance(ctx, token.AssetRef)
	if err != nil {
		log.Fatal(err)
	}

	log.Printf("asset=%s balance=%d", token.AssetRef, balance)
}

Packages

Package Role
github.com/lightninglabs/tap-sdk Public asset model, Wallet, Issuer, Universe, builders, errors, and all business types
github.com/lightninglabs/tap-sdk/grpc gRPC transport, TLS config, macaroon auth, tapd marshal/unmarshal
github.com/lightninglabs/tap-sdk/rest REST transport, TLS config, macaroon auth, WebSocket event streams
github.com/lightninglabs/tap-sdk/macaroon Low-level macaroon source helpers

Most application code imports the root package plus one transport package. Advanced integrations can use wallet.Client() to reach low-level methods without importing taprpc.

What You Can Build Today

  • Wallet apps that issue, receive, send, burn, and list Taproot Assets.
  • Services that mint fungibles, standalone NFTs, and NFT collections.
  • Indexing and discovery tools backed by universe roots and proofs.
  • Proof import/export flows for out-of-band delivery.
  • Ownership proof flows for proving wallet control of assets.
  • Regtest-backed test suites that exercise both gRPC and REST transports.

Lightning-native Taproot Assets flows such as RFQ, price oracles, asset channels, and Portfolio Pilot are intentionally outside the current SDK surface.

Demos

  • Remote Signing Coordinator - runnable regtest demo for reviewing and signing external Issuance requests through a Go coordinator and Next.js dashboard.

Documentation

License

Licensed under the MIT License.

Documentation

Index

Constants

View Source
const (
	// AssetTypeNormal is tapd's name for a fungible asset.
	AssetTypeNormal AssetType = 0

	// AssetTypeCollectible is tapd's name for a non-fungible asset.
	AssetTypeCollectible AssetType = 1

	// AssetTypeFungible is the SDK business name for a fungible token.
	AssetTypeFungible = AssetTypeNormal

	// AssetTypeNFT is the SDK business name for a non-fungible token.
	AssetTypeNFT = AssetTypeCollectible
)
View Source
const (
	// CustomAnchorBackendUnknown means the SDK cannot classify the backend.
	CustomAnchorBackendUnknown CustomAnchorBackendMode = unknownString

	// CustomAnchorBackendLocalTapd means the backend is local tapd.
	CustomAnchorBackendLocalTapd = CustomAnchorBackendMode(
		"local-tapd",
	)

	// CustomAnchorBackendRemoteTapd means the backend is remote tapd.
	CustomAnchorBackendRemoteTapd = CustomAnchorBackendMode(
		"remote-tapd",
	)

	// CustomAnchorBackendHosted means the backend is a hosted service.
	CustomAnchorBackendHosted CustomAnchorBackendMode = "hosted"

	// CustomAnchorBackendLightweight means the backend is a smaller service
	// that exposes only the SDK-required wallet, proof, or builder calls.
	CustomAnchorBackendLightweight = CustomAnchorBackendMode(
		"lightweight",
	)
)
View Source
const (
	// CustomAnchorCapabilityCommit commits asset changes into a
	// caller-visible anchor PSBT.
	CustomAnchorCapabilityCommit = CustomAnchorCapability(
		"custom_anchor_commit",
	)

	// CustomAnchorCapabilityCallerAnchorPSBT accepts a caller-supplied BTC
	// anchor PSBT template.
	CustomAnchorCapabilityCallerAnchorPSBT = CustomAnchorCapability(
		"caller_anchor_psbt",
	)

	// CustomAnchorCapabilitySkipFunding skips backend BTC wallet funding.
	CustomAnchorCapabilitySkipFunding = CustomAnchorCapability(
		"skip_funding",
	)

	// CustomAnchorCapabilityNoChangeOutput commits without adding
	// or selecting a BTC change output.
	CustomAnchorCapabilityNoChangeOutput = CustomAnchorCapability(
		"no_change_output",
	)

	// CustomAnchorCapabilityWalletFunding funds the BTC anchor from the
	// backend wallet.
	CustomAnchorCapabilityWalletFunding = CustomAnchorCapability(
		"wallet_funding",
	)

	// CustomAnchorCapabilitySkipBroadcast logs a transfer while leaving BTC
	// anchor broadcast to the caller.
	CustomAnchorCapabilitySkipBroadcast = CustomAnchorCapability(
		"skip_broadcast",
	)

	// CustomAnchorCapabilityP2AAnchorOutput supports pay-to-anchor or a
	// semantically equivalent external fee-bump policy.
	CustomAnchorCapabilityP2AAnchorOutput = CustomAnchorCapability(
		"p2a_anchor_output",
	)

	// CustomAnchorCapabilityExternalFeeBump supports caller fee bumps.
	CustomAnchorCapabilityExternalFeeBump = CustomAnchorCapability(
		"external_fee_bump",
	)

	// CustomAnchorCapabilityProofRegistration registers proof state
	// after the custom transfer is logged.
	CustomAnchorCapabilityProofRegistration = CustomAnchorCapability(
		"proof_registration",
	)

	// CustomAnchorCapabilityLocalVerification verifies the plan or
	// package in SDK/library code without trusting the backend.
	CustomAnchorCapabilityLocalVerification = CustomAnchorCapability(
		"local_verification",
	)

	// CustomAnchorCapabilityBackendVerification verifies the plan or
	// package through the backend.
	CustomAnchorCapabilityBackendVerification = CustomAnchorCapability(
		"backend_verification",
	)
)
View Source
const (
	// AssetProofPathMaxDepth bounds the number of unconfirmed transitions
	// retained in a path. Ark transaction trees are shallow, so a larger
	// value is more likely to be hostile input than a useful path.
	AssetProofPathMaxDepth = 64

	// AssetProofPathMaxConfirmedProofSize bounds the confirmed proof file.
	AssetProofPathMaxConfirmedProofSize = 32 * 1024 * 1024

	// AssetProofPathMaxStepSize bounds one serialized transition proof.
	AssetProofPathMaxStepSize = 4 * 1024 * 1024

	// AssetProofPathMaxSize bounds the complete encoded path, including
	// every recursively embedded co-input path.
	AssetProofPathMaxSize = 64 * 1024 * 1024

	// AssetProofPathMaxStepCoPaths bounds the co-input paths of one step,
	// so a merging transition carries at most 16 asset witnesses.
	AssetProofPathMaxStepCoPaths = 15

	// AssetProofPathMaxCoPathDepth bounds co-input path nesting below the
	// selected path. The bound is checked before nested content is
	// parsed, so hostile deep encodings fail without recursing into them.
	AssetProofPathMaxCoPathDepth = 3
)
View Source
const (
	// CustomAnchorVerificationScopeRequest covers the complete request.
	CustomAnchorVerificationScopeRequest CustomAnchorVerificationScope = "request"

	// CustomAnchorVerificationScopeInputProof covers proof-selected inputs.
	CustomAnchorVerificationScopeInputProof = CustomAnchorVerificationScope(
		"input_proof",
	)

	// CustomAnchorVerificationScopeAssetIdentity covers semantic and concrete
	// asset identity.
	CustomAnchorVerificationScopeAssetIdentity = CustomAnchorVerificationScope(
		"asset_identity",
	)

	// CustomAnchorVerificationScopeAmount covers asset conservation.
	CustomAnchorVerificationScopeAmount CustomAnchorVerificationScope = "amount"

	// CustomAnchorVerificationScopeOutputCommitment covers output asset
	// commitments.
	CustomAnchorVerificationScopeOutputCommitment = CustomAnchorVerificationScope(
		"output_commitment",
	)

	// CustomAnchorVerificationScopeAnchorOutput covers the BTC anchor template.
	CustomAnchorVerificationScopeAnchorOutput = CustomAnchorVerificationScope(
		"anchor_output",
	)

	// CustomAnchorVerificationScopePassiveAssets covers passive-asset policy.
	CustomAnchorVerificationScopePassiveAssets = CustomAnchorVerificationScope(
		"passive_assets",
	)

	// CustomAnchorVerificationScopeLossPolicy covers burn and loss bounds.
	CustomAnchorVerificationScopeLossPolicy = CustomAnchorVerificationScope(
		"loss_policy",
	)

	// CustomAnchorVerificationScopeCapability covers backend capabilities.
	CustomAnchorVerificationScopeCapability = CustomAnchorVerificationScope(
		"capability",
	)

	// CustomAnchorVerificationScopeBackendTrust covers backend-only checks.
	CustomAnchorVerificationScopeBackendTrust = CustomAnchorVerificationScope(
		"backend_trust",
	)
)
View Source
const (
	// CustomAnchorTransferPackageVersion is the current on-disk schema
	// version. Unknown versions are rejected instead of being decoded as the
	// current schema.
	CustomAnchorTransferPackageVersion uint16 = 1
)
View Source
const TaprootAssetsKeyFamily = 212

TaprootAssetsKeyFamily is the key family used to generate internal keys and script keys for Taproot Assets. This value must match the constant defined in the taproot-assets repository.

Variables

View Source
var (

	// ErrAssetProofPathInvalid reports malformed or unsafe path content.
	ErrAssetProofPathInvalid = errors.New("invalid asset proof path")

	// ErrAssetProofPathUnknownFormat reports an unsupported path encoding.
	ErrAssetProofPathUnknownFormat = errors.New(
		"unknown asset proof path format",
	)

	// ErrAssetProofPathUnknownPassiveAssets reports that the confirmed
	// anchor inventory was not proven complete.
	ErrAssetProofPathUnknownPassiveAssets = errors.New(
		"asset proof path passive asset inventory is unknown",
	)

	// ErrAssetProofPathPassiveAssets reports that the confirmed anchor
	// contains assets outside the tracked proof path.
	ErrAssetProofPathPassiveAssets = errors.New(
		"asset proof path contains passive assets",
	)

	// ErrAssetProofPathUnconfirmedAnchor reports that the host did not
	// attest the Bitcoin-level authorization and policy of an unconfirmed
	// anchor transition.
	ErrAssetProofPathUnconfirmedAnchor = errors.New(
		"asset proof path unconfirmed anchor is not verified",
	)
)
View Source
var (
	// ErrBuilderFinished is returned when attempting to use a TxBuilder
	// that has already completed its transaction.
	ErrBuilderFinished = errors.New("builder already finished")

	// ErrNotFunded is returned when attempting to sign a transaction
	// that hasn't been funded yet.
	ErrNotFunded = errors.New("transaction not funded")

	// ErrNotSigned is returned when attempting to complete a transaction
	// that hasn't been signed yet.
	ErrNotSigned = errors.New("transaction not signed")

	// ErrNotCommitted is returned when attempting to finish a transaction
	// that hasn't been committed yet.
	ErrNotCommitted = errors.New("transaction not committed")

	// ErrNoRecipients is returned when attempting to fund a transaction
	// with no recipients configured.
	ErrNoRecipients = errors.New("no recipients configured")

	// ErrNoReceiverKeys is returned when attempting to execute an
	// interactive transfer without setting receiver keys.
	ErrNoReceiverKeys = errors.New("receiver keys not set")

	// ErrNoAssetRef is returned when attempting to execute a transfer
	// without specifying a usable asset reference.
	ErrNoAssetRef = errors.New("asset ref not set")

	// ErrZeroAmount is returned when attempting to execute a transfer
	// with zero amount.
	ErrZeroAmount = errors.New("amount must be greater than zero")

	// ErrGroupKeyNotSupported is returned when a group-key AssetRef is
	// used in a context that cannot resolve it to a concrete issuance.
	ErrGroupKeyNotSupported = errors.New(
		"group-key AssetRef requires a wallet-backed asset resolver",
	)

	// ErrInsufficientBalance is returned when the wallet knows the asset
	// ref but cannot select enough spendable units for the requested
	// operation.
	ErrInsufficientBalance = errors.New("insufficient asset balance")

	// ErrInvalidAssetRef is returned when an AssetRef is malformed or is
	// rejected by tapd as an invalid asset identifier.
	ErrInvalidAssetRef = errors.New("invalid asset ref")

	// ErrPermissionDenied is returned when tapd rejects an operation because
	// the macaroon or user credentials do not have enough permissions.
	ErrPermissionDenied = errors.New("permission denied")

	// ErrUnauthenticated is returned when tapd rejects an operation because
	// authentication is missing or invalid.
	ErrUnauthenticated = errors.New("unauthenticated")

	// ErrProofNotFound is returned when tapd cannot locate a requested asset
	// proof.
	ErrProofNotFound = errors.New("proof not found")

	// ErrTapdPrecondition is returned when tapd rejects a request because a
	// daemon-side precondition is not satisfied.
	ErrTapdPrecondition = errors.New("tapd precondition failed")

	// ErrUnsupportedByTapd is returned when the connected tapd version does
	// not support the requested operation.
	ErrUnsupportedByTapd = errors.New("operation unsupported by tapd")

	// ErrUnsupportedCustomAnchorCapability is returned when an advanced
	// custom-anchor flow requires a backend capability that is unsupported or
	// unknown.
	ErrUnsupportedCustomAnchorCapability = errors.New(
		"custom-anchor capability unsupported",
	)

	// ErrUnconfirmedCustomAnchorPublish is returned when a package contains
	// compact unconfirmed proof-path steps. Current tapd publish/log requires
	// chain-confirmed input proofs in its local archive.
	ErrUnconfirmedCustomAnchorPublish = errors.New(
		"unconfirmed custom-anchor package cannot be published through tapd",
	)

	// ErrMixedAssetBatchUnsupported is returned when one high-level send
	// request contains recipients for multiple logical assets. Wallet.SendMulti
	// sends one logical asset in one tapd request.
	ErrMixedAssetBatchUnsupported = errors.New(
		"mixed-asset send batch unsupported",
	)

	// ErrAmountRequired is returned when attempting to send to a V2
	// address that does not embed an amount without specifying one.
	ErrAmountRequired = errors.New(
		"amount required for V2 address without an embedded amount",
	)

	// ErrAmountMismatch is returned when the caller provides an
	// explicit amount that does not match the amount embedded in the
	// destination address.
	ErrAmountMismatch = errors.New(
		"amount does not match the address-embedded amount",
	)

	// ErrAssetUnknown is returned by Wallet.GetBalance (and related
	// high-level helpers) when the wallet has no record of the asset
	// ref: no balance entry and no issuance or transfer root in the
	// local universe. Callers should detect it with errors.Is. A known
	// asset with zero confirmed units produces (0, nil) instead.
	ErrAssetUnknown = errors.New("asset ref is unknown to the wallet")

	// ErrNoProofs is returned when a proof bundle export/import path cannot
	// find any proof entries for a known asset ref.
	ErrNoProofs = errors.New("no proofs found for asset ref")

	// ErrIncompleteProofBundle is returned when a proof bundle is missing
	// entries or entry proof bytes.
	ErrIncompleteProofBundle = errors.New("proof bundle is incomplete")

	// ErrOwnershipProofRequired is returned when ownership verification is
	// attempted without proof bytes.
	ErrOwnershipProofRequired = errors.New("ownership proof is required")

	// ErrInvalidChallenge is returned when an ownership proof challenge is
	// explicitly set but is not a non-zero 32-byte value.
	ErrInvalidChallenge = errors.New("invalid ownership proof challenge")

	// ErrOwnershipAmountRequired is returned when proving fungible asset
	// ownership without an explicit amount.
	ErrOwnershipAmountRequired = errors.New(
		"ownership proof amount is required",
	)

	// ErrOwnershipProofInvalid is returned when ownership verification
	// completes but tapd reports the proof is invalid.
	ErrOwnershipProofInvalid = errors.New("ownership proof is invalid")

	// ErrAssetNameRequired is returned when an issuer call is missing the
	// asset or NFT name required by tapd.
	ErrAssetNameRequired = errors.New("asset name is required")

	// ErrMintBatchActive is returned by high-level issuer calls when tapd
	// already has a mint batch that has not reached a terminal state.
	ErrMintBatchActive = errors.New("mint batch is already active")

	// ErrWrongAssetType is returned when an AssetRef resolves successfully
	// but not to the kind of entity required by the operation.
	ErrWrongAssetType = errors.New("asset ref has the wrong asset type")

	// ErrAssetNotIssuable is returned when an operation requires a grouped
	// asset but the AssetRef resolves to a standalone issuance.
	ErrAssetNotIssuable = errors.New("asset ref is not an issuable grouped asset")

	// ErrMintResolveTimeout is returned when tapd accepted a high-level
	// issuer mint request but the SDK timed out before the wallet projection
	// exposed the resulting entity. This does not mean the mint failed. Callers
	// must inspect wallet assets, issuances, collections, or mint batches
	// before retrying to avoid duplicate issuance.
	ErrMintResolveTimeout = errors.New("mint result resolution timed out")

	// ErrMintResultNotFound is returned when the SDK resolved a wallet row for
	// an accepted mint but could not map it into the requested high-level
	// entity. This does not mean tapd rejected the mint; callers should inspect
	// wallet state before retrying.
	ErrMintResultNotFound = errors.New("mint result could not be mapped")

	// ErrExternalIssuanceKeyRequired is returned when an issuer call needs an
	// external issuance signature but no external key descriptor was provided.
	ErrExternalIssuanceKeyRequired = errors.New(
		"external issuance key is required",
	)

	// ErrExternalIssuanceSignerRequired is returned when an external issuance
	// key is configured but no signer was provided to complete the mint.
	ErrExternalIssuanceSignerRequired = errors.New(
		"external issuance signer is required",
	)

	// ErrExternalIssuanceRequestNotFound is returned when tapd does not return
	// an issuance signing payload after an external signer was configured.
	ErrExternalIssuanceRequestNotFound = errors.New(
		"external issuance signing request not found",
	)

	// ErrExternalIssuanceSignatureRequired is returned when an external signer
	// did not return a signed issuance PSBT.
	ErrExternalIssuanceSignatureRequired = errors.New(
		"external issuance signature is required",
	)

	// ErrUniverseHostRequired is returned when a universe sync request does
	// not specify the remote universe host.
	ErrUniverseHostRequired = errors.New("universe host is required")

	// ErrInvalidUniverseHost is returned when a universe sync host is not a
	// host:port address accepted by the high-level universe facade.
	ErrInvalidUniverseHost = errors.New("invalid universe host")

	// ErrDuplicateAssetRef is returned when a batch call receives the same
	// asset ref more than once.
	ErrDuplicateAssetRef = errors.New("duplicate asset ref")

	// ErrUniverseProofTypeRequired is returned when a universe proof query
	// requires an explicit issuance or transfer proof type.
	ErrUniverseProofTypeRequired = errors.New(
		"universe proof type is required",
	)

	// ErrInvalidPagination is returned when pagination options are malformed.
	ErrInvalidPagination = errors.New("invalid pagination")
)

Sentinel errors for common SDK error conditions.

View Source
var ErrInvalidFeeRate = errors.New("invalid fee rate")

ErrInvalidFeeRate is returned when a fee rate cannot be parsed or represented.

View Source
var ErrMixedRecipientAmounts = errors.New(
	"recipients mix explicit and embedded amounts",
)

ErrMixedRecipientAmounts is returned by the low-level SendAsset when a single request mixes recipients with explicit amounts and recipients relying on address-embedded amounts. tapd's wire format does not support mixing the two paths; Wallet.SendMulti normalises such inputs before reaching the low-level RPC.

Functions

func EncodeAddress

func EncodeAddress(addr *Address, network Network) (string, error)

EncodeAddress is the inverse of DecodeAddress. It accepts an Address whose AddressVersion, AssetVersion, AssetRef, key material, amount, and proof courier are set, and produces the bech32m-encoded Tap address string for the given network.

HRP selection is driven by the network argument so tests and application code don't need to know the HRP table. TaprootOutputKey and AssetType are ignored — they are not part of the address TLV.

func SetAnchorOutputTaprootAssetRoot added in v0.2.0

func SetAnchorOutputTaprootAssetRoot(anchorPSBT []byte, outputIndex int,
	root Hash) ([]byte, error)

SetAnchorOutputTaprootAssetRoot records the given Taproot Asset commitment root on the anchor PSBT output at the given index, using the same custom PSBT field tapd writes when committing an anchor transaction. It returns the re-serialized PSBT. This is intended for template tooling and test fixtures; in normal operation tapd records the field itself.

func ValidateOwnershipChallenge

func ValidateOwnershipChallenge(challenge []byte) error

ValidateOwnershipChallenge checks the wire-level ownership challenge. A nil or empty challenge means the proof is not challenge-bound.

Types

type Address

type Address struct {
	// Encoded is the bech32m encoded Taproot Asset address string.
	// This is the canonical representation used for sharing with senders.
	Encoded string

	// AssetRef is the SDK's user-facing asset identifier for the address.
	AssetRef AssetRef

	// AssetType indicates whether this is a normal or collectible asset.
	AssetType AssetType

	// Amount is the number of asset units expected at this address.
	// For V2 addresses, this may be zero to allow sender-chosen amounts.
	Amount uint64

	// ScriptKey is the Taproot output key the asset will be locked to.
	ScriptKey PubKey

	// InternalKey is the internal key for the on-chain anchor output.
	InternalKey PubKey

	// TapscriptSibling is the optional serialized tapscript sibling preimage.
	// Used when additional script paths exist alongside the asset commitment.
	TapscriptSibling []byte

	// TaprootOutputKey is the tweaked key for the on-chain Bitcoin output.
	TaprootOutputKey XOnlyPubKey

	// ProofCourierAddr is the address of the proof courier service.
	// For V2 addresses, this is mandatory and must be an auth mailbox URL.
	ProofCourierAddr string

	// AssetVersion is the asset version for transfers to this address.
	AssetVersion AssetVersion

	// AddressVersion is the address format version (V0, V1, or V2).
	AddressVersion AddressVersion
}

Address represents a Taproot Asset address for receiving assets.

func DecodeAddress

func DecodeAddress(addr string) (*Address, error)

DecodeAddress decodes a bech32m-encoded Taproot Asset address locally, without contacting tapd. The returned Address populates the fields that are recoverable from the address string alone:

  • AssetRef (from group key for grouped assets unless a concrete non-zero asset ID is present, otherwise asset ID)
  • AddressVersion, AssetVersion
  • Amount
  • ScriptKey, InternalKey
  • TapscriptSibling, ProofCourierAddr

TaprootOutputKey and AssetType are left unset — deriving them requires the asset commitment and the asset genesis, both of which live server-side.

Unknown odd TLV types are skipped for forward compatibility with future protocol extensions.

type AddressEvent

type AddressEvent struct {
	// CreationTime is the Unix timestamp when the event was created.
	CreationTime uint64

	// Address is the address that received the transfer.
	Address *Address

	// Status is the current status of the incoming transfer.
	Status AddressEventStatus

	// Outpoint is the Bitcoin outpoint containing the inbound transfer.
	// Format: "txid:index"
	Outpoint string

	// UTXOAmountSat is the amount in satoshis transferred on-chain.
	// This is independent of the asset amount.
	UTXOAmountSat uint64

	// TaprootSibling is the taproot sibling hash used for the output.
	TaprootSibling []byte

	// ConfirmationHeight is the block height where the output was confirmed.
	// Zero means the output is unconfirmed.
	ConfirmationHeight uint32

	// HasProof indicates whether a proof file exists for this transfer.
	HasProof bool
}

AddressEvent represents an incoming asset transfer event for an address.

type AddressEventStatus

type AddressEventStatus uint8

AddressEventStatus represents the status of an incoming address transfer.

const (
	// AddressEventStatusUnknown indicates an unknown status.
	AddressEventStatusUnknown AddressEventStatus = 0

	// AddressEventStatusTransactionDetected means the on-chain transaction
	// was detected in the mempool or a block.
	AddressEventStatusTransactionDetected AddressEventStatus = 1

	// AddressEventStatusTransactionConfirmed means the transaction was
	// confirmed in a block.
	AddressEventStatusTransactionConfirmed AddressEventStatus = 2

	// AddressEventStatusProofReceived means the asset proof was received
	// from the sender via the proof courier.
	AddressEventStatusProofReceived AddressEventStatus = 3

	// AddressEventStatusCompleted means the transfer is complete and the
	// asset is available in the wallet.
	AddressEventStatusCompleted AddressEventStatus = 4
)

type AddressQuery

type AddressQuery struct {
	// CreatedAfter filters addresses created after this Unix timestamp.
	// Zero means no lower bound.
	CreatedAfter int64

	// CreatedBefore filters addresses created before this Unix timestamp.
	// Zero means no upper bound.
	CreatedBefore int64

	// Limit is the maximum number of addresses to return.
	// Zero means use server default.
	Limit int32

	// Offset is the number of addresses to skip for pagination.
	Offset int32
}

AddressQuery contains filters for querying stored addresses.

type AddressReceivesQuery

type AddressReceivesQuery struct {
	// FilterAddr filters events for a specific address string.
	// Empty means return events for all addresses.
	FilterAddr string

	// FilterStatus filters events by status.
	// Zero (Unknown) means return all statuses.
	FilterStatus AddressEventStatus

	// StartTimestamp filters events created at or after this Unix timestamp.
	// Zero means no lower bound.
	StartTimestamp uint64

	// EndTimestamp filters events created at or before this Unix timestamp.
	// Zero means no upper bound.
	EndTimestamp uint64

	// Offset is the number of events to skip for pagination.
	Offset int32

	// Limit is the maximum number of events to return.
	// Zero means use server default.
	Limit int32

	// Direction specifies sort order by creation time.
	Direction SortDirection
}

AddressReceivesQuery contains filters for querying address receive events.

type AddressVersion

type AddressVersion uint8

AddressVersion represents the version of a Taproot Asset address format. Values match taprpc.AddrVersion enum (0 is unspecified).

const (
	// AddressVersionV0 is the initial address version using asset ID only.
	AddressVersionV0 AddressVersion = 1

	// AddressVersionV1 is the address version with improved encoding.
	AddressVersionV1 AddressVersion = 2

	// AddressVersionV2 supports group keys and optional amounts.
	AddressVersionV2 AddressVersion = 3
)

type AltLeaf

type AltLeaf struct {
	// Value is the raw bytes of the leaf.
	Value []byte
}

AltLeaf represents an auxiliary leaf in the Taproot tree.

type AnchorChangeOutput added in v0.2.0

type AnchorChangeOutput struct {
	// Mode selects the change-output behavior.
	Mode AnchorChangeOutputMode

	// ExistingOutputIndex is the output index to use when Mode is
	// AnchorChangeOutputExisting.
	ExistingOutputIndex int32
}

AnchorChangeOutput describes how anchor change should be handled.

type AnchorChangeOutputMode added in v0.2.0

type AnchorChangeOutputMode uint8

AnchorChangeOutputMode identifies how anchor change should be handled while funding an anchor PSBT.

const (
	// AnchorChangeOutputUnspecified leaves change-output selection unset.
	AnchorChangeOutputUnspecified AnchorChangeOutputMode = iota

	// AnchorChangeOutputAdd asks the backend to add a new change output when
	// needed.
	AnchorChangeOutputAdd

	// AnchorChangeOutputExisting asks the backend to use an existing output as
	// the change output.
	AnchorChangeOutputExisting

	// AnchorChangeOutputNoNew asks the backend not to add a new change output
	// when possible.
	AnchorChangeOutputNoNew
)

type AnchorConfirmation added in v0.2.0

type AnchorConfirmation struct {
	// BlockHeight is the height of Block in the chain.
	BlockHeight uint32

	// Block is the serialized Bitcoin block containing the anchor
	// transaction.
	Block []byte
}

AnchorConfirmation carries the on-chain inclusion of one anchor transaction: the raw serialized block that contains it and the block's height.

type AnchorFee added in v0.2.0

type AnchorFee struct {
	// Mode selects the fee behavior.
	Mode AnchorFeeMode

	// FeeRate is used when Mode is AnchorFeeSatPerVByte.
	FeeRate FeeRate

	// TargetConf is used when Mode is AnchorFeeTargetConf.
	TargetConf uint32
}

AnchorFee describes how anchor transaction fees should be selected.

type AnchorFeeMode added in v0.2.0

type AnchorFeeMode uint8

AnchorFeeMode identifies how anchor transaction fees should be selected.

const (
	// AnchorFeeUnspecified leaves fee selection unset.
	AnchorFeeUnspecified AnchorFeeMode = iota

	// AnchorFeeSatPerVByte uses an explicit sat/vB fee rate.
	AnchorFeeSatPerVByte

	// AnchorFeeTargetConf lets the backend estimate fees for a confirmation
	// target.
	AnchorFeeTargetConf
)

type AnchorFundingPlan added in v0.2.0

type AnchorFundingPlan struct {
	// ChangeOutput selects how the backend handles anchor change.
	ChangeOutput AnchorChangeOutput

	// Fee selects the anchor fee strategy.
	Fee AnchorFee

	// CustomLockID optionally identifies lnd UTXO locks created while funding.
	CustomLockID []byte

	// LockExpirationSeconds optionally overrides the backend lock duration.
	LockExpirationSeconds uint64

	// SkipFunding skips backend PSBT funding and only commits asset outputs.
	SkipFunding bool
}

AnchorFundingPlan describes backend funding options for an anchor PSBT.

type AnchorSigner

type AnchorSigner func(ctx context.Context, anchorPsbt []byte) ([]byte, error)

AnchorSigner signs and finalizes the BTC anchor PSBT returned by tapd after Commit. The callback should return the PSBT that PublishAndLogTransfer can extract and broadcast.

type AnchorTransaction

type AnchorTransaction struct {
	// AnchorPsbt is the anchor transaction PSBT packet.
	AnchorPsbt []byte

	// ChangeOutputIndex is the index of the change output, or -1 if
	// no change was produced.
	ChangeOutputIndex int32

	// ChainFeesSats is the total on-chain fees paid in satoshis.
	ChainFeesSats int64

	// TargetFeeRate is the target fee rate.
	TargetFeeRate FeeRate

	// LndLockedUtxos lists the UTXO lock leases acquired from lnd.
	LndLockedUtxos []Outpoint

	// FinalTx is the signed anchor transaction that was broadcast.
	FinalTx []byte
}

AnchorTransaction contains on-chain anchor transaction details for a send event.

type Asset

type Asset struct {
	// AssetRef is the stable SDK identifier for this asset.
	AssetRef AssetRef

	// Type is the asset type.
	Type AssetType

	// Name is the human-readable asset name.
	Name string

	// MetaHash is the asset metadata hash.
	MetaHash Hash

	// Amount is the sum of wallet rows returned by the ListAssets request. With
	// the default request this is the wallet-known confirmed, unspent, unleased
	// amount. For grouped fungibles, this may be larger than the amount a
	// single-tranche builder path can spend in one transfer.
	Amount uint64

	// CollectionRef identifies the collection this NFT belongs to. It is nil
	// for fungible assets and standalone NFTs.
	CollectionRef *AssetRef
}

Asset is the SDK's user-facing business entity for a wallet asset.

A grouped fungible token is one Asset keyed by its group AssetRef, with any underlying issuance/tranche records hidden by default. An ungrouped fungible has no group-level identifier, so it is surfaced as its own Asset keyed by asset-ID AssetRef. A non-fungible token is one Asset keyed by its unique asset-ID AssetRef. Collections are not Assets; use Collection and ListCollections for collection-level views.

type AssetFederationSyncConfig

type AssetFederationSyncConfig struct {
	// ID is the universe ID this config applies to.
	ID UniverseID

	// AllowSyncInsert enables federation insert for this asset.
	AllowSyncInsert bool

	// AllowSyncExport enables federation export for this asset.
	AllowSyncExport bool
}

AssetFederationSyncConfig is a per-asset federation sync policy.

type AssetGroupMember

type AssetGroupMember struct {
	// AssetRef is the SDK identifier for the containing group.
	AssetRef AssetRef

	// IssuanceID is the 32-byte protocol-level identifier of this issuance.
	IssuanceID AssetID

	// Amount is the asset amount.
	Amount uint64

	// LockTime is the optional absolute locktime.
	LockTime int32

	// RelativeLockTime is the optional relative locktime.
	RelativeLockTime int32

	// Tag is the name of the asset.
	Tag string

	// MetaHash is the metadata hash.
	MetaHash Hash

	// Type is the asset type.
	Type AssetType

	// Version is the asset version.
	Version uint8
}

AssetGroupMember is one protocol-level member returned by tapd's group listing RPC. It is not the SDK business Asset type; high-level callers should use Wallet.ListAssets, Wallet.ListCollections, or Wallet.ListIssuances.

type AssetGroupRecord

type AssetGroupRecord struct {
	// AssetRef is the SDK identifier for this group. Callers that need
	// the raw group public key can extract it via AssetRef.GroupKey().
	AssetRef AssetRef

	// Members are the concrete issuances or NFT items in this protocol group.
	Members []*AssetGroupMember
}

AssetGroupRecord represents a low-level Taproot Asset group listing from tapd. Use Wallet.ListAssets, Wallet.ListCollections, or Wallet.ListIssuances for the high-level business entities.

type AssetID

type AssetID [32]byte

AssetID is the 32-byte Taproot Asset identifier.

func ParseAssetID

func ParseAssetID(b []byte) (AssetID, error)

ParseAssetID parses a 32-byte asset ID from raw bytes.

func ParseAssetIDHex

func ParseAssetIDHex(s string) (AssetID, error)

ParseAssetIDHex parses a hex-encoded asset ID.

func (AssetID) IsZero

func (id AssetID) IsZero() bool

IsZero returns true when id is the all-zero sentinel value.

func (AssetID) String

func (id AssetID) String() string

String returns the hex encoding of the asset ID.

type AssetLeaf

type AssetLeaf struct {
	// Asset is the low-level asset record associated with this leaf, if
	// present.
	Asset *AssetRecord

	// Proof is the raw issuance or transfer proof bytes.
	Proof []byte
}

AssetLeaf is a leaf in the universe tree.

type AssetLeafKey

type AssetLeafKey struct {
	// Outpoint identifies the on-chain anchor point.
	Outpoint Outpoint

	// ScriptKey is the asset script key.
	ScriptKey PubKey
}

AssetLeafKey is a key in the universe tree, combining an outpoint and script key.

type AssetLeafKeysRequest

type AssetLeafKeysRequest struct {
	// ID identifies which universe to query.
	ID UniverseID

	// Offset is the page offset.
	Offset int32

	// Limit is the maximum number of keys to return.
	Limit int32

	// Direction is the page sort direction.
	Direction SortDirection
}

AssetLeafKeysRequest filters asset leaf key queries.

type AssetMeta

type AssetMeta struct {
	// Data is the raw metadata bytes. Limited to 1 MiB.
	Data []byte

	// Type is the metadata type.
	Type AssetMetaType

	// MetaHash is the hash of the TLV serialization of the meta.
	MetaHash Hash

	// UnknownOddTypes is a map of unknown odd TLV types encountered
	// during decoding.
	UnknownOddTypes map[uint64][]byte

	// DecimalDisplay is the number of decimal places for display.
	DecimalDisplay uint32

	// UniverseCommitments indicates whether the issuer publishes
	// universe supply commitments.
	UniverseCommitments bool

	// CanonicalUniverseURLs are the issuer's canonical universe URLs.
	CanonicalUniverseURLs []string

	// DelegationKey is the public key used to verify universe supply
	// commitment outputs and proofs.
	DelegationKey []byte
}

AssetMeta contains the metadata for an asset.

type AssetMetaType

type AssetMetaType uint8

AssetMetaType represents the type of asset metadata.

const (
	// AssetMetaTypeOpaque means the metadata is opaque bytes with no
	// assumed structure.
	AssetMetaTypeOpaque AssetMetaType = 0

	// AssetMetaTypeJSON means the metadata is structured JSON.
	AssetMetaTypeJSON AssetMetaType = 1
)

type AssetPacket

type AssetPacket struct {
	// AnchorTransaction is the raw bytes of the final Bitcoin anchor transaction.
	AnchorTransaction []byte

	// VirtualTransactions are the signed virtual asset transactions.
	VirtualTransactions [][]byte

	// PassiveAssetTransactions are the signed passive asset transactions.
	PassiveAssetTransactions [][]byte
}

AssetPacket represents a fully constructed and signed asset transfer packet ready for broadcasting.

type AssetProofPath added in v0.2.0

type AssetProofPath struct {
	// ConfirmedBaseProof is the complete proof file ending at the last
	// confirmed asset state of the selected lineage.
	ConfirmedBaseProof []byte

	// Steps are ordered from the first unconfirmed child transition to the
	// selected leaf in the transaction tree.
	Steps []AssetProofPathStep
}

AssetProofPath keeps a fully verified confirmed proof file followed by a compact sequence of unconfirmed transition proofs.

Derived IDs and summaries are deliberately absent from the persisted DTO. They are recomputed from ConfirmedBaseProof and Steps whenever the path is decoded or verified.

func (*AssetProofPath) Clone added in v0.2.0

func (p *AssetProofPath) Clone() *AssetProofPath

Clone returns a deep copy suitable for persistence or concurrent ownership.

func (*AssetProofPath) ConfirmProofFile added in v0.2.0

func (p *AssetProofPath) ConfirmProofFile(
	confirmations map[Hash]AnchorConfirmation) ([]byte, error)

ConfirmProofFile assembles a standard confirmed proof file for the path's final output once every step's anchor transaction has confirmed on chain. Confirmations are keyed by anchor transaction ID in natural byte order.

The result is the confirmed base proof file extended with one proof per step, each completed with its block header, height, and merkle inclusion proof. A merging step permanently embeds each of its co-input paths, confirmed recursively into a full file of its own, as its input files — the layout a confirmed multi-input transition proof carries. The caller's backend performs full validation, including chain anchoring, when the file is imported or spent; this assembly only guarantees structural completeness.

func (*AssetProofPath) ContentID added in v0.2.0

func (p *AssetProofPath) ContentID() (Hash, error)

ContentID returns a domain-separated commitment to the canonical path.

func (*AssetProofPath) MarshalBinary added in v0.2.0

func (p *AssetProofPath) MarshalBinary() ([]byte, error)

MarshalBinary returns the canonical, checksummed path encoding.

func (*AssetProofPath) UnmarshalBinary added in v0.2.0

func (p *AssetProofPath) UnmarshalBinary(encoded []byte) error

UnmarshalBinary decodes a canonical path only after all bounds, checksum, and structural policy checks pass.

func (*AssetProofPath) Validate added in v0.2.0

func (p *AssetProofPath) Validate() error

Validate checks bounded structural and policy invariants without trusting a backend or treating the unconfirmed steps as verified. Count, size, and depth bounds are enforced over the complete path tree before any proof content is decoded, so hostile shapes are rejected cheaply.

func (*AssetProofPath) Verify added in v0.2.0

Verify fully verifies the confirmed base through verifier, then locally chains every unconfirmed proof while skipping only block inclusion checks. Co-input paths are resolved recursively with the same engine before the step that merges them.

type AssetProofPathStep added in v0.2.0

type AssetProofPathStep struct {
	TransitionProof []byte

	// CoInputPaths are complete proof paths for the co-inputs merged by
	// this step. The transition must spend exactly the spine tip plus every
	// co-path tip, and every co-path must carry the same asset identity as
	// the selected lineage.
	CoInputPaths []*AssetProofPath
}

AssetProofPathStep is one witness-complete unconfirmed transition. TransitionProof uses the native single-proof encoding. It must contain all asset witnesses and commitment proofs needed for local verification.

func (*AssetProofPathStep) ContentID added in v0.2.0

func (s *AssetProofPathStep) ContentID() (Hash, error)

ContentID returns a domain-separated commitment to the transition proof.

func (*AssetProofPathStep) Summary added in v0.2.0

Summary decodes and derives the step's identity and resulting asset state. It does not cryptographically verify the transition against its predecessor.

type AssetProofPathStepSummary added in v0.2.0

type AssetProofPathStepSummary struct {
	// ContentID commits to the serialized transition proof.
	ContentID Hash

	// PreviousAnchorOutpoint is the anchor output consumed by the step.
	PreviousAnchorOutpoint Outpoint

	// AnchorOutpoint is the output containing the resulting asset state.
	AnchorOutpoint Outpoint

	// AnchorValueSat is the BTC value of the resulting anchor output.
	AnchorValueSat int64

	// AssetRef is the SDK-level identity of the resulting asset.
	AssetRef AssetRef

	// IssuanceID is the concrete asset issuance or tranche ID.
	IssuanceID AssetID

	// AssetType identifies a fungible or collectible asset.
	AssetType AssetType

	// Amount is the resulting asset amount.
	Amount uint64

	// ScriptKey locks the resulting asset state.
	ScriptKey PubKey

	// SplitAsset is true when this proof selects a non-root split output.
	SplitAsset bool
}

AssetProofPathStepSummary is derived from one transition proof.

type AssetProofPathSummary added in v0.2.0

type AssetProofPathSummary struct {
	// ContentID commits to the complete canonical path.
	ContentID Hash

	// ConfirmedBaseProofID identifies the confirmed proof-file bytes.
	ConfirmedBaseProofID Hash

	// Depth is the number of unconfirmed transitions in the path.
	Depth uint16

	// AssetRef is the SDK-level identity of the selected asset.
	AssetRef AssetRef

	// IssuanceID is the concrete asset issuance or tranche ID.
	IssuanceID AssetID

	// AssetType identifies a fungible or collectible asset.
	AssetType AssetType

	// Amount is the asset amount at the selected path tip.
	Amount uint64

	// ScriptKey locks the selected asset state.
	ScriptKey PubKey

	// AnchorOutpoint locates the selected state in its anchor transaction.
	AnchorOutpoint Outpoint

	// AnchorValueSat is the BTC value of the selected anchor output.
	AnchorValueSat int64
}

AssetProofPathSummary is the verified state at the selected path tip.

type AssetProofResponse

type AssetProofResponse struct {
	// Key is the original request key.
	Key UniverseKey

	// UniverseRoot is the root that includes this proof.
	UniverseRoot *UniverseRoot

	// UniverseInclusionProof is the raw MS-SMT inclusion proof.
	UniverseInclusionProof []byte

	// AssetLeaf is the leaf containing the asset and proof.
	AssetLeaf *AssetLeaf

	// MultiverseRoot is the root of the wider multiverse tree.
	MultiverseRoot *MerkleSumNode

	// MultiverseInclusionProof is the multiverse inclusion proof.
	MultiverseInclusionProof []byte
}

AssetProofResponse is the response from a universe proof query.

type AssetQuerySort

type AssetQuerySort int

AssetQuerySort controls the sort field for asset statistics queries.

const (
	// SortByNone applies no sorting.
	SortByNone AssetQuerySort = 0

	// SortByAssetName sorts by asset name.
	SortByAssetName AssetQuerySort = 1

	// SortByIssuanceID sorts by concrete issuance asset ID.
	SortByIssuanceID AssetQuerySort = 2

	// SortByAssetType sorts by asset type.
	SortByAssetType AssetQuerySort = 3

	// SortByTotalSyncs sorts by total sync count.
	SortByTotalSyncs AssetQuerySort = 4

	// SortByTotalProofs sorts by total proof count.
	SortByTotalProofs AssetQuerySort = 5

	// SortByGenesisHeight sorts by genesis block height.
	SortByGenesisHeight AssetQuerySort = 6

	// SortByTotalSupply sorts by total asset supply.
	SortByTotalSupply AssetQuerySort = 7
)

type AssetRecord

type AssetRecord struct {
	// AssetRef is the SDK's user-facing identifier inferred for this concrete
	// row. Grouped records use the group AssetRef; ungrouped records use the
	// issuance asset-ID AssetRef.
	AssetRef AssetRef

	// Version is the asset version.
	Version uint8

	// Genesis is the protocol issuance genesis for this concrete record.
	Genesis IssuanceGenesis

	// Amount is the asset amount.
	Amount uint64

	// LockTime is the CLTV lock time.
	LockTime uint64

	// RelativeLockTime is the CSV lock time.
	RelativeLockTime uint64

	// ScriptVersion is the script version.
	ScriptVersion uint16

	// ScriptKey is the script key.
	ScriptKey ScriptKey

	// AltLeaves are the auxiliary leaves.
	AltLeaves []AltLeaf
}

AssetRecord is the low-level tapd wallet/output row for a concrete asset commitment. Most application code should use Asset, Collection, and Issuance returned by the high-level Wallet methods instead.

type AssetRef

type AssetRef string

AssetRef is the SDK's user-facing asset identifier.

It is intentionally opaque. Callers should treat it as a stable string to store, compare, log, and pass back into SDK methods. Internally it encodes either a protocol asset ID or a group key, but callers should not need to care which one was used.

GroupKey and AssetID are exposed as escape hatches for the rare consumer that genuinely needs to peek at the underlying protocol identifier (for example, cross-referencing a non-SDK data source). They are primarily intended for SDK-internal marshaling at the RPC boundary.

func AssetRefFromAsset

func AssetRefFromAsset(issuanceID AssetID, groupKey *PubKey) AssetRef

AssetRefFromAsset returns the semantic asset identifier for an issuance when asset type is not known. Grouped assets use the group key. Ungrouped assets use the issuance asset ID.

func AssetRefFromAssetID

func AssetRefFromAssetID(assetID AssetID) AssetRef

AssetRefFromAssetID creates an AssetRef for an asset identified by a protocol asset ID.

func AssetRefFromGroupKey

func AssetRefFromGroupKey(groupKey PubKey) AssetRef

AssetRefFromGroupKey creates an AssetRef for an asset identified by a group key.

func AssetRefFromSpecifier

func AssetRefFromSpecifier(assetID *AssetID, groupKey *PubKey) (AssetRef,
	error)

AssetRefFromSpecifier creates an AssetRef from protocol identifiers. When both are present, the group key takes precedence as the semantic asset identity.

func AssetRefFromTypedAsset

func AssetRefFromTypedAsset(issuanceID AssetID, groupKey *PubKey,
	assetType AssetType) AssetRef

AssetRefFromTypedAsset returns the semantic asset identifier for an issuance when the asset type is known. Fungibles use the group key when present; collectibles use the concrete asset ID even when they belong to a collection.

func ParseAssetRef

func ParseAssetRef(s string) (AssetRef, error)

ParseAssetRef validates an encoded asset reference and returns it in canonical lowercase form.

func (AssetRef) AssetID

func (r AssetRef) AssetID() (AssetID, bool)

AssetID returns the asset ID and true when the asset reference resolves to a protocol asset ID.

func (AssetRef) Equivalent

func (r AssetRef) Equivalent(other AssetRef) bool

Equivalent reports whether two asset refs identify the same asset. Asset ID refs must match exactly. Group-key refs compare the x-only public key so a 33-byte compressed group key from wallet RPCs matches a 32-byte x-only key surfaced by universe RPCs.

func (AssetRef) GroupKey

func (r AssetRef) GroupKey() (PubKey, bool)

GroupKey returns the group key and true when the asset reference resolves to a group key.

func (AssetRef) IsAssetIDRef

func (r AssetRef) IsAssetIDRef() bool

IsAssetIDRef returns true when the reference encodes an asset ID.

func (AssetRef) IsGroupRef

func (r AssetRef) IsGroupRef() bool

IsGroupRef returns true when the reference encodes a group key.

func (AssetRef) IsZero

func (r AssetRef) IsZero() bool

IsZero reports whether the asset reference is unset.

func (AssetRef) String

func (r AssetRef) String() string

String returns the encoded asset reference string.

func (AssetRef) Validate

func (r AssetRef) Validate() error

Validate checks whether the asset reference string is well-formed.

type AssetRootRequest

type AssetRootRequest struct {
	// WithAmountsByID includes per-asset-ID amounts for grouped assets.
	WithAmountsByID bool

	// Offset is the page offset.
	Offset int32

	// Limit is the maximum number of roots to return.
	Limit int32

	// Direction is the page sort direction.
	Direction SortDirection
}

AssetRootRequest configures pagination for AssetRoots queries.

type AssetStatsAsset

type AssetStatsAsset struct {
	// AssetRef is the SDK's user-facing identifier for the asset.
	AssetRef AssetRef

	// IssuanceID is the 32-byte protocol-level identifier for the specific
	// issuance/tranche represented by this stats record.
	IssuanceID AssetID

	// GenesisPoint is the genesis outpoint string.
	GenesisPoint string

	// TotalSupply is the total units minted.
	TotalSupply int64

	// AssetName is the human-readable name.
	AssetName string

	// AssetType is the type (normal or collectible).
	AssetType AssetType

	// GenesisHeight is the block height at creation.
	GenesisHeight int32

	// GenesisTimestamp is the block timestamp (Unix seconds).
	GenesisTimestamp int64

	// AnchorPoint is the current anchor point string.
	AnchorPoint string

	// DecimalDisplay is the number of decimal places.
	DecimalDisplay uint32
}

AssetStatsAsset is a per-asset statistics record.

type AssetStatsQuery

type AssetStatsQuery struct {
	// AssetNameFilter filters by asset name substring.
	AssetNameFilter string

	// AssetRefFilter filters by a specific asset.
	AssetRefFilter *AssetRef

	// AssetTypeFilter restricts results to a specific asset type.
	AssetTypeFilter AssetTypeFilter

	// SortBy controls the sort field.
	SortBy AssetQuerySort

	// Offset is the pagination offset.
	Offset int32

	// Limit is the pagination page size.
	Limit int32

	// Direction is the sort direction.
	Direction SortDirection
}

AssetStatsQuery configures an asset statistics query.

type AssetStatsSnapshot

type AssetStatsSnapshot struct {
	// AssetRef is the SDK's user-facing identifier for the asset.
	AssetRef AssetRef

	// GroupKey is the group key, if the asset belongs to a group.
	GroupKey *PubKey

	// GroupSupply is the total group supply (zero for ungrouped assets).
	GroupSupply int64

	// GroupAnchor is the group anchor asset stats, if grouped.
	GroupAnchor *AssetStatsAsset

	// Asset is the single asset stats, if not grouped.
	Asset *AssetStatsAsset

	// TotalSyncs is the sync count.
	TotalSyncs int64

	// TotalProofs is the proof count.
	TotalProofs int64
}

AssetStatsSnapshot is a statistics snapshot for one asset or group.

type AssetTransfer

type AssetTransfer struct {
	// TransferTimestamp is the timestamp of the transfer in UTC Unix time
	// seconds.
	TransferTimestamp int64

	// TransferTxid is the anchor transaction ID (32 bytes, not reversed).
	TransferTxid [32]byte

	// AnchorTxid is the display-order transaction ID (string form).
	AnchorTxid string

	// AnchorTxHeightHint is the height hint of the anchor transaction.
	AnchorTxHeightHint uint32

	// AnchorTxChainFees is the total fees paid by the anchor transaction in
	// satoshis.
	AnchorTxChainFees int64

	// Inputs describes the set of spent assets.
	Inputs []TransferInput

	// Outputs describes the set of newly created asset outputs.
	Outputs []TransferOutput

	// AnchorTxBlockHash is the block hash of the blockchain block that contains
	// the anchor transaction (if confirmed).
	AnchorTxBlockHash [32]byte

	// AnchorTxBlockHashStr is the byte-reversed hash as a hex string (if
	// confirmed).
	AnchorTxBlockHashStr string

	// AnchorTxBlockHeight is the block height of the blockchain block that
	// contains the anchor transaction (0 if unconfirmed).
	AnchorTxBlockHeight uint32

	// Label is an optional short label for the transfer.
	Label string

	// AnchorTx is the raw anchor transaction bytes.
	AnchorTx []byte
}

AssetTransfer represents a wallet-recorded outgoing transfer.

type AssetType

type AssetType uint8

AssetType represents the type of asset.

type AssetTypeFilter

type AssetTypeFilter int

AssetTypeFilter controls asset type filtering in stats queries.

const (
	// FilterAssetNone returns all asset types.
	FilterAssetNone AssetTypeFilter = 0

	// FilterAssetNormal returns only normal (fungible) assets.
	FilterAssetNormal AssetTypeFilter = 1

	// FilterAssetCollectible returns only collectible assets.
	FilterAssetCollectible AssetTypeFilter = 2
)

type AssetVersion

type AssetVersion uint8

AssetVersion represents the version of asset encoding.

const (
	// AssetVersionV0 is the initial asset version.
	AssetVersionV0 AssetVersion = 0

	// AssetVersionV1 is the asset version with witness stripping support.
	AssetVersionV1 AssetVersion = 1
)

type BackupMode

type BackupMode uint8

BackupMode specifies the backup format to use when exporting an asset wallet backup.

const (
	// BackupModeRaw exports a full backup with complete proof data.
	BackupModeRaw BackupMode = iota

	// BackupModeCompact strips blockchain-derivable proof fields to reduce
	// backup size.
	BackupModeCompact

	// BackupModeOptimistic omits proof data and relies on universe fetches
	// during restore.
	BackupModeOptimistic
)

type Balance

type Balance struct {
	// AssetRef is the SDK identifier for the asset.
	AssetRef AssetRef

	// Balance is the confirmed amount owned by the wallet.
	Balance uint64
}

Balance is the wallet's confirmed amount for a semantic asset.

type BatchSibling

type BatchSibling struct {
	// FullTree provides the full tapscript tree.
	FullTree *TapscriptFullTree

	// Branch provides only the root branch hashes.
	Branch *TapBranch
}

BatchSibling selects the tapscript sibling used for a mint batch.

type BatchState

type BatchState uint8

BatchState is the lifecycle state of a minting batch.

const (
	// BatchStateUnknown is an unknown batch state.
	BatchStateUnknown BatchState = 0

	// BatchStatePending means the batch is still collecting assets.
	BatchStatePending BatchState = 1

	// BatchStateFrozen means the batch is sealed and no longer mutable.
	BatchStateFrozen BatchState = 2

	// BatchStateCommitted means the genesis transaction was built.
	BatchStateCommitted BatchState = 3

	// BatchStateBroadcast means the genesis transaction was broadcast.
	BatchStateBroadcast BatchState = 4

	// BatchStateConfirmed means the genesis transaction confirmed.
	BatchStateConfirmed BatchState = 5

	// BatchStateFinalized means the batch completed fully.
	BatchStateFinalized BatchState = 6

	// BatchStateSeedlingCancelled means an unfunded batch was cancelled.
	BatchStateSeedlingCancelled BatchState = 7

	// BatchStateSproutCancelled means a funded batch was cancelled.
	BatchStateSproutCancelled BatchState = 8
)

func (BatchState) String

func (s BatchState) String() string

String returns the stable name for a mint batch state.

type Burn

type Burn struct {
	// AssetRef is the user-facing identifier requested by the caller.
	AssetRef AssetRef

	// Amount is the number of units burned.
	Amount uint64

	// Note is optional user-defined metadata for this burn.
	Note string

	// Transfer is the wallet transfer that committed the burn.
	Transfer *AssetTransfer

	// Proof is the transition proof for the burn output.
	Proof *DecodedProof
}

Burn is the high-level result of burning asset units through Wallet.Burn.

type BurnAssetRequest

type BurnAssetRequest struct {
	// AssetRef identifies which asset to burn units from.
	AssetRef AssetRef

	// AmountToBurn is the number of asset units to burn. Must be
	// greater than zero.
	AmountToBurn uint64

	// ConfirmationText must be set to "assets will be destroyed" for
	// the burn to succeed. This is a safety check.
	ConfirmationText string

	// Note is optional user-defined metadata for this burn.
	Note string
}

BurnAssetRequest specifies parameters for burning asset units.

type BurnAssetResponse

type BurnAssetResponse struct {
	// BurnTransfer is the asset transfer containing the burn output.
	BurnTransfer *AssetTransfer

	// BurnProof is the transition proof for the burn output.
	BurnProof *DecodedProof
}

BurnAssetResponse contains the result of a burn operation.

type BurnOption

type BurnOption func(*BurnOptions)

BurnOption configures optional parameters for Wallet.Burn.

func WithBurnNote

func WithBurnNote(note string) BurnOption

WithBurnNote attaches user-defined metadata to a burn.

type BurnOptions

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

BurnOptions configures optional parameters for high-level burn operations.

type BurnRecord

type BurnRecord struct {
	// Note is user-defined metadata for the burn.
	Note string

	// AssetRef is the SDK's user-facing identifier for the burnt asset.
	AssetRef AssetRef

	// CollectionRef identifies the parent collection when the burnt asset
	// is an NFT collection item. It is nil for standalone NFTs and
	// fungible assets.
	CollectionRef *AssetRef

	// Type is the asset type reported by tapd for this burn. Use this
	// field for asset typing; AssetRef is the stable handle used to key
	// the burn record.
	Type AssetType

	// IssuanceID is the specific issuance/tranche that was burnt.
	IssuanceID AssetID

	// Amount is the number of burnt units.
	Amount uint64

	// AnchorTxid is the txid of the anchor transaction.
	AnchorTxid Hash
}

BurnRecord represents a single asset burn event from wallet history.

type CancelBatchResponse

type CancelBatchResponse struct {
	// BatchKey is the internal public key of the cancelled batch.
	BatchKey PubKey
}

CancelBatchResponse reports the cancelled batch key.

type Client

Client combines all sub-clients into a single interface.

type Collection

type Collection struct {
	// AssetRef is the stable SDK identifier for this collection.
	AssetRef AssetRef

	// ItemCount is the number of wallet-known NFT items in this collection.
	ItemCount uint64
}

Collection is a group of NFT assets. A collection is not itself an Asset.

type CollectionMintResult

type CollectionMintResult struct {
	// Collection is the collection-level entity keyed by group AssetRef.
	Collection *Collection

	// FirstItem is the NFT item minted to create the collection.
	FirstItem *Asset
}

CollectionMintResult is returned when creating a new NFT collection.

type CommitVirtualPsbtsRequest added in v0.2.0

type CommitVirtualPsbtsRequest struct {
	// AnchorPsbt is the caller-supplied BTC-level anchor PSBT template.
	AnchorPsbt []byte

	// VirtualPsbts are the active virtual asset PSBTs to commit.
	VirtualPsbts [][]byte

	// PassiveAssetPsbts are passive virtual asset PSBTs to commit alongside the
	// active PSBTs.
	PassiveAssetPsbts [][]byte

	// Funding controls backend anchor funding.
	Funding AnchorFundingPlan
}

CommitVirtualPsbtsRequest commits virtual PSBTs into an anchor PSBT template with V1 transition proofs.

func (*CommitVirtualPsbtsRequest) Validate added in v0.2.0

func (r *CommitVirtualPsbtsRequest) Validate() error

Validate checks that a virtual PSBT commit request can be sent.

type CommitVirtualPsbtsResponse added in v0.2.0

type CommitVirtualPsbtsResponse struct {
	// AnchorPsbt is the funded BTC-level anchor PSBT with asset commitments.
	AnchorPsbt []byte

	// VirtualPsbts are the updated active virtual asset PSBTs.
	VirtualPsbts [][]byte

	// PassiveAssetPsbts are the updated passive virtual asset PSBTs.
	PassiveAssetPsbts [][]byte

	// ChangeOutputIndex is the index of the anchor change output or -1 if no
	// change output was added.
	ChangeOutputIndex int32

	// LockedUTXOs are the lnd wallet outpoints locked while funding the anchor
	// transaction.
	LockedUTXOs []Outpoint
}

CommitVirtualPsbtsResponse is the result of committing virtual PSBTs into an anchor PSBT template.

type CommittedTransfer

type CommittedTransfer struct {
	// AnchorPsbt is the PSBT of the anchor transaction.
	AnchorPsbt []byte

	// VirtualPsbts are the committed virtual transaction PSBTs.
	VirtualPsbts [][]byte

	// PassiveAssetPsbts are the updated passive asset PSBTs.
	PassiveAssetPsbts [][]byte
}

CommittedTransfer represents the result of committing virtual transactions.

type ConfirmedProofVerification added in v0.2.0

type ConfirmedProofVerification struct {
	// AnchorAssetInventoryComplete asserts that the verifier examined the
	// full confirmed anchor commitment, not only one inclusion proof.
	AnchorAssetInventoryComplete bool

	// PassiveAssetCount is the number of other assets in the confirmed
	// anchor commitment. Compact paths currently require this to be zero.
	PassiveAssetCount uint32
}

ConfirmedProofVerification is the non-derivable part of confirmed proof verification. The SDK derives asset identity and state from the proof bytes; this result only attests whether the anchor's asset inventory is complete.

type ConfirmedProofVerifier added in v0.2.0

type ConfirmedProofVerifier interface {
	VerifyConfirmedProof(ctx context.Context,
		proofFile []byte) (*ConfirmedProofVerification, error)
}

ConfirmedProofVerifier fully verifies the confirmed base proof against the chain and reports whether its complete anchor asset inventory is known.

This interface intentionally uses SDK-only types. A tapd-backed adapter can perform header, merkle, proof, and inventory checks without exposing taproot-assets implementation types to applications.

type CustomAnchorAssetInputSummary added in v0.2.0

type CustomAnchorAssetInputSummary struct {
	// LogicalInputID is the stable caller-defined input identifier.
	LogicalInputID string `json:"logical_input_id"`

	// LogicalInputIndex is the caller-facing input position before one
	// logical selection is expanded into concrete issuance packets.
	LogicalInputIndex uint32 `json:"logical_input_index"`

	// PacketIndex identifies the committed virtual packet.
	PacketIndex uint32 `json:"packet_index"`

	// PacketRole selects the active or passive packet collection.
	PacketRole CustomAnchorPacketRole `json:"packet_role"`

	// VirtualInputIndex identifies the input within PacketIndex.
	VirtualInputIndex uint32 `json:"virtual_input_index"`

	// AnchorInputIndex identifies the input in the anchor transaction.
	AnchorInputIndex uint32 `json:"anchor_input_index"`

	// AssetRef is the caller-facing asset identity requested for the input.
	AssetRef AssetRef `json:"asset_ref"`

	// IssuanceID is the concrete asset issuance/tranche spent by this
	// input.
	IssuanceID AssetID `json:"issuance_id"`

	// AssetType is the concrete asset type for the input.
	AssetType AssetType `json:"asset_type"`

	// AnchorOutpoint is the BTC output that held the spent asset
	// commitment.
	AnchorOutpoint Outpoint `json:"anchor_outpoint"`

	// ScriptKey is the spent asset script key.
	ScriptKey PubKey `json:"script_key"`

	// Amount is the number of asset units spent.
	Amount uint64 `json:"amount"`

	// ProofSource identifies and persists the confirmed file or compact path
	// that selected this exact input.
	ProofSource CustomAnchorProofSourceSummary `json:"proof_source"`
}

CustomAnchorAssetInputSummary describes one committed asset input.

type CustomAnchorAssetOutputSummary added in v0.2.0

type CustomAnchorAssetOutputSummary struct {
	// LogicalOutputID is the stable caller-defined output identifier.
	LogicalOutputID string `json:"logical_output_id"`

	// LogicalOutputIndex is the caller-facing output position before one
	// logical allocation is expanded into concrete issuance packets.
	LogicalOutputIndex uint32 `json:"logical_output_index"`

	// PacketIndex identifies the committed virtual packet.
	PacketIndex uint32 `json:"packet_index"`

	// PacketRole selects the active or passive packet collection.
	PacketRole CustomAnchorPacketRole `json:"packet_role"`

	// VirtualOutputIndex identifies the output within PacketIndex.
	VirtualOutputIndex uint32 `json:"virtual_output_index"`

	// AnchorOutputIndex is the output index in the anchor transaction.
	AnchorOutputIndex uint32 `json:"anchor_output_index"`

	// AssetRef is the caller-facing asset identity created at this output.
	AssetRef AssetRef `json:"asset_ref"`

	// IssuanceID is the concrete asset issuance/tranche created at this
	// output.
	IssuanceID AssetID `json:"issuance_id"`

	// AssetType is the concrete asset type for the output.
	AssetType AssetType `json:"asset_type"`

	// AnchorOutpoint is the BTC output that holds the new asset commitment.
	AnchorOutpoint Outpoint `json:"anchor_outpoint"`

	// AnchorValueSat is the BTC value assigned to the asset-bearing output.
	AnchorValueSat int64 `json:"anchor_value_sat"`

	// TaprootAssetRoot is the root of the Taproot Asset commitment before
	// combining it with the host-supplied tapscript sibling. Hosts such as
	// SwapDK use this root to compose their policy tree and control blocks.
	TaprootAssetRoot Hash `json:"taproot_asset_root"`

	// TaprootMerkleRoot is the final BIP341 root that combines the Taproot
	// Asset commitment with the optional host-supplied tapscript sibling.
	// It is the tweak committed to by the anchor output key.
	TaprootMerkleRoot Hash `json:"taproot_merkle_root"`

	// ScriptKey is the asset script key for the new output.
	ScriptKey PubKey `json:"script_key"`

	// Amount is the number of asset units created at this output.
	Amount uint64 `json:"amount"`

	// ScriptMode records how the active output script was constructed. Passive
	// reanchors use CustomAssetScriptUnspecified because their key is retained.
	ScriptMode CustomAssetScriptMode `json:"script_mode"`

	// ProofDelivery preserves the complete host-owned delivery metadata.
	ProofDelivery CustomAssetProofDelivery `json:"proof_delivery"`

	// OPTrueSpend contains the exact asset script-path witness data when the
	// output was built with CustomAssetScriptOPTrue. Other output modes leave
	// it nil.
	OPTrueSpend *CustomAssetOPTrueSpendInfo `json:"op_true_spend,omitempty"`
}

CustomAnchorAssetOutputSummary describes one committed asset output.

type CustomAnchorBackendMode added in v0.2.0

type CustomAnchorBackendMode string

CustomAnchorBackendMode identifies the kind of backend that reported a custom-anchor capability set.

type CustomAnchorCallerFundedExact added in v0.2.0

type CustomAnchorCallerFundedExact struct{}

CustomAnchorCallerFundedExact selects an exact caller-funded anchor PSBT.

type CustomAnchorCallerSignedPlan added in v0.2.0

type CustomAnchorCallerSignedPlan struct{}

CustomAnchorCallerSignedPlan declares an anchor input signed entirely by the caller, outside the SDK's signing-request flow: typically a funding input from the caller's own on-chain wallet on a caller-funded anchor.

type CustomAnchorCapabilities added in v0.2.0

type CustomAnchorCapabilities struct {
	BackendMode CustomAnchorBackendMode

	CustomAnchorCommit       CustomAnchorCapabilityStatus
	CallerSuppliedAnchorPSBT CustomAnchorCapabilityStatus
	SkipFunding              CustomAnchorCapabilityStatus
	NoChangeOutput           CustomAnchorCapabilityStatus
	WalletFunding            CustomAnchorCapabilityStatus
	SkipBroadcast            CustomAnchorCapabilityStatus
	P2AAnchorOutput          CustomAnchorCapabilityStatus
	ExternalFeeBump          CustomAnchorCapabilityStatus
	ProofRegistration        CustomAnchorCapabilityStatus
	LocalVerification        CustomAnchorCapabilityStatus
	BackendVerification      CustomAnchorCapabilityStatus
}

CustomAnchorCapabilities reports backend support for advanced custom-anchor transaction operations. Unknown capabilities are treated as unavailable by Require so callers fail before signing.

func DefaultTapdCustomAnchorCapabilities added in v0.2.0

func DefaultTapdCustomAnchorCapabilities() CustomAnchorCapabilities

DefaultTapdCustomAnchorCapabilities returns an SDK-version-pinned assumption profile for tapd-compatible transports. This is not runtime discovery: tapd does not currently expose a capability RPC. Features not proven by the pinned API are deliberately left unknown so callers fail closed.

func (CustomAnchorCapabilities) Require added in v0.2.0

func (c CustomAnchorCapabilities) Require(
	capabilities ...CustomAnchorCapability) error

Require returns an unsupported-capability error unless every requested capability is explicitly supported.

func (CustomAnchorCapabilities) Support added in v0.2.0

Support returns the reported status for a capability. Unknown capability names are treated as unknown rather than supported.

type CustomAnchorCapability added in v0.2.0

type CustomAnchorCapability string

CustomAnchorCapability names a backend feature used by the advanced custom-anchor transaction flow.

type CustomAnchorCapabilityProvider added in v0.2.0

type CustomAnchorCapabilityProvider interface {
	CustomAnchorCapabilities(ctx context.Context) (
		*CustomAnchorCapabilities, error)
}

CustomAnchorCapabilityProvider is an optional extension implemented by clients that can provide a custom-anchor capability profile. It is kept separate from WalletKitClient so existing clients and test doubles aren't forced to implement an SDK-specific discovery method that tapd does not expose over RPC.

Implementations must distinguish an explicitly unsupported feature from an unknown one. Callers fail closed for both states.

type CustomAnchorCapabilityStatus added in v0.2.0

type CustomAnchorCapabilityStatus uint8

CustomAnchorCapabilityStatus describes whether a capability is available.

const (
	// CustomAnchorCapabilityUnknown means the backend did not report
	// a usable answer for the capability.
	CustomAnchorCapabilityUnknown CustomAnchorCapabilityStatus = iota

	// CustomAnchorCapabilityUnsupported means the backend reports that the
	// capability is not available.
	CustomAnchorCapabilityUnsupported

	// CustomAnchorCapabilitySupported means the backend reports that the
	// capability is available.
	CustomAnchorCapabilitySupported
)

func (CustomAnchorCapabilityStatus) String added in v0.2.0

String returns the stable text form of the support status.

func (CustomAnchorCapabilityStatus) Supported added in v0.2.0

func (s CustomAnchorCapabilityStatus) Supported() bool

Supported returns true when the capability can be used safely.

type CustomAnchorCommitAttemptError added in v0.2.0

type CustomAnchorCommitAttemptError struct {
	Err            error
	FundingLock    CustomAnchorFundingLockMetadata
	OutcomeUnknown bool
}

CustomAnchorCommitAttemptError reports a commit call that returned no usable response. If OutcomeUnknown is true, the backend may have committed the transfer and retained wallet leases before the transport failed. The caller must reconcile those leases before retrying.

func (*CustomAnchorCommitAttemptError) Error added in v0.2.0

Error returns the commit-attempt failure and highlights ambiguous results.

func (*CustomAnchorCommitAttemptError) Unwrap added in v0.2.0

Unwrap returns the underlying transport or backend error.

type CustomAnchorCommitOptions added in v0.2.0

type CustomAnchorCommitOptions struct {
	// Publish is the publish/log policy persisted for crash recovery.
	Publish CustomAnchorPublishMetadata
}

CustomAnchorCommitOptions contains metadata that must be bound into the persisted package before external signing begins.

type CustomAnchorCommitResponseError added in v0.2.0

type CustomAnchorCommitResponseError struct {
	Err         error
	LockedUTXOs []CustomAnchorLockedUTXO
}

CustomAnchorCommitResponseError reports a local verification or persistence failure after the backend returned a commit response. LockedUTXOs must be released explicitly before abandoning the attempt.

func (*CustomAnchorCommitResponseError) Error added in v0.2.0

Error returns the post-response commit failure.

func (*CustomAnchorCommitResponseError) Unwrap added in v0.2.0

Unwrap returns the underlying local failure.

type CustomAnchorExternalP2AFeeBump added in v0.2.0

type CustomAnchorExternalP2AFeeBump struct {
	// P2AOutputIndex is the zero-based P2A output index in AnchorPSBT.
	P2AOutputIndex uint32
}

CustomAnchorExternalP2AFeeBump identifies the caller's P2A output.

type CustomAnchorFundingLockMetadata added in v0.2.0

type CustomAnchorFundingLockMetadata struct {
	CustomLockID          []byte `json:"custom_lock_id"`
	LockExpirationSeconds uint64 `json:"lock_expiration_seconds"`
}

CustomAnchorFundingLockMetadata preserves the lock inputs known before the backend funding call. It does not invent lease IDs absent from tapd's reply.

type CustomAnchorFundingMode added in v0.2.0

type CustomAnchorFundingMode uint8

CustomAnchorFundingMode selects a high-level anchor funding policy.

const (
	// CustomAnchorFundingUnspecified is not a usable funding mode.
	CustomAnchorFundingUnspecified CustomAnchorFundingMode = iota

	// CustomAnchorFundingWalletFunded lets the backend wallet fund and add
	// change to the anchor transaction.
	CustomAnchorFundingWalletFunded

	// CustomAnchorFundingCallerFundedExact preserves the exact caller-funded
	// anchor template without backend funding.
	CustomAnchorFundingCallerFundedExact

	// CustomAnchorFundingExternalP2AFeeBump preserves an externally funded
	// parent containing a caller-selected P2A output.
	CustomAnchorFundingExternalP2AFeeBump
)

type CustomAnchorFundingPlan added in v0.2.0

type CustomAnchorFundingPlan struct {
	// Mode selects the active funding variant.
	Mode CustomAnchorFundingMode

	// WalletFunded configures backend wallet funding.
	WalletFunded *CustomAnchorWalletFunding

	// CallerFundedExact selects an exact caller-funded template.
	CallerFundedExact *CustomAnchorCallerFundedExact

	// ExternalP2AFeeBump selects an external P2A fee-bump plan.
	ExternalP2AFeeBump *CustomAnchorExternalP2AFeeBump
}

CustomAnchorFundingPlan is a tagged high-level funding plan. Exactly one variant must be non-nil and must match Mode.

func (*CustomAnchorFundingPlan) Validate added in v0.2.0

func (p *CustomAnchorFundingPlan) Validate() error

Validate checks that exactly one high-level funding variant is selected.

type CustomAnchorFundingSummary added in v0.2.0

type CustomAnchorFundingSummary struct {
	// Mode is the high-level funding mode selected by the inspected plan.
	Mode CustomAnchorFundingMode `json:"mode"`

	// P2AOutputIndex is present only for external P2A fee-bump parents.
	P2AOutputIndex *uint32 `json:"p2a_output_index,omitempty"`

	// ActualFeeSat is the exact fee of the committed anchor transaction.
	ActualFeeSat uint64 `json:"actual_fee_sat"`

	// MaxFeeSat is the caller's hard ceiling for wallet-funded anchors. It is
	// zero for caller-funded exact and external zero-fee P2A parents.
	MaxFeeSat uint64 `json:"max_fee_sat"`
}

CustomAnchorFundingSummary binds the committed transaction to the funding policy that authorized it.

type CustomAnchorInputSigningPlan added in v0.2.0

type CustomAnchorInputSigningPlan struct {
	// InputIndex is the input in the committed anchor transaction.
	InputIndex uint32 `json:"input_index"`

	// KeyPath selects a single-signer Taproot key spend.
	KeyPath *CustomAnchorKeyPathSigningPlan `json:"key_path,omitempty"`

	// MuSig2 selects a final aggregate MuSig2 Taproot key spend.
	MuSig2 *CustomAnchorMuSig2SigningPlan `json:"musig2,omitempty"`

	// ScriptPath selects one exact Taproot leaf spend.
	ScriptPath *CustomAnchorScriptPathSigningPlan `json:"script_path,omitempty"`

	// CallerSigned declares an input whose witness the caller supplies
	// out of band. The SDK derives no signing request and the backend
	// must not sign it.
	CallerSigned *CustomAnchorCallerSignedPlan `json:"caller_signed,omitempty"`
}

CustomAnchorInputSigningPlan selects exactly one external spending path for one committed anchor input. Pointer variants model a tagged union; callers must set exactly one variant.

type CustomAnchorKeyPathSigningPlan added in v0.2.0

type CustomAnchorKeyPathSigningPlan struct {
	// Signer is the x-only internal key controlled by the signer.
	Signer XOnlyPubKey `json:"signer"`
}

CustomAnchorKeyPathSigningPlan identifies the internal key that must authorize a single-signer Taproot key spend.

type CustomAnchorKeyPathSigningRequest added in v0.2.0

type CustomAnchorKeyPathSigningRequest struct {
	ID                Hash
	PackageDigest     Hash
	InputIndex        uint32
	PrevOut           Outpoint
	PrevOutValueSat   int64
	PrevOutScript     []byte
	SighashType       uint32
	Sighash           Hash
	InternalKey       XOnlyPubKey
	TaprootMerkleRoot []byte
	Signer            XOnlyPubKey
}

CustomAnchorKeyPathSigningRequest contains all SDK-owned data required to review and sign a single-signer Taproot key spend.

type CustomAnchorLockedUTXO added in v0.2.0

type CustomAnchorLockedUTXO struct {
	// Outpoint identifies the locked BTC output.
	Outpoint Outpoint `json:"outpoint"`
}

CustomAnchorLockedUTXO identifies a BTC UTXO locked while funding an anchor. CommitVirtualPsbts currently returns only the outpoint, so the DTO deliberately does not invent lock IDs, values, or expiration metadata.

type CustomAnchorLossAllowance added in v0.2.0

type CustomAnchorLossAllowance struct {
	// AssetRef identifies the asset whose burn is being authorized.
	AssetRef AssetRef

	// MaxAmount is the maximum number of units that may be destroyed.
	MaxAmount uint64
}

CustomAnchorLossAllowance caps explicit burns for one semantic asset.

type CustomAnchorLossMode added in v0.2.0

type CustomAnchorLossMode uint8

CustomAnchorLossMode identifies whether irreversible asset loss is allowed.

const (
	// CustomAnchorLossReject rejects burn outputs and any amount imbalance.
	// This is the safe zero-value default.
	CustomAnchorLossReject CustomAnchorLossMode = iota

	// CustomAnchorLossBurn permits only confirmed, per-asset bounded burns.
	CustomAnchorLossBurn
)

type CustomAnchorLossPolicy added in v0.2.0

type CustomAnchorLossPolicy struct {
	// Mode selects reject or explicitly bounded burn behavior.
	Mode CustomAnchorLossMode

	// Allowances contains the maximum explicit burn for each asset.
	Allowances []CustomAnchorLossAllowance

	// ConfirmIrreversibleLoss must be true before any burn is allowed.
	ConfirmIrreversibleLoss bool
}

CustomAnchorLossPolicy bounds explicitly requested asset destruction.

func (*CustomAnchorLossPolicy) Validate added in v0.2.0

func (p *CustomAnchorLossPolicy) Validate() error

Validate checks that any irreversible loss is explicit and bounded.

type CustomAnchorMuSig2SigningPlan added in v0.2.0

type CustomAnchorMuSig2SigningPlan struct {
	// Participants are the ordered 33-byte compressed keys used for key
	// aggregation. Full keys preserve Y parity, so any cosigner key can
	// participate; callers whose aggregation sorts keys declare them
	// pre-sorted.
	Participants []PubKey `json:"participants"`

	// SessionContext is caller-defined public context used to distinguish
	// signing sessions. It must never contain a secret nonce.
	SessionContext []byte `json:"session_context"`
}

CustomAnchorMuSig2SigningPlan identifies an ordered MuSig2 participant set. Participant order is significant and is preserved in the signing request.

type CustomAnchorMuSig2SigningRequest added in v0.2.0

type CustomAnchorMuSig2SigningRequest struct {
	ID                Hash
	PackageDigest     Hash
	InputIndex        uint32
	PrevOut           Outpoint
	PrevOutValueSat   int64
	PrevOutScript     []byte
	SighashType       uint32
	Sighash           Hash
	InternalKey       XOnlyPubKey
	TaprootMerkleRoot []byte
	Participants      []PubKey
	SessionContext    []byte
}

CustomAnchorMuSig2SigningRequest contains the transaction digest and ordered participant set for an external MuSig2 session. Nonce generation, exchange, and session orchestration remain the signer's responsibility.

type CustomAnchorOutputCommitmentPreview added in v0.2.0

type CustomAnchorOutputCommitmentPreview struct {
	// LogicalOutputID is the stable caller-defined output allocation ID.
	LogicalOutputID string

	// LogicalOutputIndex is the output position in the build request.
	LogicalOutputIndex uint32

	// PacketIndex identifies the prepared virtual packet.
	PacketIndex uint32

	// PacketRole identifies the active or passive packet collection.
	PacketRole CustomAnchorPacketRole

	// VirtualOutputIndex identifies the output within PacketIndex.
	VirtualOutputIndex uint32

	// AnchorOutputIndex identifies the output in the anchor transaction.
	AnchorOutputIndex uint32

	// TaprootAssetRoot is the root of the Taproot Asset commitment before
	// combining it with the host-supplied tapscript sibling.
	TaprootAssetRoot Hash

	// TaprootMerkleRoot is the final BIP341 root that combines the Taproot
	// Asset commitment with the optional host-supplied tapscript sibling.
	TaprootMerkleRoot Hash
}

CustomAnchorOutputCommitmentPreview describes the Taproot commitment roots a custom-anchor plan will insert into one Bitcoin output. The preview is computed locally and does not sign or commit a virtual transaction or mutate the plan.

type CustomAnchorOutputPlan added in v0.2.0

type CustomAnchorOutputPlan struct {
	// InternalKey is the Taproot internal key for the BTC anchor output.
	InternalKey InternalKey

	// Tapscript optionally supplies an inspectable or opaque sibling form.
	Tapscript CustomAnchorTapscriptPlan
}

CustomAnchorOutputPlan describes an asset-bearing BTC output.

func (*CustomAnchorOutputPlan) Validate added in v0.2.0

func (p *CustomAnchorOutputPlan) Validate() error

Validate checks the anchor internal key and sibling representation.

type CustomAnchorPacketRole added in v0.2.0

type CustomAnchorPacketRole uint8

CustomAnchorPacketRole identifies which committed virtual-packet collection a mapping indexes. Active and passive packet indices are independent.

const (
	// CustomAnchorPacketRoleUnknown is not valid in a sealed package.
	CustomAnchorPacketRoleUnknown CustomAnchorPacketRole = iota

	// CustomAnchorPacketRoleActive indexes ActiveVirtualPsbts.
	CustomAnchorPacketRoleActive

	// CustomAnchorPacketRolePassive indexes PassiveVirtualPsbts.
	CustomAnchorPacketRolePassive
)

type CustomAnchorPassiveAssets added in v0.2.0

type CustomAnchorPassiveAssets struct {
	// Policy selects reject, backend preserve, or caller re-anchor behavior.
	Policy CustomAnchorPassivePolicy

	// Packets are required only for caller re-anchor behavior.
	Packets []CustomAnchorPassivePacket
}

CustomAnchorPassiveAssets describes passive-asset handling for a plan.

func (*CustomAnchorPassiveAssets) Validate added in v0.2.0

func (p *CustomAnchorPassiveAssets) Validate() error

Validate checks passive-asset policy and caller packet consistency.

type CustomAnchorPassivePacket added in v0.2.0

type CustomAnchorPassivePacket struct {
	// ID is a stable caller-defined identifier for the passive packet.
	ID string

	// AssetRef is the semantic identity of the passive asset.
	AssetRef AssetRef

	// Amount is the exact passive asset amount represented by the packet.
	Amount uint64

	// VirtualPSBT is the serialized passive virtual asset PSBT.
	VirtualPSBT []byte

	// ProofFile is the complete confirmed proof that selects the passive input.
	ProofFile []byte

	// ProofDelivery contains host-owned delivery metadata for the reanchored
	// passive proof.
	ProofDelivery CustomAssetProofDelivery
}

CustomAnchorPassivePacket is a caller-supplied passive virtual packet.

type CustomAnchorPassivePolicy added in v0.2.0

type CustomAnchorPassivePolicy uint8

CustomAnchorPassivePolicy selects how co-anchored passive assets are handled.

const (
	// CustomAnchorPassiveReject rejects any discovered passive asset. This is
	// the safe zero-value default.
	CustomAnchorPassiveReject CustomAnchorPassivePolicy = iota

	// CustomAnchorPassivePreserve asks the backend to preserve every passive
	// asset it discovers.
	CustomAnchorPassivePreserve

	// CustomAnchorPassiveCallerReanchor uses caller-supplied passive packets.
	CustomAnchorPassiveCallerReanchor
)

type CustomAnchorPlan added in v0.2.0

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

CustomAnchorPlan is an immutable, pre-commit custom-anchor snapshot. Its byte slices and request are only exposed through cloning accessors.

func (*CustomAnchorPlan) ActiveVirtualPSBTs added in v0.2.0

func (p *CustomAnchorPlan) ActiveVirtualPSBTs() [][]byte

ActiveVirtualPSBTs returns the prepared active virtual packets.

func (*CustomAnchorPlan) AnchorPSBT added in v0.2.0

func (p *CustomAnchorPlan) AnchorPSBT() []byte

AnchorPSBT returns the locally verified, unsigned anchor PSBT template.

func (*CustomAnchorPlan) Commit added in v0.2.0

Commit authorizes backend-managed virtual inputs, asks tapd to bind all virtual packets into the anchor transaction, verifies the complete response locally, and returns a sealed recovery package. The optional argument may be supplied at most once.

func (*CustomAnchorPlan) ID added in v0.2.0

func (p *CustomAnchorPlan) ID() (Hash, error)

ID returns the deterministic identifier for the exact inspected plan.

func (*CustomAnchorPlan) Inputs added in v0.2.0

Inputs returns a deep copy of the exact proof-selected active inputs and their logical-to-virtual mappings.

func (*CustomAnchorPlan) Outputs added in v0.2.0

Outputs returns a deep copy of the concrete active output mappings inspected by the builder.

func (*CustomAnchorPlan) PassiveVirtualPSBTs added in v0.2.0

func (p *CustomAnchorPlan) PassiveVirtualPSBTs() [][]byte

PassiveVirtualPSBTs returns the caller-supplied passive packets.

func (*CustomAnchorPlan) PreviewOutputCommitments added in v0.2.0

func (p *CustomAnchorPlan) PreviewOutputCommitments() (
	[]CustomAnchorOutputCommitmentPreview, error)

PreviewOutputCommitments derives the exact output commitment roots without signing virtual inputs or calling CommitVirtualPsbts. It is intended for hosts that must compose and canonically order their final Bitcoin outputs before committing the transition.

Taproot Asset V1 output commitment leaves use witness-stripped asset encoding, so the roots are independent of a later backend virtual-input signature. Split commitments bind the anchor output index, however, so callers that reindex outputs after a preview must rebuild and preview again before committing.

func (*CustomAnchorPlan) Request added in v0.2.0

func (p *CustomAnchorPlan) Request() *CustomAnchorRequest

Request returns a deep copy of the request bound to this plan.

func (*CustomAnchorPlan) Verification added in v0.2.0

Verification returns a copy of the structured pre-commit verification report.

type CustomAnchorPlannedOutputSummary added in v0.2.0

type CustomAnchorPlannedOutputSummary struct {
	// LogicalOutputID is the stable caller-defined output identifier.
	LogicalOutputID string

	// LogicalOutputIndex is the output position in the build request.
	LogicalOutputIndex uint32

	// PacketIndex identifies the prepared active virtual packet.
	PacketIndex uint32

	// PacketRole identifies the active packet collection.
	PacketRole CustomAnchorPacketRole

	// VirtualOutputIndex identifies the output within PacketIndex.
	VirtualOutputIndex uint32

	// AnchorOutputIndex identifies the output in the anchor transaction.
	AnchorOutputIndex uint32

	// AssetRef is the caller-facing semantic asset identity.
	AssetRef AssetRef

	// IssuanceID is the concrete issuance created by this packet output.
	IssuanceID AssetID

	// AssetType is the concrete asset type for the output.
	AssetType AssetType

	// Amount is the number of asset units assigned to the output.
	Amount uint64

	// AnchorValueSat is the BTC value assigned to the anchor output.
	AnchorValueSat uint64

	// ScriptKey is the concrete asset script key for the output.
	ScriptKey PubKey

	// ScriptMode records how the concrete script key was constructed.
	ScriptMode CustomAssetScriptMode

	// ProofDelivery preserves the complete host-owned delivery metadata.
	ProofDelivery CustomAssetProofDelivery

	// OPTrueSpend contains the exact script-path witness data when the output
	// uses CustomAssetScriptOPTrue. Other script modes leave it nil.
	OPTrueSpend *CustomAssetOPTrueSpendInfo
}

CustomAnchorPlannedOutputSummary describes one inspected asset output before the backend commits its proof suffix and final anchor outpoint.

type CustomAnchorProofSourceKind added in v0.2.0

type CustomAnchorProofSourceKind uint8

CustomAnchorProofSourceKind identifies the persisted source used to select an exact asset input.

const (
	// CustomAnchorProofSourceUnknown is not valid in a sealed package.
	CustomAnchorProofSourceUnknown CustomAnchorProofSourceKind = iota

	// CustomAnchorProofSourceConfirmedFile is a complete confirmed proof file.
	CustomAnchorProofSourceConfirmedFile

	// CustomAnchorProofSourceCompactPath is a checksummed AssetProofPath.
	CustomAnchorProofSourceCompactPath
)

type CustomAnchorProofSourceSummary added in v0.2.0

type CustomAnchorProofSourceSummary struct {
	Kind      CustomAnchorProofSourceKind `json:"kind"`
	ContentID Hash                        `json:"content_id"`
	Blob      []byte                      `json:"blob"`
}

CustomAnchorProofSourceSummary makes the transfer package self-contained for proof-source recovery while binding the potentially large blob by content ID.

type CustomAnchorProofUpdate added in v0.2.0

type CustomAnchorProofUpdate struct {
	// LogicalOutputID identifies the caller-facing output allocation.
	LogicalOutputID string `json:"logical_output_id"`

	// LogicalOutputIndex identifies the caller-facing output allocation.
	LogicalOutputIndex uint32 `json:"logical_output_index"`

	// PacketIndex identifies the committed virtual packet.
	PacketIndex uint32 `json:"packet_index"`

	// PacketRole selects the active or passive packet collection.
	PacketRole CustomAnchorPacketRole `json:"packet_role"`

	// VirtualOutputIndex identifies the output within PacketIndex.
	VirtualOutputIndex uint32 `json:"virtual_output_index"`

	// AnchorOutputIndex identifies the output in the anchor transaction.
	AnchorOutputIndex uint32 `json:"anchor_output_index"`

	// AssetRef is the caller-facing asset identity for the proof update.
	AssetRef AssetRef `json:"asset_ref"`

	// IssuanceID is the concrete asset issuance/tranche in the proof
	// update.
	IssuanceID AssetID `json:"issuance_id"`

	// ScriptKey identifies the receiver asset script key.
	ScriptKey PubKey `json:"script_key"`

	// AnchorOutpoint identifies the anchor output referenced by the proof.
	AnchorOutpoint Outpoint `json:"anchor_outpoint"`

	// ProofBlob is the proof suffix or proof metadata returned by the
	// backend.
	ProofBlob []byte `json:"proof_blob"`

	// ProofDelivery preserves the receiver and host delivery metadata.
	ProofDelivery CustomAssetProofDelivery `json:"proof_delivery"`
}

CustomAnchorProofUpdate describes proof data needed after commit.

type CustomAnchorPublishAttemptError added in v0.2.0

type CustomAnchorPublishAttemptError struct {
	Err            error
	OutcomeUnknown bool
}

CustomAnchorPublishAttemptError reports a publish/log call that returned no usable response. If OutcomeUnknown is true, the backend may already have logged or broadcast the transfer and the caller must reconcile state before retrying.

func (*CustomAnchorPublishAttemptError) Error added in v0.2.0

Error returns the publish-attempt failure and highlights ambiguous results.

func (*CustomAnchorPublishAttemptError) Unwrap added in v0.2.0

Unwrap returns the underlying transport or backend error.

type CustomAnchorPublishMetadata added in v0.2.0

type CustomAnchorPublishMetadata struct {
	// SkipAnchorTxBroadcast asks the backend to log without broadcasting
	// the final anchor transaction.
	SkipAnchorTxBroadcast bool `json:"skip_anchor_tx_broadcast"`

	// Label is an optional backend transfer label.
	Label string `json:"label"`

	// ExternalBroadcast records that the caller intends to broadcast, or
	// has already broadcast, the final anchor transaction outside the
	// backend.
	ExternalBroadcast bool `json:"external_broadcast"`
}

CustomAnchorPublishMetadata contains publish/log retry metadata.

type CustomAnchorRequest added in v0.2.0

type CustomAnchorRequest struct {
	// Inputs are the proof-selected asset inputs to spend.
	Inputs []CustomAssetInput

	// Outputs are the logical asset outputs to create.
	Outputs []CustomAssetOutput

	// AnchorPSBT is the caller-visible BTC anchor transaction template.
	AnchorPSBT []byte

	// Funding selects exactly one high-level anchor funding mode.
	Funding CustomAnchorFundingPlan

	// PassiveAssets controls how co-anchored passive assets are handled.
	PassiveAssets CustomAnchorPassiveAssets

	// LossPolicy bounds explicitly requested protocol burn outputs. Asset
	// amounts must otherwise be conserved exactly.
	LossPolicy CustomAnchorLossPolicy

	// SigningPlans select the trusted external spend path for each BTC anchor
	// input. PSBT-bound validation occurs after the anchor template is decoded.
	SigningPlans []CustomAnchorInputSigningPlan
}

CustomAnchorRequest contains the SDK-owned inputs needed to build an advanced custom-anchor asset transaction.

func (*CustomAnchorRequest) Clone added in v0.2.0

Clone returns a deep copy whose byte slices, witness stacks, variants, and metadata do not alias the request.

func (*CustomAnchorRequest) Validate added in v0.2.0

func (r *CustomAnchorRequest) Validate() error

Validate checks that the request is internally consistent before proof or PSBT decoding begins.

type CustomAnchorScriptPathSigningPlan added in v0.2.0

type CustomAnchorScriptPathSigningPlan struct {
	// LeafHash is the TapLeaf hash of the selected script path.
	LeafHash Hash `json:"leaf_hash"`

	// RequiredSigners are the x-only keys expected to contribute witness
	// signatures. An OP_TRUE-style leaf can leave this empty.
	RequiredSigners []XOnlyPubKey `json:"required_signers,omitempty"`
}

CustomAnchorScriptPathSigningPlan identifies one exact committed Taproot leaf and any external keys expected to contribute witness signatures. The first implementation rejects leaves containing OP_CODESEPARATOR and final witnesses containing an annex.

type CustomAnchorScriptPathSigningRequest added in v0.2.0

type CustomAnchorScriptPathSigningRequest struct {
	ID                Hash
	PackageDigest     Hash
	InputIndex        uint32
	PrevOut           Outpoint
	PrevOutValueSat   int64
	PrevOutScript     []byte
	SighashType       uint32
	Sighash           Hash
	InternalKey       XOnlyPubKey
	TaprootMerkleRoot []byte
	LeafHash          Hash
	LeafVersion       uint8
	LeafScript        []byte
	ControlBlock      []byte
	RequiredSigners   []XOnlyPubKey
}

CustomAnchorScriptPathSigningRequest contains one exact Taproot leaf and the data needed to construct and review its final witness stack.

type CustomAnchorSigningMode added in v0.2.0

type CustomAnchorSigningMode uint8

CustomAnchorSigningMode identifies the selected external anchor input spend path.

const (
	// CustomAnchorSigningModeUnknown is not a valid signing plan.
	CustomAnchorSigningModeUnknown CustomAnchorSigningMode = iota

	// CustomAnchorSigningModeKeyPath selects a single-signer Taproot key
	// spend.
	CustomAnchorSigningModeKeyPath

	// CustomAnchorSigningModeMuSig2 selects a final aggregate MuSig2
	// Taproot key spend.
	CustomAnchorSigningModeMuSig2

	// CustomAnchorSigningModeScriptPath selects one exact Taproot leaf.
	CustomAnchorSigningModeScriptPath
)

type CustomAnchorSigningRequests added in v0.2.0

type CustomAnchorSigningRequests struct {
	KeyPath    []CustomAnchorKeyPathSigningRequest
	MuSig2     []CustomAnchorMuSig2SigningRequest
	ScriptPath []CustomAnchorScriptPathSigningRequest
}

CustomAnchorSigningRequests groups the typed requests derived from a sealed package and its explicit per-input signing plans.

type CustomAnchorTapscriptPlan added in v0.2.0

type CustomAnchorTapscriptPlan struct {
	// TapLeaves is an ordered set of SDK tapscript leaves.
	TapLeaves []TapLeaf

	// SerializedSibling is an opaque serialized tapscript sibling.
	SerializedSibling []byte
}

CustomAnchorTapscriptPlan represents the non-asset sibling committed at a BTC anchor output. At most one representation may be populated; leaving both empty selects a direct/BIP86-style anchor policy.

func (*CustomAnchorTapscriptPlan) Validate added in v0.2.0

func (p *CustomAnchorTapscriptPlan) Validate() error

Validate checks that at most one anchor sibling representation is present.

type CustomAnchorTransferPackage added in v0.2.0

type CustomAnchorTransferPackage struct {
	// SchemaVersion identifies the persisted package schema.
	SchemaVersion uint16 `json:"schema_version"`

	// PlanID binds the committed package to the immutable inspected plan.
	PlanID Hash `json:"plan_id"`

	// CommittedPackageDigest binds all committed package fields while
	// excluding signature and finalization fields in the anchor PSBT. It is
	// stable as external signatures are applied and is used by signing
	// request IDs.
	CommittedPackageDigest Hash `json:"committed_package_digest"`

	// UnsignedTxDigest binds the complete ordered unsigned anchor
	// transaction, including version, locktime, inputs, sequences, output
	// scripts, and output values.
	UnsignedTxDigest Hash `json:"unsigned_tx_digest"`

	// PackageDigest detects changes to the current persisted snapshot,
	// including signature and finalization fields.
	PackageDigest Hash `json:"package_digest"`

	// CommittedAnchorPsbt is the immutable post-commit BTC-level PSBT used
	// to derive signing requests and verify the current/final PSBT. It keeps
	// signing metadata that standard PSBT finalization removes.
	CommittedAnchorPsbt []byte `json:"committed_anchor_psbt"`

	// AnchorPsbt is the current BTC-level anchor PSBT. It initially equals
	// CommittedAnchorPsbt and is replaced on returned clones as signatures
	// or final witnesses are applied.
	AnchorPsbt []byte `json:"anchor_psbt"`

	// ActiveVirtualPsbts are the committed active virtual asset PSBTs.
	ActiveVirtualPsbts [][]byte `json:"active_virtual_psbts"`

	// PassiveVirtualPsbts are committed passive virtual asset PSBTs that
	// must remain paired with the active PSBTs when publishing or retrying.
	PassiveVirtualPsbts [][]byte `json:"passive_virtual_psbts"`

	// ChangeOutputIndex is the backend-selected change output index, or -1
	// when no change output exists.
	ChangeOutputIndex int32 `json:"change_output_index"`

	// LockedUTXOs are wallet UTXO locks held for backend-funded anchors.
	LockedUTXOs []CustomAnchorLockedUTXO `json:"locked_utxos"`

	// FundingLock preserves caller-supplied lease credentials and requested
	// expiration for recovery. Current tapd still returns no lease IDs.
	FundingLock CustomAnchorFundingLockMetadata `json:"funding_lock"`

	// Funding records the exact high-level funding policy and the actual
	// committed miner fee. It makes fee limits and the P2A output durable
	// across signing, restart, and external broadcast handoffs.
	Funding CustomAnchorFundingSummary `json:"funding"`

	// Inputs summarize the committed asset inputs without exposing
	// taproot-assets implementation types.
	Inputs []CustomAnchorAssetInputSummary `json:"inputs"`

	// Outputs summarize the committed asset outputs without exposing
	// taproot-assets implementation types.
	Outputs []CustomAnchorAssetOutputSummary `json:"outputs"`

	// ProofUpdates carry the proof metadata callers must keep for receiver
	// proof delivery, import, register, export, or retry flows.
	ProofUpdates []CustomAnchorProofUpdate `json:"proof_updates"`

	// SigningPlans select exactly one required external spending path for
	// each anchor input. The committed PSBT alone cannot safely infer that
	// intent when both key and script paths are available.
	SigningPlans []CustomAnchorInputSigningPlan `json:"signing_plans"`

	// BackendManagedInputIndices identifies anchor inputs that the backend
	// added or owns and will finalize through its anchor signer. Together
	// with SigningPlans, these indices must classify every anchor input
	// exactly once.
	BackendManagedInputIndices []uint32 `json:"backend_managed_input_indices"`

	// Publish stores publish/log retry metadata that is independent from
	// the final signed anchor PSBT bytes.
	Publish CustomAnchorPublishMetadata `json:"publish"`
}

CustomAnchorTransferPackage is the persistable post-commit recovery boundary for an advanced custom-anchor asset transaction.

Callers should persist this package before handing AnchorPsbt to an external signer or broadcaster. Publish/log retries after process restart should be driven from the persisted package plus the final signed anchor PSBT bytes.

func (*CustomAnchorTransferPackage) ApplyKeyPathSignature added in v0.2.0

func (p *CustomAnchorTransferPackage) ApplyKeyPathSignature(requestID Hash,
	signature []byte) (*CustomAnchorTransferPackage, error)

ApplyKeyPathSignature verifies and immutably applies either a single-signer or final aggregate MuSig2 Schnorr signature. The original package and all caller-owned buffers remain unchanged.

func (*CustomAnchorTransferPackage) ApplyScriptPathWitness added in v0.2.0

func (p *CustomAnchorTransferPackage) ApplyScriptPathWitness(
	requestID Hash, witnessElements [][]byte) (
	*CustomAnchorTransferPackage, error)

ApplyScriptPathWitness verifies and immutably applies the unlocking elements for one selected script path. The committed leaf script and control block are appended by the SDK and cannot be replaced by the caller.

func (*CustomAnchorTransferPackage) Clone added in v0.2.0

Clone returns a deep copy of the package so callers can snapshot a committed state before external signing or broadcast mutates host-owned buffers.

func (*CustomAnchorTransferPackage) MarshalBinary added in v0.2.0

func (p *CustomAnchorTransferPackage) MarshalBinary() ([]byte, error)

MarshalBinary returns a versioned deterministic binary envelope containing the canonical JSON package.

func (*CustomAnchorTransferPackage) MarshalJSON added in v0.2.0

func (p *CustomAnchorTransferPackage) MarshalJSON() ([]byte, error)

MarshalJSON returns the deterministic JSON representation of a validated package.

func (*CustomAnchorTransferPackage) Seal added in v0.2.0

Seal returns a validated deep copy with the current schema and all package digests populated. It never mutates caller-owned fields or byte slices.

func (*CustomAnchorTransferPackage) SigningRequests added in v0.2.0

SigningRequests derives deterministic, digest-bound requests from the committed anchor PSBT. It fails closed if any input is not classified as either externally signed or backend-managed, or if a plan is ambiguous or incompatible with the PSBT.

func (*CustomAnchorTransferPackage) UnmarshalBinary added in v0.2.0

func (p *CustomAnchorTransferPackage) UnmarshalBinary(data []byte) error

UnmarshalBinary decodes a versioned binary envelope and validates both its header and embedded package.

func (*CustomAnchorTransferPackage) UnmarshalJSON added in v0.2.0

func (p *CustomAnchorTransferPackage) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a package and rejects unknown fields, unsupported schema versions, and digest mismatches.

func (*CustomAnchorTransferPackage) Validate added in v0.2.0

func (p *CustomAnchorTransferPackage) Validate() error

Validate checks the package schema, structure, and all three digest bindings. A package must be sealed before it can be persisted or used for signing.

func (*CustomAnchorTransferPackage) VerifyFinalAnchorPSBT added in v0.2.0

func (p *CustomAnchorTransferPackage) VerifyFinalAnchorPSBT(
	finalAnchorPsbt []byte) error

VerifyFinalAnchorPSBT verifies that a signed or finalized PSBT contains the exact committed unsigned transaction. A fully finalized PSBT must also use every sealed external signing path and pass consensus witness validation.

func (*CustomAnchorTransferPackage) WithFinalAnchorPSBT added in v0.2.0

func (p *CustomAnchorTransferPackage) WithFinalAnchorPSBT(
	finalAnchorPsbt []byte) (*CustomAnchorTransferPackage, error)

WithFinalAnchorPSBT verifies and stores a fully finalized anchor PSBT on an immutable package clone. Each external input must use its sealed path and exact sighash, while backend-managed inputs remain consensus-validated. All non-final PSBT metadata is restored from the committed snapshot before the current package digest is refreshed.

type CustomAnchorTxBuilder added in v0.2.0

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

CustomAnchorTxBuilder builds inspectable Taproot Asset state transitions around a caller-controlled Bitcoin anchor PSBT. It is intentionally separate from TxBuilder: callers that don't need exact anchor control should continue to use the simpler send APIs.

func (*CustomAnchorTxBuilder) Build added in v0.2.0

Build validates proof-selected inputs, constructs one V1 virtual packet per concrete issuance, and merges the required Taproot Asset PSBT metadata into the caller's exact anchor transaction. No backend or anchor signature is requested by this method.

func (*CustomAnchorTxBuilder) SetConfirmedProofVerifier added in v0.2.0

func (b *CustomAnchorTxBuilder) SetConfirmedProofVerifier(
	verifier ConfirmedProofVerifier) *CustomAnchorTxBuilder

SetConfirmedProofVerifier sets the chain and inventory verifier required by compact proof-path inputs. For a non-empty path, the verifier must also implement UnconfirmedAnchorVerifier. Confirmed proof-file inputs continue to use the configured wallet proof client.

type CustomAnchorVerificationCheck added in v0.2.0

type CustomAnchorVerificationCheck struct {
	// Code is the stable machine-readable check code.
	Code CustomAnchorVerificationCode

	// Scope identifies the subject being checked.
	Scope CustomAnchorVerificationScope

	// Origin identifies whether the SDK, backend, or integrating host
	// performed the check.
	Origin CustomAnchorVerificationOrigin

	// Passed reports whether the check succeeded.
	Passed bool

	// InputIndex optionally identifies an asset input.
	InputIndex *uint32

	// OutputIndex optionally identifies an anchor output.
	OutputIndex *uint32

	// OutputID optionally identifies a logical asset output.
	OutputID string

	// Message is diagnostic text and is not a stable API value.
	Message string
}

CustomAnchorVerificationCheck records one verification checkpoint.

type CustomAnchorVerificationCode added in v0.2.0

type CustomAnchorVerificationCode string

CustomAnchorVerificationCode is a stable machine-readable check or issue code. Concrete verifiers own their code vocabulary.

type CustomAnchorVerificationIssue added in v0.2.0

type CustomAnchorVerificationIssue struct {
	// Code is the stable machine-readable issue code.
	Code CustomAnchorVerificationCode

	// Scope identifies the affected part of the plan or package.
	Scope CustomAnchorVerificationScope

	// Origin identifies whether the SDK, backend, or integrating host reported
	// the issue.
	Origin CustomAnchorVerificationOrigin

	// Severity determines whether the issue invalidates the result.
	Severity CustomAnchorVerificationSeverity

	// InputIndex optionally identifies an asset input.
	InputIndex *uint32

	// OutputIndex optionally identifies an anchor output.
	OutputIndex *uint32

	// OutputID optionally identifies a logical asset output.
	OutputID string

	// Message is diagnostic text and is not a stable API value.
	Message string
}

CustomAnchorVerificationIssue records a structured verification finding.

type CustomAnchorVerificationOrigin added in v0.2.0

type CustomAnchorVerificationOrigin uint8

CustomAnchorVerificationOrigin identifies where a check was performed.

const (
	// CustomAnchorVerificationOriginUnknown is not a trusted origin.
	CustomAnchorVerificationOriginUnknown CustomAnchorVerificationOrigin = iota

	// CustomAnchorVerificationOriginLocal identifies an SDK-local check.
	CustomAnchorVerificationOriginLocal

	// CustomAnchorVerificationOriginBackend identifies a backend-trusted
	// check.
	CustomAnchorVerificationOriginBackend

	// CustomAnchorVerificationOriginHost identifies a check performed by the
	// integrating host through an injected verifier. It is trusted by the
	// host application, not independently reproduced by the SDK.
	CustomAnchorVerificationOriginHost
)

type CustomAnchorVerificationResult added in v0.2.0

type CustomAnchorVerificationResult struct {
	// Checks are the verification checkpoints that were attempted.
	Checks []CustomAnchorVerificationCheck

	// Issues are structured informational, warning, and error findings.
	Issues []CustomAnchorVerificationIssue
}

CustomAnchorVerificationResult contains inspectable checks and issues.

func (*CustomAnchorVerificationResult) Clone added in v0.2.0

Clone returns a deep copy of the verification result and optional indices.

func (*CustomAnchorVerificationResult) Valid added in v0.2.0

Valid reports whether the result is well-formed, every check passed, and no error-severity issue was reported.

func (*CustomAnchorVerificationResult) Validate added in v0.2.0

func (r *CustomAnchorVerificationResult) Validate() error

Validate checks the structure of a verification result. An empty result is invalid so an uninitialized verifier cannot be mistaken for success.

type CustomAnchorVerificationScope added in v0.2.0

type CustomAnchorVerificationScope string

CustomAnchorVerificationScope identifies the subject of a check or issue.

type CustomAnchorVerificationSeverity added in v0.2.0

type CustomAnchorVerificationSeverity uint8

CustomAnchorVerificationSeverity describes the impact of an issue.

const (
	// CustomAnchorVerificationSeverityUnknown is not a usable severity.
	CustomAnchorVerificationSeverityUnknown CustomAnchorVerificationSeverity = iota

	// CustomAnchorVerificationSeverityInfo is informational.
	CustomAnchorVerificationSeverityInfo

	// CustomAnchorVerificationSeverityWarning does not invalidate a plan.
	CustomAnchorVerificationSeverityWarning

	// CustomAnchorVerificationSeverityError invalidates a plan.
	CustomAnchorVerificationSeverityError
)

type CustomAnchorWalletFunding added in v0.2.0

type CustomAnchorWalletFunding struct {
	// ChangeOutput selects backend change handling.
	ChangeOutput AnchorChangeOutput

	// Fee selects the backend fee policy.
	Fee AnchorFee

	// MaxFeeSat is the hard absolute fee ceiling for the committed anchor.
	// It is checked locally before any Bitcoin input is signed. This remains
	// required even when Fee uses a confirmation target because the backend
	// fee estimate is not itself a safe spending limit.
	MaxFeeSat uint64

	// CustomLockID is the required deterministic 32-byte identifier for
	// backend wallet UTXO locks and ambiguous-commit recovery.
	CustomLockID []byte

	// LockExpirationSeconds optionally overrides the backend lock duration.
	LockExpirationSeconds uint64
}

CustomAnchorWalletFunding configures backend wallet anchor funding.

type CustomAnchorWalletKitClient added in v0.2.0

type CustomAnchorWalletKitClient interface {
	// CommitVirtualPsbtsWithRequest commits virtual transactions into the
	// caller-supplied anchor PSBT according to the exact funding plan.
	CommitVirtualPsbtsWithRequest(ctx context.Context,
		req *CommitVirtualPsbtsRequest) (*CommitVirtualPsbtsResponse,
		error)

	// PublishAndLogTransferWithRequest publishes or logs a finalized custom
	// anchor transfer together with the commit response metadata.
	PublishAndLogTransferWithRequest(ctx context.Context,
		req *PublishAndLogTransferRequest) (*AssetPacket, error)
}

CustomAnchorWalletKitClient is an optional WalletKitClient extension for advanced anchor construction. It accepts the full request DTOs required to preserve caller-owned Bitcoin transaction topology and durable funding metadata. Keeping this separate from WalletKitClient preserves source compatibility for existing client implementations and test doubles.

type CustomAssetBurnScriptPlan added in v0.2.0

type CustomAssetBurnScriptPlan struct{}

CustomAssetBurnScriptPlan marks an explicitly unspendable asset output.

type CustomAssetExternalScriptPlan added in v0.2.0

type CustomAssetExternalScriptPlan struct {
	// ScriptKey is the external Taproot Asset script key.
	ScriptKey ScriptKey
}

CustomAssetExternalScriptPlan uses a complete caller-supplied script key.

type CustomAssetInput added in v0.2.0

type CustomAssetInput struct {
	// ID is a stable caller-defined identifier for this logical input.
	ID string

	// AssetRef is the semantic asset identity expected at the selected proof
	// source tip.
	AssetRef AssetRef

	// Amount must exactly match the amount at the selected proof source tip.
	Amount uint64

	// ProofFile is a complete confirmed proof file. Exactly one of ProofFile
	// and ProofPath must be set.
	ProofFile []byte

	// ProofPath is a verified confirmed base plus zero or more compact
	// unconfirmed transitions. It requires a ConfirmedProofVerifier on the
	// builder, its UnconfirmedAnchorVerifier extension when steps are present,
	// and caller-provided asset witnesses.
	ProofPath *AssetProofPath

	// Witness selects how the virtual asset input is authorized.
	Witness CustomAssetWitnessPlan
}

CustomAssetInput identifies exact asset units selected by a proof file.

func (*CustomAssetInput) Validate added in v0.2.0

func (i *CustomAssetInput) Validate() error

Validate checks a proof-file asset input before proof decoding.

type CustomAssetOPTrueScriptPlan added in v0.2.0

type CustomAssetOPTrueScriptPlan struct {
	// InternalKey is unique to this logical output. Reusing it can produce a
	// duplicate asset commitment key and is rejected by the builder.
	InternalKey KeyDescriptor
}

CustomAssetOPTrueScriptPlan describes a unique OP_TRUE asset tapscript.

type CustomAssetOPTrueSpendInfo added in v0.2.0

type CustomAssetOPTrueSpendInfo struct {
	// LeafScript is the OP_TRUE tapscript program.
	LeafScript []byte `json:"leaf_script"`

	// LeafVersion is the tapscript leaf version committed by ControlBlock.
	LeafVersion uint8 `json:"leaf_version"`

	// ControlBlock proves LeafScript against the output asset script key.
	ControlBlock []byte `json:"control_block"`

	// InternalKey is the Taproot internal key committed by ControlBlock.
	InternalKey PubKey `json:"internal_key"`
}

CustomAssetOPTrueSpendInfo contains the complete Taproot script-path data needed to spend an SDK-built OP_TRUE asset output. It deliberately uses only SDK and primitive types so applications do not need taproot-assets imports.

func (*CustomAssetOPTrueSpendInfo) Clone added in v0.2.0

Clone returns a deep copy whose script and control block do not alias the source spend information.

func (*CustomAssetOPTrueSpendInfo) Validate added in v0.2.0

func (i *CustomAssetOPTrueSpendInfo) Validate(scriptKey PubKey) error

Validate checks that the spend data reveals the expected OP_TRUE leaf and commits to scriptKey. This lets a persisted package be checked without importing taproot-assets implementation packages.

func (*CustomAssetOPTrueSpendInfo) WitnessStack added in v0.2.0

func (i *CustomAssetOPTrueSpendInfo) WitnessStack() [][]byte

WitnessStack returns the complete zero-argument asset witness for the OP_TRUE leaf. The returned byte slices never alias the spend information.

type CustomAssetOutput added in v0.2.0

type CustomAssetOutput struct {
	// ID is a stable caller-defined identifier used across planning, signing,
	// proof delivery, and persistence.
	ID string

	// AssetRef is the semantic identity of the asset being created.
	AssetRef AssetRef

	// Amount is the number of asset units assigned to this output.
	Amount uint64

	// AnchorOutputIndex is the output index in the caller anchor PSBT.
	AnchorOutputIndex uint32

	// AnchorValueSat is the exact BTC value required at the anchor output.
	AnchorValueSat uint64

	// Script selects exactly one asset script construction mode.
	Script CustomAssetScriptPlan

	// Anchor describes the anchor internal key and BTC tapscript sibling.
	Anchor CustomAnchorOutputPlan

	// ProofDelivery contains opaque receiver proof-delivery metadata.
	ProofDelivery CustomAssetProofDelivery

	// Timelocks contains asset-level lock times. Nonzero values are rejected
	// by the first custom-anchor implementation.
	Timelocks CustomAssetTimelocks
}

CustomAssetOutput is one logical asset output in a custom-anchor plan.

func (*CustomAssetOutput) Validate added in v0.2.0

func (o *CustomAssetOutput) Validate() error

Validate checks a logical asset output before proof or PSBT decoding.

type CustomAssetProofDelivery added in v0.2.0

type CustomAssetProofDelivery struct {
	// RecipientID is an optional stable recipient or delivery identifier.
	RecipientID string `json:"recipient_id"`

	// CourierAddress is an optional proof courier destination.
	CourierAddress string `json:"courier_address"`

	// OpaqueMetadata is preserved for the host application's delivery flow.
	OpaqueMetadata []byte `json:"opaque_metadata"`
}

CustomAssetProofDelivery stores host-owned proof-delivery metadata.

type CustomAssetScriptMode added in v0.2.0

type CustomAssetScriptMode uint8

CustomAssetScriptMode identifies an asset output script construction mode.

const (
	// CustomAssetScriptUnspecified is not a usable script mode.
	CustomAssetScriptUnspecified CustomAssetScriptMode = iota

	// CustomAssetScriptWallet derives a script key from the backend wallet.
	CustomAssetScriptWallet

	// CustomAssetScriptExternal uses an externally supplied script key.
	CustomAssetScriptExternal

	// CustomAssetScriptOPTrue creates a unique OP_TRUE asset tapscript.
	CustomAssetScriptOPTrue

	// CustomAssetScriptBurn creates an explicitly unspendable burn output.
	CustomAssetScriptBurn
)

type CustomAssetScriptPlan added in v0.2.0

type CustomAssetScriptPlan struct {
	// Mode selects the active script variant.
	Mode CustomAssetScriptMode

	// Wallet selects a backend wallet-derived script key.
	Wallet *CustomAssetWalletScriptPlan

	// External selects a caller-supplied script key.
	External *CustomAssetExternalScriptPlan

	// OPTrue selects a unique OP_TRUE asset tapscript.
	OPTrue *CustomAssetOPTrueScriptPlan

	// Burn selects an explicitly unspendable asset output.
	Burn *CustomAssetBurnScriptPlan
}

CustomAssetScriptPlan is a tagged asset script construction plan. Exactly one variant must be non-nil and must match Mode.

func (*CustomAssetScriptPlan) Validate added in v0.2.0

func (p *CustomAssetScriptPlan) Validate() error

Validate checks that exactly one asset script variant is selected.

type CustomAssetTimelocks added in v0.2.0

type CustomAssetTimelocks struct {
	// Absolute is the asset-level absolute lock time.
	Absolute uint64

	// Relative is the asset-level relative lock time.
	Relative uint64
}

CustomAssetTimelocks contains asset-level absolute and relative lock times.

type CustomAssetWalletScriptPlan added in v0.2.0

type CustomAssetWalletScriptPlan struct {
	// KeyLocator optionally requests a specific wallet key. Nil asks the
	// backend to derive a fresh key using its normal asset key family.
	KeyLocator *KeyLocator
}

CustomAssetWalletScriptPlan asks the backend wallet for an asset script key.

type CustomAssetWitnessMode added in v0.2.0

type CustomAssetWitnessMode uint8

CustomAssetWitnessMode selects who supplies the virtual asset witness.

const (
	// CustomAssetWitnessUnspecified is not a usable witness mode.
	CustomAssetWitnessUnspecified CustomAssetWitnessMode = iota

	// CustomAssetWitnessBackendSigner asks the backend to sign the asset
	// input. No caller witness stack may be present.
	CustomAssetWitnessBackendSigner

	// CustomAssetWitnessCallerProvided uses the exact caller-provided asset
	// witness stack.
	CustomAssetWitnessCallerProvided
)

type CustomAssetWitnessPlan added in v0.2.0

type CustomAssetWitnessPlan struct {
	// Mode selects backend signing or a caller-provided stack.
	Mode CustomAssetWitnessMode

	// Stack is the final witness stack for caller-provided mode.
	Stack [][]byte
}

CustomAssetWitnessPlan describes how a virtual asset input is authorized.

func (*CustomAssetWitnessPlan) Validate added in v0.2.0

func (p *CustomAssetWitnessPlan) Validate() error

Validate checks that exactly one supported asset witness mode is selected.

type DeclareScriptKeyRequest

type DeclareScriptKeyRequest struct {
	// ScriptKey is the script key to declare.
	ScriptKey ScriptKey
}

DeclareScriptKeyRequest specifies a script key to declare to the wallet.

type DecodedProof

type DecodedProof struct {
	// ProofAtDepth is the index depth of this proof (0 = latest).
	ProofAtDepth uint32

	// NumberOfProofs is the total number of proofs in the chain.
	NumberOfProofs uint32

	// AssetRef is the SDK's user-facing identifier for the asset.
	AssetRef AssetRef

	// IssuanceID is the 32-byte protocol-level identifier for the specific
	// issuance/tranche described by the proof.
	IssuanceID AssetID

	// ScriptKey is the 33-byte script key.
	ScriptKey PubKey

	// Amount is the number of asset units.
	Amount uint64

	// Outpoint is the output location in "txid:index" format.
	Outpoint Outpoint

	// AltLeaves are auxiliary Taproot leaves committed alongside the asset.
	// Each entry is the raw per-leaf TLV stream bytes (opaque).
	AltLeaves [][]byte

	// PrevIDs are the asset-level identifiers of the inputs referenced by this
	// proof's asset witnesses. These are required to derive STXO alt leaves for
	// v1 transfer proofs.
	PrevIDs []PrevID

	// IsIssuance is true if this is a genesis/issuance proof.
	IsIssuance bool
}

DecodedProof contains information extracted from a decoded proof.

type DerivedKeys

type DerivedKeys struct {
	// ScriptKey is used to lock the asset to the receiver.
	ScriptKey ScriptKey

	// InternalKey is used as the internal key for the anchor output.
	InternalKey InternalKey
}

DerivedKeys contains both keys needed for receiving assets in an interactive transfer. The receiver derives these keys and shares them with the sender.

type Error

type Error struct {
	// Op is the operation that failed (e.g., "DeriveScriptKey").
	Op string

	// Err is the underlying error.
	Err error
}

Error represents an SDK-specific error that wraps underlying RPC errors with additional context.

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

func (*Error) GRPCCode

func (e *Error) GRPCCode() codes.Code

GRPCCode returns the gRPC status code if the underlying error is a gRPC error, or codes.Unknown otherwise.

func (*Error) IsInvalidArgument

func (e *Error) IsInvalidArgument() bool

IsInvalidArgument returns true if the error indicates invalid input.

func (*Error) IsNotFound

func (e *Error) IsNotFound() bool

IsNotFound returns true if the error indicates a resource was not found.

func (*Error) IsUnavailable

func (e *Error) IsUnavailable() bool

IsUnavailable returns true if the error indicates the service is unavailable.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying error.

type EventClient

type EventClient interface {
	// SubscribeReceiveEvents streams incoming asset transfer events.
	// Filter by address or start time via the request. The returned
	// channels are closed when the context is cancelled.
	SubscribeReceiveEvents(ctx context.Context,
		req *SubscribeReceiveEventsRequest) (
		<-chan *ReceiveEventRecord, <-chan error, error)

	// SubscribeSendEvents streams outgoing asset transfer events.
	// Filter by script key, label, or start time via the request.
	SubscribeSendEvents(ctx context.Context,
		req *SubscribeSendEventsRequest) (
		<-chan *SendEventRecord, <-chan error, error)

	// SubscribeMintEvents streams minting batch lifecycle events.
	SubscribeMintEvents(ctx context.Context,
		req *SubscribeMintEventsRequest) (
		<-chan *MintEvent, <-chan error, error)
}

EventClient exposes server-streaming RPCs for real-time event notifications. All subscribe methods return a channel that delivers events until the context is cancelled or the stream encounters an error. The error channel receives at most one value: the terminal stream error (nil on clean shutdown).

type EventHandler

type EventHandler struct {
	// OnReceive is called for each incoming asset transfer event.
	OnReceive func(ctx context.Context, event *ReceiveEvent)

	// OnSend is called for each outgoing asset transfer event.
	OnSend func(ctx context.Context, event *SendEvent)

	// OnMint is called for each minting batch lifecycle event.
	OnMint func(ctx context.Context, event *MintEvent)

	// OnError is called when a stream encounters a non-recoverable
	// error after all retry attempts are exhausted, or when a fatal
	// (non-retriable) error occurs. If nil, errors are silently
	// dropped and the stream is abandoned.
	OnError func(streamName string, err error)

	// OnDisconnect is called on every retriable stream break,
	// before the next reconnection attempt. err is the terminal
	// error returned by the stream (may be nil on a clean server
	// close) and nextRetry is the delay (with jitter) the listener
	// will wait before retrying. Intended for observability — to
	// surface transient hiccups as logs or metrics — while OnError
	// reports the terminal case.
	OnDisconnect func(streamName string, err error,
		nextRetry time.Duration)
}

EventHandler holds optional callbacks for asset events. Nil handlers are skipped — the listener will not subscribe to event types that have no handler registered.

type EventListener

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

EventListener subscribes to tapd event streams and dispatches events to the registered handlers, reconnecting with exponential backoff on retriable failures.

func NewEventListener

func NewEventListener(
	client EventClient,
	handler EventHandler,
	opts ...EventListenerOption,
) *EventListener

NewEventListener creates an EventListener backed by the given client. The client can be either a grpc.Client or rest.Client — both satisfy the EventClient interface.

func (*EventListener) Running

func (l *EventListener) Running() bool

Running reports whether the listener is currently active.

func (*EventListener) Start

func (l *EventListener) Start(ctx context.Context) error

Start begins listening for events. It launches background goroutines for each registered handler. Start is non-blocking and returns immediately. Returns an error if the listener is already running.

func (*EventListener) Stop

func (l *EventListener) Stop() error

Stop gracefully shuts down all subscriptions and waits for goroutines to exit. Safe to call multiple times.

type EventListenerConfig

type EventListenerConfig struct {
	// MaxRetries is the maximum number of consecutive reconnection
	// attempts per stream before calling OnError. Zero means
	// unlimited retries.
	MaxRetries int

	// InitialBackoff is the delay before the first reconnection
	// attempt. Defaults to 1 second.
	InitialBackoff time.Duration

	// MaxBackoff caps the exponential backoff. Defaults to 60
	// seconds.
	MaxBackoff time.Duration

	// BackoffMultiplier is the factor applied after each retry.
	// Defaults to 2.0.
	BackoffMultiplier float64

	// ReceiveFilter optionally restricts receive events.
	ReceiveFilter *SubscribeReceiveEventsRequest

	// SendFilter optionally restricts send events.
	SendFilter *SubscribeSendEventsRequest

	// MintFilter optionally restricts mint events.
	MintFilter *SubscribeMintEventsRequest
}

EventListenerConfig configures reconnection and subscription behavior.

type EventListenerOption

type EventListenerOption func(*EventListenerConfig)

EventListenerOption is a functional option for configuring EventListenerConfig.

func WithBackoffMultiplier

func WithBackoffMultiplier(m float64) EventListenerOption

WithBackoffMultiplier sets the backoff growth factor.

func WithInitialBackoff

func WithInitialBackoff(d time.Duration) EventListenerOption

WithInitialBackoff sets the initial reconnection backoff duration.

func WithMaxBackoff

func WithMaxBackoff(d time.Duration) EventListenerOption

WithMaxBackoff sets the maximum backoff duration.

func WithMaxRetries

func WithMaxRetries(n int) EventListenerOption

WithMaxRetries sets the maximum consecutive reconnection attempts.

func WithMintFilter

WithMintFilter sets the mint event subscription filter.

func WithReceiveFilter

WithReceiveFilter sets the receive event subscription filter.

func WithSendFilter

WithSendFilter sets the send event subscription filter.

type ExportBackupRequest

type ExportBackupRequest struct {
	Mode BackupMode
}

ExportBackupRequest specifies the desired backup mode.

type ExportBackupResponse

type ExportBackupResponse struct {
	Backup []byte
}

ExportBackupResponse returns the serialized backup blob.

type ExternalIssuanceSigner

type ExternalIssuanceSigner interface {
	// SignIssuance reviews and signs one issuance authorization request.
	SignIssuance(context.Context, IssuanceSigningRequest) (
		SignedIssuance, error,
	)
}

ExternalIssuanceSigner signs issuance authorization payloads with an externally managed key.

type ExternalKey

type ExternalKey struct {
	// XPub is the account-level extended public key.
	XPub string

	// MasterFingerprint identifies the master key that derived XPub.
	MasterFingerprint [4]byte

	// DerivationPath is the full child derivation path.
	DerivationPath string
}

ExternalKey describes an externally managed BIP-86 key derivation.

type FederationServer

type FederationServer struct {
	// Host is the address of the federation server.
	Host string

	// ID is the numeric server identifier.
	ID int32
}

FederationServer is a universe federation peer.

type FederationSyncConfig

type FederationSyncConfig struct {
	// GlobalSyncConfigs are the per-proof-type configs.
	GlobalSyncConfigs []GlobalFederationSyncConfig

	// AssetSyncConfigs are the per-asset configs.
	AssetSyncConfigs []AssetFederationSyncConfig
}

FederationSyncConfig combines global and per-asset sync configs.

type FeeRate

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

FeeRate represents an on-chain fee rate.

The SDK accepts and displays fee rates in sat/vB. Internally the value is stored as sat/kvB, which is equivalent to fixed-point sat/vB with three decimal places, without using Lightning msat terminology for on-chain fees.

func NewFeeRateSatPerKVByte

func NewFeeRateSatPerKVByte(satPerKVByte uint64) FeeRate

NewFeeRateSatPerKVByte constructs a fee rate from sat/kvB.

func NewFeeRateSatPerVByte

func NewFeeRateSatPerVByte(satPerVByte uint64) (FeeRate, error)

NewFeeRateSatPerVByte constructs a fee rate from whole sat/vB.

func ParseFeeRateSatPerVByte

func ParseFeeRateSatPerVByte(value string) (FeeRate, error)

ParseFeeRateSatPerVByte parses a decimal sat/vB fee rate.

func (FeeRate) IsZero

func (r FeeRate) IsZero() bool

IsZero returns true if the fee rate is unset.

func (FeeRate) MarshalText

func (r FeeRate) MarshalText() ([]byte, error)

MarshalText formats the fee rate as decimal sat/vB.

func (FeeRate) SatPerKVByte

func (r FeeRate) SatPerKVByte() uint64

SatPerKVByte returns the fee rate in sat/kvB.

func (FeeRate) SatPerKWeight

func (r FeeRate) SatPerKWeight() uint64

SatPerKWeight returns the fee rate in sat/kWU, rounded up.

func (FeeRate) SatPerVByteCeil

func (r FeeRate) SatPerVByteCeil() uint64

SatPerVByteCeil returns the fee rate in sat/vB, rounded up.

func (FeeRate) SatPerVByteFloor

func (r FeeRate) SatPerVByteFloor() uint64

SatPerVByteFloor returns the fee rate in sat/vB, rounded down.

func (FeeRate) String

func (r FeeRate) String() string

String returns the fee rate formatted as sat/vB.

func (*FeeRate) UnmarshalText

func (r *FeeRate) UnmarshalText(text []byte) error

UnmarshalText parses a decimal sat/vB fee rate.

type FetchAssetMetaRequest

type FetchAssetMetaRequest struct {
	// AssetRef identifies the asset whose metadata should be fetched.
	AssetRef *AssetRef

	// MetaHash is the 32-byte meta hash.
	MetaHash *Hash
}

FetchAssetMetaRequest specifies how to look up asset metadata. Exactly one of the fields must be set.

type FinalizeBatchRequest

type FinalizeBatchRequest struct {
	// ShortResponse asks the daemon to omit batch asset details.
	ShortResponse bool

	// FeeRate is the optional fee rate. Zero uses the daemon default.
	FeeRate FeeRate

	// BatchSibling is the optional tapscript sibling for the batch output.
	BatchSibling *BatchSibling
}

FinalizeBatchRequest finalizes the current pending mint batch.

type FundBatchRequest

type FundBatchRequest struct {
	// ShortResponse asks the daemon to omit batch asset details.
	ShortResponse bool

	// FeeRate is the optional fee rate. Zero uses the daemon default.
	FeeRate FeeRate

	// BatchSibling is the optional tapscript sibling for the batch output.
	BatchSibling *BatchSibling
}

FundBatchRequest funds the current pending mint batch.

type FundedTransfer

type FundedTransfer struct {
	// FundedPsbt is the funded virtual transaction PSBT.
	FundedPsbt []byte

	// PassiveAssetPsbts are the PSBTs for passive assets that need to be
	// re-signed.
	PassiveAssetPsbts [][]byte
}

FundedTransfer represents the result of funding a virtual transaction.

type FungibleAssetSpec

type FungibleAssetSpec struct {
	// Name is the human-readable asset name.
	Name string

	// Amount is the number of units in the first issuance.
	Amount uint64

	// AssetMeta is the optional metadata committed to the first issuance.
	AssetMeta *AssetMeta

	// AssetVersion is the asset encoding version.
	AssetVersion AssetVersion

	// DecimalDisplay is the wallet display precision for the asset.
	DecimalDisplay uint32

	// ScriptKey is the optional custom script key for the first issuance.
	ScriptKey *ScriptKey

	// EnableSupplyCommitments enables supply commitments for the asset.
	EnableSupplyCommitments bool
}

FungibleAssetSpec describes a fungible token created through the high-level issuer surface. New fungible assets are grouped so their AssetRef remains stable across future issuances.

type GenesisInfo

type GenesisInfo struct {
	// GenesisPoint is the outpoint that created the asset.
	GenesisPoint string

	// Name is the asset name.
	Name string

	// MetaHash is the metadata hash committed into genesis.
	MetaHash Hash

	// IssuanceID is the protocol-level identifier for this concrete
	// issuance/tranche.
	IssuanceID AssetID

	// AssetType is the genesis asset type.
	AssetType AssetType

	// OutputIndex is the anchor output index in the genesis transaction.
	OutputIndex uint32
}

GenesisInfo describes a concrete issuance genesis record used in mint responses.

type GlobalFederationSyncConfig

type GlobalFederationSyncConfig struct {
	// ProofType is the universe proof type this config applies to.
	ProofType ProofType

	// AllowSyncInsert enables federation insert for this type.
	AllowSyncInsert bool

	// AllowSyncExport enables federation export for this type.
	AllowSyncExport bool
}

GlobalFederationSyncConfig is a per-proof-type federation sync policy.

type GroupKeyRequest

type GroupKeyRequest struct {
	// RawKey is the group internal key when locally managed.
	RawKey *KeyDescriptor

	// AnchorGenesis is the genesis of the asset anchoring the group.
	AnchorGenesis *GenesisInfo

	// TapscriptRoot is the optional tapscript root used in the group key.
	TapscriptRoot []byte

	// NewAsset is the serialized asset requesting group membership.
	NewAsset []byte

	// ExternalKey is the external key used for group signing, if any.
	ExternalKey *ExternalKey
}

GroupKeyRequest describes the group membership material for an unsealed mint asset.

type GroupVirtualTx

type GroupVirtualTx struct {
	// Transaction is the serialized virtual transaction.
	Transaction []byte

	// PrevOut is the output being spent in the virtual transaction.
	PrevOut *TxOut

	// GenesisID is the grouped asset's asset ID.
	GenesisID AssetID

	// TweakedKey is the tweaked group key for the request.
	TweakedKey *PubKey
}

GroupVirtualTx describes the virtual transaction used for group witness construction.

type GroupWitness

type GroupWitness struct {
	// GenesisID identifies the pending asset to authorize.
	GenesisID AssetID

	// Witness is the serialized witness stack.
	Witness [][]byte
}

GroupWitness authorizes a pending asset to join an asset group.

type GroupedUniverseEvents

type GroupedUniverseEvents struct {
	// Date is the day formatted as YYYY-MM-DD.
	Date string

	// SyncEvents is the number of sync events on this day.
	SyncEvents uint64

	// NewProofEvents is the number of new proof events on this day.
	NewProofEvents uint64
}

GroupedUniverseEvents are daily aggregated event counts.

type Hash

type Hash [32]byte

Hash is a 32-byte hash value.

func AnchorOutputTaprootAssetRoot added in v0.2.0

func AnchorOutputTaprootAssetRoot(anchorPSBT []byte,
	outputIndex int) (Hash, bool, error)

AnchorOutputTaprootAssetRoot returns the Taproot Asset commitment root that tapd records as a custom PSBT field on the asset-carrying outputs of a committed anchor transaction. The boolean reports whether the output carries the field. An error is returned when the PSBT cannot be decoded, the output index is out of range, or the recorded value is not a 32-byte root.

Integrators that persist or relay committed anchor PSBTs can use this to recover an output's commitment root without depending on tapd's internal PSBT conventions.

func ParseHash

func ParseHash(b []byte) (Hash, error)

ParseHash parses a 32-byte hash from raw bytes. An empty slice returns the zero hash.

func ParseHashHex

func ParseHashHex(s string) (Hash, error)

ParseHashHex parses a hex-encoded 32-byte hash. An empty string returns the zero hash.

func (Hash) String

func (h Hash) String() string

String returns the hex encoding of the hash.

type ImportBackupRequest

type ImportBackupRequest struct {
	Backup []byte
}

ImportBackupRequest provides a previously exported backup blob.

type ImportBackupResponse

type ImportBackupResponse struct {
	NumImported uint32
}

ImportBackupResponse reports how many assets were imported.

type Info

type Info struct {
	// Version is the version that tapd is running.
	Version string

	// LndVersion is the full version string of the LND node tapd is connected to.
	LndVersion string

	// Network is the network tapd is connected to,
	// e.g. "mainnet", "testnet", or any other supported network.
	Network string

	// LndIdentityPubkey is the public key of the LND node tapd is connected to.
	LndIdentityPubkey PubKey

	// NodeAlias is the alias of the LND node tapd is connected to.
	NodeAlias string

	// BlockHeight is the best block height that tapd has knowledge of.
	BlockHeight uint32

	// BlockHash is the current block hash as seen by the LND node
	// tapd is connected to.
	BlockHash chainhash.Hash

	// SyncedToChain is true if the wallet's view is synced to the main
	// chain.
	SyncedToChain bool
}

Info contains info about the connected tapd instance.

type InteractiveSendRequest

type InteractiveSendRequest struct {
	// AssetRef identifies the asset to send.
	AssetRef AssetRef

	// Amount is the number of asset units to send.
	Amount uint64

	// ReceiverKeys contains the keys derived by the receiver.
	ReceiverKeys DerivedKeys
}

InteractiveSendRequest represents a request to send assets interactively.

type InteractiveTxBuilder

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

InteractiveTxBuilder builds interactive Taproot Asset transfers where the receiver provides their keys directly (rather than a Taproot Asset address).

Interactive transfers require manual proof delivery after completion. The returned AssetTransfer contains the proofs that must be sent to the receiver.

func (*InteractiveTxBuilder) Execute

Execute builds and sends the interactive transfer. Returns AssetTransfer with proofs that must be delivered to the receiver.

func (*InteractiveTxBuilder) SetAsset

func (b *InteractiveTxBuilder) SetAsset(ref AssetRef,
	amount uint64) *InteractiveTxBuilder

SetAsset specifies which asset and how much to send. Asset-ID refs are used directly. Group-key refs are resolved against the wallet's spendable assets during Execute, so callers can keep using the SDK's semantic fungible asset identifier unless no single issuance/tranche can cover the requested amount.

func (*InteractiveTxBuilder) SetLockTime

func (b *InteractiveTxBuilder) SetLockTime(
	lockTime uint64) *InteractiveTxBuilder

SetLockTime sets the optional lock time for the output.

func (*InteractiveTxBuilder) SetReceiverKeys

func (b *InteractiveTxBuilder) SetReceiverKeys(
	keys DerivedKeys) *InteractiveTxBuilder

SetReceiverKeys sets the keys derived by the receiver. These keys are obtained by the receiver calling Wallet.DeriveKeys().

func (*InteractiveTxBuilder) SetRelativeLockTime

func (b *InteractiveTxBuilder) SetRelativeLockTime(
	relativeLockTime uint64) *InteractiveTxBuilder

SetRelativeLockTime sets the optional relative lock time for the output.

func (*InteractiveTxBuilder) WithAltLeaves

func (b *InteractiveTxBuilder) WithAltLeaves(
	scriptKey PubKey,
	leaves [][]byte) *InteractiveTxBuilder

WithAltLeaves attaches auxiliary Taproot leaves that should be committed to the receiver's output.

type InternalKey

type InternalKey struct {
	// PubKey is the raw public key bytes (33 bytes compressed).
	PubKey PubKey

	// KeyLocator identifies the key's derivation path.
	KeyLocator KeyLocator
}

InternalKey represents an anchor output internal key. This key is used as the internal key for the Taproot output that anchors the asset commitment on-chain.

type Issuance

type Issuance struct {
	// AssetRef is the stable SDK identifier of the fungible asset this
	// issuance belongs to.
	AssetRef AssetRef

	// IssuanceID is the protocol-level asset ID for this tranche.
	IssuanceID AssetID

	// Name is the human-readable asset tag.
	Name string

	// MetaHash is the issuance metadata hash.
	MetaHash Hash

	// Amount is the sum of wallet rows returned by the ListIssuances request
	// for this tranche. With the default request this is wallet-known,
	// confirmed, unspent, and unleased amount, not total issued supply.
	Amount uint64
}

Issuance is one concrete fungible asset issuance/tranche.

func (Issuance) Ref

func (i Issuance) Ref() AssetRef

Ref returns the AssetRef for this concrete issuance/tranche.

type IssuanceGenesis

type IssuanceGenesis struct {
	// FirstPrevOut is the outpoint of the first input of the genesis transaction.
	FirstPrevOut Outpoint

	// Tag is the asset tag.
	Tag string

	// MetaHash is the meta data hash.
	MetaHash Hash

	// IssuanceID is the unique 32-byte protocol-level identifier for this
	// specific issuance/tranche.
	IssuanceID AssetID

	// OutputIndex is the output index of the genesis transaction.
	OutputIndex uint32

	// Type is the asset type.
	Type AssetType
}

IssuanceGenesis is the protocol-level genesis information for one concrete asset issuance/tranche.

type IssuanceOperation

type IssuanceOperation uint8

IssuanceOperation identifies the high-level issuer action that needs an external signature.

const (
	// IssuanceOperationUnknown means the signing operation was not classified.
	IssuanceOperationUnknown IssuanceOperation = 0

	// IssuanceOperationCreateAsset creates the first issuance of a fungible
	// Asset.
	IssuanceOperationCreateAsset IssuanceOperation = 1

	// IssuanceOperationIssueAsset creates another Issuance for an existing
	// fungible Asset.
	IssuanceOperationIssueAsset IssuanceOperation = 2

	// IssuanceOperationCreateCollection creates the first item in a new
	// Collection.
	IssuanceOperationCreateCollection IssuanceOperation = 3

	// IssuanceOperationMintCollectionItem creates another item in an existing
	// Collection.
	IssuanceOperationMintCollectionItem IssuanceOperation = 4
)

func (IssuanceOperation) String

func (o IssuanceOperation) String() string

String returns the stable name for an issuance operation.

type IssuanceSigningRequest

type IssuanceSigningRequest struct {
	// Operation is the high-level issuer action being authorized.
	Operation IssuanceOperation

	// AssetRef is the stable SDK identifier for the Asset or Collection. For a
	// first issuance this is inferred from the funded signing payload.
	AssetRef AssetRef

	// Name is the Asset or Collection item name.
	Name string

	// AssetType is the kind of asset being issued.
	AssetType AssetType

	// Amount is the number of units this signing request authorizes.
	Amount uint64

	// ScriptKey is the asset-level spending key for the issued units.
	ScriptKey *ScriptKey

	// ExternalKey is the external key descriptor that should sign.
	ExternalKey ExternalKey

	// AnchorGenesis is the concrete genesis information committed by the funded
	// mint batch.
	AnchorGenesis *GenesisInfo

	// VirtualPSBT is the base64 PSBT that must be signed externally.
	VirtualPSBT string

	// VirtualTx is the decoded virtual transaction metadata for review.
	VirtualTx *GroupVirtualTx
}

IssuanceSigningRequest describes the SDK-level issuance authorization that needs an external Taproot signature.

type Issuer

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

Issuer is the high-level minting surface for SDK business assets.

It creates grouped fungible assets, standalone NFTs, NFT collections, and additional supply or collection items while hiding tapd batch mechanics from application code. MintClient remains available through Client for callers that need direct batch control.

Issuer serializes its own mint calls because tapd has one active mint batch per daemon. Issuers returned by the same Wallet share that lock.

func NewIssuer

func NewIssuer(client Client) *Issuer

NewIssuer creates a high-level issuer backed by the given client. Concurrent calls on the returned Issuer are serialized.

func (*Issuer) CreateCollection

func (i *Issuer) CreateCollection(ctx context.Context,
	firstItem NFTSpec,
	opts ...MintOption) (*CollectionMintResult, error)

CreateCollection creates a new NFT collection by minting the first item in a grouped collectible asset. It returns the collection and first item together in a CollectionMintResult.

If the returned error wraps ErrMintResolveTimeout, tapd may already have accepted or finalized the mint. Do not blindly retry; inspect wallet assets, collections, or mint batches first to avoid duplicate NFTs.

func (*Issuer) CreateFungible

func (i *Issuer) CreateFungible(ctx context.Context,
	spec FungibleAssetSpec,
	opts ...MintOption) (*Asset, error)

CreateFungible creates a grouped fungible asset and returns the SDK business Asset keyed by its group AssetRef.

If the returned error wraps ErrMintResolveTimeout, tapd may already have accepted or finalized the mint. Do not blindly retry; inspect wallet assets, issuances, or mint batches first to avoid duplicate issuance.

func (*Issuer) CreateNFT

func (i *Issuer) CreateNFT(ctx context.Context, spec NFTSpec,
	opts ...MintOption) (*Asset, error)

CreateNFT creates a standalone NFT and returns it as an Asset keyed by its asset-ID AssetRef.

If the returned error wraps ErrMintResolveTimeout, tapd may already have accepted or finalized the mint. Do not blindly retry; inspect wallet assets or mint batches first to avoid duplicate NFTs.

func (*Issuer) IssueFungible

func (i *Issuer) IssueFungible(ctx context.Context,
	ref AssetRef, amount uint64,
	opts ...MintOption) (*Issuance, error)

IssueFungible creates an additional issuance for an existing grouped fungible asset.

If the returned error wraps ErrMintResolveTimeout, tapd may already have accepted or finalized the mint. Do not blindly retry; inspect wallet assets, issuances, or mint batches first to avoid duplicate issuance.

func (*Issuer) MintCollectionItem

func (i *Issuer) MintCollectionItem(ctx context.Context,
	collectionRef AssetRef, item NFTSpec,
	opts ...MintOption) (*Asset, error)

MintCollectionItem mints a new NFT item into an existing collection.

If the returned error wraps ErrMintResolveTimeout, tapd may already have accepted or finalized the mint. Do not blindly retry; inspect wallet assets, collections, or mint batches first to avoid duplicate NFTs.

type KeyDescriptor

type KeyDescriptor struct {
	// RawKeyBytes is the raw public key bytes (33 bytes compressed).
	RawKeyBytes PubKey

	// KeyLocator identifies the key's derivation path.
	KeyLocator KeyLocator
}

KeyDescriptor contains key bytes and locator information.

type KeyLocator

type KeyLocator struct {
	// Family is the key family (derivation purpose).
	Family uint32

	// Index is the specific key index within the family.
	Index uint32
}

KeyLocator identifies a key in the key derivation path.

type ListAssetsRequest

type ListAssetsRequest struct {
	// WithWitness includes asset witnesses in low-level records. It is
	// forwarded to tapd unchanged by all listing surfaces.
	WithWitness bool

	// IncludeSpent includes spent assets. It is forwarded to tapd unchanged
	// by all listing surfaces.
	IncludeSpent bool

	// IncludeLeased includes leased assets. It is forwarded to tapd
	// unchanged by all listing surfaces.
	IncludeLeased bool

	// IncludeUnconfirmedMints includes freshly minted assets before anchor
	// confirmation. It is forwarded to tapd unchanged by all listing
	// surfaces.
	IncludeUnconfirmedMints bool

	// MinAmount filters by amount. Wallet.ListAssets applies it after
	// aggregating protocol rows into semantic assets; low-level
	// Client.ListAssetRecords forwards it to tapd as a per-record filter.
	// Zero means unset.
	MinAmount uint64

	// MaxAmount filters by amount. Wallet.ListAssets applies it after
	// aggregating protocol rows into semantic assets; low-level
	// Client.ListAssetRecords forwards it to tapd as a per-record filter.
	// Zero means unset.
	MaxAmount uint64

	// AssetRef filters by SDK asset identity. Group refs are forwarded to
	// tapd's group_key filter; asset-ID refs are matched locally because
	// tapd's asset listing endpoint has no asset-ID filter.
	AssetRef *AssetRef

	// AnchorOutpoint filters records by the Bitcoin outpoint that anchors
	// them. It is forwarded to tapd unchanged.
	AnchorOutpoint *Outpoint

	// ScriptKeyType filters by script-key role. It is forwarded to tapd
	// unchanged after SDK-side validation.
	ScriptKeyType *ScriptKeyTypeQuery
}

ListAssetsRequest specifies filters for listing wallet assets. Wallet-level ListAssets returns SDK business assets; low-level clients use the same request for tapd's per-record rows.

type ListBalancesRequest

type ListBalancesRequest struct {
	// AssetRef restricts the result to a single asset.
	AssetRef *AssetRef

	// IncludeLeased includes assets that are currently leased by a pending
	// transfer and therefore unavailable for coin selection.
	IncludeLeased bool

	// ScriptKeyType optionally restricts balances to a specific script key
	// type or all types.
	ScriptKeyType *ScriptKeyTypeQuery
}

ListBalancesRequest specifies filters for querying wallet balances using the SDK's semantic asset model.

type ListBalancesResponse

type ListBalancesResponse struct {
	// Balances is keyed by AssetRef.String().
	Balances map[string]*Balance

	// UnconfirmedTransfers counts outgoing transfers that are not yet
	// confirmed on-chain and therefore excluded from the reported balances.
	UnconfirmedTransfers uint64
}

ListBalancesResponse contains wallet balances keyed by AssetRef.

type ListBatchesRequest

type ListBatchesRequest struct {
	// BatchKey filters the response to a single batch when set.
	BatchKey *PubKey

	// Verbose asks the daemon to include unsealed asset details.
	Verbose bool
}

ListBatchesRequest queries known mint batches.

type ListBurnsRequest

type ListBurnsRequest struct {
	// AssetRef filters by the burnt asset.
	AssetRef *AssetRef

	// AnchorTxid filters by the anchor transaction id.
	AnchorTxid *Hash
}

ListBurnsRequest specifies filters for listing asset burns.

type ListCollectionItemsRequest

type ListCollectionItemsRequest struct {
	// CollectionRef filters by collection AssetRef.
	CollectionRef *AssetRef

	// AssetRef filters by a single NFT AssetRef.
	AssetRef *AssetRef
}

ListCollectionItemsRequest specifies filters for NFTs within collections. A nil request, or a request with both refs unset, lists all wallet-known NFT collection items. If both refs are set, CollectionRef takes precedence.

type ListCollectionsRequest

type ListCollectionsRequest struct {
	// AssetRef filters by collection AssetRef.
	AssetRef *AssetRef
}

ListCollectionsRequest specifies filters for NFT collections. A nil request or nil AssetRef lists all wallet-known collections.

type ListIssuancesRequest

type ListIssuancesRequest struct {
	// AssetRef filters by the fungible asset. For grouped fungibles this is
	// the group-key AssetRef.
	AssetRef *AssetRef
}

ListIssuancesRequest specifies filters for wallet-known fungible issuance/tranche rows. It is not a total issued-supply query; use universe roots for supply/proof data that is independent of current wallet outputs.

type ListTransfersRequest

type ListTransfersRequest struct {
	// AnchorTxid specifies the hexadecimal encoded txid string of the anchor
	// transaction for which to retrieve transfers. An empty value indicates
	// that this parameter should be disregarded in transfer selection.
	AnchorTxid string
}

ListTransfersRequest specifies filters for listing outgoing transfers.

type ListUtxosRequest

type ListUtxosRequest struct {
	// IncludeLeased includes UTXOs that are marked as leased.
	IncludeLeased bool

	// ScriptKeyType filters the assets by script key type.
	ScriptKeyType *ScriptKeyTypeQuery
}

ListUtxosRequest specifies filters for listing managed UTXOs.

type MacaroonSource

type MacaroonSource = macaroon.Source

MacaroonSource describes where the SDK should load tapd authentication macaroons from.

func MacaroonFromDir

func MacaroonFromDir(dir string) MacaroonSource

MacaroonFromDir loads one macaroon per tapd service from a directory.

func MacaroonFromHex

func MacaroonFromHex(hex string) MacaroonSource

MacaroonFromHex uses one hex-encoded macaroon for every tapd service.

func MacaroonFromPath

func MacaroonFromPath(path string) MacaroonSource

MacaroonFromPath loads a single macaroon file and reuses it for every tapd service.

type ManagedUtxo

type ManagedUtxo struct {
	// OutPoint is the outpoint of the UTXO.
	OutPoint Outpoint

	// AmtSat is the UTXO amount in satoshis.
	AmtSat int64

	// InternalKey is the internal key used for the on-chain output.
	InternalKey PubKey

	// TaprootAssetRoot is the Taproot Asset root commitment hash.
	TaprootAssetRoot Hash

	// MerkleRoot is the Taproot merkle root hash.
	MerkleRoot Hash

	// Assets are the low-level asset records held at this UTXO.
	Assets []*AssetRecord

	// LeaseOwner is the lease owner for this UTXO. Empty if unleased.
	LeaseOwner []byte

	// LeaseExpiryUnix is the unix timestamp when the lease expires.
	// Zero if unleased.
	LeaseExpiryUnix int64
}

ManagedUtxo represents a UTXO managed by the tapd daemon.

type MerkleSumNode

type MerkleSumNode struct {
	// RootHash is the MS-SMT root hash.
	RootHash Hash

	// RootSum is the aggregate supply sum of the subtree.
	RootSum int64
}

MerkleSumNode is a node in the Merkle-Sum Sparse Merkle Tree.

type MintAsset

type MintAsset struct {
	// AssetVersion is the asset encoding version.
	AssetVersion AssetVersion

	// AssetType is the type of asset to mint.
	AssetType AssetType

	// Name is the asset tag.
	Name string

	// AssetMeta is the optional metadata committed to the genesis.
	AssetMeta *AssetMeta

	// InitialSupply is the number of units in the first issuance.
	InitialSupply uint64

	// AllowIssuance creates the asset with a group key so future issuances are
	// possible.
	AllowIssuance bool

	// DecimalDisplay is the wallet display precision for the asset.
	DecimalDisplay uint32

	// ScriptKey is the optional custom script key for the first issuance.
	ScriptKey *ScriptKey

	// GroupInternalKey is the internal key for a newly issuable asset.
	GroupInternalKey *KeyDescriptor

	// GroupTapscriptRoot is the optional tapscript root for a newly issuable
	// asset.
	GroupTapscriptRoot []byte

	// ExternalGroupKey enables external signing for future issuance.
	ExternalGroupKey *ExternalKey

	// EnableSupplyCommitments enables supply commitments for a newly issuable
	// asset.
	EnableSupplyCommitments bool
}

MintAsset describes a brand-new protocol asset to add to a minting batch.

type MintAssetRequest

type MintAssetRequest struct {
	// Asset is the asset to mint.
	Asset *MintAsset

	// ShortResponse asks the daemon to omit existing batch assets.
	ShortResponse bool
}

MintAssetRequest adds a brand-new protocol asset to the pending mint batch.

type MintClient

type MintClient interface {
	// MintAsset adds a brand-new asset to the pending mint batch.
	MintAsset(ctx context.Context,
		req *MintAssetRequest) (*MintingBatch, error)

	// MintIssuance adds an additional issuance/tranche for an existing
	// asset in the pending mint batch.
	MintIssuance(ctx context.Context,
		req *MintIssuanceRequest) (*MintingBatch, error)

	// FundBatch funds the current pending mint batch.
	FundBatch(ctx context.Context,
		req *FundBatchRequest) (*VerboseMintingBatch,
		error)

	// SealBatch seals a funded batch before finalization.
	SealBatch(ctx context.Context,
		req *SealBatchRequest) (*MintingBatch, error)

	// FinalizeBatch finalizes the current pending mint batch.
	FinalizeBatch(ctx context.Context,
		req *FinalizeBatchRequest) (*MintingBatch, error)

	// CancelBatch cancels the current mint batch.
	CancelBatch(ctx context.Context) (*CancelBatchResponse, error)

	// ListBatches lists mint batches known to the daemon.
	ListBatches(ctx context.Context,
		req *ListBatchesRequest) ([]*VerboseMintingBatch,
		error)
}

MintClient exposes low-level minting operations from the Mint service gRPC client.

These methods are batch building blocks for advanced callers. Application code that wants business entities should use Issuer instead.

type MintEvent

type MintEvent struct {
	// Timestamp is the event execution time as a Unix timestamp in
	// microseconds.
	Timestamp int64

	// BatchState is the last batch state that was executed. If Error
	// is set, this is the state that caused the failure.
	BatchState BatchState

	// Batch contains the minting batch details.
	Batch *MintingBatch

	// Error is an optional error string.
	Error string
}

MintEvent represents a minting batch event.

type MintIssuance

type MintIssuance struct {
	// AssetRef identifies the asset to issue more units of. It must resolve to a
	// group key.
	AssetRef AssetRef

	// Name is the asset tag of the existing asset. tapd still requires it on the
	// underlying mint request.
	Name string

	// AssetType is the type of the existing asset.
	AssetType AssetType

	// AssetMeta is the optional metadata committed to this issuance.
	AssetMeta *AssetMeta

	// Amount is the number of units to issue in this tranche.
	Amount uint64

	// AssetVersion is the asset encoding version.
	AssetVersion AssetVersion

	// DecimalDisplay is the display precision for the issuance metadata.
	DecimalDisplay uint32

	// ScriptKey is the optional custom script key for the issuance.
	ScriptKey *ScriptKey

	// ExternalGroupKey enables external signing for the group issuance.
	ExternalGroupKey *ExternalKey
}

MintIssuance describes an additional issuance/tranche for an existing grouped asset.

type MintIssuanceRequest

type MintIssuanceRequest struct {
	// Issuance is the issuance to mint.
	Issuance *MintIssuance

	// ShortResponse asks the daemon to omit existing batch assets.
	ShortResponse bool
}

MintIssuanceRequest adds an additional issuance to the pending mint batch.

type MintOption

type MintOption func(*MintOptions)

MintOption configures high-level issuer calls.

func WithExternalIssuanceKey

func WithExternalIssuanceKey(key ExternalKey) MintOption

WithExternalIssuanceKey configures an externally managed issuance key for high-level issuer calls. It maps to tapd's external group key at the transport boundary while keeping application code on the SDK Asset, Collection, and Issuance model.

func WithExternalIssuanceSigner

func WithExternalIssuanceSigner(signer ExternalIssuanceSigner) MintOption

WithExternalIssuanceSigner configures the signer used when the issuer needs an external issuance authorization signature.

func WithMintFeeRate

func WithMintFeeRate(feeRate FeeRate) MintOption

WithMintFeeRate sets the target fee rate for the genesis transaction. A zero value uses tapd's daemon default.

func WithMintResolveTimeout

func WithMintResolveTimeout(timeout time.Duration) MintOption

WithMintResolveTimeout sets how long high-level issuer calls wait for tapd's wallet projection to expose the accepted mint result. If this timeout is hit, the call returns ErrMintResolveTimeout and the mint may still have been accepted by tapd.

type MintOptions

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

MintOptions contains optional parameters for high-level issuer calls.

type MintingBatch

type MintingBatch struct {
	// BatchKey uniquely identifies the batch.
	BatchKey PubKey

	// BatchTxid is the finalized genesis transaction ID, if any.
	BatchTxid string

	// State is the current lifecycle state.
	State BatchState

	// Assets are the assets currently staged in the batch.
	Assets []PendingMintAsset

	// CreatedAt is the batch creation time as a Unix timestamp.
	CreatedAt int64

	// HeightHint is the chain height at batch creation time.
	HeightHint uint32

	// BatchPSBT is the genesis transaction PSBT, if available.
	BatchPSBT []byte
}

MintingBatch is the daemon's view of a minting batch.

type NFTSpec

type NFTSpec struct {
	// Name is the human-readable item name.
	Name string

	// AssetMeta is the optional metadata committed to the NFT.
	AssetMeta *AssetMeta

	// AssetVersion is the asset encoding version.
	AssetVersion AssetVersion

	// ScriptKey is the optional custom script key for the NFT.
	ScriptKey *ScriptKey
}

NFTSpec describes a non-fungible token created through the high-level issuer surface. The same spec is used for standalone NFTs, first collection items, and additional collection items.

type Network

type Network string

Network defines the chain that we operate on.

const (
	// NetworkMainnet is bitcoin mainnet.
	NetworkMainnet Network = "mainnet"

	// NetworkTestnet is bitcoin testnet.
	NetworkTestnet Network = "testnet"

	// NetworkTestnet4 is bitcoin testnet version 4.
	NetworkTestnet4 Network = "testnet4"

	// NetworkRegtest is bitcoin regtest.
	NetworkRegtest Network = "regtest"

	// NetworkSimnet is bitcoin simnet.
	NetworkSimnet Network = "simnet"

	// NetworkSignet is bitcoin signet.
	NetworkSignet Network = "signet"
)

type NewAddressRequest

type NewAddressRequest struct {
	// AssetRef is the SDK's user-facing identifier for the asset to receive.
	// For V0/V1 addresses this must resolve to a concrete issuance asset ID.
	// For V2 addresses it may resolve to either an issuance asset ID or a
	// group key.
	AssetRef AssetRef

	// Amount is the number of asset units to receive.
	// Required for V0/V1 addresses. Optional for V2 addresses (zero means
	// sender chooses the amount).
	Amount uint64

	// ScriptKey is an optional custom script key for the receiving asset.
	// If nil, tapd derives a BIP-86 key from its wallet.
	// NOTE: If set, InternalKey must also be set.
	ScriptKey *ScriptKey

	// InternalKey is an optional custom internal key for the anchor output.
	// If nil, tapd derives a key from its wallet.
	// NOTE: If set, ScriptKey must also be set.
	InternalKey *KeyDescriptor

	// TapscriptSibling is an optional tapscript sibling preimage for
	// additional script paths in the Taproot tree.
	TapscriptSibling []byte

	// ProofCourierAddr is the optional proof courier address.
	// If empty, tapd uses its configured default.
	// For V2 addresses, must be a valid auth mailbox URL.
	ProofCourierAddr string

	// AssetVersion is the asset version for transfers to this address.
	// Defaults to the latest version if not specified.
	AssetVersion *AssetVersion

	// AddressVersion is the address format version to use.
	// Defaults to the latest version if not specified.
	AddressVersion *AddressVersion

	// SkipProofCourierConnCheck skips the connectivity check to the proof
	// courier when creating the address. Useful for offline address
	// creation.
	SkipProofCourierConnCheck bool
}

NewAddressRequest contains parameters for generating a new Taproot Asset address.

type Outpoint

type Outpoint struct {
	// Txid is the 32-byte transaction hash.
	Txid [32]byte

	// Index is the output index within the transaction.
	Index uint32
}

Outpoint represents a Bitcoin transaction outpoint.

func NewOutpointFromStr

func NewOutpointFromStr(s string) (Outpoint, error)

NewOutpointFromStr parses an outpoint from a string in "txid:index" format.

func (Outpoint) String

func (o Outpoint) String() string

String returns the outpoint in "txid:index" format.

type OwnershipOption

type OwnershipOption func(*ownershipOptions)

OwnershipOption configures Wallet ownership proof calls.

func WithAllOwnedCollectionItems

func WithAllOwnedCollectionItems() OwnershipOption

WithAllOwnedCollectionItems asks ProveOwnership to return a proof for every wallet-owned NFT item in the requested collection. Without this option, a collection AssetRef proves ownership of one wallet-owned collection item.

func WithOwnershipAmount

func WithOwnershipAmount(amount uint64) OwnershipOption

WithOwnershipAmount asks ProveOwnership to return enough fungible output proofs to cover at least the requested amount.

func WithOwnershipChallenge

func WithOwnershipChallenge(challenge []byte) OwnershipOption

WithOwnershipChallenge binds an ownership proof to a 32-byte challenge. The same challenge must be supplied when verifying the proof.

type OwnershipProof

type OwnershipProof struct {
	// AssetRef is the SDK handle proven by this entry. Grouped fungibles use
	// the group AssetRef; NFTs use the concrete item AssetRef.
	AssetRef AssetRef

	// IssuanceID is the protocol-level asset ID proven by this entry.
	IssuanceID AssetID

	// ScriptKey is the script key used to prove ownership.
	ScriptKey PubKey

	// Outpoint is the asset anchor outpoint verified by tapd.
	Outpoint Outpoint

	// Amount is the number of units held at the proven output.
	Amount uint64

	// ProofWithWitness is the full ownership proof with witness data.
	ProofWithWitness []byte
}

OwnershipProof is one ownership proof and its wallet-resolved metadata.

type OwnershipProofSet

type OwnershipProofSet struct {
	// AssetRef is the user-facing asset or collection handle requested by the
	// caller.
	AssetRef AssetRef

	// Proofs contains the concrete output proofs that satisfy the request.
	Proofs []OwnershipProof
}

OwnershipProofSet is a Wallet-level ownership proof result for a user-facing AssetRef.

type ParcelType

type ParcelType uint8

ParcelType represents the type of an outbound send parcel.

const (
	// ParcelTypeAddress is a parcel sent to one or more addresses.
	ParcelTypeAddress ParcelType = 0

	// ParcelTypePreSigned is a parcel created from pre-signed
	// virtual packets.
	ParcelTypePreSigned ParcelType = 1

	// ParcelTypePending is a pending parcel that has not yet been
	// broadcast.
	ParcelTypePending ParcelType = 2

	// ParcelTypePreAnchored is a parcel that was pre-anchored.
	ParcelTypePreAnchored ParcelType = 3
)

type PendingMintAsset

type PendingMintAsset struct {
	// AssetVersion is the asset encoding version.
	AssetVersion AssetVersion

	// AssetType is the type of asset to mint.
	AssetType AssetType

	// Name is the asset tag.
	Name string

	// AssetMeta is the optional metadata committed to the genesis.
	AssetMeta *AssetMeta

	// Amount is the number of units to mint.
	Amount uint64

	// NewGroupedAsset creates a new asset group for future issuance.
	NewGroupedAsset bool

	// GroupKey joins an existing group by explicit key.
	GroupKey *PubKey

	// GroupAnchor joins the group created by another asset in the batch.
	GroupAnchor string

	// GroupInternalKey is the internal key for a new group.
	GroupInternalKey *KeyDescriptor

	// GroupTapscriptRoot is the optional tapscript root for a new group.
	GroupTapscriptRoot []byte

	// ScriptKey is the optional custom script key for the asset.
	ScriptKey *ScriptKey
}

PendingMintAsset represents an asset staged in a minting batch.

type PrevID

type PrevID struct {
	// Outpoint is the bitcoin anchor output on chain.
	Outpoint Outpoint

	// IssuanceID is the 32-byte protocol-level asset identifier of the
	// previous asset tree.
	IssuanceID AssetID

	// ScriptKey is the tweaked Taproot output key.
	ScriptKey PubKey
}

PrevID represents a previous asset input to be spent. It is the Taproot Assets protocol-level identifier for an input asset.

type ProofBundle

type ProofBundle struct {
	// AssetRef is the user-facing asset or collection handle requested by
	// the caller.
	AssetRef AssetRef

	// Entries are the proof files that make up the bundle.
	Entries []ProofEntry
}

ProofBundle is a wallet-level proof export for a user-facing AssetRef.

A bundle can contain one or more proof files. For a single NFT/collectible or ungrouped asset this is normally one entry. For a grouped fungible asset, entries enumerate the wallet-known issuances/tranches behind the group ref.

type ProofClient

type ProofClient interface {
	// ExportProof exports a proof file for a specific asset output.
	// If outpoint is nil, then the latest proof for the given asset/script key
	// is exported. AssetRef must resolve to an asset ID; group-key refs are
	// rejected because a single proof commits to exactly one tranche.
	ExportProof(ctx context.Context, ref AssetRef,
		scriptKey PubKey,
		outpoint *Outpoint) (*ProofFile, error)

	// UnpackProofFile unpacks a proof file into individual proofs.
	UnpackProofFile(ctx context.Context, rawProofFile []byte) ([][]byte, error)

	// DecodeProof decodes a raw proof and returns details about it.
	DecodeProof(ctx context.Context,
		rawProof []byte) (*DecodedProof, error)

	// RegisterTransfer registers an inbound transfer for an interactive send.
	// The proof must already be in the local universe before calling this.
	RegisterTransfer(ctx context.Context, assetRef AssetRef,
		scriptKey PubKey,
		outpoint Outpoint) (*RegisteredAsset, error)
}

ProofClient exposes proof-related operations from the TaprootAssets service.

type ProofEntry

type ProofEntry struct {
	// AssetRef is the user-facing handle for this entry. For grouped
	// fungibles this is the bundle group ref. For NFTs this is the
	// concrete item asset-ID ref.
	AssetRef AssetRef

	// IssuanceID is the protocol-level asset ID proven by this entry.
	IssuanceID AssetID

	// ScriptKey is the asset script key used to locate/export the proof.
	ScriptKey PubKey

	// Outpoint is the optional anchor outpoint used to locate/export the
	// proof when known.
	Outpoint *Outpoint

	// Amount is the number of units proven by this entry.
	Amount uint64

	// ProofFile is the serialized proof file for this entry.
	ProofFile []byte
}

ProofEntry is one proof file inside a ProofBundle.

type ProofFile

type ProofFile struct {
	// RawProofFile is the serialized proof file containing the full
	// provenance chain for the asset.
	RawProofFile []byte

	// GenesisPoint is the outpoint of the asset's genesis transaction.
	GenesisPoint Outpoint
}

ProofFile represents an exported proof file for an asset.

type ProofType

type ProofType int

ProofType distinguishes issuance and transfer universe proofs.

const (
	// ProofTypeUnspecified is the default/zero proof type.
	ProofTypeUnspecified ProofType = 0

	// ProofTypeIssuance limits a query to issuance proofs.
	ProofTypeIssuance ProofType = 1

	// ProofTypeTransfer limits a query to transfer proofs.
	ProofTypeTransfer ProofType = 2
)

type ProveOwnershipRequest

type ProveOwnershipRequest struct {
	// AssetRef identifies the concrete issuance/tranche being proven. The
	// low-level wallet-kit RPC proves ownership over a single
	// (issuance, script key, outpoint) tuple, so AssetRef must resolve to an
	// asset ID.
	AssetRef AssetRef

	// ScriptKey is the script key used to spend the asset.
	ScriptKey PubKey

	// Outpoint is the UTXO outpoint being proven.
	Outpoint Outpoint

	// Challenge is an optional non-zero 32-byte challenge to bind the proof.
	Challenge []byte
}

ProveOwnershipRequest specifies low-level parameters for proving ownership of one concrete asset output. Most application code should use Wallet.ProveOwnership with an AssetRef instead.

type PubKey

type PubKey [33]byte

PubKey is a 33-byte compressed secp256k1 public key.

func ParseGroupRefKey

func ParseGroupRefKey(s string) (PubKey, error)

ParseGroupRefKey decodes a hex-encoded group key in either 33-byte compressed or 32-byte x-only form. tapd surfaces both encodings for the same group depending on which internal code path produced the key; the 33-byte form preserves the y-parity byte, the 32-byte form drops it. Using schnorr.ParsePubKey on a 33-byte input would silently discard the parity and flip odd-y keys, so callers must branch on length. This helper absorbs that ambiguity and returns a normalized compressed key.

func ParsePubKey

func ParsePubKey(b []byte) (PubKey, error)

ParsePubKey parses a 33-byte compressed secp256k1 public key.

func ParsePubKeyHex

func ParsePubKeyHex(s string) (PubKey, error)

ParsePubKeyHex parses a hex-encoded compressed secp256k1 public key.

func ParseScriptKey

func ParseScriptKey(b []byte) (PubKey, error)

ParseScriptKey is an alias for ParseTaprootPubKey.

func ParseTaprootPubKey

func ParseTaprootPubKey(b []byte) (PubKey, error)

ParseTaprootPubKey parses a Taproot public key from raw bytes. The input can be either a 32-byte x-only key or a 33-byte compressed key. The result is normalized to 33-byte compressed encoding.

func (PubKey) Bytes

func (k PubKey) Bytes() []byte

Bytes returns the 33-byte compressed encoding of the public key.

func (PubKey) String

func (k PubKey) String() string

String returns the hex encoding of the public key.

func (PubKey) XOnly

func (k PubKey) XOnly() XOnlyPubKey

XOnly returns the 32-byte x-only encoding of the public key.

type PublishAndLogTransferRequest added in v0.2.0

type PublishAndLogTransferRequest struct {
	// AnchorPsbt is the finalized BTC-level anchor PSBT.
	AnchorPsbt []byte

	// VirtualPsbts are the active virtual asset PSBTs committed to the anchor.
	VirtualPsbts [][]byte

	// PassiveAssetPsbts are passive virtual asset PSBTs committed to the anchor.
	PassiveAssetPsbts [][]byte

	// ChangeOutputIndex is the change index returned by CommitVirtualPsbts.
	ChangeOutputIndex int32

	// LockedUTXOs are the lnd wallet locks returned by CommitVirtualPsbts.
	LockedUTXOs []Outpoint

	// SkipAnchorTxBroadcast leaves the finalized anchor transaction
	// unbroadcast.
	SkipAnchorTxBroadcast bool

	// Label is an optional short label for transfer tracking.
	Label string
}

PublishAndLogTransferRequest publishes a finalized anchor PSBT and logs the corresponding asset transfer.

func (*PublishAndLogTransferRequest) Validate added in v0.2.0

func (r *PublishAndLogTransferRequest) Validate() error

Validate checks that a publish-and-log transfer request can be sent.

type QueryEventsRequest

type QueryEventsRequest struct {
	// StartTimestamp is the start of the range (Unix seconds).
	StartTimestamp int64

	// EndTimestamp is the end of the range (Unix seconds).
	EndTimestamp int64
}

QueryEventsRequest configures a time-range event query.

type QueryRootResponse

type QueryRootResponse struct {
	// IssuanceRoot is the issuance universe root.
	IssuanceRoot *UniverseRoot

	// TransferRoot is the transfer universe root.
	TransferRoot *UniverseRoot
}

QueryRootResponse is the response for a single-asset root query.

type ReceiveEvent

type ReceiveEvent struct {
	// Timestamp is the event creation time as a Unix timestamp in
	// microseconds.
	Timestamp int64

	// AssetRef is the SDK identifier from the receiving address.
	AssetRef AssetRef

	// Amount is the address amount when the address embeds one.
	Amount uint64

	// Status is the current status of the receive event.
	Status AddressEventStatus

	// Outpoint is the outpoint of the on-chain receive transaction.
	Outpoint string

	// ConfirmationHeight is the block height at which the receive
	// transaction was confirmed.
	ConfirmationHeight uint32

	// Error is an optional error string.
	Error string
}

ReceiveEvent is the high-level, AssetRef-keyed view of an incoming receive event emitted by EventListener. Use this for application code that thinks in terms of user-facing assets; for raw protocol fields consume Client.SubscribeReceiveEvents directly to receive ReceiveEventRecord.

func NewReceiveEvent

func NewReceiveEvent(record *ReceiveEventRecord) *ReceiveEvent

NewReceiveEvent projects a raw ReceiveEventRecord into the high-level ReceiveEvent. Returns nil when record is nil.

type ReceiveEventRecord

type ReceiveEventRecord struct {
	// Timestamp is the event creation time as a Unix timestamp in
	// microseconds.
	Timestamp int64

	// Address is the Taproot Asset address that received the asset.
	Address *Address

	// Outpoint is the outpoint of the on-chain transaction used to
	// receive the asset.
	Outpoint string

	// Status is the current status of the receive event.
	Status AddressEventStatus

	// ConfirmationHeight is the block height at which the receive
	// transaction was confirmed. Only set when Status is
	// AddressEventStatusTransactionConfirmed or later.
	ConfirmationHeight uint32

	// Error is an optional error string indicating that processing
	// the event at the current status failed.
	Error string
}

ReceiveEventRecord is the raw, protocol-shaped incoming asset transfer event returned by Client.SubscribeReceiveEvents. Most application code should consume the high-level ReceiveEvent emitted by EventListener instead; ReceiveEventRecord is the escape hatch for advanced callers that need every daemon field.

type Recipient

type Recipient struct {
	// Address is the Taproot Asset address of the recipient.
	Address string
	// contains filtered or unexported fields
}

Recipient represents a recipient of an asset transfer.

func RecipientWithAmount

func RecipientWithAmount(address string, amount uint64) Recipient

RecipientWithAmount creates a recipient with an explicit sender-chosen amount.

func RecipientWithEmbeddedAmount

func RecipientWithEmbeddedAmount(address string) Recipient

RecipientWithEmbeddedAmount creates a recipient that uses the amount encoded in the Taproot Asset address.

func (Recipient) Amount

func (r Recipient) Amount() (uint64, bool)

Amount returns the explicit amount and whether one was supplied. If the boolean is false, the recipient uses the amount embedded in the address.

type RegisteredAsset

type RegisteredAsset struct {
	// AssetRef is the SDK's user-facing identifier for the asset.
	AssetRef AssetRef

	// IssuanceID is the 32-byte protocol-level identifier for the specific
	// issuance/tranche that was registered.
	IssuanceID AssetID

	// ScriptKey is the 33-byte script key for this asset.
	ScriptKey PubKey

	// Amount is the number of asset units.
	Amount uint64

	// Outpoint is the output location where this asset resides.
	Outpoint Outpoint
}

RegisteredAsset represents an asset that has been registered after importing a proof. This is returned when a receiver successfully imports a proof from an interactive transfer.

type ScriptKey

type ScriptKey struct {
	// PubKey is the full Taproot output key the asset is locked to.
	// This is either a BIP-86 key if TapTweak is empty, or a key with
	// the tap tweak applied.
	PubKey PubKey

	// KeyDesc describes the internal key used to derive PubKey.
	KeyDesc KeyDescriptor

	// TapTweak is the optional Taproot tweak applied to the internal key.
	// If empty, a BIP-86 style tweak is applied.
	TapTweak []byte
}

ScriptKey represents a Taproot Asset script key for receiving assets. A script key is composed of an internal key that is optionally tweaked with a tap tweak to produce the final public key.

type ScriptKeyType

type ScriptKeyType uint8

ScriptKeyType represents the role of an asset script key.

const (
	// ScriptKeyTypeUnknown is used when the script key type is not known.
	ScriptKeyTypeUnknown ScriptKeyType = 0

	// ScriptKeyTypeBIP86 is the standard BIP-86 script key type.
	ScriptKeyTypeBIP86 ScriptKeyType = 1

	// ScriptKeyTypeScriptPathExternal represents a user-defined script path.
	ScriptKeyTypeScriptPathExternal ScriptKeyType = 2

	// ScriptKeyTypeBurn represents an unspendable burn key.
	ScriptKeyTypeBurn ScriptKeyType = 3

	// ScriptKeyTypeTombstone represents an unspendable tombstone output.
	ScriptKeyTypeTombstone ScriptKeyType = 4

	// ScriptKeyTypeChannel represents a Taproot Asset channel-related key.
	ScriptKeyTypeChannel ScriptKeyType = 5

	// ScriptKeyTypeUniquePedersen represents a unique Pedersen-based key.
	ScriptKeyTypeUniquePedersen ScriptKeyType = 6
)

func (ScriptKeyType) Valid

func (t ScriptKeyType) Valid() bool

Valid returns true if the script-key type is known by this SDK version.

type ScriptKeyTypeQuery

type ScriptKeyTypeQuery struct {
	// ExplicitType restricts results to a single script key type.
	ExplicitType *ScriptKeyType

	// AllTypes returns assets of all script key types.
	AllTypes bool
}

ScriptKeyTypeQuery specifies how to filter by script key type.

func (*ScriptKeyTypeQuery) Validate

func (q *ScriptKeyTypeQuery) Validate() error

Validate returns an error if the script-key type query cannot be mapped to tapd's filter shape.

type SealBatchRequest

type SealBatchRequest struct {
	// ShortResponse asks the daemon to omit batch asset details.
	ShortResponse bool

	// GroupWitnesses authorizes assets into externally signed groups.
	GroupWitnesses []GroupWitness

	// SignedGroupVirtualPSBTs are externally signed group virtual PSBTs.
	SignedGroupVirtualPSBTs []string
}

SealBatchRequest seals the current funded mint batch.

type SendAssetRequest

type SendAssetRequest struct {
	// Recipients is the list of send destinations.
	Recipients []Recipient

	// FeeRate is the optional target fee rate for the anchor transaction.
	// Zero uses the daemon default.
	FeeRate FeeRate

	// Label is an optional short label for tracking the send.
	Label string

	// SkipProofCourierPingCheck skips the proof courier connectivity
	// check.
	SkipProofCourierPingCheck bool
}

SendAssetRequest specifies a low-level one-shot address-based send.

Recipients carries every destination. Each recipient either has an explicit amount or uses the address's embedded amount. tapd exposes two mutually exclusive wire paths for these, so callers must not mix explicit and embedded amounts in a single call; Client.SendAsset returns ErrMixedRecipientAmounts if they do. The higher-level Wallet.SendMulti normalises mixed inputs before reaching this layer.

type SendEvent

type SendEvent struct {
	// Timestamp is the event execution time as a Unix timestamp in
	// microseconds.
	Timestamp int64

	// SendState is the last send state that was executed successfully.
	SendState SendState

	// NextSendState is the next state that will be executed.
	NextSendState SendState

	// TransferLabel is the label assigned to this transfer.
	TransferLabel string

	// AssetRefs are the logical asset refs involved in the send event.
	AssetRefs []AssetRef

	// Transfer is the final transfer when the event contains one.
	Transfer *Transfer

	// Error is an optional error string.
	Error string
}

SendEvent is the high-level, AssetRef-keyed view of an outgoing send event emitted by EventListener. Use this for application code that thinks in terms of user-facing assets; for raw protocol fields (PSBTs, virtual packets, ...) consume Client.SubscribeSendEvents directly to receive SendEventRecord.

func NewSendEvent

func NewSendEvent(record *SendEventRecord) *SendEvent

NewSendEvent projects a raw SendEventRecord into the high-level SendEvent.

AssetRefs is built from the final transfer's inputs and outputs when the transfer is available. Before tapd logs the transfer, recipient addresses provide the best available refs. The final Transfer, when set on the record, is rebuilt with AssetRef-keyed inputs and outputs.

Returns nil when record is nil.

type SendEventRecord

type SendEventRecord struct {
	// Timestamp is the event execution time as a Unix timestamp in
	// microseconds.
	Timestamp int64

	// SendState is the last send state that was executed
	// successfully. If Error is set, this is the state that caused
	// the failure.
	SendState SendState

	// ParcelType is the type of the outbound parcel.
	ParcelType ParcelType

	// Addresses lists the recipient addresses (not including change
	// back to own wallet). Only set for ParcelTypeAddress.
	Addresses []*Address

	// VirtualPackets are the raw virtual packets in the parcel.
	VirtualPackets [][]byte

	// PassiveVirtualPackets are passive virtual packets carried
	// alongside the active ones when other assets shared the input
	// commitment.
	PassiveVirtualPackets [][]byte

	// AnchorTransaction contains on-chain anchor details. Only set
	// after the anchor signing state.
	AnchorTransaction *AnchorTransaction

	// Transfer is the final transfer record. Only set after the
	// commitment is logged.
	Transfer *AssetTransfer

	// Error is an optional error string.
	Error string

	// TransferLabel is the label assigned to this transfer.
	TransferLabel string

	// NextSendState is the next state that will be executed.
	NextSendState SendState
}

SendEventRecord is the raw, protocol-shaped outgoing asset transfer event returned by Client.SubscribeSendEvents. Most application code should consume the high-level SendEvent emitted by EventListener instead; SendEventRecord is the escape hatch for advanced callers that need PSBTs, virtual packets, or other raw fields.

type SendOption

type SendOption func(*SendOptions)

SendOption is a functional option for configuring Send and SendMulti.

func WithAmount

func WithAmount(amount uint64) SendOption

WithAmount sets the explicit send amount for a V2 address that does not embed one. It is only meaningful for Wallet.Send: V0/V1 addresses and V2 addresses with an embedded amount reject any value that does not match the embedded amount.

func WithFeeRate

func WithFeeRate(feeRate FeeRate) SendOption

WithFeeRate sets the target fee rate for the anchor transaction.

func WithLabel

func WithLabel(label string) SendOption

WithLabel attaches a short label for tracking the send.

func WithSkipProofCourierPingCheck

func WithSkipProofCourierPingCheck() SendOption

WithSkipProofCourierPingCheck skips the proof courier connectivity check.

type SendOptions

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

SendOptions configures optional parameters for high-level send operations.

type SendState

type SendState string

SendState is the current state of an outbound send event. tapd exposes these as stable string names over the API, so the SDK keeps a string-backed type here as well.

const (
	// SendStateStartHandleAddrParcel is the initial send state.
	SendStateStartHandleAddrParcel SendState = "SendStateStartHandleAddrParcel" //nolint:lll

	// SendStateVirtualCommitmentSelect performs input coin selection.
	SendStateVirtualCommitmentSelect SendState = "SendStateVirtualCommitmentSelect" //nolint:lll

	// SendStateVirtualSign creates the asset-level witness data.
	SendStateVirtualSign SendState = "SendStateVirtualSign"

	// SendStateAnchorSign signs and finalizes the anchor PSBT.
	SendStateAnchorSign SendState = "SendStateAnchorSign"

	// SendStateVerifyPreBroadcast runs final pre-broadcast checks.
	SendStateVerifyPreBroadcast SendState = "SendStateVerifyPreBroadcast"

	// SendStateStorePreBroadcast persists the signed transaction
	// before broadcast.
	SendStateStorePreBroadcast SendState = "SendStateStorePreBroadcast"

	// SendStateBroadcast broadcasts the anchor transaction.
	SendStateBroadcast SendState = "SendStateBroadcast"

	// SendStateWaitTxConf waits for the anchor transaction to confirm.
	SendStateWaitTxConf SendState = "SendStateWaitTxConf"

	// SendStateStorePostAnchorTxConf stores post-confirmation state.
	SendStateStorePostAnchorTxConf SendState = "SendStateStorePostAnchorTxConf" //nolint:lll

	// SendStateTransferProofs transfers proofs to the receivers.
	SendStateTransferProofs SendState = "SendStateTransferProofs"

	// SendStateComplete means the transfer has completed fully.
	SendStateComplete SendState = "SendStateComplete"
)

type SignedIssuance

type SignedIssuance struct {
	// VirtualPSBT is the signed base64 PSBT returned by the external signer.
	VirtualPSBT string
}

SignedIssuance is the external signature result for one issuance signing request.

type SortDirection

type SortDirection uint8

SortDirection specifies the sort order for queries. Values match taprpc.SortDirection enum.

const (
	// SortDescending sorts results in descending order.
	SortDescending SortDirection = 0

	// SortAscending sorts results in ascending order.
	SortAscending SortDirection = 1
)

type SubscribeMintEventsRequest

type SubscribeMintEventsRequest struct {
	// ShortResponse omits the full asset list from batch events
	// to reduce data volume for large batches.
	ShortResponse bool
}

SubscribeMintEventsRequest contains parameters for subscribing to mint batch events.

type SubscribeReceiveEventsRequest

type SubscribeReceiveEventsRequest struct {
	// FilterAddr restricts events to a specific Taproot Asset
	// address. Leave empty to receive all events.
	FilterAddr string

	// StartTimestamp is the start time as a Unix timestamp in
	// microseconds. If zero, the daemon streams from the current
	// time.
	StartTimestamp int64
}

SubscribeReceiveEventsRequest contains parameters for subscribing to incoming transfer events.

type SubscribeSendEventsRequest

type SubscribeSendEventsRequest struct {
	// FilterScriptKey restricts events to a specific recipient
	// script key. Leave empty to receive all send events.
	FilterScriptKey []byte

	// FilterLabel restricts events to a specific transfer label.
	// Leave empty to not filter by label.
	FilterLabel string

	// StartTimestamp is the start time as a Unix timestamp in
	// microseconds. If zero, the daemon streams from the current
	// time.
	StartTimestamp int64
}

SubscribeSendEventsRequest contains parameters for subscribing to outgoing transfer events.

type SyncRequest

type SyncRequest struct {
	// UniverseHost is the remote server to sync with.
	UniverseHost string

	// SyncMode controls the sync scope.
	SyncMode UniverseSyncMode

	// SyncTargets limits the sync to specific assets. An empty list
	// means sync everything.
	SyncTargets []SyncTarget
}

SyncRequest configures a universe sync operation.

type SyncTarget

type SyncTarget struct {
	// ID is the universe ID to sync.
	ID UniverseID
}

SyncTarget identifies an asset to sync.

type SyncedUniverse

type SyncedUniverse struct {
	// OldAssetRoot is the root before the sync.
	OldAssetRoot *UniverseRoot

	// NewAssetRoot is the root after the sync.
	NewAssetRoot *UniverseRoot

	// NewAssetLeaves are the newly synced leaves.
	NewAssetLeaves []AssetLeaf
}

SyncedUniverse is the result of syncing a single universe.

type TapBranch

type TapBranch struct {
	// LeftTapHash is the tap hash of the left child.
	LeftTapHash Hash

	// RightTapHash is the tap hash of the right child.
	RightTapHash Hash
}

TapBranch describes a tapscript tree by its root children.

type TapLeaf

type TapLeaf struct {
	// Script is the tapscript leaf program.
	Script []byte
}

TapLeaf represents a single leaf in a tapscript tree.

type TapscriptFullTree

type TapscriptFullTree struct {
	// Leaves is the ordered list of tapscript leaves.
	Leaves []TapLeaf
}

TapscriptFullTree describes a full ordered tapscript tree.

type Transfer

type Transfer struct {
	// TransferTimestamp is the timestamp of the transfer in UTC Unix time
	// seconds.
	TransferTimestamp int64

	// AnchorTxid is the display-order transaction ID of the anchor
	// transaction.
	AnchorTxid string

	// AnchorTxBlockHeight is the block height containing the anchor
	// transaction, or zero if the transfer is unconfirmed.
	AnchorTxBlockHeight uint32

	// AnchorTxChainFees is the total fee paid by the anchor transaction in
	// satoshis.
	AnchorTxChainFees int64

	// Label is the optional transfer label.
	Label string

	// Inputs are the assets spent by this transfer.
	Inputs []TransferAsset

	// Outputs are the assets created by this transfer.
	Outputs []TransferAsset
}

Transfer is a high-level wallet transfer keyed by AssetRef.

func NewTransfer

func NewTransfer(raw *AssetTransfer) *Transfer

NewTransfer projects a raw AssetTransfer into the high-level, AssetRef-keyed Transfer. The AssetRef on each input and output is built from AssetType, GroupKey, and IssuanceID: fungibles prefer group-key refs, while collectibles use their concrete asset-ID refs.

Returns nil when raw is nil.

type TransferAsset

type TransferAsset struct {
	// AssetRef is the SDK identifier for the logical asset.
	AssetRef AssetRef

	// IssuanceID is the concrete protocol issuance/tranche ID.
	IssuanceID AssetID

	// Type is the transferred asset type.
	Type AssetType

	// Amount is the number of asset units.
	Amount uint64

	// ScriptKey is the script key for this transfer item.
	ScriptKey PubKey

	// Outpoint is the anchor outpoint for this transfer item.
	Outpoint Outpoint
}

TransferAsset describes one asset amount in a high-level transfer.

type TransferInput

type TransferInput struct {
	// AnchorPoint is the old/current location of the Taproot Asset commitment
	// that was spent as an input.
	AnchorPoint Outpoint

	// IssuanceID is the 32-byte protocol-level identifier of the asset
	// issuance/tranche that was spent.
	IssuanceID AssetID

	// AssetType is the type of the transferred asset.
	AssetType AssetType

	// ScriptKey is the 33-byte script key of the asset that was spent.
	ScriptKey PubKey

	// Amount is the number of asset units spent.
	Amount uint64

	// GroupKey is the asset's group public key when the asset belongs to
	// a group, or nil otherwise. For collectibles, the high-level AssetRef
	// remains the IssuanceID even when GroupKey is set.
	GroupKey *PubKey
}

TransferInput represents a single input in a transfer.

type TransferOutput

type TransferOutput struct {
	// AnchorOutpoint is the on-chain outpoint.
	AnchorOutpoint Outpoint

	// IssuanceID is the 32-byte protocol-level identifier of the
	// asset issuance/tranche created at this output.
	IssuanceID AssetID

	// AssetType is the type of the transferred asset.
	AssetType AssetType

	// AnchorValue is the BTC value of the anchor output in sats.
	AnchorValue int64

	// ScriptKey is the 33-byte compressed public key locking this output.
	ScriptKey PubKey

	// Amount is the number of asset units in this output.
	Amount uint64

	// ProofBlob is the proof suffix returned by tapd for this output.
	// A receiver needs a complete proof file, which can be exported after
	// the anchor transaction confirms by using IssuanceID, ScriptKey, and
	// AnchorOutpoint.
	ProofBlob []byte

	// AltLeaves are auxiliary Taproot leaves (if present) decoded from proofs.
	AltLeaves [][]byte

	// GroupKey is the asset's group public key when the asset belongs to
	// a group, or nil otherwise. For collectibles, the high-level AssetRef
	// remains the IssuanceID even when GroupKey is set.
	GroupKey *PubKey
}

TransferOutput represents a single output in a transfer.

type TxBuilder

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

TxBuilder builds address-based Taproot Asset transfers.

Address-based transfers use Taproot Asset addresses, which include proof courier information for automatic proof delivery.

For interactive transfers where the receiver provides keys directly, use InteractiveTxBuilder instead.

func (*TxBuilder) AddInput

func (b *TxBuilder) AddInput(input PrevID) *TxBuilder

AddInput adds a specific input to the transaction.

func (*TxBuilder) AddRecipient

func (b *TxBuilder) AddRecipient(address string, amount uint64) *TxBuilder

AddRecipient adds a recipient with an explicit send amount.

func (*TxBuilder) AddTapAddress

func (b *TxBuilder) AddTapAddress(address string) *TxBuilder

AddTapAddress adds a recipient that uses the amount embedded in the address.

func (*TxBuilder) Commit

func (b *TxBuilder) Commit(ctx context.Context) (
	*CommittedTransfer, error)

Commit commits the signed transaction and returns the committed transfer.

func (*TxBuilder) Execute

func (b *TxBuilder) Execute(ctx context.Context, opts ...TxBuilderOption) (
	*AssetPacket, error)

Execute funds, signs, commits, and publishes the transaction.

func (*TxBuilder) Finish

func (b *TxBuilder) Finish(ctx context.Context, opts ...TxBuilderOption) (
	*AssetPacket, error)

Finish publishes the transaction and returns the finalized packet.

func (*TxBuilder) Fund

func (b *TxBuilder) Fund(ctx context.Context) (*FundedTransfer,
	error)

Fund funds the transaction and returns the funded transfer details.

func (*TxBuilder) SetAnchorPsbt

func (b *TxBuilder) SetAnchorPsbt(anchorPsbt []byte) *TxBuilder

SetAnchorPsbt injects an externally finalized anchor PSBT into the builder.

func (*TxBuilder) SetAnchorSigner

func (b *TxBuilder) SetAnchorSigner(signer AnchorSigner) *TxBuilder

SetAnchorSigner sets the callback used to finalize the BTC anchor PSBT between Commit and Finish.

func (*TxBuilder) SetFeeRate

func (b *TxBuilder) SetFeeRate(feeRate FeeRate) *TxBuilder

SetFeeRate sets the fee rate. Default is 1 sat/vB.

func (*TxBuilder) SetFundedPsbt

func (b *TxBuilder) SetFundedPsbt(fundedPsbt []byte) *TxBuilder

SetFundedPsbt injects an externally funded PSBT into the builder.

func (*TxBuilder) SetPassivePsbts

func (b *TxBuilder) SetPassivePsbts(passivePsbts [][]byte) *TxBuilder

SetPassivePsbts injects externally produced passive asset PSBTs.

func (*TxBuilder) SetRecipients

func (b *TxBuilder) SetRecipients(recipients []Recipient) *TxBuilder

SetRecipients sets the recipients for the transaction.

func (*TxBuilder) SetSignedPsbt

func (b *TxBuilder) SetSignedPsbt(signedPsbt []byte) *TxBuilder

SetSignedPsbt injects an externally signed PSBT into the builder.

func (*TxBuilder) Sign

func (b *TxBuilder) Sign(ctx context.Context) ([]byte, error)

Sign signs the funded transaction and returns the signed PSBT.

type TxBuilderOption

type TxBuilderOption func(*txBuilderOptions)

TxBuilderOption configures TxBuilder finish/execute behavior.

func WithSkipBroadcast

func WithSkipBroadcast() TxBuilderOption

WithSkipBroadcast leaves the finalized anchor transaction unbroadcast.

type TxOut

type TxOut struct {
	// Value is the amount of the output.
	Value int64

	// PkScript is the output script.
	PkScript []byte
}

TxOut represents a transaction output used in a group virtual tx.

type UnconfirmedAnchorVerification added in v0.2.0

type UnconfirmedAnchorVerification struct {
	// StepIndex is the zero-based transition position in the compact path.
	StepIndex uint16

	// PreviousAnchorOutpoint is the asset-bearing output consumed by the
	// transition.
	PreviousAnchorOutpoint Outpoint

	// AnchorOutpoint is the new asset-bearing output created by the
	// transition.
	AnchorOutpoint Outpoint

	// AnchorTransaction is the complete serialized Bitcoin transaction,
	// including witness data when present.
	AnchorTransaction []byte

	// PreviousAnchorOutpoints lists every asset-bearing outpoint the
	// transition consumes: the spine tip first, then each co-input path
	// tip in declared order. It equals [PreviousAnchorOutpoint] for
	// single-input steps.
	PreviousAnchorOutpoints []Outpoint
}

UnconfirmedAnchorVerification contains the SDK-derived Bitcoin transition context that a host must verify against its complete signed transaction graph. Native Taproot Asset proof verification cannot prove the values or authorization of unrelated Bitcoin inputs, transaction standardness, or package-relay policy.

type UnconfirmedAnchorVerifier added in v0.2.0

type UnconfirmedAnchorVerifier interface {
	VerifyUnconfirmedAnchor(ctx context.Context,
		transition UnconfirmedAnchorVerification) error
}

UnconfirmedAnchorVerifier is an optional extension that becomes mandatory whenever an AssetProofPath contains unconfirmed steps. Swap or Ark hosts should use their authoritative graph, prevouts, and signing policy to verify every transition before attesting it here.

type Universe

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

Universe is the high-level AssetRef-first universe surface.

It exposes common asset discovery, proof lookup, and sync operations without requiring application code to build protocol-shaped UniverseID values. UniverseClient remains available for callers that need direct access to the tapd universe RPC model.

func NewUniverse

func NewUniverse(client UniverseClient) *Universe

NewUniverse creates a high-level universe facade backed by the given client.

func (*Universe) GetProof

func (u *Universe) GetProof(ctx context.Context, ref AssetRef,
	leafKey AssetLeafKey,
	opts ...UniverseProofOption) (*UniverseProof, error)

GetProof returns one universe proof by AssetRef and leaf key. By default it tries all locally known proof types. Use WithUniverseProofType when the proof type is already known.

func (*Universe) GetRoots

func (u *Universe) GetRoots(ctx context.Context,
	ref AssetRef) (*UniverseRoots, error)

GetRoots returns the locally known universe roots for the AssetRef.

func (*Universe) HasAsset

func (u *Universe) HasAsset(ctx context.Context,
	ref AssetRef) (bool, error)

HasAsset reports whether the local universe knows issuance or transfer roots for the AssetRef. It returns false with a nil error only when tapd successfully reports no roots; RPC and authentication failures are returned as errors.

func (*Universe) ListProofs

func (u *Universe) ListProofs(ctx context.Context,
	ref AssetRef,
	opts ...UniverseProofOption) ([]*UniverseProof, error)

ListProofs returns locally known universe proofs for the AssetRef. By default it returns all locally known proof types. Use WithUniverseProofType to request only issuance or transfer proofs. The method returns one tapd page per queried proof type, not a full auto-paginated scan.

func (*Universe) SyncAsset

func (u *Universe) SyncAsset(ctx context.Context, ref AssetRef,
	host string, opts ...UniverseSyncOption) (*UniverseSyncResult,
	error)

SyncAsset syncs universe roots and leaves for one AssetRef from a trusted remote universe server. The host is forwarded to tapd, which currently dials remote universe servers without certificate verification, so it must come from trusted configuration and not direct user input.

func (*Universe) SyncAssets

func (u *Universe) SyncAssets(ctx context.Context, refs []AssetRef,
	host string, opts ...UniverseSyncOption) ([]*UniverseSyncResult,
	error)

SyncAssets syncs universe roots and leaves for multiple AssetRefs from a trusted remote universe server. The host is forwarded to tapd, which currently dials remote universe servers without certificate verification, so it must come from trusted configuration and not direct user input.

type UniverseClient

type UniverseClient interface {
	// InsertProof inserts a proof into the local universe.
	InsertProof(ctx context.Context, rawProof []byte,
		decoded *DecodedProof) error

	// AssetRoots returns the known universe roots for all assets.
	AssetRoots(ctx context.Context,
		req *AssetRootRequest) (map[string]*UniverseRoot,
		error)

	// QueryAssetRoots queries the issuance and transfer roots for a
	// specific asset identified by its UniverseID.
	QueryAssetRoots(ctx context.Context,
		id *UniverseID) (*QueryRootResponse, error)

	// DeleteAssetRoot deletes a universe root and all associated data
	// for a given asset.
	DeleteAssetRoot(ctx context.Context,
		id *UniverseID) error

	// AssetLeafKeys returns the set of leaf keys for a universe.
	AssetLeafKeys(ctx context.Context,
		req *AssetLeafKeysRequest) ([]AssetLeafKey,
		error)

	// AssetLeaves returns the set of asset leaves for a universe.
	AssetLeaves(ctx context.Context,
		id *UniverseID) ([]AssetLeaf, error)

	// QueryProof queries a specific proof from the universe by its
	// full key (universe ID + leaf key).
	QueryProof(ctx context.Context,
		key *UniverseKey) (*AssetProofResponse,
		error)

	// UniverseStats returns aggregate statistics for the universe.
	UniverseStats(ctx context.Context) (*UniverseStats, error)

	// QueryAssetStats returns per-asset statistics filtered and sorted
	// by the given query parameters.
	QueryAssetStats(ctx context.Context,
		req *AssetStatsQuery) ([]AssetStatsSnapshot,
		error)

	// QueryEvents returns daily sync and proof event counts within a
	// time range.
	QueryEvents(ctx context.Context,
		req *QueryEventsRequest) ([]GroupedUniverseEvents,
		error)

	// ListFederationServers lists the universe federation peers.
	ListFederationServers(
		ctx context.Context) ([]FederationServer, error)

	// AddFederationServer adds servers to the federation.
	AddFederationServer(ctx context.Context,
		servers []FederationServer) error

	// DeleteFederationServer removes servers from the federation.
	DeleteFederationServer(ctx context.Context,
		servers []FederationServer) error

	// SetFederationSyncConfig sets the federation sync configuration.
	SetFederationSyncConfig(ctx context.Context,
		global []GlobalFederationSyncConfig,
		asset []AssetFederationSyncConfig) error

	// QueryFederationSyncConfig queries the federation sync
	// configuration.
	QueryFederationSyncConfig(ctx context.Context,
		ids []UniverseID) (*FederationSyncConfig,
		error)

	// Info returns basic universe server information.
	Info(ctx context.Context) (*UniverseInfo, error)

	// SyncUniverse synchronizes with a remote universe server.
	SyncUniverse(ctx context.Context,
		req *SyncRequest) ([]SyncedUniverse, error)
}

UniverseClient exposes the Universe service gRPC client.

type UniverseID

type UniverseID struct {
	// AssetRef identifies the asset universe to query.
	AssetRef AssetRef

	// ProofType filters the universe by proof type.
	ProofType ProofType
}

UniverseID identifies a universe by AssetRef plus a proof type.

func UniverseIDFromRef

func UniverseIDFromRef(
	ref AssetRef, proofType ProofType) UniverseID

UniverseIDFromRef constructs a UniverseID from an AssetRef and proof type. Fungible refs (group key) produce a group-key universe ID; collectible refs (asset ID) produce an asset-ID universe ID.

type UniverseInfo

type UniverseInfo struct {
	// RuntimeID is a per-restart pseudo-random identifier.
	RuntimeID int64
}

UniverseInfo contains basic server info.

type UniverseKey

type UniverseKey struct {
	// ID identifies the universe.
	ID UniverseID

	// LeafKey identifies the specific leaf.
	LeafKey AssetLeafKey
}

UniverseKey is the full key path into a universe: ID + leaf key.

type UniverseProof

type UniverseProof struct {
	// AssetRef identifies the asset universe that contains this proof.
	AssetRef AssetRef

	// ProofType identifies whether this is an issuance or transfer proof.
	ProofType ProofType

	// LeafKey identifies the concrete proof leaf in the universe tree.
	LeafKey AssetLeafKey

	// Proof is the raw issuance or transfer proof bytes.
	Proof []byte

	// Asset is the decoded low-level asset record, if tapd returned one.
	Asset *AssetRecord

	// UniverseRoot is the root that includes this proof.
	UniverseRoot *UniverseRoot

	// UniverseInclusionProof is the raw MS-SMT inclusion proof.
	UniverseInclusionProof []byte

	// MultiverseRoot is the root of the wider multiverse tree.
	MultiverseRoot *MerkleSumNode

	// MultiverseInclusionProof is the multiverse inclusion proof.
	MultiverseInclusionProof []byte
}

UniverseProof is a high-level universe proof entry for one AssetRef.

type UniverseProofOption

type UniverseProofOption func(*universeProofOptions)

UniverseProofOption configures high-level proof queries.

func WithUniverseProofDirection

func WithUniverseProofDirection(
	direction SortDirection) UniverseProofOption

WithUniverseProofDirection sets the leaf-key sort direction for ListProofs. The default is descending.

func WithUniverseProofPage

func WithUniverseProofPage(offset, limit int32) UniverseProofOption

WithUniverseProofPage sets the offset and limit for ListProofs. Pagination requires WithUniverseProofType so one page maps to one proof stream.

func WithUniverseProofType

func WithUniverseProofType(proofType ProofType) UniverseProofOption

WithUniverseProofType limits a proof query to issuance or transfer proofs. The default queries all locally known proof types for the AssetRef.

type UniverseRoot

type UniverseRoot struct {
	// ID is the universe identifier.
	ID UniverseID

	// MSSMTRoot is the Merkle-Sum SMT root.
	MSSMTRoot *MerkleSumNode

	// AssetName is the human-readable name of the asset.
	AssetName string

	// AmountsByIssuanceID maps hex-encoded issuance IDs to the number of units
	// minted. For multi-issuance assets this may contain more than one entry.
	AmountsByIssuanceID map[string]uint64
}

UniverseRoot is the root of a single asset universe.

type UniverseRoots

type UniverseRoots struct {
	// AssetRef identifies the asset universe.
	AssetRef AssetRef

	// IssuanceRoot is the issuance proof root, if known locally.
	IssuanceRoot *UniverseRoot

	// TransferRoot is the transfer proof root, if known locally.
	TransferRoot *UniverseRoot
}

UniverseRoots groups the issuance and transfer roots for one AssetRef.

func (*UniverseRoots) HasRoots

func (r *UniverseRoots) HasRoots() bool

HasRoots reports whether at least one universe root is present.

type UniverseStats

type UniverseStats struct {
	// NumTotalAssets is the total number of known assets.
	NumTotalAssets int64

	// NumTotalGroups is the total number of known groups.
	NumTotalGroups int64

	// NumTotalSyncs is the total number of universe syncs.
	NumTotalSyncs int64

	// NumTotalProofs is the total number of stored proofs.
	NumTotalProofs int64
}

UniverseStats contains aggregate universe statistics.

type UniverseSyncMode

type UniverseSyncMode int

UniverseSyncMode selects the sync scope.

const (
	// SyncIssuanceOnly syncs only issuance proofs.
	SyncIssuanceOnly UniverseSyncMode = 0

	// SyncFull syncs all proofs including transfers.
	SyncFull UniverseSyncMode = 1
)

type UniverseSyncOption

type UniverseSyncOption func(*universeSyncOptions)

UniverseSyncOption configures high-level universe sync calls.

func WithUniverseSyncMode

func WithUniverseSyncMode(mode UniverseSyncMode) UniverseSyncOption

WithUniverseSyncMode sets the tapd sync scope. The default is SyncFull.

type UniverseSyncResult

type UniverseSyncResult struct {
	// AssetRef identifies the synced asset universe.
	AssetRef AssetRef

	// Issuance is the issuance-universe diff, if one changed.
	Issuance *SyncedUniverse

	// Transfer is the transfer-universe diff, if one changed.
	Transfer *SyncedUniverse
}

UniverseSyncResult is the high-level sync result for one AssetRef.

type UnsealedMintAsset

type UnsealedMintAsset struct {
	// Asset is the pending asset.
	Asset *PendingMintAsset

	// GroupKeyRequest is the request used to derive the group witness.
	GroupKeyRequest *GroupKeyRequest

	// GroupVirtualTx is the virtual transaction for witness creation.
	GroupVirtualTx *GroupVirtualTx

	// GroupVirtualPSBT is the serialized PSBT form of GroupVirtualTx.
	GroupVirtualPSBT string
}

UnsealedMintAsset contains the extra verbose details for a batch asset.

type UnsupportedCustomAnchorCapabilityError added in v0.2.0

type UnsupportedCustomAnchorCapabilityError struct {
	BackendMode CustomAnchorBackendMode
	Capability  CustomAnchorCapability
	Status      CustomAnchorCapabilityStatus
}

UnsupportedCustomAnchorCapabilityError identifies a missing capability and the backend mode that reported it.

func (*UnsupportedCustomAnchorCapabilityError) Error added in v0.2.0

Error returns a human-readable unsupported capability message.

func (*UnsupportedCustomAnchorCapabilityError) Unwrap added in v0.2.0

Unwrap returns the sentinel error for errors.Is checks.

type VerboseMintingBatch

type VerboseMintingBatch struct {
	// Batch is the batch itself.
	Batch MintingBatch

	// UnsealedAssets contains pending group witness details when requested.
	UnsealedAssets []UnsealedMintAsset
}

VerboseMintingBatch is the daemon's verbose view of a minting batch.

type VerifyOwnershipRequest

type VerifyOwnershipRequest struct {
	// ProofWithWitness is the full ownership proof to verify.
	ProofWithWitness []byte

	// Challenge is the optional non-zero 32-byte challenge that the prover
	// was expected to include.
	Challenge []byte
}

VerifyOwnershipRequest specifies parameters for verifying an ownership proof.

type VerifyOwnershipResponse

type VerifyOwnershipResponse struct {
	// Valid indicates whether the ownership proof is valid.
	Valid bool

	// Outpoint is the asset anchor outpoint verified by tapd.
	Outpoint Outpoint

	// BlockHash is the hash of the block containing the anchor output.
	BlockHash Hash

	// BlockHeight is the block height of the anchor output.
	BlockHeight uint32
}

VerifyOwnershipResponse is the result of verifying an ownership proof.

type VerifyProofResponse

type VerifyProofResponse struct {
	// Valid indicates whether the proof file was valid.
	Valid bool

	// DecodedProof is the decoded last proof in the file if the proof
	// file was valid.
	DecodedProof *DecodedProof
}

VerifyProofResponse contains the result of a proof verification.

type Wallet

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

Wallet constitutes the high level service giving access to Taproot Assets features.

func NewWallet

func NewWallet(client Client, network Network,
	opts ...WalletOption) *Wallet

NewWallet creates a new Wallet instance.

func (*Wallet) Burn

func (s *Wallet) Burn(ctx context.Context, ref AssetRef,
	amount uint64, opts ...BurnOption) (*Burn, error)

Burn destroys units of the asset identified by AssetRef.

The SDK supplies tapd's confirmation text internally so normal callers do not need to carry the daemon's safety phrase through application code.

func (*Wallet) Client

func (s *Wallet) Client() Client

Client returns the low-level composite client wrapped by the wallet.

Most application code should prefer the Wallet methods. Use this accessor for advanced RPC-shaped operations that intentionally are not promoted onto the high-level wallet surface.

func (*Wallet) Close

func (s *Wallet) Close() error

Close releases resources held by the underlying client.

func (*Wallet) CustomAnchorCapabilities added in v0.2.0

func (s *Wallet) CustomAnchorCapabilities(
	ctx context.Context) (*CustomAnchorCapabilities, error)

CustomAnchorCapabilities reports the optional capability profile exposed by the configured client. tapd does not currently expose a capability RPC, so a client that doesn't implement CustomAnchorCapabilityProvider returns an all-unknown profile. Unknown capabilities fail closed when Require is used.

func (*Wallet) DeriveKeys

func (s *Wallet) DeriveKeys(ctx context.Context) (*DerivedKeys,
	error)

DeriveKeys derives a new script key and internal key for receiving assets. The receiver calls this method and shares the result with the sender for interactive transfers.

This is a convenience method that combines DeriveScriptKey and DeriveInternalKey into a single call.

func (*Wallet) ExportProof

func (s *Wallet) ExportProof(ctx context.Context,
	ref AssetRef) (*ProofBundle, error)

ExportProof exports all wallet-known proof files for the given user-facing AssetRef.

For a grouped fungible asset this enumerates each wallet-known issuance/tranche and exports one proof entry per asset output. For a single NFT/collectible or ungrouped asset-ID ref this normally returns one entry.

func (*Wallet) ExportProofFile

func (s *Wallet) ExportProofFile(ctx context.Context,
	ref AssetRef, scriptKey PubKey,
	outpoint *Outpoint) (*ProofFile, error)

ExportProofFile exports a raw proof file for a specific asset output.

This is the advanced/legacy escape hatch that maps closely to tapd's proof RPC. Most application code should use ExportProof with an AssetRef instead.

func (*Wallet) GetBalance

func (s *Wallet) GetBalance(ctx context.Context,
	ref AssetRef) (uint64, error)

GetBalance returns the confirmed balance for the given asset. If the wallet holds units across multiple issuances, the total is aggregated into a single sum.

If the wallet has no record of the asset ref, GetBalance returns an error wrapping ErrAssetUnknown; detect it with errors.Is. "Known" means the local universe has an issuance or transfer root for the ref, which tapd populates for assets the wallet minted, received, or bootstrapped via SyncUniverse. A known asset with zero confirmed units returns (0, nil).

The universe probe fires only on the cold path where ListBalances returns an empty map, so the common "have I been paid?" poll still costs a single RPC.

func (*Wallet) ImportProof

func (s *Wallet) ImportProof(ctx context.Context,
	bundle *ProofBundle) ([]*RegisteredAsset, error)

ImportProof imports every proof file in a ProofBundle and registers the resulting wallet transfers. The caller only supplies the bundle; concrete issuance IDs needed by tapd are decoded and registered internally.

func (*Wallet) ImportProofFile

func (s *Wallet) ImportProofFile(ctx context.Context,
	proofFile *ProofFile) (*RegisteredAsset, error)

ImportProofFile imports a raw proof file received from a sender during an interactive transfer. This method handles the full import flow: 1. Unpacks the proof file into individual proofs 2. Inserts each proof into the local universe 3. Registers the transfer so the wallet recognizes the new asset

Returns the registered asset details.

func (*Wallet) ListAssets

func (s *Wallet) ListAssets(ctx context.Context,
	req *ListAssetsRequest) ([]*Asset, error)

ListAssets returns wallet assets keyed by user-facing AssetRef.

Grouped fungible issuances are aggregated under one group-key AssetRef. A single NFT is returned as one asset-ID AssetRef. NFT collection items are returned as NFT assets with their item asset-ID AssetRef and optional CollectionRef; use ListCollections for collection-level rows. Amount filters are applied after this high-level aggregation.

func (*Wallet) ListBalances

func (s *Wallet) ListBalances(ctx context.Context,
	req *ListBalancesRequest) (*ListBalancesResponse, error)

ListBalances returns wallet balances keyed by user-facing AssetRef.

If the request filters by AssetRef and the wallet has no confirmed units, ListBalances checks the local universe to distinguish a known zero balance from an unknown asset ref. Known zero balances are returned as an entry with Balance set to zero. Unknown refs return an error wrapping ErrAssetUnknown.

func (*Wallet) ListBurns

func (s *Wallet) ListBurns(ctx context.Context,
	req *ListBurnsRequest) ([]*BurnRecord, error)

ListBurns returns wallet burn history filtered by AssetRef and/or anchor txid.

This is the high-level companion to Wallet.Burn. It calls the same daemon RPC as Client.ListBurns but wraps errors with operation context so callers can use errors.Is against the SDK sentinels (ErrAssetUnknown, etc.). The returned BurnRecord rows are already keyed by AssetRef, so application code stays on the same logical handle it uses everywhere else.

func (*Wallet) ListCollectionItems

func (s *Wallet) ListCollectionItems(ctx context.Context,
	req *ListCollectionItemsRequest) ([]*Asset, error)

ListCollectionItems returns wallet-known NFT assets that belong to a collection.

Each returned Asset uses the concrete NFT asset-ID AssetRef and has CollectionRef set to the collection AssetRef.

func (*Wallet) ListCollections

func (s *Wallet) ListCollections(ctx context.Context,
	req *ListCollectionsRequest) ([]*Collection, error)

ListCollections returns wallet-known NFT collections.

A collection is a group of NFT assets. It is not returned by ListAssets as an Asset because it is not itself transferable or spendable.

func (*Wallet) ListIssuances

func (s *Wallet) ListIssuances(ctx context.Context,
	req *ListIssuancesRequest) ([]*Issuance, error)

ListIssuances returns wallet-known fungible issuance/tranche records.

This is the issuer/admin/debug companion to ListAssets. It intentionally excludes NFTs and collections.

func (*Wallet) ListTransfers

func (s *Wallet) ListTransfers(ctx context.Context,
	req *ListTransfersRequest) ([]*Transfer, error)

ListTransfers returns high-level wallet transfers keyed by AssetRef.

func (*Wallet) NewCustomAnchorTxBuilder added in v0.2.0

func (s *Wallet) NewCustomAnchorTxBuilder() *CustomAnchorTxBuilder

NewCustomAnchorTxBuilder creates the advanced proof-selected builder.

func (*Wallet) NewInteractiveTxBuilder

func (s *Wallet) NewInteractiveTxBuilder() *InteractiveTxBuilder

NewInteractiveTxBuilder returns a new builder for interactive transfers where the receiver provides their keys directly.

func (*Wallet) NewIssuer

func (s *Wallet) NewIssuer() *Issuer

NewIssuer returns a high-level issuer backed by the wallet's client. Issuers returned by the same Wallet share mint-call serialization.

func (*Wallet) NewReceiveAddress

func (s *Wallet) NewReceiveAddress(ctx context.Context,
	ref AssetRef) (*Address, error)

NewReceiveAddress creates a V2 address for receiving the given asset. The sender chooses the specific units and amount to send. Collectible/NFT addresses always receive exactly one unit; the SDK automatically supplies that amount when tapd rejects the default sender-chosen amount shape.

For more control (custom keys, V0/V1 addresses, explicit amounts), use the lower-level NewAddr method on the client directly. If your tapd does not expose a suitable default proof courier for V2 addresses, configure the wallet with WithAuthMailboxCourier or WithDefaultProofCourierAddr.

func (*Wallet) NewTxBuilder

func (s *Wallet) NewTxBuilder() *TxBuilder

NewTxBuilder returns a new transaction builder for address-based transfers.

func (*Wallet) NewUniverse

func (s *Wallet) NewUniverse() *Universe

NewUniverse returns a high-level universe facade backed by the wallet's client.

func (*Wallet) ProveOwnership

func (s *Wallet) ProveOwnership(ctx context.Context, ref AssetRef,
	opts ...OwnershipOption) (*OwnershipProofSet, error)

ProveOwnership proves wallet ownership of the asset identified by AssetRef.

Fungible refs must include WithOwnershipAmount, and are resolved to the owned issuance outputs needed by tapd's low-level ownership RPC. NFT item refs prove that specific item. A collection ref proves one owned item by default, or all owned items when WithAllOwnedCollectionItems is set.

func (*Wallet) PublishCustomAnchorTransfer added in v0.2.0

func (s *Wallet) PublishCustomAnchorTransfer(ctx context.Context,
	packageSnapshot *CustomAnchorTransferPackage,
	finalAnchorPSBT []byte) (*AssetPacket, error)

PublishCustomAnchorTransfer verifies that the final PSBT has the exact committed unsigned transaction and commitments, then publishes/logs it using the metadata sealed into the package.

func (*Wallet) Send

func (s *Wallet) Send(ctx context.Context, addr string,
	opts ...SendOption) (*AssetTransfer, error)

Send performs a simple one-shot address-based asset transfer.

The addr must be a valid bech32m-encoded Taproot Asset address. The SDK decodes it up-front to decide how to frame the request:

  • If the address embeds an amount (all V0/V1 addresses and V2 addresses that bake one in), omit WithAmount or pass the exact matching value. Any other value returns ErrAmountMismatch.
  • If the address embeds no amount (only possible for V2 addresses), the caller MUST pass WithAmount with a non-zero value. Otherwise Send returns ErrAmountRequired.

For multi-recipient sends in a single anchor transaction, use SendMulti. For fine-grained control over the Fund → Sign → Commit → Publish pipeline, use NewTxBuilder.

func (*Wallet) SendMulti

func (s *Wallet) SendMulti(ctx context.Context,
	recipients []Recipient,
	opts ...SendOption) (*AssetTransfer, error)

SendMulti sends one logical asset to multiple recipients in a single anchor transaction. Every recipient address must resolve to the same AssetRef. Mixed-asset payout batches must be split by the caller.

Use RecipientWithAmount for explicit sender-chosen amounts and RecipientWithEmbeddedAmount for addresses that encode their amount. Mixing the two recipient forms is supported: SendMulti decodes each address and echoes embedded values into the wire request so tapd sees a uniform shape.

For single-recipient sends, prefer Send for simplicity.

func (*Wallet) VerifyOwnership

func (s *Wallet) VerifyOwnership(ctx context.Context, proof []byte,
	opts ...OwnershipOption) (*VerifyOwnershipResponse, error)

VerifyOwnership verifies an ownership proof produced by ProveOwnership or by another Taproot Assets wallet.

type WalletClient

type WalletClient interface {
	GetInfo(ctx context.Context) (*Info, error)

	// ListAssetRecords lists tapd wallet asset records with optional filtering.
	// This is the low-level per-output/per-issuance surface. Use the
	// high-level Wallet.ListAssets, Wallet.ListCollections, and
	// Wallet.ListIssuances methods for SDK business entities. Amount filters
	// in ListAssetsRequest are forwarded to tapd as per-record filters here.
	ListAssetRecords(ctx context.Context,
		req *ListAssetsRequest) ([]*AssetRecord, error)

	// ListBalances lists wallet balances keyed by AssetRef.
	ListBalances(ctx context.Context,
		req *ListBalancesRequest) (*ListBalancesResponse,
		error)

	// ListTransfers lists outgoing transfers with optional filtering.
	ListTransfers(ctx context.Context,
		req *ListTransfersRequest) ([]*AssetTransfer, error)

	// SendAsset performs a low-level one-shot address-based send using the
	// TaprootAssets service. For reusable V2 addresses, specify amounts
	// through SendAssetRequest.Recipients.
	//
	// This method intentionally exposes the raw daemon capability for advanced
	// callers. Higher-level send APIs should remain opinionated about semantic
	// asset identity and default address handling.
	SendAsset(ctx context.Context,
		req *SendAssetRequest) (*AssetTransfer, error)

	// NewAddr creates a new Taproot Asset address for receiving assets.
	// The address is stored in tapd and can be queried later.
	//
	// For V0/V1 addresses, AssetRef must resolve to a concrete issuance asset
	// ID. For V2 addresses, AssetRef may resolve to either an issuance asset ID
	// or a group key.
	//
	// If ScriptKey and InternalKey are not provided, tapd derives them
	// from its internal wallet.
	NewAddr(ctx context.Context,
		req *NewAddressRequest) (*Address, error)

	// DecodeAddr decodes a bech32m Taproot Asset address string into its
	// components. This does not store the address or require it to be
	// previously known.
	DecodeAddr(ctx context.Context, addr string) (*Address, error)

	// QueryAddrs returns addresses that were previously created by this
	// tapd instance, filtered by the query parameters.
	QueryAddrs(ctx context.Context,
		query *AddressQuery) ([]*Address, error)

	// AddrReceives returns incoming transfer events for addresses created
	// by this tapd instance. Use this to track the status of expected
	// incoming transfers.
	AddrReceives(ctx context.Context,
		query *AddressReceivesQuery) ([]*AddressEvent,
		error)

	// ListUtxos lists managed UTXOs with optional filtering.
	ListUtxos(ctx context.Context,
		req *ListUtxosRequest) (
		map[string]*ManagedUtxo, error)

	// ListAssetGroups lists all known protocol-level asset groups. This is a
	// low-level group inspection surface; most wallet callers should use
	// Wallet.ListAssets, Wallet.ListCollections, or Wallet.ListIssuances
	// instead.
	ListAssetGroups(ctx context.Context) ([]AssetGroupRecord, error)

	// BurnAsset burns asset units. The confirmation text must be set
	// to "assets will be destroyed" for the burn to succeed.
	BurnAsset(ctx context.Context,
		req *BurnAssetRequest) (
		*BurnAssetResponse, error)

	// ListBurns lists asset burns with optional filtering.
	ListBurns(ctx context.Context,
		req *ListBurnsRequest) ([]*BurnRecord, error)

	// FetchAssetMeta fetches the metadata for an asset by AssetRef or meta
	// hash.
	FetchAssetMeta(ctx context.Context,
		req *FetchAssetMetaRequest) (
		*AssetMeta, error)

	// VerifyProof verifies a proof file and returns the decoded last
	// proof if valid.
	VerifyProof(ctx context.Context,
		rawProofFile []byte) (
		*VerifyProofResponse, error)
}

WalletClient exposes the TaprootAssets service gRPC client.

type WalletKitClient

type WalletKitClient interface {
	// DeriveScriptKey derives a new script key for receiving assets.
	// The script key includes both the internal key and the tweaked
	// Taproot output key.
	DeriveScriptKey(ctx context.Context) (*ScriptKey, error)

	// DeriveInternalKey derives a new internal key for anchor outputs.
	DeriveInternalKey(ctx context.Context) (*InternalKey, error)

	// FundTransfer funds a virtual transaction using addresses.
	FundTransfer(ctx context.Context, recipients []Recipient,
		inputs []PrevID) (*FundedTransfer, error)

	// FundInteractivePsbt funds a virtual PSBT for interactive sends.
	FundInteractivePsbt(ctx context.Context, psbt []byte) (
		*FundedTransfer, error)

	// SignVirtualPsbt signs a virtual transaction.
	SignVirtualPsbt(ctx context.Context, fundedPsbt []byte) ([]byte, error)

	// CommitVirtualPsbts commits virtual transactions using an anchor fee
	// rate. Advanced callers that need to preserve a caller-supplied anchor
	// template should use CustomAnchorWalletKitClient when the concrete
	// client implements it.
	CommitVirtualPsbts(ctx context.Context, virtualPsbts [][]byte,
		passivePsbts [][]byte, feeRate FeeRate) (*CommittedTransfer,
		error)

	// AnchorVirtualPsbts anchors signed virtual PSBTs in a single call.
	// This combines committing and publishing into one operation.
	AnchorVirtualPsbts(ctx context.Context, signedPsbts [][]byte) (
		*AssetTransfer, error)

	// PublishAndLogTransfer publishes the anchor transaction and logs the
	// transfer.
	PublishAndLogTransfer(ctx context.Context, anchorPsbt []byte,
		virtualPsbts [][]byte, passivePsbts [][]byte,
		skipAnchorTxBroadcast bool) (*AssetPacket, error)

	// QueryInternalKey looks up an internal key by its raw public key
	// bytes. The input can be 32-byte x-only or 33-byte compressed.
	QueryInternalKey(ctx context.Context,
		internalKey []byte) (*KeyDescriptor, error)

	// QueryScriptKey looks up a script key by its tweaked public key
	// bytes. The input can be 32-byte x-only or 33-byte compressed.
	QueryScriptKey(ctx context.Context,
		tweakedScriptKey []byte) (*ScriptKey, error)

	// ProveAssetOwnership generates a proof of ownership for an
	// asset.
	ProveAssetOwnership(ctx context.Context,
		req *ProveOwnershipRequest) (
		*OwnershipProof, error)

	// VerifyAssetOwnership verifies an asset ownership proof.
	VerifyAssetOwnership(ctx context.Context,
		req *VerifyOwnershipRequest) (
		*VerifyOwnershipResponse, error)

	// RemoveUTXOLease removes a lease on a UTXO.
	RemoveUTXOLease(ctx context.Context,
		outpoint Outpoint) error

	// DeclareScriptKey informs the wallet about an externally derived
	// script key.
	DeclareScriptKey(ctx context.Context,
		req *DeclareScriptKeyRequest) (
		*ScriptKey, error)

	// ExportBackup exports an asset wallet backup blob using the requested
	// backup mode.
	ExportBackup(ctx context.Context,
		mode BackupMode) ([]byte, error)

	// ImportBackup imports assets from a previously exported wallet backup
	// blob and returns the number of imported assets.
	ImportBackup(ctx context.Context, backup []byte) (uint32, error)
}

WalletKitClient exposes the AssetWalletClient service gRPC client.

type WalletOption

type WalletOption func(*Wallet)

WalletOption configures optional Wallet behavior.

func WithAuthMailboxCourier

func WithAuthMailboxCourier(host string) WalletOption

WithAuthMailboxCourier configures the default proof courier for high-level V2 receive address helpers using the auth mailbox transport. The host should include the port, for example "tapd.example:10029".

func WithDefaultProofCourierAddr

func WithDefaultProofCourierAddr(addr string) WalletOption

WithDefaultProofCourierAddr sets the default proof courier address used by high-level V2 receive address helpers.

type XOnlyPubKey

type XOnlyPubKey [32]byte

XOnlyPubKey is a 32-byte x-only (Schnorr/Taproot) public key.

func ParseXOnlyPubKey

func ParseXOnlyPubKey(b []byte) (XOnlyPubKey, error)

ParseXOnlyPubKey parses a 32-byte x-only (Schnorr/Taproot) public key.

func (XOnlyPubKey) Bytes

func (k XOnlyPubKey) Bytes() []byte

Bytes returns the 32-byte x-only encoding of the public key.

Directories

Path Synopsis
demos
internal

Jump to

Keyboard shortcuts

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