embedded

package
v0.1.15 Latest Latest
Warning

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

Go to latest
Published: Apr 28, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package embedded provides client-side types for Zenon Network embedded contract APIs.

These types are designed for deserializing JSON-RPC responses from Zenon nodes. They include custom UnmarshalJSON implementations to properly convert string representations of big integers (as sent by the RPC protocol) into Go's *big.Int.

This follows the same pattern as the Dart SDK, which defines dedicated client-side types with fromJson factories rather than reusing server-side types.

Package embedded provides API interfaces for interacting with Zenon Network's embedded smart contracts. These protocol-level contracts handle core network functionality including staking, pillar management, token operations, plasma fusion, and more.

Embedded contracts are built into the Zenon Network protocol and provide essential functionality for network operations and governance. Each contract has a dedicated API that creates transaction templates for contract calls.

Available Embedded Contract APIs

Token Operations (TokenApi):

  • Issue new ZTS tokens
  • Mint and burn tokens
  • Update token properties

Staking (StakeApi):

  • Stake ZNN for network rewards
  • Cancel stake entries
  • Collect staking rewards

Plasma (PlasmaApi):

  • Fuse QSR for feeless transactions
  • Cancel plasma fusion
  • Query plasma availability

Pillar Operations (PillarApi):

  • Register network pillars
  • Update pillar information
  • Delegate to pillars

Sentinel Operations (SentinelApi):

  • Register sentinels
  • Revoke sentinels

Additional Contract APIs:

  • AcceleratorApi: Project funding and voting
  • BridgeApi: Cross-chain bridge operations
  • LiquidityApi: Liquidity provision
  • SwapApi: Token swaps
  • HTLCApi: Hash Time-Locked Contracts for atomic swaps
  • SporkApi: Network upgrades and governance

Basic Usage Pattern

All embedded contract methods follow the same pattern:

  1. Call the contract method to create a transaction template
  2. Sign and enhance the transaction with PoW/plasma
  3. Publish the transaction

Example - Staking ZNN:

// Create stake transaction template
template := client.StakeApi.Stake(
    durationInDays,
    amount,
)

// Sign and publish (implementation depends on your setup)
// See examples directory for complete workflows

Token Operations

Issue a new ZTS token:

template := client.TokenApi.IssueToken(
    "MyToken",           // token name
    "MTK",               // token symbol
    "example.com",       // domain
    totalSupply,         // total supply
    maxSupply,           // max supply
    8,                   // decimals
    true,                // mintable
    true,                // burnable
    false,               // utility
)

Plasma for Feeless Transactions

Fuse QSR to generate plasma for feeless transactions:

// Fuse 10 QSR
amount := big.NewInt(10 * 100000000) // 10 QSR in base units
template := client.PlasmaApi.Fuse(beneficiaryAddress, amount)

// Check required PoW for a transaction
difficulty, err := client.PlasmaApi.GetRequiredPoWForAccountBlock(accountBlock)

Pillar Delegation

Delegate weight to a pillar:

template := client.PillarApi.Delegate(pillarName)

// Undelegate
template = client.PillarApi.Undelegate()

Staking Workflow

Stake ZNN and collect rewards:

// Stake 100 ZNN for 30 days
amount := big.NewInt(100 * 100000000)
template := client.StakeApi.Stake(30, amount)

// Later, collect rewards
rewardTemplate := client.StakeApi.CollectReward()

Accelerator (Zenon Hyperspace)

Create and vote on funding projects:

template := client.AcceleratorApi.CreateProject(
    name,
    description,
    url,
    znnFundsNeeded,
    qsrFundsNeeded,
)

// Vote on project
voteTemplate := client.AcceleratorApi.VoteByProdAddress(
    projectId,
    voteOption,
)

Important Notes

- All methods return *nom.AccountBlock templates (unsigned transactions) - Templates must be signed with a keypair before submission - Most operations require PoW generation or fused plasma - Some operations have minimum requirements (e.g., pillar registration requires ZNN deposit) - Contract calls may fail if prerequisites aren't met (check embedded contract rules)

Transaction Requirements

Different operations require different amounts of PoW or plasma:

  • Simple transfers: Low PoW requirement
  • Contract calls: Higher PoW requirement
  • Token issuance: Requires ZNN burn and significant PoW

Use PlasmaApi.GetRequiredPoWForAccountBlock to check requirements before submitting.

For complete examples of embedded contract usage, see the examples directory.

For more information, see https://pkg.go.dev/github.com/0x3639/znn-sdk-go/api/embedded

Example (BurnTokens)

Example_burnTokens demonstrates burning tokens permanently.

package main

import (
	"fmt"
	"log"
	"math/big"

	"github.com/0x3639/znn-sdk-go/rpc_client"
	"github.com/zenon-network/go-zenon/common/types"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	// Token to burn (must be burnable)
	tokenZts := types.ParseZTSPanic("zts1your-token-standard")

	// Burn 500 tokens from your balance
	amount := big.NewInt(500 * 100000000)

	template := client.TokenApi.Burn(tokenZts, amount)

	fmt.Println("Token burn transaction created")
	fmt.Printf("Burning: %s tokens\n", amount)
	fmt.Printf("Token: %s\n", template.TokenStandard)
	fmt.Printf("Amount to burn: %s\n", template.Amount)

	// Burning reduces total supply permanently
	fmt.Println("\nWarning: Burning is irreversible!")

	// Note: You must have sufficient balance to burn
}
Example (CancelExpiredStake)

Example_cancelExpiredStake demonstrates canceling a stake after expiration.

package main

import (
	"fmt"
	"log"
	"time"

	"github.com/0x3639/znn-sdk-go/rpc_client"
	"github.com/zenon-network/go-zenon/common/types"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	address := types.ParseAddressPanic("z1qqjnwjjpnue8xmmpanz6csze6tcmtzzdtfsww7")

	// Get stake entries
	stakes, err := client.StakeApi.GetEntriesByAddress(address, 0, 10)
	if err != nil {
		log.Fatal(err)
	}

	if stakes.Count == 0 {
		fmt.Println("No stakes to cancel")
		return
	}

	// Find expired stakes
	now := time.Now().Unix()
	expiredCount := 0

	fmt.Println("Checking for expired stakes...")
	for _, stake := range stakes.List {
		if stake.ExpirationTimestamp <= now {
			expiredCount++
			_ = client.StakeApi.Cancel(stake.Id)

			fmt.Printf("Canceling expired stake:\n")
			fmt.Printf("  Amount: %s ZNN\n", stake.Amount)
			fmt.Printf("  Expired: %v\n", time.Unix(stake.ExpirationTimestamp, 0))
			fmt.Printf("  ID: %s...\n", stake.Id.String()[:16])
		}
	}

	if expiredCount == 0 {
		fmt.Println("No expired stakes found")
		fmt.Println("All stakes are still locked")
	} else {
		fmt.Printf("\nCancellation transactions created: %d\n", expiredCount)
		fmt.Println("After confirmation, ZNN will return to balance")
	}
}
Example (CancelFusion)

Example_cancelFusion demonstrates canceling a plasma fusion to reclaim QSR.

package main

import (
	"fmt"
	"log"

	"github.com/0x3639/znn-sdk-go/rpc_client"
	"github.com/zenon-network/go-zenon/common/types"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	address := types.ParseAddressPanic("z1qqjnwjjpnue8xmmpanz6csze6tcmtzzdtfsww7")

	// Get fusion entries
	entries, err := client.PlasmaApi.GetEntriesByAddress(address, 0, 10)
	if err != nil {
		log.Fatal(err)
	}

	if entries.Count == 0 {
		fmt.Println("No fusions to cancel")
		return
	}

	// Cancel first entry (in practice, check if lock period expired)
	entry := entries.List[0]
	_ = client.PlasmaApi.Cancel(entry.Id)

	fmt.Println("Fusion cancellation transaction created")
	fmt.Printf("Canceling fusion ID: %s...\n", entry.Id.String()[:16])
	fmt.Printf("Will reclaim: %s QSR\n", entry.QsrAmount)

	// Note: Must wait for lock period to expire before canceling
	// Plasma will be deducted when fusion is canceled
}
Example (CheckDelegation)

Example_checkDelegation demonstrates checking your current delegation.

package main

import (
	"fmt"
	"log"

	"github.com/0x3639/znn-sdk-go/rpc_client"
	"github.com/zenon-network/go-zenon/common/types"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	address := types.ParseAddressPanic("z1qqjnwjjpnue8xmmpanz6csze6tcmtzzdtfsww7")

	// Get current delegation
	delegation, err := client.PillarApi.GetDelegatedPillar(address)
	if err != nil {
		log.Fatal(err)
	}

	if delegation.Name != "" {
		fmt.Printf("Currently delegated to: %s\n", delegation.Name)
		fmt.Println("Earning delegation rewards")
	} else {
		fmt.Println("Not delegated to any Pillar")
		fmt.Println("Tip: Delegate to earn rewards")
	}
}
Example (CheckPillarNameAvailability)

Example_checkPillarNameAvailability demonstrates checking if a name is available.

package main

import (
	"fmt"
	"log"

	"github.com/0x3639/znn-sdk-go/rpc_client"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	name := "MyNewPillar"

	// Check if name is available
	available, err := client.PillarApi.CheckNameAvailability(name)
	if err != nil {
		log.Fatal(err)
	}

	if *available {
		fmt.Printf("Name '%s' is available\n", name)
		fmt.Println("You can register a Pillar with this name")
	} else {
		fmt.Printf("Name '%s' is already taken\n", name)
		fmt.Println("Choose a different name")
	}
}
Example (CheckPillarRewards)

Example_checkPillarRewards demonstrates checking Pillar operator rewards.

package main

import (
	"fmt"
	"log"

	"github.com/0x3639/znn-sdk-go/rpc_client"
	"github.com/zenon-network/go-zenon/common/types"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	pillarAddress := types.ParseAddressPanic("z1qqjnwjjpnue8xmmpanz6csze6tcmtzzdtfsww7")

	// Get uncollected rewards
	rewards, err := client.PillarApi.GetUncollectedReward(pillarAddress)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Pillar Operator Rewards")
	fmt.Printf("Uncollected ZNN: %s\n", rewards.ZnnAmount)
	fmt.Printf("Uncollected QSR: %s\n", rewards.QsrAmount)
}
Example (CheckPlasma)

Example_checkPlasma demonstrates checking plasma availability for an address.

package main

import (
	"fmt"
	"log"

	"github.com/0x3639/znn-sdk-go/rpc_client"
	"github.com/zenon-network/go-zenon/common/types"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	address := types.ParseAddressPanic("z1qqjnwjjpnue8xmmpanz6csze6tcmtzzdtfsww7")

	// Get plasma info
	plasmaInfo, err := client.PlasmaApi.Get(address)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Current Plasma: %d\n", plasmaInfo.CurrentPlasma)
	fmt.Printf("Max Plasma: %d\n", plasmaInfo.MaxPlasma)
	fmt.Printf("QSR Fused: %s\n", plasmaInfo.QsrAmount)

	if plasmaInfo.CurrentPlasma > 0 {
		fmt.Println("Has plasma for feeless transactions")
	} else {
		fmt.Println("No plasma - PoW required for transactions")
	}
}
Example (CheckRequiredPoW)

Example_checkRequiredPoW demonstrates checking PoW requirements for a transaction.

package main

import (
	"fmt"
	"log"
	"math/big"

	"github.com/0x3639/znn-sdk-go/rpc_client"
	"github.com/zenon-network/go-zenon/common/types"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	// Create a sample transaction template
	template := client.LedgerApi.SendTemplate(
		types.ParseAddressPanic("z1qqga8s8rkypgsg5qg2g7rp68nqh3r4lkm54tta"),
		types.ZnnTokenStandard,
		big.NewInt(100000000), // 1 ZNN
		[]byte{},
	)

	// Check required PoW (would need proper param structure in practice)
	fmt.Println("Checking PoW requirements for transaction")
	fmt.Printf("Transaction to: %s\n", template.ToAddress)
	fmt.Printf("Amount: %s\n", template.Amount)

	// In practice, you would:
	// 1. Get plasma info
	// 2. Call GetRequiredPoWForAccountBlock with proper params
	// 3. Generate PoW if needed or use plasma
	fmt.Println("PoW check determines if transaction can be feeless")
}
Example (CheckSentinelInfo)

Example_checkSentinelInfo demonstrates querying Sentinel information.

package main

import (
	"fmt"
	"log"

	"github.com/0x3639/znn-sdk-go/rpc_client"
	"github.com/zenon-network/go-zenon/common/types"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	sentinelOwner := types.ParseAddressPanic("z1qqjnwjjpnue8xmmpanz6csze6tcmtzzdtfsww7")

	// Get sentinel info
	sentinel, err := client.SentinelApi.GetByOwner(sentinelOwner)
	if err != nil {
		log.Fatal(err)
	}

	if sentinel.Owner.String() != "z1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqsggv2f" {
		fmt.Printf("Sentinel Owner: %s\n", sentinel.Owner)
		fmt.Printf("Revocable: %t\n", sentinel.IsRevocable)
		fmt.Printf("Registration: Momentum %d\n", sentinel.RegistrationTimestamp)
		fmt.Printf("Active: %t\n", sentinel.Active)
	} else {
		fmt.Println("No Sentinel registered for this address")
	}
}
Example (CheckSentinelRewards)

Example_checkSentinelRewards demonstrates checking Sentinel rewards.

package main

import (
	"fmt"
	"log"
	"math/big"

	"github.com/0x3639/znn-sdk-go/rpc_client"
	"github.com/zenon-network/go-zenon/common/types"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	sentinelOwner := types.ParseAddressPanic("z1qqjnwjjpnue8xmmpanz6csze6tcmtzzdtfsww7")

	// Get uncollected rewards
	rewards, err := client.SentinelApi.GetUncollectedReward(sentinelOwner)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Sentinel Rewards")
	fmt.Printf("Uncollected ZNN: %s\n", rewards.ZnnAmount)
	fmt.Printf("Uncollected QSR: %s\n", rewards.QsrAmount)

	if rewards.ZnnAmount.Cmp(big.NewInt(0)) > 0 || rewards.QsrAmount.Cmp(big.NewInt(0)) > 0 {
		fmt.Println("\nRewards available for collection!")
	}
}
Example (CheckTokenProperties)

Example_checkTokenProperties demonstrates inspecting token details.

package main

import (
	"fmt"
	"log"
	"math/big"

	"github.com/0x3639/znn-sdk-go/rpc_client"
	"github.com/zenon-network/go-zenon/common/types"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	// Check QSR token properties
	token, err := client.TokenApi.GetByZts(types.QsrTokenStandard)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Token Analysis: %s (%s)\n", token.Name, token.Symbol)
	fmt.Println("----------------------------------------")

	// Supply information
	fmt.Println("\nSupply:")
	fmt.Printf("  Current: %s\n", token.TotalSupply)
	fmt.Printf("  Maximum: %s\n", token.MaxSupply)

	// Calculate utilization
	if token.MaxSupply.Cmp(big.NewInt(0)) > 0 {
		utilization := new(big.Int).Mul(token.TotalSupply, big.NewInt(100))
		utilization.Div(utilization, token.MaxSupply)
		fmt.Printf("  Utilization: %s%%\n", utilization)
	}

	// Properties
	fmt.Println("\nProperties:")
	fmt.Printf("  Decimals: %d\n", token.Decimals)
	fmt.Printf("  Mintable: %t\n", token.IsMintable)
	fmt.Printf("  Burnable: %t\n", token.IsBurnable)
	fmt.Printf("  Utility: %t\n", token.IsUtility)

	// Ownership
	fmt.Println("\nOwnership:")
	fmt.Printf("  Owner: %s\n", token.Owner)
	fmt.Printf("  Domain: %s\n", token.Domain)

	// Capabilities
	fmt.Println("\nCapabilities:")
	if token.IsMintable {
		fmt.Println("  - Owner can mint additional supply")
	}
	if token.IsBurnable {
		fmt.Println("  - Holders can burn tokens")
	}
	if !token.IsMintable && !token.IsBurnable {
		fmt.Println("  - Token is immutable (fixed supply)")
	}
}
Example (CheckUncollectedRewards)

Example_checkUncollectedRewards demonstrates checking pending staking rewards.

package main

import (
	"fmt"
	"log"
	"math/big"

	"github.com/0x3639/znn-sdk-go/rpc_client"
	"github.com/zenon-network/go-zenon/common/types"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	address := types.ParseAddressPanic("z1qqjnwjjpnue8xmmpanz6csze6tcmtzzdtfsww7")

	// Get uncollected rewards
	rewards, err := client.StakeApi.GetUncollectedReward(address)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Uncollected Rewards:\n")
	fmt.Printf("  ZNN: %s\n", rewards.ZnnAmount)
	fmt.Printf("  QSR: %s\n", rewards.QsrAmount)

	// Check if rewards are available to collect
	if rewards.ZnnAmount.Cmp(big.NewInt(0)) > 0 || rewards.QsrAmount.Cmp(big.NewInt(0)) > 0 {
		fmt.Println("\nRewards available for collection!")
	} else {
		fmt.Println("\nNo rewards to collect yet")
	}
}
Example (CollectPillarRewards)

Example_collectPillarRewards demonstrates collecting Pillar rewards.

package main

import (
	"fmt"
	"log"

	"github.com/0x3639/znn-sdk-go/rpc_client"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	// Create reward collection transaction
	_ = client.PillarApi.CollectReward()

	fmt.Println("Pillar reward collection transaction created")
	fmt.Println("Collects both ZNN and QSR rewards")
	fmt.Println("\nReward sources:")
	fmt.Println("- Block production rewards")
	fmt.Println("- Delegation rewards")
	fmt.Println("- Momentum production participation")
}
Example (CollectRewards)

Example_collectRewards demonstrates claiming accumulated rewards.

package main

import (
	"fmt"
	"log"
	"math/big"

	"github.com/0x3639/znn-sdk-go/rpc_client"
	"github.com/zenon-network/go-zenon/common/types"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	address := types.ParseAddressPanic("z1qqjnwjjpnue8xmmpanz6csze6tcmtzzdtfsww7")

	// Check uncollected rewards first
	rewards, err := client.StakeApi.GetUncollectedReward(address)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Reward Collection")
	fmt.Printf("Uncollected ZNN: %s\n", rewards.ZnnAmount)
	fmt.Printf("Uncollected QSR: %s\n", rewards.QsrAmount)

	// Only collect if rewards are available
	if rewards.ZnnAmount.Cmp(big.NewInt(0)) > 0 || rewards.QsrAmount.Cmp(big.NewInt(0)) > 0 {
		_ = client.StakeApi.CollectReward()

		fmt.Println("\nReward collection transaction created")
		fmt.Println("After confirmation:")
		fmt.Println("- Rewards will be added to your balance")
		fmt.Println("- Uncollected amount resets to 0")
		fmt.Println("- New rewards continue accruing")
	} else {
		fmt.Println("\nNo rewards to collect yet")
		fmt.Println("Tip: Wait for rewards to accumulate before collecting")
	}
}
Example (CollectSentinelRewards)

