Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,4 @@ node_modules
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.vercel
6 changes: 6 additions & 0 deletions docs/build/sdk/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"label": "SDK",
"position": 2,
"collapsed": false,
"collapsible": false
}
6 changes: 6 additions & 0 deletions docs/build/sdk/go/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"label": "Go SDK",
"position": 4,
"collapsed": false,
"collapsible": false
}
165 changes: 165 additions & 0 deletions docs/build/sdk/go/api-reference.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
---
title: API Reference
description: Complete API reference for the Clearnode Go SDK
sidebar_position: 2
---

# Go SDK API Reference

## State Operations (Off-Chain)

```go
client.Deposit(ctx, blockchainID, asset, amount) // Prepare deposit state
client.Withdraw(ctx, blockchainID, asset, amount) // Prepare withdrawal state
client.Transfer(ctx, recipientWallet, asset, amount) // Prepare transfer state
client.CloseHomeChannel(ctx, asset) // Prepare finalize state
client.Acknowledge(ctx, asset) // Acknowledge received state
```

All return `(*core.State, error)`. Use `Checkpoint` to settle on-chain.

---

## Blockchain Settlement

```go
client.Checkpoint(ctx, asset) // Settle latest state on-chain
client.Challenge(ctx, state) // Submit on-chain challenge
client.ApproveToken(ctx, chainID, asset, amount) // Approve ChannelHub to spend tokens
client.GetOnChainBalance(ctx, chainID, asset, wallet) // Query on-chain token balance
```

`Checkpoint` routes automatically based on transition type and channel status:
- **Void** → creates channel
- **Deposit/Withdrawal** → checkpoints state
- **Finalize** → closes channel

---

## Node Information

```go
client.Ping(ctx) // Health check
client.GetConfig(ctx) // Node configuration
client.GetBlockchains(ctx) // Supported blockchains
client.GetAssets(ctx, &blockchainID) // Supported assets (nil for all)
```

---

## User Queries

```go
client.GetBalances(ctx, wallet) // User balances
client.GetTransactions(ctx, wallet, opts) // Transaction history (paginated)
```

---

## Channel Queries

```go
client.GetHomeChannel(ctx, wallet, asset) // Home channel info
client.GetEscrowChannel(ctx, escrowChannelID) // Escrow channel info
client.GetLatestState(ctx, wallet, asset, onlySigned) // Latest state
```

---

## App Registry

```go
apps, meta, err := client.GetApps(ctx, &sdk.GetAppsOptions{
AppID: &appID,
OwnerWallet: &wallet,
})

err := client.RegisterApp(ctx, "my-app", `{"name": "My App"}`, false)
```

---

## App Sessions

```go
sessions, meta, err := client.GetAppSessions(ctx, opts)
def, err := client.GetAppDefinition(ctx, appSessionID)
sessionID, version, status, err := client.CreateAppSession(ctx, def, data, sigs)
nodeSig, err := client.SubmitAppSessionDeposit(ctx, update, sigs, asset, amount)
err := client.SubmitAppState(ctx, update, sigs)
batchID, err := client.RebalanceAppSessions(ctx, signedUpdates)
```

---

## Session Keys — App Sessions

```go
state := app.AppSessionKeyStateV1{
UserAddress: client.GetUserAddress(),
SessionKey: "0xSessionKey...",
Version: 1,
ApplicationIDs: []string{"app1"},
AppSessionIDs: []string{},
ExpiresAt: time.Now().Add(24 * time.Hour),
}
sig, err := client.SignSessionKeyState(state)
state.UserSig = sig
err = client.SubmitAppSessionKeyState(ctx, state)

states, err := client.GetLastAppKeyStates(ctx, userAddress, nil)
```

---

## Session Keys — Channels

```go
state := core.ChannelSessionKeyStateV1{
UserAddress: client.GetUserAddress(),
SessionKey: "0xSessionKey...",
Version: 1,
Assets: []string{"usdc", "weth"},
ExpiresAt: time.Now().Add(24 * time.Hour),
}
sig, err := client.SignChannelSessionKeyState(state)
state.UserSig = sig
err = client.SubmitChannelSessionKeyState(ctx, state)

states, err := client.GetLastChannelKeyStates(ctx, userAddress, nil)
```

