import {
Account,
BASE_FEE,
Keypair,
Networks,
Operation,
TransactionBuilder,
} from "@stellar/stellar-sdk";
import { LumenWipeClient, runClose } from "@lumenwipe/sdk";
import {
exitExpectations,
poolWithdrawalExpectations,
verifyCloseTransaction,
} from "@lumenwipe/verify";
const network = "testnet";
const client = new LumenWipeClient({
baseUrl: process.env.LUMENWIPE_API_URL ?? "https://api.lumenwipe.com",
apiKey: process.env.LUMENWIPE_API_KEY,
network,
});
async function fund(address) {
const res = await fetch(`https://friendbot.stellar.org/?addr=${address}`);
if (!res.ok) throw new Error(`Friendbot answered ${res.status}`);
for (let i = 0; i < 20; i++) {
try {
return await client.getAccount(address);
} catch (error) {
if (error.code !== "account_not_found") throw error;
await new Promise((done) => setTimeout(done, 3000));
}
}
throw new Error(`${address} did not appear on testnet`);
}
const source = Keypair.random();
const destination = Keypair.random();
await fund(source.publicKey());
await fund(destination.publicKey());
// One data entry, so the close has a sub-entry to remove before the merge.
const funded = await client.getAccount(source.publicKey());
const setup = new TransactionBuilder(new Account(source.publicKey(), funded.sequence), {
fee: BASE_FEE,
networkPassphrase: Networks.TESTNET,
})
.addOperation(Operation.manageData({ name: "quickstart", value: "1" }))
.setTimeout(60)
.build();
setup.sign(source);
await client.submit(setup.toEnvelope().toXdr("base64"));
const account = await client.getAccount(source.publicKey());
const plan = await client.closePlan({
source: source.publicKey(),
destination: destination.publicKey(),
});
if (plan.blockers.length > 0) throw new Error(plan.blockers.map((b) => b.message).join("; "));
// A destination LumenWipe does not recognize must be acknowledged. Any other required
// decision is a choice about the user's assets: stop and ask the user instead.
const ack = `destination:${destination.publicKey()}`;
const open = plan.decisionPoints.filter((d) => d.required && d.id !== ack);
if (open.length > 0) throw new Error(`Ask the user: ${open.map((d) => d.id).join(", ")}`);
const decisions = plan.decisionPoints.some((d) => d.id === ack)
? [{ id: ack, choice: "i_control_this_address" }]
: [];
const hashes = [];
await runClose({
getTransactions: () =>
client.closeTransactions({
source: source.publicKey(),
destination: destination.publicKey(),
decisions,
}),
verify: (tx) =>
verifyCloseTransaction({
unsignedXdr: tx.xdr,
network,
expected: {
source: account.address,
destination: destination.publicKey(),
nativeBalance: account.nativeBalanceLumens,
memo: null,
memoType: null,
claimTrustlineAssets: [],
accountSigners: account.signers,
accountThresholds: account.thresholds,
transfers: {},
tokenTransfers: {},
classicConversions: {},
tokenConversions: {},
sponsoredEntries: account.sponsoredEntries,
...exitExpectations(account, network),
poolWithdrawals: poolWithdrawalExpectations(account),
},
}),
requiredWeight: () => Math.max(1, account.thresholds.high),
sign: async (_tx, xdr) => {
const tx = TransactionBuilder.fromXdr(xdr, Networks.TESTNET);
tx.sign(source);
const weight = account.signers.find((s) => s.key === source.publicKey())?.weight ?? 0;
return { xdr: tx.toEnvelope().toXdr("base64"), weight };
},
submit: async (_tx, xdr) => (await client.submit(xdr)).hash,
onConfirmed: (tx, hash) => {
hashes.push(hash);
console.log(`Confirmed ${tx.intent.summary}: ${hash}`);
},
});
const delivered = await client.closeDelivered(destination.publicKey(), hashes);
console.log(`Closed ${source.publicKey()}. Delivered ${delivered.totalStroops} stroops.`);