fswap

package module
v1.2.2 Latest Latest
Warning

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

Go to latest
Published: Jun 7, 2023 License: MIT Imports: 16 Imported by: 4 modules, 4 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

4swap SDK go

4swap

4swap is a decentralized protocol implement for automated liquidity provision on Mixin Network

Authorization

4swap supports two kinds of access tokens:

  1. the access token that complete the OAuth flow at 4swap's webpage: https://app.4swap.org
  2. the access token that generated by your own Mixn Application. The token should sign the URL /me and the scope should be "FULL". Please read this document for more details.
Example
func TestMtgSwap(t *testing.T) {
    const (
        btc   = "c6d0c728-2624-429b-8e0d-d9d19b6592fa"
        xin   = "c94ac88f-4671-3976-b60a-09064f1811e8"
        token = "your authorization token"
    )
    
    ctx := context.Background()
    
    group, err := fswap.ReadGroup(ctx)
    if err != nil {
        t.Fatal(err)
    }
    
    me, err := mixin.UserMe(ctx, token)
    if err != nil {
        t.Fatal(err)
    }
    
    followID, _ := uuid.NewV4()
    action := mtg.SwapAction(
        me.UserID,
        followID.String(),
        btc,
        "", // leave the routes field as empty to let the engine decide the route. 
        decimal.NewFromFloat(0.1),
    )
    
    memo, err := action.Encode(group.PublicKey)
    if err != nil {
        t.Fatal(err)
    }
    
    t.Log(memo)
    
    // use mixin-sdk-go or bot-api-client-go to transfer to 4swap's multisig address
    
    // query the order.
    ctx = fswap.WithToken(ctx, token)
    order, err := fswap.ReadOrder(ctx, followID.String())
    if err != nil {
        t.Fatal(err)
    }
    
    t.Log(order.State)
}

Documentation

Index

Constants

View Source
const (
	DepositStatePending   = "Pending"
	DepositStateCancelled = "Cancelled"
	DepositStateDone      = "Done"
)
View Source
const (
	OrderStateTrading  = "Trading"
	OrderStateRejected = "Rejected"
	OrderStateDone     = "Done"
)
View Source
const (
	LegacyEndpoint = "https://legacy-api.4swap.org"
	ClientID       = "a753e0eb-3010-4c4a-a7b2-a7bda4063f62"

	MtgEndpoint = "https://api.4swap.org"
)
View Source
const (
	TransactionTypeAdd    = "Add"
	TransactionTypeRemove = "Remove"
	TransactionTypeSwap   = "Swap"
)
View Source
const (
	MaxRouteDepth = 4
)

Variables

View Source
var (
	ErrInsufficientLiquiditySwapped = errors.New("insufficient liquidity swapped")
)

Functions

func Ceil

func Ceil(d decimal.Decimal, precision int32) decimal.Decimal

func Decimal

func Decimal(v string) decimal.Decimal

func DecodeResponse

func DecodeResponse(resp *resty.Response) ([]byte, error)

func DecodeRoutes added in v1.1.0

func DecodeRoutes(id string) []int64

func EncodeAction

func EncodeAction(action TransactionAction) string

func EncodeRoutes

func EncodeRoutes(ids []int64) string

func GenerateToken

func GenerateToken(clientID, sessionID, sessionKey string, exp time.Duration) (string, error)

GenerateToken create a new mixin authorization token store.Scope must be 'FULL'

func GetClient added in v1.2.1

func GetClient() *http.Client

func GetRestyClient added in v1.2.1

func GetRestyClient() *resty.Client

func Request

func Request(ctx context.Context) *resty.Request

func TokenFrom

func TokenFrom(ctx context.Context) (string, bool)

func UnmarshalResponse

func UnmarshalResponse(resp *resty.Response, v interface{}) error

func UseEndpoint added in v1.0.4

func UseEndpoint(endpoint string)

func WithToken

func WithToken(ctx context.Context, token string) context.Context

Types

type AddDepositReq

type AddDepositReq struct {
	BaseAssetID  string          `json:"base_asset_id,omitempty"`
	BaseAmount   decimal.Decimal `json:"base_amount,omitempty"`
	QuoteAssetID string          `json:"quote_asset_id,omitempty"`
	QuoteAmount  decimal.Decimal `json:"quote_amount,omitempty"`
	// optional, default 0.01
	Slippage decimal.Decimal `json:"slippage,omitempty"`
}

type Asset added in v1.0.4

type Asset struct {
	ID            string          `json:"id,omitempty"`
	Name          string          `json:"name,omitempty"`
	Symbol        string          `json:"symbol,omitempty"`
	DisplaySymbol string          `json:"display_symbol,omitempty"`
	ChainID       string          `json:"chain_id,omitempty"`
	Price         decimal.Decimal `json:"price,omitempty"`
	Chain         struct {
		ID      string          `json:"id,omitempty"`
		Name    string          `json:"name,omitempty"`
		Symbol  string          `json:"symbol,omitempty"`
		Logo    string          `json:"logo,omitempty"`
		ChainID string          `json:"chain_id,omitempty"`
		Price   decimal.Decimal `json:"price,omitempty"`
		Tag     string          `json:"tag,omitempty"`
	} `json:"chain,omitempty"`
}

func ListAssets added in v1.0.4

func ListAssets(ctx context.Context) ([]*Asset, error)

ListAssets list all assets

func ReadAsset added in v1.0.4

func ReadAsset(ctx context.Context, assetID string) (*Asset, error)

ReadAsset read asset

type Deposit

type Deposit struct {
	ID        string         `json:"id,omitempty"`
	CreatedAt time.Time      `json:"created_at,omitempty"`
	State     string         `json:"state,omitempty"`
	UserID    string         `json:"user_id,omitempty"`
	Transfers []*TransferReq `json:"transfers,omitempty"`
}

func AddDeposit

func AddDeposit(ctx context.Context, req *AddDepositReq) (*Deposit, error)

func ReadDeposit

func ReadDeposit(ctx context.Context, depositID string) (*Deposit, error)

type Error

type Error struct {
	Code int    `json:"code,omitempty"`
	Msg  string `json:"msg,omitempty"`
}

func (*Error) Error

func (err *Error) Error() string

type Graph

type Graph map[string]map[string]*Pair

func (Graph) Add

func (g Graph) Add(pay, fill string, pair *Pair)

func (Graph) AddPair

func (g Graph) AddPair(pair *Pair)

type Group added in v1.0.4

type Group struct {
	Members   []string          `json:"members,omitempty"`
	Threshold uint              `json:"threshold,omitempty"`
	PublicKey ed25519.PublicKey `json:"public_key"`
}

func ReadGroup added in v1.0.4

func ReadGroup(ctx context.Context) (*Group, error)

ReadGroup return mtg Group info ( MTG only)

type Order

type Order struct {
	ID          string          `json:"id,omitempty"`
	CreatedAt   time.Time       `json:"created_at,omitempty"`
	State       string          `json:"state,omitempty"`
	PayAssetID  string          `json:"pay_asset_id,omitempty"`
	PayAmount   decimal.Decimal `json:"pay_amount,omitempty"`
	FillAssetID string          `json:"fill_asset_id,omitempty"`
	FillAmount  decimal.Decimal `json:"fill_amount,omitempty"`
	MinAmount   decimal.Decimal `json:"min_amount,omitempty"`
	RouteAssets []string        `json:"route_assets,omitempty"`
	// route id
	Routes string `json:"routes,omitempty"`

	// deprecated, Use PayAmount instead
	Funds decimal.Decimal `json:"funds,omitempty"`
	// deprecated, Use FillAmount instead
	Amount decimal.Decimal `json:"amount,omitempty"`
}

func PreOrder

func PreOrder(ctx context.Context, req *PreOrderReq) (*Order, error)

PreOrder 预下单

如果要同时对多个交易对预下单,不建议使用这个方法;而是先调用 ListPairs 然后重复使用 Pairs 去 Route 或者 ReverseRoute,这样只需要调用一次 /pairs 接口 不会那么容易触发 Rate Limit

func PreOrderWithPairs added in v1.0.4

func PreOrderWithPairs(pairs []*Pair, req *PreOrderReq) (*Order, error)

func ReadOrder

func ReadOrder(ctx context.Context, id string) (*Order, error)

ReadOrder return order detail by id WithToken required

func ReverseRoute

func ReverseRoute(pairs []*Pair, payAssetID, fillAssetID string, fillAmount decimal.Decimal) (*Order, error)

func Route

func Route(pairs []*Pair, payAssetID, fillAssetID string, payAmount decimal.Decimal) (*Order, error)