---

## Utilities

```go
client.Close() // Close connection
client.WaitCh() // Connection monitor channel
client.SignState(state) // Sign a state (advanced)
client.GetUserAddress() // Get signer's address
client.SetHomeBlockchain(asset, chainID) // Set default blockchain
```

---

## Types

```go
// Core types
core.State // Channel state
core.Channel // Channel info
core.Transition // State transition
core.Transaction // Transaction record
core.Asset // Asset info
core.Blockchain // Blockchain info
core.ChannelSessionKeyStateV1 // Channel session key state

// App types
app.AppV1 // Application definition
app.AppInfoV1 // Application info with timestamps
app.AppSessionInfoV1 // Session info
app.AppDefinitionV1 // Session definition
app.AppStateUpdateV1 // Session update
app.AppSessionKeyStateV1 // App session key state
```
156 changes: 156 additions & 0 deletions docs/build/sdk/go/getting-started.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
---
title: Getting Started
description: Install and set up the Clearnode Go SDK
sidebar_position: 1
---

# Getting Started with the Go SDK

Go SDK for Clearnode payment channels providing both high-level and low-level operations in a unified client. It has full feature parity with the TypeScript SDK.

## Requirements

- Go 1.21+
- Running Clearnode instance
- Blockchain RPC endpoint (for `Checkpoint` settlement)

## Installation

```bash
go get github.com/layer-3/nitrolite/sdk/go
```

## Quick Start

```go
package main

import (
"context"
"fmt"
"github.com/layer-3/nitrolite/pkg/core"
"github.com/layer-3/nitrolite/pkg/sign"
sdk "github.com/layer-3/nitrolite/sdk/go"
"github.com/shopspring/decimal"
)

func main() {
// 1. Create signers from private key
msgSigner, _ := sign.NewEthereumMsgSigner(privateKeyHex)
stateSigner, _ := core.NewChannelDefaultSigner(msgSigner)
txSigner, _ := sign.NewEthereumRawSigner(privateKeyHex)

// 2. Create unified client
client, _ := sdk.NewClient(
"wss://clearnode.example.com/ws",
stateSigner,
txSigner,
sdk.WithBlockchainRPC(80002, "https://polygon-amoy.alchemy.com/v2/KEY"),
)
defer client.Close()

ctx := context.Background()

// 3. Build and co-sign states off-chain
state, _ := client.Deposit(ctx, 80002, "usdc", decimal.NewFromInt(100))
fmt.Printf("Deposit state version: %d\n", state.Version)

// 4. Settle on-chain via Checkpoint
txHash, _ := client.Checkpoint(ctx, "usdc")
fmt.Printf("On-chain tx: %s\n", txHash)

// 5. Transfer (off-chain only)
state, _ = client.Transfer(ctx, "0xRecipient...", "usdc", decimal.NewFromInt(50))

// 6. Low-level operations on the same client
config, _ := client.GetConfig(ctx)
balances, _ := client.GetBalances(ctx, client.GetUserAddress())
}
```

## Creating a Client

```go
// Step 1: Create signers
msgSigner, err := sign.NewEthereumMsgSigner("0x1234...")
stateSigner, err := core.NewChannelDefaultSigner(msgSigner)
txSigner, err := sign.NewEthereumRawSigner("0x1234...")

// Step 2: Create unified client
client, err := sdk.NewClient(
wsURL,
stateSigner, // core.ChannelSigner for channel states
txSigner, // sign.Signer for blockchain transactions
sdk.WithBlockchainRPC(chainID, rpcURL),
sdk.WithHandshakeTimeout(10*time.Second),
sdk.WithPingInterval(5*time.Second),
)

// Step 3: (Optional) Set home blockchain for assets
err = client.SetHomeBlockchain("usdc", 80002)
```

## Channel Signers

The Go SDK wraps raw signers with a `ChannelSigner` interface that prepends a type byte to every signature:

| Type | Byte | Struct | Usage |
|------|------|--------|-------|
| Default | `0x00` | `core.ChannelDefaultSigner` | Main wallet signs directly |
| Session Key | `0x01` | `core.ChannelSessionKeySignerV1` | Delegated session key |

