trigger

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: MIT Imports: 20 Imported by: 1 module, 0 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.

Documentation

Overview

Package trigger implements Jupiter's Trigger V2 API: wallet authentication, vaults, and deposits.

Trigger V2 is custodial: deposits move funds into a Privy-managed vault that Jupiter controls on the wallet's behalf until orders fill or are cancelled.

Authenticated operations run on a Session, which belongs to exactly one wallet. The Client holds no wallet identity and can serve many sessions concurrently.

Index

Constants

View Source
const (
	ChallengeMessage     = "message"
	ChallengeTransaction = "transaction"
)
View Source
const (
	MinDCAOrderCount = 2
	MinDCAInterval   = time.Minute
	MaxDCAInterval   = 365 * 24 * time.Hour
	MaxDCAStartDelay = 30 * 24 * time.Hour
)
View Source
const (
	TriggerAbove = "above"
	TriggerBelow = "below"

	DCATimeBased        = "time_based"
	DCAPriceConditional = "price_conditional"

	HistoryActive = "active"
	HistoryPast   = "past"

	SortUpdatedAt  = "updated_at"
	SortCreatedAt  = "created_at"
	SortExpiresAt  = "expires_at"
	SortNextFillAt = "next_fill_at"

	DirectionAscending  = "asc"
	DirectionDescending = "desc"
)
View Source
const (
	BasisPointsPerWhole = 10000
	MinTrailingBps      = 50
	MaxTrailingBps      = 9000
	MinHistoryLimit     = 1
	MaxHistoryLimit     = 100
)
View Source
const (
	OrderTypePrice = "price"
	OrderTypeDCA   = "dca"

	OrderSubTypeSingle = "single"
	OrderSubTypeOCO    = "oco"
	OrderSubTypeOTOCO  = "otoco"
)

Variables

View Source
var (
	// ErrInvalidAddress is the same value as swap.ErrInvalidAddress.
	ErrInvalidAddress = address.ErrInvalid

	ErrUnsupportedSigner   = errors.New("signer does not provide an ed25519 public key")
	ErrUnexpectedTokenType = errors.New("unexpected token response")
)
View Source
var (
	// ErrSessionExpired means the refresh token was rejected (expired, revoked, or
	// reused). Authenticate again to obtain a new session.
	ErrSessionExpired = errors.New("trigger session expired")

	// ErrOutcomeUnknown marks failures of operations that submit a signed
	// transaction (order creation and cancellation confirmation) after which the
	// transaction may still land. Check order history before creating another order.
	ErrOutcomeUnknown = errors.New("trigger submission outcome unknown")

	// ErrSessionClosed means Logout was called on the session.
	ErrSessionClosed = errors.New("trigger session closed")

	// ErrTokenPersistence means the session rotated its tokens but
	// SessionOptions.OnRefresh failed. The session holds the new tokens and stays
	// usable; the stored copy is stale until OnRefresh succeeds.
	ErrTokenPersistence = errors.New("persist rotated trigger tokens")
)
View Source
var ErrNoVault = errors.New("trigger vault not registered")

ErrNoVault means the wallet has no vault yet; see RegisterVault or EnsureVault.

Functions

This section is empty.

Types

type AuthTokens

type AuthTokens struct {
	AuthMode     string    `json:"authMode"`
	AccessToken  string    `json:"accessToken"`
	RefreshToken string    `json:"refreshToken"`
	ExpiresAt    time.Time `json:"expiresAt"`
	TokenType    string    `json:"tokenType"`
}

AuthTokens is an access and refresh token pair. Treat it as a secret: keep it out of logs. The refresh token rotates on every refresh.

type Cancellation

type Cancellation struct {
	ID              string `json:"id"`
	Transaction     string `json:"transaction"`
	RequestID       string `json:"requestId"`
	RoundsRemaining int    `json:"roundsRemaining"`
	RefundAmount    string `json:"refundAmount"`

	Metadata response.Metadata `json:"-"`
}

Cancellation is an unsigned withdrawal transaction from step one of a two-step cancellation. RoundsRemaining and RefundAmount are set for DCA orders.

type Challenge

type Challenge struct {
	Type        string `json:"type"`
	Message     string `json:"challenge"`
	Transaction string `json:"transaction"`
}

Challenge is a wallet-ownership challenge that expires after five minutes. Message is set for ChallengeMessage; Transaction (base64, never submitted on-chain) is set for ChallengeTransaction.

type Client

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