Example_collectSentinelRewards demonstrates collecting Sentinel rewards.

package main

import (
	"fmt"
	"log"

	"github.com/0x3639/znn-sdk-go/rpc_client"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	// Create reward collection transaction
	_ = client.SentinelApi.CollectReward()

	fmt.Println("Sentinel reward collection transaction created")
	fmt.Println("Collects both ZNN and QSR rewards")
	fmt.Println("\nSentinel rewards come from:")
	fmt.Println("- Network infrastructure participation")
	fmt.Println("- Protocol-level reward distribution")
}
Example (CompoundRewards)

Example_compoundRewards demonstrates collecting and restaking rewards.

package main

import (
	"fmt"
	"log"
	"math/big"

	"github.com/0x3639/znn-sdk-go/rpc_client"
	"github.com/zenon-network/go-zenon/common/types"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	address := types.ParseAddressPanic("z1qqjnwjjpnue8xmmpanz6csze6tcmtzzdtfsww7")

	// Check uncollected rewards
	rewards, err := client.StakeApi.GetUncollectedReward(address)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Compound Staking Strategy")
	fmt.Printf("Uncollected ZNN: %s\n", rewards.ZnnAmount)
	fmt.Printf("Uncollected QSR: %s\n", rewards.QsrAmount)

	minStake := big.NewInt(100000000) // 1 ZNN minimum

	if rewards.ZnnAmount.Cmp(minStake) >= 0 {
		fmt.Println("\nStep 1: Collect rewards")
		_ = client.StakeApi.CollectReward()

		fmt.Println("Step 2: Restake collected ZNN")
		_ = client.StakeApi.Stake(31536000, rewards.ZnnAmount)

		fmt.Println("\nCompounding benefits:")
		fmt.Println("- Rewards earn rewards")
		fmt.Println("- Exponential growth over time")
		fmt.Println("- Maximizes long-term returns")
		fmt.Println("- Best for multi-year holders")
	} else {
		fmt.Printf("\nNot enough ZNN to compound yet")
		fmt.Printf("Minimum stake: %s ZNN\n", minStake)
		fmt.Println("Continue accumulating rewards")
	}
}
Example (CreateAcceleratorProject)

Example_createAcceleratorProject demonstrates submitting a new project proposal.

package main

import (
	"fmt"
	"log"
	"math/big"

	"github.com/0x3639/znn-sdk-go/rpc_client"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	// Project details
	name := "My Ecosystem Project"
	description := "Building a tool to enhance the Zenon ecosystem..."
	url := "https://myproject.com"

	// Funding request
	znnNeeded := big.NewInt(5000 * 100000000)  // 5,000 ZNN
	qsrNeeded := big.NewInt(50000 * 100000000) // 50,000 QSR

	_ = client.AcceleratorApi.CreateProject(
		name,
		description,
		url,
		znnNeeded,
		qsrNeeded,
	)

	fmt.Println("Accelerator Project Created")
	fmt.Printf("Name: %s\n", name)
	fmt.Printf("Requesting: %s ZNN, %s QSR\n", znnNeeded, qsrNeeded)
	fmt.Println("\nNext steps:")
	fmt.Println("1. Wait for Pillar voting period")
	fmt.Println("2. If approved, add project phases")
	fmt.Println("3. Complete milestones to receive funding")
}
Example (DelegateToPillar)

Example_delegateToP illar demonstrates delegating to a Pillar.

package main

import (
	"fmt"
	"log"

	"github.com/0x3639/znn-sdk-go/rpc_client"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	pillarName := "MyFavoritePillar"

	// Create delegation transaction
	_ = client.PillarApi.Delegate(pillarName)

	fmt.Println("Delegation transaction created")
	fmt.Printf("Delegating to: %s\n", pillarName)
	fmt.Println("\nBenefits:")
	fmt.Println("- Earn rewards from pillar")
	fmt.Println("- Support network decentralization")
	fmt.Println("- ZNN stays in your wallet")
	fmt.Println("- Can change delegation anytime")
}
Example (DepositQsrForSentinel)

Example_depositQsrForSentinel demonstrates depositing QSR for a Sentinel.

package main

import (
	"fmt"
	"log"
	"math/big"

	"github.com/0x3639/znn-sdk-go/rpc_client"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	// Deposit 10,000 QSR
	amount := big.NewInt(10000 * 100000000)

	_ = client.SentinelApi.DepositQsr(amount)

	fmt.Println("QSR Deposit Transaction Created")
	fmt.Printf("Depositing: %s QSR\n", amount)
	fmt.Println("\nDeposit benefits:")
	fmt.Println("- Increase Sentinel rewards weight")
	fmt.Println("- Strengthen network participation")
	fmt.Println("- Can withdraw after lock period")
}
Example (DiversifiedStaking)

Example_diversifiedStaking demonstrates creating multiple stakes.

package main

import (
	"fmt"
	"log"
	"math/big"

	"github.com/0x3639/znn-sdk-go/rpc_client"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	fmt.Println("Diversified Staking Strategy")
	fmt.Println("Creating multiple stakes with different durations:")

	// Short-term stake (1 month)
	_ = client.StakeApi.Stake(2592000, big.NewInt(100*100000000))
	fmt.Println("1. Short-term: 100 ZNN for 1 month")
	fmt.Println("   - Quick liquidity return")

	// Medium-term stake (6 months)
	_ = client.StakeApi.Stake(15552000, big.NewInt(300*100000000))
	fmt.Println("\n2. Medium-term: 300 ZNN for 6 months")
	fmt.Println("   - Balanced rewards/liquidity")

	// Long-term stake (12 months)
	_ = client.StakeApi.Stake(31536000, big.NewInt(600*100000000))
	fmt.Println("\n3. Long-term: 600 ZNN for 12 months")
	fmt.Println("   - Maximum rewards")

	fmt.Println("\nBenefits:")
	fmt.Println("- Staggered expiration dates")
	fmt.Println("- Risk diversification")
	fmt.Println("- Regular liquidity events")
	fmt.Println("- Optimized reward/flexibility balance")
}
Example (DonateToAccelerator)

Example_donateToAccelerator demonstrates donating to the Accelerator fund.

package main

import (
	"fmt"
	"log"
	"math/big"

	"github.com/0x3639/znn-sdk-go/rpc_client"
	"github.com/zenon-network/go-zenon/common/types"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	// Donate 100 ZNN to Accelerator
	amount := big.NewInt(100 * 100000000)

	_ = client.AcceleratorApi.Donate(amount, types.ZnnTokenStandard)

	fmt.Println("Accelerator Donation")
	fmt.Printf("Amount: %s ZNN\n", amount)
	fmt.Println("\nDonations support ecosystem development")
	fmt.Println("Funds are used for approved projects")
}
Example (FinalizeToken)

Example_finalizeToken demonstrates making a token immutable.

package main

import (
	"fmt"
	"log"

	"github.com/0x3639/znn-sdk-go/rpc_client"
	"github.com/zenon-network/go-zenon/common/types"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	myTokenZts := types.ParseZTSPanic("zts1your-token-standard")
	myAddress := types.ParseAddressPanic("z1qqjnwjjpnue8xmmpanz6csze6tcmtzzdtfsww7")

	// Disable minting to finalize supply
	_ = client.TokenApi.UpdateToken(
		myTokenZts,
		myAddress, // keep same owner
		false,     // disable minting permanently
		true,      // keep burning enabled
	)

	fmt.Println("Token finalization transaction created")
	fmt.Println("Minting will be permanently disabled")
	fmt.Println("Supply becomes fixed after confirmation")

	// Warning: This is permanent and cannot be undone!
	fmt.Println("\nAfter confirmation:")
	fmt.Println("- No more tokens can be minted")
	fmt.Println("- Supply is capped at current total")
	fmt.Println("- Change is irreversible")
}
Example (FuseForAnotherAddress)

Example_fuseForAnotherAddress demonstrates fusing QSR for a different address.

package main

import (
	"fmt"
	"log"
	"math/big"

	"github.com/0x3639/znn-sdk-go/rpc_client"
	"github.com/zenon-network/go-zenon/common/types"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	// Sender pays QSR, beneficiary gets plasma
	beneficiary := types.ParseAddressPanic("z1qqga8s8rkypgsg5qg2g7rp68nqh3r4lkm54tta")
	amount := big.NewInt(20 * 100000000) // 20 QSR

	template := client.PlasmaApi.Fuse(beneficiary, amount)

	fmt.Println("Fusing QSR for another address")
	fmt.Printf("Beneficiary will receive plasma: %s\n", beneficiary)
	fmt.Printf("Amount: %s QSR\n", template.Amount)

	// Useful for:
	// - Setting up new accounts with plasma
	// - Gifting plasma to others
	// - Service providers funding client accounts
}
Example (FuseQSR)

Example_fuseQSR demonstrates creating a plasma fusion transaction.

package main

import (
	"fmt"
	"log"
	"math/big"

	"github.com/0x3639/znn-sdk-go/rpc_client"
	"github.com/zenon-network/go-zenon/common/types"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	myAddress := types.ParseAddressPanic("z1qqjnwjjpnue8xmmpanz6csze6tcmtzzdtfsww7")

	// Fuse 10 QSR for plasma
	amount := big.NewInt(10 * 100000000) // 10 QSR in base units

	template := client.PlasmaApi.Fuse(myAddress, amount)

	fmt.Println("Plasma fusion transaction created")
	fmt.Printf("Fusing %s QSR\n", template.Amount)
	fmt.Printf("Beneficiary: %s\n", myAddress)
	fmt.Println("Token: QSR")

	// Note: Template must be autofilled, enhanced with PoW, signed, and published
	// First fusion requires PoW since you don't have plasma yet
}
Example (GetOwnedPillars)

Example_getOwnedPillars demonstrates listing Pillars owned by an address.

package main

import (
	"fmt"
	"log"

	"github.com/0x3639/znn-sdk-go/rpc_client"
	"github.com/zenon-network/go-zenon/common/types"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	owner := types.ParseAddressPanic("z1qqjnwjjpnue8xmmpanz6csze6tcmtzzdtfsww7")

	// Get pillars owned by address
	pillars, err := client.PillarApi.GetByOwner(owner)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Pillars owned: %d\n", len(pillars))

	if len(pillars) > 0 {
		for _, pillar := range pillars {
			fmt.Printf("- %s (Weight: %s)\n", pillar.Name, pillar.Weight)
		}
	} else {
		fmt.Println("No pillars owned by this address")
	}
}
Example (GetPillarByName)

Example_getPillarByName demonstrates querying specific Pillar details.

package main

import (
	"fmt"
	"log"

	"github.com/0x3639/znn-sdk-go/rpc_client"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	pillarName := "MyPillar"

	// Get pillar info
	pillar, err := client.PillarApi.GetByName(pillarName)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Pillar: %s\n", pillar.Name)
	fmt.Printf("Owner: %s\n", pillar.OwnerAddress)
	fmt.Printf("Producer: %s\n", pillar.ProducerAddress)
	fmt.Printf("Reward: %s\n", pillar.WithdrawAddress)
	fmt.Printf("Weight: %s\n", pillar.Weight)
	fmt.Printf("Give Momentum Reward: %d%%\n", pillar.GiveMomentumRewardPercentage)
	fmt.Printf("Give Delegation Reward: %d%%\n", pillar.GiveDelegateRewardPercentage)
}
Example (GetProjectVoteBreakdown)

Example_getProjectVoteBreakdown demonstrates checking vote results.

package main

import (
	"fmt"
	"log"

	"github.com/0x3639/znn-sdk-go/rpc_client"
	"github.com/zenon-network/go-zenon/common/types"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	projectId := types.HexToHashPanic("0x123...")

	// Get vote breakdown
	breakdown, err := client.AcceleratorApi.GetVoteBreakdown(projectId)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Vote Breakdown for Project\n")
	fmt.Printf("ID: %s\n\n", projectId)
	fmt.Printf("Yes votes: %d\n", breakdown.Yes)
	fmt.Printf("No votes: %d\n", breakdown.No)
	fmt.Printf("Total votes: %d\n", breakdown.Total)
}
Example (IssueFixedSupplyToken)

Example_issueFixedSupplyToken demonstrates creating a token with fixed supply.

package main

import (
	"fmt"
	"log"
	"math/big"

	"github.com/0x3639/znn-sdk-go/rpc_client"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	// Fixed supply: 21M tokens (like Bitcoin)
	supply := big.NewInt(21000000 * 100000000)

	template := client.TokenApi.IssueToken(
		"Fixed Token",
		"FTK",
		"",
		supply, // total supply
		supply, // max = total (fixed)
		8,
		false, // NOT mintable
		false, // NOT burnable
		false,
	)

	fmt.Println("Fixed supply token created")
	fmt.Printf("Total supply: %s (immutable)\n", supply)
	fmt.Printf("Cost: %s %s\n", template.Amount, template.TokenStandard)
	fmt.Println("No minting or burning allowed")

	// This token's supply cannot change after issuance
}
Example (IssueToken)

Example_issueToken demonstrates creating a new ZTS token.

package main

import (
	"fmt"
	"log"
	"math/big"

	"github.com/0x3639/znn-sdk-go/rpc_client"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	// Token parameters
	tokenName := "My Token"
	tokenSymbol := "MTK"
	tokenDomain := "example.com"

	// Initial supply: 1M tokens with 8 decimals
	totalSupply := big.NewInt(1000000 * 100000000)
	// Max supply: 10M tokens
	maxSupply := big.NewInt(10000000 * 100000000)

	// Create token issuance template
	template := client.TokenApi.IssueToken(
		tokenName,
		tokenSymbol,
		tokenDomain,
		totalSupply,
		maxSupply,
		8,     // decimals
		true,  // mintable
		true,  // burnable
		false, // not utility token
	)

	fmt.Println("Token issuance transaction created")
	fmt.Printf("Token: %s (%s)\n", tokenName, tokenSymbol)
	fmt.Printf("Initial supply: %s\n", totalSupply)
	fmt.Printf("Maximum supply: %s\n", maxSupply)
	fmt.Println("Properties: Mintable, Burnable")
	fmt.Printf("Cost: 1 ZNN (to %s)\n", template.ToAddress)

	// Note: Template must be autofilled, enhanced with PoW, signed, and published
	// Token ZTS will be generated after confirmation
}
Example (ListAcceleratorProjects)

Example_listAcceleratorProjects demonstrates listing all Accelerator-Z projects.

package main

import (
	"fmt"
	"log"

	"github.com/0x3639/znn-sdk-go/rpc_client"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	// Get all projects
	projects, err := client.AcceleratorApi.GetAll(0, 25)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Total Accelerator Projects: %d\n\n", projects.Count)

	for i, project := range projects.List {
		fmt.Printf("%d. %s\n", i+1, project.Name)
		fmt.Printf("   Owner: %s\n", project.Owner)
		fmt.Printf("   Status: %d\n", project.Status)
		fmt.Printf("   ZNN Requested: %s\n", project.ZnnFundsNeeded)
		fmt.Printf("   QSR Requested: %s\n", project.QsrFundsNeeded)
	}
}
Example (ListActiveSentinels)

Example_listActiveSentinels demonstrates listing all active Sentinels.

package main

import (
	"fmt"
	"log"

	"github.com/0x3639/znn-sdk-go/rpc_client"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	// Get all active sentinels
	sentinels, err := client.SentinelApi.GetAllActive(0, 50)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Active Sentinels: %d\n\n", sentinels.Count)

	for i, sentinel := range sentinels.List {
		fmt.Printf("%d. Owner: %s\n", i+1, sentinel.Owner)
		fmt.Printf("   Registration: Momentum %d\n", sentinel.RegistrationTimestamp)
		fmt.Printf("   Active: %t\n", sentinel.Active)
	}
}
Example (ListAllPillars)

Example_listAllPillars demonstrates listing all network Pillars.

package main

import (
	"fmt"
	"log"

	"github.com/0x3639/znn-sdk-go/rpc_client"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	// Get all pillars
	pillars, err := client.PillarApi.GetAll(0, 50)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Total Pillars: %d\n\n", pillars.Count)

	for i, pillar := range pillars.List {
		fmt.Printf("%d. %s\n", i+1, pillar.Name)
		fmt.Printf("   Weight: %s\n", pillar.Weight)
		fmt.Printf("   Rank: %d\n", pillar.Rank)
	}
}
Example (ListAllTokens)

Example_listAllTokens demonstrates listing all tokens on the network.

package main

import (
	"fmt"
	"log"

	"github.com/0x3639/znn-sdk-go/rpc_client"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	// Get first page of tokens
	tokens, err := client.TokenApi.GetAll(0, 25)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Total tokens: %d\n", tokens.Count)
	fmt.Println("\nTokens on network:")
	for i, token := range tokens.List {
		fmt.Printf("%d. %s (%s)\n", i+1, token.Name, token.Symbol)
		fmt.Printf("   ZTS: %s\n", token.TokenStandard)
		fmt.Printf("   Supply: %s / %s\n", token.TotalSupply, token.MaxSupply)
	}
}
Example (ListFusionEntries)

Example_listFusionEntries demonstrates listing all plasma fusions for an address.

package main

import (
	"fmt"
	"log"

	"github.com/0x3639/znn-sdk-go/rpc_client"
	"github.com/zenon-network/go-zenon/common/types"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	myAddress := types.ParseAddressPanic("z1qqjnwjjpnue8xmmpanz6csze6tcmtzzdtfsww7")

	// Get fusion entries
	entries, err := client.PlasmaApi.GetEntriesByAddress(myAddress, 0, 10)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Total fusion entries: %d\n", entries.Count)

	if entries.Count > 0 {
		fmt.Println("Active fusions:")
		for i, entry := range entries.List {
			fmt.Printf("%d. Amount: %s QSR, ID: %s...\n",
				i+1, entry.QsrAmount, entry.Id.String()[:16])
		}
	} else {
		fmt.Println("No active plasma fusions")
	}
}
Example (ListSporks)

Example_listSporks demonstrates viewing protocol sporks.

package main

import (
	"fmt"
	"log"

	"github.com/0x3639/znn-sdk-go/rpc_client"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	// Get all sporks
	sporks, err := client.SporkApi.GetAll(0, 10)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Protocol Sporks: %d\n\n", sporks.Count)

	for i, spork := range sporks.List {
		fmt.Printf("%d. %s\n", i+1, spork.Name)
		fmt.Printf("   ID: %s\n", spork.Id)
		fmt.Printf("   Activated: %t\n", spork.Activated)
	}

	fmt.Println("\nSporks enable protocol features without hard forks")
}
Example (ListStakeEntries)

Example_listStakeEntries demonstrates viewing all active stakes.

package main

