import {
address,
getAddressEncoder,
getProgramDerivedAddress,
type Address,
type Signature,
type TransactionSigner,
} from "@solana/kit";
import { MEMO_PROGRAM_ADDRESS } from "@solana-program/memo";
import {
getTransferCheckedInstruction as getUsdcTransferInstruction,
TOKEN_PROGRAM_ADDRESS,
} from "@solana-program/token";
import {
findAssociatedTokenPda,
getCreateAssociatedTokenIdempotentInstruction,
getThawAccountInstruction,
getTransferCheckedInstruction,
TOKEN_2022_PROGRAM_ADDRESS,
} from "@solana-program/token-2022";
import { failure } from "./blocked-transfer";
import { rpc, send } from "./config";
import { units } from "./price";
import {
DVP_SWAP_PROGRAM_PROGRAM_ADDRESS,
getDvpSwapProgramErrorMessage,
findSwapDvpEscrowAta,
findSwapDvpPda,
getCreateDvpInstruction,
getSettleDvpInstruction,
verifySwapDvp,
type DvpSwapProgramError,
} from "./dvp";
// Devnet USDC by default. On mainnet: EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v.
export const USDC_MINT = address(
process.env.USDC_MINT ?? "4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU",
);
export interface Terms {
seller: Address; // delivers the asset (user_a)
buyer: Address; // delivers the cash (user_b)
agent: Address; // the settlement authority, e.g. the venue
asset: Address; // the asset's mint (Token-2022)
assetAmount: bigint;
cashAmount: bigint; // USDC base units (SPL Token)
}
export type Trade = Terms & {
record: Address;
escrowA: Address;
escrowB: Address;
};
const ataOf = async (owner: Address, mint: Address, tokenProgram: Address) =>
(await findAssociatedTokenPda({ owner, mint, tokenProgram }))[0];
/**
* Record the terms with CreateDvp. It creates the trade record and one escrow
* account per leg, and moves no tokens. Anyone can create a record, so read
* it back and check it against the agreed terms before anyone funds it.
*/
export async function createTrade(agent: TransactionSigner, terms: Terms) {
// A random 64-bit nonce, so nobody can occupy this trade's address first.
const nonce = new DataView(
crypto.getRandomValues(new Uint8Array(8)).buffer,
).getBigUint64(0);
const seeds = {
settlementAuthority: terms.agent,
userA: terms.seller,
userB: terms.buyer,
mintA: terms.asset,
mintB: USDC_MINT,
nonce,
};
const [record] = await findSwapDvpPda(seeds);
const [escrowA] = await findSwapDvpEscrowAta({
swapDvp: record,
mint: terms.asset,
tokenProgram: TOKEN_2022_PROGRAM_ADDRESS,
});
const [escrowB] = await findSwapDvpEscrowAta({
swapDvp: record,
mint: USDC_MINT,
tokenProgram: TOKEN_PROGRAM_ADDRESS,
});
const [nonceTombstone] = await getProgramDerivedAddress({
programAddress: DVP_SWAP_PROGRAM_PROGRAM_ADDRESS,
seeds: ["nonce", getAddressEncoder().encode(record)],
});
const signature = await send(agent, [
getCreateDvpInstruction({
payer: agent,
swapDvp: record,
nonceTombstone,
...seeds,
dvpAtaA: escrowA,
dvpAtaB: escrowB,
tokenProgramA: TOKEN_2022_PROGRAM_ADDRESS,
tokenProgramB: TOKEN_PROGRAM_ADDRESS,
amountA: terms.assetAmount,
amountB: terms.cashAmount,
expiryTimestamp: BigInt(Math.floor(Date.now() / 1000) + 24 * 60 * 60),
refString: "LSF-TRADE-0001",
userASettlementDestination: null, // proceeds go to the seller
userBSettlementDestination: null, // the asset goes to the buyer
earliestSettlementTimestamp: null,
}),
]);
const trade: Trade = { ...terms, record, escrowA, escrowB };
console.log("Trade record:", record);
console.log(" asset leg:", units(terms.assetAmount), "LSF, escrow", escrowA);
console.log(" cash leg:", units(terms.cashAmount), "USDC, escrow", escrowB);
await verifyTrade(trade);
console.log("Record checked: owner, size, address and terms match");
console.log("Signature:", signature);
return { trade, signature };
}
/** Check the record is the DvP program's and holds exactly the agreed terms. */
export async function verifyTrade(trade: Trade) {
// Owner, size and address checks; throws on a forged record.
const { data } = await verifySwapDvp(rpc, trade.record);
const expected = {
userA: trade.seller,
userB: trade.buyer,
settlementAuthority: trade.agent,
mintA: trade.asset,
mintB: USDC_MINT,
amountA: trade.assetAmount,
amountB: trade.cashAmount,
userASettlementDestination: trade.seller,
userBSettlementDestination: trade.buyer,
};
for (const [field, value] of Object.entries(expected))
if (data[field as keyof typeof expected] !== value)
throw new Error(`trade record ${field} does not match the agreed terms`);
return data;
}
/**
* The asset's accounts start frozen (Issue an asset), and so does the trade's
* new escrow. The issuer approves the escrow the same way it approves a holder.
*/
export async function approveEscrow(issuer: TransactionSigner, trade: Trade) {
const signature = await send(issuer, [
getThawAccountInstruction({
account: trade.escrowA,
mint: trade.asset,
owner: issuer,
}),
]);
console.log(
"Issuer approved the LSF escrow for the trade. Signature:",
signature,
);
return signature;
}
/** Each party funds its leg with an ordinary transfer into the escrow. */
export async function fundAssetLeg(seller: TransactionSigner, trade: Trade) {
const signature = await send(seller, [
getTransferCheckedInstruction({
source: await ataOf(
seller.address,
trade.asset,
TOKEN_2022_PROGRAM_ADDRESS,
),
mint: trade.asset,
destination: trade.escrowA,
authority: seller,
amount: trade.assetAmount,
decimals: 6,
}),
]);
console.log("Seller funded the asset leg. Signature:", signature);
return signature;
}
export async function fundCashLeg(buyer: TransactionSigner, trade: Trade) {
const signature = await send(buyer, [
getUsdcTransferInstruction({
source: await ataOf(buyer.address, USDC_MINT, TOKEN_PROGRAM_ADDRESS),
mint: USDC_MINT,
destination: trade.escrowB,
authority: buyer,
amount: trade.cashAmount,
decimals: 6,
}),
]);
console.log("Buyer funded the cash leg. Signature:", signature);
return signature;
}
/**
* SettleDvp moves both legs in one transaction: the asset to the buyer, the
* USDC to the seller. If either escrow holds less than its agreed amount it
* fails with LegNotFunded (custom error 4) and nothing moves.
*/
export async function settle(
agent: TransactionSigner,
trade: Trade,
options: { skipPreflight?: boolean } = {},
): Promise<Signature> {
await verifyTrade(trade);
const T22 = TOKEN_2022_PROGRAM_ADDRESS;
const T = TOKEN_PROGRAM_ADDRESS;
// The four accounts SettleDvp writes to: each side's proceeds, and each
// side's own account for any surplus in its escrow.
const accounts = {
userADestinationAtaB: [trade.seller, USDC_MINT, T],
userBDestinationAtaA: [trade.buyer, trade.asset, T22],
userAAtaA: [trade.seller, trade.asset, T22],
userBAtaB: [trade.buyer, USDC_MINT, T],
} as const;
const ata = {} as Record<keyof typeof accounts, Address>;
const createAccounts = [];
for (const [name, [owner, mint, tokenProgram]] of Object.entries(accounts)) {
ata[name as keyof typeof accounts] = await ataOf(owner, mint, tokenProgram);
createAccounts.push(
getCreateAssociatedTokenIdempotentInstruction({
payer: agent,
ata: ata[name as keyof typeof accounts],
owner,
mint,
tokenProgram,
}),
);
}
const signature = await send(
agent,
[
...createAccounts,
getSettleDvpInstruction({
settlementAuthority: agent,
swapDvp: trade.record,
mintA: trade.asset,
mintB: USDC_MINT,
dvpAtaA: trade.escrowA,
dvpAtaB: trade.escrowB,
...ata,
tokenProgramA: T22,
tokenProgramB: T,
memoProgram: MEMO_PROGRAM_ADDRESS,
legAExtrasCount: 0, // no transfer hooks on either mint
}),
],
options,
);
console.log("Settled both legs in one transaction. Signature:", signature);
const [buyerLsf, buyerUsdc, sellerLsf, sellerUsdc] = await Promise.all([
holding(trade.buyer, trade.asset),
holding(trade.buyer, USDC_MINT),
holding(trade.seller, trade.asset),
holding(trade.seller, USDC_MINT),
]);
console.log(
`Balances: buyer ${units(buyerLsf)} LSF, ${units(buyerUsdc)} USDC |`,
`seller ${units(sellerLsf)} LSF, ${units(sellerUsdc)} USDC`,
);
const closed = !(await rpc.getAccountInfo(trade.record).send()).value;
console.log("Trade record and escrows closed:", closed);
return signature;
}
/** Token balance of an account, or 0 when it doesn't exist (yet, or any more). */
export async function balance(account: Address) {
const info = await rpc.getAccountInfo(account, { encoding: "base64" }).send();
if (!info.value) return 0n;
const { value } = await rpc.getTokenAccountBalance(account).send();
return BigInt(value.amount);
}
export async function holding(owner: Address, mint: Address) {
const tokenProgram =
mint === USDC_MINT ? TOKEN_PROGRAM_ADDRESS : TOKEN_2022_PROGRAM_ADDRESS;
return balance(await ataOf(owner, mint, tokenProgram));
}
/**
* Settle while a leg is still unfunded, with skipPreflight so the failed
* transaction lands onchain and you can read its error, log and fee.
*/
export async function settleUnfunded(agent: TransactionSigner, trade: Trade) {
try {
await settle(agent, trade, { skipPreflight: true });
throw new Error("expected settle to fail");
} catch (error) {
const signature = (error as { signature?: Signature }).signature;
if (!signature) throw error;
const { err, fee } = await failure(signature);
// err is {"InstructionError":[<instruction index>,{"Custom":<code>}]}
const [instruction, { Custom }] = (
err as { InstructionError: [number, { Custom: number }] }
).InstructionError;
const code = Number(Custom) as DvpSwapProgramError;
const message = getDvpSwapProgramErrorMessage(code);
console.log(
"Settle with the cash leg unfunded (skipPreflight): failed onchain",
);
console.log("Failed signature:", signature);
console.log(
" err:",
JSON.stringify(err, (_k, v) => (typeof v === "bigint" ? Number(v) : v)),
);
console.log(` DvP error ${code}:`, message);
console.log(" fee paid anyway:", String(fee), "lamports");
const [escrowA, escrowB, buyerLsf, sellerUsdc] = await Promise.all([
balance(trade.escrowA),
balance(trade.escrowB),
holding(trade.buyer, trade.asset),
holding(trade.seller, USDC_MINT),
]);
console.log(
`Nothing moved: asset escrow ${units(escrowA)} LSF | cash escrow`,
`${units(escrowB)} USDC | buyer ${units(buyerLsf)} LSF | seller`,
`${units(sellerUsdc)} USDC`,
);
return {
signature,
err,
fee,
instruction,
code,
message,
after: { escrowA, escrowB, buyerLsf, sellerUsdc },
};
}
}