nkn_sdk_go

package module
v1.1.0-beta.9 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2019 License: Apache-2.0 Imports: 26 Imported by: 41

README

nkn-sdk-go

Go implementation of NKN SDK.

Note: This repository is in the early development stage and may not have all functions working properly. It should be used only for testing now.

Usage

Before you use SDK please call:

Init()

Client Usage

Create a client with a generated key pair:

account, _ := vault.NewAccount()
client, _ := NewClient(account, "")

Or with an identifier (used to distinguish different clients sharing the same key pair):

client, _ := NewClient(account, "any string")

Get client key pair:

fmt.Println(account.PrivateKey, account.PublicKey)

Create a client using an existing seed:

seed, _ := common.HexStringToBytes("039e481266e5a05168c1d834a94db512dbc235877f150c5a3cc1e3903672c673")
privateKey := crypto.GetPrivateKeyFromSeed(seed)
account, _ := vault.NewAccountWithPrivatekey(privateKey)
client, _ := NewClient(account, "any string")

By default the client will use bootstrap RPC server (for getting node address) provided by us. Any NKN full node can serve as a bootstrap RPC server. To create a client using customized bootstrap RPC server:

client, _ := NewClient(account, "any string", ClientConfig{SeedRPCServerAddr: "https://ip:port"})

Private key should be kept SECRET! Never put it in version control system like here.

Get client NKN address, which is used to receive data from other clients:

fmt.Println(client.Address)

Listen for connection established:

<- client.OnConnect
fmt.Println("Connection opened.")

Send text message to other clients:

client.Send([]string{"another client address"}, []byte("hello world!"))

You can also send byte array directly:

client.Send([]string{"another client address"}, []byte{1, 2, 3, 4, 5})

Or publish text message to a bucket 0 of specified topic:

client.Publish("topic", 0, []byte("hello world!"))

Receive data from other clients:

msg := <- client.OnMessage
fmt.Println("Receive binary message from", msg.Src + ":", string(msg.Payload))

Listen for new blocks mined:

block := <- client.OnBlock
fmt.Println("New block mined:", block.Header.Height)

Wallet Usage

Create wallet SDK:

account, _ := vault.NewAccount()
w := NewWalletSDK(account)

By default the wallet will use RPC server provided by us. Any NKN full node can serve as a RPC server. To create a wallet using customized RPC server:

account, _ := vault.NewAccount()
w := NewWalletSDK(account, WalletConfig{SeedRPCServerAddr: "https://ip:port"})

Query asset balance for this wallet:

balance, err := w.Balance()
if err == nil {
    log.Println("asset balance:", balance.String())
} else {
    log.Println("query balance fail:", err)
}

Query asset balance for address:

balance, err := w.BalanceByAddress("address")
if err == nil {
    log.Println("asset balance:", balance.String())
} else {
    log.Println("query balance fail:", err)
}

Transfer asset to some address:

address, _ := account.ProgramHash.ToAddress()
txid, err := w.Transfer(address, "100")
if err == nil {
    log.Println("success:", txid)
} else {
    log.Println("fail:", err)
}

Open nano pay channel to specified address:

// you can optionally pass channel duration after address (default is 4320 blocks, roughly 24h)
// after expired new channel (with new id) will be created under-the-hood
// this means that receiver need to claim old channel and reset amount calculation
np, err := w.NewNanoPay(address)
if err == nil {
    log.Println("success:", txid)
} else {
    log.Println("fail:", err)
}

Increment channel balance by 100 NKN:

txid, err = np.IncrementAmount("100")
if err == nil {
    log.Println("success:", txid)
} else {
    log.Println("fail:", err)
}

Register name for this wallet:

txid, err = w.RegisterName("somename")
if err == nil {
    log.Println("success:", txid)
} else {
    log.Println("fail:", err)
}

Delete name for this wallet:

txid, err = w.DeleteName("somename")
if err == nil {
    log.Println("success:", txid)
} else {
    log.Println("fail:", err)
}

Resolve name to wallet address:

address, _ := w.GetAddressByName("somename")

