arksdk

package module
v0.10.1 Latest Latest
Warning

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

Go to latest
Published: Jun 24, 2026 License: MIT Imports: 45 Imported by: 1

README

Arkade Go SDK

The complete API documentation for the Go SDK is automatically generated and published on pkg.go.dev with each GitHub release. To view the documentation, visit: https://pkg.go.dev/github.com/arkade-os/go-sdk

Installation

To install the Arkade Go SDK, use the following command:

go get github.com/arkade-os/go-sdk

Usage

Here's a comprehensive guide on how to use the Arkade Go SDK:

1. Setting up the Wallet

NewWallet(datadir string, opts ...WalletOption) creates a brand new wallet and can't be used to load an existing one.
LoadWallet(datadir string, opts ...WalletOption) loads an existing wallet and can't be used to create a new one.
Both accept one required parameter plus optional wallet options:

  • datadir — path to the directory where wallet and transaction data are persisted. Pass "" to use in-memory storage (useful for testing; loading from an in-memory datadir won't work for obvious reasons).
  • opts — optional WalletOption values:
    • WithRefreshDbInterval(d time.Duration) — configure periodic background refresh of the local database from the server. Defaults to 30s and must be at least 30s.
    • WithVerbose() — enables verbose logging.
    • WithGapLimit(n uint32) — HD discovery gap limit used on unlock to recover externally-funded addresses. Defaults to 20 and must be at least 20.
    • WithIdentity(svc identity.Identity) — inject a custom key-management implementation. By default the SDK creates an HD identity (BIP86) backed by the persistent datadir; see the identity package for the default implementation.
    • WithScheduler(svc scheduler.SchedulerService) — inject a custom scheduler implementation for auto-settle. Defaults to a gocron-backed in-process scheduler.
    • WithoutAutoSettle() — disable the background auto-settle loop entirely. By default the wallet schedules a Settle at ~90% of each spendable vtxo's remaining lifetime and re-schedules as fresher vtxos arrive.
import arksdk (
    "errors"
    "log"

    "github.com/arkade-os/go-sdk"
)

// In-memory storage
wallet, err := arksdk.NewWallet("")

// Persistent storage
var wallet arksdk.Wallet
var err error
// Try to load the wallet (with default options).
wallet, err = arksdk.LoadWallet("/path/to/data/dir")
if err != nil {
    if !errors.Is(err, arksdk.ErrNotInitialized) {
        return err
    }
    // If not initialized, create a new one (with default options).
    wallet, err = arksdk.NewWallet("/path/to/data/dir")
    if err != nil {
        log.Fatal(err)
    }
}

// Wallet with periodic DB refresh every 5 minutes and verbose logs
wallet, err := arksdk.NewWallet(
    "/path/to/data/dir", arksdk.WithRefreshDbInterval(5 * time.Minute), arksdk.WithVerbose(),
)

Once you have a wallet, call Init to connect it to an Arkade server and set up the identity:

// Generate a fresh HD identity (default). Pass an empty seed.
if err := wallet.Init(ctx, "localhost:7070", "", "your_password"); err != nil {
    return fmt.Errorf("failed to initialize wallet: %s", err)
}

// Restore an existing HD identity from its BIP39 mnemonic.
if err := wallet.Init(
    ctx, "localhost:7070", "abandon abandon ...", "your_password",
); err != nil {
    return fmt.Errorf("failed to restore wallet: %s", err)
}

// Custom explorer URL.
if err := wallet.Init(
    ctx, "localhost:7070", "your_seed", "your_password",
    arksdk.WithExplorerURL("https://example.com"),
); err != nil {
    return fmt.Errorf("failed to initialize wallet: %s", err)
}

After Init + Unlock, wait for sync to complete before using balances or history. The SDK performs HD key discovery on unlock and restores any known offchain, boarding, redemption, and direct onchain state from the configured gap limit (see WithGapLimit in §1).

if err := wallet.Unlock(ctx, "your_password"); err != nil {
    return err
}

syncEvent := <-wallet.IsSynced(ctx)
if syncEvent.Err != nil {
    return syncEvent.Err
}

Each call to NewOnchainAddress, NewBoardingAddress, and NewOffchainAddress allocates a fresh derived key, so GetAddresses() returns the full discovered address set rather than a single stable address per family.

2. Init Options

Init has the following signature:

Init(ctx context.Context, serverUrl, seed, password string, opts ...InitOption) error
  • serverUrl — address of the Arkade server (e.g. "localhost:7070").
  • seed — BIP39 mnemonic. Pass "" to have the SDK generate a fresh one (recoverable via Dump).
  • password — used to encrypt and protect the identity material at rest.
  • opts — optional functional options:
    • WithExplorerURL(url string) — override the default mempool explorer URL for the network.

To plug in a non-HD identity (hardware wallet, KMS, remote signer, …), inject it at construction time via arksdk.WithIdentity(svc) — see §1.

Note: Always keep your seed and password secure. Never share them or store them in plaintext.

3. Wallet Operations

Unlock and Lock the Wallet
if err := wallet.Unlock(ctx, password); err != nil {
    log.Fatal(err)
}
defer wallet.Lock(ctx)
Receive Funds

The old Receive API has been split into three dedicated methods:

onchainAddr, err := wallet.NewOnchainAddress(ctx)
if err != nil {
    log.Fatal(err)
}
log.Infof("Onchain address: %s", onchainAddr)

boardingAddr, err := wallet.NewBoardingAddress(ctx)
if err != nil {
    log.Fatal(err)
}
log.Infof("Boarding address: %s", boardingAddr)

offchainAddr, err := wallet.NewOffchainAddress(ctx)
if err != nil {
    log.Fatal(err)
}
log.Infof("Offchain address: %s", offchainAddr)
Check Balance
balance, err := wallet.Balance(ctx)
if err != nil {
    log.Fatal(err)
}
log.Infof("Onchain balance: %d", balance.OnchainBalance.SpendableAmount)
log.Infof("Offchain balance: %d", balance.OffchainBalance.Total)

// Asset balances are keyed by asset ID (string).
for assetID, amount := range balance.AssetBalances {
    log.Infof("Asset %s balance: %d", assetID, amount)
}
Send Offchain
import clientTypes "github.com/arkade-os/arkd/pkg/client-lib/types"

// Send sats offchain.
receivers := []clientTypes.Receiver{
    {To: recipientOffchainAddr, Amount: 1000},
}
txid, err := wallet.SendOffChain(ctx, receivers)
if err != nil {
    log.Fatal(err)
}
log.Infof("Transaction completed: %s", txid)

// Send assets offchain. If not specified, like in this example, the real recipient's amount defaults to 330 sats (dust).
assetReceivers := []clientTypes.Receiver{
    {
        To: recipientOffchainAddr,
        Assets: []clientTypes.Asset{
            {AssetId: assetID, Amount: 1200},
        },
    },
}
txid, err = wallet.SendOffChain(ctx, assetReceivers)
if err != nil {
    log.Fatal(err)
}
log.Infof("Asset transfer completed: %s", txid)
Submit Transaction

SendOffChain is useful for simple send operations. But complex contract or collaborative transactions require more flexibility. In this case, you can use the Client.SubmitTx and Client.FinalizeTx APIs (the transport client, exposed via wallet.Client() or built standalone with grpcclient.NewClient).

// Create a new transport client
transportClient, err := grpcclient.NewClient("localhost:7070")
require.NoError(t, err)

// Use ark-lib/tree util function to build ark and checkpoint transactions.
arkTx, checkpointTxs, err := offchain.BuildTxs(
	[]offchain.VtxoInput{
		// ... your inputs here
	},
	[]*wire.TxOut{
		// ... your outputs here
	},
	batchOutputSweepClosure,
)

signedArkTx, err := wallet.SignTransaction(ctx, arkTx)
if err != nil {
	return "", err
}

arkTxid, _, signedCheckpointTxs, err := grpcclient.SubmitTx(ctx, signedArkTx, checkpointTxs)
if err != nil {
	return "", err
}

// Counter-sign and checkpoint txs and send them back to the server to complete the process.
finalCheckpointTxs := make([]string, 0, len(signedCheckpointTxs))
for _, checkpointTx := range signedCheckpointTxs {
	finalCheckpointTx, err := a.SignTransaction(ctx, checkpointTx)
	if err != nil {
		return "", nil
	}
	finalCheckpointTxs = append(finalCheckpointTxs, finalCheckpointTx)
}

if err = a.client.FinalizeTx(ctx, arkTxid, finalCheckpointTxs); err != nil {
	return "", err
}
Asset Operations

Arkade supports issuing, transferring, reissuing, and burning custom assets offchain.

Concepts:

  • An asset is identified by a string asset ID derived from the genesis transaction ID and group index.
  • A control asset is a special asset that grants authority to reissue a given asset. Holding the control asset vtxo in your wallet is required to call ReissueAsset.
  • Without a control asset, an issued asset has a fixed, immutable supply.
Issue Asset
import (
    "github.com/arkade-os/arkd/pkg/ark-lib/asset"
    clientTypes "github.com/arkade-os/arkd/pkg/client-lib/types"
)

// 1. Fixed supply — no control asset. Returns one asset ID.
txid, assetIds, err := wallet.IssueAsset(ctx, 5000, nil, nil)
if err != nil {
    log.Fatal(err)
}
assetID := assetIds[0].String()
log.Infof("Issued asset %s in tx %s", assetID, txid)

// 2. With a new control asset issued together with the controlled one.
//    Returns two asset IDs: [controlAssetId, issuedAssetId].
txid, assetIds, err = wallet.IssueAsset(ctx, 5000, clientTypes.NewControlAsset{Amount: 1}, nil)
if err != nil {
    log.Fatal(err)
}
controlAssetID := assetIds[0].String()
assetID = assetIds[1].String()
log.Infof("Control asset: %s, issued asset: %s", controlAssetID, assetID)

// 3. With an existing control asset.
//    Returns one asset ID for the newly issued asset.
txid, assetIds, err = wallet.IssueAsset(
    ctx, 5000, clientTypes.ExistingControlAsset{ID: controlAssetID}, nil,
)
if err != nil {
    log.Fatal(err)
}
log.Infof("Issued asset %s under existing control asset", assetIds[0].String())

// Optional: attach metadata to the asset.
meta := []asset.Metadata{
    {Key: "name", Value: "My Token"},
    {Key: "ticker", Value: "MTK"},
}
txid, assetIds, err = wallet.IssueAsset(ctx, 5000, clientTypes.NewControlAsset{Amount: 1}, meta)
Reissue Asset

The caller must hold the control asset vtxo in their wallet.

txid, err := wallet.ReissueAsset(ctx, assetID, 1000)
if err != nil {
    log.Fatal(err)
}
log.Infof("Reissued 1000 units of %s in tx %s", assetID, txid)
Burn Asset

Destroys the specified amount. Any remaining balance is returned to the caller's address as change.

txid, err := wallet.BurnAsset(ctx, assetID, 500)
if err != nil {
    log.Fatal(err)
}
log.Infof("Burned 500 units of %s in tx %s", assetID, txid)

4. Advanced Usage

Multiple Recipients

You can send to multiple recipients in a single transaction:

receivers := []clientTypes.Receiver{
    {To: recipient1OffchainAddr, Amount: amount1},
    {To: recipient2OffchainAddr, Amount: amount2},
}
txid, err = wallet.SendOffChain(ctx, receivers)
Settle

Finalize pending boarding or preconfirmed funds into a commitment transaction:

// Basic settle
txid, err := wallet.Settle(ctx)
if err != nil {
    log.Fatal(err)
}
log.Infof("commitment tx: %s", txid)

// Settle with automatic retries on failure (max 5)
txid, err = wallet.Settle(ctx, arksdk.WithRetries(3))
if err != nil {
    log.Fatal(err)
}
log.Infof("commitment tx: %s", txid)
Cooperative Exit

To redeem offchain funds to onchain:

// Basic collaborative exit
txid, err := wallet.CollaborativeExit(ctx, onchainAddress, redeemAmount)
if err != nil {
    log.Fatal(err)
}
log.Infof("commitment tx: %s", txid)

// Collaborative exit with automatic retries on failure (max 5)
txid, err = wallet.CollaborativeExit(ctx, onchainAddress, redeemAmount, arksdk.WithRetries(3))
if err != nil {
    log.Fatal(err)
}
log.Infof("Redeemed with tx: %s", txid)
Custom Contract Handlers

The contract manager ships with built-in handlers for the default (offchain) and boarding contract types. You can teach it additional contract types by registering your own handlers.Handler at wallet construction.

⚠️ Custom handlers must produce scripts/signing data that your wallet identity can actually sign. Registering an invalid handler can lead to contracts that are not spendable.

import "github.com/arkade-os/go-sdk/contract/handlers"

// myHandler implements contract/handlers.Handler. The key method is
// NewContract, which derives the script, address, and params for a given key.
// See contract/handlers/default for a reference implementation.
var myHandler handlers.Handler = NewCustomHandler(...)

wallet, err := arksdk.NewWallet(
    datadir, arksdk.WithContractHandler("custom", myHandler),
)

Once registered, create and look up contracts of the custom type through the usual manager API:

mgr := wallet.ContractManager()

// Discover the registered types (built-ins plus your custom ones).
supported := mgr.Registry().SupportedTypes() // [boarding custom default]

// Create a contract using your handler.
c, err := mgr.NewContract(ctx, "custom")

5. Additional Wallet Methods

The Wallet interface exposes a number of utility methods beyond the basic workflow shown above. Here is a quick overview:

Lifecycle & metadata
  • Version() string - return the SDK version.
  • Init(ctx, serverUrl, seed, password, opts...) - create or restore an identity and connect to the server. See §2 for available options.
  • IsLocked(ctx) - check if the wallet is currently locked.
  • Unlock(ctx, password) / Lock(ctx) - unlock or lock the wallet.
  • IsSynced(ctx) <-chan types.SyncEvent - returns a channel that emits once the local database has finished syncing after unlock.
  • Reset(ctx) - wipe the local state (clears stores and locks the identity). Use for "logout" / re-init flows.
  • Stop() - stop any running background loops (sync, listeners, scheduler).
Dependency accessors

These return the underlying services so callers can drive lower-level flows directly:

  • Store() types.Store - the wallet's persistent store (per-domain repositories).
  • Identity() identity.Identity - the active identity (HD by default).
  • Explorer() explorer.Explorer - the mempool explorer client.
  • Indexer() indexer.Indexer - the arkd indexer client.
  • Client() client.Client - the transport client. See §6.
  • ContractManager() contract.Manager - the contract manager. See the contract package for its surface.
Balances and addresses
  • Balance(ctx) - query onchain and offchain balances. The returned struct includes AssetBalances map[string]uint64 keyed by asset ID.
  • GetAddresses(ctx) - return all known onchain, offchain, boarding and redemption addresses.
  • NewOnchainAddress(ctx) / NewBoardingAddress(ctx) / NewOffchainAddress(ctx) - derive a fresh address of the respective type.
Assets
  • IssueAsset(ctx, amount, controlAsset, metadata) — mint a new offchain asset. Pass nil for a fixed-supply asset, types.NewControlAsset{Amount} to create a reissuable asset with a new control asset, or types.ExistingControlAsset{ID} to issue under an existing control asset. Returns the ark txid and the resulting asset IDs.
  • ReissueAsset(ctx, assetId, amount) — mint additional supply of an existing controllable asset. Requires the caller to hold the corresponding control asset vtxo.
  • BurnAsset(ctx, assetID, amount) — permanently destroy a quantity of an asset. Remaining balance is returned as change to the caller's address.
Spending and batching
  • SendOffChain(ctx, receivers) - send funds offchain. Each clientTypes.Receiver can carry an Assets []clientTypes.Asset slice to transfer assets alongside sats.
  • Settle(ctx, opts ...BatchSessionOption) (string, error) - finalize pending or preconfirmed funds into a commitment transaction. Accepts WithRetries(n) to retry on failure (max 5 retries).
  • RegisterIntent(...) / DeleteIntent(...) - manage spend intents for collaborative transactions.
  • CollaborativeExit(ctx, addr, amount, opts ...BatchSessionOption) (string, error) - redeem offchain funds onchain. Accepts WithRetries(n) to retry on failure (max 5 retries).
  • Unroll(ctx) error - broadcast unroll transactions when ready.
  • CompleteUnroll(ctx, to string) (string, error) - finalize an unroll and sweep to an onchain address.
  • OnboardAgainAllExpiredBoardings(ctx) (string, error) - onboard again using expired boarding UTXOs.
  • WithdrawFromAllExpiredBoardings(ctx, to string) (string, error) - withdraw expired boarding amounts onchain.
  • WhenNextSettlement() time.Time - inspect the next auto-settle firing time. Returns the zero value when auto-settle is disabled or nothing is scheduled.

Concurrency: spend (SendOffChain, IssueAsset, ReissueAsset, BurnAsset) and batch (Settle, CollaborativeExit) operations on the same wallet are internally serialized, so they can be called concurrently without double-spending VTXOs. A pending Settle/CollaborativeExit takes precedence over queued spends, and concurrent Settle calls de-duplicate into a single settlement. Each call returns only once the server has tracked its result, so a following operation can safely spend the change. CollaborativeExit returns ErrSettleInProgress if a batch is already in flight.

State, signing, and notifications
  • ListVtxos(ctx) (spendable, spent []clientTypes.Vtxo, err error) - list virtual UTXOs. Each Vtxo includes an Assets []types.Asset field listing any assets it carries.
  • ListSpendableVtxos(ctx) - list only spendable virtual UTXOs.
  • Dump(ctx) (seed string, error) - export the identity's seed (BIP39 mnemonic for the default HD identity).
  • GetTransactionHistory(ctx) - fetch past transactions.
  • GetTransactionEventChannel(ctx), GetVtxoEventChannel(ctx) and GetUtxoEventChannel(ctx) - subscribe to wallet events.
  • FinalizePendingTxs(ctx, createdAfter *time.Time) ([]string, error) - finalize any pending transactions, optionally filtered by creation time.
  • RedeemNotes(ctx, notes) - redeem Arkade notes back to your wallet.
  • SignTransaction(ctx, tx) - sign an arbitrary transaction.
  • NotifyIncomingFunds(ctx, address) - wait until a specific offchain address receives funds and return the resulting vtxos.

6. Transport Client

For lower-level control over transaction batching you can use the client.Client transport interface directly (obtained via wallet.Client() or constructed standalone):

  • GetInfo(ctx) - return server configuration and network data.
  • RegisterIntent(ctx, signature, message) and DeleteIntent(ctx, signature, message) - manage collaborative intents.
  • ConfirmRegistration(ctx, intentID) - confirm intent registration on chain.
  • SubmitTreeNonces(ctx, batchId, cosignerPubkey, nonces) and SubmitTreeSignatures(ctx, batchId, cosignerPubkey, sigs) - coordinate cosigner trees.
  • SubmitSignedForfeitTxs(ctx, signedForfeitTxs, signedCommitmentTx) - provide fully signed forfeit and commitment transactions.
  • GetEventStream(ctx, topics) - subscribe to batch events from the server.
  • SubmitTx(ctx, signedArkTx, checkpointTxs) and FinalizeTx(ctx, arkTxid, finalCheckpointTxs) - submit collaborative transactions.
  • GetTransactionsStream(ctx) - stream transaction notifications.
  • Close() - close the transport connection.

See the pkg.go.dev documentation for detailed API information.

Testing

Run integration tests (start nigiri if needed first):

make regtest
make integrationtest
make regtestdown

Full Example

The snippet below shows the complete flow from wallet creation to an offchain send:

package main

import (
    "context"
    "fmt"
    "log"

    arksdk "github.com/arkade-os/go-sdk"
    clientTypes "github.com/arkade-os/arkd/pkg/client-lib/types"
)

func main() {
    ctx := context.Background()
    seed := "" // empty → generate a fresh BIP39 mnemonic; recoverable via Dump
    password := "secret"
    serverUrl := "localhost:7070"

    // Create a persistent wallet.
    wallet, err := arksdk.NewWallet("/path/to/data/dir")
    if err != nil {
        log.Fatal(err)
    }
    defer wallet.Stop()

    // Connect to the server and set up the identity.
    if err := wallet.Init(ctx, serverUrl, seed, password); err != nil {
        log.Fatal(err)
    }

    // Unlock the wallet to start syncing.
    if err := wallet.Unlock(ctx, password); err != nil {
        log.Fatal(err)
    }
    defer wallet.Lock(ctx)

    // Wait for the local database to finish syncing.
    syncCh := wallet.IsSynced(ctx)
    if event := <-syncCh; event.Err != nil {
        log.Fatal(event.Err)
    }

    // Generate a fresh offchain address to receive funds.
    offchainAddr, err := wallet.NewOffchainAddress(ctx)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("Offchain address:", offchainAddr)

    // Check balance.
    balance, err := wallet.Balance(ctx)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Offchain balance: %d sats\n", balance.OffchainBalance.Total)

    // Send offchain.
    receivers := []clientTypes.Receiver{
        {To: "<recipient_offchain_addr>", Amount: 1000},
    }
    txid, err := wallet.SendOffChain(ctx, receivers)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("Transaction ID:", txid)
}

Support

If you encounter any issues or have questions, please file an issue on our GitHub repository.

Documentation

Index

Constants

View Source
const HeaderVersion = "go-sdk/0.10.1"

Variables

View Source
var (
	ErrInvalidLimit            = errors.New("limit must be between 1 and 1000")
	ErrConflictingStatusOption = errors.New(
		"WithSpendableOnly and WithSpentOnly are mutually exclusive",
	)
	ErrInvalidCursor        = errors.New("cursor is malformed")
	ErrCursorFilterMismatch = errors.New("cursor was issued under a different filter set")
	ErrEmptyScript          = errors.New("script must not be empty")
)
View Source
var (
	ErrNotInitialized   = fmt.Errorf("wallet not initialized")
	ErrIsLocked         = fmt.Errorf("wallet is locked")
	ErrIsSyncing        = fmt.Errorf("wallet is still syncing")
	ErrSettleInProgress = fmt.Errorf("settle in progress, retry later")
)
View Source
var (
	ErrNoFundsToSettle = fmt.Errorf("no funds to settle")
)
View Source
var Version = readSDKVersion()

Version reports the SDK's module version as resolved by the Go module system at build time of the importing binary. Populated from runtime/debug.ReadBuildInfo on package init:

  • For a binary that imported the SDK via `go get …@vX.Y.Z`, returns "vX.Y.Z".
  • For a pseudo-version (commit / branch import), returns "v0.0.0-<utc-timestamp>-<short-commit-sha>".
  • For a local replace directive (or `go test ./…` inside the SDK repo itself), returns "(devel)".
  • When build info is unavailable (vendored builds without modules, certain test harnesses), returns "unknown".

Wallet.Version() proxies this value, so callers can read either.

Functions

func ApplyBatchSessionOptions

func ApplyBatchSessionOptions(opts ...BatchSessionOption) error

ApplyBatchOptions applies the given BatchSessionOption functions to a new default batchSessionOptions struct and returns the first error encountered, if any. Exposed for use in external (arksdk_test) test packages.

func ApplyInitOptions

func ApplyInitOptions(opts ...InitOption) error

ApplyInitOptions applies the given InitOption functions to a new default initOptions struct and returns the first error encountered, if any. Exposed for use in external (arksdk_test) test packages.

func ApplyWalletOptions added in v0.10.0

func ApplyWalletOptions(opts ...WalletOption) error

ApplyWalletOptions applies opts to a new default clientOptions and returns the first error encountered, if any. Exposed for use in external (arksdk_test) test packages.

Types

type BatchSessionOption

type BatchSessionOption func(options *batchSessionOptions) error

func WithRetries

func WithRetries(num int) BatchSessionOption

type InitOption

type InitOption func(options *initOptions) error

func WithExplorerURL

func WithExplorerURL(explorerUrl string) InitOption

type ListVtxosOption added in v0.10.0

type ListVtxosOption func(*listVtxosOpts) error

ListVtxosOption configures a Wallet.ListVtxos call. Options are validated when applied; an invalid option causes ListVtxos to return the corresponding sentinel error.

func WithAssetID added in v0.10.0

func WithAssetID(id string) ListVtxosOption

WithAssetID restricts results to VTXOs that hold the given asset. Selected VTXOs include all their assets in the response, not just the filtered one.

func WithCursor added in v0.10.0

func WithCursor(c string) ListVtxosOption

WithCursor resumes pagination from the given opaque cursor. An empty string starts from the first page.

func WithLimit added in v0.10.0

func WithLimit(n int) ListVtxosOption

WithLimit sets the maximum number of VTXOs to return in one page. Valid range: [1, 1000]. Default and max are both 1000.

func WithScript added in v0.10.1

func WithScript(script string) ListVtxosOption

WithScript restricts results to VTXOs whose script field exactly matches the given script. An empty string is rejected.

func WithSpendableOnly added in v0.10.0

func WithSpendableOnly() ListVtxosOption

WithSpendableOnly restricts results to VTXOs with spent = false AND unrolled = false.

func WithSpentOnly added in v0.10.0

func WithSpentOnly() ListVtxosOption

WithSpentOnly restricts results to VTXOs with spent = true OR unrolled = true.

type SendOffChainOption added in v0.10.1

type SendOffChainOption = client.SendOption

SendOffChainOption configures a SendOffChain call.

func WithExtraPacket added in v0.10.1

func WithExtraPacket(packets ...extension.Packet) SendOffChainOption

WithExtraPacket appends extra extension.Packet values to the OP_RETURN extension blob written by SendOffChain. Re-exports client.WithExtraPacket so callers don't need to import client-lib directly.

type Wallet added in v0.10.0

type Wallet interface {
	Version() string
	Store() types.Store
	Identity() identity.Identity
	Explorer() explorer.Explorer
	Indexer() indexer.Indexer
	Client() client.Client
	ContractManager() contract.Manager

	Init(ctx context.Context, serverUrl, seed, password string, opts ...InitOption) error
	IsLocked(ctx context.Context) bool
	Unlock(ctx context.Context, password string) error
	Lock(ctx context.Context) error
	IsSynced(ctx context.Context) <-chan types.SyncEvent
	Balance(ctx context.Context) (*types.Balance, error)
	GetAddresses(ctx context.Context) (
		onchainAddresses, offchainAddresses, boardingAddresses, redemptionAddresses []string,
		err error,
	)
	NewOffchainAddress(ctx context.Context) (string, error)
	NewBoardingAddress(ctx context.Context) (string, error)
	NewOnchainAddress(ctx context.Context) (string, error)
	IssueAsset(
		ctx context.Context,
		amount uint64, controlAsset clienttypes.ControlAsset, metadata []asset.Metadata,
	) (string, []asset.AssetId, error)
	ReissueAsset(
		ctx context.Context, assetId string, amount uint64,
	) (string, error)
	BurnAsset(
		ctx context.Context, assetID string, amount uint64,
	) (string, error)
	SendOffChain(
		ctx context.Context, receivers []clienttypes.Receiver, opts ...SendOffChainOption,
	) (string, error)
	RegisterIntent(
		ctx context.Context,
		vtxos []clienttypes.Vtxo, boardingUtxos []clienttypes.Utxo, notes []string,
		outputs []clienttypes.Receiver, cosignersPublicKeys []string,
	) (intentID string, err error)
	DeleteIntent(
		ctx context.Context,
		vtxos []clienttypes.Vtxo, boardingUtxos []clienttypes.Utxo, notes []string,
	) error
	Settle(ctx context.Context, opts ...BatchSessionOption) (string, error)
	CollaborativeExit(
		ctx context.Context, addr string, amount uint64, opts ...BatchSessionOption,
	) (string, error)
	Unroll(ctx context.Context) error
	CompleteUnroll(ctx context.Context, to string) (string, error)
	OnboardAgainAllExpiredBoardings(ctx context.Context) (string, error)
	WithdrawFromAllExpiredBoardings(ctx context.Context, to string) (string, error)

	// ListVtxos returns one page of wallet VTXOs plus an opaque cursor for the
	// next page. The cursor is empty when there are no more results; callers
	// should pass a non-empty cursor back with WithCursor without parsing it.
	ListVtxos(ctx context.Context, opts ...ListVtxosOption) ([]clienttypes.Vtxo, string, error)

	Dump(ctx context.Context) (seed string, err error)
	GetTransactionHistory(ctx context.Context) ([]clienttypes.Transaction, error)
	GetTransactionEventChannel(ctx context.Context) <-chan types.TransactionEvent
	GetVtxoEventChannel(ctx context.Context) <-chan types.VtxoEvent
	GetUtxoEventChannel(ctx context.Context) <-chan types.UtxoEvent
	RedeemNotes(ctx context.Context, notes []string) (string, error)
	SignTransaction(ctx context.Context, tx string) (string, error)
	NotifyIncomingFunds(ctx context.Context, address string) ([]clienttypes.Vtxo, error)
	FinalizePendingTxs(ctx context.Context, createdAfter *time.Time) ([]string, error)
	Reset(ctx context.Context)
	Stop()
	// WhenNextSettlement returns the time at which the next automatic settlement
	// is scheduled to fire. Returns the zero time.Time when auto-settle is
	// disabled or no settlement is currently scheduled.
	WhenNextSettlement() time.Time
}

func LoadWallet added in v0.10.0

func LoadWallet(datadir string, opts ...WalletOption) (Wallet, error)

func NewWallet added in v0.10.0

func NewWallet(datadir string, opts ...WalletOption) (Wallet, error)

type WalletOption added in v0.10.0

type WalletOption func(*walletOptions) error

func WithContractHandler added in v0.10.0

func WithContractHandler(t types.ContractType, h handlers.Handler) WalletOption

WithContractHandler registers a custom contract handler that the wallet's contract manager will dispatch to for the given contract type. The type must be non-empty, the handler non-nil, and must not collide with another previously registered custom handler. Collisions with a built-in type (default, boarding) are detected at Unlock time via the underlying contract.WithHandler / contract.NewManager checks. Multiple calls are allowed for different types.

func WithGapLimit added in v0.10.0

func WithGapLimit(limit uint32) WalletOption

WithGapLimit sets the HD wallet discovery gap limit used during startup recovery. Must be at least 20. Can only be set once. If not set, hdGapLimit defaults to 20.

func WithIdentity added in v0.10.0

func WithIdentity(identitySvc identity.Identity) WalletOption

WithIdentity injects a custom Identity implementation for key management. Can only be set once and must not be nil.

func WithRefreshDbInterval

func WithRefreshDbInterval(d time.Duration) WalletOption

WithRefreshDbInterval sets the interval at which the local database is periodically refreshed from the server. Must be at least 30s. Can only be set once. If not set, refreshDbInterval defaults to 30s.

func WithScheduler added in v0.10.0

func WithScheduler(svc scheduler.SchedulerService) WalletOption

WithScheduler injects a custom SchedulerService implementation for task scheduling.

func WithVerbose

func WithVerbose() WalletOption

WithVerbose enables verbose logging.

func WithoutAutoSettle added in v0.10.0

func WithoutAutoSettle() WalletOption

WithoutAutoSettle disables the auto-settle feature.

Directories

Path Synopsis
api-spec module
Package contract manages the lifecycle of contracts derived from an identity for a Wallet: it owns the per-type handlers, persists the contracts via a pluggable store, and rescans for not-yet tracked contracts to store.
Package contract manages the lifecycle of contracts derived from an identity for a Wallet: it owns the per-type handlers, persists the contracts via a pluggable store, and rescans for not-yet tracked contracts to store.
Package identity provides an HD (BIP32/BIP86) implementation of the upstream client-lib identity.Identity interface, backed by a pluggable IdentityStore for persistence.
Package identity provides an HD (BIP32/BIP86) implementation of the upstream client-lib identity.Identity interface, backed by a pluggable IdentityStore for persistence.
internal
Package scheduler provides a tiny "at-most-one task in flight" scheduler interface, with a gocron-backed implementation in scheduler/gocron.
Package scheduler provides a tiny "at-most-one task in flight" scheduler interface, with a gocron-backed implementation in scheduler/gocron.
Package store is the aggregating factory for the SDK's persistence layer.
Package store is the aggregating factory for the SDK's persistence layer.
sql
test
docker command
#nosec
#nosec

Jump to

Keyboard shortcuts

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