Skip to content

locallaunchsc-cloud/solana-dev-skills / squads-multisig

solana-squads-multisig

Verified

Use this skill when the user wants to set up a Squads V4 multisig on Solana — create the multisig, manage members and threshold, propose transactions, approve, and execute. Standard for team treasuries and program upgrade authority.

FileKindSize
SKILL.mdskill md13.6 KB
scripts/create-multisig.tsscript9.0 KB
scripts/propose-and-execute.tsscript10.5 KB

scripts/propose-and-execute.ts

View on GitHub
/**
 * propose-and-execute.ts
 *
 * Runs the full proposal lifecycle against an already-created Squads V4
 * multisig on devnet:
 *
 *   1. Read the multisig's current transactionIndex and bump by 1.
 *   2. Build a TransactionMessage where the vault PDA is the payer + signer.
 *   3. vaultTransactionCreate    — store the proposed message on-chain
 *   4. proposalCreate            — open it for voting
 *   5. proposalApprove (member 1) — first vote
 *   6. proposalApprove (member 2) — second vote, hits 2-of-3 threshold
 *   7. vaultTransactionExecute   — the vault PDA signs the inner transfer
 *
 * Usage:
 *   npx ts-node scripts/propose-and-execute.ts
 *
 * Reads the multisig PDA from $SQUADS_MULTISIG_PDA, or from the
 * ./.demo-keys/multisig.json file written by create-multisig.ts.
 *
 * Loads member 2's keypair from ./.demo-keys/member2.json (also written by
 * create-multisig.ts). In production each member runs this approve step from
 * their own machine — you never centralize signing keys.
 */

import * as multisig from "@sqds/multisig";
import {
  Connection,
  Keypair,
  LAMPORTS_PER_SOL,
  PublicKey,
  SystemProgram,
  TransactionMessage,
} from "@solana/web3.js";
import { readFileSync, existsSync } from "fs";
import path from "path";
import os from "os";

// ---------------------------------------------------------------------------
// Config
// ---------------------------------------------------------------------------
const RPC_URL = process.env.RPC_URL ?? "https://api.devnet.solana.com";
const KEYPAIR_PATH =
  process.env.KEYPAIR_PATH ??
  path.join(os.homedir(), ".config", "solana", "id.json");

const DEMO_KEYS_DIR = path.join(process.cwd(), ".demo-keys");

// How much SOL the proposal will move out of the vault.
const TRANSFER_LAMPORTS = 0.01 * LAMPORTS_PER_SOL;

// ---------------------------------------------------------------------------

function loadKeypair(p: string): Keypair {
  const secret = JSON.parse(readFileSync(p, "utf8")) as number[];
  return Keypair.fromSecretKey(Uint8Array.from(secret));
}

function resolveMultisigPda(): PublicKey {
  if (process.env.SQUADS_MULTISIG_PDA) {
    return new PublicKey(process.env.SQUADS_MULTISIG_PDA);
  }
  const f = path.join(DEMO_KEYS_DIR, "multisig.json");
  if (existsSync(f)) {
    const { multisigPda } = JSON.parse(readFileSync(f, "utf8")) as {
      multisigPda: string;
    };
    return new PublicKey(multisigPda);
  }
  throw new Error(
    "No multisig PDA found. Either run scripts/create-multisig.ts first " +
      "or set SQUADS_MULTISIG_PDA=<pubkey>."
  );
}