Subscribe to specified topic for this wallet for next 10 blocks:

txid, err = w.Subscribe("identifier", "topic", 10, "meta")
if err == nil {
    log.Println("success:", txid)
} else {
    log.Println("fail:", err)
}

Unsubscribe from specified topic:

txid, err = w.Unsubscribe("identifier", "topic")
if err == nil {
    log.Println("success:", txid)
} else {
    log.Println("fail:", err)
}

Get subscription:

subscription, _ := w.GetSubscription("topic", "identifier.publickey")
fmt.Printf("%+v\n", subscription) // &{Meta:meta ExpiresAt:100000}

Get 10 subscribers of specified topic starting from 0 offset, including those in tx pool (fetch meta):

subscribers, subscribersInTxPool, _ := w.GetSubscribers("topic", 0, 10, true, true)

Get subscribers count for specified topic:

count, _ := w.GetSubscribersCount("topic")

Contributing

Can I submit a bug, suggestion or feature request?

Yes. Please open an issue for that.

Can I contribute patches?

Yes, we appreciate your help! To make contributions, please fork the repo, push your changes to the forked repo with signed-off commits, and open a pull request here.

Please sign off your commit. This means adding a line "Signed-off-by: Name " at the end of each commit, indicating that you wrote the code and have the right to pass it on as an open source patch. This can be done automatically by adding -s when committing:

git commit -s

Community

Documentation

Index

Constants

This section is empty.

Variables

View Source
var AlreadySubscribed = errors.New("already subscribed to this topic")

Functions

func Init

func Init()

Types

type BlockInfo

type BlockInfo struct {
	Header       HeaderInfo `json:"header"`
	Transactions []TxnInfo  `json:"transactions"`
	Size         int        `json:"size"`
	Hash         string     `json:"hash"`
}

type Client

type Client struct {
	Address string

	OnConnect chan struct{}
	OnMessage chan *pb.InboundMessage
	OnBlock   chan *BlockInfo

	sync.RWMutex
	// contains filtered or unexported fields
}

func NewClient

func NewClient(account *vault.Account, identifier string, configs ...ClientConfig) (*Client, error)

func (*Client) Close

func (c *Client) Close()

func (*Client) GetConn

func (c *Client) GetConn() *websocket.Conn

func (*Client) GetNodeInfo

func (c *Client) GetNodeInfo() *NodeInfo

func (*Client) IsClosed

func (c *Client) IsClosed() bool

func (*Client) Publish

func (c *Client) Publish(topic string, offset, limit uint32, txPool bool, payload []byte, MaxHoldingSeconds ...uint32) error

func (*Client) Send

func (c *Client) Send(dests []string, payload []byte, MaxHoldingSeconds ...uint32) error

type ClientConfig

type ClientConfig struct {
	SeedRPCServerAddr string
	ReconnectInterval time.Duration
	MaxHoldingSeconds uint32
	MsgChanLen        uint32
	BlockChanLen      uint32
	ConnectRetries    uint32
}

type HeaderInfo

type HeaderInfo struct {
	Version          uint32 `json:"version"`
	PrevBlockHash    string `json:"prevBlockHash"`
	TransactionsRoot string `json:"transactionsRoot"`
	StateRoot        string `json:"stateRoot"`
	Timestamp        int64  `json:"timestamp"`
	Height           uint32 `json:"height"`
	RandomBeacon     string `json:"randomBeacon"`
	WinnerHash       string `json:"winnerHash"`
	WinnerType       string `json:"winnerType"`
	SignerPk         string `json:"signerPk"`
	SignerId         string `json:"signerId"`
	Signature        string `json:"signature"`
	Hash             string `json:"hash"`
}

type NanoPay

type NanoPay struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func NewNanoPay

func NewNanoPay(w *WalletSDK, address string, fee common.Fixed64, duration ...uint32) (*NanoPay, error)

func (*NanoPay) Address

func (np *NanoPay) Address() string

func (*NanoPay) IncrementAmount

func (np *NanoPay) IncrementAmount(delta string) (*transaction.Transaction, error)