func NewClient

func NewClient(t *transport.Client) *Client

NewClient is called by jupiter.NewClient, which applications use instead; it takes the SDK's internal transport.

func (*Client) Login

func (c *Client) Login(
	ctx context.Context,
	signer crypto.Signer,
	options SessionOptions,
) (*Session, error)

Login authenticates with a message challenge signed by signer, which must hold the wallet's ed25519 key. Hardware wallets that sign only transactions should use RequestChallenge, sign the challenge transaction, and call Verify.

func (*Client) RequestChallenge

func (c *Client) RequestChallenge(
	ctx context.Context,
	wallet string,
	challengeType string,
) (*Challenge, error)

RequestChallenge starts authentication. Use ChallengeTransaction for hardware wallets that can only sign transactions.

func (*Client) Resume

func (c *Client) Resume(
	wallet string,
	tokens AuthTokens,
	options SessionOptions,
) (*Session, error)

Resume opens a session from previously stored tokens without a network call. If the refresh token has been rotated or revoked since, the first refresh fails with ErrSessionExpired.

func (*Client) Verify

func (c *Client) Verify(
	ctx context.Context,
	r VerifyRequest,
	options SessionOptions,
) (*Session, error)

Verify exchanges a signed challenge for tokens and opens a session. It always requests access_refresh tokens; the deprecated access_only mode is not supported. Verify makes one attempt because a challenge can be used only once.

type ConfirmCancelRequest

type ConfirmCancelRequest struct {
	SignedTransaction string `json:"signedTransaction"`
	CancelRequestID   string `json:"cancelRequestId"`
}

ConfirmCancelRequest completes a cancellation with the signed withdrawal transaction and the Cancellation's RequestID.

type DCAEvent

type DCAEvent struct {
	Type         string `json:"type"`
	Timestamp    string `json:"timestamp"`
	TxSignature  string `json:"txSignature"`
	RoundNumber  int    `json:"roundNumber"`
	InputAmount  string `json:"inputAmount"`
	OutputAmount string `json:"outputAmount"`
	State        string `json:"state"`
	AttemptCount int    `json:"attemptCount"`
}

type DCAOrderHistory

type DCAOrderHistory struct {
	Orders     []DCAOrderRecord `json:"orders"`
	Pagination Pagination       `json:"pagination"`

	Metadata response.Metadata `json:"-"`
}

type DCAOrderRecord

type DCAOrderRecord struct {
	ID                   string      `json:"id"`
	RequestID            string      `json:"requestId"`
	UserPubkey           string      `json:"userPubkey"`
	VaultPubkey          string      `json:"vaultPubkey"`
	InputMint            string      `json:"inputMint"`
	OutputMint           string      `json:"outputMint"`
	InputAmountInitial   string      `json:"inputAmountInitial"`
	InputAmountRemaining string      `json:"inputAmountRemaining"`
	AmountPerRound       string      `json:"amountPerRound"`
	OutputAmountTotal    string      `json:"outputAmountTotal"`
	InputAmountUsed      string      `json:"inputAmountUsed"`
	OrderType            string      `json:"orderType"`
	MinPriceUSD          json.Number `json:"minPriceUsd"`
	MaxPriceUSD          json.Number `json:"maxPriceUsd"`
	TriggerMint          *string     `json:"triggerMint"`
	RetryWindowSeconds   json.Number `json:"retryWindowSeconds"`
	JLEnabled            bool        `json:"jlEnabled"`
	JLYieldUSD           json.Number `json:"jlYieldUsd"`
	NumberOfRounds       int         `json:"numberOfRounds"`
	IntervalSeconds      int64       `json:"intervalSeconds"`
	BeginFillAt          string      `json:"beginFillAt"`
	NextFillAt           string      `json:"nextFillAt"`
	LastFillAt           *string     `json:"lastFillAt"`
	RoundsFilled         int         `json:"roundsFilled"`

	// FillPercent is progress from 0 to 1, unlike the price-order field.
	FillPercent  json.Number `json:"fillPercent"`
	State        string      `json:"state"`
	DisplayState string      `json:"displayState"`
	CreatedAt    string      `json:"createdAt"`
	UpdatedAt    string      `json:"updatedAt"`
	Events       []DCAEvent  `json:"events"`

	Metadata response.Metadata `json:"-"`
}

type DCAOrderRequest