async function main() {
  const connection = new Connection(RPC_URL, "confirmed");

  // member 1 = creator (paying fees and casting first vote)
  const member1 = loadKeypair(KEYPAIR_PATH);
  // member 2 was generated by create-multisig.ts and persisted to disk
  const member2Path = path.join(DEMO_KEYS_DIR, "member2.json");
  if (!existsSync(member2Path)) {
    throw new Error(
      `member 2 keypair not found at ${member2Path}. ` +
        `Run scripts/create-multisig.ts first to generate it.`
    );
  }
  const member2 = loadKeypair(member2Path);

  const multisigPda = resolveMultisigPda();
  const [vaultPda] = multisig.getVaultPda({ multisigPda, index: 0 });

  console.log("multisig PDA:", multisigPda.toBase58());
  console.log("vault PDA   :", vaultPda.toBase58());
  console.log("member 1    :", member1.publicKey.toBase58());
  console.log("member 2    :", member2.publicKey.toBase58());

  // -------------------------------------------------------------------------
  // Sanity: vault must have SOL to send. create-multisig.ts seeded 0.1 SOL.
  // -------------------------------------------------------------------------
  const vaultBalance = await connection.getBalance(vaultPda);
  console.log(`vault balance before: ${vaultBalance / LAMPORTS_PER_SOL} SOL`);
  if (vaultBalance < TRANSFER_LAMPORTS) {
    throw new Error(
      `vault has only ${vaultBalance} lamports; need at least ${TRANSFER_LAMPORTS}.`
    );
  }

  // -------------------------------------------------------------------------
  // 1. Read the multisig's current transactionIndex and bump by 1.
  //    Squads tracks a monotonic index; every new vault transaction uses the
  //    next integer. NEVER hardcode this — only `1n` is valid on a brand new
  //    multisig.
  // -------------------------------------------------------------------------
  const multisigAccount =
    await multisig.accounts.Multisig.fromAccountAddress(
      connection,
      multisigPda
    );
  const newTransactionIndex = BigInt(
    Number(multisigAccount.transactionIndex) + 1
  );
  console.log("new transactionIndex:", newTransactionIndex.toString());

  // -------------------------------------------------------------------------
  // 2. Build the TransactionMessage that the vault will sign.
  //    Key point: payerKey AND fromPubkey are the vault PDA, not the caller.
  //    The vault PDA cannot sign in userspace — Squads' on-chain program
  //    invokes the CPI with the vault as a signer during vaultTransactionExecute.
  // -------------------------------------------------------------------------
  const transferIx = SystemProgram.transfer({
    fromPubkey: vaultPda,
    toPubkey: member1.publicKey, // send the SOL back to member1 for the demo
    lamports: TRANSFER_LAMPORTS,
  });

  const transferMessage = new TransactionMessage({
    payerKey: vaultPda,
    recentBlockhash: (await connection.getLatestBlockhash("confirmed"))
      .blockhash,
    instructions: [transferIx],
  });

  // -------------------------------------------------------------------------
  // 3. vaultTransactionCreate — store the proposed message on-chain.
  //    `vaultIndex` MUST match the index you used to derive vaultPda (0 here).
  //    `ephemeralSigners` is 0 unless your inner instructions need extra
  //    program-derived signers (e.g. for token account creation).
  // -------------------------------------------------------------------------
  console.log("[1/4] vaultTransactionCreate...");
  const createSig = await multisig.rpc.vaultTransactionCreate({
    connection,
    feePayer: member1,
    multisigPda,
    transactionIndex: newTransactionIndex,
    creator: member1.publicKey,
    vaultIndex: 0,
    ephemeralSigners: 0,
    transactionMessage: transferMessage,
    memo: `transfer ${TRANSFER_LAMPORTS} lamports out of vault 0`,
  });
  await connection.confirmTransaction(
    { signature: createSig, ...(await connection.getLatestBlockhash("confirmed")) },
    "confirmed"
  );
  console.log("       sig:", createSig);

  // -------------------------------------------------------------------------
  // 4. proposalCreate — opens voting on the transaction we just stored.
  //    Separate call (the SDK splits create vs. propose so you can build
  //    drafts / batches). Skipping this is the #1 source of cryptic
  //    "proposal not found" errors at the approve step.
  // -------------------------------------------------------------------------
  console.log("[2/4] proposalCreate...");
  const proposeSig = await multisig.rpc.proposalCreate({
    connection,
    feePayer: member1,
    multisigPda,
    transactionIndex: newTransactionIndex,
    creator: member1,
  });
  await connection.confirmTransaction(
    { signature: proposeSig, ...(await connection.getLatestBlockhash("confirmed")) },
    "confirmed"
  );
  console.log("       sig:", proposeSig);

  // -------------------------------------------------------------------------
  // 5+6. Two approvals to hit the 2-of-3 threshold.
  //    In production each call happens on the respective member's own
  //    machine, signed by their own keypair. Here we do both back-to-back
  //    because it's a demo.
  // -------------------------------------------------------------------------
  console.log("[3/4] proposalApprove (member 1)...");
  const approve1Sig = await multisig.rpc.proposalApprove({
    connection,
    feePayer: member1,
    multisigPda,
    transactionIndex: newTransactionIndex,
    member: member1,
  });
  await connection.confirmTransaction(
    { signature: approve1Sig, ...(await connection.getLatestBlockhash("confirmed")) },
    "confirmed"
  );
  console.log("       sig:", approve1Sig);

  console.log("[3/4] proposalApprove (member 2)...");
  const approve2Sig = await multisig.rpc.proposalApprove({
    connection,
    feePayer: member1, // member1 pays fees; member2 just signs the vote
    multisigPda,
    transactionIndex: newTransactionIndex,
    member: member2,
  });
  await connection.confirmTransaction(
    { signature: approve2Sig, ...(await connection.getLatestBlockhash("confirmed")) },
    "confirmed"
  );
  console.log("       sig:", approve2Sig);

  // -------------------------------------------------------------------------
  // 7. vaultTransactionExecute — any member with Permission.Execute can fire
  //    this once the proposal is Approved. The vault PDA signs the inner
  //    CPI via the on-chain program; we don't sign for it here.
  //
  //    skipPreflight is on because Squads CPIs frequently confuse the
  //    simulator into reporting false errors. Trust the on-chain result.
  // -------------------------------------------------------------------------
  console.log("[4/4] vaultTransactionExecute...");
  const executeSig = await multisig.rpc.vaultTransactionExecute({
    connection,
    feePayer: member1,
    multisigPda,
    transactionIndex: newTransactionIndex,
    member: member1.publicKey,
    signers: [member1],
    sendOptions: { skipPreflight: true },
  });
  await connection.confirmTransaction(
    { signature: executeSig, ...(await connection.getLatestBlockhash("confirmed")) },
    "confirmed"
  );
  console.log("       sig:", executeSig);

  // -------------------------------------------------------------------------
  // Final state
  // -------------------------------------------------------------------------
  const vaultBalanceAfter = await connection.getBalance(vaultPda);
  const refreshedMultisig =
    await multisig.accounts.Multisig.fromAccountAddress(
      connection,
      multisigPda
    );

  console.log("\n========================================");
  console.log("DONE.");
  console.log("========================================");
  console.log(`vault balance before: ${vaultBalance / LAMPORTS_PER_SOL} SOL`);
  console.log(
    `vault balance after : ${vaultBalanceAfter / LAMPORTS_PER_SOL} SOL`
  );
  console.log(
    `transactionIndex    : ${refreshedMultisig.transactionIndex.toString()}`
  );
  console.log(
    `view on explorer    : https://explorer.solana.com/tx/${executeSig}?cluster=devnet`
  );
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 322kUpdated Claude CodeCodexVerifiedInstall