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";
import { Server, Api } from "@stellar/stellar-sdk/rpc";

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

// Submits a tx and then polls for its status until a timeout is reached.
async function yeetTx(
tx: Transaction | FeeBumpTransaction,
): Promise<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 Api.GetTransactionStatus.FAILED:
throw tmpStatus;
case Api.GetTransactionStatus.NOT_FOUND:
await sleep(500);
continue;
case Api.GetTransactionStatus.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.