From 848db28aee1303d3a674772c7e9111b4930002be Mon Sep 17 00:00:00 2001 From: kepler-ops-maker Date: Mon, 21 Sep 2026 06:37:19 -0400 Subject: [PATCH 1/8] docs/tutorial: add tutorial overview and runner guide Introduced a comprehensive tutorial for the Fleet SDK, detailing setup and usage of examples. --- docs/tutorial/index.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 docs/tutorial/index.md diff --git a/docs/tutorial/index.md b/docs/tutorial/index.md new file mode 100644 index 0000000..3c0c503 --- /dev/null +++ b/docs/tutorial/index.md @@ -0,0 +1,31 @@ +# Fleet SDK Tutorial + +A hands-on course for building on Ergo with Fleet SDK. Each chapter is small, self-contained, and every code example runs as-is against a local mock blockchain - no node, no wallet, and no real funds required. + +## How to run the examples + +Every example in this tutorial is a plain Node.js script. Create a project once and reuse it for all chapters: + +```bash +mkdir fleet-tutorial && cd fleet-tutorial +npm init -y +npm install @fleet-sdk/core @fleet-sdk/mock-chain +``` + +Save any example as an `.mjs` file (for example `send.mjs`) and run it: + +```bash +node send.mjs +``` + +:::info Why a mock chain? +The examples use [`@fleet-sdk/mock-chain`](https://www.npmjs.com/package/@fleet-sdk/mock-chain), Fleet's in-memory Ergo blockchain. It executes real, fully signed transactions and validates them exactly like a node would, so the code you test locally is the same code you point at mainnet later. When you are ready for a live network, swap the mock inputs for boxes fetched from your wallet or the explorer - the transaction-building code does not change. +::: + +## Chapters + +### Basics + +1. [Send ERG to a wallet](./basics/send-transactions) - inputs, outputs, change, and miner fees +2. [Mint a token](./basics/mint-tokens) - EIP-4 token standards +3. [Burn a token](./basics/burn-tokens) - destroying token supply From 3e6c3c6c86934c1dfa3ffee507fc31d51195b8af Mon Sep 17 00:00:00 2001 From: kepler-ops-maker Date: Mon, 21 Sep 2026 06:37:54 -0400 Subject: [PATCH 2/8] tutorial: add send-transactions chapter (milestones 1) This document provides a comprehensive guide on sending ERG from one wallet to another using the Fleet SDK, including concepts, a complete example, and execution details. --- docs/tutorial/basics/send-transactions.md | 77 +++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 docs/tutorial/basics/send-transactions.md diff --git a/docs/tutorial/basics/send-transactions.md b/docs/tutorial/basics/send-transactions.md new file mode 100644 index 0000000..8f5f1e0 --- /dev/null +++ b/docs/tutorial/basics/send-transactions.md @@ -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). From ce80e027e9dadcd1f9b5b2da397962009aac9a02 Mon Sep 17 00:00:00 2001 From: kepler-ops-maker Date: Mon, 21 Sep 2026 06:38:19 -0400 Subject: [PATCH 3/8] tutorial: add mint-tokens chapter (milestone 2) Added a tutorial on how to mint tokens using the Fleet SDK, including concepts, a complete example, and expected output. --- docs/tutorial/basics/mint-tokens.md | 67 +++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 docs/tutorial/basics/mint-tokens.md diff --git a/docs/tutorial/basics/mint-tokens.md b/docs/tutorial/basics/mint-tokens.md new file mode 100644 index 0000000..c544b79 --- /dev/null +++ b/docs/tutorial/basics/mint-tokens.md @@ -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`. From 957bdd2e5a193174471add328cce4388973e3418 Mon Sep 17 00:00:00 2001 From: kepler-ops-maker Date: Mon, 21 Sep 2026 06:38:31 -0400 Subject: [PATCH 4/8] tutorial: add burn-tokens chapter (milestone 3) --- docs/tutorial/basics/burn-tokens.md | 79 +++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 docs/tutorial/basics/burn-tokens.md diff --git a/docs/tutorial/basics/burn-tokens.md b/docs/tutorial/basics/burn-tokens.md new file mode 100644 index 0000000..7d50090 --- /dev/null +++ b/docs/tutorial/basics/burn-tokens.md @@ -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). From 67142acfd09fa327c2c3719850508a20ca195458 Mon Sep 17 00:00:00 2001 From: kepler-ops-maker Date: Mon, 21 Sep 2026 06:39:17 -0400 Subject: [PATCH 5/8] sidebar: add Tutorial section --- docs/.vitepress/config.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index 8476c59..d22b8f0 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -62,6 +62,22 @@ 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" } + ] + } + ] } ]; } From 4e63cd1112ae7b4eb12f61687db954d4f5bcc550 Mon Sep 17 00:00:00 2001 From: kepler-ops-maker Date: Mon, 21 Sep 2026 06:41:34 -0400 Subject: [PATCH 6/8] tutorial: fix cross-page links in send-transactions --- docs/tutorial/basics/send-transactions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/tutorial/basics/send-transactions.md b/docs/tutorial/basics/send-transactions.md index 8f5f1e0..7764ce5 100644 --- a/docs/tutorial/basics/send-transactions.md +++ b/docs/tutorial/basics/send-transactions.md @@ -74,4 +74,4 @@ Bob received exactly 1 ERG (1e9 nanoERG). Alice's balance dropped by 1.001 ERG: ## 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). +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). From 82be548ad87e771c9ea40c9af35599ed6848ac10 Mon Sep 17 00:00:00 2001 From: kepler-ops-maker Date: Mon, 21 Sep 2026 06:41:47 -0400 Subject: [PATCH 7/8] tutorial: fix cross-page link in burn-tokens --- docs/tutorial/basics/burn-tokens.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/tutorial/basics/burn-tokens.md b/docs/tutorial/basics/burn-tokens.md index 7d50090..9e2e129 100644 --- a/docs/tutorial/basics/burn-tokens.md +++ b/docs/tutorial/basics/burn-tokens.md @@ -76,4 +76,4 @@ remaining amount: 600 - `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). +- 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). From e0bbaa63d209765019474dae75f89d1e9bb11b16 Mon Sep 17 00:00:00 2001 From: kepler-ops-maker Date: Tue, 29 Sep 2026 22:23:24 +0900 Subject: [PATCH 8/8] tutorial: add crowdfunding multi-interaction example (milestone 11) Runnable example + six-check test suite against @fleet-sdk/mock-chain: create -> pledge -> collect happy path, plus negative paths (late pledge, early collect, below-goal collect, refund after success). --- docs/.vitepress/config.ts | 6 + docs/tutorial/examples/crowdfunding.md | 139 +++++++++++ docs/tutorial/index.md | 4 + examples/crowdfunding/.gitignore | 1 + examples/crowdfunding/README.md | 9 + examples/crowdfunding/crowdfunding.mjs | 94 ++++++++ examples/crowdfunding/crowdfunding.test.mjs | 149 ++++++++++++ examples/crowdfunding/package-lock.json | 241 ++++++++++++++++++++ examples/crowdfunding/package.json | 15 ++ 9 files changed, 658 insertions(+) create mode 100644 docs/tutorial/examples/crowdfunding.md create mode 100644 examples/crowdfunding/.gitignore create mode 100644 examples/crowdfunding/README.md create mode 100644 examples/crowdfunding/crowdfunding.mjs create mode 100644 examples/crowdfunding/crowdfunding.test.mjs create mode 100644 examples/crowdfunding/package-lock.json create mode 100644 examples/crowdfunding/package.json diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index d22b8f0..e244602 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -76,6 +76,12 @@ function sidebarGuide() { { 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" } + ] } ] } diff --git a/docs/tutorial/examples/crowdfunding.md b/docs/tutorial/examples/crowdfunding.md new file mode 100644 index 0000000..7e9a1c3 --- /dev/null +++ b/docs/tutorial/examples/crowdfunding.md @@ -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. diff --git a/docs/tutorial/index.md b/docs/tutorial/index.md index 3c0c503..0ce1cf6 100644 --- a/docs/tutorial/index.md +++ b/docs/tutorial/index.md @@ -29,3 +29,7 @@ The examples use [`@fleet-sdk/mock-chain`](https://www.npmjs.com/package/@fleet- 1. [Send ERG to a wallet](./basics/send-transactions) - inputs, outputs, change, and miner fees 2. [Mint a token](./basics/mint-tokens) - EIP-4 token standards 3. [Burn a token](./basics/burn-tokens) - destroying token supply + +### Examples + +1. [Crowdfunding contract](./examples/crowdfunding) - a multi-transaction campaign box with collect and refund paths diff --git a/examples/crowdfunding/.gitignore b/examples/crowdfunding/.gitignore new file mode 100644 index 0000000..c2658d7 --- /dev/null +++ b/examples/crowdfunding/.gitignore @@ -0,0 +1 @@ +node_modules/ diff --git a/examples/crowdfunding/README.md b/examples/crowdfunding/README.md new file mode 100644 index 0000000..becb749 --- /dev/null +++ b/examples/crowdfunding/README.md @@ -0,0 +1,9 @@ +# Crowdfunding example (Fleet SDK) + +Multi-transaction example for the [tutorial chapter](../../docs/tutorial/examples/crowdfunding.md): a crowdfunding campaign box with raise-more, collect, and refund paths, executed against `@fleet-sdk/mock-chain`. + +```bash +npm install +node crowdfunding.mjs # happy path: create -> pledge -> collect +node crowdfunding.test.mjs # six path checks (positive and negative) +``` diff --git a/examples/crowdfunding/crowdfunding.mjs b/examples/crowdfunding/crowdfunding.mjs new file mode 100644 index 0000000..557cad6 --- /dev/null +++ b/examples/crowdfunding/crowdfunding.mjs @@ -0,0 +1,94 @@ +import { MockChain } from "@fleet-sdk/mock-chain"; +import { + TransactionBuilder, + OutputBuilder, + ErgoAddress, + RECOMMENDED_MIN_FEE_VALUE +} from "@fleet-sdk/core"; +import { compile } from "@fleet-sdk/compiler"; +import { SInt, SLong, SGroupElement } from "@fleet-sdk/serializer"; + +const chain = new MockChain({ height: 1_000_000 }); +const alice = chain.newParty("Alice (backer)"); +const bob = chain.newParty("Bob (backer)"); +const project = chain.newParty("Project"); + +alice.addBalance({ nanoergs: 5_000_000_000n }); +bob.addBalance({ nanoergs: 5_000_000_000n }); + +const pub = (party) => + ErgoAddress.fromBase58(party.address.toString()).getPublicKeys()[0]; + +const DEADLINE = chain.height + 100; // Int +const GOAL = 2_000_000_000n; // 2 ERG + +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); + +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"); + +// 1) Alice opens the campaign with 1 ERG +const PLEDGE1 = 1_000_000_000n; +const tx1 = new TransactionBuilder(chain.height) + .from(alice.utxos.toArray()) + .to(new OutputBuilder(PLEDGE1, contract).setAdditionalRegisters(regs())) + .sendChangeTo(alice.address) + .payFee(RECOMMENDED_MIN_FEE_VALUE) + .build(); +console.log("create:", chain.execute(tx1, { signers: [alice] })); + +const campaignBox = () => campaign.utxos.toArray()[0]; + +// 2) Bob pledges 1.5 ERG (extends the same box) +const PLEDGE2 = 1_500_000_000n; +const box1 = campaignBox(); +const tx2 = new TransactionBuilder(chain.height) + .from([box1, ...bob.utxos.toArray()]) + .to(new OutputBuilder(box1.value + PLEDGE2, contract).setAdditionalRegisters(regs())) + .sendChangeTo(bob.address) + .payFee(RECOMMENDED_MIN_FEE_VALUE) + .build(); +console.log("pledge:", chain.execute(tx2, { signers: [bob] })); + +// 3) deadline passes +chain.newBlocks(101); + +// 4) success path: project collects 2.5 ERG (>= 2 ERG goal) +const box2 = campaignBox(); +console.log("campaign value (nanoERG):", box2.value.toString(), "height:", chain.height); +const tx3 = new TransactionBuilder(chain.height) + .from(box2) + .to(new OutputBuilder(box2.value - RECOMMENDED_MIN_FEE_VALUE, project.address.toString())) + .payFee(RECOMMENDED_MIN_FEE_VALUE) + .build(); +console.log("collect:", chain.execute(tx3, { signers: [project] })); +console.log("project balance:", project.balance.nanoergs.toString()); diff --git a/examples/crowdfunding/crowdfunding.test.mjs b/examples/crowdfunding/crowdfunding.test.mjs new file mode 100644 index 0000000..3d98b44 --- /dev/null +++ b/examples/crowdfunding/crowdfunding.test.mjs @@ -0,0 +1,149 @@ +import { MockChain } from "@fleet-sdk/mock-chain"; +import { + TransactionBuilder, + OutputBuilder, + ErgoAddress, + RECOMMENDED_MIN_FEE_VALUE +} from "@fleet-sdk/core"; +import { compile } from "@fleet-sdk/compiler"; +import { SInt, SLong, SGroupElement } from "@fleet-sdk/serializer"; +import assert from "node:assert"; + +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 GOAL = 2_000_000_000n; + +function setup() { + const chain = new MockChain({ height: 1_000_000 }); + const alice = chain.newParty("Alice"); + const bob = chain.newParty("Bob"); + const project = chain.newParty("Project"); + alice.addBalance({ nanoergs: 5_000_000_000n }); + bob.addBalance({ nanoergs: 5_000_000_000n }); + const pub = (p) => ErgoAddress.fromBase58(p.address.toString()).getPublicKeys()[0]; + const contract = compile(SCRIPT); + const DEADLINE = chain.height + 100; + 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"); + return { chain, alice, bob, project, contract, regs, campaign, DEADLINE }; +} + +function createCampaign({ chain, alice, contract, regs }, amount) { + const tx = new TransactionBuilder(chain.height) + .from(alice.utxos.toArray()) + .to(new OutputBuilder(amount, contract).setAdditionalRegisters(regs())) + .sendChangeTo(alice.address) + .payFee(RECOMMENDED_MIN_FEE_VALUE) + .build(); + return chain.execute(tx, { signers: [alice] }); +} + +function pledge(ctx, backer, amount) { + const box = ctx.campaign.utxos.toArray()[0]; + const tx = new TransactionBuilder(ctx.chain.height) + .from([box, ...backer.utxos.toArray()]) + .to(new OutputBuilder(box.value + amount, ctx.contract).setAdditionalRegisters(ctx.regs())) + .sendChangeTo(backer.address) + .payFee(RECOMMENDED_MIN_FEE_VALUE) + .build(); + return ctx.chain.execute(tx, { signers: [backer] }); +} + +function collect(ctx) { + const box = ctx.campaign.utxos.toArray()[0]; + const tx = new TransactionBuilder(ctx.chain.height) + .from(box) + .to(new OutputBuilder(box.value - RECOMMENDED_MIN_FEE_VALUE, ctx.project.address.toString())) + .payFee(RECOMMENDED_MIN_FEE_VALUE) + .build(); + return ctx.chain.execute(tx, { signers: [ctx.project] }); +} + +function refund(ctx) { + const box = ctx.campaign.utxos.toArray()[0]; + const tx = new TransactionBuilder(ctx.chain.height) + .from(box) + .to(new OutputBuilder(box.value - RECOMMENDED_MIN_FEE_VALUE, ctx.alice.address.toString())) + .payFee(RECOMMENDED_MIN_FEE_VALUE) + .build(); + return ctx.chain.execute(tx, { signers: [ctx.alice] }); +} + +function attempt(fn) { + try { return fn(); } catch { return false; } +} + +// 1: pledge before deadline works +{ + const ctx = setup(); + assert.equal(createCampaign(ctx, 1_000_000_000n), true); + assert.equal(pledge(ctx, ctx.bob, 1_500_000_000n), true); + assert.equal(ctx.campaign.utxos.toArray()[0].value, 2_500_000_000n); + console.log("ok 1 - pledge before deadline"); +} +// 2: pledge after deadline rejected +{ + const ctx = setup(); + createCampaign(ctx, 1_000_000_000n); + ctx.chain.newBlocks(101); + assert.equal(attempt(() => pledge(ctx, ctx.bob, 1_500_000_000n)), false); + console.log("ok 2 - pledge after deadline rejected"); +} +// 3: collect before deadline rejected +{ + const ctx = setup(); + createCampaign(ctx, 2_500_000_000n); + assert.equal(attempt(() => collect(ctx)), false); + console.log("ok 3 - collect before deadline rejected"); +} +// 4: collect below goal rejected +{ + const ctx = setup(); + createCampaign(ctx, 1_000_000_000n); + ctx.chain.newBlocks(101); + assert.equal(attempt(() => collect(ctx)), false); + console.log("ok 4 - collect below goal rejected"); +} +// 5: refund after deadline when below goal +{ + const ctx = setup(); + createCampaign(ctx, 1_000_000_000n); + ctx.chain.newBlocks(101); + assert.equal(refund(ctx), true); + console.log("ok 5 - refund after deadline below goal"); +} +// 6: refund rejected when goal met +{ + const ctx = setup(); + createCampaign(ctx, 2_500_000_000n); + ctx.chain.newBlocks(101); + assert.equal(attempt(() => refund(ctx)), false); + console.log("ok 6 - refund rejected when goal met"); +} +console.log("all tests passed"); diff --git a/examples/crowdfunding/package-lock.json b/examples/crowdfunding/package-lock.json new file mode 100644 index 0000000..f77cac9 --- /dev/null +++ b/examples/crowdfunding/package-lock.json @@ -0,0 +1,241 @@ +{ + "name": "fleet-tutorial-crowdfunding", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "fleet-tutorial-crowdfunding", + "dependencies": { + "@fleet-sdk/compiler": "^0.12.0", + "@fleet-sdk/core": "^0.12.0", + "@fleet-sdk/mock-chain": "^0.12.0", + "@fleet-sdk/serializer": "^0.11.0" + } + }, + "node_modules/@fleet-sdk/common": { + "version": "0.10.0", + "resolved": "https://registry.npmjs.org/@fleet-sdk/common/-/common-0.10.0.tgz", + "integrity": "sha512-N92zENyHYhKtKxhJ6jJbWgV3PCkCGM0LYLmn6OOXNqDVbwT9UFgHOTt7eXFd9tqIhwMMPCnlffNe4c+P+CnsJA==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@fleet-sdk/compiler": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/@fleet-sdk/compiler/-/compiler-0.12.0.tgz", + "integrity": "sha512-WH05qMRmWe8qTI1oX2NZ3qJobp2ZYPh3DqAAtKRPxmeHmfWmvFWM6QHwWeGR7M86QCQczWNdqeOY7qJKs12G4g==", + "license": "MIT", + "dependencies": { + "@fleet-sdk/common": "^0.10.0", + "@fleet-sdk/core": "^0.12.0", + "@fleet-sdk/crypto": "^0.11.0", + "@fleet-sdk/serializer": "^0.11.0", + "sigmastate-js": "0.4.6" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@fleet-sdk/core": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/@fleet-sdk/core/-/core-0.12.0.tgz", + "integrity": "sha512-AYdfivEzfokem2eovnhp5rfv+cFrVR87l/ff71uxt1Xn1Arv0QivNtXn9H00i0t3LkiTxI7ttgU56FAbjWbUKw==", + "license": "MIT", + "dependencies": { + "@fleet-sdk/common": "^0.10.0", + "@fleet-sdk/crypto": "^0.11.0", + "@fleet-sdk/serializer": "^0.11.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@fleet-sdk/crypto": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@fleet-sdk/crypto/-/crypto-0.11.0.tgz", + "integrity": "sha512-oGyrnL0AyzPSsPdA32y4TEFQ6vJlNDMt9nwiArd2TYbtRCDMNTslHQmC/An4clf4R0e/c4yuZJSdfzHC3F0ssQ==", + "license": "MIT", + "dependencies": { + "@fleet-sdk/common": "^0.10.0", + "@noble/hashes": "^1.8.0", + "@scure/base": "^1.2.6" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@fleet-sdk/mock-chain": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/@fleet-sdk/mock-chain/-/mock-chain-0.12.0.tgz", + "integrity": "sha512-AlUhtshCOyZnqhs1TJIzrWoEQj8/a8MVkjZxH23SPBiKLL7/qCyCfXYCGPdkgkjlhhQm819EeAAgMoG6wGgpXw==", + "license": "MIT", + "dependencies": { + "@fleet-sdk/common": "^0.10.0", + "@fleet-sdk/core": "^0.12.0", + "@fleet-sdk/crypto": "^0.11.0", + "@fleet-sdk/serializer": "^0.11.0", + "@fleet-sdk/wallet": "^0.12.0", + "diff": "^7.0.0", + "picocolors": "^1.1.1", + "sigmastate-js": "0.4.6" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@fleet-sdk/serializer": { + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@fleet-sdk/serializer/-/serializer-0.11.0.tgz", + "integrity": "sha512-EYun0nzxJn+23aOeaMM5COj62ibVrzgNOx2I6AM6P23mRs72I0Dv2prdBnU/lst4hqbNHi8a1E6UNvpjH2vhGQ==", + "license": "MIT", + "dependencies": { + "@fleet-sdk/common": "^0.10.0", + "@fleet-sdk/crypto": "^0.11.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@fleet-sdk/wallet": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/@fleet-sdk/wallet/-/wallet-0.12.0.tgz", + "integrity": "sha512-ErAOa1mLG5XzmQRarQ3SR879Mm/Bk1Cp0KkQP0lSZovBbSOWlem0isHMlIfhpJEHkvdGdW+YkrbQ4DtEG5z+ew==", + "license": "MIT", + "dependencies": { + "@fleet-sdk/common": "^0.10.0", + "@fleet-sdk/core": "^0.12.0", + "@fleet-sdk/crypto": "^0.11.0", + "@fleet-sdk/serializer": "^0.11.0", + "@noble/curves": "^1.9.2", + "@scure/bip32": "^1.7.0", + "@scure/bip39": "^1.6.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@noble/curves": { + "version": "1.9.7", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.9.7.tgz", + "integrity": "sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.8.0" + }, + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/hashes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", + "integrity": "sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/base": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@scure/base/-/base-1.2.6.tgz", + "integrity": "sha512-g/nm5FgUa//MCj1gV09zTJTaM6KBAHqLN907YVQqf7zC49+DcO4B1so4ZX07Ef10Twr6nuqYEH9GEggFXA4Fmg==", + "license": "MIT", + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/bip32": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@scure/bip32/-/bip32-1.7.0.tgz", + "integrity": "sha512-E4FFX/N3f4B80AKWp5dP6ow+flD1LQZo/w8UnLGYZO674jS6YnYeepycOOksv+vLPSpgN35wgKgy+ybfTb2SMw==", + "license": "MIT", + "dependencies": { + "@noble/curves": "~1.9.0", + "@noble/hashes": "~1.8.0", + "@scure/base": "~1.2.5" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/bip39": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@scure/bip39/-/bip39-1.6.0.tgz", + "integrity": "sha512-+lF0BbLiJNwVlev4eKelw1WWLaiKXw7sSl8T6FvBlWkdX+94aGJ4o8XjUdlyhTCjd8c+B3KT3JfS8P0bLRNU6A==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "~1.8.0", + "@scure/base": "~1.2.5" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/diff": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/diff/-/diff-7.0.0.tgz", + "integrity": "sha512-PJWHUb1RFevKCwaFA9RlG5tCd+FO5iRh9A8HEtkmBH2Li03iJriB6m6JIN4rGz3K3JLawI7/veA1xzRKP6ISBw==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/sigmajs-crypto-facade": { + "version": "0.0.7", + "resolved": "https://registry.npmjs.org/sigmajs-crypto-facade/-/sigmajs-crypto-facade-0.0.7.tgz", + "integrity": "sha512-4XK8ZS9NKAbo8aGnU6o5GkBW6Upl8+OK8A1KreVDMAamfvZ0iq4LoVH8rHaeEPf9moVtaC4QZY5RYI+0OwiydA==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "^1.1.4" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/sigmastate-js": { + "version": "0.4.6", + "resolved": "https://registry.npmjs.org/sigmastate-js/-/sigmastate-js-0.4.6.tgz", + "integrity": "sha512-Vo/TSFbkKrG28eiWn7EmoaBNgyabC6En6B7cKjb3z2ivBpFBMCGxUZgmKu83GgJboRvCikZ3/vvWFfbxpbloig==", + "license": "MIT", + "dependencies": { + "@fleet-sdk/common": "0.1.3", + "@noble/hashes": "1.1.4", + "sigmajs-crypto-facade": "0.0.7" + } + }, + "node_modules/sigmastate-js/node_modules/@fleet-sdk/common": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@fleet-sdk/common/-/common-0.1.3.tgz", + "integrity": "sha512-gYEkHhgGpgIcmCL3nCw8E9zHkT2WLmR+mPdxFlUE6fwcwISURbJrP6W9mF7D5Y0ShAP5Is2w3edh7AyIc7ctIQ==", + "license": "MIT", + "engines": { + "node": ">=14" + } + }, + "node_modules/sigmastate-js/node_modules/@noble/hashes": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.1.4.tgz", + "integrity": "sha512-+PYsVPrTSqtVjatKt2A/Proukn2Yrz61OBThOCKErc5w2/r1Fh37vbDv0Eah7pyNltrmacjwTvdw3JoR+WE4TA==", + "funding": [ + { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + ], + "license": "MIT" + } + } +} diff --git a/examples/crowdfunding/package.json b/examples/crowdfunding/package.json new file mode 100644 index 0000000..5b80ff6 --- /dev/null +++ b/examples/crowdfunding/package.json @@ -0,0 +1,15 @@ +{ + "name": "fleet-tutorial-crowdfunding", + "private": true, + "type": "module", + "scripts": { + "start": "node crowdfunding.mjs", + "test": "node crowdfunding.test.mjs" + }, + "dependencies": { + "@fleet-sdk/compiler": "^0.12.0", + "@fleet-sdk/core": "^0.12.0", + "@fleet-sdk/mock-chain": "^0.12.0", + "@fleet-sdk/serializer": "^0.11.0" + } +}