Skip to content

Commit

Permalink
Merge pull request #29 from terra-money/feature/legacy-tx-broadcast
Browse files Browse the repository at this point in the history
Add legacy tx broadcast endpoint
  • Loading branch information
yun-yeo authored May 28, 2022
2 parents ea682c4 + b896aa5 commit 5a3cd66
Show file tree
Hide file tree
Showing 5 changed files with 130 additions and 130 deletions.
3 changes: 3 additions & 0 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ import (
wasmclient "github.com/CosmWasm/wasmd/x/wasm/client"
wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper"
"github.com/prometheus/client_golang/prometheus"
customtx "github.com/terra-money/core/v2/app/tx"

// this line is used by starport scaffolding # stargate/app/moduleImport

Expand Down Expand Up @@ -762,6 +763,8 @@ func (app *TerraApp) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APIC
rpc.RegisterRoutes(clientCtx, apiSvr.Router)
// Register legacy tx routes.
authrest.RegisterTxRoutes(clientCtx, apiSvr.Router)
// Register custom legacy tx routes.
customtx.RegisterTxRoutes(clientCtx, apiSvr.Router)
// Register new tx routes from grpc-gateway.
authtx.RegisterGRPCGatewayRoutes(clientCtx, apiSvr.GRPCGatewayRouter)
// Register new tendermint queries routes from grpc-gateway.
Expand Down
126 changes: 126 additions & 0 deletions app/tx/broadcast.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
package tx

import (
"errors"
"fmt"
"io/ioutil"
"net/http"

"github.com/cosmos/cosmos-sdk/client"
clientrest "github.com/cosmos/cosmos-sdk/client/rest"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/rest"
"github.com/cosmos/cosmos-sdk/x/auth/legacy/legacytx"
"github.com/gorilla/mux"
)

// RegisterTxRoutes registers registers terra custom transaction routes on the provided router.
func RegisterTxRoutes(clientCtx client.Context, rtr *mux.Router) {
r := clientrest.WithHTTPDeprecationHeaders(rtr)
r.HandleFunc("/txs", BroadcastTxRequest(clientCtx)).Methods("POST")
}

// BroadcastReq defines a tx broadcasting request.
type BroadcastReq struct {
Tx legacytx.StdTx `json:"tx" yaml:"tx"`
Mode string `json:"mode" yaml:"mode"`
Sequences []uint64 `json:"sequences" yaml:"sequences"`
FeeGranter string `json:"fee_granter" yaml:"fee_granter"`
}

var _ codectypes.UnpackInterfacesMessage = BroadcastReq{}

// UnpackInterfaces implements the UnpackInterfacesMessage interface.
func (m BroadcastReq) UnpackInterfaces(unpacker codectypes.AnyUnpacker) error {
return m.Tx.UnpackInterfaces(unpacker)
}

// BroadcastTxRequest implements a tx broadcasting handler that is responsible
// for broadcasting a valid and signed tx to a full node. The tx can be
// broadcasted via a sync|async|block mechanism.
func BroadcastTxRequest(clientCtx client.Context) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req BroadcastReq

body, err := ioutil.ReadAll(r.Body)
if rest.CheckBadRequestError(w, err) {
return
}

// NOTE: amino is used intentionally here, don't migrate it!
err = clientCtx.LegacyAmino.UnmarshalJSON(body, &req)
if err != nil {
err := fmt.Errorf("this transaction cannot be broadcasted via legacy REST endpoints, because it does not support"+
" Amino serialization. Please either use CLI, gRPC, gRPC-gateway, or directly query the Tendermint RPC"+
" endpoint to broadcast this transaction. The new REST endpoint (via gRPC-gateway) is POST /cosmos/tx/v1beta1/txs."+
" Please also see the REST endpoints migration guide at %s for more info", clientrest.DeprecationURL)
if rest.CheckBadRequestError(w, err) {
return
}
}

txBuilder := clientCtx.TxConfig.NewTxBuilder()
txBuilder.SetFeeAmount(req.Tx.GetFee())
txBuilder.SetGasLimit(req.Tx.GetGas())
txBuilder.SetMemo(req.Tx.GetMemo())
if err := txBuilder.SetMsgs(req.Tx.GetMsgs()...); rest.CheckBadRequestError(w, err) {
return
}

txBuilder.SetTimeoutHeight(req.Tx.GetTimeoutHeight())
if req.FeeGranter != "" {
addr, err := sdk.AccAddressFromBech32(req.FeeGranter)
if rest.CheckBadRequestError(w, err) {
return
}

txBuilder.SetFeeGranter(addr)
}

signatures, err := req.Tx.GetSignaturesV2()
if rest.CheckBadRequestError(w, err) {
return
}

// if sequence is not given, try fetch from the chain
if len(req.Sequences) == 0 {
for _, sig := range signatures {
_, seq, err := clientCtx.AccountRetriever.GetAccountNumberSequence(clientCtx, sdk.AccAddress(sig.PubKey.Address().Bytes()))
if rest.CheckBadRequestError(w, err) {
return
}
req.Sequences = append(req.Sequences, seq)
}
}

// check the sequence nubmer is equal with the signature nubmer
if len(signatures) != len(req.Sequences) {
rest.CheckBadRequestError(w, errors.New("Must provide each signers's sequence number"))
return
}

// fill sequence number to new signature
for i, seq := range req.Sequences {
signatures[i].Sequence = seq
}

if err := txBuilder.SetSignatures(signatures...); rest.CheckBadRequestError(w, err) {
return
}

// compute tx bytes
txBytes, err := clientCtx.TxConfig.TxEncoder()(txBuilder.GetTx())
if rest.CheckInternalServerError(w, err) {
return
}

clientCtx = clientCtx.WithBroadcastMode(req.Mode)
res, err := clientCtx.BroadcastTx(txBytes)
if rest.CheckInternalServerError(w, err) {
return
}

rest.PostProcessResponseBare(w, clientCtx, res)
}
}
2 changes: 1 addition & 1 deletion client/docs/statik/statik.go

