support lighter spot

This commit is contained in:
discountry
2025-12-07 21:37:58 +08:00
parent 5f79b134f2
commit 180f47b6e0
89 changed files with 11921 additions and 124 deletions
View File
@@ -0,0 +1,2 @@
*.go text eol=lf
+5
View File
@@ -0,0 +1,5 @@
.idea
vendor
build/*
!build/.keep
/build
+201
View File
@@ -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.
+94
View File
@@ -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
}
+28
View File
@@ -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
)
+76
View File
@@ -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=
+49
View File
@@ -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
}
+731
View File
@@ -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 {}
}
+616 -23
View File
@@ -7,7 +7,15 @@ import type {
OrderListener,
TickerListener,
} from "../adapter";
import type { AsterAccountSnapshot, AsterDepth, AsterKline, AsterOrder, AsterTicker, CreateOrderParams } from "../types";
import type {
AsterAccountAsset,
AsterAccountSnapshot,
AsterDepth,
AsterKline,
AsterOrder,
AsterTicker,
CreateOrderParams,
} from "../types";
import { extractMessage } from "../../utils/errors";
import type { OrderSide, OrderType } from "../types";
import { LighterHttpClient } from "./http-client";
@@ -16,10 +24,12 @@ import { LighterSigner, type CreateOrderSignParams } from "./signer";
import { bytesToHex } from "./bytes";
import type {
LighterAccountDetails,
LighterAccountAsset,
LighterKline,
LighterMarketStats,
LighterOrder,
LighterOrderBookLevel,
LighterOrderBookMetadata,
LighterOrderBookSnapshot,
LighterPosition,
} from "./types";
@@ -145,6 +155,10 @@ const TERMINAL_ORDER_STATUSES = new Set([
"canceled-reduce-only",
]);
const KNOWN_SPOT_MARKETS: Record<string, { marketId: number; base: string; quote: string; priceDecimals?: number; sizeDecimals?: number }> = {
ETHUSDC: { marketId: 2048, base: "ETH", quote: "USDC", priceDecimals: 2, sizeDecimals: 4 },
};
export interface LighterGatewayOptions {
symbol: string; // display symbol used by strategy logging
marketSymbol?: string; // actual Lighter order book symbol (e.g., BTC)
@@ -188,10 +202,19 @@ export class LighterGateway {
private lastWsPositionUpdateAt = 0;
private readonly lastWsPositionByMarket = new Map<number, number>();
private httpPositionsEmptyLogged = false;
private forcedSpotPreset = false;
private marketId: number | null = null;
private marketType: "perp" | "spot" | null = null;
private priceDecimals: number | null = null;
private sizeDecimals: number | null = null;
private baseAssetId: number | null = null;
private quoteAssetId: number | null = null;
private baseAssetSymbol: string | null = null;
private quoteAssetSymbol: string | null = null;
private readonly assets = new Map<string, LighterAccountAsset>();
private minBaseAmount: number | null = null;
private minQuoteAmount: number | null = null;
private readonly orderIndexByClientId = new Map<string, string>();
private ws: WebSocket | null = null;
@@ -209,6 +232,10 @@ export class LighterGateway {
private orderBook: LighterOrderBookSnapshot | null = null;
private ticker: LighterMarketStats | null = null;
private initialized = false;
private readonly pendingJsonRequests = new Map<
string,
{ resolve: (value: unknown) => void; reject: (error: unknown) => void }
>();
private readonly tickerPollMs: number;
private readonly klinePollMs: number;
@@ -226,11 +253,33 @@ export class LighterGateway {
constructor(options: LighterGatewayOptions) {
this.displaySymbol = options.symbol;
this.marketSymbol = (options.marketSymbol ?? options.symbol).toUpperCase();
this.environment = inferEnvironment(options.environment, options.baseUrl);
this.marketType = guessMarketType(this.marketSymbol);
const parsedSymbols = parseBaseQuote(this.marketSymbol);
this.baseAssetSymbol = parsedSymbols.base ?? null;
this.quoteAssetSymbol = parsedSymbols.quote ?? null;
this.applyPresetMarket();
if (process.env.LIGHTER_MARKET_ID) {
this.marketId = Number(process.env.LIGHTER_MARKET_ID);
}
if (process.env.LIGHTER_MARKET_TYPE) {
this.marketType = normalizeMarketType(process.env.LIGHTER_MARKET_TYPE) ?? this.marketType;
}
const envPreference =
options.environment ??
process.env.LIGHTER_ENV ??
(this.forcedSpotPreset && !options.baseUrl ? "mainnet" : undefined);
this.environment = inferEnvironment(envPreference, options.baseUrl);
const host = options.baseUrl ?? LIGHTER_HOSTS[this.environment]?.rest;
if (!host) {
throw new Error(`Unknown Lighter environment ${this.environment}`);
}
if (process.env.LIGHTER_DEBUG === "1" || process.env.LIGHTER_DEBUG === "true") {
// eslint-disable-next-line no-console
console.error(
"[LighterGateway] init",
JSON.stringify({ env: this.environment, host, marketId: this.marketId, marketType: this.marketType })
);
}
const wsHost = LIGHTER_HOSTS[this.environment]?.ws;
if (!wsHost) {
throw new Error(`WebSocket endpoint not configured for env ${this.environment}`);
@@ -244,6 +293,9 @@ export class LighterGateway {
baseUrl: host,
});
this.apiKeyIndices = options.apiKeyIndices ?? Object.keys(options.apiKeys).map(Number);
if (this.forcedSpotPreset && this.apiKeyIndices.length > 1) {
this.apiKeyIndices.splice(1); // stick to the first key to avoid nonce drift
}
this.nonceManager = new HttpNonceManager({
accountIndex: options.accountIndex,
apiKeyIndices: this.apiKeyIndices,
@@ -306,6 +358,8 @@ export class LighterGateway {
await this.ensureInitialized();
const conversion = this.mapCreateOrderParams(params);
const { baseAmountScaledString, priceScaledString, triggerPriceScaledString, ...signParams } = conversion;
const attemptCreate = async (): Promise<AsterOrder> => {
const { apiKeyIndex, nonce } = this.nonceManager.next();
try {
const signed = await this.signer.signCreateOrder({
@@ -314,16 +368,15 @@ export class LighterGateway {
nonce,
});
const debugEnabled = process.env.LIGHTER_DEBUG === "1" || process.env.LIGHTER_DEBUG === "true";
if (this.logTxInfo && !this.loggedCreateOrderPayload) {
this.logger("createOrder.txInfo", signed.txInfo);
this.loggedCreateOrderPayload = true;
if (this.logTxInfo || debugEnabled) {
// eslint-disable-next-line no-console
console.error(
"[LighterGateway] createOrder.tx",
JSON.stringify({ txType: signed.txType, txInfo: signed.txInfo })
);
}
const auth = await this.ensureAuthToken();
const response = await this.http.sendTransaction(signed.txType, signed.txInfo, {
authToken: auth,
priceProtection: false,
});
if (debugEnabled && response.code !== 200) {
const response = await this.dispatchTransaction(signed.txType, signed.txInfo, { priceProtection: false });
if (debugEnabled && (response as { code?: number })?.code && (response as { code?: number }).code !== 200) {
this.logger("createOrder.sendTx.response", response);
}
const clientOrderIndexStr = signParams.clientOrderIndex.toString();
@@ -346,9 +399,23 @@ export class LighterGateway {
} as LighterOrder);
} catch (error) {
this.nonceManager.acknowledgeFailure(apiKeyIndex);
if (isInvalidNonce(error)) {
await this.nonceManager.refresh(apiKeyIndex).catch((err) => this.logger("nonce.refresh", err));
throw new Error("RETRY_INVALID_NONCE");
}
this.logger("createOrder", error);
throw error;
}
};
try {
return await attemptCreate();
} catch (error) {
if (error instanceof Error && error.message === "RETRY_INVALID_NONCE") {
return await attemptCreate();
}
throw error;
}
}
async cancelOrder(params: { marketIndex?: number; orderId: number | string; apiKeyIndex?: number }): Promise<void> {
@@ -365,12 +432,14 @@ export class LighterGateway {
nonce,
apiKeyIndex,
});
const auth = await this.ensureAuthToken();
await this.http.sendTransaction(signed.txType, signed.txInfo, { authToken: auth });
await this.dispatchTransaction(signed.txType, signed.txInfo);
// Optimistically remove the order locally to avoid stale duplicates until WS confirms
this.removeOrderLocally(String(params.orderId));
} catch (error) {
this.nonceManager.acknowledgeFailure(apiKeyIndex);
if (isInvalidNonce(error)) {
await this.nonceManager.refresh(apiKeyIndex).catch((err) => this.logger("nonce.refresh", err));
}
throw error;
}
}
@@ -387,10 +456,12 @@ export class LighterGateway {
nonce,
apiKeyIndex,
});
const auth = await this.ensureAuthToken();
await this.http.sendTransaction(signed.txType, signed.txInfo, { authToken: auth });
await this.dispatchTransaction(signed.txType, signed.txInfo);
} catch (error) {
this.nonceManager.acknowledgeFailure(apiKeyIndex);
if (isInvalidNonce(error)) {
await this.nonceManager.refresh(apiKeyIndex).catch((err) => this.logger("nonce.refresh", err));
}
throw error;
}
}
@@ -409,12 +480,47 @@ export class LighterGateway {
}
private async loadMetadata(): Promise<void> {
if (this.marketId != null && this.priceDecimals != null && this.sizeDecimals != null) return;
const books = await this.http.getOrderBooks();
const desiredSymbol = this.marketSymbol;
let target = books.find((book) => (book.symbol ? String(book.symbol).toUpperCase() : "") === desiredSymbol);
if (!target && this.marketId != null) {
target = books.find((book) => Number(book.market_id) === Number(this.marketId));
const wantsSpot = guessMarketType(desiredSymbol) === "spot" || this.marketType === "spot";
this.logger("loadMetadata", { desiredSymbol, wantsSpot, presetMarketId: this.marketId, bookCount: books.length });
let target: LighterOrderBookMetadata | null = null;
if (!this.marketId && wantsSpot) {
const normalized = desiredSymbol.toUpperCase().replace(/[^A-Z0-9]/g, "");
const preset = KNOWN_SPOT_MARKETS[normalized];
if (preset) {
this.marketId = preset.marketId;
this.baseAssetSymbol = this.baseAssetSymbol ?? preset.base;
this.quoteAssetSymbol = this.quoteAssetSymbol ?? preset.quote;
this.marketType = "spot";
}
}
// If marketId is explicitly set (env/preset), force-match by ID first
if (this.marketId != null) {
target = books.find((book) => Number(book.market_id) === Number(this.marketId)) ?? null;
if (wantsSpot && target && normalizeMarketType(target.market_type) !== "spot") {
// Do not silently switch to perp; enforce spot
const spotById = books.find(
(book) =>
normalizeMarketType(book.market_type) === "spot" && Number(book.market_id) === Number(this.marketId)
);
target = spotById ?? null;
}
if (!target) {
throw new Error(
`Configured market id ${this.marketId} not found in Lighter order books. Check LIGHTER_ENV/baseUrl matches the venue that lists spot ETH/USDC (e.g., mainnet).`
);
}
}
if (!target) {
target = this.pickBestOrderBook(books, desiredSymbol, this.marketId);
if (wantsSpot && (!target || normalizeMarketType(target.market_type) !== "spot")) {
const spotAlt = this.findSpotSibling(books, desiredSymbol, this.marketId);
if (spotAlt) target = spotAlt;
}
}
if (!target) {
if (this.marketId != null && this.priceDecimals != null && this.sizeDecimals != null) {
@@ -422,13 +528,31 @@ export class LighterGateway {
}
throw new Error(`Symbol ${desiredSymbol} not listed on Lighter order books`);
}
if (wantsSpot && normalizeMarketType(target.market_type) !== "spot") {
throw new Error(
`Expected spot market for ${desiredSymbol}, but resolved to market_id=${target.market_id} type=${target.market_type ?? "unknown"}`
);
}
this.marketId = Number(target.market_id);
this.marketType = normalizeMarketType(target.market_type) ?? this.marketType ?? guessMarketType(target.symbol);
this.baseAssetId = target.base_asset_id ?? this.baseAssetId;
this.quoteAssetId = target.quote_asset_id ?? this.quoteAssetId;
this.minBaseAmount = Number(target.min_base_amount ?? target.min_base_amount);
this.minQuoteAmount = Number(target.min_quote_amount ?? target.min_quote_amount);
if (this.priceDecimals == null) {
this.priceDecimals = target.supported_price_decimals;
}
if (this.sizeDecimals == null) {
this.sizeDecimals = target.supported_size_decimals;
}
if (!this.baseAssetSymbol || !this.quoteAssetSymbol) {
const parsed = parseBaseQuote(target.symbol ?? this.marketSymbol);
if (!this.baseAssetSymbol) this.baseAssetSymbol = parsed.base ?? null;
if (!this.quoteAssetSymbol) this.quoteAssetSymbol = parsed.quote ?? null;
}
if (wantsSpot && this.marketType !== "spot") {
throw new Error(`Expected spot market for ${desiredSymbol}, but resolved to ${target.market_type ?? "unknown"}`);
}
}
private async refreshAccountSnapshot(): Promise<void> {
@@ -462,6 +586,7 @@ export class LighterGateway {
}
this.accountDetails = details;
this.applyHttpPositions(details);
this.applyAccountAssets(details.assets);
this.emitAccount();
} catch (error) {
this.logger("refreshAccount", error);
@@ -487,6 +612,27 @@ export class LighterGateway {
}
}
private applyAccountAssets(assets?: LighterAccountAsset[] | Record<string, LighterAccountAsset> | null): void {
const normalized = this.normalizeAssets(assets);
if (!normalized.length) {
return; // ignore empty payloads to avoid wiping spot balances
}
for (const asset of normalized) {
const key = this.normalizeAssetKey(asset);
if (!key) continue;
this.assets.set(key, asset);
const assetId = Number(asset.asset_id);
if (Number.isFinite(assetId)) {
if (this.baseAssetId != null && assetId === this.baseAssetId && asset.symbol) {
this.baseAssetSymbol = asset.symbol.toUpperCase();
}
if (this.quoteAssetId != null && assetId === this.quoteAssetId && asset.symbol) {
this.quoteAssetSymbol = asset.symbol.toUpperCase();
}
}
}
}
private recordWsPositionUpdate(): void {
this.lastWsPositionUpdateAt = Date.now();
this.httpPositionsEmptyLogged = false;
@@ -531,6 +677,7 @@ export class LighterGateway {
ws.removeAllListeners();
this.stopHeartbeat();
this.stopClientPing();
this.rejectPendingJsonRequests(new Error("WebSocket closed"));
if (this.ws === ws) {
this.ws = null;
}
@@ -608,6 +755,13 @@ export class LighterGateway {
auth,
})
);
ws.send(
JSON.stringify({
type: "subscribe",
channel: `account_all_assets/${Number(this.signer.accountIndex)}`,
auth,
})
);
}
private async ensureAuthToken(): Promise<string> {
@@ -622,6 +776,109 @@ export class LighterGateway {
return token;
}
private async dispatchTransaction(
txType: number,
txInfo: string,
options: { priceProtection?: boolean } = {}
): Promise<unknown> {
const auth = await this.ensureAuthToken();
try {
return await this.http.sendTransaction(txType, txInfo, {
authToken: auth,
priceProtection: options.priceProtection,
});
} catch (error) {
this.logger("http:sendTx", error);
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
return this.sendTransactionViaWs(txType, txInfo);
}
throw error;
}
}
private async sendTransactionViaWs(txType: number, txInfo: string): Promise<unknown> {
const ws = this.ws;
if (!ws || ws.readyState !== WebSocket.OPEN) {
throw new Error("WebSocket not connected for tx dispatch");
}
const id = `tx-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`;
const payload = {
type: "jsonapi/sendtx",
data: {
id,
tx_type: txType,
tx_info: tryParseTxInfo(txInfo),
},
};
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
this.pendingJsonRequests.delete(id);
reject(new Error("WebSocket sendtx timeout"));
}, 3000);
this.pendingJsonRequests.set(id, {
resolve: (value) => {
clearTimeout(timer);
resolve(value);
},
reject: (error) => {
clearTimeout(timer);
reject(error);
},
});
try {
ws.send(JSON.stringify(payload));
} catch (error) {
clearTimeout(timer);
this.pendingJsonRequests.delete(id);
reject(error);
}
});
}
private pickBestOrderBook(
books: LighterOrderBookMetadata[],
desiredSymbol: string,
desiredMarketId?: number | null
): LighterOrderBookMetadata | null {
const desiredForms = normalizeSymbolForms(desiredSymbol);
let candidates = books.filter((book) => {
const symbolForms = normalizeSymbolForms(book.symbol);
const idMatch = desiredMarketId != null && Number(book.market_id) === Number(desiredMarketId);
const symbolMatch = desiredForms.some((form) => symbolForms.includes(form));
return idMatch || symbolMatch;
});
if (!candidates.length && desiredMarketId != null) {
candidates = books.filter((book) => Number(book.market_id) === Number(desiredMarketId));
}
if (!candidates.length) return null;
const normalizedDesired = desiredSymbol.toUpperCase();
const wantsSpot =
desiredSymbol.includes("/") ||
desiredSymbol.includes("-") ||
desiredSymbol.includes(":") ||
normalizedDesired.includes("USDC") ||
normalizedDesired.endsWith("USD");
const preferred = candidates.filter((book) =>
wantsSpot ? normalizeMarketType(book.market_type) === "spot" : true
);
if (wantsSpot && preferred.length) {
candidates = preferred;
}
candidates.sort((a, b) => {
const aExact = normalizeSymbolForms(a.symbol).includes(desiredSymbol.toUpperCase()) ? 1 : 0;
const bExact = normalizeSymbolForms(b.symbol).includes(desiredSymbol.toUpperCase()) ? 1 : 0;
if (aExact !== bExact) return bExact - aExact;
const aSpot = normalizeMarketType(a.market_type) === "spot" ? 1 : 0;
const bSpot = normalizeMarketType(b.market_type) === "spot" ? 1 : 0;
if (aSpot !== bSpot) return bSpot - aSpot;
return 0;
});
return candidates[0];
}
private scheduleReconnect(): void {
if (this.reconnectTimer) return;
this.reconnectTimer = setTimeout(() => {
@@ -730,9 +987,14 @@ export class LighterGateway {
case "update/account_all_orders":
this.handleAccountOrders(message);
break;
case "subscribed/account_all_assets":
case "update/account_all_assets":
this.handleAccountAssets(message);
break;
default:
break;
}
this.maybeResolveJsonRequest(message);
} catch (error) {
this.logger("ws:message", error);
}
@@ -760,6 +1022,27 @@ export class LighterGateway {
}
}
private maybeResolveJsonRequest(message: any): void {
const id = extractJsonRequestId(message);
if (!id) return;
const pending = this.pendingJsonRequests.get(id);
if (!pending) return;
this.pendingJsonRequests.delete(id);
pending.resolve(message);
}
private rejectPendingJsonRequests(reason: unknown): void {
for (const [id, pending] of Array.from(this.pendingJsonRequests.entries())) {
try {
pending.reject(reason);
} catch (error) {
this.logger(`ws:pending:${id}`, error);
} finally {
this.pendingJsonRequests.delete(id);
}
}
}
private handleOrderBookSnapshot(message: any): void {
if (!message?.order_book) return;
const incomingOffset = Number(message.offset ?? message.order_book?.offset ?? 0);
@@ -858,6 +1141,14 @@ export class LighterGateway {
this.applyOrderBuckets(ordersObject, snapshot);
}
private handleAccountAssets(message: any): void {
if (!message) return;
const assets = this.normalizeAssets(message.assets);
if (!assets.length) return;
this.applyAccountAssets(assets);
this.emitAccount();
}
private normalizePositions(source: unknown): LighterPosition[] {
if (!source) return [];
if (Array.isArray(source)) {
@@ -986,6 +1277,54 @@ export class LighterGateway {
return typeof value === "object" && value != null;
}
private normalizeAssets(source: unknown): LighterAccountAsset[] {
if (!source) return [];
const coerce = (entry: unknown): LighterAccountAsset | null => {
if (!this.isAsset(entry)) return null;
const balance =
typeof entry.balance === "number" ? entry.balance.toString() : entry.balance ?? "0";
const locked =
typeof entry.locked_balance === "number"
? entry.locked_balance.toString()
: entry.locked_balance;
const rawSymbol =
(entry.symbol ?? (entry.asset_id != null ? String(entry.asset_id) : undefined)) ?? undefined;
const symbol = rawSymbol ? rawSymbol.toUpperCase() : undefined;
return { ...entry, balance, locked_balance: locked, symbol };
};
if (Array.isArray(source)) {
return (source as unknown[])
.map(coerce)
.filter((entry): entry is LighterAccountAsset => Boolean(entry));
}
if (isPlainObject(source)) {
return Object.values(source)
.map(coerce)
.filter((entry): entry is LighterAccountAsset => Boolean(entry));
}
if (this.isAsset(source)) {
const coerced = coerce(source);
return coerced ? [coerced] : [];
}
return [];
}
private normalizeAssetKey(asset: LighterAccountAsset): string | null {
if (asset.asset_id != null && Number.isFinite(Number(asset.asset_id))) {
return `id:${Number(asset.asset_id)}`;
}
if (asset.symbol) {
return `symbol:${asset.symbol.toUpperCase()}`;
}
return null;
}
private isAsset(value: unknown): value is LighterAccountAsset {
if (typeof value !== "object" || value == null) return false;
const balance = (value as LighterAccountAsset).balance as unknown;
return typeof balance === "string" || typeof balance === "number";
}
private applyOrderList(rawOrders: unknown, marketId: number | null, snapshot: boolean): void {
const orders = this.normalizeOrders(rawOrders);
if (snapshot) {
@@ -1101,8 +1440,16 @@ export class LighterGateway {
this.displaySymbol,
this.accountDetails,
this.positions,
[],
{ marketSymbol: this.marketSymbol, marketId: this.marketId }
this.buildAccountAssets(),
{
marketSymbol: this.marketSymbol,
marketId: this.marketId,
marketType: this.marketType ?? guessMarketType(this.marketSymbol),
baseAssetSymbol: this.baseAssetSymbol,
quoteAssetSymbol: this.quoteAssetSymbol,
baseAssetId: this.baseAssetId,
quoteAssetId: this.quoteAssetId,
}
);
this.accountEvent.emit(snapshot);
this.lastAccountUpdateAt = Date.now();
@@ -1306,6 +1653,69 @@ export class LighterGateway {
this.tickerEvent.emit(ticker);
}
private buildAccountAssets(): AsterAccountAsset[] {
if (!this.assets.size) return [];
const now = Date.now();
const list: AsterAccountAsset[] = [];
for (const asset of this.assets.values()) {
const balanceNum = parseNumber(asset.balance);
const lockedNum = parseNumber(asset.locked_balance ?? 0);
const availableRaw = balanceNum != null && lockedNum != null ? balanceNum - lockedNum : null;
const available = availableRaw != null ? Math.max(0, availableRaw) : null;
const assetId = Number(asset.asset_id);
const matchSymbol =
Number.isFinite(assetId) && this.baseAssetId != null && assetId === this.baseAssetId
? this.baseAssetSymbol
: Number.isFinite(assetId) && this.quoteAssetId != null && assetId === this.quoteAssetId
? this.quoteAssetSymbol
: null;
const assetSymbol =
(matchSymbol ?? asset.symbol ?? (asset.asset_id != null ? String(asset.asset_id) : "ASSET")).toUpperCase();
list.push({
asset: assetSymbol,
walletBalance: asset.balance ?? "0",
availableBalance: available != null && Number.isFinite(available) ? available.toString() : asset.balance ?? "0",
updateTime: now,
assetId: Number.isFinite(assetId) ? assetId : undefined,
});
}
return list.sort((a, b) => a.asset.localeCompare(b.asset));
}
private applyPresetMarket(): void {
const normalized = (this.marketSymbol ?? "").toUpperCase().replace(/[^A-Z0-9]/g, "");
const preset = KNOWN_SPOT_MARKETS[normalized];
if (!preset) return;
if (this.marketId == null) this.marketId = preset.marketId;
if (!this.baseAssetSymbol) this.baseAssetSymbol = preset.base;
if (!this.quoteAssetSymbol) this.quoteAssetSymbol = preset.quote;
if (!this.marketType) this.marketType = "spot";
if (preset.priceDecimals != null) this.priceDecimals = this.priceDecimals ?? preset.priceDecimals;
if (preset.sizeDecimals != null) this.sizeDecimals = this.sizeDecimals ?? preset.sizeDecimals;
this.forcedSpotPreset = true;
}
private findSpotSibling(
books: LighterOrderBookMetadata[],
desiredSymbol: string,
desiredMarketId?: number | null
): LighterOrderBookMetadata | null {
const parsed = parseBaseQuote(desiredSymbol);
const base = parsed.base;
const quote = parsed.quote;
if (!base || !quote) return null;
const matches = books.filter((book) => {
if (normalizeMarketType(book.market_type) !== "spot") return false;
const forms = normalizeSymbolForms(book.symbol);
const hasBase = forms.includes(base) || forms.includes(`${base}${quote}`) || forms.includes(`${base}-${quote}`);
const hasQuote = forms.includes(quote) || forms.includes(`${base}${quote}`) || forms.includes(`${base}-${quote}`);
const idMatch = desiredMarketId != null && Number(book.market_id) === Number(desiredMarketId);
return (hasBase && hasQuote) || idMatch;
});
if (!matches.length) return null;
return matches[0];
}
async getPrecision(): Promise<{
priceTick: number;
qtyStep: number;
@@ -1328,6 +1738,66 @@ export class LighterGateway {
};
}
private isSpotMarket(): boolean {
return (this.marketType ?? "").toLowerCase() === "spot";
}
private enforceMinimums(quantity: number, price: number | null | undefined): number {
let qty = Number(quantity);
if (!Number.isFinite(qty) || qty <= 0) {
throw new Error("Lighter order requires positive quantity");
}
if (this.minBaseAmount != null && Number.isFinite(this.minBaseAmount)) {
qty = Math.max(qty, this.minBaseAmount);
}
if (this.minQuoteAmount != null && Number.isFinite(this.minQuoteAmount) && Number.isFinite(price)) {
const minByQuote = this.minQuoteAmount / Number(price);
if (Number.isFinite(minByQuote) && minByQuote > 0) {
qty = Math.max(qty, minByQuote);
}
}
return qty;
}
private getAvailableAssetAmount(assetId?: number | null, symbol?: string | null): number | null {
if (!this.assets.size) return null;
const normalizedSymbol = symbol ? symbol.toUpperCase() : null;
for (const asset of this.assets.values()) {
const idMatches = assetId != null && Number.isFinite(Number(asset.asset_id)) && Number(asset.asset_id) === assetId;
const symbolMatches = normalizedSymbol && asset.symbol && asset.symbol.toUpperCase() === normalizedSymbol;
if (!idMatches && !symbolMatches) continue;
const balance = parseNumber(asset.balance);
const locked = parseNumber(asset.locked_balance ?? 0);
if (balance == null) continue;
const available = locked != null ? balance - locked : balance;
return Number.isFinite(available) ? available : null;
}
return null;
}
private assertSpotBalance(params: { isAsk: boolean; quantity: number | null | undefined; price: number | null }): void {
const qty = Number(params.quantity);
if (!Number.isFinite(qty) || qty <= 0) return;
if (params.isAsk) {
const availableBase = this.getAvailableAssetAmount(this.baseAssetId, this.baseAssetSymbol);
if (availableBase != null && availableBase + 1e-9 < qty) {
throw new Error(
`Insufficient base asset (${this.baseAssetSymbol ?? "BASE"} available ${availableBase}) for spot sell ${qty}`
);
}
return;
}
const price = Number(params.price);
if (!Number.isFinite(price) || price <= 0) return;
const requiredQuote = qty * price;
const availableQuote = this.getAvailableAssetAmount(this.quoteAssetId, this.quoteAssetSymbol);
if (availableQuote != null && availableQuote + 1e-9 < requiredQuote) {
throw new Error(
`Insufficient quote asset (${this.quoteAssetSymbol ?? "QUOTE"} available ${availableQuote}) for spot buy requiring ${requiredQuote}`
);
}
}
private mapCreateOrderParams(params: CreateOrderParams): Omit<CreateOrderSignParams, "nonce"> & {
baseAmountScaledString: string;
priceScaledString: string;
@@ -1337,12 +1807,41 @@ export class LighterGateway {
if (this.marketId == null || this.priceDecimals == null || this.sizeDecimals == null) {
throw new Error("Lighter market metadata not initialized");
}
const wantsSpot = guessMarketType(this.marketSymbol) === "spot" || this.marketType === "spot";
if (wantsSpot && this.marketType !== "spot") {
throw new Error(
`Refusing to place order on non-spot market (marketId=${this.marketId}, type=${this.marketType ?? "unknown"}) for symbol=${this.marketSymbol}`
);
}
if (params.quantity == null || !Number.isFinite(params.quantity)) {
throw new Error("Lighter orders require quantity");
}
if (process.env.LIGHTER_DEBUG === "1" || process.env.LIGHTER_DEBUG === "true") {
// eslint-disable-next-line no-console
console.error(
"[LighterGateway] createOrder.inputs",
JSON.stringify({
marketId: this.marketId,
marketType: this.marketType,
priceDecimals: this.priceDecimals,
sizeDecimals: this.sizeDecimals,
symbol: this.marketSymbol,
wantsSpot,
})
);
}
const side = params.side;
const isAsk = side === "SELL" ? 1 : 0;
const baseAmount = scaleQuantityWithMinimum(params.quantity, this.sizeDecimals);
const enforcedQty = this.enforceMinimums(params.quantity, params.price ?? null);
if (this.isSpotMarket() && isAsk === 1) {
const availableBase = this.getAvailableAssetAmount(this.baseAssetId, this.baseAssetSymbol);
if (availableBase != null && availableBase + 1e-9 < enforcedQty) {
throw new Error(
`Spot sell quantity ${enforcedQty} exceeds available base ${availableBase} (min trade size may be higher than balance)`
);
}
}
const baseAmount = scaleQuantityWithMinimum(enforcedQty, this.sizeDecimals);
const baseAmountScaledString = scaledToDecimalString(baseAmount, this.sizeDecimals);
const clientOrderIndex = BigInt(Date.now() % Number.MAX_SAFE_INTEGER);
let priceScaled = params.price != null ? decimalToScaled(params.price, this.priceDecimals) : null;
@@ -1352,7 +1851,8 @@ export class LighterGateway {
if (priceScaled == null) {
throw new Error("Lighter order requires price");
}
const reduceOnly = params.reduceOnly === "true" || params.closePosition === "true" ? 1 : 0;
const reduceOnly =
this.isSpotMarket() ? 0 : params.reduceOnly === "true" || params.closePosition === "true" ? 1 : 0;
const resultType = mapOrderType(params.type ?? "LIMIT");
const resultTimeInForce = mapTimeInForce(params.timeInForce, params.type ?? "LIMIT");
let triggerPriceScaled = 0n;
@@ -1369,6 +1869,23 @@ export class LighterGateway {
? BigInt(IMMEDIATE_OR_CANCEL_EXPIRY_PLACEHOLDER)
: BigInt(Date.now() + TWENTY_EIGHT_DAYS_MS);
const resolvedPrice =
params.price ??
(() => {
try {
return Number(scaledToDecimalString(priceScaled, this.priceDecimals));
} catch {
return null;
}
})();
if (this.isSpotMarket()) {
this.assertSpotBalance({
isAsk: isAsk === 1,
quantity: params.quantity,
price: resolvedPrice,
});
}
return {
marketIndex: this.marketId,
clientOrderIndex,
@@ -1533,3 +2050,79 @@ function decimalsToStep(decimals: number): number {
function isPlainObject(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value != null && !Array.isArray(value);
}
function parseNumber(value: string | number): number | null {
const num = typeof value === "number" ? value : Number(value);
if (!Number.isFinite(num)) return null;
return num;
}
function parseBaseQuote(symbol: string | null | undefined): { base?: string; quote?: string } {
if (!symbol) return {};
const sanitized = symbol.toUpperCase();
const delimiters = ["/", "-", ":"];
for (const delimiter of delimiters) {
if (sanitized.includes(delimiter)) {
const [base, quote] = sanitized.split(delimiter);
return { base: base || undefined, quote: quote || undefined };
}
}
if (sanitized.length >= 6) {
// Fall back to first 3/remaining split for compact symbols like ETHUSDC
return { base: sanitized.slice(0, 3), quote: sanitized.slice(3) };
}
return { base: sanitized };
}
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 guessMarketType(symbol: string | null | undefined): "perp" | "spot" | null {
if (!symbol) return null;
const upper = symbol.toUpperCase();
if (upper.includes("/") || upper.includes("-") || upper.includes(":") || upper.endsWith("USDC")) {
return "spot";
}
return null;
}
function isInvalidNonce(error: unknown): boolean {
const message = typeof error === "string" ? error : error instanceof Error ? error.message : String(error);
return message.includes("invalid nonce") || message.includes("\"code\":21104") || message.includes("21104");
}
function extractJsonRequestId(message: any): string | null {
if (!message || typeof message !== "object") return null;
const direct = (message as { id?: unknown }).id;
const nested = (message as { data?: { id?: unknown } }).data?.id;
const value = direct ?? nested;
if (value === undefined || value === null) return null;
const str = String(value);
return str ? str : null;
}
function tryParseTxInfo(value: string): unknown {
try {
return JSON.parse(value);
} catch (_) {
return value;
}
}
function normalizeSymbolForms(value: string | null | undefined): string[] {
if (!value) return [];
const upper = value.toUpperCase();
const sanitized = upper.replace(/[^A-Z0-9]/g, "");
const parts = upper.split(/[-:/]/).filter(Boolean);
const base = parts.length ? parts[0] : "";
const forms = new Set<string>();
if (upper) forms.add(upper);
if (sanitized) forms.add(sanitized);
if (base) forms.add(base);
return Array.from(forms);
}
+9 -5
View File
@@ -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: {
+62 -42
View File
@@ -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)
+66 -6
View File
@@ -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";
@@ -249,3 +301,11 @@ function normalizeSymbolForms(value: string): string[] {
if (base) forms.add(base);
return Array.from(forms);
}
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;
}
+4
View File
@@ -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.
@@ -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 {}
}
Binary file not shown.
Binary file not shown.
+17 -2
View File
@@ -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;
+6
View File
@@ -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> {
+208 -15
View File
@@ -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";
@@ -67,6 +71,13 @@ export class OffsetMakerEngine {
private priceTick: number = 0.1;
private qtyStep: number = 0.001;
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 timer: ReturnType<typeof setInterval> | null = null;
private processing = false;
@@ -106,6 +117,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 +160,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();
},
@@ -279,7 +317,10 @@ 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;
const handledImbalance = await this.handleImbalanceExit(position, buySum, sellSum);
if (handledImbalance) {
this.emitUpdate();
@@ -306,30 +347,71 @@ export class OffsetMakerEngine {
const desired: DesiredOrder[] = [];
const canEnter = !this.rateLimit.shouldBlockEntries();
if (absPosition < EPS) {
if (absPosition < EPS && isSpotMarket) {
this.entryPricePendingLogged = false;
if (!skipBuySide && canEnter) {
if (bidPrice != null) {
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: this.config.tradeAmount, reduceOnly: false });
desired.push({ side: "BUY", price: bidPrice, amount: buyAmount, reduceOnly: false });
} else if (this.lastBuyPriceViable) {
this.lastBuyPriceViable = false;
this.tradeLog.push("info", "跳过买单:价差不足以构造maker价格");
const reason =
buyAmount < EPS && isSpotMarket
? "现货可用报价资产不足,跳过买单"
: "跳过买单:价差不足以构造maker价格";
this.tradeLog.push("info", reason);
}
}
if (!skipSellSide && canEnter) {
if (askPrice != null) {
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: this.config.tradeAmount, reduceOnly: false });
desired.push({ side: "SELL", price: askPrice, amount: sellAmount, reduceOnly: false });
} else if (this.lastSellPriceViable) {
this.lastSellPriceViable = false;
this.tradeLog.push("info", "跳过卖单:价差不足以构造maker价格");
const reason =
sellAmount < EPS && isSpotMarket
? "现货可用基础资产不足,跳过卖单"
: "跳过卖单:价差不足以构造maker价格";
this.tradeLog.push("info", reason);
}
}
} else if (absPosition < EPS) {
this.entryPricePendingLogged = false;
if (!skipBuySide && canEnter) {
desired.push({ side: "BUY", price: bidPrice, amount: this.config.tradeAmount, reduceOnly: false });
}
if (!skipSellSide && canEnter) {
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 });
const closeQty =
isSpotMarket && balancesForSpot
? this.computeSpotOrderSize({
side: "SELL",
desiredAmount: absPosition,
price: closePrice != null ? Number(closePrice) : null,
balances: balancesForSpot,
})
: absPosition;
if (closePrice != null && closeQty >= EPS) {
desired.push({ side: closeSide, price: closePrice, amount: closeQty, reduceOnly: false });
}
}
this.desiredOrders = desired;
@@ -354,7 +436,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 +521,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;
@@ -548,6 +632,7 @@ export class OffsetMakerEngine {
if (!target) continue;
if (target.amount < EPS) continue;
try {
const reduceOnlyFlag = this.marketType === "spot" ? false : target.reduceOnly;
await placeOrder(
this.exchange,
this.config.symbol,
@@ -559,9 +644,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 +678,43 @@ 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) return;
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.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;
@@ -724,7 +846,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 +872,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 +883,73 @@ export class OffsetMakerEngine {
return getMidOrLast(this.depthSnapshot, this.tickerSnapshot);
}
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);
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 +990,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);
+47 -1
View File
@@ -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;
});
}