Skip to content

Commit

Permalink
adds route and helper to submit transaction to the horizon rpc
Browse files Browse the repository at this point in the history
  • Loading branch information
aristidesstaffieri committed Dec 14, 2023
1 parent 88d8d43 commit 207156e
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 1 deletion.
33 changes: 32 additions & 1 deletion src/helper/horizon-rpc.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import BigNumber from "bignumber.js";
import { AssetType, Horizon } from "stellar-sdk";
import { AssetType, Horizon, TransactionBuilder } from "stellar-sdk";

export const BASE_RESERVE = 0.5;
export const BASE_RESERVE_MIN_COUNT = 2;
Expand Down Expand Up @@ -229,3 +229,34 @@ export const fetchAccountHistory = async (
throw new Error(JSON.stringify(error));
}
};

export const submitTransaction = async (
signedXDR: string,
networkUrl: string,
networkPassphrase: string
): Promise<{
data: Horizon.HorizonApi.SubmitTransactionResponse | null;
error: unknown;
}> => {
const tx = TransactionBuilder.fromXDR(signedXDR, networkPassphrase);
const server = new Horizon.Server(networkUrl);

try {
const data = await server.submitTransaction(tx);
return {
data,
error: null,
};
} catch (e: any) {
if (e.response.status === 504) {
// in case of 504, keep retrying this tx until submission succeeds or we get a different error
// https://developers.stellar.org/api/errors/http-status-codes/horizon-specific/timeout
// https://developers.stellar.org/docs/encyclopedia/error-handling
return await submitTransaction(signedXDR, networkUrl, networkPassphrase);
}
return {
data: null,
error: e,
};
}
};
46 changes: 46 additions & 0 deletions src/route/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
isNetwork,
NetworkNames,
} from "../helper/validate";
import { submitTransaction } from "../helper/horizon-rpc";

const API_VERSION = "v1";

Expand Down Expand Up @@ -259,6 +260,51 @@ export function initApiServer(
},
});

instance.route({
method: "POST",
url: "/submit-tx",
schema: {
body: {
type: "object",
properties: {
signed_xdr: { type: "string" },
network_url: { type: "string" },
network_passphrase: { type: "string" },
},
},
response: {
200: {
type: "object",
properties: {
data: { type: "object" },
},
},
},
},
handler: async (
request: FastifyRequest<{
Body: {
signed_xdr: string;
network_url: string;
network_passphrase: string;
};
}>,
reply
) => {
const { signed_xdr, network_url, network_passphrase } = request.body;
const { data, error } = await submitTransaction(
signed_xdr,
network_url,
network_passphrase
);
if (error) {
reply.code(400).send(error);
} else {
reply.code(200).send(data);
}
},
});

next();
},
{ prefix: `/api/${API_VERSION}` }
Expand Down

0 comments on commit 207156e

Please sign in to comment.