Skip to content
This repository was archived by the owner on Nov 22, 2026. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions docs/.vitepress/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,28 @@ function sidebarGuide() {
{ text: "Transaction building", link: "/transaction-building" },
{ text: "Token burning", link: "/token-burning" }
]
},
{
text: "Tutorial",
collapsible: false,
items: [
{ text: "Overview", link: "/tutorial/" },
{
text: "Basics",
collapsed: false,
items: [
{ text: "Send ERG to a wallet", link: "/tutorial/basics/send-transactions" },
{ text: "Mint a token", link: "/tutorial/basics/mint-tokens" },
{ text: "Burn a token", link: "/tutorial/basics/burn-tokens" }
]
},
{
text: "Examples",
items: [
{ text: "Crowdfunding contract", link: "/tutorial/examples/crowdfunding" }
]
}
]
}
];
}
79 changes: 79 additions & 0 deletions docs/tutorial/basics/burn-tokens.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# Burn a Token

Burning permanently destroys token supply: the burned tokens can never be spent again. By the end of this chapter you can burn part or all of a token balance.

## Concepts

A burn happens when a transaction spends inputs containing tokens but creates fewer of those tokens in its outputs. Because accidental burns are irreversible, Fleet blocks them by default - you declare the burn explicitly with `burnTokens()`.

## Complete example

```ts
import { MockChain } from "@fleet-sdk/mock-chain";
import {
TransactionBuilder,
OutputBuilder,
RECOMMENDED_MIN_FEE_VALUE
} from "@fleet-sdk/core";

const chain = new MockChain({ height: 1_000_000 });
const alice = chain.newParty("Alice");
alice.addBalance({ nanoergs: 10_000_000_000n });

// Mint 1000 tokens first, so there is something to burn
const mintTx = new TransactionBuilder(chain.height)
.from(alice.utxos.toArray())
.to(
new OutputBuilder("1000000", alice.address)
.mintToken({ amount: "1000", name: "TutorialToken", decimals: 2, description: "burn demo" })
)
.sendChangeTo(alice.address)
.payFee(RECOMMENDED_MIN_FEE_VALUE)
.build();
chain.execute(mintTx, { signers: [alice] });
chain.newBlock();

// Find the token box created by the mint
const tokenBox = alice.utxos.toArray().find((b) => b.assets.length > 0);
const tokenId = tokenBox.assets[0].tokenId;

// Burn 400 of the 1000 tokens and return the remaining 600
const burnTx = new TransactionBuilder(chain.height)
.from(alice.utxos.toArray())
.to(
new OutputBuilder("1000000", alice.address)
.addTokens({ tokenId, amount: "600" })
)
.burnTokens({ tokenId, amount: "400" })
.sendChangeTo(alice.address)
.payFee(RECOMMENDED_MIN_FEE_VALUE)
.build();

const ok = chain.execute(burnTx, { signers: [alice] });

console.log("burn tx executed:", ok);
for (const t of alice.balance.tokens ?? []) {
console.log("remaining amount:", t.amount.toString());
}
```

## Run it

```bash
node burn.mjs
```

Expected output:

```
burn tx executed: true
remaining amount: 600
```

600 tokens remain; 400 are gone for good.

## Notes

- `burnTokens()` accepts a single object or an array, so one transaction can burn several different tokens.
- To burn an entire balance, omit the token from the outputs and pass the full amount to `burnTokens()`.
- If you ever need manual control instead of `burnTokens()`, burning can be allowed globally with `configure((x) => x.allowTokenBurning(true))` - see [Token Burning](/token-burning).
67 changes: 67 additions & 0 deletions docs/tutorial/basics/mint-tokens.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# Mint a Token