type DCAOrderRequest struct {
	DepositRequestID         string
	DepositSignedTransaction string
	InputMint                string
	OutputMint               string
	InputAmount              string
	OrderCount               uint32
	Interval                 time.Duration
	OrderType                string
	MinPriceUSD              json.Number
	MaxPriceUSD              json.Number
	TriggerMint              string
	BeginFillAt              time.Time
	JLEnabled                bool
	JLMint                   string
}

DCAOrderRequest splits a signed deposit, crafted with OrderTypeDCA, into OrderCount equal rounds every Interval. OrderType is DCATimeBased (the default when empty) or DCAPriceConditional, which fills only while TriggerMint's USD price is within [MinPriceUSD, MaxPriceUSD]. JLEnabled (Earn While You Wait) requires DCATimeBased, a supported stablecoin input, and a deposit crafted with JLMint.

Jupiter enforces at least 10 USD per round and at most 10 active DCA orders. Rounds use automatic slippage; there is no slippage parameter.

type Deposit

type Deposit struct {
	Transaction        string `json:"transaction"`
	RequestID          string `json:"requestId"`
	ReceiverAddress    string `json:"receiverAddress"`
	Mint               string `json:"mint"`
	Amount             string `json:"amount"`
	TokenDecimals      int    `json:"tokenDecimals"`
	InputTokenAccount  string `json:"inputTokenAccount"`
	OutputTokenAccount string `json:"outputTokenAccount"`
	JLTokenAccount     string `json:"jlTokenAccount"`

	Metadata response.Metadata `json:"-"`
}

Deposit is an unsigned deposit transaction. Sign Transaction with the wallet and pass it with RequestID, which is single-use, to the order creation call.

type DepositRequest

type DepositRequest struct {
	InputMint    string
	OutputMint   string
	Amount       string
	OrderType    string
	OrderSubType string
	JLMint       string
}

DepositRequest crafts a deposit of Amount raw input units from the session's wallet into its vault. OrderSubType is required for OrderTypePrice and must be empty for OrderTypeDCA. JLMint (Earn While You Wait) applies only to DCA.

type HistoryRequest

type HistoryRequest struct {
	State     string
	Mint      string
	Limit     *uint8
	Offset    uint32
	Sort      string
	Direction string
}

HistoryRequest filters and pages order history. State, Sort, and Direction take the documented constants; other values are passed through so upstream additions remain usable. Zero values use Jupiter's defaults: limit 20, offset 0, sort by update time, descending. Mint matches either side of the order.

type OrderUpdate

type OrderUpdate struct {
	ID string `json:"id"`

	Metadata response.Metadata `json:"-"`
}

OrderUpdate is the result of UpdatePriceOrder.

type Pagination

type Pagination struct {
	Total  int `json:"total"`
	Limit  int `json:"limit"`
	Offset int `json:"offset"`
}

type PriceOrder

type PriceOrder struct {
	ID               string `json:"id"`
	TxSignature      string `json:"txSignature"`
	DepositConfirmed bool   `json:"depositConfirmed"`
	Message          string `json:"message"`

	Metadata response.Metadata `json:"-"`
}

PriceOrder is the result of creating a price order. The deposit lands during the call; DepositConfirmed reports whether it has landed and the order is active.

type PriceOrderEvent

type PriceOrderEvent struct {
	Type         string `json:"type"`
	Timestamp    int64  `json:"timestamp"`
	TxSignature  string `json:"txSignature"`
	State        string `json:"state"`
	Mint         string `json:"mint"`
	Amount       string `json:"amount"`
	OutputMint   string `json:"outputMint"`
	OutputAmount string `json:"outputAmount"`
	OrderContext string `json:"orderContext"`
}

type PriceOrderHistory

type PriceOrderHistory struct {
	Orders     []PriceOrderRecord `json:"orders"`
	Pagination Pagination         `json:"pagination"`

	Metadata response.Metadata `json:"-"`
}

type PriceOrderRecord

