Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adds route and helper to submit transaction to the horizon rpc #13

Merged
merged 5 commits into from
Dec 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know you're just picking up this code from the Freighter codebase, but maybe we can type this error now. I think it should be BadResponseError from stellar-sdk

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh yeah so I actually tried this but it turns out in TS, you can only annotate the error from the catch block as an any or unknown. https://byby.dev/ts-try-catch-error-type#:~:text=The%20only%20type%20annotations%20that,on%20it%20without%20type%20checking.

So I did annotate it in the response shape from this function but not sure if I can actually annotate the error as it come in from the catch block.

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,
};
}
};
142 changes: 142 additions & 0 deletions src/route/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,16 @@ import {
isNetwork,
NetworkNames,
} from "../helper/validate";
import { submitTransaction } from "../helper/horizon-rpc";
import {
Memo,
MemoType,
Operation,
SorobanRpc,
Transaction,
TransactionBuilder,
} from "stellar-sdk";
import { simulateTx } from "../helper/soroban-rpc";

const API_VERSION = "v1";

Expand Down Expand Up @@ -150,6 +160,58 @@ export function initApiServer(
},
});

instance.route({
method: "GET",
url: "/token-details/:contractId",
schema: {
params: {
["contractId"]: {
type: "string",
validator: (qStr: string) => isContractId(qStr),
},
},
querystring: {
["pub_key"]: {
type: "string",
validator: (qStr: string) => isPubKey(qStr),
},
["network"]: {
type: "string",
validator: (qStr: string) => isNetwork(qStr),
},
["soroban_url"]: {
type: "string",
},
},
},
handler: async (
request: FastifyRequest<{
Params: { ["contractId"]: string };
Querystring: {
["contract_ids"]: string;
["pub_key"]: string;
["network"]: NetworkNames;
["soroban_url"]?: string;
};
}>,
reply
) => {
const contractId = request.params["contractId"];
const { network, pub_key, soroban_url } = request.query;
try {
const data = await mercuryClient.tokenDetails(
pub_key,
contractId,
network,
soroban_url
);
reply.code(200).send(data);
} catch (error) {
reply.code(400).send(error);
}
},
});

instance.route({
method: "POST",
url: "/subscription/token",
Expand Down Expand Up @@ -279,6 +341,86 @@ 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" },
},
},
},
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);
}
},
});

instance.route({
method: "POST",
url: "/simulate-tx",
schema: {
body: {
type: "object",
properties: {
signed_xdr: { type: "string" },
network_url: { type: "string" },
network_passphrase: { type: "string" },
},
},
},
handler: async (
request: FastifyRequest<{
Body: {
signed_xdr: string;
network_url: string;
network_passphrase: string;
};
}>,
reply
) => {
const { signed_xdr, network_url, network_passphrase } = request.body;

try {
const tx = TransactionBuilder.fromXDR(
signed_xdr,
network_passphrase
);
const server = new SorobanRpc.Server(network_url);

const data = await simulateTx<unknown>(
tx as Transaction<Memo<MemoType>, Operation[]>,
server
);
reply.code(200).send(data);
} catch (error) {
reply.code(400).send(error);
}
},
});

next();
},
{ prefix: `/api/${API_VERSION}` }
Expand Down
5 changes: 3 additions & 2 deletions src/service/mercury/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,8 @@ export class MercuryClient {
tokenDetails = async (
pubKey: string,
contractId: string,
network: NetworkNames
network: NetworkNames,
customRpcUrl?: string
): Promise<
{ name: string; symbol: string; decimals: number } | undefined
> => {
Expand All @@ -345,7 +346,7 @@ export class MercuryClient {
return JSON.parse(tokenDetails);
}
}
const server = await getServer(network);
const server = await getServer(network, customRpcUrl);
// we need a builder per operation, 1 op per tx in Soroban
const decimalsBuilder = await getTxBuilder(pubKey, network, server);
const decimals = await getTokenDecimals(
Expand Down
Loading