diff --git a/pkg/chains/stellar/proto_helpers.go b/pkg/chains/stellar/proto_helpers.go index adfde03bcb..f58c59d3dd 100644 --- a/pkg/chains/stellar/proto_helpers.go +++ b/pkg/chains/stellar/proto_helpers.go @@ -220,3 +220,105 @@ func ConvertReadContractRequestFromProto(p *ReadContractRequest) (stellar.ReadCo LedgerSequence: p.GetLedgerSequence(), }, nil } + +// ConvertSubmitTransactionRequestToProto converts a domain SubmitTransactionRequest to proto. +func ConvertSubmitTransactionRequestToProto(req stellar.SubmitTransactionRequest) (*SubmitTransactionRequest, error) { + if req.ContractID == "" { + return nil, errors.New("contract_id is required") + } + if req.Function == "" { + return nil, errors.New("function is required") + } + args := make([]*scval.ScVal, len(req.Args)) + for i, sv := range req.Args { + psv, err := stellarcap.ScValToProto(sv) + if err != nil { + return nil, fmt.Errorf("args[%d]: %w", i, err) + } + args[i] = psv + } + return &SubmitTransactionRequest{ + IdempotencyKey: req.IdempotencyKey, + FromAddress: req.FromAddress, + ContractId: req.ContractID, + Function: req.Function, + Args: args, + LedgerBoundsOffset: req.LedgerBoundsOffset, + }, nil +} + +// ConvertSubmitTransactionRequestFromProto converts proto SubmitTransactionRequest to domain. +func ConvertSubmitTransactionRequestFromProto(p *SubmitTransactionRequest) (stellar.SubmitTransactionRequest, error) { + if p == nil { + return stellar.SubmitTransactionRequest{}, errors.New("submit transaction request is nil") + } + if p.GetContractId() == "" { + return stellar.SubmitTransactionRequest{}, errors.New("contract_id is required") + } + if p.GetFunction() == "" { + return stellar.SubmitTransactionRequest{}, errors.New("function is required") + } + pArgs := p.GetArgs() + var args []stellar.ScVal + if len(pArgs) > 0 { + args = make([]stellar.ScVal, len(pArgs)) + for i, psv := range pArgs { + sv, err := stellarcap.ProtoToScVal(psv) + if err != nil { + return stellar.SubmitTransactionRequest{}, fmt.Errorf("args[%d]: %w", i, err) + } + args[i] = sv + } + } + return stellar.SubmitTransactionRequest{ + IdempotencyKey: p.GetIdempotencyKey(), + FromAddress: p.GetFromAddress(), + ContractID: p.GetContractId(), + Function: p.GetFunction(), + Args: args, + LedgerBoundsOffset: p.GetLedgerBoundsOffset(), + }, nil +} + +// ConvertSubmitTransactionResponseToProto converts a domain SubmitTransactionResponse to proto. +func ConvertSubmitTransactionResponseToProto(reply *stellar.SubmitTransactionResponse) (*SubmitTransactionResponse, error) { + if reply == nil { + return nil, errors.New("submit transaction reply is nil") + } + var resultXDR, resultMetaXDR []byte + if reply.ResultXDR != "" { + var err error + resultXDR, err = base64.StdEncoding.DecodeString(reply.ResultXDR) + if err != nil { + return nil, fmt.Errorf("invalid result xdr %q: %w", reply.ResultXDR, err) + } + } + if reply.ResultMetaXDR != "" { + var err error + resultMetaXDR, err = base64.StdEncoding.DecodeString(reply.ResultMetaXDR) + if err != nil { + return nil, fmt.Errorf("invalid result meta xdr %q: %w", reply.ResultMetaXDR, err) + } + } + return &SubmitTransactionResponse{ + TxStatus: TxStatus(reply.TxStatus), + TxHash: reply.TxHash, + TxIdempotencyKey: reply.TxIdempotencyKey, + ResultXdr: resultXDR, + ResultMetaXdr: resultMetaXDR, + }, nil +} + +// ConvertSubmitTransactionResponseFromProto converts proto SubmitTransactionResponse to domain. +func ConvertSubmitTransactionResponseFromProto(p *SubmitTransactionResponse) (*stellar.SubmitTransactionResponse, error) { + if p == nil { + return nil, errors.New("submit transaction reply is nil") + } + return &stellar.SubmitTransactionResponse{ + TxStatus: stellar.TransactionStatus(p.GetTxStatus()), + TxHash: p.GetTxHash(), + TxIdempotencyKey: p.GetTxIdempotencyKey(), + ResultXDR: base64.StdEncoding.EncodeToString(p.GetResultXdr()), + ResultMetaXDR: base64.StdEncoding.EncodeToString(p.GetResultMetaXdr()), + }, nil +} diff --git a/pkg/chains/stellar/proto_helpers_test.go b/pkg/chains/stellar/proto_helpers_test.go index 206b8e4597..2e52fc36af 100644 --- a/pkg/chains/stellar/proto_helpers_test.go +++ b/pkg/chains/stellar/proto_helpers_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/require" conv "github.com/smartcontractkit/chainlink-common/pkg/chains/stellar" + "github.com/smartcontractkit/chainlink-common/pkg/capabilities/v2/chain-capabilities/stellar/scval" stellartypes "github.com/smartcontractkit/chainlink-common/pkg/types/chains/stellar" ) @@ -308,6 +309,155 @@ func TestConvertGetLedgerEntriesResponseFromProto_NilEntry(t *testing.T) { // ---- ConvertGetLatestLedgerResponseToProto error cases ---------------------- +func TestConvertSubmitTransactionRequest_RoundTrip(t *testing.T) { + boolVal := true + u64 := uint64(42) + sym := "amount" + domain := stellartypes.SubmitTransactionRequest{ + IdempotencyKey: "idem-123", + FromAddress: "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF", + ContractID: "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABSC4", + Function: "transfer", + Args: []stellartypes.ScVal{ + {Type: stellartypes.ScValTypeBool, Bool: &boolVal}, + {Type: stellartypes.ScValTypeU64, U64: &u64}, + {Type: stellartypes.ScValTypeSymbol, Symbol: &sym}, + }, + LedgerBoundsOffset: 10, + } + + proto, err := conv.ConvertSubmitTransactionRequestToProto(domain) + require.NoError(t, err) + require.Equal(t, "idem-123", proto.GetIdempotencyKey()) + require.Equal(t, "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABSC4", proto.GetContractId()) + require.Equal(t, "transfer", proto.GetFunction()) + require.Len(t, proto.GetArgs(), 3) + require.Equal(t, uint32(10), proto.GetLedgerBoundsOffset()) + + got, err := conv.ConvertSubmitTransactionRequestFromProto(proto) + require.NoError(t, err) + require.Equal(t, domain, got) +} + +func TestConvertSubmitTransactionRequest_NoArgs(t *testing.T) { + domain := stellartypes.SubmitTransactionRequest{ + ContractID: "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABSC4", + Function: "ping", + } + + proto, err := conv.ConvertSubmitTransactionRequestToProto(domain) + require.NoError(t, err) + require.Empty(t, proto.GetArgs()) + + got, err := conv.ConvertSubmitTransactionRequestFromProto(proto) + require.NoError(t, err) + require.Equal(t, domain, got) +} + +func TestConvertSubmitTransactionRequestToProto_MissingContractID(t *testing.T) { + _, err := conv.ConvertSubmitTransactionRequestToProto(stellartypes.SubmitTransactionRequest{Function: "fn"}) + require.EqualError(t, err, "contract_id is required") +} + +func TestConvertSubmitTransactionRequestToProto_MissingFunction(t *testing.T) { + _, err := conv.ConvertSubmitTransactionRequestToProto(stellartypes.SubmitTransactionRequest{ContractID: "C_X"}) + require.EqualError(t, err, "function is required") +} + +func TestConvertSubmitTransactionRequestToProto_BadArg(t *testing.T) { + _, err := conv.ConvertSubmitTransactionRequestToProto(stellartypes.SubmitTransactionRequest{ + ContractID: "C_X", + Function: "fn", + Args: []stellartypes.ScVal{{Type: stellartypes.ScValTypeBool}}, // Bool is nil + }) + require.Error(t, err) + require.Contains(t, err.Error(), "args[0]") +} + +func TestConvertSubmitTransactionRequestFromProto_Nil(t *testing.T) { + _, err := conv.ConvertSubmitTransactionRequestFromProto(nil) + require.EqualError(t, err, "submit transaction request is nil") +} + +func TestConvertSubmitTransactionRequestFromProto_MissingContractID(t *testing.T) { + _, err := conv.ConvertSubmitTransactionRequestFromProto(&conv.SubmitTransactionRequest{Function: "fn"}) + require.EqualError(t, err, "contract_id is required") +} + +func TestConvertSubmitTransactionRequestFromProto_MissingFunction(t *testing.T) { + _, err := conv.ConvertSubmitTransactionRequestFromProto(&conv.SubmitTransactionRequest{ContractId: "C_X"}) + require.EqualError(t, err, "function is required") +} + +func TestConvertSubmitTransactionResponse_RoundTrip(t *testing.T) { + domain := &stellartypes.SubmitTransactionResponse{ + TxStatus: stellartypes.TxSuccess, + TxHash: "abc123hash", + TxIdempotencyKey: "idem-456", + ResultXDR: base64.StdEncoding.EncodeToString([]byte("result")), + ResultMetaXDR: base64.StdEncoding.EncodeToString([]byte("meta")), + } + + proto, err := conv.ConvertSubmitTransactionResponseToProto(domain) + require.NoError(t, err) + require.Equal(t, conv.TxStatus_TX_STATUS_SUCCESS, proto.GetTxStatus()) + + got, err := conv.ConvertSubmitTransactionResponseFromProto(proto) + require.NoError(t, err) + require.Equal(t, domain, got) +} + +func TestConvertSubmitTransactionResponse_RoundTrip_EmptyResultFields(t *testing.T) { + domain := &stellartypes.SubmitTransactionResponse{ + TxStatus: stellartypes.TxFatal, + TxHash: "", + TxIdempotencyKey: "idem-789", + } + + proto, err := conv.ConvertSubmitTransactionResponseToProto(domain) + require.NoError(t, err) + + got, err := conv.ConvertSubmitTransactionResponseFromProto(proto) + require.NoError(t, err) + require.Equal(t, domain, got) +} + +func TestConvertSubmitTransactionResponseToProto_Nil(t *testing.T) { + _, err := conv.ConvertSubmitTransactionResponseToProto(nil) + require.EqualError(t, err, "submit transaction reply is nil") +} + +func TestConvertSubmitTransactionResponseFromProto_Nil(t *testing.T) { + _, err := conv.ConvertSubmitTransactionResponseFromProto(nil) + require.EqualError(t, err, "submit transaction reply is nil") +} + +func TestConvertSubmitTransactionResponseToProto_InvalidResultXDR(t *testing.T) { + _, err := conv.ConvertSubmitTransactionResponseToProto(&stellartypes.SubmitTransactionResponse{ + ResultXDR: "!!!invalid!!!", + }) + require.Error(t, err) + require.Contains(t, err.Error(), "invalid result xdr") +} + +func TestConvertSubmitTransactionResponseToProto_InvalidResultMetaXDR(t *testing.T) { + _, err := conv.ConvertSubmitTransactionResponseToProto(&stellartypes.SubmitTransactionResponse{ + ResultMetaXDR: "!!!invalid!!!", + }) + require.Error(t, err) + require.Contains(t, err.Error(), "invalid result meta xdr") +} + +func TestConvertSubmitTransactionRequestFromProto_BadArg(t *testing.T) { + _, err := conv.ConvertSubmitTransactionRequestFromProto(&conv.SubmitTransactionRequest{ + ContractId: "C_X", + Function: "fn", + Args: []*scval.ScVal{{}}, // missing oneof value + }) + require.Error(t, err) + require.Contains(t, err.Error(), "args[0]") +} + func TestConvertGetLatestLedgerResponseToProto_InvalidFields(t *testing.T) { tests := []struct { name string diff --git a/pkg/chains/stellar/stellar.pb.go b/pkg/chains/stellar/stellar.pb.go index 81f3165fe1..1c69e27996 100644 --- a/pkg/chains/stellar/stellar.pb.go +++ b/pkg/chains/stellar/stellar.pb.go @@ -23,6 +23,55 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) +type TxStatus int32 + +const ( + TxStatus_TX_STATUS_FATAL TxStatus = 0 // Submission failed before on-chain inclusion + TxStatus_TX_STATUS_FAILED TxStatus = 1 // Included on-chain but execution failed + TxStatus_TX_STATUS_SUCCESS TxStatus = 2 // Included on-chain and succeeded +) + +// Enum value maps for TxStatus. +var ( + TxStatus_name = map[int32]string{ + 0: "TX_STATUS_FATAL", + 1: "TX_STATUS_FAILED", + 2: "TX_STATUS_SUCCESS", + } + TxStatus_value = map[string]int32{ + "TX_STATUS_FATAL": 0, + "TX_STATUS_FAILED": 1, + "TX_STATUS_SUCCESS": 2, + } +) + +func (x TxStatus) Enum() *TxStatus { + p := new(TxStatus) + *p = x + return p +} + +func (x TxStatus) String() string { + return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) +} + +func (TxStatus) Descriptor() protoreflect.EnumDescriptor { + return file_stellar_proto_enumTypes[0].Descriptor() +} + +func (TxStatus) Type() protoreflect.EnumType { + return &file_stellar_proto_enumTypes[0] +} + +func (x TxStatus) Number() protoreflect.EnumNumber { + return protoreflect.EnumNumber(x) +} + +// Deprecated: Use TxStatus.Descriptor instead. +func (TxStatus) EnumDescriptor() ([]byte, []int) { + return file_stellar_proto_rawDescGZIP(), []int{0} +} + // ReadContractRequest invokes a read-only (simulation) Soroban contract function. type ReadContractRequest struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -338,6 +387,169 @@ func (x *GetLedgerEntriesResponse) GetLatestLedger() uint32 { return 0 } +// SubmitTransactionRequest invokes a Soroban contract via the TXM pipeline. +// The TXM handles simulation, sequence management, fee bumping, signing, and confirmation. +type SubmitTransactionRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + IdempotencyKey string `protobuf:"bytes,1,opt,name=idempotency_key,json=idempotencyKey,proto3" json:"idempotency_key,omitempty"` // Optional idempotency / deduplication key + FromAddress string `protobuf:"bytes,2,opt,name=from_address,json=fromAddress,proto3" json:"from_address,omitempty"` // Source/signer account (G… StrKey); empty = TXM default + ContractId string `protobuf:"bytes,3,opt,name=contract_id,json=contractId,proto3" json:"contract_id,omitempty"` // Soroban contract address (C… StrKey) + Function string `protobuf:"bytes,4,opt,name=function,proto3" json:"function,omitempty"` // Soroban function name + Args []*scval.ScVal `protobuf:"bytes,5,rep,name=args,proto3" json:"args,omitempty"` // Typed Soroban arguments + LedgerBoundsOffset uint32 `protobuf:"varint,6,opt,name=ledger_bounds_offset,json=ledgerBoundsOffset,proto3" json:"ledger_bounds_offset,omitempty"` // Per-tx ledger-bounds override; 0 = use TXM default + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SubmitTransactionRequest) Reset() { + *x = SubmitTransactionRequest{} + mi := &file_stellar_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SubmitTransactionRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SubmitTransactionRequest) ProtoMessage() {} + +func (x *SubmitTransactionRequest) ProtoReflect() protoreflect.Message { + mi := &file_stellar_proto_msgTypes[5] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SubmitTransactionRequest.ProtoReflect.Descriptor instead. +func (*SubmitTransactionRequest) Descriptor() ([]byte, []int) { + return file_stellar_proto_rawDescGZIP(), []int{5} +} + +func (x *SubmitTransactionRequest) GetIdempotencyKey() string { + if x != nil { + return x.IdempotencyKey + } + return "" +} + +func (x *SubmitTransactionRequest) GetFromAddress() string { + if x != nil { + return x.FromAddress + } + return "" +} + +func (x *SubmitTransactionRequest) GetContractId() string { + if x != nil { + return x.ContractId + } + return "" +} + +func (x *SubmitTransactionRequest) GetFunction() string { + if x != nil { + return x.Function + } + return "" +} + +func (x *SubmitTransactionRequest) GetArgs() []*scval.ScVal { + if x != nil { + return x.Args + } + return nil +} + +func (x *SubmitTransactionRequest) GetLedgerBoundsOffset() uint32 { + if x != nil { + return x.LedgerBoundsOffset + } + return 0 +} + +// SubmitTransactionResponse carries the outcome of a transaction submission. +type SubmitTransactionResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + TxStatus TxStatus `protobuf:"varint,1,opt,name=tx_status,json=txStatus,proto3,enum=loop.stellar.TxStatus" json:"tx_status,omitempty"` + TxHash string `protobuf:"bytes,2,opt,name=tx_hash,json=txHash,proto3" json:"tx_hash,omitempty"` + TxIdempotencyKey string `protobuf:"bytes,3,opt,name=tx_idempotency_key,json=txIdempotencyKey,proto3" json:"tx_idempotency_key,omitempty"` + ResultXdr []byte `protobuf:"bytes,4,opt,name=result_xdr,json=resultXdr,proto3" json:"result_xdr,omitempty"` // TransactionResult binary XDR; empty if unavailable + ResultMetaXdr []byte `protobuf:"bytes,5,opt,name=result_meta_xdr,json=resultMetaXdr,proto3" json:"result_meta_xdr,omitempty"` // TransactionMeta binary XDR; empty if unavailable + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SubmitTransactionResponse) Reset() { + *x = SubmitTransactionResponse{} + mi := &file_stellar_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SubmitTransactionResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SubmitTransactionResponse) ProtoMessage() {} + +func (x *SubmitTransactionResponse) ProtoReflect() protoreflect.Message { + mi := &file_stellar_proto_msgTypes[6] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SubmitTransactionResponse.ProtoReflect.Descriptor instead. +func (*SubmitTransactionResponse) Descriptor() ([]byte, []int) { + return file_stellar_proto_rawDescGZIP(), []int{6} +} + +func (x *SubmitTransactionResponse) GetTxStatus() TxStatus { + if x != nil { + return x.TxStatus + } + return TxStatus_TX_STATUS_FATAL +} + +func (x *SubmitTransactionResponse) GetTxHash() string { + if x != nil { + return x.TxHash + } + return "" +} + +func (x *SubmitTransactionResponse) GetTxIdempotencyKey() string { + if x != nil { + return x.TxIdempotencyKey + } + return "" +} + +func (x *SubmitTransactionResponse) GetResultXdr() []byte { + if x != nil { + return x.ResultXdr + } + return nil +} + +func (x *SubmitTransactionResponse) GetResultMetaXdr() []byte { + if x != nil { + return x.ResultMetaXdr + } + return nil +} + // GetLatestLedgerResponse holds current ledger state. type GetLatestLedgerResponse struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -353,7 +565,7 @@ type GetLatestLedgerResponse struct { func (x *GetLatestLedgerResponse) Reset() { *x = GetLatestLedgerResponse{} - mi := &file_stellar_proto_msgTypes[5] + mi := &file_stellar_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -365,7 +577,7 @@ func (x *GetLatestLedgerResponse) String() string { func (*GetLatestLedgerResponse) ProtoMessage() {} func (x *GetLatestLedgerResponse) ProtoReflect() protoreflect.Message { - mi := &file_stellar_proto_msgTypes[5] + mi := &file_stellar_proto_msgTypes[7] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -378,7 +590,7 @@ func (x *GetLatestLedgerResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetLatestLedgerResponse.ProtoReflect.Descriptor instead. func (*GetLatestLedgerResponse) Descriptor() ([]byte, []int) { - return file_stellar_proto_rawDescGZIP(), []int{5} + return file_stellar_proto_rawDescGZIP(), []int{7} } func (x *GetLatestLedgerResponse) GetHash() []byte { @@ -449,18 +661,38 @@ const file_stellar_proto_rawDesc = "" + "\rextension_xdr\x18\x06 \x01(\fR\fextensionXdr\"z\n" + "\x18GetLedgerEntriesResponse\x129\n" + "\aentries\x18\x01 \x03(\v2\x1f.loop.stellar.LedgerEntryResultR\aentries\x12#\n" + - "\rlatest_ledger\x18\x02 \x01(\rR\flatestLedger\"\xfc\x01\n" + + "\rlatest_ledger\x18\x02 \x01(\rR\flatestLedger\"\x99\x02\n" + + "\x18SubmitTransactionRequest\x12'\n" + + "\x0fidempotency_key\x18\x01 \x01(\tR\x0eidempotencyKey\x12!\n" + + "\ffrom_address\x18\x02 \x01(\tR\vfromAddress\x12\x1f\n" + + "\vcontract_id\x18\x03 \x01(\tR\n" + + "contractId\x12\x1a\n" + + "\bfunction\x18\x04 \x01(\tR\bfunction\x12B\n" + + "\x04args\x18\x05 \x03(\v2..capabilities.blockchain.stellar.v1alpha.ScValR\x04args\x120\n" + + "\x14ledger_bounds_offset\x18\x06 \x01(\rR\x12ledgerBoundsOffset\"\xde\x01\n" + + "\x19SubmitTransactionResponse\x123\n" + + "\ttx_status\x18\x01 \x01(\x0e2\x16.loop.stellar.TxStatusR\btxStatus\x12\x17\n" + + "\atx_hash\x18\x02 \x01(\tR\x06txHash\x12,\n" + + "\x12tx_idempotency_key\x18\x03 \x01(\tR\x10txIdempotencyKey\x12\x1d\n" + + "\n" + + "result_xdr\x18\x04 \x01(\fR\tresultXdr\x12&\n" + + "\x0fresult_meta_xdr\x18\x05 \x01(\fR\rresultMetaXdr\"\xfc\x01\n" + "\x17GetLatestLedgerResponse\x12\x12\n" + "\x04hash\x18\x01 \x01(\fR\x04hash\x12)\n" + "\x10protocol_version\x18\x02 \x01(\rR\x0fprotocolVersion\x12\x1a\n" + "\bsequence\x18\x03 \x01(\rR\bsequence\x12*\n" + "\x11ledger_close_time\x18\x04 \x01(\x03R\x0fledgerCloseTime\x12*\n" + "\x11ledger_header_xdr\x18\x05 \x01(\fR\x0fledgerHeaderXdr\x12.\n" + - "\x13ledger_metadata_xdr\x18\x06 \x01(\fR\x11ledgerMetadataXdr2\x95\x02\n" + + "\x13ledger_metadata_xdr\x18\x06 \x01(\fR\x11ledgerMetadataXdr*L\n" + + "\bTxStatus\x12\x13\n" + + "\x0fTX_STATUS_FATAL\x10\x00\x12\x14\n" + + "\x10TX_STATUS_FAILED\x10\x01\x12\x15\n" + + "\x11TX_STATUS_SUCCESS\x10\x022\xfb\x02\n" + "\aStellar\x12a\n" + "\x10GetLedgerEntries\x12%.loop.stellar.GetLedgerEntriesRequest\x1a&.loop.stellar.GetLedgerEntriesResponse\x12P\n" + "\x0fGetLatestLedger\x12\x16.google.protobuf.Empty\x1a%.loop.stellar.GetLatestLedgerResponse\x12U\n" + - "\fReadContract\x12!.loop.stellar.ReadContractRequest\x1a\".loop.stellar.ReadContractResponseBAZ?github.com/smartcontractkit/chainlink-common/pkg/chains/stellarb\x06proto3" + "\fReadContract\x12!.loop.stellar.ReadContractRequest\x1a\".loop.stellar.ReadContractResponse\x12d\n" + + "\x11SubmitTransaction\x12&.loop.stellar.SubmitTransactionRequest\x1a'.loop.stellar.SubmitTransactionResponseBAZ?github.com/smartcontractkit/chainlink-common/pkg/chains/stellarb\x06proto3" var ( file_stellar_proto_rawDescOnce sync.Once @@ -474,31 +706,39 @@ func file_stellar_proto_rawDescGZIP() []byte { return file_stellar_proto_rawDescData } -var file_stellar_proto_msgTypes = make([]protoimpl.MessageInfo, 6) +var file_stellar_proto_enumTypes = make([]protoimpl.EnumInfo, 1) +var file_stellar_proto_msgTypes = make([]protoimpl.MessageInfo, 8) var file_stellar_proto_goTypes = []any{ - (*ReadContractRequest)(nil), // 0: loop.stellar.ReadContractRequest - (*ReadContractResponse)(nil), // 1: loop.stellar.ReadContractResponse - (*GetLedgerEntriesRequest)(nil), // 2: loop.stellar.GetLedgerEntriesRequest - (*LedgerEntryResult)(nil), // 3: loop.stellar.LedgerEntryResult - (*GetLedgerEntriesResponse)(nil), // 4: loop.stellar.GetLedgerEntriesResponse - (*GetLatestLedgerResponse)(nil), // 5: loop.stellar.GetLatestLedgerResponse - (*scval.ScVal)(nil), // 6: capabilities.blockchain.stellar.v1alpha.ScVal - (*emptypb.Empty)(nil), // 7: google.protobuf.Empty + (TxStatus)(0), // 0: loop.stellar.TxStatus + (*ReadContractRequest)(nil), // 1: loop.stellar.ReadContractRequest + (*ReadContractResponse)(nil), // 2: loop.stellar.ReadContractResponse + (*GetLedgerEntriesRequest)(nil), // 3: loop.stellar.GetLedgerEntriesRequest + (*LedgerEntryResult)(nil), // 4: loop.stellar.LedgerEntryResult + (*GetLedgerEntriesResponse)(nil), // 5: loop.stellar.GetLedgerEntriesResponse + (*SubmitTransactionRequest)(nil), // 6: loop.stellar.SubmitTransactionRequest + (*SubmitTransactionResponse)(nil), // 7: loop.stellar.SubmitTransactionResponse + (*GetLatestLedgerResponse)(nil), // 8: loop.stellar.GetLatestLedgerResponse + (*scval.ScVal)(nil), // 9: capabilities.blockchain.stellar.v1alpha.ScVal + (*emptypb.Empty)(nil), // 10: google.protobuf.Empty } var file_stellar_proto_depIdxs = []int32{ - 6, // 0: loop.stellar.ReadContractRequest.args:type_name -> capabilities.blockchain.stellar.v1alpha.ScVal - 3, // 1: loop.stellar.GetLedgerEntriesResponse.entries:type_name -> loop.stellar.LedgerEntryResult - 2, // 2: loop.stellar.Stellar.GetLedgerEntries:input_type -> loop.stellar.GetLedgerEntriesRequest - 7, // 3: loop.stellar.Stellar.GetLatestLedger:input_type -> google.protobuf.Empty - 0, // 4: loop.stellar.Stellar.ReadContract:input_type -> loop.stellar.ReadContractRequest - 4, // 5: loop.stellar.Stellar.GetLedgerEntries:output_type -> loop.stellar.GetLedgerEntriesResponse - 5, // 6: loop.stellar.Stellar.GetLatestLedger:output_type -> loop.stellar.GetLatestLedgerResponse - 1, // 7: loop.stellar.Stellar.ReadContract:output_type -> loop.stellar.ReadContractResponse - 5, // [5:8] is the sub-list for method output_type - 2, // [2:5] is the sub-list for method input_type - 2, // [2:2] is the sub-list for extension type_name - 2, // [2:2] is the sub-list for extension extendee - 0, // [0:2] is the sub-list for field type_name + 9, // 0: loop.stellar.ReadContractRequest.args:type_name -> capabilities.blockchain.stellar.v1alpha.ScVal + 4, // 1: loop.stellar.GetLedgerEntriesResponse.entries:type_name -> loop.stellar.LedgerEntryResult + 9, // 2: loop.stellar.SubmitTransactionRequest.args:type_name -> capabilities.blockchain.stellar.v1alpha.ScVal + 0, // 3: loop.stellar.SubmitTransactionResponse.tx_status:type_name -> loop.stellar.TxStatus + 3, // 4: loop.stellar.Stellar.GetLedgerEntries:input_type -> loop.stellar.GetLedgerEntriesRequest + 10, // 5: loop.stellar.Stellar.GetLatestLedger:input_type -> google.protobuf.Empty + 1, // 6: loop.stellar.Stellar.ReadContract:input_type -> loop.stellar.ReadContractRequest + 6, // 7: loop.stellar.Stellar.SubmitTransaction:input_type -> loop.stellar.SubmitTransactionRequest + 5, // 8: loop.stellar.Stellar.GetLedgerEntries:output_type -> loop.stellar.GetLedgerEntriesResponse + 8, // 9: loop.stellar.Stellar.GetLatestLedger:output_type -> loop.stellar.GetLatestLedgerResponse + 2, // 10: loop.stellar.Stellar.ReadContract:output_type -> loop.stellar.ReadContractResponse + 7, // 11: loop.stellar.Stellar.SubmitTransaction:output_type -> loop.stellar.SubmitTransactionResponse + 8, // [8:12] is the sub-list for method output_type + 4, // [4:8] is the sub-list for method input_type + 4, // [4:4] is the sub-list for extension type_name + 4, // [4:4] is the sub-list for extension extendee + 0, // [0:4] is the sub-list for field type_name } func init() { file_stellar_proto_init() } @@ -511,13 +751,14 @@ func file_stellar_proto_init() { File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_stellar_proto_rawDesc), len(file_stellar_proto_rawDesc)), - NumEnums: 0, - NumMessages: 6, + NumEnums: 1, + NumMessages: 8, NumExtensions: 0, NumServices: 1, }, GoTypes: file_stellar_proto_goTypes, DependencyIndexes: file_stellar_proto_depIdxs, + EnumInfos: file_stellar_proto_enumTypes, MessageInfos: file_stellar_proto_msgTypes, }.Build() File_stellar_proto = out.File diff --git a/pkg/chains/stellar/stellar.proto b/pkg/chains/stellar/stellar.proto index 8142f1ec5d..b346494fce 100644 --- a/pkg/chains/stellar/stellar.proto +++ b/pkg/chains/stellar/stellar.proto @@ -10,6 +10,7 @@ service Stellar { rpc GetLedgerEntries(GetLedgerEntriesRequest) returns (GetLedgerEntriesResponse); rpc GetLatestLedger(google.protobuf.Empty) returns (GetLatestLedgerResponse); rpc ReadContract(ReadContractRequest) returns (ReadContractResponse); + rpc SubmitTransaction(SubmitTransactionRequest) returns (SubmitTransactionResponse); } // ReadContractRequest invokes a read-only (simulation) Soroban contract function. @@ -50,6 +51,32 @@ message GetLedgerEntriesResponse { uint32 latest_ledger = 2; } +// SubmitTransactionRequest invokes a Soroban contract via the TXM pipeline. +// The TXM handles simulation, sequence management, fee bumping, signing, and confirmation. +message SubmitTransactionRequest { + string idempotency_key = 1; // Optional idempotency / deduplication key + string from_address = 2; // Source/signer account (G… StrKey); empty = TXM default + string contract_id = 3; // Soroban contract address (C… StrKey) + string function = 4; // Soroban function name + repeated capabilities.blockchain.stellar.v1alpha.ScVal args = 5; // Typed Soroban arguments + uint32 ledger_bounds_offset = 6; // Per-tx ledger-bounds override; 0 = use TXM default +} + +enum TxStatus { + TX_STATUS_FATAL = 0; // Submission failed before on-chain inclusion + TX_STATUS_FAILED = 1; // Included on-chain but execution failed + TX_STATUS_SUCCESS = 2; // Included on-chain and succeeded +} + +// SubmitTransactionResponse carries the outcome of a transaction submission. +message SubmitTransactionResponse { + TxStatus tx_status = 1; + string tx_hash = 2; + string tx_idempotency_key = 3; + bytes result_xdr = 4; // TransactionResult binary XDR; empty if unavailable + bytes result_meta_xdr = 5; // TransactionMeta binary XDR; empty if unavailable +} + // GetLatestLedgerResponse holds current ledger state. message GetLatestLedgerResponse { bytes hash = 1; // 32-byte raw ledger hash diff --git a/pkg/chains/stellar/stellar_grpc.pb.go b/pkg/chains/stellar/stellar_grpc.pb.go index 6c6da20432..51e6b17348 100644 --- a/pkg/chains/stellar/stellar_grpc.pb.go +++ b/pkg/chains/stellar/stellar_grpc.pb.go @@ -20,9 +20,10 @@ import ( const _ = grpc.SupportPackageIsVersion9 const ( - Stellar_GetLedgerEntries_FullMethodName = "/loop.stellar.Stellar/GetLedgerEntries" - Stellar_GetLatestLedger_FullMethodName = "/loop.stellar.Stellar/GetLatestLedger" - Stellar_ReadContract_FullMethodName = "/loop.stellar.Stellar/ReadContract" + Stellar_GetLedgerEntries_FullMethodName = "/loop.stellar.Stellar/GetLedgerEntries" + Stellar_GetLatestLedger_FullMethodName = "/loop.stellar.Stellar/GetLatestLedger" + Stellar_ReadContract_FullMethodName = "/loop.stellar.Stellar/ReadContract" + Stellar_SubmitTransaction_FullMethodName = "/loop.stellar.Stellar/SubmitTransaction" ) // StellarClient is the client API for Stellar service. @@ -32,6 +33,7 @@ type StellarClient interface { GetLedgerEntries(ctx context.Context, in *GetLedgerEntriesRequest, opts ...grpc.CallOption) (*GetLedgerEntriesResponse, error) GetLatestLedger(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*GetLatestLedgerResponse, error) ReadContract(ctx context.Context, in *ReadContractRequest, opts ...grpc.CallOption) (*ReadContractResponse, error) + SubmitTransaction(ctx context.Context, in *SubmitTransactionRequest, opts ...grpc.CallOption) (*SubmitTransactionResponse, error) } type stellarClient struct { @@ -72,6 +74,16 @@ func (c *stellarClient) ReadContract(ctx context.Context, in *ReadContractReques return out, nil } +func (c *stellarClient) SubmitTransaction(ctx context.Context, in *SubmitTransactionRequest, opts ...grpc.CallOption) (*SubmitTransactionResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(SubmitTransactionResponse) + err := c.cc.Invoke(ctx, Stellar_SubmitTransaction_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + // StellarServer is the server API for Stellar service. // All implementations must embed UnimplementedStellarServer // for forward compatibility. @@ -79,6 +91,7 @@ type StellarServer interface { GetLedgerEntries(context.Context, *GetLedgerEntriesRequest) (*GetLedgerEntriesResponse, error) GetLatestLedger(context.Context, *emptypb.Empty) (*GetLatestLedgerResponse, error) ReadContract(context.Context, *ReadContractRequest) (*ReadContractResponse, error) + SubmitTransaction(context.Context, *SubmitTransactionRequest) (*SubmitTransactionResponse, error) mustEmbedUnimplementedStellarServer() } @@ -98,6 +111,9 @@ func (UnimplementedStellarServer) GetLatestLedger(context.Context, *emptypb.Empt func (UnimplementedStellarServer) ReadContract(context.Context, *ReadContractRequest) (*ReadContractResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method ReadContract not implemented") } +func (UnimplementedStellarServer) SubmitTransaction(context.Context, *SubmitTransactionRequest) (*SubmitTransactionResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method SubmitTransaction not implemented") +} func (UnimplementedStellarServer) mustEmbedUnimplementedStellarServer() {} func (UnimplementedStellarServer) testEmbeddedByValue() {} @@ -173,6 +189,24 @@ func _Stellar_ReadContract_Handler(srv interface{}, ctx context.Context, dec fun return interceptor(ctx, in, info, handler) } +func _Stellar_SubmitTransaction_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(SubmitTransactionRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(StellarServer).SubmitTransaction(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Stellar_SubmitTransaction_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(StellarServer).SubmitTransaction(ctx, req.(*SubmitTransactionRequest)) + } + return interceptor(ctx, in, info, handler) +} + // Stellar_ServiceDesc is the grpc.ServiceDesc for Stellar service. // It's only intended for direct use with grpc.RegisterService, // and not to be introspected or modified (even as a copy) @@ -192,6 +226,10 @@ var Stellar_ServiceDesc = grpc.ServiceDesc{ MethodName: "ReadContract", Handler: _Stellar_ReadContract_Handler, }, + { + MethodName: "SubmitTransaction", + Handler: _Stellar_SubmitTransaction_Handler, + }, }, Streams: []grpc.StreamDesc{}, Metadata: "stellar.proto", diff --git a/pkg/loop/internal/relayer/stellar.go b/pkg/loop/internal/relayer/stellar.go index cf860995b7..6676f379fc 100644 --- a/pkg/loop/internal/relayer/stellar.go +++ b/pkg/loop/internal/relayer/stellar.go @@ -52,6 +52,22 @@ func (sc *StellarClient) GetLatestLedger(ctx context.Context) (stellar.GetLatest return resp, nil } +func (sc *StellarClient) SubmitTransaction(ctx context.Context, req stellar.SubmitTransactionRequest) (*stellar.SubmitTransactionResponse, error) { + pReq, err := stelpb.ConvertSubmitTransactionRequestToProto(req) + if err != nil { + return nil, fmt.Errorf("invalid SubmitTransaction request: %w", err) + } + pResp, err := sc.grpcClient.SubmitTransaction(ctx, pReq) + if err != nil { + return nil, net.WrapRPCErr(err) + } + resp, err := stelpb.ConvertSubmitTransactionResponseFromProto(pResp) + if err != nil { + return nil, fmt.Errorf("invalid SubmitTransaction response: %w", err) + } + return resp, nil +} + func (sc *StellarClient) ReadContract(ctx context.Context, req stellar.ReadContractRequest) (stellar.ReadContractResponse, error) { pReq, err := stelpb.ConvertReadContractRequestToProto(req) if err != nil { @@ -111,6 +127,22 @@ func (s *stellarServer) GetLatestLedger(ctx context.Context, _ *emptypb.Empty) ( return pResp, nil } +func (s *stellarServer) SubmitTransaction(ctx context.Context, req *stelpb.SubmitTransactionRequest) (*stelpb.SubmitTransactionResponse, error) { + dReq, err := stelpb.ConvertSubmitTransactionRequestFromProto(req) + if err != nil { + return nil, fmt.Errorf("invalid SubmitTransaction request: %w", err) + } + dResp, err := s.impl.SubmitTransaction(ctx, dReq) + if err != nil { + return nil, net.WrapRPCErr(err) + } + pResp, err := stelpb.ConvertSubmitTransactionResponseToProto(dResp) + if err != nil { + return nil, fmt.Errorf("invalid SubmitTransaction response: %w", err) + } + return pResp, nil +} + func (s *stellarServer) ReadContract(ctx context.Context, req *stelpb.ReadContractRequest) (*stelpb.ReadContractResponse, error) { dReq, err := stelpb.ConvertReadContractRequestFromProto(req) if err != nil { diff --git a/pkg/loop/internal/relayer/stellar_test.go b/pkg/loop/internal/relayer/stellar_test.go index 35068a0081..e3e6b31eb4 100644 --- a/pkg/loop/internal/relayer/stellar_test.go +++ b/pkg/loop/internal/relayer/stellar_test.go @@ -2,6 +2,8 @@ package relayer import ( "context" + "encoding/base64" + "errors" "net" "testing" @@ -171,6 +173,78 @@ func TestStellarDomainRoundTripThroughGRPC(t *testing.T) { require.Equal(t, resultB64, resp.Result) }) + t.Run("SubmitTransaction_roundtrip", func(t *testing.T) { + sym := "transfer" + argVal := stellartypes.ScVal{Type: stellartypes.ScValTypeSymbol, Symbol: &sym} + + svc.submitTransaction = func(_ context.Context, req stellartypes.SubmitTransactionRequest) (*stellartypes.SubmitTransactionResponse, error) { + require.Equal(t, "idem-key", req.IdempotencyKey) + require.Equal(t, "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF", req.FromAddress) + require.Equal(t, "CABC123", req.ContractID) + require.Equal(t, "my_fn", req.Function) + require.Len(t, req.Args, 1) + require.Equal(t, stellartypes.ScValTypeSymbol, req.Args[0].Type) + require.Equal(t, uint32(5), req.LedgerBoundsOffset) + return &stellartypes.SubmitTransactionResponse{ + TxStatus: stellartypes.TxSuccess, + TxHash: "hash123", + TxIdempotencyKey: "idem-key", + }, nil + } + + reply, err := client.SubmitTransaction(ctx, stellartypes.SubmitTransactionRequest{ + IdempotencyKey: "idem-key", + FromAddress: "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF", + ContractID: "CABC123", + Function: "my_fn", + Args: []stellartypes.ScVal{argVal}, + LedgerBoundsOffset: 5, + }) + require.NoError(t, err) + require.Equal(t, stellartypes.TxSuccess, reply.TxStatus) + require.Equal(t, "hash123", reply.TxHash) + require.Equal(t, "idem-key", reply.TxIdempotencyKey) + }) + + t.Run("SubmitTransaction_withResultXDR", func(t *testing.T) { + svc.submitTransaction = func(_ context.Context, _ stellartypes.SubmitTransactionRequest) (*stellartypes.SubmitTransactionResponse, error) { + return &stellartypes.SubmitTransactionResponse{ + TxStatus: stellartypes.TxSuccess, + TxHash: "hash-with-xdr", + TxIdempotencyKey: "idem-xdr", + ResultXDR: base64.StdEncoding.EncodeToString([]byte("result")), + ResultMetaXDR: base64.StdEncoding.EncodeToString([]byte("meta")), + }, nil + } + + reply, err := client.SubmitTransaction(ctx, stellartypes.SubmitTransactionRequest{ + ContractID: "CABC123", + Function: "my_fn", + }) + require.NoError(t, err) + require.Equal(t, "hash-with-xdr", reply.TxHash) + require.Equal(t, base64.StdEncoding.EncodeToString([]byte("result")), reply.ResultXDR) + require.Equal(t, base64.StdEncoding.EncodeToString([]byte("meta")), reply.ResultMetaXDR) + }) + + t.Run("SubmitTransaction_invalidRequest", func(t *testing.T) { + _, err := client.SubmitTransaction(ctx, stellartypes.SubmitTransactionRequest{Function: "fn"}) + require.Error(t, err) + require.Contains(t, err.Error(), "invalid SubmitTransaction request") + }) + + t.Run("SubmitTransaction_implError", func(t *testing.T) { + svc.submitTransaction = func(_ context.Context, _ stellartypes.SubmitTransactionRequest) (*stellartypes.SubmitTransactionResponse, error) { + return nil, errors.New("submit failed") + } + + _, err := client.SubmitTransaction(ctx, stellartypes.SubmitTransactionRequest{ + ContractID: "CABC123", + Function: "my_fn", + }) + require.Error(t, err) + }) + t.Run("ReadContract_noArgs_noResult", func(t *testing.T) { svc.readContract = func(_ context.Context, req stellartypes.ReadContractRequest) (stellartypes.ReadContractResponse, error) { require.Empty(t, req.Args) @@ -193,9 +267,10 @@ func TestStellarDomainRoundTripThroughGRPC(t *testing.T) { type staticStellarService struct { types.UnimplementedStellarService - getLedgerEntries func(ctx context.Context, req stellartypes.GetLedgerEntriesRequest) (stellartypes.GetLedgerEntriesResponse, error) - getLatestLedger func(ctx context.Context) (stellartypes.GetLatestLedgerResponse, error) - readContract func(ctx context.Context, req stellartypes.ReadContractRequest) (stellartypes.ReadContractResponse, error) + getLedgerEntries func(ctx context.Context, req stellartypes.GetLedgerEntriesRequest) (stellartypes.GetLedgerEntriesResponse, error) + getLatestLedger func(ctx context.Context) (stellartypes.GetLatestLedgerResponse, error) + readContract func(ctx context.Context, req stellartypes.ReadContractRequest) (stellartypes.ReadContractResponse, error) + submitTransaction func(ctx context.Context, req stellartypes.SubmitTransactionRequest) (*stellartypes.SubmitTransactionResponse, error) } func (s *staticStellarService) GetLedgerEntries(ctx context.Context, req stellartypes.GetLedgerEntriesRequest) (stellartypes.GetLedgerEntriesResponse, error) { @@ -218,3 +293,10 @@ func (s *staticStellarService) ReadContract(ctx context.Context, req stellartype } return s.readContract(ctx, req) } + +func (s *staticStellarService) SubmitTransaction(ctx context.Context, req stellartypes.SubmitTransactionRequest) (*stellartypes.SubmitTransactionResponse, error) { + if s.submitTransaction == nil { + return s.UnimplementedStellarService.SubmitTransaction(ctx, req) + } + return s.submitTransaction(ctx, req) +} diff --git a/pkg/loop/internal/relayerset/relayerset_test.go b/pkg/loop/internal/relayerset/relayerset_test.go index 5d02ec0b8b..bf8fd0fdab 100644 --- a/pkg/loop/internal/relayerset/relayerset_test.go +++ b/pkg/loop/internal/relayerset/relayerset_test.go @@ -1639,6 +1639,32 @@ func Test_RelayerSet_StellarService(t *testing.T) { require.Equal(t, int64(9000000), resp.LedgerCloseTime) }, }, + { + name: "SubmitTransaction", + run: func(t *testing.T, svc types.StellarService, mockSvc *mocks2.StellarService) { + sym := "transfer" + req := stellartypes.SubmitTransactionRequest{ + IdempotencyKey: "idem-123", + FromAddress: "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF", + ContractID: "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABSC4", + Function: "transfer", + Args: []stellartypes.ScVal{{Type: stellartypes.ScValTypeSymbol, Symbol: &sym}}, + LedgerBoundsOffset: 2, + } + expected := &stellartypes.SubmitTransactionResponse{ + TxStatus: stellartypes.TxSuccess, + TxHash: "stellar-tx-hash", + TxIdempotencyKey: "idem-123", + } + mockSvc.EXPECT().SubmitTransaction(mock.Anything, req).Return(expected, nil) + + reply, err := svc.SubmitTransaction(ctx, req) + require.NoError(t, err) + require.Equal(t, expected.TxHash, reply.TxHash) + require.Equal(t, expected.TxIdempotencyKey, reply.TxIdempotencyKey) + require.Equal(t, expected.TxStatus, reply.TxStatus) + }, + }, } for _, tc := range tests { diff --git a/pkg/loop/internal/relayerset/stellar.go b/pkg/loop/internal/relayerset/stellar.go index a8a5a95177..d160176d79 100644 --- a/pkg/loop/internal/relayerset/stellar.go +++ b/pkg/loop/internal/relayerset/stellar.go @@ -33,6 +33,10 @@ func (sc *stellarClient) ReadContract(ctx context.Context, in *stelpb.ReadContra return sc.client.ReadContract(appendRelayID(ctx, sc.relayID), in, opts...) } +func (sc *stellarClient) SubmitTransaction(ctx context.Context, in *stelpb.SubmitTransactionRequest, opts ...grpc.CallOption) (*stelpb.SubmitTransactionResponse, error) { + return sc.client.SubmitTransaction(appendRelayID(ctx, sc.relayID), in, opts...) +} + // stellarServer implements stelpb.StellarServer by routing each RPC through the RelayerSet. type stellarServer struct { stelpb.UnimplementedStellarServer @@ -77,6 +81,26 @@ func (ss *stellarServer) GetLatestLedger(ctx context.Context, _ *emptypb.Empty) return pResp, nil } +func (ss *stellarServer) SubmitTransaction(ctx context.Context, req *stelpb.SubmitTransactionRequest) (*stelpb.SubmitTransactionResponse, error) { + svc, err := ss.parent.getStellarService(ctx) + if err != nil { + return nil, err + } + dReq, err := stelpb.ConvertSubmitTransactionRequestFromProto(req) + if err != nil { + return nil, fmt.Errorf("invalid SubmitTransaction request: %w", err) + } + dResp, err := svc.SubmitTransaction(ctx, dReq) + if err != nil { + return nil, net.WrapRPCErr(err) + } + pResp, err := stelpb.ConvertSubmitTransactionResponseToProto(dResp) + if err != nil { + return nil, fmt.Errorf("invalid SubmitTransaction response: %w", err) + } + return pResp, nil +} + func (ss *stellarServer) ReadContract(ctx context.Context, req *stelpb.ReadContractRequest) (*stelpb.ReadContractResponse, error) { svc, err := ss.parent.getStellarService(ctx) if err != nil { diff --git a/pkg/loop/internal/relayerset/stellar_test.go b/pkg/loop/internal/relayerset/stellar_test.go new file mode 100644 index 0000000000..8c38603a15 --- /dev/null +++ b/pkg/loop/internal/relayerset/stellar_test.go @@ -0,0 +1,161 @@ +package relayerset + +import ( + "context" + "errors" + "testing" + + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/types/known/emptypb" + + stelpb "github.com/smartcontractkit/chainlink-common/pkg/chains/stellar" + "github.com/smartcontractkit/chainlink-common/pkg/logger" + "github.com/smartcontractkit/chainlink-common/pkg/loop/internal/net" + "github.com/smartcontractkit/chainlink-common/pkg/types" + stellartypes "github.com/smartcontractkit/chainlink-common/pkg/types/chains/stellar" + "github.com/smartcontractkit/chainlink-common/pkg/types/core" + coremocks "github.com/smartcontractkit/chainlink-common/pkg/types/core/mocks" + stellarmocks "github.com/smartcontractkit/chainlink-common/pkg/types/mocks" +) + +type stubStellarGRPC struct { + submit func(ctx context.Context, in *stelpb.SubmitTransactionRequest, opts ...grpc.CallOption) (*stelpb.SubmitTransactionResponse, error) +} + +func (s *stubStellarGRPC) GetLedgerEntries(context.Context, *stelpb.GetLedgerEntriesRequest, ...grpc.CallOption) (*stelpb.GetLedgerEntriesResponse, error) { + panic("not implemented") +} + +func (s *stubStellarGRPC) GetLatestLedger(context.Context, *emptypb.Empty, ...grpc.CallOption) (*stelpb.GetLatestLedgerResponse, error) { + panic("not implemented") +} + +func (s *stubStellarGRPC) ReadContract(context.Context, *stelpb.ReadContractRequest, ...grpc.CallOption) (*stelpb.ReadContractResponse, error) { + panic("not implemented") +} + +func (s *stubStellarGRPC) SubmitTransaction(ctx context.Context, in *stelpb.SubmitTransactionRequest, opts ...grpc.CallOption) (*stelpb.SubmitTransactionResponse, error) { + return s.submit(ctx, in, opts...) +} + +func TestStellarClient_SubmitTransaction_ForwardsRelayID(t *testing.T) { + t.Parallel() + + relayID := types.RelayID{Network: "stellar-net", ChainID: "stellar-chain"} + var gotNetwork, gotChain string + + inner := &stubStellarGRPC{ + submit: func(ctx context.Context, _ *stelpb.SubmitTransactionRequest, _ ...grpc.CallOption) (*stelpb.SubmitTransactionResponse, error) { + md, ok := metadata.FromOutgoingContext(ctx) + require.True(t, ok) + gotNetwork = md.Get(metadataNetwork)[0] + gotChain = md.Get(metadataChain)[0] + return &stelpb.SubmitTransactionResponse{TxStatus: stelpb.TxStatus_TX_STATUS_SUCCESS}, nil + }, + } + + sc := &stellarClient{relayID: relayID, client: inner} + _, err := sc.SubmitTransaction(context.Background(), &stelpb.SubmitTransactionRequest{ + ContractId: "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABSC4", + Function: "ping", + }) + require.NoError(t, err) + require.Equal(t, relayID.Network, gotNetwork) + require.Equal(t, relayID.ChainID, gotChain) +} + +func TestStellarServer_SubmitTransaction(t *testing.T) { + t.Parallel() + + relayID := types.RelayID{Network: "N1", ChainID: "C1"} + mockRelayer := coremocks.NewRelayer(t) + mockSvc := stellarmocks.NewStellarService(t) + + mockRelayer.On("Stellar").Return(mockSvc, nil).Once() + + rs := &TestRelayerSet{relayers: map[types.RelayID]core.Relayer{relayID: mockRelayer}} + srv, _ := NewRelayerSetServer(logger.Nop(), rs, &net.BrokerExt{ + BrokerConfig: net.BrokerConfig{Logger: logger.Nop()}, + }) + + ctx := metadata.NewIncomingContext(context.Background(), metadata.Pairs( + metadataNetwork, relayID.Network, + metadataChain, relayID.ChainID, + )) + + domainReq := stellartypes.SubmitTransactionRequest{ + ContractID: "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABSC4", + Function: "transfer", + } + expected := &stellartypes.SubmitTransactionResponse{ + TxStatus: stellartypes.TxSuccess, + TxHash: "hash-abc", + TxIdempotencyKey: "idem-1", + } + mockSvc.EXPECT().SubmitTransaction(mock.Anything, domainReq).Return(expected, nil).Once() + + pReq, err := stelpb.ConvertSubmitTransactionRequestToProto(domainReq) + require.NoError(t, err) + + resp, err := srv.stellar.SubmitTransaction(ctx, pReq) + require.NoError(t, err) + require.Equal(t, stelpb.TxStatus_TX_STATUS_SUCCESS, resp.GetTxStatus()) + require.Equal(t, expected.TxHash, resp.GetTxHash()) +} + +func TestStellarServer_SubmitTransaction_InvalidRequest(t *testing.T) { + t.Parallel() + + relayID := types.RelayID{Network: "N1", ChainID: "C1"} + mockRelayer := coremocks.NewRelayer(t) + mockRelayer.On("Stellar").Return(stellarmocks.NewStellarService(t), nil).Once() + + rs := &TestRelayerSet{relayers: map[types.RelayID]core.Relayer{relayID: mockRelayer}} + srv, _ := NewRelayerSetServer(logger.Nop(), rs, &net.BrokerExt{ + BrokerConfig: net.BrokerConfig{Logger: logger.Nop()}, + }) + + ctx := metadata.NewIncomingContext(context.Background(), metadata.Pairs( + metadataNetwork, relayID.Network, + metadataChain, relayID.ChainID, + )) + + _, err := srv.stellar.SubmitTransaction(ctx, &stelpb.SubmitTransactionRequest{Function: "only-fn"}) + require.Error(t, err) + require.Contains(t, err.Error(), "invalid SubmitTransaction request") +} + +func TestStellarServer_SubmitTransaction_ServiceError(t *testing.T) { + t.Parallel() + + relayID := types.RelayID{Network: "N1", ChainID: "C1"} + mockRelayer := coremocks.NewRelayer(t) + mockSvc := stellarmocks.NewStellarService(t) + mockRelayer.On("Stellar").Return(mockSvc, nil).Once() + + rs := &TestRelayerSet{relayers: map[types.RelayID]core.Relayer{relayID: mockRelayer}} + srv, _ := NewRelayerSetServer(logger.Nop(), rs, &net.BrokerExt{ + BrokerConfig: net.BrokerConfig{Logger: logger.Nop()}, + }) + + ctx := metadata.NewIncomingContext(context.Background(), metadata.Pairs( + metadataNetwork, relayID.Network, + metadataChain, relayID.ChainID, + )) + + domainReq := stellartypes.SubmitTransactionRequest{ + ContractID: "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABSC4", + Function: "fail", + } + mockSvc.EXPECT().SubmitTransaction(mock.Anything, domainReq). + Return(nil, errors.New("txm unavailable")).Once() + + pReq, err := stelpb.ConvertSubmitTransactionRequestToProto(domainReq) + require.NoError(t, err) + + _, err = srv.stellar.SubmitTransaction(ctx, pReq) + require.Error(t, err) +} diff --git a/pkg/types/chains/stellar/stellar.go b/pkg/types/chains/stellar/stellar.go index 0577b37a20..771231b297 100644 --- a/pkg/types/chains/stellar/stellar.go +++ b/pkg/types/chains/stellar/stellar.go @@ -44,6 +44,8 @@ type Client interface { // ReadContract simulates a read-only Soroban contract function call. // Each element of req.Args is a domain ScVal value. ReadContract(ctx context.Context, req ReadContractRequest) (ReadContractResponse, error) + // SubmitTransaction invokes a Soroban contract via the chain's TXM pipeline. + SubmitTransaction(ctx context.Context, req SubmitTransactionRequest) (*SubmitTransactionResponse, error) } // GetLedgerEntriesRequest fetches ledger entries by XDR-encoded keys. @@ -97,6 +99,49 @@ type ReadContractResponse struct { Error string } +// SubmitTransactionRequest invokes a Soroban contract via the chain's TXM pipeline. +// The TXM handles simulation, sequence management, signing, fee bumping, and on-chain confirmation; +// callers only need to supply the logical contract invocation parameters. +type SubmitTransactionRequest struct { + // IdempotencyKey optionally identifies the transaction for deduplication and status look-up. + IdempotencyKey string + // FromAddress is the source/signer account (G… StrKey). + // Leave empty to use the TXM's default keystore account. + FromAddress string + // ContractID is the Soroban contract address to invoke (C… StrKey). + ContractID string + // Function is the Soroban function name to call. + Function string + // Args holds the typed Soroban function arguments. + Args []ScVal + // LedgerBoundsOffset overrides the TXM's configured ledger bounds for this transaction. + // Zero means use the TXM default. + LedgerBoundsOffset uint32 +} + +// TransactionStatus is the outcome of a submitted transaction. +type TransactionStatus int + +const ( + // TxFatal indicates submission failed before reaching the network (RPC, signing, validation). + TxFatal TransactionStatus = iota + // TxFailed indicates the transaction was accepted but failed on-chain. + TxFailed + // TxSuccess indicates the transaction was accepted and succeeded on-chain. + TxSuccess +) + +// SubmitTransactionResponse carries the result of SubmitTransaction. +type SubmitTransactionResponse struct { + TxStatus TransactionStatus + TxHash string + TxIdempotencyKey string + // ResultXDR is the base64-encoded transaction result XDR when available. + ResultXDR string + // ResultMetaXDR is the base64-encoded result meta XDR when available. + ResultMetaXDR string +} + // GetLatestLedgerResponse holds the current ledger state. type GetLatestLedgerResponse struct { // Hash is the hex-encoded latest ledger hash. diff --git a/pkg/types/mocks/stellar_service.go b/pkg/types/mocks/stellar_service.go index 078dc3dc35..756a52f7c7 100644 --- a/pkg/types/mocks/stellar_service.go +++ b/pkg/types/mocks/stellar_service.go @@ -192,6 +192,65 @@ func (_c *StellarService_ReadContract_Call) RunAndReturn(run func(context.Contex return _c } +// SubmitTransaction provides a mock function with given fields: ctx, req +func (_m *StellarService) SubmitTransaction(ctx context.Context, req stellar.SubmitTransactionRequest) (*stellar.SubmitTransactionResponse, error) { + ret := _m.Called(ctx, req) + + if len(ret) == 0 { + panic("no return value specified for SubmitTransaction") + } + + var r0 *stellar.SubmitTransactionResponse + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, stellar.SubmitTransactionRequest) (*stellar.SubmitTransactionResponse, error)); ok { + return rf(ctx, req) + } + if rf, ok := ret.Get(0).(func(context.Context, stellar.SubmitTransactionRequest) *stellar.SubmitTransactionResponse); ok { + r0 = rf(ctx, req) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*stellar.SubmitTransactionResponse) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, stellar.SubmitTransactionRequest) error); ok { + r1 = rf(ctx, req) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// StellarService_SubmitTransaction_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubmitTransaction' +type StellarService_SubmitTransaction_Call struct { + *mock.Call +} + +// SubmitTransaction is a helper method to define mock.On call +// - ctx context.Context +// - req stellar.SubmitTransactionRequest +func (_e *StellarService_Expecter) SubmitTransaction(ctx interface{}, req interface{}) *StellarService_SubmitTransaction_Call { + return &StellarService_SubmitTransaction_Call{Call: _e.mock.On("SubmitTransaction", ctx, req)} +} + +func (_c *StellarService_SubmitTransaction_Call) Run(run func(ctx context.Context, req stellar.SubmitTransactionRequest)) *StellarService_SubmitTransaction_Call { + _c.Call.Run(func(args mock.Arguments) { + run(args[0].(context.Context), args[1].(stellar.SubmitTransactionRequest)) + }) + return _c +} + +func (_c *StellarService_SubmitTransaction_Call) Return(_a0 *stellar.SubmitTransactionResponse, _a1 error) *StellarService_SubmitTransaction_Call { + _c.Call.Return(_a0, _a1) + return _c +} + +func (_c *StellarService_SubmitTransaction_Call) RunAndReturn(run func(context.Context, stellar.SubmitTransactionRequest) (*stellar.SubmitTransactionResponse, error)) *StellarService_SubmitTransaction_Call { + _c.Call.Return(run) + return _c +} + // NewStellarService creates a new instance of StellarService. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. // The first argument is typically a *testing.T value. func NewStellarService(t interface { diff --git a/pkg/types/relayer.go b/pkg/types/relayer.go index dc5c0f459e..ce5b240ce4 100644 --- a/pkg/types/relayer.go +++ b/pkg/types/relayer.go @@ -270,9 +270,12 @@ type AptosService interface { } // StellarService exposes the Stellar RPC operations needed by CRE: -// fetch ledger entries and get the latest ledger. +// fetch ledger entries, get the latest ledger, and submit transactions. type StellarService interface { stellar.Client + + // SubmitTransaction submits a prebuilt transaction envelope XDR to the network. + SubmitTransaction(ctx context.Context, req stellar.SubmitTransactionRequest) (*stellar.SubmitTransactionResponse, error) } // Relayer extends ChainService with providers for each product. @@ -660,3 +663,7 @@ func (u *UnimplementedStellarService) GetLedgerEntries(_ context.Context, _ stel func (u *UnimplementedStellarService) GetLatestLedger(_ context.Context) (stellar.GetLatestLedgerResponse, error) { return stellar.GetLatestLedgerResponse{}, status.Errorf(codes.Unimplemented, "method GetLatestLedger not implemented") } + +func (u *UnimplementedStellarService) SubmitTransaction(_ context.Context, _ stellar.SubmitTransactionRequest) (*stellar.SubmitTransactionResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method SubmitTransaction not implemented") +} diff --git a/pkg/types/relayer_stellar_test.go b/pkg/types/relayer_stellar_test.go new file mode 100644 index 0000000000..83f5e9045a --- /dev/null +++ b/pkg/types/relayer_stellar_test.go @@ -0,0 +1,22 @@ +package types_test + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "github.com/smartcontractkit/chainlink-common/pkg/types" + stellartypes "github.com/smartcontractkit/chainlink-common/pkg/types/chains/stellar" +) + +func TestUnimplementedStellarService_SubmitTransaction(t *testing.T) { + t.Parallel() + + var svc types.UnimplementedStellarService + _, err := svc.SubmitTransaction(context.Background(), stellartypes.SubmitTransactionRequest{}) + require.Error(t, err) + require.Equal(t, codes.Unimplemented, status.Code(err)) +}