feat: 添加 Lighter 适配器及相关功能,支持 trailing stops 和新的交易逻辑

This commit is contained in:
discountry
2025-09-30 22:08:05 +08:00
parent e83bdfccf9
commit c8b0ab1c8e
101 changed files with 90621 additions and 3 deletions
+4
View File
@@ -0,0 +1,4 @@
.idea
vendor
build/*
!build/.keep
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+9
View File
@@ -0,0 +1,9 @@
# lighter-go
In its current form, this repo serves as a starting point for anyone who wants to trade on Lighter using GO.
It covers all the signing procedures in order to trade on Lighter with an API key.
Minimal HTTP calls are implemented
On chain support, like depositing on Ethereum or modifying an API key directly with an Ethereum Tx are not supported yet.
At the moment, its main purpose is to offer visibility on the code behind the precompiled libraries used by the Python SDK.
If you'd like to compile your own binaries, the commands are in the `justfile`
@@ -0,0 +1,49 @@
package client
import (
"crypto/tls"
"net"
"net/http"
"time"
)
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: true},
}
httpClient = &http.Client{
Timeout: time.Second * 30,
Transport: transport,
}
)
type HTTPClient struct {
endpoint string
channelName string
fatFingerProtection bool
}
func NewHTTPClient(baseUrl string) *HTTPClient {
if baseUrl == "" {
return nil
}
return &HTTPClient{
endpoint: baseUrl,
channelName: "",
fatFingerProtection: true,
}
}
func (c *HTTPClient) SetFatFingerProtection(enabled bool) {
c.fatFingerProtection = enabled
}
@@ -0,0 +1,128 @@
package client
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/elliottech/lighter-go/types/txtypes"
)
func (c *HTTPClient) 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 *HTTPClient) 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 *HTTPClient) 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 *HTTPClient) GetApiKey(accountIndex int64, apiKeyIndex uint8) (*AccountApiKeys, error) {
result := &AccountApiKeys{}
err := c.getAndParseL2HTTPResponse("api/v1/apikeys", map[string]any{"account_index": accountIndex, "api_key_index": apiKeyIndex}, result)
if err != nil {
return nil, err
}
return result, nil
}
func (c *HTTPClient) SendRawTx(tx txtypes.TxInfo) (string, error) {
txType := tx.GetTxType()
txInfo, err := tx.GetTxInfo()
if err != nil {
return "", err
}
data := url.Values{"tx_type": {strconv.Itoa(int(txType))}, "tx_info": {txInfo}}
if c.fatFingerProtection == false {
data.Add("price_protection", "false")
}
req, _ := http.NewRequest("POST", c.endpoint+"/api/v1/sendTx", strings.NewReader(data.Encode()))
req.Header.Set("Channel-Name", c.channelName)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := httpClient.Do(req)
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
}
res := &TxHash{}
if err := json.Unmarshal(body, res); err != nil {
return "", err
}
return res.TxHash, nil
}
func (c *HTTPClient) GetTransferFeeInfo(accountIndex, toAccountIndex int64, auth string) (*TransferFeeInfo, error) {
result := &TransferFeeInfo{}
err := c.getAndParseL2HTTPResponse("api/v1/transferFeeInfo", map[string]any{
"account_index": accountIndex,
"to_account_index": toAccountIndex,
"auth": auth,
}, result)
if err != nil {
return nil, err
}
return result, nil
}
@@ -0,0 +1,37 @@
package client
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"`
}
type TxHash struct {
ResultCode
TxHash string `json:"tx_hash,example=0x70997970C51812dc3A010C7d01b50e0d17dc79C8"`
}
type TransferFeeInfo struct {
ResultCode
TransferFee int64 `json:"transfer_fee_usdc"`
}
@@ -0,0 +1,109 @@
package client
import (
"encoding/hex"
"fmt"
"time"
"github.com/elliottech/lighter-go/signer"
"github.com/elliottech/lighter-go/types"
)
const (
defaultExpireTime = time.Minute*10 - time.Second // we need to give a second margin, to eliminate millisecond differences
)
type TxClient struct {
apiClient *HTTPClient
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 *HTTPClient, 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
}
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 {
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) GetAccountIndex() int64 {
return c.accountIndex
}
func (c *TxClient) GetApiKeyIndex() uint8 {
return c.apiKeyIndex
}
func (c *TxClient) GetKeyManager() signer.KeyManager {
return c.keyManager
}
func (c *TxClient) GetAuthToken(deadline time.Time) (string, error) {
if time.Until(deadline) > (7 * time.Hour) {
return "", fmt.Errorf("deadline should be within 7 hours")
}
return types.ConstructAuthToken(c.keyManager, deadline, &types.TransactOpts{
ApiKeyIndex: &c.apiKeyIndex,
FromAccountIndex: &c.accountIndex,
})
}
func (c *TxClient) HTTP() *HTTPClient {
return c.apiClient
}
func (c *TxClient) SwitchAPIKey(apiKey uint8) {
c.apiKeyIndex = apiKey
}
@@ -0,0 +1,192 @@
package client
import (
"fmt"
"github.com/elliottech/lighter-go/types"
"github.com/elliottech/lighter-go/types/txtypes"
schnorr "github.com/elliottech/poseidon_crypto/signature/schnorr"
)
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) 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) {
if c.keyManager == nil {
return nil, fmt.Errorf("key manager is nil")
}
if ops == nil {
ops = new(types.TransactOpts)
}
txInfo, err := types.ConstructUpdateMarginTx(c.keyManager, c.chainId, tx, ops)
if err != nil {
return nil, err
}
return txInfo, nil
}
+18
View File
@@ -0,0 +1,18 @@
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/gnark-crypto v0.14.0 // indirect
github.com/holiman/uint256 v1.3.2 // indirect
golang.org/x/crypto v0.35.0 // indirect
golang.org/x/sys v0.30.0 // indirect
)
+24
View File
@@ -0,0 +1,24 @@
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/consensys/gnark-crypto v0.14.0 h1:DDBdl4HaBtdQsq/wfMwJvZNE80sHidrK3Nfrefatm0E=
github.com/consensys/gnark-crypto v0.14.0/go.mod h1:CU4UijNPsHawiVGNxe9co07FkzCeWHHrb1li/n1XoU0=
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/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/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/holiman/uint256 v1.3.2 h1:a9EgMPSC1AAaj1SZL5zIQD3WbwTuHrMGOerLjGmM/TA=
github.com/holiman/uint256 v1.3.2/go.mod h1:EOMSn4q6Nyt9P6efbI3bueV4e1b3dGlUCXeiRV4ng7E=
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/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
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/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+12
View File
@@ -0,0 +1,12 @@
build-darwin-local:
go mod vendor
go build -buildmode=c-shared -trimpath -o ./build/signer-arm64.dylib ./sharedlib/sharedlib.go
build-linux-local:
go mod vendor
go build -buildmode=c-shared -trimpath -o ./build/signer-amd64.so ./sharedlib/sharedlib.go
build-linux-docker:
go mod vendor
docker run --platform linux/amd64 -v $(pwd):/go/src/sdk golang:1.23.2-bullseye /bin/sh -c "cd /go/src/sdk && go build -buildmode=c-shared -trimpath -o ./build/signer-amd64.so ./sharedlib/sharedlib.go"
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,54 @@
package signer
import (
"fmt"
"hash"
curve "github.com/elliottech/poseidon_crypto/curve/ecgfp5"
gFp5 "github.com/elliottech/poseidon_crypto/field/goldilocks_quintic_extension"
schnorr "github.com/elliottech/poseidon_crypto/signature/schnorr"
)
type Signer interface {
Sign(message []byte, hFunc hash.Hash) ([]byte, error)
}
type KeyManager interface {
Signer
PubKey() gFp5.Element
PubKeyBytes() [40]byte
PrvKeyBytes() []byte
}
type keyManager struct {
key curve.ECgFp5Scalar
}
func NewKeyManager(b []byte) (KeyManager, error) {
if len(b) != 40 {
return nil, fmt.Errorf("invalid private key length. expected: 40 got: %v", len(b))
}
return &keyManager{key: curve.ScalarElementFromLittleEndianBytes(b)}, nil
}
func (key *keyManager) Sign(hashedMessage []byte, hFunc hash.Hash) ([]byte, error) {
hashedMessageAsQuinticExtension, err := gFp5.FromCanonicalLittleEndianBytes(hashedMessage)
if err != nil {
return nil, fmt.Errorf("failed to parse message while signing. message: %v err: %w", hashedMessage, err)
}
return schnorr.SchnorrSignHashedMessage(hashedMessageAsQuinticExtension, key.key).ToBytes(), nil
}
func (key *keyManager) PubKey() gFp5.Element {
return schnorr.SchnorrPkFromSk(key.key)
}
func (key *keyManager) PubKeyBytes() (res [40]byte) {
bytes := key.PubKey().ToLittleEndianBytes()
copy(res[:], bytes[:])
return
}
func (key *keyManager) PrvKeyBytes() []byte {
return key.key.ToLittleEndianBytes()
}
@@ -0,0 +1,659 @@
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
USDCAmount int64
Fee int64
Memo [32]byte
}
type WithdrawTxReq struct {
USDCAmount uint64
}
type CreateOrderTxReq struct {
MarketIndex uint8
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 uint8
Index int64
BaseAmount int64
Price uint32
TriggerPrice uint32
}
type CancelOrderTxReq struct {
MarketIndex uint8
Index int64
}
type CancelAllOrdersTxReq struct {
TimeInForce uint8
Time int64
}
type CreatePublicPoolTxReq struct {
OperatorFee int64
InitialTotalShares int64
MinOperatorShareRate int64
}
type UpdatePublicPoolTxReq struct {
PublicPoolIndex int64
Status uint8
OperatorFee int64
MinOperatorShareRate int64
}
type MintSharesTxReq struct {
PublicPoolIndex int64
ShareAmount int64
}
type BurnSharesTxReq struct {
PublicPoolIndex int64
ShareAmount int64
}
type UpdateLeverageTxReq struct {
MarketIndex uint8
InitialMarginFraction uint16
MarginMode uint8
}
type UpdateMarginTxReq struct {
MarketIndex uint8
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,
USDCAmount: tx.USDCAmount,
Fee: tx.Fee,
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,
USDCAmount: tx.USDCAmount,
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,
ExpiredAt: ops.ExpiredAt,
Nonce: *ops.Nonce,
}
}
func ConvertUpdateMarginTx(tx *UpdateMarginTxReq, ops *TransactOpts) *txtypes.L2UpdateMarginTxInfo {
return &txtypes.L2UpdateMarginTxInfo{
AccountIndex: *ops.FromAccountIndex,
ApiKeyIndex: *ops.ApiKeyIndex,
MarketIndex: tx.MarketIndex,
USDCAmount: tx.USDCAmount,
Direction: tx.Direction,
ExpiredAt: ops.ExpiredAt,
Nonce: *ops.Nonce,
}
}
@@ -0,0 +1,91 @@
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 < MinAccountIndex {
return ErrPublicPoolIndexTooLow
}
if txInfo.PublicPoolIndex > MaxAccountIndex {
return ErrPublicPoolIndexTooHigh
}
if txInfo.ShareAmount < MinPoolSharesToMintOrBurn {
return ErrPoolBurnShareAmountTooLow
}
if txInfo.ShareAmount > MaxPoolSharesToMintOrBurn {
return ErrPoolBurnShareAmountTooHigh
}
if txInfo.Nonce < MinNonce {
return ErrNonceTooLow
}
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
return ErrExpiredAtInvalid
}
return nil
}
func (txInfo *L2BurnSharesTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
elems := make([]g.Element, 0, 8)
elems = append(elems, g.FromUint32(lighterChainId))
elems = append(elems, g.FromUint32(TxTypeL2BurnShares))
elems = append(elems, g.FromInt64(txInfo.Nonce))
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
elems = append(elems, g.FromInt64(txInfo.PublicPoolIndex))
elems = append(elems, g.FromInt64(txInfo.ShareAmount))
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
}
@@ -0,0 +1,95 @@
package txtypes
import (
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
)
var _ TxInfo = (*L2CancelAllOrdersTxInfo)(nil)
type L2CancelAllOrdersTxInfo struct {
AccountIndex int64
ApiKeyIndex uint8
TimeInForce uint8
Time int64
ExpiredAt int64
Nonce int64
Sig []byte
SignedHash string `json:"-"`
}
func (txInfo *L2CancelAllOrdersTxInfo) GetTxType() uint8 {
return TxTypeL2CancelAllOrders
}
func (txInfo *L2CancelAllOrdersTxInfo) GetTxInfo() (string, error) {
return getTxInfo(txInfo)
}
func (txInfo *L2CancelAllOrdersTxInfo) GetTxHash() string {
return txInfo.SignedHash
}
func (txInfo *L2CancelAllOrdersTxInfo) Validate() error {
// AccountIndex
if txInfo.AccountIndex < MinAccountIndex {
return ErrAccountIndexTooLow
}
if txInfo.AccountIndex > MaxAccountIndex {
return ErrAccountIndexTooHigh
}
if txInfo.ApiKeyIndex < MinApiKeyIndex {
return ErrApiKeyIndexTooLow
}
if txInfo.ApiKeyIndex > MaxApiKeyIndex && txInfo.ApiKeyIndex != NilApiKeyIndex {
return ErrApiKeyIndexTooHigh
}
// Nonce
if txInfo.Nonce < MinNonce {
return ErrNonceTooLow
}
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
return ErrExpiredAtInvalid
}
// TimeInForce and Time
switch txInfo.TimeInForce {
case ImmediateCancelAll:
if txInfo.Time != NilOrderExpiry {
return ErrCancelAllTimeisNotNill
}
case ScheduledCancelAll:
if txInfo.Time < MinOrderExpiry || txInfo.Time > MaxOrderExpiry {
return ErrCancelAllTimeIsNotInRange
}
case AbortScheduledCancelAll:
if txInfo.Time != 0 {
return ErrCancelAllTimeIsNotInRange
}
default:
return ErrInvalidCancelAllTimeInForce
}
return nil
}
func (txInfo *L2CancelAllOrdersTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
elems := make([]g.Element, 0, 8)
elems = append(elems, g.FromUint32(lighterChainId))
elems = append(elems, g.FromUint32(TxTypeL2CancelAllOrders))
elems = append(elems, g.FromInt64(txInfo.Nonce))
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
elems = append(elems, g.FromUint32(uint32(txInfo.TimeInForce)))
elems = append(elems, g.FromInt64(txInfo.Time))
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
}
@@ -0,0 +1,94 @@
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 uint8
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
if txInfo.MarketIndex < MinMarketIndex {
return ErrMarketIndexTooLow
}
if txInfo.MarketIndex > MaxMarketIndex {
return ErrMarketIndexTooHigh
}
// Index
if txInfo.Index < MinClientOrderIndex && txInfo.Index < MinOrderIndex {
return ErrOrderIndexTooLow
}
if txInfo.Index > MaxClientOrderIndex && txInfo.Index > MaxOrderIndex {
return ErrOrderIndexTooHigh
}
// Nonce
if txInfo.Nonce < MinNonce {
return ErrNonceTooLow
}
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
return ErrExpiredAtInvalid
}
return nil
}
func (txInfo *L2CancelOrderTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
elems := make([]g.Element, 0, 7)
elems = append(elems, g.FromUint32(lighterChainId))
elems = append(elems, g.FromUint32(TxTypeL2CancelOrder))
elems = append(elems, g.FromInt64(txInfo.Nonce))
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
elems = append(elems, g.FromUint32(uint32(txInfo.MarketIndex)))
elems = append(elems, g.FromInt64(txInfo.Index))
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
}
@@ -0,0 +1,121 @@
package txtypes
import (
"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"
"github.com/ethereum/go-ethereum/common/hexutil"
)
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!"
)
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))
}
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 !IsValidPubKey(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) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
elems := make([]g.Element, 0, 11)
elems = append(elems, g.FromUint32(lighterChainId))
elems = append(elems, g.FromUint32(TxTypeL2ChangePubKey))
elems = append(elems, g.FromInt64(txInfo.Nonce))
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
pubKeyFieldElems, err := g.ArrayFromCanonicalLittleEndianBytes(txInfo.PubKey)
if err != nil {
return nil, fmt.Errorf("failed to convert bytes to field element. bytes: %v, error: %w", txInfo.PubKey, err)
}
elems = append(elems, pubKeyFieldElems...)
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
}
@@ -0,0 +1,175 @@
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 (
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
)
// 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
)
const (
HashLength int = 32
OneUSDC = 1000000
FeeTick int64 = 1_000_000
MarginFractionTick int64 = 10_000
ShareTick int64 = 10_000
MinAccountIndex int64 = 0
MaxAccountIndex int64 = 281474976710654 // (1 << 48) - 2
MinApiKeyIndex uint8 = 0
MaxApiKeyIndex uint8 = 254 // (1 << 8) - 2
MaxMasterAccountIndex int64 = 140737488355327 // (1 << 47) - 1
MinMarketIndex uint8 = 0
MaxMarketIndex uint8 = 254 // (1 << 8) - 2
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 << 56) - 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
)
// Margin Modes
const (
CrossMargin = iota
IsolatedMargin = 1
)
const (
RemoveFromIsolatedMargin = 0
AddToIsolatedMargin = 1
)
@@ -0,0 +1,336 @@
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 < MinMarketIndex {
return ErrMarketIndexTooLow
}
if txInfo.Orders[0].MarketIndex > MaxMarketIndex {
return ErrMarketIndexTooHigh
}
// Perform range checks for all orders
for _, order := range txInfo.Orders {
// MarketIndex
if order.MarketIndex != txInfo.Orders[0].MarketIndex {
return ErrMarketIndexMismatch
}
// ClientOrderIndex
if order.ClientOrderIndex != NilClientOrderIndex {
return ErrClientOrderIndexNotNil
}
// BaseAmount
if order.ReduceOnly != 1 && order.BaseAmount == NilOrderBaseAmount {
return ErrBaseAmountTooLow
}
if order.BaseAmount != NilOrderBaseAmount && order.BaseAmount < MinOrderBaseAmount {
return ErrBaseAmountTooLow
}
if order.BaseAmount > MaxOrderBaseAmount {
return ErrBaseAmountTooHigh
}
// Price
if order.Price < MinOrderPrice {
return ErrPriceTooLow
}
if order.Price > MaxOrderPrice {
return ErrPriceTooHigh
}
// IsAsk
if order.IsAsk != 0 && order.IsAsk != 1 {
return ErrIsAskInvalid
}
// TimeInForce
if order.TimeInForce != ImmediateOrCancel && order.TimeInForce != GoodTillTime && order.TimeInForce != PostOnly {
return ErrOrderTimeInForceInvalid
}
// ReduceOnly
if order.ReduceOnly != 0 && order.ReduceOnly != 1 {
return ErrOrderReduceOnlyInvalid
}
// OrderExpiry
if (order.OrderExpiry < MinOrderExpiry || order.OrderExpiry > MaxOrderExpiry) && order.OrderExpiry != NilOrderExpiry {
return ErrOrderExpiryInvalid
}
// TriggerPrice
if (order.TriggerPrice < MinOrderTriggerPrice || order.TriggerPrice > MaxOrderTriggerPrice) && order.TriggerPrice != NilOrderTriggerPrice {
return ErrOrderTriggerPriceInvalid
}
}
// Nonce
if txInfo.Nonce < MinNonce {
return ErrNonceTooLow
}
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
return ErrExpiredAtInvalid
}
switch txInfo.GroupingType {
case GroupingType_OneCancelsTheOther:
return txInfo.ValidateOCO()
case GroupingType_OneTriggersTheOther:
return txInfo.ValidateOTO()
case GroupingType_OneTriggersAOneCancelsTheOther:
return txInfo.ValidateOTOCO()
default:
return ErrGroupingTypeInvalid
}
}
func (txInfo *L2CreateGroupedOrdersTxInfo) ValidateParentOrder(order *OrderInfo) error {
switch order.Type {
case MarketOrder:
if order.TimeInForce != ImmediateOrCancel {
return ErrOrderTimeInForceInvalid
} else if order.OrderExpiry != NilOrderExpiry {
return ErrOrderExpiryInvalid
} else if order.TriggerPrice != NilOrderTriggerPrice {
return ErrOrderTriggerPriceInvalid
}
case LimitOrder:
if order.TriggerPrice != NilOrderTriggerPrice {
return ErrOrderTriggerPriceInvalid
} else if order.TimeInForce == ImmediateOrCancel && order.OrderExpiry != NilOrderExpiry {
return ErrOrderExpiryInvalid
} else if order.TimeInForce != ImmediateOrCancel && order.OrderExpiry == NilOrderExpiry {
return ErrOrderExpiryInvalid
}
default:
return ErrOrderTypeInvalid
}
return nil
}
func (txInfo *L2CreateGroupedOrdersTxInfo) ValidateChildOrder(order *OrderInfo) error {
switch order.Type {
case StopLossOrder, TakeProfitOrder:
if order.TimeInForce != ImmediateOrCancel {
return ErrOrderTimeInForceInvalid
} else if order.TriggerPrice == NilOrderTriggerPrice {
return ErrOrderTriggerPriceInvalid
} else if order.OrderExpiry == NilOrderExpiry {
return ErrOrderExpiryInvalid
}
case StopLossLimitOrder, TakeProfitLimitOrder:
if order.TriggerPrice == NilOrderTriggerPrice {
return ErrOrderTriggerPriceInvalid
} else if order.OrderExpiry == NilOrderExpiry {
return ErrOrderExpiryInvalid
}
default:
return ErrOrderTypeInvalid
}
return nil
}
func (txInfo *L2CreateGroupedOrdersTxInfo) ValidateSiblingOrders(orders []*OrderInfo) error {
if len(orders) != 2 {
return ErrOrderGroupSizeInvalid
}
slFlag := false
tpFlag := false
for _, order := range orders {
err := txInfo.ValidateChildOrder(order)
if err != nil {
return err
}
if order.Type == StopLossOrder || order.Type == StopLossLimitOrder {
slFlag = true
} else if order.Type == TakeProfitOrder || order.Type == TakeProfitLimitOrder {
tpFlag = true
}
}
if !slFlag || !tpFlag {
return ErrOrderTypeInvalid
}
return nil
}
func (txInfo *L2CreateGroupedOrdersTxInfo) ValidateOCO() error {
if len(txInfo.Orders) != 2 {
return ErrOrderGroupSizeInvalid
}
// Ensure both orders base sizes are same
if txInfo.Orders[0].BaseAmount != txInfo.Orders[1].BaseAmount {
return ErrBaseAmountsNotEqual
}
// Orders should be in the same direction
if txInfo.Orders[0].IsAsk != txInfo.Orders[1].IsAsk {
return ErrIsAskInvalid
}
// Ensure both orders are reduce only
if txInfo.Orders[0].ReduceOnly != 1 || txInfo.Orders[1].ReduceOnly != 1 {
return ErrOrderReduceOnlyInvalid
}
// Ensure both orders have the same non-nil expiry
if txInfo.Orders[0].OrderExpiry != txInfo.Orders[1].OrderExpiry {
return ErrOrderExpiryInvalid
}
return txInfo.ValidateSiblingOrders(txInfo.Orders)
}
func (txInfo *L2CreateGroupedOrdersTxInfo) ValidateOTO() error {
if len(txInfo.Orders) != 2 {
return ErrOrderGroupSizeInvalid
}
// Ensure child order base size is 0
if txInfo.Orders[1].BaseAmount != NilOrderBaseAmount {
return ErrBaseAmountNotNil
}
// Orders should be in the opposite direction
if txInfo.Orders[0].IsAsk == txInfo.Orders[1].IsAsk {
return ErrIsAskInvalid
}
// Ensure if expiries are not nil, they are the same
if txInfo.Orders[0].OrderExpiry != NilOrderExpiry &&
txInfo.Orders[0].OrderExpiry != txInfo.Orders[1].OrderExpiry {
return ErrOrderExpiryInvalid
}
err := txInfo.ValidateParentOrder(txInfo.Orders[0])
if err != nil {
return err
}
return txInfo.ValidateChildOrder(txInfo.Orders[1])
}
func (txInfo *L2CreateGroupedOrdersTxInfo) ValidateOTOCO() error {
if len(txInfo.Orders) != 3 {
return ErrOrderGroupSizeInvalid
}
// Ensure child orders base size is 0
if txInfo.Orders[1].BaseAmount != NilOrderBaseAmount || txInfo.Orders[2].BaseAmount != NilOrderBaseAmount {
return ErrBaseAmountNotNil
}
// Primary and child orders should be in the oppsite direction
if txInfo.Orders[0].IsAsk == txInfo.Orders[1].IsAsk || txInfo.Orders[0].IsAsk == txInfo.Orders[2].IsAsk {
return ErrIsAskInvalid
}
// Ensure child orders has the same expiry
if txInfo.Orders[1].OrderExpiry != txInfo.Orders[2].OrderExpiry {
return ErrOrderExpiryInvalid
}
// Ensure if expiries are not nil, they are the same
if txInfo.Orders[0].OrderExpiry != NilOrderExpiry &&
txInfo.Orders[0].OrderExpiry != txInfo.Orders[1].OrderExpiry {
return ErrOrderExpiryInvalid
}
err := txInfo.ValidateParentOrder(txInfo.Orders[0])
if err != nil {
return err
}
return txInfo.ValidateSiblingOrders(txInfo.Orders[1:])
}
func (txInfo *L2CreateGroupedOrdersTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
elems := make([]g.Element, 0, 11)
elems = append(elems, g.FromUint32(lighterChainId))
elems = append(elems, g.FromUint32(TxTypeL2CreateGroupedOrders))
elems = append(elems, g.FromInt64(txInfo.Nonce))
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
elems = append(elems, g.FromUint32(uint32(txInfo.GroupingType)))
aggregatedOrderHash := p2.EmptyHashOut()
for index, order := range txInfo.Orders {
orderHash := p2.HashNoPad([]g.Element{
g.FromUint32(uint32(order.MarketIndex)),
g.FromInt64(order.ClientOrderIndex),
g.FromInt64(order.BaseAmount),
g.FromUint32(order.Price),
g.FromUint32(uint32(order.IsAsk)),
g.FromUint32(uint32(order.Type)),
g.FromUint32(uint32(order.TimeInForce)),
g.FromUint32(uint32(order.ReduceOnly)),
g.FromUint32(order.TriggerPrice),
g.FromInt64(order.OrderExpiry),
})
if index == 0 {
aggregatedOrderHash = orderHash
} else {
aggregatedOrderHash = p2.HashNToOne([]p2.HashOut{aggregatedOrderHash, orderHash})
}
}
elems = append(elems, aggregatedOrderHash[:]...)
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
}
@@ -0,0 +1,186 @@
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
if txInfo.MarketIndex < MinMarketIndex {
return ErrMarketIndexTooLow
}
if txInfo.MarketIndex > MaxMarketIndex {
return ErrMarketIndexTooHigh
}
// 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
}
if txInfo.TimeInForce != ImmediateOrCancel && txInfo.TimeInForce != GoodTillTime && txInfo.TimeInForce != PostOnly {
return ErrOrderTimeInForceInvalid
}
if txInfo.ReduceOnly != 0 && txInfo.ReduceOnly != 1 {
return ErrOrderReduceOnlyInvalid
}
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 txInfo.TimeInForce != ImmediateOrCancel {
return ErrOrderTimeInForceInvalid
} else if txInfo.TriggerPrice == NilOrderTriggerPrice {
return ErrOrderTriggerPriceInvalid
} else if txInfo.OrderExpiry == NilOrderExpiry {
return ErrOrderExpiryInvalid
}
case StopLossLimitOrder, TakeProfitLimitOrder:
if txInfo.TriggerPrice == NilOrderTriggerPrice {
return ErrOrderTriggerPriceInvalid
} else if txInfo.OrderExpiry == NilOrderExpiry {
return ErrOrderExpiryInvalid
}
case TWAPOrder:
if txInfo.TimeInForce != GoodTillTime {
return ErrOrderTimeInForceInvalid
} else if txInfo.TriggerPrice != NilOrderTriggerPrice {
return ErrOrderTriggerPriceInvalid
} else if txInfo.OrderExpiry == NilOrderExpiry {
return ErrOrderExpiryInvalid
}
default:
return ErrOrderTypeInvalid
}
// TriggerPrice
if (txInfo.TriggerPrice < MinOrderTriggerPrice || txInfo.TriggerPrice > MaxOrderTriggerPrice) && txInfo.TriggerPrice != NilOrderTriggerPrice {
return ErrOrderTriggerPriceInvalid
}
// Nonce
if txInfo.Nonce < MinNonce {
return ErrNonceTooLow
}
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
return ErrExpiredAtInvalid
}
return nil
}
func (txInfo *L2CreateOrderTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
elems := make([]g.Element, 0, 16)
elems = append(elems, g.FromUint32(lighterChainId))
elems = append(elems, g.FromUint32(TxTypeL2CreateOrder))
elems = append(elems, g.FromInt64(txInfo.Nonce))
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
elems = append(elems, g.FromUint32(uint32(txInfo.MarketIndex)))
elems = append(elems, g.FromInt64(txInfo.ClientOrderIndex))
elems = append(elems, g.FromInt64(txInfo.BaseAmount))
elems = append(elems, g.FromUint32(txInfo.Price))
elems = append(elems, g.FromUint32(uint32(txInfo.IsAsk)))
elems = append(elems, g.FromUint32(uint32(txInfo.Type)))
elems = append(elems, g.FromUint32(uint32(txInfo.TimeInForce)))
elems = append(elems, g.FromUint32(uint32(txInfo.ReduceOnly)))
elems = append(elems, g.FromUint32(txInfo.TriggerPrice))
elems = append(elems, g.FromInt64(txInfo.OrderExpiry))
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
}
@@ -0,0 +1,101 @@
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 int64
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 < 0 {
return ErrPoolMinOperatorShareRateTooLow
}
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.FromInt64(txInfo.MinOperatorShareRate))
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
}
@@ -0,0 +1,73 @@
package txtypes
import (
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
)
var _ TxInfo = (*L2CreateSubAccountTxInfo)(nil)
type L2CreateSubAccountTxInfo struct {
AccountIndex int64 // Master account index
ApiKeyIndex uint8
ExpiredAt int64
Nonce int64
Sig []byte
SignedHash string `json:"-"`
}
func (txInfo *L2CreateSubAccountTxInfo) GetTxType() uint8 {
return TxTypeL2CreateSubAccount
}
func (txInfo *L2CreateSubAccountTxInfo) GetTxInfo() (string, error) {
return getTxInfo(txInfo)
}
func (txInfo *L2CreateSubAccountTxInfo) GetTxHash() string {
return txInfo.SignedHash
}
func (txInfo *L2CreateSubAccountTxInfo) Validate() error {
// AccountIndex
if txInfo.AccountIndex < MinAccountIndex {
return ErrFromAccountIndexTooLow
}
if txInfo.AccountIndex > MaxAccountIndex {
return ErrFromAccountIndexTooHigh
}
// ApiKeyIndex
if txInfo.ApiKeyIndex < MinApiKeyIndex {
return ErrApiKeyIndexTooLow
}
if txInfo.ApiKeyIndex > MaxApiKeyIndex {
return ErrApiKeyIndexTooHigh
}
// Nonce
if txInfo.Nonce < MinNonce {
return ErrNonceTooLow
}
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
return ErrExpiredAtInvalid
}
return nil
}
func (txInfo *L2CreateSubAccountTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
elems := make([]g.Element, 0, 6)
elems = append(elems, g.FromUint32(lighterChainId))
elems = append(elems, g.FromUint32(TxTypeL2CreateSubAccount))
elems = append(elems, g.FromInt64(txInfo.Nonce))
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
}
@@ -0,0 +1,66 @@
package txtypes
import "fmt"
var (
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)
ErrMarketIndexTooLow = fmt.Errorf("MarketIndex should not be less than %d", MinMarketIndex)
ErrMarketIndexTooHigh = fmt.Errorf("MarketIndex should not be larger than %d", MaxMarketIndex)
ErrMarketIndexMismatch = fmt.Errorf("MarketIndex should match the market index of the order")
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")
ErrTransferFeeNegative = fmt.Errorf("Transfer fee is negative")
ErrTransferFeeTooHigh = fmt.Errorf("Transfer fee is higher than %d", MaxTransferAmount)
)
@@ -0,0 +1,37 @@
package txtypes
import g "github.com/elliottech/poseidon_crypto/field/goldilocks"
type TxInfo interface {
GetTxType() uint8
GetTxInfo() (string, error)
// GetTxHash returns the hash that was signed when creating this transaction.
// The hash coincides with the TxHash received from Lighter after submitting this Tx.
// It can be used to get the TxHash in advance, or to double-check the correctness of the SDK.
// As this hash is signed by the ApiKey, if the value differs than the one computed by the server,
// it'll result in an invalid signature.
// Returns empty string if the Tx is not signed.
GetTxHash() string
Validate() error
Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error)
}
type OrderInfo struct {
MarketIndex uint8
ClientOrderIndex int64
BaseAmount int64
Price uint32
IsAsk uint8
Type uint8
TimeInForce uint8
ReduceOnly uint8
TriggerPrice uint32
OrderExpiry int64
}
@@ -0,0 +1,91 @@
package txtypes
import (
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
)
var _ TxInfo = (*L2MintSharesTxInfo)(nil)
type L2MintSharesTxInfo struct {
AccountIndex int64
ApiKeyIndex uint8
PublicPoolIndex int64
ShareAmount int64
ExpiredAt int64
Nonce int64
Sig []byte
SignedHash string `json:"-"`
}
func (txInfo *L2MintSharesTxInfo) GetTxType() uint8 {
return TxTypeL2MintShares
}
func (txInfo *L2MintSharesTxInfo) GetTxInfo() (string, error) {
return getTxInfo(txInfo)
}
func (txInfo *L2MintSharesTxInfo) GetTxHash() string {
return txInfo.SignedHash
}
func (txInfo *L2MintSharesTxInfo) Validate() error {
if txInfo.AccountIndex < MinAccountIndex {
return ErrFromAccountIndexTooLow
}
if txInfo.AccountIndex > MaxAccountIndex {
return ErrFromAccountIndexTooHigh
}
// ApiKeyIndex
if txInfo.ApiKeyIndex < MinApiKeyIndex {
return ErrApiKeyIndexTooLow
}
if txInfo.ApiKeyIndex > MaxApiKeyIndex {
return ErrApiKeyIndexTooHigh
}
// PublicPoolIndex
if txInfo.PublicPoolIndex < MinAccountIndex {
return ErrPublicPoolIndexTooLow
}
if txInfo.PublicPoolIndex > MaxAccountIndex {
return ErrPublicPoolIndexTooHigh
}
if txInfo.ShareAmount < MinPoolSharesToMintOrBurn {
return ErrPoolMintShareAmountTooLow
}
if txInfo.ShareAmount > MaxPoolSharesToMintOrBurn {
return ErrPoolMintShareAmountTooHigh
}
if txInfo.Nonce < MinNonce {
return ErrNonceTooLow
}
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
return ErrExpiredAtInvalid
}
return nil
}
func (txInfo *L2MintSharesTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
elems := make([]g.Element, 0, 8)
elems = append(elems, g.FromUint32(lighterChainId))
elems = append(elems, g.FromUint32(TxTypeL2MintShares))
elems = append(elems, g.FromInt64(txInfo.Nonce))
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
elems = append(elems, g.FromInt64(txInfo.PublicPoolIndex))
elems = append(elems, g.FromInt64(txInfo.ShareAmount))
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
}
@@ -0,0 +1,120 @@
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 uint8
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
if txInfo.MarketIndex < MinMarketIndex {
return ErrMarketIndexTooLow
}
if txInfo.MarketIndex > MaxMarketIndex {
return ErrMarketIndexTooHigh
}
// Index
if txInfo.Index < MinClientOrderIndex && txInfo.Index < MinOrderIndex {
return ErrClientOrderIndexTooLow
}
if txInfo.Index > MaxClientOrderIndex && txInfo.Index > MaxOrderIndex {
return ErrClientOrderIndexTooHigh
}
// BaseAmount
if txInfo.BaseAmount != NilOrderBaseAmount && txInfo.BaseAmount < MinOrderBaseAmount {
return ErrBaseAmountTooLow
}
if txInfo.BaseAmount > MaxOrderBaseAmount {
return ErrBaseAmountTooHigh
}
// Price
if txInfo.Price < MinOrderPrice {
return ErrPriceTooLow
}
if txInfo.Price > MaxOrderPrice {
return ErrPriceTooHigh
}
// TriggerPrice
if (txInfo.TriggerPrice < MinOrderTriggerPrice || txInfo.TriggerPrice > MaxOrderTriggerPrice) && txInfo.TriggerPrice != NilOrderTriggerPrice {
return ErrOrderTriggerPriceInvalid
}
// Nonce
if txInfo.Nonce < MinNonce {
return ErrNonceTooLow
}
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
return ErrExpiredAtInvalid
}
return nil
}
func (txInfo *L2ModifyOrderTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
elems := make([]g.Element, 0, 11)
elems = append(elems, g.FromUint32(lighterChainId))
elems = append(elems, g.FromUint32(TxTypeL2ModifyOrder))
elems = append(elems, g.FromInt64(txInfo.Nonce))
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
elems = append(elems, g.FromUint32(uint32(txInfo.MarketIndex)))
elems = append(elems, g.FromInt64(txInfo.Index))
elems = append(elems, g.FromInt64(txInfo.BaseAmount))
elems = append(elems, g.FromUint32(txInfo.Price))
elems = append(elems, g.FromUint32(txInfo.TriggerPrice))
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
}
@@ -0,0 +1,128 @@
package txtypes
import (
"encoding/hex"
"fmt"
"strings"
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
)
const templateTransfer = "Transfer\n\nnonce: %s\nfrom: %s\napi key: %s\nto: %s\namount: %s\nfee: %s\nmemo: %s\nOnly sign this message for a trusted client!"
var _ TxInfo = (*L2TransferTxInfo)(nil)
type L2TransferTxInfo struct {
FromAccountIndex int64
ApiKeyIndex uint8
ToAccountIndex int64
USDCAmount int64 // USDCAmount is given with 6 decimals
Fee int64
Memo [32]byte
ExpiredAt int64
Nonce int64
Sig []byte
SignedHash string `json:"-"`
}
func (txInfo *L2TransferTxInfo) Validate() error {
// plus one for treasury account
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
}
if txInfo.ToAccountIndex < MinAccountIndex+1 {
return ErrToAccountIndexTooLow
}
if txInfo.ToAccountIndex > MaxAccountIndex {
return ErrToAccountIndexTooHigh
}
if txInfo.USDCAmount <= 0 {
return ErrTransferAmountTooLow
}
if txInfo.USDCAmount > MaxTransferAmount {
return ErrTransferAmountTooHigh
}
if txInfo.Fee < 0 {
return ErrTransferFeeNegative
}
if txInfo.Fee > 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) 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(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.FromUint64(uint64(txInfo.USDCAmount)&0xFFFFFFFF)) //nolint:gosec
elems = append(elems, g.FromUint64(uint64(txInfo.USDCAmount)>>32)) //nolint:gosec
elems = append(elems, g.FromUint64(uint64(txInfo.Fee)&0xFFFFFFFF)) //nolint:gosec
elems = append(elems, g.FromUint64(uint64(txInfo.Fee)>>32)) //nolint:gosec
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
}
func (txInfo *L2TransferTxInfo) GetL1SignatureBody() 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.ApiKeyIndex)),
getHex10FromUint64(uint64(txInfo.ToAccountIndex)),
getHex10FromUint64(uint64(txInfo.USDCAmount)),
getHex10FromUint64(uint64(txInfo.Fee)),
hexMemo,
)
return signatureBody
}
@@ -0,0 +1,98 @@
package txtypes
import (
g "github.com/elliottech/poseidon_crypto/field/goldilocks"
p2 "github.com/elliottech/poseidon_crypto/hash/poseidon2_goldilocks"
)
var _ TxInfo = (*L2UpdateLeverageTxInfo)(nil)
type L2UpdateLeverageTxInfo struct {
AccountIndex int64
ApiKeyIndex uint8
MarketIndex uint8
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 < MinMarketIndex {
return ErrMarketIndexTooLow
}
if txInfo.MarketIndex > MaxMarketIndex {
return ErrMarketIndexTooHigh
}
// 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
}
if txInfo.MarginMode != CrossMargin && txInfo.MarginMode != IsolatedMargin {
return ErrInvalidMarginMode
}
return nil
}
func (txInfo *L2UpdateLeverageTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
elems := make([]g.Element, 0, 9)
elems = append(elems, g.FromUint32(lighterChainId))
elems = append(elems, g.FromUint32(TxTypeL2UpdateLeverage))
elems = append(elems, g.FromInt64(txInfo.Nonce))
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
elems = append(elems, g.FromInt64(int64(txInfo.MarketIndex)))
elems = append(elems, g.FromInt64(int64(txInfo.InitialMarginFraction)))
elems = append(elems, g.FromUint32(uint32(txInfo.MarginMode)))
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
}
@@ -0,0 +1,98 @@
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 uint8
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 < MinMarketIndex {
return ErrMarketIndexTooLow
}
if txInfo.MarketIndex > MaxMarketIndex {
return ErrMarketIndexTooHigh
}
if txInfo.USDCAmount <= 0 {
return ErrTransferAmountTooLow
}
if txInfo.USDCAmount > MaxTransferAmount {
return ErrTransferAmountTooHigh
}
if txInfo.Direction != RemoveFromIsolatedMargin && txInfo.Direction != AddToIsolatedMargin {
return ErrInvalidUpdateMarginDirection
}
if txInfo.Nonce < MinNonce {
return ErrNonceTooLow
}
if txInfo.ExpiredAt < 0 || txInfo.ExpiredAt > MaxTimestamp {
return ErrExpiredAtInvalid
}
return nil
}
func (txInfo *L2UpdateMarginTxInfo) Hash(lighterChainId uint32, extra ...g.Element) (msgHash []byte, err error) {
elems := make([]g.Element, 0, 10)
elems = append(elems, g.FromUint32(lighterChainId))
elems = append(elems, g.FromUint32(TxTypeL2UpdateMargin))
elems = append(elems, g.FromInt64(txInfo.Nonce))
elems = append(elems, g.FromInt64(txInfo.ExpiredAt))
elems = append(elems, g.FromInt64(txInfo.AccountIndex))
elems = append(elems, g.FromUint32(uint32(txInfo.ApiKeyIndex)))
elems = append(elems, g.FromInt64(int64(txInfo.MarketIndex)))
elems = append(elems, g.FromUint64(uint64(txInfo.USDCAmount)&0xFFFFFFFF)) //nolint:gosec
elems = append(elems, g.FromUint64(uint64(txInfo.USDCAmount)>>32)) //nolint:gosec
elems = append(elems, g.FromUint32(uint32(txInfo.Direction)))
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
}
@@ -0,0 +1,109 @@
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 int64
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 < 0 {
return ErrPoolMinOperatorShareRateTooLow
}
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.FromInt64(txInfo.MinOperatorShareRate))
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
}
@@ -0,0 +1,28 @@
package txtypes
import "encoding/json"
func IsValidPubKey(bytes []byte) bool {
if len(bytes) != 40 {
return false
}
return !isZeroByteSlice(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
}
@@ -0,0 +1,82 @@
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
USDCAmount uint64 // USDCAmount is given with 6 decimals
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
}
if txInfo.USDCAmount == 0 {
return ErrWithdrawalAmountTooLow
}
if txInfo.USDCAmount > 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, 8)
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.FromUint64(uint64(txInfo.USDCAmount)&0xFFFFFFFF)) //nolint:gosec
elems = append(elems, g.FromUint64(uint64(txInfo.USDCAmount)>>32)) //nolint:gosec
return p2.HashToQuinticExtension(elems).ToLittleEndianBytes(), nil
}