import (
	"fmt"
	"log"
	"math/big"
	"time"

	"github.com/0x3639/znn-sdk-go/rpc_client"
	"github.com/zenon-network/go-zenon/common/types"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	address := types.ParseAddressPanic("z1qqjnwjjpnue8xmmpanz6csze6tcmtzzdtfsww7")

	// Get stake entries
	stakes, err := client.StakeApi.GetEntriesByAddress(address, 0, 10)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Active stakes: %d\n", stakes.Count)

	if stakes.Count > 0 {
		totalStaked := big.NewInt(0)
		now := time.Now().Unix()

		fmt.Println("\nStake details:")
		for i, stake := range stakes.List {
			totalStaked.Add(totalStaked, stake.Amount)
			expired := stake.ExpirationTimestamp <= now

			fmt.Printf("%d. Amount: %s ZNN\n", i+1, stake.Amount)
			fmt.Printf("   Expires: %v\n", time.Unix(stake.ExpirationTimestamp, 0))
			fmt.Printf("   Status: %s\n", map[bool]string{true: "Expired (can cancel)", false: "Active"}[expired])
		}

		fmt.Printf("\nTotal staked: %s ZNN\n", totalStaked)
	} else {
		fmt.Println("No active stakes")
	}
}
Example (ListTokensByOwner)

Example_listTokensByOwner demonstrates listing tokens owned by an address.

package main

import (
	"fmt"
	"log"

	"github.com/0x3639/znn-sdk-go/rpc_client"
	"github.com/zenon-network/go-zenon/common/types"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	ownerAddr := types.ParseAddressPanic("z1qqjnwjjpnue8xmmpanz6csze6tcmtzzdtfsww7")

	// Get tokens owned by address
	tokens, err := client.TokenApi.GetByOwner(ownerAddr, 0, 10)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Tokens owned by %s: %d\n", ownerAddr, tokens.Count)

	if tokens.Count > 0 {
		fmt.Println("\nOwned tokens:")
		for _, token := range tokens.List {
			fmt.Printf("- %s (%s)\n", token.Name, token.Symbol)
			fmt.Printf("  Can mint: %t, Can burn: %t\n", token.IsMintable, token.IsBurnable)
		}
	} else {
		fmt.Println("No tokens owned by this address")
	}
}
Example (MintTokens)

Example_mintTokens demonstrates minting additional tokens.

package main

import (
	"fmt"
	"log"
	"math/big"

	"github.com/0x3639/znn-sdk-go/rpc_client"
	"github.com/zenon-network/go-zenon/common/types"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	// Token to mint (must be mintable and you must be owner)
	myTokenZts := types.ParseZTSPanic("zts1your-token-standard")

	// Mint 1000 tokens
	amount := big.NewInt(1000 * 100000000)
	receiver := types.ParseAddressPanic("z1qqjnwjjpnue8xmmpanz6csze6tcmtzzdtfsww7")

	_ = client.TokenApi.Mint(myTokenZts, amount, receiver)

	fmt.Println("Token mint transaction created")
	fmt.Printf("Minting: %s tokens\n", amount)
	fmt.Printf("Receiver: %s\n", receiver)
	fmt.Printf("Token: %s\n", myTokenZts)

	// Note: Only token owner can mint
	// Must be processed through transaction pipeline and published
}
Example (QueryToken)

Example_queryToken demonstrates retrieving token information by ZTS.

package main

import (
	"fmt"
	"log"

	"github.com/0x3639/znn-sdk-go/rpc_client"
	"github.com/zenon-network/go-zenon/common/types"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	// Query ZNN token info
	token, err := client.TokenApi.GetByZts(types.ZnnTokenStandard)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Token: %s (%s)\n", token.Name, token.Symbol)
	fmt.Printf("Total Supply: %s\n", token.TotalSupply)
	fmt.Printf("Max Supply: %s\n", token.MaxSupply)
	fmt.Printf("Decimals: %d\n", token.Decimals)
	fmt.Printf("Owner: %s\n", token.Owner)
	fmt.Printf("Mintable: %t, Burnable: %t\n", token.IsMintable, token.IsBurnable)
}
Example (RegisterSentinel)

Example_registerSentinel demonstrates registering a new Sentinel.

package main

import (
	"fmt"
	"log"

	"github.com/0x3639/znn-sdk-go/rpc_client"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	// Create Sentinel registration transaction
	_ = client.SentinelApi.Register()

	fmt.Println("Sentinel Registration Transaction Created")
	fmt.Println("\nRequirements:")
	fmt.Println("- 5,000 ZNN (locked as collateral)")
	fmt.Println("- 50,000 QSR (locked as collateral)")
	fmt.Println("- Running Sentinel node infrastructure")

	fmt.Println("\nBenefits:")
	fmt.Println("- Earn ZNN and QSR rewards")
	fmt.Println("- Support network infrastructure")
	fmt.Println("- Lower barrier than Pillar")
	fmt.Println("- Full collateral return on revocation")
}
Example (RevokeSentinel)

Example_revokeSentinel demonstrates revoking a Sentinel.

package main

import (
	"fmt"
	"log"

	"github.com/0x3639/znn-sdk-go/rpc_client"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	// Create revocation transaction
	_ = client.SentinelApi.Revoke()

	fmt.Println("Sentinel Revocation Transaction Created")
	fmt.Println("\nRevocation process:")
	fmt.Println("- Sentinel stops participating")
	fmt.Println("- Collateral enters cooldown period")
	fmt.Println("- After cooldown: 5,000 ZNN returned")
	fmt.Println("- After cooldown: 50,000 QSR returned")

	fmt.Println("\nNote: Must wait for cooldown before collateral is released")
}
Example (StakeFor12Months)

Example_stakeFor12Months demonstrates staking for maximum rewards.

package main

import (
	"fmt"
	"log"
	"math/big"

	"github.com/0x3639/znn-sdk-go/rpc_client"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	// Stake 1000 ZNN for 12 months (maximum duration)
	amount := big.NewInt(1000 * 100000000)
	duration := int64(31536000) // 365 days in seconds

	_ = client.StakeApi.Stake(duration, amount)

	fmt.Println("12-Month Stake Created")
	fmt.Printf("Amount: %s ZNN\n", amount)
	fmt.Printf("Duration: %d seconds (365 days)\n", duration)

	fmt.Println("\nMaximum rewards strategy:")
	fmt.Println("- Highest reward multiplier")
	fmt.Println("- Best for long-term holders")
	fmt.Println("- Maximizes ZNN and QSR earnings")
	fmt.Println("- Requires commitment to 1-year lockup")

	// Note: ZNN will be locked for the full 12 months
}
Example (StakeFor1Month)

Example_stakeFor1Month demonstrates staking ZNN for 1 month.

package main

import (
	"fmt"
	"log"
	"math/big"

	"github.com/0x3639/znn-sdk-go/rpc_client"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	// Stake 100 ZNN for 1 month
	amount := big.NewInt(100 * 100000000)
	duration := int64(2592000) // 30 days in seconds

	template := client.StakeApi.Stake(duration, amount)

	fmt.Println("1-Month Stake Created")
	fmt.Printf("Amount: %s ZNN\n", amount)
	fmt.Printf("Duration: %d seconds (30 days)\n", duration)
	fmt.Printf("To: %s\n", template.ToAddress)

	fmt.Println("\nStake characteristics:")
	fmt.Println("- Shortest duration")
	fmt.Println("- Lowest reward multiplier")
	fmt.Println("- Fastest liquidity return")
	fmt.Println("- Good for testing or short-term holds")

	// Template must be autofilled, enhanced with PoW, signed, and published
}
Example (StakingDurationComparison)

Example_stakingDurationComparison demonstrates comparing different durations.

package main

import (
	"fmt"
	"log"
	"math/big"

	"github.com/0x3639/znn-sdk-go/rpc_client"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	amount := big.NewInt(1000 * 100000000) // 1000 ZNN

	fmt.Println("Staking Duration Comparison")
	fmt.Printf("Amount: %s ZNN\n\n", amount)

	durations := []struct {
		name    string
		seconds int64
		days    int
	}{
		{"1 Month", 2592000, 30},
		{"3 Months", 7776000, 90},
		{"6 Months", 15552000, 180},
		{"12 Months", 31536000, 365},
	}

	for i, d := range durations {
		_ = client.StakeApi.Stake(d.seconds, amount)

		fmt.Printf("%d. %s (%d days)\n", i+1, d.name, d.days)
		fmt.Printf("   Duration: %d seconds\n", d.seconds)
		fmt.Printf("   Liquidity: Returns after %d days\n", d.days)

		// Reward multiplier increases with duration
		multiplier := float64(d.days) / 30.0
		fmt.Printf("   Reward multiplier: ~%.1fx\n\n", multiplier)
	}

	fmt.Println("Selection guide:")
	fmt.Println("- Short term: Need liquidity, willing to accept lower rewards")
	fmt.Println("- Medium term: Balance of rewards and flexibility")
	fmt.Println("- Long term: Maximum rewards, committed to holding")
}
Example (TransferTokenOwnership)

Example_transferTokenOwnership demonstrates transferring token ownership.

package main

import (
	"fmt"
	"log"

	"github.com/0x3639/znn-sdk-go/rpc_client"
	"github.com/zenon-network/go-zenon/common/types"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	myTokenZts := types.ParseZTSPanic("zts1your-token-standard")
	newOwner := types.ParseAddressPanic("z1qqga8s8rkypgsg5qg2g7rp68nqh3r4lkm54tta")

	// Transfer ownership while keeping properties unchanged
	_ = client.TokenApi.UpdateToken(
		myTokenZts,
		newOwner,
		true, // keep mintable
		true, // keep burnable
	)

	fmt.Println("Token ownership transfer created")
	fmt.Printf("New owner: %s\n", newOwner)
	fmt.Println("Token properties unchanged")

	// New owner will control minting and further updates
}
Example (UndelegateFromPillar)

Example_undelegateFromPillar demonstrates removing delegation.

package main

import (
	"fmt"
	"log"

	"github.com/0x3639/znn-sdk-go/rpc_client"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	// Create undelegation transaction
	_ = client.PillarApi.Undelegate()

	fmt.Println("Undelegation transaction created")
	fmt.Println("\nAfter undelegation:")
	fmt.Println("- Stop earning pillar rewards")
	fmt.Println("- Voting weight returns to unallocated")
	fmt.Println("- Can delegate to different pillar")
	fmt.Println("- No cooldown period required")
}
Example (ViewRewardHistory)

Example_viewRewardHistory demonstrates checking reward collection history.

package main

import (
	"fmt"
	"log"
	"math/big"

	"github.com/0x3639/znn-sdk-go/rpc_client"
	"github.com/zenon-network/go-zenon/common/types"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	address := types.ParseAddressPanic("z1qqjnwjjpnue8xmmpanz6csze6tcmtzzdtfsww7")

	// Get reward history
	history, err := client.StakeApi.GetFrontierRewardByPage(address, 0, 25)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Reward Collection History\n")
	fmt.Printf("Total collections: %d\n\n", history.Count)

	if history.Count > 0 {
		totalZnn := big.NewInt(0)
		totalQsr := big.NewInt(0)

		for i, entry := range history.List {
			totalZnn.Add(totalZnn, entry.ZnnAmount)
			totalQsr.Add(totalQsr, entry.QsrAmount)

			fmt.Printf("%d. Collected at epoch %d\n", i+1, entry.Epoch)
			fmt.Printf("   ZNN: %s, QSR: %s\n", entry.ZnnAmount, entry.QsrAmount)
		}

		fmt.Printf("\nTotal rewards collected:\n")
		fmt.Printf("  ZNN: %s\n", totalZnn)
		fmt.Printf("  QSR: %s\n", totalQsr)
	} else {
		fmt.Println("No reward collections yet")
	}
}
Example (ViewSentinelRewardHistory)

Example_viewSentinelRewardHistory demonstrates viewing reward collection history.

package main

import (
	"fmt"
	"log"
	"math/big"

	"github.com/0x3639/znn-sdk-go/rpc_client"
	"github.com/zenon-network/go-zenon/common/types"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	sentinelOwner := types.ParseAddressPanic("z1qqjnwjjpnue8xmmpanz6csze6tcmtzzdtfsww7")

	// Get reward history
	history, err := client.SentinelApi.GetFrontierRewardByPage(sentinelOwner, 0, 25)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Reward Collection History: %d entries\n\n", history.Count)

	if history.Count > 0 {
		totalZnn := big.NewInt(0)
		totalQsr := big.NewInt(0)

		for i, entry := range history.List {
			totalZnn.Add(totalZnn, entry.ZnnAmount)
			totalQsr.Add(totalQsr, entry.QsrAmount)

			fmt.Printf("%d. Epoch %d\n", i+1, entry.Epoch)
			fmt.Printf("   ZNN: %s, QSR: %s\n", entry.ZnnAmount, entry.QsrAmount)
		}

		fmt.Printf("\nTotal collected:\n")
		fmt.Printf("  ZNN: %s\n", totalZnn)
		fmt.Printf("  QSR: %s\n", totalQsr)
	} else {
		fmt.Println("No reward collections yet")
	}
}
Example (VoteOnAcceleratorProject)

Example_voteOnAcceleratorProject demonstrates Pillar voting.

package main

import (
	"fmt"
	"log"

	"github.com/0x3639/znn-sdk-go/rpc_client"
	"github.com/zenon-network/go-zenon/common/types"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	projectId := types.HexToHashPanic("0x123...")
	pillarName := "MyPillar"

	// Vote yes on project
	_ = client.AcceleratorApi.VoteByName(projectId, pillarName, 1)

	fmt.Println("Vote Cast on Accelerator Project")
	fmt.Printf("Pillar: %s\n", pillarName)
	fmt.Printf("Project: %s\n", projectId)
	fmt.Println("Vote: YES")

	fmt.Println("\nVote options:")
	fmt.Println("  0 = Abstain")
	fmt.Println("  1 = Yes (approve)")
	fmt.Println("  2 = No (reject)")
}
Example (WithdrawQsrFromSentinel)

Example_withdrawQsrFromSentinel demonstrates withdrawing deposited QSR.

package main

import (
	"fmt"
	"log"
	"math/big"

	"github.com/0x3639/znn-sdk-go/rpc_client"
	"github.com/zenon-network/go-zenon/common/types"
)

func main() {
	client, err := rpc_client.NewRpcClient("ws://127.0.0.1:35998")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Stop()

	sentinelOwner := types.ParseAddressPanic("z1qqjnwjjpnue8xmmpanz6csze6tcmtzzdtfsww7")

	// Check deposited QSR first
	deposited, err := client.SentinelApi.GetDepositedQsr(sentinelOwner)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Deposited QSR: %s\n", deposited)

	if deposited.Cmp(big.NewInt(0)) > 0 {
		// Create withdrawal transaction
		_ = client.SentinelApi.WithdrawQsr()

		fmt.Println("\nWithdrawal transaction created")
		fmt.Println("All deposited QSR will be returned")
	} else {
		fmt.Println("\nNo QSR deposited to withdraw")
	}
}

Index

Examples

Constants

View Source
const (
	// UnknownPillarType indicates a pillar with unknown origin.
	UnknownPillarType = 0
	// LegacyPillarType indicates a pillar migrated from the legacy network.
	LegacyPillarType = 1
	// RegularPillarType indicates a pillar registered on the current network.
	RegularPillarType = 2
)

Pillar type constants identify the origin of a Pillar.

View Source
const SecondsPerDay = 24 * 60 * 60

SecondsPerDay is the number of seconds in a day, used for epoch math in the swap-decay schedule. Mirrors Dart's Duration.secondsPerDay.

Variables

This section is empty.

Functions

This section is empty.

Types

type AcceleratorApi

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

func NewAcceleratorApi

func NewAcceleratorApi(client *server.Client) *AcceleratorApi

func (*AcceleratorApi) AddPhase

func (aa *AcceleratorApi) AddPhase(id types.Hash, name, description, url string, znnFundsNeeded, qsrFundsNeeded *big.Int) *nom.AccountBlock

func (*AcceleratorApi) CreateProject

func (aa *AcceleratorApi) CreateProject(name, description, url string, znnFundsNeeded, qsrFundsNeeded *big.Int) *nom.AccountBlock

CreateProject creates a transaction template to submit a new Accelerator-Z project proposal.

Accelerator-Z is Zenon's decentralized funding mechanism for ecosystem development. Projects submit proposals requesting ZNN/QSR funding, which Pillars vote on.

Requirements:

  • Cost: 1 ZNN (project creation fee, non-refundable)
  • Project must include clear deliverables and milestones
  • Funding delivered in phases as milestones are completed

Parameters:

  • name: Project name (3-50 characters)
  • description: Detailed project description
  • url: Project website or documentation URL
  • znnFundsNeeded: Total ZNN requested
  • qsrFundsNeeded: Total QSR requested

Returns an unsigned AccountBlock template ready for processing.

Example:

znnNeeded := big.NewInt(5000 * 100000000) // 5,000 ZNN
qsrNeeded := big.NewInt(50000 * 100000000) // 50,000 QSR

template := client.AcceleratorApi.CreateProject(
    "My Zenon Project",
    "Building a new tool for the ecosystem...",
    "https://myproject.com",
    znnNeeded,
    qsrNeeded,
)

Note: After submission, Pillars vote on the project. If approved, add phases with milestones.

func (*AcceleratorApi) Donate

func (aa *AcceleratorApi) Donate(amount *big.Int, tokenStandard types.ZenonTokenStandard) *nom.AccountBlock

func (*AcceleratorApi) GetAll

func (aa *AcceleratorApi) GetAll(pageIndex, pageSize uint32) (*ProjectList, error)

func (*AcceleratorApi) GetPhaseById

func (aa *AcceleratorApi) GetPhaseById(id types.Hash) (*Phase, error)

func (*AcceleratorApi) GetPillarVotes

func (aa *AcceleratorApi) GetPillarVotes(name string, hashes []types.Hash) ([]*definition.PillarVote, error)

func (*AcceleratorApi) GetProjectById

func (aa *AcceleratorApi) GetProjectById(id types.Hash) (*Project, error)

func (*AcceleratorApi) GetVoteBreakdown

func (aa *AcceleratorApi) GetVoteBreakdown(id types.Hash) (*VoteBreakdown, error)

func (*AcceleratorApi) UpdatePhase

func (aa *AcceleratorApi) UpdatePhase(id types.Hash, name, description, url string, znnFundsNeeded, qsrFundsNeeded *big.Int) *nom.AccountBlock

func (*AcceleratorApi) VoteByName

func (aa *AcceleratorApi) VoteByName(id types.Hash, pillarName string, vote uint8) *nom.AccountBlock

VoteByName creates a transaction template for a Pillar to vote on a project/phase.

Only Pillar operators can vote on Accelerator proposals. Votes determine whether projects receive funding and whether phases are approved for payment.

Vote options:

  • 0: Abstain
  • 1: Yes (approve)
  • 2: No (reject)

Parameters:

  • id: Project or phase ID to vote on
  • pillarName: Name of the voting Pillar
  • vote: Vote choice (0=abstain, 1=yes, 2=no)

Returns an unsigned AccountBlock template ready for processing.

Example:

projectId := types.HexToHashPanic("0x123...")
template := client.AcceleratorApi.VoteByName(projectId, "MyPillar", 1) // Vote yes

Note: Only Pillar owners can call this. Voting period has time limits.

func (*AcceleratorApi) VoteByProducerAddress

func (aa *AcceleratorApi) VoteByProducerAddress(id types.Hash, vote uint8) *nom.AccountBlock

type BridgeApi

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

func NewBridgeApi

func NewBridgeApi(client *server.Client) *BridgeApi

func (*BridgeApi) AddNetwork

func (ba *BridgeApi) AddNetwork(networkClass uint32, chainId uint32, name, contractAddress, metadata string) *nom.AccountBlock

func (*BridgeApi) ChangeAdministrator

func (ba *BridgeApi) ChangeAdministrator(administrator types.Address) *nom.AccountBlock

func (*BridgeApi) ChangeTssECDSAPubKey

func (ba *BridgeApi) ChangeTssECDSAPubKey(pubKey, signature, newSignature string) *nom.AccountBlock

func (*BridgeApi) Emergency

func (ba *BridgeApi) Emergency() *nom.AccountBlock

func (*BridgeApi) GetAllNetworks

func (ba *BridgeApi) GetAllNetworks(pageIndex, pageSize uint32) (*BridgeNetworkInfoList, error)

func (*BridgeApi) GetAllUnsignedWrapTokenRequests

func (ba *BridgeApi) GetAllUnsignedWrapTokenRequests(pageIndex, pageSize uint32) (*WrapTokenRequestList, error)

func (*BridgeApi) GetAllUnwrapTokenRequests

func (ba *BridgeApi) GetAllUnwrapTokenRequests(pageIndex, pageSize uint32) (*UnwrapTokenRequestList, error)

func (*BridgeApi) GetAllUnwrapTokenRequestsByToAddress

func (ba *BridgeApi) GetAllUnwrapTokenRequestsByToAddress(toAddress string, pageIndex, pageSize uint32) (*UnwrapTokenRequestList, error)

func (*BridgeApi) GetAllWrapTokenRequests

func (ba *BridgeApi) GetAllWrapTokenRequests(pageIndex, pageSize uint32) (*WrapTokenRequestList, error)

func (*BridgeApi) GetAllWrapTokenRequestsByToAddress

func (ba *BridgeApi) GetAllWrapTokenRequestsByToAddress(toAddress string, pageIndex, pageSize uint32) (*WrapTokenRequestList, error)

func (*BridgeApi) GetAllWrapTokenRequestsByToAddressNetworkClassAndChainId

func (ba *BridgeApi) GetAllWrapTokenRequestsByToAddressNetworkClassAndChainId(toAddress string, networkClass, pageIndex, pageSize uint32) (*WrapTokenRequestList, error)

func (*BridgeApi) GetBridgeInfo

func (ba *BridgeApi) GetBridgeInfo() (*BridgeInfo, error)

func (*BridgeApi) GetFeeTokenPair added in v0.1.13

func (ba *BridgeApi) GetFeeTokenPair(zts types.ZenonTokenStandard) (*ZtsFeesInfo, error)

GetFeeTokenPair queries accumulated bridge fees for the given token.

Reference: znn_sdk_dart/lib/src/api/embedded/bridge.dart:151-155

func (*BridgeApi) GetNetworkInfo

func (ba *BridgeApi) GetNetworkInfo(networkClass, chainId uint32) (*BridgeNetworkInfo, error)

func (*BridgeApi) GetOrchestratorInfo

func (ba *BridgeApi) GetOrchestratorInfo() (*OrchestratorInfo, error)

func (*BridgeApi) GetSecurityInfo

func (ba *BridgeApi) GetSecurityInfo() (*SecurityInfo, error)

func (*BridgeApi) GetTimeChallengesInfo

func (ba *BridgeApi) GetTimeChallengesInfo() (*TimeChallengesList, error)

func (*BridgeApi) GetUnwrapTokenRequestByHashAndLog

func (ba *BridgeApi) GetUnwrapTokenRequestByHashAndLog(txHash types.Hash, logIndex uint32) (*UnwrapTokenRequest, error)

func (*BridgeApi) GetWrapTokenRequestById

func (ba *BridgeApi) GetWrapTokenRequestById(id types.Hash) (*WrapTokenRequest, error)

func (*BridgeApi) Halt

func (ba *BridgeApi) Halt(signature string) *nom.AccountBlock

func (*BridgeApi) NominateGuardians

func (ba *BridgeApi) NominateGuardians(guardians []types.Address) *nom.AccountBlock

func (*BridgeApi) ProposeAdministrator added in v0.1.13

func (ba *BridgeApi) ProposeAdministrator(address types.Address) *nom.AccountBlock

ProposeAdministrator creates a transaction template that proposes a new administrator for the bridge contract. Used by guardians during recovery when the prior administrator is unreachable.

Reference: znn_sdk_dart/lib/src/api/embedded/bridge.dart:242-249

func (*BridgeApi) Redeem

func (ba *BridgeApi) Redeem(hash types.Hash, logIndex uint32) *nom.AccountBlock

func (*BridgeApi) RemoveNetwork

func (ba *BridgeApi) RemoveNetwork(networkClass uint32, chainId uint32) *nom.AccountBlock

func (*BridgeApi) RemoveTokenPair

func (ba *BridgeApi) RemoveTokenPair(networkClass uint32, chainId uint32, tokenStandard types.ZenonTokenStandard, tokenAddress string) *nom.AccountBlock

func (*BridgeApi) RevokeUnwrapRequest added in v0.1.13

func (ba *BridgeApi) RevokeUnwrapRequest(transactionHash types.Hash, logIndex uint32) *nom.AccountBlock

RevokeUnwrapRequest creates a transaction template that revokes an unwrap request identified by the foreign-chain transaction hash and log index.

Reference: znn_sdk_dart/lib/src/api/embedded/bridge.dart:376-383

func (*BridgeApi) SetAllowKeygen

func (ba *BridgeApi) SetAllowKeygen(allowKeyGen bool) *nom.AccountBlock

func (*BridgeApi) SetBridgeMetadata

func (ba *BridgeApi) SetBridgeMetadata(metadata string) *nom.AccountBlock

func (*BridgeApi) SetNetworkMetadata

func (ba *BridgeApi) SetNetworkMetadata(networkClass uint32, chainId uint32, metadata string) *nom.AccountBlock

func (*BridgeApi) SetOrchestratorInfo

func (ba *BridgeApi) SetOrchestratorInfo(windowSize uint64, keyGenThreshold, confirmationsToFinality, estimatedMomentumTime uint32) *nom.AccountBlock

func (*BridgeApi) SetTokenPair

func (ba *BridgeApi) SetTokenPair(networkClass uint32, chainId uint32, tokenStandard types.ZenonTokenStandard, tokenAddress string, bridgeable, redeemable, owned bool, minAmount *big.Int, fee, redeemDelay uint32, metadata string) *nom.AccountBlock

func (*BridgeApi) Unhalt

func (ba *BridgeApi) Unhalt() *nom.AccountBlock

func (*BridgeApi) UnwrapToken

func (ba *BridgeApi) UnwrapToken(networkClass uint32, chainId uint32, tokenAddress string, txHash types.Hash, logIndex uint32, amount *big.Int, toAddress types.Address, signature string) *nom.AccountBlock

func (*BridgeApi) UpdateWrapRequest

func (ba *BridgeApi) UpdateWrapRequest(id types.Hash, signature string) *nom.AccountBlock

func (*BridgeApi) WrapToken

func (ba *BridgeApi) WrapToken(networkClass uint32, chainId uint32, toAddress string, amount *big.Int, tokenStandard types.ZenonTokenStandard) *nom.AccountBlock

type BridgeInfo added in v0.1.9

type BridgeInfo struct {
	Administrator              types.Address `json:"administrator"`
	CompressedTssECDSAPubKey   string        `json:"compressedTssECDSAPubKey"`
	DecompressedTssECDSAPubKey string        `json:"decompressedTssECDSAPubKey"`
	AllowKeyGen                bool          `json:"allowKeyGen"`
	Halted                     bool          `json:"halted"`
	UnhaltedAt                 uint64        `json:"unhaltedAt"`
	UnhaltDurationInMomentums  uint64        `json:"unhaltDurationInMomentums"`
	TssNonce                   uint64        `json:"tssNonce"`
	Metadata                   string        `json:"metadata"`
}

BridgeInfo represents bridge contract configuration.

The bridge enables cross-chain transfers between Zenon and other networks (e.g., Ethereum). This type contains the current configuration and state of the bridge contract.

Fields:

  • Administrator: Address that can configure the bridge
  • CompressedTssECDSAPubKey: Compressed TSS public key for signing
  • DecompressedTssECDSAPubKey: Decompressed TSS public key
  • AllowKeyGen: Whether key generation ceremonies are enabled
  • Halted: Whether bridge operations are currently paused
  • UnhaltedAt: Momentum height when the bridge was last unhalted
  • UnhaltDurationInMomentums: How long the bridge stays unhalted
  • TssNonce: Current nonce for TSS operations
  • Metadata: Additional bridge configuration data

type BridgeNetworkInfo added in v0.1.9

type BridgeNetworkInfo struct {
	NetworkClass    uint32       `json:"networkClass"`
	ChainId         uint32       `json:"chainId"`
	Name            string       `json:"name"`
	ContractAddress string       `json:"contractAddress"`
	Metadata        string       `json:"metadata"`
	TokenPairs      []*TokenPair `json:"tokenPairs"`
}

BridgeNetworkInfo represents bridge network configuration.

This type contains information about an external blockchain network that is connected via the bridge, including supported token pairs.

Fields:

  • NetworkClass: Category of network (e.g., EVM-based)
  • ChainId: Chain identifier for the external network
  • Name: Human-readable name of the network
  • ContractAddress: Bridge contract address on the external network
  • Metadata: Additional network configuration data
  • TokenPairs: List of token pairs supported on this network

type BridgeNetworkInfoList added in v0.1.9

type BridgeNetworkInfoList struct {
	Count int                  `json:"count"`
	List  []*BridgeNetworkInfo `json:"list"`
}

BridgeNetworkInfoList represents a paginated list of bridge networks.

Fields:

  • Count: Total number of networks matching the query
  • List: Slice of BridgeNetworkInfo entries for the current page

type DelegationInfo added in v0.1.9

type DelegationInfo struct {
	Name       string   `json:"name"`
	Status     int32    `json:"status"`
	Weight     *big.Int `json:"weight"`
	WeightJson string   `json:"-"` // Internal field to track original
}

DelegationInfo represents delegation information for an address.

When a user delegates their ZNN to a Pillar, they earn a share of the Pillar's rewards proportional to their delegation weight. This type contains information about a delegation relationship.

Fields:

  • Name: Name of the Pillar being delegated to (empty if no delegation)
  • Status: Delegation status (1 = active, 0 = inactive/no delegation)
  • Weight: Delegated amount (in base units, 8 decimals)

Example:

delegation, err := client.PillarApi.GetDelegatedPillar(address)
if err != nil {
    log.Fatal(err)
}
if delegation.IsPillarActive() {
    fmt.Printf("Delegated to: %s, Weight: %s\n", delegation.Name, delegation.Weight)
}

func (*DelegationInfo) IsPillarActive added in v0.1.9

func (d *DelegationInfo) IsPillarActive() bool

IsPillarActive returns true if the delegation is to an active Pillar.

A delegation is considered active when Status equals 1, meaning the user has an active delegation to a Pillar that is currently participating in the network.

Returns:

  • true if delegated to an active Pillar
  • false if no delegation or Pillar is inactive

func (*DelegationInfo) UnmarshalJSON added in v0.1.9

func (d *DelegationInfo) UnmarshalJSON(data []byte) error

type FusionEntry added in v0.1.9

type FusionEntry struct {
	QsrAmount        *big.Int      `json:"qsrAmount"`
	Beneficiary      types.Address `json:"beneficiary"`
	ExpirationHeight uint64        `json:"expirationHeight"`
	Id               types.Hash    `json:"id"`
}

FusionEntry represents a single plasma fusion entry.

When QSR is fused for plasma, a FusionEntry is created tracking the fusion. The beneficiary receives plasma from this fusion, which may be different from the address that provided the QSR.

Fields:

  • QsrAmount: Amount of QSR fused (in base units, 8 decimals)
  • Beneficiary: Address that receives plasma from this fusion
  • ExpirationHeight: Momentum height when the fusion can be canceled
  • Id: Unique identifier for this fusion entry

After the lock period expires (ExpirationHeight), the fusion can be canceled to reclaim the fused QSR.

func (*FusionEntry) UnmarshalJSON added in v0.1.9

func (f *FusionEntry) UnmarshalJSON(data []byte) error

type FusionEntryList added in v0.1.9

type FusionEntryList struct {
	QsrAmount *big.Int       `json:"qsrAmount"`
	Count     int            `json:"count"`
	List      []*FusionEntry `json:"list"`
}

FusionEntryList represents a paginated list of fusion entries.

This type is returned by methods that list fusions, such as GetEntriesByAddress. It includes the total QSR amount across all fusions for the queried address.

Fields:

  • QsrAmount: Total QSR fused across all entries (in base units, 8 decimals)
  • Count: Total number of fusion entries matching the query
  • List: Slice of FusionEntry entries for the current page

func (*FusionEntryList) UnmarshalJSON added in v0.1.9

func (f *FusionEntryList) UnmarshalJSON(data []byte) error

type GetRequiredParam added in v0.1.9

type GetRequiredParam struct {
	Address   types.Address `json:"address"`
	BlockType uint64        `json:"blockType"`
	ToAddress types.Address `json:"toAddress"`
	Data      []byte        `json:"data"`
}

GetRequiredParam represents parameters for GetRequiredPoWForAccountBlock.

This type is used when querying the PoW difficulty required for a transaction based on the sender's available plasma and the transaction details.

Fields:

  • Address: Sender address
  • BlockType: Type of account block being created
  • ToAddress: Destination address for the transaction
  • Data: Transaction data payload

type GetRequiredResult added in v0.1.9

type GetRequiredResult struct {
	AvailablePlasma    uint64 `json:"availablePlasma"`
	BasePlasma         uint64 `json:"basePlasma"`
	RequiredDifficulty uint64 `json:"requiredDifficulty"`
}

GetRequiredResult represents the result of GetRequiredPoWForAccountBlock.

This type indicates whether a transaction can be sent using available plasma or if Proof-of-Work must be computed. If RequiredDifficulty is 0, the transaction can proceed using plasma alone.

Fields:

  • AvailablePlasma: Current plasma available for the address
  • BasePlasma: Minimum plasma required for this transaction type
  • RequiredDifficulty: PoW difficulty to compute (0 if plasma is sufficient)

Example:

result, err := client.PlasmaApi.GetRequiredPoWForAccountBlock(params)
if err != nil {
    log.Fatal(err)
}
if result.RequiredDifficulty > 0 {
    fmt.Printf("PoW required, difficulty: %d\n", result.RequiredDifficulty)
} else {
    fmt.Println("Sufficient plasma, no PoW needed")
}

type HtlcApi

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

HtlcApi provides access to the HTLC (Hashed Timelock Contract) embedded contract

func NewHtlcApi

func NewHtlcApi(client *server.Client) *HtlcApi

NewHtlcApi creates a new HTLC API instance

func (*HtlcApi) AllowProxyUnlock

func (h *HtlcApi) AllowProxyUnlock() *nom.AccountBlock

AllowProxyUnlock allows proxy unlock for the caller's address

func (*HtlcApi) Create

func (h *HtlcApi) Create(
	token types.ZenonTokenStandard,
	amount *big.Int,
	hashLocked types.Address,
	expirationTime int64,
	hashType uint8,
	keyMaxSize uint8,
	hashLock []byte,
) *nom.AccountBlock

Create creates a new HTLC contract Parameters:

  • hashLocked: The address that can unlock with preimage
  • expirationTime: Unix timestamp when HTLC expires
  • hashType: 0 for SHA3-256, 1 for SHA-256
  • keyMaxSize: Maximum size of the preimage key
  • hashLock: Hash of the preimage

func (*HtlcApi) DenyProxyUnlock

func (h *HtlcApi) DenyProxyUnlock() *nom.AccountBlock

DenyProxyUnlock denies proxy unlock for the caller's address

func (*HtlcApi) GetById

func (h *HtlcApi) GetById(id types.Hash) (*HtlcInfo, error)

GetById retrieves HTLC information by ID

func (*HtlcApi) GetProxyUnlockStatus

func (h *HtlcApi) GetProxyUnlockStatus(address types.Address) (bool, error)

GetProxyUnlockStatus retrieves the proxy unlock status for an address

func (*HtlcApi) Reclaim

func (h *HtlcApi) Reclaim(id types.Hash) *nom.AccountBlock

Reclaim reclaims an expired HTLC

func (*HtlcApi) Unlock

func (h *HtlcApi) Unlock(id types.Hash, preimage []byte) *nom.AccountBlock

Unlock unlocks an HTLC with the preimage

type HtlcInfo added in v0.1.9

type HtlcInfo struct {
	Id             types.Hash               `json:"id"`
	TimeLocked     types.Address            `json:"timeLocked"`
	HashLocked     types.Address            `json:"hashLocked"`
	TokenStandard  types.ZenonTokenStandard `json:"tokenStandard"`
	Amount         *big.Int                 `json:"amount"`
	ExpirationTime int64                    `json:"expirationTime"`
	HashType       uint8                    `json:"hashType"`
	KeyMaxSize     uint8                    `json:"keyMaxSize"`
	HashLock       []byte                   `json:"hashLock"`
}

HtlcInfo represents HTLC (Hashed Timelock Contract) information.

HTLCs enable trustless atomic swaps between parties by locking tokens with both a hash lock (requires revealing a preimage) and a time lock (expires after a deadline). This allows for cross-chain atomic swaps and payment channels.

Fields:

  • Id: Unique identifier for this HTLC
  • TimeLocked: Address that can reclaim tokens after expiration
  • HashLocked: Address that can claim tokens by revealing the preimage
  • TokenStandard: ZTS identifier of the locked tokens
  • Amount: Locked amount (in base units, 8 decimals)
  • ExpirationTime: Unix timestamp when the time lock expires
  • HashType: Hash algorithm used (0 = SHA256, 1 = SHA3)
  • KeyMaxSize: Maximum size of the preimage in bytes
  • HashLock: Hash that must be satisfied to claim tokens

HTLC Flow:

  1. Creator locks tokens with a hash lock and time lock
  2. HashLocked address reveals preimage to claim tokens
  3. If not claimed before expiration, TimeLocked can reclaim

Example:

htlc, err := client.HtlcApi.GetById(htlcId)
if err != nil {
    log.Fatal(err)
}
if htlc.ExpirationTime > time.Now().Unix() {
    fmt.Printf("HTLC active, amount: %s\n", htlc.Amount)
}

func (*HtlcInfo) UnmarshalJSON added in v0.1.9

