Skip to main content

Submit a transaction to Soroban RPC using the JavaScript SDK

Here is a simple, rudimentary looping mechanism to submit a transaction to Soroban RPC and wait for a result.

import {
Transaction,
FeeBumpTransaction,
SorobanRpc,
} from "@stellar/stellar-sdk";

const RPC_SERVER = "https://soroban-testnet.stellar.org/";
const server = new SorobanRpc.Server(RPC_SERVER);

// Submits a tx and then polls for its status until a timeout is reached.
async function yeetTx(
tx: Transaction | FeeBumpTransaction,
): Promise<SorobanRpc.Api.GetTransactionResponse> {
return server.sendTransaction(tx).then(async (reply) => {
if (reply.status !== "PENDING") {
throw reply;
}

let status;
let attempts = 0;
while (attempts++ < 5) {
const tmpStatus = await server.getTransaction(reply.hash);
switch (tmpStatus.status) {
case "FAILED":
throw tmpStatus;
case "NOT_FOUND":
await sleep(500);
continue;
case "SUCCESS":
status = tmpStatus;
break;
}
}

if (attempts >= 5 || !status) {
throw new Error(`Failed to find transaction ${reply.hash} in time.`);
}

return status;
});
}

function sleep(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
caution

Remember: You should always handle errors gracefully! This is a fail-hard and fail-fast approach that should only be used in these examples.