upvest

package module
v0.0.0-...-c847d37 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2019 License: MIT Imports: 18 Imported by: 0

README

GoDoc Build Status

Go library for the Upvest API.

In order to retrieve your API credentials for using this Go client, you'll need to sign up with Upvest.

Where possible, the services available on the client groups the API into logical chunks and correspond to the structure of the Upvest API documentation.

First, create an Upvest client and depending on what action to take, you either create tenancy or clientele client. All tenancy related operations must be authenticated using the API Keys Authentication, whereas all actions on a user's behalf need to be authenticated via OAuth. The API calls are built along with those two authentication objects.

// NewClient creates a new Upvest API client with the given base URL
// and HTTP client, allowing overriding of the HTTP client to use.
// This is useful if you're running in a Google AppEngine environment
// where the http.DefaultClient is not available.

c := NewClient("", nil)

// Configure logging using the Loggingenabled config key
c.Loggingenabled = true
Tenancy API - API Keys Authentication

The Upvest API uses the notion of tenants, which represent customers that build their platform upon the Upvest API. The end-users of the tenant (i.e. your customers), are referred to as clients. A tenant is able to manage their users directly (CRUD operations for the user instance) and is also able to initiate actions on the user's behalf (create wallets, send transactions).

The authentication via API keys and secret allows you to perform all tenant related operations. Please create an API key pair within the Upvest account management.

The default BASE_URL for both authentication objects is https://api.playground.upvest.co, but feel free to adjust it, once you retrieve your live keys. Next, create an Tenancy object in order to authenticate your API calls:

tenant = c.NewTenant(apiKey, apiSecret, apiPassphrase)

// create a user
user, err := tenant.User.Create(username, randomString(12))
if err != nil {
    t.Errorf("CREATE User returned error: %v", err)
}

// list users
users, err := tenant.User.List()
if err != nil {
    t.Errorf("List Users returned error: %v", err)
}

// retrieve 20 users
users, err := tenant.User.ListN(20)
if err != nil {
    t.Errorf("List Users returned error: %v", err)
}

// change password
user, err = tenant.User.ChangePassword(username, params)
Clientele API - OAuth Authentication

The authentication via OAuth allows you to perform operations on behalf of your user. For more information on the OAuth concept, please refer to our documentation. Again, please retrieve your client credentials from the Upvest account management.

Next, create an Clientele object with these credentials and your user authentication data in order to authenticate your API calls on behalf of a user:


clientele = c.NewClientele(clientID, clientSecret, username, password)
wp := &WalletParams{
    Password: staticUserPW,
    AssetID: "8fc19cd0-8f50-4626-becb-c9e284d2315b",
}

// create the wallet
wallet, err := clientele.Wallet.Create(wp)
if err != nil {
    t.Errorf("CREATE Wallet returned error: %v", err)
}

// // retrieve the wallet
wallet1, err := clientele.Wallet.Get(wallet.ID)
if err != nil {
    t.Errorf("GET Wallet returned error: %v", err)
}

Usage

Tenancy
User management
Create a user
user, err := tenant.User.Create('username','password')
Retrieve a user
user, err := tenant.User.Get('username')
List all users under tenancy
users, err := tenant.User.List()

for _, user := range users.Values {
  //do something with user
}
List a specific number of users under tenancy
users, err := tenant.User.listN(10)
Change password of a user
params := &upvest.ChangePasswordParams{
    OldPassword: "current password",
    NewPassword: "new pasword",
}
user, err := tenant.User.ChangePassword(username, params)
Delete a user
tenant.User.Delete('username')
Clientele
Assets
List available assets
assets, err := clientele.Asset.List()
for _, asset := range assets.Values {
  //do something with asset
}
Wallets
Create a wallet for a user
wp := &upvest.WalletParams{
    Password: "current user password",
    AssetID:  "asset ID",
    // Type:     "encrypted",
    // Index:    0,
}

// create the wallet
wallet, err := clientele.Wallet.Create(wp)
Retrieve specific wallet for a user
wallet1, err := clientele.Wallet.Get(walletID)
List all wallets for a user
wallets, err := clientele.Wallet.List()
for _, wallet := range wallets.Values {
  //do something with wallet
}
List a specific number of wallets
wallets, err := clientele.Wallet.ListN(40)
Transactions
Create transaction
tp := &upvest.TransactionParams{
    Password:  "current user password",
    AssetID:   "asset ID",
    Quantity:  "quantity, e.g. 10000000000000000",
    Fee:       "fee, e.g. 41180000000000",
    Recipient: "transaction address, e.g. 0xf9b44Ba370CAfc6a7AF77D0BDB0d50106823D91b",
}