func (h *HtlcInfo) UnmarshalJSON(data []byte) error

type LiquidityApi

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

func NewLiquidityApi

func NewLiquidityApi(client *server.Client) *LiquidityApi

func (*LiquidityApi) CancelLiquidity

func (sa *LiquidityApi) CancelLiquidity(id types.Hash) *nom.AccountBlock

func (*LiquidityApi) ChangeAdministrator added in v0.1.13

func (sa *LiquidityApi) ChangeAdministrator(administrator types.Address) *nom.AccountBlock

ChangeAdministrator creates a transaction template that transfers administrator rights of the liquidity contract to a new address.

Reference: znn_sdk_dart/lib/src/api/embedded/liquidity.dart:134-141

func (*LiquidityApi) CollectReward

func (sa *LiquidityApi) CollectReward() *nom.AccountBlock

func (*LiquidityApi) Emergency added in v0.1.13

func (sa *LiquidityApi) Emergency() *nom.AccountBlock

Emergency creates a transaction template that triggers an emergency halt of the liquidity contract. Callable by the administrator.

Reference: znn_sdk_dart/lib/src/api/embedded/liquidity.dart:150-153

func (*LiquidityApi) GetFrontierRewardByPage

func (sa *LiquidityApi) GetFrontierRewardByPage(address types.Address, pageIndex, pageSize uint32) (*RewardHistoryList, error)

func (*LiquidityApi) GetLiquidityInfo

func (sa *LiquidityApi) GetLiquidityInfo() (*LiquidityInfo, error)

func (*LiquidityApi) GetLiquidityStakeEntriesByAddress

func (sa *LiquidityApi) GetLiquidityStakeEntriesByAddress(address types.Address, pageIndex, pageSize uint32) (*LiquidityStakeList, error)

func (*LiquidityApi) GetSecurityInfo

func (sa *LiquidityApi) GetSecurityInfo() (*SecurityInfo, error)

func (*LiquidityApi) GetTimeChallengesInfo

func (sa *LiquidityApi) GetTimeChallengesInfo() (*TimeChallengesList, error)

func (*LiquidityApi) GetUncollectedReward

func (sa *LiquidityApi) GetUncollectedReward(address types.Address) (*UncollectedReward, error)

func (*LiquidityApi) LiquidityStake

func (sa *LiquidityApi) LiquidityStake(durationInSec int64, amount *big.Int, zts types.ZenonTokenStandard) *nom.AccountBlock

func (*LiquidityApi) NominateGuardians

func (sa *LiquidityApi) NominateGuardians(guardians []types.Address) *nom.AccountBlock

func (*LiquidityApi) ProposeAdministrator added in v0.1.13

func (sa *LiquidityApi) ProposeAdministrator(address types.Address) *nom.AccountBlock

ProposeAdministrator creates a transaction template that proposes a new administrator for the liquidity contract. Used by guardians during recovery when the prior administrator is unreachable.

Reference: znn_sdk_dart/lib/src/api/embedded/liquidity.dart:108-115

func (*LiquidityApi) SetAdditionalReward

func (sa *LiquidityApi) SetAdditionalReward(znnReward *big.Int, qsrAmount *big.Int) *nom.AccountBlock

func (*LiquidityApi) SetIsHalted

func (sa *LiquidityApi) SetIsHalted(value bool) *nom.AccountBlock

func (*LiquidityApi) SetTokenTupleMethod

func (sa *LiquidityApi) SetTokenTupleMethod(tokenStandards []string, znnPercentages []uint32, qsrPercentages []uint32, minAmounts []*big.Int) *nom.AccountBlock

func (*LiquidityApi) UnlockLiquidityStakeEntries

func (sa *LiquidityApi) UnlockLiquidityStakeEntries(zts types.ZenonTokenStandard) *nom.AccountBlock

type LiquidityInfo added in v0.1.9

type LiquidityInfo struct {
	Administrator types.Address `json:"administrator"`
	IsHalted      bool          `json:"isHalted"`
	ZnnReward     *big.Int      `json:"znnReward"`
	QsrReward     *big.Int      `json:"qsrReward"`
	TokenTuples   []*TokenTuple `json:"tokenTuples"`
}

LiquidityInfo represents liquidity contract configuration.

This type contains the global configuration for the liquidity rewards program, including reward amounts and supported token configurations.

Fields:

  • Administrator: Address that can configure the liquidity contract
  • IsHalted: Whether the liquidity program is currently paused
  • ZnnReward: Total ZNN rewards available per epoch (in base units, 8 decimals)
  • QsrReward: Total QSR rewards available per epoch (in base units, 8 decimals)
  • TokenTuples: List of supported tokens and their reward configurations

func (*LiquidityInfo) UnmarshalJSON added in v0.1.9

func (l *LiquidityInfo) UnmarshalJSON(data []byte) error

type LiquidityStakeEntry added in v0.1.9

type LiquidityStakeEntry struct {
	Amount         *big.Int                 `json:"amount"`
	TokenStandard  types.ZenonTokenStandard `json:"tokenStandard"`
	WeightedAmount *big.Int                 `json:"weightedAmount"`
	StartTime      int64                    `json:"startTime"`
	RevokeTime     int64                    `json:"revokeTime"`
	ExpirationTime int64                    `json:"expirationTime"`
	StakeAddress   types.Address            `json:"stakeAddress"`
	Id             types.Hash               `json:"id"`
}

LiquidityStakeEntry represents a single liquidity stake entry.

Users can stake supported tokens in the liquidity program to earn ZNN and QSR rewards. This type contains information about an individual liquidity stake.

Fields:

  • Amount: Staked amount (in base units, 8 decimals)
  • TokenStandard: ZTS identifier of the staked token
  • WeightedAmount: Amount multiplied by duration factor for reward calculation
  • StartTime: Unix timestamp when the stake was created
  • RevokeTime: Unix timestamp when revocation was initiated (0 if not revoked)
  • ExpirationTime: Unix timestamp when the stake can be canceled
  • StakeAddress: Address that owns this stake
  • Id: Unique identifier for this stake entry

func (*LiquidityStakeEntry) UnmarshalJSON added in v0.1.9

func (l *LiquidityStakeEntry) UnmarshalJSON(data []byte) error

type LiquidityStakeList added in v0.1.9

type LiquidityStakeList struct {
	TotalAmount         *big.Int               `json:"totalAmount"`
	TotalWeightedAmount *big.Int               `json:"totalWeightedAmount"`
	Count               int                    `json:"count"`
	List                []*LiquidityStakeEntry `json:"list"`
}

LiquidityStakeList represents a paginated list of liquidity stake entries.

This type is returned by methods that list liquidity stakes. It includes aggregate totals for all stakes belonging to the queried address.

Fields:

  • TotalAmount: Sum of all staked amounts (in base units, 8 decimals)
  • TotalWeightedAmount: Sum of all weighted amounts for reward calculation
  • Count: Total number of stake entries matching the query
  • List: Slice of LiquidityStakeEntry entries for the current page

func (*LiquidityStakeList) UnmarshalJSON added in v0.1.9

func (l *LiquidityStakeList) UnmarshalJSON(data []byte) error

type OrchestratorInfo added in v0.1.9

type OrchestratorInfo struct {
	WindowSize              uint64 `json:"windowSize"`
	KeyGenThreshold         uint32 `json:"keyGenThreshold"`
	ConfirmationsToFinality uint32 `json:"confirmationsToFinality"`
	EstimatedMomentumTime   uint32 `json:"estimatedMomentumTime"`
	AllowKeyGenHeight       uint64 `json:"allowKeyGenHeight"`
}

OrchestratorInfo represents orchestrator configuration.

Orchestrators are the bridge operators that facilitate cross-chain transfers using threshold signature scheme (TSS). This type contains configuration parameters for orchestrator operations.

Fields:

  • WindowSize: Time window for orchestrator operations
  • KeyGenThreshold: Minimum participants required for key generation
  • ConfirmationsToFinality: Block confirmations needed on external chain
  • EstimatedMomentumTime: Estimated time per momentum in seconds
  • AllowKeyGenHeight: Momentum height when key generation becomes allowed

type Phase added in v0.1.9

type Phase struct {
	Phase *PhaseInfo     `json:"phase"`
	Votes *VoteBreakdown `json:"votes"`
}

Phase represents a project phase with its voting info.

This type combines the phase details with the current vote breakdown.

Fields:

  • Phase: Core phase information
  • Votes: Current voting results for this phase

type PhaseInfo added in v0.1.9

type PhaseInfo struct {
	Id                types.Hash `json:"id"`
	ProjectID         types.Hash `json:"projectID"`
	Name              string     `json:"name"`
	Description       string     `json:"description"`
	Url               string     `json:"url"`
	ZnnFundsNeeded    *big.Int   `json:"znnFundsNeeded"`
	QsrFundsNeeded    *big.Int   `json:"qsrFundsNeeded"`
	CreationTimestamp int64      `json:"creationTimestamp"`
	AcceptedTimestamp int64      `json:"acceptedTimestamp"`
	Status            uint8      `json:"status"`
}

PhaseInfo represents the phase details within a Phase.

Accelerator-Z projects are divided into phases, each with its own funding requirements and approval process. This type contains the core information about a project phase.

Fields:

  • Id: Unique identifier for this phase
  • ProjectID: Parent project's identifier
  • Name: Human-readable name of the phase
  • Description: Detailed description of phase deliverables
  • Url: Link to additional information or documentation
  • ZnnFundsNeeded: ZNN funding requested (in base units, 8 decimals)
  • QsrFundsNeeded: QSR funding requested (in base units, 8 decimals)
  • CreationTimestamp: Unix timestamp when phase was created
  • AcceptedTimestamp: Unix timestamp when phase was accepted (0 if pending)
  • Status: Current phase status

func (*PhaseInfo) UnmarshalJSON added in v0.1.9

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

type PillarApi

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

func NewPillarApi

func NewPillarApi(client *server.Client) *PillarApi

func (*PillarApi) CheckNameAvailability

func (pa *PillarApi) CheckNameAvailability(name string) (*bool, error)

func (*PillarApi) CollectReward

func (pa *PillarApi) CollectReward() *nom.AccountBlock

func (*PillarApi) Delegate

func (pa *PillarApi) Delegate(name string) *nom.AccountBlock

Delegate creates a transaction template to delegate your stake weight to a Pillar.

Delegation allows ZNN holders to support Pillars and earn rewards without running infrastructure. Your ZNN remains in your wallet - only voting weight is delegated.

Delegation benefits:

  • Earn rewards from pillar's delegation percentage
  • Support network decentralization
  • No ZNN lockup required
  • Can change delegation anytime

Parameters:

  • name: Name of the Pillar to delegate to

Returns an unsigned AccountBlock template ready for processing.

Example:

template := client.PillarApi.Delegate("MyFavoritePillar")
// Sign and publish transaction

Note: Only one Pillar can be delegated to at a time. Delegating to a new Pillar automatically undelegates from the previous one.

func (*PillarApi) DepositQsr

func (pa *PillarApi) DepositQsr(amount *big.Int) *nom.AccountBlock

func (*PillarApi) GetAll

func (pa *PillarApi) GetAll(pageIndex, pageSize uint32) (*PillarInfoList, error)

func (*PillarApi) GetByName

func (pa *PillarApi) GetByName(name string) (*PillarInfo, error)

func (*PillarApi) GetByOwner

func (pa *PillarApi) GetByOwner(address types.Address) ([]*PillarInfo, error)

func (*PillarApi) GetDelegatedPillar

func (pa *PillarApi) GetDelegatedPillar(address types.Address) (*DelegationInfo, error)

func (*PillarApi) GetDepositedQsr

func (pa *PillarApi) GetDepositedQsr(address types.Address) (*big.Int, error)

GetDepositedQsr retrieves the amount of QSR deposited for a Pillar.

Pillar operators can deposit QSR to increase their momentum rewards weight. Deposited QSR can be withdrawn after meeting the lock period requirement.

Parameters:

  • address: Pillar owner address

Returns deposited QSR amount or an error.

Example:

deposited, err := client.PillarApi.GetDepositedQsr(pillarAddress)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Deposited QSR: %s\n", deposited)

func (*PillarApi) GetFrontierRewardByPage

func (pa *PillarApi) GetFrontierRewardByPage(address types.Address, pageIndex, pageSize uint32) (*RewardHistoryList, error)

func (*PillarApi) GetPillarEpochHistory

func (pa *PillarApi) GetPillarEpochHistory(pillarName string, pageIndex, pageSize uint32) (*PillarEpochHistoryList, error)

func (*PillarApi) GetPillarsHistoryByEpoch

func (pa *PillarApi) GetPillarsHistoryByEpoch(epoch uint64, pageIndex, pageSize uint32) (*PillarEpochHistoryList, error)

func (*PillarApi) GetQsrRegistrationCost

func (pa *PillarApi) GetQsrRegistrationCost() (*big.Int, error)

GetQsrRegistrationCost retrieves the current QSR cost for Pillar registration.

The cost may vary based on network parameters. Check this before attempting to register a Pillar to ensure sufficient QSR balance.

Returns QSR registration cost or an error.

Example:

cost, err := client.PillarApi.GetQsrRegistrationCost()
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Registration cost: %s QSR\n", cost)

func (*PillarApi) GetUncollectedReward

func (pa *PillarApi) GetUncollectedReward(address types.Address) (*UncollectedReward, error)

func (*PillarApi) Register

func (pa *PillarApi) Register(name string, producerAddress, rewardAddress types.Address, blockProducingPercentage, delegationPercentage uint8) *nom.AccountBlock

Register creates a transaction template to register a new Pillar.

Pillars are the backbone consensus nodes of Zenon Network. Running a Pillar requires:

  • 15,000 ZNN collateral (locked, returned upon revocation)
  • Variable QSR cost (check GetQsrRegistrationCost)
  • Dedicated infrastructure (node + block producer)
  • Unique pillar name (check CheckNameAvailability)

Parameters:

  • name: Unique pillar name (3-40 characters)
  • producerAddress: Address that will produce blocks
  • rewardAddress: Address that receives pillar rewards
  • blockProducingPercentage: % of block rewards kept by pillar (0-100)
  • delegationPercentage: % of delegation rewards kept by pillar (0-100)

Returns an unsigned AccountBlock template ready for processing.

Example:

template := client.PillarApi.Register(
    "MyPillar",
    producerAddr,
    rewardAddr,
    0,  // Give all block rewards to delegators
    50, // Keep 50% of delegation rewards
)

Note: Requires 15,000 ZNN + QSR cost. Pillar name cannot be changed after registration.

func (*PillarApi) RegisterLegacy

func (pa *PillarApi) RegisterLegacy(name string, producerAddress, rewardAddress types.Address, blockProducingPercentage, delegationPercentage uint8, publicKey, signature string) *nom.AccountBlock

func (*PillarApi) Revoke

func (pa *PillarApi) Revoke(name string) *nom.AccountBlock

Revoke creates a transaction template that revokes the named Pillar.

Parameters:

  • name: Name of the Pillar to revoke. Must match the registered name; the embedded contract uses it to look up and authorize the revocation.

Reference: znn_sdk_dart/lib/src/api/embedded/pillar.dart:143-146

func (*PillarApi) Undelegate

func (pa *PillarApi) Undelegate() *nom.AccountBlock

func (*PillarApi) UpdatePillar

func (pa *PillarApi) UpdatePillar(name string, producerAddress, rewardAddress types.Address, blockProducingPercentage, delegationPercentage uint8) *nom.AccountBlock

func (*PillarApi) WithdrawQsr

func (pa *PillarApi) WithdrawQsr() *nom.AccountBlock

type PillarEpochHistory added in v0.1.9

type PillarEpochHistory struct {
	Name                         string   `json:"name"`
	Epoch                        uint64   `json:"epoch"`
	GiveBlockRewardPercentage    int32    `json:"giveBlockRewardPercentage"`
	GiveDelegateRewardPercentage int32    `json:"giveDelegateRewardPercentage"`
	ProducedBlockNum             int32    `json:"producedBlockNum"`
	ExpectedBlockNum             int32    `json:"expectedBlockNum"`
	Weight                       *big.Int `json:"weight"`
}

PillarEpochHistory represents historical data for a Pillar in a specific epoch.

This type records a Pillar's configuration and performance during a past epoch, useful for analyzing historical trends and reward distributions.

Fields:

  • Name: Name of the Pillar
  • Epoch: The epoch number this history entry represents
  • GiveBlockRewardPercentage: Momentum reward percentage during this epoch
  • GiveDelegateRewardPercentage: Delegate reward percentage during this epoch
  • ProducedBlockNum: Number of momentums produced during this epoch
  • ExpectedBlockNum: Number of momentums expected during this epoch
  • Weight: Total delegation weight during this epoch (in base units, 8 decimals)

func (*PillarEpochHistory) UnmarshalJSON added in v0.1.9

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

type PillarEpochHistoryList added in v0.1.9

type PillarEpochHistoryList struct {
	Count int                   `json:"count"`
	List  []*PillarEpochHistory `json:"list"`
}

PillarEpochHistoryList represents a paginated list of Pillar epoch histories.

This type is returned by methods that query historical Pillar data, such as GetPillarEpochHistory.

Fields:

  • Count: Total number of history entries matching the query
  • List: Slice of PillarEpochHistory entries for the current page

type PillarEpochStats added in v0.1.9

type PillarEpochStats struct {
	ProducedMomentums int32 `json:"producedMomentums"`
	ExpectedMomentums int32 `json:"expectedMomentums"`
}

PillarEpochStats represents momentum production statistics for an epoch.

This type tracks how many momentums a Pillar was expected to produce versus how many it actually produced during a given epoch. This data is used for calculating Pillar performance metrics.

Fields:

  • ProducedMomentums: Number of momentums the Pillar actually produced
  • ExpectedMomentums: Number of momentums the Pillar was expected to produce

type PillarInfo added in v0.1.9

type PillarInfo struct {
	Name                         string            `json:"name"`
	Rank                         int32             `json:"rank"`
	Type                         int32             `json:"type"`
	OwnerAddress                 types.Address     `json:"ownerAddress"`
	ProducerAddress              types.Address     `json:"producerAddress"`
	WithdrawAddress              types.Address     `json:"withdrawAddress"`
	GiveMomentumRewardPercentage int32             `json:"giveMomentumRewardPercentage"`
	GiveDelegateRewardPercentage int32             `json:"giveDelegateRewardPercentage"`
	IsRevocable                  bool              `json:"isRevocable"`
	RevokeCooldown               int64             `json:"revokeCooldown"`
	RevokeTimestamp              int64             `json:"revokeTimestamp"`
	CurrentStats                 *PillarEpochStats `json:"currentStats"`
	Weight                       *big.Int          `json:"weight"`
}

PillarInfo represents detailed information about a Pillar.

Pillars are the consensus nodes of the Zenon Network. They produce momentums and participate in network governance. This type contains all configuration and status information for a Pillar.

