import { init, SwapClient, SwapMasterKey, SwapScript, toJson } from "@kaleidorg/swap-sdk";
import { writeFile } from "node:fs/promises";
await init();
const network = "signet";
const makerUrl = "https://maker.signet.kaleidoswap.com/v2";
const liquidEsploraUrl = "https://blockstream.info/liquidtestnet/api";
const payoutAddress = process.env.LIQUID_ADDRESS!; // a Liquid testnet address you control
const client = new SwapClient(makerUrl);
// Keys and the swap secret come from a mnemonic you keep. Use a new index for every swap.
const master = SwapMasterKey.fromWalletMnemonic(process.env.WALLET_MNEMONIC!, network);
const index = BigInt(process.env.SWAP_INDEX ?? "0"); // use a new index for every run
const claimKey = master.deriveSwapKey(index);
const preimage = master.derivePreimage(index);
// Create the swap. The SDK checks the maker's answer against your key and secret.
const card = (await client.reversePairs()).BTC["L-BTC"];
const swap = await client.createReverseSwap(network, {
from: "BTC",
to: "L-BTC",
invoiceAmount: 50_000n,
preimageHash: preimage.sha256,
claimPublicKey: claimKey.publicKey,
pairHash: card.hash,
});
await writeFile(`${swap.id}.json`, toJson({ index, swap })); // save before paying
console.log(`Pay this invoice:\n${swap.invoice}`);
// Wait until the maker's lockup confirms; stop if the swap fails.
const failed = ["swap.expired", "invoice.expired", "transaction.failed", "transaction.refunded"];
for (;;) {
const { status } = await client.swap(swap.id);
if (status === "transaction.confirmed") break;
if (failed.includes(status)) throw new Error(`swap ${swap.id} ended in ${status}`);
await new Promise((r) => setTimeout(r, 5_000));
}
// Claim it. Broadcasting reveals the secret, and the maker settles your payment.
const script = SwapScript.fromReverse("liquid", network, swap, claimKey.publicKey);
const claim = await script.constructClaim(preimage.preimage, {
outputAddress: payoutAddress,
swapId: swap.id,
keysSecretHex: claimKey.secretKey,
makerBaseUrl: makerUrl,
network,
liquidEsploraUrl,
});
console.log("Claimed:", await claim.broadcast(network, undefined, liquidEsploraUrl));