type PriceOrderRecord struct {
	ID                   string            `json:"id"`
	OrderType            string            `json:"orderType"`
	OrderState           string            `json:"orderState"`
	RawState             string            `json:"rawState"`
	UserPubkey           string            `json:"userPubkey"`
	PrivyWalletPubkey    string            `json:"privyWalletPubkey"`
	InputMint            string            `json:"inputMint"`
	InitialInputAmount   string            `json:"initialInputAmount"`
	RemainingInputAmount string            `json:"remainingInputAmount"`
	OutputMint           string            `json:"outputMint"`
	TriggerMint          string            `json:"triggerMint"`
	TriggerCondition     string            `json:"triggerCondition"`
	TriggerPriceUSD      json.Number       `json:"triggerPriceUsd"`
	SlippageBps          json.Number       `json:"slippageBps"`
	ExpiresAt            *int64            `json:"expiresAt"`
	CreatedAt            int64             `json:"createdAt"`
	UpdatedAt            int64             `json:"updatedAt"`
	TriggeredAt          *int64            `json:"triggeredAt"`
	OutputAmount         *string           `json:"outputAmount"`
	InputUsed            *string           `json:"inputUsed"`
	FillPercent          json.Number       `json:"fillPercent"`
	TrailingBps          json.Number       `json:"trailingBps"`
	HighWatermark        json.Number       `json:"highWatermark"`
	LowWatermark         json.Number       `json:"lowWatermark"`
	Events               []PriceOrderEvent `json:"events"`
}

type PriceOrderRequest

type PriceOrderRequest struct {
	OrderType                string
	DepositRequestID         string
	DepositSignedTransaction string
	InputMint                string
	InputAmount              string
	OutputMint               string
	TriggerMint              string
	TriggerCondition         string
	TriggerPriceUSD          json.Number
	TrailingBps              *uint16
	SlippageBps              *uint16
	TakeProfitPriceUSD       json.Number
	StopLossPriceUSD         json.Number
	TakeProfitSlippageBps    *uint16
	StopLossSlippageBps      *uint16
	ExpiresAt                time.Time
}

PriceOrderRequest creates a price order funded by a signed deposit. OrderType is OrderSubTypeSingle, OrderSubTypeOCO, or OrderSubTypeOTOCO and must match the deposit's sub-type. Prices are USD JSON numbers, kept exact as json.Number.

  • single: TriggerCondition plus exactly one of TriggerPriceUSD or TrailingBps. A trailing order uses TriggerMint == InputMint for TriggerBelow and TriggerMint == OutputMint for TriggerAbove.
  • oco: TakeProfitPriceUSD above StopLossPriceUSD; no trigger fields.
  • otoco: TriggerCondition and TriggerPriceUSD for the parent, plus the take-profit and stop-loss pair.

Jupiter enforces a 10 USD minimum and does not check whether a trigger price makes economic sense.

type PriceOrderUpdate

type PriceOrderUpdate struct {
	OrderType             string
	TriggerPriceUSD       json.Number
	TrailingBps           *uint16
	SlippageBps           *uint16
	TakeProfitPriceUSD    json.Number
	StopLossPriceUSD      json.Number
	TakeProfitSlippageBps *uint16
	StopLossSlippageBps   *uint16
}

PriceOrderUpdate changes an open price order in place. OrderType is required and must be the order's type; set only the fields to change.

type Session

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

Session holds one wallet's tokens and authorizes Trigger operations for that wallet only. It is safe for concurrent use; refreshes are serialized because presenting an already rotated refresh token revokes the session.

func (*Session) AuthTokens

func (s *Session) AuthTokens() AuthTokens

AuthTokens returns the current token pair, for example to persist it before exit.

func (*Session) CancelDCAOrder

func (s *Session) CancelDCAOrder(ctx context.Context, id string) (*Cancellation, error)

CancelDCAOrder starts cancelling a DCA order and returns the withdrawal for the unfilled remainder. Filled rounds are not reversed and the order cannot return to active. Repeating the call while withdrawing is documented as idempotent.

func (*Session) CancelPriceOrder

func (s *Session) CancelPriceOrder(ctx context.Context, id string) (*Cancellation, error)

CancelPriceOrder starts cancelling an order, including an expired one whose funds remain in the vault. It only crafts a withdrawal transaction, so transient failures are retried. HTTP 400 can mean the order is not yet ready to cancel.

func (*Session) ConfirmCancelDCAOrder

func (s *Session) ConfirmCancelDCAOrder(
	ctx context.Context,
	id string,
	r ConfirmCancelRequest,
) (*Submission, error)

ConfirmCancelDCAOrder submits the signed withdrawal. It makes one attempt; failures after which the withdrawal may have landed wrap ErrOutcomeUnknown. A failed confirmation leaves the order withdrawing; call CancelDCAOrder again to re-craft the withdrawal.

func (*Session) ConfirmCancelPriceOrder

func (s *Session) ConfirmCancelPriceOrder(
	ctx context.Context,
	id string,
	r ConfirmCancelRequest,
) (*Submission, error)

