Documentación
Guía rápida
Añade la pregunta del vuelto a tu app en Stellar. Primero pruébalo de punta a punta en testnet con la fundación de demo, y luego apúntalo a una fundación real.
1. Instala los paquetes
Agrega spare-sdk y spare-wallets-kit a tu app. El kit abre la confirmación en wallets como Freighter, LOBSTR o Ledger. Ambos paquetes son solo ESM y piden Node 20 o superior: en un proyecto Node pon "type": "module" en el package.json.
npm install spare-wallets-kit spare-sdk @creit.tech/stellar-wallets-kit @stellar/stellar-sdkpnpm add spare-wallets-kit spare-sdk @creit.tech/stellar-wallets-kit @stellar/stellar-sdkyarn add spare-wallets-kit spare-sdk @creit.tech/stellar-wallets-kit @stellar/stellar-sdk2. Pruébalo en testnet
Consigue USDC de testnet
Necesitas una cuenta de testnet con el USDC de testnet de Circle (emisor GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5). Crea una con stellar keys generate my-user --network testnet --fund y lee la clave secreta con stellar keys secret my-user, o deja que Friendbot fondee cualquier par de claves. El script de abajo la fondea, agrega la trustline de USDC y cambia XLM por 5 USDC en el DEX de testnet.
import { Asset, BASE_FEE, Horizon, Keypair, Networks, Operation, TransactionBuilder } from "@stellar/stellar-sdk";
const server = new Horizon.Server("https://horizon-testnet.stellar.org");
const keypair = Keypair.fromSecret(process.env.SECRET!); // a testnet secret key (S...)
const usdc = new Asset("USDC", "GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5"); // Circle testnet
// 1. Friendbot funds the account with testnet XLM (skip if it already has some).
await fetch(`https://friendbot.stellar.org?addr=${keypair.publicKey()}`);
// 2. Trust Circle's testnet USDC, then swap XLM for exactly 5 USDC on the testnet DEX.
const tx = new TransactionBuilder(await server.loadAccount(keypair.publicKey()), {
fee: BASE_FEE,
networkPassphrase: Networks.TESTNET,
})
.addOperation(Operation.changeTrust({ asset: usdc }))
.addOperation(
Operation.pathPaymentStrictReceive({
sendAsset: Asset.native(),
sendMax: "500", // XLM you are willing to spend
destination: keypair.publicKey(),
destAsset: usdc,
destAmount: "5",
}),
)
.setTimeout(60)
.build();
tx.sign(keypair);
console.log("funded:", (await server.submitTransaction(tx)).hash);Corre una donación de punta a punta
Este script de Node arma un pago, le pide a Spare una donación de US$0,50 para la fundación de demo, firma y envía a Horizon. El signer sin interfaz hace de wallet y confirm hace de modal. Guárdalo como donate.ts y córrelo con SECRET=S... npx tsx donate.ts.
import { Asset, BASE_FEE, Horizon, Keypair, Networks, Operation, TransactionBuilder } from "@stellar/stellar-sdk";
import { HorizonAccountPort } from "spare-sdk";
import { withSpare } from "spare-wallets-kit";
const server = new Horizon.Server("https://horizon-testnet.stellar.org");
const keypair = Keypair.fromSecret(process.env.SECRET!); // a testnet secret key (S...)
// 1. The transaction your app already builds: pay 1 XLM to a (freshly funded) merchant.
const merchant = Keypair.random();
await fetch(`https://friendbot.stellar.org?addr=${merchant.publicKey()}`);
const tx = new TransactionBuilder(await server.loadAccount(keypair.publicKey()), {
fee: BASE_FEE,
networkPassphrase: Networks.TESTNET,
})
.addOperation(Operation.payment({ destination: merchant.publicKey(), asset: Asset.native(), amount: "1" }))
.setTimeout(60)
.build();
// 2. A headless "wallet". The kit only needs a signTransaction(xdr, opts) that returns { signedTxXdr }.
const signer = {
async signTransaction(xdr: string, opts?: { networkPassphrase?: string }) {
const toSign = TransactionBuilder.fromXDR(xdr, opts?.networkPassphrase ?? Networks.TESTNET);
toSign.sign(keypair);
return { signedTxXdr: toSign.toXDR() };
},
};
// 3. Spare wraps it. A custom `confirm` replaces the browser modal: return true only on an explicit yes.
const spare = withSpare(signer, {
foundation: { account: "GCAEBBLSVFM2RLNBYMEZLFWHCXFHOGVJAXQK2K3WVHS2UGVDVWJOXGQJ", domain: "donatespare.xyz" },
foundationName: "Spare demo foundation",
mode: { amount: "0.50" },
appId: "quickstart",
maxAmount: "5",
accounts: new HorizonAccountPort({ network: "testnet" }),
network: "testnet",
confirm: async (prompt) => {
console.log(`Add US$${prompt.amount} for ${prompt.foundationName}? (auto-yes in this demo)`);
return true;
},
});
// Pass the passphrase so the kit can parse the XDR.
const result = await spare.signWithDonation(tx.toXDR(), { networkPassphrase: Networks.TESTNET });
console.log(result.outcome, result.reason ?? "", "changed:", result.changed);
// "donated": changed is true and the signed tx carries the donation.
// "declined" | "not-offered" | "passthrough" | "error": the original tx was signed.
// 4. Submitting is your job.
const signed = TransactionBuilder.fromXDR(result.signedTxXdr, Networks.TESTNET);
console.log("submitted:", (await server.submitTransaction(signed)).hash);Deberías ver donated changed: true y el hash de una transacción. Ábrela en un explorador de testnet: tras el pago hay otro pago de 0,50 USDC a la fundación de demo, con el memo spare:quickstart.
3. Haz la pregunta al firmar
En una app de navegador, envuelve Stellar Wallets Kit. Antes de la firma, la persona ve la opción de sumar un poco o redondear para una fundación. El ejemplo de abajo tiene la forma de producción: reemplaza los marcadores G... y foundation.org por la cuenta registrada de tu fundación y el dominio de su sitio, y network por "mainnet".
Transacciones clásicas
import { StellarWalletsKit } from "@creit.tech/stellar-wallets-kit";
import { HorizonAccountPort } from "spare-sdk";
import { withSpare } from "spare-wallets-kit";
const network = "testnet"; // "mainnet" in production
const spare = withSpare(StellarWalletsKit, {
foundation: { account: "G...", domain: "foundation.org" }, // listed in its stellar.toml
foundationName: "Tellus Cooperative",
mode: { amount: "0.50" }, // or { roundUp: true } for USDC purchases
appId: "my-app", // <= 22 ASCII bytes
maxAmount: "5",
accounts: new HorizonAccountPort({ network }),
network,
locale: "es",
});
// Same signature as the kit: use it wherever you called kit.signTransaction.
const { signedTxXdr } = await spare.signTransaction(xdr, { address });network es opcional si le pasas a signTransaction el passphrase de testnet o de mainnet y tu versión de spare-wallets-kit infiere la red a partir de él. Pasarla explícitamente siempre funciona.
¿Necesitas saber si el hash cambió, o por qué no se ofreció nada? Usa signWithDonation en vez de signTransaction: devuelve { signedTxXdr, donation, changed, outcome, reason? }. El outcome es donated, declined, not-offered, passthrough o error, y todos salvo donated firman tu transacción original.
const result = await spare.signWithDonation(xdr, { address });
// result.outcome: "donated" | "declined" | "not-offered" | "passthrough" | "error"
// result.changed is true only for "donated" (the hash changed); result.donation has the details.
// For the other outcomes the original tx was signed; result.reason says why (when there is one).
if (result.outcome === "donated") console.log("Donated", result.donation!.amount, "USDC");
else console.log(result.outcome, result.reason ?? "");
// Submitting is your job: send result.signedTxXdr as it is (it may carry a different hash).
const signed = TransactionBuilder.fromXDR(result.signedTxXdr, Networks.TESTNET);
await server.submitTransaction(signed);Llamadas Soroban
// A Soroban tx holds one operation: the donation is a separate payment after success.
const follow = await spare.offerFollowUp({ successful: true, sourceAccount: address, hash });
if (follow.status === "signed") await submit(follow.signedTxXdr); // submitting is your job¿Construyes tu propia interfaz? Usa addDonation (clásicas) o donateAfter (Soroban) de spare-sdk directamente.
4. Deja el registro a la vista
El aporte va directo a la fundación. El indexador y el tablero publican el movimiento.