type Pair

type Pair struct {
	BaseAssetID  string          `json:"base_asset_id,omitempty"`
	BaseAmount   decimal.Decimal `json:"base_amount,omitempty"`
	QuoteAssetID string          `json:"quote_asset_id,omitempty"`
	QuoteAmount  decimal.Decimal `json:"quote_amount,omitempty"`
	FeePercent   decimal.Decimal `json:"fee_percent,omitempty"`
	RouteID      int64           `json:"route_id,omitempty"`
	// 池子总的流动性份额
	LiquidityAssetID string          `json:"liquidity_asset_id,omitempty"`
	Liquidity        decimal.Decimal `json:"liquidity,omitempty"`
	// 我的流动性份额,需要 WithToken
	Share      decimal.Decimal `json:"share,omitempty"`
	SwapMethod string          `json:"swap_method,omitempty"`
	Version    int64           `json:"version,omitempty"`
	// volume
	Volume24h      decimal.Decimal `json:"volume_24h,omitempty"`
	BaseVolume24h  decimal.Decimal `json:"base_volume_24h,omitempty"`
	QuoteVolume24h decimal.Decimal `json:"quote_volume_24h,omitempty"`
	// value
	BaseValue  decimal.Decimal `json:"base_value,omitempty"`
	QuoteValue decimal.Decimal `json:"quote_value,omitempty"`
	// stat
	Fee24h              decimal.Decimal `json:"fee_24h,omitempty"`
	TransactionCount24h int64           `json:"transaction_count_24h,omitempty"`
}

func ListPairs

func ListPairs(ctx context.Context) ([]*Pair, error)

ReadPairs list all pairs

func ReadPair

func ReadPair(ctx context.Context, base, quote string) (*Pair, error)

ReadPair return pair detail by base asset id & quote asset id

type PreOrderReq

type PreOrderReq struct {
	PayAssetID  string `json:"pay_asset_id,omitempty"`
	FillAssetID string `json:"fill_asset_id,omitempty"`
	// pay amount 和 fill amount 二选一
	PayAmount  decimal.Decimal `json:"pay_amount,omitempty"`
	FillAmount decimal.Decimal `json:"fill_amount,omitempty"`
	// deprecated
	Funds decimal.Decimal `json:"funds,omitempty"`
	// deprecated
	Amount decimal.Decimal `json:"amount,omitempty"`
	// deprecated
	MinAmount decimal.Decimal `json:"min_amount,omitempty"`
}

type Result

type Result struct {
	PayAssetID  string
	PayAmount   decimal.Decimal
	FillAssetID string
	FillAmount  decimal.Decimal
	FeeAssetID  string
	FeeAmount   decimal.Decimal
	RouteID     int64
}

Result represent Swap Result

func ReverseSwap

func ReverseSwap(pair *Pair, fillAssetID string, fillAmount decimal.Decimal) (*Result, error)

ReverseSwap is a Reverse version of Swap

func Swap

func Swap(pair *Pair, payAssetID string, payAmount decimal.Decimal) (*Result, error)

Swap trade in a pair

type TransactionAction

type TransactionAction struct {
	// Transaction type add remove swap
	Type string `json:"t,omitempty" msgpack:"t,omitempty"`
	// deposit
	Deposit string `json:"d,omitempty" msgpack:"d,omitempty"`
	// withdraw
	Pairs         []string `json:"p,omitempty" msgpack:"p,omitempty"`
	RemovePercent int64    `json:"l,omitempty" msgpack:"l,omitempty"`

	// 要买的币的 asset id
	AssetID string `json:"a,omitempty" msgpack:"a,omitempty"`
	// 路径 id,由 preOrder 得到,为空则由系统分配
	Routes string `json:"r,omitempty" msgpack:"r,omitempty"`
	// 最小买入数量,为空则不限制
	Minimum string `json:"m,omitempty" msgpack:"m,omitempty"`
}

type TransferReq

type TransferReq struct {
	AssetID    string          `json:"asset_id,omitempty"`
	OpponentID string          `json:"opponent_id,omitempty"`
	TraceID    string          `json:"trace_id,omitempty"`
	Amount     decimal.Decimal `json:"amount,omitempty"`
	Memo       string          `json:"memo,omitempty"`
}

Directories

Path Synopsis
cmd
swap command
mtg
aes
uni

Jump to

Keyboard shortcuts

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