Ergo has native tokens: no smart contract is required to create one. By the end of this chapter you can mint a token that follows the [EIP-4](https://github.com/ergoplatform/eips/blob/master/eip-0004.md) standard, so wallets and explorers display its name, description, and decimals correctly.

## Concepts

- A token is minted when a transaction creates an output containing a token that did not exist in the inputs.
- The **token ID** is the ID of the first input box of the minting transaction. Fleet derives it automatically.
- EIP-4 metadata lives in the output's registers: R4 = name, R5 = description, R6 = decimals. Fleet's `mintToken()` sets all three for you.

## Complete example

```ts
import { MockChain } from "@fleet-sdk/mock-chain";
import {
TransactionBuilder,
OutputBuilder,
RECOMMENDED_MIN_FEE_VALUE
} from "@fleet-sdk/core";

const chain = new MockChain({ height: 1_000_000 });
const alice = chain.newParty("Alice");
alice.addBalance({ nanoergs: 10_000_000_000n });

const unsigned = new TransactionBuilder(chain.height)
.from(alice.utxos.toArray())
.to(
new OutputBuilder("1000000", alice.address) // 0.001 ERG minimum box value
.mintToken({
amount: "1000",
name: "TutorialToken",
decimals: 2,
description: "A token minted in the Fleet SDK tutorial"
})
)
.sendChangeTo(alice.address)
.payFee(RECOMMENDED_MIN_FEE_VALUE)
.build();

const ok = chain.execute(unsigned, { signers: [alice] });

console.log("mint tx executed:", ok);
for (const t of alice.balance.tokens ?? []) {
console.log("token:", t.tokenId, "amount:", t.amount.toString());
}
```

## Run it

```bash
node mint.mjs
```

Expected output:

```
mint tx executed: true
token: <64-char token id> amount: 1000
```

Alice now holds 1000 TutorialToken. With `decimals: 2` that displays as 10.00 in wallets.

## Notes

- The minting box still needs the **minimum box value** (0.001 ERG) in addition to the token.
- Minting is one-time: the token ID is bound to the input box, so the same supply can never be minted again.
- To send tokens instead of minting them, use `.addTokens({ tokenId, amount })` on an `OutputBuilder`.
77 changes: 77 additions & 0 deletions docs/tutorial/basics/send-transactions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# Send ERG to a Wallet

The most common transaction on Ergo: move ERG from one wallet to another. By the end of this chapter you can build, sign, and execute a payment transaction with Fleet SDK.

## Concepts

Ergo uses the eUTxO model. A transaction spends existing **boxes** (inputs) and creates new ones (outputs). A payment needs three kinds of outputs:

1. **Payment** - the box going to the recipient.
2. **Change** - what is left over, sent back to yourself.
3. **Miner fee** - a small payment to the network (minimum 0.001 ERG).

Fleet's `TransactionBuilder` calculates and checks all of this for you.

## Complete example

```ts
import { MockChain } from "@fleet-sdk/mock-chain";
import {
TransactionBuilder,
OutputBuilder,
RECOMMENDED_MIN_FEE_VALUE
} from "@fleet-sdk/core";

// A local mock blockchain at height 1,000,000
const chain = new MockChain({ height: 1_000_000 });
const alice = chain.newParty("Alice");
const bob = chain.newParty("Bob");

// Fund Alice with 10 ERG (amounts are in nanoERG: 1 ERG = 1e9 nanoERG)
alice.addBalance({ nanoergs: 10_000_000_000n });

const SEND_AMOUNT = 1_000_000_000n; // 1 ERG

const unsigned = new TransactionBuilder(chain.height)
.from(alice.utxos.toArray()) // inputs: Alice's boxes
.to(
new OutputBuilder(SEND_AMOUNT, bob.address.toString()) // payment to Bob
)
.sendChangeTo(alice.address) // change back to Alice
.payFee(RECOMMENDED_MIN_FEE_VALUE) // 0.001 ERG miner fee
.build();

// Sign with Alice's key and execute on the chain
const ok = chain.execute(unsigned, { signers: [alice] });

console.log("tx executed:", ok);
console.log("Bob balance:", bob.balance.nanoergs.toString());
```

## Run it

```bash
node send.mjs
```

Expected output:

```
tx executed: true
Bob balance: 1000000000
```

Bob received exactly 1 ERG (1e9 nanoERG). Alice's balance dropped by 1.001 ERG: the payment plus the miner fee.

## How it works

- `new TransactionBuilder(chain.height)` starts a transaction. The creation height is required because every new box records the block height at which it was created.
- `.from(alice.utxos.toArray())` spends Alice's unspent boxes as inputs.
- `new OutputBuilder(amount, recipient)` creates the payment output. The recipient is any Ergo address string - paste a wallet address from Nautilus or any other wallet here.
- `.sendChangeTo(alice.address)` sends leftover funds back to Alice. Without it, the remainder would be burned.
- `.payFee(RECOMMENDED_MIN_FEE_VALUE)` attaches the minimum miner fee, 0.001 ERG.
- `chain.execute(unsigned, { signers: [alice] })` signs the transaction with Alice's key and executes it, applying all consensus validations.

## Sending to a real wallet

On a live network the only difference is where inputs and height come from. Fetch the current height from the explorer API and the sender's boxes from their wallet (see [Wallet Interaction](/wallet-interaction)), then build the transaction exactly as above. Read more about the builder methods in [Transaction Building](/transaction-building).
139 changes: 139 additions & 0 deletions docs/tutorial/examples/crowdfunding.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
# Example: Crowdfunding Contract

A complete multi-transaction example that composes everything from the earlier chapters: a compiled contract, registers, and several transactions interacting with the same box over time.

A crowdfunding campaign is a box that three different parties touch:

1. **Alice** creates the campaign box with an initial pledge.
2. **Bob** (or anyone) adds funds to the same box before the deadline.
3. After the deadline, **the project** collects the funds if the goal was met - otherwise **Alice** takes a refund.

## The contract

The campaign box stores its parameters in registers so every participant can verify them on-chain:

| Register | Content | Type |
| -------- | ------- | ---- |
| R4 | Deadline height | `Int` |
| R5 | Backer's public key (refund recipient) | `GroupElement` |
| R6 | Project's public key (collection recipient) | `GroupElement` |
| R7 | Funding goal in nanoERG | `Long` |

The contract allows exactly three spending paths:

- **Raise more** - before the deadline, anyone can spend the box as long as it is recreated with the same script and registers and a higher value. No signature is needed to *add* funds.
- **Collect** - at or after the deadline, if the goal is met, the project key signs and takes the funds.
- **Refund** - at or after the deadline, if the goal was missed, the original backer key signs and takes the funds back.

```ts
const script = `{
val deadline = SELF.R4[Int].get
val backer = SELF.R5[GroupElement].get
val projectKey = SELF.R6[GroupElement].get
val goal = SELF.R7[Long].get

val raiseMore = sigmaProp({
val out = OUTPUTS(0)
out.propositionBytes == SELF.propositionBytes &&
out.R4[Int].get == deadline &&
out.R5[GroupElement].get == backer &&
out.R6[GroupElement].get == projectKey &&
out.R7[Long].get == goal &&
out.value > SELF.value &&
HEIGHT < deadline
})

val success = sigmaProp(HEIGHT >= deadline && SELF.value >= goal) && proveDlog(projectKey)
val refund = sigmaProp(HEIGHT >= deadline && SELF.value < goal) && proveDlog(backer)

raiseMore || success || refund
}`;

const contract = compile(script);
```

## Step 1: create the campaign

Alice compiles the contract, fills the registers, and seeds the campaign with 1 ERG. The register values come from the participants' public keys, extracted from their addresses:

```ts
import { SInt, SLong, SGroupElement } from "@fleet-sdk/serializer";

const pub = (party) =>
ErgoAddress.fromBase58(party.address.toString()).getPublicKeys()[0];

const DEADLINE = chain.height + 100;
const GOAL = 2_000_000_000n; // 2 ERG

const regs = () => ({
R4: SInt(DEADLINE).toHex(),
R5: SGroupElement(pub(alice)).toHex(),
R6: SGroupElement(pub(project)).toHex(),
R7: SLong(GOAL).toHex()
});

const campaign = chain.addParty(contract.toHex(), "Campaign"); // tracks boxes at this script

const tx1 = new TransactionBuilder(chain.height)
.from(alice.utxos.toArray())
.to(new OutputBuilder(1_000_000_000n, contract).setAdditionalRegisters(regs()))
.sendChangeTo(alice.address)
.payFee(RECOMMENDED_MIN_FEE_VALUE)
.build();

chain.execute(tx1, { signers: [alice] }); // true
```

`chain.addParty(contract.toHex())` creates a watch-only party for the contract script, so `campaign.utxos` always lists the live campaign box - the same lookup a real app would do through the explorer.

## Step 2: pledge to the campaign

Bob spends the campaign box and recreates it with his 1.5 ERG added. The `raiseMore` path checks that the script and all registers survive unchanged, so no one can hijack the campaign mid-flight:

```ts
const box = campaign.utxos.toArray()[0];

const tx2 = new TransactionBuilder(chain.height)
.from([box, ...bob.utxos.toArray()])
.to(new OutputBuilder(box.value + 1_500_000_000n, contract).setAdditionalRegisters(regs()))
.sendChangeTo(bob.address)
.payFee(RECOMMENDED_MIN_FEE_VALUE)
.build();

chain.execute(tx2, { signers: [bob] }); // true
```

## Step 3: collect after a successful campaign

Once the deadline passes and the box holds at least the goal, the project signs and collects:

```ts
chain.newBlocks(101); // time passes, height > deadline

const current = campaign.utxos.toArray()[0];

const tx3 = new TransactionBuilder(chain.height)
.from(current)
.to(new OutputBuilder(current.value - RECOMMENDED_MIN_FEE_VALUE, project.address.toString()))
.payFee(RECOMMENDED_MIN_FEE_VALUE)
.build();

chain.execute(tx3, { signers: [project] }); // true - project receives 2.499 ERG
```

Had the campaign missed the goal, the same transaction shape with `signers: [alice]` and Alice's address would refund the backer instead. Every other combination is rejected by the contract: pledging after the deadline, collecting early, collecting below the goal, or refunding a successful campaign.

## Run it

The full script and a test suite covering all three paths live in [`examples/crowdfunding`](https://github.com/fleet-sdk/docs/tree/master/examples/crowdfunding):

```bash
cd examples/crowdfunding
npm install
node crowdfunding.mjs # happy path: create, pledge, collect
node crowdfunding.test.mjs # all six path checks
```

## On a live network

Only the inputs change. Replace the mock parties with boxes fetched from the explorer or a connected wallet, keep the current network height in the builder, and compile the same script with real public keys in the registers. The transaction-building code is identical.
Loading