// create the transaction
txn, err := clientele.Transaction.Create("wallet ID", tp)
Retrieve specific transaction
wallet1, err := clientele.Wallet.Get("wallet ID")
List all transactions of a wallet for a user
transactions, err := clientele.Transaction.List("wallet ID")
for _, txn := range transactions.Values {
  //do something with transaction
}
List a specific number of transactions of a wallet for a user
transactions, err := clientele.Transaction.ListN("wallet ID", 8)

Development

  1. Code must be go fmt compliant: make fmt

  2. All types, structs and funcs should be documented.

  3. Ensure that make test succeeds.

  4. Set up config settings via environment variables:

    # Set your tenancy API key information here.
    export API_KEY=xxxx
    export API_SECRET=xxxx
    export API_PASSPHRASE=xxxx
    
    # Set your OAuth2 client information here.
    export OAUTH2_CLIENT_ID=xxxx
    export OAUTH2_CLIENT_SECRET=xxxx
    

Test

Run all tests:

make test

Run a single test:

DEBUG=1 go test -run TestChangePassword

More

For a comprehensive reference, check out the Upvest documentation.

For details on all the functionality in this library, see the GoDoc documentation.

Documentation

Overview

Package upvest provides the binding for Upvest REST APIs. Where possible, the services available on the client groups the API into logical chunks and correspond to the structure of the Upvest API documentation at https://doc.upvest.co/reference.

First, create an Upvest client and depending on what action to take, you either create tenancy or clientele client. All tenancy related operations must be authenticated using the API Keys Authentication, whereas all actions on a user's behalf need to be authenticated via OAuth. The API calls are built along with those two authentication objects.

Usage:

	  // NewClient creates a new Upvest API client with the given base URL
	  // and HTTP client, allowing overriding of the HTTP client to use.
	  // This is useful if you're running in a Google AppEngine environment
	  // where the http.DefaultClient is not available.

	  c := NewClient("", nil)

	  // Tenant API - API Keys Authentication
	  // The Upvest API uses the notion of _tenants_, which represent customers that build their platform upon the Upvest API.
	  // The authentication via API keys and secret allows you to perform all tenant related operations.

	  tenancyClient = c.NewTenant(apiKey, apiSecret, apiPassphrase)

	  // create a user
	  user, err := tenancyClient.User.Create(username, randomString(12))
	  if err != nil {
		  t.Errorf("CREATE User returned error: %v", err)
	  }

	  // list users
	  users, err := tenancyClient.User.List()
	  if err != nil {
		  t.Errorf("List Users returned error: %v", err)
	  }

	  // retrieve 20 users
	  users, err := tenancyClient.User.ListN(20)
	  if err != nil {
		  t.Errorf("List Users returned error: %v", err)
	  }

	  // change password
	  user, err = tenancyClient.User.Update(username, params)

	  // Clinetele API - OAuth Authentication
	  // The authentication via OAuth allows you to perform operations on behalf of your user.
	  // For more information on the OAuth concept, please refer to our documentation at https://doc.upvest.co/docs/oauth2-authentication
	  // Next, create an `Clientele` object with these credentials
      // and your user authentication data in order to authenticate your API calls on behalf of a user:

	  clienteleClient = c.NewClientele(clientID, clientSecret, username, password)
	  wp := &WalletParams{
		  Password: staticUserPW,
		  AssetID:  ethWallet.Balances[0].AssetID,
	  }

	  // create the wallet
	  wallet, err := clienteleTestClient.Wallet.Create(wp)
	  if err != nil {
		  t.Errorf("CREATE Wallet returned error: %v", err)
	  }

	  // // retrieve the wallet
	  wallet1, err := clienteleTestClient.Wallet.Get(wallet.ID)
	  if err != nil {
		  t.Errorf("GET Wallet returned error: %v", err)
	  }

Index

Constants

View Source
const (
	ErrInvalidRequest ErrorType = "invalid_request_error"
	ErrAuthorization            = "authorization_error"
	ErrAuthentication           = "authentication_error"
	ErrDuplicateUser            = "duplicate_user"
	ErrServer                   = "server_error"
)

List of values that ErrorType can take.

