Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 41 additions & 38 deletions loadtest/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,31 +32,34 @@ type EncodingConfig struct {
}

var (
TEST_CONFIG EncodingConfig
TX_CLIENT typestx.ServiceClient
TX_HASH_FILE *os.File
CHAIN_ID string
TestConfig EncodingConfig
TxClient typestx.ServiceClient
TxHashFile *os.File
ChainID string
)

const BATCH_SIZE = 100
const (
BatchSize = 100
VortexData = "{\"position_effect\":\"Open\",\"leverage\":\"1\"}"
)

var FROM_MILI = sdk.NewDec(1000000)
var FromMili = sdk.NewDec(1000000)

func init() {
cdc := codec.NewLegacyAmino()
interfaceRegistry := types.NewInterfaceRegistry()
marshaler := codec.NewProtoCodec(interfaceRegistry)

TEST_CONFIG = EncodingConfig{
TestConfig = EncodingConfig{
InterfaceRegistry: interfaceRegistry,
Marshaler: marshaler,
TxConfig: tx.NewTxConfig(marshaler, tx.DefaultSignModes),
Amino: cdc,
}
std.RegisterLegacyAminoCodec(TEST_CONFIG.Amino)
std.RegisterInterfaces(TEST_CONFIG.InterfaceRegistry)
app.ModuleBasics.RegisterLegacyAminoCodec(TEST_CONFIG.Amino)
app.ModuleBasics.RegisterInterfaces(TEST_CONFIG.InterfaceRegistry)
std.RegisterLegacyAminoCodec(TestConfig.Amino)
std.RegisterInterfaces(TestConfig.InterfaceRegistry)
app.ModuleBasics.RegisterLegacyAminoCodec(TestConfig.Amino)
app.ModuleBasics.RegisterInterfaces(TestConfig.InterfaceRegistry)
}

func run(
Expand All @@ -75,7 +78,7 @@ func run(
grpc.WithInsecure(),
)
defer grpcConn.Close()
TX_CLIENT = typestx.NewServiceClient(grpcConn)
TxClient = typestx.NewServiceClient(grpcConn)
userHomeDir, _ := os.UserHomeDir()
filename := filepath.Join(userHomeDir, "outputs", "test_tx_hash")
_ = os.Remove(filename)
Expand All @@ -84,7 +87,7 @@ func run(
fmt.Printf("Error opening file %s", err)
return
}
TX_HASH_FILE = file
TxHashFile = file
var mu sync.Mutex

activeAccounts := []int{}
Expand All @@ -99,36 +102,38 @@ func run(
wgs := []*sync.WaitGroup{}
sendersList := [][]func(){}
for i := 0; i < int(numberOfBlocks); i++ {
fmt.Println(fmt.Sprintf("Preparing %d-th block", i))
var wg *sync.WaitGroup = &sync.WaitGroup{}
fmt.Printf("Preparing %d-th block\n", i)
wg := &sync.WaitGroup{}
var senders []func()
wgs = append(wgs, wg)
for j, account := range activeAccounts {
key := GetKey(uint64(account))
orderPlacements := []*dextypes.OrderPlacement{}
orderPlacements := []*dextypes.Order{}
longPrice := uint64(j)%(longPriceCeiling-longPriceFloor) + longPriceFloor
longQuantity := uint64(rand.Intn(int(quantityCeiling)-int(quantityFloor))) + quantityFloor
shortPrice := uint64(j)%(shortPriceCeiling-shortPriceFloor) + shortPriceFloor
shortQuantity := uint64(rand.Intn(int(quantityCeiling)-int(quantityFloor))) + quantityFloor
for j := 0; j < BATCH_SIZE; j++ {
orderPlacements = append(orderPlacements, &dextypes.OrderPlacement{
for j := 0; j < BatchSize; j++ {
orderPlacements = append(orderPlacements, &dextypes.Order{
Account: sdk.AccAddress(key.PubKey().Address()).String(),
ContractAddr: contractAddress,
PositionDirection: dextypes.PositionDirection_LONG,
Price: sdk.NewDec(int64(longPrice)).Quo(FROM_MILI),
Quantity: sdk.NewDec(int64(longQuantity)).Quo(FROM_MILI),
PriceDenom: "usdc",
AssetDenom: "sei",
PositionEffect: dextypes.PositionEffect_OPEN,
Price: sdk.NewDec(int64(longPrice)).Quo(FromMili),
Quantity: sdk.NewDec(int64(longQuantity)).Quo(FromMili),
PriceDenom: "SEI",
AssetDenom: "ATOM",
OrderType: dextypes.OrderType_LIMIT,
Leverage: sdk.NewDec(1),
}, &dextypes.OrderPlacement{
Data: VortexData,
}, &dextypes.Order{
Account: sdk.AccAddress(key.PubKey().Address()).String(),
ContractAddr: contractAddress,
PositionDirection: dextypes.PositionDirection_SHORT,
Price: sdk.NewDec(int64(shortPrice)).Quo(FROM_MILI),
Quantity: sdk.NewDec(int64(shortQuantity)).Quo(FROM_MILI),
PriceDenom: "usdc",
AssetDenom: "sei",
PositionEffect: dextypes.PositionEffect_OPEN,
Price: sdk.NewDec(int64(shortPrice)).Quo(FromMili),
Quantity: sdk.NewDec(int64(shortQuantity)).Quo(FromMili),
PriceDenom: "SEI",
AssetDenom: "ATOM",
OrderType: dextypes.OrderType_LIMIT,
Leverage: sdk.NewDec(1),
Data: VortexData,
})
}
amount, err := sdk.ParseCoinsNormalized(fmt.Sprintf("%d%s", longPrice*longQuantity+shortPrice*shortQuantity, "usei"))
Expand All @@ -141,7 +146,7 @@ func run(
ContractAddr: contractAddress,
Funds: amount,
}
txBuilder := TEST_CONFIG.TxConfig.NewTxBuilder()
txBuilder := TestConfig.TxConfig.NewTxBuilder()
_ = txBuilder.SetMsgs(&msg)
seqDelta := uint64(i / 2)
SignTx(&txBuilder, key, seqDelta)
Expand All @@ -158,9 +163,7 @@ func run(
}
sendersList = append(sendersList, senders)

tmp := inactiveAccounts
inactiveAccounts = activeAccounts
activeAccounts = tmp
inactiveAccounts, activeAccounts = activeAccounts, inactiveAccounts
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does this actually work? wouldn't it assign inactiveAccounts = activeAccounts first and then the variable for active accounts is the same as a result? if not, kinda cool

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is like python, you can do multiple variable assignments in 1 line

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah i didn't know it works but this is what the linter asked me to do lol

}

lastHeight := getLastHeight()
Expand All @@ -170,7 +173,7 @@ func run(
time.Sleep(50 * time.Millisecond)
newHeight = getLastHeight()
}
fmt.Println(fmt.Sprintf("Sending %d-th block", i))
fmt.Printf("Sending %d-th block\n", i)

senders := sendersList[i]
wg := wgs[i]
Expand Down Expand Up @@ -210,8 +213,8 @@ func main() {
shortPriceCeiling, _ := strconv.ParseUint(args[6], 10, 64)
quantityFloor, _ := strconv.ParseUint(args[7], 10, 64)
quantityCeiling, _ := strconv.ParseUint(args[8], 10, 64)
chainId := args[9]
CHAIN_ID = chainId
chainID := args[9]
ChainID = chainID
run(
contractAddress,
numberOfAccounts,
Expand Down
20 changes: 11 additions & 9 deletions loadtest/sign.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import (
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
)

const NODE_URI = "tcp://localhost:26657"
const NodeURI = "tcp://localhost:26657"

type AccountInfo struct {
Address string `json:"address"`
Expand All @@ -39,7 +39,9 @@ func GetKey(accountIdx uint64) cryptotypes.PrivKey {
panic(err)
}
jsonFile.Close()
json.Unmarshal(byteVal, &accountInfo)
if err := json.Unmarshal(byteVal, &accountInfo); err != nil {
panic(err)
}
kr, _ := keyring.New(sdk.KeyringServiceName(), "os", filepath.Join(userHomeDir, ".sei-chain"), os.Stdin)
keyringAlgos, _ := kr.SupportedAlgorithms()
algoStr := string(hd.Secp256k1Type)
Expand All @@ -56,7 +58,7 @@ func SignTx(txBuilder *client.TxBuilder, privKey cryptotypes.PrivKey, seqDelta u
sigV2 := signing.SignatureV2{
PubKey: privKey.PubKey(),
Data: &signing.SingleSignatureData{
SignMode: TEST_CONFIG.TxConfig.SignModeHandler().DefaultMode(),
SignMode: TestConfig.TxConfig.SignModeHandler().DefaultMode(),
Signature: nil,
},
Sequence: seqNum,
Expand All @@ -65,16 +67,16 @@ func SignTx(txBuilder *client.TxBuilder, privKey cryptotypes.PrivKey, seqDelta u
_ = (*txBuilder).SetSignatures(sigsV2...)
sigsV2 = []signing.SignatureV2{}
signerData := xauthsigning.SignerData{
ChainID: CHAIN_ID,
ChainID: ChainID,
AccountNumber: accountNum,
Sequence: seqNum,
}
sigV2, _ = clienttx.SignWithPrivKey(
TEST_CONFIG.TxConfig.SignModeHandler().DefaultMode(),
TestConfig.TxConfig.SignModeHandler().DefaultMode(),
signerData,
*txBuilder,
privKey,
TEST_CONFIG.TxConfig,
TestConfig.TxConfig,
seqNum,
)
sigsV2 = append(sigsV2, sigV2)
Expand All @@ -88,14 +90,14 @@ func GetAccountNumberSequenceNumber(privKey cryptotypes.PrivKey) (uint64, uint64
panic(err)
}
accountRetriever := authtypes.AccountRetriever{}
cl, err := client.NewClientFromNode(NODE_URI)
cl, err := client.NewClientFromNode(NodeURI)
if err != nil {
panic(err)
}
context := client.Context{}
context = context.WithNodeURI(NODE_URI)
context = context.WithNodeURI(NodeURI)
context = context.WithClient(cl)
context = context.WithInterfaceRegistry(TEST_CONFIG.InterfaceRegistry)
context = context.WithInterfaceRegistry(TestConfig.InterfaceRegistry)
account, seq, err := accountRetriever.GetAccountNumberSequence(context, address)
if err != nil {
time.Sleep(5 * time.Second)
Expand Down
118 changes: 7 additions & 111 deletions loadtest/tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,17 @@ package main

import (
"context"
"encoding/json"
"fmt"
"strconv"
"sync"
"time"

wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types"
"github.com/cosmos/cosmos-sdk/client"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
typestx "github.com/cosmos/cosmos-sdk/types/tx"
)

const (
LONG = "Long"
SHORT = "Short"
OPEN = "Open"
CLOSE = "Close"
)

func SendTx(
key cryptotypes.PrivKey,
txBuilder *client.TxBuilder,
Expand All @@ -35,9 +25,9 @@ func SendTx(
sdk.NewCoin("usei", sdk.NewInt(100000)),
})
SignTx(txBuilder, key, seqDelta)
txBytes, _ := TEST_CONFIG.TxConfig.TxEncoder()((*txBuilder).GetTx())
txBytes, _ := TestConfig.TxConfig.TxEncoder()((*txBuilder).GetTx())
return func() {
grpcRes, err := TX_CLIENT.BroadcastTx(
grpcRes, err := TxClient.BroadcastTx(
context.Background(),
&typestx.BroadcastTxRequest{
Mode: mode,
Expand All @@ -51,7 +41,7 @@ func SendTx(
// retry after a second until either succeed or fail for some other reason
fmt.Printf("Mempool full\n")
time.Sleep(1 * time.Second)
grpcRes, err = TX_CLIENT.BroadcastTx(
grpcRes, err = TxClient.BroadcastTx(
context.Background(),
&typestx.BroadcastTxRequest{
Mode: mode,
Expand All @@ -63,107 +53,13 @@ func SendTx(
}
}
if grpcRes.TxResponse.Code != 0 {
fmt.Printf("Error: %d\n", grpcRes.TxResponse.Code)
fmt.Printf("Error: %d, %s\n", grpcRes.TxResponse.Code, grpcRes.TxResponse.RawLog)
} else {
mu.Lock()
defer mu.Unlock()
TX_HASH_FILE.WriteString(fmt.Sprintf("%s\n", grpcRes.TxResponse.TxHash))
if _, err := TxHashFile.WriteString(fmt.Sprintf("%s\n", grpcRes.TxResponse.TxHash)); err != nil {
panic(err)
}
}
}
}

func GetLimitOrderTxBuilder(
contractAddress string,
key cryptotypes.PrivKey,
price uint64,
quantity uint64,
long bool,
open bool,
nonce uint64,
) client.TxBuilder {
txBuilder := TEST_CONFIG.TxConfig.NewTxBuilder()
var direction string
if long {
direction = LONG
} else {
direction = SHORT
}
var effect string
if open {
effect = OPEN
} else {
effect = CLOSE
}
body := map[string]interface{}{
"limit_order": map[string]interface{}{
"price": strconv.FormatUint(price, 10),
"quantity": strconv.FormatUint(quantity, 10),
"position_direction": direction,
"position_effect": effect,
"price_denom": "ust",
"asset_denom": "luna",
"nonce": nonce,
},
}
amount, err := sdk.ParseCoinsNormalized(fmt.Sprintf("%d%s", price*quantity, "ust"))
if err != nil {
panic(err)
}
serialized_body, _ := json.Marshal(body)
msg := wasmtypes.MsgExecuteContract{
Sender: sdk.AccAddress(key.PubKey().Address()).String(),
Contract: contractAddress,
Msg: serialized_body,
Funds: amount,
}
_ = txBuilder.SetMsgs(&msg)
return txBuilder
}

func GetMarketOrderTxBuilder(
contractAddress string,
key cryptotypes.PrivKey,
price uint64,
quantity uint64,
long bool,
open bool,
nonce uint64,
) client.TxBuilder {
txBuilder := TEST_CONFIG.TxConfig.NewTxBuilder()
var direction string
if long {
direction = LONG
} else {
direction = SHORT
}
var effect string
if open {
effect = OPEN
} else {
effect = CLOSE
}
body := map[string]interface{}{
"market_order": map[string]interface{}{
"worst_price": strconv.FormatUint(price, 10),
"quantity": strconv.FormatUint(quantity, 10),
"position_direction": direction,
"position_effect": effect,
"price_denom": "ust",
"asset_denom": "luna",
"nonce": nonce,
},
}
amount, err := sdk.ParseCoinsNormalized(fmt.Sprintf("%d%s", price*quantity, "ust"))
if err != nil {
panic(err)
}
serialized_body, _ := json.Marshal(body)
msg := wasmtypes.MsgExecuteContract{
Sender: sdk.AccAddress(key.PubKey().Address()).String(),
Contract: contractAddress,
Msg: serialized_body,
Funds: amount,
}
_ = txBuilder.SetMsgs(&msg)
return txBuilder
}