Integrating (writes)
Send Spield transactions from your app. Use @spield/sdk, or build Soroban contract calls yourself with @stellar/stellar-sdk.
There are two ways to write to Spield.
@spield/sdk(recommended). It picks the series, builds the right calls, adds missing trustlines, simulates, asks the wallet to sign, submits and waits for confirmation. See the SDK page.- Raw contract calls with
@stellar/stellar-sdk. More work, full control. Use it if you cannot use the SDK or need a call it does not wrap.
The recommended path: the SDK
import { SpieldClient, SpieldSdkError } from '@spield/sdk';
import { pickWallet, restoreWallet } from '@spield/sdk/wallets';
const wallet = (await restoreWallet()) ?? (await pickWallet()); // null if the user closes the picker
const spield = new SpieldClient({ signer: wallet ?? undefined }); // Testnet by default
await spield.loadSeries();
const series = spield.series('testnet-blend-3'); // pick an id explicitly
const info = await series.getInfo();
if (info.actions.buyPt) {
const quote = await series.quoteBuyPt({ amount: '10' }); // 10 USDC
console.log(`${quote.ptOut.formatted} PT at ${quote.fixedApyPct.toFixed(2)}% fixed`);
try {
const result = await series.buyPt({ amount: '10', slippageBps: 50 });
console.log(result.explorerUrl);
} catch (e) {
if (!(e instanceof SpieldSdkError)) throw e;
if (e.reason !== 'wallet_rejected') console.error(e.reason, e.message); // wallet_rejected: the user cancelled
}
}Every write simulates first, signs, submits, and resolves when the network confirms. It returns
{ hash, explorerUrl, status: 'success', steps }. Reads and previews need no wallet.
Do not guess, preview
series.preview('buyPt', { amount: '10' }) tells you whether an action will work for a wallet, and how
many signatures it needs, without signing or sending anything. Use it to label buttons and to dry-run on mainnet.
The raw path: the write lifecycle
Writing without the SDK uses the standard Soroban transaction lifecycle. Your app builds, simulates, asks the user's wallet to sign, submits and polls.
Build
Construct the contract call (for example buy_pt_with_usdc) with the user's account as the source.
Simulate and prepare
Simulate to get the resource footprint and authorization, then assemble the prepared transaction.
prepareTransaction does this in one step, and a failed simulation tells you the call would revert.
Sign
Hand the prepared XDR to the user's wallet. Sign for the correct network passphrase, and check the wallet is on that network first.
Submit and poll
Submit the signed transaction and poll getTransaction until it leaves NOT_FOUND.
import { Address, BASE_FEE, Contract, TransactionBuilder, nativeToScVal, rpc, xdr } from '@stellar/stellar-sdk';
const server = new rpc.Server(RPC_URL);
export async function write(
walletAddress: string,
contractId: string,
method: string,
args: xdr.ScVal[],
signXDR: (xdr: string) => Promise<string>, // your wallet adapter
): Promise<string> {
const account = await server.getAccount(walletAddress);
const tx = new TransactionBuilder(account, { fee: BASE_FEE, networkPassphrase: PASSPHRASE })
.addOperation(new Contract(contractId).call(method, ...args))
.setTimeout(60)
.build();
const prepared = await server.prepareTransaction(tx); // simulate + assemble
const signed = TransactionBuilder.fromXDR(await signXDR(prepared.toXDR()), PASSPHRASE);
const sent = await server.sendTransaction(signed);
if (sent.status === 'ERROR') throw new Error('submit failed');
let res = await server.getTransaction(sent.hash);
while (res.status === 'NOT_FOUND') {
await new Promise((r) => setTimeout(r, 1000));
res = await server.getTransaction(sent.hash);
}
if (res.status !== 'SUCCESS') throw new Error('transaction failed');
return sent.hash;
}Fees on mainnet
Mainnet's Soroban inclusion fee often sits above BASE_FEE, and a transaction that offers less can wait
until it expires. Read the network's fee stats and offer a competitive inclusion fee. The SDK does
this for you.
Example write calls
These use the Router, the one-signature front door for plain USDC. Amounts are in base units
(7 decimals) and every swap takes a deadline_ledger.
const addr = (a: string) => new Address(a).toScVal();
const i128 = (n: bigint) => nativeToScVal(n, { type: 'i128' });
const u32 = (n: number) => nativeToScVal(n, { type: 'u32' });
const toBase = (h: string) => BigInt(Math.round(parseFloat(h) * 1e7));
const { sequence } = await server.getLatestLedger();
const deadline = u32(sequence + 100);
// 1. Quote, then buy PT with 100 USDC. Protect the user with min_pt_out.
const quoted = await read<bigint>(ROUTER, 'quote_buy_pt_with_usdc', [i128(toBase('100'))]);
const minPtOut = (quoted * 99n) / 100n; // 1% slippage
await write(wallet, ROUTER, 'buy_pt_with_usdc',
[addr(wallet), i128(toBase('100')), i128(minPtOut), deadline], signXDR);
// 2. Lock a fixed rate in the Fixed-Rate Vault. Returns the receipt id.
await write(wallet, VAULT, 'deposit', [addr(wallet), i128(toBase('100'))], signXDR);
// 3. After maturity: redeem PT at face, straight to USDC.
const payout = await read<bigint>(ROUTER, 'quote_redeem_py_for_usdc', [i128(ptBalance)]);
await write(wallet, ROUTER, 'redeem_py_for_usdc',
[addr(wallet), i128(ptBalance), i128(payout)], signXDR); // min_usdc_out
// 4. Claim accrued YT yield as USDC. quote_claim_yield gives the floor.
const owed = await read<bigint>(ROUTER, 'quote_claim_yield', [addr(wallet)]);
await write(wallet, ROUTER, 'claim_yield_to_usdc', [addr(wallet), i128(owed)], signXDR);
// 5. Redeem a matured vault receipt.
await write(wallet, VAULT, 'redeem', [nativeToScVal(receiptId, { type: 'u64' })], signXDR);read is the simulation helper from Reading state.
For the full function list see Contracts.
Things to handle yourself
- Trustlines. PT and USDC are classic assets, so the receiving account needs a trustline (a
changeTrustoperation) before it can receive them. SR and YT are contract tokens and need none. In USTRY series, USTRY needs one and the claim tokens do not. - Series state. Check
expiry()first. After maturity, buys, swaps andadd_liquidityare refused and only exits work. - Multi-step actions. Some actions are more than one transaction. On Blend series the SDK signs two transactions to buy or sell YT (wrap USDC to SR, then trade), because the one-call Router route does not fit in a single Soroban transaction against the live Blend pool. If the second step fails the first has already confirmed, so re-read state before you retry.
- Wallet network. Verify the wallet is on the passphrase you are building for. A mainnet transaction signed on the wrong network is rejected before it is sent.
Wallet signing
Use any Stellar wallet adapter. @spield/sdk/wallets ships a picker for Freighter, xBull, LOBSTR, Albedo,
Rabet and Hana. Each wallet exposes a signTransaction(xdr) you can wrap as the signXDR callback above.
Handling common errors
| Situation | What you see | Handle by |
|---|---|---|
| Slippage exceeded | Simulation fails | Re-quote, or widen the user's tolerance. SDK reason: 'slippage'. |
| Not enough liquidity | A quote_* read returns 0, or the swap reverts | Tell the user the size is too large. SDK reason: 'no_liquidity'. |
| Deposit cap reached | Deposit reverts (#107) | Show the room left (deposit_headroom()). SDK reason: 'cap_reached'. |
| Paused | New-exposure call fails | Tell the user new deposits are paused. Exits still work. |
| Series matured | Buys and swaps fail | Offer redeem and claim instead. SDK reason: 'series_matured'. |
| Redeem before maturity without YT | redeem_py needs equal YT | Offer to sell the PT, or hold to maturity. |
| Missing trustline | Receiving PT or USDC fails | Add the trustline first. SDK reason: 'trustline_missing'. |
| Deadline passed | Swap reverts | Rebuild with a later deadline_ledger. |
Next: index protocol activity with Events.