View Source
const (

	// DefaultHTTPTimeout is the default timeout on the http client
	DefaultHTTPTimeout = 60 * time.Second

	// DefaultBaseURL for all requests. default to playground environment
	DefaultBaseURL = "https://api.playground.upvest.co/"

	// UserAgent used when communicating with the Upvest API.
	UserAgent = "upvest-go/" + version

	// APIVersion is the currently supported API version
	APIVersion = "1.0"

	// Encoding is the text encoding to use
	Encoding = "utf-8"

	// MaxPageSize is the maximum page size when retrieving list
	MaxPageSize = 100
)
View Source
const (
	// URLEncodeHeader is the content-type header for OuAth2
	URLEncodeHeader = "application/x-www-form-urlencoded"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Asset

type Asset struct {
	ID       string                 `json:"id"`
	Name     string                 `json:"name"`
	Symbol   string                 `json:"symbol"`
	Exponent int64                  `json:"exponent"`
	Protocol string                 `json:"protocol"`
	MetaData map[string]interface{} `json:"metadata"`
}

Asset is the resource representing your Upvest Tenant asset. For more details see https://doc.upvest.co/reference#assets

type AssetList

type AssetList struct {
	Meta   ListMeta
	Values []Asset `json:"results"`
}

AssetList is a list object for assets.

type AssetService

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

AssetService handles operations related to the asset For more details see https://doc.upvest.co/reference#assets/

func (*AssetService) Get

func (s *AssetService) Get(assetID string) (*Asset, error)

Get returns the details of a asset. For more details see https://doc.upvest.co/reference#common_assets_read

func (*AssetService) List

func (s *AssetService) List() (*AssetList, error)

List returns list of all assets. For more details see https://doc.upvest.co/reference#asset

type AuthProvider

type AuthProvider interface {
	// GetHeaders returns authorization headers (or other info) to be attached to requests.
	GetHeaders(method, path string, body interface{}, c *Client) (Headers, error)
}

AuthProvider interface for authentication mechanisms supported by Upvest API

type Balance

type Balance struct {
	Amount   int64  `json:"amount"`
	AssetID  string `json:"asset_id"`
	Name     string `json:"name"`
	Symbol   string `json:"symbol"`
	Exponent int    `json:"exponent"`
}

Balance has a quantity and an asset

type ChangePasswordParams

type ChangePasswordParams struct {
	//Params   `json:"-"`
	OldPassword string `json:"old_password"`
	NewPassword string `json:"new_password"`
}

ChangePasswordParams is the set of parameters that can be used when changing user password For more details see https://doc.upvest.co/reference#tenancy_user_password_update

type Client

type Client struct {
	LoggingEnabled bool
	Log            Logger
	// contains filtered or unexported fields
}

Client manages communication with the Upvest API Service specific actions are implemented on resource services mapped to the Upvest API. Miscellaneous actions are directly implemented on the Client object

func NewClient

func NewClient(baseURL string, httpClient *http.Client) *Client

NewClient creates a new Upvest API client with the given base URL and HTTP client, allowing overriding of the HTTP client to use. This is useful if you're running in a Google AppEngine environment where the http.DefaultClient is not available.

func (*Client) Call

func (c *Client) Call(method, path string, body, v interface{}, p *Params) error

Call actually does the HTTP request to Upvest API TODO: refactor additional params into Param struct

func (*Client) NewClientele

func (c *Client) NewClientele(clientID, clientSecret, username, password string) *ClienteleAPI

NewClientele creates a new clientele for interacting with your Upvest clients/users

func (*Client) NewRequest

func (c *Client) NewRequest(method, path string, body interface{}, params *Params) (*http.Request, error)

NewRequest is used by Call to generate an http.Request. It handles encoding parameters and attaching the appropriate headers.

func (*Client) NewTenant

func (c *Client) NewTenant(apiKey, apiSecret, apiPassphrase string) *TenancyAPI

NewTenant creates a new tenant for interacting with your Upvest tenant

type ClienteleAPI

type ClienteleAPI struct {
	Wallet      *WalletService
	Transaction *TransactionService
}

ClienteleAPI represents Upvest Clientele API For more details, please see https://doc.upvest.co/reference#clientele

type Error

type Error struct {
	Type       ErrorType              `json:"type,omitempty"`
	Message    string                 `json:"message,omitempty"`
	StatusCode int                    `json:"code,omitempty"`
	Details    map[string]interface{} `json:"details,omitempty"`
	URL        *url.URL               `json:"url,omitempty"`
	Header     http.Header            `json:"header,omitempty"`
}

Error represents an error response from the Upvest API server

func NewError

func NewError(resp *http.Response) *Error

func (*Error) Error

func (aerr *Error) Error() string

httpError supports the error interface

type ErrorType

type ErrorType string

ErrorType is represents the allowed values for the error's type.

type Headers

type Headers map[string]string

Headers represent the HTTP headers sent to Upvest API

type KeyAuth

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

KeyAuth (The API Key Authentication) is used to authenticate requests as a tenant.

func (KeyAuth) GetHeaders

func (auth KeyAuth) GetHeaders(method, path string, body interface{}, c *Client) (Headers, error)

GetHeaders returns authorization headers for requests as a tenant.

type ListMeta

type ListMeta struct {
	Previous string `json:"previous"`
	Next     string `json:"next"`
}

ListMeta is pagination metadata for paginated responses from the Upvest API

type Logger

type Logger interface {
	Printf(format string, v ...interface{})
}

Logger interface for custom loggers

type OAuth

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

OAuth (The OAuth2 Key Authentication) is used to authenticate requests on behalf of a user

func (OAuth) GetHeaders

func (oauth OAuth) GetHeaders(method, path string, body interface{}, c *Client) (Headers, error)

GetHeaders returns authorization headers for requests as a clientele

type OAuthResponse

type OAuthResponse struct {
	AccessToken  string `json:"access_token"`
	ExpiresIn    string `json:"exxpires_in"`
	TokenType    string `json:"token_type"`
	Scope        string `json:"scope"`
	RefreshToken string `json:"refresh_token"`
}

OAuthResponse represents succesful OAuth response

type Params

type Params struct {
	// Headers may be used to provide extra header lines on the HTTP request.
	Headers http.Header `json:"-"`

	// AuthProvider for authenticating the request
	AuthProvider AuthProvider `json:"-"`
}

Params is the structure that contains the common properties of any *Params structure.

func (*Params) AddHeader

func (p *Params) AddHeader(key, value string)

AddHeader adds a new arbitrary key-value pair to the request header

func (*Params) SetAuthProvider

func (p *Params) SetAuthProvider(auth AuthProvider)

SetAuthProvider sets a value for the auth mechanism

type Response

type Response map[string]interface{}

Response represents arbitrary response data

type Signature

type Signature struct {
	// Has the same value as the "output_format" parameter.
	// The name of the string format for the big numbers in the signature. (Some JSON implementations can not handle integers which need more than 64 bits to be represented.)
	BigNumberFormat string `json:"big_number_format"`

	// The encryption algorithm used. (Currently only ECDSA)
	Algorithm string `json:"algorithm"`

	// The name of the elliptic curve used.
	Curve string `json:"curve"`

	// The x coordinate of the public key of the wallet
	PublicKey map[string]interface{} `json:"public_key"`

	// The "r" signature component.
	// Represented in the format given in the "big_number_format" field.
	R string `json:"r"`

	// The "s" signature component.
	// Represented in the format given in the "big_number_format" field.
	S string `json:"s"`

	// The "recover" signature component, sometimes also called "v".
	// Since this is a small integer with less than 64 bits, this is an actual JSON integer, and NOT represented in the big integer format.
	Recover string `json:"string"`
}

Signature represents the signed wallet signature For more details, see https://doc.upvest.co/reference#kms_sign

type SignatureParams

type SignatureParams struct {
	//Params   `json:"-"`
	Password     string `json:"password"`
	ToSign       string `json:"to_sign"`
	InputFormat  string `json:"input_format,omitempty"`
	OutputFormat string `json:"output_format,omitempty"`
}

SignatureParams is the set of parameters that can be used when signing a wallet For more details see https://doc.upvest.co/reference#kms_sign

type TenancyAPI

type TenancyAPI struct {
	User  *UserService
	Asset *AssetService
}

TenancyAPI represents Upvest tenancy API For more details, please see https://doc.upvest.co/reference#tenancy

type Transaction

type Transaction struct {
	ID        string `json:"id"`
	TxHash    string `json:"txhash"`
	WalletID  string `json:"wallet_id"`
	AssetID   string `json:"asset_id"`
	AssetName string `json:"asset_name"`
	Exponent  string `json:"exponent"`
	Sender    string `json:"sender"`
	Recipient string `json:"recipient"`
	Quantity  string `json:"quantity"`
	Fee       string `json:"fee"`
	Status    string `json:"status"`
}

Transaction represents a wallet transaction For more details, see https://doc.upvest.co/reference#kms_transaction_create

type TransactionList

type TransactionList struct {
	Meta   ListMeta
	Values []Transaction `json:"results"`
}

TransactionList is a list object for transactions

type TransactionParams

type TransactionParams struct {
	Password  string `json:"password"`
	AssetID   string `json:"asset_id"`
	Quantity  int64  `json:"quantity"`
	Fee       int64  `json:"fee"`
	Recipient string `json:"recipient"`
}

TransactionParams is the set of parameters that can be used when creating a transaction For more details see https://doc.upvest.co/reference#kms_transaction_create

type TransactionService

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

TransactionService handles operations related to the transaction For more details see https://doc.upvest.co/reference#kms_transaction_create

func (*TransactionService) Create

func (s *TransactionService) Create(walletID string, tp *TransactionParams) (*Transaction, error)

Create creates a new transaction For more details https://doc.upvest.co/reference#kms_transaction_create

func (*TransactionService) Get

func (s *TransactionService) Get(walletID, txnID string) (*Transaction, error)

Get returns the details of a transaction. For more details see https://doc.upvest.co/reference#kms_transactions_read

func (*TransactionService) List

func (s *TransactionService) List(walletID string) (*TransactionList, error)

List returns list of all transactions. For more details see https://doc.upvest.co/reference#kms_transaction_list

type User

type User struct {
	Username    string         `json:"username,omitempty"`
	RecoveryKit string         `json:"recoverykit,omitempty"`
	WalletIDs   map[int]string `json:"wallet_ids,omitempty"`
}

User is the resource representing your Upvest Tenant user. For more details see https://doc.upvest.co/reference#tenancy_user_create

type UserList

type UserList struct {
	Meta   ListMeta
	Values []User `json:"results"`
}

UserList is a list object for users.

type UserService

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

UserService handles operations related to the user For more details see https://doc.upvest.co/reference#tenancy_user_create

func (*UserService) ChangePassword

func (s *UserService) ChangePassword(username string, params *ChangePasswordParams) (*User, error)

ChangePassword changes user password with the provided password For more details https://doc.upvest.co/reference#tenancy_user_password_update

func (*UserService) Create

func (s *UserService) Create(username, password string) (*User, error)

Create creates a new user For more details https://doc.upvest.co/reference#tenancy_user_create

func (*UserService) Delete

func (s *UserService) Delete(username string) error

Delete permanently deletes a user For more details https://doc.upvest.co/reference#tenancy_user_create

func (*UserService) Get

func (s *UserService) Get(username string) (*User, error)

Get returns the details of a user. For more details see

func (*UserService) List

func (s *UserService) List() (*UserList, error)

List returns list of all users. For more details see https://doc.upvest.co/reference#tenancy_user_list

func (*UserService) ListN

func (s *UserService) ListN(count int) (*UserList, error)

ListN returns a specific number of users For more details see https://doc.upvest.co/reference#tenancy_user_list

type Wallet

type Wallet struct {
	ID       string    `json:"id"`
	Path     string    `json:"path"`
	Balances []Balance `json:"balances"`
	Protocol string    `json:"protocol"`
	Address  string    `json:"address"`
	Status   string    `json:"status"`
	Index    int64     `json:"index"`
}

Wallet represents an Upvest wallet

type WalletList

type WalletList struct {
	Meta   ListMeta
	Values []Wallet `json:"results"`
}

WalletList is a list object for wallets.

type WalletParams

type WalletParams struct {
	//Params   `json:"-"`
	Password string `json:"password"`
	AssetID  string `json:"asset_id"`
	Type     string `json:"type,omitempty"`
	Index    int    `json:"index,omitempty"`
}

WalletParams is the set of parameters that can be used when creating or updating a wallet For more details see https://doc.upvest.co/reference#kms_wallet_create

type WalletService

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

WalletService handles operations related to the wallet For more details see https://doc.upvest.co/reference#kms_wallet_create

func (*WalletService) Create

func (s *WalletService) Create(wp *WalletParams) (*Wallet, error)

Create creates a new wallet For more details https://doc.upvest.co/reference#kms_wallet_create

func (*WalletService) Get

func (s *WalletService) Get(walletID string) (*Wallet, error)

Get returns the details of a wallet. For more details see https://doc.upvest.co/reference#kms_wallets_read

func (*WalletService) List

func (s *WalletService) List() (*WalletList, error)

List returns list of all wallets. For more details see https://doc.upvest.co/reference#wallet

func (*WalletService) ListN

func (s *WalletService) ListN(count int) (*WalletList, error)

ListN returns a specific number of wallets For more details see https://doc.upvest.co/reference#tenancy_wallet_list

func (*WalletService) Sign

func (s *WalletService) Sign(walletID string, sp *SignatureParams) (*Signature, error)

Sign signs (the hash of) data with the private key corresponding to this wallet. For more details, see https://doc.upvest.co/reference#kms_sign

Jump to

Keyboard shortcuts

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