type NanoPayClaimer

type NanoPayClaimer struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func NewNanoPayClaimer

func NewNanoPayClaimer(w *WalletSDK, address string, claimInterval time.Duration, errChan chan error) (*NanoPayClaimer, error)

func (*NanoPayClaimer) Address

func (npc *NanoPayClaimer) Address() string

func (*NanoPayClaimer) Amount

func (npc *NanoPayClaimer) Amount() common.Fixed64

func (*NanoPayClaimer) Claim

func (*NanoPayClaimer) Close

func (npc *NanoPayClaimer) Close() error

func (*NanoPayClaimer) Flush

func (npc *NanoPayClaimer) Flush() error

func (*NanoPayClaimer) IsClosed

func (npc *NanoPayClaimer) IsClosed() bool

type NodeInfo

type NodeInfo struct {
	Address   string `json:"addr"`
	PublicKey string `json:"pubkey"`
	Id        string `json:"id"`
}

type ProgramInfo

type ProgramInfo struct {
	Code      string `json:"code"`
	Parameter string `json:"parameter"`
}

type SetClientResult

type SetClientResult struct {
	NodeInfo          *NodeInfo `json:"node"`
	SigChainBlockHash string    `json:"sigChainBlockHash"`
}

type Subscription

type Subscription struct {
	Meta      string
	ExpiresAt uint32
}

type TxnInfo

type TxnInfo struct {
	TxType      string        `json:"txType"`
	PayloadData string        `json:"payloadData"`
	Nonce       uint64        `json:"nonce"`
	Fee         int64         `json:"fee"`
	Attributes  string        `json:"attributes"`
	Programs    []ProgramInfo `json:"programs"`
	Hash        string        `json:"hash"`
}

type WalletConfig

type WalletConfig struct {
	SeedRPCServerAddr string
}

type WalletSDK

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

func NewWalletSDK

func NewWalletSDK(account *vault.Account, config ...WalletConfig) *WalletSDK

func (*WalletSDK) Balance

func (w *WalletSDK) Balance() (common.Fixed64, error)

func (*WalletSDK) BalanceByAddress

func (w *WalletSDK) BalanceByAddress(address string) (common.Fixed64, error)

func (*WalletSDK) DeleteName

func (w *WalletSDK) DeleteName(name string, fee ...string) (string, error)

func (*WalletSDK) GetAddressByName

func (w *WalletSDK) GetAddressByName(name string) (string, error)

func (*WalletSDK) GetSubscribers

func (w *WalletSDK) GetSubscribers(topic string, offset, limit uint32, meta, txPool bool) (map[string]string, map[string]string, error)

func (*WalletSDK) GetSubscribersCount

func (w *WalletSDK) GetSubscribersCount(topic string) (uint32, error)

func (*WalletSDK) GetSubscription

func (w *WalletSDK) GetSubscription(topic string, subscriber string) (*Subscription, error)

func (*WalletSDK) NewNanoPay

func (w *WalletSDK) NewNanoPay(address string, fee string, duration ...uint32) (*NanoPay, error)

func (*WalletSDK) NewNanoPayClaimer

func (w *WalletSDK) NewNanoPayClaimer(claimInterval time.Duration, errChan chan error, address ...string) (*NanoPayClaimer, error)

func (*WalletSDK) RegisterName

func (w *WalletSDK) RegisterName(name string, fee ...string) (string, error)

func (*WalletSDK) SendRawTransaction

func (w *WalletSDK) SendRawTransaction(tx *transaction.Transaction) (string, error, int32)

func (*WalletSDK) Subscribe

func (w *WalletSDK) Subscribe(identifier string, topic string, duration uint32, meta string, fee ...string) (string, error)

func (*WalletSDK) Transfer

func (w *WalletSDK) Transfer(address string, value string, fee ...string) (string, error)

func (*WalletSDK) Unsubscribe

func (w *WalletSDK) Unsubscribe(identifier string, topic string, fee ...string) (string, error)

Directories

Path Synopsis
examples
session/grpc Module

Jump to

Keyboard shortcuts

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