mattercloud

package module
v0.5.3 Latest Latest
Warning

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

Go to latest
Published: Feb 1, 2022 License: MIT Imports: 13 Imported by: 1

README

go-mattercloud

The unofficial Go implementation for the MatterCloud API

Go Build Status Report Release GoDoc Sponsor Donate

Table of Contents

Installation

go-mattercloud requires a supported release of Go.

go get -u github.com/mrz1836/go-mattercloud

Documentation

You can view the generated documentation here.

You can also view the MatterCloud API documentation.

Features
  • Client is completely configurable
  • Customize the network per request (main, test or stn)
  • Using heimdall http client with exponential backoff & more
  • Current (V3) coverage for the MatterCloud API
    • Authentication
    • Address
    • Transaction
Library Deployment

goreleaser for easy binary or library deployment to Github and can be installed via: brew install goreleaser.

The .goreleaser.yml file is used to configure goreleaser.

Use make release-snap to create a snapshot version of the release, and finally make release to ship to production.

Makefile Commands

View all makefile commands

make help

List of all current commands:

all                  Runs lint, test-short and vet
clean                Remove previous builds and any test cache data
clean-mods           Remove all the Go mod cache
coverage             Shows the test coverage
godocs               Sync the latest tag with GoDocs
help                 Show this help message
install              Install the application
install-go           Install the application (Using Native Go)
lint                 Run the golangci-lint application (install if not found)
release              Full production release (creates release in Github)
release              Runs common.release then runs godocs
release-snap         Test the full release (build binaries)
release-test         Full production test release (everything except deploy)
replace-version      Replaces the version in HTML/JS (pre-deploy)
tag                  Generate a new tag and push (tag version=0.0.0)
tag-remove           Remove a tag if found (tag-remove version=0.0.0)
tag-update           Update an existing tag to current commit (tag-update version=0.0.0)
test                 Runs vet, lint and ALL tests
test-ci              Runs all tests via CI (exports coverage)
test-ci-no-race      Runs all tests via CI (no race) (exports coverage)
test-ci-short        Runs unit tests via CI (exports coverage)
test-short           Runs vet, lint and tests (excludes integration tests)
uninstall            Uninstall the application (and remove files)
update-linter        Update the golangci-lint package (macOS only)
vet                  Run the Go vet application

Examples & Tests

All unit tests and examples run via Github Actions and uses Go version 1.16.x. View the configuration file.

Run all tests (including integration tests)

make test

Run tests (excluding integration tests)

make test-short

Benchmarks

Run the Go benchmarks:

make bench

Code Standards

Read more about this Go project's code standards.

Usage

Basic implementation:

package main

import (
	"context"
	"log"

	"github.com/mrz1836/go-mattercloud"
)

func main() {

	// Create a new client
	client, _ := mattercloud.NewClient("your-secret-api-key", mattercloud.NetworkMain, nil, nil)

	// Get balance for an address
	balance, _ := client.AddressBalance(context.Background(),"16ZqP5Tb22KJuvSAbjNkoiZs13mmRmexZA")

	// What's the confirmed balance?
	log.Println("confirmed balance:", balance.Confirmed)
}

Maintainers

MrZ
MrZ

Contributing

View the contributing guidelines and please follow the code of conduct.

How can I help?

All kinds of contributions are welcome 🙌! The most basic way to show your support is to star 🌟 the project, or to raise issues 💬. You can also support this project by becoming a sponsor on GitHub 👏 or by making a bitcoin donation to ensure this journey continues indefinitely! 🚀

Credits

@Attila & MatterCloud for their hard work on the MatterCloud API

Looking for a Javascript version? Check out the MatterCloud JS SDK

License

License

Documentation

Overview

Package mattercloud is the unofficial golang implementation for the MatterCloud API

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type APIInternalError

type APIInternalError struct {
	Code         int      `json:"code,omitempty"`
	ErrorMessage string   `json:"message,omitempty"`
	Error        string   `json:"error,omitempty"`
	Errors       []string `json:"errors,omitempty"`
	Success      bool     `json:"success,omitempty"`
}

APIInternalError is for internal server errors (most requests)

type AddressList

type AddressList struct {
	Addrs string `json:"addrs"`
}

AddressList is the list of addresses for batch

type AddressService added in v0.5.1

type AddressService interface {
	AddressBalance(ctx context.Context, address string) (balance *Balance, err error)
	AddressBalanceBatch(ctx context.Context, addresses []string) (balances []*Balance, err error)
	AddressHistory(ctx context.Context, address string) (history *History, err error)
	AddressHistoryBatch(ctx context.Context, addresses []string) (history *History, err error)
	AddressUtxos(ctx context.Context, address string) (utxos []*UnspentTransaction, err error)
	AddressUtxosBatch(ctx context.Context, addresses []string) (utxos []*UnspentTransaction, err error)
}

AddressService is the MatterCloud address related requests

type Balance

type Balance struct {
	Address     string `json:"address"`
	Confirmed   int64  `json:"confirmed"`
	Unconfirmed int64  `json:"unconfirmed"`
}

Balance is the response from the get balance request

