mirror of
https://github.com/discountry/ritmex-bot.git
synced 2026-09-09 08:18:07 +00:00
Remove lighter-go-main directory and associated files, including client, types, and documentation, to streamline the project structure. Update .gitignore to exclude temporary files.
This commit is contained in:
@@ -33,3 +33,6 @@ report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
|
||||
|
||||
# Finder (MacOS) folder config
|
||||
.DS_Store
|
||||
|
||||
.tmp
|
||||
.tmp/*
|
||||
Binary file not shown.
@@ -1,2 +0,0 @@
|
||||
*.go text eol=lf
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
.idea
|
||||
vendor
|
||||
build/*
|
||||
!build/.keep
|
||||
/build
|
||||
@@ -1,201 +0,0 @@
|
||||
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.
|
||||
@@ -1,94 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,116 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,45 +0,0 @@
|
||||
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,
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
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"`
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
package client
|
||||
|
||||
type MinimalHTTPClient interface {
|
||||
GetNextNonce(accountIndex int64, apiKeyIndex uint8) (int64, error)
|
||||
GetApiKey(accountIndex int64, apiKeyIndex uint8) (string, error)
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,209 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
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
|
||||
)
|
||||
@@ -1,76 +0,0 @@
|
||||
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=
|
||||
@@ -1,49 +0,0 @@
|
||||
### 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/
|
||||
@@ -1,690 +0,0 @@
|
||||
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() {}
|
||||
@@ -1,54 +0,0 @@
|
||||
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()
|
||||
}
|
||||
@@ -1,670 +0,0 @@
|
||||
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,
|
||||
}
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,208 +0,0 @@
|
||||
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
|
||||
)
|
||||
@@ -1,333 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,192 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
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")
|
||||
)
|
||||
@@ -1,37 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,158 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,731 +0,0 @@
|
||||
//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 {}
|
||||
}
|
||||
Reference in New Issue
Block a user