ConfirmCancelPriceOrder submits the signed withdrawal. It makes one attempt; failures after which the withdrawal may have landed wrap ErrOutcomeUnknown. If the withdrawal did not land, the documented recovery is to confirm again with the same cancel request ID.

func (*Session) CraftDeposit

func (s *Session) CraftDeposit(ctx context.Context, r DepositRequest) (*Deposit, error)

CraftDeposit builds an unsigned deposit transaction from the session's wallet. Signing alone moves no funds; the order creation call submits it.

func (*Session) CreateDCAOrder

func (s *Session) CreateDCAOrder(ctx context.Context, r DCAOrderRequest) (*Submission, error)

CreateDCAOrder submits the signed deposit and creates the DCA order. It makes one attempt; failures after which the deposit may have landed wrap ErrOutcomeUnknown. Check DCAOrderHistory before creating another order.

func (*Session) CreatePriceOrder

func (s *Session) CreatePriceOrder(ctx context.Context, r PriceOrderRequest) (*PriceOrder, error)

CreatePriceOrder submits the signed deposit and creates the order. It makes one attempt; failures after which the deposit may have landed wrap ErrOutcomeUnknown. Check PriceOrderHistory before creating another order.

func (*Session) DCAOrder

func (s *Session) DCAOrder(ctx context.Context, id string) (*DCAOrderRecord, error)

DCAOrder returns one DCA order with its events.

func (*Session) DCAOrderHistory

func (s *Session) DCAOrderHistory(ctx context.Context, r HistoryRequest) (*DCAOrderHistory, error)

DCAOrderHistory lists the wallet's DCA orders.

func (*Session) EnsureVault

func (s *Session) EnsureVault(ctx context.Context) (*Vault, error)

EnsureVault returns the wallet's vault, registering it first if none exists.

func (*Session) Logout

func (s *Session) Logout(ctx context.Context) error

Logout revokes this session's refresh token and closes the session. Access tokens already issued remain valid upstream until they expire.

func (*Session) LogoutAll

func (s *Session) LogoutAll(ctx context.Context) error

LogoutAll revokes every refresh token issued for the wallet, on all devices, and closes this session.

func (*Session) PriceOrderHistory

func (s *Session) PriceOrderHistory(ctx context.Context, r HistoryRequest) (*PriceOrderHistory, error)

PriceOrderHistory lists the wallet's price orders.

func (*Session) RegisterVault

func (s *Session) RegisterVault(ctx context.Context) (*Vault, error)

RegisterVault creates the wallet's vault. It makes one attempt because the operation creates state; an already registered vault returns HTTP 409. Prefer EnsureVault, which handles both cases.

func (*Session) UpdatePriceOrder

func (s *Session) UpdatePriceOrder(
	ctx context.Context,
	id string,
	u PriceOrderUpdate,
) (*OrderUpdate, error)

UpdatePriceOrder changes an open order. Updates set absolute values, so transient failures are retried.

func (*Session) Vault

func (s *Session) Vault(ctx context.Context) (*Vault, error)

Vault returns the wallet's vault, or an error wrapping ErrNoVault.

func (*Session) Wallet

func (s *Session) Wallet() string

Wallet returns the address the session is authorized for.

type SessionOptions

type SessionOptions struct {
	// OnRefresh receives every rotated token pair, for example to persist it for
	// Resume. Rotation invalidates the previous refresh token, so a stored copy that
	// is not updated cannot resume the session. Calls are serialized.
	OnRefresh func(context.Context, AuthTokens) error
}

type Submission

type Submission struct {
	ID          string `json:"id"`
	TxSignature string `json:"txSignature"`

	Metadata response.Metadata `json:"-"`
}

Submission identifies an order and the on-chain transaction submitted for it.

type Vault

type Vault struct {
	UserPubkey   string `json:"userPubkey"`
	VaultPubkey  string `json:"vaultPubkey"`
	PrivyVaultID string `json:"privyVaultId"`
	PrivyUserID  string `json:"privyUserId"`

	Metadata response.Metadata `json:"-"`
}

Vault is the custodial vault that holds deposits for the wallet's orders.

type VerifyRequest

type VerifyRequest struct {
	Wallet            string
	Type              string
	Signature         string
	SignedTransaction string
}

VerifyRequest submits a signed challenge. Set Signature (base58) for a message challenge or SignedTransaction (base64) for a transaction challenge.

Jump to

Keyboard shortcuts

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