type BroadcastResponse

type BroadcastResponse struct {
	Success bool             `json:"success"`
	Result  *BroadcastResult `json:"result"`
}

BroadcastResponse is the response for the broadcast

type BroadcastResult added in v0.5.3

type BroadcastResult struct {
	TxID string `json:"txid"`
}

BroadcastResult is the internal response payload

type Client

type Client struct {
	LastRequest *LastRequest // is the raw information from the last request
	Parameters  *Parameters  // contains application specific values
	// contains filtered or unexported fields
}

Client is the parent struct that wraps the heimdall client

func (*Client) AddressBalance

func (c *Client) AddressBalance(ctx context.Context, address string) (balance *Balance, err error)

AddressBalance this endpoint retrieves balance for a specific address.

For more information: https://developers.mattercloud.io/#get-balance

func (*Client) AddressBalanceBatch

func (c *Client) AddressBalanceBatch(ctx context.Context, addresses []string) (balances []*Balance, err error)

AddressBalanceBatch this endpoint retrieves balances for multiple addresses at same time

For more information: https://developers.mattercloud.io/#get-balance-batch

func (*Client) AddressHistory

func (c *Client) AddressHistory(ctx context.Context, address string) (history *History, err error)

AddressHistory this endpoint retrieves history for a specific address

For more information: https://developers.mattercloud.io/#get-history

func (*Client) AddressHistoryBatch

func (c *Client) AddressHistoryBatch(ctx context.Context, addresses []string) (history *History, err error)

AddressHistoryBatch this endpoint retrieves history for multiple addresses

For more information: https://developers.mattercloud.io/#get-history-batch

func (*Client) AddressUtxos

func (c *Client) AddressUtxos(ctx context.Context, address string) (utxos []*UnspentTransaction, err error)

AddressUtxos this endpoint retrieves utxos for a specific address

For more information: https://developers.mattercloud.io/#get-utxos

func (*Client) AddressUtxosBatch

func (c *Client) AddressUtxosBatch(ctx context.Context, addresses []string) (utxos []*UnspentTransaction, err error)

AddressUtxosBatch this endpoint retrieves utxos for multiple addresses

For more information: https://developers.mattercloud.io/#get-utxos-batch

func (*Client) Broadcast

func (c *Client) Broadcast(ctx context.Context, rawTx string) (response *BroadcastResponse, err error)

Broadcast this endpoint broadcasts a raw transaction to the network

For more information: https://developers.mattercloud.io/#broadcast-transaction

func (*Client) Network added in v0.5.0

func (c *Client) Network() NetworkType

Network will return the current network

func (*Client) Request

func (c *Client) Request(ctx context.Context, endpoint, method string,
	payload []byte) (response string, err error)

Request is a generic request wrapper that can be used without constraints

func (*Client) Transaction

func (c *Client) Transaction(ctx context.Context, tx string) (transaction *Transaction, err error)

Transaction this endpoint retrieves specific transaction

For more information: https://developers.mattercloud.io/#get-transaction

func (*Client) TransactionBatch

func (c *Client) TransactionBatch(ctx context.Context, txIDs []string) (transactions []*Transaction, err error)

TransactionBatch this endpoint retrieves details for multiple transactions at same time

For more information: https://developers.mattercloud.io/#get-transaction-batch

type ClientInterface added in v0.5.0

type ClientInterface interface {
	AddressService
	TransactionService
	Network() NetworkType
	Request(ctx context.Context, endpoint, method string, payload []byte) (response string, err error)
}

ClientInterface is the MatterCloud client interface

func NewClient

func NewClient(apiKey string, network NetworkType, clientOptions *Options,
	customHTTPClient HTTPInterface) (c ClientInterface, err error)

NewClient creates a new client to submit requests Parameters values are set to the defaults defined by the API documentation.

For more information: https://developers.mattercloud.io/

Example

ExampleNewClient example using NewClient()

client, _ := NewClient(testAPIKey, NetworkMain, nil, nil)
fmt.Println(client.Network())
Output:

main

type HTTPInterface added in v0.4.0

type HTTPInterface interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPInterface is used for the http client (mocking heimdall)

type History

type History struct {
	From    int            `json:"from"`
	Results []*HistoryItem `json:"results"`
	To      int            `json:"to"`
}

History is the response from address history

type HistoryItem

type HistoryItem struct {
	TxID   string `json:"txid"`
	Height int64  `json:"height"`
}

HistoryItem is the individual history item

type LastRequest

type LastRequest struct {
	Method     string `json:"method"`      // method is the HTTP method used
	PostData   string `json:"post_data"`   // postData is the post data submitted if POST/PUT request
	StatusCode int    `json:"status_code"` // statusCode is the last code from the request
	URL        string `json:"url"`         // url is the url used for the request
}

LastRequest is used to track what was submitted via the Request()

type NetworkType

type NetworkType string

NetworkType is used internally to represent the possible values for network in queries to be submitted: {"main", "test", "stn"}

