2517 lines
157 KiB
HTML
2517 lines
157 KiB
HTML
<!DOCTYPE HTML>
|
||
<html lang="en" class="sidebar-visible no-js light">
|
||
<head>
|
||
<!-- Book generated using mdBook -->
|
||
<meta charset="UTF-8">
|
||
<title>The Anchor Book v0.29.0</title>
|
||
<meta name="robots" content="noindex" />
|
||
<!-- Custom HTML head -->
|
||
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
|
||
<meta name="description" content="">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||
<meta name="theme-color" content="#ffffff" />
|
||
|
||
<link rel="icon" href="favicon.svg">
|
||
<link rel="shortcut icon" href="favicon.png">
|
||
<link rel="stylesheet" href="css/variables.css">
|
||
<link rel="stylesheet" href="css/general.css">
|
||
<link rel="stylesheet" href="css/chrome.css">
|
||
<link rel="stylesheet" href="css/print.css" media="print">
|
||
<!-- Fonts -->
|
||
<link rel="stylesheet" href="FontAwesome/css/font-awesome.css">
|
||
<link rel="stylesheet" href="fonts/fonts.css">
|
||
<!-- Highlight.js Stylesheets -->
|
||
<link rel="stylesheet" href="highlight.css">
|
||
<link rel="stylesheet" href="tomorrow-night.css">
|
||
<link rel="stylesheet" href="ayu-highlight.css">
|
||
|
||
<!-- Custom theme stylesheets -->
|
||
</head>
|
||
<body>
|
||
<!-- Provide site root to javascript -->
|
||
<script type="text/javascript">
|
||
var path_to_root = "";
|
||
var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
|
||
</script>
|
||
|
||
<!-- Work around some values being stored in localStorage wrapped in quotes -->
|
||
<script type="text/javascript">
|
||
try {
|
||
var theme = localStorage.getItem('mdbook-theme');
|
||
var sidebar = localStorage.getItem('mdbook-sidebar');
|
||
|
||
if (theme.startsWith('"') && theme.endsWith('"')) {
|
||
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
|
||
}
|
||
|
||
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
|
||
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
|
||
}
|
||
} catch (e) { }
|
||
</script>
|
||
|
||
<!-- Set the theme before any content is loaded, prevents flash -->
|
||
<script type="text/javascript">
|
||
var theme;
|
||
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
|
||
if (theme === null || theme === undefined) { theme = default_theme; }
|
||
var html = document.querySelector('html');
|
||
html.classList.remove('no-js')
|
||
html.classList.remove('light')
|
||
html.classList.add(theme);
|
||
html.classList.add('js');
|
||
</script>
|
||
|
||
<!-- Hide / unhide sidebar before it is displayed -->
|
||
<script type="text/javascript">
|
||
var html = document.querySelector('html');
|
||
var sidebar = 'hidden';
|
||
if (document.body.clientWidth >= 1080) {
|
||
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
|
||
sidebar = sidebar || 'visible';
|
||
}
|
||
html.classList.remove('sidebar-visible');
|
||
html.classList.add("sidebar-" + sidebar);
|
||
</script>
|
||
|
||
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
|
||
<div class="sidebar-scrollbox">
|
||
<ol class="chapter"><li class="chapter-item expanded "><a href="introduction/introduction.html"><strong aria-hidden="true">1.</strong> Introduction</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="introduction/what_is_anchor.html"><strong aria-hidden="true">1.1.</strong> What is Anchor</a></li><li class="chapter-item expanded "><a href="introduction/anchor_documentation.html"><strong aria-hidden="true">1.2.</strong> Anchor Documentation</a></li></ol></li><li class="chapter-item expanded "><a href="prerequisites/prerequisites.html"><strong aria-hidden="true">2.</strong> Prerequisites</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="prerequisites/useful_resources.html"><strong aria-hidden="true">2.1.</strong> Useful Resources</a></li><li class="chapter-item expanded "><a href="prerequisites/intro_to_solana.html"><strong aria-hidden="true">2.2.</strong> Intro to Solana</a></li></ol></li><li class="chapter-item expanded "><a href="getting_started/getting_started.html"><strong aria-hidden="true">3.</strong> Getting Started</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="getting_started/installation.html"><strong aria-hidden="true">3.1.</strong> Installation</a></li><li class="chapter-item expanded "><a href="getting_started/hello_anchor.html"><strong aria-hidden="true">3.2.</strong> Hello, Anchor!</a></li></ol></li><li class="chapter-item expanded "><a href="anchor_in_depth/anchor_programs_in-depth.html"><strong aria-hidden="true">4.</strong> Anchor Programs In-Depth</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="anchor_in_depth/essentials.html"><strong aria-hidden="true">4.1.</strong> Essentials</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="anchor_in_depth/high-level_overview.html"><strong aria-hidden="true">4.1.1.</strong> High-level Overview</a></li><li class="chapter-item expanded "><a href="anchor_in_depth/the_accounts_struct.html"><strong aria-hidden="true">4.1.2.</strong> The Accounts Struct</a></li><li class="chapter-item expanded "><a href="anchor_in_depth/the_program_module.html"><strong aria-hidden="true">4.1.3.</strong> The Program Module</a></li><li class="chapter-item expanded "><a href="anchor_in_depth/errors.html"><strong aria-hidden="true">4.1.4.</strong> Errors</a></li><li class="chapter-item expanded "><a href="anchor_in_depth/milestone_project_tic-tac-toe.html"><strong aria-hidden="true">4.1.5.</strong> Milestone Project - Tic-Tac-Toe</a></li></ol></li><li class="chapter-item expanded "><a href="anchor_in_depth/intermediate.html"><strong aria-hidden="true">4.2.</strong> Intermediate</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="anchor_in_depth/CPIs.html"><strong aria-hidden="true">4.2.1.</strong> Cross-Program Invocations</a></li><li class="chapter-item expanded "><a href="anchor_in_depth/PDAs.html"><strong aria-hidden="true">4.2.2.</strong> PDAs</a></li><li class="chapter-item expanded "><a href="anchor_in_depth/events.html"><strong aria-hidden="true">4.2.3.</strong> Events</a></li><li class="chapter-item expanded "><div><strong aria-hidden="true">4.2.4.</strong> Constants</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">4.2.5.</strong> Zero-Copy</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">4.2.6.</strong> Access Control</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">4.2.7.</strong> Building & Testing</div></li><li class="chapter-item expanded "><div><strong aria-hidden="true">4.2.8.</strong> Milestone Project - The Nightclub</div></li></ol></li></ol></li><li class="chapter-item expanded "><div><strong aria-hidden="true">5.</strong> Anchor BTS</div></li><li><ol class="section"><li class="chapter-item expanded "><a href="anchor_bts/discriminator.html"><strong aria-hidden="true">5.1.</strong> The Discriminator</a></li><li class="chapter-item expanded "><div><strong aria-hidden="true">5.2.</strong> Dispatch</div></li><li class="spacer"></li></ol></li><li class="chapter-item expanded "><a href="anchor_references/anchor_references.html"><strong aria-hidden="true">6.</strong> Anchor References</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="anchor_references/space.html"><strong aria-hidden="true">6.1.</strong> Space Reference</a></li><li class="chapter-item expanded "><a href="anchor_references/javascript_anchor_types_reference.html"><strong aria-hidden="true">6.2.</strong> Javascript Anchor Types Reference</a></li><li class="chapter-item expanded "><a href="anchor_references/cli.html"><strong aria-hidden="true">6.3.</strong> CLI Reference</a></li><li class="chapter-item expanded "><a href="anchor_references/avm.html"><strong aria-hidden="true">6.4.</strong> AVM Reference</a></li><li class="chapter-item expanded "><a href="anchor_references/anchor-toml_reference.html"><strong aria-hidden="true">6.5.</strong> Anchor.toml Reference</a></li><li class="chapter-item expanded "><a href="anchor_references/reference_links.html"><strong aria-hidden="true">6.6.</strong> Code References</a></li></ol></li></ol>
|
||
</div>
|
||
<div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
|
||
</nav>
|
||
|
||
<div id="page-wrapper" class="page-wrapper">
|
||
|
||
<div class="page">
|
||
<div id="menu-bar-hover-placeholder"></div>
|
||
<div id="menu-bar" class="menu-bar sticky bordered">
|
||
<div class="left-buttons">
|
||
<button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
|
||
<i class="fa fa-bars"></i>
|
||
</button>
|
||
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
|
||
<i class="fa fa-paint-brush"></i>
|
||
</button>
|
||
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
|
||
<li role="none"><button role="menuitem" class="theme" id="light">Light (default)</button></li>
|
||
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
|
||
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
|
||
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
|
||
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
|
||
</ul>
|
||
<button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
|
||
<i class="fa fa-search"></i>
|
||
</button>
|
||
</div>
|
||
|
||
<h1 class="menu-title">The Anchor Book v0.29.0</h1>
|
||
|
||
<div class="right-buttons">
|
||
<a href="print.html" title="Print this book" aria-label="Print this book">
|
||
<i id="print-button" class="fa fa-print"></i>
|
||
</a>
|
||
</div>
|
||
</div>
|
||
|
||
<div id="search-wrapper" class="hidden">
|
||
<form id="searchbar-outer" class="searchbar-outer">
|
||
<input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
|
||
</form>
|
||
<div id="searchresults-outer" class="searchresults-outer hidden">
|
||
<div id="searchresults-header" class="searchresults-header"></div>
|
||
<ul id="searchresults">
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
|
||
<script type="text/javascript">
|
||
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
|
||
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
|
||
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
|
||
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
|
||
});
|
||
</script>
|
||
|
||
<div id="content" class="content">
|
||
<main>
|
||
<h1 id="introduction"><a class="header" href="#introduction">Introduction</a></h1>
|
||
<p>Welcome to The Anchor Book! ⚓</p>
|
||
<p>This chapter covers what anchor is, how its documentation is structured, and what you should know to have a good time with this guide.</p>
|
||
<p>If you find errors or something doesn't work, please report it <a href="https://github.com/coral-xyz/anchor-book/issues">here</a>.</p>
|
||
<div style="break-before: page; page-break-before: always;"></div><h1 id="what-is-anchor"><a class="header" href="#what-is-anchor">What is Anchor</a></h1>
|
||
<p>Anchor is a framework for quickly building secure Solana programs.</p>
|
||
<p>With Anchor you can build programs quickly because it writes various boilerplate for you such as (de)serialization of accounts and instruction data.</p>
|
||
<p>You can build secure programs more easily because Anchor handles certain security checks for you. On top of that, it allows you to succinctly define additional checks and keep them separate from your business logic.</p>
|
||
<p>Both of these aspects mean that instead of working on the tedious parts of raw Solana programs, you can spend more time working on what matters most, your product.</p>
|
||
<div style="break-before: page; page-break-before: always;"></div><h1 id="anchor-documentation"><a class="header" href="#anchor-documentation">Anchor Documentation</a></h1>
|
||
<p>Anchor's official documentation is split up into multiple parts, namely the guide, which is what you are reading right now and the references.</p>
|
||
<p>There are three references. One for the <a href="https://docs.rs/anchor-lang/latest/anchor_lang/">core library</a> and one for each official client library (<a href="https://coral-xyz.github.io/anchor/ts/index.html">typescript</a> and <a href="https://docs.rs/anchor-client/latest/anchor_client/">rust</a>). These references are close to the code and detailed. If you know what you are looking for and want to understand how it works more deeply, you'll find explanations there.</p>
|
||
<p>However, if you're new to anchor, you need to know what anchor has to offer before you can even try to understand it more deeply. That's what this guide is for. Its purpose is to introduce you to anchor, to help you become familiar with it. It teaches you what features are available in Anchor so you can explore them yourself in detail using the references.</p>
|
||
<div style="break-before: page; page-break-before: always;"></div><h1 id="prerequisites"><a class="header" href="#prerequisites">Prerequisites</a></h1>
|
||
<p>This chapter provides you with the necessary background knowledge to get started with anchor.</p>
|
||
<div style="break-before: page; page-break-before: always;"></div><h1 id="useful-resources"><a class="header" href="#useful-resources">Useful Resources</a></h1>
|
||
<h2 id="rust"><a class="header" href="#rust">Rust</a></h2>
|
||
<p>This guide assumes that you already have some knowledge of basic Rust. We recommend reading chapters 1-9 of the <a href="https://doc.rust-lang.org/book/title-page.html">Rust book</a> which cover the basics of using Rust (Most of the time you don't need advanced Rust to write anchor programs).</p>
|
||
<h2 id="solana"><a class="header" href="#solana">Solana</a></h2>
|
||
<p>The next chapter explains some of the basic concepts required to make it through this book. That said, our intro chapter currently only briefly covers the basics, so we also recommend checking out the official <a href="https://solana.com/developers">Solana developers page</a>. </p>
|
||
<div style="break-before: page; page-break-before: always;"></div><h1 id="intro-to-programming-on-solana"><a class="header" href="#intro-to-programming-on-solana">Intro to Programming on Solana</a></h1>
|
||
<p>This is a brief intro to programming on Solana that explains the most important topics.
|
||
It aims to provide everything you need to understand the following chapters in the book.</p>
|
||
<h2 id="memory-on-solana"><a class="header" href="#memory-on-solana">Memory on Solana</a></h2>
|
||
<p>On a high level, memory inside a Solana cluster can be thought of as a monolithic heap of data. Smart contracts on Solana ("programs" in Solana jargon) each have access to their own part of that heap.</p>
|
||
<p>While a program may read any part of the global heap, if a program tries to write to a part of the heap that is not theirs, the Solana runtime makes the transaction fail (there is one exception to this which is increasing the balance of an account).</p>
|
||
<p>All state lives in this heap. Your SOL accounts, smart contracts, and memory used by smart contracts. And each memory region has a program that manages it (sometimes called the “owner”). The solana term for a memory region is "account". Some programs own thousands of independent accounts. As shown in the figure, these accounts (even when owned by the same program) do not have to be equal in size.</p>
|
||
<div style="text-align: center">
|
||
<p><img src="prerequisites/../images/heap_segment.svg" alt="Heap Segment" /></p>
|
||
</div>
|
||
<p>Since all state lives in the heap, even programs themselves live there. Accounts that store programs are owned by the <code>BPFLoader</code>. This is a program that can be used to deploy and upgrade other programs. The <code>BPFLoader</code> is owned by the <code>Native Loader</code> and that is where the recursion ends.</p>
|
||
<h2 id="transactions-and-accounts"><a class="header" href="#transactions-and-accounts">Transactions and Accounts</a></h2>
|
||
<p>You can make a program read and write data by sending transactions. Programs provide endpoints that can be called via transactions (In reality it's a bit more complex than that but frameworks like Anchor abstract away this complexity). A function signature usually takes the following arguments:</p>
|
||
<ul>
|
||
<li>the accounts that the program may read from and write to during this transaction.</li>
|
||
<li>additional data specific to the function</li>
|
||
</ul>
|
||
<p>The first point means that even if in theory the program may read and write to a large part of the global heap, in the context of a transaction, it may only read from and write to the specific regions specified in the arguments of the transaction.</p>
|
||
<blockquote>
|
||
<p>This design is partly responsible for Solana’s high throughput. The runtime can look at all the incoming transactions of a program (and even across programs) and can check whether the memory regions in the first argument of the transactions overlap. If they don’t, the runtime can run these transactions in parallel because they don’t conflict with each other. Even better, if the runtime sees that two transactions access overlapping memory regions but only read and don’t write, it can also parallelize those transactions because they do not conflict with each other.</p>
|
||
</blockquote>
|
||
<p>How exactly can a transaction specify a memory region/account? To answer that, we need to look deeper into what properties an account has (<a href="https://docs.rs/solana-program/latest/solana_program/account_info/struct.AccountInfo.html">docs here</a>. This is the data structure for an account in a transaction. The <code>is_signer</code> and <code>is_writable</code> fields are set per transaction (e.g. <code>is_signed</code> is set if the corresponding private key of the account's <code>key</code> field signed the transaction) and are not part of the metadata that is saved in the heap). In front of the user data that the account can store (in the <code>data</code> field) , there is some metadata connected to each account. First, it has a key property which is a ed25519 public key and serves as the address of the account. This is how the transaction can specify which accounts the program may access in the transaction.</p>
|
||
<div style="text-align: center">
|
||
<p><img src="prerequisites/../images/transaction.svg" alt="Transaction" /></p>
|
||
</div>
|
||
<p>An account also has a lamports field (a lamport is SOL’s smallest unit). Since all state lives in the heap, normal SOL accounts are on the heap too. They're accounts with a <code>data</code> field of length 0 (they still have metadata though!) and some amount of lamports. The System Program owns all regular SOL accounts. </p>
|
||
<h2 id="rent"><a class="header" href="#rent">Rent</a></h2>
|
||
<p>Because validators don’t have infinite storage and providing storage costs money, accounts need to pay rent for their existence. This rent is subtracted from their lamports regularly. However, if an account's lamports balance is above the rent-exemption threshold, it is rent-exempt and does not lose its lamports. This threshold depends on the size of the account. In 99% of cases, you will create rent-exempt accounts. It's even being considered to disable non-rent-exempt accounts.</p>
|
||
<h2 id="program-example-the-system-program"><a class="header" href="#program-example-the-system-program">Program Example: The System Program</a></h2>
|
||
<p>Let’s now look at an example of a program: The System Program. The System Program is a smart contract with some additional privileges.</p>
|
||
<p>All "normal" SOL accounts are owned by the System Program. One of the system program’s responsibilities is handling transfers between the accounts it owns. This is worth repeating: Even normal SOL transfers on Solana are handled by a smart contract.</p>
|
||
<p>To provide transfer functionality, the system program has a “transfer” endpoint. This endpoint takes 2 accounts - from and to - and a “lamports” argument. The system program checks whether <code>from</code> signed the transaction via the <code>is_signer</code> field on the <code>from</code> account. The runtime will set this flag to <code>true</code> if the private key of the keypair that the account’s public key belongs to signed the transaction. If “from” signed the transaction, the system program removes lamports from <code>from</code>’s account and adds them to <code>to</code>’s account.</p>
|
||
<pre><code class="language-ignore">/// simplified system program code
|
||
|
||
fn transfer(accounts, lamports) {
|
||
if !accounts.from.is_signer {
|
||
error();
|
||
}
|
||
accounts.from.lamports -= lamports;
|
||
accounts.to.lamports += lamports;
|
||
}
|
||
</code></pre>
|
||
<p>Take a moment to guess would happen if the user passed in a <code>from</code> account that was not owned by the system program!</p>
|
||
<p>...</p>
|
||
<p>...</p>
|
||
<p>The transaction would fail! A program may not write to any accounts that it doesn't own. There's one exception to this rule though.
|
||
If the <code>to</code> account was owned by a different program, the transaction would still succeed. This is because programs may increase the lamports of an account even if they do not own it.</p>
|
||
<p>Next to transferring lamports, the system program is used to create accounts for other programs. An account is created with a specific size and a specific amount of lamports. Let's now look at program composition to see how creating accounts works in practice.</p>
|
||
<h2 id="program-composition"><a class="header" href="#program-composition">Program Composition</a></h2>
|
||
<p>There are two ways for developers to make programs interact with each other. To explain these, we'll use a common flow on Solana: Create & Initialize. </p>
|
||
<p>Consider a counter program with two endpoints. One to initialize the counter and one to increment it. To create a new counter, we call the system program's <code>create_account</code> to create the account in memory and then the counter's <code>initialize</code> function.</p>
|
||
<h3 id="program-composition-via-multiple-instructions-in-a-transaction"><a class="header" href="#program-composition-via-multiple-instructions-in-a-transaction">Program Composition via multiple instructions in a transaction</a></h3>
|
||
<p>The first way to create and initialize the counter is by using multiple instructions in a transaction.
|
||
While a transaction can be used to execute a single call to a program like it was done above with <code>transfer</code>,
|
||
a single transaction can also include multiple calls to different programs.</p>
|
||
<p><img src="prerequisites/../images/create_initialize_multiple_ix.svg" alt="create & initialize using multiple instructions in a transaction" /></p>
|
||
<p>If we went with this approach, our counter data structure would look like this:</p>
|
||
<pre><pre class="playground"><code class="language-rust">
|
||
<span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>pub struct Counter {
|
||
pub count: u64,
|
||
pub is_initialized: bool
|
||
}
|
||
<span class="boring">}
|
||
</span></code></pre></pre>
|
||
<p>and our <code>initialize</code> function would look like this:</p>
|
||
<pre><code class="language-ignore">/// pseudo code
|
||
fn initialize(accounts) {
|
||
let counter = deserialize(accounts.counter);
|
||
if counter.is_initialized {
|
||
error("already initialized");
|
||
}
|
||
counter.count = 0;
|
||
counter.is_initialized = true;
|
||
}
|
||
</code></pre>
|
||
<p>This approach could also be called the "implicit" approach. This is because the programs do not explicitly communicate with each other. They are glued together by the user on the client side.</p>
|
||
<p>This also means that the counter needs to have an <code>is_initialized</code> variable so <code>initialize</code> can only be called once per counter account.</p>
|
||
<h3 id="program-composition-via-cross-program-invocations"><a class="header" href="#program-composition-via-cross-program-invocations">Program Composition via Cross-Program Invocations</a></h3>
|
||
<p>Cross-Program Invocations (CPIs) are the explicit tool to compose programs. A CPI is a direct call from one program into another within the same instruction.</p>
|
||
<p>Using CPIs the create & initialize flow can be executed inside the <code>initialize</code> function of the counter:</p>
|
||
<pre><code class="language-ignore">/// pseudo code
|
||
fn initialize(accounts) {
|
||
accounts.system_program.create_account(accounts.payer, accounts.counter);
|
||
let counter = deserialize(accounts.counter);
|
||
counter.count = 0;
|
||
}
|
||
</code></pre>
|
||
<p>In this example, no <code>is_initialized</code> is needed. This is because the CPI to the system program will fail if the counter exists already.</p>
|
||
<p>Anchor recommends CPIs to create and initialize accounts when possible (Accounts that are created by CPI can only be created with a maximum size of <code>10</code> kibibytes. This is large enough for most use cases though.). This is because creating an account inside your own instruction means that you can be certain about its properties. Any account that you don't create yourself is passed in by some other program or user that cannot be trusted. This brings us to the next section.</p>
|
||
<h3 id="validating-inputs"><a class="header" href="#validating-inputs">Validating Inputs</a></h3>
|
||
<p>On Solana it is crucial to validate program inputs. Clients pass accounts and program inputs to programs which means that malicious clients can pass malicious accounts and inputs. Programs need to be written in a way that handles those malicious inputs.</p>
|
||
<p>Consider the transfer function in the system program for example. It checks that <code>from</code> has signed the transaction.</p>
|
||
<pre><code class="language-ignore">/// simplified system program code
|
||
|
||
fn transfer(accounts, lamports) {
|
||
if !accounts.from.is_signer {
|
||
error();
|
||
}
|
||
accounts.from.lamports -= lamports;
|
||
accounts.to.lamports += lamports;
|
||
}
|
||
</code></pre>
|
||
<p>If it didn't do that, anyone could call the endpoint with your account and make the system program transfer the lamports from your account into theirs.</p>
|
||
<p>The book will eventually have a chapter explaining all the different types of attacks and how anchor prevents them but for now here's one more example. Consider the counter program from earlier. Now imagine that next to the counter struct, there's another struct that is a singleton which is used to count how many counters there are.</p>
|
||
<pre><code class="language-rust ignore">struct CounterCounter {
|
||
count: u64
|
||
}
|
||
</code></pre>
|
||
<p>Every time a new counter is created, the <code>count</code> variable of the counter counter should be incremented by one.</p>
|
||
<p>Consider the following <code>increment</code> instruction that increases the value of a counter account:</p>
|
||
<pre><code class="language-ignore">/// pseudo code
|
||
fn increment(accounts) {
|
||
let counter = deserialize(accounts.counter);
|
||
counter.count += 1;
|
||
}
|
||
</code></pre>
|
||
<p>This function is insecure. But why? It's not possible to pass in an account owned by a different program because the function writes to the account so the runtime would make the transaction fail. But it is possible to pass in the counter counter singleton account because both the counter and the counter counter struct have the same structure (they're a rust struct with a single <code>u64</code> variable). This would then increase the counter counter's count and it would no longer track how many counters there are.</p>
|
||
<p>The fix is simple:</p>
|
||
<pre><code class="language-ignore">/// pseudo code
|
||
|
||
// a better approach than hardcoding the address is using a PDA.
|
||
// We will cover those later in the book.
|
||
let HARDCODED_COUNTER_COUNTER_ADDRESS = SOME_ADDRESS;
|
||
|
||
fn increment(accounts) {
|
||
if accounts.counter.key == HARDCODED_COUNTER_COUNTER_ADDRESS {
|
||
error("Wrong account type");
|
||
}
|
||
let counter = deserialize(accounts.counter);
|
||
counter.count += 1;
|
||
}
|
||
</code></pre>
|
||
<p>There are many types of attacks possible on Solana that all revolve around passing in one account where another was expected but it wasn't checked that the actual one is really the expected one. This brings us from Solana to Anchor. A big part of Anchor's raison d'être is making input validation easier or even doing it for you when possible (e.g. with idiomatic anchor, this account type confusion cannot happen thanks to anchor's discriminator which we'll cover later in the book).</p>
|
||
<p>Let's dive in.</p>
|
||
<div style="break-before: page; page-break-before: always;"></div><h1 id="getting-started"><a class="header" href="#getting-started">Getting Started</a></h1>
|
||
<p>This chapter walks you through the installation process and the folder structure of an anchor workspace.</p>
|
||
<div style="break-before: page; page-break-before: always;"></div><h1 id="installation"><a class="header" href="#installation">Installation</a></h1>
|
||
<h2 id="rust-1"><a class="header" href="#rust-1">Rust</a></h2>
|
||
<p>Go <a href="https://www.rust-lang.org/tools/install">here</a> to install Rust.</p>
|
||
<h2 id="solana-1"><a class="header" href="#solana-1">Solana</a></h2>
|
||
<p>Go <a href="https://docs.solana.com/cli/install-solana-cli-tools">here</a> to install Solana and then run <code>solana-keygen new</code> to create a keypair at the default location. Anchor uses this keypair to run your program tests.</p>
|
||
<h2 id="yarn"><a class="header" href="#yarn">Yarn</a></h2>
|
||
<p>Go <a href="https://yarnpkg.com/getting-started/install">here</a> to install Yarn.</p>
|
||
<h2 id="anchor"><a class="header" href="#anchor">Anchor</a></h2>
|
||
<h3 id="installing-using-anchor-version-manager-avm-recommended"><a class="header" href="#installing-using-anchor-version-manager-avm-recommended">Installing using Anchor version manager (avm) (recommended)</a></h3>
|
||
<p>Anchor version manager is a tool for using multiple versions of the anchor-cli. It will require the same dependencies as building from source. It is recommended you uninstall the NPM package if you have it installed.</p>
|
||
<p>Install <code>avm</code> using Cargo. Note this will replace your <code>anchor</code> binary if you had one installed.</p>
|
||
<pre><code>cargo install --git https://github.com/coral-xyz/anchor avm --locked --force
|
||
</code></pre>
|
||
<p>On Linux systems you may need to install additional dependencies if cargo install fails. E.g. on Ubuntu:</p>
|
||
<pre><code>sudo apt-get update && sudo apt-get upgrade && sudo apt-get install -y pkg-config build-essential libudev-dev
|
||
</code></pre>
|
||
<p>Install the latest version of the CLI using <code>avm</code>, and then set it to be the version to use.</p>
|
||
<pre><code>avm install latest
|
||
avm use latest
|
||
</code></pre>
|
||
<p>Verify the installation.</p>
|
||
<pre><code>anchor --version
|
||
</code></pre>
|
||
<h3 id="install-using-pre-build-binary-on-x86_64-linux"><a class="header" href="#install-using-pre-build-binary-on-x86_64-linux">Install using pre-build binary on x86_64 Linux</a></h3>
|
||
<p>Anchor binaries are available via an NPM package <a href="https://www.npmjs.com/package/@coral-xyz/anchor-cli"><code>@coral-xyz/anchor-cli</code></a>. Only <code>x86_64</code> Linux is supported currently, you must build from source for other OS'.</p>
|
||
<h3 id="build-from-source-for-other-operating-systems-without-avm"><a class="header" href="#build-from-source-for-other-operating-systems-without-avm">Build from source for other operating systems without avm</a></h3>
|
||
<p>We can also use Cargo to install the CLI directly. Make sure that the <code>--tag</code> argument uses the version you want (the version here is just an example).</p>
|
||
<pre><code>cargo install --git https://github.com/coral-xyz/anchor --tag v0.29.0 anchor-cli --locked
|
||
</code></pre>
|
||
<p>On Linux systems you may need to install additional dependencies if cargo install fails. On Ubuntu,</p>
|
||
<pre><code>sudo apt-get update && sudo apt-get upgrade && sudo apt-get install -y pkg-config build-essential libudev-dev
|
||
</code></pre>
|
||
<p>Now verify the CLI is installed properly.</p>
|
||
<pre><code>anchor --version
|
||
</code></pre>
|
||
<div style="break-before: page; page-break-before: always;"></div><h1 id="hello-anchor"><a class="header" href="#hello-anchor">Hello, Anchor!</a></h1>
|
||
<p>To initialize a new project, simply run:</p>
|
||
<pre><code>anchor init <new-workspace-name>
|
||
</code></pre>
|
||
<p>This creates a new anchor workspace you can move into. The following are some of the important files in the folder:</p>
|
||
<ul>
|
||
<li>The <code>.anchor</code> folder: It includes the most recent program logs and a local ledger that is used for testing</li>
|
||
<li>The <code>app</code> folder: An empty folder that you can use to hold your frontend if you use a monorepo</li>
|
||
<li>The <code>programs</code> folder: This folder contains your programs. It can contain multiple but initially only contains a program with the same name as <code><new-workspace-name></code>. This program already contains a <code>lib.rs</code> file with some sample code.</li>
|
||
<li>The <code>tests</code> folder: The folder that contains your E2E tests. It will already include a file that tests the sample code in the <code>programs/<new-workspace-name></code>.</li>
|
||
<li>The <code>migrations</code> folder: In this folder you can save your deploy and migration scripts for your programs.</li>
|
||
<li>The <code>Anchor.toml</code> file: This file configures workspace wide settings for your programs. Initially, it configures
|
||
<ul>
|
||
<li>The addresses of your programs on localnet (<code>[programs.localnet]</code>)</li>
|
||
<li>A registry your program can be pushed to (<code>[registry]</code>)</li>
|
||
<li>A provider which can be used in your tests (<code>[provider]</code>)</li>
|
||
<li>Scripts that Anchor executes for you (<code>[scripts]</code>). The <code>test</code> script is run when running <code>anchor test</code>. You can run your own scripts with <code>anchor run <script_name></code>.</li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
<div style="break-before: page; page-break-before: always;"></div><h1 id="anchor-programs-in-depth"><a class="header" href="#anchor-programs-in-depth">Anchor Programs In-Depth</a></h1>
|
||
<p>This section explains how you can use Anchor to build Solana programs. Each section includes code examples, so it is recommended that you start up a new Anchor project before you proceed so you can play around with the code yourself while reading. Call it <code>hello-anchor</code>.</p>
|
||
<pre><code>anchor init hello-anchor
|
||
</code></pre>
|
||
<p>This section begins with the essentials and then explains more intermediate content afterwards.</p>
|
||
<div style="break-before: page; page-break-before: always;"></div><h1 id="essentials"><a class="header" href="#essentials">Essentials</a></h1>
|
||
<p>This chapter teaches you Anchor essentials and includes a milestone project with which you can test your understanding.</p>
|
||
<div style="break-before: page; page-break-before: always;"></div><h1 id="high-level-overview"><a class="header" href="#high-level-overview">High-level Overview</a></h1>
|
||
<p>An Anchor program consists of three parts. The <code>program</code> module, the Accounts structs which are marked with <code>#[derive(Accounts)]</code>, and the <code>declare_id</code> macro. The <code>program</code> module is where you write your business logic. The Accounts structs is where you validate accounts. The<code>declare_id</code> macro creates an <code>ID</code> field that stores the address of your program. Anchor uses this hardcoded <code>ID</code> for security checks and it also allows other crates to access your program's address.</p>
|
||
<p>When you start up a new Anchor project, you'll see the following:</p>
|
||
<pre><code class="language-rust ignore">// use this import to gain access to common anchor features
|
||
use anchor_lang::prelude::*;
|
||
|
||
// declare an id for your program
|
||
declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
|
||
|
||
// write your business logic here
|
||
#[program]
|
||
mod hello_anchor {
|
||
use super::*;
|
||
pub fn initialize(_ctx: Context<Initialize>) -> Result<()> {
|
||
Ok(())
|
||
}
|
||
}
|
||
|
||
// validate incoming accounts here
|
||
#[derive(Accounts)]
|
||
pub struct Initialize {}
|
||
</code></pre>
|
||
<p>We'll go into more detail in the next sections but for now, note that the way an endpoint is connected to its corresponding Accounts struct is the <code>ctx</code> argument in the endpoint. The argument is of type <code>Context</code> which is generic over an Accounts struct, i.e. this is where you put the name of your account validation struct. In this example, it's <code>Initialize</code>.</p>
|
||
<div style="break-before: page; page-break-before: always;"></div><h1 id="the-accounts-struct"><a class="header" href="#the-accounts-struct">The Accounts Struct</a></h1>
|
||
<p>The Accounts struct is where you define which accounts your instruction expects and which constraints these accounts should adhere to. You do this via two constructs: Types and constraints.</p>
|
||
<h2 id="types"><a class="header" href="#types">Types</a></h2>
|
||
<blockquote>
|
||
<p><a href="https://docs.rs/anchor-lang/latest/anchor_lang/accounts/index.html">Account Types Reference</a></p>
|
||
</blockquote>
|
||
<p>Each type has a specific use case in mind. Detailed explanations for the types can be found in the <a href="https://docs.rs/anchor-lang/latest/anchor_lang/accounts/index.html">reference</a>. We will briefly explain the most important type here, the <code>Account</code> type.</p>
|
||
<h3 id="the-account-type"><a class="header" href="#the-account-type">The Account Type</a></h3>
|
||
<blockquote>
|
||
<p><a href="https://docs.rs/anchor-lang/latest/anchor_lang/accounts/account/struct.Account.html">Account Reference</a></p>
|
||
</blockquote>
|
||
<p>The <code>Account</code> type is used when an instruction is interested in the deserialized data of the account. Consider the following example where we set some data in an account:</p>
|
||
<pre><code class="language-rust ignore">use anchor_lang::prelude::*;
|
||
|
||
declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
|
||
|
||
#[program]
|
||
mod hello_anchor {
|
||
use super::*;
|
||
pub fn set_data(ctx: Context<SetData>, data: u64) -> Result<()> {
|
||
ctx.accounts.my_account.data = data;
|
||
Ok(())
|
||
}
|
||
}
|
||
|
||
#[account]
|
||
#[derive(Default)]
|
||
pub struct MyAccount {
|
||
data: u64
|
||
}
|
||
|
||
#[derive(Accounts)]
|
||
pub struct SetData<'info> {
|
||
#[account(mut)]
|
||
pub my_account: Account<'info, MyAccount>
|
||
}
|
||
</code></pre>
|
||
<p><code>Account</code> is generic over <code>T</code>. This <code>T</code> is a type you can create yourself to store data. In this example, we have created a struct <code>MyAccount</code> with a single <code>data</code> field to store a <code>u64</code>. Account requires <code>T</code> to implement certain functions (e.g. functions that (de)serialize <code>T</code>). Most of the time, you can use the <code>#[account]</code> attribute to add these functions to your data, as is done in the example.</p>
|
||
<p>Most importantly, the <code>#[account]</code> attribute sets the owner of that data to the <code>ID</code> (the one we created earlier with <code>declare_id</code>) of the crate <code>#[account]</code> is used in. The Account type can then check for you that the <code>AccountInfo</code> passed into your instruction has its <code>owner</code> field set to the correct program. In this example, <code>MyAccount</code> is declared in our own crate so <code>Account</code> will verify that the owner of <code>my_account</code> equals the address we declared with <code>declare_id</code>.</p>
|
||
<h4 id="using-accounta-t-with-non-anchor-program-accounts"><a class="header" href="#using-accounta-t-with-non-anchor-program-accounts">Using <code>Account<'a, T></code> with non-anchor program accounts</a></h4>
|
||
<p>There may be cases where you want your program to interact with a non-Anchor program. You can still get all the benefits of <code>Account</code> but you have to write a custom wrapper type instead of using <code>#[account]</code>. For instance, Anchor provides wrapper types for the token program accounts so they can be used with <code>Account</code>.</p>
|
||
<pre><code class="language-rust ignore">use anchor_lang::prelude::*;
|
||
use anchor_spl::token::TokenAccount;
|
||
|
||
declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
|
||
|
||
#[program]
|
||
mod hello_anchor {
|
||
use super::*;
|
||
pub fn set_data(ctx: Context<SetData>, data: u64) -> Result<()> {
|
||
if ctx.accounts.token_account.amount > 0 {
|
||
ctx.accounts.my_account.data = data;
|
||
}
|
||
Ok(())
|
||
}
|
||
}
|
||
|
||
#[account]
|
||
#[derive(Default)]
|
||
pub struct MyAccount {
|
||
data: u64,
|
||
mint: Pubkey
|
||
}
|
||
|
||
#[derive(Accounts)]
|
||
pub struct SetData<'info> {
|
||
#[account(mut)]
|
||
pub my_account: Account<'info, MyAccount>,
|
||
#[account(
|
||
constraint = my_account.mint == token_account.mint,
|
||
has_one = owner
|
||
)]
|
||
pub token_account: Account<'info, TokenAccount>,
|
||
pub owner: Signer<'info>
|
||
}
|
||
</code></pre>
|
||
<p>To run this example, add <code>anchor-spl = "<version>"</code> to the dependencies section in your <code>Cargo.toml</code>, located in the <code>programs/<your-project-name>/</code> directory. <code><version></code> should be equal to the <code>anchor-lang</code> version you're using.</p>
|
||
<p>In this example, we set the <code>data</code> field of an account if the caller has admin rights. We decide whether the caller is an admin by checking whether they own admin tokens for the account they want to change. We do most of this via constraints which we will look at in the next section.
|
||
The important thing to take away is that we use the <code>TokenAccount</code> type (that wraps around the token program's <code>Account</code> struct and adds the required functions) to make anchor ensure that the incoming account is owned by the token program and to make anchor deserialize it. This means we can use the <code>TokenAccount</code> properties inside our constraints (e.g. <code>token_account.mint</code>) as well as in the instruction function.</p>
|
||
<p>Check out the <a href="https://docs.rs/anchor-lang/latest/anchor_lang/accounts/account/struct.Account.html">reference for the Account type</a> to learn how to implement your own wrapper types for non-anchor programs.</p>
|
||
<h2 id="constraints"><a class="header" href="#constraints">Constraints</a></h2>
|
||
<blockquote>
|
||
<p><a href="https://docs.rs/anchor-lang/latest/anchor_lang/derive.Accounts.html">Constraints reference</a></p>
|
||
</blockquote>
|
||
<p>Account types can do a lot of work for you but they're not dynamic enough to handle all the security checks a secure program requires.</p>
|
||
<p>Add constraints to an account with the following format:</p>
|
||
<pre><code class="language-rust ignore">#[account(<constraints>)]
|
||
pub account: AccountType
|
||
</code></pre>
|
||
<p>Some constraints support custom Errors (we will explore errors <a href="anchor_in_depth/./errors.html">later</a>):</p>
|
||
<pre><code class="language-rust ignore">#[account(...,<constraint> @ MyError::MyErrorVariant, ...)]
|
||
pub account: AccountType
|
||
</code></pre>
|
||
<p>For example, in the examples above, we used the <code>mut</code> constraint to indicate that <code>my_account</code> should be mutable. We used <code>has_one</code> to check that <code>token_account.owner == owner.key()</code>. And finally we used <code>constraint</code> to check an arbitrary expression; in this case, whether the incoming <code>TokenAccount</code> belongs to the admin mint.</p>
|
||
<pre><code class="language-rust ignore">#[derive(Accounts)]
|
||
pub struct SetData<'info> {
|
||
#[account(mut)]
|
||
pub my_account: Account<'info, MyAccount>,
|
||
#[account(
|
||
constraint = my_account.mint == token_account.mint,
|
||
has_one = owner
|
||
)]
|
||
pub token_account: Account<'info, TokenAccount>,
|
||
pub owner: Signer<'info>
|
||
}
|
||
</code></pre>
|
||
<p>You can find information about all constraints in the reference. We will cover some of the most important ones in the milestone project at the end of the Essentials section.</p>
|
||
<h2 id="safety-checks"><a class="header" href="#safety-checks">Safety checks</a></h2>
|
||
<p>Two of the Anchor account types, <a href="https://docs.rs/anchor-lang/latest/anchor_lang/accounts/account_info/index.html">AccountInfo</a> and <a href="https://docs.rs/anchor-lang/latest/anchor_lang/accounts/unchecked_account/index.html">UncheckedAccount</a> do not implement any checks on the account being passed. Anchor implements safety checks that encourage additional documentation describing why additional checks are not necessary.</p>
|
||
<p>Attempting to build a program containing the following excerpt with <code>anchor build</code>:</p>
|
||
<pre><code class="language-rust ignore">#[derive(Accounts)]
|
||
pub struct Initialize<'info> {
|
||
pub potentially_dangerous: UncheckedAccount<'info>
|
||
}
|
||
</code></pre>
|
||
<p>will result in an error similar to the following:</p>
|
||
<pre><code>Error:
|
||
/anchor/tests/unchecked/programs/unchecked/src/lib.rs:15:8
|
||
Struct field "potentially_dangerous" is unsafe, but is not documented.
|
||
Please add a `/// CHECK:` doc comment explaining why no checks through types are necessary.
|
||
See https://book.anchor-lang.com/anchor_in_depth/the_accounts_struct.html#safety-checks for more information.
|
||
</code></pre>
|
||
<p>To fix this, write a doc comment describing the potential security implications, e.g.:</p>
|
||
<pre><code class="language-rust ignore">#[derive(Accounts)]
|
||
pub struct Initialize<'info> {
|
||
/// CHECK: This is not dangerous because we don't read or write from this account
|
||
pub potentially_dangerous: UncheckedAccount<'info>
|
||
}
|
||
</code></pre>
|
||
<p>Note the doc comment needs to be a <a href="https://doc.rust-lang.org/reference/comments.html#doc-comments">line or block doc comment</a> (/// or /**) to be interpreted as doc attribute by Rust. Double slash comments (//) are not interpreted as such.</p>
|
||
<div style="break-before: page; page-break-before: always;"></div><h1 id="the-program-module"><a class="header" href="#the-program-module">The Program Module</a></h1>
|
||
<p>The program module is where you define your business logic. You do so by writing functions which can be called by clients or other programs. You've already seen one example of such a function, the <code>set_data</code> function from the previous section.</p>
|
||
<pre><code class="language-rust ignore">#[program]
|
||
mod hello_anchor {
|
||
use super::*;
|
||
pub fn set_data(ctx: Context<SetData>, data: u64) -> Result<()> {
|
||
if ctx.accounts.token_account.amount > 0 {
|
||
ctx.accounts.my_account.data = data;
|
||
}
|
||
Ok(())
|
||
}
|
||
}
|
||
</code></pre>
|
||
<h2 id="context"><a class="header" href="#context">Context</a></h2>
|
||
<blockquote>
|
||
<p><a href="https://docs.rs/anchor-lang/latest/anchor_lang/context/index.html">Context Reference</a></p>
|
||
</blockquote>
|
||
<p>Each endpoint function takes a <code>Context</code> type as its first argument. Through this context argument it can access the accounts (<code>ctx.accounts</code>), the program id (<code>ctx.program_id</code>) of the executing program, and the remaining accounts (<code>ctx.remaining_accounts</code>). <code>remaining_accounts</code> is a vector that contains all accounts that were passed into the instruction but are not declared in the <code>Accounts</code> struct. This is useful when you want your function to handle a variable amount of accounts, e.g. when initializing a game with a variable number of players.</p>
|
||
<h2 id="instruction-data"><a class="header" href="#instruction-data">Instruction Data</a></h2>
|
||
<p>If your function requires instruction data, you can add it by adding arguments to the function after the context argument. Anchor will then automatically deserialize the instruction data into the arguments. You can have as many as you like. You can even pass in your own types as long as you use<code>#[derive(AnchorDeserialize)]</code> on them or implement <code>AnchorDeserialize</code> for them yourself. Here's an example with a custom type used as an instruction data arg:</p>
|
||
<pre><code class="language-rust ignore">...
|
||
|
||
#[program]
|
||
mod hello_anchor {
|
||
use super::*;
|
||
pub fn set_data(ctx: Context<SetData>, data: Data) -> Result<()> {
|
||
ctx.accounts.my_account.data = data.data;
|
||
ctx.accounts.my_account.age = data.age;
|
||
Ok(())
|
||
}
|
||
}
|
||
|
||
#[account]
|
||
#[derive(Default)]
|
||
pub struct MyAccount {
|
||
pub data: u64,
|
||
pub age: u8
|
||
}
|
||
|
||
#[derive(AnchorSerialize, AnchorDeserialize, Eq, PartialEq, Clone, Copy, Debug)]
|
||
pub struct Data {
|
||
pub data: u64,
|
||
pub age: u8
|
||
}
|
||
|
||
...
|
||
</code></pre>
|
||
<p>Conveniently, <code>#[account]</code> implements <code>Anchor(De)Serialize</code> for <code>MyAccount</code>, so the example above can be simplified.</p>
|
||
<pre><code class="language-rust ignore">...
|
||
|
||
#[program]
|
||
mod hello_anchor {
|
||
use super::*;
|
||
pub fn set_data(ctx: Context<SetData>, data: MyAccount) -> Result<()> {
|
||
ctx.accounts.my_account.set_inner(data);
|
||
Ok(())
|
||
}
|
||
}
|
||
|
||
#[account]
|
||
#[derive(Default)]
|
||
pub struct MyAccount {
|
||
pub data: u64,
|
||
pub age: u8
|
||
}
|
||
|
||
...
|
||
</code></pre>
|
||
<div style="break-before: page; page-break-before: always;"></div><h1 id="errors"><a class="header" href="#errors">Errors</a></h1>
|
||
<blockquote>
|
||
<p><a href="https://docs.rs/anchor-lang/latest/anchor_lang/error/struct.AnchorError.html"><code>AnchorError</code> Rust Reference</a></p>
|
||
</blockquote>
|
||
<blockquote>
|
||
<p><a href="https://project-serum.github.io/anchor/ts/classes/AnchorError.html"><code>AnchorError</code> Typescript Reference</a></p>
|
||
</blockquote>
|
||
<p>There are two types of errors in anchor programs. AnchorErrors and non-anchor errors.
|
||
AnchorErrors can be divided into Anchor Internal Errors that the framework returns from inside its own code or
|
||
custom errors which the user (you!) can return. </p>
|
||
<ul>
|
||
<li>AnchorErrors
|
||
<ul>
|
||
<li>Anchor Internal Errors</li>
|
||
<li>Custom Errors</li>
|
||
</ul>
|
||
</li>
|
||
<li>Non-anchor errors.</li>
|
||
</ul>
|
||
<p><a href="https://docs.rs/anchor-lang/latest/anchor_lang/error/struct.AnchorError.html">AnchorErrors</a> provide a range of information like the error name and number or the location in the code where the anchor was thrown, or the account that violated a constraint (e.g. a <code>mut</code> constraint). Once thrown inside the program, <a href="https://project-serum.github.io/anchor/ts/classes/AnchorError.html">you can access the error information</a> in the anchor clients like the typescript client. The typescript client also enriches the error with additional information about which program the error was thrown in and the CPI calls (which are explained <a href="anchor_in_depth/./CPIs.html">here</a> in the book) that led to the program from which the error was thrown from. <a href="anchor_in_depth/./milestone_project_tic-tac-toe.html">The milestone chapter</a> explores how all of this works together in practice. For now, let's look at how different errors can be returned from inside a program.</p>
|
||
<h2 id="anchor-internal-errors"><a class="header" href="#anchor-internal-errors">Anchor Internal Errors</a></h2>
|
||
<blockquote>
|
||
<p><a href="https://docs.rs/anchor-lang/latest/anchor_lang/error/enum.ErrorCode.html">Anchor Internal Error Code Reference</a></p>
|
||
</blockquote>
|
||
<p>Anchor has many different internal error codes. These are not meant to be used by users, but it's useful to study the reference to learn about the mappings between codes and their causes. They are, for example, thrown when a constraint has been violated, e.g. when an account is marked with <code>mut</code> but its <code>is_writable</code> property is <code>false</code>.</p>
|
||
<h2 id="custom-errors"><a class="header" href="#custom-errors">Custom Errors</a></h2>
|
||
<p>You can add errors that are unique to your program by using the <code>error_code</code> attribute. </p>
|
||
<p>Simply add it to an enum with a name of your choice. You can then use the variants of the enum as errors in your program. Additionally, you can add a message attribute to the individual variants. Clients will then display this error message if the error occurs. Custom Error code numbers start at the <a href="https://docs.rs/anchor-lang/latest/anchor_lang/error/constant.ERROR_CODE_OFFSET.html">custom error offset</a>.</p>
|
||
<p>To actually throw an error use the <a href="https://docs.rs/anchor-lang/latest/anchor_lang/macro.err.html"><code>err!</code></a> or the <a href="https://docs.rs/anchor-lang/latest/anchor_lang/prelude/macro.error.html"><code>error!</code></a> macro. These add file and line information to the error that is then logged by anchor.</p>
|
||
<pre><code class="language-rust ignore">#[program]
|
||
mod hello_anchor {
|
||
use super::*;
|
||
pub fn set_data(ctx: Context<SetData>, data: MyAccount) -> Result<()> {
|
||
if data.data >= 100 {
|
||
return err!(MyError::DataTooLarge);
|
||
}
|
||
ctx.accounts.my_account.set_inner(data);
|
||
Ok(())
|
||
}
|
||
}
|
||
|
||
|
||
#[error_code]
|
||
pub enum MyError {
|
||
#[msg("MyAccount may only hold data below 100")]
|
||
DataTooLarge
|
||
}
|
||
</code></pre>
|
||
<h3 id="require"><a class="header" href="#require">require!</a></h3>
|
||
<p>You can use the <a href="https://docs.rs/anchor-lang/latest/anchor_lang/macro.require.html"><code>require</code></a> macro to simplify writing errors. The code above can be simplified to this (Note that the <code>>=</code> flips to <code><</code>):</p>
|
||
<pre><code class="language-rust ignore">#[program]
|
||
mod hello_anchor {
|
||
use super::*;
|
||
pub fn set_data(ctx: Context<SetData>, data: MyAccount) -> Result<()> {
|
||
require!(data.data < 100, MyError::DataTooLarge);
|
||
ctx.accounts.my_account.set_inner(data);
|
||
Ok(())
|
||
}
|
||
}
|
||
|
||
|
||
#[error_code]
|
||
pub enum MyError {
|
||
#[msg("MyAccount may only hold data below 100")]
|
||
DataTooLarge
|
||
}
|
||
</code></pre>
|
||
<p>There are a couple of <code>require</code> macros to choose from (<a href="https://docs.rs/anchor-lang/latest/anchor_lang/?search=require">search for require in the docs</a>). When comparing public keys, it's important to use the <code>keys</code> variants of the require statements like <code>require_keys_eq</code> instead of <code>require_eq</code> because comparing public keys with <code>require_eq</code> is very expensive.</p>
|
||
<blockquote>
|
||
<p>(Ultimately, all programs return the same Error: The <a href="https://docs.rs/solana-program/latest/solana_program/program_error/enum.ProgramError.html"><code>ProgramError</code></a>. This Error has a field for a custom error number. This is where Anchor puts its internal and custom error codes. However, this is just a single number and a single number is only so useful. So in addition, in the case of AnchorErrors, Anchor logs the returned AnchorError and the Anchor clients parse these logs to provide as much information as possible. This is not always possible. For example, there is currently no easy way to get the logs of a <code>processed</code> transaction with preflight checks turned off. In addition, non-anchor or old anchor programs might not log AnchorErrors. In these cases, Anchor will fall back to checking whether the returned error number by the transaction matches an error number defined in the <code>IDL</code> or an Anchor internal error code. If so, Anchor will at least enrich the error with the error message. Also, if there are logs available, Anchor will always try to parse the program error stack and return that so you know which program the error was returned from.</p>
|
||
</blockquote>
|
||
<div style="break-before: page; page-break-before: always;"></div><h1 id="milestone-project---tic-tac-toe"><a class="header" href="#milestone-project---tic-tac-toe">Milestone Project - Tic-Tac-Toe</a></h1>
|
||
<blockquote>
|
||
<p><a href="https://github.com/coral-xyz/anchor-book/tree/master/programs/tic-tac-toe">Program Code</a></p>
|
||
</blockquote>
|
||
<p>You're now ready to build your first anchor project. Create a new anchor workspace with</p>
|
||
<pre><code>anchor init tic-tac-toe
|
||
</code></pre>
|
||
<p>The program will have 2 instructions. First, we need to setup the game. We need to save who is playing it and create a board to play on. Then, the players take turns until there is a winner or a tie.</p>
|
||
<p>We recommend keeping programs in a single <code>lib.rs</code> file until they get too big. We would not split up this project into multiple files either but there is a section at the end of this chapter that explains how to do it for this and other programs.</p>
|
||
<h2 id="setting-up-the-game"><a class="header" href="#setting-up-the-game">Setting up the game</a></h2>
|
||
<h3 id="state"><a class="header" href="#state">State</a></h3>
|
||
<p>Let's begin by thinking about what data we should store. Each game has players, turns, a board, and a game state. This game state describes whether the game is active, tied, or one of the two players won. We can save all this data in an account. This means that each new game will have its own account. Add the following to the bottom of the <code>lib.rs</code> file:</p>
|
||
<pre><code class="language-rust ignore">#[account]
|
||
pub struct Game {
|
||
players: [Pubkey; 2], // (32 * 2)
|
||
turn: u8, // 1
|
||
board: [[Option<Sign>; 3]; 3], // 9 * (1 + 1) = 18
|
||
state: GameState, // 32 + 1
|
||
}
|
||
</code></pre>
|
||
<p>This is the game account. Next to the field definitions, you can see how many bytes each field requires. This will be very important later. Let's also add the <code>Sign</code> and the <code>GameState</code> type.</p>
|
||
<pre><code class="language-rust ignore">#[derive(AnchorSerialize, AnchorDeserialize, Clone, PartialEq, Eq)]
|
||
pub enum GameState {
|
||
Active,
|
||
Tie,
|
||
Won { winner: Pubkey },
|
||
}
|
||
|
||
#[derive(
|
||
AnchorSerialize,
|
||
AnchorDeserialize,
|
||
FromPrimitive,
|
||
ToPrimitive,
|
||
Copy,
|
||
Clone,
|
||
PartialEq,
|
||
Eq
|
||
)]
|
||
pub enum Sign {
|
||
X,
|
||
O,
|
||
}
|
||
</code></pre>
|
||
<p>Both <code>GameState</code> and <code>Sign</code> derive some traits. <code>AnchorSerialize</code> and <code>AnchorDeserialize</code> are the crucial ones. All types that are used in types that are marked with <code>#[account]</code> must implement these two traits (or be marked with <code>#[account]</code> themselves). All other traits are important to our game logic and we are going to use them later. Generally, it is good practice to derive even more traits to make the life of others trying to interface with your program easier (see <a href="https://rust-lang.github.io/api-guidelines/interoperability.html#types-eagerly-implement-common-traits-c-common-traits">Rust's API guidelines</a>) but for brevity's sake, we are not going to do that in this guide.</p>
|
||
<p>This won't quite work yet because <code>FromPrimitive</code> and <code>ToPrimitive</code> are unknown. Go to the <code>Cargo.toml</code> file right outside <code>src</code> (not the one at the root of the workspace) and add these two dependencies:</p>
|
||
<pre><code class="language-toml">num-traits = "0.2"
|
||
num-derive = "0.3"
|
||
</code></pre>
|
||
<p>Then, import them at the top of <code>lib.rs</code>:</p>
|
||
<pre><code class="language-rust ignore">use num_derive::*;
|
||
use num_traits::*;
|
||
</code></pre>
|
||
<p>Now add the game logic:</p>
|
||
<pre><code class="language-rust ignore">impl Game {
|
||
pub const MAXIMUM_SIZE: usize = (32 * 2) + 1 + (9 * (1 + 1)) + (32 + 1);
|
||
|
||
pub fn start(&mut self, players: [Pubkey; 2]) -> Result<()> {
|
||
require_eq!(self.turn, 0, TicTacToeError::GameAlreadyStarted);
|
||
self.players = players;
|
||
self.turn = 1;
|
||
Ok(())
|
||
}
|
||
|
||
pub fn is_active(&self) -> bool {
|
||
self.state == GameState::Active
|
||
}
|
||
|
||
fn current_player_index(&self) -> usize {
|
||
((self.turn - 1) % 2) as usize
|
||
}
|
||
|
||
pub fn current_player(&self) -> Pubkey {
|
||
self.players[self.current_player_index()]
|
||
}
|
||
|
||
pub fn play(&mut self, tile: &Tile) -> Result<()> {
|
||
require!(self.is_active(), TicTacToeError::GameAlreadyOver);
|
||
|
||
match tile {
|
||
tile @ Tile {
|
||
row: 0..=2,
|
||
column: 0..=2,
|
||
} => match self.board[tile.row as usize][tile.column as usize] {
|
||
Some(_) => return Err(TicTacToeError::TileAlreadySet.into()),
|
||
None => {
|
||
self.board[tile.row as usize][tile.column as usize] =
|
||
Some(Sign::from_usize(self.current_player_index()).unwrap());
|
||
}
|
||
},
|
||
_ => return Err(TicTacToeError::TileOutOfBounds.into()),
|
||
}
|
||
|
||
self.update_state();
|
||
|
||
if GameState::Active == self.state {
|
||
self.turn += 1;
|
||
}
|
||
|
||
Ok(())
|
||
}
|
||
|
||
fn is_winning_trio(&self, trio: [(usize, usize); 3]) -> bool {
|
||
let [first, second, third] = trio;
|
||
self.board[first.0][first.1].is_some()
|
||
&& self.board[first.0][first.1] == self.board[second.0][second.1]
|
||
&& self.board[first.0][first.1] == self.board[third.0][third.1]
|
||
}
|
||
|
||
fn update_state(&mut self) {
|
||
for i in 0..=2 {
|
||
// three of the same in one row
|
||
if self.is_winning_trio([(i, 0), (i, 1), (i, 2)]) {
|
||
self.state = GameState::Won {
|
||
winner: self.current_player(),
|
||
};
|
||
return;
|
||
}
|
||
// three of the same in one column
|
||
if self.is_winning_trio([(0, i), (1, i), (2, i)]) {
|
||
self.state = GameState::Won {
|
||
winner: self.current_player(),
|
||
};
|
||
return;
|
||
}
|
||
}
|
||
|
||
// three of the same in one diagonal
|
||
if self.is_winning_trio([(0, 0), (1, 1), (2, 2)])
|
||
|| self.is_winning_trio([(0, 2), (1, 1), (2, 0)])
|
||
{
|
||
self.state = GameState::Won {
|
||
winner: self.current_player(),
|
||
};
|
||
return;
|
||
}
|
||
|
||
// reaching this code means the game has not been won,
|
||
// so if there are unfilled tiles left, it's still active
|
||
for row in 0..=2 {
|
||
for column in 0..=2 {
|
||
if self.board[row][column].is_none() {
|
||
return;
|
||
}
|
||
}
|
||
}
|
||
|
||
// game has not been won
|
||
// game has no more free tiles
|
||
// -> game ends in a tie
|
||
self.state = GameState::Tie;
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>We are not going to explore this code in detail together because it's rather simple rust code. It's just tic-tac-toe after all! Roughly, what happens when <code>play</code> is called:</p>
|
||
<ol>
|
||
<li>Return error if game is over or
|
||
return error if given row or column are outside the 3x3 board or
|
||
return error if tile on board is already set</li>
|
||
<li>Determine current player and set tile to X or O</li>
|
||
<li>Update game state</li>
|
||
<li>If game is still active, increase the turn</li>
|
||
</ol>
|
||
<p>Currently, the code doesn't compile because we need to add the <code>Tile</code></p>
|
||
<pre><code class="language-rust ignore">#[derive(AnchorSerialize, AnchorDeserialize)]
|
||
pub struct Tile {
|
||
row: u8,
|
||
column: u8,
|
||
}
|
||
</code></pre>
|
||
<p>and the <code>TicTacToeError</code> type.</p>
|
||
<pre><code class="language-rust ignore">#[error_code]
|
||
pub enum TicTacToeError {
|
||
TileOutOfBounds,
|
||
TileAlreadySet,
|
||
GameAlreadyOver,
|
||
NotPlayersTurn,
|
||
GameAlreadyStarted
|
||
}
|
||
</code></pre>
|
||
<h3 id="the-setup-instruction"><a class="header" href="#the-setup-instruction">The Setup Instruction</a></h3>
|
||
<p>Before we write any game logic, we can add the instruction that will set up the game in its initial state. Rename the already existing instruction function and accounts struct to <code>setup_game</code> and <code>SetupGame</code> respectively. Now think about which accounts are needed to set up the game. Clearly, we need the game account. Before we can fill it with values, we need to create it. For that, we use the <code>init</code> constraint.</p>
|
||
<pre><code class="language-rust ignore">#[derive(Accounts)]
|
||
pub struct SetupGame<'info> {
|
||
#[account(init)]
|
||
pub game: Account<'info, Game>
|
||
}
|
||
</code></pre>
|
||
<p><code>init</code> immediately shouts at us and tells us to add a payer. Why do we need it? Because <code>init</code> creates <code>rent-exempt</code> accounts and someone has to pay for that. Naturally, if we want to take money from someone, we should make them sign as well as mark their account as mutable.</p>
|
||
<pre><code class="language-rust ignore">#[derive(Accounts)]
|
||
pub struct SetupGame<'info> {
|
||
#[account(init, payer = player_one)]
|
||
pub game: Account<'info, Game>,
|
||
#[account(mut)]
|
||
pub player_one: Signer<'info>
|
||
}
|
||
</code></pre>
|
||
<p><code>init</code> is not happy yet. It wants the system program to be inside the struct because <code>init</code> creates the game account by making a call to that program. So let's add it.</p>
|
||
<pre><code class="language-rust ignore">#[derive(Accounts)]
|
||
pub struct SetupGame<'info> {
|
||
#[account(init, payer = player_one)]
|
||
pub game: Account<'info, Game>,
|
||
#[account(mut)]
|
||
pub player_one: Signer<'info>,
|
||
pub system_program: Program<'info, System>
|
||
}
|
||
</code></pre>
|
||
<p>There's one more thing to do to complete <code>SetupGame</code>. Every account is created with a fixed amount of space, so we have to add this space to the instruction as well. This is what the comments next to the <code>Game</code> struct indicated.</p>
|
||
<pre><code class="language-rust ignore">#[derive(Accounts)]
|
||
pub struct SetupGame<'info> {
|
||
#[account(init, payer = player_one, space = 8 + Game::MAXIMUM_SIZE)]
|
||
pub game: Account<'info, Game>,
|
||
#[account(mut)]
|
||
pub player_one: Signer<'info>,
|
||
pub system_program: Program<'info, System>
|
||
}
|
||
</code></pre>
|
||
<p>Let us briefly explain how we arrived at the <code>Game::MAXIMUM_SIZE</code>. Anchor uses the <a href="https://borsh.io">borsh</a> specification to (de)serialize its state accounts.</p>
|
||
<ul>
|
||
<li>Pubkey has a length of <code>32</code> bytes so <code>2*32 = 64</code></li>
|
||
<li>u8 as a vector has a length of <code>1</code></li>
|
||
<li>the <code>board</code> has a length of (<code>9 * (1 + 1)</code>). We know the board has 9 tiles (-> <code>9</code>) of type <code>Option</code> which borsh serializes with 1 byte (set to <code>1</code> for Some and <code>0</code> for None) plus the size of whatever's in the <code>Option</code>. In this case, it's a simple enum with types that don't hold more types so the maximum size of the enum is also just <code>1</code> (for its discriminant). In total that means we get <code>9 (tiles) * (1 (Option) + 1(Sign discriminant))</code>.</li>
|
||
<li><code>state</code> is also an enum so we need <code>1</code> byte for the discriminant. We have to init the account with the maximum size and the maximum size of an enum is the size of its biggest variant. In this case that's the <code>winner</code> variant which holds a Pubkey. A Pubkey is <code>32</code> bytes long so the size of <code>state</code> is <code>1 (discriminant) + 32 (winner pubkey)</code> (<code>MAXIMUM_SIZE</code> is a <a href="https://doc.rust-lang.org/std/keyword.const.html"><code>const</code></a> variable so specifying it in terms of a sum of the sizes of <code>Game</code>'s members' fields does not incur any runtime cost).</li>
|
||
</ul>
|
||
<p>In addition to the game's size, we have to add another 8 to the space. This is space for the internal discriminator which anchor sets automatically. In short, the discriminator is how anchor can differentiate between different accounts of the same program. For more information, check out the Anchor space reference.</p>
|
||
<blockquote>
|
||
<p><a href="anchor_in_depth/./../anchor_references/space.html">Anchor Space Reference</a></p>
|
||
</blockquote>
|
||
<blockquote>
|
||
<p>(What about using <code>mem::size_of<Game>()</code>? This almost works but not quite. The issue is that borsh will always serialize an option as 1 byte for the variant identifier and then additional x bytes for the content if it's Some. Rust uses null-pointer optimization to make Option's variant identifier 0 bytes when it can, so an option is sometimes just as big as its contents. This is the case with <code>Sign</code>. This means the <code>MAXIMUM_SIZE</code> could also be expressed as <code>mem::size_of<Game>() + 9</code>.)</p>
|
||
</blockquote>
|
||
<p>And with this, <code>SetupGame</code> is complete and we can move on to the <code>setup_game</code> function. (If you like playing detective, you can pause here and try to figure out why what we just did will not work. Hint: Have a look at the <a href="https://borsh.io/">specification</a> of the serialization library Anchor uses. If you cannot figure it out, don't worry. We are going to fix it very soon, together.)</p>
|
||
<p>Let's start by adding an argument to the <code>setup_game</code> function.</p>
|
||
<pre><code class="language-rust ignore">pub fn setup_game(ctx: Context<SetupGame>, player_two: Pubkey) -> Result<()> {
|
||
|
||
}
|
||
</code></pre>
|
||
<p>Why didn't we just add <code>player_two</code> as an account in the accounts struct? There are two reasons for this. First, adding it there requires a little more space in the transaction that saves whether the account is writable and whether it's a signer. But we care about neither the mutability of the account nor whether it's a signer. We just need its address. This brings us to the second and more important reason: Simultaneous network transactions can affect each other if they share the same accounts. For example, if we add <code>player_two</code> to the accounts struct, during our transaction, no other transaction can edit <code>player_two</code>'s account. Therefore, we block all other transactions that want to edit <code>player_two</code>'s account, even though we neither want to read from nor write to the account. We just care about its address!</p>
|
||
<p>Finish the instruction function by setting the game to its initial values:</p>
|
||
<pre><code class="language-rust ignore">pub fn setup_game(ctx: Context<SetupGame>, player_two: Pubkey) -> Result<()> {
|
||
ctx.accounts.game.start([ctx.accounts.player_one.key(), player_two])
|
||
}
|
||
</code></pre>
|
||
<p>Now, run <code>anchor build</code>. On top of compiling your program, this command creates an <a href="https://en.wikipedia.org/wiki/Interface_description_language">IDL</a> for your program. You can find it in <code>target/idl</code>. The anchor typescript client can automatically parse this IDL and generate functions based on it. What this means is that each anchor program gets its own typescript client for free! (Technically, you don't have to call <code>anchor build</code> before testing. <code>anchor test</code> will do it for you.)</p>
|
||
<h3 id="testing-the-setup-instruction"><a class="header" href="#testing-the-setup-instruction">Testing the Setup Instruction</a></h3>
|
||
<p>Time to test our code! Head over into the <code>tests</code> folder in the root directory. Open the <code>tic-tac-toe.ts</code> file and remove the existing <code>it</code> test. Then, put the following into the <code>describe</code> section:</p>
|
||
<pre><code class="language-typescript">it("setup game!", async () => {
|
||
const gameKeypair = anchor.web3.Keypair.generate();
|
||
const playerOne = (program.provider as anchor.AnchorProvider).wallet;
|
||
const playerTwo = anchor.web3.Keypair.generate();
|
||
await program.methods
|
||
.setupGame(playerTwo.publicKey)
|
||
.accounts({
|
||
game: gameKeypair.publicKey,
|
||
playerOne: playerOne.publicKey,
|
||
})
|
||
.signers([gameKeypair])
|
||
.rpc();
|
||
|
||
let gameState = await program.account.game.fetch(gameKeypair.publicKey);
|
||
expect(gameState.turn).to.equal(1);
|
||
expect(gameState.players).to.eql([playerOne.publicKey, playerTwo.publicKey]);
|
||
expect(gameState.state).to.eql({ active: {} });
|
||
expect(gameState.board).to.eql([
|
||
[null, null, null],
|
||
[null, null, null],
|
||
[null, null, null],
|
||
]);
|
||
});
|
||
</code></pre>
|
||
<p>and add this to the top of your file:</p>
|
||
<pre><code class="language-typescript">import { expect } from "chai";
|
||
</code></pre>
|
||
<blockquote>
|
||
<p>When you adjust your test files it may happen that you'll see errors everywhere.
|
||
This is likely because the test file is looking for types from your program that haven't been generated yet.
|
||
To generate them, run <code>anchor build</code>. This builds the program and creates the idl and typescript types.</p>
|
||
</blockquote>
|
||
<p>The test begins by creating some keypairs. Importantly, <code>playerOne</code> is not a keypair but the wallet of the program's provider. The provider details are defined in the <code>Anchor.toml</code> file in the root of the project. The provider serves as the keypair that pays for (and therefore signs) all transactions.
|
||
Then, we send the transaction.
|
||
The structure of the transaction function is as follows: First come the instruction arguments. For this function, the public key of the second player. Then come the accounts. Lastly, we add a signers array. We have to add the <code>gameKeypair</code> here because whenever an account gets created, it has to sign its creation transaction. We don't have to add <code>playerOne</code> even though we gave it the <code>Signer</code> type in the program because it is the program provider and therefore signs the transaction by default.
|
||
We did not have to specify the <code>system_program</code> account. This is because anchor recognizes this account and is able to infer it. This is also true for other known accounts such as the <code>token_program</code> or the <code>rent</code> sysvar account.</p>
|
||
<p>After the transaction returns, we can fetch the state of the game account. You can fetch account state using the <code>program.account</code> namespace.
|
||
Finally, we verify the game has been set up properly by comparing the actual state and the expected state. To learn how Anchor maps the Rust types to the js/ts types, check out the <a href="anchor_in_depth/./../anchor_references/javascript_anchor_types_reference.html">Javascript Anchor Types Reference</a>.</p>
|
||
<p>Now, run <code>anchor test</code>. This starts up (and subsequently shuts down) a local validator (make sure you don't have one running before) and runs your tests using the test script defined in <code>Anchor.toml</code>.</p>
|
||
<blockquote>
|
||
<p>If you get the error <code>Error: Unable to read keypair file</code> when running the test, you likely need to generate a Solana keypair using <code>solana-keygen new</code>.</p>
|
||
</blockquote>
|
||
<h2 id="playing-the-game"><a class="header" href="#playing-the-game">Playing the game</a></h2>
|
||
<h3 id="the-play-instruction"><a class="header" href="#the-play-instruction">The Play Instruction</a></h3>
|
||
<p>The <code>Play</code> accounts struct is straightforward. We need the game and a player:</p>
|
||
<pre><code class="language-rust ignore">#[derive(Accounts)]
|
||
pub struct Play<'info> {
|
||
#[account(mut)]
|
||
pub game: Account<'info, Game>,
|
||
pub player: Signer<'info>,
|
||
}
|
||
</code></pre>
|
||
<p><code>player</code> needs to sign or someone else could play for the player.</p>
|
||
<p>Finally, we can add the <code>play</code> function inside the program module.</p>
|
||
<pre><code class="language-rust ignore">pub fn play(ctx: Context<Play>, tile: Tile) -> Result<()> {
|
||
let game = &mut ctx.accounts.game;
|
||
|
||
require_keys_eq!(
|
||
game.current_player(),
|
||
ctx.accounts.player.key(),
|
||
TicTacToeError::NotPlayersTurn
|
||
);
|
||
|
||
game.play(&tile)
|
||
}
|
||
</code></pre>
|
||
<p>We've checked in the accounts struct that the <code>player</code> account has signed the transaction, but we do not check that it is the <code>player</code> we expect. That's what the <code>require_keys_eq</code> check in <code>play</code> is for.</p>
|
||
<h3 id="testing-the-play-instruction"><a class="header" href="#testing-the-play-instruction">Testing the Play Instruction</a></h3>
|
||
<p>Testing the <code>play</code> instruction works the exact same way. To avoid repeating yourself, create a helper function at the top of the test file:</p>
|
||
<pre><code class="language-typescript">async function play(
|
||
program: Program<TicTacToe>,
|
||
game,
|
||
player,
|
||
tile,
|
||
expectedTurn,
|
||
expectedGameState,
|
||
expectedBoard
|
||
) {
|
||
await program.methods
|
||
.play(tile)
|
||
.accounts({
|
||
player: player.publicKey,
|
||
game,
|
||
})
|
||
.signers(player instanceof (anchor.Wallet as any) ? [] : [player])
|
||
.rpc();
|
||
|
||
const gameState = await program.account.game.fetch(game);
|
||
expect(gameState.turn).to.equal(expectedTurn);
|
||
expect(gameState.state).to.eql(expectedGameState);
|
||
expect(gameState.board).to.eql(expectedBoard);
|
||
}
|
||
</code></pre>
|
||
<p>You can create then a new <code>it</code> test, setup the game like in the previous test, but then keep calling the <code>play</code> function you just added to simulate a complete run of the game. Let's begin with the first turn:</p>
|
||
<pre><code class="language-typescript">it("player one wins", async () => {
|
||
const gameKeypair = anchor.web3.Keypair.generate();
|
||
const playerOne = program.provider.wallet;
|
||
const playerTwo = anchor.web3.Keypair.generate();
|
||
await program.methods
|
||
.setupGame(playerTwo.publicKey)
|
||
.accounts({
|
||
game: gameKeypair.publicKey,
|
||
playerOne: playerOne.publicKey,
|
||
})
|
||
.signers([gameKeypair])
|
||
.rpc();
|
||
|
||
let gameState = await program.account.game.fetch(gameKeypair.publicKey);
|
||
expect(gameState.turn).to.equal(1);
|
||
expect(gameState.players).to.eql([playerOne.publicKey, playerTwo.publicKey]);
|
||
expect(gameState.state).to.eql({ active: {} });
|
||
expect(gameState.board).to.eql([
|
||
[null, null, null],
|
||
[null, null, null],
|
||
[null, null, null],
|
||
]);
|
||
|
||
await play(
|
||
program,
|
||
gameKeypair.publicKey,
|
||
playerOne,
|
||
{ row: 0, column: 0 },
|
||
2,
|
||
{ active: {} },
|
||
[
|
||
[{ x: {} }, null, null],
|
||
[null, null, null],
|
||
[null, null, null],
|
||
]
|
||
);
|
||
});
|
||
</code></pre>
|
||
<p>and run <code>anchor test</code>.</p>
|
||
<p>You can finish writing the test by yourself (or check out <a href="https://github.com/coral-xyz/anchor-book/tree/master/programs/tic-tac-toe">the reference implementation</a>). Try to simulate a win and a tie!</p>
|
||
<p>Proper testing also includes tests that try to exploit the contract. You can check whether you've protected yourself properly by calling <code>play</code> with unexpected parameters. You can also familiarize yourself with the returned <code>AnchorErrors</code> this way. For example:</p>
|
||
<pre><code class="language-typescript">try {
|
||
await play(
|
||
program,
|
||
gameKeypair.publicKey,
|
||
playerTwo,
|
||
{ row: 5, column: 1 }, // ERROR: out of bounds row
|
||
4,
|
||
{ active: {} },
|
||
[
|
||
[{ x: {} }, { x: {} }, null],
|
||
[{ o: {} }, null, null],
|
||
[null, null, null],
|
||
]
|
||
);
|
||
// we use this to make sure we definitely throw an error
|
||
chai.assert(false, "should've failed but didn't ");
|
||
} catch (_err) {
|
||
expect(_err).to.be.instanceOf(AnchorError);
|
||
const err: AnchorError = _err;
|
||
expect(err.error.errorCode.number).to.equal(6000);
|
||
}
|
||
</code></pre>
|
||
<p>or</p>
|
||
<pre><code class="language-typescript">try {
|
||
await play(
|
||
program,
|
||
gameKeypair.publicKey,
|
||
playerOne, // ERROR: same player in subsequent turns
|
||
|
||
// change sth about the tx because
|
||
// duplicate tx that come in too fast
|
||
// after each other may get dropped
|
||
{ row: 1, column: 0 },
|
||
2,
|
||
{ active: {} },
|
||
[
|
||
[{ x: {} }, null, null],
|
||
[null, null, null],
|
||
[null, null, null],
|
||
]
|
||
);
|
||
chai.assert(false, "should've failed but didn't ");
|
||
} catch (_err) {
|
||
expect(_err).to.be.instanceOf(AnchorError);
|
||
const err: AnchorError = _err;
|
||
expect(err.error.errorCode.code).to.equal("NotPlayersTurn");
|
||
expect(err.error.errorCode.number).to.equal(6003);
|
||
expect(err.program.equals(program.programId)).is.true;
|
||
expect(err.error.comparedValues).to.deep.equal([
|
||
playerTwo.publicKey,
|
||
playerOne.publicKey,
|
||
]);
|
||
}
|
||
</code></pre>
|
||
<h2 id="deployment"><a class="header" href="#deployment">Deployment</a></h2>
|
||
<p>Solana has three main clusters: <code>mainnet-beta</code>, <code>devnet</code>, and <code>testnet</code>.
|
||
For developers, <code>devnet</code> and <code>mainnet-beta</code> are the most interesting. <code>devnet</code> is where you test your application in a more realistic environment than <code>localnet</code>. <code>testnet</code> is mostly for validators.</p>
|
||
<p>We are going to deploy on <code>devnet</code>.</p>
|
||
<p>Here is your deployment checklist 🚀</p>
|
||
<ol>
|
||
<li>Run <code>anchor build</code>. Your program keypair is now in <code>target/deploy</code>. Keep this keypair secret. You can reuse it on all clusters.</li>
|
||
<li>Run <code>anchor keys list</code> to display the keypair's public key and copy it into your <code>declare_id!</code> macro at the top of <code>lib.rs</code>.</li>
|
||
<li>Run <code>anchor build</code> again. This step is necessary to include the new program id in the binary.</li>
|
||
<li>Change the <code>provider.cluster</code> variable in <code>Anchor.toml</code> to <code>devnet</code>.</li>
|
||
<li>Run <code>anchor deploy</code></li>
|
||
<li>Run <code>anchor test</code></li>
|
||
</ol>
|
||
<p>There is more to deployments than this e.g. understanding how the BPFLoader works, how to manage keys, how to upgrade your programs and more. Keep reading to learn more!</p>
|
||
<h2 id="program-directory-organization"><a class="header" href="#program-directory-organization">Program directory organization</a></h2>
|
||
<blockquote>
|
||
<p><a href="https://github.com/coral-xyz/anchor-book/tree/master/programs/tic-tac-toe">Program Code</a></p>
|
||
</blockquote>
|
||
<p>Eventually, some programs become too big to keep them in a single file and it makes sense to break them up.</p>
|
||
<p>Splitting a program into multiple files works almost the exact same way as splitting up a regular rust program, so if you haven't already, now is the time to read all about that in the <a href="https://doc.rust-lang.org/book/ch07-00-managing-growing-projects-with-packages-crates-and-modules.html">rust book</a>.</p>
|
||
<p>We recommend the following directory structure (using the tic-tac-toe program as an example):</p>
|
||
<pre><code>.
|
||
+-- lib.rs
|
||
+-- errors.rs
|
||
+-- instructions
|
||
| +-- play.rs
|
||
| +-- setup_game.rs
|
||
| +-- mod.rs
|
||
+-- state
|
||
| +-- game.rs
|
||
| +-- mod.rs
|
||
</code></pre>
|
||
<p>The crucial difference to a normal rust layout is the way that instructions have to be imported. The <code>lib.rs</code> file has to import each instruction module with a wildcard import (e.g. <code>use instructions::play::*;</code>). This has to be done because the <code>#[program]</code> macro depends on generated code inside each instruction file.</p>
|
||
<p>To make the imports shorter you can re-export the instruction modules in the <code>mod.rs</code> file in the instructions directory with the <code>pub use</code> syntax and then import all instructions in the <code>lib.rs</code> file with <code>use instructions::*;</code>.</p>
|
||
<p>Well done! You've finished the essentials section. You can now move on to the more advanced parts of Anchor.</p>
|
||
<div style="break-before: page; page-break-before: always;"></div><h1 id="intermediate"><a class="header" href="#intermediate">Intermediate</a></h1>
|
||
<p>This chapter teaches you intermediate anchor concepts like PDAs and Cross-Program Invocations.</p>
|
||
<div style="break-before: page; page-break-before: always;"></div><h1 id="cross-program-invocations"><a class="header" href="#cross-program-invocations">Cross-Program Invocations</a></h1>
|
||
<p>Often it's useful for programs to interact with each other. In Solana this is achieved via Cross-Program Invocations (CPIs).</p>
|
||
<p>Consider the following example of a puppet and a puppet master. Admittedly, it is not very realistic but it allows us to show you the many nuances of CPIs. The milestone project of the intermediate section covers a more realistic program with multiple CPIs.</p>
|
||
<h2 id="setting-up-basic-cpi-functionality"><a class="header" href="#setting-up-basic-cpi-functionality">Setting up basic CPI functionality</a></h2>
|
||
<p>Create a new workspace</p>
|
||
<pre><code>anchor init puppet
|
||
</code></pre>
|
||
<p>and copy the following code.</p>
|
||
<pre><code class="language-rust ignore">use anchor_lang::prelude::*;
|
||
|
||
declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
|
||
|
||
#[program]
|
||
pub mod puppet {
|
||
use super::*;
|
||
pub fn initialize(_ctx: Context<Initialize>) -> Result<()> {
|
||
Ok(())
|
||
}
|
||
|
||
pub fn set_data(ctx: Context<SetData>, data: u64) -> Result<()> {
|
||
let puppet = &mut ctx.accounts.puppet;
|
||
puppet.data = data;
|
||
Ok(())
|
||
}
|
||
}
|
||
|
||
#[derive(Accounts)]
|
||
pub struct Initialize<'info> {
|
||
#[account(init, payer = user, space = 8 + 8)]
|
||
pub puppet: Account<'info, Data>,
|
||
#[account(mut)]
|
||
pub user: Signer<'info>,
|
||
pub system_program: Program<'info, System>,
|
||
}
|
||
|
||
#[derive(Accounts)]
|
||
pub struct SetData<'info> {
|
||
#[account(mut)]
|
||
pub puppet: Account<'info, Data>,
|
||
}
|
||
|
||
#[account]
|
||
pub struct Data {
|
||
pub data: u64,
|
||
}
|
||
</code></pre>
|
||
<p>There's nothing special happening here. It's a pretty simple program! The interesting part is how it interacts with the next program we are going to create.</p>
|
||
<p>Run</p>
|
||
<pre><code>anchor new puppet-master
|
||
</code></pre>
|
||
<p>inside the workspace and copy the following code:</p>
|
||
<pre><code class="language-rust ignore">use anchor_lang::prelude::*;
|
||
use puppet::cpi::accounts::SetData;
|
||
use puppet::program::Puppet;
|
||
use puppet::{self, Data};
|
||
|
||
declare_id!("HmbTLCmaGvZhKnn1Zfa1JVnp7vkMV4DYVxPLWBVoN65L");
|
||
|
||
#[program]
|
||
mod puppet_master {
|
||
use super::*;
|
||
pub fn pull_strings(ctx: Context<PullStrings>, data: u64) -> Result<()> {
|
||
let cpi_program = ctx.accounts.puppet_program.to_account_info();
|
||
let cpi_accounts = SetData {
|
||
puppet: ctx.accounts.puppet.to_account_info(),
|
||
};
|
||
let cpi_ctx = CpiContext::new(cpi_program, cpi_accounts);
|
||
puppet::cpi::set_data(cpi_ctx, data)
|
||
}
|
||
}
|
||
|
||
#[derive(Accounts)]
|
||
pub struct PullStrings<'info> {
|
||
#[account(mut)]
|
||
pub puppet: Account<'info, Data>,
|
||
pub puppet_program: Program<'info, Puppet>,
|
||
}
|
||
</code></pre>
|
||
<p>Also add the line <code>puppet_master = "HmbTLCmaGvZhKnn1Zfa1JVnp7vkMV4DYVxPLWBVoN65L"</code> in the <code>[programs.localnet]</code> section of your <code>Anchor.toml</code>. Finally, import the puppet program into the puppet-master program by adding the following line to the <code>[dependencies]</code> section of the <code>Cargo.toml</code> file inside the <code>puppet-master</code> program folder:</p>
|
||
<pre><code class="language-toml">puppet = { path = "../puppet", features = ["cpi"]}
|
||
</code></pre>
|
||
<p>The <code>features = ["cpi"]</code> is used so we can not only use puppet's types but also its instruction builders and cpi functions. Without those, we would have to use low level solana syscalls. Fortunately, anchor provides abstractions on top of those. By enabling the <code>cpi</code> feature, the puppet-master program gets access to the <code>puppet::cpi</code> module. Anchor generates this module automatically and it contains tailor-made instructions builders and cpi helpers for the program.</p>
|
||
<p>In the case of the puppet program, the puppet-master uses the <code>SetData</code> instruction builder struct provided by the <code>puppet::cpi::accounts</code> module to submit the accounts the <code>SetData</code> instruction of the puppet program expects. Then, the puppet-master creates a new cpi context and passes it to the <code>puppet::cpi::set_data</code> cpi function. This function has the exact same function as the <code>set_data</code> function in the puppet program with the exception that it expects a <code>CpiContext</code> instead of a <code>Context</code>.</p>
|
||
<p>Setting up a CPI can distract from the business logic of the program so it's recommended to move the CPI setup into the <code>impl</code> block of the instruction. The puppet-master program then looks like this:</p>
|
||
<pre><code class="language-rust ignore">use anchor_lang::prelude::*;
|
||
use puppet::cpi::accounts::SetData;
|
||
use puppet::program::Puppet;
|
||
use puppet::{self, Data};
|
||
|
||
declare_id!("HmbTLCmaGvZhKnn1Zfa1JVnp7vkMV4DYVxPLWBVoN65L");
|
||
|
||
#[program]
|
||
mod puppet_master {
|
||
use super::*;
|
||
pub fn pull_strings(ctx: Context<PullStrings>, data: u64) -> Result<()> {
|
||
puppet::cpi::set_data(ctx.accounts.set_data_ctx(), data)
|
||
}
|
||
}
|
||
|
||
#[derive(Accounts)]
|
||
pub struct PullStrings<'info> {
|
||
#[account(mut)]
|
||
pub puppet: Account<'info, Data>,
|
||
pub puppet_program: Program<'info, Puppet>,
|
||
}
|
||
|
||
impl<'info> PullStrings<'info> {
|
||
pub fn set_data_ctx(&self) -> CpiContext<'_, '_, '_, 'info, SetData<'info>> {
|
||
let cpi_program = self.puppet_program.to_account_info();
|
||
let cpi_accounts = SetData {
|
||
puppet: self.puppet.to_account_info()
|
||
};
|
||
CpiContext::new(cpi_program, cpi_accounts)
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>We can verify that everything works as expected by replacing the contents of the <code>puppet.ts</code> file with:</p>
|
||
<pre><code class="language-ts">import * as anchor from "@coral-xyz/anchor";
|
||
import { Program } from "@coral-xyz/anchor";
|
||
import { Keypair } from "@solana/web3.js";
|
||
import { expect } from "chai";
|
||
import { Puppet } from "../target/types/puppet";
|
||
import { PuppetMaster } from "../target/types/puppet_master";
|
||
|
||
describe("puppet", () => {
|
||
const provider = anchor.AnchorProvider.env();
|
||
anchor.setProvider(provider);
|
||
|
||
const puppetProgram = anchor.workspace.Puppet as Program<Puppet>;
|
||
const puppetMasterProgram = anchor.workspace
|
||
.PuppetMaster as Program<PuppetMaster>;
|
||
|
||
const puppetKeypair = Keypair.generate();
|
||
|
||
it("Does CPI!", async () => {
|
||
await puppetProgram.methods
|
||
.initialize()
|
||
.accounts({
|
||
puppet: puppetKeypair.publicKey,
|
||
user: provider.wallet.publicKey,
|
||
})
|
||
.signers([puppetKeypair])
|
||
.rpc();
|
||
|
||
await puppetMasterProgram.methods
|
||
.pullStrings(new anchor.BN(42))
|
||
.accounts({
|
||
puppetProgram: puppetProgram.programId,
|
||
puppet: puppetKeypair.publicKey,
|
||
})
|
||
.rpc();
|
||
|
||
expect(
|
||
(
|
||
await puppetProgram.account.data.fetch(puppetKeypair.publicKey)
|
||
).data.toNumber()
|
||
).to.equal(42);
|
||
});
|
||
});
|
||
</code></pre>
|
||
<p>and running <code>anchor test</code>.</p>
|
||
<h2 id="privilege-extension"><a class="header" href="#privilege-extension">Privilege Extension</a></h2>
|
||
<p>CPIs extend the privileges of the caller to the callee. The puppet account was passed as a mutable account to the puppet-master but it was still mutable in the puppet program as well (otherwise the <code>expect</code> in the test would've failed). The same applies to signatures.</p>
|
||
<p>If you want to prove this for yourself, add an <code>authority</code> field to the <code>Data</code> struct in the puppet program.</p>
|
||
<pre><code class="language-rust ignore">#[account]
|
||
pub struct Data {
|
||
pub data: u64,
|
||
pub authority: Pubkey
|
||
}
|
||
</code></pre>
|
||
<p>and adjust the <code>initialize</code> function:</p>
|
||
<pre><code class="language-rust ignore">pub fn initialize(ctx: Context<Initialize>, authority: Pubkey) -> Result<()> {
|
||
ctx.accounts.puppet.authority = authority;
|
||
Ok(())
|
||
}
|
||
</code></pre>
|
||
<p>Add <code>32</code> to the <code>space</code> constraint of the <code>puppet</code> field for the <code>Pubkey</code> field in the <code>Data</code> struct.</p>
|
||
<pre><code class="language-rust ignore">#[derive(Accounts)]
|
||
pub struct Initialize<'info> {
|
||
#[account(init, payer = user, space = 8 + 8 + 32)]
|
||
pub puppet: Account<'info, Data>,
|
||
#[account(mut)]
|
||
pub user: Signer<'info>,
|
||
pub system_program: Program<'info, System>,
|
||
}
|
||
</code></pre>
|
||
<p>Then, adjust the <code>SetData</code> validation struct:</p>
|
||
<pre><code class="language-rust ignore">#[derive(Accounts)]
|
||
pub struct SetData<'info> {
|
||
#[account(mut, has_one = authority)]
|
||
pub puppet: Account<'info, Data>,
|
||
pub authority: Signer<'info>
|
||
}
|
||
</code></pre>
|
||
<p>The <code>has_one</code> constraint checks that <code>puppet.authority = authority.key()</code>.</p>
|
||
<p>The puppet-master program now also needs adjusting:</p>
|
||
<pre><code class="language-rust ignore">use anchor_lang::prelude::*;
|
||
use puppet::cpi::accounts::SetData;
|
||
use puppet::program::Puppet;
|
||
use puppet::{self, Data};
|
||
|
||
declare_id!("HmbTLCmaGvZhKnn1Zfa1JVnp7vkMV4DYVxPLWBVoN65L");
|
||
|
||
#[program]
|
||
mod puppet_master {
|
||
use super::*;
|
||
pub fn pull_strings(ctx: Context<PullStrings>, data: u64) -> Result<()> {
|
||
puppet::cpi::set_data(ctx.accounts.set_data_ctx(), data)
|
||
}
|
||
}
|
||
|
||
#[derive(Accounts)]
|
||
pub struct PullStrings<'info> {
|
||
#[account(mut)]
|
||
pub puppet: Account<'info, Data>,
|
||
pub puppet_program: Program<'info, Puppet>,
|
||
// Even though the puppet program already checks that authority is a signer
|
||
// using the Signer type here is still required because the anchor ts client
|
||
// can not infer signers from programs called via CPIs
|
||
pub authority: Signer<'info>
|
||
}
|
||
|
||
impl<'info> PullStrings<'info> {
|
||
pub fn set_data_ctx(&self) -> CpiContext<'_, '_, '_, 'info, SetData<'info>> {
|
||
let cpi_program = self.puppet_program.to_account_info();
|
||
let cpi_accounts = SetData {
|
||
puppet: self.puppet.to_account_info(),
|
||
authority: self.authority.to_account_info()
|
||
};
|
||
CpiContext::new(cpi_program, cpi_accounts)
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>Finally, change the test:</p>
|
||
<pre><code class="language-ts">import * as anchor from "@coral-xyz/anchor";
|
||
import { Program } from "@coral-xyz/anchor";
|
||
import { Keypair } from "@solana/web3.js";
|
||
import { Puppet } from "../target/types/puppet";
|
||
import { PuppetMaster } from "../target/types/puppet_master";
|
||
import { expect } from "chai";
|
||
|
||
describe("puppet", () => {
|
||
const provider = anchor.AnchorProvider.env();
|
||
anchor.setProvider(provider);
|
||
|
||
const puppetProgram = anchor.workspace.Puppet as Program<Puppet>;
|
||
const puppetMasterProgram = anchor.workspace
|
||
.PuppetMaster as Program<PuppetMaster>;
|
||
|
||
const puppetKeypair = Keypair.generate();
|
||
const authorityKeypair = Keypair.generate();
|
||
|
||
it("Does CPI!", async () => {
|
||
await puppetProgram.methods
|
||
.initialize(authorityKeypair.publicKey)
|
||
.accounts({
|
||
puppet: puppetKeypair.publicKey,
|
||
user: provider.wallet.publicKey,
|
||
})
|
||
.signers([puppetKeypair])
|
||
.rpc();
|
||
|
||
await puppetMasterProgram.methods
|
||
.pullStrings(new anchor.BN(42))
|
||
.accounts({
|
||
puppetProgram: puppetProgram.programId,
|
||
puppet: puppetKeypair.publicKey,
|
||
authority: authorityKeypair.publicKey,
|
||
})
|
||
.signers([authorityKeypair])
|
||
.rpc();
|
||
|
||
expect(
|
||
(
|
||
await puppetProgram.account.data.fetch(puppetKeypair.publicKey)
|
||
).data.toNumber()
|
||
).to.equal(42);
|
||
});
|
||
});
|
||
</code></pre>
|
||
<p>The test passes because the signature that was given to the puppet-master by the authority was then extended to the puppet program which used it to check that the authority for the puppet account had signed the transaction.</p>
|
||
<blockquote>
|
||
<p>Privilege extension is convenient but also dangerous. If a CPI is unintentionally made to a malicious program,
|
||
this program has the same privileges as the caller.
|
||
Anchor protects you from CPIs to malicious programs with two measures.
|
||
First, the <code>Program<'info, T></code> type checks that the given account is the expected program <code>T</code>.
|
||
Should you ever forget to use the <code>Program</code> type, the automatically generated cpi function
|
||
(in the previous example this was <code>puppet::cpi::set_data</code>)
|
||
also checks that the <code>cpi_program</code> argument equals the expected program.</p>
|
||
</blockquote>
|
||
<h2 id="reloading-an-account"><a class="header" href="#reloading-an-account">Reloading an Account</a></h2>
|
||
<p>In the puppet program, the <code>Account<'info, T></code> type is used for the <code>puppet</code> account. If a CPI edits an account of that type,
|
||
the caller's account does not change during the instruction.</p>
|
||
<p>You can easily see this for yourself by adding the following right after the <code>puppet::cpi::set_data(ctx.accounts.set_data_ctx(), data)</code> cpi call.</p>
|
||
<pre><code class="language-rust ignore">puppet::cpi::set_data(ctx.accounts.set_data_ctx(), data)?;
|
||
if ctx.accounts.puppet.data != 42 {
|
||
panic!();
|
||
}
|
||
Ok(())
|
||
</code></pre>
|
||
<p>Now your test will fail. But why? After all the test used to pass, so the cpi definitely did change the <code>data</code> field to <code>42</code>.</p>
|
||
<p>The reason the <code>data</code> field has not been updated to <code>42</code> in the caller is that at the beginning of the instruction the <code>Account<'info, T></code> type deserializes the incoming bytes into a new struct. This struct is no longer connected to the underlying data in the account. The CPI changes the data in the underlying account but since the struct in the caller has no connection to the underlying account the struct in the caller remains unchanged.</p>
|
||
<p>If you need to read the value of an account that has just been changed by a CPI, you can call its <code>reload</code> method which will re-deserialize the account. If you put <code>ctx.accounts.puppet.reload()?;</code> right after the cpi call, the test will pass again.</p>
|
||
<pre><code class="language-rust ignore">puppet::cpi::set_data(ctx.accounts.set_data_ctx(), data)?;
|
||
ctx.accounts.puppet.reload()?;
|
||
if ctx.accounts.puppet.data != 42 {
|
||
panic!();
|
||
}
|
||
Ok(())
|
||
</code></pre>
|
||
<h2 id="returning-values-from-handler-functions"><a class="header" href="#returning-values-from-handler-functions">Returning values from handler functions</a></h2>
|
||
<p>The Anchor handler functions are capable of returning data using the Solana <code>set_return_data</code> and <code>get_return_data</code> syscalls. This data can be used in CPI callers and clients.</p>
|
||
<p>Instead of returning a <code>Result<()></code>, consider this version of the <code>set_data</code> function from above which has been modified to return <code>Result<u64></code>:</p>
|
||
<pre><code class="language-rust ignore">pub fn set_data(ctx: Context<SetData>, data: u64) -> Result<u64> {
|
||
let puppet = &mut ctx.accounts.puppet;
|
||
puppet.data = data;
|
||
Ok(data)
|
||
}
|
||
</code></pre>
|
||
<p>Defining a return type that isn't the unit type <code>()</code> will cause Anchor to transparently call <code>set_return_data</code> with the given type (<code>u64</code> in this example) when this function is called. The return from the CPI call is wrapped in a struct to allow for lazy retrieval of this return data. E.g.</p>
|
||
<pre><code class="language-rust ignore">pub fn pull_strings(ctx: Context<PullStrings>, data: u64) -> Result<()> {
|
||
let cpi_program = ctx.accounts.puppet_program.to_account_info();
|
||
let cpi_accounts = SetData {
|
||
puppet: ctx.accounts.puppet.to_account_info(),
|
||
};
|
||
let cpi_ctx = CpiContext::new(cpi_program, cpi_accounts);
|
||
let result = puppet::cpi::set_data(cpi_ctx, data)?;
|
||
// The below statement calls sol_get_return and deserializes the result.
|
||
// `return_data` contains the return from `set_data`,
|
||
// which in this example is just `data`.
|
||
let return_data = result.get();
|
||
// ... do something with the `return_data` ...
|
||
}
|
||
</code></pre>
|
||
<p>Note that the type being returned must implement the <code>AnchorSerialize</code> and <code>AnchorDeserialize</code> traits, for example:</p>
|
||
<pre><code class="language-rust ignore">#[derive(AnchorSerialize, AnchorDeserialize)]
|
||
pub struct StructReturn {
|
||
pub value: u64,
|
||
}
|
||
</code></pre>
|
||
<h3 id="reading-return-data-in-the-clients"><a class="header" href="#reading-return-data-in-the-clients">Reading return data in the clients</a></h3>
|
||
<p>It's even possible to use return values without CPIs. This may be useful if you're using a function to calculate a value that you need on the frontend without rewriting the code in the frontend.</p>
|
||
<p>Whether you're using a CPI or not, you can use the <code>view</code> function to read whatever was set last as return data in the transaction (<code>view</code> simulates the transaction and reads the <code>Program return</code> log).</p>
|
||
<p>For example:</p>
|
||
<pre><code class="language-typescript ignore">const returnData = await program.methods
|
||
.calculate(someVariable)
|
||
.accounts({
|
||
acc: somePubkey,
|
||
anotherAcc: someOtherPubkey
|
||
})
|
||
.view();
|
||
</code></pre>
|
||
<h3 id="return-data-size-limit-workarounds"><a class="header" href="#return-data-size-limit-workarounds">Return Data Size Limit Workarounds</a></h3>
|
||
<p>The <code>set_return_data</code> and <code>get_return_data</code> syscalls are limited to 1024 bytes so it's worth briefly explaining the old workaround for CPI return values.</p>
|
||
<p>By using a CPI together with <code>reload</code> it's possible to simulate return values. One could imagine that instead of just setting the <code>data</code> field to <code>42</code> the puppet program did some calculation with the <code>42</code> and saved the result in <code>data</code>. The puppet-master can then call <code>reload</code> after the cpi and use the result of the puppet program's calculation.</p>
|
||
<h2 id="programs-as-signers"><a class="header" href="#programs-as-signers">Programs as Signers</a></h2>
|
||
<p>There's one more thing that can be done with CPIs. But for that, you need to first learn what PDAs are. We'll cover those in the next chapter.</p>
|
||
<div style="break-before: page; page-break-before: always;"></div><h1 id="pdas"><a class="header" href="#pdas">PDAs</a></h1>
|
||
<p>Knowing how to use PDAs is one of the most important skills for Solana Programming.
|
||
They simplify the programming model and make programs more secure. So what are they?</p>
|
||
<p>PDAs (program derived addresses) are addresses with special properties.</p>
|
||
<p>Unlike normal addresses, PDAs are not public keys and therefore do not have an associated private key. There are two use cases for PDAs. They provide a mechanism to build hashmap-like structures on-chain and they allow programs to sign instructions.</p>
|
||
<h2 id="creation-of-a-pda"><a class="header" href="#creation-of-a-pda">Creation of a PDA</a></h2>
|
||
<p>Before we dive into how to use PDAs in anchor, here's a short explainer on what PDAs are.</p>
|
||
<p>PDAs are created by hashing a number of seeds the user can choose and the id of a program:</p>
|
||
<pre><code class="language-rust ignore">// pseudo code
|
||
let pda = hash(seeds, program_id);
|
||
</code></pre>
|
||
<p>The seeds can be anything. A pubkey, a string, an array of numbers etc.</p>
|
||
<p>There's a 50% chance that this hash function results in a public key (but PDAs are not public keys), so a bump has to be searched for so that we get a PDA:</p>
|
||
<pre><code class="language-rust ignore">// pseudo code
|
||
fn find_pda(seeds, program_id) {
|
||
for bump in 0..256 {
|
||
let potential_pda = hash(seeds, bump, program_id);
|
||
if is_pubkey(potential_pda) {
|
||
continue;
|
||
}
|
||
return (potential_pda, bump);
|
||
}
|
||
panic!("Could not find pda after 256 tries.");
|
||
}
|
||
</code></pre>
|
||
<p>It is technically possible that no bump is found within 256 tries but this probability is negligible.
|
||
If you're interested in the exact calculation of a PDA, check out the <a href="https://docs.rs/solana-program/latest/solana_program/pubkey/struct.Pubkey.html#method.find_program_address"><code>solana_program</code> source code</a>.</p>
|
||
<p>The first bump that results in a PDA is commonly called the "canonical bump". Other bumps may also result in a PDA but it's recommended to only use the canonical bump to avoid confusion.</p>
|
||
<h2 id="using-pdas"><a class="header" href="#using-pdas">Using PDAs</a></h2>
|
||
<p>We are now going to show you what you can do with PDAs and how to do it in Anchor!</p>
|
||
<h3 id="hashmap-like-structures-using-pdas"><a class="header" href="#hashmap-like-structures-using-pdas">Hashmap-like structures using PDAs</a></h3>
|
||
<p>Before we dive into the specifics of creating hashmaps in anchor, let's look at how to create a hashmap with PDAs in general.</p>
|
||
<h4 id="building-hashmaps-with-pdas"><a class="header" href="#building-hashmaps-with-pdas">Building hashmaps with PDAs</a></h4>
|
||
<p>PDAs are hashed from the bump, a program id, but also a number of seeds which can be freely chosen by the user.
|
||
These seeds can be used to build hashmap-like structures on-chain.</p>
|
||
<p>For instance, imagine you're building an in-browser game and want to store some user stats. Maybe their level and their in-game name. You could create an account with a layout that looks like this:</p>
|
||
<pre><code class="language-rust ignore">pub struct UserStats {
|
||
level: u16,
|
||
name: String,
|
||
authority: Pubkey
|
||
}
|
||
</code></pre>
|
||
<p>The <code>authority</code> would be the user the accounts belongs to.</p>
|
||
<p>This approach creates the following problem. It's easy to go from the user stats account to the user account address (just read the <code>authority</code> field) but if you just have the user account address (which is more likely), how do you find the user stats account? You can't. This is a problem because your game probably has instructions that require both the user stats account and its authority which means the client needs to pass those accounts into the instruction (for example, a <code>ChangeName</code> instruction). So maybe the frontend could store a mapping between a user's account address and a user's info address in local storage. This works until the user accidentally wipes their local storage.</p>
|
||
<p>With PDAs you can have a layout like this:</p>
|
||
<pre><code class="language-rust ignore">pub struct UserStats {
|
||
level: u16,
|
||
name: String,
|
||
bump: u8
|
||
}
|
||
</code></pre>
|
||
<p>and encode the information about the relationship between the user and the user stats account in the address of the user stats account itself.</p>
|
||
<p>Reusing the pseudo code from above:</p>
|
||
<pre><code class="language-rust ignore">// pseudo code
|
||
let seeds = [b"user-stats", authority];
|
||
let (pda, bump) = find_pda(seeds, game_program_id);
|
||
</code></pre>
|
||
<p>When a user connects to your website, this pda calculation can be done client-side using their user account address as the <code>authority</code>. The resulting pda then serves as the address of the user's stats account. The <code>b"user-stats"</code> is added in case there are other account types that are also PDAs. If there were an inventory account, it could be inferred using these seeds:</p>
|
||
<pre><code class="language-rust ignore">let seeds = [b"inventory", authority];
|
||
</code></pre>
|
||
<p>To summarize, we have used PDAs to create a mapping between a user and their user stats account. There is no single hashmap object that exposes a <code>get</code> function. Instead, each value (the user stats address) can be found by using certain seeds ("user-stats" and the user account address) as inputs to the <code>find_pda</code> function.</p>
|
||
<h4 id="how-to-build-pda-hashmaps-in-anchor"><a class="header" href="#how-to-build-pda-hashmaps-in-anchor">How to build PDA hashmaps in Anchor</a></h4>
|
||
<p>Continuing with the example from the previous sections, create a new workspace</p>
|
||
<pre><code>anchor init game
|
||
</code></pre>
|
||
<p>and copy the following code</p>
|
||
<pre><code class="language-rust ignore">use anchor_lang::prelude::*;
|
||
|
||
declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
|
||
|
||
#[program]
|
||
pub mod game {
|
||
use super::*;
|
||
// handler function
|
||
pub fn create_user_stats(ctx: Context<CreateUserStats>, name: String) -> Result<()> {
|
||
let user_stats = &mut ctx.accounts.user_stats;
|
||
user_stats.level = 0;
|
||
if name.as_bytes().len() > 200 {
|
||
// proper error handling omitted for brevity
|
||
panic!();
|
||
}
|
||
user_stats.name = name;
|
||
user_stats.bump = ctx.bumps.user_stats;
|
||
Ok(())
|
||
}
|
||
}
|
||
|
||
#[account]
|
||
pub struct UserStats {
|
||
level: u16,
|
||
name: String,
|
||
bump: u8,
|
||
}
|
||
|
||
// validation struct
|
||
#[derive(Accounts)]
|
||
pub struct CreateUserStats<'info> {
|
||
#[account(mut)]
|
||
pub user: Signer<'info>,
|
||
// space: 8 discriminator + 2 level + 4 name length + 200 name + 1 bump
|
||
#[account(
|
||
init,
|
||
payer = user,
|
||
space = 8 + 2 + 4 + 200 + 1, seeds = [b"user-stats", user.key().as_ref()], bump
|
||
)]
|
||
pub user_stats: Account<'info, UserStats>,
|
||
pub system_program: Program<'info, System>,
|
||
}
|
||
</code></pre>
|
||
<p>In the account validation struct we use <code>seeds</code> together with <code>init</code> to create a PDA with the desired seeds.
|
||
Additionally, we add an empty <code>bump</code> constraint to signal to anchor that it should find the canonical bump itself.
|
||
Then, in the handler, we access <code>ctx.bumps.user_stats</code> to get the bump anchor found and save it to the user stats
|
||
account as an extra property.</p>
|
||
<p>If we then want to use the created pda in a different instruction, we can add a new validation struct (This will check that the <code>user_stats</code> account is the pda created by running <code>hash(seeds, user_stats.bump, game_program_id)</code>):</p>
|
||
<pre><code class="language-rust ignore">// validation struct
|
||
#[derive(Accounts)]
|
||
pub struct ChangeUserName<'info> {
|
||
pub user: Signer<'info>,
|
||
#[account(mut, seeds = [b"user-stats", user.key().as_ref()], bump = user_stats.bump)]
|
||
pub user_stats: Account<'info, UserStats>,
|
||
}
|
||
</code></pre>
|
||
<p>and another handler function:</p>
|
||
<pre><code class="language-rust ignore">// handler function (add this next to the create_user_stats function in the game module)
|
||
pub fn change_user_name(ctx: Context<ChangeUserName>, new_name: String) -> Result<()> {
|
||
if new_name.as_bytes().len() > 200 {
|
||
// proper error handling omitted for brevity
|
||
panic!();
|
||
}
|
||
ctx.accounts.user_stats.name = new_name;
|
||
Ok(())
|
||
}
|
||
</code></pre>
|
||
<p>Finally, let's add a test. Copy this into <code>game.ts</code></p>
|
||
<pre><code class="language-ts">import * as anchor from "@coral-xyz/anchor";
|
||
import { Program } from "@coral-xyz/anchor";
|
||
import { PublicKey } from "@solana/web3.js";
|
||
import { Game } from "../target/types/game";
|
||
import { expect } from "chai";
|
||
|
||
describe("game", async () => {
|
||
const provider = anchor.AnchorProvider.env();
|
||
anchor.setProvider(provider);
|
||
|
||
const program = anchor.workspace.Game as Program<Game>;
|
||
|
||
it("Sets and changes name!", async () => {
|
||
const [userStatsPDA, _] = await PublicKey.findProgramAddress(
|
||
[
|
||
anchor.utils.bytes.utf8.encode("user-stats"),
|
||
provider.wallet.publicKey.toBuffer(),
|
||
],
|
||
program.programId
|
||
);
|
||
|
||
await program.methods
|
||
.createUserStats("brian")
|
||
.accounts({
|
||
user: provider.wallet.publicKey,
|
||
userStats: userStatsPDA,
|
||
})
|
||
.rpc();
|
||
|
||
expect((await program.account.userStats.fetch(userStatsPDA)).name).to.equal(
|
||
"brian"
|
||
);
|
||
|
||
await program.methods
|
||
.changeUserName("tom")
|
||
.accounts({
|
||
user: provider.wallet.publicKey,
|
||
userStats: userStatsPDA,
|
||
})
|
||
.rpc();
|
||
|
||
expect((await program.account.userStats.fetch(userStatsPDA)).name).to.equal(
|
||
"tom"
|
||
);
|
||
});
|
||
});
|
||
</code></pre>
|
||
<p>Exactly as described in the subchapter before this one, we use a <code>find</code> function to find the PDA. We can then use it just like a normal address. Well, almost. When we call <code>createUserStats</code>, we don't have to add the PDA to the <code>[signers]</code> array even though account creation requires a signature. This is because it is impossible to sign the transaction from outside the program as the PDA (it's not a public key so there is no private key to sign with). Instead, the signature is added when the CPI to the system program is made. We're going to explain how this works in the <a href="anchor_in_depth/PDAs.html#programs-as-signers">Programs as Signers</a> section.</p>
|
||
<h4 id="enforcing-uniqueness"><a class="header" href="#enforcing-uniqueness">Enforcing uniqueness</a></h4>
|
||
<p>A subtle result of this hashmap structure is enforced uniqueness. When <code>init</code> is used with <code>seeds</code> and <code>bump</code>, it will always search for the canonical bump. This means that it can only be called once (because the 2nd time it's called the PDA will already be initialized). To illustrate how powerful enforced uniqueness is, consider a decentralized exchange program. In this program, anyone can create a new market for two assets. However, the program creators want liquidity to be concentrated so there should only be one market for every combination of two assets. This could be done without PDAs but would require a global account that saves all the different markets. Then upon market creation, the program would check whether the asset combination exists in the global market list. With PDAs this can be done in a much more straightforward way. Any market would simply be the PDA of the mint addresses of the two assets. The program would then check whether either of the two possible PDAs (because the market could've been created with the assets in reverse order) already exists.</p>
|
||
<h3 id="programs-as-signers-1"><a class="header" href="#programs-as-signers-1">Programs as Signers</a></h3>
|
||
<p>Creating PDAs requires them to sign the <code>createAccount</code> CPI of the system program. How does that work?</p>
|
||
<p>PDAs are not public keys so it's impossible for them to sign anything. However, PDAs can still pseudo sign CPIs.
|
||
In anchor, to sign with a pda you have to change <code>CpiContext::new(cpi_program, cpi_accounts)</code> to <code>CpiContext::new_with_signer(cpi_program, cpi_accounts, seeds)</code> where the <code>seeds</code> argument are the seeds <em>and</em> the bump the PDA was created with.
|
||
When the CPI is invoked, for each account in <code>cpi_accounts</code> the Solana runtime will check whether<code>hash(seeds, current_program_id) == account address</code> is true. If yes, that account's <code>is_signer</code> flag will be turned to true.
|
||
This means a PDA derived from some program X, may only be used to sign CPIs that originate from that program X. This means that on a high level, PDA signatures can be considered program signatures.</p>
|
||
<p>This is great news because for many programs it is necessary that the program itself takes the authority over some assets.
|
||
For instance, lending protocol programs need to manage deposited collateral and automated market maker programs need to manage the tokens put into their liquidity pools.</p>
|
||
<p>Let's revisit the puppet workspace and add a PDA signature.</p>
|
||
<p>First, adjust the puppet-master code:</p>
|
||
<pre><code class="language-rust ignore">use anchor_lang::prelude::*;
|
||
use puppet::cpi::accounts::SetData;
|
||
use puppet::program::Puppet;
|
||
use puppet::{self, Data};
|
||
|
||
declare_id!("HmbTLCmaGvZhKnn1Zfa1JVnp7vkMV4DYVxPLWBVoN65L");
|
||
|
||
#[program]
|
||
mod puppet_master {
|
||
use super::*;
|
||
pub fn pull_strings(ctx: Context<PullStrings>, bump: u8, data: u64) -> Result<()> {
|
||
let bump = &[bump][..];
|
||
puppet::cpi::set_data(
|
||
ctx.accounts.set_data_ctx().with_signer(&[&[bump][..]]),
|
||
data,
|
||
)
|
||
}
|
||
}
|
||
|
||
#[derive(Accounts)]
|
||
pub struct PullStrings<'info> {
|
||
#[account(mut)]
|
||
pub puppet: Account<'info, Data>,
|
||
pub puppet_program: Program<'info, Puppet>,
|
||
/// CHECK: only used as a signing PDA
|
||
pub authority: UncheckedAccount<'info>,
|
||
}
|
||
|
||
impl<'info> PullStrings<'info> {
|
||
pub fn set_data_ctx(&self) -> CpiContext<'_, '_, '_, 'info, SetData<'info>> {
|
||
let cpi_program = self.puppet_program.to_account_info();
|
||
let cpi_accounts = SetData {
|
||
puppet: self.puppet.to_account_info(),
|
||
authority: self.authority.to_account_info(),
|
||
};
|
||
CpiContext::new(cpi_program, cpi_accounts)
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>The <code>authority</code> account is now an <code>UncheckedAccount</code> instead of a <code>Signer</code>. When the puppet-master is invoked, the <code>authority</code> pda is not a signer yet so we mustn't add a check for it. We just care about the puppet-master being able to sign so we don't add any additional seeds. Just a bump that is calculated off-chain and then passed to the function.</p>
|
||
<p>Finally, this is the new <code>puppet.ts</code>:</p>
|
||
<pre><code class="language-ts">import * as anchor from "@coral-xyz/anchor";
|
||
import { Program } from "@coral-xyz/anchor";
|
||
import { Keypair, PublicKey } from "@solana/web3.js";
|
||
import { Puppet } from "../target/types/puppet";
|
||
import { PuppetMaster } from "../target/types/puppet_master";
|
||
import { expect } from "chai";
|
||
|
||
describe("puppet", () => {
|
||
const provider = anchor.AnchorProvider.env();
|
||
anchor.setProvider(provider);
|
||
|
||
const puppetProgram = anchor.workspace.Puppet as Program<Puppet>;
|
||
const puppetMasterProgram = anchor.workspace
|
||
.PuppetMaster as Program<PuppetMaster>;
|
||
|
||
const puppetKeypair = Keypair.generate();
|
||
|
||
it("Does CPI!", async () => {
|
||
const [puppetMasterPDA, puppetMasterBump] =
|
||
await PublicKey.findProgramAddress([], puppetMasterProgram.programId);
|
||
|
||
await puppetProgram.methods
|
||
.initialize(puppetMasterPDA)
|
||
.accounts({
|
||
puppet: puppetKeypair.publicKey,
|
||
user: provider.wallet.publicKey,
|
||
})
|
||
.signers([puppetKeypair])
|
||
.rpc();
|
||
|
||
await puppetMasterProgram.methods
|
||
.pullStrings(puppetMasterBump, new anchor.BN(42))
|
||
.accounts({
|
||
puppetProgram: puppetProgram.programId,
|
||
puppet: puppetKeypair.publicKey,
|
||
authority: puppetMasterPDA,
|
||
})
|
||
.rpc();
|
||
|
||
expect(
|
||
(
|
||
await puppetProgram.account.data.fetch(puppetKeypair.publicKey)
|
||
).data.toNumber()
|
||
).to.equal(42);
|
||
});
|
||
});
|
||
</code></pre>
|
||
<p>The <code>authority</code> is no longer a randomly generated keypair but a PDA derived from the puppet-master program. This means the puppet-master can sign with it which it does inside <code>pullStrings</code>. It's worth noting that our implementation also allows non-canonical bumps but again because we are only interested in being able to sign we don't care which bump is used.</p>
|
||
<blockquote>
|
||
<p>In some cases it's possible to reduce the number of accounts you need by making a PDA storing state also sign a CPI instead of defining a separate PDA to do that.</p>
|
||
</blockquote>
|
||
<h2 id="pdas-conclusion"><a class="header" href="#pdas-conclusion">PDAs: Conclusion</a></h2>
|
||
<p>This section serves as a brief recap of the different things you can do with PDAs.</p>
|
||
<p>First, you can create hashmaps with them. We created a user stats PDA which was derived from the user address. This derivation linked the user address and the user stats account, allowing the latter to be easily found given the former.
|
||
Hashmaps also result in enforced uniqueness which can be used in many different ways, e.g. for only allowing one market per two assets in a decentralized exchange.</p>
|
||
<p>Secondly, PDAs can be used to allow programs to sign CPIs. This means that programs can be given control over assets which they then manage according to the rules defined in their code.</p>
|
||
<p>You can even combine these two use cases and use a PDA that's used in an instruction as a state account to also sign a CPI.</p>
|
||
<p>Admittedly, working with PDAs is one of the most challenging parts of working with Solana.
|
||
This is why in addition to our explanations here, we want to provide you with some further resources.</p>
|
||
<ul>
|
||
<li><a href="https://twitter.com/pencilflip/status/1455948263853600768?s=20&t=J2JXCwv395D7MNkX7a9LGw">Pencilflips's twitter thread on PDAs</a></li>
|
||
<li><a href="https://www.youtube.com/watch?v=iMWaQRyjpl4">jarry xiao's talk on PDAs and CPIs</a></li>
|
||
<li><a href="https://paulx.dev/blog/2021/01/14/programming-on-solana-an-introduction/">paulx's guide on everything Solana (covers much more than PDAs)</a></li>
|
||
</ul>
|
||
<div style="break-before: page; page-break-before: always;"></div><h1 id="events"><a class="header" href="#events">Events</a></h1>
|
||
<p>Events in Anchor provide a powerful mechanism for notifying and communicating between different components of a Solana dApp. They allow for the emission and tracking of occurrences within the program's execution. This documentation will cover the concept of events in Anchor and how to use them in your program development.</p>
|
||
<h2 id="table-of-contents"><a class="header" href="#table-of-contents">Table of Contents</a></h2>
|
||
<ul>
|
||
<li><a href="anchor_in_depth/events.html#introduction-to-events">Introduction to Events</a></li>
|
||
<li><a href="anchor_in_depth/events.html#defining-events">Defining Events</a></li>
|
||
<li><a href="anchor_in_depth/events.html#emitting-events">Emitting Events</a></li>
|
||
<li><a href="anchor_in_depth/events.html#subscribing-to-events">Subscribing to Events</a></li>
|
||
<li><a href="anchor_in_depth/events.html#unsubscribing-from-events">Unsubscribing from Events</a></li>
|
||
<li><a href="anchor_in_depth/events.html#cpi-events">CPI Events</a></li>
|
||
</ul>
|
||
<h2 id="introduction-to-events"><a class="header" href="#introduction-to-events">Introduction to Events</a></h2>
|
||
<p>An event is a structured piece of data that holds information about a specific occurrence in a program. Events can be used to provide transparency, traceability, and synchronization in decentralized applications.</p>
|
||
<p>There is no native support for events in Solana. Because of this, Anchor events depends on logging in order to emit events. Programs log base64 encoded event data and clients parse the logs of the transaction to interpret the events.</p>
|
||
<p><a href="https://github.com/solana-foundation/solana-improvement-documents/pull/57">SIMD-0057</a> aims to add support for native events.</p>
|
||
<h2 id="defining-events"><a class="header" href="#defining-events">Defining Events</a></h2>
|
||
<p>Events are defined using the <code>#[event]</code> attribute macro. This macro allows you to specify the fields that an event should contain. Events can include various data types, making them versatile for different use cases.</p>
|
||
<pre><pre class="playground"><code class="language-rust">
|
||
<span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>#[event]
|
||
pub struct TransferEvent {
|
||
from: Pubkey,
|
||
to: Pubkey,
|
||
amount: u64,
|
||
}
|
||
<span class="boring">}
|
||
</span></code></pre></pre>
|
||
<p>In this example, we define an event named <code>TransferEvent</code> with three fields: <code>from</code> (sender's address), <code>to</code> (receiver's address), and <code>amount</code> (the transferred amount).</p>
|
||
<h2 id="emitting-events"><a class="header" href="#emitting-events">Emitting Events</a></h2>
|
||
<p>To emit an event within your Anchor program, you can use the <code>emit!</code> macro:</p>
|
||
<pre><pre class="playground"><code class="language-rust">
|
||
<span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>#[program]
|
||
pub mod my_program {
|
||
use super::*;
|
||
|
||
pub fn transfer(ctx: Context<TransferContext>, amount: u64) -> Result<()> {
|
||
// Perform transfer logic
|
||
|
||
// Emit the TransferEvent
|
||
emit!(TransferEvent {
|
||
from: *ctx.accounts.from.key,
|
||
to: *ctx.accounts.to.key,
|
||
amount,
|
||
});
|
||
|
||
Ok(())
|
||
}
|
||
}
|
||
<span class="boring">}
|
||
</span></code></pre></pre>
|
||
<p>In this example, when the <code>transfer</code> function is called, a <code>TransferEvent</code> is emitted using the <code>emit!</code> macro. The relevant data is populated into the event fields.</p>
|
||
<h2 id="subscribing-to-events"><a class="header" href="#subscribing-to-events">Subscribing to Events</a></h2>
|
||
<p>Anyone can subscribe to events emitted by your program using Anchor's event subscription mechanisms.</p>
|
||
<p>You can subscribe to events using Anchor TS library(<a href="https://www.npmjs.com/package/@coral-xyz/anchor">@coral-xyz/anchor</a>):</p>
|
||
<pre><code class="language-ts">const subscriptionId = program.addEventListener("TransferEvent", (event) => {
|
||
// Handle event...
|
||
});
|
||
</code></pre>
|
||
<h2 id="unsubscribing-from-events"><a class="header" href="#unsubscribing-from-events">Unsubscribing from Events</a></h2>
|
||
<p>The event listener should be removed once it's no longer required:</p>
|
||
<pre><code class="language-ts">program.removeEventListener(subscriptionId);
|
||
</code></pre>
|
||
<h2 id="cpi-events"><a class="header" href="#cpi-events">CPI Events</a></h2>
|
||
<p>Solana nodes truncate logs larger than 10 KB by default which makes regular events emitted via <code>emit!</code> macro unreliable.</p>
|
||
<p>Unlike logs, RPC providers store instruction data without truncation. CPI events make use of this by executing a self-invoke with the event data in order to store the event(s) in the instruction.</p>
|
||
<p>To use CPI events, enable <code>event-cpi</code> feature of <code>anchor-lang</code>:</p>
|
||
<pre><code class="language-toml">anchor-lang = { version = "0.29.0", features = ["event-cpi"] }
|
||
</code></pre>
|
||
<p>add <code>#[event_cpi]</code> to accounts struct:</p>
|
||
<pre><code class="language-rs">#[event_cpi]
|
||
#[derive(Accounts)]
|
||
pub struct TransferContext {}
|
||
</code></pre>
|
||
<p>and in your instruction handler, use <code>emit_cpi!</code>:</p>
|
||
<pre><pre class="playground"><code class="language-rust">
|
||
<span class="boring">#![allow(unused)]
|
||
</span><span class="boring">fn main() {
|
||
</span>#[program]
|
||
pub mod my_program {
|
||
use super::*;
|
||
|
||
pub fn transfer(ctx: Context<TransferContext>, amount: u64) -> Result<()> {
|
||
// Perform transfer logic
|
||
|
||
// Emit the TransferEvent
|
||
emit_cpi!(TransferEvent {
|
||
from: *ctx.accounts.from.key,
|
||
to: *ctx.accounts.to.key,
|
||
amount,
|
||
});
|
||
|
||
Ok(())
|
||
}
|
||
}
|
||
<span class="boring">}
|
||
</span></code></pre></pre>
|
||
<blockquote>
|
||
<p>Note: <code>#[event_cpi]</code> appends 2 accounts to the instruction; one being the event authority and the other the program itself.
|
||
This is necessary in order to make sure only the program can invoke the event CPI instruction.</p>
|
||
</blockquote>
|
||
<div style="break-before: page; page-break-before: always;"></div><h2 id="the-discriminator"><a class="header" href="#the-discriminator">The Discriminator</a></h2>
|
||
<p>In the context of Anchor, a discriminator is a unique identifier used to distinguish between various types of data. A discriminator is particularly crucial for differentiating between different types of account data structures at runtime. In addition, the discriminator is also prefixed to instructions, which assists the dispatch function in Anchor in routing these instructions to their corresponding methods within the program.</p>
|
||
<p><code>Discriminator</code> is defined as a trait with a <code>discriminator()</code> method and a <code>DISCRIMINATOR</code> constant:</p>
|
||
<pre><code class="language-rs">pub trait Discriminator {
|
||
const DISCRIMINATOR: [u8; 8];
|
||
fn discriminator() -> [u8; 8] {
|
||
Self::DISCRIMINATOR
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>Here, <code>DISCRIMINATOR</code> is an 8-byte array that represents the unique identifier of a type of data. The <code>discriminator()</code> method returns the value of <code>DISCRIMINATOR</code>.</p>
|
||
<h2 id="the-necessity-of-the-discriminator-in-anchor"><a class="header" href="#the-necessity-of-the-discriminator-in-anchor">The Necessity of the Discriminator in Anchor</a></h2>
|
||
<p>Other traits such as <code>ZeroCopy</code>, <code>InstructionData</code>, <code>Event</code>, and <code>EventData</code> all require a type to implement <code>Discriminator</code>. This means that each type of data that wishes to be serialized, deserialized, or used in an event or instruction must have a unique <code>Discriminator</code>.</p>
|
||
<pre><code class="language-rs">/// An account data structure capable of zero copy deserialization.
|
||
pub trait ZeroCopy: Discriminator + Copy + Clone + Zeroable + Pod {}
|
||
|
||
/// Calculates the data for an instruction invocation, where the data is
|
||
/// `Sha256(<namespace>:<method_name>)[..8] || BorshSerialize(args)`.
|
||
/// `args` is a borsh serialized struct of named fields for each argument given
|
||
/// to an instruction.
|
||
pub trait InstructionData: Discriminator + AnchorSerialize {
|
||
fn data(&self) -> Vec<u8> {
|
||
let mut d = Self::discriminator().to_vec();
|
||
d.append(&mut self.try_to_vec().expect("Should always serialize"));
|
||
d
|
||
}
|
||
}
|
||
|
||
/// An event that can be emitted via a Solana log. See [`emit!`](crate::prelude::emit) for an example.
|
||
pub trait Event: AnchorSerialize + AnchorDeserialize + Discriminator {
|
||
fn data(&self) -> Vec<u8>;
|
||
}
|
||
</code></pre>
|
||
<p>For instance, the <code>data()</code> method of the <code>InstructionData</code> trait creates a byte array containing the <code>Discriminator</code> and the serialized data of the instruction:</p>
|
||
<pre><code class="language-rs">pub trait InstructionData: Discriminator + AnchorSerialize {
|
||
fn data(&self) -> Vec<u8> {
|
||
let mut d = Self::discriminator().to_vec();
|
||
d.append(&mut self.try_to_vec().expect("Should always serialize"));
|
||
d
|
||
}
|
||
}
|
||
</code></pre>
|
||
<p>Here, <code>Self::discriminator().to_vec()</code> creates a vector containing the <code>Discriminator</code> of the data type, and <code>self.try_to_vec().expect("Should always serialize")</code> creates a vector containing the serialized data of the instruction. Both vectors are then concatenated to create the resulting byte array.</p>
|
||
<h2 id="discriminators-in-anchor-account-processing"><a class="header" href="#discriminators-in-anchor-account-processing">Discriminators in Anchor Account Processing</a></h2>
|
||
<p>This code block is part of the <code>#[account]</code> procedural macro implementation and is responsible for implementing the <code>Discriminator</code> trait for a specific account struct.</p>
|
||
<pre><code class="language-rs">impl #impl_gen anchor_lang::Discriminator for #account_name #type_gen #where_clause {
|
||
const DISCRIMINATOR: [u8; 8] = #discriminator;
|
||
}
|
||
</code></pre>
|
||
<p>The following piece of code computes the Discriminator by hashing the namespace of the account structure and the name of the account structure. It then takes the first 8 bytes of this hash to form the discriminator. This Discriminator is used to uniquely identify the account structure during the serialization and deserialization process.</p>
|
||
<pre><code class="language-rs">let discriminator: proc_macro2::TokenStream = {
|
||
// Namespace the discriminator to prevent collisions.
|
||
let discriminator_preimage = {
|
||
// For now, zero copy accounts can't be namespaced.
|
||
if namespace.is_empty() {
|
||
format!("account:{account_name}")
|
||
} else {
|
||
format!("{namespace}:{account_name}")
|
||
}
|
||
};
|
||
let mut discriminator = [0u8; 8];
|
||
discriminator.copy_from_slice(
|
||
&anchor_syn::hash::hash(discriminator_preimage.as_bytes()).to_bytes()[..8],
|
||
);
|
||
format!("{discriminator:?}").parse().unwrap()
|
||
};
|
||
</code></pre>
|
||
<p>When the account data is being deserialized, this function first checks the length of the data buffer to ensure it is at least as long as the discriminator. It then compares the first 8 bytes of the data buffer with the expected discriminator. If they do not match, this is an indication that an incorrect account data structure is being used, and the function will return with an error.</p>
|
||
<pre><code class="language-rs">fn try_deserialize(buf: &mut &[u8]) -> anchor_lang::Result<Self> {
|
||
if buf.len() < #discriminator.len() {
|
||
return Err(anchor_lang::error::ErrorCode::AccountDiscriminatorNotFound.into());
|
||
}
|
||
let given_disc = &buf[..8];
|
||
if &#discriminator != given_disc {
|
||
return Err(anchor_lang::error!(anchor_lang::error::ErrorCode::AccountDiscriminatorMismatch).with_account_name(#account_name_str));
|
||
}
|
||
Self::try_deserialize_unchecked(buf)
|
||
}
|
||
</code></pre>
|
||
<p>Let's illustrate the importance of the discriminator with an example.</p>
|
||
<p>Consider a program that manages two types of accounts, Account A and Account B. Both accounts are owned by the same program and have identical fields. Now, suppose you have an instruction called <code>foo</code> that is designed to only operate on Account A.</p>
|
||
<p>However, a user mistakenly passes Account B as an argument to the <code>foo</code> instruction. Given that Account B shares the same owner and the same fields as Account A, how can the program detect this mistake and throw an error?</p>
|
||
<p>This is where the discriminator comes into play. It uniquely identifies the type of an account. Even though Account A and Account B are structurally identical and share the same owner, they have different discriminators.</p>
|
||
<p>When the <code>foo</code> instruction gets executed, the Anchor framework checks the discriminator of the account passed as an argument. If you have declared <code>foo</code> as <code>foo: Account<'info, A></code>, Anchor will make sure that the passed account's discriminator matches that of Account A. If the discriminators don't match (as would be the case if Account B was passed), Anchor raises an error, preventing any unintended effects on Account B.</p>
|
||
<p>The discriminator helps Anchor to ensure that the account being processed is indeed the one expected, preventing type-related errors at runtime. This mechanism is automatically handled when you use the <code>Account</code> type in Anchor, adding an extra layer of security to your program.</p>
|
||
<h2 id="conclusion"><a class="header" href="#conclusion">Conclusion</a></h2>
|
||
<p>In conclusion, discriminators in Anchor play an essential role in managing and distinguishing between various types of data and account structures. They serve as unique identifiers, enabling the Anchor framework to handle data correctly during runtime. The discriminator ensures that each is treated as a distinct entity, thereby preventing any inadvertent account manipulations. This mechanism greatly enhances the robustness and security of your programs, providing reassurance that potential type-related errors are kept to a minimum.</p>
|
||
<div style="break-before: page; page-break-before: always;"></div><h1 id="anchor-references"><a class="header" href="#anchor-references">Anchor References</a></h1>
|
||
<p>Is exactly what it says on the tin.</p>
|
||