> ## Documentation Index
> Fetch the complete documentation index at: https://solana.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> This page is part of the Solana developer documentation at https://solana.com/developers/docs. Append `.md` to any docs URL, or send `Accept: text/markdown`, to get the page as Markdown.
> Index of all pages: https://solana.com/llms.txt. Per-section indexes such as https://solana.com/developers/docs/payments/llms.txt are smaller; prefer them when working on one task.
> Coding agents: install the official Solana skill for current APIs and conventions with `npx skills add https://github.com/solana-foundation/solana-dev-skill` (also served at https://solana.com/SKILL.md).
> Code in the cookbook and task pages comes from tested example files. Prefer it over writing API calls from memory.

# Durable & Offline Transaction Signing using Nonces

> One-stop shop for Solana's Durable Nonces: an easy way to power your Solana dApps

This guide is meant to be a one-stop shop for Solana's Durable Nonces: a highly
under-utilized and under-appreciated way to power your Solana dApps and make
your user's experience more reliable and deterministic.

> The code for this guide can be found in
> [this repository](https://github.com/0xproflupin/solana-durable-nonces), and
> it's advisable to follow along and run the examples locally to get a better
> grasp of Durable Nonces

## Durable Nonce Applications

Before we dive deep into Durable Nonces, its important to understand that
durable nonces provide an opportunity to create and sign a transaction that can
be submitted at any point in the future, and much more. This opens up a wide
range of use cases that are otherwise not possible or too difficult to
implement:

1. **Scheduled Transactions**: One of the most apparent applications of Durable
   Nonces is the ability to schedule transactions. Users can pre-sign a
   transaction and then submit it at a later date, allowing for planned
   transfers, contract interactions, or even executing pre-determined investment
   strategies.

2. **Multisig Wallets**: Durable Nonces are very useful for multi-signature
   wallets where one party signs a transaction, and others may confirm at a
   later time. This feature enables the proposal, review, and later execution of
   a transaction within a trustless system.

3. **Programs Requiring Future Interaction**: If a program on Solana requires
   interaction at a future point (such as a vesting contract or a timed release
   of funds), a transaction can be pre-signed using a Durable Nonce. This
   ensures the contract interaction happens at the correct time without
   necessitating the presence of the transaction creator.

4. **Cross-chain Interactions**: When you need to interact with another
   blockchain, and it requires waiting for confirmations, you could sign the
   transaction with a Durable Nonce and then execute it once the required
   confirmations are received.

5. **Decentralized Derivatives Platforms**: In a decentralized derivatives
   platform, complex transactions might need to be executed based on specific
   triggers. With Durable Nonces, these transactions can be pre-signed and
   executed when the trigger condition is met.

## Introduction to Durable Nonces

### Double Spend

Imagine you're buying an NFT on MagicEden or Tensor. You have to sign a
transaction that allows the marketplace's program to extract some SOL from your
wallets.

What is stopping them from reusing your signature to extract SOL again? Without
a way to check if the transaction was already submitted once, they can keep
submitting the signed transaction until there's no SOL left in their wallet.

This is known as the problem of Double-Spend and is one of the core issues that
blockchains like Solana solve.

A naive solution could be to crosscheck all transactions made in the past and
see if we find the signature there. This is not practically possible, as the
size of the Solana ledger is >80 TB.

### Recent Blockhashes

Solution: Crosscheck signatures within only a set period of recent time, and
discard the transaction if it gets "too" old.

Recent Blockhashes are used to achieve this. A blockhash contains a 32-byte
SHA-256 hash. It is used to indicate when a client last observed the ledger.
Using recent blockhashes, transactions are checked in the last 150 blocks. If
they are found, they are rejected. They are also rejected if they get older than
150 blocks. The only case they are accepted is if they are unique and the
blockhash is more recent than 150 blocks (about 30 seconds at 200ms slots).

As you can imagine, a side-effect of using recent blockhashes is the forced
mortality of a transaction even before its submission.

Another issue with blockhashes is the forced non-uniqueness of signed
transactions in very small timeframes. In some cases, if the transactions are
executed very quickly in succession, some get the same recent blockhashes with
high probability, thus
[making them duplicate and avoid their execution](https://solana.stackexchange.com/questions/1161/how-to-avoid-sendtransactionerror-this-transaction-has-already-been-processed?rq=1).

To summarize:

1. What if I don't want to send the transaction right away?
2. What if I want to sign the transaction offline as I don't want to keep my
   keys on a device that is connected to the net?
3. What if I want to co-sign the transaction from multiple devices owned by
   multiple people, and the co-signing takes more than 30 seconds, like in a
   case of a multi-sig operated by a DAO?
4. What if I want to sign and send a burst of transactions and don't want them
   to fail due to duplication?

The solution lies with Durable Nonces⚡️

### Durable Nonces

Durable Transaction Nonces, which are 32-byte in length (usually represented as
base58 encoded strings), are used in place of recent blockhashes to make every
transaction unique (to avoid double-spending) while removing the mortality on
the unexecuted transaction.

> How do they make transactions unique to avoid double spending?
>
> If nonces are used in place of recent blockhashes, the first instruction of
> the transaction needs to be a `nonceAdvance` instruction, which changes or
> advances the nonce. This ensures that every transaction which is signed using
> the nonce as the recent blockhash, irrespective of being successfully
> submitted or not, will be unique.

Let's look at a couple of accounts that are important for using durable nonces
with Solana transactions.

### Nonce Account

The Nonce Account is the account that stores the value of the nonce. This
account is owned by the `SystemProgram` and is rent-exempt; thus needs to
maintain the minimum balance for rent exemption (around 0.0015 SOL).

### Nonce Authority

Nonce authority is the account that controls the Nonce Account. It has the
authority to generate a new nonce, advance the nonce, or withdraw SOL from the
Nonce Account. By default, the account that creates the Nonce Account is
delegated as the Nonce Authority, but it's possible to transfer the authority
onto a different keypair account.

## Durable Nonces with Solana CLI

Now that we know what Durable Nonces are, it's time to use them to send durable
transactions.

> If you do not have the Solana CLI installed, please go through
> [this tutorial](/developers/docs/quickstart) and set up the Solana CLI. The
> commands below run on devnet (`solana config set --url devnet`).

### Create Nonce Authority

Let's start with creating a new keypair which we will use as our Nonce
authority. We can use the keypair currently configured in our Solana CLI, but
it's better to make a fresh one (make sure you're on devnet).

```shell
solana-keygen new -o nonce-authority.json
# pubkey: AXuXnVBviRjUqLgXPtLVBuydkQdkfvuznCQEYdqxV8h4
```

Set the current Solana CLI keypair to `nonce-authority.json` and print its
address:

```shell
solana config set -k ~/<path>/nonce-authority.json
solana address
```

Fund that address with devnet SOL from the
[Solana Faucet](https://faucet.solana.com) (the public devnet endpoint no longer
serves `solana airdrop`; see
[other ways to get devnet SOL](/developers/cookbook/development/airdrops-and-faucets)).

Okay, we're set. Let's create our nonce account.

### Create Nonce Account

Create a new keypair `nonce-account` and use the `create-nonce-account`
instruction to delegate this keypair as the Nonce Account. We will also transfer
0.0015 SOL to the Nonce Account from the Nonce Authority, which is usually just
above the minimum quantity needed for rent exemption.

```shell
solana-keygen new -o nonce-account.json
# pubkey: 93WqP9WF6YPrqhae9MyBLfkcL8ErjmKha4veEUi7xQ8K

solana create-nonce-account nonce-account.json 0.0015
```

Output

```shell
Signature: 43t3NkMZNCEPCMHi8g7gzRsvU4qCfzbHAKhA8jmQAMcdgecavx6wyVTgYn73TnrT7vs7S3dPXmfo3T1XtMrfDMDZ
```

Upon searching the
[signature](https://solscan.io/tx/43t3NkMZNCEPCMHi8g7gzRsvU4qCfzbHAKhA8jmQAMcdgecavx6wyVTgYn73TnrT7vs7S3dPXmfo3T1XtMrfDMDZ?cluster=devnet)
on the explorer, we can see that the Nonce Account was created and the
`InitializeNonce` instruction was used to initialize a nonce within the account.

### Fetch Nonce

We can query the value of the stored Nonce as follows.

```shell
solana nonce nonce-account.json
```

Output

```shell
47fKDun1VvTu85w4DzC9i6Un28vEMbjNBMoHwQz1zQR4
```

This is the base58 encoded hash that will be used in place of recent blockhashes
while signing a transaction.

### Display Nonce Account

We can inspect the details of a Nonce Account in a prettier formatted version

```shell
solana nonce-account nonce-account.json
```

Output

```shell
Balance: 0.0015 SOL
Minimum Balance Required: 0.00105664 SOL
Nonce blockhash: 47fKDun1VvTu85w4DzC9i6Un28vEMbjNBMoHwQz1zQR4
Fee: 5000 lamports per signature
Authority: AXuXnVBviRjUqLgXPtLVBuydkQdkfvuznCQEYdqxV8h4
```

### Advancing Nonce

As discussed before, advancing the Nonce or changing the value of the nonce is
an important step for making subsequent transactions unique. The Nonce Authority
needs to sign the transaction with the `nonceAdvance` instruction.

```shell
solana new-nonce nonce-account.json
```

Output

```shell
Signature: 4Aycf55BQPcrMgjvwMyZfE5KnkQsqigNh9qWsv8DKsHoEUabf6ZCWgphPJ32bMbS1ieihzVmNgXHbPjPsLRyuL9e
```

If we check the nonce again, the value of the nonce has changed or advanced.

```shell
solana nonce nonce-account.json
```

Output

```shell
8rxU25ZLAAwwMwRW9yUihRLeh4HBbJFRwJVa3suEtXEk
```

### Withdraw from Nonce Account

We transferred 0.0015 SOL when creating the Nonce Account. The Nonce Authority
can transfer these funds back to itself or some other account.

```shell
solana withdraw-from-nonce-account nonce-account.json nonce-authority.json 0.0000001
```

Output

```shell
Signature: 5RWuBgxqNP5NrhG3c9Hjrk4MaKv6yhkbf4hHgzqW9mCyVG2aG9Tyg9HtecywvXCqCKSaLbf5UiB4BQa39EqJC9uW
```

We can check the status of the Nonce Account after the withdrawal; the balance
should have changed.

```shell
solana nonce-account nonce-account.json
```

Output

```shell
Balance: 0.0014999 SOL
Minimum Balance Required: 0.00105664 SOL
Nonce blockhash: 8rxU25ZLAAwwMwRW9yUihRLeh4HBbJFRwJVa3suEtXEk
Fee: 5000 lamports per signature
Authority: AXuXnVBviRjUqLgXPtLVBuydkQdkfvuznCQEYdqxV8h4
```

## Live Example: DAO Offline Co-Signing

We will use an example where a DAO committee needs to transfer some SOL to a new
wallet. Two co-signers are needed before sending the SOL, where `co-sender` pays
for the transaction and `sender` sends the SOL. To add to this, the `co-sender`
is very careful when it comes to connecting his device to the internet and thus
wants to sign the transaction offline.

Let's create three new keypairs, which will act as the two members of the DAO
and the receiver. Although, for this example, we are creating the keypairs in
the same system, we will assume that these accounts are on different systems to
replicate an IRL scenario.

```shell
solana-keygen new -o sender.json
# pubkey: CwisZiMtsEQi7vUYSQwV1ZZhue1LVoQmaM91STpRqt2L

solana-keygen new -o co-sender.json
# pubkey: 9aNXYV2fw8bzZaPA3LHvspzqX9X3tyXPJXHV22oV1pvJ

solana-keygen new -o receiver.json
# pubkey: F8AwkFNLCYiMychDuDrVgeoeSmr7Pwyhmov8fALvrdx5
```

Let's add some SOL to the member wallets. Transfer it from the funded
`nonce-authority.json` wallet (the current CLI keypair):

```shell
solana transfer --allow-unfunded-recipient sender.json 0.5
solana transfer --allow-unfunded-recipient co-sender.json 0.5
```

### Using Recent Blockhashes

Before we try to sign and send a durable transaction, let's see how transactions
are normally submitted using recent blockhashes.

> Its important to note that although we'll attempt to achieve the above using
> recent blockhashes, the expected outcome is failure, which will help us
> appreciate why durable nonces are necessary here.

The first step is to build a transfer transaction from `sender` to `receiver`
and sign it with `co-sender`'s wallet.

To sign an offline transaction, we need to use:

1. `--sign-only`: which prevents clients from sending the transaction.
2. `--blockhash`: which lets us specify a recent blockhash so that the client
   does not try to fetch for it in an offline setting.

- We can get a recent blockhash from
  [solscan](https://solscan.io/blocks?cluster=devnet). Just copy the first
  blockhash from the list.
- We will also need the pubkey of `sender`:
  `CwisZiMtsEQi7vUYSQwV1ZZhue1LVoQmaM91STpRqt2L`
- You can even turn off your internet when you sign this transaction using the
  `co-sender`'s wallet :).

```shell
solana transfer receiver.json 0.1 \
  --sign-only \
  --blockhash 24ZZMi8bz1wxAnqRgvtV8exZam5WNKGYxVXuoeuUZVcL \
  --fee-payer co-sender.json \
  --from CwisZiMtsEQi7vUYSQwV1ZZhue1LVoQmaM91STpRqt2L \
  --keypair co-sender.json
```

Output

```shell
Blockhash: 24ZZMi8bz1wxAnqRgvtV8exZam5WNKGYxVXuoeuUZVcL
Signers (Pubkey=Signature):
 9aNXYV2fw8bzZaPA3LHvspzqX9X3tyXPJXHV22oV1pvJ=4mqN6GsCHBkRV5v4SHV23yyym8CjwvRDoRj8Vmut24HPvvhQwxMM86BGYRGJvxPA893owDnBATs6F9CpRHA2SVRK
Absent Signers (Pubkey):
 CwisZiMtsEQi7vUYSQwV1ZZhue1LVoQmaM91STpRqt2L
```

The transaction is signed by `co-sender`'s wallet, who will pay the tx fee.
Also, we are notified about the pending signature from the `sender`'s wallet
(`CwisZiMtsEQi7vUYSQwV1ZZhue1LVoQmaM91STpRqt2L`).

In a real-world scenario, `co-sender` can share their `Pubkey=Signature` pair
with the `sender` who will need this sign and submit the transaction. This share
may take more than a minute to happen. Once the `sender` receives this pair,
they can initiate the transfer. The command has to rebuild exactly the
transaction `co-sender` signed, so it repeats every option that shaped it:
`--fee-payer` names `co-sender` by pubkey, and `--signer` supplies their
signature.

```shell
solana transfer receiver.json 0.1 \
  --allow-unfunded-recipient \
  --blockhash 24ZZMi8bz1wxAnqRgvtV8exZam5WNKGYxVXuoeuUZVcL \
  --fee-payer 9aNXYV2fw8bzZaPA3LHvspzqX9X3tyXPJXHV22oV1pvJ \
  --from sender.json \
  --keypair sender.json \
  --signer 9aNXYV2fw8bzZaPA3LHvspzqX9X3tyXPJXHV22oV1pvJ=4mqN6GsCHBkRV5v4SHV23yyym8CjwvRDoRj8Vmut24HPvvhQwxMM86BGYRGJvxPA893owDnBATs6F9CpRHA2SVRK
```

Output

```shell
Error: Hash has expired 24ZZMi8bz1wxAnqRgvtV8exZam5WNKGYxVXuoeuUZVcL
```

The transfer is not successful because the hash has expired. How do we overcome
this issue of expired blockhashes? With durable nonces.

### Using Durable Nonces

We will use the `nonce-account.json` and `nonce-authority.json` keypairs that we
created earlier. We already have a nonce initialized in the `nonce-account`.
Let's advance it to get a new one first, just to be sure that the `nonce` isn't
already used.

```shell
solana new-nonce nonce-account.json
solana nonce-account nonce-account.json
```

Output

```shell
Signature: 4iyDoKgY4LutioDC8UeQiuUt1CNpLYWUt7Zx5YjV2SREBP3QKawutY6S4xUiJu2V1NgWLsyL91zq7XeMdx18cguQ

Balance: 0.0014999 SOL
Minimum Balance Required: 0.00105664 SOL
Nonce blockhash: 4xR4tRiFULyYw71WPS2JCP8KZ4zJWqKQoigWofD8F46Y
Fee: 5000 lamports per signature
Authority: AXuXnVBviRjUqLgXPtLVBuydkQdkfvuznCQEYdqxV8h4
```

Perfect, now let's start with offline co-signing the transaction with
`co-sender`'s wallet, but this time, we'll use the `Nonce blockhash` printed
above, which is basically the `nonce` stored in the `nonce-account` as the
blockhash for the transfer transaction.

The nonce adds an `AdvanceNonce` instruction that the nonce authority signs, so
`co-sender` has to name the nonce account and the nonce authority by pubkey
(`--nonce` and `--nonce-authority`). Without them, `co-sender` signs a different
transaction from the one `sender` submits, and their signature is dropped.

```shell
solana transfer receiver.json 0.1 \
  --sign-only \
  --nonce 93WqP9WF6YPrqhae9MyBLfkcL8ErjmKha4veEUi7xQ8K \
  --nonce-authority AXuXnVBviRjUqLgXPtLVBuydkQdkfvuznCQEYdqxV8h4 \
  --blockhash 4xR4tRiFULyYw71WPS2JCP8KZ4zJWqKQoigWofD8F46Y \
  --fee-payer co-sender.json \
  --from CwisZiMtsEQi7vUYSQwV1ZZhue1LVoQmaM91STpRqt2L \
  --keypair co-sender.json
```

Output

```shell
Blockhash: 4xR4tRiFULyYw71WPS2JCP8KZ4zJWqKQoigWofD8F46Y
Signers (Pubkey=Signature):
 9aNXYV2fw8bzZaPA3LHvspzqX9X3tyXPJXHV22oV1pvJ=gtDzzT4SPaGFttiRz5iFcB9j9TssPutoJtdqSbBbu2AZ6Yxc3xKAKkcxNEFGCD1CDSiw5kPFHsEJHKyTh8WB8Kw
Absent Signers (Pubkey):
 CwisZiMtsEQi7vUYSQwV1ZZhue1LVoQmaM91STpRqt2L
 AXuXnVBviRjUqLgXPtLVBuydkQdkfvuznCQEYdqxV8h4
```

This time two signatures are pending: `sender`'s and the nonce authority's.
Unlike the recent blockhash, the nonce doesn't expire, so the signature stays
valid however long it takes to reach `sender`. Now we'll sign and send the
transaction with the `sender`'s wallet and the nonce authority, naming
`co-sender` as the fee payer:

```shell
solana transfer receiver.json 0.1 \
  --allow-unfunded-recipient \
  --nonce nonce-account.json \
  --nonce-authority nonce-authority.json \
  --blockhash 4xR4tRiFULyYw71WPS2JCP8KZ4zJWqKQoigWofD8F46Y \
  --fee-payer 9aNXYV2fw8bzZaPA3LHvspzqX9X3tyXPJXHV22oV1pvJ \
  --from sender.json \
  --keypair sender.json \
  --signer 9aNXYV2fw8bzZaPA3LHvspzqX9X3tyXPJXHV22oV1pvJ=gtDzzT4SPaGFttiRz5iFcB9j9TssPutoJtdqSbBbu2AZ6Yxc3xKAKkcxNEFGCD1CDSiw5kPFHsEJHKyTh8WB8Kw
```

Output

```shell
Signature: gtDzzT4SPaGFttiRz5iFcB9j9TssPutoJtdqSbBbu2AZ6Yxc3xKAKkcxNEFGCD1CDSiw5kPFHsEJHKyTh8WB8Kw
```

The transaction is submitted. Its signature is `co-sender`'s, because the fee
payer signs first.

If we check it on the
[explorer](https://solscan.io/tx/gtDzzT4SPaGFttiRz5iFcB9j9TssPutoJtdqSbBbu2AZ6Yxc3xKAKkcxNEFGCD1CDSiw5kPFHsEJHKyTh8WB8Kw?cluster=devnet),
we can see that an `AdvanceNonce` instruction was prepended to the transaction,
as we discussed before. This is done to avoid using the same nonce again. All
three signers are there, and `co-sender` paid the 15,000-lamport fee (5,000 per
signature).

Voila, we've gone through a very real-life use case of Durable Nonces. Now let's
see how to use them in transactions using JavaScript and the
[`@solana/web3.js`](https://solana-foundation.github.io/solana-web3.js/v1.x/)
package.

## Durable Nonces with Solana Web3.js

We'll use a similar example of making a simple transfer to demonstrate how to
send transactions using durable nonces.

<Warning>
  **`@solana/web3.js` 1.x is no longer actively maintained**

  It receives critical fixes only. Use [Kit](/developers/docs/clients/official/javascript#solana-kit) for new code. To migrate existing code, follow the [Kit upgrade guide](https://www.solanakit.com/docs/upgrade-guide), or the [web3.js v3 migration guide](https://github.com/solana-foundation/solana-web3.js/blob/main/docs/web3js-v1-to-v3-migration.md) to keep the class-based API.

  To run this code, install 1.x with `npm install @solana/web3.js@1`. A plain `npm install @solana/web3.js` installs v3, which this code doesn't run on.
</Warning>

### Create Nonce Authority (Web3.js)

<CodeGroup>

```ts title="Web3.js (legacy)"
const nonceAuthKP = Keypair.generate();
```

```py Python
import asyncio
import base64

from solana.rpc.async_api import AsyncClient
from solana.rpc.commitment import Confirmed
from solders.hash import Hash
from solders.keypair import Keypair
from solders.message import MessageV0
from solders.system_program import (
    AdvanceNonceAccountParams,
    TransferParams,
    advance_nonce_account,
    create_nonce_account,
    transfer,
)
from solders.transaction import VersionedTransaction


async def main():
    async with AsyncClient("http://localhost:8899", commitment=Confirmed) as client:
        nonce_authority = Keypair()
        airdrop = await client.request_airdrop(nonce_authority.pubkey(), 1_000_000_000)
        await client.confirm_transaction(airdrop.value)

        # The next steps run here, inside main()

asyncio.run(main())
```

```go Go
ctx := context.Background()
client := rpc.New("http://localhost:8899")

nonceAuthority := solana.NewWallet()
_, err := client.RequestAirdrop(ctx, nonceAuthority.PublicKey(), solana.LAMPORTS_PER_SOL, rpc.CommitmentConfirmed)
if err != nil {
	panic(err)
}
time.Sleep(2 * time.Second)
```

</CodeGroup>

_If you need SOL, you can use the
[faucet.solana.com](https://faucet.solana.com/)_ to get some.

### Create Nonce Accounts (Web3.js)

<CodeGroup>

```ts title="Web3.js (legacy)"
const nonceKeypair = Keypair.generate();
const tx = new Transaction();

// the fee payer can be any account
tx.feePayer = nonceAuthKP.publicKey;

// to create the nonce account, you can use fetch the recent blockhash
// or use a nonce from a different, pre-existing nonce account
tx.recentBlockhash = (await connection.getLatestBlockhash()).blockhash;

tx.add(
  // create system account with the minimum amount needed for rent exemption.
  // NONCE_ACCOUNT_LENGTH is the space a nonce account takes
  SystemProgram.createAccount({
    fromPubkey: nonceAuthKP.publicKey,
    newAccountPubkey: nonceKeypair.publicKey,
    lamports: 0.0015 * LAMPORTS_PER_SOL,
    space: NONCE_ACCOUNT_LENGTH,
    programId: SystemProgram.programId
  }),
  // initialise nonce with the created nonceKeypair's pubkey as the noncePubkey
  // also specify the authority of the nonce account
  SystemProgram.nonceInitialize({
    noncePubkey: nonceKeypair.publicKey,
    authorizedPubkey: nonceAuthKP.publicKey
  })
);

// sign the transaction with both the nonce keypair and the authority keypair
tx.sign(nonceKeypair, nonceAuthKP);

// send the transaction
const sig = await sendAndConfirmRawTransaction(
  connection,
  tx.serialize({ requireAllSignatures: false })
);
console.log("Nonce initiated: ", sig);
```

```py Python
nonce_keypair = Keypair()

# create the nonce account (80 bytes) and initialize it with its authority
instructions = create_nonce_account(
    nonce_authority.pubkey(),  # pays for the account
    nonce_keypair.pubkey(),
    nonce_authority.pubkey(),  # authority of the nonce
    (await client.get_minimum_balance_for_rent_exemption(80)).value,
)

blockhash = (await client.get_latest_blockhash()).value.blockhash
message = MessageV0.try_compile(
    nonce_authority.pubkey(), list(instructions), [], blockhash
)
tx = VersionedTransaction(message, [nonce_authority, nonce_keypair])
signature = (await client.send_transaction(tx)).value
await client.confirm_transaction(signature)
print("Nonce initiated:", signature)
```

```go Go
nonceAccount := solana.NewWallet()

const nonceAccountLength = 80
rent, err := client.GetMinimumBalanceForRentExemption(ctx, nonceAccountLength, rpc.CommitmentConfirmed)
if err != nil {
	panic(err)
}

recent, err := client.GetLatestBlockhash(ctx, rpc.CommitmentConfirmed)
if err != nil {
	panic(err)
}
tx, err := solana.NewTransaction(
	[]solana.Instruction{
		// create the nonce account, then initialize it with its authority
		system.NewCreateAccountInstruction(
			rent, nonceAccountLength, solana.SystemProgramID,
			nonceAuthority.PublicKey(), nonceAccount.PublicKey(),
		).Build(),
		system.NewInitializeNonceAccountInstruction(
			nonceAuthority.PublicKey(), nonceAccount.PublicKey(),
			solana.SysVarRecentBlockHashesPubkey, solana.SysVarRentPubkey,
		).Build(),
	},
	recent.Value.Blockhash,
	solana.TransactionPayer(nonceAuthority.PublicKey()),
)
if err != nil {
	panic(err)
}
// sign with both the nonce account and the authority
tx.Sign(func(key solana.PublicKey) *solana.PrivateKey {
	if key.Equals(nonceAccount.PublicKey()) {
		return &nonceAccount.PrivateKey
	}
	return &nonceAuthority.PrivateKey
})

sig, err := client.SendTransactionWithOpts(ctx, tx, rpc.TransactionOpts{PreflightCommitment: rpc.CommitmentConfirmed})
if err != nil {
	panic(err)
}
fmt.Println("Nonce initiated:", sig)
time.Sleep(2 * time.Second)
```

</CodeGroup>

### Fetch Nonce Account (Web3.js)

<CodeGroup>

```ts title="Web3.js (legacy)"
const accountInfo = await connection.getAccountInfo(nonceKeypair.publicKey);
const nonceAccount = NonceAccount.fromAccountData(accountInfo.data);
```

```py Python
nonce_info = (
    await client.get_account_info_json_parsed(nonce_keypair.pubkey())
).value
nonce = Hash.from_string(nonce_info.data.parsed["info"]["blockhash"])
```

```go Go
info, err := client.GetAccountInfoWithOpts(ctx, nonceAccount.PublicKey(), &rpc.GetAccountInfoOpts{Commitment: rpc.CommitmentConfirmed})
if err != nil {
	panic(err)
}
// nonce account layout: version (4 bytes), state (4), authority (32), nonce (32)
nonce := solana.HashFromBytes(info.GetBinary()[40:72])
```

</CodeGroup>

### Sign Transaction using Durable Nonce

<CodeGroup>

```ts title="Web3.js (legacy)"
// make a system transfer instruction
const ix = SystemProgram.transfer({
  fromPubkey: publicKey,
  toPubkey: publicKey,
  lamports: 100
});

// make a nonce advance instruction
const advanceIX = SystemProgram.nonceAdvance({
  authorizedPubkey: nonceAuthKP.publicKey,
  noncePubkey: noncePubKey
});

// add them to a transaction
const tx = new Transaction();
tx.add(advanceIX);
tx.add(ix);

// use the nonceAccount's stored nonce as the recentBlockhash
tx.recentBlockhash = nonceAccount.nonce;
tx.feePayer = publicKey;

// sign the tx with the nonce authority's keypair
tx.sign(nonceAuthKP);

// make the owner of the publicKey sign the transaction
// this should open a wallet popup and let the user sign the tx
const signedTx = await signTransaction(tx);

// once you have the signed tx, you can serialize it and store it
// in a database, or send it to another device. You can submit it
// at a later point, without the tx having a mortality
const serialisedTx = bs58.encode(
  signedTx.serialize({ requireAllSignatures: false })
);
console.log("Signed Durable Transaction: ", serialisedTx);
```

```py Python
payer = nonce_authority

# advancing the nonce must be the first instruction
advance_instruction = advance_nonce_account(
    AdvanceNonceAccountParams(
        nonce_pubkey=nonce_keypair.pubkey(),
        authorized_pubkey=nonce_authority.pubkey(),
    )
)
transfer_instruction = transfer(
    TransferParams(
        from_pubkey=payer.pubkey(), to_pubkey=payer.pubkey(), lamports=100
    )
)

# use the stored nonce as the recent blockhash
message = MessageV0.try_compile(
    payer.pubkey(), [advance_instruction, transfer_instruction], [], nonce
)
durable_tx = VersionedTransaction(message, [payer])

# the signed transaction doesn't expire: store it and submit it later
serialized_tx = base64.b64encode(bytes(durable_tx)).decode()
print("Signed Durable Transaction:", serialized_tx)
```

```go Go
payer := nonceAuthority

durableTx, err := solana.NewTransaction(
	[]solana.Instruction{
		// advancing the nonce must be the first instruction
		system.NewAdvanceNonceAccountInstruction(
			nonceAccount.PublicKey(), solana.SysVarRecentBlockHashesPubkey, nonceAuthority.PublicKey(),
		).Build(),
		system.NewTransferInstruction(100, payer.PublicKey(), payer.PublicKey()).Build(),
	},
	nonce, // use the stored nonce as the recent blockhash
	solana.TransactionPayer(payer.PublicKey()),
)
if err != nil {
	panic(err)
}
durableTx.Sign(func(solana.PublicKey) *solana.PrivateKey { return &payer.PrivateKey })

// the signed transaction doesn't expire: store it and submit it later
serializedTx, err := durableTx.ToBase64()
if err != nil {
	panic(err)
}
fmt.Println("Signed Durable Transaction:", serializedTx)
```

</CodeGroup>

## Live Example: Poll Simulation App

The Poll Simulation app simulates a real-life poll mechanism, wherein voters are
allowed to vote for a given set of times. Once the time comes for determining
the results of the poll: the votes are counted, the count is publicly announced
to everyone, and the winner is declared.

This is tough to build onchain, as changing the state of an account onchain is a
public action, and hence if a user votes for someone, others would know, and
hence the count won't be hidden from the public until the voting has been
completed.

Durable nonces can be used to partially fix this. Instead of signing and sending
the transaction when voting for your candidate, the dApp can let the user sign
the transaction using durable nonces, serialize the transaction as shown above
in the web3.js example, and save the serialized transactions in a database until
the time comes for counting.

For counting the votes, the dApp then needs to sync, send, or submit all the
signed transactions one by one. With each submitted transaction, the state
change will happen onchain, and the winner can be decided.

### Live App

- The app is live on:
  [**https://durable-nonces-demo.vercel.app/**](https://durable-nonces-demo.vercel.app/)

- Information on how to use the dApp can be found
  [here](https://github.com/0xproflupin/solana-durable-nonces/blob/main/durable-nonces-demo/README.md#how-to-use-the-dapp)

- Information on how to build the dApp locally can be found
  [here](https://github.com/0xproflupin/solana-durable-nonces/blob/main/durable-nonces-demo/README.md#how-to-build-the-dapp-locally)

## References

- [Neodyme Blog: Nonce Upon a Time, or a Total Loss of Funds](https://neodyme.io/blog/nonce-upon-a-time/)
- [Solana Durable Nonces CLI](https://docs.anza.xyz/cli/examples/durable-nonce)
- [Solana Durable Transaction Nonces Proposal](https://docs.anza.xyz/implemented-proposals/durable-tx-nonces)
