Cartouche.Solana.Token (Cartouche v0.1.0)

Copy Markdown View Source

High-level token operations for Solana: balance queries, transfers, and ATA management.

Combines RPC calls with PDA derivation and instruction building. Analogous to Cartouche.Erc20 on the Ethereum side.

Examples

# Get USDC balance for a wallet
{:ok, balance} = Cartouche.Solana.Token.get_balance(wallet, usdc_mint)

# Get all token balances
{:ok, balances} = Cartouche.Solana.Token.get_all_balances(wallet)

# Build transfer instructions (includes ATA creation if needed)
instructions = Cartouche.Solana.Token.transfer_instructions(
  from_wallet, to_wallet, mint, 1_000_000, 6
)

Summary

Functions

Get all token balances for a wallet.

Get the balance of a specific token for a wallet.

Build instructions for a token transfer between wallets.

Functions

get_all_balances(wallet, opts \\ [])

@spec get_all_balances(
  <<_::256>>,
  keyword()
) ::
  {:ok,
   [
     %{
       mint: String.t(),
       amount: non_neg_integer(),
       decimals: non_neg_integer(),
       token_account: String.t()
     }
   ]}
  | {:error, term()}

Get all token balances for a wallet.

Queries both SPL Token Program and Token-2022 by default.

Options

  • :include_token_2022 - also query Token-2022 (default: true)

get_balance(wallet, mint, opts \\ [])

@spec get_balance(<<_::256>>, <<_::256>>, keyword()) ::
  {:ok,
   %{amount: non_neg_integer(), decimals: non_neg_integer(), mint: String.t()}}
  | {:error, term()}

Get the balance of a specific token for a wallet.

Uses getTokenAccountsByOwner with a mint filter and jsonParsed encoding. Sums across all token accounts for the mint (usually just the ATA, but handles edge cases with multiple accounts).

Returns the raw integer amount, decimals, and mint address.

transfer_instructions(from_wallet, to_wallet, mint, amount, decimals, opts \\ [])

@spec transfer_instructions(
  <<_::256>>,
  <<_::256>>,
  <<_::256>>,
  non_neg_integer(),
  non_neg_integer(),
  keyword()
) :: [Cartouche.Solana.Transaction.Instruction.t()]

Build instructions for a token transfer between wallets.

Handles ATA derivation for both source and destination. Includes an idempotent ATA creation for the destination (no-op if it already exists). Uses transfer_checked for safety.

Returns a list of instructions suitable for Transaction.build_message/3.

Options

  • :token_program - Override the token program (default: SPL Token Program).