Large diffs are not rendered by default.

88 changes: 0 additions & 88 deletions client/docs/swagger-ui/swagger.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -1264,94 +1264,6 @@ paths:
description: The tx was malformed
'500':
description: Server internal error
/txs/estimate_fee:
post:
deprecated: true
tags:
- Transactions
summary: Estimate fee and gas of a transaction
description: Estimate fee and gas of a transaction according to given parameters
consumes:
- application/json
produces:
- application/json
parameters:
- in: body
name: transaction
description: The sender and tx information
required: true
schema:
type: object
properties:
base_req:
type: object
properties:
from:
type: string
example: terra1wg2mlrxdmnnkkykgqg4znky86nyrtc45q336yv
description: Sender address or Keybase name to generate a transaction
memo:
type: string
example: Sent via Terra Station 🚀
chain_id:
type: string
example: Columbus-5
account_number:
type: string
example: '0'
sequence:
type: string
example: '1'
gas:
type: string
example: '200000'
gas_adjustment:
type: string
example: '1.2'
fees:
type: array
items:
type: object
properties:
denom:
type: string
example: uluna
amount:
type: string
example: '50'
simulate:
type: boolean
example: false
description: >-
Estimate gas for a transaction (cannot be used in
conjunction with generate_only)
msgs:
type: array
items:
type: string
responses:
'200':
description: The fee was successfully estimated
schema:
type: object
properties:
gas:
type: string
amount:
type: array
items:
type: object
properties:
denom:
type: string
example: uluna
amount:
type: string
example: '50'
'400':
description: The tx was malformed
'500':
description: Server internal error
/bank/balances/{address}:
get:
deprecated: true
Expand Down
41 changes: 0 additions & 41 deletions client/docs/swagger_legacy.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -403,47 +403,6 @@ paths:
description: The tx was malformed
500:
description: Server internal error
/txs/estimate_fee:
post:
deprecated: true
tags:
- Transactions
summary: Estimate fee and gas of a transaction
description: Estimate fee and gas of a transaction according to given parameters
consumes:
- application/json
produces:
- application/json
parameters:
- in: body
name: transaction
description: The sender and tx information
required: true
schema:
type: object
properties:
base_req:
$ref: "#/definitions/BaseReq"
msgs:
type: array
items:
$ref: "#/definitions/Msg"
responses:
200:
description: The fee was successfully estimated
schema:
type: object
properties:
gas:
type: string
amount:
type: array
items:
$ref: "#/definitions/Coin"
400:
description: The tx was malformed
500:
description: Server internal error
/bank/balances/{address}:
get:
deprecated: true
Expand Down

0 comments on commit 5a3cd66

Please sign in to comment.