Fields:

  • Name: Unique name of the Pillar
  • Rank: Current rank based on total weight (delegations)
  • Type: Origin type (UnknownPillarType, LegacyPillarType, or RegularPillarType)
  • OwnerAddress: Address that owns and controls the Pillar
  • ProducerAddress: Address used for producing momentums
  • WithdrawAddress: Address for withdrawing rewards
  • GiveMomentumRewardPercentage: Percentage of momentum rewards shared with delegators
  • GiveDelegateRewardPercentage: Percentage of delegate rewards shared
  • IsRevocable: Whether the Pillar can be revoked
  • RevokeCooldown: Remaining cooldown time before revocation completes
  • RevokeTimestamp: Unix timestamp when revocation was initiated
  • CurrentStats: Momentum production statistics for current epoch
  • Weight: Total delegation weight (in base units, 8 decimals)

Example:

pillar, err := client.PillarApi.GetByName("MyPillar")
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Pillar rank: %d, Weight: %s\n", pillar.Rank, pillar.Weight)

func (*PillarInfo) UnmarshalJSON added in v0.1.9

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

type PillarInfoList added in v0.1.9

type PillarInfoList struct {
	Count int           `json:"count"`
	List  []*PillarInfo `json:"list"`
}

PillarInfoList represents a paginated list of Pillars.

This type is returned by methods that list multiple Pillars, such as GetAll.

Fields:

  • Count: Total number of Pillars matching the query
  • List: Slice of PillarInfo entries for the current page

type PlasmaApi

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

func NewPlasmaApi

func NewPlasmaApi(client *server.Client) *PlasmaApi

func (*PlasmaApi) Cancel

func (pa *PlasmaApi) Cancel(id types.Hash) *nom.AccountBlock

Cancel creates a transaction template to cancel a plasma fusion and reclaim QSR.

After the fusion lock period expires, you can cancel the fusion to:

  • Reclaim your fused QSR
  • Remove the plasma (plasma will be deducted)

Parameters:

  • id: Hash ID of the fusion entry to cancel (from GetEntriesByAddress)

Returns an unsigned AccountBlock template ready for processing.

Example:

// Get fusion entries
entries, _ := client.PlasmaApi.GetEntriesByAddress(address, 0, 10)

// Cancel first entry (check if lock period expired first)
if len(entries.List) > 0 {
    entry := entries.List[0]
    template := client.PlasmaApi.Cancel(entry.Id)
    // Process and publish transaction
}

Note: Canceling requires the fusion lock period to have elapsed. Attempting to cancel before the period expires will fail.

func (*PlasmaApi) Fuse

func (pa *PlasmaApi) Fuse(address types.Address, amount *big.Int) *nom.AccountBlock

Fuse creates a transaction template to fuse QSR for plasma generation.

Fusing QSR locks it in the plasma contract and generates plasma for the beneficiary address. The plasma enables feeless transactions without PoW generation.

Fusion details:

  • Minimum: 10 QSR
  • Fused QSR is locked for a period
  • Plasma generation is proportional to QSR amount
  • Can be canceled after lock period expires

Parameters:

  • address: Beneficiary address that will receive the plasma
  • amount: Amount of QSR to fuse (in base units: 1 QSR = 10^8)

Returns an unsigned AccountBlock template that must be:

  1. Autofilled with account details
  2. Enhanced with PoW (since you need plasma to get plasma!)
  3. Signed with keypair
  4. Published via PublishRawTransaction

Example - Fuse 10 QSR:

amount := big.NewInt(10 * 100000000) // 10 QSR
template := client.PlasmaApi.Fuse(myAddress, amount)
// Process through transaction pipeline and publish

Example - Fuse for another address:

// Fuse QSR but give plasma to a different address
template := client.PlasmaApi.Fuse(beneficiaryAddress, amount)
// The sender pays QSR, beneficiary gets plasma

Note: The first fusion requires PoW since you don't have plasma yet. After that, the generated plasma enables feeless transactions.

func (*PlasmaApi) Get

func (pa *PlasmaApi) Get(address types.Address) (*PlasmaInfo, error)

Get retrieves the current plasma information for an address.

Plasma is Zenon's feeless transaction mechanism. Instead of generating computational PoW for each transaction, users can fuse QSR to generate plasma, enabling feeless transactions.

Returns PlasmaInfo containing:

  • CurrentPlasma: Available plasma units
  • MaxPlasma: Maximum plasma capacity
  • QsrAmount: Amount of QSR currently fused

Parameters:

  • address: Account address to query

Example:

plasmaInfo, err := client.PlasmaApi.Get(address)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Current Plasma: %d\n", plasmaInfo.CurrentPlasma)
fmt.Printf("Max Plasma: %d\n", plasmaInfo.MaxPlasma)
fmt.Printf("QSR Fused: %s\n", plasmaInfo.QsrAmount)

Use this to check if an address has sufficient plasma for feeless transactions.

func (*PlasmaApi) GetEntriesByAddress

func (pa *PlasmaApi) GetEntriesByAddress(address types.Address, pageIndex, pageSize uint32) (*FusionEntryList, error)

func (*PlasmaApi) GetPlasmaByQsr added in v0.1.13

func (pa *PlasmaApi) GetPlasmaByQsr(qsrAmount *big.Int) *big.Int

GetPlasmaByQsr returns the plasma units obtained by fusing the given QSR amount, using the protocol's fixed 1 QSR = 2100 plasma ratio.

Pure local helper — no RPC call.

Reference: znn_sdk_dart/lib/src/api/embedded/plasma.dart:35-37

func (*PlasmaApi) GetRequiredFusionAmount added in v0.1.13

func (pa *PlasmaApi) GetRequiredFusionAmount(requiredPlasma uint64) (uint64, error)

GetRequiredFusionAmount queries the QSR amount that must be fused to obtain the requested amount of plasma.

This is a node-side calculation that accounts for the current plasma:QSR ratio. Use it before calling Fuse to size the fusion correctly.

Reference: znn_sdk_dart/lib/src/api/embedded/plasma.dart:30-33

func (*PlasmaApi) GetRequiredPoWForAccountBlock

func (pa *PlasmaApi) GetRequiredPoWForAccountBlock(param GetRequiredParam) (*GetRequiredResult, error)

GetRequiredPoWForAccountBlock calculates the PoW difficulty required for a transaction based on available plasma.

This determines whether:

  • The transaction can be feeless (sufficient plasma)
  • PoW is needed and how much difficulty

The required PoW decreases as plasma increases. With enough plasma, no PoW is needed.

Parameters:

  • param: GetRequiredParam containing the account block to check

Returns GetRequiredResult with:

  • AvailablePlasma: Current plasma available
  • BasePlasma: Base plasma requirement
  • RequiredDifficulty: PoW difficulty needed (0 if plasma sufficient)

Example:

param := embedded.GetRequiredParam{
    AccountBlock: accountBlock,
    Address:      address,
}

result, err := client.PlasmaApi.GetRequiredPoWForAccountBlock(param)
if err != nil {
    log.Fatal(err)
}

if result.RequiredDifficulty == 0 {
    fmt.Println("Transaction can be feeless")
} else {
    fmt.Printf("PoW difficulty required: %d\n", result.RequiredDifficulty)
    // Generate PoW with this difficulty
}

Call this before publishing a transaction to determine if PoW generation is needed.

type PlasmaInfo added in v0.1.9

type PlasmaInfo struct {
	CurrentPlasma uint64   `json:"currentPlasma"`
	MaxPlasma     uint64   `json:"maxPlasma"`
	QsrAmount     *big.Int `json:"qsrAmount"`
}

PlasmaInfo represents plasma information for an address.

Plasma is the resource required to send transactions on the Zenon Network. It can be obtained by fusing QSR (generating plasma over time) or by computing Proof-of-Work for individual transactions.

Fields:

  • CurrentPlasma: Available plasma units for transactions
  • MaxPlasma: Maximum plasma capacity based on fused QSR
  • QsrAmount: Total QSR fused for this address (in base units, 8 decimals)

Plasma regenerates over time proportional to the fused QSR amount. More fused QSR means faster regeneration and higher maximum capacity.

Example:

plasma, err := client.PlasmaApi.Get(address)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Plasma: %d / %d (Fused: %s QSR)\n",
    plasma.CurrentPlasma, plasma.MaxPlasma, plasma.QsrAmount)

func (*PlasmaInfo) UnmarshalJSON added in v0.1.9

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

type Project added in v0.1.9

type Project struct {
	Id                  types.Hash     `json:"id"`
	Owner               types.Address  `json:"owner"`
	Name                string         `json:"name"`
	Description         string         `json:"description"`
	Url                 string         `json:"url"`
	ZnnFundsNeeded      *big.Int       `json:"znnFundsNeeded"`
	QsrFundsNeeded      *big.Int       `json:"qsrFundsNeeded"`
	CreationTimestamp   int64          `json:"creationTimestamp"`
	LastUpdateTimestamp int64          `json:"lastUpdateTimestamp"`
	Status              uint8          `json:"status"`
	PhaseIds            []types.Hash   `json:"phaseIds"`
	Votes               *VoteBreakdown `json:"votes"`
	Phases              []*Phase       `json:"phases"`
}

Project represents an Accelerator-Z project.

Accelerator-Z is Zenon's ecosystem fund that supports community development projects. Projects request funding in ZNN and QSR, and Pillars vote to approve or reject them.

Fields:

  • Id: Unique identifier for this project
  • Owner: Address that submitted and manages the project
  • Name: Human-readable name of the project
  • Description: Detailed description of project goals and deliverables
  • Url: Link to additional information or documentation
  • ZnnFundsNeeded: Total ZNN funding requested (in base units, 8 decimals)
  • QsrFundsNeeded: Total QSR funding requested (in base units, 8 decimals)
  • CreationTimestamp: Unix timestamp when project was submitted
  • LastUpdateTimestamp: Unix timestamp of last modification
  • Status: Current project status
  • PhaseIds: List of phase identifiers for this project
  • Votes: Current voting results for the project
  • Phases: Detailed phase information with voting data

Example:

projects, err := client.AcceleratorApi.GetAll(0, 10)
if err != nil {
    log.Fatal(err)
}
for _, project := range projects.List {
    fmt.Printf("Project: %s, Votes: %d/%d\n",
        project.Name, project.Votes.Yes, project.Votes.Total)
}

func (*Project) UnmarshalJSON added in v0.1.9

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

type ProjectList added in v0.1.9

type ProjectList struct {
	Count int        `json:"count"`
	List  []*Project `json:"list"`
}

ProjectList represents a paginated list of projects.

This type is returned by methods that list Accelerator-Z projects, such as GetAll.

Fields:

  • Count: Total number of projects matching the query
  • List: Slice of Project entries for the current page

type RewardHistoryEntry added in v0.1.9

type RewardHistoryEntry struct {
	Epoch     uint64   `json:"epoch"`
	ZnnAmount *big.Int `json:"znnAmount"`
	QsrAmount *big.Int `json:"qsrAmount"`
}

RewardHistoryEntry represents a single reward collection event.

This type records historical reward distributions by epoch. It is used in paginated lists returned by GetFrontierRewardByPage methods.

Fields:

  • Epoch: The epoch number when rewards were distributed
  • ZnnAmount: ZNN rewards for this epoch (in base units, 8 decimals)
  • QsrAmount: QSR rewards for this epoch (in base units, 8 decimals)

func (*RewardHistoryEntry) UnmarshalJSON added in v0.1.9

func (r *RewardHistoryEntry) UnmarshalJSON(data []byte) error

type RewardHistoryList added in v0.1.9

type RewardHistoryList struct {
	Count int                   `json:"count"`
	List  []*RewardHistoryEntry `json:"list"`
}

RewardHistoryList represents a paginated list of reward history entries

type SecurityInfo added in v0.1.9

type SecurityInfo struct {
	Guardians          []types.Address `json:"guardians"`
	GuardiansVotes     []types.Address `json:"guardiansVotes"`
	AdministratorDelay uint64          `json:"administratorDelay"`
	SoftDelay          uint64          `json:"softDelay"`
}

SecurityInfo represents security configuration for embedded contracts

type SentinelApi

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

func NewSentinelApi

func NewSentinelApi(client *server.Client) *SentinelApi

func (*SentinelApi) CollectReward

func (sa *SentinelApi) CollectReward() *nom.AccountBlock

func (*SentinelApi) DepositQsr

func (sa *SentinelApi) DepositQsr(amount *big.Int) *nom.AccountBlock

func (*SentinelApi) GetAllActive

func (sa *SentinelApi) GetAllActive(pageIndex, pageSize uint32) (*SentinelInfoList, error)

func (*SentinelApi) GetByOwner

func (sa *SentinelApi) GetByOwner(address types.Address) (*SentinelInfo, error)

func (*SentinelApi) GetDepositedQsr

func (sa *SentinelApi) GetDepositedQsr(address types.Address) (*big.Int, error)

func (*SentinelApi) GetFrontierRewardByPage

func (sa *SentinelApi) GetFrontierRewardByPage(address types.Address, pageIndex, pageSize uint32) (*RewardHistoryList, error)

func (*SentinelApi) GetUncollectedReward

func (sa *SentinelApi) GetUncollectedReward(address types.Address) (*UncollectedReward, error)

func (*SentinelApi) Register

func (sa *SentinelApi) Register() *nom.AccountBlock

Register creates a transaction template to register a new Sentinel.

Sentinels are network infrastructure nodes that provide reliability and support. Running a Sentinel requires:

  • 5,000 ZNN collateral (locked, returned upon revocation)
  • 50,000 QSR collateral (locked, returned upon revocation)
  • Dedicated node infrastructure

Sentinel benefits:

  • Earn ZNN and QSR rewards
  • Support network infrastructure
  • Lower barrier than Pillar operation
  • Collateral fully returned on revocation

Returns an unsigned AccountBlock template ready for processing.

Example:

template := client.SentinelApi.Register()
// Sign and publish transaction
// Requires 5,000 ZNN + 50,000 QSR

Note: Ensure you have sufficient ZNN and QSR before attempting registration.

func (*SentinelApi) Revoke

func (sa *SentinelApi) Revoke() *nom.AccountBlock

func (*SentinelApi) WithdrawQsr

func (sa *SentinelApi) WithdrawQsr() *nom.AccountBlock

type SentinelInfo added in v0.1.9

type SentinelInfo struct {
	Owner                 types.Address `json:"owner"`
	RegistrationTimestamp int64         `json:"registrationTimestamp"`
	IsRevocable           bool          `json:"isRevocable"`
	RevokeCooldown        int64         `json:"revokeCooldown"`
	Active                bool          `json:"active"`
}

SentinelInfo represents detailed information about a Sentinel.

Sentinels are infrastructure nodes that support the Zenon Network by providing additional network services. They require a collateral deposit of ZNN and QSR and earn rewards for their participation.

Fields:

  • Owner: Address that owns and controls the Sentinel
  • RegistrationTimestamp: Unix timestamp when the Sentinel was registered
  • IsRevocable: Whether the Sentinel can be revoked (after cooldown period)
  • RevokeCooldown: Remaining cooldown time before revocation completes
  • Active: Whether the Sentinel is currently active and earning rewards

Collateral Requirements:

  • 5,000 ZNN
  • 50,000 QSR

Example:

sentinel, err := client.SentinelApi.GetByOwner(address)
if err != nil {
    log.Fatal(err)
}
if sentinel.Active {
    fmt.Printf("Sentinel owned by %s is active\n", sentinel.Owner)
}

type SentinelInfoList added in v0.1.9

type SentinelInfoList struct {
	Count int             `json:"count"`
	List  []*SentinelInfo `json:"list"`
}

SentinelInfoList represents a paginated list of Sentinels.

This type is returned by methods that list multiple Sentinels, such as GetAllActive.

Fields:

  • Count: Total number of Sentinels matching the query
  • List: Slice of SentinelInfo entries for the current page

type Spork added in v0.1.9

type Spork struct {
	Id                types.Hash `json:"id"`
	Name              string     `json:"name"`
	Description       string     `json:"description"`
	Activated         bool       `json:"activated"`
	EnforcementHeight uint64     `json:"enforcementHeight"`
}

Spork represents a protocol spork configuration.

Sporks are protocol upgrade mechanisms that allow the network to activate new features or changes at a specific block height. Once activated, nodes must comply with the new rules after the enforcement height.

Fields:

  • Id: Unique identifier for this spork
  • Name: Human-readable name of the spork
  • Description: Detailed description of what this spork enables
  • Activated: Whether the spork has been activated
  • EnforcementHeight: Momentum height when the spork becomes mandatory

Spork Lifecycle:

  1. Spork is created but not activated
  2. Spork is activated by governance
  3. After EnforcementHeight, all nodes must support the new feature

type SporkApi

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

func NewSporkApi

func NewSporkApi(client *server.Client) *SporkApi

func (*SporkApi) ActivateSpork added in v0.1.13

func (sa *SporkApi) ActivateSpork(id types.Hash) *nom.AccountBlock

ActivateSpork creates a transaction template that activates an existing spork.

Parameters:

  • id: Hash identifier of the spork to activate (returned by GetAll)

Returns an unsigned AccountBlock template ready for signing and publishing.

Reference: znn_sdk_dart/lib/src/api/embedded/spork.dart:28-31

func (*SporkApi) CreateSpork added in v0.1.13

func (sa *SporkApi) CreateSpork(name, description string) *nom.AccountBlock

CreateSpork creates a transaction template that proposes a new spork.

Sporks are protocol-feature flags governed by the spork administrator. After creation, a spork must be activated via ActivateSpork before its enforcement height takes effect across the network.

Parameters:

  • name: Human-readable spork name
  • description: Description of the protocol change the spork enables

Returns an unsigned AccountBlock template ready for signing and publishing.

Reference: znn_sdk_dart/lib/src/api/embedded/spork.dart:23-26

func (*SporkApi) GetAll

func (sa *SporkApi) GetAll(pageIndex, pageSize uint32) (*SporkList, error)

GetAll retrieves a paginated list of all sporks.

Sporks are protocol activation mechanisms that enable/disable features across the network in a coordinated manner. They allow safe protocol upgrades without hard forks.

Parameters:

  • pageIndex: Page number (0-indexed)
  • pageSize: Number of sporks per page

Returns spork list or an error.

Example:

sporks, err := client.SporkApi.GetAll(0, 10)
if err != nil {
    log.Fatal(err)
}
for _, spork := range sporks.List {
    fmt.Printf("Spork: %s, Active: %t\n", spork.Name, spork.Activated)
}

type SporkList added in v0.1.9

type SporkList struct {
	Count int      `json:"count"`
	List  []*Spork `json:"list"`
}

SporkList represents a paginated list of sporks.

Fields:

  • Count: Total number of sporks matching the query
  • List: Slice of Spork entries for the current page

type StakeApi

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

func NewStakeApi

func NewStakeApi(client *server.Client) *StakeApi

func (*StakeApi) Cancel

func (sa *StakeApi) Cancel(id types.Hash) *nom.AccountBlock