```go
// Default signer (wraps EthereumMsgSigner with 0x00 prefix)
msgSigner, _ := sign.NewEthereumMsgSigner(privateKeyHex)
channelSigner, _ := core.NewChannelDefaultSigner(msgSigner)
client, _ := sdk.NewClient(wsURL, channelSigner, txSigner, opts...)
```

## Key Concepts

### Two-Step Pattern

```go
// Step 1: Build and co-sign state off-chain
state, _ := client.Deposit(ctx, 80002, "usdc", decimal.NewFromInt(100))

// Step 2: Settle on-chain (when needed)
txHash, _ := client.Checkpoint(ctx, "usdc")
```

### Channel Lifecycle

1. **Void** — No channel exists
2. **Create** — `Deposit()` creates channel on-chain via `Checkpoint()`
3. **Open** — Channel active; can deposit, withdraw, transfer
4. **Challenged** — Dispute initiated
5. **Closed** — Channel finalized

## Configuration Options

```go
sdk.WithBlockchainRPC(chainID, rpcURL) // Required for Checkpoint
sdk.WithHandshakeTimeout(duration) // Default: 5s
sdk.WithPingInterval(duration) // Default: 5s
sdk.WithErrorHandler(func(error)) // Connection error handler
```

## Error Handling

```go
state, err := client.Deposit(ctx, 80002, "usdc", amount)
if err != nil {
log.Printf("State error: %v", err)
}

txHash, err := client.Checkpoint(ctx, "usdc")
if err != nil {
log.Printf("Checkpoint error: %v", err)
}
```

Common errors:
- `"home blockchain not set for asset"` — Missing `SetHomeBlockchain`
- `"blockchain RPC not configured for chain"` — Missing `WithBlockchainRPC`
- `"no channel exists for asset"` — `Checkpoint` without a co-signed state
- `"insufficient balance"` — Not enough funds in channel/wallet
49 changes: 49 additions & 0 deletions docs/build/sdk/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
---
title: SDK Overview
description: Yellow Network SDKs for building state channel applications
sidebar_position: 1
---

# SDK Overview

Yellow Network provides official SDKs for building applications on top of Nitrolite payment channels. All SDKs share the same two-step architecture: **build and co-sign states off-chain**, then **settle on-chain when needed**.

## Available SDKs

| Package | Language | Description |
|---------|----------|-------------|
| [`@yellow-org/sdk`](./typescript/getting-started) | TypeScript | Main SDK with full API coverage |
| [`@yellow-org/sdk-compat`](./typescript-compat/overview) | TypeScript | Compatibility layer for migrating from v0.5.3 |
| [`clearnode-go-sdk`](./go/getting-started) | Go | Go SDK with full feature parity |

## Architecture

All SDKs follow a unified design:

- **State Operations** (off-chain): `deposit()`, `withdraw()`, `transfer()`, `closeHomeChannel()`, `acknowledge()` — build and co-sign channel states without touching the blockchain.
- **Blockchain Settlement**: `checkpoint()` — the single entry point for all on-chain transactions. Routes to the correct contract method based on transition type and channel status.
- **Low-Level Operations**: Direct RPC access for app sessions, session keys, queries, and custom flows.

```mermaid
sequenceDiagram
participant App
participant SDK
participant Node as Clearnode
participant Chain as Blockchain

App->>SDK: deposit(chain, asset, amount)
SDK->>Node: Build & co-sign state
Node-->>SDK: Co-signed state
SDK-->>App: State object

App->>SDK: checkpoint(asset)
SDK->>Chain: Create/checkpoint/close channel
Chain-->>SDK: Transaction hash
SDK-->>App: tx hash
```

## Choosing an SDK

- **New TypeScript projects**: Use [`@yellow-org/sdk`](./typescript/getting-started) directly.
- **Migrating from v0.5.3**: Use [`@yellow-org/sdk-compat`](./typescript-compat/overview) to minimise code changes, then migrate to the main SDK at your own pace.
- **Go projects**: Use the [Go SDK](./go/getting-started) — it has full feature parity with the TypeScript SDK.
6 changes: 6 additions & 0 deletions docs/build/sdk/typescript-compat/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"label": "TypeScript Compat SDK",
"position": 3,
"collapsed": false,
"collapsible": false
}
Loading