How to decode stellar XDR

771 views Asked by At

I am working on stellar blockchain and need to decode stellar XDR which is in GO language. I know how to decode using JavaScript but couldn't find a way to do it in GO.

 //JS code

 const {Transaction} = require('stellar-base')

 const parsedTx = new Transaction('tx_envelope_encoded_as_XDR')
 console.log(parsedTx)

This works fine. what i have tried and not working...

//GO code

import (

   "bytes"
   "encoding/json"
   "fmt"
   "net/http"
   "github.com/stellar/go/xdr"
   "github.com/gorilla/mux"

 )

func DecodeXDR(w http.ResponseWriter, r *http.Request) {

    var OBJ model.TransactionCollectionBody
    err := json.NewDecoder(r.Body).Decode(&OBJ)
    if err != nil {
      w.WriteHeader(http.StatusBadRequest)
      json.NewEncoder(w).Encode("Error while Decoding the body")
      fmt.Println(err)

      return
    }

    // fmt.Println(OBJ)

    // lol:=xdr.Value(OBJ.XDR)

    var txe xdr.Transaction
    err = xdr.SafeUnmarshalBase64(XDRB64, &txe)
    if err != nil {
      fmt.Println(err)
    }

    fmt.Println(txe)

}

//Output
{{PublicKeyTypePublicKeyTypeEd25519 0xc042055d20} 200 2800572080062465 <nil> {MemoTypeMemoNone <nil> <nil> <nil> <nil>} [{<nil> {OperationTypeManageData <nil> <nil> <nil> <nil> <nil> <nil> <nil> <nil> <nil> 0xc042174040 <nil>}} {<nil> {OperationTypeManageData <nil> <nil> <nil> <nil> <nil> <nil> <nil> <nil> <nil> 0xc042174080 <nil>}}] {0}}

//Expected Output

{ type: 'payment', destination: 'GCKUXI3JRJANYOF3AM35Z22FGUGYYUIEBPE5TTZ7P3G6XAEFGYZC2POM', asset: Asset { code: 'Blog', issuer: 'GDOPTRADBVWJR6BMB6H5ACQTAVUS6XMT53CDNAJZLOSTIUICIW57ISMF' }, amount: '10' }

{ type: 'payment', destination: 'GCKUXI3JRJANYOF3AM35Z22FGUGYYUIEBPE5TTZ7P3G6XAEFGYZC2POM', asset: Asset { code: 'Blog', issuer: 'GDOPTRADBVWJR6BMB6H5ACQTAVUS6XMT53CDNAJZLOSTIUICIW57ISMF' }, amount: '10' }

{ type: 'payment', destination: 'GCKUXI3JRJANYOF3AM35Z22FGUGYYUIEBPE5TTZ7P3G6XAEFGYZC2POM', asset: Asset { code: 'Blog', issuer: 'GDOPTRADBVWJR6BMB6H5ACQTAVUS6XMT53CDNAJZLOSTIUICIW57ISMF' }, amount: '10' }

Can anyone help me to solve this?

1

There are 1 answers

0
configbug On

I come with a perhaps late solution. But to get what you need you can use the package:

"github.com/stellar/go-xdr/xdr3"

And using the following function.

// DecodeFrom decodes this value using the Decoder.
func (s *Value) DecodeFrom(d *xdr.Decoder) (int, error) {
    var err error
    var n, nTmp int
    (*s), nTmp, err = d.DecodeOpaque(0)
    n += nTmp
    if err != nil {
        return n, fmt.Errorf("decoding Value: %s", err)
    }
    return n, nil
}