简体   繁体   中英

Converting Go gRPC call to Node.js

There is a function that uses grpc call to get certain data from a grpc node.

func GetVotesByAddr(r *http.Request, cli iotexapi.APIServiceClient) (proto.Message, error) {
    method := &iotexapi.ReadStakingDataMethod{
        Method: iotexapi.ReadStakingDataMethod_BUCKETS_BY_VOTER,
    }
    methodData, err := proto.Marshal(method)
    if err != nil {
        return nil, err
    }
    vars := mux.Vars(r)
    readStakingdataRequest := &iotexapi.ReadStakingDataRequest{
        Request: &iotexapi.ReadStakingDataRequest_BucketsByVoter{
            BucketsByVoter: &iotexapi.ReadStakingDataRequest_VoteBucketsByVoter{
                VoterAddress: vars["addr"],
                Pagination: &iotexapi.PaginationParam{
                    Offset: uint32(0),
                    Limit:  uint32(1000),
                },
            },
        },
    }
    requestData, err := proto.Marshal(readStakingdataRequest)
    if err != nil {
        return nil, err
    }
    request := &iotexapi.ReadStateRequest{
        ProtocolID: []byte("staking"),
        MethodName: methodData,
        Arguments:  [][]byte{requestData},
    }

    response, err := cli.ReadState(context.Background(), request)
    if err != nil {
        return nil, err
    }

    bucketlist := &iotextypes.VoteBucketList{}
    if err := proto.Unmarshal(response.Data, bucketlist); err != nil {
        return nil, err
    }
    return bucketlist, nil
}

code taken from https://github.com/iotexproject/pharos/blob/master/handler/handler_votes.go

I need to convert this to js, I am using this library https://docs.iotex.io/native-development/reference-code/call-any-rpc-method which supports rpc calls using js for ioTex network.

const state = await antenna.iotx.readState({
    protocolID: "",
    methodName: "",
    arguments: "",
});

RPC call document https://docs.iotex.io/reference/node-core-api-grpc#readstate

Any help on how we can rebuild this call from GO to Node.js would be helpful.

Ok so after playing a bit I was able to solve this myself below is code for future references

const state = await antenna.iotx.readState({
  protocolID: Buffer.from("staking"),
  methodName: IReadStakingDataMethodToBuffer({
    method: IReadStakingDataMethodName.BUCKETS_BY_VOTER,
  }),
  arguments: [
    IReadStakingDataRequestToBuffer({
      bucketsByVoter: {
        voterAddress: ioAddress,
        pagination: {
          offset: 0,
          limit: 1000,
        },
      },
    }),
  ],
  height: undefined,
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM