mirror of
https://github.com/discountry/ritmex-bot.git
synced 2026-09-11 17:28:08 +00:00
Compare commits
18
Commits
5f79b134f2
...
6dcf13481d
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6dcf13481d | ||
|
|
3fd0f715a1 | ||
|
|
85e7f245c0 | ||
|
|
03df1006cc | ||
|
|
3099cb1319 | ||
|
|
49b8f0bcf1 | ||
|
|
a23eb91f04 | ||
|
|
974d3017e0 | ||
|
|
668c3a57d3 | ||
|
|
819ce93a90 | ||
|
|
061a8dd8f1 | ||
|
|
49df78c075 | ||
|
|
6a6b61c491 | ||
|
|
7612e25dd1 | ||
|
|
705e489c17 | ||
|
|
9a418aba41 | ||
|
|
2cb6c4fef1 | ||
|
|
180f47b6e0 |
@@ -1,3 +1,6 @@
|
||||
# UI language (zh | en)
|
||||
LANG=zh
|
||||
|
||||
# Exchange selection
|
||||
EXCHANGE=aster # Pick aster (default) or grvt/lighter/backpack/paradex
|
||||
|
||||
|
||||
@@ -33,3 +33,6 @@ report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
|
||||
|
||||
# Finder (MacOS) folder config
|
||||
.DS_Store
|
||||
|
||||
.tmp
|
||||
.tmp/*
|
||||
@@ -1,5 +1,11 @@
|
||||
# ritmex-bot
|
||||
|
||||
> For English users, please see [README_en.md](README_en.md).
|
||||
|
||||
Please set `LANG=en` in `.env` for English interface.
|
||||
|
||||
A Bun-powered multi-exchange perpetuals workstation that ships an SMA30 trend engine, a Guardian stop sentinel, and two market-making modes. It offers instant restarts, realtime market data, structured logging, and an Ink-based CLI dashboard.
|
||||
|
||||
基于 Bun 的多交易所永续合约量化终端,内置趋势跟随(SMA30)、Guardian 防守与做市策略,支持快速恢复、实时行情订阅、日志追踪与 CLI 仪表盘。
|
||||
|
||||
如果您希望获取优惠并支持本项目,请考虑使用以下注册链接:
|
||||
@@ -14,7 +20,6 @@
|
||||
* [Apex 手续费优惠注册链接](https://join.omni.apex.exchange/SEA)
|
||||
|
||||
## 文档索引
|
||||
- [English README](README_en.md)
|
||||
- [简明上手指南(零基础)](simple-readme.md)
|
||||
- [基础网格策略使用教程](grid-trading.md)
|
||||
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
*.go text eol=lf
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
.idea
|
||||
vendor
|
||||
build/*
|
||||
!build/.keep
|
||||
/build
|
||||
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,94 @@
|
||||
# lighter-go
|
||||
|
||||
This repository serves as the reference implementation of signing & hashing of Lighter transactions.
|
||||
The sharedlib is compiled for a variety of platforms.
|
||||
- macOS (darwin) dynamic library (.dylib) for arm architecture (M processor, not Intel)
|
||||
- linux shared object (.so) for both amd64 and arm architectures
|
||||
- windows .ddl (dynamic-link library) for amd64 architecture
|
||||
|
||||
The go SDK implements just the core signing, as well as a small HTTP client so that users can:
|
||||
- not specify the nonce of the transaction (this will result in an HTTP call, so beware)
|
||||
- check that a client was initialized correctly, by verifying that the given API key matches the one on the server
|
||||
|
||||
The [Python SDK](https://github.com/elliottech/lighter-python) offers support for HTTP and WebSocket functionality as well as [examples](https://github.com/elliottech/lighter-python/tree/main/examples) on how to generate the API keys, how to create and cancel orders, generate AUTH tokens for various HTTP/WS endpoints which require them.
|
||||
|
||||
All generated shared libraries follow the naming convention `lighter_signer_{os}_{arch}` where os is linux/windows/darwin and arch is amd64(x86) or arm64.\
|
||||
The build & accompanying `.h` files can be found in the release notes [here](https://github.com/elliottech/lighter-go/releases).\
|
||||
If you'd like to compile your own binaries, the commands are in the `justfile`.
|
||||
|
||||
|
||||
## Transactions
|
||||
```
|
||||
=== Client ===
|
||||
CreateClient
|
||||
CheckClient
|
||||
|
||||
=== API Key ===
|
||||
CreateAuthToken
|
||||
SignChangePubKey
|
||||
GenerateAPIKey
|
||||
|
||||
=== Order ===
|
||||
SignCreateOrder
|
||||
SignCreateGroupedOrders
|
||||
SignCancelOrder
|
||||
SignCancelAllOrders
|
||||
SignModifyOrder
|
||||
|
||||
=== Leverage & Margin ===
|
||||
SignUpdateLeverage
|
||||
SignUpdateMargin
|
||||
|
||||
=== Transfers ===
|
||||
SignWithdraw
|
||||
SignTransfer
|
||||
|
||||
=== Sub account & pools ===
|
||||
SignCreateSubAccount
|
||||
SignCreatePublicPool
|
||||
SignUpdatePublicPool
|
||||
SignMintShares
|
||||
SignBurnShares
|
||||
```
|
||||
|
||||
## How to specify an account
|
||||
Accounts are loaded into the signer by calling the `CreateClient` method. If you wish to load multiple API keys in the signer, you need to call the method multiple times, each time with the correct private key.
|
||||
|
||||
By default, signer will work out of the box with 1 client and no need to manage nonces in any specific way. Just pass `-1, 255, 0` for all methods (more explanations below).
|
||||
|
||||
You can call `CheckClient` to verify that the provided Private key & (apiKeyIndex, accountIndex) are configured correctly.
|
||||
This checks that the public key associated with the pair (apiKey,account) matches the one from the exchange.
|
||||
|
||||
The majority of methods receive 3 arguments at the end:
|
||||
- `nonce`
|
||||
- default `-1`
|
||||
- required to be strictly incremental
|
||||
- you can fetch the next nonce using `nextNonce` HTTP call
|
||||
- if default is passed, signer will do the HTTP call automatically
|
||||
- ideally the caller should manage nonces locally to avoid latency
|
||||
- `apiKeyIndex`
|
||||
- default `255`
|
||||
- specified which API key will be used for the specific transaction
|
||||
- all API keys are equal. Orders created by one API key can be canceled by others, for example
|
||||
- each API key has its own nonce
|
||||
- if default is passed, signer will use the default txClient
|
||||
- `accountIndex`
|
||||
- default `0`
|
||||
- specified which account will be used for the specific transaction
|
||||
- this can be a subaccount or a different main account all together
|
||||
- if default is passed, signer will use the default txClient
|
||||
|
||||
**Note:** in order to use the default client, you need to bash both the default values for `apiKeyIndex` and `accountIndex`
|
||||
|
||||
## Auth tokens
|
||||
|
||||
Auth tokens are used to call various HTTP & WS endpoints which hold sensitive information, like open orders.
|
||||
An auth token is valid for 8 hours.
|
||||
|
||||
`CreateAuthToken(deadline=0)` will result in a token that's valid for 7 hours from now.
|
||||
|
||||
Calling `CreateAuthToken` with an expiry 20 hours in the future will work, but the token will start to be valid in 12 hours, because the max accepted deadline duration by the server is 8 hours. \
|
||||
This still allows you to generate all the tokens ahead of time and use them accordingly. \
|
||||
Such an approach (both implementation & how to manage them) can be found in great details in the [python-sdk](https://github.com/elliottech/lighter-python/tree/main/examples/read-only-auth).
|
||||
|
||||
**Note:** auth tokens are bound to an API key. Changing the API key to something else **will invalidate** all generated auth tokens.
|
||||
@@ -0,0 +1,116 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
curve "github.com/elliottech/poseidon_crypto/curve/ecgfp5"
|
||||
schnorr "github.com/elliottech/poseidon_crypto/signature/schnorr"
|
||||
"github.com/ethereum/go-ethereum/common/hexutil"
|
||||
)
|
||||
|
||||
// SharedClientManager holds the global txClient and backupTxClients
|
||||
// This will be managed by both sharedlib and wasm builds
|
||||
// Supports multiple accounts and API keys with thread safety
|
||||
var (
|
||||
txClientMu sync.Mutex
|
||||
defaultTxClient *TxClient
|
||||
defaultClientPerAccount = make(map[int64]*TxClient)
|
||||
allTxClients map[int64]map[uint8]*TxClient // accountIndex -> apiKeyIndex -> client
|
||||
)
|
||||
|
||||
// GenerateAPIKey generates a new API key pair from a seed
|
||||
func GenerateAPIKey(seed string) (string, string, error) {
|
||||
var seedP *string
|
||||
if seed != "" {
|
||||
seedP = &seed
|
||||
}
|
||||
|
||||
key := curve.SampleScalar(seedP)
|
||||
publicKeyStr := hexutil.Encode(schnorr.SchnorrPkFromSk(key).ToLittleEndianBytes())
|
||||
privateKeyStr := hexutil.Encode(key.ToLittleEndianBytes())
|
||||
|
||||
return privateKeyStr, publicKeyStr, nil
|
||||
}
|
||||
|
||||
// GetClient retrieves a client for specific account and API key
|
||||
// If apiKeyIndex==255 && accountIndex==-1, returns default client
|
||||
func GetClient(apiKeyIndex uint8, accountIndex int64) (*TxClient, error) {
|
||||
txClientMu.Lock()
|
||||
defer txClientMu.Unlock()
|
||||
|
||||
if apiKeyIndex == 255 && accountIndex != -1 {
|
||||
client := defaultClientPerAccount[accountIndex]
|
||||
if client != nil {
|
||||
return client, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Special case: return default client
|
||||
if apiKeyIndex == 255 && accountIndex == -1 {
|
||||
if defaultTxClient == nil {
|
||||
return nil, fmt.Errorf("client is not created, call CreateClient() first")
|
||||
}
|
||||
return defaultTxClient, nil
|
||||
}
|
||||
|
||||
// Look up client in double map
|
||||
var c *TxClient
|
||||
if allTxClients[accountIndex] != nil {
|
||||
c = allTxClients[accountIndex][apiKeyIndex]
|
||||
}
|
||||
|
||||
if c == nil {
|
||||
return nil, fmt.Errorf("client is not created for apiKeyIndex: %v accountIndex: %v", apiKeyIndex, accountIndex)
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// CreateClient creates a new TxClient and stores it
|
||||
// httpClientFactory is a function that creates an HTTP client from a URL string
|
||||
func CreateClient(httpClient MinimalHTTPClient, privateKey string, chainId uint32, apiKeyIndex uint8, accountIndex int64) (*TxClient, error) {
|
||||
if accountIndex <= 0 {
|
||||
return nil, fmt.Errorf("invalid account index")
|
||||
}
|
||||
|
||||
txClientInstance, err := NewTxClient(httpClient, privateKey, accountIndex, apiKeyIndex, chainId)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error occurred when creating TxClient. err: %v", err)
|
||||
}
|
||||
|
||||
txClientMu.Lock()
|
||||
if allTxClients == nil {
|
||||
allTxClients = make(map[int64]map[uint8]*TxClient)
|
||||
}
|
||||
if allTxClients[accountIndex] == nil {
|
||||
allTxClients[accountIndex] = make(map[uint8]*TxClient)
|
||||
}
|
||||
allTxClients[accountIndex][apiKeyIndex] = txClientInstance
|
||||
|
||||
// Update default client (most recently created becomes default)
|
||||
defaultTxClient = txClientInstance
|
||||
defaultClientPerAccount[accountIndex] = txClientInstance
|
||||
txClientMu.Unlock()
|
||||
|
||||
return txClientInstance, nil
|
||||
}
|
||||
|
||||
// Check validates that the client exists and the API key matches the one on the server
|
||||
func (c *TxClient) Check() error {
|
||||
// check that the API key registered on Lighter matches this one
|
||||
publicKey, err := c.HTTP().GetApiKey(c.accountIndex, c.apiKeyIndex)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get Api Keys. err: %v", err)
|
||||
}
|
||||
|
||||
pubKeyBytes := c.GetKeyManager().PubKeyBytes()
|
||||
pubKeyStr := hexutil.Encode(pubKeyBytes[:])
|
||||
pubKeyStr = strings.Replace(pubKeyStr, "0x", "", 1)
|
||||
|
||||
if publicKey != pubKeyStr {
|
||||
return fmt.Errorf("private key does not match the one on Lighter. ownPubKey: %s response: %+v", pubKeyStr, publicKey)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
# HTTP
|
||||
The HTTP module is a simple implementation that aims to provide just 2 things:
|
||||
- `GetNextNonce` so that users can send transactions w/out calling managing nonces on their side
|
||||
- `GetApiKey` so that users can call `CheckClient` from other sources, which makes sure that the client was configured correctly.
|
||||
|
||||
Other usages, like sending trades, fetching open orders or any WebSocket operations should happen outside the core SDK.
|
||||
@@ -0,0 +1,45 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"net"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
core "github.com/elliottech/lighter-go/client"
|
||||
)
|
||||
|
||||
var (
|
||||
dialer = &net.Dialer{
|
||||
Timeout: 10 * time.Second,
|
||||
KeepAlive: 60 * time.Second,
|
||||
}
|
||||
transport = &http.Transport{
|
||||
DialContext: dialer.DialContext,
|
||||
MaxConnsPerHost: 1000,
|
||||
MaxIdleConnsPerHost: 100,
|
||||
IdleConnTimeout: 10 * time.Second,
|
||||
TLSClientConfig: &tls.Config{InsecureSkipVerify: false},
|
||||
}
|
||||
|
||||
httpClient = &http.Client{
|
||||
Timeout: time.Second * 30,
|
||||
Transport: transport,
|
||||
}
|
||||
)
|
||||
|
||||
var _ core.MinimalHTTPClient = (*client)(nil)
|
||||
|
||||
type client struct {
|
||||
endpoint string
|
||||
}
|
||||
|
||||
func NewClient(baseUrl string) core.MinimalHTTPClient {
|
||||
if baseUrl == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
return &client{
|
||||
endpoint: baseUrl,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package http
|
||||
|
||||
const (
|
||||
CodeOK = 200
|
||||
)
|
||||
|
||||
type ResultCode struct {
|
||||
Code int32 `json:"code,example=200"`
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
type NextNonce struct {
|
||||
ResultCode
|
||||
Nonce int64 `json:"nonce,example=722"`
|
||||
}
|
||||
|
||||
type ApiKey struct {
|
||||
AccountIndex int64 `json:"account_index,example=3"`
|
||||
ApiKeyIndex uint8 `json:"api_key_index,example=0"`
|
||||
Nonce int64 `json:"nonce,example=722"`
|
||||
PublicKey string `json:"public_key"`
|
||||
}
|
||||
|
||||
type AccountApiKeys struct {
|
||||
ResultCode
|
||||
ApiKeys []*ApiKey `json:"api_keys"`
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
func (c *client) parseResultStatus(respBody []byte) error {
|
||||
resultStatus := &ResultCode{}
|
||||
if err := json.Unmarshal(respBody, resultStatus); err != nil {
|
||||
return err
|
||||
}
|
||||
if resultStatus.Code != CodeOK {
|
||||
return errors.New(resultStatus.Message)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *client) getAndParseL2HTTPResponse(path string, params map[string]any, result interface{}) error {
|
||||
u, err := url.Parse(c.endpoint)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
u.Path = path
|
||||
|
||||
q := u.Query()
|
||||
for k, v := range params {
|
||||
q.Set(k, fmt.Sprintf("%v", v))
|
||||
}
|
||||
u.RawQuery = q.Encode()
|
||||
resp, err := httpClient.Get(u.String())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return errors.New(string(body))
|
||||
}
|
||||
if err = c.parseResultStatus(body); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := json.Unmarshal(body, result); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *client) GetNextNonce(accountIndex int64, apiKeyIndex uint8) (int64, error) {
|
||||
result := &NextNonce{}
|
||||
err := c.getAndParseL2HTTPResponse("api/v1/nextNonce", map[string]any{"account_index": accountIndex, "api_key_index": apiKeyIndex}, result)
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
return result.Nonce, nil
|
||||
}
|
||||
|
||||
func (c *client) GetApiKey(accountIndex int64, apiKeyIndex uint8) (string, error) {
|
||||
result := &AccountApiKeys{}
|
||||
err := c.getAndParseL2HTTPResponse("api/v1/apikeys", map[string]any{"account_index": accountIndex, "api_key_index": apiKeyIndex}, result)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(result.ApiKeys) == 0 {
|
||||
return "", fmt.Errorf("no api keys returned")
|
||||
}
|
||||
return result.ApiKeys[0].PublicKey, nil
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package client
|
||||
|
||||
type MinimalHTTPClient interface {
|
||||
GetNextNonce(accountIndex int64, apiKeyIndex uint8) (int64, error)
|
||||
GetApiKey(accountIndex int64, apiKeyIndex uint8) (string, error)
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/elliottech/lighter-go/signer"
|
||||
"github.com/elliottech/lighter-go/types"
|
||||
)
|
||||
|
||||
var (
|
||||
// DefaultExpireTime is a public var, so it can be changed directly in the SDK if required.
|
||||
// The encouraged behaviour is the manually specify the TX deadline in types.TransactOpts.ExpiredAt
|
||||
DefaultExpireTime = time.Minute*10 - time.Second // we need to give a second margin, to eliminate millisecond differences
|
||||
)
|
||||
|
||||
type TxClient struct {
|
||||
apiClient MinimalHTTPClient
|
||||
chainId uint32
|
||||
keyManager signer.KeyManager
|
||||
accountIndex int64
|
||||
apiKeyIndex uint8
|
||||
}
|
||||
|
||||
// NewTxClient is linked to a specific (account, apiKey) pair
|
||||
// apiKeyPrivateKey should be hex-encoded bytes generated using `hexutil.Encode(TxClient.GetKeyManager().PrvKeyBytes())`
|
||||
func NewTxClient(apiClient MinimalHTTPClient, apiKeyPrivateKey string, accountIndex int64, apiKeyIndex uint8, chainId uint32) (*TxClient, error) {
|
||||
// remove 0x from private key, if any, and parse to bytes
|
||||
if len(apiKeyPrivateKey) < 2 {
|
||||
return nil, fmt.Errorf("empty private key")
|
||||
}
|
||||
if apiKeyPrivateKey[:2] == "0x" {
|
||||
apiKeyPrivateKey = apiKeyPrivateKey[2:]
|
||||
}
|
||||
|
||||
b, err := hex.DecodeString(apiKeyPrivateKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
keyManager, err := signer.NewKeyManager(b)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &TxClient{
|
||||
apiClient: apiClient,
|
||||
apiKeyIndex: apiKeyIndex,
|
||||
accountIndex: accountIndex,
|
||||
chainId: chainId,
|
||||
keyManager: keyManager,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// FullFillDefaultOps returns a usable TransactOpts object if none was provided.
|
||||
// This should not the be case for sharedlib, except for the nonce, which is optional.
|
||||
// Still, the behaviour is implemented, so it can be extended easily by extending the code GO SDK.
|
||||
func (c *TxClient) FullFillDefaultOps(ops *types.TransactOpts) (*types.TransactOpts, error) {
|
||||
if ops == nil {
|
||||
ops = new(types.TransactOpts)
|
||||
}
|
||||
if ops.ExpiredAt == 0 {
|
||||
ops.ExpiredAt = time.Now().Add(DefaultExpireTime).UnixMilli()
|
||||
}
|
||||
if ops.FromAccountIndex == nil {
|
||||
ops.FromAccountIndex = &c.accountIndex
|
||||
}
|
||||
if ops.ApiKeyIndex == nil {
|
||||
ops.ApiKeyIndex = &c.apiKeyIndex
|
||||
}
|
||||
if ops.Nonce == nil || *ops.Nonce == -1 {
|
||||
if c.apiClient == nil {
|
||||
return nil, fmt.Errorf("nonce was not provided & HTTPClient is nil. Either provide the nonce or enable HTTPClient to get the nonce from Lighter")
|
||||
}
|
||||
nonce, err := c.apiClient.GetNextNonce(*ops.FromAccountIndex, *ops.ApiKeyIndex)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ops.Nonce = &nonce
|
||||
}
|
||||
|
||||
return ops, nil
|
||||
}
|
||||
|
||||
func (c *TxClient) GetChainId() uint32 {
|
||||
return c.chainId
|
||||
}
|
||||
|
||||
func (c *TxClient) GetKeyManager() signer.KeyManager {
|
||||
return c.keyManager
|
||||
}
|
||||
|
||||
func (c *TxClient) GetAccountIndex() int64 {
|
||||
return c.accountIndex
|
||||
}
|
||||
|
||||
func (c *TxClient) GetApiKeyIndex() uint8 {
|
||||
return c.apiKeyIndex
|
||||
}
|
||||
|
||||
func (c *TxClient) HTTP() MinimalHTTPClient {
|
||||
return c.apiClient
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
schnorr "github.com/elliottech/poseidon_crypto/signature/schnorr"
|
||||
|
||||
"github.com/elliottech/lighter-go/types"
|
||||
"github.com/elliottech/lighter-go/types/txtypes"
|
||||
)
|
||||
|
||||
func (c *TxClient) GetAuthToken(deadline time.Time) (string, error) {
|
||||
return types.ConstructAuthToken(c.keyManager, deadline, &types.TransactOpts{
|
||||
ApiKeyIndex: &c.apiKeyIndex,
|
||||
FromAccountIndex: &c.accountIndex,
|
||||
})
|
||||
}
|
||||
|
||||
func (c *TxClient) GetChangePubKeyTransaction(tx *types.ChangePubKeyReq, ops *types.TransactOpts) (*txtypes.L2ChangePubKeyTxInfo, error) {
|
||||
ops, err := c.FullFillDefaultOps(ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
txInfo, err := types.ConstructChangePubKeyTx(c.keyManager, c.chainId, tx, ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
pk := c.keyManager.PubKeyBytes()
|
||||
msgHash, _ := txInfo.Hash(c.chainId)
|
||||
|
||||
if err := schnorr.Validate(pk[:], msgHash, txInfo.Sig); err != nil {
|
||||
return nil, fmt.Errorf("failed to validate signature. error: %v", err)
|
||||
}
|
||||
|
||||
return txInfo, nil
|
||||
}
|
||||
|
||||
func (c *TxClient) GetCreateSubAccountTransaction(ops *types.TransactOpts) (*txtypes.L2CreateSubAccountTxInfo, error) {
|
||||
ops, err := c.FullFillDefaultOps(ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
txInfo, err := types.ConstructCreateSubAccountTx(c.keyManager, c.chainId, ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return txInfo, nil
|
||||
}
|
||||
|
||||
func (c *TxClient) GetCreatePublicPoolTransaction(tx *types.CreatePublicPoolTxReq, ops *types.TransactOpts) (*txtypes.L2CreatePublicPoolTxInfo, error) {
|
||||
ops, err := c.FullFillDefaultOps(ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
txInfo, err := types.ConstructCreatePublicPoolTx(c.keyManager, c.chainId, tx, ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return txInfo, nil
|
||||
}
|
||||
|
||||
func (c *TxClient) GetUpdatePublicPoolTransaction(tx *types.UpdatePublicPoolTxReq, ops *types.TransactOpts) (*txtypes.L2UpdatePublicPoolTxInfo, error) {
|
||||
ops, err := c.FullFillDefaultOps(ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
txInfo, err := types.ConstructUpdatePublicPoolTx(c.keyManager, c.chainId, tx, ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return txInfo, nil
|
||||
}
|
||||
|
||||
func (c *TxClient) GetTransferTransaction(tx *types.TransferTxReq, ops *types.TransactOpts) (*txtypes.L2TransferTxInfo, error) {
|
||||
ops, err := c.FullFillDefaultOps(ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
txInfo, err := types.ConstructTransferTx(c.keyManager, c.chainId, tx, ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return txInfo, nil
|
||||
}
|
||||
|
||||
func (c *TxClient) GetWithdrawTransaction(tx *types.WithdrawTxReq, ops *types.TransactOpts) (*txtypes.L2WithdrawTxInfo, error) {
|
||||
ops, err := c.FullFillDefaultOps(ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
txInfo, err := types.ConstructWithdrawTx(c.keyManager, c.chainId, tx, ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return txInfo, nil
|
||||
}
|
||||
|
||||
func (c *TxClient) GetCreateOrderTransaction(tx *types.CreateOrderTxReq, ops *types.TransactOpts) (*txtypes.L2CreateOrderTxInfo, error) {
|
||||
ops, err := c.FullFillDefaultOps(ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
txInfo, err := types.ConstructCreateOrderTx(c.keyManager, c.chainId, tx, ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return txInfo, nil
|
||||
}
|
||||
|
||||
func (c *TxClient) GetCreateGroupedOrdersTransaction(tx *types.CreateGroupedOrdersTxReq, ops *types.TransactOpts) (*txtypes.L2CreateGroupedOrdersTxInfo, error) {
|
||||
ops, err := c.FullFillDefaultOps(ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
txInfo, err := types.ConstructL2CreateGroupedOrdersTx(c.keyManager, c.chainId, tx, ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return txInfo, nil
|
||||
}
|
||||
|
||||
func (c *TxClient) GetCancelOrderTransaction(tx *types.CancelOrderTxReq, ops *types.TransactOpts) (*txtypes.L2CancelOrderTxInfo, error) {
|
||||
ops, err := c.FullFillDefaultOps(ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
txInfo, err := types.ConstructL2CancelOrderTx(c.keyManager, c.chainId, tx, ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return txInfo, nil
|
||||
}
|
||||
|
||||
func (c *TxClient) GetModifyOrderTransaction(tx *types.ModifyOrderTxReq, ops *types.TransactOpts) (*txtypes.L2ModifyOrderTxInfo, error) {
|
||||
ops, err := c.FullFillDefaultOps(ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
txInfo, err := types.ConstructL2ModifyOrderTx(c.keyManager, c.chainId, tx, ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return txInfo, nil
|
||||
}
|
||||
|
||||
func (c *TxClient) GetCancelAllOrdersTransaction(tx *types.CancelAllOrdersTxReq, ops *types.TransactOpts) (*txtypes.L2CancelAllOrdersTxInfo, error) {
|
||||
ops, err := c.FullFillDefaultOps(ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
txInfo, err := types.ConstructL2CancelAllOrdersTx(c.keyManager, c.chainId, tx, ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return txInfo, nil
|
||||
}
|
||||
|
||||
func (c *TxClient) GetMintSharesTransaction(tx *types.MintSharesTxReq, ops *types.TransactOpts) (*txtypes.L2MintSharesTxInfo, error) {
|
||||
ops, err := c.FullFillDefaultOps(ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
txInfo, err := types.ConstructMintSharesTx(c.keyManager, c.chainId, tx, ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return txInfo, nil
|
||||
}
|
||||
|
||||
func (c *TxClient) GetBurnSharesTransaction(tx *types.BurnSharesTxReq, ops *types.TransactOpts) (*txtypes.L2BurnSharesTxInfo, error) {
|
||||
ops, err := c.FullFillDefaultOps(ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
txInfo, err := types.ConstructBurnSharesTx(c.keyManager, c.chainId, tx, ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return txInfo, nil
|
||||
}
|
||||
|
||||
func (c *TxClient) GetUpdateLeverageTransaction(tx *types.UpdateLeverageTxReq, ops *types.TransactOpts) (*txtypes.L2UpdateLeverageTxInfo, error) {
|
||||
ops, err := c.FullFillDefaultOps(ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
txInfo, err := types.ConstructUpdateLeverageTx(c.keyManager, c.chainId, tx, ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return txInfo, nil
|
||||
}
|
||||
|
||||
func (c *TxClient) GetUpdateMarginTransaction(tx *types.UpdateMarginTxReq, ops *types.TransactOpts) (*txtypes.L2UpdateMarginTxInfo, error) {
|
||||
ops, err := c.FullFillDefaultOps(ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
txInfo, err := types.ConstructUpdateMarginTx(c.keyManager, c.chainId, tx, ops)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return txInfo, nil
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
module github.com/elliottech/lighter-go
|
||||
|
||||
go 1.23.0
|
||||
|
||||
toolchain go1.23.1
|
||||
|
||||
require (
|
||||
github.com/elliottech/poseidon_crypto v0.0.11
|
||||
github.com/ethereum/go-ethereum v1.15.6
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/bits-and-blooms/bitset v1.17.0 // indirect
|
||||
github.com/consensys/bavard v0.1.22 // indirect
|
||||
github.com/consensys/gnark-crypto v0.14.0 // indirect
|
||||
github.com/crate-crypto/go-ipa v0.0.0-20240724233137-53bbb0ceb27a // indirect
|
||||
github.com/crate-crypto/go-kzg-4844 v1.1.0 // indirect
|
||||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 // indirect
|
||||
github.com/ethereum/c-kzg-4844 v1.0.0 // indirect
|
||||
github.com/ethereum/go-verkle v0.2.2 // indirect
|
||||
github.com/holiman/uint256 v1.3.2 // indirect
|
||||
github.com/mmcloughlin/addchain v0.4.0 // indirect
|
||||
github.com/supranational/blst v0.3.14 // indirect
|
||||
golang.org/x/crypto v0.35.0 // indirect
|
||||
golang.org/x/sync v0.11.0 // indirect
|
||||
golang.org/x/sys v0.30.0 // indirect
|
||||
rsc.io/tmplfunc v0.0.3 // indirect
|
||||
)
|
||||
@@ -0,0 +1,76 @@
|
||||
github.com/StackExchange/wmi v1.2.1 h1:VIkavFPXSjcnS+O8yTq7NI32k0R5Aj+v39y29VYDOSA=
|
||||
github.com/StackExchange/wmi v1.2.1/go.mod h1:rcmrprowKIVzvc+NUiLncP2uuArMWLCbu9SBzvHz7e8=
|
||||
github.com/VictoriaMetrics/fastcache v1.12.2 h1:N0y9ASrJ0F6h0QaC3o6uJb3NIZ9VKLjCM7NQbSmF7WI=
|
||||
github.com/VictoriaMetrics/fastcache v1.12.2/go.mod h1:AmC+Nzz1+3G2eCPapF6UcsnkThDcMsQicp4xDukwJYI=
|
||||
github.com/bits-and-blooms/bitset v1.17.0 h1:1X2TS7aHz1ELcC0yU1y2stUs/0ig5oMU6STFZGrhvHI=
|
||||
github.com/bits-and-blooms/bitset v1.17.0/go.mod h1:7hO7Gc7Pp1vODcmWvKMRA9BNmbv6a/7QIWpPxHddWR8=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/consensys/bavard v0.1.22 h1:Uw2CGvbXSZWhqK59X0VG/zOjpTFuOMcPLStrp1ihI0A=
|
||||
github.com/consensys/bavard v0.1.22/go.mod h1:k/zVjHHC4B+PQy1Pg7fgvG3ALicQw540Crag8qx+dZs=
|
||||
github.com/consensys/gnark-crypto v0.14.0 h1:DDBdl4HaBtdQsq/wfMwJvZNE80sHidrK3Nfrefatm0E=
|
||||
github.com/consensys/gnark-crypto v0.14.0/go.mod h1:CU4UijNPsHawiVGNxe9co07FkzCeWHHrb1li/n1XoU0=
|
||||
github.com/crate-crypto/go-ipa v0.0.0-20240724233137-53bbb0ceb27a h1:W8mUrRp6NOVl3J+MYp5kPMoUZPp7aOYHtaua31lwRHg=
|
||||
github.com/crate-crypto/go-ipa v0.0.0-20240724233137-53bbb0ceb27a/go.mod h1:sTwzHBvIzm2RfVCGNEBZgRyjwK40bVoun3ZnGOCafNM=
|
||||
github.com/crate-crypto/go-kzg-4844 v1.1.0 h1:EN/u9k2TF6OWSHrCCDBBU6GLNMq88OspHHlMnHfoyU4=
|
||||
github.com/crate-crypto/go-kzg-4844 v1.1.0/go.mod h1:JolLjpSff1tCCJKaJx4psrlEdlXuJEC996PL3tTAFks=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/decred/dcrd/crypto/blake256 v1.0.0 h1:/8DMNYp9SGi5f0w7uCm6d6M4OU2rGFK09Y2A4Xv7EE0=
|
||||
github.com/decred/dcrd/crypto/blake256 v1.0.0/go.mod h1:sQl2p6Y26YV+ZOcSTP6thNdn47hh8kt6rqSlvmrXFAc=
|
||||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1 h1:YLtO71vCjJRCBcrPMtQ9nqBsqpA1m5sE92cU+pd5Mcc=
|
||||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.0.1/go.mod h1:hyedUtir6IdtD/7lIxGeCxkaw7y45JueMRL4DIyJDKs=
|
||||
github.com/elliottech/poseidon_crypto v0.0.11 h1:iX4rCg0m1XIX/7mhXVUEYUJIdQD57zNGNLeb6RZRl7g=
|
||||
github.com/elliottech/poseidon_crypto v0.0.11/go.mod h1:NhWxSjPGr5JXRuB2Aepl/+ZrbmUG3hvku/GarB1JR8c=
|
||||
github.com/ethereum/c-kzg-4844 v1.0.0 h1:0X1LBXxaEtYD9xsyj9B9ctQEZIpnvVDeoBx8aHEwTNA=
|
||||
github.com/ethereum/c-kzg-4844 v1.0.0/go.mod h1:VewdlzQmpT5QSrVhbBuGoCdFJkpaJlO1aQputP83wc0=
|
||||
github.com/ethereum/go-ethereum v1.15.6 h1:jgLoUM6/pNjp0uEnXyWcWikDwa4j1wZlcqkX8Pm8A+I=
|
||||
github.com/ethereum/go-ethereum v1.15.6/go.mod h1:+S9k+jFzlyVTNcYGvqFhzN/SFhI6vA+aOY4T5tLSPL0=
|
||||
github.com/ethereum/go-verkle v0.2.2 h1:I2W0WjnrFUIzzVPwm8ykY+7pL2d4VhlsePn4j7cnFk8=
|
||||
github.com/ethereum/go-verkle v0.2.2/go.mod h1:M3b90YRnzqKyyzBEWJGqj8Qff4IDeXnzFw0P9bFw3uk=
|
||||
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
|
||||
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
|
||||
github.com/gofrs/flock v0.8.1 h1:+gYjHKf32LDeiEEFhQaotPbLuUXjY5ZqxKgXy7n59aw=
|
||||
github.com/gofrs/flock v0.8.1/go.mod h1:F1TvTiK9OcQqauNUHlbJvyl9Qa1QvF/gOUDKA14jxHU=
|
||||
github.com/golang/snappy v0.0.5-0.20220116011046-fa5810519dcb h1:PBC98N2aIaM3XXiurYmW7fx4GZkL8feAMVq7nEjURHk=
|
||||
github.com/golang/snappy v0.0.5-0.20220116011046-fa5810519dcb/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||
github.com/google/subcommands v1.2.0/go.mod h1:ZjhPrFU+Olkh9WazFPsl27BQ4UPiG37m3yTrtFlrHVk=
|
||||
github.com/holiman/uint256 v1.3.2 h1:a9EgMPSC1AAaj1SZL5zIQD3WbwTuHrMGOerLjGmM/TA=
|
||||
github.com/holiman/uint256 v1.3.2/go.mod h1:EOMSn4q6Nyt9P6efbI3bueV4e1b3dGlUCXeiRV4ng7E=
|
||||
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
|
||||
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
|
||||
github.com/leanovate/gopter v0.2.11 h1:vRjThO1EKPb/1NsDXuDrzldR28RLkBflWYcU9CvzWu4=
|
||||
github.com/leanovate/gopter v0.2.11/go.mod h1:aK3tzZP/C+p1m3SPRE4SYZFGP7jjkuSI4f7Xvpt0S9c=
|
||||
github.com/mattn/go-runewidth v0.0.13 h1:lTGmDsbAYt5DmK6OnoV7EuIF1wEIFAcxld6ypU4OSgU=
|
||||
github.com/mattn/go-runewidth v0.0.13/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||
github.com/mmcloughlin/addchain v0.4.0 h1:SobOdjm2xLj1KkXN5/n0xTIWyZA2+s99UCY1iPfkHRY=
|
||||
github.com/mmcloughlin/addchain v0.4.0/go.mod h1:A86O+tHqZLMNO4w6ZZ4FlVQEadcoqkyU72HC5wJ4RlU=
|
||||
github.com/mmcloughlin/profile v0.1.1/go.mod h1:IhHD7q1ooxgwTgjxQYkACGA77oFTDdFVejUS1/tS/qU=
|
||||
github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=
|
||||
github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
|
||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible h1:Bn1aCHHRnjv4Bl16T8rcaFjYSrGrIZvpiGO6P3Q4GpU=
|
||||
github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA=
|
||||
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/supranational/blst v0.3.14 h1:xNMoHRJOTwMn63ip6qoWJ2Ymgvj7E2b9jY2FAwY+qRo=
|
||||
github.com/supranational/blst v0.3.14/go.mod h1:jZJtfjgudtNl4en1tzwPIV3KjUnQUvG3/j+w+fVonLw=
|
||||
github.com/tklauser/go-sysconf v0.3.12 h1:0QaGUFOdQaIVdPgfITYzaTegZvdCjmYO52cSFAEVmqU=
|
||||
github.com/tklauser/go-sysconf v0.3.12/go.mod h1:Ho14jnntGE1fpdOqQEEaiKRpvIavV0hSfmBq8nJbHYI=
|
||||
github.com/tklauser/numcpus v0.6.1 h1:ng9scYS7az0Bk4OZLvrNXNSAO2Pxr1XXRAPyjhIx+Fk=
|
||||
github.com/tklauser/numcpus v0.6.1/go.mod h1:1XfjsgE2zo8GVw7POkMbHENHzVg3GzmoZ9fESEdAacY=
|
||||
golang.org/x/crypto v0.35.0 h1:b15kiHdrGCHrP6LvwaQ3c03kgNhhiMgvlhxHQhmg2Xs=
|
||||
golang.org/x/crypto v0.35.0/go.mod h1:dy7dXNW32cAb/6/PRuTNsix8T+vJAqvuIy5Bli/x0YQ=
|
||||
golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w=
|
||||
golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
|
||||
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
rsc.io/tmplfunc v0.0.3 h1:53XFQh69AfOa8Tw0Jm7t+GV7KZhOi6jzsCzTtKbMvzU=
|
||||
rsc.io/tmplfunc v0.0.3/go.mod h1:AG3sTPzElb1Io3Yg4voV9AGZJuleGAwaVRxL9M49PhA=
|
||||
@@ -0,0 +1,49 @@
|
||||
### Local builds
|
||||
|
||||
build-darwin-local:
|
||||
go mod vendor
|
||||
go build -buildmode=c-shared -trimpath -o ./build/lighter-signer-darwin-arm64.dylib ./sharedlib/main.go
|
||||
|
||||
# Note: build-linux-local does not append -arm or amd64 at end
|
||||
build-linux-local:
|
||||
go mod vendor
|
||||
CGO_ENABLED=1 go build -buildmode=c-shared -trimpath -o ./build/lighter-signer-linux.so ./sharedlib/main.go
|
||||
|
||||
# Note: build-windows-local does not append -arm or amd64 at end
|
||||
# Windows build (requires gcc from msys2: choco install msys2)
|
||||
# CMD: set PATH=C:\msys64\mingw64\bin;%PATH% && set CGO_ENABLED=1 && go mod vendor && go build -buildmode=c-shared -trimpath -o ./build/signer-amd64.dll ./sharedlib/main.go
|
||||
# PowerShell: $env:Path='C:\msys64\mingw64\bin;'+$env:Path; $env:CGO_ENABLED='1'; go mod vendor; go build -buildmode=c-shared -trimpath -o ./build/signer-amd64.dll ./sharedlib/main.go
|
||||
build-windows-local:
|
||||
go mod vendor
|
||||
$env:Path='C:\msys64\mingw64\bin;'+$env:Path; $env:CGO_ENABLED='1'; go build -buildmode=c-shared -trimpath -o ./build/lighter-signer-windows.dll ./sharedlib/main.go
|
||||
|
||||
### Docker builds
|
||||
|
||||
# Note: I don't think this works TBH
|
||||
#build-darwin-arm64-docker:
|
||||
# docker run --rm -v ${PWD}:/go/src/sdk -w /go/src/sdk golang:1.23.2-bullseye bash -c " \
|
||||
# cd /go/src/sdk && \
|
||||
# go build -buildmode=c-shared -trimpath -o ./build/lighter-signer-darwin-arm64.dylib ./sharedlib"
|
||||
|
||||
build-linux-amd64-docker:
|
||||
go mod vendor
|
||||
docker run --rm --platform linux/amd64 -v ${PWD}:/go/src/sdk -w /go/src/sdk golang:1.23.2-bullseye /bin/sh -c " \
|
||||
CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -buildmode=c-shared -trimpath -o ./build/lighter-signer-linux-amd64.so ./sharedlib"
|
||||
|
||||
build-linux-arm64-docker:
|
||||
go mod vendor
|
||||
docker run --rm --platform linux/arm64 -v ${PWD}:/go/src/sdk -w /go/src/sdk golang:1.23.2-bullseye /bin/sh -c " \
|
||||
CGO_ENABLED=1 GOOS=linux GOARCH=arm64 go build -buildmode=c-shared -trimpath -o ./build/lighter-signer-linux-arm64.so ./sharedlib"
|
||||
|
||||
build-windows-amd64-docker:
|
||||
go mod vendor
|
||||
docker run --rm --platform linux/amd64 -v ${PWD}:/go/src/sdk -w /go/src/sdk golang:1.23.2-bullseye bash -c " \
|
||||
apt-get update && \
|
||||
apt-get install -y gcc-mingw-w64-x86-64 && \
|
||||
CGO_ENABLED=1 GOOS=windows GOARCH=amd64 CC=x86_64-w64-mingw32-gcc go build -buildmode=c-shared -trimpath -o ./build/lighter-signer-windows-amd64.dll ./sharedlib"
|
||||
|
||||
### WASM builds
|
||||
|
||||
build-wasm:
|
||||
go mod vendor
|
||||
GOOS=js GOARCH=wasm go build -trimpath -o ./build/lighter-signer.wasm ./wasm/
|
||||
@@ -0,0 +1,690 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/elliottech/lighter-go/client"
|
||||
"github.com/elliottech/lighter-go/client/http"
|
||||
"github.com/elliottech/lighter-go/types"
|
||||
"github.com/elliottech/lighter-go/types/txtypes"
|
||||
"github.com/ethereum/go-ethereum/common/hexutil"
|
||||
)
|
||||
|
||||
/*
|
||||
#include <stdlib.h>
|
||||
#include <stdint.h>
|
||||
typedef struct {
|
||||
char* str;
|
||||
char* err;
|
||||
} StrOrErr;
|
||||
|
||||
typedef struct {
|
||||
uint8_t txType;
|
||||
char* txInfo;
|
||||
char* txHash;
|
||||
char* messageToSign;
|
||||
char* err;
|
||||
} SignedTxResponse;
|
||||
|
||||
typedef struct {
|
||||
char* privateKey;
|
||||
char* publicKey;
|
||||
char* err;
|
||||
} ApiKeyResponse;
|
||||
|
||||
typedef struct {
|
||||
uint8_t MarketIndex;
|
||||
int64_t ClientOrderIndex;
|
||||
int64_t BaseAmount;
|
||||
uint32_t Price;
|
||||
uint8_t IsAsk;
|
||||
uint8_t Type;
|
||||
uint8_t TimeInForce;
|
||||
uint8_t ReduceOnly;
|
||||
uint32_t TriggerPrice;
|
||||
int64_t OrderExpiry;
|
||||
} CreateOrderTxReq;
|
||||
*/
|
||||
import "C"
|
||||
|
||||
var chainId uint32
|
||||
|
||||
func wrapErr(err any) *C.char {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
return C.CString(fmt.Sprintf("%v", err))
|
||||
}
|
||||
|
||||
func messageToSign(txInfo txtypes.TxInfo) string {
|
||||
switch typed := txInfo.(type) {
|
||||
case *txtypes.L2ChangePubKeyTxInfo:
|
||||
return typed.GetL1SignatureBody()
|
||||
case *txtypes.L2TransferTxInfo:
|
||||
return typed.GetL1SignatureBody(chainId)
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func signedTxResponseErr(err any) C.SignedTxResponse {
|
||||
return C.SignedTxResponse{err: wrapErr(err)}
|
||||
}
|
||||
|
||||
func signedTxResponsePanic(err any) C.SignedTxResponse {
|
||||
return signedTxResponseErr(fmt.Errorf("panic: %v", err))
|
||||
}
|
||||
|
||||
func convertTxInfoToResponse(txInfo txtypes.TxInfo, err error) C.SignedTxResponse {
|
||||
if err != nil {
|
||||
return signedTxResponseErr(err)
|
||||
}
|
||||
if txInfo == nil {
|
||||
return signedTxResponseErr("nil transaction info")
|
||||
}
|
||||
|
||||
txInfoStr, err := txInfo.GetTxInfo()
|
||||
if err != nil {
|
||||
return signedTxResponseErr(err)
|
||||
}
|
||||
|
||||
resp := C.SignedTxResponse{
|
||||
txType: C.uint8_t(txInfo.GetTxType()),
|
||||
txInfo: C.CString(txInfoStr),
|
||||
txHash: C.CString(txInfo.GetTxHash()),
|
||||
}
|
||||
|
||||
if msg := messageToSign(txInfo); msg != "" {
|
||||
resp.messageToSign = C.CString(msg)
|
||||
}
|
||||
|
||||
return resp
|
||||
}
|
||||
|
||||
// getClient returns the go TxClient from the specified cApiKeyIndex and cAccountIndex
|
||||
func getClient(cApiKeyIndex C.int, cAccountIndex C.longlong) (*client.TxClient, error) {
|
||||
apiKeyIndex := uint8(cApiKeyIndex)
|
||||
accountIndex := int64(cAccountIndex)
|
||||
return client.GetClient(apiKeyIndex, accountIndex)
|
||||
}
|
||||
|
||||
func getTransactOpts(cNonce C.longlong) *types.TransactOpts {
|
||||
nonce := int64(cNonce)
|
||||
return &types.TransactOpts{
|
||||
Nonce: &nonce,
|
||||
}
|
||||
}
|
||||
|
||||
//export GenerateAPIKey
|
||||
func GenerateAPIKey(cSeed *C.char) (ret C.ApiKeyResponse) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
ret = C.ApiKeyResponse{err: wrapErr(fmt.Errorf("panic: %v", r))}
|
||||
}
|
||||
}()
|
||||
|
||||
seed := C.GoString(cSeed)
|
||||
privateKeyStr, publicKeyStr, err := client.GenerateAPIKey(seed)
|
||||
if err != nil {
|
||||
return C.ApiKeyResponse{err: wrapErr(err)}
|
||||
}
|
||||
|
||||
return C.ApiKeyResponse{
|
||||
privateKey: C.CString(privateKeyStr),
|
||||
publicKey: C.CString(publicKeyStr),
|
||||
}
|
||||
}
|
||||
|
||||
//export CreateClient
|
||||
func CreateClient(cUrl *C.char, cPrivateKey *C.char, cChainId C.int, cApiKeyIndex C.int, cAccountIndex C.longlong) (ret *C.char) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
ret = wrapErr(fmt.Errorf("panic: %v", r))
|
||||
}
|
||||
}()
|
||||
|
||||
url := C.GoString(cUrl)
|
||||
privateKey := C.GoString(cPrivateKey)
|
||||
chainId = uint32(cChainId)
|
||||
apiKeyIndex := uint8(cApiKeyIndex)
|
||||
accountIndex := int64(cAccountIndex)
|
||||
|
||||
httpClient := http.NewClient(url)
|
||||
|
||||
_, err := client.CreateClient(httpClient, privateKey, chainId, apiKeyIndex, accountIndex)
|
||||
return wrapErr(err)
|
||||
}
|
||||
|
||||
//export CheckClient
|
||||
func CheckClient(cApiKeyIndex C.int, cAccountIndex C.longlong) (ret *C.char) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
ret = wrapErr(fmt.Errorf("panic: %v", r))
|
||||
}
|
||||
}()
|
||||
|
||||
c, err := getClient(cApiKeyIndex, cAccountIndex)
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
|
||||
return wrapErr(c.Check())
|
||||
}
|
||||
|
||||
//export SignChangePubKey
|
||||
func SignChangePubKey(cPubKey *C.char, cNonce C.longlong, cApiKeyIndex C.int, cAccountIndex C.longlong) (ret C.SignedTxResponse) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
ret = signedTxResponsePanic(r)
|
||||
}
|
||||
}()
|
||||
|
||||
c, err := getClient(cApiKeyIndex, cAccountIndex)
|
||||
if err != nil {
|
||||
return signedTxResponseErr(err)
|
||||
}
|
||||
|
||||
pubKeyStr := C.GoString(cPubKey)
|
||||
pubKeyBytes, err := hexutil.Decode(pubKeyStr)
|
||||
if err != nil {
|
||||
return signedTxResponseErr(err)
|
||||
}
|
||||
if len(pubKeyBytes) != 40 {
|
||||
return signedTxResponseErr(fmt.Errorf("invalid pub key length. expected 40 but got %v", len(pubKeyBytes)))
|
||||
}
|
||||
var pubKey [40]byte
|
||||
copy(pubKey[:], pubKeyBytes)
|
||||
|
||||
tx := &types.ChangePubKeyReq{
|
||||
PubKey: pubKey,
|
||||
}
|
||||
ops := getTransactOpts(cNonce)
|
||||
|
||||
txInfo, err := c.GetChangePubKeyTransaction(tx, ops)
|
||||
return convertTxInfoToResponse(txInfo, err)
|
||||
}
|
||||
|
||||
//export SignCreateOrder
|
||||
func SignCreateOrder(cMarketIndex C.int, cClientOrderIndex C.longlong, cBaseAmount C.longlong, cPrice C.int, cIsAsk C.int, cOrderType C.int, cTimeInForce C.int, cReduceOnly C.int, cTriggerPrice C.int, cOrderExpiry C.longlong, cNonce C.longlong, cApiKeyIndex C.int, cAccountIndex C.longlong) (ret C.SignedTxResponse) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
ret = signedTxResponsePanic(r)
|
||||
}
|
||||
}()
|
||||
|
||||
c, err := getClient(cApiKeyIndex, cAccountIndex)
|
||||
if err != nil {
|
||||
return signedTxResponseErr(err)
|
||||
}
|
||||
|
||||
marketIndex := int16(cMarketIndex)
|
||||
clientOrderIndex := int64(cClientOrderIndex)
|
||||
baseAmount := int64(cBaseAmount)
|
||||
price := uint32(cPrice)
|
||||
isAsk := uint8(cIsAsk)
|
||||
orderType := uint8(cOrderType)
|
||||
timeInForce := uint8(cTimeInForce)
|
||||
reduceOnly := uint8(cReduceOnly)
|
||||
triggerPrice := uint32(cTriggerPrice)
|
||||
orderExpiry := int64(cOrderExpiry)
|
||||
|
||||
if orderExpiry == -1 {
|
||||
orderExpiry = time.Now().Add(time.Hour * 24 * 28).UnixMilli() // 28 days
|
||||
}
|
||||
|
||||
tx := &types.CreateOrderTxReq{
|
||||
MarketIndex: marketIndex,
|
||||
ClientOrderIndex: clientOrderIndex,
|
||||
BaseAmount: baseAmount,
|
||||
Price: price,
|
||||
IsAsk: isAsk,
|
||||
Type: orderType,
|
||||
TimeInForce: timeInForce,
|
||||
ReduceOnly: reduceOnly,
|
||||
TriggerPrice: triggerPrice,
|
||||
OrderExpiry: orderExpiry,
|
||||
}
|
||||
ops := getTransactOpts(cNonce)
|
||||
|
||||
txInfo, err := c.GetCreateOrderTransaction(tx, ops)
|
||||
return convertTxInfoToResponse(txInfo, err)
|
||||
}
|
||||
|
||||
//export SignCreateGroupedOrders
|
||||
func SignCreateGroupedOrders(cGroupingType C.uint8_t, cOrders *C.CreateOrderTxReq, cLen C.int, cNonce C.longlong, cApiKeyIndex C.int, cAccountIndex C.longlong) (ret C.SignedTxResponse) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
ret = signedTxResponsePanic(r)
|
||||
}
|
||||
}()
|
||||
|
||||
c, err := getClient(cApiKeyIndex, cAccountIndex)
|
||||
if err != nil {
|
||||
return signedTxResponseErr(err)
|
||||
}
|
||||
|
||||
length := int(cLen)
|
||||
orders := make([]*types.CreateOrderTxReq, length)
|
||||
size := unsafe.Sizeof(*cOrders)
|
||||
|
||||
for i := 0; i < length; i++ {
|
||||
order := (*C.CreateOrderTxReq)(unsafe.Pointer(uintptr(unsafe.Pointer(cOrders)) + uintptr(i)*uintptr(size)))
|
||||
|
||||
orderExpiry := int64(order.OrderExpiry)
|
||||
if orderExpiry == -1 {
|
||||
orderExpiry = time.Now().Add(time.Hour * 24 * 28).UnixMilli()
|
||||
}
|
||||
|
||||
orders[i] = &types.CreateOrderTxReq{
|
||||
MarketIndex: int16(order.MarketIndex),
|
||||
ClientOrderIndex: int64(order.ClientOrderIndex),
|
||||
BaseAmount: int64(order.BaseAmount),
|
||||
Price: uint32(order.Price),
|
||||
IsAsk: uint8(order.IsAsk),
|
||||
Type: uint8(order.Type),
|
||||
TimeInForce: uint8(order.TimeInForce),
|
||||
ReduceOnly: uint8(order.ReduceOnly),
|
||||
TriggerPrice: uint32(order.TriggerPrice),
|
||||
OrderExpiry: orderExpiry,
|
||||
}
|
||||
}
|
||||
|
||||
tx := &types.CreateGroupedOrdersTxReq{
|
||||
GroupingType: uint8(cGroupingType),
|
||||
Orders: orders,
|
||||
}
|
||||
ops := getTransactOpts(cNonce)
|
||||
|
||||
txInfo, err := c.GetCreateGroupedOrdersTransaction(tx, ops)
|
||||
return convertTxInfoToResponse(txInfo, err)
|
||||
}
|
||||
|
||||
//export SignCancelOrder
|
||||
func SignCancelOrder(cMarketIndex C.int, cOrderIndex C.longlong, cNonce C.longlong, cApiKeyIndex C.int, cAccountIndex C.longlong) (ret C.SignedTxResponse) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
ret = signedTxResponsePanic(r)
|
||||
}
|
||||
}()
|
||||
|
||||
c, err := getClient(cApiKeyIndex, cAccountIndex)
|
||||
if err != nil {
|
||||
return signedTxResponseErr(err)
|
||||
}
|
||||
|
||||
marketIndex := int16(cMarketIndex)
|
||||
orderIndex := int64(cOrderIndex)
|
||||
|
||||
tx := &types.CancelOrderTxReq{
|
||||
MarketIndex: marketIndex,
|
||||
Index: orderIndex,
|
||||
}
|
||||
ops := getTransactOpts(cNonce)
|
||||
|
||||
txInfo, err := c.GetCancelOrderTransaction(tx, ops)
|
||||
return convertTxInfoToResponse(txInfo, err)
|
||||
}
|
||||
|
||||
//export SignWithdraw
|
||||
func SignWithdraw(cAssetIndex C.int, cRouteType C.int, cAmount C.ulonglong, cNonce C.longlong, cApiKeyIndex C.int, cAccountIndex C.longlong) (ret C.SignedTxResponse) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
ret = signedTxResponsePanic(r)
|
||||
}
|
||||
}()
|
||||
|
||||
c, err := getClient(cApiKeyIndex, cAccountIndex)
|
||||
if err != nil {
|
||||
return signedTxResponseErr(err)
|
||||
}
|
||||
|
||||
assetIndex := int16(cAssetIndex)
|
||||
routeType := uint8(cRouteType)
|
||||
amount := uint64(cAmount)
|
||||
|
||||
tx := &types.WithdrawTxReq{
|
||||
AssetIndex: assetIndex,
|
||||
RouteType: routeType,
|
||||
Amount: amount,
|
||||
}
|
||||
ops := getTransactOpts(cNonce)
|
||||
|
||||
txInfo, err := c.GetWithdrawTransaction(tx, ops)
|
||||
return convertTxInfoToResponse(txInfo, err)
|
||||
}
|
||||
|
||||
//export SignCreateSubAccount
|
||||
func SignCreateSubAccount(cNonce C.longlong, cApiKeyIndex C.int, cAccountIndex C.longlong) (ret C.SignedTxResponse) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
ret = signedTxResponsePanic(r)
|
||||
}
|
||||
}()
|
||||
|
||||
c, err := getClient(cApiKeyIndex, cAccountIndex)
|
||||
if err != nil {
|
||||
return signedTxResponseErr(err)
|
||||
}
|
||||
|
||||
ops := getTransactOpts(cNonce)
|
||||
|
||||
txInfo, err := c.GetCreateSubAccountTransaction(ops)
|
||||
return convertTxInfoToResponse(txInfo, err)
|
||||
}
|
||||
|
||||
//export SignCancelAllOrders
|
||||
func SignCancelAllOrders(cTimeInForce C.int, cTime C.longlong, cNonce C.longlong, cApiKeyIndex C.int, cAccountIndex C.longlong) (ret C.SignedTxResponse) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
ret = signedTxResponsePanic(r)
|
||||
}
|
||||
}()
|
||||
|
||||
c, err := getClient(cApiKeyIndex, cAccountIndex)
|
||||
if err != nil {
|
||||
return signedTxResponseErr(err)
|
||||
}
|
||||
|
||||
timeInForce := uint8(cTimeInForce)
|
||||
t := int64(cTime)
|
||||
|
||||
tx := &types.CancelAllOrdersTxReq{
|
||||
TimeInForce: timeInForce,
|
||||
Time: t,
|
||||
}
|
||||
ops := getTransactOpts(cNonce)
|
||||
|
||||
txInfo, err := c.GetCancelAllOrdersTransaction(tx, ops)
|
||||
return convertTxInfoToResponse(txInfo, err)
|
||||
}
|
||||
|
||||
//export SignModifyOrder
|
||||
func SignModifyOrder(cMarketIndex C.int, cIndex C.longlong, cBaseAmount C.longlong, cPrice C.longlong, cTriggerPrice C.longlong, cNonce C.longlong, cApiKeyIndex C.int, cAccountIndex C.longlong) (ret C.SignedTxResponse) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
ret = signedTxResponsePanic(r)
|
||||
}
|
||||
}()
|
||||
|
||||
c, err := getClient(cApiKeyIndex, cAccountIndex)
|
||||
if err != nil {
|
||||
return signedTxResponseErr(err)
|
||||
}
|
||||
|
||||
marketIndex := int16(cMarketIndex)
|
||||
index := int64(cIndex)
|
||||
baseAmount := int64(cBaseAmount)
|
||||
price := uint32(cPrice)
|
||||
triggerPrice := uint32(cTriggerPrice)
|
||||
|
||||
tx := &types.ModifyOrderTxReq{
|
||||
MarketIndex: marketIndex,
|
||||
Index: index,
|
||||
BaseAmount: baseAmount,
|
||||
Price: price,
|
||||
TriggerPrice: triggerPrice,
|
||||
}
|
||||
ops := getTransactOpts(cNonce)
|
||||
|
||||
txInfo, err := c.GetModifyOrderTransaction(tx, ops)
|
||||
return convertTxInfoToResponse(txInfo, err)
|
||||
}
|
||||
|
||||
//export SignTransfer
|
||||
func SignTransfer(cToAccountIndex C.longlong, cAssetIndex C.int16_t, cFromRouteType, cToRouteType C.uint8_t, cAmount, cUsdcFee C.longlong, cMemo *C.char, cNonce C.longlong, cApiKeyIndex C.int, cAccountIndex C.longlong) (ret C.SignedTxResponse) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
ret = signedTxResponsePanic(r)
|
||||
}
|
||||
}()
|
||||
|
||||
c, err := getClient(cApiKeyIndex, cAccountIndex)
|
||||
if err != nil {
|
||||
return signedTxResponseErr(err)
|
||||
}
|
||||
|
||||
toAccountIndex := int64(cToAccountIndex)
|
||||
assetIndex := int16(cAssetIndex)
|
||||
fromRouteType := uint8(cFromRouteType)
|
||||
toRouteType := uint8(cToRouteType)
|
||||
amount := int64(cAmount)
|
||||
usdcFee := int64(cUsdcFee)
|
||||
memo := [32]byte{}
|
||||
memoStr := C.GoString(cMemo)
|
||||
if len(memoStr) == 66 {
|
||||
if memoStr[0:2] == "0x" {
|
||||
memoStr = memoStr[2:66]
|
||||
} else {
|
||||
return signedTxResponseErr(fmt.Sprintf("memo expected to be 32 bytes or 64 hex encoded or 66 if 0x hex encoded -- long but received %v", len(memoStr)))
|
||||
}
|
||||
}
|
||||
|
||||
// assume hex encoded here
|
||||
if len(memoStr) == 64 {
|
||||
b, err := hex.DecodeString(memoStr)
|
||||
if err != nil {
|
||||
return signedTxResponseErr(fmt.Sprintf("failed to decode hex string. err: %v", err))
|
||||
}
|
||||
|
||||
for i := 0; i < 32; i += 1 {
|
||||
memo[i] = b[i]
|
||||
}
|
||||
} else if len(memoStr) == 32 {
|
||||
for i := 0; i < 32; i++ {
|
||||
memo[i] = byte(memoStr[i])
|
||||
}
|
||||
} else {
|
||||
return signedTxResponseErr(fmt.Sprintf("memo expected to be 32 bytes or 64 hex encoded or 66 if 0x hex encoded -- long but received %v", len(memoStr)))
|
||||
}
|
||||
|
||||
tx := &types.TransferTxReq{
|
||||
ToAccountIndex: toAccountIndex,
|
||||
AssetIndex: assetIndex,
|
||||
FromRouteType: fromRouteType,
|
||||
ToRouteType: toRouteType,
|
||||
Amount: amount,
|
||||
USDCFee: usdcFee,
|
||||
Memo: memo,
|
||||
}
|
||||
ops := getTransactOpts(cNonce)
|
||||
|
||||
txInfo, err := c.GetTransferTransaction(tx, ops)
|
||||
return convertTxInfoToResponse(txInfo, err)
|
||||
}
|
||||
|
||||
//export SignCreatePublicPool
|
||||
func SignCreatePublicPool(cOperatorFee C.longlong, cInitialTotalShares C.int, cMinOperatorShareRate C.longlong, cNonce C.longlong, cApiKeyIndex C.int, cAccountIndex C.longlong) (ret C.SignedTxResponse) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
ret = signedTxResponsePanic(r)
|
||||
}
|
||||
}()
|
||||
|
||||
c, err := getClient(cApiKeyIndex, cAccountIndex)
|
||||
if err != nil {
|
||||
return signedTxResponseErr(err)
|
||||
}
|
||||
|
||||
operatorFee := int64(cOperatorFee)
|
||||
initialTotalShares := int64(cInitialTotalShares)
|
||||
minOperatorShareRate := uint16(cMinOperatorShareRate)
|
||||
|
||||
tx := &types.CreatePublicPoolTxReq{
|
||||
OperatorFee: operatorFee,
|
||||
InitialTotalShares: initialTotalShares,
|
||||
MinOperatorShareRate: minOperatorShareRate,
|
||||
}
|
||||
ops := getTransactOpts(cNonce)
|
||||
|
||||
txInfo, err := c.GetCreatePublicPoolTransaction(tx, ops)
|
||||
return convertTxInfoToResponse(txInfo, err)
|
||||
}
|
||||
|
||||
//export SignUpdatePublicPool
|
||||
func SignUpdatePublicPool(cPublicPoolIndex C.longlong, cStatus C.int, cOperatorFee C.longlong, cMinOperatorShareRate C.int, cNonce C.longlong, cApiKeyIndex C.int, cAccountIndex C.longlong) (ret C.SignedTxResponse) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
ret = signedTxResponsePanic(r)
|
||||
}
|
||||
}()
|
||||
|
||||
c, err := getClient(cApiKeyIndex, cAccountIndex)
|
||||
if err != nil {
|
||||
return signedTxResponseErr(err)
|
||||
}
|
||||
|
||||
publicPoolIndex := int64(cPublicPoolIndex)
|
||||
status := uint8(cStatus)
|
||||
operatorFee := int64(cOperatorFee)
|
||||
minOperatorShareRate := uint16(cMinOperatorShareRate)
|
||||
|
||||
tx := &types.UpdatePublicPoolTxReq{
|
||||
PublicPoolIndex: publicPoolIndex,
|
||||
Status: status,
|
||||
OperatorFee: operatorFee,
|
||||
MinOperatorShareRate: minOperatorShareRate,
|
||||
}
|
||||
ops := getTransactOpts(cNonce)
|
||||
|
||||
txInfo, err := c.GetUpdatePublicPoolTransaction(tx, ops)
|
||||
return convertTxInfoToResponse(txInfo, err)
|
||||
}
|
||||
|
||||
//export SignMintShares
|
||||
func SignMintShares(cPublicPoolIndex C.longlong, cShareAmount C.longlong, cNonce C.longlong, cApiKeyIndex C.int, cAccountIndex C.longlong) (ret C.SignedTxResponse) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
ret = signedTxResponsePanic(r)
|
||||
}
|
||||
}()
|
||||
|
||||
c, err := getClient(cApiKeyIndex, cAccountIndex)
|
||||
if err != nil {
|
||||
return signedTxResponseErr(err)
|
||||
}
|
||||
|
||||
publicPoolIndex := int64(cPublicPoolIndex)
|
||||
shareAmount := int64(cShareAmount)
|
||||
|
||||
tx := &types.MintSharesTxReq{
|
||||
PublicPoolIndex: publicPoolIndex,
|
||||
ShareAmount: shareAmount,
|
||||
}
|
||||
ops := getTransactOpts(cNonce)
|
||||
|
||||
txInfo, err := c.GetMintSharesTransaction(tx, ops)
|
||||
return convertTxInfoToResponse(txInfo, err)
|
||||
}
|
||||
|
||||
//export SignBurnShares
|
||||
func SignBurnShares(cPublicPoolIndex C.longlong, cShareAmount C.longlong, cNonce C.longlong, cApiKeyIndex C.int, cAccountIndex C.longlong) (ret C.SignedTxResponse) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
ret = signedTxResponsePanic(r)
|
||||
}
|
||||
}()
|
||||
|
||||
c, err := getClient(cApiKeyIndex, cAccountIndex)
|
||||
if err != nil {
|
||||
return signedTxResponseErr(err)
|
||||
}
|
||||
|
||||
publicPoolIndex := int64(cPublicPoolIndex)
|
||||
shareAmount := int64(cShareAmount)
|
||||
|
||||
tx := &types.BurnSharesTxReq{
|
||||
PublicPoolIndex: publicPoolIndex,
|
||||
ShareAmount: shareAmount,
|
||||
}
|
||||
ops := getTransactOpts(cNonce)
|
||||
|
||||
txInfo, err := c.GetBurnSharesTransaction(tx, ops)
|
||||
return convertTxInfoToResponse(txInfo, err)
|
||||
}
|
||||
|
||||
//export SignUpdateLeverage
|
||||
func SignUpdateLeverage(cMarketIndex C.int, cInitialMarginFraction C.int, cMarginMode C.int, cNonce C.longlong, cApiKeyIndex C.int, cAccountIndex C.longlong) (ret C.SignedTxResponse) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
ret = signedTxResponsePanic(r)
|
||||
}
|
||||
}()
|
||||
|
||||
c, err := getClient(cApiKeyIndex, cAccountIndex)
|
||||
if err != nil {
|
||||
return signedTxResponseErr(err)
|
||||
}
|
||||
|
||||
marketIndex := int16(cMarketIndex)
|
||||
initialMarginFraction := uint16(cInitialMarginFraction)
|
||||
marginMode := uint8(cMarginMode)
|
||||
|
||||
tx := &types.UpdateLeverageTxReq{
|
||||
MarketIndex: marketIndex,
|
||||
InitialMarginFraction: initialMarginFraction,
|
||||
MarginMode: marginMode,
|
||||
}
|
||||
ops := getTransactOpts(cNonce)
|
||||
|
||||
txInfo, err := c.GetUpdateLeverageTransaction(tx, ops)
|
||||
return convertTxInfoToResponse(txInfo, err)
|
||||
}
|
||||
|
||||
//export CreateAuthToken
|
||||
func CreateAuthToken(cDeadline C.longlong, cApiKeyIndex C.int, cAccountIndex C.longlong) (ret C.StrOrErr) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
ret = C.StrOrErr{err: wrapErr(fmt.Errorf("panic: %v", r))}
|
||||
}
|
||||
}()
|
||||
|
||||
c, err := getClient(cApiKeyIndex, cAccountIndex)
|
||||
if err != nil {
|
||||
return C.StrOrErr{err: wrapErr(err)}
|
||||
}
|
||||
|
||||
deadline := int64(cDeadline)
|
||||
if deadline == 0 {
|
||||
deadline = time.Now().Add(time.Hour * 7).Unix()
|
||||
}
|
||||
|
||||
authToken, err := c.GetAuthToken(time.Unix(deadline, 0))
|
||||
if err != nil {
|
||||
return C.StrOrErr{err: wrapErr(err)}
|
||||
}
|
||||
|
||||
return C.StrOrErr{str: C.CString(authToken)}
|
||||
}
|
||||
|
||||
//export SignUpdateMargin
|
||||
func SignUpdateMargin(cMarketIndex C.int, cUSDCAmount C.longlong, cDirection C.int, cNonce C.longlong, cApiKeyIndex C.int, cAccountIndex C.longlong) (ret C.SignedTxResponse) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
ret = signedTxResponsePanic(r)
|
||||
}
|
||||
}()
|
||||
|
||||
c, err := getClient(cApiKeyIndex, cAccountIndex)
|
||||
if err != nil {
|
||||
return signedTxResponseErr(err)
|
||||
}
|
||||
|
||||
marketIndex := int16(cMarketIndex)
|
||||
usdcAmount := int64(cUSDCAmount)
|
||||
direction := uint8(cDirection)
|
||||
|
||||
tx := &types.UpdateMarginTxReq{
|
||||
MarketIndex: marketIndex,
|
||||
USDCAmount: usdcAmount,
|
||||
Direction: direction,
|
||||
}
|
||||
ops := getTransactOpts(cNonce)
|
||||
|
||||
txInfo, err := c.GetUpdateMarginTransaction(tx, ops)
|
||||
return convertTxInfoToResponse(txInfo, err)
|
||||
}
|
||||
|
||||
func main() {}
|
||||
@@ -0,0 +1,54 @@
|
||||
package signer
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"hash"
|
||||
|
||||
curve "github.com/elliottech/poseidon_crypto/curve/ecgfp5"
|
||||
gFp5 "github.com/elliottech/poseidon_crypto/field/goldilocks_quintic_extension"
|
||||
schnorr "github.com/elliottech/poseidon_crypto/signature/schnorr"
|
||||
)
|
||||
|
||||
type Signer interface {
|
||||
Sign(message []byte, hFunc hash.Hash) ([]byte, error)
|
||||
}
|
||||
|
||||
type KeyManager interface {
|
||||
Signer
|
||||
PubKey() gFp5.Element
|
||||
PubKeyBytes() [40]byte
|
||||
PrvKeyBytes() []byte
|
||||
}
|
||||
|
||||
type keyManager struct {
|
||||
key curve.ECgFp5Scalar
|
||||
}
|
||||
|
||||
func NewKeyManager(b []byte) (KeyManager, error) {
|
||||
if len(b) != 40 {
|
||||
return nil, fmt.Errorf("invalid private key length. expected: 40 got: %v", len(b))
|
||||
}
|
||||
return &keyManager{key: curve.ScalarElementFromLittleEndianBytes(b)}, nil
|
||||
}
|
||||
|
||||
func (key *keyManager) Sign(hashedMessage []byte, hFunc hash.Hash) ([]byte, error) {
|
||||
hashedMessageAsQuinticExtension, err := gFp5.FromCanonicalLittleEndianBytes(hashedMessage)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse message while signing. message: %v err: %w", hashedMessage, err)
|
||||
}
|
||||
return schnorr.SchnorrSignHashedMessage(hashedMessageAsQuinticExtension, key.key).ToBytes(), nil
|
||||
}
|
||||
|
||||
func (key *keyManager) PubKey() gFp5.Element {
|
||||
return schnorr.SchnorrPkFromSk(key.key)
|
||||
}
|
||||
|
||||
func (key *keyManager) PubKeyBytes() (res [40]byte) {
|
||||
bytes := key.PubKey().ToLittleEndianBytes()
|
||||
copy(res[:], bytes[:])
|
||||
return
|
||||
}
|
||||
|
||||
func (key *keyManager) PrvKeyBytes() []byte {
|
||||
return key.key.ToLittleEndianBytes()
|
||||
}
|
||||
@@ -0,0 +1,670 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/elliottech/lighter-go/signer"
|
||||
"github.com/elliottech/lighter-go/types/txtypes"
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
gFp5 "github.com/elliottech/poseidon_crypto/field/goldilocks_quintic_extension"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
ethCommon "github.com/ethereum/go-ethereum/common"
|
||||
)
|
||||
|
||||
type TransactOpts struct {
|
||||
FromAccountIndex *int64
|
||||
ApiKeyIndex *uint8
|
||||
ExpiredAt int64
|
||||
Nonce *int64
|
||||
DryRun bool
|
||||
}
|
||||
|
||||
type PublicKey = gFp5.Element
|
||||
|
||||
type ChangePubKeyReq struct {
|
||||
PubKey [40]byte
|
||||
}
|
||||
|
||||
type TransferTxReq struct {
|
||||
ToAccountIndex int64
|
||||
AssetIndex int16
|
||||
FromRouteType uint8
|
||||
ToRouteType uint8
|
||||
Amount int64
|
||||
USDCFee int64
|
||||
Memo [32]byte
|
||||
}
|
||||
|
||||
type WithdrawTxReq struct {
|
||||
AssetIndex int16
|
||||
RouteType uint8
|
||||
Amount uint64
|
||||
}
|
||||
|
||||
type CreateOrderTxReq struct {
|
||||
MarketIndex int16
|
||||
ClientOrderIndex int64
|
||||
BaseAmount int64
|
||||
Price uint32
|
||||
IsAsk uint8
|
||||
Type uint8
|
||||
TimeInForce uint8
|
||||
ReduceOnly uint8
|
||||
TriggerPrice uint32
|
||||
OrderExpiry int64
|
||||
}
|
||||
|
||||
type CreateGroupedOrdersTxReq struct {
|
||||
GroupingType uint8
|
||||
Orders []*CreateOrderTxReq
|
||||
}
|
||||
|
||||
type ModifyOrderTxReq struct {
|
||||
MarketIndex int16
|
||||
Index int64
|
||||
BaseAmount int64
|
||||
Price uint32
|
||||
TriggerPrice uint32
|
||||
}
|
||||
|
||||
type CancelOrderTxReq struct {
|
||||
MarketIndex int16
|
||||
Index int64
|
||||
}
|
||||
|
||||
type CancelAllOrdersTxReq struct {
|
||||
TimeInForce uint8
|
||||
Time int64
|
||||
}
|
||||
|
||||
type CreatePublicPoolTxReq struct {
|
||||
OperatorFee int64
|
||||
InitialTotalShares int64
|
||||
MinOperatorShareRate uint16
|
||||
}
|
||||
|
||||
type UpdatePublicPoolTxReq struct {
|
||||
PublicPoolIndex int64
|
||||
Status uint8
|
||||
OperatorFee int64
|
||||
MinOperatorShareRate uint16
|
||||
}
|
||||
|
||||
type MintSharesTxReq struct {
|
||||
PublicPoolIndex int64
|
||||
ShareAmount int64
|
||||
}
|
||||
|
||||
type BurnSharesTxReq struct {
|
||||
PublicPoolIndex int64
|
||||
ShareAmount int64
|
||||
}
|
||||
|
||||
type UpdateLeverageTxReq struct {
|
||||
MarketIndex int16
|
||||
InitialMarginFraction uint16
|
||||
MarginMode uint8
|
||||
}
|
||||
|
||||
type UpdateMarginTxReq struct {
|
||||
MarketIndex int16
|
||||
USDCAmount int64
|
||||
Direction uint8
|
||||
}
|
||||
|
||||
func ConstructAuthToken(key signer.Signer, deadline time.Time, ops *TransactOpts) (string, error) {
|
||||
if ops.FromAccountIndex == nil {
|
||||
return "", fmt.Errorf("missing FromAccountIndex")
|
||||
}
|
||||
if ops.ApiKeyIndex == nil {
|
||||
return "", fmt.Errorf("missing ApiKeyIndex")
|
||||
}
|
||||
message := fmt.Sprintf("%v:%v:%v", deadline.Unix(), *ops.FromAccountIndex, *ops.ApiKeyIndex)
|
||||
|
||||
msgInField, err := g.ArrayFromCanonicalLittleEndianBytes([]byte(message))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to convert bytes to field element. message: %s, error: %w", message, err)
|
||||
}
|
||||
|
||||
msgHash := p2.HashToQuinticExtension(msgInField).ToLittleEndianBytes()
|
||||
|
||||
signatureBytes, err := key.Sign(msgHash, p2.NewPoseidon2())
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
signature := ethCommon.Bytes2Hex(signatureBytes)
|
||||
|
||||
return fmt.Sprintf("%v:%v", message, signature), err
|
||||
}
|
||||
|
||||
func ConstructChangePubKeyTx(key signer.Signer, lighterChainId uint32, tx *ChangePubKeyReq, ops *TransactOpts) (*txtypes.L2ChangePubKeyTxInfo, error) {
|
||||
convertedTx := ConvertChangePubKeyTx(tx, ops)
|
||||
err := convertedTx.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgHash, err := convertedTx.Hash(lighterChainId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signature, err := key.Sign(msgHash, p2.NewPoseidon2())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
convertedTx.SignedHash = ethCommon.Bytes2Hex(msgHash)
|
||||
convertedTx.Sig = signature
|
||||
return convertedTx, nil
|
||||
}
|
||||
|
||||
func ConstructCreateSubAccountTx(key signer.Signer, lighterChainId uint32, ops *TransactOpts) (*txtypes.L2CreateSubAccountTxInfo, error) {
|
||||
convertedTx := ConvertCreateSubAccountTx(ops)
|
||||
err := convertedTx.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgHash, err := convertedTx.Hash(lighterChainId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signature, err := key.Sign(msgHash, p2.NewPoseidon2())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
convertedTx.SignedHash = ethCommon.Bytes2Hex(msgHash)
|
||||
convertedTx.Sig = signature
|
||||
return convertedTx, nil
|
||||
}
|
||||
|
||||
func ConstructCreatePublicPoolTx(key signer.Signer, lighterChainId uint32, tx *CreatePublicPoolTxReq, ops *TransactOpts) (*txtypes.L2CreatePublicPoolTxInfo, error) {
|
||||
convertedTx := ConvertCreatePublicPoolTx(tx, ops)
|
||||
err := convertedTx.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgHash, err := convertedTx.Hash(lighterChainId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signature, err := key.Sign(msgHash, p2.NewPoseidon2())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
convertedTx.SignedHash = ethCommon.Bytes2Hex(msgHash)
|
||||
convertedTx.Sig = signature
|
||||
return convertedTx, nil
|
||||
}
|
||||
|
||||
func ConstructUpdatePublicPoolTx(key signer.Signer, lighterChainId uint32, tx *UpdatePublicPoolTxReq, ops *TransactOpts) (*txtypes.L2UpdatePublicPoolTxInfo, error) {
|
||||
convertedTx := ConvertUpdatePublicPoolTx(tx, ops)
|
||||
err := convertedTx.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgHash, err := convertedTx.Hash(lighterChainId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signature, err := key.Sign(msgHash, p2.NewPoseidon2())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
convertedTx.SignedHash = ethCommon.Bytes2Hex(msgHash)
|
||||
convertedTx.Sig = signature
|
||||
return convertedTx, nil
|
||||
}
|
||||
|
||||
func ConstructWithdrawTx(key signer.Signer, lighterChainId uint32, tx *WithdrawTxReq, ops *TransactOpts) (*txtypes.L2WithdrawTxInfo, error) {
|
||||
convertedTx := ConvertWithdrawTx(tx, ops)
|
||||
err := convertedTx.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgHash, err := convertedTx.Hash(lighterChainId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signature, err := key.Sign(msgHash, p2.NewPoseidon2())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
convertedTx.SignedHash = ethCommon.Bytes2Hex(msgHash)
|
||||
convertedTx.Sig = signature
|
||||
return convertedTx, nil
|
||||
}
|
||||
|
||||
func ConstructCreateOrderTx(key signer.Signer, lighterChainId uint32, tx *CreateOrderTxReq, ops *TransactOpts) (*txtypes.L2CreateOrderTxInfo, error) {
|
||||
convertedTx := ConvertCreateOrderTx(tx, ops)
|
||||
err := convertedTx.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgHash, err := convertedTx.Hash(lighterChainId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signature, err := key.Sign(msgHash, p2.NewPoseidon2())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
convertedTx.SignedHash = ethCommon.Bytes2Hex(msgHash)
|
||||
convertedTx.Sig = signature
|
||||
return convertedTx, nil
|
||||
}
|
||||
|
||||
func ConstructL2CreateGroupedOrdersTx(key signer.Signer, lighterChainId uint32, tx *CreateGroupedOrdersTxReq, ops *TransactOpts) (*txtypes.L2CreateGroupedOrdersTxInfo, error) {
|
||||
convertedTx := ConvertCreateGroupedOrdersTx(tx, ops)
|
||||
err := convertedTx.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgHash, err := convertedTx.Hash(lighterChainId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signature, err := key.Sign(msgHash, p2.NewPoseidon2())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
convertedTx.SignedHash = ethCommon.Bytes2Hex(msgHash)
|
||||
convertedTx.Sig = signature
|
||||
return convertedTx, nil
|
||||
}
|
||||
|
||||
func ConstructL2CancelOrderTx(key signer.Signer, lighterChainId uint32, tx *CancelOrderTxReq, ops *TransactOpts) (*txtypes.L2CancelOrderTxInfo, error) {
|
||||
convertedTx := ConvertCancelOrderTx(tx, ops)
|
||||
err := convertedTx.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgHash, err := convertedTx.Hash(lighterChainId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signature, err := key.Sign(msgHash, p2.NewPoseidon2())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
convertedTx.SignedHash = ethCommon.Bytes2Hex(msgHash)
|
||||
convertedTx.Sig = signature
|
||||
return convertedTx, nil
|
||||
}
|
||||
|
||||
func ConstructL2ModifyOrderTx(key signer.Signer, lighterChainId uint32, tx *ModifyOrderTxReq, ops *TransactOpts) (*txtypes.L2ModifyOrderTxInfo, error) {
|
||||
convertedTx := ConvertModifyOrderTx(tx, ops)
|
||||
err := convertedTx.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgHash, err := convertedTx.Hash(lighterChainId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signature, err := key.Sign(msgHash, p2.NewPoseidon2())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
convertedTx.SignedHash = ethCommon.Bytes2Hex(msgHash)
|
||||
convertedTx.Sig = signature
|
||||
return convertedTx, nil
|
||||
}
|
||||
|
||||
func ConstructL2CancelAllOrdersTx(key signer.Signer, lighterChainId uint32, tx *CancelAllOrdersTxReq, ops *TransactOpts) (*txtypes.L2CancelAllOrdersTxInfo, error) {
|
||||
convertedTx := ConvertCancelAllOrdersTx(tx, ops)
|
||||
err := convertedTx.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgHash, err := convertedTx.Hash(lighterChainId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signature, err := key.Sign(msgHash, p2.NewPoseidon2())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
convertedTx.SignedHash = ethCommon.Bytes2Hex(msgHash)
|
||||
convertedTx.Sig = signature
|
||||
return convertedTx, nil
|
||||
}
|
||||
|
||||
func ConstructTransferTx(key signer.Signer, lighterChainId uint32, tx *TransferTxReq, ops *TransactOpts) (*txtypes.L2TransferTxInfo, error) {
|
||||
convertedTx := ConvertTransferTx(tx, ops)
|
||||
err := convertedTx.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgHash, err := convertedTx.Hash(lighterChainId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signature, err := key.Sign(msgHash, p2.NewPoseidon2())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
convertedTx.SignedHash = ethCommon.Bytes2Hex(msgHash)
|
||||
convertedTx.Sig = signature
|
||||
return convertedTx, nil
|
||||
}
|
||||
|
||||
func ConstructMintSharesTx(key signer.Signer, lighterChainId uint32, tx *MintSharesTxReq, ops *TransactOpts) (*txtypes.L2MintSharesTxInfo, error) {
|
||||
convertedTx := ConvertMintSharesTx(tx, ops)
|
||||
err := convertedTx.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgHash, err := convertedTx.Hash(lighterChainId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signature, err := key.Sign(msgHash, p2.NewPoseidon2())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
convertedTx.SignedHash = ethCommon.Bytes2Hex(msgHash)
|
||||
convertedTx.Sig = signature
|
||||
return convertedTx, nil
|
||||
}
|
||||
|
||||
func ConstructBurnSharesTx(key signer.Signer, lighterChainId uint32, tx *BurnSharesTxReq, ops *TransactOpts) (*txtypes.L2BurnSharesTxInfo, error) {
|
||||
convertedTx := ConvertBurnSharesTx(tx, ops)
|
||||
err := convertedTx.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgHash, err := convertedTx.Hash(lighterChainId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signature, err := key.Sign(msgHash, p2.NewPoseidon2())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
convertedTx.SignedHash = ethCommon.Bytes2Hex(msgHash)
|
||||
convertedTx.Sig = signature
|
||||
return convertedTx, nil
|
||||
}
|
||||
|
||||
func ConstructUpdateLeverageTx(key signer.Signer, lighterChainId uint32, tx *UpdateLeverageTxReq, ops *TransactOpts) (*txtypes.L2UpdateLeverageTxInfo, error) {
|
||||
convertedTx := ConvertUpdateLeverageTx(tx, ops)
|
||||
err := convertedTx.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgHash, err := convertedTx.Hash(lighterChainId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signature, err := key.Sign(msgHash, p2.NewPoseidon2())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
convertedTx.SignedHash = ethCommon.Bytes2Hex(msgHash)
|
||||
convertedTx.Sig = signature
|
||||
return convertedTx, nil
|
||||
}
|
||||
|
||||
func ConstructUpdateMarginTx(key signer.Signer, lighterChainId uint32, tx *UpdateMarginTxReq, ops *TransactOpts) (*txtypes.L2UpdateMarginTxInfo, error) {
|
||||
convertedTx := ConvertUpdateMarginTx(tx, ops)
|
||||
err := convertedTx.Validate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
msgHash, err := convertedTx.Hash(lighterChainId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
signature, err := key.Sign(msgHash, p2.NewPoseidon2())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
convertedTx.SignedHash = ethCommon.Bytes2Hex(msgHash)
|
||||
convertedTx.Sig = signature
|
||||
return convertedTx, nil
|
||||
}
|
||||
|
||||
func ConvertTransferTx(tx *TransferTxReq, ops *TransactOpts) *txtypes.L2TransferTxInfo {
|
||||
return &txtypes.L2TransferTxInfo{
|
||||
FromAccountIndex: *ops.FromAccountIndex,
|
||||
ApiKeyIndex: *ops.ApiKeyIndex,
|
||||
ToAccountIndex: tx.ToAccountIndex,
|
||||
AssetIndex: tx.AssetIndex,
|
||||
FromRouteType: tx.FromRouteType,
|
||||
ToRouteType: tx.ToRouteType,
|
||||
Amount: tx.Amount,
|
||||
USDCFee: tx.USDCFee,
|
||||
Memo: tx.Memo,
|
||||
ExpiredAt: ops.ExpiredAt,
|
||||
Nonce: *ops.Nonce,
|
||||
}
|
||||
}
|
||||
|
||||
func ConvertCreateOrderTx(tx *CreateOrderTxReq, ops *TransactOpts) *txtypes.L2CreateOrderTxInfo {
|
||||
return &txtypes.L2CreateOrderTxInfo{
|
||||
AccountIndex: *ops.FromAccountIndex,
|
||||
ApiKeyIndex: *ops.ApiKeyIndex,
|
||||
OrderInfo: &txtypes.OrderInfo{MarketIndex: tx.MarketIndex,
|
||||
ClientOrderIndex: tx.ClientOrderIndex,
|
||||
BaseAmount: tx.BaseAmount,
|
||||
Price: tx.Price,
|
||||
IsAsk: tx.IsAsk,
|
||||
Type: tx.Type,
|
||||
TimeInForce: tx.TimeInForce,
|
||||
ReduceOnly: tx.ReduceOnly,
|
||||
TriggerPrice: tx.TriggerPrice,
|
||||
OrderExpiry: tx.OrderExpiry,
|
||||
},
|
||||
ExpiredAt: ops.ExpiredAt,
|
||||
Nonce: *ops.Nonce,
|
||||
}
|
||||
}
|
||||
|
||||
func ConvertCreateGroupedOrdersTx(tx *CreateGroupedOrdersTxReq, ops *TransactOpts) *txtypes.L2CreateGroupedOrdersTxInfo {
|
||||
ret := &txtypes.L2CreateGroupedOrdersTxInfo{
|
||||
AccountIndex: *ops.FromAccountIndex,
|
||||
ApiKeyIndex: *ops.ApiKeyIndex,
|
||||
GroupingType: tx.GroupingType,
|
||||
Orders: []*txtypes.OrderInfo{},
|
||||
ExpiredAt: ops.ExpiredAt,
|
||||
Nonce: *ops.Nonce,
|
||||
}
|
||||
|
||||
for _, order := range tx.Orders {
|
||||
ret.Orders = append(ret.Orders, &txtypes.OrderInfo{
|
||||
MarketIndex: order.MarketIndex,
|
||||
ClientOrderIndex: order.ClientOrderIndex,
|
||||
BaseAmount: order.BaseAmount,
|
||||
Price: order.Price,
|
||||
IsAsk: order.IsAsk,
|
||||
Type: order.Type,
|
||||
TimeInForce: order.TimeInForce,
|
||||
ReduceOnly: order.ReduceOnly,
|
||||
TriggerPrice: order.TriggerPrice,
|
||||
OrderExpiry: order.OrderExpiry,
|
||||
})
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
func ConvertCancelOrderTx(tx *CancelOrderTxReq, ops *TransactOpts) *txtypes.L2CancelOrderTxInfo {
|
||||
return &txtypes.L2CancelOrderTxInfo{
|
||||
AccountIndex: *ops.FromAccountIndex,
|
||||
ApiKeyIndex: *ops.ApiKeyIndex,
|
||||
MarketIndex: tx.MarketIndex,
|
||||
Index: tx.Index,
|
||||
ExpiredAt: ops.ExpiredAt,
|
||||
Nonce: *ops.Nonce,
|
||||
}
|
||||
}
|
||||
|
||||
func ConvertModifyOrderTx(tx *ModifyOrderTxReq, ops *TransactOpts) *txtypes.L2ModifyOrderTxInfo {
|
||||
return &txtypes.L2ModifyOrderTxInfo{
|
||||
AccountIndex: *ops.FromAccountIndex,
|
||||
ApiKeyIndex: *ops.ApiKeyIndex,
|
||||
MarketIndex: tx.MarketIndex,
|
||||
Index: tx.Index,
|
||||
BaseAmount: tx.BaseAmount,
|
||||
Price: tx.Price,
|
||||
TriggerPrice: tx.TriggerPrice,
|
||||
ExpiredAt: ops.ExpiredAt,
|
||||
Nonce: *ops.Nonce,
|
||||
}
|
||||
}
|
||||
|
||||
func ConvertCancelAllOrdersTx(tx *CancelAllOrdersTxReq, ops *TransactOpts) *txtypes.L2CancelAllOrdersTxInfo {
|
||||
return &txtypes.L2CancelAllOrdersTxInfo{
|
||||
AccountIndex: *ops.FromAccountIndex,
|
||||
ApiKeyIndex: *ops.ApiKeyIndex,
|
||||
TimeInForce: tx.TimeInForce,
|
||||
Time: tx.Time,
|
||||
ExpiredAt: ops.ExpiredAt,
|
||||
Nonce: *ops.Nonce,
|
||||
}
|
||||
}
|
||||
|
||||
func ConvertWithdrawTx(tx *WithdrawTxReq, ops *TransactOpts) *txtypes.L2WithdrawTxInfo {
|
||||
return &txtypes.L2WithdrawTxInfo{
|
||||
FromAccountIndex: *ops.FromAccountIndex,
|
||||
ApiKeyIndex: *ops.ApiKeyIndex,
|
||||
AssetIndex: tx.AssetIndex,
|
||||
RouteType: tx.RouteType,
|
||||
Amount: tx.Amount,
|
||||
ExpiredAt: ops.ExpiredAt,
|
||||
Nonce: *ops.Nonce,
|
||||
}
|
||||
}
|
||||
|
||||
func ConvertChangePubKeyTx(tx *ChangePubKeyReq, ops *TransactOpts) *txtypes.L2ChangePubKeyTxInfo {
|
||||
return &txtypes.L2ChangePubKeyTxInfo{
|
||||
AccountIndex: *ops.FromAccountIndex,
|
||||
ApiKeyIndex: *ops.ApiKeyIndex,
|
||||
PubKey: tx.PubKey[:],
|
||||
ExpiredAt: ops.ExpiredAt,
|
||||
Nonce: *ops.Nonce,
|
||||
}
|
||||
}
|
||||
|
||||
func ConvertCreateSubAccountTx(ops *TransactOpts) *txtypes.L2CreateSubAccountTxInfo {
|
||||
return &txtypes.L2CreateSubAccountTxInfo{
|
||||
AccountIndex: *ops.FromAccountIndex,
|
||||
ApiKeyIndex: *ops.ApiKeyIndex,
|
||||
ExpiredAt: ops.ExpiredAt,
|
||||
Nonce: *ops.Nonce,
|
||||
}
|
||||
}
|
||||
|
||||
func ConvertCreatePublicPoolTx(tx *CreatePublicPoolTxReq, ops *TransactOpts) *txtypes.L2CreatePublicPoolTxInfo {
|
||||
return &txtypes.L2CreatePublicPoolTxInfo{
|
||||
AccountIndex: *ops.FromAccountIndex,
|
||||
ApiKeyIndex: *ops.ApiKeyIndex,
|
||||
OperatorFee: tx.OperatorFee,
|
||||
InitialTotalShares: tx.InitialTotalShares,
|
||||
MinOperatorShareRate: tx.MinOperatorShareRate,
|
||||
ExpiredAt: ops.ExpiredAt,
|
||||
Nonce: *ops.Nonce,
|
||||
}
|
||||
}
|
||||
|
||||
func ConvertUpdatePublicPoolTx(tx *UpdatePublicPoolTxReq, ops *TransactOpts) *txtypes.L2UpdatePublicPoolTxInfo {
|
||||
return &txtypes.L2UpdatePublicPoolTxInfo{
|
||||
AccountIndex: *ops.FromAccountIndex,
|
||||
ApiKeyIndex: *ops.ApiKeyIndex,
|
||||
PublicPoolIndex: tx.PublicPoolIndex,
|
||||
Status: tx.Status,
|
||||
OperatorFee: tx.OperatorFee,
|
||||
MinOperatorShareRate: tx.MinOperatorShareRate,
|
||||
ExpiredAt: ops.ExpiredAt,
|
||||
Nonce: *ops.Nonce,
|
||||
}
|
||||
}
|
||||
|
||||
func ConvertMintSharesTx(tx *MintSharesTxReq, ops *TransactOpts) *txtypes.L2MintSharesTxInfo {
|
||||
return &txtypes.L2MintSharesTxInfo{
|
||||
AccountIndex: *ops.FromAccountIndex,
|
||||
ApiKeyIndex: *ops.ApiKeyIndex,
|
||||
PublicPoolIndex: tx.PublicPoolIndex,
|
||||
ShareAmount: tx.ShareAmount,
|
||||
ExpiredAt: ops.ExpiredAt,
|
||||
Nonce: *ops.Nonce,
|
||||
}
|
||||
}
|
||||
|
||||
func ConvertBurnSharesTx(tx *BurnSharesTxReq, ops *TransactOpts) *txtypes.L2BurnSharesTxInfo {
|
||||
return &txtypes.L2BurnSharesTxInfo{
|
||||
AccountIndex: *ops.FromAccountIndex,
|
||||
ApiKeyIndex: *ops.ApiKeyIndex,
|
||||
PublicPoolIndex: tx.PublicPoolIndex,
|
||||
ShareAmount: tx.ShareAmount,
|
||||
ExpiredAt: ops.ExpiredAt,
|
||||
Nonce: *ops.Nonce,
|
||||
}
|
||||
}
|
||||
|
||||
func ConvertUpdateLeverageTx(tx *UpdateLeverageTxReq, ops *TransactOpts) *txtypes.L2UpdateLeverageTxInfo {
|
||||
return &txtypes.L2UpdateLeverageTxInfo{
|
||||
AccountIndex: *ops.FromAccountIndex,
|
||||
ApiKeyIndex: *ops.ApiKeyIndex,
|
||||
MarketIndex: tx.MarketIndex,
|
||||
InitialMarginFraction: tx.InitialMarginFraction,
|
||||
MarginMode: tx.MarginMode,
|
||||
ExpiredAt: ops.ExpiredAt,
|
||||
Nonce: *ops.Nonce,
|
||||
}
|
||||
}
|
||||
|
||||
func ConvertUpdateMarginTx(tx *UpdateMarginTxReq, ops *TransactOpts) *txtypes.L2UpdateMarginTxInfo {
|
||||
return &txtypes.L2UpdateMarginTxInfo{
|
||||
AccountIndex: *ops.FromAccountIndex,
|
||||
ApiKeyIndex: *ops.ApiKeyIndex,
|
||||
MarketIndex: tx.MarketIndex,
|
||||
USDCAmount: tx.USDCAmount,
|
||||
Direction: tx.Direction,
|
||||
ExpiredAt: ops.ExpiredAt,
|
||||
Nonce: *ops.Nonce,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package txtypes
|
||||
|
||||
import (
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
)
|
||||
|
||||
var _ TxInfo = (*L2BurnSharesTxInfo)(nil)
|
||||
|
||||
type L2BurnSharesTxInfo struct {
|
||||
AccountIndex int64
|
||||
ApiKeyIndex uint8
|
||||
|
||||
PublicPoolIndex int64
|
||||
ShareAmount int64
|
||||
|
||||
ExpiredAt int64
|
||||
Nonce int64
|
||||
Sig []byte
|
||||
SignedHash string `json:"-"`
|
||||
}
|
||||
|
||||
func (txInfo *L2BurnSharesTxInfo) GetTxType() uint8 {
|
||||
return TxTypeL2BurnShares
|
||||
}
|
||||
|
||||
func (txInfo *L2BurnSharesTxInfo) GetTxInfo() (string, error) {
|
||||
return getTxInfo(txInfo)
|
||||
}
|
||||
|
||||
func (txInfo *L2BurnSharesTxInfo) GetTxHash() string {
|
||||
return txInfo.SignedHash
|
||||
}
|
||||
|
||||
func (txInfo *L2BurnSharesTxInfo) Validate() error {
|
||||
if txInfo.AccountIndex < MinAccountIndex {
|
||||
return ErrFromAccountIndexTooLow
|
||||
}
|
||||
if txInfo.AccountIndex > MaxAccountIndex {
|
||||
return ErrFromAccountIndexTooHigh
|
||||
}
|
||||
|
||||
// ApiKeyIndex
|
||||
if txInfo.ApiKeyIndex < MinApiKeyIndex {
|
||||
return ErrApiKeyIndexTooLow
|
||||
}
|
||||
if txInfo.ApiKeyIndex > MaxApiKeyIndex {
|
||||
return ErrApiKeyIndexTooHigh
|
||||
}
|
||||
|
||||
// PublicPoolIndex
|
||||
if txInfo.PublicPoolIndex < MinSubAccountIndex {
|
||||
return ErrPublicPoolIndexTooLow
|
||||
}
|
||||
if txInfo.PublicPoolIndex > MaxAccountIndex {
|
||||
return ErrPublicPoolIndexTooHigh
|
||||
}
|
||||
|
||||
if txInfo.ShareAmount < MinPoolSharesToMintOrBurn {
|
||||
return ErrPoolBurnShareAmountTooLow
|
||||
}
|
||||
if txInfo.ShareAmount > MaxPoolSharesToMintOrBurn {
|
||||
return ErrPoolBurnShareAmountTooHigh
|
||||
}
|
||||
|
||||
if txInfo.Nonce < MinNonce {
|
||||
return ErrNonceTooLow
|
||||
}
|
||||
|
||||
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
|
||||
return ErrExpiredAtInvalid
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
func (txInfo *L2BurnSharesTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
|
||||
elems := make([]g.Element, 0, 8)
|
||||
|
||||
elems = append(elems, g.FromUint32(lighterChainId))
|
||||
elems = append(elems, g.FromUint32(TxTypeL2BurnShares))
|
||||
elems = append(elems, g.FromInt64(txInfo.Nonce))
|
||||
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
|
||||
|
||||
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
|
||||
elems = append(elems, g.FromInt64(txInfo.PublicPoolIndex))
|
||||
elems = append(elems, g.FromInt64(txInfo.ShareAmount))
|
||||
|
||||
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package txtypes
|
||||
|
||||
import (
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
)
|
||||
|
||||
var _ TxInfo = (*L2CancelAllOrdersTxInfo)(nil)
|
||||
|
||||
type L2CancelAllOrdersTxInfo struct {
|
||||
AccountIndex int64
|
||||
ApiKeyIndex uint8
|
||||
|
||||
TimeInForce uint8
|
||||
Time int64
|
||||
|
||||
ExpiredAt int64
|
||||
Nonce int64
|
||||
Sig []byte
|
||||
SignedHash string `json:"-"`
|
||||
}
|
||||
|
||||
func (txInfo *L2CancelAllOrdersTxInfo) GetTxType() uint8 {
|
||||
return TxTypeL2CancelAllOrders
|
||||
}
|
||||
|
||||
func (txInfo *L2CancelAllOrdersTxInfo) GetTxInfo() (string, error) {
|
||||
return getTxInfo(txInfo)
|
||||
}
|
||||
|
||||
func (txInfo *L2CancelAllOrdersTxInfo) GetTxHash() string {
|
||||
return txInfo.SignedHash
|
||||
}
|
||||
|
||||
func (txInfo *L2CancelAllOrdersTxInfo) Validate() error {
|
||||
// AccountIndex
|
||||
if txInfo.AccountIndex < MinAccountIndex {
|
||||
return ErrAccountIndexTooLow
|
||||
}
|
||||
if txInfo.AccountIndex > MaxAccountIndex {
|
||||
return ErrAccountIndexTooHigh
|
||||
}
|
||||
|
||||
if txInfo.ApiKeyIndex < MinApiKeyIndex {
|
||||
return ErrApiKeyIndexTooLow
|
||||
}
|
||||
if txInfo.ApiKeyIndex > MaxApiKeyIndex && txInfo.ApiKeyIndex != NilApiKeyIndex {
|
||||
return ErrApiKeyIndexTooHigh
|
||||
}
|
||||
|
||||
// Nonce
|
||||
if txInfo.Nonce < MinNonce {
|
||||
return ErrNonceTooLow
|
||||
}
|
||||
|
||||
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
|
||||
return ErrExpiredAtInvalid
|
||||
}
|
||||
|
||||
// TimeInForce and Time
|
||||
switch txInfo.TimeInForce {
|
||||
case ImmediateCancelAll:
|
||||
if txInfo.Time != NilOrderExpiry {
|
||||
return ErrCancelAllTimeisNotNill
|
||||
}
|
||||
case ScheduledCancelAll:
|
||||
if txInfo.Time < MinOrderExpiry || txInfo.Time > MaxOrderExpiry {
|
||||
return ErrCancelAllTimeIsNotInRange
|
||||
}
|
||||
case AbortScheduledCancelAll:
|
||||
if txInfo.Time != 0 {
|
||||
return ErrCancelAllTimeisNotNill
|
||||
}
|
||||
default:
|
||||
return ErrInvalidCancelAllTimeInForce
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (txInfo *L2CancelAllOrdersTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
|
||||
elems := make([]g.Element, 0, 8)
|
||||
|
||||
elems = append(elems, g.FromUint32(lighterChainId))
|
||||
elems = append(elems, g.FromUint32(TxTypeL2CancelAllOrders))
|
||||
elems = append(elems, g.FromInt64(txInfo.Nonce))
|
||||
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
|
||||
|
||||
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.TimeInForce)))
|
||||
elems = append(elems, g.FromInt64(txInfo.Time))
|
||||
|
||||
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package txtypes
|
||||
|
||||
import (
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
)
|
||||
|
||||
var _ TxInfo = (*L2CancelOrderTxInfo)(nil)
|
||||
|
||||
type L2CancelOrderTxInfo struct {
|
||||
AccountIndex int64
|
||||
ApiKeyIndex uint8
|
||||
|
||||
MarketIndex int16
|
||||
Index int64 // Client Order Index or Order Index of the order to cancel
|
||||
|
||||
ExpiredAt int64
|
||||
Nonce int64
|
||||
Sig []byte
|
||||
SignedHash string `json:"-"`
|
||||
}
|
||||
|
||||
func (txInfo *L2CancelOrderTxInfo) GetTxType() uint8 {
|
||||
return TxTypeL2CancelOrder
|
||||
}
|
||||
|
||||
func (txInfo *L2CancelOrderTxInfo) GetTxInfo() (string, error) {
|
||||
return getTxInfo(txInfo)
|
||||
}
|
||||
|
||||
func (txInfo *L2CancelOrderTxInfo) GetTxHash() string {
|
||||
return txInfo.SignedHash
|
||||
}
|
||||
|
||||
func (txInfo *L2CancelOrderTxInfo) Validate() error {
|
||||
// AccountIndex
|
||||
if txInfo.AccountIndex < MinAccountIndex {
|
||||
return ErrAccountIndexTooLow
|
||||
}
|
||||
if txInfo.AccountIndex > MaxAccountIndex {
|
||||
return ErrAccountIndexTooHigh
|
||||
}
|
||||
|
||||
// ApiKeyIndex
|
||||
if txInfo.ApiKeyIndex < MinApiKeyIndex {
|
||||
return ErrApiKeyIndexTooLow
|
||||
}
|
||||
if txInfo.ApiKeyIndex > MaxApiKeyIndex {
|
||||
return ErrApiKeyIndexTooHigh
|
||||
}
|
||||
|
||||
// MarketIndex
|
||||
isSpotMarket := txInfo.MarketIndex >= MinSpotMarketIndex && txInfo.MarketIndex <= MaxSpotMarketIndex
|
||||
isPerpsMarket := txInfo.MarketIndex >= MinPerpsMarketIndex && txInfo.MarketIndex <= MaxPerpsMarketIndex
|
||||
if !isSpotMarket && !isPerpsMarket {
|
||||
return ErrInvalidMarketIndex
|
||||
}
|
||||
|
||||
// Index
|
||||
if txInfo.Index < MinClientOrderIndex && txInfo.Index < MinOrderIndex {
|
||||
return ErrOrderIndexTooLow
|
||||
}
|
||||
if txInfo.Index > MaxClientOrderIndex && txInfo.Index > MaxOrderIndex {
|
||||
return ErrOrderIndexTooHigh
|
||||
}
|
||||
|
||||
// Nonce
|
||||
if txInfo.Nonce < MinNonce {
|
||||
return ErrNonceTooLow
|
||||
}
|
||||
|
||||
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
|
||||
return ErrExpiredAtInvalid
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (txInfo *L2CancelOrderTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
|
||||
elems := make([]g.Element, 0, 7)
|
||||
|
||||
elems = append(elems, g.FromUint32(lighterChainId))
|
||||
elems = append(elems, g.FromUint32(TxTypeL2CancelOrder))
|
||||
elems = append(elems, g.FromInt64(txInfo.Nonce))
|
||||
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
|
||||
|
||||
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.MarketIndex)))
|
||||
elems = append(elems, g.FromInt64(txInfo.Index))
|
||||
|
||||
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package txtypes
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
)
|
||||
|
||||
var _ TxInfo = (*L2ChangePubKeyTxInfo)(nil)
|
||||
|
||||
type L2ChangePubKeyTxInfo struct {
|
||||
AccountIndex int64
|
||||
ApiKeyIndex uint8
|
||||
|
||||
PubKey []byte
|
||||
L1Sig string
|
||||
|
||||
ExpiredAt int64
|
||||
Nonce int64
|
||||
Sig []byte
|
||||
SignedHash string `json:"-"`
|
||||
}
|
||||
|
||||
func (txInfo *L2ChangePubKeyTxInfo) GetTxType() uint8 {
|
||||
return TxTypeL2ChangePubKey
|
||||
}
|
||||
|
||||
func (txInfo *L2ChangePubKeyTxInfo) GetTxInfo() (string, error) {
|
||||
return getTxInfo(txInfo)
|
||||
}
|
||||
|
||||
func (txInfo *L2ChangePubKeyTxInfo) GetTxHash() string {
|
||||
return txInfo.SignedHash
|
||||
}
|
||||
|
||||
func (txInfo *L2ChangePubKeyTxInfo) Validate() error {
|
||||
// AccountIndex
|
||||
if txInfo.AccountIndex < MinAccountIndex {
|
||||
return ErrFromAccountIndexTooLow
|
||||
}
|
||||
if txInfo.AccountIndex > MaxAccountIndex {
|
||||
return ErrFromAccountIndexTooHigh
|
||||
}
|
||||
|
||||
// ApiKeyIndex
|
||||
if txInfo.ApiKeyIndex < MinApiKeyIndex {
|
||||
return ErrApiKeyIndexTooLow
|
||||
}
|
||||
|
||||
if txInfo.ApiKeyIndex > MaxApiKeyIndex {
|
||||
return ErrApiKeyIndexTooHigh
|
||||
}
|
||||
|
||||
if txInfo.Nonce < MinNonce {
|
||||
return ErrNonceTooLow
|
||||
}
|
||||
|
||||
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
|
||||
return ErrExpiredAtInvalid
|
||||
}
|
||||
|
||||
if !IsValidPubKeyLength(txInfo.PubKey) {
|
||||
return ErrPubKeyInvalid
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (txInfo *L2ChangePubKeyTxInfo) GetL1SignatureBody() string {
|
||||
signatureBody := fmt.Sprintf(
|
||||
TemplateChangePubKey,
|
||||
common.Bytes2Hex(txInfo.PubKey),
|
||||
getHex10FromUint64(uint64(txInfo.Nonce)),
|
||||
getHex10FromUint64(uint64(txInfo.AccountIndex)),
|
||||
getHex10FromUint64(uint64(txInfo.ApiKeyIndex)),
|
||||
)
|
||||
return signatureBody
|
||||
}
|
||||
|
||||
func (txInfo *L2ChangePubKeyTxInfo) GetL1AddressBySignature() common.Address {
|
||||
return calculateL1AddressBySignature(txInfo.GetL1SignatureBody(), txInfo.L1Sig)
|
||||
}
|
||||
|
||||
func (txInfo *L2ChangePubKeyTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
|
||||
elems := make([]g.Element, 0, 11)
|
||||
|
||||
elems = append(elems, g.FromUint32(lighterChainId))
|
||||
elems = append(elems, g.FromUint32(TxTypeL2ChangePubKey))
|
||||
elems = append(elems, g.FromInt64(txInfo.Nonce))
|
||||
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
|
||||
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
|
||||
|
||||
pubKeyFieldElems, err := g.ArrayFromCanonicalLittleEndianBytes(txInfo.PubKey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to convert bytes to field element. bytes: %v, error: %w", txInfo.PubKey, err)
|
||||
}
|
||||
elems = append(elems, pubKeyFieldElems...)
|
||||
|
||||
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package txtypes
|
||||
|
||||
import (
|
||||
"math"
|
||||
|
||||
curve "github.com/elliottech/poseidon_crypto/curve/ecgfp5"
|
||||
schnorr "github.com/elliottech/poseidon_crypto/signature/schnorr"
|
||||
)
|
||||
|
||||
type (
|
||||
Signature = schnorr.Signature
|
||||
PrivateKey = curve.ECgFp5Scalar
|
||||
)
|
||||
|
||||
const (
|
||||
NilApiKeyIndex = MaxApiKeyIndex + 1
|
||||
)
|
||||
|
||||
const (
|
||||
TxTypeEmpty = 0
|
||||
TxTypeL1Deposit = 1
|
||||
TxTypeL1ChangePubKey = 2
|
||||
TxTypeL1CreateMarket = 3
|
||||
TxTypeL1UpdateMarket = 4
|
||||
TxTypeL1CancelAllOrders = 5
|
||||
TxTypeL1Withdraw = 6
|
||||
TxTypeL1CreateOrder = 7
|
||||
|
||||
TxTypeL2ChangePubKey = 8
|
||||
TxTypeL2CreateSubAccount = 9
|
||||
TxTypeL2CreatePublicPool = 10
|
||||
TxTypeL2UpdatePublicPool = 11
|
||||
TxTypeL2Transfer = 12
|
||||
TxTypeL2Withdraw = 13
|
||||
TxTypeL2CreateOrder = 14
|
||||
TxTypeL2CancelOrder = 15
|
||||
TxTypeL2CancelAllOrders = 16
|
||||
TxTypeL2ModifyOrder = 17
|
||||
TxTypeL2MintShares = 18
|
||||
TxTypeL2BurnShares = 19
|
||||
TxTypeL2UpdateLeverage = 20
|
||||
|
||||
TxTypeInternalClaimOrder = 21
|
||||
TxTypeInternalCancelOrder = 22
|
||||
TxTypeInternalDeleverage = 23
|
||||
TxTypeInternalExitPosition = 24
|
||||
TxTypeInternalCancelAllOrders = 25
|
||||
TxTypeInternalLiquidatePosition = 26
|
||||
TxTypeInternalCreateOrder = 27
|
||||
|
||||
TxTypeL2CreateGroupedOrders = 28
|
||||
TxTypeL2UpdateMargin = 29
|
||||
TxTypeL1BurnShares = 30
|
||||
)
|
||||
|
||||
// Order Type
|
||||
const (
|
||||
// User set order types
|
||||
LimitOrder = iota
|
||||
MarketOrder = 1
|
||||
StopLossOrder = 2
|
||||
StopLossLimitOrder = 3
|
||||
TakeProfitOrder = 4
|
||||
TakeProfitLimitOrder = 5
|
||||
TWAPOrder = 6
|
||||
|
||||
// Internal order types
|
||||
TWAPSubOrder = 7
|
||||
LiquidationOrder = 8
|
||||
|
||||
ApiMaxOrderType = TWAPOrder
|
||||
)
|
||||
|
||||
// Order Time-In-Force
|
||||
const (
|
||||
ImmediateOrCancel = iota
|
||||
GoodTillTime = 1
|
||||
PostOnly = 2
|
||||
)
|
||||
|
||||
// Grouping Type
|
||||
const (
|
||||
GroupingType = 0
|
||||
GroupingType_OneTriggersTheOther = 1
|
||||
GroupingType_OneCancelsTheOther = 2
|
||||
GroupingType_OneTriggersAOneCancelsTheOther = 3
|
||||
)
|
||||
|
||||
// Cancel All Orders Time-In-Force
|
||||
const (
|
||||
ImmediateCancelAll = iota
|
||||
ScheduledCancelAll = 1
|
||||
AbortScheduledCancelAll = 2
|
||||
)
|
||||
|
||||
// Asset Margin Mode
|
||||
const (
|
||||
AssetMarginMode_Disabled = 0
|
||||
AssetMarginMode_Enabled = 1
|
||||
AssetMarginMode_Max = AssetMarginMode_Enabled
|
||||
)
|
||||
|
||||
// Asset Route Type
|
||||
const (
|
||||
AssetRouteType_Perps = 0
|
||||
AssetRouteType_Spot = 1
|
||||
)
|
||||
|
||||
// Position Margin Mode
|
||||
const (
|
||||
CrossMargin = iota
|
||||
IsolatedMargin = 1
|
||||
)
|
||||
|
||||
// Margin Update Direction
|
||||
const (
|
||||
RemoveFromIsolatedMargin = iota
|
||||
AddToIsolatedMargin = 1
|
||||
)
|
||||
|
||||
const (
|
||||
OneUSDC = 1000000
|
||||
|
||||
FeeTick int64 = 1_000_000
|
||||
MarginFractionTick int64 = 10_000
|
||||
ShareTick uint16 = 10_000
|
||||
|
||||
MinAccountIndex int64 = 0
|
||||
MaxAccountIndex int64 = 281474976710654 // (1 << 48) - 2
|
||||
MaxMasterAccountIndex int64 = 140737488355327 // (1 << 47) - 1
|
||||
MinSubAccountIndex int64 = 140737488355328 // (1 << 47)
|
||||
MinApiKeyIndex uint8 = 0
|
||||
MaxApiKeyIndex uint8 = 254 // (1 << 8) - 2
|
||||
|
||||
MinMarketIndex int16 = 0
|
||||
MinPerpsMarketIndex int16 = 0
|
||||
MaxPerpsMarketIndex int16 = 254 // (1 << 8) - 2
|
||||
NilMarketIndex int16 = 255
|
||||
MinSpotMarketIndex int16 = 2048 // (1 << 11)
|
||||
MaxSpotMarketIndex int16 = 4094 // (1 << 12) - 2
|
||||
|
||||
NativeAssetIndex = uint16(1)
|
||||
USDCAssetIndex = uint16(3)
|
||||
MinAssetIndex = 1
|
||||
MaxAssetIndex = (1 << 6) - 2
|
||||
NilAssetIndex = 0
|
||||
|
||||
MaxInvestedPublicPoolCount int64 = 16
|
||||
InitialPoolShareValue int64 = 1_000 // 0.001 USDC
|
||||
MinInitialTotalShares int64 = 1_000 * (OneUSDC / InitialPoolShareValue) // 1,000 USDC worth of shares
|
||||
MaxInitialTotalShares int64 = 1_000_000_000 * (OneUSDC / InitialPoolShareValue) // 1,000,000,000 USDC worth of shares
|
||||
MaxPoolShares int64 = (1 << 60) - 1
|
||||
MaxBurntShareUSDCValue int64 = (1 << 60) - 1
|
||||
|
||||
MaxPoolEntryUSDC = (1 << 56) - 1 // 2^56 - 1 max USDC to invest in a pool
|
||||
MinPoolSharesToMintOrBurn int64 = 1
|
||||
MaxPoolSharesToMintOrBurn int64 = (1 << 60) - 1
|
||||
|
||||
MinNonce int64 = 0
|
||||
|
||||
MinOrderNonce int64 = 0
|
||||
MaxOrderNonce int64 = (1 << 48) - 1
|
||||
|
||||
NilClientOrderIndex int64 = 0
|
||||
NilOrderIndex int64 = 0
|
||||
|
||||
MinClientOrderIndex int64 = 1
|
||||
MaxClientOrderIndex int64 = (1 << 48) - 1
|
||||
|
||||
MinOrderIndex int64 = MaxClientOrderIndex + 1
|
||||
MaxOrderIndex int64 = (1 << 60) - 1
|
||||
|
||||
MinOrderBaseAmount int64 = 1
|
||||
MaxOrderBaseAmount int64 = (1 << 48) - 1
|
||||
NilOrderBaseAmount int64 = 0
|
||||
|
||||
NilOrderPrice uint32 = 0
|
||||
MinOrderPrice uint32 = 1
|
||||
MaxOrderPrice uint32 = (1 << 32) - 1
|
||||
|
||||
MinOrderCancelAllPeriod int64 = 1000 * 60 * 5 // 5 minutes
|
||||
MaxOrderCancelAllPeriod int64 = 1000 * 60 * 60 * 24 * 15 // 15 days
|
||||
|
||||
NilOrderExpiry int64 = 0
|
||||
MinOrderExpiry int64 = 1
|
||||
MaxOrderExpiry int64 = math.MaxInt64
|
||||
|
||||
MinOrderExpiryPeriod int64 = 1000 * 60 * 5 // 5 minutes
|
||||
MaxOrderExpiryPeriod int64 = 1000 * 60 * 60 * 24 * 30 // 30 days
|
||||
|
||||
NilOrderTriggerPrice uint32 = 0
|
||||
MinOrderTriggerPrice uint32 = 1
|
||||
MaxOrderTriggerPrice uint32 = (1 << 32) - 1
|
||||
|
||||
MaxGroupedOrderCount int64 = 3
|
||||
|
||||
MaxTimestamp = (1 << 48) - 1
|
||||
)
|
||||
|
||||
const (
|
||||
MaxExchangeUSDC = (1 << 60) - 1
|
||||
|
||||
MinTransferAmount int64 = 1
|
||||
MaxTransferAmount int64 = MaxExchangeUSDC
|
||||
|
||||
MinWithdrawalAmount uint64 = 1
|
||||
MaxWithdrawalAmount uint64 = MaxExchangeUSDC
|
||||
)
|
||||
@@ -0,0 +1,333 @@
|
||||
package txtypes
|
||||
|
||||
import (
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
)
|
||||
|
||||
var _ TxInfo = (*L2CreateGroupedOrdersTxInfo)(nil)
|
||||
|
||||
// !!! Ensure that if primary order is reduce only, all child orders are also reduce only
|
||||
// !!! Otherwise CancelPositionTiedAccountOrders flow breaks
|
||||
type L2CreateGroupedOrdersTxInfo struct {
|
||||
AccountIndex int64
|
||||
ApiKeyIndex uint8
|
||||
GroupingType uint8
|
||||
|
||||
Orders []*OrderInfo
|
||||
|
||||
ExpiredAt int64
|
||||
Nonce int64
|
||||
Sig []byte
|
||||
SignedHash string `json:"-"`
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateGroupedOrdersTxInfo) GetTxType() uint8 {
|
||||
return TxTypeL2CreateGroupedOrders
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateGroupedOrdersTxInfo) GetTxInfo() (string, error) {
|
||||
return getTxInfo(txInfo)
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateGroupedOrdersTxInfo) GetTxHash() string {
|
||||
return txInfo.SignedHash
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateGroupedOrdersTxInfo) Validate() error {
|
||||
// AccountIndex
|
||||
if txInfo.AccountIndex < MinAccountIndex {
|
||||
return ErrAccountIndexTooLow
|
||||
}
|
||||
if txInfo.AccountIndex > MaxAccountIndex {
|
||||
return ErrAccountIndexTooHigh
|
||||
}
|
||||
// ApiKeyIndex
|
||||
if txInfo.ApiKeyIndex < MinApiKeyIndex {
|
||||
return ErrApiKeyIndexTooLow
|
||||
}
|
||||
if txInfo.ApiKeyIndex > MaxApiKeyIndex {
|
||||
return ErrApiKeyIndexTooHigh
|
||||
}
|
||||
|
||||
if len(txInfo.Orders) == 0 || len(txInfo.Orders) > int(MaxGroupedOrderCount) {
|
||||
return ErrOrderGroupSizeInvalid
|
||||
}
|
||||
|
||||
// MarketIndex for first order
|
||||
if txInfo.Orders[0].MarketIndex < MinPerpsMarketIndex || txInfo.Orders[0].MarketIndex > MaxPerpsMarketIndex {
|
||||
return ErrInvalidMarketIndex
|
||||
}
|
||||
|
||||
// Perform range checks for all orders
|
||||
for _, order := range txInfo.Orders {
|
||||
// MarketIndex
|
||||
if order.MarketIndex != txInfo.Orders[0].MarketIndex {
|
||||
return ErrMarketIndexMismatch
|
||||
}
|
||||
|
||||
// ClientOrderIndex
|
||||
if order.ClientOrderIndex != NilClientOrderIndex {
|
||||
return ErrClientOrderIndexNotNil
|
||||
}
|
||||
|
||||
// BaseAmount
|
||||
if order.ReduceOnly != 1 && order.BaseAmount == NilOrderBaseAmount {
|
||||
return ErrBaseAmountTooLow
|
||||
}
|
||||
if order.BaseAmount != NilOrderBaseAmount && order.BaseAmount < MinOrderBaseAmount {
|
||||
return ErrBaseAmountTooLow
|
||||
}
|
||||
if order.BaseAmount > MaxOrderBaseAmount {
|
||||
return ErrBaseAmountTooHigh
|
||||
}
|
||||
|
||||
// Price
|
||||
if order.Price < MinOrderPrice {
|
||||
return ErrPriceTooLow
|
||||
}
|
||||
if order.Price > MaxOrderPrice {
|
||||
return ErrPriceTooHigh
|
||||
}
|
||||
|
||||
// IsAsk
|
||||
if order.IsAsk != 0 && order.IsAsk != 1 {
|
||||
return ErrIsAskInvalid
|
||||
}
|
||||
|
||||
// TimeInForce
|
||||
if order.TimeInForce != ImmediateOrCancel && order.TimeInForce != GoodTillTime && order.TimeInForce != PostOnly {
|
||||
return ErrOrderTimeInForceInvalid
|
||||
}
|
||||
|
||||
// ReduceOnly
|
||||
if order.ReduceOnly != 0 && order.ReduceOnly != 1 {
|
||||
return ErrOrderReduceOnlyInvalid
|
||||
}
|
||||
|
||||
// OrderExpiry
|
||||
if (order.OrderExpiry < MinOrderExpiry || order.OrderExpiry > MaxOrderExpiry) && order.OrderExpiry != NilOrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
}
|
||||
|
||||
// TriggerPrice
|
||||
if (order.TriggerPrice < MinOrderTriggerPrice || order.TriggerPrice > MaxOrderTriggerPrice) && order.TriggerPrice != NilOrderTriggerPrice {
|
||||
return ErrOrderTriggerPriceInvalid
|
||||
}
|
||||
}
|
||||
|
||||
// Nonce
|
||||
if txInfo.Nonce < MinNonce {
|
||||
return ErrNonceTooLow
|
||||
}
|
||||
|
||||
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
|
||||
return ErrExpiredAtInvalid
|
||||
}
|
||||
|
||||
switch txInfo.GroupingType {
|
||||
case GroupingType_OneCancelsTheOther:
|
||||
return txInfo.ValidateOCO()
|
||||
case GroupingType_OneTriggersTheOther:
|
||||
return txInfo.ValidateOTO()
|
||||
case GroupingType_OneTriggersAOneCancelsTheOther:
|
||||
return txInfo.ValidateOTOCO()
|
||||
default:
|
||||
return ErrGroupingTypeInvalid
|
||||
}
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateGroupedOrdersTxInfo) ValidateParentOrder(order *OrderInfo) error {
|
||||
switch order.Type {
|
||||
case MarketOrder:
|
||||
if order.TimeInForce != ImmediateOrCancel {
|
||||
return ErrOrderTimeInForceInvalid
|
||||
} else if order.OrderExpiry != NilOrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
} else if order.TriggerPrice != NilOrderTriggerPrice {
|
||||
return ErrOrderTriggerPriceInvalid
|
||||
}
|
||||
case LimitOrder:
|
||||
if order.TriggerPrice != NilOrderTriggerPrice {
|
||||
return ErrOrderTriggerPriceInvalid
|
||||
} else if order.TimeInForce == ImmediateOrCancel && order.OrderExpiry != NilOrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
} else if order.TimeInForce != ImmediateOrCancel && order.OrderExpiry == NilOrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
}
|
||||
default:
|
||||
return ErrOrderTypeInvalid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateGroupedOrdersTxInfo) ValidateChildOrder(order *OrderInfo) error {
|
||||
switch order.Type {
|
||||
case StopLossOrder, TakeProfitOrder:
|
||||
if order.TimeInForce != ImmediateOrCancel {
|
||||
return ErrOrderTimeInForceInvalid
|
||||
} else if order.TriggerPrice == NilOrderTriggerPrice {
|
||||
return ErrOrderTriggerPriceInvalid
|
||||
} else if order.OrderExpiry == NilOrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
}
|
||||
case StopLossLimitOrder, TakeProfitLimitOrder:
|
||||
if order.TriggerPrice == NilOrderTriggerPrice {
|
||||
return ErrOrderTriggerPriceInvalid
|
||||
} else if order.OrderExpiry == NilOrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
}
|
||||
default:
|
||||
return ErrOrderTypeInvalid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateGroupedOrdersTxInfo) ValidateSiblingOrders(orders []*OrderInfo) error {
|
||||
if len(orders) != 2 {
|
||||
return ErrOrderGroupSizeInvalid
|
||||
}
|
||||
slFlag := false
|
||||
tpFlag := false
|
||||
for _, order := range orders {
|
||||
err := txInfo.ValidateChildOrder(order)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if order.Type == StopLossOrder || order.Type == StopLossLimitOrder {
|
||||
slFlag = true
|
||||
} else if order.Type == TakeProfitOrder || order.Type == TakeProfitLimitOrder {
|
||||
tpFlag = true
|
||||
}
|
||||
}
|
||||
if !slFlag || !tpFlag {
|
||||
return ErrOrderTypeInvalid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateGroupedOrdersTxInfo) ValidateOCO() error {
|
||||
if len(txInfo.Orders) != 2 {
|
||||
return ErrOrderGroupSizeInvalid
|
||||
}
|
||||
|
||||
// Ensure both orders base sizes are same
|
||||
if txInfo.Orders[0].BaseAmount != txInfo.Orders[1].BaseAmount {
|
||||
return ErrBaseAmountsNotEqual
|
||||
}
|
||||
|
||||
// Orders should be in the same direction
|
||||
if txInfo.Orders[0].IsAsk != txInfo.Orders[1].IsAsk {
|
||||
return ErrIsAskInvalid
|
||||
}
|
||||
|
||||
// Ensure both orders are reduce only
|
||||
if txInfo.Orders[0].ReduceOnly != 1 || txInfo.Orders[1].ReduceOnly != 1 {
|
||||
return ErrOrderReduceOnlyInvalid
|
||||
}
|
||||
|
||||
// Ensure both orders have the same non-nil expiry
|
||||
if txInfo.Orders[0].OrderExpiry != txInfo.Orders[1].OrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
}
|
||||
|
||||
return txInfo.ValidateSiblingOrders(txInfo.Orders)
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateGroupedOrdersTxInfo) ValidateOTO() error {
|
||||
if len(txInfo.Orders) != 2 {
|
||||
return ErrOrderGroupSizeInvalid
|
||||
}
|
||||
|
||||
// Ensure child order base size is 0
|
||||
if txInfo.Orders[1].BaseAmount != NilOrderBaseAmount {
|
||||
return ErrBaseAmountNotNil
|
||||
}
|
||||
|
||||
// Orders should be in the opposite direction
|
||||
if txInfo.Orders[0].IsAsk == txInfo.Orders[1].IsAsk {
|
||||
return ErrIsAskInvalid
|
||||
}
|
||||
|
||||
// Ensure if expiries are not nil, they are the same
|
||||
if txInfo.Orders[0].OrderExpiry != NilOrderExpiry &&
|
||||
txInfo.Orders[0].OrderExpiry != txInfo.Orders[1].OrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
}
|
||||
|
||||
err := txInfo.ValidateParentOrder(txInfo.Orders[0])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return txInfo.ValidateChildOrder(txInfo.Orders[1])
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateGroupedOrdersTxInfo) ValidateOTOCO() error {
|
||||
if len(txInfo.Orders) != 3 {
|
||||
return ErrOrderGroupSizeInvalid
|
||||
}
|
||||
|
||||
// Ensure child orders base size is 0
|
||||
if txInfo.Orders[1].BaseAmount != NilOrderBaseAmount || txInfo.Orders[2].BaseAmount != NilOrderBaseAmount {
|
||||
return ErrBaseAmountNotNil
|
||||
}
|
||||
|
||||
// Primary and child orders should be in the oppsite direction
|
||||
if txInfo.Orders[0].IsAsk == txInfo.Orders[1].IsAsk || txInfo.Orders[0].IsAsk == txInfo.Orders[2].IsAsk {
|
||||
return ErrIsAskInvalid
|
||||
}
|
||||
|
||||
// Ensure child orders has the same expiry
|
||||
if txInfo.Orders[1].OrderExpiry != txInfo.Orders[2].OrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
}
|
||||
|
||||
// Ensure if expiries are not nil, they are the same
|
||||
if txInfo.Orders[0].OrderExpiry != NilOrderExpiry &&
|
||||
txInfo.Orders[0].OrderExpiry != txInfo.Orders[1].OrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
}
|
||||
|
||||
err := txInfo.ValidateParentOrder(txInfo.Orders[0])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return txInfo.ValidateSiblingOrders(txInfo.Orders[1:])
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateGroupedOrdersTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
|
||||
elems := make([]g.Element, 0, 11)
|
||||
elems = append(elems, g.FromUint32(lighterChainId))
|
||||
elems = append(elems, g.FromUint32(TxTypeL2CreateGroupedOrders))
|
||||
elems = append(elems, g.FromInt64(txInfo.Nonce))
|
||||
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
|
||||
|
||||
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.GroupingType)))
|
||||
|
||||
aggregatedOrderHash := p2.EmptyHashOut()
|
||||
for index, order := range txInfo.Orders {
|
||||
orderHash := p2.HashNoPad([]g.Element{
|
||||
g.FromUint32(uint32(order.MarketIndex)),
|
||||
g.FromInt64(order.ClientOrderIndex),
|
||||
g.FromInt64(order.BaseAmount),
|
||||
g.FromUint32(order.Price),
|
||||
g.FromUint32(uint32(order.IsAsk)),
|
||||
g.FromUint32(uint32(order.Type)),
|
||||
g.FromUint32(uint32(order.TimeInForce)),
|
||||
g.FromUint32(uint32(order.ReduceOnly)),
|
||||
g.FromUint32(order.TriggerPrice),
|
||||
g.FromInt64(order.OrderExpiry),
|
||||
})
|
||||
if index == 0 {
|
||||
aggregatedOrderHash = orderHash
|
||||
} else {
|
||||
aggregatedOrderHash = p2.HashNToOne([]p2.HashOut{aggregatedOrderHash, orderHash})
|
||||
}
|
||||
}
|
||||
elems = append(elems, aggregatedOrderHash[:]...)
|
||||
|
||||
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
package txtypes
|
||||
|
||||
import (
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
)
|
||||
|
||||
var _ TxInfo = (*L2CreateOrderTxInfo)(nil)
|
||||
|
||||
type L2CreateOrderTxInfo struct {
|
||||
AccountIndex int64
|
||||
ApiKeyIndex uint8
|
||||
|
||||
*OrderInfo
|
||||
|
||||
ExpiredAt int64
|
||||
Nonce int64
|
||||
Sig []byte
|
||||
SignedHash string `json:"-"`
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateOrderTxInfo) GetTxType() uint8 {
|
||||
return TxTypeL2CreateOrder
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateOrderTxInfo) GetTxInfo() (string, error) {
|
||||
return getTxInfo(txInfo)
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateOrderTxInfo) GetTxHash() string {
|
||||
return txInfo.SignedHash
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateOrderTxInfo) Validate() error {
|
||||
// AccountIndex
|
||||
if txInfo.AccountIndex < MinAccountIndex {
|
||||
return ErrAccountIndexTooLow
|
||||
}
|
||||
if txInfo.AccountIndex > MaxAccountIndex {
|
||||
return ErrAccountIndexTooHigh
|
||||
}
|
||||
// ApiKeyIndex
|
||||
if txInfo.ApiKeyIndex < MinApiKeyIndex {
|
||||
return ErrApiKeyIndexTooLow
|
||||
}
|
||||
if txInfo.ApiKeyIndex > MaxApiKeyIndex {
|
||||
return ErrApiKeyIndexTooHigh
|
||||
}
|
||||
|
||||
// MarketIndex
|
||||
isSpotMarket := txInfo.MarketIndex >= MinSpotMarketIndex && txInfo.MarketIndex <= MaxSpotMarketIndex
|
||||
isPerpsMarket := txInfo.MarketIndex >= MinPerpsMarketIndex && txInfo.MarketIndex <= MaxPerpsMarketIndex
|
||||
if !isSpotMarket && !isPerpsMarket {
|
||||
return ErrInvalidMarketIndex
|
||||
}
|
||||
|
||||
// ClientOrderIndex
|
||||
if txInfo.ClientOrderIndex != NilClientOrderIndex {
|
||||
if txInfo.ClientOrderIndex < MinClientOrderIndex {
|
||||
return ErrClientOrderIndexTooLow
|
||||
}
|
||||
if txInfo.ClientOrderIndex > MaxClientOrderIndex {
|
||||
return ErrClientOrderIndexTooHigh
|
||||
}
|
||||
}
|
||||
|
||||
// BaseAmount
|
||||
if txInfo.ReduceOnly != 1 && txInfo.BaseAmount == NilOrderBaseAmount {
|
||||
return ErrBaseAmountTooLow
|
||||
}
|
||||
if txInfo.BaseAmount != NilOrderBaseAmount && txInfo.BaseAmount < MinOrderBaseAmount {
|
||||
return ErrBaseAmountTooLow
|
||||
}
|
||||
if txInfo.BaseAmount > MaxOrderBaseAmount {
|
||||
return ErrBaseAmountTooHigh
|
||||
}
|
||||
|
||||
// Price
|
||||
if txInfo.Price < MinOrderPrice {
|
||||
return ErrPriceTooLow
|
||||
}
|
||||
if txInfo.Price > MaxOrderPrice {
|
||||
return ErrPriceTooHigh
|
||||
}
|
||||
|
||||
// IsAsk
|
||||
if txInfo.IsAsk != 0 && txInfo.IsAsk != 1 {
|
||||
return ErrIsAskInvalid
|
||||
}
|
||||
|
||||
// Type
|
||||
if txInfo.TimeInForce != ImmediateOrCancel && txInfo.TimeInForce != GoodTillTime && txInfo.TimeInForce != PostOnly {
|
||||
return ErrOrderTimeInForceInvalid
|
||||
}
|
||||
|
||||
// ReduceOnly
|
||||
if (txInfo.ReduceOnly != 0 && txInfo.ReduceOnly != 1) || (isSpotMarket && txInfo.ReduceOnly == 1) {
|
||||
return ErrOrderReduceOnlyInvalid
|
||||
}
|
||||
|
||||
// OrderExpiry
|
||||
if (txInfo.OrderExpiry < MinOrderExpiry || txInfo.OrderExpiry > MaxOrderExpiry) && txInfo.OrderExpiry != NilOrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
}
|
||||
|
||||
switch txInfo.Type {
|
||||
case MarketOrder:
|
||||
if txInfo.TimeInForce != ImmediateOrCancel {
|
||||
return ErrOrderTimeInForceInvalid
|
||||
} else if txInfo.OrderExpiry != NilOrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
} else if txInfo.TriggerPrice != NilOrderTriggerPrice {
|
||||
return ErrOrderTriggerPriceInvalid
|
||||
}
|
||||
case LimitOrder:
|
||||
if txInfo.TriggerPrice != NilOrderTriggerPrice {
|
||||
return ErrOrderTriggerPriceInvalid
|
||||
} else if txInfo.TimeInForce == ImmediateOrCancel && txInfo.OrderExpiry != NilOrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
} else if txInfo.TimeInForce != ImmediateOrCancel && txInfo.OrderExpiry == NilOrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
}
|
||||
case StopLossOrder, TakeProfitOrder:
|
||||
if !isPerpsMarket {
|
||||
return ErrOrderTypeInvalid
|
||||
} else if txInfo.TimeInForce != ImmediateOrCancel {
|
||||
return ErrOrderTimeInForceInvalid
|
||||
} else if txInfo.TriggerPrice == NilOrderTriggerPrice {
|
||||
return ErrOrderTriggerPriceInvalid
|
||||
} else if txInfo.OrderExpiry == NilOrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
}
|
||||
case StopLossLimitOrder, TakeProfitLimitOrder:
|
||||
if !isPerpsMarket {
|
||||
return ErrOrderTypeInvalid
|
||||
} else if txInfo.TriggerPrice == NilOrderTriggerPrice {
|
||||
return ErrOrderTriggerPriceInvalid
|
||||
} else if txInfo.OrderExpiry == NilOrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
}
|
||||
case TWAPOrder:
|
||||
if txInfo.TimeInForce != GoodTillTime {
|
||||
return ErrOrderTimeInForceInvalid
|
||||
} else if txInfo.TriggerPrice != NilOrderTriggerPrice {
|
||||
return ErrOrderTriggerPriceInvalid
|
||||
} else if txInfo.OrderExpiry == NilOrderExpiry {
|
||||
return ErrOrderExpiryInvalid
|
||||
}
|
||||
default:
|
||||
return ErrOrderTypeInvalid
|
||||
}
|
||||
|
||||
// TriggerPrice
|
||||
if (txInfo.TriggerPrice < MinOrderTriggerPrice || txInfo.TriggerPrice > MaxOrderTriggerPrice) && txInfo.TriggerPrice != NilOrderTriggerPrice {
|
||||
return ErrOrderTriggerPriceInvalid
|
||||
}
|
||||
|
||||
// Nonce
|
||||
if txInfo.Nonce < MinNonce {
|
||||
return ErrNonceTooLow
|
||||
}
|
||||
|
||||
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
|
||||
return ErrExpiredAtInvalid
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateOrderTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
|
||||
elems := make([]g.Element, 0, 16)
|
||||
|
||||
elems = append(elems, g.FromUint32(lighterChainId))
|
||||
elems = append(elems, g.FromUint32(TxTypeL2CreateOrder))
|
||||
elems = append(elems, g.FromInt64(txInfo.Nonce))
|
||||
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
|
||||
|
||||
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.MarketIndex)))
|
||||
elems = append(elems, g.FromInt64(txInfo.ClientOrderIndex))
|
||||
elems = append(elems, g.FromInt64(txInfo.BaseAmount))
|
||||
elems = append(elems, g.FromUint32(txInfo.Price))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.IsAsk)))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.Type)))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.TimeInForce)))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.ReduceOnly)))
|
||||
elems = append(elems, g.FromUint32(txInfo.TriggerPrice))
|
||||
elems = append(elems, g.FromInt64(txInfo.OrderExpiry))
|
||||
|
||||
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package txtypes
|
||||
|
||||
import (
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
)
|
||||
|
||||
var _ TxInfo = (*L2CreatePublicPoolTxInfo)(nil)
|
||||
|
||||
type L2CreatePublicPoolTxInfo struct {
|
||||
AccountIndex int64 // Master account index
|
||||
ApiKeyIndex uint8
|
||||
|
||||
OperatorFee int64
|
||||
InitialTotalShares int64
|
||||
MinOperatorShareRate uint16
|
||||
|
||||
ExpiredAt int64
|
||||
Nonce int64
|
||||
Sig []byte
|
||||
SignedHash string `json:"-"`
|
||||
}
|
||||
|
||||
func (txInfo *L2CreatePublicPoolTxInfo) GetTxType() uint8 {
|
||||
return TxTypeL2CreatePublicPool
|
||||
}
|
||||
|
||||
func (txInfo *L2CreatePublicPoolTxInfo) GetTxInfo() (string, error) {
|
||||
return getTxInfo(txInfo)
|
||||
}
|
||||
|
||||
func (txInfo *L2CreatePublicPoolTxInfo) GetTxHash() string {
|
||||
return txInfo.SignedHash
|
||||
}
|
||||
|
||||
func (txInfo *L2CreatePublicPoolTxInfo) Validate() error {
|
||||
// AccountIndex
|
||||
if txInfo.AccountIndex < MinAccountIndex {
|
||||
return ErrFromAccountIndexTooLow
|
||||
}
|
||||
if txInfo.AccountIndex > MaxMasterAccountIndex {
|
||||
return ErrFromAccountIndexTooHigh
|
||||
}
|
||||
|
||||
// ApiKeyIndex
|
||||
if txInfo.ApiKeyIndex < MinApiKeyIndex {
|
||||
return ErrApiKeyIndexTooLow
|
||||
}
|
||||
if txInfo.ApiKeyIndex > MaxApiKeyIndex {
|
||||
return ErrApiKeyIndexTooHigh
|
||||
}
|
||||
|
||||
// OperatorFee
|
||||
if txInfo.OperatorFee < 0 || txInfo.OperatorFee > FeeTick {
|
||||
return ErrInvalidPoolOperatorFee
|
||||
}
|
||||
|
||||
// InitialTotalShares
|
||||
if txInfo.InitialTotalShares <= 0 {
|
||||
return ErrPoolInitialTotalSharesTooLow
|
||||
}
|
||||
if txInfo.InitialTotalShares > MaxInitialTotalShares {
|
||||
return ErrPoolInitialTotalSharesTooHigh
|
||||
}
|
||||
|
||||
// MinOperatorShareRate
|
||||
if txInfo.MinOperatorShareRate > ShareTick {
|
||||
return ErrPoolMinOperatorShareRateTooHigh
|
||||
}
|
||||
|
||||
// Nonce
|
||||
if txInfo.Nonce < MinNonce {
|
||||
return ErrNonceTooLow
|
||||
}
|
||||
|
||||
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
|
||||
return ErrExpiredAtInvalid
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (txInfo *L2CreatePublicPoolTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
|
||||
elems := make([]g.Element, 0, 9)
|
||||
|
||||
elems = append(elems, g.FromUint32(lighterChainId))
|
||||
elems = append(elems, g.FromUint32(TxTypeL2CreatePublicPool))
|
||||
elems = append(elems, g.FromInt64(txInfo.Nonce))
|
||||
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
|
||||
|
||||
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
|
||||
elems = append(elems, g.FromInt64(txInfo.OperatorFee))
|
||||
elems = append(elems, g.FromInt64(txInfo.InitialTotalShares))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.MinOperatorShareRate)))
|
||||
|
||||
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package txtypes
|
||||
|
||||
import (
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
)
|
||||
|
||||
var _ TxInfo = (*L2CreateSubAccountTxInfo)(nil)
|
||||
|
||||
type L2CreateSubAccountTxInfo struct {
|
||||
AccountIndex int64 // Master account index
|
||||
ApiKeyIndex uint8
|
||||
|
||||
ExpiredAt int64
|
||||
Nonce int64
|
||||
Sig []byte
|
||||
SignedHash string `json:"-"`
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateSubAccountTxInfo) GetTxType() uint8 {
|
||||
return TxTypeL2CreateSubAccount
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateSubAccountTxInfo) GetTxInfo() (string, error) {
|
||||
return getTxInfo(txInfo)
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateSubAccountTxInfo) GetTxHash() string {
|
||||
return txInfo.SignedHash
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateSubAccountTxInfo) Validate() error {
|
||||
// AccountIndex
|
||||
if txInfo.AccountIndex < MinAccountIndex {
|
||||
return ErrFromAccountIndexTooLow
|
||||
}
|
||||
if txInfo.AccountIndex > MaxMasterAccountIndex {
|
||||
return ErrFromAccountIndexTooHigh
|
||||
}
|
||||
|
||||
// ApiKeyIndex
|
||||
if txInfo.ApiKeyIndex < MinApiKeyIndex {
|
||||
return ErrApiKeyIndexTooLow
|
||||
}
|
||||
if txInfo.ApiKeyIndex > MaxApiKeyIndex {
|
||||
return ErrApiKeyIndexTooHigh
|
||||
}
|
||||
|
||||
// Nonce
|
||||
if txInfo.Nonce < MinNonce {
|
||||
return ErrNonceTooLow
|
||||
}
|
||||
|
||||
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
|
||||
return ErrExpiredAtInvalid
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (txInfo *L2CreateSubAccountTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
|
||||
elems := make([]g.Element, 0, 6)
|
||||
|
||||
elems = append(elems, g.FromUint32(lighterChainId))
|
||||
elems = append(elems, g.FromUint32(TxTypeL2CreateSubAccount))
|
||||
elems = append(elems, g.FromInt64(txInfo.Nonce))
|
||||
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
|
||||
|
||||
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
|
||||
|
||||
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package txtypes
|
||||
|
||||
import "fmt"
|
||||
|
||||
var (
|
||||
ErrAssetIndexTooLow = fmt.Errorf("AssetIndex should not be less than %d", MinAssetIndex)
|
||||
ErrAssetIndexTooHigh = fmt.Errorf("AssetIndex should not be larger than %d", MaxAssetIndex)
|
||||
ErrRouteTypeInvalid = fmt.Errorf("RouteType is invalid")
|
||||
ErrAccountIndexTooLow = fmt.Errorf("AccountIndex should not be less than %d", MinAccountIndex)
|
||||
ErrAccountIndexTooHigh = fmt.Errorf("AccountIndex should not be larger than %d", MaxAccountIndex)
|
||||
ErrNonceTooLow = fmt.Errorf("AccountNonce should not be less than %d", MinNonce)
|
||||
ErrInvalidCancelAllTimeInForce = fmt.Errorf("CancelAllTimeInForce is invalid")
|
||||
ErrOrderReduceOnlyInvalid = fmt.Errorf("ReduceOnly is invalid")
|
||||
ErrOrderTriggerPriceInvalid = fmt.Errorf("TriggerPrice is invalid")
|
||||
ErrOrderExpiryInvalid = fmt.Errorf("OrderExpiry is invalid")
|
||||
ErrExpiredAtInvalid = fmt.Errorf("ExpiredAt is invalid")
|
||||
ErrCancelAllTimeIsNotInRange = fmt.Errorf("CancelAllTime should be larger than 0 and not larger than %d", MaxOrderExpiry)
|
||||
ErrCancelAllTimeisNotNill = fmt.Errorf("CancelAllTime should be nil")
|
||||
ErrPubKeyInvalid = fmt.Errorf("PubKey is invalid")
|
||||
ErrToAccountIndexTooLow = fmt.Errorf("ToAccountIndex should not be less than %d", MinAccountIndex)
|
||||
ErrToAccountIndexTooHigh = fmt.Errorf("ToAccountIndex should not be larger than %d", MaxAccountIndex)
|
||||
ErrFromAccountIndexTooLow = fmt.Errorf("FromAccountIndex should not be less than %d", MinAccountIndex)
|
||||
ErrFromAccountIndexTooHigh = fmt.Errorf("FromAccountIndex should not be larger than %d", MaxAccountIndex)
|
||||
ErrApiKeyIndexTooLow = fmt.Errorf("ApiKeyIndex should not be less than %d", MinApiKeyIndex)
|
||||
ErrApiKeyIndexTooHigh = fmt.Errorf("ApiKeyIndex should not be larger than %d", MaxApiKeyIndex)
|
||||
ErrPublicPoolIndexTooLow = fmt.Errorf("PublicPoolIndex should not be less than %d", MinAccountIndex)
|
||||
ErrPublicPoolIndexTooHigh = fmt.Errorf("PublicPoolIndex should not be larger than %d", MaxAccountIndex)
|
||||
ErrInvalidPoolOperatorFee = fmt.Errorf("PoolOperatorFee should be larger than 0 and not larger than %d", FeeTick)
|
||||
ErrInvalidPoolStatus = fmt.Errorf("PoolStatus should be either 0 or 1")
|
||||
ErrPoolInitialTotalSharesTooLow = fmt.Errorf("PoolInitialTotalShares should be larger than %d", MinInitialTotalShares)
|
||||
ErrPoolInitialTotalSharesTooHigh = fmt.Errorf("PoolInitialTotalShares should not be larger than %d", MaxInitialTotalShares)
|
||||
ErrPoolMinOperatorShareRateTooLow = fmt.Errorf("PoolMinOperatorShareRate should be larger than 0")
|
||||
ErrPoolMinOperatorShareRateTooHigh = fmt.Errorf("PoolMinOperatorShareRate should not be larger than %d", ShareTick)
|
||||
ErrPoolMintShareAmountTooLow = fmt.Errorf("PoolMintShareAmount should be larger than %d", MinPoolSharesToMintOrBurn)
|
||||
ErrPoolMintShareAmountTooHigh = fmt.Errorf("PoolMintShareAmount should not be larger than %d", MaxPoolSharesToMintOrBurn)
|
||||
ErrPoolBurnShareAmountTooLow = fmt.Errorf("PoolBurnShareAmount should be larger than %d", MinPoolSharesToMintOrBurn)
|
||||
ErrPoolBurnShareAmountTooHigh = fmt.Errorf("PoolBurnShareAmount should not be larger than %d", MaxPoolSharesToMintOrBurn)
|
||||
ErrWithdrawalAmountTooLow = fmt.Errorf("WithdrawalAmount should be larger than %d", MinWithdrawalAmount)
|
||||
ErrWithdrawalAmountTooHigh = fmt.Errorf("WithdrawalAmount should not be larger than %d", MaxWithdrawalAmount)
|
||||
ErrTransferAmountTooLow = fmt.Errorf("TransferAmount should be larger than %d", MinTransferAmount)
|
||||
ErrTransferAmountTooHigh = fmt.Errorf("TransferAmount should not be larger than %d", MaxTransferAmount)
|
||||
ErrTransferFeeNegative = fmt.Errorf("TransferFee should not be negative")
|
||||
ErrTransferFeeTooHigh = fmt.Errorf("TransferFee should not be larger than %d", MaxTransferAmount)
|
||||
ErrMarketIndexTooLow = fmt.Errorf("MarketIndex should not be less than %d", MinMarketIndex)
|
||||
ErrMarketIndexTooHigh = fmt.Errorf("MarketIndex should not be larger than %d", MaxSpotMarketIndex)
|
||||
ErrMarketIndexMismatch = fmt.Errorf("MarketIndex should match the market index of the order")
|
||||
ErrInvalidMarketIndex = fmt.Errorf("MarketIndex is not valid")
|
||||
ErrInitialMarginFractionTooLow = fmt.Errorf("InitialMarginFraction should not be less than %d", 0)
|
||||
ErrInitialMarginFractionTooHigh = fmt.Errorf("InitialMarginFraction should not be larger than %d", MarginFractionTick)
|
||||
ErrClientOrderIndexTooLow = fmt.Errorf("ClientOrderIndex should not be less than %d", MinClientOrderIndex)
|
||||
ErrClientOrderIndexTooHigh = fmt.Errorf("ClientOrderIndex should not be larger than %d", MaxClientOrderIndex)
|
||||
ErrClientOrderIndexNotNil = fmt.Errorf("ClientOrderIndex should be nil")
|
||||
ErrOrderIndexTooLow = fmt.Errorf("OrderIndex should not be less than %d", MinOrderIndex)
|
||||
ErrOrderIndexTooHigh = fmt.Errorf("OrderIndex should not be larger than %d", MaxOrderIndex)
|
||||
ErrBaseAmountTooLow = fmt.Errorf("BaseAmount should not be less than %d", MinOrderBaseAmount)
|
||||
ErrBaseAmountTooHigh = fmt.Errorf("BaseAmount should not be larger than %d", MaxOrderBaseAmount)
|
||||
ErrBaseAmountsNotEqual = fmt.Errorf("BaseAmounts should be equal")
|
||||
ErrBaseAmountNotNil = fmt.Errorf("BaseAmount should be nil")
|
||||
ErrPriceTooLow = fmt.Errorf("OrderPrice should not be less than %d", MinOrderPrice)
|
||||
ErrPriceTooHigh = fmt.Errorf("OrderPrice should not be larger than %d", MaxOrderPrice)
|
||||
ErrIsAskInvalid = fmt.Errorf("IsAsk should be 0 or 1")
|
||||
ErrOrderTypeInvalid = fmt.Errorf("OrderType is not valid")
|
||||
ErrOrderTimeInForceInvalid = fmt.Errorf("OrderTimeInForce is not valid")
|
||||
ErrGroupingTypeInvalid = fmt.Errorf("GroupingType is not valid")
|
||||
ErrOrderGroupSizeInvalid = fmt.Errorf("OrderGroupSize is not valid")
|
||||
ErrInvalidSignature = fmt.Errorf("TxSignature is invalid")
|
||||
ErrInvalidMarginMode = fmt.Errorf("MarginMode is not valid")
|
||||
ErrCancelModeInvalid = fmt.Errorf("CancelMode is not valid")
|
||||
ErrInvalidUpdateMarginDirection = fmt.Errorf("Margin movement direction is not valid")
|
||||
)
|
||||
@@ -0,0 +1,37 @@
|
||||
package txtypes
|
||||
|
||||
import g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
|
||||
type TxInfo interface {
|
||||
GetTxType() uint8
|
||||
|
||||
GetTxInfo() (string, error)
|
||||
|
||||
// GetTxHash returns the hash that was signed when creating this transaction.
|
||||
// The hash coincides with the TxHash received from Lighter after submitting this Tx.
|
||||
// It can be used to get the TxHash in advance, or to double-check the correctness of the SDK.
|
||||
// As this hash is signed by the ApiKey, if the value differs than the one computed by the server,
|
||||
// it'll result in an invalid signature.
|
||||
// Returns empty string if the Tx is not signed.
|
||||
GetTxHash() string
|
||||
|
||||
Validate() error
|
||||
|
||||
Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error)
|
||||
}
|
||||
|
||||
type OrderInfo struct {
|
||||
MarketIndex int16
|
||||
|
||||
ClientOrderIndex int64
|
||||
|
||||
BaseAmount int64
|
||||
Price uint32
|
||||
IsAsk uint8
|
||||
|
||||
Type uint8
|
||||
TimeInForce uint8
|
||||
ReduceOnly uint8
|
||||
TriggerPrice uint32
|
||||
OrderExpiry int64
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package txtypes
|
||||
|
||||
import (
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
)
|
||||
|
||||
var _ TxInfo = (*L2MintSharesTxInfo)(nil)
|
||||
|
||||
type L2MintSharesTxInfo struct {
|
||||
AccountIndex int64
|
||||
ApiKeyIndex uint8
|
||||
|
||||
PublicPoolIndex int64
|
||||
ShareAmount int64
|
||||
|
||||
ExpiredAt int64
|
||||
Nonce int64
|
||||
Sig []byte
|
||||
SignedHash string `json:"-"`
|
||||
}
|
||||
|
||||
func (txInfo *L2MintSharesTxInfo) GetTxType() uint8 {
|
||||
return TxTypeL2MintShares
|
||||
}
|
||||
|
||||
func (txInfo *L2MintSharesTxInfo) GetTxInfo() (string, error) {
|
||||
return getTxInfo(txInfo)
|
||||
}
|
||||
|
||||
func (txInfo *L2MintSharesTxInfo) GetTxHash() string {
|
||||
return txInfo.SignedHash
|
||||
}
|
||||
|
||||
func (txInfo *L2MintSharesTxInfo) Validate() error {
|
||||
if txInfo.AccountIndex < MinAccountIndex {
|
||||
return ErrFromAccountIndexTooLow
|
||||
}
|
||||
if txInfo.AccountIndex > MaxAccountIndex {
|
||||
return ErrFromAccountIndexTooHigh
|
||||
}
|
||||
|
||||
// ApiKeyIndex
|
||||
if txInfo.ApiKeyIndex < MinApiKeyIndex {
|
||||
return ErrApiKeyIndexTooLow
|
||||
}
|
||||
if txInfo.ApiKeyIndex > MaxApiKeyIndex {
|
||||
return ErrApiKeyIndexTooHigh
|
||||
}
|
||||
|
||||
// PublicPoolIndex
|
||||
if txInfo.PublicPoolIndex < MinSubAccountIndex {
|
||||
return ErrPublicPoolIndexTooLow
|
||||
}
|
||||
if txInfo.PublicPoolIndex > MaxAccountIndex {
|
||||
return ErrPublicPoolIndexTooHigh
|
||||
}
|
||||
|
||||
if txInfo.ShareAmount < MinPoolSharesToMintOrBurn {
|
||||
return ErrPoolMintShareAmountTooLow
|
||||
}
|
||||
if txInfo.ShareAmount > MaxPoolSharesToMintOrBurn {
|
||||
return ErrPoolMintShareAmountTooHigh
|
||||
}
|
||||
|
||||
if txInfo.Nonce < MinNonce {
|
||||
return ErrNonceTooLow
|
||||
}
|
||||
|
||||
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
|
||||
return ErrExpiredAtInvalid
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (txInfo *L2MintSharesTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
|
||||
elems := make([]g.Element, 0, 8)
|
||||
|
||||
elems = append(elems, g.FromUint32(lighterChainId))
|
||||
elems = append(elems, g.FromUint32(TxTypeL2MintShares))
|
||||
elems = append(elems, g.FromInt64(txInfo.Nonce))
|
||||
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
|
||||
|
||||
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
|
||||
elems = append(elems, g.FromInt64(txInfo.PublicPoolIndex))
|
||||
elems = append(elems, g.FromInt64(txInfo.ShareAmount))
|
||||
|
||||
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package txtypes
|
||||
|
||||
import (
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
)
|
||||
|
||||
var _ TxInfo = (*L2ModifyOrderTxInfo)(nil)
|
||||
|
||||
type L2ModifyOrderTxInfo struct {
|
||||
AccountIndex int64
|
||||
ApiKeyIndex uint8
|
||||
|
||||
MarketIndex int16
|
||||
Index int64 // Client Order Index or Order Index of the order to modify
|
||||
BaseAmount int64
|
||||
Price uint32
|
||||
TriggerPrice uint32
|
||||
|
||||
ExpiredAt int64
|
||||
Nonce int64
|
||||
Sig []byte
|
||||
SignedHash string `json:"-"`
|
||||
}
|
||||
|
||||
func (txInfo *L2ModifyOrderTxInfo) GetTxType() uint8 {
|
||||
return TxTypeL2ModifyOrder
|
||||
}
|
||||
|
||||
func (txInfo *L2ModifyOrderTxInfo) GetTxInfo() (string, error) {
|
||||
return getTxInfo(txInfo)
|
||||
}
|
||||
|
||||
func (txInfo *L2ModifyOrderTxInfo) GetTxHash() string {
|
||||
return txInfo.SignedHash
|
||||
}
|
||||
|
||||
func (txInfo *L2ModifyOrderTxInfo) Validate() error {
|
||||
// AccountIndex
|
||||
if txInfo.AccountIndex < MinAccountIndex {
|
||||
return ErrAccountIndexTooLow
|
||||
}
|
||||
if txInfo.AccountIndex > MaxAccountIndex {
|
||||
return ErrAccountIndexTooHigh
|
||||
}
|
||||
// ApiKeyIndex
|
||||
if txInfo.ApiKeyIndex < MinApiKeyIndex {
|
||||
return ErrApiKeyIndexTooLow
|
||||
}
|
||||
if txInfo.ApiKeyIndex > MaxApiKeyIndex {
|
||||
return ErrApiKeyIndexTooHigh
|
||||
}
|
||||
|
||||
// MarketIndex
|
||||
isSpotMarket := txInfo.MarketIndex >= MinSpotMarketIndex && txInfo.MarketIndex <= MaxSpotMarketIndex
|
||||
isPerpsMarket := txInfo.MarketIndex >= MinPerpsMarketIndex && txInfo.MarketIndex <= MaxPerpsMarketIndex
|
||||
if !isSpotMarket && !isPerpsMarket {
|
||||
return ErrInvalidMarketIndex
|
||||
}
|
||||
|
||||
// Index
|
||||
if txInfo.Index < MinClientOrderIndex && txInfo.Index < MinOrderIndex {
|
||||
return ErrClientOrderIndexTooLow
|
||||
}
|
||||
if txInfo.Index > MaxClientOrderIndex && txInfo.Index > MaxOrderIndex {
|
||||
return ErrClientOrderIndexTooHigh
|
||||
}
|
||||
|
||||
// BaseAmount
|
||||
if txInfo.BaseAmount != NilOrderBaseAmount && txInfo.BaseAmount < MinOrderBaseAmount {
|
||||
return ErrBaseAmountTooLow
|
||||
}
|
||||
if txInfo.BaseAmount > MaxOrderBaseAmount {
|
||||
return ErrBaseAmountTooHigh
|
||||
}
|
||||
|
||||
// Price
|
||||
if txInfo.Price < MinOrderPrice {
|
||||
return ErrPriceTooLow
|
||||
}
|
||||
if txInfo.Price > MaxOrderPrice {
|
||||
return ErrPriceTooHigh
|
||||
}
|
||||
|
||||
// TriggerPrice
|
||||
if (txInfo.TriggerPrice < MinOrderTriggerPrice || txInfo.TriggerPrice > MaxOrderTriggerPrice) && txInfo.TriggerPrice != NilOrderTriggerPrice {
|
||||
return ErrOrderTriggerPriceInvalid
|
||||
}
|
||||
|
||||
// Nonce
|
||||
if txInfo.Nonce < MinNonce {
|
||||
return ErrNonceTooLow
|
||||
}
|
||||
|
||||
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
|
||||
return ErrExpiredAtInvalid
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (txInfo *L2ModifyOrderTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
|
||||
elems := make([]g.Element, 0, 11)
|
||||
|
||||
elems = append(elems, g.FromUint32(lighterChainId))
|
||||
elems = append(elems, g.FromUint32(TxTypeL2ModifyOrder))
|
||||
elems = append(elems, g.FromInt64(txInfo.Nonce))
|
||||
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
|
||||
|
||||
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.MarketIndex)))
|
||||
elems = append(elems, g.FromInt64(txInfo.Index))
|
||||
elems = append(elems, g.FromInt64(txInfo.BaseAmount))
|
||||
elems = append(elems, g.FromUint32(txInfo.Price))
|
||||
elems = append(elems, g.FromUint32(txInfo.TriggerPrice))
|
||||
|
||||
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package txtypes
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
)
|
||||
|
||||
var _ TxInfo = (*L2TransferTxInfo)(nil)
|
||||
|
||||
type L2TransferTxInfo struct {
|
||||
FromAccountIndex int64
|
||||
ApiKeyIndex uint8
|
||||
ToAccountIndex int64
|
||||
AssetIndex int16
|
||||
FromRouteType uint8
|
||||
ToRouteType uint8
|
||||
Amount int64
|
||||
USDCFee int64
|
||||
|
||||
Memo [32]byte
|
||||
ExpiredAt int64
|
||||
Nonce int64
|
||||
Sig []byte
|
||||
L1Sig string
|
||||
SignedHash string `json:"-"`
|
||||
}
|
||||
|
||||
func (txInfo *L2TransferTxInfo) Validate() error {
|
||||
// FromAccountIndex
|
||||
if txInfo.FromAccountIndex < MinAccountIndex+1 {
|
||||
return ErrFromAccountIndexTooLow
|
||||
}
|
||||
if txInfo.FromAccountIndex > MaxAccountIndex {
|
||||
return ErrFromAccountIndexTooHigh
|
||||
}
|
||||
|
||||
// ApiKeyIndex
|
||||
if txInfo.ApiKeyIndex < MinApiKeyIndex {
|
||||
return ErrApiKeyIndexTooLow
|
||||
}
|
||||
if txInfo.ApiKeyIndex > MaxApiKeyIndex {
|
||||
return ErrApiKeyIndexTooHigh
|
||||
}
|
||||
|
||||
// ToAccountIndex
|
||||
if txInfo.ToAccountIndex < MinAccountIndex {
|
||||
return ErrToAccountIndexTooLow
|
||||
}
|
||||
if txInfo.ToAccountIndex > MaxAccountIndex {
|
||||
return ErrToAccountIndexTooHigh
|
||||
}
|
||||
|
||||
// AssetIndex
|
||||
if txInfo.AssetIndex < MinAssetIndex {
|
||||
return ErrAssetIndexTooLow
|
||||
}
|
||||
if txInfo.AssetIndex > MaxAssetIndex {
|
||||
return ErrAssetIndexTooHigh
|
||||
}
|
||||
|
||||
// FromRouteType
|
||||
if txInfo.FromRouteType != AssetRouteType_Perps && txInfo.FromRouteType != AssetRouteType_Spot {
|
||||
return ErrRouteTypeInvalid
|
||||
}
|
||||
|
||||
// ToRouteType
|
||||
if txInfo.ToRouteType != AssetRouteType_Perps && txInfo.ToRouteType != AssetRouteType_Spot {
|
||||
return ErrRouteTypeInvalid
|
||||
}
|
||||
|
||||
if txInfo.Amount <= 0 {
|
||||
return ErrTransferAmountTooLow
|
||||
}
|
||||
if txInfo.Amount > MaxTransferAmount {
|
||||
return ErrTransferAmountTooHigh
|
||||
}
|
||||
|
||||
if txInfo.USDCFee < 0 {
|
||||
return ErrTransferFeeNegative
|
||||
}
|
||||
if txInfo.USDCFee > MaxTransferAmount {
|
||||
return ErrTransferFeeTooHigh
|
||||
}
|
||||
|
||||
if txInfo.Nonce < MinNonce {
|
||||
return ErrNonceTooLow
|
||||
}
|
||||
|
||||
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
|
||||
return ErrExpiredAtInvalid
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (txInfo *L2TransferTxInfo) GetTxType() uint8 {
|
||||
return TxTypeL2Transfer
|
||||
}
|
||||
|
||||
func (txInfo *L2TransferTxInfo) GetTxHash() string {
|
||||
return txInfo.SignedHash
|
||||
}
|
||||
|
||||
func (txInfo *L2TransferTxInfo) GetTxInfo() (string, error) {
|
||||
return getTxInfo(txInfo)
|
||||
}
|
||||
|
||||
func (txInfo *L2TransferTxInfo) GetL1SignatureBody(chainId uint32) string {
|
||||
hexMemo := hex.EncodeToString(txInfo.Memo[:])
|
||||
hexMemo = strings.Replace(hexMemo, "0x", "", 1)
|
||||
|
||||
signatureBody := fmt.Sprintf(
|
||||
TemplateTransfer,
|
||||
getHex10FromUint64(uint64(txInfo.Nonce)),
|
||||
getHex10FromUint64(uint64(txInfo.FromAccountIndex)),
|
||||
getHex10FromUint64(uint64(txInfo.FromRouteType)),
|
||||
getHex10FromUint64(uint64(txInfo.ApiKeyIndex)),
|
||||
getHex10FromUint64(uint64(txInfo.ToAccountIndex)),
|
||||
getHex10FromUint64(uint64(txInfo.ToRouteType)),
|
||||
getHex10FromUint64(uint64(txInfo.AssetIndex)),
|
||||
getHex10FromUint64(uint64(txInfo.Amount)), //nolint:gosec
|
||||
getHex10FromUint64(uint64(txInfo.USDCFee)), //nolint:gosec
|
||||
getHex10FromUint64(uint64(chainId)), //nolint:gosec
|
||||
hexMemo,
|
||||
)
|
||||
return signatureBody
|
||||
}
|
||||
|
||||
func (txInfo *L2TransferTxInfo) GetL1AddressBySignature(chainId uint32) common.Address {
|
||||
return calculateL1AddressBySignature(txInfo.GetL1SignatureBody(chainId), txInfo.L1Sig)
|
||||
}
|
||||
|
||||
func (txInfo *L2TransferTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
|
||||
elems := make([]g.Element, 0, 14)
|
||||
|
||||
elems = append(elems, g.FromUint32(lighterChainId))
|
||||
elems = append(elems, g.FromUint32(TxTypeL2Transfer))
|
||||
elems = append(elems, g.FromInt64(txInfo.Nonce))
|
||||
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
|
||||
|
||||
elems = append(elems, g.FromInt64(txInfo.FromAccountIndex))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
|
||||
elems = append(elems, g.FromInt64(txInfo.ToAccountIndex))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.AssetIndex)))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.FromRouteType)))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.ToRouteType)))
|
||||
elems = append(elems, g.FromUint64((uint64(txInfo.Amount))&0xFFFFFFFF)) //nolint:gosec
|
||||
elems = append(elems, g.FromUint64(uint64(txInfo.Amount)>>32)) //nolint:gosec
|
||||
elems = append(elems, g.FromUint64((uint64(txInfo.USDCFee))&0xFFFFFFFF)) //nolint:gosec
|
||||
elems = append(elems, g.FromUint64((uint64(txInfo.USDCFee))>>32)) //nolint:gosec
|
||||
|
||||
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package txtypes
|
||||
|
||||
import (
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
)
|
||||
|
||||
var _ TxInfo = (*L2UpdateLeverageTxInfo)(nil)
|
||||
|
||||
type L2UpdateLeverageTxInfo struct {
|
||||
AccountIndex int64
|
||||
ApiKeyIndex uint8
|
||||
|
||||
MarketIndex int16
|
||||
InitialMarginFraction uint16
|
||||
MarginMode uint8
|
||||
|
||||
ExpiredAt int64
|
||||
Nonce int64
|
||||
Sig []byte
|
||||
SignedHash string `json:"-"`
|
||||
}
|
||||
|
||||
func (txInfo *L2UpdateLeverageTxInfo) GetTxType() uint8 {
|
||||
return TxTypeL2UpdateLeverage
|
||||
}
|
||||
|
||||
func (txInfo *L2UpdateLeverageTxInfo) GetTxInfo() (string, error) {
|
||||
return getTxInfo(txInfo)
|
||||
}
|
||||
|
||||
func (txInfo *L2UpdateLeverageTxInfo) GetTxHash() string {
|
||||
return txInfo.SignedHash
|
||||
}
|
||||
|
||||
func (txInfo *L2UpdateLeverageTxInfo) Validate() error {
|
||||
if txInfo.AccountIndex < MinAccountIndex {
|
||||
return ErrFromAccountIndexTooLow
|
||||
}
|
||||
if txInfo.AccountIndex > MaxAccountIndex {
|
||||
return ErrFromAccountIndexTooHigh
|
||||
}
|
||||
|
||||
// ApiKeyIndex
|
||||
if txInfo.ApiKeyIndex < MinApiKeyIndex {
|
||||
return ErrApiKeyIndexTooLow
|
||||
}
|
||||
if txInfo.ApiKeyIndex > MaxApiKeyIndex {
|
||||
return ErrApiKeyIndexTooHigh
|
||||
}
|
||||
// MarketIndex
|
||||
if txInfo.MarketIndex == NilMarketIndex {
|
||||
return ErrInvalidMarketIndex
|
||||
}
|
||||
|
||||
if txInfo.MarginMode != CrossMargin && txInfo.MarginMode != IsolatedMargin {
|
||||
return ErrInvalidMarginMode
|
||||
}
|
||||
|
||||
// InitialMarginFraction
|
||||
if txInfo.InitialMarginFraction <= 0 {
|
||||
return ErrInitialMarginFractionTooLow
|
||||
}
|
||||
if txInfo.InitialMarginFraction > uint16(MarginFractionTick) { //nolint:gosec
|
||||
return ErrInitialMarginFractionTooHigh
|
||||
}
|
||||
|
||||
if txInfo.Nonce < MinNonce {
|
||||
return ErrNonceTooLow
|
||||
}
|
||||
|
||||
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
|
||||
return ErrExpiredAtInvalid
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (txInfo *L2UpdateLeverageTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
|
||||
elems := make([]g.Element, 0, 9)
|
||||
|
||||
elems = append(elems, g.FromUint32(lighterChainId))
|
||||
elems = append(elems, g.FromUint32(TxTypeL2UpdateLeverage))
|
||||
elems = append(elems, g.FromInt64(txInfo.Nonce))
|
||||
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
|
||||
|
||||
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
|
||||
elems = append(elems, g.FromInt64(int64(txInfo.MarketIndex)))
|
||||
elems = append(elems, g.FromInt64(int64(txInfo.InitialMarginFraction)))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.MarginMode)))
|
||||
|
||||
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package txtypes
|
||||
|
||||
import (
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
)
|
||||
|
||||
var _ TxInfo = (*L2UpdateMarginTxInfo)(nil)
|
||||
|
||||
type L2UpdateMarginTxInfo struct {
|
||||
AccountIndex int64
|
||||
ApiKeyIndex uint8
|
||||
|
||||
MarketIndex int16
|
||||
USDCAmount int64
|
||||
Direction uint8
|
||||
|
||||
ExpiredAt int64
|
||||
Nonce int64
|
||||
Sig []byte
|
||||
SignedHash string `json:"-"`
|
||||
}
|
||||
|
||||
func (txInfo *L2UpdateMarginTxInfo) GetTxType() uint8 {
|
||||
return TxTypeL2UpdateMargin
|
||||
}
|
||||
|
||||
func (txInfo *L2UpdateMarginTxInfo) GetTxInfo() (string, error) {
|
||||
return getTxInfo(txInfo)
|
||||
}
|
||||
|
||||
func (txInfo *L2UpdateMarginTxInfo) GetTxHash() string {
|
||||
return txInfo.SignedHash
|
||||
}
|
||||
|
||||
func (txInfo *L2UpdateMarginTxInfo) Validate() error {
|
||||
if txInfo.AccountIndex < MinAccountIndex {
|
||||
return ErrFromAccountIndexTooLow
|
||||
}
|
||||
if txInfo.AccountIndex > MaxAccountIndex {
|
||||
return ErrFromAccountIndexTooHigh
|
||||
}
|
||||
|
||||
// ApiKeyIndex
|
||||
if txInfo.ApiKeyIndex < MinApiKeyIndex {
|
||||
return ErrApiKeyIndexTooLow
|
||||
}
|
||||
if txInfo.ApiKeyIndex > MaxApiKeyIndex {
|
||||
return ErrApiKeyIndexTooHigh
|
||||
}
|
||||
|
||||
// MarketIndex
|
||||
if txInfo.MarketIndex < MinPerpsMarketIndex || txInfo.MarketIndex > MaxPerpsMarketIndex {
|
||||
return ErrInvalidMarketIndex
|
||||
}
|
||||
|
||||
if txInfo.USDCAmount == 0 {
|
||||
return ErrTransferAmountTooLow
|
||||
}
|
||||
if txInfo.USDCAmount > MaxTransferAmount {
|
||||
return ErrTransferAmountTooHigh
|
||||
}
|
||||
if txInfo.Direction != RemoveFromIsolatedMargin && txInfo.Direction != AddToIsolatedMargin {
|
||||
return ErrInvalidUpdateMarginDirection
|
||||
}
|
||||
|
||||
if txInfo.Nonce < MinNonce {
|
||||
return ErrNonceTooLow
|
||||
}
|
||||
|
||||
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
|
||||
return ErrExpiredAtInvalid
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (txInfo *L2UpdateMarginTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
|
||||
elems := make([]g.Element, 0, 10)
|
||||
|
||||
elems = append(elems, g.FromUint32(lighterChainId))
|
||||
elems = append(elems, g.FromUint32(TxTypeL2UpdateMargin))
|
||||
elems = append(elems, g.FromInt64(txInfo.Nonce))
|
||||
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
|
||||
|
||||
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
|
||||
elems = append(elems, g.FromInt64(int64(txInfo.MarketIndex)))
|
||||
elems = append(elems, g.FromUint64(uint64(txInfo.USDCAmount)&0xFFFFFFFF)) //nolint:gosec
|
||||
elems = append(elems, g.FromUint64(uint64(txInfo.USDCAmount)>>32)) //nolint:gosec
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.Direction)))
|
||||
|
||||
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package txtypes
|
||||
|
||||
import (
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
)
|
||||
|
||||
var _ TxInfo = (*L2UpdatePublicPoolTxInfo)(nil)
|
||||
|
||||
type L2UpdatePublicPoolTxInfo struct {
|
||||
AccountIndex int64 // Master account index
|
||||
ApiKeyIndex uint8
|
||||
|
||||
PublicPoolIndex int64
|
||||
|
||||
Status uint8
|
||||
OperatorFee int64
|
||||
MinOperatorShareRate uint16
|
||||
|
||||
ExpiredAt int64
|
||||
Nonce int64
|
||||
Sig []byte
|
||||
SignedHash string `json:"-"`
|
||||
}
|
||||
|
||||
func (txInfo *L2UpdatePublicPoolTxInfo) GetTxType() uint8 {
|
||||
return TxTypeL2UpdatePublicPool
|
||||
}
|
||||
|
||||
func (txInfo *L2UpdatePublicPoolTxInfo) GetTxInfo() (string, error) {
|
||||
return getTxInfo(txInfo)
|
||||
}
|
||||
|
||||
func (txInfo *L2UpdatePublicPoolTxInfo) GetTxHash() string {
|
||||
return txInfo.SignedHash
|
||||
}
|
||||
|
||||
func (txInfo *L2UpdatePublicPoolTxInfo) Validate() error {
|
||||
// AccountIndex
|
||||
if txInfo.AccountIndex < MinAccountIndex {
|
||||
return ErrFromAccountIndexTooLow
|
||||
}
|
||||
if txInfo.AccountIndex > MaxAccountIndex {
|
||||
return ErrFromAccountIndexTooHigh
|
||||
}
|
||||
|
||||
// ApiKeyIndex
|
||||
if txInfo.ApiKeyIndex < MinApiKeyIndex {
|
||||
return ErrApiKeyIndexTooLow
|
||||
}
|
||||
if txInfo.ApiKeyIndex > MaxApiKeyIndex {
|
||||
return ErrApiKeyIndexTooHigh
|
||||
}
|
||||
|
||||
// PublicPoolIndex
|
||||
if txInfo.PublicPoolIndex < MinAccountIndex {
|
||||
return ErrPublicPoolIndexTooLow
|
||||
}
|
||||
if txInfo.PublicPoolIndex > MaxAccountIndex {
|
||||
return ErrPublicPoolIndexTooHigh
|
||||
}
|
||||
|
||||
// Status
|
||||
if txInfo.Status != 0 && txInfo.Status != 1 {
|
||||
return ErrInvalidPoolStatus
|
||||
}
|
||||
|
||||
// OperatorFee
|
||||
if txInfo.OperatorFee < 0 || txInfo.OperatorFee > FeeTick {
|
||||
return ErrInvalidPoolOperatorFee
|
||||
}
|
||||
|
||||
// MinOperatorShareRate
|
||||
if txInfo.MinOperatorShareRate > ShareTick {
|
||||
return ErrPoolMinOperatorShareRateTooHigh
|
||||
}
|
||||
|
||||
// Nonce
|
||||
if txInfo.Nonce < MinNonce {
|
||||
return ErrNonceTooLow
|
||||
}
|
||||
|
||||
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
|
||||
return ErrExpiredAtInvalid
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (txInfo *L2UpdatePublicPoolTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
|
||||
elems := make([]g.Element, 0, 10)
|
||||
|
||||
elems = append(elems, g.FromUint32(lighterChainId))
|
||||
elems = append(elems, g.FromUint32(TxTypeL2UpdatePublicPool))
|
||||
elems = append(elems, g.FromInt64(txInfo.Nonce))
|
||||
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
|
||||
|
||||
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
|
||||
elems = append(elems, g.FromInt64(txInfo.PublicPoolIndex))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.Status)))
|
||||
elems = append(elems, g.FromInt64(txInfo.OperatorFee))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.MinOperatorShareRate)))
|
||||
|
||||
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package txtypes
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
gFp5 "github.com/elliottech/poseidon_crypto/field/goldilocks_quintic_extension"
|
||||
gQuint "github.com/elliottech/poseidon_crypto/field/goldilocks_quintic_extension"
|
||||
"github.com/ethereum/go-ethereum/accounts"
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/common/hexutil"
|
||||
"github.com/ethereum/go-ethereum/crypto"
|
||||
)
|
||||
|
||||
const (
|
||||
TemplateChangePubKey = "Register Lighter Account\n\npubkey: 0x%s\nnonce: %s\naccount index: %s\napi key index: %s\nOnly sign this message for a trusted client!"
|
||||
TemplateTransfer = "Transfer\n\nnonce: %s\nfrom: %s (route %s)\napi key: %s\nto: %s (route %s)\nasset: %s\namount: %s\nfee: %s" +
|
||||
"\nchainId: %s\nmemo: %s\nOnly sign this message for a trusted client!"
|
||||
TemplateSubAccount = "Create Lighter Sub Account\n\nmaster account index: %s\nOnly sign this message for a trusted client!"
|
||||
)
|
||||
|
||||
const SignatureLength = 80
|
||||
const L1SignatureLength = 65
|
||||
const PubKeyLength = gFp5.Bytes
|
||||
const HashLength = gQuint.Bytes
|
||||
|
||||
func IsValidPubKeyLength(bytes []byte) bool {
|
||||
return len(bytes) == gFp5.Bytes
|
||||
}
|
||||
|
||||
func IsZeroByteSlice(bytes []byte) bool {
|
||||
for _, s := range bytes {
|
||||
if s != 0 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func getTxInfo(tx interface{}) (string, error) {
|
||||
txInfoBytes, err := json.Marshal(tx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(txInfoBytes), nil
|
||||
}
|
||||
|
||||
func getHex10FromUint64(value uint64) string {
|
||||
v := hexutil.EncodeUint64(value)
|
||||
v = strings.Replace(v, "0x", "", 1)
|
||||
|
||||
// Make sure result has fixed bytes
|
||||
vBytes := []byte(v)
|
||||
if len(vBytes) < 16 {
|
||||
toAppend := make([]byte, 16-len(vBytes))
|
||||
for i := range toAppend {
|
||||
toAppend[i] = 48
|
||||
}
|
||||
vBytes = append(toAppend, vBytes...)
|
||||
}
|
||||
|
||||
return fmt.Sprintf("0x%s", string(vBytes))
|
||||
}
|
||||
|
||||
func calculateL1AddressBySignature(signatureBody, l1Signature string) common.Address {
|
||||
message := accounts.TextHash([]byte(signatureBody))
|
||||
// Decode from signature string to get the signature byte array
|
||||
signatureContent, err := hexutil.Decode(l1Signature)
|
||||
if err != nil {
|
||||
return [20]byte{}
|
||||
}
|
||||
|
||||
// Transform yellow paper V from 27/28 to 0/1
|
||||
if signatureContent[64] >= 27 {
|
||||
signatureContent[64] -= 27
|
||||
}
|
||||
|
||||
// Calculate the public key from the signature and source string
|
||||
signaturePublicKey, err := crypto.SigToPub(message, signatureContent)
|
||||
if err != nil {
|
||||
return [20]byte{}
|
||||
}
|
||||
|
||||
// Calculate the address from the public key
|
||||
publicAddress := crypto.PubkeyToAddress(*signaturePublicKey)
|
||||
return publicAddress
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package txtypes
|
||||
|
||||
import (
|
||||
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
|
||||
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
|
||||
)
|
||||
|
||||
var _ TxInfo = (*L2WithdrawTxInfo)(nil)
|
||||
|
||||
type L2WithdrawTxInfo struct {
|
||||
FromAccountIndex int64
|
||||
ApiKeyIndex uint8
|
||||
AssetIndex int16
|
||||
RouteType uint8
|
||||
Amount uint64
|
||||
ExpiredAt int64
|
||||
Nonce int64
|
||||
Sig []byte
|
||||
SignedHash string `json:"-"`
|
||||
}
|
||||
|
||||
func (txInfo *L2WithdrawTxInfo) Validate() error {
|
||||
if txInfo.FromAccountIndex < MinAccountIndex {
|
||||
return ErrFromAccountIndexTooLow
|
||||
}
|
||||
if txInfo.FromAccountIndex > MaxAccountIndex {
|
||||
return ErrFromAccountIndexTooHigh
|
||||
}
|
||||
|
||||
// ApiKeyIndex
|
||||
if txInfo.ApiKeyIndex < MinApiKeyIndex {
|
||||
return ErrApiKeyIndexTooLow
|
||||
}
|
||||
if txInfo.ApiKeyIndex > MaxApiKeyIndex {
|
||||
return ErrApiKeyIndexTooHigh
|
||||
}
|
||||
|
||||
// AssetIndex
|
||||
if txInfo.AssetIndex < MinAssetIndex {
|
||||
return ErrAssetIndexTooLow
|
||||
}
|
||||
if txInfo.AssetIndex > MaxAssetIndex {
|
||||
return ErrAssetIndexTooHigh
|
||||
}
|
||||
|
||||
// RouteType
|
||||
if txInfo.RouteType != AssetRouteType_Perps && txInfo.RouteType != AssetRouteType_Spot {
|
||||
return ErrRouteTypeInvalid
|
||||
}
|
||||
|
||||
// Amount
|
||||
if txInfo.Amount == 0 {
|
||||
return ErrWithdrawalAmountTooLow
|
||||
}
|
||||
if txInfo.Amount > MaxWithdrawalAmount {
|
||||
return ErrWithdrawalAmountTooHigh
|
||||
}
|
||||
|
||||
if txInfo.Nonce < MinNonce {
|
||||
return ErrNonceTooLow
|
||||
}
|
||||
|
||||
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
|
||||
return ErrExpiredAtInvalid
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (txInfo *L2WithdrawTxInfo) GetTxType() uint8 {
|
||||
return TxTypeL2Withdraw
|
||||
}
|
||||
|
||||
func (txInfo *L2WithdrawTxInfo) GetTxInfo() (string, error) {
|
||||
return getTxInfo(txInfo)
|
||||
}
|
||||
|
||||
func (txInfo *L2WithdrawTxInfo) GetTxHash() string {
|
||||
return txInfo.SignedHash
|
||||
}
|
||||
|
||||
func (txInfo *L2WithdrawTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
|
||||
elems := make([]g.Element, 0, 14)
|
||||
|
||||
elems = append(elems, g.FromUint32(lighterChainId))
|
||||
elems = append(elems, g.FromUint32(TxTypeL2Withdraw))
|
||||
elems = append(elems, g.FromInt64(txInfo.Nonce))
|
||||
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
|
||||
|
||||
elems = append(elems, g.FromInt64(txInfo.FromAccountIndex))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.AssetIndex)))
|
||||
elems = append(elems, g.FromUint32(uint32(txInfo.RouteType)))
|
||||
elems = append(elems, g.FromUint64(uint64(txInfo.Amount&0xFFFFFFFF)))
|
||||
elems = append(elems, g.FromUint64(uint64(txInfo.Amount>>32)))
|
||||
|
||||
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
|
||||
}
|
||||
@@ -0,0 +1,731 @@
|
||||
//go:build js
|
||||
// +build js
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"syscall/js"
|
||||
"time"
|
||||
|
||||
"github.com/elliottech/lighter-go/client"
|
||||
"github.com/elliottech/lighter-go/client/http"
|
||||
"github.com/elliottech/lighter-go/types"
|
||||
"github.com/elliottech/lighter-go/types/txtypes"
|
||||
"github.com/ethereum/go-ethereum/common/hexutil"
|
||||
)
|
||||
|
||||
func wrapErr(err error) js.Value {
|
||||
if err != nil {
|
||||
return js.ValueOf(map[string]interface{}{"error": fmt.Sprintf("%v", err)})
|
||||
}
|
||||
return js.ValueOf(map[string]interface{}{})
|
||||
}
|
||||
|
||||
func messageToSign(info txtypes.TxInfo) string {
|
||||
switch tx := info.(type) {
|
||||
case *txtypes.L2ChangePubKeyTxInfo:
|
||||
return tx.GetL1SignatureBody()
|
||||
case *txtypes.L2TransferTxInfo:
|
||||
return tx.GetL1SignatureBody()
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func convertTxInfoToJS(info txtypes.TxInfo, err error) js.Value {
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
if info == nil {
|
||||
return js.ValueOf(map[string]interface{}{"error": "nil response"})
|
||||
}
|
||||
|
||||
txInfoStr, strErr := info.GetTxInfo()
|
||||
if strErr != nil {
|
||||
return wrapErr(strErr)
|
||||
}
|
||||
|
||||
out := map[string]interface{}{
|
||||
"txType": info.GetTxType(),
|
||||
"txInfo": txInfoStr,
|
||||
"txHash": info.GetTxHash(),
|
||||
}
|
||||
if msg := messageToSign(info); msg != "" {
|
||||
out["messageToSign"] = msg
|
||||
}
|
||||
return js.ValueOf(out)
|
||||
}
|
||||
|
||||
// safeInt safely extracts an int from a js.Value, handling undefined values
|
||||
func safeInt(v js.Value, index int) (int64, error) {
|
||||
if v.Type() == js.TypeUndefined {
|
||||
return 0, fmt.Errorf("argument %d is undefined", index)
|
||||
}
|
||||
return int64(v.Int()), nil
|
||||
}
|
||||
|
||||
// safeUint8 safely extracts a uint8 from a js.Value, handling undefined values
|
||||
func safeUint8(v js.Value, index int) (uint8, error) {
|
||||
if v.Type() == js.TypeUndefined {
|
||||
return 0, fmt.Errorf("argument %d is undefined", index)
|
||||
}
|
||||
return uint8(v.Int()), nil
|
||||
}
|
||||
|
||||
// safeUint32 safely extracts a uint32 from a js.Value, handling undefined values
|
||||
func safeUint32(v js.Value, index int) (uint32, error) {
|
||||
if v.Type() == js.TypeUndefined {
|
||||
return 0, fmt.Errorf("argument %d is undefined", index)
|
||||
}
|
||||
return uint32(v.Int()), nil
|
||||
}
|
||||
|
||||
func getClient(args []js.Value) (*client.TxClient, error) {
|
||||
l := len(args)
|
||||
if l < 2 {
|
||||
return nil, fmt.Errorf("insufficient arguments: need at least 2 for apiKeyIndex and accountIndex")
|
||||
}
|
||||
// Check if the last two arguments are valid and extract safely
|
||||
if args[l-2].Type() == js.TypeUndefined || args[l-1].Type() == js.TypeUndefined {
|
||||
return nil, fmt.Errorf("apiKeyIndex or accountIndex is undefined")
|
||||
}
|
||||
apiKeyIndexVal, err := safeUint8(args[l-2], l-2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
accountIndexVal, err := safeInt(args[l-1], l-1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return client.GetClient(apiKeyIndexVal, accountIndexVal)
|
||||
}
|
||||
|
||||
// recoverPanic wraps a function execution with panic recovery
|
||||
func recoverPanic(fn func() js.Value) (result js.Value) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
result = wrapErr(fmt.Errorf("panic: %v", r))
|
||||
}
|
||||
}()
|
||||
return fn()
|
||||
}
|
||||
|
||||
func main() {
|
||||
js.Global().Set("GenerateAPIKey", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
|
||||
return recoverPanic(func() js.Value {
|
||||
if len(args) < 1 {
|
||||
return js.ValueOf(map[string]interface{}{"error": "GenerateAPIKey expects 1 arg: seed"})
|
||||
}
|
||||
seed := args[0].String()
|
||||
privateKey, publicKey, err := client.GenerateAPIKey(seed)
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
return js.ValueOf(map[string]interface{}{"privateKey": privateKey, "publicKey": publicKey})
|
||||
})
|
||||
}))
|
||||
|
||||
js.Global().Set("CreateClient", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
|
||||
return recoverPanic(func() js.Value {
|
||||
if len(args) < 5 {
|
||||
return js.ValueOf(map[string]interface{}{"error": "CreateClient expects 5 args: url, privateKey, chainId, apiKeyIndex, accountIndex"})
|
||||
}
|
||||
url := args[0].String()
|
||||
privateKey := args[1].String()
|
||||
chainId := uint32(args[2].Int())
|
||||
apiKeyIndex := uint8(args[3].Int())
|
||||
accountIndex := int64(args[4].Int())
|
||||
httpClient := http.NewClient(url)
|
||||
_, err := client.CreateClient(httpClient, privateKey, chainId, apiKeyIndex, accountIndex)
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
return wrapErr(nil)
|
||||
})
|
||||
}))
|
||||
|
||||
js.Global().Set("CheckClient", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
|
||||
return recoverPanic(func() js.Value {
|
||||
if len(args) < 2 {
|
||||
return js.ValueOf(map[string]interface{}{"error": "CheckClient expects 2 args: apiKeyIndex, accountIndex"})
|
||||
}
|
||||
c, err := getClient(args)
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
|
||||
err = c.Check()
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
return wrapErr(nil)
|
||||
})
|
||||
}))
|
||||
|
||||
js.Global().Set("CreateAuthToken", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
|
||||
return recoverPanic(func() js.Value {
|
||||
if len(args) < 3 {
|
||||
return js.ValueOf(map[string]interface{}{"error": "CreateAuthToken expects 3 args: deadline, apiKeyIndex, accountIndex"})
|
||||
}
|
||||
c, err := getClient(args)
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
|
||||
deadline := int64(args[0].Int())
|
||||
if deadline == 0 {
|
||||
deadline = time.Now().Add(time.Hour * 7).Unix()
|
||||
}
|
||||
|
||||
token, err := c.GetAuthToken(time.Unix(deadline, 0))
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
return js.ValueOf(map[string]interface{}{"authToken": token})
|
||||
})
|
||||
}))
|
||||
|
||||
js.Global().Set("SignChangePubKey", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
|
||||
return recoverPanic(func() js.Value {
|
||||
if len(args) < 4 {
|
||||
return js.ValueOf(map[string]interface{}{"error": "SignChangePubKey expects 4 args: pubKeyHex, nonce, apiKeyIndex, accountIndex"})
|
||||
}
|
||||
pubKeyHex := args[0].String()
|
||||
nonce := int64(args[1].Int())
|
||||
|
||||
c, err := getClient(args)
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
|
||||
pubKeyBytes, err := hexutil.Decode(pubKeyHex)
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
if len(pubKeyBytes) != 40 {
|
||||
return js.ValueOf(map[string]interface{}{"error": "invalid pub key length. expected 40 but got " + strconv.Itoa(len(pubKeyBytes))})
|
||||
}
|
||||
var pubKey [40]byte
|
||||
copy(pubKey[:], pubKeyBytes)
|
||||
|
||||
txInfo := &types.ChangePubKeyReq{
|
||||
PubKey: pubKey,
|
||||
}
|
||||
ops := &types.TransactOpts{
|
||||
Nonce: &nonce,
|
||||
}
|
||||
|
||||
tx, err := c.GetChangePubKeyTransaction(txInfo, ops)
|
||||
return convertTxInfoToJS(tx, err)
|
||||
})
|
||||
}))
|
||||
|
||||
js.Global().Set("SignCreateOrder", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
|
||||
return recoverPanic(func() js.Value {
|
||||
if len(args) < 13 {
|
||||
return js.ValueOf(map[string]interface{}{"error": "SignCreateOrder expects 13 args: marketIndex, clientOrderIndex, baseAmount, price, isAsk, orderType, timeInForce, reduceOnly, triggerPrice, orderExpiry, nonce, apiKeyIndex, accountIndex"})
|
||||
}
|
||||
// Validate all arguments are defined before accessing
|
||||
for i := 0; i < 13; i++ {
|
||||
if args[i].Type() == js.TypeUndefined {
|
||||
return js.ValueOf(map[string]interface{}{"error": fmt.Sprintf("argument %d is undefined", i)})
|
||||
}
|
||||
}
|
||||
c, err := getClient(args)
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
|
||||
marketIndex, err := safeUint8(args[0], 0)
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
clientOrderIndex, err := safeInt(args[1], 1)
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
baseAmount, err := safeInt(args[2], 2)
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
price, err := safeUint32(args[3], 3)
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
isAsk, err := safeUint8(args[4], 4)
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
orderType, err := safeUint8(args[5], 5)
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
timeInForce, err := safeUint8(args[6], 6)
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
reduceOnly, err := safeUint8(args[7], 7)
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
triggerPrice, err := safeUint32(args[8], 8)
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
orderExpiry, err := safeInt(args[9], 9)
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
nonce, err := safeInt(args[10], 10)
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
|
||||
if orderExpiry == -1 {
|
||||
orderExpiry = time.Now().Add(time.Hour * 24 * 28).UnixMilli() // 28 days
|
||||
}
|
||||
|
||||
txInfo := &types.CreateOrderTxReq{
|
||||
MarketIndex: marketIndex,
|
||||
ClientOrderIndex: clientOrderIndex,
|
||||
BaseAmount: baseAmount,
|
||||
Price: price,
|
||||
IsAsk: isAsk,
|
||||
Type: orderType,
|
||||
TimeInForce: timeInForce,
|
||||
ReduceOnly: reduceOnly,
|
||||
TriggerPrice: triggerPrice,
|
||||
OrderExpiry: orderExpiry,
|
||||
}
|
||||
ops := new(types.TransactOpts)
|
||||
if nonce != -1 {
|
||||
ops.Nonce = &nonce
|
||||
}
|
||||
|
||||
tx, err := c.GetCreateOrderTransaction(txInfo, ops)
|
||||
return convertTxInfoToJS(tx, err)
|
||||
})
|
||||
}))
|
||||
|
||||
js.Global().Set("SignCancelOrder", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
|
||||
return recoverPanic(func() js.Value {
|
||||
if len(args) < 5 {
|
||||
return js.ValueOf(map[string]interface{}{"error": "SignCancelOrder expects 5 args: marketIndex, orderIndex, nonce, apiKeyIndex, accountIndex"})
|
||||
}
|
||||
c, err := getClient(args)
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
|
||||
marketIndex := uint8(args[0].Int())
|
||||
orderIndex := int64(args[1].Int())
|
||||
nonce := int64(args[2].Int())
|
||||
|
||||
txInfo := &types.CancelOrderTxReq{
|
||||
MarketIndex: marketIndex,
|
||||
Index: orderIndex,
|
||||
}
|
||||
ops := new(types.TransactOpts)
|
||||
if nonce != -1 {
|
||||
ops.Nonce = &nonce
|
||||
}
|
||||
|
||||
tx, err := c.GetCancelOrderTransaction(txInfo, ops)
|
||||
return convertTxInfoToJS(tx, err)
|
||||
})
|
||||
}))
|
||||
|
||||
js.Global().Set("SignCancelAllOrders", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
|
||||
return recoverPanic(func() js.Value {
|
||||
if len(args) < 5 {
|
||||
return js.ValueOf(map[string]interface{}{"error": "SignCancelAllOrders expects 5 args: timeInForce, time, nonce, apiKeyIndex, accountIndex"})
|
||||
}
|
||||
c, err := getClient(args)
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
|
||||
timeInForce := uint8(args[0].Int())
|
||||
timeVal := int64(args[1].Int())
|
||||
nonce := int64(args[2].Int())
|
||||
|
||||
txInfo := &types.CancelAllOrdersTxReq{
|
||||
TimeInForce: timeInForce,
|
||||
Time: timeVal,
|
||||
}
|
||||
ops := new(types.TransactOpts)
|
||||
if nonce != -1 {
|
||||
ops.Nonce = &nonce
|
||||
}
|
||||
|
||||
tx, err := c.GetCancelAllOrdersTransaction(txInfo, ops)
|
||||
return convertTxInfoToJS(tx, err)
|
||||
})
|
||||
}))
|
||||
|
||||
js.Global().Set("SignTransfer", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
|
||||
return recoverPanic(func() js.Value {
|
||||
if len(args) < 7 {
|
||||
return js.ValueOf(map[string]interface{}{"error": "SignTransfer expects 7 args: toAccount, usdcAmount, fee, memo, nonce, apiKeyIndex, accountIndex"})
|
||||
}
|
||||
c, err := getClient(args)
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
|
||||
toAccount := int64(args[0].Int())
|
||||
usdcAmount := int64(args[1].Int())
|
||||
fee := int64(args[2].Int())
|
||||
memoStr := args[3].String()
|
||||
nonce := int64(args[4].Int())
|
||||
|
||||
var memoArr [32]byte
|
||||
bs := []byte(memoStr)
|
||||
if len(bs) != 32 {
|
||||
return wrapErr(fmt.Errorf("memo expected to be 32 bytes long"))
|
||||
}
|
||||
for i := 0; i < 32; i++ {
|
||||
memoArr[i] = bs[i]
|
||||
}
|
||||
|
||||
txInfo := &types.TransferTxReq{
|
||||
ToAccountIndex: toAccount,
|
||||
USDCAmount: usdcAmount,
|
||||
Fee: fee,
|
||||
Memo: memoArr,
|
||||
}
|
||||
ops := new(types.TransactOpts)
|
||||
if nonce != -1 {
|
||||
ops.Nonce = &nonce
|
||||
}
|
||||
|
||||
tx, err := c.GetTransferTransaction(txInfo, ops)
|
||||
return convertTxInfoToJS(tx, err)
|
||||
})
|
||||
}))
|
||||
|
||||
js.Global().Set("SignWithdraw", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
|
||||
return recoverPanic(func() js.Value {
|
||||
if len(args) < 4 {
|
||||
return js.ValueOf(map[string]interface{}{"error": "SignWithdraw expects 4 args: usdcAmount, nonce, apiKeyIndex, accountIndex"})
|
||||
}
|
||||
c, err := getClient(args)
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
|
||||
usdcAmount := uint64(args[0].Int())
|
||||
nonce := int64(args[1].Int())
|
||||
|
||||
txInfo := &types.WithdrawTxReq{
|
||||
USDCAmount: usdcAmount,
|
||||
}
|
||||
ops := new(types.TransactOpts)
|
||||
if nonce != -1 {
|
||||
ops.Nonce = &nonce
|
||||
}
|
||||
|
||||
tx, err := c.GetWithdrawTransaction(txInfo, ops)
|
||||
return convertTxInfoToJS(tx, err)
|
||||
})
|
||||
}))
|
||||
|
||||
js.Global().Set("SignUpdateLeverage", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
|
||||
return recoverPanic(func() js.Value {
|
||||
if len(args) < 6 {
|
||||
return js.ValueOf(map[string]interface{}{"error": "SignUpdateLeverage expects 6 args: marketIndex, fraction, marginMode, nonce, apiKeyIndex, accountIndex"})
|
||||
}
|
||||
c, err := getClient(args)
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
|
||||
marketIndex := uint8(args[0].Int())
|
||||
fraction := uint16(args[1].Int())
|
||||
marginMode := uint8(args[2].Int())
|
||||
nonce := int64(args[3].Int())
|
||||
|
||||
txInfo := &types.UpdateLeverageTxReq{
|
||||
MarketIndex: marketIndex,
|
||||
InitialMarginFraction: fraction,
|
||||
MarginMode: marginMode,
|
||||
}
|
||||
ops := new(types.TransactOpts)
|
||||
if nonce != -1 {
|
||||
ops.Nonce = &nonce
|
||||
}
|
||||
|
||||
tx, err := c.GetUpdateLeverageTransaction(txInfo, ops)
|
||||
return convertTxInfoToJS(tx, err)
|
||||
})
|
||||
}))
|
||||
|
||||
js.Global().Set("SignModifyOrder", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
|
||||
return recoverPanic(func() js.Value {
|
||||
if len(args) < 8 {
|
||||
return js.ValueOf(map[string]interface{}{"error": "SignModifyOrder expects 8 args: marketIndex, index, baseAmount, price, triggerPrice, nonce, apiKeyIndex, accountIndex"})
|
||||
}
|
||||
c, err := getClient(args)
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
|
||||
marketIndex := uint8(args[0].Int())
|
||||
index := int64(args[1].Int())
|
||||
baseAmount := int64(args[2].Int())
|
||||
price := uint32(args[3].Int())
|
||||
triggerPrice := uint32(args[4].Int())
|
||||
nonce := int64(args[5].Int())
|
||||
|
||||
txInfo := &types.ModifyOrderTxReq{
|
||||
MarketIndex: marketIndex,
|
||||
Index: index,
|
||||
BaseAmount: baseAmount,
|
||||
Price: price,
|
||||
TriggerPrice: triggerPrice,
|
||||
}
|
||||
ops := new(types.TransactOpts)
|
||||
if nonce != -1 {
|
||||
ops.Nonce = &nonce
|
||||
}
|
||||
|
||||
tx, err := c.GetModifyOrderTransaction(txInfo, ops)
|
||||
return convertTxInfoToJS(tx, err)
|
||||
})
|
||||
}))
|
||||
|
||||
js.Global().Set("SignCreateSubAccount", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
|
||||
return recoverPanic(func() js.Value {
|
||||
if len(args) < 3 {
|
||||
return js.ValueOf(map[string]interface{}{"error": "SignCreateSubAccount expects 3 args: nonce, apiKeyIndex, accountIndex"})
|
||||
}
|
||||
c, err := getClient(args)
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
|
||||
nonce := int64(args[0].Int())
|
||||
|
||||
ops := new(types.TransactOpts)
|
||||
if nonce != -1 {
|
||||
ops.Nonce = &nonce
|
||||
}
|
||||
|
||||
tx, err := c.GetCreateSubAccountTransaction(ops)
|
||||
return convertTxInfoToJS(tx, err)
|
||||
})
|
||||
}))
|
||||
|
||||
js.Global().Set("SignCreatePublicPool", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
|
||||
return recoverPanic(func() js.Value {
|
||||
if len(args) < 6 {
|
||||
return js.ValueOf(map[string]interface{}{"error": "SignCreatePublicPool expects 6 args: operatorFee, initialTotalShares, minOperatorShareRate, nonce, apiKeyIndex, accountIndex"})
|
||||
}
|
||||
c, err := getClient(args)
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
|
||||
operatorFee := int64(args[0].Int())
|
||||
initialTotalShares := int64(args[1].Int())
|
||||
minOperatorShareRate := int64(args[2].Int())
|
||||
nonce := int64(args[3].Int())
|
||||
|
||||
txInfo := &types.CreatePublicPoolTxReq{
|
||||
OperatorFee: operatorFee,
|
||||
InitialTotalShares: initialTotalShares,
|
||||
MinOperatorShareRate: minOperatorShareRate,
|
||||
}
|
||||
ops := new(types.TransactOpts)
|
||||
if nonce != -1 {
|
||||
ops.Nonce = &nonce
|
||||
}
|
||||
|
||||
tx, err := c.GetCreatePublicPoolTransaction(txInfo, ops)
|
||||
return convertTxInfoToJS(tx, err)
|
||||
})
|
||||
}))
|
||||
|
||||
js.Global().Set("SignUpdatePublicPool", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
|
||||
return recoverPanic(func() js.Value {
|
||||
if len(args) < 7 {
|
||||
return js.ValueOf(map[string]interface{}{"error": "SignUpdatePublicPool expects 7 args: publicPoolIndex, status, operatorFee, minOperatorShareRate, nonce, apiKeyIndex, accountIndex"})
|
||||
}
|
||||
c, err := getClient(args)
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
|
||||
publicPoolIndex := uint8(args[0].Int())
|
||||
status := uint8(args[1].Int())
|
||||
operatorFee := int64(args[2].Int())
|
||||
minOperatorShareRate := int64(args[3].Int())
|
||||
nonce := int64(args[4].Int())
|
||||
|
||||
txInfo := &types.UpdatePublicPoolTxReq{
|
||||
PublicPoolIndex: int64(publicPoolIndex),
|
||||
Status: status,
|
||||
OperatorFee: operatorFee,
|
||||
MinOperatorShareRate: minOperatorShareRate,
|
||||
}
|
||||
ops := new(types.TransactOpts)
|
||||
if nonce != -1 {
|
||||
ops.Nonce = &nonce
|
||||
}
|
||||
|
||||
tx, err := c.GetUpdatePublicPoolTransaction(txInfo, ops)
|
||||
return convertTxInfoToJS(tx, err)
|
||||
})
|
||||
}))
|
||||
|
||||
js.Global().Set("SignMintShares", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
|
||||
return recoverPanic(func() js.Value {
|
||||
if len(args) < 5 {
|
||||
return js.ValueOf(map[string]interface{}{"error": "SignMintShares expects 5 args: publicPoolIndex, shareAmount, nonce, apiKeyIndex, accountIndex"})
|
||||
}
|
||||
c, err := getClient(args)
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
|
||||
publicPoolIndex := int64(args[0].Int())
|
||||
shareAmount := int64(args[1].Int())
|
||||
nonce := int64(args[2].Int())
|
||||
|
||||
txInfo := &types.MintSharesTxReq{
|
||||
PublicPoolIndex: publicPoolIndex,
|
||||
ShareAmount: shareAmount,
|
||||
}
|
||||
ops := new(types.TransactOpts)
|
||||
if nonce != -1 {
|
||||
ops.Nonce = &nonce
|
||||
}
|
||||
|
||||
tx, err := c.GetMintSharesTransaction(txInfo, ops)
|
||||
return convertTxInfoToJS(tx, err)
|
||||
})
|
||||
}))
|
||||
|
||||
js.Global().Set("SignBurnShares", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
|
||||
return recoverPanic(func() js.Value {
|
||||
if len(args) < 5 {
|
||||
return js.ValueOf(map[string]interface{}{"error": "SignBurnShares expects 5 args: publicPoolIndex, shareAmount, nonce, apiKeyIndex, accountIndex"})
|
||||
}
|
||||
c, err := getClient(args)
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
|
||||
publicPoolIndex := int64(args[0].Int())
|
||||
shareAmount := int64(args[1].Int())
|
||||
nonce := int64(args[2].Int())
|
||||
|
||||
txInfo := &types.BurnSharesTxReq{
|
||||
PublicPoolIndex: publicPoolIndex,
|
||||
ShareAmount: shareAmount,
|
||||
}
|
||||
ops := new(types.TransactOpts)
|
||||
if nonce != -1 {
|
||||
ops.Nonce = &nonce
|
||||
}
|
||||
|
||||
tx, err := c.GetBurnSharesTransaction(txInfo, ops)
|
||||
return convertTxInfoToJS(tx, err)
|
||||
})
|
||||
}))
|
||||
|
||||
js.Global().Set("SignUpdateMargin", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
|
||||
return recoverPanic(func() js.Value {
|
||||
if len(args) < 6 {
|
||||
return js.ValueOf(map[string]interface{}{"error": "SignUpdateMargin expects 6 args: marketIndex, usdcAmount, direction, nonce, apiKeyIndex, accountIndex"})
|
||||
}
|
||||
c, err := getClient(args)
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
|
||||
marketIndex := uint8(args[0].Int())
|
||||
usdcAmount := int64(args[1].Int())
|
||||
direction := uint8(args[2].Int())
|
||||
nonce := int64(args[3].Int())
|
||||
|
||||
txInfo := &types.UpdateMarginTxReq{
|
||||
MarketIndex: marketIndex,
|
||||
USDCAmount: usdcAmount,
|
||||
Direction: direction,
|
||||
}
|
||||
ops := new(types.TransactOpts)
|
||||
if nonce != -1 {
|
||||
ops.Nonce = &nonce
|
||||
}
|
||||
|
||||
tx, err := c.GetUpdateMarginTransaction(txInfo, ops)
|
||||
return convertTxInfoToJS(tx, err)
|
||||
})
|
||||
}))
|
||||
|
||||
js.Global().Set("SignCreateGroupedOrders", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
|
||||
return recoverPanic(func() js.Value {
|
||||
if len(args) < 5 {
|
||||
return js.ValueOf(map[string]interface{}{"error": "SignCreateGroupedOrders expects 5 args: groupingType, orders array, nonce, apiKeyIndex, accountIndex"})
|
||||
}
|
||||
c, err := getClient(args)
|
||||
if err != nil {
|
||||
return wrapErr(err)
|
||||
}
|
||||
|
||||
groupingType := uint8(args[0].Int())
|
||||
|
||||
// Parse orders array from JS
|
||||
ordersArg := args[1]
|
||||
if ordersArg.Type() != js.TypeObject {
|
||||
return js.ValueOf(map[string]interface{}{"error": "orders must be an array"})
|
||||
}
|
||||
length := ordersArg.Length()
|
||||
orders := make([]*types.CreateOrderTxReq, length)
|
||||
|
||||
for i := 0; i < length; i++ {
|
||||
orderObj := ordersArg.Index(i)
|
||||
if orderObj.Type() != js.TypeObject {
|
||||
return js.ValueOf(map[string]interface{}{"error": fmt.Sprintf("order %d must be an object", i)})
|
||||
}
|
||||
|
||||
orderExpiry := int64(orderObj.Get("OrderExpiry").Int())
|
||||
if orderExpiry == -1 {
|
||||
orderExpiry = time.Now().Add(time.Hour * 24 * 28).UnixMilli()
|
||||
}
|
||||
|
||||
orders[i] = &types.CreateOrderTxReq{
|
||||
MarketIndex: uint8(orderObj.Get("MarketIndex").Int()),
|
||||
ClientOrderIndex: int64(orderObj.Get("ClientOrderIndex").Int()),
|
||||
BaseAmount: int64(orderObj.Get("BaseAmount").Int()),
|
||||
Price: uint32(orderObj.Get("Price").Int()),
|
||||
IsAsk: uint8(orderObj.Get("IsAsk").Int()),
|
||||
Type: uint8(orderObj.Get("Type").Int()),
|
||||
TimeInForce: uint8(orderObj.Get("TimeInForce").Int()),
|
||||
ReduceOnly: uint8(orderObj.Get("ReduceOnly").Int()),
|
||||
TriggerPrice: uint32(orderObj.Get("TriggerPrice").Int()),
|
||||
OrderExpiry: orderExpiry,
|
||||
}
|
||||
}
|
||||
|
||||
nonce := int64(args[2].Int())
|
||||
|
||||
req := &types.CreateGroupedOrdersTxReq{
|
||||
GroupingType: groupingType,
|
||||
Orders: orders,
|
||||
}
|
||||
ops := new(types.TransactOpts)
|
||||
if nonce != -1 {
|
||||
ops.Nonce = &nonce
|
||||
}
|
||||
|
||||
txInfo, err := c.GetCreateGroupedOrdersTransaction(req, ops)
|
||||
return convertTxInfoToJS(txInfo, err)
|
||||
})
|
||||
}))
|
||||
|
||||
select {}
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
*/
|
||||
|
||||
import { resolveExchangeId, type SupportedExchangeId } from "./exchanges/create-adapter";
|
||||
import { language, type Language } from "./i18n";
|
||||
|
||||
export interface TradingConfig {
|
||||
symbol: string;
|
||||
@@ -211,3 +212,5 @@ export function isBasisStrategyEnabled(): boolean {
|
||||
const normalized = raw.trim().toLowerCase();
|
||||
return normalized === "1" || normalized === "true" || normalized === "yes";
|
||||
}
|
||||
|
||||
export const uiLanguage: Language = language;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { LogHandler } from "../order-coordinator";
|
||||
import { t } from "../../i18n";
|
||||
|
||||
type RateLimitState = "normal" | "degraded" | "paused";
|
||||
|
||||
@@ -32,13 +33,13 @@ export class RateLimitController {
|
||||
private suppressEntries(source?: string): void {
|
||||
if (this.entriesSuppressed) return;
|
||||
this.entriesSuppressed = true;
|
||||
this.log("info", `${source ? `${source} ` : ""}限频期间暂停新开仓`);
|
||||
this.log("info", t("rate.limit.suppress", { source: source ? `${source} ` : "" }));
|
||||
}
|
||||
|
||||
private allowEntries(): void {
|
||||
if (!this.entriesSuppressed) return;
|
||||
this.entriesSuppressed = false;
|
||||
this.log("info", "限频恢复,允许重新开仓");
|
||||
this.log("info", t("rate.limit.resumeEntries"));
|
||||
}
|
||||
|
||||
beforeCycle(): RateLimitDecision {
|
||||
@@ -47,7 +48,7 @@ export class RateLimitController {
|
||||
if (this.pausedUntil != null && now >= this.pausedUntil) {
|
||||
this.state = "degraded";
|
||||
this.pausedUntil = null;
|
||||
this.log("info", "限频暂停结束,继续以降频模式运行");
|
||||
this.log("info", t("rate.limit.pausedEnd"));
|
||||
} else {
|
||||
this.lastCycleAt = now;
|
||||
return "paused";
|
||||
@@ -69,7 +70,7 @@ export class RateLimitController {
|
||||
this.state = "degraded";
|
||||
this.log(
|
||||
"warn",
|
||||
`${source ? `${source} ` : ""}触发 429,降频至 ${(this.currentInterval() / 1000).toFixed(2)}s`
|
||||
t("rate.limit.hit", { source: source ? `${source} ` : "", interval: (this.currentInterval() / 1000).toFixed(2) })
|
||||
);
|
||||
this.lastCycleAt = now;
|
||||
this.suppressEntries(source);
|
||||
@@ -80,7 +81,7 @@ export class RateLimitController {
|
||||
this.pausedUntil = now + this.pauseMs;
|
||||
this.log(
|
||||
"warn",
|
||||
`${source ? `${source} ` : ""}连续 429,暂停请求 ${(this.pauseMs / 1000).toFixed(0)}s`
|
||||
t("rate.limit.consecutive", { source: source ? `${source} ` : "", seconds: (this.pauseMs / 1000).toFixed(0) })
|
||||
);
|
||||
this.suppressEntries(source);
|
||||
return;
|
||||
@@ -88,7 +89,7 @@ export class RateLimitController {
|
||||
this.pausedUntil = now + this.pauseMs;
|
||||
this.log(
|
||||
"warn",
|
||||
`${source ? `${source} ` : ""}限频仍在持续,延长暂停 ${(this.pauseMs / 1000).toFixed(0)}s`
|
||||
t("rate.limit.still", { source: source ? `${source} ` : "", seconds: (this.pauseMs / 1000).toFixed(0) })
|
||||
);
|
||||
this.suppressEntries(source);
|
||||
}
|
||||
@@ -99,7 +100,7 @@ export class RateLimitController {
|
||||
const now = Date.now();
|
||||
if (now - this.lastRateLimitAt >= this.recoveryMs) {
|
||||
this.state = "normal";
|
||||
this.log("info", "限频恢复,重置为正常请求频率");
|
||||
this.log("info", t("rate.limit.reset"));
|
||||
this.allowEntries();
|
||||
this.lastRateLimitAt = 0;
|
||||
}
|
||||
@@ -119,4 +120,3 @@ export class RateLimitController {
|
||||
return this.baseInterval;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -33,6 +33,8 @@ export interface ExchangePrecision {
|
||||
priceDecimals?: number;
|
||||
sizeDecimals?: number;
|
||||
marketId?: number;
|
||||
minBaseAmount?: number;
|
||||
minQuoteAmount?: number;
|
||||
}
|
||||
|
||||
export interface ExchangeAdapter {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -38,7 +38,7 @@ interface NextNonceResponse extends ApiResponseBase {
|
||||
nonce: number;
|
||||
}
|
||||
|
||||
interface SendTxResponse extends ApiResponseBase {
|
||||
export interface SendTxResponse extends ApiResponseBase {
|
||||
tx_hash: string;
|
||||
predicted_execution_time_ms?: number;
|
||||
}
|
||||
@@ -61,6 +61,7 @@ interface CandlesticksResponse extends ApiResponseBase {
|
||||
|
||||
interface AccountResponse extends ApiResponseBase {
|
||||
account?: LighterAccountDetails;
|
||||
accounts?: LighterAccountDetails[];
|
||||
}
|
||||
|
||||
export interface LighterHttpClientOptions {
|
||||
@@ -100,10 +101,12 @@ export class LighterHttpClient {
|
||||
return stats.map((entry) => ({
|
||||
market_id: entry.market_id,
|
||||
symbol: entry.symbol,
|
||||
index_price: entry.index_price ?? entry.mark_price ?? entry.last_trade_price,
|
||||
mark_price: entry.mark_price ?? entry.last_trade_price,
|
||||
market_type: (entry as any).market_type,
|
||||
index_price: (entry as any).index_price ?? entry.mark_price ?? entry.last_trade_price,
|
||||
mid_price: (entry as any).mid_price,
|
||||
mark_price: entry.mark_price ?? (entry as any).mid_price ?? entry.last_trade_price,
|
||||
last_trade_price: entry.last_trade_price,
|
||||
open_interest: entry.open_interest ?? "0",
|
||||
open_interest: (entry as any).open_interest ?? "0",
|
||||
daily_base_token_volume: entry.daily_base_token_volume,
|
||||
daily_quote_token_volume: entry.daily_quote_token_volume,
|
||||
daily_price_low: entry.daily_price_low,
|
||||
@@ -136,7 +139,8 @@ export class LighterHttpClient {
|
||||
headers: authToken ? { Authorization: authToken } : undefined,
|
||||
tolerateNotFound: true,
|
||||
});
|
||||
return response.account ?? null;
|
||||
const account = response.account ?? (Array.isArray(response.accounts) ? response.accounts[0] : null);
|
||||
return account ?? null;
|
||||
}
|
||||
|
||||
async getCandlesticks(params: {
|
||||
|
||||
@@ -15,6 +15,16 @@ class StrOrErr(ctypes.Structure):
|
||||
_fields_ = [("str", ctypes.c_char_p), ("err", ctypes.c_char_p)]
|
||||
|
||||
|
||||
class SignedTxResponse(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("txType", ctypes.c_uint8),
|
||||
("txInfo", ctypes.c_char_p),
|
||||
("txHash", ctypes.c_char_p),
|
||||
("messageToSign", ctypes.c_char_p),
|
||||
("err", ctypes.c_char_p),
|
||||
]
|
||||
|
||||
|
||||
def _resolve_signer_path() -> str:
|
||||
base = os.path.abspath(os.path.dirname(__file__))
|
||||
signers_dir = os.path.join(base, "signers")
|
||||
@@ -57,35 +67,54 @@ except OSError as exc: # pragma: no cover - runtime environment guard
|
||||
LIB.CreateClient.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int, ctypes.c_int, ctypes.c_longlong]
|
||||
LIB.CreateClient.restype = ctypes.c_char_p
|
||||
|
||||
LIB.SwitchAPIKey.argtypes = [ctypes.c_int]
|
||||
LIB.SwitchAPIKey.restype = ctypes.c_char_p
|
||||
|
||||
# New signer exports: SwitchAPIKey removed; apiKeyIndex is passed to every call
|
||||
LIB.SignCreateOrder.argtypes = [
|
||||
ctypes.c_int,
|
||||
ctypes.c_longlong,
|
||||
ctypes.c_longlong,
|
||||
ctypes.c_int,
|
||||
ctypes.c_int,
|
||||
ctypes.c_int,
|
||||
ctypes.c_int,
|
||||
ctypes.c_int,
|
||||
ctypes.c_int,
|
||||
ctypes.c_longlong,
|
||||
ctypes.c_longlong,
|
||||
ctypes.c_int, # marketIndex
|
||||
ctypes.c_longlong, # clientOrderIndex
|
||||
ctypes.c_longlong, # baseAmount
|
||||
ctypes.c_int, # price
|
||||
ctypes.c_int, # isAsk
|
||||
ctypes.c_int, # orderType
|
||||
ctypes.c_int, # timeInForce
|
||||
ctypes.c_int, # reduceOnly
|
||||
ctypes.c_int, # triggerPrice
|
||||
ctypes.c_longlong, # orderExpiry
|
||||
ctypes.c_longlong, # nonce
|
||||
ctypes.c_int, # apiKeyIndex
|
||||
ctypes.c_longlong, # accountIndex
|
||||
]
|
||||
LIB.SignCreateOrder.restype = StrOrErr
|
||||
LIB.SignCreateOrder.restype = SignedTxResponse
|
||||
|
||||
LIB.SignCancelOrder.argtypes = [ctypes.c_int, ctypes.c_longlong, ctypes.c_longlong]
|
||||
LIB.SignCancelOrder.restype = StrOrErr
|
||||
LIB.SignCancelOrder.argtypes = [
|
||||
ctypes.c_int, # marketIndex
|
||||
ctypes.c_longlong, # orderIndex
|
||||
ctypes.c_longlong, # nonce
|
||||
ctypes.c_int, # apiKeyIndex
|
||||
ctypes.c_longlong, # accountIndex
|
||||
]
|
||||
LIB.SignCancelOrder.restype = SignedTxResponse
|
||||
|
||||
LIB.SignCancelAllOrders.argtypes = [ctypes.c_int, ctypes.c_longlong, ctypes.c_longlong]
|
||||
LIB.SignCancelAllOrders.restype = StrOrErr
|
||||
LIB.SignCancelAllOrders.argtypes = [
|
||||
ctypes.c_int, # timeInForce
|
||||
ctypes.c_longlong, # scheduledTime
|
||||
ctypes.c_longlong, # nonce
|
||||
ctypes.c_int, # apiKeyIndex
|
||||
ctypes.c_longlong, # accountIndex
|
||||
]
|
||||
LIB.SignCancelAllOrders.restype = SignedTxResponse
|
||||
|
||||
LIB.CreateAuthToken.argtypes = [ctypes.c_longlong]
|
||||
LIB.CreateAuthToken.argtypes = [ctypes.c_longlong, ctypes.c_int, ctypes.c_longlong]
|
||||
LIB.CreateAuthToken.restype = StrOrErr
|
||||
|
||||
|
||||
def _unwrap(result: StrOrErr) -> Dict[str, Any]:
|
||||
if isinstance(result, SignedTxResponse):
|
||||
if result.err:
|
||||
return {"error": ctypes.string_at(result.err).decode("utf-8", errors="replace")}
|
||||
tx_info = ctypes.string_at(result.txInfo).decode("utf-8", errors="replace") if result.txInfo else None
|
||||
tx_hash = ctypes.string_at(result.txHash).decode("utf-8", errors="replace") if result.txHash else None
|
||||
msg = ctypes.string_at(result.messageToSign).decode("utf-8", errors="replace") if result.messageToSign else None
|
||||
return {"result": tx_info, "txHash": tx_hash, "messageToSign": msg}
|
||||
if result.err:
|
||||
return {"error": ctypes.string_at(result.err).decode("utf-8", errors="replace")}
|
||||
if result.str:
|
||||
@@ -119,9 +148,6 @@ def _ensure_client(params: Dict[str, Any]) -> Dict[str, Any]:
|
||||
if config is None:
|
||||
return {"error": "client_not_initialized"}
|
||||
|
||||
if api_key_index in _INITIALISED_KEYS:
|
||||
return {"result": "ok"}
|
||||
|
||||
err_ptr = LIB.CreateClient(
|
||||
config["baseUrl"].encode("utf-8"),
|
||||
config["privateKey"].encode("utf-8"),
|
||||
@@ -132,14 +158,13 @@ def _ensure_client(params: Dict[str, Any]) -> Dict[str, Any]:
|
||||
outcome = _maybe_error(err_ptr)
|
||||
if "error" in outcome:
|
||||
return outcome
|
||||
|
||||
_INITIALISED_KEYS.add(api_key_index)
|
||||
return {"result": "ok"}
|
||||
|
||||
|
||||
def _switch_api_key(api_key_index: int) -> Dict[str, Any]:
|
||||
err_ptr = LIB.SwitchAPIKey(ctypes.c_int(api_key_index))
|
||||
return _maybe_error(err_ptr)
|
||||
# No-op with new signer (apiKeyIndex is passed to each call)
|
||||
return {"result": "ok"}
|
||||
|
||||
|
||||
def handle_create_client(params: Dict[str, Any]) -> Dict[str, Any]:
|
||||
@@ -152,10 +177,6 @@ def handle_sign_create_order(params: Dict[str, Any]) -> Dict[str, Any]:
|
||||
return ensure
|
||||
|
||||
api_key_index = int(params["apiKeyIndex"])
|
||||
switched = _switch_api_key(api_key_index)
|
||||
if "error" in switched:
|
||||
return switched
|
||||
|
||||
expiry = int(params["orderExpiry"])
|
||||
result = LIB.SignCreateOrder(
|
||||
ctypes.c_int(int(params["marketIndex"])),
|
||||
@@ -169,6 +190,8 @@ def handle_sign_create_order(params: Dict[str, Any]) -> Dict[str, Any]:
|
||||
ctypes.c_int(int(params["triggerPrice"])),
|
||||
ctypes.c_longlong(expiry),
|
||||
ctypes.c_longlong(int(params["nonce"])),
|
||||
ctypes.c_int(api_key_index),
|
||||
ctypes.c_longlong(int(params["accountIndex"])),
|
||||
)
|
||||
return _unwrap(result)
|
||||
|
||||
@@ -179,14 +202,12 @@ def handle_sign_cancel_order(params: Dict[str, Any]) -> Dict[str, Any]:
|
||||
return ensure
|
||||
|
||||
api_key_index = int(params["apiKeyIndex"])
|
||||
switched = _switch_api_key(api_key_index)
|
||||
if "error" in switched:
|
||||
return switched
|
||||
|
||||
result = LIB.SignCancelOrder(
|
||||
ctypes.c_int(int(params["marketIndex"])),
|
||||
ctypes.c_longlong(int(params["orderIndex"])),
|
||||
ctypes.c_longlong(int(params["nonce"])),
|
||||
ctypes.c_int(api_key_index),
|
||||
ctypes.c_longlong(int(params["accountIndex"])),
|
||||
)
|
||||
return _unwrap(result)
|
||||
|
||||
@@ -197,14 +218,12 @@ def handle_sign_cancel_all(params: Dict[str, Any]) -> Dict[str, Any]:
|
||||
return ensure
|
||||
|
||||
api_key_index = int(params["apiKeyIndex"])
|
||||
switched = _switch_api_key(api_key_index)
|
||||
if "error" in switched:
|
||||
return switched
|
||||
|
||||
result = LIB.SignCancelAllOrders(
|
||||
ctypes.c_int(int(params["timeInForce"])),
|
||||
ctypes.c_longlong(int(params["scheduledTime"])),
|
||||
ctypes.c_longlong(int(params["nonce"])),
|
||||
ctypes.c_int(api_key_index),
|
||||
ctypes.c_longlong(int(params["accountIndex"])),
|
||||
)
|
||||
return _unwrap(result)
|
||||
|
||||
@@ -215,11 +234,12 @@ def handle_create_auth_token(params: Dict[str, Any]) -> Dict[str, Any]:
|
||||
return ensure
|
||||
|
||||
api_key_index = int(params["apiKeyIndex"])
|
||||
switched = _switch_api_key(api_key_index)
|
||||
if "error" in switched:
|
||||
return switched
|
||||
|
||||
result = LIB.CreateAuthToken(ctypes.c_longlong(int(params["deadlineMs"])))
|
||||
result = LIB.CreateAuthToken(
|
||||
ctypes.c_longlong(int(params["deadlineMs"])),
|
||||
ctypes.c_int(api_key_index),
|
||||
ctypes.c_longlong(int(params["accountIndex"])),
|
||||
)
|
||||
return _unwrap(result)
|
||||
|
||||
|
||||
|
||||
@@ -48,7 +48,7 @@ export function toTicker(symbol: string, stats: LighterMarketStats): AsterTicker
|
||||
volume: stats.daily_base_token_volume != null ? String(stats.daily_base_token_volume) : "0",
|
||||
quoteVolume: stats.daily_quote_token_volume != null ? String(stats.daily_quote_token_volume) : "0",
|
||||
priceChange: stats.daily_price_change != null ? String(stats.daily_price_change) : undefined,
|
||||
markPrice: undefined,
|
||||
markPrice: stats.mid_price ?? stats.mark_price ?? stats.index_price,
|
||||
weightedAvgPrice: undefined,
|
||||
} as AsterTicker;
|
||||
}
|
||||
@@ -163,7 +163,15 @@ export function toAccountSnapshot(
|
||||
details: LighterAccountDetails,
|
||||
positions: LighterPosition[] = [],
|
||||
assets: AsterAccountAsset[] = [],
|
||||
options?: { marketSymbol?: string | null; marketId?: number | null }
|
||||
options?: {
|
||||
marketSymbol?: string | null;
|
||||
marketId?: number | null;
|
||||
marketType?: string | null;
|
||||
baseAssetSymbol?: string | null;
|
||||
quoteAssetSymbol?: string | null;
|
||||
baseAssetId?: number | null;
|
||||
quoteAssetId?: number | null;
|
||||
}
|
||||
): AsterAccountSnapshot {
|
||||
const targetSymbol = options?.marketSymbol ?? null;
|
||||
const targetMarketId =
|
||||
@@ -184,24 +192,46 @@ export function toAccountSnapshot(
|
||||
return true;
|
||||
});
|
||||
const transformedPositions = filteredPositions.map((position) => lighterPositionToAster(symbol, position));
|
||||
if (!transformedPositions.length && normalizeMarketType(options?.marketType) === "spot") {
|
||||
const baseSymbol = options?.baseAssetSymbol ?? options?.marketSymbol ?? symbol;
|
||||
const baseAsset = findAsset(assets, baseSymbol);
|
||||
const baseSize = Number(baseAsset?.walletBalance ?? 0);
|
||||
if (Number.isFinite(baseSize) && baseSize > 0) {
|
||||
transformedPositions.push({
|
||||
symbol,
|
||||
positionAmt: baseSize.toString(),
|
||||
entryPrice: "0",
|
||||
unrealizedProfit: "0",
|
||||
positionSide: "BOTH",
|
||||
updateTime: Date.now(),
|
||||
});
|
||||
}
|
||||
}
|
||||
const aggregateUnrealized = transformedPositions.reduce((acc, pos) => acc + Number(pos.unrealizedProfit ?? 0), 0);
|
||||
const assetList = assets.length ? assets : defaultAsset(details);
|
||||
const assetList = assets.length ? assets : defaultAsset(details, options?.quoteAssetSymbol ?? "USDC");
|
||||
const totalWallet = computeTotalWalletBalance(assetList, details);
|
||||
return {
|
||||
canTrade: details.status !== 0,
|
||||
canDeposit: true,
|
||||
canWithdraw: true,
|
||||
updateTime: Date.now(),
|
||||
totalWalletBalance: details.collateral ?? "0",
|
||||
totalWalletBalance: totalWallet,
|
||||
availableBalance: details.available_balance ?? undefined,
|
||||
totalUnrealizedProfit: aggregateUnrealized.toFixed(8),
|
||||
positions: transformedPositions,
|
||||
assets: assetList,
|
||||
marketType: normalizeMarketType(options?.marketType),
|
||||
baseAsset: options?.baseAssetSymbol ?? undefined,
|
||||
quoteAsset: options?.quoteAssetSymbol ?? undefined,
|
||||
baseAssetId: options?.baseAssetId ?? undefined,
|
||||
quoteAssetId: options?.quoteAssetId ?? undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function defaultAsset(details: LighterAccountDetails): AsterAccountAsset[] {
|
||||
function defaultAsset(details: LighterAccountDetails, quoteAsset: string): AsterAccountAsset[] {
|
||||
return [
|
||||
{
|
||||
asset: "USDC",
|
||||
asset: quoteAsset || "USDC",
|
||||
walletBalance: details.collateral ?? "0",
|
||||
availableBalance: details.available_balance ?? details.collateral ?? "0",
|
||||
updateTime: Date.now(),
|
||||
@@ -209,6 +239,28 @@ function defaultAsset(details: LighterAccountDetails): AsterAccountAsset[] {
|
||||
];
|
||||
}
|
||||
|
||||
function computeTotalWalletBalance(assets: AsterAccountAsset[], details: LighterAccountDetails): string {
|
||||
const sum = assets.reduce((acc, asset) => acc + Number(asset.walletBalance ?? 0), 0);
|
||||
if (Number.isFinite(sum) && sum > 0) {
|
||||
return sum.toString();
|
||||
}
|
||||
return details.total_asset_value ?? details.collateral ?? "0";
|
||||
}
|
||||
|
||||
function findAsset(assets: AsterAccountAsset[], target: string | undefined | null): AsterAccountAsset | undefined {
|
||||
if (!target) return undefined;
|
||||
const normalizedTarget = target.toUpperCase().split(/[-:/]/)[0];
|
||||
return assets.find((asset) => asset.asset.toUpperCase().split(/[-:/]/)[0] === normalizedTarget);
|
||||
}
|
||||
|
||||
function normalizeMarketType(value: string | null | undefined): "perp" | "spot" | undefined {
|
||||
if (!value) return undefined;
|
||||
const normalized = value.toLowerCase();
|
||||
if (normalized === "spot") return "spot";
|
||||
if (normalized === "perp" || normalized === "perpetual" || normalized === "futures") return "perp";
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function lighterPositionToAster(symbol: string, position: LighterPosition): AsterAccountPosition {
|
||||
const sign = position.sign ?? 0;
|
||||
const positionSide = sign > 0 ? "LONG" : sign < 0 ? "SHORT" : "BOTH";
|
||||
|
||||
@@ -67,6 +67,20 @@ export class HttpNonceManager implements LighterNonceManager {
|
||||
this.slots.set(apiKeyIndex, { apiKeyIndex, next: nonce, lastIssued: null });
|
||||
}
|
||||
|
||||
nextFor(apiKeyIndex: number): { apiKeyIndex: number; nonce: bigint } {
|
||||
if (!this.slots.size) {
|
||||
throw new Error("Nonce manager not initialized");
|
||||
}
|
||||
const slot = this.slots.get(apiKeyIndex);
|
||||
if (!slot) {
|
||||
throw new Error(`Nonce slot for API key index ${apiKeyIndex} is not initialized`);
|
||||
}
|
||||
const nonce = slot.next;
|
||||
slot.lastIssued = nonce;
|
||||
slot.next = nonce + 1n;
|
||||
return { apiKeyIndex, nonce };
|
||||
}
|
||||
|
||||
private async refreshAll(force: boolean): Promise<void> {
|
||||
await Promise.all(
|
||||
this.apiKeyIndices.map(async (index) => {
|
||||
|
||||
@@ -194,6 +194,7 @@ export class LighterSigner {
|
||||
triggerPrice: params.triggerPrice,
|
||||
orderExpiry: params.orderExpiry.toString(),
|
||||
nonce: params.nonce.toString(),
|
||||
accountIndex: this.accountIndex.toString(),
|
||||
});
|
||||
|
||||
const txInfo = String(result);
|
||||
@@ -224,6 +225,7 @@ export class LighterSigner {
|
||||
marketIndex: params.marketIndex,
|
||||
orderIndex: params.orderIndex.toString(),
|
||||
nonce: params.nonce.toString(),
|
||||
accountIndex: this.accountIndex.toString(),
|
||||
});
|
||||
|
||||
const txInfo = String(result);
|
||||
@@ -251,6 +253,7 @@ export class LighterSigner {
|
||||
timeInForce: params.timeInForce,
|
||||
scheduledTime: params.scheduledTime.toString(),
|
||||
nonce: params.nonce.toString(),
|
||||
accountIndex: this.accountIndex.toString(),
|
||||
});
|
||||
|
||||
const txInfo = String(result);
|
||||
@@ -275,6 +278,7 @@ export class LighterSigner {
|
||||
const result = await this.bridge.call("create_auth_token", {
|
||||
apiKeyIndex: index,
|
||||
deadlineMs: Math.floor(deadlineMs / 1000),
|
||||
accountIndex: this.accountIndex.toString(),
|
||||
});
|
||||
return String(result ?? "");
|
||||
}
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -54,7 +54,10 @@ export interface LighterPosition {
|
||||
export interface LighterAccountDetails {
|
||||
collateral: string;
|
||||
available_balance?: string;
|
||||
total_asset_value?: string;
|
||||
cross_asset_value?: string;
|
||||
total_order_count?: number;
|
||||
assets?: LighterAccountAsset[];
|
||||
positions?: LighterPosition[];
|
||||
status?: number;
|
||||
account_index: number;
|
||||
@@ -64,6 +67,13 @@ export interface LighterAccountDetails {
|
||||
pending_order_count?: number;
|
||||
}
|
||||
|
||||
export interface LighterAccountAsset {
|
||||
symbol: string;
|
||||
asset_id?: number;
|
||||
balance: string | number;
|
||||
locked_balance?: string | number;
|
||||
}
|
||||
|
||||
export interface LighterAuthToken {
|
||||
token: string;
|
||||
expiresAt: number;
|
||||
@@ -85,10 +95,12 @@ export interface LighterOrderBookSnapshot {
|
||||
export interface LighterMarketStats {
|
||||
market_id: number;
|
||||
index_price: string;
|
||||
mark_price: string;
|
||||
open_interest: string;
|
||||
mark_price?: string;
|
||||
mid_price?: string;
|
||||
open_interest?: string;
|
||||
last_trade_price: string;
|
||||
symbol?: string;
|
||||
market_type?: "perp" | "spot" | string;
|
||||
current_funding_rate?: string;
|
||||
funding_rate?: string;
|
||||
funding_timestamp?: number;
|
||||
@@ -114,6 +126,9 @@ export interface LighterKline {
|
||||
export interface LighterOrderBookMetadata {
|
||||
symbol: string;
|
||||
market_id: number;
|
||||
market_type?: "perp" | "spot" | string;
|
||||
base_asset_id?: number;
|
||||
quote_asset_id?: number;
|
||||
maker_fee: string;
|
||||
taker_fee: string;
|
||||
min_base_amount: string;
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { AsterCredentials } from "./aster-adapter";
|
||||
import type { LighterCredentials } from "./lighter/adapter";
|
||||
import type { BackpackCredentials } from "./backpack/adapter";
|
||||
import type { ParadexCredentials } from "./paradex/adapter";
|
||||
import { t } from "../i18n";
|
||||
|
||||
interface BuildAdapterOptions {
|
||||
symbol: string;
|
||||
@@ -41,7 +42,7 @@ function resolveAsterCredentials(): AsterCredentials {
|
||||
const apiKey = process.env.ASTER_API_KEY;
|
||||
const apiSecret = process.env.ASTER_API_SECRET;
|
||||
if (!apiKey || !apiSecret) {
|
||||
throw new Error("缺少 ASTER_API_KEY 或 ASTER_API_SECRET 环境变量");
|
||||
throw new Error(t("env.missingAster"));
|
||||
}
|
||||
return { apiKey, apiSecret };
|
||||
}
|
||||
@@ -50,11 +51,11 @@ function resolveLighterCredentials(symbol: string): LighterCredentials {
|
||||
const accountIndexRaw = process.env.LIGHTER_ACCOUNT_INDEX;
|
||||
const apiPrivateKey = process.env.LIGHTER_API_PRIVATE_KEY;
|
||||
if (!accountIndexRaw || !apiPrivateKey) {
|
||||
throw new Error("缺少 LIGHTER_ACCOUNT_INDEX 或 LIGHTER_API_PRIVATE_KEY 环境变量");
|
||||
throw new Error(t("env.missingLighter"));
|
||||
}
|
||||
const accountIndex = Number(accountIndexRaw);
|
||||
if (!Number.isInteger(accountIndex)) {
|
||||
throw new Error("LIGHTER_ACCOUNT_INDEX 必须是整数");
|
||||
throw new Error(t("env.lighterIndexInteger"));
|
||||
}
|
||||
const credentials: LighterCredentials = {
|
||||
displaySymbol: symbol,
|
||||
@@ -76,7 +77,7 @@ function resolveBackpackCredentials(symbol: string): BackpackCredentials {
|
||||
const apiKey = process.env.BACKPACK_API_KEY;
|
||||
const apiSecret = process.env.BACKPACK_API_SECRET;
|
||||
if (!apiKey || !apiSecret) {
|
||||
throw new Error("缺少 BACKPACK_API_KEY 或 BACKPACK_API_SECRET 环境变量");
|
||||
throw new Error(t("env.missingBackpack"));
|
||||
}
|
||||
const credentials: BackpackCredentials = {
|
||||
apiKey,
|
||||
@@ -94,13 +95,13 @@ function resolveParadexCredentials(): ParadexCredentials {
|
||||
const walletAddress = process.env.PARADEX_WALLET_ADDRESS;
|
||||
|
||||
if (!privateKey || !walletAddress) {
|
||||
throw new Error("Paradex 需要配置 PARADEX_PRIVATE_KEY 与 PARADEX_WALLET_ADDRESS");
|
||||
throw new Error(t("env.missingParadex"));
|
||||
}
|
||||
if (!isHex32(privateKey)) {
|
||||
throw new Error("PARADEX_PRIVATE_KEY 必须是 0x 开头的 32 字节十六进制字符串");
|
||||
throw new Error(t("env.invalidParadexPrivateKey"));
|
||||
}
|
||||
if (!isHexAddress(walletAddress)) {
|
||||
throw new Error("PARADEX_WALLET_ADDRESS 必须是有效的 0x 开头 40 字节十六进制地址");
|
||||
throw new Error(t("env.invalidParadexAddress"));
|
||||
}
|
||||
|
||||
const credentials: ParadexCredentials = {
|
||||
|
||||
@@ -256,6 +256,7 @@ export interface AsterAccountAsset {
|
||||
walletBalance: string;
|
||||
availableBalance: string;
|
||||
updateTime: number;
|
||||
assetId?: number;
|
||||
unrealizedProfit?: string;
|
||||
marginBalance?: string;
|
||||
maintMargin?: string;
|
||||
@@ -286,6 +287,11 @@ export interface AsterAccountSnapshot {
|
||||
maxWithdrawAmount?: string;
|
||||
positions: AsterAccountPosition[];
|
||||
assets: AsterAccountAsset[];
|
||||
marketType?: "perp" | "spot";
|
||||
baseAsset?: string;
|
||||
quoteAsset?: string;
|
||||
baseAssetId?: number;
|
||||
quoteAssetId?: number;
|
||||
}
|
||||
|
||||
export interface AsterDepthLevel extends Array<string> {
|
||||
|
||||
@@ -0,0 +1,629 @@
|
||||
export type Language = "zh" | "en";
|
||||
|
||||
const normalizeLanguage = (value: string | undefined): Language => {
|
||||
if (!value) return "zh";
|
||||
const normalized = value.trim().toLowerCase();
|
||||
if (normalized === "en" || normalized.startsWith("en-") || normalized.startsWith("en_")) return "en";
|
||||
if (normalized === "zh" || normalized.startsWith("zh")) return "zh";
|
||||
if (normalized === "english") return "en";
|
||||
if (normalized === "chinese") return "zh";
|
||||
return "zh";
|
||||
};
|
||||
|
||||
export const language: Language = normalizeLanguage(process.env.LANG);
|
||||
|
||||
type TranslationValue = string | ((params: Record<string, unknown>, lang: Language) => string);
|
||||
|
||||
type TranslationEntry = {
|
||||
zh: TranslationValue;
|
||||
en: TranslationValue;
|
||||
};
|
||||
|
||||
const translations: Record<string, TranslationEntry> = {
|
||||
"app.strategy.trend.label": { zh: "趋势跟随策略 (SMA30)", en: "Trend Following (SMA30)" },
|
||||
"app.strategy.trend.desc": {
|
||||
zh: "监控均线信号,自动进出场并维护止损/止盈",
|
||||
en: "Monitors SMA signals, automates entries/exits, maintains stops.",
|
||||
},
|
||||
"app.strategy.guardian.label": { zh: "Guardian 防守策略", en: "Guardian Protection" },
|
||||
"app.strategy.guardian.desc": {
|
||||
zh: "不主动开仓,只为现有仓位补挂/移动止损,防止裸奔",
|
||||
en: "Does not open positions; only manages stops for existing positions.",
|
||||
},
|
||||
"app.strategy.maker.label": { zh: "做市刷单策略", en: "Maker Market Making" },
|
||||
"app.strategy.maker.desc": {
|
||||
zh: "双边挂单提供流动性,自动追价与风控止损",
|
||||
en: "Places two-sided quotes, auto-chases and risk-manages stops.",
|
||||
},
|
||||
"app.strategy.grid.label": { zh: "基础网格策略", en: "Grid Strategy" },
|
||||
"app.strategy.grid.desc": {
|
||||
zh: "在上下边界之间布设等比网格,自动加仓与减仓",
|
||||
en: "Places geometric grids between bounds, auto scale-in/out.",
|
||||
},
|
||||
"app.strategy.offset.label": { zh: "偏移做市策略", en: "Offset Maker Strategy" },
|
||||
"app.strategy.offset.desc": {
|
||||
zh: "根据盘口深度自动偏移挂单并在极端不平衡时撤退",
|
||||
en: "Offsets quotes by depth, retreats on extreme imbalance.",
|
||||
},
|
||||
"app.strategy.basis.label": { zh: "期现套利策略", en: "Basis Arbitrage" },
|
||||
"app.strategy.basis.desc": {
|
||||
zh: "监控期货与现货盘口差价,辅助发现套利机会",
|
||||
en: "Monitors futures/spot spread to surface arbitrage windows.",
|
||||
},
|
||||
"app.integrity.warning": {
|
||||
zh: "警告: 版权校验失败,当前版本可能被篡改。",
|
||||
en: "Warning: Copyright integrity check failed; build may be tampered.",
|
||||
},
|
||||
"app.pickStrategy": { zh: "请选择要运行的策略", en: "Select a strategy to run" },
|
||||
"app.pickHint": {
|
||||
zh: "使用 ↑/↓ 选择,回车开始,Ctrl+C 退出。",
|
||||
en: "Use ↑/↓ to choose, Enter to start, Ctrl+C to exit.",
|
||||
},
|
||||
"common.waiting": { zh: "等待", en: "Waiting" },
|
||||
"common.startFailed": { zh: "启动失败: {message}", en: "Failed to start: {message}" },
|
||||
"common.checkEnv": {
|
||||
zh: "请检查环境变量和网络连通性。",
|
||||
en: "Please check environment variables and network connectivity.",
|
||||
},
|
||||
"common.initializing": { zh: "正在初始化{target}…", en: "Initializing {target}..." },
|
||||
"common.statusWithBack": {
|
||||
zh: "状态: {status} | 按 Esc 返回策略选择",
|
||||
en: "Status: {status} | Press Esc to return to menu.",
|
||||
},
|
||||
"common.backHint": { zh: "按 Esc 返回策略选择", en: "Press Esc to return to menu." },
|
||||
"common.section.position": { zh: "持仓", en: "Position" },
|
||||
"common.section.performance": { zh: "绩效", en: "Performance" },
|
||||
"common.section.orders": { zh: "当前挂单", en: "Open Orders" },
|
||||
"common.section.recent": { zh: "最近事件", en: "Recent Events" },
|
||||
"common.section.recentTrades": { zh: "最近交易与事件", en: "Recent Trades & Events" },
|
||||
"common.noPosition": { zh: "当前无持仓", en: "No open position" },
|
||||
"common.noOrders": { zh: "暂无挂单", en: "No open orders" },
|
||||
"common.noLogs": { zh: "暂无日志", en: "No logs yet" },
|
||||
"common.direction.long": { zh: "多", en: "Long" },
|
||||
"common.direction.short": { zh: "空", en: "Short" },
|
||||
"common.enabled": { zh: "启用", en: "Enabled" },
|
||||
"common.disabled": { zh: "关闭", en: "Disabled" },
|
||||
"status.live": { zh: "实时运行", en: "Live" },
|
||||
"status.running": { zh: "运行中", en: "Running" },
|
||||
"status.paused": { zh: "暂停", en: "Paused" },
|
||||
"status.waitingData": { zh: "等待市场数据", en: "Waiting for market data" },
|
||||
"trend.name": { zh: "趋势策略", en: "trend strategy" },
|
||||
"trend.title": { zh: "趋势策略仪表盘", en: "Trend Strategy Dashboard" },
|
||||
"trend.headerLine": {
|
||||
zh: "交易所: {exchange} | 交易对: {symbol} | 最近价格: {lastPrice} | SMA30: {sma} | 趋势: {trend}",
|
||||
en: "Exchange: {exchange} | Symbol: {symbol} | Last: {lastPrice} | SMA30: {sma} | Trend: {trend}",
|
||||
},
|
||||
"trend.statusLine": {
|
||||
zh: "状态: {status} | 按 Esc 返回策略选择",
|
||||
en: "Status: {status} | Press Esc to return to menu.",
|
||||
},
|
||||
"trend.positionLine": {
|
||||
zh: "方向: {direction} | 数量: {qty} | 开仓价: {entry}",
|
||||
en: "Direction: {direction} | Size: {qty} | Entry: {entry}",
|
||||
},
|
||||
"trend.pnlLine": {
|
||||
zh: "浮动盈亏: {pnl} USDT | 账户未实现盈亏: {unrealized} USDT",
|
||||
en: "Floating PnL: {pnl} USDT | Account Unrealized: {unrealized} USDT",
|
||||
},
|
||||
"trend.performanceLine": {
|
||||
zh: "累计交易次数: {trades} | 累计收益: {profit} USDT",
|
||||
en: "Total trades: {trades} | Total profit: {profit} USDT",
|
||||
},
|
||||
"trend.volumeLine": { zh: "累计成交量: {volume} USDT", en: "Total volume: {volume} USDT" },
|
||||
"trend.lastSignal": {
|
||||
zh: "最近开仓信号: {side} @ {price}",
|
||||
en: "Last entry signal: {side} @ {price}",
|
||||
},
|
||||
"trend.readyMessage": { zh: "正在等待交易所推送数据…", en: "Waiting for exchange feeds..." },
|
||||
"trend.label.long": { zh: "做多", en: "Long" },
|
||||
"trend.label.short": { zh: "做空", en: "Short" },
|
||||
"trend.label.none": { zh: "无信号", en: "No signal" },
|
||||
"guardian.name": { zh: "Guardian 策略", en: "Guardian strategy" },
|
||||
"guardian.title": { zh: "Guardian 策略仪表盘", en: "Guardian Strategy Dashboard" },
|
||||
"guardian.readyMessage": { zh: "正在等待行情/账户推送…", en: "Waiting for market/account feeds..." },
|
||||
"guardian.startFailed": {
|
||||
zh: "Guardian 策略启动失败: {message}",
|
||||
en: "Guardian strategy failed to start: {message}",
|
||||
},
|
||||
"guardian.initializing": { zh: "正在初始化 Guardian 策略…", en: "Initializing Guardian strategy..." },
|
||||
"guardian.headerLine": {
|
||||
zh: "交易所: {exchange} | 交易对: {symbol} | 最近价格: {lastPrice} | 状态: {status}",
|
||||
en: "Exchange: {exchange} | Symbol: {symbol} | Last: {lastPrice} | Status: {status}",
|
||||
},
|
||||
"guardian.hint": {
|
||||
zh: "策略只会维护止损/止盈,不会主动开仓。按 Esc 返回菜单。",
|
||||
en: "Maintains stops/take-profit only; does not open positions. Press Esc to return.",
|
||||
},
|
||||
"guardian.positionTitle": { zh: "当前仓位与风控", en: "Position & Protection" },
|
||||
"guardian.positionLine": {
|
||||
zh: "方向: {direction} | 数量: {qty} | 开仓价: {entry} | 浮动盈亏: {pnl} USDT",
|
||||
en: "Direction: {direction} | Size: {qty} | Entry: {entry} | Floating PnL: {pnl} USDT",
|
||||
},
|
||||
"guardian.stopLine": {
|
||||
zh: "目标止损价: {targetStop} | 当前止损单: {stopOrder} | 动态止盈触发: {trailingTrigger} | 动态止盈单: {trailingOrder}",
|
||||
en: "Target stop: {targetStop} | Active stop: {stopOrder} | Trailing trigger: {trailingTrigger} | Trailing order: {trailingOrder}",
|
||||
},
|
||||
"guardian.status.protecting": { zh: "已挂止损", en: "Stop placed" },
|
||||
"guardian.status.pending": { zh: "缺少止损,正在同步", en: "Missing stop, syncing" },
|
||||
"guardian.status.listening": { zh: "监听中", en: "Listening" },
|
||||
"guardian.stateLabel": { zh: "Guardian 状态: {state}", en: "Guardian status: {state}" },
|
||||
"guardian.noPosition": {
|
||||
zh: "当前无持仓,Guardian 正在监听新的仓位变化。",
|
||||
en: "No open position; Guardian is listening for new positions.",
|
||||
},
|
||||
"guardian.noProtectiveOrders": { zh: "暂无保护类挂单", en: "No protective orders" },
|
||||
"maker.name": { zh: "做市策略", en: "market-making strategy" },
|
||||
"maker.title": { zh: "做市策略仪表盘", en: "Maker Strategy Dashboard" },
|
||||
"maker.initializing": { zh: "正在初始化做市策略…", en: "Initializing maker strategy..." },
|
||||
"maker.headerLine": {
|
||||
zh: "交易所: {exchange} | 交易对: {symbol} | 买一价: {bid} | 卖一价: {ask} | 点差: {spread}",
|
||||
en: "Exchange: {exchange} | Symbol: {symbol} | Best Bid: {bid} | Best Ask: {ask} | Spread: {spread}",
|
||||
},
|
||||
"maker.dataStatus": { zh: "数据状态:", en: "Data status:" },
|
||||
"maker.feed.account": { zh: "账户", en: "Account" },
|
||||
"maker.feed.orders": { zh: "订单", en: "Orders" },
|
||||
"maker.feed.depth": { zh: "深度", en: "Depth" },
|
||||
"maker.feed.ticker": { zh: "Ticker", en: "Ticker" },
|
||||
"maker.positionLine": {
|
||||
zh: "方向: {direction} | 数量: {qty} | 开仓价: {entry}",
|
||||
en: "Direction: {direction} | Size: {qty} | Entry: {entry}",
|
||||
},
|
||||
"maker.pnlLine": {
|
||||
zh: "浮动盈亏: {pnl} USDT | 账户未实现盈亏: {accountPnl} USDT",
|
||||
en: "Floating PnL: {pnl} USDT | Account Unrealized: {accountPnl} USDT",
|
||||
},
|
||||
"maker.targetOrders": { zh: "目标挂单", en: "Target Orders" },
|
||||
"maker.noTargetOrders": { zh: "暂无目标挂单", en: "No target orders" },
|
||||
"offset.name": { zh: "偏移做市策略", en: "offset maker strategy" },
|
||||
"offset.title": { zh: "偏移做市策略仪表盘", en: "Offset Maker Strategy Dashboard" },
|
||||
"offset.initializing": { zh: "正在初始化偏移做市策略…", en: "Initializing offset maker strategy..." },
|
||||
"offset.headerLine": {
|
||||
zh: "交易所: {exchange} | 交易对: {symbol} | 买一价: {bid} | 卖一价: {ask} | 点差: {spread}",
|
||||
en: "Exchange: {exchange} | Symbol: {symbol} | Best Bid: {bid} | Best Ask: {ask} | Spread: {spread}",
|
||||
},
|
||||
"offset.depthLine": {
|
||||
zh: "买10档累计: {buy} | 卖10档累计: {sell} | 状态: {status}",
|
||||
en: "Top 10 bid sum: {buy} | Top 10 ask sum: {sell} | Status: {status}",
|
||||
},
|
||||
"offset.strategyStatus": {
|
||||
zh: "当前挂单策略: BUY {buyStatus} | SELL {sellStatus} | 按 Esc 返回策略选择",
|
||||
en: "Quote status: BUY {buyStatus} | SELL {sellStatus} | Press Esc to return to menu",
|
||||
},
|
||||
"offset.imbalance.balanced": { zh: "均衡", en: "Balanced" },
|
||||
"offset.imbalance.buy": { zh: "买盘占优", en: "Bid dominant" },
|
||||
"offset.imbalance.sell": { zh: "卖盘占优", en: "Ask dominant" },
|
||||
"grid.name": { zh: "网格策略", en: "grid strategy" },
|
||||
"grid.title": { zh: "网格策略仪表盘", en: "Grid Strategy Dashboard" },
|
||||
"grid.initializing": { zh: "正在初始化网格策略…", en: "Initializing grid strategy..." },
|
||||
"grid.headerLine": {
|
||||
zh: "交易所: {exchange} | 交易对: {symbol} | 状态: {status} | 方向: {direction}",
|
||||
en: "Exchange: {exchange} | Symbol: {symbol} | Status: {status} | Direction: {direction}",
|
||||
},
|
||||
"grid.priceLine": {
|
||||
zh: "实时价格: {lastPrice} | 下界: {lower} | 上界: {upper} | 网格数量: {count}",
|
||||
en: "Last price: {lastPrice} | Lower: {lower} | Upper: {upper} | Grid count: {count}",
|
||||
},
|
||||
"grid.dataStatus": { zh: "数据状态:", en: "Data status:" },
|
||||
"grid.stopReason": { zh: "暂停原因: {reason}", en: "Pause reason: {reason}" },
|
||||
"grid.configTitle": { zh: "网格配置", en: "Grid Config" },
|
||||
"grid.configSize": {
|
||||
zh: "单笔数量: {orderSize} | 最大仓位: {maxPosition}",
|
||||
en: "Order size: {orderSize} | Max position: {maxPosition}",
|
||||
},
|
||||
"grid.configRisk": {
|
||||
zh: "止损阈值: {stopLoss}% | 重启阈值: {restart}% | 自动重启: {autoRestart}",
|
||||
en: "Stop loss: {stopLoss}% | Restart trigger: {restart}% | Auto restart: {autoRestart}",
|
||||
},
|
||||
"grid.refreshInterval": { zh: "刷新间隔: {interval} ms", en: "Refresh interval: {interval} ms" },
|
||||
"grid.positionLine": {
|
||||
zh: "当前持仓: {direction} | 数量: {qty} | 均价: {avgPrice}",
|
||||
en: "Position: {direction} | Size: {qty} | Avg price: {avgPrice}",
|
||||
},
|
||||
"grid.unrealizedLine": {
|
||||
zh: "未实现盈亏: {pnl} | 标记价: {mark}",
|
||||
en: "Unrealized PnL: {pnl} | Mark: {mark}",
|
||||
},
|
||||
"grid.linesTitle": { zh: "网格线", en: "Grid Lines" },
|
||||
"grid.noLines": { zh: "暂无网格线", en: "No grid lines" },
|
||||
"grid.direction.both": { zh: "双向", en: "Both" },
|
||||
"grid.direction.long": { zh: "多", en: "Long" },
|
||||
"grid.direction.short": { zh: "空", en: "Short" },
|
||||
"basis.onlyAster": {
|
||||
zh: "期现套利策略目前仅支持 Aster 交易所。请设置 EXCHANGE=aster 后重试。",
|
||||
en: "Basis arbitrage currently supports only Aster. Set EXCHANGE=aster and retry.",
|
||||
},
|
||||
"basis.startFailed": {
|
||||
zh: "无法启动期现套利策略: {message}",
|
||||
en: "Unable to start basis arbitrage: {message}",
|
||||
},
|
||||
"basis.initializing": { zh: "正在初始化期现套利监控…", en: "Initializing basis arbitrage monitor..." },
|
||||
"basis.title": { zh: "期现套利仪表盘", en: "Basis Arbitrage Dashboard" },
|
||||
"basis.headerLine": {
|
||||
zh: "交易所: {exchange} | 期货合约: {futures} | 现货交易对: {spot}",
|
||||
en: "Exchange: {exchange} | Futures: {futures} | Spot: {spot}",
|
||||
},
|
||||
"basis.statusLine": {
|
||||
zh: "按 Esc 返回策略选择 | 数据状态: 期货({futuresStatus}) 现货({spotStatus}) 资金费率({fundingStatus})",
|
||||
en: "Press Esc to return | Feeds: Futures({futuresStatus}) Spot({spotStatus}) Funding({fundingStatus})",
|
||||
},
|
||||
"basis.lastUpdated": { zh: "最近更新时间: {time}", en: "Last updated: {time}" },
|
||||
"basis.section.futures": { zh: "期货盘口", en: "Futures Book" },
|
||||
"basis.section.spot": { zh: "现货盘口", en: "Spot Book" },
|
||||
"basis.bookLine": { zh: "买一: {bid} | 卖一: {ask}", en: "Best bid: {bid} | Best ask: {ask}" },
|
||||
"basis.updatedAt": { zh: "更新时间: {time}", en: "Updated: {time}" },
|
||||
"basis.section.funding": { zh: "资金费率", en: "Funding" },
|
||||
"basis.fundingRate": { zh: "当前资金费率: {rate}", en: "Current funding rate: {rate}" },
|
||||
"basis.fundingTimes": {
|
||||
zh: "资金费率更新时间: {updated} | 下次结算时间: {next}",
|
||||
en: "Funding updated: {updated} | Next settlement: {next}",
|
||||
},
|
||||
"basis.fundingIncome": {
|
||||
zh: "单次资金费率收益(估): {per} | 日收益(估): {perDay}",
|
||||
en: "Est. income per funding: {per} | Est. daily income: {perDay}",
|
||||
},
|
||||
"basis.takerFees": {
|
||||
zh: "双边吃单手续费(估): {fees} | 回本所需资金费率次数: {count}",
|
||||
en: "Est. taker fees (round trip): {fees} | Funding counts to breakeven: {count}",
|
||||
},
|
||||
"basis.spotBalanceTitle": { zh: "现货账户余额(非0)", en: "Spot balances (non-zero)" },
|
||||
"basis.futuresBalanceTitle": { zh: "合约账户余额(非0)", en: "Futures balances (non-zero)" },
|
||||
"basis.balanceLine": { zh: "{asset}: 可用 {free} | 冻结 {locked}", en: "{asset}: Free {free} | Locked {locked}" },
|
||||
"basis.futuresBalanceLine": {
|
||||
zh: "{asset}: 钱包 {wallet} | 可用 {available}",
|
||||
en: "{asset}: Wallet {wallet} | Available {available}",
|
||||
},
|
||||
"basis.none": { zh: "无", en: "None" },
|
||||
"basis.spreadTitle": { zh: "套利差价(卖期货 / 买现货)", en: "Arb spread (sell futures / buy spot)" },
|
||||
"basis.spreadLine": { zh: "毛价差: {spread} USDT | {bps} bp", en: "Gross spread: {spread} USDT | {bps} bp" },
|
||||
"basis.netSpreadLine": {
|
||||
zh: "扣除 taker 手续费 ({feePct}% × 双边): {net} USDT | {netBps} bp",
|
||||
en: "Net after taker fee ({feePct}% x round trip): {net} USDT | {netBps} bp",
|
||||
},
|
||||
"rate.limit.suppress": {
|
||||
zh: "{source}限频期间暂停新开仓",
|
||||
en: "{source}Rate limit active, pausing new entries",
|
||||
},
|
||||
"rate.limit.resumeEntries": { zh: "限频恢复,允许重新开仓", en: "Rate limit cleared, resuming entries" },
|
||||
"rate.limit.pausedEnd": { zh: "限频暂停结束,继续以降频模式运行", en: "Pause ended; running in degraded mode" },
|
||||
"rate.limit.hit": {
|
||||
zh: "{source}触发 429,降频至 {interval}s",
|
||||
en: "{source}429 detected, slowing to {interval}s",
|
||||
},
|
||||
"rate.limit.consecutive": {
|
||||
zh: "{source}连续 429,暂停请求 {seconds}s",
|
||||
en: "{source}Consecutive 429s, pausing requests for {seconds}s",
|
||||
},
|
||||
"rate.limit.still": {
|
||||
zh: "{source}限频仍在持续,延长暂停 {seconds}s",
|
||||
en: "{source}Rate limit persists, extending pause {seconds}s",
|
||||
},
|
||||
"rate.limit.reset": { zh: "限频恢复,重置为正常请求频率", en: "Rate limit cleared, reset to normal cadence" },
|
||||
"env.missingAster": {
|
||||
zh: "缺少 ASTER_API_KEY 或 ASTER_API_SECRET 环境变量",
|
||||
en: "Missing ASTER_API_KEY or ASTER_API_SECRET",
|
||||
},
|
||||
"env.missingLighter": {
|
||||
zh: "缺少 LIGHTER_ACCOUNT_INDEX 或 LIGHTER_API_PRIVATE_KEY 环境变量",
|
||||
en: "Missing LIGHTER_ACCOUNT_INDEX or LIGHTER_API_PRIVATE_KEY",
|
||||
},
|
||||
"env.lighterIndexInteger": {
|
||||
zh: "LIGHTER_ACCOUNT_INDEX 必须是整数",
|
||||
en: "LIGHTER_ACCOUNT_INDEX must be an integer",
|
||||
},
|
||||
"env.missingBackpack": {
|
||||
zh: "缺少 BACKPACK_API_KEY 或 BACKPACK_API_SECRET 环境变量",
|
||||
en: "Missing BACKPACK_API_KEY or BACKPACK_API_SECRET",
|
||||
},
|
||||
"env.missingParadex": {
|
||||
zh: "Paradex 需要配置 PARADEX_PRIVATE_KEY 与 PARADEX_WALLET_ADDRESS",
|
||||
en: "Paradex requires PARADEX_PRIVATE_KEY and PARADEX_WALLET_ADDRESS",
|
||||
},
|
||||
"env.invalidParadexPrivateKey": {
|
||||
zh: "PARADEX_PRIVATE_KEY 必须是 0x 开头的 32 字节十六进制字符串",
|
||||
en: "PARADEX_PRIVATE_KEY must be a 0x-prefixed 32-byte hex string",
|
||||
},
|
||||
"env.invalidParadexAddress": {
|
||||
zh: "PARADEX_WALLET_ADDRESS 必须是有效的 0x 开头 40 字节十六进制地址",
|
||||
en: "PARADEX_WALLET_ADDRESS must be a valid 0x-prefixed 40-byte hex address",
|
||||
},
|
||||
"log.subscribe.accountFail": {
|
||||
zh: "订阅账户失败: {error}",
|
||||
en: "Failed to subscribe account: {error}",
|
||||
},
|
||||
"log.process.accountError": {
|
||||
zh: "账户推送处理异常: {error}",
|
||||
en: "Account stream processing error: {error}",
|
||||
},
|
||||
"log.subscribe.orderFail": {
|
||||
zh: "订阅订单失败: {error}",
|
||||
en: "Failed to subscribe orders: {error}",
|
||||
},
|
||||
"log.process.orderError": {
|
||||
zh: "订单推送处理异常: {error}",
|
||||
en: "Order stream processing error: {error}",
|
||||
},
|
||||
"log.subscribe.tickerFail": {
|
||||
zh: "订阅Ticker失败: {error}",
|
||||
en: "Failed to subscribe ticker: {error}",
|
||||
},
|
||||
"log.process.tickerError": {
|
||||
zh: "价格推送处理异常: {error}",
|
||||
en: "Price stream processing error: {error}",
|
||||
},
|
||||
"log.guardian.executeError": {
|
||||
zh: "Guardian 执行异常: {error}",
|
||||
en: "Guardian runtime error: {error}",
|
||||
},
|
||||
"log.guardian.entryPricePending": {
|
||||
zh: "持仓均价尚未同步,等待交易所账户快照更新后再补挂止损",
|
||||
en: "Entry price not synced yet; waiting for account snapshot before placing stop.",
|
||||
},
|
||||
"log.guardian.pricePending": {
|
||||
zh: "行情尚未就绪,等待最新价格以同步止损",
|
||||
en: "Market data not ready; waiting for latest price to sync stop.",
|
||||
},
|
||||
"log.guardian.placeStopFail": {
|
||||
zh: "挂止损单失败: {error}",
|
||||
en: "Failed to place stop order: {error}",
|
||||
},
|
||||
"log.guardian.stopMissingSkip": {
|
||||
zh: "原止损单已不存在,跳过撤销",
|
||||
en: "Existing stop missing, skipping cancel.",
|
||||
},
|
||||
"log.guardian.cancelStopFail": {
|
||||
zh: "取消原止损单失败: {error}",
|
||||
en: "Failed to cancel existing stop: {error}",
|
||||
},
|
||||
"log.guardian.moveStop": {
|
||||
zh: "移动止损到 {price}",
|
||||
en: "Moved stop to {price}",
|
||||
},
|
||||
"log.guardian.moveStopFail": {
|
||||
zh: "移动止损失败: {error}",
|
||||
en: "Failed to move stop: {error}",
|
||||
},
|
||||
"log.guardian.restoreStop": {
|
||||
zh: "恢复原止损 @ {price}",
|
||||
en: "Restored original stop @ {price}",
|
||||
},
|
||||
"log.guardian.restoreStopFail": {
|
||||
zh: "恢复原止损失败: {error}",
|
||||
en: "Failed to restore original stop: {error}",
|
||||
},
|
||||
"log.guardian.trailingFail": {
|
||||
zh: "挂动态止盈失败: {error}",
|
||||
en: "Failed to place trailing stop: {error}",
|
||||
},
|
||||
"log.guardian.cleanupOrders": {
|
||||
zh: "清理遗留保护单: {ids}",
|
||||
en: "Cleaning leftover protective orders: {ids}",
|
||||
},
|
||||
"log.guardian.protectiveMissing": {
|
||||
zh: "保护单已不存在,跳过清理",
|
||||
en: "Protective orders already gone; skipping cleanup.",
|
||||
},
|
||||
"log.guardian.cleanupFail": {
|
||||
zh: "清理保护单失败: {error}",
|
||||
en: "Failed to clean protective orders: {error}",
|
||||
},
|
||||
"log.guardian.dispatchError": {
|
||||
zh: "更新分发异常: {error}",
|
||||
en: "Update dispatch error: {error}",
|
||||
},
|
||||
"log.guardian.snapshotFail": {
|
||||
zh: "构建快照失败: {error}",
|
||||
en: "Failed to build snapshot: {error}",
|
||||
},
|
||||
"log.guardian.precisionSynced": {
|
||||
zh: "已同步交易精度: priceTick={priceTick} qtyStep={qtyStep}",
|
||||
en: "Synced precision: priceTick={priceTick} qtyStep={qtyStep}",
|
||||
},
|
||||
"log.guardian.precisionFailed": {
|
||||
zh: "同步精度失败: {error}",
|
||||
en: "Failed to sync precision: {error}",
|
||||
},
|
||||
"log.basis.subscribeFuturesDepthFail": {
|
||||
zh: "订阅期货深度失败: {error}",
|
||||
en: "Failed to subscribe futures depth: {error}",
|
||||
},
|
||||
"log.basis.processFuturesDepthError": {
|
||||
zh: "处理期货深度异常: {error}",
|
||||
en: "Error processing futures depth: {error}",
|
||||
},
|
||||
"log.basis.futuresReady": {
|
||||
zh: "期货深度已就绪 ({symbol})",
|
||||
en: "Futures depth ready ({symbol})",
|
||||
},
|
||||
"log.basis.spotDepthError": {
|
||||
zh: "获取现货盘口失败: {error}",
|
||||
en: "Failed to fetch spot orderbook: {error}",
|
||||
},
|
||||
"log.basis.fundingReady": {
|
||||
zh: "资金费率已就绪 ({symbol})",
|
||||
en: "Funding rate ready ({symbol})",
|
||||
},
|
||||
"log.basis.fundingError": {
|
||||
zh: "获取资金费率失败: {error}",
|
||||
en: "Failed to fetch funding rate: {error}",
|
||||
},
|
||||
"log.basis.spotBalanceError": {
|
||||
zh: "获取现货余额失败: {error}",
|
||||
en: "Failed to fetch spot balance: {error}",
|
||||
},
|
||||
"log.basis.futuresBalanceError": {
|
||||
zh: "获取合约余额失败: {error}",
|
||||
en: "Failed to fetch futures balance: {error}",
|
||||
},
|
||||
"log.basis.spotReady": { zh: "现货盘口已就绪 ({symbol})", en: "Spot orderbook ready ({symbol})" },
|
||||
"log.basis.pushError": { zh: "推送订阅失败: {error}", en: "Subscription push failed: {error}" },
|
||||
"log.basis.entryOpportunity": {
|
||||
zh: "入场机会: 扣费后价差 {bp} bp | 距下次资金费约 {minutes} 分钟",
|
||||
en: "Entry opportunity: net spread {bp} bp | ~{minutes} mins to next funding",
|
||||
},
|
||||
"log.basis.exitOpportunity": {
|
||||
zh: "出场机会: 资金费率为负 | 距收取约 {minutes} 分钟",
|
||||
en: "Exit opportunity: funding negative | ~{minutes} mins to settlement",
|
||||
},
|
||||
"log.account.snapshotSynced": { zh: "账户快照已同步", en: "Account snapshot synced" },
|
||||
"log.order.snapshotReturned": { zh: "订单快照已返回", en: "Order snapshot received" },
|
||||
"log.depth.ready": { zh: "获得最新深度行情", en: "Latest depth ready" },
|
||||
"log.ticker.ready": { zh: "Ticker 已就绪", en: "Ticker ready" },
|
||||
"log.subscribe.depthFail": { zh: "订阅深度失败: {error}", en: "Failed to subscribe depth: {error}" },
|
||||
"log.process.depthError": {
|
||||
zh: "深度推送处理异常: {error}",
|
||||
en: "Depth stream processing error: {error}",
|
||||
},
|
||||
"log.maker.loopError": { zh: "做市循环异常: {error}", en: "Maker loop error: {error}" },
|
||||
"log.maker.cleanOrdersStart": { zh: "启动时清理历史挂单", en: "Cleaning legacy orders at startup" },
|
||||
"log.maker.cleanOrdersMissing": {
|
||||
zh: "历史挂单已消失,跳过启动清理",
|
||||
en: "Legacy orders already gone, skipping startup cleanup",
|
||||
},
|
||||
"log.maker.cleanOrdersFail": { zh: "启动撤单失败: {error}", en: "Failed to cancel at startup: {error}" },
|
||||
"log.maker.cancelMismatched": {
|
||||
zh: "撤销不匹配订单 {side} @ {price} reduceOnly={reduceOnly}",
|
||||
en: "Cancel unmatched order {side} @ {price} reduceOnly={reduceOnly}",
|
||||
},
|
||||
"log.maker.cancelMissing": {
|
||||
zh: "撤销时发现订单已被成交/取消,忽略",
|
||||
en: "Order already filled/canceled, ignoring cancel",
|
||||
},
|
||||
"log.maker.cancelFail": { zh: "撤销订单失败: {error}", en: "Failed to cancel order: {error}" },
|
||||
"log.maker.placeFail": {
|
||||
zh: "挂单失败({side} {price}): {error}",
|
||||
en: "Failed to place order ({side} {price}): {error}",
|
||||
},
|
||||
"log.maker.avgPending": {
|
||||
zh: "做市持仓均价未同步,等待账户快照刷新后再执行止损判断",
|
||||
en: "Maker entry price not synced; waiting for account snapshot before stop check",
|
||||
},
|
||||
"log.maker.stopTriggered": {
|
||||
zh: "触发止损,方向={direction} 当前亏损={pnl} USDT",
|
||||
en: "Stop triggered direction={direction} current loss={pnl} USDT",
|
||||
},
|
||||
"log.maker.stopOrderMissing": { zh: "止损平仓时订单已不存在", en: "Stop close order missing" },
|
||||
"log.maker.stopCloseFail": { zh: "止损平仓失败: {error}", en: "Failed to close on stop: {error}" },
|
||||
"log.maker.orderMissing": { zh: "订单已不存在,撤销跳过", en: "Order already gone, skipping cancel" },
|
||||
"log.common.precisionSynced": {
|
||||
zh: "已同步交易精度: priceTick={priceTick} qtyStep={qtyStep}",
|
||||
en: "Synced precision: priceTick={priceTick} qtyStep={qtyStep}",
|
||||
},
|
||||
"log.common.precisionFailed": { zh: "同步精度失败: {error}", en: "Failed to sync precision: {error}" },
|
||||
"log.maker.updateHandlerError": { zh: "更新回调处理异常: {error}", en: "Update handler error: {error}" },
|
||||
"log.maker.snapshotDispatchError": {
|
||||
zh: "快照或更新分发异常: {error}",
|
||||
en: "Snapshot/update dispatch error: {error}",
|
||||
},
|
||||
"log.maker.waitAccount": { zh: "等待账户快照同步,尚未开始做市", en: "Waiting for account snapshot before quoting" },
|
||||
"log.maker.waitDepth": { zh: "等待深度行情推送,尚未开始做市", en: "Waiting for depth stream before quoting" },
|
||||
"log.maker.waitTicker": { zh: "等待Ticker推送,尚未开始做市", en: "Waiting for ticker stream before quoting" },
|
||||
"log.maker.waitOrders": {
|
||||
zh: "等待订单快照返回,尚未执行初始化撤单",
|
||||
en: "Waiting for order snapshot before startup cancels",
|
||||
},
|
||||
"log.maker.noTargets": { zh: "当前无目标挂单,等待下一次刷新", en: "No target orders; waiting for next refresh" },
|
||||
"log.maker.targetsSummary": { zh: "目标挂单: {summary}", en: "Target orders: {summary}" },
|
||||
"log.maker.balanceThrottle": {
|
||||
zh: "余额不足,暂停新挂单 {seconds}s: {detail}",
|
||||
en: "Insufficient balance, pausing new orders for {seconds}s: {detail}",
|
||||
},
|
||||
"log.maker.balanceResumed": {
|
||||
zh: "余额检测恢复,重新尝试挂单",
|
||||
en: "Balance check recovered, retrying orders",
|
||||
},
|
||||
"log.maker.rateLimit429": { zh: "MakerEngine 429: {error}", en: "MakerEngine 429: {error}" },
|
||||
"log.kline.subscribeFail": { zh: "订阅K线失败: {error}", en: "Failed to subscribe klines: {error}" },
|
||||
"log.kline.processError": { zh: "K线推送处理异常: {error}", en: "Kline stream processing error: {error}" },
|
||||
"log.trend.klineInsufficient": {
|
||||
zh: "K线不足 {count}/{min},最近收盘({recentCount}): {recent}",
|
||||
en: "Insufficient klines {count}/{min}, recent closes ({recentCount}): {recent}",
|
||||
},
|
||||
"log.trend.klineReady": {
|
||||
zh: "K线就绪 {count} 根,可计算 SMA30。最近收盘: {recent}",
|
||||
en: "Klines ready {count} bars; SMA30 available. Recent closes: {recent}",
|
||||
},
|
||||
"log.trend.rateLimit429": { zh: "TrendEngine 429: {error}", en: "TrendEngine 429: {error}" },
|
||||
"log.trend.loopError": { zh: "策略循环异常: {error}", en: "Strategy loop error: {error}" },
|
||||
"log.trend.rateLimitUpdateError": {
|
||||
zh: "限频控制器状态更新失败: {error}",
|
||||
en: "Rate limit controller update failed: {error}",
|
||||
},
|
||||
"log.trend.detectPosition": {
|
||||
zh: "检测到已有持仓: {direction} {amount} @ {price}",
|
||||
en: "Detected existing position: {direction} {amount} @ {price}",
|
||||
},
|
||||
"log.trend.detectOrders": {
|
||||
zh: "检测到已有挂单 {count} 笔,将按策略规则接管",
|
||||
en: "Detected {count} existing orders; taking over per strategy rules",
|
||||
},
|
||||
"log.trend.stopCooldown": {
|
||||
zh: "止损后冷却中 {seconds}s,忽略入场信号",
|
||||
en: "Post-stop cooldown {seconds}s; ignoring entry signals",
|
||||
},
|
||||
"log.trend.alreadyEntered": {
|
||||
zh: "本分钟已入场,忽略新的 SMA 入场信号",
|
||||
en: "Entry already executed this minute; ignoring new SMA signal",
|
||||
},
|
||||
"log.trend.bandwidthBlocked": {
|
||||
zh: "布林带宽度不足:{bandwidth} < {minBandwidth},忽略入场信号",
|
||||
en: "Bollinger bandwidth too low: {bandwidth} < {minBandwidth}, ignoring entry",
|
||||
},
|
||||
"log.trend.cancelMissing": { zh: "撤单时部分订单已不存在,忽略", en: "Some orders missing during cancel; ignore" },
|
||||
"log.trend.cancelFail": { zh: "撤销挂单失败: {error}", en: "Failed to cancel orders: {error}" },
|
||||
"log.trend.crossDown": { zh: "下穿SMA30,市价开空", en: "Crossed below SMA30, market sell" },
|
||||
"log.trend.crossUp": { zh: "上穿SMA30,市价开多", en: "Crossed above SMA30, market buy" },
|
||||
"log.trend.marketOrderFail": { zh: "市价下单失败: {error}", en: "Market order failed: {error}" },
|
||||
"log.trend.entryPricePending": {
|
||||
zh: "持仓均价尚未同步,等待交易所账户快照更新后再执行风控",
|
||||
en: "Entry price not synced; waiting for account snapshot before risk checks",
|
||||
},
|
||||
"log.trend.stopPreCancelMissing": { zh: "止损前撤单发现订单已不存在", en: "Stop pre-close cancel found missing order" },
|
||||
"log.trend.marketCloseGuard": {
|
||||
zh: "市价平仓保护触发:closePx={closePx} mark={mark} 偏离 {pctDiff}% > {limitPct}%",
|
||||
en: "Market close guard triggered: closePx={closePx} mark={mark} deviation {pctDiff}% > {limitPct}%",
|
||||
},
|
||||
"log.trend.stopClose": { zh: "止损平仓: {side}", en: "Stop close: {side}" },
|
||||
"log.trend.targetStopMissing": { zh: "止损平仓时目标订单已不存在", en: "Target order missing during stop close" },
|
||||
"log.trend.stopCloseFail": { zh: "止损平仓失败: {error}", en: "Failed to close position on stop: {error}" },
|
||||
"log.trend.placeStopFail": { zh: "挂止损单失败: {error}", en: "Failed to place stop order: {error}" },
|
||||
"log.trend.stopMissingSkip": { zh: "原止损单已不存在,跳过撤销", en: "Existing stop missing, skipping cancel" },
|
||||
"log.trend.cancelStopFail": { zh: "取消原止损单失败: {error}", en: "Failed to cancel existing stop: {error}" },
|
||||
"log.trend.moveStop": { zh: "移动止损到 {price}", en: "Moved stop to {price}" },
|
||||
"log.trend.moveStopFail": { zh: "移动止损失败: {error}", en: "Failed to move stop: {error}" },
|
||||
"log.trend.restoreStop": { zh: "恢复原止损 @ {price}", en: "Restored original stop @ {price}" },
|
||||
"log.trend.restoreStopFail": { zh: "恢复原止损失败: {error}", en: "Failed to restore original stop: {error}" },
|
||||
"log.trend.trailingFail": { zh: "挂动态止盈失败: {error}", en: "Failed to place trailing stop: {error}" },
|
||||
"log.trend.precisionSynced": {
|
||||
zh: "已同步交易精度: priceTick={priceTick} qtyStep={qtyStep}",
|
||||
en: "Synced precision: priceTick={priceTick} qtyStep={qtyStep}",
|
||||
},
|
||||
"log.trend.precisionFailed": { zh: "同步精度失败: {error}", en: "Failed to sync precision: {error}" },
|
||||
"log.trend.updateHandlerError": { zh: "更新回调处理异常: {error}", en: "Update handler error: {error}" },
|
||||
"log.trend.snapshotDispatchError": { zh: "快照或更新分发异常: {error}", en: "Snapshot/update dispatch error: {error}" },
|
||||
};
|
||||
|
||||
const formatTemplate = (template: string, params: Record<string, unknown>): string => {
|
||||
return template.replace(/\{(\w+)\}/g, (_match, key) => {
|
||||
const value = params[key];
|
||||
return value === undefined || value === null ? `{${key}}` : String(value);
|
||||
});
|
||||
};
|
||||
|
||||
export type TranslationKey = keyof typeof translations | string;
|
||||
|
||||
export function t(key: TranslationKey, params: Record<string, unknown> = {}, lang: Language = language): string {
|
||||
const entry = translations[key as keyof typeof translations];
|
||||
const value = entry ? entry[lang] ?? entry.zh : null;
|
||||
if (typeof value === "function") {
|
||||
return value(params, lang);
|
||||
}
|
||||
if (typeof value === "string") {
|
||||
return Object.keys(params).length ? formatTemplate(value, params) : value;
|
||||
}
|
||||
// Fallback: return key to surface missing translations
|
||||
return String(key);
|
||||
}
|
||||
|
||||
export function isEnglish(lang: Language = language): boolean {
|
||||
return lang === "en";
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { AsterSpotRestClient, AsterRestClient } from "../exchanges/aster/client"
|
||||
import { createTradeLog, type TradeLogEntry } from "../logging/trade-log";
|
||||
import { StrategyEventEmitter } from "./common/event-emitter";
|
||||
import { safeSubscribe, type LogHandler } from "./common/subscriptions";
|
||||
import { t } from "../i18n";
|
||||
|
||||
export interface BasisArbSnapshot {
|
||||
ready: boolean;
|
||||
@@ -159,8 +160,8 @@ export class BasisArbEngine {
|
||||
},
|
||||
log,
|
||||
{
|
||||
subscribeFail: (error) => `订阅期货深度失败: ${String(error)}`,
|
||||
processFail: (error) => `处理期货深度异常: ${String(error)}`,
|
||||
subscribeFail: (error) => t("log.basis.subscribeFuturesDepthFail", { error: String(error) }),
|
||||
processFail: (error) => t("log.basis.processFuturesDepthError", { error: String(error) }),
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -179,7 +180,7 @@ export class BasisArbEngine {
|
||||
this.futures.updatedAt = depth.eventTime ?? depth.tradeTime ?? this.now();
|
||||
if (!this.feedReady.futures) {
|
||||
this.feedReady.futures = true;
|
||||
this.tradeLog.push("info", `期货深度已就绪 (${this.config.futuresSymbol})`);
|
||||
this.tradeLog.push("info", t("log.basis.futuresReady", { symbol: this.config.futuresSymbol }));
|
||||
}
|
||||
if (this.feedReady.futures && this.feedReady.spot && this.marketReadyAt == null) {
|
||||
this.marketReadyAt = this.now();
|
||||
@@ -197,7 +198,10 @@ export class BasisArbEngine {
|
||||
this.applySpotTicker(ticker);
|
||||
} catch (error) {
|
||||
this.feedReady.spot = false;
|
||||
this.tradeLog.push("error", `获取现货盘口失败: ${String(error instanceof Error ? error.message : error)}`);
|
||||
this.tradeLog.push(
|
||||
"error",
|
||||
t("log.basis.spotDepthError", { error: String(error instanceof Error ? error.message : error) })
|
||||
);
|
||||
} finally {
|
||||
this.spotInFlight = false;
|
||||
}
|
||||
@@ -217,13 +221,16 @@ export class BasisArbEngine {
|
||||
this.funding.updatedAt = typeof ts === "number" ? ts : this.now();
|
||||
if (!this.feedReady.funding) {
|
||||
this.feedReady.funding = true;
|
||||
this.tradeLog.push("info", `资金费率已就绪 (${this.config.futuresSymbol})`);
|
||||
this.tradeLog.push("info", t("log.basis.fundingReady", { symbol: this.config.futuresSymbol }));
|
||||
}
|
||||
this.emitUpdate();
|
||||
}
|
||||
} catch (error) {
|
||||
this.feedReady.funding = false;
|
||||
this.tradeLog.push("error", `获取资金费率失败: ${String(error instanceof Error ? error.message : error)}`);
|
||||
this.tradeLog.push(
|
||||
"error",
|
||||
t("log.basis.fundingError", { error: String(error instanceof Error ? error.message : error) })
|
||||
);
|
||||
} finally {
|
||||
this.fundingInFlight = false;
|
||||
}
|
||||
@@ -250,7 +257,10 @@ export class BasisArbEngine {
|
||||
this.spotBalances = next;
|
||||
this.emitUpdate();
|
||||
} catch (error) {
|
||||
this.tradeLog.push("error", `获取现货余额失败: ${String(error instanceof Error ? error.message : error)}`);
|
||||
this.tradeLog.push(
|
||||
"error",
|
||||
t("log.basis.spotBalanceError", { error: String(error instanceof Error ? error.message : error) })
|
||||
);
|
||||
} finally {
|
||||
this.spotAccountInFlight = false;
|
||||
}
|
||||
@@ -278,7 +288,10 @@ export class BasisArbEngine {
|
||||
this.futuresBalances = next;
|
||||
this.emitUpdate();
|
||||
} catch (error) {
|
||||
this.tradeLog.push("error", `获取合约余额失败: ${String(error instanceof Error ? error.message : error)}`);
|
||||
this.tradeLog.push(
|
||||
"error",
|
||||
t("log.basis.futuresBalanceError", { error: String(error instanceof Error ? error.message : error) })
|
||||
);
|
||||
} finally {
|
||||
this.futuresAccountInFlight = false;
|
||||
}
|
||||
@@ -295,7 +308,7 @@ export class BasisArbEngine {
|
||||
this.spot.updatedAt = ticker.time ?? this.now();
|
||||
if (!this.feedReady.spot) {
|
||||
this.feedReady.spot = true;
|
||||
this.tradeLog.push("info", `现货盘口已就绪 (${this.config.spotSymbol})`);
|
||||
this.tradeLog.push("info", t("log.basis.spotReady", { symbol: this.config.spotSymbol }));
|
||||
}
|
||||
if (this.feedReady.futures && this.feedReady.spot && this.marketReadyAt == null) {
|
||||
this.marketReadyAt = this.now();
|
||||
@@ -308,7 +321,7 @@ export class BasisArbEngine {
|
||||
const snapshot = this.buildSnapshot();
|
||||
this.evaluateSignals(snapshot);
|
||||
this.events.emit("update", snapshot, (error) => {
|
||||
this.tradeLog.push("error", `推送订阅失败: ${String(error)}`);
|
||||
this.tradeLog.push("error", t("log.basis.pushError", { error: String(error) }));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -410,7 +423,7 @@ export class BasisArbEngine {
|
||||
this.lastEntrySignalAt = now;
|
||||
const bpTxt = (spreadBps as number).toFixed(2);
|
||||
const minutes = Math.floor(((msUntilFunding as number) / 60000));
|
||||
this.tradeLog.push("entry", `入场机会: 扣费后价差 ${bpTxt} bp | 距下次资金费约 ${minutes} 分钟`);
|
||||
this.tradeLog.push("entry", t("log.basis.entryOpportunity", { bp: bpTxt, minutes }));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -419,7 +432,7 @@ export class BasisArbEngine {
|
||||
if (now - this.lastExitSignalAt >= 60 * 1000) { // debounce 60s
|
||||
this.lastExitSignalAt = now;
|
||||
const minutes = Math.max(0, Math.floor(((msUntilFunding as number) / 60000)));
|
||||
this.tradeLog.push("exit", `出场机会: 资金费率为负 | 距收取约 ${minutes} 分钟`);
|
||||
this.tradeLog.push("exit", t("log.basis.exitOpportunity", { minutes }));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ import { createTradeLog, type TradeLogEntry } from "../logging/trade-log";
|
||||
import { extractMessage, isUnknownOrderError } from "../utils/errors";
|
||||
import { formatPriceToString } from "../utils/math";
|
||||
import { computePositionPnl } from "../utils/pnl";
|
||||
import { t } from "../i18n";
|
||||
|
||||
export interface GuardianEngineSnapshot {
|
||||
ready: boolean;
|
||||
@@ -108,8 +109,8 @@ export class GuardianEngine {
|
||||
},
|
||||
log,
|
||||
{
|
||||
subscribeFail: (error) => `订阅账户失败: ${String(error)}`,
|
||||
processFail: (error) => `账户推送处理异常: ${extractMessage(error)}`,
|
||||
subscribeFail: (error) => t("log.subscribe.accountFail", { error: String(error) }),
|
||||
processFail: (error) => t("log.process.accountError", { error: extractMessage(error) }),
|
||||
}
|
||||
);
|
||||
|
||||
@@ -135,8 +136,8 @@ export class GuardianEngine {
|
||||
},
|
||||
log,
|
||||
{
|
||||
subscribeFail: (error) => `订阅订单失败: ${String(error)}`,
|
||||
processFail: (error) => `订单推送处理异常: ${extractMessage(error)}`,
|
||||
subscribeFail: (error) => t("log.subscribe.orderFail", { error: String(error) }),
|
||||
processFail: (error) => t("log.process.orderError", { error: extractMessage(error) }),
|
||||
}
|
||||
);
|
||||
|
||||
@@ -148,8 +149,8 @@ export class GuardianEngine {
|
||||
},
|
||||
log,
|
||||
{
|
||||
subscribeFail: (error) => `订阅Ticker失败: ${String(error)}`,
|
||||
processFail: (error) => `价格推送处理异常: ${extractMessage(error)}`,
|
||||
subscribeFail: (error) => t("log.subscribe.tickerFail", { error: String(error) }),
|
||||
processFail: (error) => t("log.process.tickerError", { error: extractMessage(error) }),
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -179,7 +180,7 @@ export class GuardianEngine {
|
||||
}
|
||||
await this.ensureProtection();
|
||||
} catch (error) {
|
||||
this.tradeLog.push("error", `Guardian 执行异常: ${extractMessage(error)}`);
|
||||
this.tradeLog.push("error", t("log.guardian.executeError", { error: extractMessage(error) }));
|
||||
} finally {
|
||||
this.processing = false;
|
||||
this.emitUpdate();
|
||||
@@ -200,7 +201,7 @@ export class GuardianEngine {
|
||||
const hasEntryPrice = Number.isFinite(position.entryPrice) && Math.abs(position.entryPrice) > 1e-8;
|
||||
if (!hasEntryPrice) {
|
||||
if (!this.entryPricePendingLogged) {
|
||||
this.tradeLog.push("info", "持仓均价尚未同步,等待交易所账户快照更新后再补挂止损");
|
||||
this.tradeLog.push("info", t("log.guardian.entryPricePending"));
|
||||
this.entryPricePendingLogged = true;
|
||||
}
|
||||
return;
|
||||
@@ -210,7 +211,7 @@ export class GuardianEngine {
|
||||
const price = this.getLastPrice();
|
||||
if (!Number.isFinite(price)) {
|
||||
if (!this.priceUnavailableLogged) {
|
||||
this.tradeLog.push("info", "行情尚未就绪,等待最新价格以同步止损");
|
||||
this.tradeLog.push("info", t("log.guardian.pricePending"));
|
||||
this.priceUnavailableLogged = true;
|
||||
}
|
||||
return;
|
||||
@@ -406,7 +407,7 @@ export class GuardianEngine {
|
||||
this.lastStopAttempt.price = stopPrice;
|
||||
this.lastStopAttempt.at = now;
|
||||
} catch (err) {
|
||||
this.tradeLog.push("error", `挂止损单失败: ${String(err)}`);
|
||||
this.tradeLog.push("error", t("log.guardian.placeStopFail", { error: String(err) }));
|
||||
this.lastStopAttempt.side = side;
|
||||
this.lastStopAttempt.price = stopPrice;
|
||||
this.lastStopAttempt.at = now;
|
||||
@@ -430,10 +431,10 @@ export class GuardianEngine {
|
||||
await this.exchange.cancelOrder({ symbol: this.config.symbol, orderId: currentOrder.orderId });
|
||||
} catch (err) {
|
||||
if (isUnknownOrderError(err)) {
|
||||
this.tradeLog.push("order", "原止损单已不存在,跳过撤销");
|
||||
this.tradeLog.push("order", t("log.guardian.stopMissingSkip"));
|
||||
this.openOrders = this.openOrders.filter((o) => o.orderId !== currentOrder.orderId);
|
||||
} else {
|
||||
this.tradeLog.push("error", `取消原止损单失败: ${String(err)}`);
|
||||
this.tradeLog.push("error", t("log.guardian.cancelStopFail", { error: String(err) }));
|
||||
}
|
||||
}
|
||||
try {
|
||||
@@ -462,10 +463,15 @@ export class GuardianEngine {
|
||||
{ priceTick: this.config.priceTick, qtyStep: this.config.qtyStep }
|
||||
);
|
||||
if (order) {
|
||||
this.tradeLog.push("stop", `移动止损到 ${formatPriceToString(nextStopPrice, this.resolvePriceDecimals())}`);
|
||||
this.tradeLog.push(
|
||||
"stop",
|
||||
t("log.guardian.moveStop", {
|
||||
price: formatPriceToString(nextStopPrice, this.resolvePriceDecimals()),
|
||||
})
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
this.tradeLog.push("error", `移动止损失败: ${String(err)}`);
|
||||
this.tradeLog.push("error", t("log.guardian.moveStopFail", { error: String(err) }));
|
||||
try {
|
||||
const position = getPosition(this.accountSnapshot, this.config.symbol);
|
||||
const quantity = Math.abs(position.positionAmt);
|
||||
@@ -494,11 +500,13 @@ export class GuardianEngine {
|
||||
if (restored && Number.isFinite(existingStopPrice)) {
|
||||
this.tradeLog.push(
|
||||
"order",
|
||||
`恢复原止损 @ ${formatPriceToString(existingStopPrice, this.resolvePriceDecimals())}`
|
||||
t("log.guardian.restoreStop", {
|
||||
price: formatPriceToString(existingStopPrice, this.resolvePriceDecimals()),
|
||||
})
|
||||
);
|
||||
}
|
||||
} catch (recoverErr) {
|
||||
this.tradeLog.push("error", `恢复原止损失败: ${String(recoverErr)}`);
|
||||
this.tradeLog.push("error", t("log.guardian.restoreStopFail", { error: String(recoverErr) }));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -531,7 +539,7 @@ export class GuardianEngine {
|
||||
{ priceTick: this.config.priceTick, qtyStep: this.config.qtyStep }
|
||||
);
|
||||
} catch (err) {
|
||||
this.tradeLog.push("error", `挂动态止盈失败: ${String(err)}`);
|
||||
this.tradeLog.push("error", t("log.guardian.trailingFail", { error: String(err) }));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -541,12 +549,12 @@ export class GuardianEngine {
|
||||
const orderIdList = protectiveOrders.map((order) => order.orderId);
|
||||
try {
|
||||
await this.exchange.cancelOrders({ symbol: this.config.symbol, orderIdList });
|
||||
this.tradeLog.push("order", `清理遗留保护单: ${orderIdList.join(",")}`);
|
||||
this.tradeLog.push("order", t("log.guardian.cleanupOrders", { ids: orderIdList.join(",") }));
|
||||
} catch (err) {
|
||||
if (isUnknownOrderError(err)) {
|
||||
this.tradeLog.push("order", "保护单已不存在,跳过清理");
|
||||
this.tradeLog.push("order", t("log.guardian.protectiveMissing"));
|
||||
} else {
|
||||
this.tradeLog.push("error", `清理保护单失败: ${String(err)}`);
|
||||
this.tradeLog.push("error", t("log.guardian.cleanupFail", { error: String(err) }));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -625,10 +633,10 @@ export class GuardianEngine {
|
||||
try {
|
||||
const snapshot = this.buildSnapshot();
|
||||
this.events.emit("update", snapshot, (error) => {
|
||||
this.tradeLog.push("error", `更新分发异常: ${String(error)}`);
|
||||
this.tradeLog.push("error", t("log.guardian.dispatchError", { error: String(error) }));
|
||||
});
|
||||
} catch (err) {
|
||||
this.tradeLog.push("error", `构建快照失败: ${String(err)}`);
|
||||
this.tradeLog.push("error", t("log.guardian.snapshotFail", { error: String(err) }));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -668,12 +676,15 @@ export class GuardianEngine {
|
||||
if (updated) {
|
||||
this.tradeLog.push(
|
||||
"info",
|
||||
`已同步交易精度: priceTick=${precision.priceTick} qtyStep=${precision.qtyStep}`
|
||||
t("log.guardian.precisionSynced", {
|
||||
priceTick: precision.priceTick,
|
||||
qtyStep: precision.qtyStep,
|
||||
})
|
||||
);
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
this.tradeLog.push("error", `同步精度失败: ${extractMessage(error)}`);
|
||||
this.tradeLog.push("error", t("log.guardian.precisionFailed", { error: extractMessage(error) }));
|
||||
this.precisionSync = null;
|
||||
setTimeout(() => this.syncPrecision(), 2000);
|
||||
});
|
||||
|
||||
@@ -27,6 +27,7 @@ import { RateLimitController } from "../core/lib/rate-limit";
|
||||
import { StrategyEventEmitter } from "./common/event-emitter";
|
||||
import { safeSubscribe, type LogHandler } from "./common/subscriptions";
|
||||
import { SessionVolumeTracker } from "./common/session-volume";
|
||||
import { t } from "../i18n";
|
||||
|
||||
interface DesiredOrder {
|
||||
side: "BUY" | "SELL";
|
||||
@@ -164,7 +165,7 @@ export class MakerEngine {
|
||||
const position = getPosition(snapshot, this.config.symbol);
|
||||
this.sessionVolume.update(position, this.getReferencePrice());
|
||||
if (!this.feedArrived.account) {
|
||||
this.tradeLog.push("info", "账户快照已同步");
|
||||
this.tradeLog.push("info", t("log.account.snapshotSynced"));
|
||||
this.feedArrived.account = true;
|
||||
}
|
||||
this.feedStatus.account = true;
|
||||
@@ -172,8 +173,8 @@ export class MakerEngine {
|
||||
},
|
||||
log,
|
||||
{
|
||||
subscribeFail: (error) => `订阅账户失败: ${String(error)}`,
|
||||
processFail: (error) => `账户推送处理异常: ${String(error)}`,
|
||||
subscribeFail: (error) => t("log.subscribe.accountFail", { error: String(error) }),
|
||||
processFail: (error) => t("log.process.accountError", { error: String(error) }),
|
||||
}
|
||||
);
|
||||
|
||||
@@ -192,7 +193,7 @@ export class MakerEngine {
|
||||
}
|
||||
this.initialOrderSnapshotReady = true;
|
||||
if (!this.feedArrived.orders) {
|
||||
this.tradeLog.push("info", "订单快照已返回");
|
||||
this.tradeLog.push("info", t("log.order.snapshotReturned"));
|
||||
this.feedArrived.orders = true;
|
||||
}
|
||||
this.feedStatus.orders = true;
|
||||
@@ -200,8 +201,8 @@ export class MakerEngine {
|
||||
},
|
||||
log,
|
||||
{
|
||||
subscribeFail: (error) => `订阅订单失败: ${String(error)}`,
|
||||
processFail: (error) => `订单推送处理异常: ${String(error)}`,
|
||||
subscribeFail: (error) => t("log.subscribe.orderFail", { error: String(error) }),
|
||||
processFail: (error) => t("log.process.orderError", { error: String(error) }),
|
||||
}
|
||||
);
|
||||
|
||||
@@ -210,7 +211,7 @@ export class MakerEngine {
|
||||
(depth) => {
|
||||
this.depthSnapshot = depth;
|
||||
if (!this.feedArrived.depth) {
|
||||
this.tradeLog.push("info", "获得最新深度行情");
|
||||
this.tradeLog.push("info", t("log.depth.ready"));
|
||||
this.feedArrived.depth = true;
|
||||
}
|
||||
this.feedStatus.depth = true;
|
||||
@@ -218,8 +219,8 @@ export class MakerEngine {
|
||||
},
|
||||
log,
|
||||
{
|
||||
subscribeFail: (error) => `订阅深度失败: ${String(error)}`,
|
||||
processFail: (error) => `深度推送处理异常: ${String(error)}`,
|
||||
subscribeFail: (error) => t("log.subscribe.depthFail", { error: String(error) }),
|
||||
processFail: (error) => t("log.process.depthError", { error: String(error) }),
|
||||
}
|
||||
);
|
||||
|
||||
@@ -228,7 +229,7 @@ export class MakerEngine {
|
||||
(ticker) => {
|
||||
this.tickerSnapshot = ticker;
|
||||
if (!this.feedArrived.ticker) {
|
||||
this.tradeLog.push("info", "Ticker 已就绪");
|
||||
this.tradeLog.push("info", t("log.ticker.ready"));
|
||||
this.feedArrived.ticker = true;
|
||||
}
|
||||
this.feedStatus.ticker = true;
|
||||
@@ -236,8 +237,8 @@ export class MakerEngine {
|
||||
},
|
||||
log,
|
||||
{
|
||||
subscribeFail: (error) => `订阅Ticker失败: ${String(error)}`,
|
||||
processFail: (error) => `价格推送处理异常: ${String(error)}`,
|
||||
subscribeFail: (error) => t("log.subscribe.tickerFail", { error: String(error) }),
|
||||
processFail: (error) => t("log.process.tickerError", { error: String(error) }),
|
||||
}
|
||||
);
|
||||
|
||||
@@ -331,9 +332,9 @@ export class MakerEngine {
|
||||
hadRateLimit = true;
|
||||
this.rateLimit.registerRateLimit("maker");
|
||||
await this.enforceRateLimitStop();
|
||||
this.tradeLog.push("warn", `MakerEngine 429: ${String(error)}`);
|
||||
this.tradeLog.push("warn", t("log.maker.rateLimit429", { error: String(error) }));
|
||||
} else {
|
||||
this.tradeLog.push("error", `做市循环异常: ${String(error)}`);
|
||||
this.tradeLog.push("error", t("log.maker.loopError", { error: String(error) }));
|
||||
}
|
||||
this.emitUpdate();
|
||||
} finally {
|
||||
@@ -367,18 +368,18 @@ export class MakerEngine {
|
||||
unlockOperating(this.locks, this.timers, this.pending, "LIMIT");
|
||||
this.openOrders = [];
|
||||
this.emitUpdate();
|
||||
this.tradeLog.push("order", "启动时清理历史挂单");
|
||||
this.tradeLog.push("order", t("log.maker.cleanOrdersStart"));
|
||||
this.initialOrderResetDone = true;
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (isUnknownOrderError(error)) {
|
||||
this.tradeLog.push("order", "历史挂单已消失,跳过启动清理");
|
||||
this.tradeLog.push("order", t("log.maker.cleanOrdersMissing"));
|
||||
this.initialOrderResetDone = true;
|
||||
this.openOrders = [];
|
||||
this.emitUpdate();
|
||||
return true;
|
||||
}
|
||||
this.tradeLog.push("error", `启动撤单失败: ${String(error)}`);
|
||||
this.tradeLog.push("error", t("log.maker.cleanOrdersFail", { error: String(error) }));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -401,16 +402,20 @@ export class MakerEngine {
|
||||
() => {
|
||||
this.tradeLog.push(
|
||||
"order",
|
||||
`撤销不匹配订单 ${order.side} @ ${order.price} reduceOnly=${order.reduceOnly}`
|
||||
t("log.maker.cancelMismatched", {
|
||||
side: order.side,
|
||||
price: order.price,
|
||||
reduceOnly: order.reduceOnly,
|
||||
})
|
||||
);
|
||||
},
|
||||
() => {
|
||||
this.tradeLog.push("order", "撤销时发现订单已被成交/取消,忽略");
|
||||
this.tradeLog.push("order", t("log.maker.cancelMissing"));
|
||||
this.pendingCancelOrders.delete(String(order.orderId));
|
||||
this.openOrders = this.openOrders.filter((existing) => existing.orderId !== order.orderId);
|
||||
},
|
||||
(error) => {
|
||||
this.tradeLog.push("error", `撤销订单失败: ${String(error)}`);
|
||||
this.tradeLog.push("error", t("log.maker.cancelFail", { error: String(error) }));
|
||||
this.pendingCancelOrders.delete(String(order.orderId));
|
||||
this.openOrders = this.openOrders.filter((existing) => existing.orderId !== order.orderId);
|
||||
}
|
||||
@@ -449,7 +454,11 @@ export class MakerEngine {
|
||||
}
|
||||
this.tradeLog.push(
|
||||
"error",
|
||||
`挂单失败(${target.side} ${target.price}): ${extractMessage(error)}`
|
||||
t("log.maker.placeFail", {
|
||||
side: target.side,
|
||||
price: target.price,
|
||||
error: extractMessage(error),
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -462,7 +471,7 @@ export class MakerEngine {
|
||||
const hasEntryPrice = Number.isFinite(position.entryPrice) && Math.abs(position.entryPrice) > 1e-8;
|
||||
if (!hasEntryPrice) {
|
||||
if (!this.entryPricePendingLogged) {
|
||||
this.tradeLog.push("info", "做市持仓均价未同步,等待账户快照刷新后再执行止损判断");
|
||||
this.tradeLog.push("info", t("log.maker.avgPending"));
|
||||
this.entryPricePendingLogged = true;
|
||||
}
|
||||
return;
|
||||
@@ -478,7 +487,10 @@ export class MakerEngine {
|
||||
const closeSidePrice = closeSideIsSell ? bidPrice : askPrice;
|
||||
this.tradeLog.push(
|
||||
"stop",
|
||||
`触发止损,方向=${position.positionAmt > 0 ? "多" : "空"} 当前亏损=${pnl.toFixed(4)} USDT`
|
||||
t("log.maker.stopTriggered", {
|
||||
direction: position.positionAmt > 0 ? t("common.direction.long") : t("common.direction.short"),
|
||||
pnl: pnl.toFixed(4),
|
||||
})
|
||||
);
|
||||
try {
|
||||
await this.flushOrders();
|
||||
@@ -501,9 +513,9 @@ export class MakerEngine {
|
||||
);
|
||||
} catch (error) {
|
||||
if (isUnknownOrderError(error)) {
|
||||
this.tradeLog.push("order", "止损平仓时订单已不存在");
|
||||
this.tradeLog.push("order", t("log.maker.stopOrderMissing"));
|
||||
} else {
|
||||
this.tradeLog.push("error", `止损平仓失败: ${String(error)}`);
|
||||
this.tradeLog.push("error", t("log.maker.stopCloseFail", { error: String(error) }));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -522,12 +534,12 @@ export class MakerEngine {
|
||||
// 成功撤销不记录日志,保持现有行为
|
||||
},
|
||||
() => {
|
||||
this.tradeLog.push("order", "订单已不存在,撤销跳过");
|
||||
this.tradeLog.push("order", t("log.maker.orderMissing"));
|
||||
this.pendingCancelOrders.delete(String(order.orderId));
|
||||
this.openOrders = this.openOrders.filter((existing) => existing.orderId !== order.orderId);
|
||||
},
|
||||
(error) => {
|
||||
this.tradeLog.push("error", `撤销订单失败: ${String(error)}`);
|
||||
this.tradeLog.push("error", t("log.maker.cancelFail", { error: String(error) }));
|
||||
this.pendingCancelOrders.delete(String(order.orderId));
|
||||
this.openOrders = this.openOrders.filter((existing) => existing.orderId !== order.orderId);
|
||||
}
|
||||
@@ -559,12 +571,15 @@ export class MakerEngine {
|
||||
if (updated) {
|
||||
this.tradeLog.push(
|
||||
"info",
|
||||
`已同步交易精度: priceTick=${precision.priceTick} qtyStep=${precision.qtyStep}`
|
||||
t("log.common.precisionSynced", {
|
||||
priceTick: precision.priceTick,
|
||||
qtyStep: precision.qtyStep,
|
||||
})
|
||||
);
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
this.tradeLog.push("error", `同步精度失败: ${extractMessage(error)}`);
|
||||
this.tradeLog.push("error", t("log.common.precisionFailed", { error: extractMessage(error) }));
|
||||
this.precisionSync = null;
|
||||
setTimeout(() => this.syncPrecision(), 2000);
|
||||
});
|
||||
@@ -581,10 +596,10 @@ export class MakerEngine {
|
||||
try {
|
||||
const snapshot = this.buildSnapshot();
|
||||
this.events.emit("update", snapshot, (error) => {
|
||||
this.tradeLog.push("error", `更新回调处理异常: ${String(error)}`);
|
||||
this.tradeLog.push("error", t("log.maker.updateHandlerError", { error: String(error) }));
|
||||
});
|
||||
} catch (err) {
|
||||
this.tradeLog.push("error", `快照或更新分发异常: ${String(err)}`);
|
||||
this.tradeLog.push("error", t("log.maker.snapshotDispatchError", { error: String(err) }));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -619,19 +634,19 @@ export class MakerEngine {
|
||||
|
||||
private logReadinessBlockers(): void {
|
||||
if (!this.feedStatus.account && !this.readinessLogged.account) {
|
||||
this.tradeLog.push("info", "等待账户快照同步,尚未开始做市");
|
||||
this.tradeLog.push("info", t("log.maker.waitAccount"));
|
||||
this.readinessLogged.account = true;
|
||||
}
|
||||
if (!this.feedStatus.depth && !this.readinessLogged.depth) {
|
||||
this.tradeLog.push("info", "等待深度行情推送,尚未开始做市");
|
||||
this.tradeLog.push("info", t("log.maker.waitDepth"));
|
||||
this.readinessLogged.depth = true;
|
||||
}
|
||||
if (!this.feedStatus.ticker && !this.readinessLogged.ticker) {
|
||||
this.tradeLog.push("info", "等待Ticker推送,尚未开始做市");
|
||||
this.tradeLog.push("info", t("log.maker.waitTicker"));
|
||||
this.readinessLogged.ticker = true;
|
||||
}
|
||||
if (!this.feedStatus.orders && !this.readinessLogged.orders) {
|
||||
this.tradeLog.push("info", "等待订单快照返回,尚未执行初始化撤单");
|
||||
this.tradeLog.push("info", t("log.maker.waitOrders"));
|
||||
this.readinessLogged.orders = true;
|
||||
}
|
||||
}
|
||||
@@ -648,7 +663,7 @@ export class MakerEngine {
|
||||
private logDesiredOrders(desired: DesiredOrder[]): void {
|
||||
if (!desired.length) {
|
||||
if (this.lastDesiredSummary !== "none") {
|
||||
this.tradeLog.push("info", "当前无目标挂单,等待下一次刷新");
|
||||
this.tradeLog.push("info", t("log.maker.noTargets"));
|
||||
this.lastDesiredSummary = "none";
|
||||
}
|
||||
return;
|
||||
@@ -657,7 +672,7 @@ export class MakerEngine {
|
||||
.map((order) => `${order.side}@${order.price}${order.reduceOnly ? "(RO)" : ""}`)
|
||||
.join(" | ");
|
||||
if (summary !== this.lastDesiredSummary) {
|
||||
this.tradeLog.push("info", `目标挂单: ${summary}`);
|
||||
this.tradeLog.push("info", t("log.maker.targetsSummary", { summary }));
|
||||
this.lastDesiredSummary = summary;
|
||||
}
|
||||
}
|
||||
@@ -673,14 +688,14 @@ export class MakerEngine {
|
||||
this.insufficientBalanceCooldownUntil = now + INSUFFICIENT_BALANCE_COOLDOWN_MS;
|
||||
this.lastInsufficientMessage = detail;
|
||||
const seconds = Math.ceil(INSUFFICIENT_BALANCE_COOLDOWN_MS / 1000);
|
||||
this.tradeLog.push("warn", `余额不足,暂停新挂单 ${seconds}s: ${detail}`);
|
||||
this.tradeLog.push("warn", t("log.maker.balanceThrottle", { seconds, detail }));
|
||||
this.insufficientBalanceNotified = true;
|
||||
}
|
||||
|
||||
private applyInsufficientBalanceState(now: number): boolean {
|
||||
const active = now < this.insufficientBalanceCooldownUntil;
|
||||
if (!active && this.insufficientBalanceNotified) {
|
||||
this.tradeLog.push("info", "余额检测恢复,重新尝试挂单");
|
||||
this.tradeLog.push("info", t("log.maker.balanceResumed"));
|
||||
this.insufficientBalanceNotified = false;
|
||||
this.lastInsufficientMessage = null;
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import type {
|
||||
import { formatPriceToString } from "../utils/math";
|
||||
import { createTradeLog } from "../logging/trade-log";
|
||||
import { isUnknownOrderError, isRateLimitError } from "../utils/errors";
|
||||
import { getPosition } from "../utils/strategy";
|
||||
import { getPosition, parseSymbolParts } from "../utils/strategy";
|
||||
import type { PositionSnapshot } from "../utils/strategy";
|
||||
import { computeDepthStats } from "../utils/depth";
|
||||
import { computePositionPnl } from "../utils/pnl";
|
||||
@@ -43,6 +43,10 @@ export interface OffsetMakerEngineSnapshot extends MakerEngineSnapshot {
|
||||
depthImbalance: "balanced" | "buy_dominant" | "sell_dominant";
|
||||
skipBuySide: boolean;
|
||||
skipSellSide: boolean;
|
||||
marketType?: "perp" | "spot";
|
||||
baseAsset?: string | null;
|
||||
quoteAsset?: string | null;
|
||||
spotBalances?: { baseAvailable: number; quoteAvailable: number; baseWallet?: number } | null;
|
||||
}
|
||||
|
||||
type MakerEvent = "update";
|
||||
@@ -54,6 +58,8 @@ export class OffsetMakerEngine {
|
||||
private accountSnapshot: AsterAccountSnapshot | null = null;
|
||||
private depthSnapshot: AsterDepth | null = null;
|
||||
private tickerSnapshot: AsterTicker | null = null;
|
||||
private lastKline: AsterKline | null = null;
|
||||
private liveCandle: { startMs: number; open: number; close: number } | null = null;
|
||||
private openOrders: AsterOrder[] = [];
|
||||
|
||||
private readonly locks: OrderLockMap = {};
|
||||
@@ -66,7 +72,19 @@ export class OffsetMakerEngine {
|
||||
private readonly sessionVolume = new SessionVolumeTracker();
|
||||
private priceTick: number = 0.1;
|
||||
private qtyStep: number = 0.001;
|
||||
private minBaseAmount: number | null = null;
|
||||
private minQuoteAmount: number | null = null;
|
||||
private precisionSync: Promise<void> | null = null;
|
||||
private marketType: "perp" | "spot" = "perp";
|
||||
private baseAsset: string | null = null;
|
||||
private quoteAsset: string | null = null;
|
||||
private baseAssetId: number | null = null;
|
||||
private quoteAssetId: number | null = null;
|
||||
private spotEntryPrice: number | null = null;
|
||||
private lastSpotWallet = 0;
|
||||
private spotKlineUp: boolean | null = null;
|
||||
private lastSpotBuyGuardLogged = false;
|
||||
private lastSpotStopSkipped = false;
|
||||
|
||||
private timer: ReturnType<typeof setInterval> | null = null;
|
||||
private processing = false;
|
||||
@@ -106,6 +124,9 @@ export class OffsetMakerEngine {
|
||||
);
|
||||
this.priceTick = Math.max(1e-9, this.config.priceTick);
|
||||
this.qtyStep = Math.max(1e-9, this.qtyStep);
|
||||
const parsedSymbols = parseSymbolParts(this.config.symbol);
|
||||
this.baseAsset = parsedSymbols.base ?? null;
|
||||
this.quoteAsset = parsedSymbols.quote ?? null;
|
||||
this.syncPrecision();
|
||||
// Debounce window defaults to 3x refresh interval, min 1s
|
||||
this.repriceDwellMs = Math.max(1000, this.config.refreshIntervalMs * 3);
|
||||
@@ -146,11 +167,35 @@ export class OffsetMakerEngine {
|
||||
(snapshot) => {
|
||||
this.accountSnapshot = snapshot;
|
||||
this.feedStatus.account = true;
|
||||
if (snapshot.marketType) {
|
||||
this.marketType = snapshot.marketType;
|
||||
}
|
||||
const parsed = parseSymbolParts(this.config.symbol);
|
||||
this.baseAsset = snapshot.baseAsset ?? this.baseAsset ?? parsed.base ?? null;
|
||||
this.quoteAsset = snapshot.quoteAsset ?? this.quoteAsset ?? parsed.quote ?? null;
|
||||
this.baseAssetId = snapshot.baseAssetId ?? this.baseAssetId;
|
||||
this.quoteAssetId = snapshot.quoteAssetId ?? this.quoteAssetId;
|
||||
const totalUnrealized = Number(snapshot.totalUnrealizedProfit ?? "0");
|
||||
if (Number.isFinite(totalUnrealized)) {
|
||||
this.accountUnrealized = totalUnrealized;
|
||||
}
|
||||
const balances = this.getSpotBalances(snapshot);
|
||||
if (snapshot.marketType === "spot" || this.marketType === "spot") {
|
||||
const baseWallet = balances?.baseWallet ?? 0;
|
||||
if (baseWallet < EPS) {
|
||||
this.spotEntryPrice = null;
|
||||
} else if (baseWallet > this.lastSpotWallet + EPS) {
|
||||
const ref = this.getReferencePrice();
|
||||
if (Number.isFinite(ref)) {
|
||||
this.spotEntryPrice = Number(ref);
|
||||
}
|
||||
}
|
||||
this.lastSpotWallet = baseWallet;
|
||||
}
|
||||
const position = getPosition(snapshot, this.config.symbol);
|
||||
if (this.marketType === "spot" && this.spotEntryPrice != null) {
|
||||
position.entryPrice = this.spotEntryPrice;
|
||||
}
|
||||
this.sessionVolume.update(position, this.getReferencePrice());
|
||||
this.emitUpdate();
|
||||
},
|
||||
@@ -215,8 +260,15 @@ export class OffsetMakerEngine {
|
||||
|
||||
safeSubscribe<AsterKline[]>(
|
||||
this.exchange.watchKlines.bind(this.exchange, this.config.symbol, "1m"),
|
||||
(_klines) => {
|
||||
/* no-op */
|
||||
(klines) => {
|
||||
if (!Array.isArray(klines) || !klines.length) return;
|
||||
const latest = klines[klines.length - 1];
|
||||
this.lastKline = latest;
|
||||
const open = Number(latest.open);
|
||||
const close = Number(latest.close);
|
||||
if (Number.isFinite(open) && Number.isFinite(close)) {
|
||||
this.spotKlineUp = close > open;
|
||||
}
|
||||
},
|
||||
log,
|
||||
{
|
||||
@@ -279,7 +331,11 @@ export class OffsetMakerEngine {
|
||||
this.lastSkipSell = skipSellSide;
|
||||
this.lastImbalance = imbalance;
|
||||
|
||||
const position = getPosition(this.accountSnapshot, this.config.symbol);
|
||||
const position = this.getPositionSnapshot();
|
||||
const isSpotMarket = this.marketType === "spot";
|
||||
const spotBalances = isSpotMarket ? this.getSpotBalances() : null;
|
||||
const balancesForSpot = isSpotMarket ? spotBalances ?? { baseAvailable: 0, quoteAvailable: 0 } : spotBalances;
|
||||
this.updateLiveCandle();
|
||||
const handledImbalance = await this.handleImbalanceExit(position, buySum, sellSum);
|
||||
if (handledImbalance) {
|
||||
this.emitUpdate();
|
||||
@@ -302,34 +358,141 @@ export class OffsetMakerEngine {
|
||||
const safeAsk = this.ensureMakerPrice("SELL", rawAskPrice, finalBid, finalAsk);
|
||||
const bidPrice = safeBid != null ? formatPriceToString(safeBid, priceDecimals) : null;
|
||||
const askPrice = safeAsk != null ? formatPriceToString(safeAsk, priceDecimals) : null;
|
||||
const absPosition = Math.abs(position.positionAmt);
|
||||
const rawAbsPosition = Math.abs(position.positionAmt);
|
||||
const minSell =
|
||||
Number.isFinite(this.minBaseAmount) && this.minBaseAmount! > 0
|
||||
? this.minBaseAmount!
|
||||
: Math.max(this.config.tradeAmount, this.qtyStep);
|
||||
let absPosition = rawAbsPosition;
|
||||
const tinySpotPosition =
|
||||
isSpotMarket &&
|
||||
minSell > 0 &&
|
||||
rawAbsPosition > EPS &&
|
||||
rawAbsPosition + EPS < minSell;
|
||||
if (tinySpotPosition) {
|
||||
absPosition = 0; // treat as flat to allow buys to accumulate until reaching minimum sell size
|
||||
}
|
||||
const desired: DesiredOrder[] = [];
|
||||
const canEnter = !this.rateLimit.shouldBlockEntries();
|
||||
const allowSpotBuy = !isSpotMarket || this.isSpotKlineUp();
|
||||
|
||||
if (absPosition < EPS) {
|
||||
if (absPosition < EPS && isSpotMarket) {
|
||||
this.entryPricePendingLogged = false;
|
||||
const baseAvail = balancesForSpot?.baseAvailable ?? 0;
|
||||
const baseWallet = balancesForSpot?.baseWallet ?? baseAvail;
|
||||
const maxBase = Math.max(baseAvail, baseWallet);
|
||||
if (isSpotMarket && minSell > 0 && maxBase + EPS < minSell) {
|
||||
// 无法卖出,跳过卖单,允许买单累计
|
||||
this.lastSellPriceViable = false;
|
||||
if (!skipSellSide) {
|
||||
this.tradeLog.push("info", "现货持仓低于最小卖单量,暂不挂卖单");
|
||||
}
|
||||
}
|
||||
if (!skipBuySide && canEnter) {
|
||||
if (bidPrice != null) {
|
||||
this.lastBuyPriceViable = true;
|
||||
desired.push({ side: "BUY", price: bidPrice, amount: this.config.tradeAmount, reduceOnly: false });
|
||||
} else if (this.lastBuyPriceViable) {
|
||||
this.lastBuyPriceViable = false;
|
||||
this.tradeLog.push("info", "跳过买单:价差不足以构造maker价格");
|
||||
if (!allowSpotBuy) {
|
||||
if (this.lastBuyPriceViable) {
|
||||
this.tradeLog.push("info", "现货买入仅在1m阳线,当前跳过买单");
|
||||
this.lastBuyPriceViable = false;
|
||||
}
|
||||
} else {
|
||||
const buyAmount = this.computeSpotOrderSize({
|
||||
side: "BUY",
|
||||
desiredAmount: this.config.tradeAmount,
|
||||
price: bidPrice != null ? Number(bidPrice) : null,
|
||||
balances: balancesForSpot,
|
||||
});
|
||||
if (bidPrice != null && buyAmount >= EPS) {
|
||||
this.lastBuyPriceViable = true;
|
||||
desired.push({ side: "BUY", price: bidPrice, amount: buyAmount, reduceOnly: false });
|
||||
} else if (this.lastBuyPriceViable) {
|
||||
this.lastBuyPriceViable = false;
|
||||
const reason =
|
||||
buyAmount < EPS && isSpotMarket
|
||||
? "现货可用报价资产不足,跳过买单"
|
||||
: "跳过买单:价差不足以构造maker价格";
|
||||
this.tradeLog.push("info", reason);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!skipSellSide && canEnter) {
|
||||
if (askPrice != null) {
|
||||
this.lastSellPriceViable = true;
|
||||
desired.push({ side: "SELL", price: askPrice, amount: this.config.tradeAmount, reduceOnly: false });
|
||||
} else if (this.lastSellPriceViable) {
|
||||
this.lastSellPriceViable = false;
|
||||
this.tradeLog.push("info", "跳过卖单:价差不足以构造maker价格");
|
||||
const baseAvail = balancesForSpot?.baseAvailable ?? 0;
|
||||
const baseWallet = balancesForSpot?.baseWallet ?? baseAvail;
|
||||
const maxBase = Math.max(baseAvail, baseWallet);
|
||||
if (isSpotMarket && minSell > 0 && maxBase + EPS < minSell) {
|
||||
// 持仓低于最小卖单量,跳过卖单,等待累积
|
||||
if (this.lastSellPriceViable) {
|
||||
this.lastSellPriceViable = false;
|
||||
this.tradeLog.push("info", "现货持仓低于最小卖单量,跳过卖单");
|
||||
}
|
||||
} else {
|
||||
const desiredSellAmount =
|
||||
isSpotMarket && balancesForSpot ? balancesForSpot.baseAvailable : this.config.tradeAmount;
|
||||
const sellAmount = this.computeSpotOrderSize({
|
||||
side: "SELL",
|
||||
desiredAmount: desiredSellAmount,
|
||||
price: askPrice != null ? Number(askPrice) : null,
|
||||
balances: balancesForSpot,
|
||||
});
|
||||
if (askPrice != null && sellAmount >= EPS) {
|
||||
this.lastSellPriceViable = true;
|
||||
desired.push({ side: "SELL", price: askPrice, amount: sellAmount, reduceOnly: false });
|
||||
} else if (this.lastSellPriceViable) {
|
||||
this.lastSellPriceViable = false;
|
||||
const reason =
|
||||
sellAmount < EPS && isSpotMarket
|
||||
? "现货可用基础资产不足,跳过卖单"
|
||||
: "跳过卖单:价差不足以构造maker价格";
|
||||
this.tradeLog.push("info", reason);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (absPosition < EPS) {
|
||||
this.entryPricePendingLogged = false;
|
||||
if (!skipBuySide && canEnter) {
|
||||
if (isSpotMarket && !allowSpotBuy) {
|
||||
if (this.lastBuyPriceViable) {
|
||||
this.tradeLog.push("info", "现货买入仅在1m阳线,当前跳过买单");
|
||||
this.lastBuyPriceViable = false;
|
||||
}
|
||||
} else {
|
||||
desired.push({ side: "BUY", price: bidPrice, amount: this.config.tradeAmount, reduceOnly: false });
|
||||
}
|
||||
}
|
||||
if (!skipSellSide && canEnter) {
|
||||
if (isSpotMarket && minSell > 0 && this.minBaseAmount != null) {
|
||||
const baseAvail = balancesForSpot?.baseAvailable ?? 0;
|
||||
const baseWallet = balancesForSpot?.baseWallet ?? baseAvail;
|
||||
if (Math.max(baseAvail, baseWallet) + EPS < minSell) {
|
||||
this.lastSellPriceViable = false;
|
||||
this.tradeLog.push("info", "现货持仓低于最小卖单量,跳过卖单");
|
||||
}
|
||||
}
|
||||
desired.push({ side: "SELL", price: askPrice, amount: this.config.tradeAmount, reduceOnly: false });
|
||||
}
|
||||
} else {
|
||||
const closeSide: "BUY" | "SELL" = position.positionAmt > 0 ? "SELL" : "BUY";
|
||||
const closePrice = closeSide === "SELL" ? closeAskPrice : closeBidPrice;
|
||||
desired.push({ side: closeSide, price: closePrice, amount: absPosition, reduceOnly: true });
|
||||
if (isSpotMarket && minSell > 0 && rawAbsPosition + EPS < minSell) {
|
||||
// 持仓未达最小卖出量,等待累积,不下单
|
||||
this.lastSellPriceViable = false;
|
||||
this.lastBuyPriceViable = false;
|
||||
this.desiredOrders = [];
|
||||
this.sessionVolume.update(position, this.getReferencePrice());
|
||||
this.emitUpdate();
|
||||
return;
|
||||
}
|
||||
const closeQty =
|
||||
isSpotMarket && balancesForSpot
|
||||
? this.computeSpotOrderSize({
|
||||
side: "SELL",
|
||||
desiredAmount: rawAbsPosition,
|
||||
price: closePrice != null ? Number(closePrice) : null,
|
||||
balances: balancesForSpot,
|
||||
})
|
||||
: rawAbsPosition;
|
||||
if (closePrice != null && closeQty >= EPS) {
|
||||
desired.push({ side: closeSide, price: closePrice, amount: closeQty, reduceOnly: false });
|
||||
}
|
||||
}
|
||||
|
||||
this.desiredOrders = desired;
|
||||
@@ -354,7 +517,8 @@ export class OffsetMakerEngine {
|
||||
}
|
||||
|
||||
private async enforceRateLimitStop(): Promise<void> {
|
||||
const position = getPosition(this.accountSnapshot, this.config.symbol);
|
||||
if (this.marketType === "spot") return;
|
||||
const position = this.getPositionSnapshot();
|
||||
if (Math.abs(position.positionAmt) < EPS) return;
|
||||
await this.flushOrders();
|
||||
const absPosition = Math.abs(position.positionAmt);
|
||||
@@ -438,6 +602,7 @@ export class OffsetMakerEngine {
|
||||
buySum: number,
|
||||
sellSum: number
|
||||
): Promise<boolean> {
|
||||
if (this.marketType === "spot") return false;
|
||||
const absPosition = Math.abs(position.positionAmt);
|
||||
if (absPosition < EPS) return false;
|
||||
|
||||
@@ -547,7 +712,21 @@ export class OffsetMakerEngine {
|
||||
for (const target of toPlace) {
|
||||
if (!target) continue;
|
||||
if (target.amount < EPS) continue;
|
||||
if (
|
||||
this.marketType === "spot" &&
|
||||
this.minBaseAmount != null &&
|
||||
target.side === "SELL" &&
|
||||
target.amount + EPS < this.minBaseAmount
|
||||
) {
|
||||
// Skip placing sells that would be bumped by venue minimums
|
||||
if (this.lastSellPriceViable) {
|
||||
this.lastSellPriceViable = false;
|
||||
this.tradeLog.push("info", "现货卖单低于最小成交量,跳过挂单等待累积");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
const reduceOnlyFlag = this.marketType === "spot" ? false : target.reduceOnly;
|
||||
await placeOrder(
|
||||
this.exchange,
|
||||
this.config.symbol,
|
||||
@@ -559,9 +738,9 @@ export class OffsetMakerEngine {
|
||||
target.price, // 已经是字符串价格
|
||||
target.amount,
|
||||
(type, detail) => this.tradeLog.push(type, detail),
|
||||
target.reduceOnly,
|
||||
reduceOnlyFlag,
|
||||
{
|
||||
markPrice: getPosition(this.accountSnapshot, this.config.symbol).markPrice,
|
||||
markPrice: this.getPositionSnapshot().markPrice,
|
||||
maxPct: this.config.maxCloseSlippagePct,
|
||||
},
|
||||
{
|
||||
@@ -593,6 +772,57 @@ export class OffsetMakerEngine {
|
||||
}
|
||||
|
||||
private async checkRisk(position: PositionSnapshot, bidPrice: number, askPrice: number): Promise<void> {
|
||||
// For spot: use balance-derived size; if loss exceeds threshold, market sell to exit.
|
||||
if (this.marketType === "spot") {
|
||||
const absPosition = Math.abs(position.positionAmt);
|
||||
if (absPosition < EPS) {
|
||||
this.lastSpotStopSkipped = false;
|
||||
return;
|
||||
}
|
||||
const minStopQty = Number.isFinite(this.minBaseAmount) ? this.minBaseAmount! : null;
|
||||
if (minStopQty != null && minStopQty > 0 && absPosition + EPS < minStopQty) {
|
||||
if (!this.lastSpotStopSkipped) {
|
||||
this.tradeLog.push("info", "现货持仓低于最小平仓数量,跳过止损检查");
|
||||
this.lastSpotStopSkipped = true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
this.lastSpotStopSkipped = false;
|
||||
const pnl = computePositionPnl(position, bidPrice, askPrice);
|
||||
const triggerStop = shouldStopLoss(position, bidPrice, askPrice, this.config.lossLimit);
|
||||
if (!triggerStop) return;
|
||||
this.tradeLog.push("stop", `现货止损,当前仓位=${absPosition.toFixed(6)} PnL=${pnl.toFixed(4)} USDT`);
|
||||
try {
|
||||
// 尽力撤销所有未完成挂单,避免锁定基础资产导致余额不足
|
||||
await this.exchange.cancelAllOrders({ symbol: this.config.symbol }).catch(() => {});
|
||||
await this.flushOrders();
|
||||
await marketClose(
|
||||
this.exchange,
|
||||
this.config.symbol,
|
||||
this.openOrders,
|
||||
this.locks,
|
||||
this.timers,
|
||||
this.pending,
|
||||
"SELL",
|
||||
absPosition,
|
||||
(type, detail) => this.tradeLog.push(type, detail),
|
||||
{
|
||||
markPrice: position.markPrice,
|
||||
expectedPrice: bidPrice || null,
|
||||
maxPct: this.config.maxCloseSlippagePct,
|
||||
},
|
||||
{ qtyStep: this.qtyStep }
|
||||
);
|
||||
} catch (error) {
|
||||
if (isRateLimitError(error)) throw error;
|
||||
if (isUnknownOrderError(error)) {
|
||||
this.tradeLog.push("order", "止损平仓时订单已不存在");
|
||||
} else {
|
||||
this.tradeLog.push("error", `现货止损失败: ${String(error)}`);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
const absPosition = Math.abs(position.positionAmt);
|
||||
if (absPosition < EPS) return;
|
||||
|
||||
@@ -691,6 +921,12 @@ export class OffsetMakerEngine {
|
||||
updated = true;
|
||||
}
|
||||
}
|
||||
if (Number.isFinite(precision.minBaseAmount)) {
|
||||
this.minBaseAmount = precision.minBaseAmount!;
|
||||
}
|
||||
if (Number.isFinite(precision.minQuoteAmount)) {
|
||||
this.minQuoteAmount = precision.minQuoteAmount!;
|
||||
}
|
||||
if (updated) {
|
||||
this.tradeLog.push(
|
||||
"info",
|
||||
@@ -724,7 +960,7 @@ export class OffsetMakerEngine {
|
||||
}
|
||||
|
||||
private buildSnapshot(): OffsetMakerEngineSnapshot {
|
||||
const position = getPosition(this.accountSnapshot, this.config.symbol);
|
||||
const position = this.getPositionSnapshot();
|
||||
const { topBid, topAsk } = getTopPrices(this.depthSnapshot);
|
||||
const spread = topBid != null && topAsk != null ? topAsk - topBid : null;
|
||||
const pnl = computePositionPnl(position, topBid, topAsk);
|
||||
@@ -750,6 +986,10 @@ export class OffsetMakerEngine {
|
||||
depthImbalance: this.lastImbalance,
|
||||
skipBuySide: this.lastSkipBuy,
|
||||
skipSellSide: this.lastSkipSell,
|
||||
marketType: this.marketType,
|
||||
baseAsset: this.baseAsset,
|
||||
quoteAsset: this.quoteAsset,
|
||||
spotBalances: this.marketType === "spot" ? this.getSpotBalances() : null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -757,6 +997,98 @@ export class OffsetMakerEngine {
|
||||
return getMidOrLast(this.depthSnapshot, this.tickerSnapshot);
|
||||
}
|
||||
|
||||
private isSpotKlineUp(): boolean {
|
||||
return this.spotKlineUp === true || this.isLiveCandleUp();
|
||||
}
|
||||
|
||||
private isLiveCandleUp(): boolean {
|
||||
if (!this.liveCandle) return false;
|
||||
return this.liveCandle.close > this.liveCandle.open;
|
||||
}
|
||||
|
||||
private updateLiveCandle(): void {
|
||||
const price = this.getReferencePrice();
|
||||
if (!Number.isFinite(price)) return;
|
||||
const now = Date.now();
|
||||
const minuteStart = now - (now % 60000);
|
||||
if (!this.liveCandle || this.liveCandle.startMs !== minuteStart) {
|
||||
this.liveCandle = { startMs: minuteStart, open: price as number, close: price as number };
|
||||
} else {
|
||||
this.liveCandle.close = price as number;
|
||||
}
|
||||
this.spotKlineUp = this.isLiveCandleUp();
|
||||
}
|
||||
|
||||
private getPositionSnapshot(): PositionSnapshot {
|
||||
const position = getPosition(this.accountSnapshot, this.config.symbol);
|
||||
if (this.marketType === "spot" && this.spotEntryPrice != null && Math.abs(position.positionAmt) > EPS) {
|
||||
return { ...position, entryPrice: this.spotEntryPrice };
|
||||
}
|
||||
return position;
|
||||
}
|
||||
|
||||
private getSpotBalances(snapshot: AsterAccountSnapshot | null = this.accountSnapshot): { baseAvailable: number; quoteAvailable: number; baseWallet: number } | null {
|
||||
const assets = snapshot?.assets ?? [];
|
||||
if (!assets.length) return null;
|
||||
const parsed = parseSymbolParts(this.config.symbol);
|
||||
const baseSymbol = (this.baseAsset ?? snapshot?.baseAsset ?? parsed.base ?? "").toUpperCase();
|
||||
const quoteSymbol = (this.quoteAsset ?? snapshot?.quoteAsset ?? parsed.quote ?? "").toUpperCase();
|
||||
const baseId = snapshot?.baseAssetId ?? this.baseAssetId ?? null;
|
||||
const quoteId = snapshot?.quoteAssetId ?? this.quoteAssetId ?? null;
|
||||
const normalize = (asset?: string) => (asset ? asset.toUpperCase() : "");
|
||||
const pickAvailable = (asset?: { availableBalance?: string; walletBalance: string }) => {
|
||||
const available = Number(asset?.availableBalance ?? asset?.walletBalance ?? 0);
|
||||
return Number.isFinite(available) ? available : 0;
|
||||
};
|
||||
const pickWallet = (asset?: { walletBalance: string }) => {
|
||||
const wallet = Number(asset?.walletBalance ?? 0);
|
||||
return Number.isFinite(wallet) ? wallet : 0;
|
||||
};
|
||||
const baseAssetEntry = assets.find(
|
||||
(asset) =>
|
||||
(Number.isFinite(baseId) && Number(asset.assetId) === Number(baseId)) ||
|
||||
normalize(asset.asset) === baseSymbol
|
||||
);
|
||||
const quoteAssetEntry = assets.find(
|
||||
(asset) =>
|
||||
(Number.isFinite(quoteId) && Number(asset.assetId) === Number(quoteId)) ||
|
||||
normalize(asset.asset) === quoteSymbol
|
||||
);
|
||||
return {
|
||||
baseAvailable: pickAvailable(baseAssetEntry),
|
||||
quoteAvailable: pickAvailable(quoteAssetEntry),
|
||||
baseWallet: pickWallet(baseAssetEntry),
|
||||
};
|
||||
}
|
||||
|
||||
private computeSpotOrderSize(params: {
|
||||
side: "BUY" | "SELL";
|
||||
desiredAmount: number;
|
||||
price: number | null;
|
||||
balances: { baseAvailable: number; quoteAvailable: number; baseWallet?: number } | null;
|
||||
}): number {
|
||||
const desired = Number(params.desiredAmount);
|
||||
if (!Number.isFinite(desired) || desired <= 0) return 0;
|
||||
if (!params.balances) return desired;
|
||||
if (params.side === "SELL") {
|
||||
const cap = Math.max(0, params.balances.baseAvailable, params.balances.baseWallet ?? 0);
|
||||
if (this.minBaseAmount != null && cap + EPS < this.minBaseAmount) {
|
||||
return 0; // below venue min trade size; skip sell until enough balance
|
||||
}
|
||||
return this.roundToStep(Math.max(0, Math.min(desired, cap)));
|
||||
}
|
||||
const price = Number(params.price);
|
||||
const quoteAvailable = Math.max(0, params.balances.quoteAvailable ?? 0);
|
||||
if (!Number.isFinite(price) || price <= 0) return desired;
|
||||
const maxByQuote = quoteAvailable / price;
|
||||
return this.roundToStep(Math.max(0, Math.min(desired, maxByQuote)));
|
||||
}
|
||||
|
||||
private roundToStep(amount: number): number {
|
||||
const step = Math.max(1e-9, this.qtyStep);
|
||||
return Math.floor(amount / step) * step;
|
||||
}
|
||||
|
||||
private ensureMakerPrice(
|
||||
side: "BUY" | "SELL",
|
||||
rawPrice: number,
|
||||
@@ -797,7 +1129,7 @@ export class OffsetMakerEngine {
|
||||
private async tryDustMarketClose(target: DesiredOrder, error: unknown): Promise<boolean> {
|
||||
if (!target.reduceOnly) return false;
|
||||
if (!this.isInvalidAmountError(error)) return false;
|
||||
const position = getPosition(this.accountSnapshot, this.config.symbol);
|
||||
const position = this.getPositionSnapshot();
|
||||
const absQty = Math.abs(target.amount);
|
||||
if (absQty < EPS) return false;
|
||||
const { topBid, topAsk } = getTopPrices(this.depthSnapshot);
|
||||
|
||||
@@ -35,6 +35,7 @@ import { RateLimitController } from "../core/lib/rate-limit";
|
||||
import { StrategyEventEmitter } from "./common/event-emitter";
|
||||
import { safeSubscribe, type LogHandler } from "./common/subscriptions";
|
||||
import { SessionVolumeTracker } from "./common/session-volume";
|
||||
import { t } from "../i18n";
|
||||
|
||||
export interface TrendEngineSnapshot {
|
||||
ready: boolean;
|
||||
@@ -175,8 +176,8 @@ export class TrendEngine {
|
||||
},
|
||||
log,
|
||||
{
|
||||
subscribeFail: (error) => `订阅账户失败: ${String(error)}`,
|
||||
processFail: (error) => `账户推送处理异常: ${extractMessage(error)}`,
|
||||
subscribeFail: (error) => t("log.subscribe.accountFail", { error: String(error) }),
|
||||
processFail: (error) => t("log.process.accountError", { error: extractMessage(error) }),
|
||||
}
|
||||
);
|
||||
|
||||
@@ -209,8 +210,8 @@ export class TrendEngine {
|
||||
},
|
||||
log,
|
||||
{
|
||||
subscribeFail: (error) => `订阅订单失败: ${String(error)}`,
|
||||
processFail: (error) => `订单推送处理异常: ${extractMessage(error)}`,
|
||||
subscribeFail: (error) => t("log.subscribe.orderFail", { error: String(error) }),
|
||||
processFail: (error) => t("log.process.orderError", { error: extractMessage(error) }),
|
||||
}
|
||||
);
|
||||
|
||||
@@ -222,8 +223,8 @@ export class TrendEngine {
|
||||
},
|
||||
log,
|
||||
{
|
||||
subscribeFail: (error) => `订阅深度失败: ${String(error)}`,
|
||||
processFail: (error) => `深度推送处理异常: ${extractMessage(error)}`,
|
||||
subscribeFail: (error) => t("log.subscribe.depthFail", { error: String(error) }),
|
||||
processFail: (error) => t("log.process.depthError", { error: extractMessage(error) }),
|
||||
}
|
||||
);
|
||||
|
||||
@@ -235,8 +236,8 @@ export class TrendEngine {
|
||||
},
|
||||
log,
|
||||
{
|
||||
subscribeFail: (error) => `订阅Ticker失败: ${String(error)}`,
|
||||
processFail: (error) => `价格推送处理异常: ${extractMessage(error)}`,
|
||||
subscribeFail: (error) => t("log.subscribe.tickerFail", { error: String(error) }),
|
||||
processFail: (error) => t("log.process.tickerError", { error: extractMessage(error) }),
|
||||
}
|
||||
);
|
||||
|
||||
@@ -251,8 +252,8 @@ export class TrendEngine {
|
||||
},
|
||||
log,
|
||||
{
|
||||
subscribeFail: (error) => `订阅K线失败: ${String(error)}`,
|
||||
processFail: (error) => `K线推送处理异常: ${extractMessage(error)}`,
|
||||
subscribeFail: (error) => t("log.kline.subscribeFail", { error: String(error) }),
|
||||
processFail: (error) => t("log.kline.processError", { error: extractMessage(error) }),
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -287,7 +288,12 @@ export class TrendEngine {
|
||||
const closes = this.klineSnapshot.slice(-5).map((k) => Number(k.close).toFixed(2));
|
||||
this.tradeLog.push(
|
||||
"info",
|
||||
`K线不足 ${count}/${minKlines},最近收盘(${closes.length}): ${closes.join(", ")}`
|
||||
t("log.trend.klineInsufficient", {
|
||||
count,
|
||||
min: minKlines,
|
||||
recentCount: closes.length,
|
||||
recent: closes.join(", "),
|
||||
})
|
||||
);
|
||||
this.klineInsufficientLogged = true;
|
||||
}
|
||||
@@ -297,7 +303,7 @@ export class TrendEngine {
|
||||
const closes = this.klineSnapshot.slice(-5).map((k) => Number(k.close).toFixed(2));
|
||||
this.tradeLog.push(
|
||||
"info",
|
||||
`K线就绪 ${count} 根,可计算 SMA30。最近收盘: ${closes.join(", ")}`
|
||||
t("log.trend.klineReady", { count, recent: closes.join(", ") })
|
||||
);
|
||||
this.klineReadyLogged = true;
|
||||
}
|
||||
@@ -361,16 +367,16 @@ export class TrendEngine {
|
||||
hadRateLimit = true;
|
||||
this.rateLimit.registerRateLimit("trend");
|
||||
await this.enforceRateLimitStop();
|
||||
this.tradeLog.push("warn", `TrendEngine 429: ${String(error)}`);
|
||||
this.tradeLog.push("warn", t("log.trend.rateLimit429", { error: String(error) }));
|
||||
} else {
|
||||
this.tradeLog.push("error", `策略循环异常: ${String(error)}`);
|
||||
this.tradeLog.push("error", t("log.trend.loopError", { error: String(error) }));
|
||||
}
|
||||
this.emitUpdate();
|
||||
} finally {
|
||||
try {
|
||||
this.rateLimit.onCycleComplete(hadRateLimit);
|
||||
} catch (rateLimitError) {
|
||||
this.tradeLog.push("error", `限频控制器状态更新失败: ${String(rateLimitError)}`);
|
||||
this.tradeLog.push("error", t("log.trend.rateLimitUpdateError", { error: String(rateLimitError) }));
|
||||
} finally {
|
||||
this.processing = false;
|
||||
}
|
||||
@@ -395,11 +401,15 @@ export class TrendEngine {
|
||||
if (hasPosition) {
|
||||
this.tradeLog.push(
|
||||
"info",
|
||||
`检测到已有持仓: ${position.positionAmt > 0 ? "多" : "空"} ${Math.abs(position.positionAmt).toFixed(4)} @ ${position.entryPrice.toFixed(2)}`
|
||||
t("log.trend.detectPosition", {
|
||||
direction: position.positionAmt > 0 ? t("common.direction.long") : t("common.direction.short"),
|
||||
amount: Math.abs(position.positionAmt).toFixed(4),
|
||||
price: position.entryPrice.toFixed(2),
|
||||
})
|
||||
);
|
||||
}
|
||||
if (this.openOrders.length > 0) {
|
||||
this.tradeLog.push("info", `检测到已有挂单 ${this.openOrders.length} 笔,将按策略规则接管`);
|
||||
this.tradeLog.push("info", t("log.trend.detectOrders", { count: this.openOrders.length }));
|
||||
}
|
||||
this.startupLogged = true;
|
||||
}
|
||||
@@ -415,12 +425,12 @@ export class TrendEngine {
|
||||
// 止损后的冷却期:60s 内不允许基于 SMA 穿越再次入场
|
||||
if (this.lastStopLossAt != null && now - this.lastStopLossAt < 60_000) {
|
||||
const remaining = Math.max(0, 60_000 - (now - this.lastStopLossAt));
|
||||
this.tradeLog.push("info", `止损后冷却中 ${(remaining / 1000).toFixed(0)}s,忽略入场信号`);
|
||||
this.tradeLog.push("info", t("log.trend.stopCooldown", { seconds: (remaining / 1000).toFixed(0) }));
|
||||
return;
|
||||
}
|
||||
// 同一分钟只允许一次入场
|
||||
if (this.lastEntryMinute != null && this.lastEntryMinute === currentMinute) {
|
||||
this.tradeLog.push("info", "本分钟已入场,忽略新的 SMA 入场信号");
|
||||
this.tradeLog.push("info", t("log.trend.alreadyEntered"));
|
||||
return;
|
||||
}
|
||||
if (
|
||||
@@ -431,7 +441,10 @@ export class TrendEngine {
|
||||
if (now - this.lastBollingerBlockLogged > 15_000) {
|
||||
this.tradeLog.push(
|
||||
"info",
|
||||
`布林带宽度不足:${Number(currentBandwidth).toFixed(4)} < ${this.config.minBollingerBandwidth},忽略入场信号`
|
||||
t("log.trend.bandwidthBlocked", {
|
||||
bandwidth: Number(currentBandwidth).toFixed(4),
|
||||
minBandwidth: this.config.minBollingerBandwidth,
|
||||
})
|
||||
);
|
||||
this.lastBollingerBlockLogged = now;
|
||||
}
|
||||
@@ -450,22 +463,22 @@ export class TrendEngine {
|
||||
this.openOrders = [];
|
||||
} catch (err) {
|
||||
if (isUnknownOrderError(err)) {
|
||||
this.tradeLog.push("order", "撤单时部分订单已不存在,忽略");
|
||||
this.tradeLog.push("order", t("log.trend.cancelMissing"));
|
||||
this.cancelAllRequested = true;
|
||||
// 与成功撤单路径保持一致,立即清空本地缓存,等待订单流推送重建
|
||||
this.pendingCancelOrders.clear();
|
||||
this.openOrders = [];
|
||||
} else {
|
||||
this.tradeLog.push("error", `撤销挂单失败: ${String(err)}`);
|
||||
this.tradeLog.push("error", t("log.trend.cancelFail", { error: String(err) }));
|
||||
this.cancelAllRequested = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (this.lastPrice > currentSma && currentPrice < currentSma) {
|
||||
await this.submitMarketOrder("SELL", currentPrice, "下穿SMA30,市价开空");
|
||||
await this.submitMarketOrder("SELL", currentPrice, t("log.trend.crossDown"));
|
||||
this.lastEntryMinute = currentMinute;
|
||||
} else if (this.lastPrice < currentSma && currentPrice > currentSma) {
|
||||
await this.submitMarketOrder("BUY", currentPrice, "上穿SMA30,市价开多");
|
||||
await this.submitMarketOrder("BUY", currentPrice, t("log.trend.crossUp"));
|
||||
this.lastEntryMinute = currentMinute;
|
||||
}
|
||||
}
|
||||
@@ -493,7 +506,7 @@ export class TrendEngine {
|
||||
this.tradeLog.push("open", `${reason}: ${side} @ ${price}`);
|
||||
this.lastOpenPlan = { side, price };
|
||||
} catch (err) {
|
||||
this.tradeLog.push("error", `市价下单失败: ${String(err)}`);
|
||||
this.tradeLog.push("error", t("log.trend.marketOrderFail", { error: String(err) }));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -504,7 +517,7 @@ export class TrendEngine {
|
||||
const hasEntryPrice = Number.isFinite(position.entryPrice) && Math.abs(position.entryPrice) > 1e-8;
|
||||
if (!hasEntryPrice) {
|
||||
if (!this.entryPricePendingLogged) {
|
||||
this.tradeLog.push("info", "持仓均价尚未同步,等待交易所账户快照更新后再执行风控");
|
||||
this.tradeLog.push("info", t("log.trend.entryPricePending"));
|
||||
this.entryPricePendingLogged = true;
|
||||
}
|
||||
return { closed: false, pnl: position.unrealizedProfit };
|
||||
@@ -697,7 +710,7 @@ export class TrendEngine {
|
||||
orderIdSet.forEach((id) => this.pendingCancelOrders.add(id));
|
||||
} catch (err) {
|
||||
if (isUnknownOrderError(err)) {
|
||||
this.tradeLog.push("order", "止损前撤单发现订单已不存在");
|
||||
this.tradeLog.push("order", t("log.trend.stopPreCancelMissing"));
|
||||
// 清理本地缓存,避免重复对同一订单执行撤单
|
||||
for (const id of orderIdSet) {
|
||||
this.pendingCancelOrders.delete(id);
|
||||
@@ -720,7 +733,12 @@ export class TrendEngine {
|
||||
if (pctDiff > limitPct) {
|
||||
this.tradeLog.push(
|
||||
"info",
|
||||
`市价平仓保护触发:closePx=${Number(closeSidePrice).toFixed(2)} mark=${mark.toFixed(2)} 偏离 ${(pctDiff * 100).toFixed(2)}% > ${(limitPct * 100).toFixed(2)}%`
|
||||
t("log.trend.marketCloseGuard", {
|
||||
closePx: Number(closeSidePrice).toFixed(2),
|
||||
mark: mark.toFixed(2),
|
||||
pctDiff: (pctDiff * 100).toFixed(2),
|
||||
limitPct: (limitPct * 100).toFixed(2),
|
||||
})
|
||||
);
|
||||
return { closed: false, pnl };
|
||||
}
|
||||
@@ -747,14 +765,14 @@ export class TrendEngine {
|
||||
{ qtyStep: this.config.qtyStep }
|
||||
);
|
||||
result.closed = true;
|
||||
this.tradeLog.push("close", `止损平仓: ${direction === "long" ? "SELL" : "BUY"}`);
|
||||
this.tradeLog.push("close", t("log.trend.stopClose", { side: direction === "long" ? "SELL" : "BUY" }));
|
||||
// 记录止损时间以便短期内抑制再次入场
|
||||
this.lastStopLossAt = Date.now();
|
||||
} catch (err) {
|
||||
if (isUnknownOrderError(err)) {
|
||||
this.tradeLog.push("order", "止损平仓时目标订单已不存在");
|
||||
this.tradeLog.push("order", t("log.trend.targetStopMissing"));
|
||||
} else {
|
||||
this.tradeLog.push("error", `止损平仓失败: ${String(err)}`);
|
||||
this.tradeLog.push("error", t("log.trend.stopCloseFail", { error: String(err) }));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -808,7 +826,7 @@ export class TrendEngine {
|
||||
);
|
||||
this.lastStopAttempt = { side, price: stopPrice, at: Date.now() };
|
||||
} catch (err) {
|
||||
this.tradeLog.push("error", `挂止损单失败: ${String(err)}`);
|
||||
this.tradeLog.push("error", t("log.trend.placeStopFail", { error: String(err) }));
|
||||
// 记录尝试以避免在错误被抛回时立即再次重复尝试
|
||||
this.lastStopAttempt = { side, price: stopPrice, at: Date.now() };
|
||||
}
|
||||
@@ -833,11 +851,11 @@ export class TrendEngine {
|
||||
await this.exchange.cancelOrder({ symbol: this.config.symbol, orderId: currentOrder.orderId });
|
||||
} catch (err) {
|
||||
if (isUnknownOrderError(err)) {
|
||||
this.tradeLog.push("order", "原止损单已不存在,跳过撤销");
|
||||
this.tradeLog.push("order", t("log.trend.stopMissingSkip"));
|
||||
// 订单已不存在,移除本地记录,防止后续重复匹配
|
||||
this.openOrders = this.openOrders.filter((o) => o.orderId !== currentOrder.orderId);
|
||||
} else {
|
||||
this.tradeLog.push("error", `取消原止损单失败: ${String(err)}`);
|
||||
this.tradeLog.push("error", t("log.trend.cancelStopFail", { error: String(err) }));
|
||||
}
|
||||
}
|
||||
// 仅在成功创建新止损单后记录“移动止损”日志
|
||||
@@ -867,10 +885,18 @@ export class TrendEngine {
|
||||
{ priceTick: this.config.priceTick, qtyStep: this.config.qtyStep }
|
||||
);
|
||||
if (order) {
|
||||
this.tradeLog.push("stop", `移动止损到 ${formatPriceToString(nextStopPrice, Math.max(0, Math.floor(Math.log10(1 / this.config.priceTick))))}`);
|
||||
this.tradeLog.push(
|
||||
"stop",
|
||||
t("log.trend.moveStop", {
|
||||
price: formatPriceToString(
|
||||
nextStopPrice,
|
||||
Math.max(0, Math.floor(Math.log10(1 / this.config.priceTick)))
|
||||
),
|
||||
})
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
this.tradeLog.push("error", `移动止损失败: ${String(err)}`);
|
||||
this.tradeLog.push("error", t("log.trend.moveStopFail", { error: String(err) }));
|
||||
// 回滚策略:尝试用原价恢复止损,以避免出现短时间内无止损保护
|
||||
try {
|
||||
const position = getPosition(this.accountSnapshot, this.config.symbol);
|
||||
@@ -902,11 +928,19 @@ export class TrendEngine {
|
||||
{ priceTick: this.config.priceTick, qtyStep: this.config.qtyStep }
|
||||
);
|
||||
if (restored) {
|
||||
this.tradeLog.push("order", `恢复原止损 @ ${formatPriceToString(existingStopPrice, Math.max(0, Math.floor(Math.log10(1 / this.config.priceTick))))}`);
|
||||
this.tradeLog.push(
|
||||
"order",
|
||||
t("log.trend.restoreStop", {
|
||||
price: formatPriceToString(
|
||||
existingStopPrice,
|
||||
Math.max(0, Math.floor(Math.log10(1 / this.config.priceTick)))
|
||||
),
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (recoverErr) {
|
||||
this.tradeLog.push("error", `恢复原止损失败: ${String(recoverErr)}`);
|
||||
this.tradeLog.push("error", t("log.trend.restoreStopFail", { error: String(recoverErr) }));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -939,7 +973,7 @@ export class TrendEngine {
|
||||
{ priceTick: this.config.priceTick, qtyStep: this.config.qtyStep }
|
||||
);
|
||||
} catch (err) {
|
||||
this.tradeLog.push("error", `挂动态止盈失败: ${String(err)}`);
|
||||
this.tradeLog.push("error", t("log.trend.trailingFail", { error: String(err) }));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -968,12 +1002,12 @@ export class TrendEngine {
|
||||
if (updated) {
|
||||
this.tradeLog.push(
|
||||
"info",
|
||||
`已同步交易精度: priceTick=${precision.priceTick} qtyStep=${precision.qtyStep}`
|
||||
t("log.trend.precisionSynced", { priceTick: precision.priceTick, qtyStep: precision.qtyStep })
|
||||
);
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
this.tradeLog.push("error", `同步精度失败: ${extractMessage(error)}`);
|
||||
this.tradeLog.push("error", t("log.trend.precisionFailed", { error: extractMessage(error) }));
|
||||
this.precisionSync = null;
|
||||
setTimeout(() => this.syncPrecision(), 2000);
|
||||
});
|
||||
@@ -983,10 +1017,10 @@ export class TrendEngine {
|
||||
try {
|
||||
const snapshot = this.buildSnapshot();
|
||||
this.events.emit("update", snapshot, (error) => {
|
||||
this.tradeLog.push("error", `更新回调处理异常: ${String(error)}`);
|
||||
this.tradeLog.push("error", t("log.trend.updateHandlerError", { error: String(error) }));
|
||||
});
|
||||
} catch (err) {
|
||||
this.tradeLog.push("error", `快照或更新分发异常: ${String(err)}`);
|
||||
this.tradeLog.push("error", t("log.trend.snapshotDispatchError", { error: String(err) }));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+16
-15
@@ -9,6 +9,7 @@ import { BasisApp } from "./BasisApp";
|
||||
import { isBasisStrategyEnabled } from "../config";
|
||||
import { loadCopyrightFragments, verifyCopyrightIntegrity } from "../utils/copyright";
|
||||
import { resolveExchangeId } from "../exchanges/create-adapter";
|
||||
import { t } from "../i18n";
|
||||
|
||||
interface StrategyOption {
|
||||
id: "trend" | "guardian" | "maker" | "offset-maker" | "basis" | "grid";
|
||||
@@ -20,32 +21,32 @@ interface StrategyOption {
|
||||
const BASE_STRATEGIES: StrategyOption[] = [
|
||||
{
|
||||
id: "trend",
|
||||
label: "趋势跟随策略 (SMA30)",
|
||||
description: "监控均线信号,自动进出场并维护止损/止盈",
|
||||
label: t("app.strategy.trend.label"),
|
||||
description: t("app.strategy.trend.desc"),
|
||||
component: TrendApp,
|
||||
},
|
||||
{
|
||||
id: "guardian",
|
||||
label: "Guardian 防守策略",
|
||||
description: "不主动开仓,只为现有仓位补挂/移动止损,防止裸奔",
|
||||
label: t("app.strategy.guardian.label"),
|
||||
description: t("app.strategy.guardian.desc"),
|
||||
component: GuardianApp,
|
||||
},
|
||||
{
|
||||
id: "maker",
|
||||
label: "做市刷单策略",
|
||||
description: "双边挂单提供流动性,自动追价与风控止损",
|
||||
label: t("app.strategy.maker.label"),
|
||||
description: t("app.strategy.maker.desc"),
|
||||
component: MakerApp,
|
||||
},
|
||||
{
|
||||
id: "grid",
|
||||
label: "基础网格策略",
|
||||
description: "在上下边界之间布设等比网格,自动加仓与减仓",
|
||||
label: t("app.strategy.grid.label"),
|
||||
description: t("app.strategy.grid.desc"),
|
||||
component: GridApp,
|
||||
},
|
||||
{
|
||||
id: "offset-maker",
|
||||
label: "偏移做市策略",
|
||||
description: "根据盘口深度自动偏移挂单并在极端不平衡时撤退",
|
||||
label: t("app.strategy.offset.label"),
|
||||
description: t("app.strategy.offset.desc"),
|
||||
component: OffsetMakerApp,
|
||||
},
|
||||
];
|
||||
@@ -66,8 +67,8 @@ export function App() {
|
||||
...BASE_STRATEGIES,
|
||||
{
|
||||
id: "basis" as const,
|
||||
label: "期现套利策略",
|
||||
description: "监控期货与现货盘口差价,辅助发现套利机会",
|
||||
label: t("app.strategy.basis.label"),
|
||||
description: t("app.strategy.basis.desc"),
|
||||
component: BasisApp,
|
||||
},
|
||||
];
|
||||
@@ -99,13 +100,13 @@ export function App() {
|
||||
<Box flexDirection="column" paddingX={1} paddingY={1}>
|
||||
<Text color="gray">{copyright.bannerText}</Text>
|
||||
{integrityOk ? null : (
|
||||
<Text color="red">警告: 版权校验失败,当前版本可能被篡改。</Text>
|
||||
<Text color="red">{t("app.integrity.warning")}</Text>
|
||||
)}
|
||||
<Box height={1}>
|
||||
<Text color="gray">────────────────────────────────────────────────────</Text>
|
||||
</Box>
|
||||
<Text color="cyanBright">请选择要运行的策略</Text>
|
||||
<Text color="gray">使用 ↑/↓ 选择,回车开始,Ctrl+C 退出。</Text>
|
||||
<Text color="cyanBright">{t("app.pickStrategy")}</Text>
|
||||
<Text color="gray">{t("app.pickHint")}</Text>
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
{strategies.map((strategy, index) => {
|
||||
const active = index === cursor;
|
||||
|
||||
+62
-34
@@ -5,6 +5,7 @@ import { getExchangeDisplayName, resolveExchangeId } from "../exchanges/create-a
|
||||
import { buildAdapterFromEnv } from "../exchanges/resolve-from-env";
|
||||
import { BasisArbEngine, type BasisArbSnapshot } from "../strategy/basis-arb-engine";
|
||||
import { formatNumber } from "../utils/format";
|
||||
import { t } from "../i18n";
|
||||
|
||||
interface BasisAppProps {
|
||||
onExit: () => void;
|
||||
@@ -31,7 +32,7 @@ export function BasisApp({ onExit }: BasisAppProps) {
|
||||
|
||||
useEffect(() => {
|
||||
if (exchangeId !== "aster") {
|
||||
setError(new Error("期现套利策略目前仅支持 Aster 交易所。请设置 EXCHANGE=aster 后重试。"));
|
||||
setError(new Error(t("basis.onlyAster")));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
@@ -57,8 +58,8 @@ export function BasisApp({ onExit }: BasisAppProps) {
|
||||
if (error) {
|
||||
return (
|
||||
<Box flexDirection="column" padding={1}>
|
||||
<Text color="red">无法启动期现套利策略: {error.message}</Text>
|
||||
<Text color="gray">按 Esc 返回菜单。</Text>
|
||||
<Text color="red">{t("basis.startFailed", { message: error.message })}</Text>
|
||||
<Text color="gray">{t("common.backHint")}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -66,7 +67,7 @@ export function BasisApp({ onExit }: BasisAppProps) {
|
||||
if (!snapshot) {
|
||||
return (
|
||||
<Box padding={1}>
|
||||
<Text>正在初始化期现套利监控…</Text>
|
||||
<Text>{t("basis.initializing")}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -85,10 +86,15 @@ export function BasisApp({ onExit }: BasisAppProps) {
|
||||
const fundingRatePct = snapshot.fundingRate != null ? `${(snapshot.fundingRate * 100).toFixed(4)}%` : "-";
|
||||
const fundingUpdated = snapshot.fundingLastUpdate ? new Date(snapshot.fundingLastUpdate).toLocaleTimeString() : "-";
|
||||
const nextFundingTime = snapshot.nextFundingTime ? new Date(snapshot.nextFundingTime).toLocaleTimeString() : "-";
|
||||
const fundingIncomePerFunding = snapshot.fundingIncomePerFunding != null ? `${formatNumber(snapshot.fundingIncomePerFunding, 4)} USDT` : "-";
|
||||
const fundingIncomePerDay = snapshot.fundingIncomePerDay != null ? `${formatNumber(snapshot.fundingIncomePerDay, 4)} USDT` : "-";
|
||||
const takerFeesPerRoundTrip = snapshot.takerFeesPerRoundTrip != null ? `${formatNumber(snapshot.takerFeesPerRoundTrip, 4)} USDT` : "-";
|
||||
const fundingCountToBreakeven = snapshot.fundingCountToBreakeven != null ? `${formatNumber(snapshot.fundingCountToBreakeven, 2)} 次` : "-";
|
||||
const fundingIncomePerFunding =
|
||||
snapshot.fundingIncomePerFunding != null ? `${formatNumber(snapshot.fundingIncomePerFunding, 4)} USDT` : "-";
|
||||
const fundingIncomePerDay =
|
||||
snapshot.fundingIncomePerDay != null ? `${formatNumber(snapshot.fundingIncomePerDay, 4)} USDT` : "-";
|
||||
const takerFeesPerRoundTrip =
|
||||
snapshot.takerFeesPerRoundTrip != null ? `${formatNumber(snapshot.takerFeesPerRoundTrip, 4)} USDT` : "-";
|
||||
const fundingCountToBreakeven =
|
||||
snapshot.fundingCountToBreakeven != null ? formatNumber(snapshot.fundingCountToBreakeven, 2) : "-";
|
||||
const feePct = (basisConfig.takerFeeRate * 100).toFixed(4);
|
||||
const feedStatus = snapshot.feedStatus;
|
||||
const lastLogs = snapshot.tradeLog.slice(-5);
|
||||
const spotBalances = (snapshot.spotBalances ?? []).filter((b) => Math.abs(b.free) > 0 || Math.abs(b.locked) > 0);
|
||||
@@ -97,72 +103,94 @@ export function BasisApp({ onExit }: BasisAppProps) {
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1}>
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text color="cyanBright">Basis Arbitrage Dashboard</Text>
|
||||
<Text color="cyanBright">{t("basis.title")}</Text>
|
||||
<Text>
|
||||
交易所: {exchangeName} | 期货合约: {snapshot.futuresSymbol} | 现货交易对: {snapshot.spotSymbol}
|
||||
{t("basis.headerLine", {
|
||||
exchange: exchangeName,
|
||||
futures: snapshot.futuresSymbol,
|
||||
spot: snapshot.spotSymbol,
|
||||
})}
|
||||
</Text>
|
||||
<Text color="gray">按 Esc 返回策略选择 | 数据状态: 期货({feedStatus.futures ? "OK" : "--"}) 现货({feedStatus.spot ? "OK" : "--"}) 资金费率({feedStatus.funding ? "OK" : "--"})</Text>
|
||||
<Text color="gray">最近更新时间: {lastUpdated}</Text>
|
||||
<Text color="gray">
|
||||
{t("basis.statusLine", {
|
||||
futuresStatus: feedStatus.futures ? "OK" : "--",
|
||||
spotStatus: feedStatus.spot ? "OK" : "--",
|
||||
fundingStatus: feedStatus.funding ? "OK" : "--",
|
||||
})}
|
||||
</Text>
|
||||
<Text color="gray">{t("basis.lastUpdated", { time: lastUpdated })}</Text>
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="row" marginBottom={1}>
|
||||
<Box flexDirection="column" marginRight={4}>
|
||||
<Text color="greenBright">期货盘口</Text>
|
||||
<Text>买一: {futuresBid} | 卖一: {futuresAsk}</Text>
|
||||
<Text color="gray">更新时间: {futuresUpdated}</Text>
|
||||
<Text color="greenBright">{t("basis.section.futures")}</Text>
|
||||
<Text>{t("basis.bookLine", { bid: futuresBid, ask: futuresAsk })}</Text>
|
||||
<Text color="gray">{t("basis.updatedAt", { time: futuresUpdated })}</Text>
|
||||
</Box>
|
||||
<Box flexDirection="column">
|
||||
<Text color="greenBright">现货盘口</Text>
|
||||
<Text>买一: {spotBid} | 卖一: {spotAsk}</Text>
|
||||
<Text color="gray">更新时间: {spotUpdated}</Text>
|
||||
<Text color="greenBright">{t("basis.section.spot")}</Text>
|
||||
<Text>{t("basis.bookLine", { bid: spotBid, ask: spotAsk })}</Text>
|
||||
<Text color="gray">{t("basis.updatedAt", { time: spotUpdated })}</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text color="yellow">资金费率</Text>
|
||||
<Text>当前资金费率: {fundingRatePct}</Text>
|
||||
<Text color="gray">资金费率更新时间: {fundingUpdated} | 下次结算时间: {nextFundingTime}</Text>
|
||||
<Text>单次资金费率收益(估): {fundingIncomePerFunding} | 日收益(估): {fundingIncomePerDay}</Text>
|
||||
<Text>双边吃单手续费(估): {takerFeesPerRoundTrip} | 回本所需资金费率次数: {fundingCountToBreakeven}</Text>
|
||||
<Text color="yellow">{t("basis.section.funding")}</Text>
|
||||
<Text>{t("basis.fundingRate", { rate: fundingRatePct })}</Text>
|
||||
<Text color="gray">
|
||||
{t("basis.fundingTimes", { updated: fundingUpdated, next: nextFundingTime })}
|
||||
</Text>
|
||||
<Text>{t("basis.fundingIncome", { per: fundingIncomePerFunding, perDay: fundingIncomePerDay })}</Text>
|
||||
<Text>{t("basis.takerFees", { fees: takerFeesPerRoundTrip, count: fundingCountToBreakeven })}</Text>
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="row" marginBottom={1}>
|
||||
<Box flexDirection="column" marginRight={4}>
|
||||
<Text color="cyan">现货账户余额(非0)</Text>
|
||||
<Text color="cyan">{t("basis.spotBalanceTitle")}</Text>
|
||||
{spotBalances.length ? (
|
||||
spotBalances.map((b) => (
|
||||
<Text key={`spot-${b.asset}`}>
|
||||
{b.asset}: 可用 {formatNumber(b.free, 8)} | 冻结 {formatNumber(b.locked, 8)}
|
||||
{t("basis.balanceLine", {
|
||||
asset: b.asset,
|
||||
free: formatNumber(b.free, 8),
|
||||
locked: formatNumber(b.locked, 8),
|
||||
})}
|
||||
</Text>
|
||||
))
|
||||
) : (
|
||||
<Text color="gray">无</Text>
|
||||
<Text color="gray">{t("basis.none")}</Text>
|
||||
)}
|
||||
</Box>
|
||||
<Box flexDirection="column">
|
||||
<Text color="cyan">合约账户余额(非0)</Text>
|
||||
<Text color="cyan">{t("basis.futuresBalanceTitle")}</Text>
|
||||
{futuresBalances.length ? (
|
||||
futuresBalances.map((b) => (
|
||||
<Text key={`fut-${b.asset}`}>
|
||||
{b.asset}: 钱包 {formatNumber(b.wallet, 8)} | 可用 {formatNumber(b.available, 8)}
|
||||
{t("basis.futuresBalanceLine", {
|
||||
asset: b.asset,
|
||||
wallet: formatNumber(b.wallet, 8),
|
||||
available: formatNumber(b.available, 8),
|
||||
})}
|
||||
</Text>
|
||||
))
|
||||
) : (
|
||||
<Text color="gray">无</Text>
|
||||
<Text color="gray">{t("basis.none")}</Text>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text color={snapshot.opportunity ? "greenBright" : "redBright"}>套利差价(卖期货 / 买现货)</Text>
|
||||
<Text color={snapshot.opportunity ? "green" : undefined}>毛价差: {spread} USDT | {spreadBps} bp</Text>
|
||||
<Text color={snapshot.opportunity ? "greenBright" : "redBright"}>{t("basis.spreadTitle")}</Text>
|
||||
<Text color={snapshot.opportunity ? "green" : undefined}>
|
||||
{t("basis.spreadLine", { spread, bps: spreadBps })}
|
||||
</Text>
|
||||
<Text color={snapshot.opportunity ? "green" : "red"}>
|
||||
扣除 taker 手续费 ({(basisConfig.takerFeeRate * 100).toFixed(4)}% × 双边): {netSpread} USDT | {netSpreadBps} bp
|
||||
{t("basis.netSpreadLine", { feePct, net: netSpread, netBps: netSpreadBps })}
|
||||
</Text>
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="column">
|
||||
<Text color="yellow">最近事件</Text>
|
||||
<Text color="yellow">{t("common.section.recent")}</Text>
|
||||
{lastLogs.length ? (
|
||||
lastLogs.map((entry, index) => {
|
||||
const color = entry.type === "entry" ? "green" : entry.type === "exit" ? "red" : undefined;
|
||||
@@ -173,7 +201,7 @@ export function BasisApp({ onExit }: BasisAppProps) {
|
||||
);
|
||||
})
|
||||
) : (
|
||||
<Text color="gray">暂无日志</Text>
|
||||
<Text color="gray">{t("common.noLogs")}</Text>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
+69
-27
@@ -6,6 +6,7 @@ import { buildAdapterFromEnv } from "../exchanges/resolve-from-env";
|
||||
import { GridEngine, type GridEngineSnapshot } from "../strategy/grid-engine";
|
||||
import { DataTable, type TableColumn } from "./components/DataTable";
|
||||
import { formatNumber } from "../utils/format";
|
||||
import { t } from "../i18n";
|
||||
|
||||
interface GridAppProps {
|
||||
onExit: () => void;
|
||||
@@ -59,8 +60,8 @@ export function GridApp({ onExit }: GridAppProps) {
|
||||
if (error) {
|
||||
return (
|
||||
<Box flexDirection="column" padding={1}>
|
||||
<Text color="red">启动失败: {error.message}</Text>
|
||||
<Text color="gray">请检查环境变量和网络连通性。</Text>
|
||||
<Text color="red">{t("common.startFailed", { message: error.message })}</Text>
|
||||
<Text color="gray">{t("common.checkEnv")}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -68,17 +69,17 @@ export function GridApp({ onExit }: GridAppProps) {
|
||||
if (!snapshot) {
|
||||
return (
|
||||
<Box padding={1}>
|
||||
<Text>正在初始化网格策略…</Text>
|
||||
<Text>{t("grid.initializing")}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
const feedStatus = snapshot.feedStatus;
|
||||
const feedEntries: Array<{ key: keyof typeof feedStatus; label: string }> = [
|
||||
{ key: "account", label: "账户" },
|
||||
{ key: "orders", label: "订单" },
|
||||
{ key: "depth", label: "深度" },
|
||||
{ key: "ticker", label: "行情" },
|
||||
{ key: "account", label: t("maker.feed.account") },
|
||||
{ key: "orders", label: t("maker.feed.orders") },
|
||||
{ key: "depth", label: t("maker.feed.depth") },
|
||||
{ key: "ticker", label: t("maker.feed.ticker") },
|
||||
];
|
||||
const stopReason = snapshot.running ? null : snapshot.stopReason;
|
||||
const lastLogs = snapshot.tradeLog.slice(-5);
|
||||
@@ -112,71 +113,112 @@ export function GridApp({ onExit }: GridAppProps) {
|
||||
price: order.price,
|
||||
amount: formatNumber(order.amount, 4),
|
||||
}));
|
||||
const statusLabel = snapshot.running ? t("status.running") : t("status.paused");
|
||||
const directionLabel =
|
||||
snapshot.direction === "both"
|
||||
? t("grid.direction.both")
|
||||
: snapshot.direction === "long"
|
||||
? t("grid.direction.long")
|
||||
: t("grid.direction.short");
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1}>
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text color="cyanBright">Grid Strategy Dashboard</Text>
|
||||
<Text color="cyanBright">{t("grid.title")}</Text>
|
||||
<Text>
|
||||
交易所: {exchangeName} | 交易对: {snapshot.symbol} | 状态: {snapshot.running ? "运行中" : "暂停"} | 方向: {snapshot.direction}
|
||||
{t("grid.headerLine", {
|
||||
exchange: exchangeName,
|
||||
symbol: snapshot.symbol,
|
||||
status: statusLabel,
|
||||
direction: directionLabel,
|
||||
})}
|
||||
</Text>
|
||||
<Text>
|
||||
实时价格: {formatNumber(snapshot.lastPrice, 4)} | 下界: {formatNumber(snapshot.lowerPrice, 4)} | 上界: {formatNumber(snapshot.upperPrice, 4)} | 网格数量: {snapshot.gridLines.length}
|
||||
{t("grid.priceLine", {
|
||||
lastPrice: formatNumber(snapshot.lastPrice, 4),
|
||||
lower: formatNumber(snapshot.lowerPrice, 4),
|
||||
upper: formatNumber(snapshot.upperPrice, 4),
|
||||
count: snapshot.gridLines.length,
|
||||
})}
|
||||
</Text>
|
||||
<Text color="gray">数据状态:
|
||||
<Text color="gray">
|
||||
{t("grid.dataStatus")}
|
||||
{feedEntries.map((entry, index) => (
|
||||
<Text key={entry.key} color={feedStatus[entry.key] ? "green" : "red"}>
|
||||
{index === 0 ? " " : " "}
|
||||
{entry.label}
|
||||
</Text>
|
||||
))}
|
||||
| 按 Esc 返回策略选择
|
||||
{" | "}
|
||||
{t("common.backHint")}
|
||||
</Text>
|
||||
{stopReason ? <Text color="yellow">暂停原因: {stopReason}</Text> : null}
|
||||
{stopReason ? <Text color="yellow">{t("grid.stopReason", { reason: stopReason })}</Text> : null}
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="row" marginBottom={1}>
|
||||
<Box flexDirection="column" marginRight={4}>
|
||||
<Text color="greenBright">网格配置</Text>
|
||||
<Text color="greenBright">{t("grid.configTitle")}</Text>
|
||||
<Text>
|
||||
单笔数量: {formatNumber(gridConfig.orderSize, 6)} | 最大仓位: {formatNumber(gridConfig.maxPositionSize, 6)}
|
||||
{t("grid.configSize", {
|
||||
orderSize: formatNumber(gridConfig.orderSize, 6),
|
||||
maxPosition: formatNumber(gridConfig.maxPositionSize, 6),
|
||||
})}
|
||||
</Text>
|
||||
<Text>
|
||||
止损阈值: {(gridConfig.stopLossPct * 100).toFixed(2)}% | 重启阈值: {(gridConfig.restartTriggerPct * 100).toFixed(2)}% | 自动重启: {gridConfig.autoRestart ? "启用" : "关闭"}
|
||||
{t("grid.configRisk", {
|
||||
stopLoss: (gridConfig.stopLossPct * 100).toFixed(2),
|
||||
restart: (gridConfig.restartTriggerPct * 100).toFixed(2),
|
||||
autoRestart: gridConfig.autoRestart ? t("common.enabled") : t("common.disabled"),
|
||||
})}
|
||||
</Text>
|
||||
<Text>
|
||||
刷新间隔: {gridConfig.refreshIntervalMs} ms
|
||||
{t("grid.refreshInterval", { interval: gridConfig.refreshIntervalMs })}
|
||||
</Text>
|
||||
</Box>
|
||||
<Box flexDirection="column">
|
||||
<Text color="greenBright">持仓</Text>
|
||||
<Text color="greenBright">{t("common.section.position")}</Text>
|
||||
{hasPosition ? (
|
||||
<>
|
||||
<Text>
|
||||
当前持仓: {position.positionAmt > 0 ? "多" : "空"} | 数量: {formatNumber(Math.abs(position.positionAmt), 6)} | 均价: {formatNumber(position.entryPrice, 4)}
|
||||
{t("grid.positionLine", {
|
||||
direction: position.positionAmt > 0 ? t("common.direction.long") : t("common.direction.short"),
|
||||
qty: formatNumber(Math.abs(position.positionAmt), 6),
|
||||
avgPrice: formatNumber(position.entryPrice, 4),
|
||||
})}
|
||||
</Text>
|
||||
<Text>
|
||||
未实现盈亏: {formatNumber(position.unrealizedProfit, 4)} | 标记价: {formatNumber(position.markPrice, 4)}
|
||||
{t("grid.unrealizedLine", {
|
||||
pnl: formatNumber(position.unrealizedProfit, 4),
|
||||
mark: formatNumber(position.markPrice, 4),
|
||||
})}
|
||||
</Text>
|
||||
</>
|
||||
) : (
|
||||
<Text color="gray">当前无持仓</Text>
|
||||
<Text color="gray">{t("common.noPosition")}</Text>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text color="yellow">网格线</Text>
|
||||
{gridRows.length > 0 ? <DataTable columns={gridColumns} rows={gridRows} /> : <Text color="gray">暂无网格线</Text>}
|
||||
<Text color="yellow">{t("grid.linesTitle")}</Text>
|
||||
{gridRows.length > 0 ? (
|
||||
<DataTable columns={gridColumns} rows={gridRows} />
|
||||
) : (
|
||||
<Text color="gray">{t("grid.noLines")}</Text>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text color="yellow">目标挂单</Text>
|
||||
{desiredRows.length > 0 ? <DataTable columns={desiredColumns} rows={desiredRows} /> : <Text color="gray">暂无目标挂单</Text>}
|
||||
<Text color="yellow">{t("maker.targetOrders")}</Text>
|
||||
{desiredRows.length > 0 ? (
|
||||
<DataTable columns={desiredColumns} rows={desiredRows} />
|
||||
) : (
|
||||
<Text color="gray">{t("maker.noTargetOrders")}</Text>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="column">
|
||||
<Text color="yellow">最近事件</Text>
|
||||
<Text color="yellow">{t("common.section.recent")}</Text>
|
||||
{lastLogs.length > 0 ? (
|
||||
lastLogs.map((item, index) => (
|
||||
<Text key={`${item.time}-${index}`}>
|
||||
@@ -184,7 +226,7 @@ export function GridApp({ onExit }: GridAppProps) {
|
||||
</Text>
|
||||
))
|
||||
) : (
|
||||
<Text color="gray">暂无日志</Text>
|
||||
<Text color="gray">{t("common.noLogs")}</Text>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
+39
-16
@@ -6,12 +6,13 @@ import { buildAdapterFromEnv } from "../exchanges/resolve-from-env";
|
||||
import { GuardianEngine, type GuardianEngineSnapshot } from "../strategy/guardian-engine";
|
||||
import { formatNumber } from "../utils/format";
|
||||
import { DataTable, type TableColumn } from "./components/DataTable";
|
||||
import { t } from "../i18n";
|
||||
|
||||
interface GuardianAppProps {
|
||||
onExit: () => void;
|
||||
}
|
||||
|
||||
const READY_MESSAGE = "正在等待行情/账户推送…";
|
||||
const READY_MESSAGE = t("guardian.readyMessage");
|
||||
const inputSupported = Boolean(process.stdin && (process.stdin as any).isTTY);
|
||||
|
||||
export function GuardianApp({ onExit }: GuardianAppProps) {
|
||||
@@ -55,8 +56,8 @@ export function GuardianApp({ onExit }: GuardianAppProps) {
|
||||
if (error) {
|
||||
return (
|
||||
<Box flexDirection="column" padding={1}>
|
||||
<Text color="red">Guardian 策略启动失败: {error.message}</Text>
|
||||
<Text color="gray">请检查环境变量和网络连通性。</Text>
|
||||
<Text color="red">{t("guardian.startFailed", { message: error.message })}</Text>
|
||||
<Text color="gray">{t("common.checkEnv")}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -64,7 +65,7 @@ export function GuardianApp({ onExit }: GuardianAppProps) {
|
||||
if (!snapshot) {
|
||||
return (
|
||||
<Box padding={1}>
|
||||
<Text>正在初始化 Guardian 策略…</Text>
|
||||
<Text>{t("guardian.initializing")}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -97,43 +98,65 @@ export function GuardianApp({ onExit }: GuardianAppProps) {
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1} paddingY={0}>
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text color="cyanBright">Guardian Strategy Dashboard</Text>
|
||||
<Text color="cyanBright">{t("guardian.title")}</Text>
|
||||
<Text>
|
||||
交易所: {exchangeName} | 交易对: {snapshot.symbol} | 最近价格: {formatNumber(snapshot.lastPrice, 2)} | 状态: {ready ? "实时运行" : READY_MESSAGE}
|
||||
{t("guardian.headerLine", {
|
||||
exchange: exchangeName,
|
||||
symbol: snapshot.symbol,
|
||||
lastPrice: formatNumber(snapshot.lastPrice, 2),
|
||||
status: ready ? t("status.live") : READY_MESSAGE,
|
||||
})}
|
||||
</Text>
|
||||
<Text color="gray">策略只会维护止损/止盈,不会主动开仓。按 Esc 返回菜单。</Text>
|
||||
<Text color="gray">{t("guardian.hint")}</Text>
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text color="greenBright">当前仓位与风控</Text>
|
||||
<Text color="greenBright">{t("guardian.positionTitle")}</Text>
|
||||
{hasPosition ? (
|
||||
<>
|
||||
<Text>
|
||||
方向: {position.positionAmt > 0 ? "多" : "空"} | 数量: {formatNumber(Math.abs(position.positionAmt), 4)} | 开仓价: {formatNumber(position.entryPrice, 2)} | 浮动盈亏: {formatNumber(snapshot.pnl, 4)} USDT
|
||||
{t("guardian.positionLine", {
|
||||
direction: position.positionAmt > 0 ? t("common.direction.long") : t("common.direction.short"),
|
||||
qty: formatNumber(Math.abs(position.positionAmt), 4),
|
||||
entry: formatNumber(position.entryPrice, 2),
|
||||
pnl: formatNumber(snapshot.pnl, 4),
|
||||
})}
|
||||
</Text>
|
||||
<Text>
|
||||
目标止损价: {formatNumber(snapshot.targetStopPrice, 2)} | 当前止损单: {formatNumber(stopOrderPrice, 2)} | 动态止盈触发: {formatNumber(snapshot.trailingActivationPrice, 2)} | 动态止盈单: {formatNumber(trailingActivate, 2)}
|
||||
{t("guardian.stopLine", {
|
||||
targetStop: formatNumber(snapshot.targetStopPrice, 2),
|
||||
stopOrder: formatNumber(stopOrderPrice, 2),
|
||||
trailingTrigger: formatNumber(snapshot.trailingActivationPrice, 2),
|
||||
trailingOrder: formatNumber(trailingActivate, 2),
|
||||
})}
|
||||
</Text>
|
||||
<Text color={snapshot.requiresStop ? "yellow" : "gray"}>
|
||||
Guardian 状态: {guardStatus === "protecting" ? "已挂止损" : guardStatus === "pending" ? "缺少止损,正在同步" : "监听中"}
|
||||
{t("guardian.stateLabel", {
|
||||
state:
|
||||
guardStatus === "protecting"
|
||||
? t("guardian.status.protecting")
|
||||
: guardStatus === "pending"
|
||||
? t("guardian.status.pending")
|
||||
: t("guardian.status.listening"),
|
||||
})}
|
||||
</Text>
|
||||
</>
|
||||
) : (
|
||||
<Text color="gray">当前无持仓,Guardian 正在监听新的仓位变化。</Text>
|
||||
<Text color="gray">{t("guardian.noPosition")}</Text>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text color="yellow">当前挂单</Text>
|
||||
<Text color="yellow">{t("common.section.orders")}</Text>
|
||||
{orderRows.length > 0 ? (
|
||||
<DataTable columns={orderColumns} rows={orderRows} />
|
||||
) : (
|
||||
<Text color="gray">暂无保护类挂单</Text>
|
||||
<Text color="gray">{t("guardian.noProtectiveOrders")}</Text>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="column">
|
||||
<Text color="yellow">最近事件</Text>
|
||||
<Text color="yellow">{t("common.section.recent")}</Text>
|
||||
{lastLogs.length > 0 ? (
|
||||
lastLogs.map((item, index) => (
|
||||
<Text key={`${item.time}-${index}`}>
|
||||
@@ -141,7 +164,7 @@ export function GuardianApp({ onExit }: GuardianAppProps) {
|
||||
</Text>
|
||||
))
|
||||
) : (
|
||||
<Text color="gray">暂无日志</Text>
|
||||
<Text color="gray">{t("common.noLogs")}</Text>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
+38
-22
@@ -6,6 +6,7 @@ import { buildAdapterFromEnv } from "../exchanges/resolve-from-env";
|
||||
import { MakerEngine, type MakerEngineSnapshot } from "../strategy/maker-engine";
|
||||
import { DataTable, type TableColumn } from "./components/DataTable";
|
||||
import { formatNumber } from "../utils/format";
|
||||
import { t } from "../i18n";
|
||||
|
||||
interface MakerAppProps {
|
||||
onExit: () => void;
|
||||
@@ -54,8 +55,8 @@ export function MakerApp({ onExit }: MakerAppProps) {
|
||||
if (error) {
|
||||
return (
|
||||
<Box flexDirection="column" padding={1}>
|
||||
<Text color="red">启动失败: {error.message}</Text>
|
||||
<Text color="gray">请检查环境变量和网络连通性。</Text>
|
||||
<Text color="red">{t("common.startFailed", { message: error.message })}</Text>
|
||||
<Text color="gray">{t("common.checkEnv")}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -63,7 +64,7 @@ export function MakerApp({ onExit }: MakerAppProps) {
|
||||
if (!snapshot) {
|
||||
return (
|
||||
<Box padding={1}>
|
||||
<Text>正在初始化做市策略…</Text>
|
||||
<Text>{t("maker.initializing")}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -113,22 +114,29 @@ export function MakerApp({ onExit }: MakerAppProps) {
|
||||
const lastLogs = snapshot.tradeLog.slice(-5);
|
||||
const feedStatus = snapshot.feedStatus;
|
||||
const feedEntries: Array<{ key: keyof typeof feedStatus; label: string }> = [
|
||||
{ key: "account", label: "账户" },
|
||||
{ key: "orders", label: "订单" },
|
||||
{ key: "depth", label: "深度" },
|
||||
{ key: "ticker", label: "Ticker" },
|
||||
{ key: "account", label: t("maker.feed.account") },
|
||||
{ key: "orders", label: t("maker.feed.orders") },
|
||||
{ key: "depth", label: t("maker.feed.depth") },
|
||||
{ key: "ticker", label: t("maker.feed.ticker") },
|
||||
];
|
||||
const readyStatus = snapshot.ready ? t("status.live") : t("status.waitingData");
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1}>
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text color="cyanBright">Maker Strategy Dashboard</Text>
|
||||
<Text color="cyanBright">{t("maker.title")}</Text>
|
||||
<Text>
|
||||
交易所: {exchangeName} | 交易对: {snapshot.symbol} | 买一价: {formatNumber(topBid, priceDigits)} | 卖一价: {formatNumber(topAsk, priceDigits)} | 点差: {spreadDisplay}
|
||||
{t("maker.headerLine", {
|
||||
exchange: exchangeName,
|
||||
symbol: snapshot.symbol,
|
||||
bid: formatNumber(topBid, priceDigits),
|
||||
ask: formatNumber(topAsk, priceDigits),
|
||||
spread: spreadDisplay,
|
||||
})}
|
||||
</Text>
|
||||
<Text color="gray">状态: {snapshot.ready ? "实时运行" : "等待市场数据"} | 按 Esc 返回策略选择</Text>
|
||||
<Text color="gray">{t("trend.statusLine", { status: readyStatus })}</Text>
|
||||
<Text>
|
||||
数据状态:
|
||||
{t("maker.dataStatus")}
|
||||
{feedEntries.map((entry, index) => (
|
||||
<Text key={entry.key} color={feedStatus[entry.key] ? "green" : "red"}>
|
||||
{index === 0 ? " " : " "}
|
||||
@@ -140,44 +148,52 @@ export function MakerApp({ onExit }: MakerAppProps) {
|
||||
|
||||
<Box flexDirection="row" marginBottom={1}>
|
||||
<Box flexDirection="column" marginRight={4}>
|
||||
<Text color="greenBright">持仓</Text>
|
||||
<Text color="greenBright">{t("common.section.position")}</Text>
|
||||
{hasPosition ? (
|
||||
<>
|
||||
<Text>
|
||||
方向: {snapshot.position.positionAmt > 0 ? "多" : "空"} | 数量: {formatNumber(Math.abs(snapshot.position.positionAmt), 4)} | 开仓价: {formatNumber(snapshot.position.entryPrice, priceDigits)}
|
||||
{t("maker.positionLine", {
|
||||
direction:
|
||||
snapshot.position.positionAmt > 0 ? t("common.direction.long") : t("common.direction.short"),
|
||||
qty: formatNumber(Math.abs(snapshot.position.positionAmt), 4),
|
||||
entry: formatNumber(snapshot.position.entryPrice, priceDigits),
|
||||
})}
|
||||
</Text>
|
||||
<Text>
|
||||
浮动盈亏: {formatNumber(snapshot.pnl, 4)} USDT | 账户未实现盈亏: {formatNumber(snapshot.accountUnrealized, 4)} USDT
|
||||
{t("maker.pnlLine", {
|
||||
pnl: formatNumber(snapshot.pnl, 4),
|
||||
accountPnl: formatNumber(snapshot.accountUnrealized, 4),
|
||||
})}
|
||||
</Text>
|
||||
</>
|
||||
) : (
|
||||
<Text color="gray">当前无持仓</Text>
|
||||
<Text color="gray">{t("common.noPosition")}</Text>
|
||||
)}
|
||||
</Box>
|
||||
<Box flexDirection="column">
|
||||
<Text color="greenBright">目标挂单</Text>
|
||||
<Text color="greenBright">{t("maker.targetOrders")}</Text>
|
||||
{desiredRows.length > 0 ? (
|
||||
<DataTable columns={desiredColumns} rows={desiredRows} />
|
||||
) : (
|
||||
<Text color="gray">暂无目标挂单</Text>
|
||||
<Text color="gray">{t("maker.noTargetOrders")}</Text>
|
||||
)}
|
||||
<Text>
|
||||
累计成交量: {formatNumber(snapshot.sessionVolume, 2)} USDT
|
||||
{t("trend.volumeLine", { volume: formatNumber(snapshot.sessionVolume, 2) })}
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text color="yellow">当前挂单</Text>
|
||||
<Text color="yellow">{t("common.section.orders")}</Text>
|
||||
{openOrderRows.length > 0 ? (
|
||||
<DataTable columns={openOrderColumns} rows={openOrderRows} />
|
||||
) : (
|
||||
<Text color="gray">暂无挂单</Text>
|
||||
<Text color="gray">{t("common.noOrders")}</Text>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="column">
|
||||
<Text color="yellow">最近事件</Text>
|
||||
<Text color="yellow">{t("common.section.recent")}</Text>
|
||||
{lastLogs.length > 0 ? (
|
||||
lastLogs.map((item, index) => (
|
||||
<Text key={`${item.time}-${index}`}>
|
||||
@@ -185,7 +201,7 @@ export function MakerApp({ onExit }: MakerAppProps) {
|
||||
</Text>
|
||||
))
|
||||
) : (
|
||||
<Text color="gray">暂无日志</Text>
|
||||
<Text color="gray">{t("common.noLogs")}</Text>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
+48
-24
@@ -6,6 +6,7 @@ import { buildAdapterFromEnv } from "../exchanges/resolve-from-env";
|
||||
import { OffsetMakerEngine, type OffsetMakerEngineSnapshot } from "../strategy/offset-maker-engine";
|
||||
import { DataTable, type TableColumn } from "./components/DataTable";
|
||||
import { formatNumber } from "../utils/format";
|
||||
import { t } from "../i18n";
|
||||
|
||||
interface OffsetMakerAppProps {
|
||||
onExit: () => void;
|
||||
@@ -54,8 +55,8 @@ export function OffsetMakerApp({ onExit }: OffsetMakerAppProps) {
|
||||
if (error) {
|
||||
return (
|
||||
<Box flexDirection="column" padding={1}>
|
||||
<Text color="red">启动失败: {error.message}</Text>
|
||||
<Text color="gray">请检查环境变量和网络连通性。</Text>
|
||||
<Text color="red">{t("common.startFailed", { message: error.message })}</Text>
|
||||
<Text color="gray">{t("common.checkEnv")}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -63,7 +64,7 @@ export function OffsetMakerApp({ onExit }: OffsetMakerAppProps) {
|
||||
if (!snapshot) {
|
||||
return (
|
||||
<Box padding={1}>
|
||||
<Text>正在初始化偏移做市策略…</Text>
|
||||
<Text>{t("offset.initializing")}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -113,68 +114,91 @@ export function OffsetMakerApp({ onExit }: OffsetMakerAppProps) {
|
||||
];
|
||||
|
||||
const lastLogs = snapshot.tradeLog.slice(-5);
|
||||
const imbalanceLabel = snapshot.depthImbalance === "balanced"
|
||||
? "均衡"
|
||||
: snapshot.depthImbalance === "buy_dominant"
|
||||
? "买盘占优"
|
||||
: "卖盘占优";
|
||||
const imbalanceLabel =
|
||||
snapshot.depthImbalance === "balanced"
|
||||
? t("offset.imbalance.balanced")
|
||||
: snapshot.depthImbalance === "buy_dominant"
|
||||
? t("offset.imbalance.buy")
|
||||
: t("offset.imbalance.sell");
|
||||
const readyStatus = snapshot.ready ? t("status.live") : t("status.waitingData");
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1}>
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text color="cyanBright">Offset Maker Strategy Dashboard</Text>
|
||||
<Text color="cyanBright">{t("offset.title")}</Text>
|
||||
<Text>
|
||||
交易所: {exchangeName} | 交易对: {snapshot.symbol} | 买一价: {formatNumber(topBid, priceDigits)} | 卖一价: {formatNumber(topAsk, priceDigits)} | 点差: {spreadDisplay}
|
||||
{t("offset.headerLine", {
|
||||
exchange: exchangeName,
|
||||
symbol: snapshot.symbol,
|
||||
bid: formatNumber(topBid, priceDigits),
|
||||
ask: formatNumber(topAsk, priceDigits),
|
||||
spread: spreadDisplay,
|
||||
})}
|
||||
</Text>
|
||||
<Text>
|
||||
买10档累计: {formatNumber(snapshot.buyDepthSum10, 4)} | 卖10档累计: {formatNumber(snapshot.sellDepthSum10, 4)} | 状态: {imbalanceLabel}
|
||||
{t("offset.depthLine", {
|
||||
buy: formatNumber(snapshot.buyDepthSum10, 4),
|
||||
sell: formatNumber(snapshot.sellDepthSum10, 4),
|
||||
status: imbalanceLabel,
|
||||
})}
|
||||
</Text>
|
||||
<Text color="gray">
|
||||
当前挂单策略: BUY {snapshot.skipBuySide ? "暂停" : "启用"} | SELL {snapshot.skipSellSide ? "暂停" : "启用"} | 按 Esc 返回策略选择
|
||||
{t("offset.strategyStatus", {
|
||||
buyStatus: snapshot.skipBuySide ? t("common.disabled") : t("common.enabled"),
|
||||
sellStatus: snapshot.skipSellSide ? t("common.disabled") : t("common.enabled"),
|
||||
})}
|
||||
</Text>
|
||||
<Text color="gray">状态: {snapshot.ready ? "实时运行" : "等待市场数据"}</Text>
|
||||
<Text color="gray">{t("trend.statusLine", { status: readyStatus })}</Text>
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="row" marginBottom={1}>
|
||||
<Box flexDirection="column" marginRight={4}>
|
||||
<Text color="greenBright">持仓</Text>
|
||||
<Text color="greenBright">{t("common.section.position")}</Text>
|
||||
{hasPosition ? (
|
||||
<>
|
||||
<Text>
|
||||
方向: {snapshot.position.positionAmt > 0 ? "多" : "空"} | 数量: {formatNumber(Math.abs(snapshot.position.positionAmt), 4)} | 开仓价: {formatNumber(snapshot.position.entryPrice, priceDigits)}
|
||||
{t("maker.positionLine", {
|
||||
direction:
|
||||
snapshot.position.positionAmt > 0 ? t("common.direction.long") : t("common.direction.short"),
|
||||
qty: formatNumber(Math.abs(snapshot.position.positionAmt), 4),
|
||||
entry: formatNumber(snapshot.position.entryPrice, priceDigits),
|
||||
})}
|
||||
</Text>
|
||||
<Text>
|
||||
浮动盈亏: {formatNumber(snapshot.pnl, 4)} USDT | 账户未实现盈亏: {formatNumber(snapshot.accountUnrealized, 4)} USDT
|
||||
{t("maker.pnlLine", {
|
||||
pnl: formatNumber(snapshot.pnl, 4),
|
||||
accountPnl: formatNumber(snapshot.accountUnrealized, 4),
|
||||
})}
|
||||
</Text>
|
||||
</>
|
||||
) : (
|
||||
<Text color="gray">当前无持仓</Text>
|
||||
<Text color="gray">{t("common.noPosition")}</Text>
|
||||
)}
|
||||
</Box>
|
||||
<Box flexDirection="column">
|
||||
<Text color="greenBright">目标挂单</Text>
|
||||
<Text color="greenBright">{t("maker.targetOrders")}</Text>
|
||||
{desiredRows.length > 0 ? (
|
||||
<DataTable columns={desiredColumns} rows={desiredRows} />
|
||||
) : (
|
||||
<Text color="gray">暂无目标挂单</Text>
|
||||
<Text color="gray">{t("maker.noTargetOrders")}</Text>
|
||||
)}
|
||||
<Text>
|
||||
累计成交量: {formatNumber(snapshot.sessionVolume, 2)} USDT
|
||||
{t("trend.volumeLine", { volume: formatNumber(snapshot.sessionVolume, 2) })}
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text color="yellow">当前挂单</Text>
|
||||
<Text color="yellow">{t("common.section.orders")}</Text>
|
||||
{openOrderRows.length > 0 ? (
|
||||
<DataTable columns={openOrderColumns} rows={openOrderRows} />
|
||||
) : (
|
||||
<Text color="gray">暂无挂单</Text>
|
||||
<Text color="gray">{t("common.noOrders")}</Text>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="column">
|
||||
<Text color="yellow">最近事件</Text>
|
||||
<Text color="yellow">{t("common.section.recent")}</Text>
|
||||
{lastLogs.length > 0 ? (
|
||||
lastLogs.map((item, index) => (
|
||||
<Text key={`${item.time}-${index}`}>
|
||||
@@ -182,7 +206,7 @@ export function OffsetMakerApp({ onExit }: OffsetMakerAppProps) {
|
||||
</Text>
|
||||
))
|
||||
) : (
|
||||
<Text color="gray">暂无日志</Text>
|
||||
<Text color="gray">{t("common.noLogs")}</Text>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
+42
-20
@@ -4,10 +4,11 @@ import { tradingConfig } from "../config";
|
||||
import { getExchangeDisplayName, resolveExchangeId } from "../exchanges/create-adapter";
|
||||
import { buildAdapterFromEnv } from "../exchanges/resolve-from-env";
|
||||
import { TrendEngine, type TrendEngineSnapshot } from "../strategy/trend-engine";
|
||||
import { formatNumber } from "../utils/format";
|
||||
import { formatNumber, formatTrendLabel } from "../utils/format";
|
||||
import { DataTable, type TableColumn } from "./components/DataTable";
|
||||
import { t } from "../i18n";
|
||||
|
||||
const READY_MESSAGE = "正在等待交易所推送数据…";
|
||||
const READY_MESSAGE = t("trend.readyMessage");
|
||||
|
||||
interface TrendAppProps {
|
||||
onExit: () => void;
|
||||
@@ -56,8 +57,8 @@ export function TrendApp({ onExit }: TrendAppProps) {
|
||||
if (error) {
|
||||
return (
|
||||
<Box flexDirection="column" padding={1}>
|
||||
<Text color="red">启动失败: {error.message}</Text>
|
||||
<Text color="gray">请检查环境变量和网络连通性。</Text>
|
||||
<Text color="red">{t("common.startFailed", { message: error.message })}</Text>
|
||||
<Text color="gray">{t("common.checkEnv")}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -65,7 +66,7 @@ export function TrendApp({ onExit }: TrendAppProps) {
|
||||
if (!snapshot) {
|
||||
return (
|
||||
<Box padding={1}>
|
||||
<Text>正在初始化趋势策略…</Text>
|
||||
<Text>{t("common.initializing", { target: t("trend.name") })}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -96,56 +97,77 @@ export function TrendApp({ onExit }: TrendAppProps) {
|
||||
return (
|
||||
<Box flexDirection="column" paddingX={1} paddingY={0}>
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text color="cyanBright">Trend Strategy Dashboard</Text>
|
||||
<Text color="cyanBright">{t("trend.title")}</Text>
|
||||
<Text>
|
||||
交易所: {exchangeName} | 交易对: {snapshot.symbol} | 最近价格: {formatNumber(lastPrice, 2)} | SMA30: {formatNumber(sma30, 2)} | 趋势: {trend}
|
||||
{t("trend.headerLine", {
|
||||
exchange: exchangeName,
|
||||
symbol: snapshot.symbol,
|
||||
lastPrice: formatNumber(lastPrice, 2),
|
||||
sma: formatNumber(sma30, 2),
|
||||
trend: formatTrendLabel(trend),
|
||||
})}
|
||||
</Text>
|
||||
<Text color="gray">
|
||||
{t("trend.statusLine", { status: ready ? t("status.live") : READY_MESSAGE })}
|
||||
</Text>
|
||||
<Text color="gray">状态: {ready ? "实时运行" : READY_MESSAGE} | 按 Esc 返回策略选择</Text>
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="row" marginBottom={1}>
|
||||
<Box flexDirection="column" marginRight={4}>
|
||||
<Text color="greenBright">持仓</Text>
|
||||
<Text color="greenBright">{t("common.section.position")}</Text>
|
||||
{hasPosition ? (
|
||||
<>
|
||||
<Text>
|
||||
方向: {position.positionAmt > 0 ? "多" : "空"} | 数量: {formatNumber(Math.abs(position.positionAmt), 4)} | 开仓价: {formatNumber(position.entryPrice, 2)}
|
||||
{t("trend.positionLine", {
|
||||
direction: position.positionAmt > 0 ? t("common.direction.long") : t("common.direction.short"),
|
||||
qty: formatNumber(Math.abs(position.positionAmt), 4),
|
||||
entry: formatNumber(position.entryPrice, 2),
|
||||
})}
|
||||
</Text>
|
||||
<Text>
|
||||
浮动盈亏: {formatNumber(snapshot.pnl, 4)} USDT | 账户未实现盈亏: {formatNumber(snapshot.unrealized, 4)} USDT
|
||||
{t("trend.pnlLine", {
|
||||
pnl: formatNumber(snapshot.pnl, 4),
|
||||
unrealized: formatNumber(snapshot.unrealized, 4),
|
||||
})}
|
||||
</Text>
|
||||
</>
|
||||
) : (
|
||||
<Text color="gray">当前无持仓</Text>
|
||||
<Text color="gray">{t("common.noPosition")}</Text>
|
||||
)}
|
||||
</Box>
|
||||
<Box flexDirection="column">
|
||||
<Text color="greenBright">绩效</Text>
|
||||
<Text color="greenBright">{t("common.section.performance")}</Text>
|
||||
<Text>
|
||||
累计交易次数: {snapshot.totalTrades} | 累计收益: {formatNumber(snapshot.totalProfit, 4)} USDT
|
||||
{t("trend.performanceLine", {
|
||||
trades: snapshot.totalTrades,
|
||||
profit: formatNumber(snapshot.totalProfit, 4),
|
||||
})}
|
||||
</Text>
|
||||
<Text>
|
||||
累计成交量: {formatNumber(sessionVolume, 2)} USDT
|
||||
{t("trend.volumeLine", { volume: formatNumber(sessionVolume, 2) })}
|
||||
</Text>
|
||||
{snapshot.lastOpenSignal.side ? (
|
||||
<Text color="gray">
|
||||
最近开仓信号: {snapshot.lastOpenSignal.side} @ {formatNumber(snapshot.lastOpenSignal.price, 2)}
|
||||
{t("trend.lastSignal", {
|
||||
side: snapshot.lastOpenSignal.side,
|
||||
price: formatNumber(snapshot.lastOpenSignal.price, 2),
|
||||
})}
|
||||
</Text>
|
||||
) : null}
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="column" marginBottom={1}>
|
||||
<Text color="yellow">当前挂单</Text>
|
||||
<Text color="yellow">{t("common.section.orders")}</Text>
|
||||
{orderRows.length > 0 ? (
|
||||
<DataTable columns={orderColumns} rows={orderRows} />
|
||||
) : (
|
||||
<Text color="gray">暂无挂单</Text>
|
||||
<Text color="gray">{t("common.noOrders")}</Text>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<Box flexDirection="column">
|
||||
<Text color="yellow">最近交易与事件</Text>
|
||||
<Text color="yellow">{t("common.section.recentTrades")}</Text>
|
||||
{lastLogs.length > 0 ? (
|
||||
lastLogs.map((item, index) => (
|
||||
<Text key={`${item.time}-${index}`}>
|
||||
@@ -153,7 +175,7 @@ export function TrendApp({ onExit }: TrendAppProps) {
|
||||
</Text>
|
||||
))
|
||||
) : (
|
||||
<Text color="gray">暂无日志</Text>
|
||||
<Text color="gray">{t("common.noLogs")}</Text>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
+10
-4
@@ -1,8 +1,14 @@
|
||||
import { t } from "../i18n";
|
||||
|
||||
export type TrendLabel = "做多" | "做空" | "无信号";
|
||||
|
||||
export function formatTrendLabel(trend: TrendLabel): string {
|
||||
if (trend === "做多") return t("trend.label.long");
|
||||
if (trend === "做空") return t("trend.label.short");
|
||||
return t("trend.label.none");
|
||||
}
|
||||
|
||||
export function formatNumber(value: number | null | undefined, digits = 4, fallback = "-"): string {
|
||||
if (value == null || Number.isNaN(value)) return fallback;
|
||||
return Number(value).toFixed(digits);
|
||||
}
|
||||
|
||||
export function formatTrendLabel(trend: "做多" | "做空" | "无信号"): string {
|
||||
return trend;
|
||||
}
|
||||
|
||||
+47
-1
@@ -1,4 +1,4 @@
|
||||
import type { AsterAccountSnapshot, AsterKline } from "../exchanges/types";
|
||||
import type { AsterAccountAsset, AsterAccountSnapshot, AsterKline } from "../exchanges/types";
|
||||
|
||||
export interface PositionSnapshot {
|
||||
positionAmt: number;
|
||||
@@ -11,6 +11,22 @@ export function getPosition(snapshot: AsterAccountSnapshot | null, symbol: strin
|
||||
if (!snapshot) {
|
||||
return { positionAmt: 0, entryPrice: 0, unrealizedProfit: 0, markPrice: null };
|
||||
}
|
||||
// For spot, derive position strictly from asset balances to avoid WS-cleared positions.
|
||||
if (snapshot.marketType === "spot") {
|
||||
const baseSymbol =
|
||||
normalizeBaseSymbol(snapshot.baseAsset) ?? parseSymbolParts(symbol).base ?? normalizeBaseSymbol(symbol);
|
||||
if (baseSymbol) {
|
||||
const asset = selectAsset(snapshot.assets ?? [], baseSymbol, snapshot.baseAssetId);
|
||||
const amt = Number(asset?.walletBalance ?? 0);
|
||||
const available = Number(asset?.availableBalance ?? asset?.walletBalance ?? 0);
|
||||
const size = Number.isFinite(amt) && amt > 0 ? amt : Number.isFinite(available) ? Math.max(0, available) : 0;
|
||||
if (size > 0) {
|
||||
return { positionAmt: size, entryPrice: 0, unrealizedProfit: 0, markPrice: null };
|
||||
}
|
||||
}
|
||||
return { positionAmt: 0, entryPrice: 0, unrealizedProfit: 0, markPrice: null };
|
||||
}
|
||||
|
||||
const positions = snapshot.positions?.filter((p) => p.symbol === symbol) ?? [];
|
||||
if (positions.length === 0) {
|
||||
return { positionAmt: 0, entryPrice: 0, unrealizedProfit: 0, markPrice: null };
|
||||
@@ -112,3 +128,33 @@ export function isOrderPriceAllowedByMark(params: {
|
||||
}
|
||||
return price >= mark * (1 - Math.max(0, maxPct));
|
||||
}
|
||||
|
||||
export function parseSymbolParts(symbol: string | undefined): { base?: string; quote?: string } {
|
||||
const normalized = (symbol ?? "").toUpperCase();
|
||||
if (!normalized) return {};
|
||||
const delimiters = ["/", "-", ":"];
|
||||
for (const delimiter of delimiters) {
|
||||
if (normalized.includes(delimiter)) {
|
||||
const [base, quote] = normalized.split(delimiter);
|
||||
return { base: base || undefined, quote: quote || undefined };
|
||||
}
|
||||
}
|
||||
if (normalized.length >= 6) {
|
||||
return { base: normalized.slice(0, 3), quote: normalized.slice(3) };
|
||||
}
|
||||
return { base: normalized };
|
||||
}
|
||||
|
||||
function normalizeBaseSymbol(symbol: string | undefined): string | undefined {
|
||||
return parseSymbolParts(symbol).base;
|
||||
}
|
||||
|
||||
function selectAsset(assets: AsterAccountAsset[], baseSymbol: string, baseAssetId?: number): AsterAccountAsset | undefined {
|
||||
const normalized = baseSymbol.toUpperCase();
|
||||
const targetId = Number(baseAssetId);
|
||||
return assets.find((asset) => {
|
||||
const matchesId = Number.isFinite(targetId) && Number(asset.assetId) === targetId;
|
||||
const matchesSymbol = normalizeBaseSymbol(asset.asset) === normalized;
|
||||
return matchesId || matchesSymbol;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { LighterOrderBookMetadata } from "../../src/exchanges/lighter/types";
|
||||
import { LighterGateway } from "../../src/exchanges/lighter/gateway";
|
||||
|
||||
const pickBestOrderBook = (books: LighterOrderBookMetadata[], desiredSymbol: string) =>
|
||||
(LighterGateway.prototype as any).pickBestOrderBook.call({}, books, desiredSymbol);
|
||||
|
||||
describe("pickBestOrderBook", () => {
|
||||
const spotBook = {
|
||||
market_id: 2048,
|
||||
symbol: "ETH/USDC",
|
||||
market_type: "spot",
|
||||
supported_price_decimals: 2,
|
||||
supported_size_decimals: 4,
|
||||
min_base_amount: "0.0001",
|
||||
min_quote_amount: "5",
|
||||
} as LighterOrderBookMetadata;
|
||||
|
||||
const perpBook = {
|
||||
market_id: 3048,
|
||||
symbol: "ETH-PERP",
|
||||
market_type: "perp",
|
||||
supported_price_decimals: 2,
|
||||
supported_size_decimals: 3,
|
||||
min_base_amount: "0.001",
|
||||
min_quote_amount: "5",
|
||||
} as LighterOrderBookMetadata;
|
||||
|
||||
it("prefers perp when desired symbol does not explicitly request spot", () => {
|
||||
const picked = pickBestOrderBook([spotBook, perpBook], "ETH");
|
||||
expect(picked?.market_type).toBe("perp");
|
||||
expect(picked?.market_id).toBe(3048);
|
||||
});
|
||||
|
||||
it("still prefers spot when symbol clearly indicates spot", () => {
|
||||
const picked = pickBestOrderBook([spotBook, perpBook], "ETH/USDC");
|
||||
expect(picked?.market_type).toBe("spot");
|
||||
expect(picked?.market_id).toBe(2048);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user