const (

	// NetworkMain is for main-net
	NetworkMain NetworkType = "main"

	// NetworkTest is for test-net
	NetworkTest NetworkType = "test"

	// NetworkStn is for the stn-net
	NetworkStn NetworkType = "stn"
)

type Options

type Options struct {
	BackOffExponentFactor          float64       `json:"back_off_exponent_factor"`
	BackOffInitialTimeout          time.Duration `json:"back_off_initial_timeout"`
	BackOffMaximumJitterInterval   time.Duration `json:"back_off_maximum_jitter_interval"`
	BackOffMaxTimeout              time.Duration `json:"back_off_max_timeout"`
	DialerKeepAlive                time.Duration `json:"dialer_keep_alive"`
	DialerTimeout                  time.Duration `json:"dialer_timeout"`
	RequestRetryCount              int           `json:"request_retry_count"`
	RequestTimeout                 time.Duration `json:"request_timeout"`
	TransportExpectContinueTimeout time.Duration `json:"transport_expect_continue_timeout"`
	TransportIdleTimeout           time.Duration `json:"transport_idle_timeout"`
	TransportMaxIdleConnections    int           `json:"transport_max_idle_connections"`
	TransportTLSHandshakeTimeout   time.Duration `json:"transport_tls_handshake_timeout"`
	UserAgent                      string        `json:"user_agent"`
}

Options holds all the configuration for connection, dialer and transport

func ClientDefaultOptions

func ClientDefaultOptions() (clientOptions *Options)

ClientDefaultOptions will return an "Options" struct with the default settings Useful for starting with the default and then modifying as needed

type Parameters

type Parameters struct {
	Network   NetworkType // is the BitcoinSV network to use
	UserAgent string      // (optional for changing user agents)
	// contains filtered or unexported fields
}

Parameters are application specific values for requests

type ScriptPubKeyType

type ScriptPubKeyType struct {
	Addresses          []string `json:"addresses"`
	Asm                string   `json:"asm"`
	Hex                string   `json:"hex"`
	RequiredSignatures int      `json:"reqSigs"`
	Type               string   `json:"type"`
}

ScriptPubKeyType is the script pubKey data

type ScriptSigType

type ScriptSigType struct {
	Asm string `json:"asm"`
	Hex string `json:"hex"`
}

ScriptSigType is the script signature data

type Transaction

type Transaction struct {
	APIInternalError
	BlockHash     string     `json:"blockhash"`
	BlockHeight   int64      `json:"blockheight"`
	BlockTime     int64      `json:"blocktime"`
	Confirmations int64      `json:"confirmations"`
	Fees          float64    `json:"fees"`
	Hash          string     `json:"hash"`
	LockTime      int64      `json:"locktime"`
	RawTx         string     `json:"rawtx"`
	Size          int64      `json:"size"`
	Time          int64      `json:"time"`
	TxID          string     `json:"txid"`
	ValueIn       float64    `json:"valueIn"`
	ValueOut      float64    `json:"valueOut"`
	Version       int        `json:"version"`
	Vin           []VinType  `json:"vin"`
	Vout          []VoutType `json:"vout"`
}

Transaction is returned to the GetTransactionsResponse

type TransactionList

type TransactionList struct {
	TxIDs string `json:"txids"`
}

TransactionList is the list of tx ids for batch

type TransactionService added in v0.5.1

type TransactionService interface {
	Broadcast(ctx context.Context, rawTx string) (response *BroadcastResponse, err error)
	Transaction(ctx context.Context, tx string) (transaction *Transaction, err error)
	TransactionBatch(ctx context.Context, txIDs []string) (transactions []*Transaction, err error)
}

TransactionService is the MatterCloud transaction related requests

type UnspentTransaction

type UnspentTransaction struct {
	Address       string  `json:"address"`
	Amount        float64 `json:"amount"`
	Confirmations int64   `json:"confirmations"`
	Height        int64   `json:"height"`
	OutputIndex   int64   `json:"outputIndex"`
	Satoshis      int64   `json:"satoshis"`
	Script        string  `json:"script"`
	ScriptPubKey  string  `json:"scriptPubKey"`
	TxID          string  `json:"txid"`
	Value         int64   `json:"value"`
	Vout          int     `json:"vout"`
}

UnspentTransaction is a standard UTXO response

type VinType

type VinType struct {
	Address       string        `json:"address"`
	AddressAddr   string        `json:"addr"`
	N             int           `json:"n"`
	ScriptSig     ScriptSigType `json:"scriptSig"`
	Sequence      int64         `json:"sequence"`
	TxID          string        `json:"txid"`
	Value         float64       `json:"value"`
	ValueSatoshis int64         `json:"valueSat"`
	Vout          int           `json:"vout"`
}

VinType is the vin data

type VoutType

type VoutType struct {
	N             int              `json:"n"`
	ScriptPubKey  ScriptPubKeyType `json:"scriptPubKey"`
	SpentHeight   int64            `json:"spentHeight"`
	SpentIndex    int64            `json:"spentIndex"`
	SpentTxID     string           `json:"spentTxId"`
	Value         float64          `json:"value"`
	ValueSatoshis int64            `json:"valueSat"`
}

VoutType is the vout data

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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