Cancel creates a transaction template to cancel an expired stake and reclaim ZNN.

After a stake's duration expires, you must explicitly cancel it to reclaim your ZNN. The staked amount returns to your balance, but the stake entry remains until canceled.

Cancellation requirements:

  • Stake duration must have fully elapsed
  • Cannot cancel before expiration timestamp
  • Stake ID obtained from GetEntriesByAddress()

Process:

  1. Check stake entries with GetEntriesByAddress()
  2. Find entries where ExpirationTimestamp has passed
  3. Cancel using the stake's ID
  4. Staked ZNN returns to your balance

Parameters:

  • id: Hash ID of the stake entry to cancel (from GetEntriesByAddress)

Returns an unsigned AccountBlock template ready for processing.

Example - Cancel expired stake:

// Get stake entries
stakes, _ := client.StakeApi.GetEntriesByAddress(address, 0, 10)

// Find expired stakes
now := time.Now().Unix()
for _, stake := range stakes.List {
    if stake.ExpirationTimestamp <= now {
        // This stake has expired, can cancel
        template := client.StakeApi.Cancel(stake.Id)
        // Sign and publish transaction
        fmt.Printf("Canceling stake: %s ZNN\n", stake.Amount)
    }
}

Example - Cancel specific stake by ID:

stakeId := types.HexToHashPanic("0x123...")
template := client.StakeApi.Cancel(stakeId)
// Process and publish

Note: Always check expiration timestamp before attempting to cancel. Canceling before expiration will fail.

func (*StakeApi) CollectReward

func (sa *StakeApi) CollectReward() *nom.AccountBlock

CollectReward creates a transaction template to claim accumulated staking rewards.

Staking rewards (both ZNN and QSR) accumulate automatically but must be explicitly collected. This transaction withdraws all uncollected rewards to your balance.

Reward collection:

  • Collects both ZNN and QSR rewards simultaneously
  • No minimum amount required to collect
  • Can collect as frequently as desired
  • Rewards continue accruing after collection

Typical collection strategies:

  • Regular collection (e.g., weekly/monthly)
  • Collect when rewards reach target threshold
  • Compound by restaking collected ZNN
  • Collect before stake cancellation

Returns an unsigned AccountBlock template ready for processing.

Example - Basic reward collection:

// Check uncollected rewards
rewards, _ := client.StakeApi.GetUncollectedReward(myAddress)

if rewards.Znn.Cmp(big.NewInt(0)) > 0 || rewards.Qsr.Cmp(big.NewInt(0)) > 0 {
    fmt.Printf("Collecting: %s ZNN, %s QSR\n", rewards.Znn, rewards.Qsr)
    template := client.StakeApi.CollectReward()
    // Sign and publish transaction
}

Example - Collect before canceling stakes:

// Always collect rewards before canceling stakes
collectTemplate := client.StakeApi.CollectReward()
// Publish collect transaction

// Then cancel expired stakes
// This ensures no rewards are left unclaimed

Example - Compound rewards (collect and restake):

rewards, _ := client.StakeApi.GetUncollectedReward(myAddress)
if rewards.Znn.Cmp(big.NewInt(100000000)) > 0 { // At least 1 ZNN
    // Collect rewards
    collectTemplate := client.StakeApi.CollectReward()
    // After collection confirms, restake the ZNN
    stakeTemplate := client.StakeApi.Stake(31536000, rewards.Znn)
}

Note: Collection requires a small amount of PoW/plasma. Ensure you have sufficient resources before attempting to collect.

func (*StakeApi) GetEntriesByAddress

func (sa *StakeApi) GetEntriesByAddress(address types.Address, pageIndex, pageSize uint32) (*StakeList, error)

GetEntriesByAddress retrieves all active stake entries for an address.

Each stake entry represents a separate staking commitment with:

  • Staked amount (ZNN)
  • Start timestamp
  • Expiration timestamp
  • Duration in months (1, 3, 6, or 12)
  • Unique stake ID for cancellation

Use this to:

  • Monitor active stakes
  • Check when stakes expire
  • Find stakes eligible for cancellation
  • Calculate total staked amount

Parameters:

  • address: Address to query stake entries for
  • pageIndex: Page number (0-indexed)
  • pageSize: Number of entries per page

Returns paginated stake list or an error.

Example:

stakes, err := client.StakeApi.GetEntriesByAddress(address, 0, 10)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Active stakes: %d\n", stakes.Count)
totalStaked := big.NewInt(0)
for _, stake := range stakes.List {
    totalStaked.Add(totalStaked, stake.Amount)
    fmt.Printf("Stake: %s ZNN, expires at %v\n",
        stake.Amount, stake.ExpirationTimestamp)
}
fmt.Printf("Total staked: %s ZNN\n", totalStaked)

func (*StakeApi) GetFrontierRewardByPage

func (sa *StakeApi) GetFrontierRewardByPage(address types.Address, pageIndex, pageSize uint32) (*RewardHistoryList, error)

GetFrontierRewardByPage retrieves a paginated history of collected staking rewards.

This provides a historical record of all reward collections, useful for:

  • Tracking reward earnings over time
  • Auditing reward history
  • Analyzing staking performance
  • Generating reward reports

Each entry includes:

  • ZNN and QSR amounts collected
  • Timestamp of collection
  • Momentum height when collected

Parameters:

  • address: Address to query reward history for
  • pageIndex: Page number (0-indexed)
  • pageSize: Number of entries per page

Returns paginated reward history or an error.

Example:

history, err := client.StakeApi.GetFrontierRewardByPage(address, 0, 25)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Total reward collections: %d\n", history.Count)
for _, entry := range history.List {
    fmt.Printf("Collected: %s ZNN, %s QSR at momentum %d\n",
        entry.Znn, entry.Qsr, entry.Height)
}

func (*StakeApi) GetUncollectedReward

func (sa *StakeApi) GetUncollectedReward(address types.Address) (*UncollectedReward, error)

GetUncollectedReward retrieves pending staking rewards that haven't been collected yet.

Staking ZNN generates rewards over time. These rewards accumulate and must be explicitly collected using CollectReward(). This method shows the current uncollected amount available for withdrawal.

Returns a RewardDeposit containing:

  • Qsr: Pending QSR rewards
  • Znn: Pending ZNN rewards

Parameters:

  • address: Address to check for uncollected rewards

Returns reward deposit information or an error.

Example:

rewards, err := client.StakeApi.GetUncollectedReward(address)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Uncollected ZNN: %s\n", rewards.Znn)
fmt.Printf("Uncollected QSR: %s\n", rewards.Qsr)

// Collect rewards if any available
if rewards.Qsr.Cmp(big.NewInt(0)) > 0 || rewards.Znn.Cmp(big.NewInt(0)) > 0 {
    template := client.StakeApi.CollectReward()
    // Sign and publish transaction
}

func (*StakeApi) Stake

func (sa *StakeApi) Stake(durationInSec int64, amount *big.Int) *nom.AccountBlock

Stake creates a transaction template to stake ZNN and earn rewards.

Staking is Zenon's native yield mechanism. By locking ZNN for a specified duration, you earn both ZNN and QSR rewards proportional to the amount and duration.

Staking parameters:

  • Minimum amount: 1 ZNN (10^8 base units)
  • Duration options (in seconds):
  • 1 month: 2592000 (30 days)
  • 3 months: 7776000 (90 days)
  • 6 months: 15552000 (180 days)
  • 12 months: 31536000 (365 days)
  • Longer durations = higher rewards
  • Can stake multiple times with different durations

Reward mechanics:

  • Rewards begin accruing immediately after staking
  • Must call CollectReward() to claim accumulated rewards
  • Stake entries are locked until duration expires
  • Early cancellation not possible

Parameters:

  • durationInSec: Stake duration in seconds (must match valid options above)
  • amount: Amount of ZNN to stake (in base units: 1 ZNN = 10^8)

Returns an unsigned AccountBlock template ready for processing.

Example - Stake for 1 month:

amount := big.NewInt(100 * 100000000)  // Stake 100 ZNN
duration := int64(2592000)             // 1 month in seconds

template := client.StakeApi.Stake(duration, amount)
// Sign and publish transaction

Example - Stake for maximum rewards (12 months):

amount := big.NewInt(1000 * 100000000) // Stake 1000 ZNN
duration := int64(31536000)            // 12 months = highest rewards

template := client.StakeApi.Stake(duration, amount)
// Process through transaction pipeline

Example - Multiple stake entries:

// Diversify by creating multiple stakes with different durations
stake1 := client.StakeApi.Stake(2592000, big.NewInt(100*100000000))  // 1 month
stake2 := client.StakeApi.Stake(15552000, big.NewInt(500*100000000)) // 6 months
// Each creates a separate entry with different expiration times

Note: Staked ZNN is locked and cannot be withdrawn until the duration expires. Plan your liquidity needs accordingly.

type StakeEntry added in v0.1.9

type StakeEntry struct {
	Amount              *big.Int      `json:"amount"`
	WeightedAmount      *big.Int      `json:"weightedAmount"`
	StartTimestamp      int64         `json:"startTimestamp"`
	ExpirationTimestamp int64         `json:"expirationTimestamp"`
	Address             types.Address `json:"address"`
	Id                  types.Hash    `json:"id"`
}

StakeEntry represents a single staking entry.

Users can stake ZNN for various durations (1-12 months) to earn QSR rewards. Longer staking durations receive higher reward multipliers. This type contains information about an individual stake.

Fields:

  • Amount: Staked amount (in base units, 8 decimals)
  • WeightedAmount: Amount multiplied by duration factor for reward calculation
  • StartTimestamp: Unix timestamp when the stake was created
  • ExpirationTimestamp: Unix timestamp when the stake can be canceled
  • Address: Address that owns this stake
  • Id: Unique identifier for this stake entry

Duration Multipliers:

  • 1 month: 1x weight
  • 3 months: 3x weight
  • 6 months: 6x weight
  • 12 months: 12x weight

Example:

stakes, err := client.StakeApi.GetEntriesByAddress(address, 0, 10)
if err != nil {
    log.Fatal(err)
}
for _, stake := range stakes.List {
    expired := stake.ExpirationTimestamp <= time.Now().Unix()
    fmt.Printf("Stake: %s ZNN, Expired: %t\n", stake.Amount, expired)
}

func (*StakeEntry) UnmarshalJSON added in v0.1.9

func (s *StakeEntry) UnmarshalJSON(data []byte) error

type StakeList added in v0.1.9

type StakeList struct {
	TotalAmount         *big.Int      `json:"totalAmount"`
	TotalWeightedAmount *big.Int      `json:"totalWeightedAmount"`
	Count               int           `json:"count"`
	List                []*StakeEntry `json:"list"`
}

StakeList represents a paginated list of stake entries.

This type is returned by methods that list stakes, such as GetEntriesByAddress. It includes aggregate totals for all stakes belonging to the address.

Fields:

  • TotalAmount: Sum of all staked amounts (in base units, 8 decimals)
  • TotalWeightedAmount: Sum of all weighted amounts for reward calculation
  • Count: Total number of stake entries matching the query
  • List: Slice of StakeEntry entries for the current page

Example:

stakes, err := client.StakeApi.GetEntriesByAddress(address, 0, 10)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Total staked: %s ZNN across %d entries\n",
    stakes.TotalAmount, stakes.Count)

func (*StakeList) UnmarshalJSON added in v0.1.9

func (s *StakeList) UnmarshalJSON(data []byte) error

type SwapApi

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

func NewSwapApi

func NewSwapApi(client *server.Client) *SwapApi

func (*SwapApi) GetAssets

func (sa *SwapApi) GetAssets() (map[types.Hash]*SwapAssetEntrySimple, error)

func (*SwapApi) GetAssetsByKeyIdHash

func (sa *SwapApi) GetAssetsByKeyIdHash(keyIdHash types.Hash) (*SwapAssetEntry, error)

GetAssetsByKeyIdHash retrieves swap asset information by key ID hash.

The Swap contract manages the legacy swap from old Zenon assets. This query returns information about swapped assets for a specific key.

Parameters:

  • keyIdHash: Hash of the key ID to query

Returns swap asset entry or an error.

func (*SwapApi) GetLegacyPillars

func (sa *SwapApi) GetLegacyPillars() ([]*SwapLegacyPillarEntry, error)

func (*SwapApi) GetSwapDecayPercentage added in v0.1.13

func (sa *SwapApi) GetSwapDecayPercentage(currentTimestamp int64) int

GetSwapDecayPercentage returns the percentage of the swap that has decayed at the given Unix timestamp. The result is the inverse of percentageToGive in the Dart reference (i.e. 0 means no decay, 100 means fully decayed).

Decay schedule (mirrors reference/.../lib/src/embedded/constants.dart):

  • Before SwapAssetDecayTimestampStart: 0% decay
  • After: every SwapAssetDecayTickEpochs days past the offset, the decay grows by SwapAssetDecayTickValuePercentage percentage points until 100%

Pure helper — no RPC call.

Reference: znn_sdk_dart/lib/src/api/embedded/swap.dart:44-61

func (*SwapApi) RetrieveAssets added in v0.1.13

func (sa *SwapApi) RetrieveAssets(publicKey, signature string) *nom.AccountBlock

RetrieveAssets creates a transaction template that retrieves swapped assets using a public key and signature proving ownership of the legacy key.

Reference: znn_sdk_dart/lib/src/api/embedded/swap.dart:39-42

type SwapAssetEntry added in v0.1.9

type SwapAssetEntry struct {
	KeyIdHash types.Hash `json:"keyIdHash"`
	Qsr       *big.Int   `json:"qsr"`
	Znn       *big.Int   `json:"znn"`
}

SwapAssetEntry represents swap asset information with full details.

This type is used for the legacy network swap functionality, which allows users who held tokens on the legacy Zenon network to claim their tokens on the current network.

Fields:

  • KeyIdHash: Hash identifier linking to the legacy network address
  • Qsr: QSR amount available to claim (in base units, 8 decimals)
  • Znn: ZNN amount available to claim (in base units, 8 decimals)

func (*SwapAssetEntry) HasBalance added in v0.1.9

func (s *SwapAssetEntry) HasBalance() bool

HasBalance returns true if there is any remaining balance.

This method checks whether there are any unclaimed tokens (either ZNN or QSR) available in this swap entry.

Returns:

  • true if either Qsr or Znn has a positive balance
  • false if both balances are zero or negative

func (*SwapAssetEntry) UnmarshalJSON added in v0.1.9

func (s *SwapAssetEntry) UnmarshalJSON(data []byte) error

type SwapAssetEntrySimple added in v0.1.9

type SwapAssetEntrySimple struct {
	Qsr *big.Int `json:"qsr"`
	Znn *big.Int `json:"znn"`
}

SwapAssetEntrySimple represents simplified swap asset information.

A simplified version of SwapAssetEntry without the KeyIdHash, used when only the token amounts are needed.

Fields:

  • Qsr: QSR amount (in base units, 8 decimals)
  • Znn: ZNN amount (in base units, 8 decimals)

func (*SwapAssetEntrySimple) UnmarshalJSON added in v0.1.9

func (s *SwapAssetEntrySimple) UnmarshalJSON(data []byte) error

type SwapLegacyPillarEntry added in v0.1.9

type SwapLegacyPillarEntry struct {
	NumPillars int        `json:"numPillars"`
	KeyIdHash  types.Hash `json:"keyIdHash"`
}

SwapLegacyPillarEntry represents a legacy pillar swap entry.

This type is used for legacy pillar holders who need to claim their pillar slots on the current network.

Fields:

  • NumPillars: Number of pillar slots to claim
  • KeyIdHash: Hash identifier linking to the legacy network address

type TimeChallengeInfo added in v0.1.9

type TimeChallengeInfo struct {
	MethodName           string     `json:"MethodName"`
	ParamsHash           types.Hash `json:"ParamsHash"`
	ChallengeStartHeight uint64     `json:"ChallengeStartHeight"`
}

TimeChallengeInfo represents a time challenge for administrative operations

type TimeChallengesList added in v0.1.9

type TimeChallengesList struct {
	Count int                  `json:"count"`
	List  []*TimeChallengeInfo `json:"list"`
}

TimeChallengesList represents a list of time challenges

type Token added in v0.1.9

type Token struct {
	Name          string                   `json:"name"`
	Symbol        string                   `json:"symbol"`
	Domain        string                   `json:"domain"`
	TotalSupply   *big.Int                 `json:"totalSupply"`
	Decimals      uint8                    `json:"decimals"`
	Owner         types.Address            `json:"owner"`
	TokenStandard types.ZenonTokenStandard `json:"tokenStandard"`
	MaxSupply     *big.Int                 `json:"maxSupply"`
	IsBurnable    bool                     `json:"isBurnable"`
	IsMintable    bool                     `json:"isMintable"`
	IsUtility     bool                     `json:"isUtility"`
}

Token represents detailed information about a ZTS (Zenon Token Standard) token.

ZTS tokens are native tokens on the Zenon Network. Any address can issue new tokens with customizable properties including supply limits, mintability, and burnability.

Fields:

  • Name: Human-readable name of the token (e.g., "Zenon")
  • Symbol: Short ticker symbol (e.g., "ZNN")
  • Domain: Associated domain for verification (optional)
  • TotalSupply: Current circulating supply (in base units)
  • Decimals: Number of decimal places (typically 8)
  • Owner: Address that controls minting and token updates
  • TokenStandard: Unique ZTS identifier for this token
  • MaxSupply: Maximum possible supply (in base units)
  • IsBurnable: Whether token holders can burn their tokens
  • IsMintable: Whether the owner can mint additional tokens
  • IsUtility: Whether this is a utility token

Built-in Tokens:

  • ZNN (types.ZnnTokenStandard): The native governance token
  • QSR (types.QsrTokenStandard): The native utility token for plasma

Example:

token, err := client.TokenApi.GetByZts(types.ZnnTokenStandard)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Token: %s (%s)\n", token.Name, token.Symbol)
fmt.Printf("Supply: %s / %s\n", token.TotalSupply, token.MaxSupply)

func (*Token) UnmarshalJSON added in v0.1.9

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

type TokenApi

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

func NewTokenApi

func NewTokenApi(client *server.Client) *TokenApi

func (*TokenApi) Burn

func (ta *TokenApi) Burn(tokenStandard types.ZenonTokenStandard, amount *big.Int) *nom.AccountBlock

Burn creates a transaction template to permanently destroy tokens.

Burning requirements:

  • Token must have isBurnable = true
  • Can be called by any token holder
  • Burns tokens from caller's balance
  • Reduces total supply permanently

Common burn use cases:

  • Deflationary tokenomics
  • Fee mechanisms (burn fees)
  • Supply management
  • Protocol buyback and burn programs

Parameters:

  • tokenStandard: ZTS identifier of the token to burn
  • amount: Number of tokens to burn (in base units)

Returns an unsigned AccountBlock template ready for processing.

Example - Burn tokens from your balance:

zts := types.ParseZTS("zts1your-token-standard")
amount := big.NewInt(500 * 100000000) // Burn 500 tokens

