0g-chain/rest_test/setup/setuptest.go
JM fd39cea7a5
CDP rest api automating testing (#401)
* adding script to start the chain

* fixed val rewards test

* fix outstanding rewards test

* fixed rewards

* hooks skeleton

* adding test file and hooks

* Add Savings Rate (#365)

* fix: ensure cdp module accounts created at gensis

* feat: add savings rate

* chore: update alias

* fix: update default test param values

* chore: update spec for savings rate

* fix: add distribution time to genesis state

* fix: iterate over accounts using callback function

* feat: use seprate mod account for savings rate

* fix: remove mod account coins from total supply

* address review comments

* fix: genesis function initialization

* fix: update alias

* add comment about maintaining module account list

* feat: add genesis example

* R4R: bep3 module upgrades (#388)

* bep3 module scaffold from cosmos/scaffold

* Populated types, keeper with HTLT msgs, module params, and scaffolding for keys, and genesis

* added KavaHTLT struct, UpdateHTLT struct, resolved compilation errors

* refactored kavaHTLT struct <-> msgs

* Implemented params, refactored UpdateKavaHTLT to UpdateKHTLT interface

* Updated keeper with byTimeIndex methods

* HTLT creation flow

* adjustments in prep for repo config updates

* App moudle updated for bep3, MsgCreateHTLT tested, HTLT keeper methods tested

* Updated bep3 params to match spec

* tests for MsgRefundHTLT, MsgDepositHTLT, MsgClaimHTLT

* AddHtlt cli cmd, queryHtlts cmd, added conversion funcs for binance -> cosmos types, refactored MsgCreateHTLT from binance.AccAddress to sdk.AccAddress

* working edits related to bep3-deputy compatibility

* removed binance-chain go sdk dependency

* updated msg ValidateBasic() return to sdk.Error type

* implement MsgCalculateSwapID

* added MsgCalculateSwapID test, updated randomNumberHash type to []byte

* removed binance type conversions

* msg codec registration

* clean /types directory

* CLI cmds:create htlt, query htlt

* update keeper logic

* handle MsgCreateHTLT

* implement htlt type, msg types

* implement global chain types

* update querier

* added go-ethereum to go mod

* refactor QuerySwap to QueryHTLT

* update HTLTMsg to MsgCreateHTLT

* implemented htlt deposit

* add token transfer to MsgCreateHTLT

* implement refund, claim client txs

* add refund/claim cmds to tx cmd

* commiting go.sum for build

* implemented keeper claim logic

* add RandomNumberHash to create-htlt event

* implement refund keeper logic

* AddHTLT updated to CreateHTLT

* added params keeper

* updated params to single chain, added sample genesis file

* implemented htlt keeper param checks

* removed go-ethereum dependency

* updated go.sum

* housekeeping on keeper tests

* updated cli tx cmds

* ran go.tidy

* remove links from module readme

* updated coin construction in tests

* added expectedIncome checks in ValidateBasic()

* made ValidateAsset() more robust

* update param format for tests

* added basic HTLTByTime index

* implement abci, fix expectedIncome validation

* byTime index updated to blocks, added swap ID & expiration block to htlt

* added not-expired check to HTLT claims

* cross-chain mint/burn logic, htlt string type refactored to []byte

* fix bnb_deputy_address param

* remove abci panic

* cmn.HexBytes, byTime index iteration update, claim-mint logic update

* update genesis example

* general codebase cleaning

* renamed HTLT to AtomicSwap

* staging for PR

* updated naming conventions

* refactor + revisions

* removed code related to deposits & swap block index

* added timestamp validation comment

* post-refactor housekeeping

* post refactor housekeeping (keeper)

* remove GenesisAtomicSwap type

* refactor asset supply logic

* BeginBlocker expires swaps automatically

* param asset.limit type updated to sdk.Int

* remove claimed swaps from block index

* fix DefaultDeputyAddress

* removed BaseSwap

* revisions

* total genesis coins

* updated tx examples

* timestamp to unix

* add past timestamp limit

* update random number byte encoding

* add recipient_other_chain to AtomicSwap

* add TODO for timestamp arg parsing

* generate secure random numbers

* update tx cli

* keeper tests

* add bnb token

* bep3 params test set up, test CreateAtomicSwap

* swap table tests

* Revert "bep3 params test set up, test CreateAtomicSwap"

This reverts commits containing tests.

* use tmtime.Now()

* updates on the hooks working

* now creates a transaction and sends to the chain via rest api successfully

* small fix - now works

* 34 tests now passing successfully

* Kava distribution module (#387)

* wip: kavadist module structure

* feat: implement minting logic

* wip: sketch module

* wip: module level code

* wip: bug fixes

* wip: add tests

* wip: resolve todos and tidy

* fix: remove unused file

* address review comments

* fix print statement error

* instructions on how to run the tests

* changing function names when to run the hooks

* adding instructions on how to setup and run the dredd tests

* removing large error output file

* removing binary file

* removing more output logging files

* creating a vote on a proposal to send to the blockchain

* adding instructions on how to setup chain

* adding function to get account number and sequence number

* adding send msg to blockchain method

* posting vote tx to blockchain - successfully prepares and sends vote to endpoint but endpoint returns 'inactive proposal with id'

* successfully depositing 600 stake to a proposal

* successfully depositing onto a proposal and then voting on it

* got another governance test working now after submitting a vote to the blockchain

* updating instructions on how to run

* fixed another voting test

* fixed deposits test

* fixed another gov test

* fix print line

* fix circle ci build issue with println

* improving instructions on how to build and run the hooks and dredd tests

* improving instructions on how to build and run the hooks and dredd tests

* finally fixed param change governance proposal test

* trying to unskip tests wip

* fixed gov/proposals test

* fixed another test

* fixed a slashing test

* fixed another redelegation test

* fixed another unbonding delegation test

* fixed more staking tests

* fixed another staking test

* fixed another test

* fixed more tests. 50 now passing, 15 failing

* fix: update genesis for guide (#394)

* fixed mislabeled variable

* managed to fix unjail test

* fixed bank acct transfers test

* add kava_dist to sample genesis file (#396)

* change certain types from number to string to match the output, typo fix

* another typo fix

* fixed delegation test

* finally figured out and fixed the latest blocks types mismatch - fixed the test

* fixed staking delegators validators test

* removed and noted unimplemented tests from yaml file. fixed blocks height test

* fixed transcations test

* adding functionality to send transfer of coins to blockchain, and to send delegations

* updating the yaml to line up with a valid message format

* added delegation method

* adding test results showing 57 are now passing and only 5 failing

* remove test yaml file from pull req

* testing file updates

* adding test memo

* added undelegation hook method - fixed unbonding delegation test

* fixed the get tx from hash test

* adding not if you encounter validator set is different errors how to fix. 59 tests now passsing, 3 failing

* adding test results showing 59 passing, 3 failing

* finally fixed encode test - 60 tests now passing only 2 failing

* adding test results 60 passing 1 failing

* more test updates

* finally fixed decode test - 61 tests now passing only 1 failing

* test results 61 tests passing 1 failing

* remove dead code

* all 62 tests are now passingga swagger.yaml  0 failing

* used for testing and generating transactions and testing hooks

* updating run instructions

* more instructions updates

* updating the test file

* adding note on reading from a file

* refactoring code and cleanup

* refactoring getting the keybase

* code cleanup for address, keyname methods, remove unused code

* more code cleanup around addresses

* updating the instructions on how to run the dredd tests

* adding comment

* R4R: BEP3 module test suite (#395)

* refactor secure rng

* refactor common tests, implement keeper tests

* implement asset tests

* implement params, querier tests

* implement keeper swap tests

* refactor import naming conventions

* implement core types tests

* improve keeper swap tests

* implement genesis types test

* implement params test + revisions

* implement duplicate swap test

* implement duplicate swap ID test

* adding additional requirements to the go.mod dependency file

* remove hardcoded home directory, read using os golang library

* increase timeout in example run script

* remove hardcoded home directory

* reordering commands to get rid of errors if key directory is deleted

* changing to use temporary directory

* updating dredd timeout time

* finally managed to get the script wroking using a temporary directory instead of the default

* adding notes and comments

* changing to use a temp directory instead of default directory

* remove un-needed file

* rename debugging tools folder

* adding instructions to install dredd and npm

* Update swagger-ui/startchain.sh

Send output to dev null not to console

Co-Authored-By: Kevin Davis <karzak@users.noreply.github.com>

* Update swagger-ui/startchain.sh

Send output to dev null not to console

Co-Authored-By: Kevin Davis <karzak@users.noreply.github.com>

* adding new version of test.go to setup the chain

* adding todo to update instructions for new workflow

* updating script to start and setup the chain

* updating the transaction hash test

* update the start chain script to setup the chain correctly

* add the script to stop the chain and the rest server

* updated the instructions for the new workflow so that all the tests pass the first time

* updated the instructions on how to run the tests

* update instructions for printing logs or not

* updating the startchain script to add messages when starting the rest server and preparing transactions

* adding print messages when stop chain is completed

* updating test results to just include test output and not the debug log statements

* cleaning up the messages that are printed to the user

* moving files to their own directory

* build go test file and remove previous binary

* move instructions

* updating instructions now that test file is auto built

* building, running dredd tests, propagating error code, shut down blockchain all in one script

* fix object type to array type for block latests

* cleaning up the script

* rename script as it now does all the setup, test running, shutdown, and cleanup

* update instructions for new workflow

* adding a shell script to call from the makefile

* adding a make command to build and run all the dredd tests

* update instructions to run using make

* updated code review comment

* minor update to instructions

* update remove file command so doesn't print an error if the file has already been deleted

* renaming folder and test

* adjust code comment

* removing example test results

* updating instructions to remove reference to the test results

* remove old hooks file

* remove obsolete code comment

* remove swagger file, will change references to the other one

* remove shell script, will now use the one called from make instead

* renaming as underscore messes up go build

* clean up script, fix return code issues

* cleanup output file

* fix object to array issue

* add comments to explain functionality

* use variables for kvd home and kvcli home, check for errors

* change the kvcli home directory. need to take this from command line

* take kvcli from command line parameter to golang file

* take kvcli directory from command line parameter

* do not shut down the blockchain, use new swagger file

* initial fixes to get yaml to pass the dredd validator

* first test results - 19 passing, 66 failing

* R4R: BEP3 additional features + module test suite (#397)

* update and reorder errors

* implement swap deletion block delay

* add swap deletion block delay, set up tests

* add secure random number gen

* implement AtomicSwapLongtermStorage index

* fix syntax error

* abci test updates

* implement handler test

* implement core genesis tests

* update asset supply logic

* implement functional asset supply

* pretty print atomic swaps

* requested revisions

* fix test suite post merge

* implement and integrate asset supply tests

* update import genesis, add storage duration param

* implement swap deletion ABCI test

* go mod tidy

* remove duplicated interface assertion

* add new bep3 param to contrib genesis file

* remove btc from supported assets

* revisions: LongtermStorageDuration param

* revisions: suite ctx, fix genesis, update contrib

* implement AssetSupply type, store key, keeper

* integrate supply and swaps; genesis, tests

* remove legacy comments

* requested revisions

* update alias

* Swagger Rest Automating Testing With Dredd  (#390)

* swagger testing and mods

* fixed a test

* fixed withdraw address

* adding script to start the chain

* fixed val rewards test

* fix outstanding rewards test

* fixed rewards

* hooks skeleton

* adding test file and hooks

* updates on the hooks working

* now creates a transaction and sends to the chain via rest api successfully

* small fix - now works

* 34 tests now passing successfully

* fix print statement error

* instructions on how to run the tests

* changing function names when to run the hooks

* adding instructions on how to setup and run the dredd tests

* removing large error output file

* removing binary file

* removing more output logging files

* creating a vote on a proposal to send to the blockchain

* adding instructions on how to setup chain

* adding function to get account number and sequence number

* adding send msg to blockchain method

* posting vote tx to blockchain - successfully prepares and sends vote to endpoint but endpoint returns 'inactive proposal with id'

* successfully depositing 600 stake to a proposal

* successfully depositing onto a proposal and then voting on it

* got another governance test working now after submitting a vote to the blockchain

* updating instructions on how to run

* fixed another voting test

* fixed deposits test

* fixed another gov test

* fix print line

* fix circle ci build issue with println

* improving instructions on how to build and run the hooks and dredd tests

* improving instructions on how to build and run the hooks and dredd tests

* finally fixed param change governance proposal test

* trying to unskip tests wip

* fixed gov/proposals test

* fixed another test

* fixed a slashing test

* fixed another redelegation test

* fixed another unbonding delegation test

* fixed more staking tests

* fixed another staking test

* fixed another test

* fixed more tests. 50 now passing, 15 failing

* fixed mislabeled variable

* managed to fix unjail test

* fixed bank acct transfers test

* change certain types from number to string to match the output, typo fix

* another typo fix

* fixed delegation test

* finally figured out and fixed the latest blocks types mismatch - fixed the test

* fixed staking delegators validators test

* removed and noted unimplemented tests from yaml file. fixed blocks height test

* fixed transcations test

* adding functionality to send transfer of coins to blockchain, and to send delegations

* updating the yaml to line up with a valid message format

* added delegation method

* adding test results showing 57 are now passing and only 5 failing

* remove test yaml file from pull req

* testing file updates

* adding test memo

* added undelegation hook method - fixed unbonding delegation test

* fixed the get tx from hash test

* adding not if you encounter validator set is different errors how to fix. 59 tests now passsing, 3 failing

* adding test results showing 59 passing, 3 failing

* finally fixed encode test - 60 tests now passing only 2 failing

* adding test results 60 passing 1 failing

* more test updates

* finally fixed decode test - 61 tests now passing only 1 failing

* test results 61 tests passing 1 failing

* remove dead code

* all 62 tests are now passingga swagger.yaml  0 failing

* used for testing and generating transactions and testing hooks

* updating run instructions

* more instructions updates

* updating the test file

* adding note on reading from a file

* refactoring code and cleanup

* refactoring getting the keybase

* code cleanup for address, keyname methods, remove unused code

* more code cleanup around addresses

* updating the instructions on how to run the dredd tests

* adding comment

* adding additional requirements to the go.mod dependency file

* remove hardcoded home directory, read using os golang library

* increase timeout in example run script

* remove hardcoded home directory

* reordering commands to get rid of errors if key directory is deleted

* changing to use temporary directory

* updating dredd timeout time

* finally managed to get the script wroking using a temporary directory instead of the default

* adding notes and comments

* changing to use a temp directory instead of default directory

* remove un-needed file

* rename debugging tools folder

* adding instructions to install dredd and npm

* Update swagger-ui/startchain.sh

Send output to dev null not to console

Co-Authored-By: Kevin Davis <karzak@users.noreply.github.com>

* Update swagger-ui/startchain.sh

Send output to dev null not to console

Co-Authored-By: Kevin Davis <karzak@users.noreply.github.com>

* adding new version of test.go to setup the chain

* adding todo to update instructions for new workflow

* updating script to start and setup the chain

* updating the transaction hash test

* update the start chain script to setup the chain correctly

* add the script to stop the chain and the rest server

* updated the instructions for the new workflow so that all the tests pass the first time

* updated the instructions on how to run the tests

* update instructions for printing logs or not

* updating the startchain script to add messages when starting the rest server and preparing transactions

* adding print messages when stop chain is completed

* updating test results to just include test output and not the debug log statements

* cleaning up the messages that are printed to the user

* moving files to their own directory

* build go test file and remove previous binary

* move instructions

* updating instructions now that test file is auto built

* building, running dredd tests, propagating error code, shut down blockchain all in one script

* fix object type to array type for block latests

* cleaning up the script

* rename script as it now does all the setup, test running, shutdown, and cleanup

* update instructions for new workflow

* adding a shell script to call from the makefile

* adding a make command to build and run all the dredd tests

* update instructions to run using make

* updated code review comment

* minor update to instructions

* update remove file command so doesn't print an error if the file has already been deleted

* renaming folder and test

* adjust code comment

* removing example test results

* updating instructions to remove reference to the test results

* remove old hooks file

* remove obsolete code comment

* remove swagger file, will change references to the other one

* remove shell script, will now use the one called from make instead

* renaming as underscore messes up go build

* clean up script, fix return code issues

* cleanup output file

* fix object to array issue

* add comments to explain functionality

* use variables for kvd home and kvcli home, check for errors

* change the kvcli home directory. need to take this from command line

* take kvcli from command line parameter to golang file

* take kvcli directory from command line parameter

Co-authored-by: John Maheswaran <john@kava.io>
Co-authored-by: Kevin Davis <karzak@users.noreply.github.com>

* remove test results

* fix merge conflict

* fix more merge conflicts

* keeping track of number of passing tests, currently 19 passing, 66 failing

* fix /supply/total test

* fix /minting/annual-provisions test

* fix inflation test

* fix community pool test

* fix distribution test

* fix another validator operator test

* fix two more tests

* fix a rewards test

* fix outstanding rewards test

* fixed ~7 more tests

* fixed another test

* fixed another test

* fixed another test

* fixed bech32 encoding issue and two more tests

* fixed another address issue test

* fixed another test

* fixed two more tests

* another test fix

* fix param change test

* fix gov proposal test

* fixed another gov issue

* fixed unjail test

* fixed slashing test

* fixed another few tests

* another fix

* another fix

* another fix

* another fix

* several more fixes

* another test fixed...

* more fixes

* another fix, 61 now passing, 21 failing

* another fix

* multiple more fixes

* another fix...

* 70 tests now passing, 12 failing. Failing tests are CDPs, auction, and pricefeed tests

* R4R: Update BEP3 rest endpoints + format example requests (#402)

* update and reorder errors

* implement swap deletion block delay

* add swap deletion block delay, set up tests

* add secure random number gen

* implement AtomicSwapLongtermStorage index

* fix syntax error

* abci test updates

* implement handler test

* implement core genesis tests

* update asset supply logic

* implement functional asset supply

* pretty print atomic swaps

* requested revisions

* fix test suite post merge

* implement and integrate asset supply tests

* update import genesis, add storage duration param

* implement swap deletion ABCI test

* go mod tidy

* remove duplicated interface assertion

* add new bep3 param to contrib genesis file

* remove btc from supported assets

* revisions: LongtermStorageDuration param

* revisions: suite ctx, fix genesis, update contrib

* implement AssetSupply type, store key, keeper

* integrate supply and swaps; genesis, tests

* remove legacy comments

* requested revisions

* update alias

* rest queries

* implement BEP3 REST txs

* draft rest server readme + example json files

* tested all swap rest examples

* implement query swaps rest endpoint

* use the cdp and pricefeed genesis file

* changes to several addresses and denominations in several tests

* adding script to start without rebuilding the genesis file

* comment out file copy that was causing script to fail

* fix a pricefeed test

* adding a new test genesis file for use in the dredd tests

* fixed another pricefeed test

* fixed oracle test

* fixed pricefeed markets

* fixed oracles issue

* fixed two cdp tests

* feat: update genesis examples

* fix: use post instead of put (#405)

* finally fixed a timestamp format issue for put pricefeed test

* update contrib structure (#403)

* used for testing

* update chain name

* adding xrp to vlad in genesis

* updaing to set xrp and pricefeed and cdp params in genesis file

* changes to create cdp method

* some minor changes

* finally successfully creating the cdp

* all the pure cdp tests are now passing, so overall 79 passing, 3 failing (3 auction tests)

* fix to kill the blockchain when done and shutting down

* uncomment to run all functions

* minor changes

* fix on tx test

* adding method to update price of xrp to hopefully trigger auction

* adding btc to the vlad wallet, keep blockchain running

* create btc cdp and update price to trigger auction

* fixed an auction test - 80 tests now passing, 2 failing

* fix auction bid test, 81 now passing only 1 failing

* fixes to the script to setup chain and run all tests

* adding code review note

* setup and send all messages to blockchain

* add note to readme how to run the dredd tests

* kill the kava if it is already running

* ALL 82 TESTS NOW PASSINGga swagger-ui/testnet-4000/swagger-testnet-4000.yamlga swagger-ui/testnet-4000/swagger-testnet-4000.yaml 0 FAILING

* remove unused genesis file as we now create it on the fly from the run all tests script

* remove old file

* fixed jq issue - 81 tests now passing. one is failing for some reason - taking a look

* fixed pricefeed - all 82 tests now passing zero failing

* Update README.md

Co-Authored-By: Federico Kunze <31522760+fedekunze@users.noreply.github.com>

* remove old file

* Update rest_test/run_all_tests_from_make.sh

Co-Authored-By: Kevin Davis <karzak@users.noreply.github.com>

* fix setup test

Co-authored-by: John Maheswaran <john@kava.io>
Co-authored-by: Kevin Davis <karzak@users.noreply.github.com>
Co-authored-by: Denali Marsh <denali@kava.io>
Co-authored-by: Kevin Davis <kjydavis3@gmail.com>
Co-authored-by: Federico Kunze <31522760+fedekunze@users.noreply.github.com>
2020-04-01 13:17:02 -04:00

481 lines
12 KiB
Go

package main
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"os"
"time"
"github.com/cosmos/cosmos-sdk/client/keys"
crkeys "github.com/cosmos/cosmos-sdk/crypto/keys"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkrest "github.com/cosmos/cosmos-sdk/types/rest"
"github.com/cosmos/cosmos-sdk/x/auth"
authrest "github.com/cosmos/cosmos-sdk/x/auth/client/rest"
authclient "github.com/cosmos/cosmos-sdk/x/auth/client/utils"
authexported "github.com/cosmos/cosmos-sdk/x/auth/exported"
"github.com/cosmos/cosmos-sdk/x/bank"
"github.com/cosmos/cosmos-sdk/x/gov"
"github.com/cosmos/cosmos-sdk/x/gov/types"
"github.com/cosmos/cosmos-sdk/x/staking"
"github.com/kava-labs/kava/app"
"github.com/kava-labs/kava/x/cdp"
"github.com/kava-labs/kava/x/pricefeed"
"github.com/tendermint/go-amino"
tmtime "github.com/tendermint/tendermint/types/time"
)
func init() {
config := sdk.GetConfig()
app.SetBech32AddressPrefixes(config)
app.SetBip44CoinType(config)
config.Seal()
}
func main() {
if len(os.Args) < 2 {
fmt.Printf("Please include the kvcli home directory as a command line argument\n")
fmt.Printf("For example: ./setuptest /tmp/kvcliHome\n")
fmt.Printf("Exiting...goodbye!\n")
return
}
// setup messages send to blockchain so it is in the correct state for testing
sendProposal()
sendDeposit()
sendVote()
sendDelegation()
sendUndelegation()
sendCoins()
sendProposal()
sendDeposit()
sendVote()
sendDelegation()
sendUndelegation()
sendCoins()
// create an XRP cdp and send to blockchain
sendXrpCdp()
// create a BTC cdp and send to blockchain
sendBtcCdp()
// reduce the price of BTC to trigger an auction
sendMsgPostPrice()
}
// lower the price of xrp to trigger an auction
func sendMsgPostPrice() {
// get the address
address := getTestAddress()
// get the keyname and password
keyname, password := getKeynameAndPassword()
addr, err := sdk.AccAddressFromBech32(address) // validator address
if err != nil {
panic(err)
}
price, err := sdk.NewDecFromStr("1")
if err != nil {
panic(err)
}
// set the expiry time
expiry := tmtime.Now().Add(time.Second * 100000)
// create a cdp message to send to the blockchain
// from, assetcode, price, expiry
msg := pricefeed.NewMsgPostPrice(
addr,
"btc:usd",
price,
expiry,
)
// helper methods for transactions
cdc := app.MakeCodec() // make codec for the app
// get the keybase
keybase := getKeybase()
// cast to the generic msg type
msgToSend := []sdk.Msg{msg}
// send the message to the blockchain
sendMsgToBlockchain(cdc, address, keyname, password, msgToSend, keybase)
}
func sendBtcCdp() {
// get the address
address := getTestAddress()
// get the keyname and password
keyname, password := getKeynameAndPassword()
addr, err := sdk.AccAddressFromBech32(address) // validator address
if err != nil {
panic(err)
}
// create a cdp message to send to the blockchain
// sender, collateral, principal
msg := cdp.NewMsgCreateCDP(
addr,
sdk.NewCoins(sdk.NewInt64Coin("btc", 200000000)),
sdk.NewCoins(sdk.NewInt64Coin("usdx", 10000000)),
)
// helper methods for transactions
cdc := app.MakeCodec() // make codec for the app
// get the keybase
keybase := getKeybase()
// cast to the generic msg type
msgToSend := []sdk.Msg{msg}
// send the message to the blockchain
sendMsgToBlockchain(cdc, address, keyname, password, msgToSend, keybase)
}
func sendXrpCdp() {
// get the address
address := getTestAddress()
// get the keyname and password
keyname, password := getKeynameAndPassword()
addr, err := sdk.AccAddressFromBech32(address) // validator address
if err != nil {
panic(err)
}
// create a cdp message to send to the blockchain
// sender, collateral, principal
msg := cdp.NewMsgCreateCDP(
addr,
sdk.NewCoins(sdk.NewInt64Coin("xrp", 200000000)),
sdk.NewCoins(sdk.NewInt64Coin("usdx", 10000000)),
)
// helper methods for transactions
cdc := app.MakeCodec() // make codec for the app
// get the keybase
keybase := getKeybase()
// cast to the generic msg type
msgToSend := []sdk.Msg{msg}
// send the message to the blockchain
sendMsgToBlockchain(cdc, address, keyname, password, msgToSend, keybase)
}
func sendProposal() {
// get the address
address := getTestAddress()
// get the keyname and password
keyname, password := getKeynameAndPassword()
proposalContent := gov.ContentFromProposalType("A Test Title", "A test description on this proposal.", gov.ProposalTypeText)
addr, err := sdk.AccAddressFromBech32(address) // validator address
if err != nil {
panic(err)
}
// create a message to send to the blockchain
msg := gov.NewMsgSubmitProposal(
proposalContent,
sdk.NewCoins(sdk.NewInt64Coin("stake", 1000)),
addr,
)
// helper methods for transactions
cdc := app.MakeCodec() // make codec for the app
// get the keybase
keybase := getKeybase()
// SEND THE PROPOSAL
// cast to the generic msg type
msgToSend := []sdk.Msg{msg}
// send the PROPOSAL message to the blockchain
sendMsgToBlockchain(cdc, address, keyname, password, msgToSend, keybase)
}
func sendDeposit() {
// get the address
address := getTestAddress()
// get the keyname and password
keyname, password := getKeynameAndPassword()
addr, err := sdk.AccAddressFromBech32(address) // validator
if err != nil {
panic(err)
}
// helper methods for transactions
cdc := app.MakeCodec() // make codec for the app
// get the keybase
keybase := getKeybase()
// NOW SEND THE DEPOSIT
// create a deposit transaction to send to the proposal
amount := sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 10000000))
deposit := gov.NewMsgDeposit(addr, 2, amount) // TODO IMPORTANT '2' must match 'x-example' in swagger.yaml
depositToSend := []sdk.Msg{deposit}
sendMsgToBlockchain(cdc, address, keyname, password, depositToSend, keybase)
}
func sendVote() {
// get the address
address := getTestAddress()
// get the keyname and password
keyname, password := getKeynameAndPassword()
addr, err := sdk.AccAddressFromBech32(address) // validator
if err != nil {
panic(err)
}
// helper methods for transactions
cdc := app.MakeCodec() // make codec for the app
// get the keybase
keybase := getKeybase()
// NOW SEND THE VOTE
// create a vote on a proposal to send to the blockchain
vote := gov.NewMsgVote(addr, uint64(2), types.OptionYes) // TODO IMPORTANT '2' must match 'x-example' in swagger.yaml
// send a vote to the blockchain
voteToSend := []sdk.Msg{vote}
sendMsgToBlockchain(cdc, address, keyname, password, voteToSend, keybase)
}
// this should send coins from one address to another
func sendCoins() {
// get the address
address := getTestAddress()
// get the keyname and password
keyname, password := getKeynameAndPassword()
addrFrom, err := sdk.AccAddressFromBech32(address) // validator
if err != nil {
panic(err)
}
addrTo, err := sdk.AccAddressFromBech32("kava1ls82zzghsx0exkpr52m8vht5jqs3un0ceysshz") // TODO IMPORTANT this is the faucet address
if err != nil {
panic(err)
}
// helper methods for transactions
cdc := app.MakeCodec() // make codec for the app
// get the keybase
keybase := getKeybase()
// create coins
amount := sdk.NewCoins(sdk.NewInt64Coin(sdk.DefaultBondDenom, 2000000))
coins := bank.NewMsgSend(addrFrom, addrTo, amount) // TODO IMPORTANT '2' must match 'x-example' in swagger.yaml
coinsToSend := []sdk.Msg{coins}
// NOW SEND THE COINS
// send the coin message to the blockchain
sendMsgToBlockchain(cdc, address, keyname, password, coinsToSend, keybase)
}
func getTestAddress() (address string) {
// the test address - TODO IMPORTANT make sure this lines up with startchain.sh
address = "kava1ffv7nhd3z6sych2qpqkk03ec6hzkmufy0r2s4c"
return address
}
func getKeynameAndPassword() (keyname string, password string) {
keyname = "vlad" // TODO - IMPORTANT this must match the keys in the startchain.sh script
password = "password" // TODO - IMPORTANT this must match the keys in the startchain.sh script
return keyname, password
}
// this should send a delegation
func sendDelegation() {
// get the address
address := getTestAddress()
// get the keyname and password
keyname, password := getKeynameAndPassword()
addrFrom, err := sdk.AccAddressFromBech32(address) // validator
if err != nil {
panic(err)
}
// helper methods for transactions
cdc := app.MakeCodec() // make codec for the app
// get the keybase
keybase := getKeybase()
// get the validator address for delegation
valAddr, err := sdk.ValAddressFromBech32("kavavaloper1ffv7nhd3z6sych2qpqkk03ec6hzkmufyz4scd0") // **FAUCET**
if err != nil {
panic(err)
}
// create delegation amount
delAmount := sdk.NewInt64Coin(sdk.DefaultBondDenom, 1000000)
delegation := staking.NewMsgDelegate(addrFrom, valAddr, delAmount)
delegationToSend := []sdk.Msg{delegation}
// send the delegation to the blockchain
sendMsgToBlockchain(cdc, address, keyname, password, delegationToSend, keybase)
}
// this should send a MsgUndelegate
func sendUndelegation() {
// get the address
address := getTestAddress()
// get the keyname and password
keyname, password := getKeynameAndPassword()
addrFrom, err := sdk.AccAddressFromBech32(address) // validator
if err != nil {
panic(err)
}
// helper methods for transactions
cdc := app.MakeCodec() // make codec for the app
// get the keybase
keybase := getKeybase()
// get the validator address for delegation
valAddr, err := sdk.ValAddressFromBech32("kavavaloper1ffv7nhd3z6sych2qpqkk03ec6hzkmufyz4scd0") // **FAUCET**
if err != nil {
panic(err)
}
// create delegation amount
undelAmount := sdk.NewInt64Coin(sdk.DefaultBondDenom, 1000000)
undelegation := staking.NewMsgUndelegate(addrFrom, valAddr, undelAmount)
delegationToSend := []sdk.Msg{undelegation}
// send the delegation to the blockchain
sendMsgToBlockchain(cdc, address, keyname, password, delegationToSend, keybase)
}
func getKeybase() crkeys.Keybase {
// create a keybase
// IMPORTANT - TAKE THIS FROM COMMAND LINE PARAMETER and does NOT work with tilde i.e. ~/ does NOT work
keybase, err := keys.NewKeyBaseFromDir(os.Args[1])
if err != nil {
panic(err)
}
return keybase
}
// sendMsgToBlockchain sends a message to the blockchain via the rest api
func sendMsgToBlockchain(cdc *amino.Codec, address string, keyname string,
password string, msg []sdk.Msg, keybase crkeys.Keybase) {
// get the account number and sequence number
accountNumber, sequenceNumber := getAccountNumberAndSequenceNumber(cdc, address)
txBldr := auth.NewTxBuilderFromCLI().
WithTxEncoder(authclient.GetTxEncoder(cdc)).WithChainID("testing").
WithKeybase(keybase).WithAccountNumber(accountNumber).
WithSequence(sequenceNumber).WithGas(500000)
// build and sign the transaction
// this is the *Amino* encoded version of the transaction
// fmt.Printf("%+v", txBldr.Keybase())
txBytes, err := txBldr.BuildAndSign("vlad", "password", msg)
if err != nil {
panic(err)
}
// fmt.Printf("txBytes: %s", txBytes)
// need to convert the Amino encoded version back to an actual go struct
var tx auth.StdTx
cdc.UnmarshalBinaryLengthPrefixed(txBytes, &tx) // might be unmarshal binary bare
// now we re-marshall it again into json
jsonBytes, err := cdc.MarshalJSON(
authrest.BroadcastReq{
Tx: tx,
Mode: "block",
},
)
fmt.Printf("%s", bytes.NewBuffer(jsonBytes))
if err != nil {
panic(err)
}
// fmt.Println("post body: ", string(jsonBytes))
resp, err := http.Post("http://localhost:1317/txs", "application/json", bytes.NewBuffer(jsonBytes))
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
fmt.Printf("\n\nBody:\n\n")
fmt.Println(string(body))
}
// getAccountNumberAndSequenceNumber gets an account number and sequence number from the blockchain
func getAccountNumberAndSequenceNumber(cdc *amino.Codec, address string) (accountNumber uint64, sequenceNumber uint64) {
// we need to setup the account number and sequence in order to have a valid transaction
resp, err := http.Get("http://localhost:1317/auth/accounts/" + address)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
var bodyUnmarshalled sdkrest.ResponseWithHeight
err = cdc.UnmarshalJSON(body, &bodyUnmarshalled)
if err != nil {
panic(err)
}
var account authexported.Account
err = cdc.UnmarshalJSON(bodyUnmarshalled.Result, &account)
if err != nil {
panic(err)
}
return account.GetAccountNumber(), account.GetSequence()
}