Solana wallets in your game

A game you upload to indie.fun runs in a sandboxed frame, where wallet extensions like Phantom cannot reach it. Ask the indie.fun page around your game instead: it talks to the player's wallet and passes the answers back.

Why your wallet code needs a change

indie.fun runs an uploaded build inside a sandboxed iframe with no origin of its own (its origin is null). That keeps the player's indie.fun account safe from code that is not ours, but wallet extensions do not serve a page like that: window.phantom and window.solana are missing or refuse to connect. So connect(), signMessage() and signTransaction() fail inside your game.

The page around your game is indie.fun, and the wallet works there. Your game posts a request to its parent page, the player approves it, the wallet signs, and the answer comes back to your game. This is the wallet bridge. It works with Phantom, Solflare, Backpack and any wallet that injects a Solana provider. Only games uploaded as a build use it.

1

Paste the helper into your game

This is the whole client side. It sends a request to the parent page and resolves with the answer.

// indieWallet.js
const indieWallet = (() => {
  const inFrame = window.parent !== window;
  const pending = new Map();
  const listeners = new Set();
  let next = 0;

  window.addEventListener('message', (event) => {
    if (event.source !== window.parent) return;
    const msg = event.data;
    if (msg?.type === 'indiefun:wallet:result' && pending.has(msg.id)) {
      const { resolve, reject } = pending.get(msg.id);
      pending.delete(msg.id);
      if (msg.error) {
        const err = new Error(msg.error.message);
        err.code = msg.error.code;
        reject(err);
      } else {
        resolve(msg.result);
      }
    } else if (msg?.type === 'indiefun:wallet:event') {
      listeners.forEach((fn) => fn(msg));
    }
  });

  function request(method, params = {}) {
    return new Promise((resolve, reject) => {
      if (!inFrame) return reject(new Error('Not running inside indie.fun'));
      const id = 'w' + ++next;
      pending.set(id, { resolve, reject });
      window.parent.postMessage({ type: 'indiefun:wallet', id, method, params }, '*');
    });
  }

  const toBase64 = (bytes) => btoa(String.fromCharCode(...bytes));
  const fromBase64 = (b64) => Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));

  return {
    inFrame,
    available: () => request('available'),
    connect: (opts = {}) => request('connect', opts),
    disconnect: () => request('disconnect'),
    // message: a string. Resolves { signature, signedMessage, publicKey }.
    signMessage: (message) =>
      request('signMessage', { message: toBase64(new TextEncoder().encode(message)) }),
    // tx: a @solana/web3.js Transaction or VersionedTransaction, unsigned by the player.
    // Resolves to the signed transaction's bytes; send them yourself.
    signTransaction: async (tx) => {
      const bytes = tx.serialize({ requireAllSignatures: false, verifySignatures: false });
      const { transaction } = await request('signTransaction', { transaction: toBase64(bytes) });
      return fromBase64(transaction);
    },
    onAccountChanged: (fn) => listeners.add((m) => m.event === 'accountChanged' && fn(m.publicKey)),
  };
})();

A VersionedTransaction's serialize() takes no options, so call it plainly for one of those. When your game runs anywhere other than indie.fun (your own site, local development), indieWallet.inFrame is false: use the wallet directly there, as you do today.

2

Connect, sign, send

// A returning player who connected this game before: no prompt.
let address = null;
try {
  ({ publicKey: address } = await indieWallet.connect({ onlyIfTrusted: true }));
} catch {
  // Not connected yet. Show your "Connect wallet" button.
}

// From your Connect button:
const { publicKey } = await indieWallet.connect();

// Log in: sign your server's challenge, send the answer to your server.
const nonce = await fetch('https://your-server.example/auth/nonce').then((r) => r.text());
const signed = await indieWallet.signMessage(`Log in to My Game\nNonce: ${nonce}`);
await fetch('https://your-server.example/auth/verify', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ nonce, ...signed }),
});

// A transaction: build it, have it signed, send it yourself.
const signedBytes = await indieWallet.signTransaction(tx);
const sig = await connection.sendRawTransaction(signedBytes);

indieWallet.onAccountChanged((address) => {
  // The player switched account in their wallet, or disconnected it (null).
});
3

Verify a signed message on your server

The wallet signs your message with a header in front of it, naming your game, so the player can see in their wallet which game is asking. The answer carries the exact bytes that were signed as signedMessage. It looks like this:

Message from the game "My Game".
Game address: indie.fun/play/my-game
The game wrote the text below, not indie.fun. Signing it is not a transaction.

Log in to My Game
Nonce: 8f3c...

On your server, check three things: the Game address line is exactly your game's address, everything after the first blank line is exactly the message you asked for, and the signature over signedMessage is valid for the wallet you expect.

// Node, with tweetnacl and bs58 (any ed25519 library works).
import nacl from 'tweetnacl';
import bs58 from 'bs58';

const GAME_ADDRESS = 'Game address: indie.fun/play/my-game'; // your slug

function verifyIndieSignature({ publicKey, signature, signedMessage }, expectedMessage, expectedWallet) {
  if (publicKey !== expectedWallet) return false;
  const bytes = Buffer.from(signedMessage, 'base64');
  const text = bytes.toString('utf8');
  const split = text.indexOf('\n\n');
  if (split < 0) return false;
  const header = text.slice(0, split).split('\n');
  if (!header[0].startsWith('Message from the game ')) return false;
  if (header[1] !== GAME_ADDRESS) return false;
  if (text.slice(split + 2) !== expectedMessage) return false;
  return nacl.sign.detached.verify(bytes, bs58.decode(signature), bs58.decode(publicKey));
}

Check the address line, not just the end

Another game can ask a player to sign your exact message too, under its own header. The Game address line is what says the signature was made for your game, so a check that only looks at the end of the text accepts signatures other games collected. If you change your game's address in Settings, change it on your server as well. The title on the first line is for the player and may change; do not check it.

The protocol

The helper above is all of this. If you would rather write your own, these are the messages.

Requests, game to page

{ type: 'indiefun:wallet', id, method, params }Post to window.parent with target '*'. id is a string (up to 128 characters) or a number, and comes back on the answer.

Methods

availableThe wallets installed, e.g. ['Phantom']. An empty list means none.
connect { onlyIfTrusted?, wallet? }Returns { publicKey } (base58). The wallet asks the player, unless it already trusts indie.fun. onlyIfTrusted answers silently, only with the wallet the player connected this game with before in this browser; otherwise it fails with 4001. wallet picks one of the names from available.
signMessage { message }message is base64 of UTF-8 text, up to 2,048 bytes. Returns { signature (base58), signedMessage (base64 of the exact bytes signed, header included), publicKey (the wallet that signed) }.
signTransaction { transaction }transaction is base64 of a serialized transaction, legacy or v0. Returns { transaction }, base64, with the player's signature added. Your game sends it.
disconnectReturns null. The game loses access until the next connect, and onlyIfTrusted stops working for it. The player's wallet stays connected to indie.fun.

Answers and events, page to game

{ type: 'indiefun:wallet:result', id, result }It worked.
{ type: 'indiefun:wallet:result', id, error: { message, code } }It did not.
{ type: 'indiefun:wallet:event', event: 'accountChanged', publicKey }The player switched account in their wallet, or it disconnected (publicKey is null). Sent only while your game is connected.

Error codes:

4001
The player said no in their wallet.
4100
Not connected. Call connect first.
4200
Unknown method, a wallet that cannot do this, or a transaction indie.fun will not sign (below).
4900
No Solana wallet is installed.
-32002
Another request is still waiting on the player. Wait for it to finish.
-32602
The params are wrong: not base64, not text, too long, or not a transaction.
-32603
The wallet failed for its own reason. The message says what it said.

What the player sees

Each request opens the player's wallet, which names indie.fun as the site asking, because your game runs inside indie.fun. A signed message carries your game's name in its header, so the player can see which game it is for.

A wallet the player has already connected to indie.fun may answer connect without opening at all. Ask for the connection when the player presses your Connect button, so it never happens without them asking.

If your game reloads or navigates its own page, the connection ends and anything still waiting is dropped. Connect again after a load (onlyIfTrusted makes that silent for a returning player).

What is refused

Bytes that are not text
signMessage takes UTF-8 text without control characters (newlines and tabs are fine). A player can read text in their wallet; raw bytes would be a signature over something nobody read.
Transactions that call the indie.fun launch program
Backing, refunding and claiming a token raise happen on indie.fun’s own pages. A transaction whose instructions call that program is refused.
Sending
The bridge signs and hands the transaction back. Your game sends it with its own RPC, so you choose the network and the fees.