template := client.TokenApi.Burn(zts, amount)
// Sign and publish transaction

Example - Burn 10% of holdings:

// Get current balance first
info, _ := client.LedgerApi.GetAccountInfoByAddress(myAddress)
balance := info.BalanceInfoMap[myTokenZts].Balance

// Burn 10%
burnAmount := new(big.Int).Div(balance, big.NewInt(10))
template := client.TokenApi.Burn(myTokenZts, burnAmount)

Note: Burning is permanent and irreversible. Ensure you have sufficient balance before attempting to burn. Transaction will fail if amount exceeds your balance.

func (*TokenApi) GetAll

func (ta *TokenApi) GetAll(pageIndex, pageSize uint32) (*TokenList, error)

GetAll retrieves a paginated list of all tokens issued on the Zenon Network.

This includes both native tokens (ZNN, QSR) and all ZTS (Zenon Token Standard) tokens created by users. Each token entry contains metadata like name, symbol, domain, supply information, and ownership details.

Parameters:

  • pageIndex: Page number (0-indexed)
  • pageSize: Number of tokens per page (typically 10-50)

Returns a TokenList containing token entries or an error if the query fails.

Example:

// Get first page of all tokens
tokens, err := client.TokenApi.GetAll(0, 25)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Total tokens: %d\n", tokens.Count)
for _, token := range tokens.List {
    fmt.Printf("%s (%s): %s\n", token.Name, token.Symbol, token.TokenStandard)
}

func (*TokenApi) GetByOwner

func (ta *TokenApi) GetByOwner(address types.Address, pageIndex, pageSize uint32) (*TokenList, error)

GetByOwner retrieves a paginated list of tokens owned by a specific address.

Token owners can:

  • Update token properties (if enabled)
  • Mint additional supply (if mintable)
  • Transfer ownership to another address

This is useful for:

  • Managing your own tokens
  • Auditing tokens owned by an address
  • Tracking token portfolios

Parameters:

  • address: Token owner address
  • pageIndex: Page number (0-indexed)
  • pageSize: Number of tokens per page

Returns a TokenList of owned tokens or an error.

Example:

ownerAddr := types.ParseAddressPanic("z1qqjnwjjpnue8xmmpanz6csze6tcmtzzdtfsww7")
tokens, err := client.TokenApi.GetByOwner(ownerAddr, 0, 10)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Tokens owned: %d\n", tokens.Count)
for _, token := range tokens.List {
    fmt.Printf("- %s (%s)\n", token.Name, token.Symbol)
}

func (*TokenApi) GetByZts

func (ta *TokenApi) GetByZts(zts types.ZenonTokenStandard) (*Token, error)

GetByZts retrieves detailed information about a specific token by its ZTS identifier.

Returns complete token metadata including:

  • Name, symbol, and domain
  • Total supply, max supply, and decimals
  • Owner address
  • Properties: isMintable, isBurnable, isUtility
  • Token standard identifier (ZTS)

Use this to:

  • Verify token properties before transactions
  • Check supply limits before minting
  • Validate token ownership
  • Display token information in applications

Parameters:

  • zts: Token standard identifier (types.ZnnTokenStandard, types.QsrTokenStandard, or custom ZTS)

Returns detailed Token information or an error if the token doesn't exist.

Example:

// Get ZNN token info
token, err := client.TokenApi.GetByZts(types.ZnnTokenStandard)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Token: %s (%s)\n", token.Name, token.Symbol)
fmt.Printf("Total Supply: %s\n", token.TotalSupply)
fmt.Printf("Decimals: %d\n", token.Decimals)
fmt.Printf("Mintable: %t, Burnable: %t\n", token.IsMintable, token.IsBurnable)

func (*TokenApi) IssueToken

func (ta *TokenApi) IssueToken(tokenName, tokenSymbol, tokenDomain string, totalSupply, maxSupply *big.Int, decimals uint8, isMintable, isBurnable, isUtility bool) *nom.AccountBlock

IssueToken creates a transaction template to issue a new ZTS token on Zenon Network.

Token issuance allows anyone to create custom tokens following the ZTS (Zenon Token Standard). The issuing address becomes the token owner with special privileges.

Token requirements:

  • Cost: 1 ZNN (burned as protocol fee)
  • Name: 1-40 characters
  • Symbol: 1-10 uppercase characters
  • Domain: Optional metadata field (max 128 chars)
  • TotalSupply: Initial minted supply (can be 0)
  • MaxSupply: Maximum possible supply (must be >= totalSupply)
  • Decimals: 0-18 (typically 8 for ZNN/QSR compatibility)

Token properties (permanent once set false):

  • isMintable: Owner can mint additional supply up to maxSupply
  • isBurnable: Token holders can burn their tokens
  • isUtility: Marks token as utility token (metadata flag)

Parameters:

  • tokenName: Human-readable token name
  • tokenSymbol: Short trading symbol (uppercase)
  • tokenDomain: Optional domain/URL for token metadata
  • totalSupply: Initial supply to mint (in base units)
  • maxSupply: Maximum total supply allowed (in base units)
  • decimals: Number of decimal places (0-18)
  • isMintable: Enable future minting by owner
  • isBurnable: Enable token burning by holders
  • isUtility: Flag as utility token

Returns an unsigned AccountBlock template that must be:

  1. Autofilled with account details
  2. Enhanced with PoW/plasma
  3. Signed with keypair
  4. Published via PublishRawTransaction

Example - Issue mintable token:

totalSupply := big.NewInt(1000000 * 100000000) // 1M tokens with 8 decimals
maxSupply := big.NewInt(10000000 * 100000000)  // 10M max

template := client.TokenApi.IssueToken(
    "My Token",           // name
    "MTK",                // symbol
    "example.com",        // domain
    totalSupply,          // initial supply
    maxSupply,            // maximum supply
    8,                    // decimals
    true,                 // mintable
    true,                 // burnable
    false,                // not utility token
)
// Process through transaction pipeline and publish

Example - Issue fixed supply token:

supply := big.NewInt(21000000 * 100000000) // 21M tokens (Bitcoin-style)

template := client.TokenApi.IssueToken(
    "Fixed Token",
    "FTK",
    "",
    supply,              // total supply
    supply,              // max = total (fixed)
    8,
    false,               // not mintable
    false,               // not burnable
    false,
)

Note: Token issuance costs 1 ZNN which is burned. Ensure you have sufficient balance plus plasma/PoW for the transaction.

func (*TokenApi) Mint

func (ta *TokenApi) Mint(tokenStandard types.ZenonTokenStandard, amount *big.Int, receiver types.Address) *nom.AccountBlock

Mint creates a transaction template to mint additional tokens.

Minting requirements:

  • Must be called by token owner
  • Token must have isMintable = true
  • Cannot exceed maxSupply limit
  • Newly minted tokens sent to receiver address

This is commonly used for:

  • Increasing token supply over time
  • Reward distribution programs
  • Protocol-controlled token emission
  • Gradual token launches

Parameters:

  • tokenStandard: ZTS identifier of the token to mint
  • amount: Number of tokens to mint (in base units)
  • receiver: Address that will receive the newly minted tokens

Returns an unsigned AccountBlock template ready for processing.

Example - Mint tokens to specific address:

zts := types.ParseZTS("zts1your-token-standard")
amount := big.NewInt(1000 * 100000000) // 1000 tokens with 8 decimals
receiver := types.ParseAddressPanic("z1qqjnwjjpnue8xmmpanz6csze6tcmtzzdtfsww7")

template := client.TokenApi.Mint(zts, amount, receiver)
// Sign and publish transaction

Example - Mint to own address:

template := client.TokenApi.Mint(myTokenZts, amount, myAddress)
// Process and publish

Note: Only the token owner can mint. Attempting to mint as non-owner will fail. Verify token properties and current supply with GetByZts() before minting.

func (*TokenApi) UpdateToken

func (ta *TokenApi) UpdateToken(tokenStandard types.ZenonTokenStandard, owner types.Address, isMintable, isBurnable bool) *nom.AccountBlock

UpdateToken creates a transaction template to update token properties.

Update capabilities:

  • Transfer ownership to a new address
  • Disable minting (cannot be re-enabled)
  • Disable burning (cannot be re-enabled)

Update requirements:

  • Must be called by current token owner
  • Cannot enable properties that were disabled
  • Can only disable features, not enable them
  • Ownership transfer is permanent

Common update scenarios:

  • Finalize token by disabling minting
  • Transfer ownership to DAO/multisig
  • Lock token properties permanently
  • Decentralize token control

Parameters:

  • tokenStandard: ZTS identifier of the token to update
  • owner: New owner address (or current owner to keep unchanged)
  • isMintable: Minting status (can only change true -> false)
  • isBurnable: Burning status (can only change true -> false)

Returns an unsigned AccountBlock template ready for processing.

Example - Transfer ownership:

newOwner := types.ParseAddressPanic("z1qqga8s8rkypgsg5qg2g7rp68nqh3r4lkm54tta")
template := client.TokenApi.UpdateToken(
    myTokenZts,
    newOwner,
    true,  // keep mintable
    true,  // keep burnable
)
// Sign and publish

Example - Finalize token (disable minting):

template := client.TokenApi.UpdateToken(
    myTokenZts,
    myAddress,  // keep same owner
    false,      // disable minting permanently
    true,       // keep burning enabled
)
// This makes the token fixed supply

Example - Lock all properties:

template := client.TokenApi.UpdateToken(
    myTokenZts,
    myAddress,
    false,  // disable minting
    false,  // disable burning
)
// Token is now immutable

Note: Property changes are permanent. Once minting or burning is disabled, it cannot be re-enabled. Use with caution.

type TokenList added in v0.1.9

type TokenList struct {
	Count int      `json:"count"`
	List  []*Token `json:"list"`
}

TokenList represents a paginated list of tokens.

This type is returned by methods that list multiple tokens, such as GetAll or GetByOwner.

Fields:

  • Count: Total number of tokens matching the query
  • List: Slice of Token entries for the current page

type TokenPair added in v0.1.9

type TokenPair struct {
	TokenStandard types.ZenonTokenStandard `json:"tokenStandard"`
	TokenAddress  string                   `json:"tokenAddress"`
	Bridgeable    bool                     `json:"bridgeable"`
	Redeemable    bool                     `json:"redeemable"`
	Owned         bool                     `json:"owned"`
	MinAmount     *big.Int                 `json:"minAmount"`
	FeePercentage uint32                   `json:"feePercentage"`
	RedeemDelay   uint32                   `json:"redeemDelay"`
	Metadata      string                   `json:"metadata"`
}

TokenPair represents a bridge token pair configuration.

This type defines the mapping between a Zenon ZTS token and its corresponding token on an external chain, along with bridge operation parameters.

Fields:

  • TokenStandard: ZTS identifier on the Zenon side
  • TokenAddress: Contract address on the external chain
  • Bridgeable: Whether tokens can be wrapped (Zenon -> external)
  • Redeemable: Whether tokens can be unwrapped (external -> Zenon)
  • Owned: Whether the bridge owns the external token contract
  • MinAmount: Minimum amount for bridge operations (in base units, 8 decimals)
  • FeePercentage: Fee charged for bridge operations (basis points)
  • RedeemDelay: Delay before unwrapped tokens can be claimed
  • Metadata: Additional token pair configuration data

func (*TokenPair) UnmarshalJSON added in v0.1.9

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

type TokenTuple added in v0.1.9

type TokenTuple struct {
	TokenStandard types.ZenonTokenStandard `json:"tokenStandard"`
	ZnnPercentage uint32                   `json:"znnPercentage"`
	QsrPercentage uint32                   `json:"qsrPercentage"`
	MinAmount     *big.Int                 `json:"minAmount"`
}

TokenTuple represents a token configuration for liquidity rewards.

This type defines how rewards are distributed for a specific token in the liquidity program. Each token can have different reward percentages and minimum staking requirements.

Fields:

  • TokenStandard: ZTS identifier for the token
  • ZnnPercentage: Percentage of ZNN rewards allocated to this token
  • QsrPercentage: Percentage of QSR rewards allocated to this token
  • MinAmount: Minimum amount required to stake (in base units, 8 decimals)

func (*TokenTuple) UnmarshalJSON added in v0.1.9

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

type UncollectedReward added in v0.1.9

type UncollectedReward struct {
	Address   types.Address `json:"address"`
	ZnnAmount *big.Int      `json:"znnAmount"`
	QsrAmount *big.Int      `json:"qsrAmount"`
}

UncollectedReward represents pending rewards that haven't been collected yet.

This type is returned by GetUncollectedReward methods across pillar, sentinel, stake, and liquidity APIs. Rewards accumulate over time and can be collected using the respective CollectReward transaction methods.

Fields:

  • Address: The address that owns the uncollected rewards
  • ZnnAmount: Uncollected ZNN rewards (in base units, 8 decimals)
  • QsrAmount: Uncollected QSR rewards (in base units, 8 decimals)

Example:

rewards, err := client.StakeApi.GetUncollectedReward(address)
if err != nil {
    log.Fatal(err)
}
if rewards.ZnnAmount.Sign() > 0 {
    fmt.Printf("Uncollected ZNN: %s\n", rewards.ZnnAmount)
}

func (*UncollectedReward) UnmarshalJSON added in v0.1.9

func (r *UncollectedReward) UnmarshalJSON(data []byte) error

type UnwrapTokenRequest added in v0.1.9

type UnwrapTokenRequest struct {
	RegistrationMomentumHeight uint64                   `json:"registrationMomentumHeight"`
	NetworkClass               uint32                   `json:"networkClass"`
	ChainId                    uint32                   `json:"chainId"`
	TransactionHash            types.Hash               `json:"transactionHash"`
	LogIndex                   uint32                   `json:"logIndex"`
	ToAddress                  types.Address            `json:"toAddress"`
	TokenAddress               string                   `json:"tokenAddress"`
	TokenStandard              types.ZenonTokenStandard `json:"tokenStandard"`
	Amount                     *big.Int                 `json:"amount"`
	Signature                  string                   `json:"signature"`
	Redeemed                   uint32                   `json:"redeemed"`
	Revoked                    uint32                   `json:"revoked"`
	RedeemableIn               uint64                   `json:"redeemableIn"`
}

UnwrapTokenRequest represents an unwrap token request.

When transferring tokens from an external chain to Zenon, an unwrap request is created after the external transaction is detected. Orchestrators verify and sign these requests to release tokens on Zenon.

Fields:

  • RegistrationMomentumHeight: Momentum height when request was registered
  • NetworkClass: Category of source network
  • ChainId: Chain identifier of source network
  • TransactionHash: Transaction hash on the external chain
  • LogIndex: Log index within the external transaction
  • ToAddress: Recipient address on Zenon
  • TokenAddress: Token contract address on the external chain
  • TokenStandard: ZTS identifier of the token to receive
  • Amount: Amount to unwrap (in base units, 8 decimals)
  • Signature: TSS signature for the unwrap (added by orchestrators)
  • Redeemed: Whether tokens have been claimed (1 = yes, 0 = no)
  • Revoked: Whether request was revoked (1 = yes, 0 = no)
  • RedeemableIn: Number of momentums until the request can be redeemed

func (*UnwrapTokenRequest) UnmarshalJSON added in v0.1.9

func (u *UnwrapTokenRequest) UnmarshalJSON(data []byte) error

type UnwrapTokenRequestList added in v0.1.9

type UnwrapTokenRequestList struct {
	Count int                   `json:"count"`
	List  []*UnwrapTokenRequest `json:"list"`
}

UnwrapTokenRequestList represents a paginated list of unwrap requests.

Fields:

  • Count: Total number of unwrap requests matching the query
  • List: Slice of UnwrapTokenRequest entries for the current page

type VoteBreakdown added in v0.1.9

type VoteBreakdown struct {
	Id    types.Hash `json:"id"`
	Total uint32     `json:"total"`
	Yes   uint32     `json:"yes"`
	No    uint32     `json:"no"`
}

VoteBreakdown represents voting results for a project or phase.

Pillars vote on Accelerator-Z projects and phases. This type contains the vote tally for a specific project or phase.

Fields:

  • Id: Hash of the project or phase being voted on
  • Total: Total number of votes cast
  • Yes: Number of approval votes
  • No: Number of rejection votes

type WrapTokenRequest added in v0.1.9

type WrapTokenRequest struct {
	NetworkClass            uint32                   `json:"networkClass"`
	ChainId                 uint32                   `json:"chainId"`
	Id                      types.Hash               `json:"id"`
	ToAddress               string                   `json:"toAddress"`
	TokenStandard           types.ZenonTokenStandard `json:"tokenStandard"`
	TokenAddress            string                   `json:"tokenAddress"`
	Amount                  *big.Int                 `json:"amount"`
	Fee                     *big.Int                 `json:"fee"`
	Signature               string                   `json:"signature"`
	CreationMomentumHeight  uint64                   `json:"creationMomentumHeight"`
	ConfirmationsToFinality uint32                   `json:"confirmationsToFinality"`
}

WrapTokenRequest represents a wrap token request.

When transferring tokens from Zenon to an external chain, a wrap request is created. Orchestrators process these requests and mint tokens on the destination chain.

Fields:

  • NetworkClass: Category of destination network
  • ChainId: Chain identifier of destination network
  • Id: Unique identifier for this wrap request
  • ToAddress: Recipient address on the external chain
  • TokenStandard: ZTS identifier of the token being wrapped
  • TokenAddress: Token contract address on the external chain
  • Amount: Amount to wrap (in base units, 8 decimals)
  • Fee: Fee charged for the wrap operation (in base units)
  • Signature: TSS signature for the wrap (added by orchestrators)
  • CreationMomentumHeight: Momentum height when request was created
  • ConfirmationsToFinality: Number of confirmations remaining until finality

func (*WrapTokenRequest) UnmarshalJSON added in v0.1.9

func (w *WrapTokenRequest) UnmarshalJSON(data []byte) error

type WrapTokenRequestList added in v0.1.9

type WrapTokenRequestList struct {
	Count int                 `json:"count"`
	List  []*WrapTokenRequest `json:"list"`
}

WrapTokenRequestList represents a paginated list of wrap requests.

Fields:

  • Count: Total number of wrap requests matching the query
  • List: Slice of WrapTokenRequest entries for the current page

type ZtsFeesInfo added in v0.1.9

type ZtsFeesInfo struct {
	TokenStandard  types.ZenonTokenStandard `json:"tokenStandard"`
	AccumulatedFee *big.Int                 `json:"accumulatedFee"`
}

ZtsFeesInfo represents accumulated fees for a token.

Bridge operations charge fees that accumulate in the bridge contract. This type tracks the total fees collected for a specific token.

Fields:

  • TokenStandard: ZTS identifier of the token
  • AccumulatedFee: Total fees collected (in base units, 8 decimals)

func (*ZtsFeesInfo) UnmarshalJSON added in v0.1.9

func (z *ZtsFeesInfo) UnmarshalJSON(data []byte) error

Jump to

Keyboard shortcuts

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