dotwallet

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Mar 9, 2024 License: MIT Imports: 21 Imported by: 0

README

DotWallet SDK

A golang client for the DotWallet API

Release Build Status Report codecov Mergify Status Gitpod Ready-to-Code Go


Table of Contents


Installation

dotwallet-go-sdk requires a supported release of Go.

go get -u github.com/dotwallet/dotwallet-go-sdk

Documentation

View the generated documentation

GoDoc

Features
  • Client is completely configurable
  • Using default Resty http client with exponential backoff & more
  • Use your own custom HTTP resty client
  • Autoload the application_access_token when required by Authorization in client.Request()
  • Current coverage for the DotWallet API
    • Authorization
      • Application Authorization
      • User Authorization
      • Signature Authorization
    • User Info
      • Get User Info
      • Get User Receive Address
      • Get User Badge Balance
    • Transactions
      • Single Payment Order
      • Query Order Status
    • Automatic Payment
      • Automatic Payment Flow
      • Insufficient Balance
      • Get Autopay Balance
    • Badge
      • Create Badge
      • Transfer Badge to User
      • Transfer Badge to Address
      • Query Badge Balance
      • Query Badge Transaction
    • Merchant API
      • Query Miner Fees
      • Query Transaction Status
      • Send Transaction
    • Blockchain Queries
      • Block Header
      • Block Info from Hash
      • Block Info from Height
      • Block Info Batch Query from Height
      • Block Transaction List
      • Blockchain Basic Info
      • Transaction Inquiry
      • Merkle Branch Inquiry
    • DAPP API
      • List UTXOS
      • Sign Raw Transaction
      • Get Signature
      • Broadcast Transaction
      • Get Raw Change Address
      • Get Balance
      • Get Public Key
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 multiple commands
clean                 Remove previous builds and any test cache data
clean-mods            Remove all the Go mod cache
coverage              Shows the test coverage
diff                  Show the git diff
generate              Runs the go generate command in the base of the repo
godocs                Sync the latest tag with GoDocs
help                  Show this help message
install               Install the application
install-go            Install the application (Using Native Go)
install-releaser      Install the GoReleaser application
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 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-no-lint          Runs just tests
test-short            Runs vet, lint and tests (excludes integration tests)
test-unit             Runs tests and outputs coverage
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.19.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

Checkout all the examples!


Maintainers & Contributors

吴浩瑜 chenhao MrZ
吴浩瑜 chenhao MrZ

Contributing

View the contributing guidelines and 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 👏!

Stars


License

License

Documentation

Overview

Package dotwallet is the official golang implementation for the DotWallet API

If you have any suggestions or comments, please feel free to open an issue on this GitHub repository!

By DotWallet (https://dotwallet.com)

Index

Examples

Constants

View Source
const (

	// ScopeUserInfo is for getting user info
	ScopeUserInfo = "user.info"

	// ScopeAutoPayBSV is for auto-pay with a BSV balance
	ScopeAutoPayBSV = "autopay.bsv"

	// ScopeAutoPayBTC is for auto-pay with a BTC balance
	ScopeAutoPayBTC = "autopay.btc"

	// ScopeAutoPayETH is for auto-pay with a ETH balance
	ScopeAutoPayETH = "autopay.eth"
)
View Source
const (
	NftVoutLen            = 2188
	NftVinPushedDataCount = 11
)

NFT constants

View Source
const (
	CoinTypeBSV coinType = "BSV" // BitcoinSV
	CoinTypeBTC coinType = "BTC" // BitcoinCore
	CoinTypeETH coinType = "ETH" // Ethereum
)

These are used for the accepted coin types in regard to wallet functions

View Source
const (
	NftTxTypeCasting    = 1
	NftTxTypeTransfer   = 2
	NftTxTypeDestroy    = 3
	NftTxTypeError      = 4
	NftTxTypeIrrelevant = 5
)

NFT Types

Variables

View Source
var NftVoutScriptPrefix = []byte{} /* 2168 elements not displayed */

NftVoutScriptPrefix is the prefix

Functions

func ParseNftVoutScript added in v0.0.6

func ParseNftVoutScript(pkScript []byte) (btcutil.Address, error)

ParseNftVoutScript will parse th NFT script

func ToJSONStr added in v0.0.6

func ToJSONStr(i interface{}) string

ToJSONStr will convert json to string

func UserAgent

func UserAgent() string

UserAgent will return the default user-agent string

func Version

func Version() string

Version will return the version of the library

Types

type AddressBadgeCodePair added in v0.0.6

type AddressBadgeCodePair struct {
	Address   string `json:"address"`
	BadgeCode string `json:"badge_code"`
}

AddressBadgeCodePair is the badge code pair

type AddressIndexPair added in v0.0.6

type AddressIndexPair struct {
	Address string
	Index   int
}

AddressIndexPair is the index pair

type Client

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

Client is the TonicPow client/configuration

func NewClient

func NewClient(opts ...ClientOps) (*Client, error)

NewClient creates a new client for all TonicPow requests

If no options are given, it will use the DefaultClientOptions() If there is no client is supplied, it will use a default Resty HTTP client.

Example

ExampleNewClient example using NewClient()

See more examples in /examples/

client, err := NewClient(
	WithCredentials("your-client-id", "your-secret-id"),
	WithRedirectURI("http://localhost:3000/v1/auth/dotwallet/callback"),
)
if err != nil {
	fmt.Printf("error loading client: %s", err.Error())
	return
}
fmt.Printf("loaded client: %s", client.options.userAgent)
Output:

loaded client: dotwallet-go-sdk: v0.2.0

func (*Client) DeserializeRawTx added in v0.0.6

func (c *Client) DeserializeRawTx(rawTx string) (*wire.MsgTx, error)

DeserializeRawTx deserialize the raw tx

func (*Client) GetAuthorizeURL

func (c *Client) GetAuthorizeURL(state string, scopes []string) string

GetAuthorizeURL will return a new url for starting the user oauth2 authorization process

For more information: https://developers.dotwallet.com/documents/en/#user-authorization

func (*Client) GetMerkleProof added in v0.0.6

func (c *Client) GetMerkleProof(txHash *chainhash.Hash) (*MerkelProof, error)

GetMerkleProof get merkle proof

func (*Client) GetMerkleProofByHashStr added in v0.0.6

func (c *Client) GetMerkleProofByHashStr(txID string) (*MerkelProof, error)

GetMerkleProofByHashStr get merkle proof by hash string

func (*Client) GetMsgTx added in v0.0.6

func (c *Client) GetMsgTx(hash *chainhash.Hash) (*wire.MsgTx, error)

GetMsgTx get message tx

func (*Client) GetMsgTxByStr added in v0.0.6

func (c *Client) GetMsgTxByStr(txID string) (*wire.MsgTx, error)

GetMsgTxByStr get message tx by string

func (*Client) GetNft added in v0.0.5

func (c *Client) GetNft(txID string) (*NftData, error)

GetNft can obtain information authorized by DotWallet users via their user access_token

func (*Client) GetNftReceiveAddresses added in v0.0.6

func (c *Client) GetNftReceiveAddresses(msgTx *wire.MsgTx) ([]*AddressBadgeCodePair, error)

GetNftReceiveAddresses get nft addresses

func (*Client) GetNftReceiveAddressesByTxidStr added in v0.0.6

func (c *Client) GetNftReceiveAddressesByTxidStr(txID string) ([]*AddressBadgeCodePair, error)

GetNftReceiveAddressesByTxidStr get address by tx id

func (*Client) GetUserAgent

func (c *Client) GetUserAgent() string

GetUserAgent will return the user agent string of the client

func (*Client) GetUserToken

func (c *Client) GetUserToken(code string) (*DotAccessToken, error)

GetUserToken will get the user's access_token for the first time given the "code" from the oauth2 callback This will also store the user's token on the client for easy access (c.options.userToken)

For more information: https://developers.dotwallet.com/documents/en/#user-authorization

func (*Client) IsTokenExpired

func (c *Client) IsTokenExpired(token *DotAccessToken) bool

IsTokenExpired will check if the token is expired

func (*Client) MintNft added in v0.0.5

func (c *Client) MintNft(codeHash string, param string) (*NftMintData, error)

MintNft can obtain information authorized by DotWallet users via their user access_token

func (*Client) NewState

func (c *Client) NewState() (string, error)

NewState returns a new state key for CSRF protection It is not required to use this method, you can use your own UUID() for state validation

For more information: https://developers.dotwallet.com/documents/en/#user-authorization

func (*Client) RefreshUserToken

func (c *Client) RefreshUserToken(token *DotAccessToken) (*DotAccessToken, error)

RefreshUserToken will refresh the user's auth_token using the refresh_token This will also store the user's token on the client for easy access (c.options.userToken)

For more information: https://developers.dotwallet.com/documents/en/#user-authorization

func (*Client) Request

func (c *Client) Request(httpMethod string, requestEndpoint string,
	data interface{}, expectedCode int, authorization *DotAccessToken) (response *StandardResponse, err error)

Request is a standard GET / POST / PUT / DELETE request for all outgoing HTTP requests Omit the data attribute if using a GET request

func (*Client) SerializeRawTx added in v0.0.6

func (c *Client) SerializeRawTx(tx *wire.MsgTx) string

SerializeRawTx serialize the raw tx

func (*Client) Token

func (c *Client) Token() *DotAccessToken

Token will return the token for the application

func (*Client) TransferNftToAddress added in v0.0.6

func (c *Client) TransferNftToAddress(txID string, address string, name string,
	description string, picURL string) (*TransferNftToAddressData, error)

TransferNftToAddress can obtain information authorized by DotWallet users via their user access_token

func (*Client) UpdateApplicationAccessToken

func (c *Client) UpdateApplicationAccessToken() error

UpdateApplicationAccessToken will update the application access token This will also store the token on the client for easy access (c.options.token)

For more information: https://developers.dotwallet.com/documents/en/#application-authorization

func (*Client) UserInfo

func (c *Client) UserInfo(userToken *DotAccessToken) (*User, error)

UserInfo can obtain information authorized by DotWallet users via their user access_token

For more information: https://developers.dotwallet.com/documents/en/#user-info

func (*Client) UserReceiveAddress

func (c *Client) UserReceiveAddress(userID string, coinType coinType) (*Wallets, error)

UserReceiveAddress will return the wallets for the user based on the given coin_type Currently supported: BSV, BTC and ETH Paymail is currently only supported on BSV

For more information: https://developers.dotwallet.com/documents/en/#get-user-receive-address

func (*Client) VerifyCastingNftTransaction added in v0.0.6

func (c *Client) VerifyCastingNftTransaction(msgTx *wire.MsgTx) (bool, error)

VerifyCastingNftTransaction verify the tx

func (*Client) VerifyCastingNftTransactionByRawTx added in v0.0.6

func (c *Client) VerifyCastingNftTransactionByRawTx(rawTx string) (bool, error)

VerifyCastingNftTransactionByRawTx will verify the casting

func (*Client) VerifyCastingNftTransactionByTxid added in v0.0.6

func (c *Client) VerifyCastingNftTransactionByTxid(txID string) (bool, error)

VerifyCastingNftTransactionByTxid get by tx id

func (*Client) VerifyMerkleProof added in v0.0.6

func (c *Client) VerifyMerkleProof(txID string, nIndex int, nodes []string, exceptMerkleRoot string) bool

VerifyMerkleProof verify merkle proof

func (*Client) VerifyNftCastingOpReturn added in v0.0.6

func (c *Client) VerifyNftCastingOpReturn(msgTx *wire.MsgTx) bool

VerifyNftCastingOpReturn verify the op return

type ClientOps

type ClientOps func(c *clientOptions)

ClientOps allow functional options to be supplied that overwrite default client options.

func WithApplicationAccessToken

func WithApplicationAccessToken(token DotAccessToken) ClientOps

WithApplicationAccessToken will override the token on the client

func WithAutoLoadToken

func WithAutoLoadToken() ClientOps

WithAutoLoadToken will load the application token when spawning a new client By default, this is disabled, so you can make a new client without making an HTTP request

func WithCredentials

func WithCredentials(clientID, clientSecret string) ClientOps

WithCredentials will set the ClientID and ClientSecret There is no default

func WithCustomHTTPClient

func WithCustomHTTPClient(client *resty.Client) ClientOps

WithCustomHTTPClient will overwrite the default client with a custom client.

func WithCustomHeaders

func WithCustomHeaders(headers map[string][]string) ClientOps

WithCustomHeaders will add custom headers to outgoing requests Custom headers is empty by default

func WithHTTPTimeout

func WithHTTPTimeout(timeout time.Duration) ClientOps

WithHTTPTimeout can be supplied to adjust the default http client timeouts. The http client is used when creating requests Default timeout is 10 seconds.

func WithHost

func WithHost(host string) ClientOps

WithHost will overwrite the default host. Default is located in definitions

func WithRedirectURI

func WithRedirectURI(redirectURI string) ClientOps

WithRedirectURI will set the redirect URI for user authentication callbacks There is no default

func WithRequestTracing

func WithRequestTracing() ClientOps

WithRequestTracing will enable tracing. Tracing is disabled by default.

func WithRetryCount

func WithRetryCount(retries int) ClientOps

WithRetryCount will overwrite the default retry count for http requests. Default retries is 2.

func WithUserAgent

func WithUserAgent(userAgent string) ClientOps

WithUserAgent will overwrite the default useragent. Default is package name + version.

type DotAccessToken

type DotAccessToken struct {
	AccessToken           string   `json:"access_token"`                       // Access token from the API
	ExpiresAt             int64    `json:"expires_at,omitempty"`               // Friendly unix time from UTC when the access_token expires
	ExpiresIn             int64    `json:"expires_in"`                         // Seconds from now that the token expires
	RefreshToken          string   `json:"refresh_token,omitempty"`            // Refresh token for the user
	RefreshTokenExpiresIn int64    `json:"refresh_token_expires_in,omitempty"` // Seconds from now that the token expires
	RefreshTokenExpiresAt int64    `json:"refresh_token_expires_at,omitempty"` // Friendly unix time from UTC when the refresh_token expires
	Scopes                []string `json:"scopes,omitempty"`                   // Scopes for the user token
	TokenType             string   `json:"token_type"`                         // Token type
}

DotAccessToken is the access token information

For more information: https://developers.dotwallet.com/documents/en/#user-authorization

type Error

type Error struct {
	Data      interface{} `json:"data"`
	Method    string      `json:"method"`
	RequestID string      `json:"req_id"`
	URL       string      `json:"url"`
	// contains filtered or unexported fields
}

Error is the universal Error response from the API

For more information: https://developers.dotwallet.com/documents/en/#errors

type GetMerkleProofRequest added in v0.0.6

type GetMerkleProofRequest struct {
	Txid string `json:"txid"`
}

GetMerkleProofRequest is the request

type GetMerkleProofResponse added in v0.0.6

type GetMerkleProofResponse struct {
	Data struct {
		MerkelProof
	}
	// contains filtered or unexported fields
}

GetMerkleProofResponse is the response

type GetRawTransactionRequest added in v0.0.6

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

GetRawTransactionRequest is the request

type GetRawTransactionResponse added in v0.0.6

type GetRawTransactionResponse struct {
	Data struct {
		MsgTxInfo
	}
	// contains filtered or unexported fields
}

GetRawTransactionResponse is the response

type MerkelProof added in v0.0.6

type MerkelProof struct {
	Flags  int      `json:"flags"`
	Index  int      `json:"index"`
	Nodes  []string `json:"nodes"`
	Target *Target  `json:"target"`
	TxOrID string   `json:"txOrId"`
}

MerkelProof is the merkle proof

type MsgTxInfo added in v0.0.6

type MsgTxInfo struct {
	MsgTx     *wire.MsgTx
	Height    int64
	BlockHash string
	Timestamp int64
	RawTx     string
}

MsgTxInfo is the msg tx info

type NftAuthInfo added in v0.0.6

type NftAuthInfo struct {
	Sig []byte `json:"sig"`
	Pub []byte `json:"pub"`
}

NftAuthInfo is the auth info

type NftData added in v0.0.5

type NftData struct {
	CodeHash string `json:"code_hash"`
	Param    string `json:"param"`
}

NftData is the NFT data

type NftMintData added in v0.0.5

type NftMintData struct {
	Fee       int64    `json:"fee"`
	FeeStr    string   `json:"fee_str"`
	TxID      string   `json:"txid"`
	BadgePath []string `json:"badge_path"`
}

NftMintData is the data struct

type NftTxInfo added in v0.0.6

type NftTxInfo struct {
	TxID            string
	NftPreOutPoints []*TxIDIndexPair
	NftOutPoints    []*AddressIndexPair
	Type            int
}

NftTxInfo is the tx info

type StandardResponse

type StandardResponse struct {
	Body       []byte          `json:"-"` // Body of the response request
	Error      *Error          `json:"-"` // API error response
	StatusCode int             `json:"-"` // Status code returned on the request
	Tracing    resty.TraceInfo `json:"-"` // Trace information if enabled on the request
}

StandardResponse is the standard fields returned on all responses from Request()

type Target added in v0.0.6

type Target struct {
	Hash              string  `json:"hash"`
	Confirmations     int     `json:"confirmations"`
	Height            int     `json:"height"`
	Version           int     `json:"version"`
	VersionHex        string  `json:"versionHex"`
	Merkleroot        string  `json:"merkleroot"`
	NumTx             int     `json:"num_tx"`
	Time              int     `json:"time"`
	Mediantime        int     `json:"mediantime"`
	Nonce             int     `json:"nonce"`
	Bits              string  `json:"bits"`
	Difficulty        float64 `json:"difficulty"`
	Chainwork         string  `json:"chainwork"`
	Previousblockhash string  `json:"previousblockhash"`
	Nextblockhash     string  `json:"nextblockhash"`
}

Target is the target

type TransferNftToAddressData added in v0.0.6

type TransferNftToAddressData struct {
	Fee    int64  `json:"fee"`
	FeeStr string `json:"fee_str"`
}

TransferNftToAddressData is the transfer to address struct

type TxIDIndexPair added in v0.0.6

type TxIDIndexPair struct {
	TxID  string
	Index int
}

TxIDIndexPair is the pair

type User

type User struct {
	Avatar           string            `json:"avatar"`
	ID               string            `json:"id"`
	Nickname         string            `json:"nickname"`
	WebWalletAddress *webWalletAddress `json:"web_wallet_address"`
}

User is the DotWallet user profile information

For more information: https://developers.dotwallet.com/documents/en/#user-info

type Wallets

type Wallets struct {
	AutopayWallet *walletInfo `json:"autopay_wallet"`
	PrimaryWallet *walletInfo `json:"primary_wallet"`
}

Wallets is the user's wallet information

Jump to

Keyboard shortcuts

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