From 90d0b62f06b9443e0bd834aecee59a2189fabb40 Mon Sep 17 00:00:00 2001 From: lisicky Date: Sun, 22 Nov 2026 15:06:26 +0100 Subject: [PATCH 01/15] docs: migrating to TxBuilder --- content/docs/ai/skills.mdx | 8 + content/docs/apis/txbuilder/basics.mdx | 1 + content/docs/apis/txbuilder/index.mdx | 2 + content/docs/apis/txbuilder/meta.json | 2 +- content/docs/apis/txbuilder/migration.mdx | 245 ++++++++++++++++++++++ data/links-txbuilders.ts | 6 + 6 files changed, 263 insertions(+), 1 deletion(-) create mode 100644 content/docs/apis/txbuilder/migration.mdx diff --git a/content/docs/ai/skills.mdx b/content/docs/ai/skills.mdx index a2f9119..68a43fb 100644 --- a/content/docs/ai/skills.mdx +++ b/content/docs/ai/skills.mdx @@ -24,6 +24,7 @@ Compatible with Claude Code, Cursor, GitHub Copilot, Codex, and Staking - Delegation and rewards - Governance - Voting and proposals - Blockfrost Provider - Provider setup +- Migrating to TxBuilder - Move to the new builder diff --git a/content/docs/apis/txbuilder/index.mdx b/content/docs/apis/txbuilder/index.mdx index de58ac0..ab6e01b 100644 --- a/content/docs/apis/txbuilder/index.mdx +++ b/content/docs/apis/txbuilder/index.mdx @@ -12,6 +12,8 @@ import { CardTitle, } from "@/components/ui/card"; +> **Note:** `MeshTxBuilder` is deprecated but still works. New code uses `TxBuilder`, which takes a list of parts instead of a chain of calls. See [Migrating to TxBuilder](/apis/txbuilder/migration). + ## Overview `MeshTxBuilder` is a powerful, low-level API for constructing Cardano transactions. It provides complete control over every aspect of transaction building, from simple ADA transfers to complex smart contract interactions, staking operations, and governance actions. diff --git a/content/docs/apis/txbuilder/meta.json b/content/docs/apis/txbuilder/meta.json index d43a6ec..c814af7 100644 --- a/content/docs/apis/txbuilder/meta.json +++ b/content/docs/apis/txbuilder/meta.json @@ -1,5 +1,5 @@ { "title": "Transaction Builder", "icon": "BanknotesIcon", - "pages": ["basics", "minting", "smart-contracts", "staking", "governance"] + "pages": ["basics", "minting", "smart-contracts", "staking", "governance", "migration"] } \ No newline at end of file diff --git a/content/docs/apis/txbuilder/migration.mdx b/content/docs/apis/txbuilder/migration.mdx new file mode 100644 index 0000000..c7ad81d --- /dev/null +++ b/content/docs/apis/txbuilder/migration.mdx @@ -0,0 +1,245 @@ +--- +title: "Migrating to TxBuilder" +description: "Move code from the deprecated MeshTxBuilder chain to TxBuilder parts, with before and after examples." +--- + +## Overview + +A transaction is now a list of parts, such as `output(...)` or `mint.native(...)`. Pass the list to `builder.build()`. The builder picks inputs, adds change and sets the fee. Then you sign and submit. `MeshTxBuilder` is deprecated but still works. All new names come from `@meshsdk/core`. + +Even if you do not migrate, `MeshTxBuilder` now runs on `TxBuilder`, so it can throw `OUTPUT_BELOW_MIN_COIN`, `FEE_TOO_LOW`, `NETWORK_MISMATCH` and `DATUM_MISMATCH` where it used to return a transaction the ledger refused. + +To move a transaction: + +1. Make one `TxBuilder`. +2. Turn each chain into parts. +3. Replace sign and submit. +4. Check error codes. + +Examples assume `wallet`, `provider`, `utxos`, `changeAddress` and `recipient` exist. + +## What Changes + +### Before and After + +**Before:** + +```tsx +import { MeshTxBuilder } from "@meshsdk/core"; + +const txBuilder = new MeshTxBuilder({ fetcher: provider }); + +const unsignedTx = await txBuilder + .txOut(recipient, [{ unit: "lovelace", quantity: "5000000" }]) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos) + .complete(); +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); +``` + +**After:** + +```tsx +import { output, TxBuilder } from "@meshsdk/core"; + +const builder = new TxBuilder({ network: "preprod", provider }); + +const built = await builder.build( + output({ address: recipient, value: { lovelace: 5_000_000n } }), + { payer: wallet }, +); +await built.sign(); +await built.submit(); +console.log(built.txHash); +``` + +### Old to New + +| Old | New | +|-----|-----| +| `new MeshTxBuilder({ fetcher })`, one per transaction | `new TxBuilder({ network, provider })`. `network` is required. One builder serves every transaction. | +| `.txOut()`, `.mint()`, `.txIn()` in a chain | One part per call, in a list: `output`, `mint.native`, `spend.plutus`, ... | +| `.changeAddress()` and `.selectUtxosFrom()` | `{ payer }`: a wallet, an address, or `{ changeAddress, utxos }` | +| `.complete()` returns a CBOR string | `builder.build()` returns a `BuiltTx`. `built.tx` is the string. | +| Amounts as strings: `"5000000"` | Amounts as `bigint`: `5_000_000n` | +| `mintPlutusScriptV2()` and friends | Not needed. The version is in `script`. | +| `txInInlineDatumPresent()`, `txInCollateral()`, execution units | Not needed. The builder reads the datum, picks collateral and evaluates units. | +| `.mintPlutusScriptV2().mint(...).mintingScript(code).mintRedeemerValue(r)` | `mint.plutus({ script, redeemer: { data: r }, assets })` | +| `.metadataValue(674, { msg: [...] })` | `message({ text })`. For another label: `metadata({ metadataLabel: 721n, value })` | +| `.requiredSignerHash(hash)` | `guard.pubKey({ address })`, or `{ keyHash }` | +| `.invalidHereafter(slot)` | `validity({ until: ms })`. It takes milliseconds, so `resolveSlotNo` is not needed. Slots still work with `invalidBefore` and `invalidHereafter`. | +| `.voteDelegationCertificate(drep, address)` | `certificate.voteDelegation({ stake, drep })`. `drep` can be `"alwaysAbstain"`. | +| `.drepRegistrationCertificate(id, anchor)` | `certificate.drepRegistration({ drep, anchor, deposit })`. The old call assumed the deposit. Now give `deposit`, or `deposits` to `new TxBuilder`. | +| `wallet.signTx(tx)` and `wallet.signTx(tx, true)` | `built.sign()`. Signing is partial by default, so there is no flag. | +| `.signingKey(skey)` and `.completeSigning()` | `built.sign({ signers: keySigner(skey) })` | +| `wallet.submitTx(signedTx)` | `built.submit()`. The hash is `built.txHash`, known before signing. | + +## Examples + +### Mint and Burn with a Native Script + +**Before:** + +```tsx +const forgingScript = ForgeScript.withOneSignature(changeAddress); +const policyId = resolveScriptHash(forgingScript); + +const unsignedTx = await txBuilder + .mint("1", policyId, stringToHex("MeshToken")) // burn: "-1" + .mintingScript(forgingScript) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos) + .complete(); +``` + +**After:** + +```tsx +import { ForgeScript, mint, stringToHex } from "@meshsdk/core"; + +const forgingScript = ForgeScript.withOneSignature(changeAddress); +const tokenNameHex = stringToHex("MeshToken"); + +const built = await builder.build( + mint.native({ script: forgingScript, assets: { [tokenNameHex]: 1n } }), // burn: -1n + { payer: wallet }, +); +``` + +The policy id comes from the script. Use one mint part per policy and put every asset name in its `assets`: a second part of the same policy is `DUPLICATE_PART`. + +### Spend from a Plutus Script with a Reference Script + +**Before:** + +```tsx +const unsignedTx = await txBuilder + .spendingPlutusScriptV2() + .txIn(assetUtxo.input.txHash, assetUtxo.input.outputIndex) + .txInInlineDatumPresent() + .txInRedeemerValue(mConStr0([])) + .spendingTxInReference(refTxHash, 0) // the script sits in a reference output + .txInCollateral( + collateral.input.txHash, + collateral.input.outputIndex, + collateral.output.amount, + collateral.output.address, + ) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos) + .complete(); +``` + +**After:** + +```tsx +import { mConStr0, spend } from "@meshsdk/core"; + +const built = await builder.build( + spend.plutus({ + utxo: assetUtxo, + script: { reference: { txHash: refTxHash, outputIndex: 0 } }, + redeemer: { data: mConStr0([]) }, + }), + { payer: wallet }, +); +``` + +The builder reads the datum from the output, so `txInInlineDatumPresent()` is gone. For an output that holds a datum hash, add `datum: { data: myDatum }` where the old code called `txInDatumValue(myDatum)`. + +### Stake: Register, Delegate and Withdraw + +**Before:** + +```tsx +const poolId = "pool1pu5jlj4q9w9jlxeu370a3c9myx47md5j5m2str0naunn2q3lkdy"; + +const registerTx = await txBuilder + .registerStakeCertificate(rewardAddress) + .delegateStakeCertificate(rewardAddress, deserializePoolId(poolId)) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos) + .complete(); + +txBuilder.reset(); // one chain per transaction +const withdrawTx = await txBuilder + .withdrawal(rewardAddress, "5000000") + .changeAddress(changeAddress) + .selectUtxosFrom(utxos) + .complete(); +``` + +**After:** + +```tsx +import { certificate, withdrawal } from "@meshsdk/core"; + +const registerTx = await builder.build( + [ + certificate.stakeRegistration({ stake: rewardAddress }), + certificate.stakeDelegation({ stake: rewardAddress, pool: poolId }), + ], + { payer: wallet }, +); + +const withdrawTx = await builder.build( + withdrawal.pubKey({ rewardAddress, amount: 5_000_000n }), + { payer: wallet }, +); +``` + +> **Note:** `stakeRegistration` is not the old certificate. It states the deposit and the stake key must sign. + +Give the pool id as it is: no `deserializePoolId`. `amount` is a `bigint`, and it must be the whole reward balance. `amount: "all"` looks the balance up for you. + +## Signing and Submitting + +```tsx +// build(): wait for a block after submit() +const { slot } = await built.awaitInclusion(); + +// plan(): sign, submit and wait in one call +const plan = await builder.plan(parts, { payer: wallet }); +await plan.run(); +console.log(plan.step("main").txHash); +``` + +`plan()` sends several transactions in order and tracks each one. A one-to-one port only needs `build()`. + +**Remember:** + +- `submit()` goes through the provider, not the wallet. Pass `{ submitter: wallet }` to send through the wallet. +- Never rebuild a transaction to retry it. A new build may pick other inputs, and both could land. Call `submit()` again on the same `BuiltTx`. +- `plan()` needs a provider that returns block heights, and `awaitInclusion()` of a Plutus transaction needs the validity flag. The plain `BlockfrostProvider` has neither. + +## Troubleshooting + +### If You Keep MeshTxBuilder + +- Error messages differ from before, and so may the final CBOR. +- Every Plutus transaction gets collateral and a collateral return. Collateral from `txInCollateral` is used as given. +- On a test network, script transactions with a validity interval need `new MeshTxBuilder({ network: "preprod", fetcher })`. +- Internal helpers such as `selectUtxos` and `sortInputs` were removed. The builder does that work. + +### Error Codes + +Check the code, not the message: `TxError.is(error, "MISSING_SIGNATURES")`. + +| Code | Fix | +|------|-----| +| `MISSING_PAYER` | Pass `{ payer }` to `build()` or `plan()`. | +| `MISSING_PARAMETER` | Give a `provider`, or `params` and `costModels`. For governance, give `deposits`. | +| `OUTPUT_BELOW_MIN_COIN` | Raise the output's lovelace, or leave `lovelace` out. | +| `NETWORK_MISMATCH` | An address, wallet or provider is on another network than `network`. | +| `INSUFFICIENT_FUNDS` | The payer cannot cover it. `error.details` names the unit and the amount missing. | +| `DUPLICATE_PART` | One mint part per policy, one `validity`, one `message`. The same input twice is also refused. | +| `UTXO_NOT_FOUND` | The output does not exist, is spent, or the provider has not seen it yet. Pass the UTxO in full. | +| `MISSING_SIGNATURES` | A key has not signed. `built.missing` lists the keys. A stake registration needs the stake key. | +| `EVALUATION_FAILED` | A script failed. `error.details.failures` names the part and its label. | +| `CANNOT_OBSERVE` | `plan()` needs block heights. `awaitInclusion()` needs the transaction search and, for a Plutus transaction, the validity flag. `build()` and `submit()` need none of these. | + +## Related + +- [Skills](/ai/skills) - install the `mesh-tx-builder-migration` skill +- [Package README](https://github.com/MeshJS/mesh/tree/main/packages/mesh-transaction) - the `@meshsdk/transaction` guide diff --git a/data/links-txbuilders.ts b/data/links-txbuilders.ts index bafcaf4..e1af7be 100644 --- a/data/links-txbuilders.ts +++ b/data/links-txbuilders.ts @@ -25,6 +25,11 @@ export const metaTxbuilderGovernance = { title: "Governance Transactions", desc: "Transactions for participating in Cardano's on-chain governance", }; +export const metaTxbuilderMigration = { + link: `/apis/txbuilder/migration`, + title: "Migrating to TxBuilder", + desc: "Move from the MeshTxBuilder chain to TxBuilder parts", +}; export const linksTxbuilder = [ metaTxbuilderBasic, @@ -32,6 +37,7 @@ export const linksTxbuilder = [ metaTxbuilderSmartContract, metaTxbuilderStaking, metaTxbuilderGovernance, + metaTxbuilderMigration, ]; export const metaTxbuilder = { From 3cafd0bc677f0382fa5c75311b30a7d0c9e5f20e Mon Sep 17 00:00:00 2001 From: lisicky Date: Sun, 22 Nov 2026 16:39:11 +0100 Subject: [PATCH 02/15] docs: Transaction Builder on TxBuilder --- content/docs/apis/txbuilder/basics.mdx | 600 +++------- content/docs/apis/txbuilder/governance.mdx | 1022 ++--------------- content/docs/apis/txbuilder/index.mdx | 70 +- content/docs/apis/txbuilder/legacy/basics.mdx | 515 +++++++++ .../docs/apis/txbuilder/legacy/governance.mdx | 996 ++++++++++++++++ content/docs/apis/txbuilder/legacy/index.mdx | 62 + content/docs/apis/txbuilder/legacy/meta.json | 5 + .../docs/apis/txbuilder/legacy/minting.mdx | 678 +++++++++++ .../apis/txbuilder/legacy/smart-contracts.mdx | 708 ++++++++++++ .../docs/apis/txbuilder/legacy/staking.mdx | 591 ++++++++++ content/docs/apis/txbuilder/meta.json | 4 +- .../{migration.mdx => migration/index.mdx} | 0 content/docs/apis/txbuilder/minting.mdx | 749 +++--------- .../docs/apis/txbuilder/smart-contracts.mdx | 765 ++---------- content/docs/apis/txbuilder/staking.mdx | 632 ++-------- content/docs/apis/x402/withdrawal.mdx | 2 +- data/links-transactions.ts | 2 +- data/links-txbuilders.ts | 14 +- 18 files changed, 4192 insertions(+), 3223 deletions(-) create mode 100644 content/docs/apis/txbuilder/legacy/basics.mdx create mode 100644 content/docs/apis/txbuilder/legacy/governance.mdx create mode 100644 content/docs/apis/txbuilder/legacy/index.mdx create mode 100644 content/docs/apis/txbuilder/legacy/meta.json create mode 100644 content/docs/apis/txbuilder/legacy/minting.mdx create mode 100644 content/docs/apis/txbuilder/legacy/smart-contracts.mdx create mode 100644 content/docs/apis/txbuilder/legacy/staking.mdx rename content/docs/apis/txbuilder/{migration.mdx => migration/index.mdx} (100%) diff --git a/content/docs/apis/txbuilder/basics.mdx b/content/docs/apis/txbuilder/basics.mdx index f370bd0..a41aa7a 100644 --- a/content/docs/apis/txbuilder/basics.mdx +++ b/content/docs/apis/txbuilder/basics.mdx @@ -1,514 +1,250 @@ --- -title: "Transaction Builder Basics" -description: "Build and customize Cardano transactions with the MeshTxBuilder low-level API." +title: "Transaction Basics" +description: "Build, sign and submit a Cardano transaction with TxBuilder: payer, outputs, metadata, validity and signers." --- -import Link from "fumadocs-core/link"; - ## Overview -`MeshTxBuilder` is a powerful, low-level API for constructing Cardano transactions. It provides fine-grained control over every aspect of transaction building, from simple ADA transfers to complex multi-signature and smart contract interactions. +A transaction is a list of parts, such as `output(...)`. Give the list and a payer to `builder.build()` and you get a `BuiltTx` to sign and submit. The builder selects inputs, adds change and sets the fee. For scripts it also adds collateral and execution units, so you set none of them. -**When to use MeshTxBuilder:** -- Building custom transaction logic beyond standard transfers -- Creating multi-signature transactions -- Interacting with Plutus smart contracts -- Optimizing transaction fees and execution units +Examples use these names, which your application defines: -## Quick Start +- `provider`, `wallet` - a provider such as `BlockfrostProvider` ([Providers](/providers)), and a `MeshWallet` or `BrowserWallet` ([Wallets](/apis/wallets)) +- `changeAddress` - the wallet's address, from `await wallet.getChangeAddress()` +- `recipient`, `partner` - addresses +- `utxo`, `utxos` - one output of yours and a list of them, as Mesh `UTxO`s (an unspent output: coins held at an address) +- `unit` - a policy id plus an asset name in hex +- `params`, `costModels` - protocol parameters (`Protocol`) and cost models (`number[][]`) +- `builder` - the one made in the next section -```tsx -import { MeshTxBuilder, BlockfrostProvider } from "@meshsdk/core"; - -// Initialize provider and builder -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -// Build a simple transfer -const unsignedTx = await txBuilder - .txOut("addr_test1qz...", [{ unit: "lovelace", quantity: "5000000" }]) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos) - .complete(); - -// Sign and submit -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); -``` +## Create a Builder -## Configuration +`network` is required: `"mainnet"`, `"preprod"`, `"preview"`, or `customNetwork(...)` for a devnet. Give a `provider` to read from the chain. One builder serves every transaction. -### Constructor Options +To build offline, give `params` and `costModels` instead of a provider. Then name the payer as `{ changeAddress, utxos }`, and give any outputs that parts name by out ref in the `knownUtxos` build option. `params` and `costModels` also replace what a provider would read. ```tsx -const txBuilder = new MeshTxBuilder({ - fetcher: provider, // Required for auto-fetching UTXO data - submitter: provider, // Optional: for direct submission via builder - evaluator: provider, // Optional: for script execution unit optimization - serializer: serializer, // Optional: custom serializer (default: CSLSerializer) - params: protocolParams, // Optional: custom protocol parameters - isHydra: false, // Optional: use Hydra protocol parameters - verbose: true, // Optional: enable detailed logging -}); -``` - -| Option | Type | Required | Description | -|--------|------|----------|-------------| -| `fetcher` | `IFetcher` | Recommended | Provider for fetching blockchain data | -| `submitter` | `ISubmitter` | No | Provider for submitting transactions | -| `evaluator` | `IEvaluator` | No | Provider for evaluating script execution | -| `serializer` | `IMeshTxSerializer` | No | Custom transaction serializer | -| `params` | `Partial` | No | Custom protocol parameters | -| `isHydra` | `boolean` | No | Enable Hydra-specific parameters | -| `verbose` | `boolean` | No | Enable detailed console logging | +import { TxBuilder } from "@meshsdk/core"; -## Sending ADA +// Online: parameters, UTxOs and outputs are read through the provider +const builder = new TxBuilder({ network: "preprod", provider }); -### Basic Transfer - -Send ADA to a recipient address: - -```tsx -import { MeshTxBuilder, BlockfrostProvider } from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -// Get wallet data -const utxos = await wallet.getUtxos(); -const changeAddress = await wallet.getChangeAddress(); - -// Build transaction -const unsignedTx = await txBuilder - .txOut("addr_test1qz...", [{ unit: "lovelace", quantity: "5000000" }]) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos) - .complete(); - -// Sign and submit -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); +// Offline: nothing is read, so give the parameters yourself +const offline = new TxBuilder({ network: "preprod", params, costModels }); ``` -### Send Multiple Outputs +`builder.add(...parts)` returns a new builder that also holds those parts, so a function that returns parts is a reusable piece. A part that a transaction holds once, such as `validity` or `message`, held and also given again is `DUPLICATE_PART`. -Send to multiple recipients in a single transaction: +## Choose the Payer -```tsx -const unsignedTx = await txBuilder - .txOut("addr_test1qz...", [{ unit: "lovelace", quantity: "5000000" }]) - .txOut("addr_test1qr...", [{ unit: "lovelace", quantity: "3000000" }]) - .txOut("addr_test1qs...", [{ unit: "lovelace", quantity: "2000000" }]) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos) - .complete(); -``` - -### Send Native Assets - -Include native assets (tokens/NFTs) in the output: +The payer pays and gets the change. There is no default: without one, `build()` throws `MISSING_PAYER`. Give a wallet, an address or your own UTxOs. A wallet also signs by default. ```tsx -const unsignedTx = await txBuilder - .txOut("addr_test1qz...", [ - { unit: "lovelace", quantity: "2000000" }, - { unit: "d9312da562da182b02322fd8acb536f37eb9d29fba7c49dc172555274d657368546f6b656e", quantity: "1" } - ]) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos) - .complete(); -``` - -## Input Selection - -### Automatic Selection +import { output } from "@meshsdk/core"; -Let Mesh automatically select UTXOs to cover the transaction: +const pay = output({ address: recipient, value: { lovelace: 5_000_000n } }); -```tsx -const unsignedTx = await txBuilder - .txOut(recipientAddress, [{ unit: "lovelace", quantity: "5000000" }]) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos) - .complete(); +// A wallet: its change address and UTxOs are read +const byWallet = await builder.build(pay, { payer: wallet }); +// An address: change goes there, its UTxOs are read through the provider +const byAddress = await builder.build(pay, { payer: changeAddress }); +// Your own data: nothing is read +const byData = await builder.build(pay, { payer: { changeAddress, utxos } }); ``` -### Selection Strategies +## Send Lovelace and Assets -Configure how UTXOs are selected: +`value` maps `lovelace` and units to `bigint` amounts. Leave `lovelace` out and the builder adds the minimum the output needs. Too little is `OUTPUT_BELOW_MIN_COIN`. For several outputs, pass a list: outputs keep their order, and a part that is `false`, `null` or `undefined` is skipped, so `condition && output(...)` works. To attach a datum to an output, see [Smart Contracts](/apis/txbuilder/smart-contracts#lock-assets-at-a-script). ```tsx -txBuilder.selectUtxosFrom( - utxos, // Available UTXOs - "largestFirst", // Selection strategy - "5000000", // Minimum threshold (lovelace) - true // Include transaction fees in calculation +import { output } from "@meshsdk/core"; + +const built = await builder.build( + [ + output({ + address: recipient, + value: { lovelace: 2_000_000n, [unit]: 1n }, + }), + output({ address: partner, value: { [unit]: 1n } }), // no lovelace: the minimum is added + ], + { payer: wallet }, ); ``` -| Strategy | Description | -|----------|-------------| -| `experimental` | Mesh's optimized selection algorithm | -| `keepRelevant` | Prefer UTXOs with relevant assets | -| `largestFirst` | Select largest UTXOs first | -| `largestFirstMultiAsset` | Optimized for transactions with multiple assets | - -### Manual Input Selection +## Build, Sign and Submit -Explicitly specify which UTXOs to spend: +`build()` signs nothing and sends nothing. It returns a `BuiltTx`. `built.tx` is the unsigned transaction as a hex string (CBOR), and `built.txHash` is known before signing. `sign()` signs as the payer, and `submit()` sends through the provider, or through the `submitter` you name. ```tsx -const unsignedTx = await txBuilder - .txIn( - "abc123...", // Transaction hash - 0, // Output index - [{ unit: "lovelace", quantity: "10000000" }], // Amount - "addr_test1qz..." // Address - ) - .txOut("addr_test1qr...", [{ unit: "lovelace", quantity: "5000000" }]) - .changeAddress(changeAddress) - .complete(); -``` - -## Multi-Signature Transactions +import { output } from "@meshsdk/core"; -Create transactions requiring multiple signatures: - -```tsx -import { MeshTxBuilder, ForgeScript, resolveScriptHash, stringToHex } from "@meshsdk/core"; -import { MeshCardanoHeadlessWallet, AddressType } from "@meshsdk/wallet"; - -// Create minting wallet -const mintingWallet = await MeshCardanoHeadlessWallet.fromMnemonic({ - networkId: 0, - walletAddressType: AddressType.Base, - fetcher: provider, - submitter: provider, - mnemonic: ["your", "mnemonic", "words", "..."], -}); - -// Create forging script -const forgingScript = ForgeScript.withOneSignature( - await mintingWallet.getChangeAddressBech32() +const built = await builder.build( + output({ address: recipient, value: { lovelace: 5_000_000n } }), + { payer: wallet }, ); - -const policyId = resolveScriptHash(forgingScript); -const assetName = "MeshToken"; - -// Get user wallet data -const address = (await wallet.getUsedAddresses())[0]; -const utxos = await wallet.getUtxos(); - -// Build multi-sig transaction -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -const unsignedTx = await txBuilder - .mint("1", policyId, stringToHex(assetName)) - .mintingScript(forgingScript) - .metadataValue(721, { - [policyId]: { - [assetName]: { name: "Mesh Token", image: "ipfs://..." } - } - }) - .changeAddress(address) - .selectUtxosFrom(utxos) - .complete(); - -// Sign with both wallets (partial signing) -const signedTx1 = await wallet.signTx(unsignedTx, true, false); -const signedTx2 = await mintingWallet.signTx(signedTx1, true, false); - -// Submit final transaction -const txHash = await wallet.submitTx(signedTx2); +const { tx, txHash, fee } = built; +await built.sign(); // the payer signs +await built.submit({ submitter: wallet }); // the wallet sends it +const { slot } = await built.awaitInclusion(); // found in a block ``` -## Native Script Multi-Sig +Never rebuild a transaction to retry it: a new build may pick other inputs, and both could land. Call `submit()` again on the same `BuiltTx`. -Spend from a native script address requiring multiple signatures: +### Sign with a Key or Several Signers -```tsx -import { deserializeAddress, serializeNativeScript, NativeScript } from "@meshsdk/core"; - -// Get key hashes from addresses -const { pubKeyHash: keyHash1 } = deserializeAddress(walletAddress1); -const { pubKeyHash: keyHash2 } = deserializeAddress(walletAddress2); - -// Create native script requiring both signatures -const nativeScript: NativeScript = { - type: "all", - scripts: [ - { type: "sig", keyHash: keyHash1 }, - { type: "sig", keyHash: keyHash2 }, - ], -}; - -// Serialize script to get address -const { address: scriptAddress, scriptCbor } = serializeNativeScript(nativeScript); - -// Fetch UTXOs from script address -const scriptUtxos = await provider.fetchAddressUTxOs(scriptAddress); -const utxo = scriptUtxos[0]; - -// Build transaction spending from script -const unsignedTx = await txBuilder - .txIn( - utxo.input.txHash, - utxo.input.outputIndex, - utxo.output.amount, - utxo.output.address - ) - .txInScript(scriptCbor) - .txOut("addr_test1qz...", [{ unit: "lovelace", quantity: "2000000" }]) - .changeAddress(scriptAddress) - .selectUtxosFrom(scriptUtxos) - .complete(); - -// Both wallets must sign -const signedTx1 = await wallet1.signTx(unsignedTx, true, false); -const signedTx2 = await wallet2.signTx(signedTx1, true, false); -const txHash = await wallet1.submitTx(signedTx2); -``` - -## Transaction Metadata - -### Add Messages - -Attach messages to transactions using label 674 (CIP-20): +`sign({ signers })` takes one signer or a list. A signer is a wallet, or `keySigner(key)`, where `key` is hex, bech32 (such as `ed25519_sk`) or the `cborHex` of a signing key file. Each signer is asked, in order, for the keys that are still missing. `built.missing` lists the keys that have not signed yet. ```tsx -const unsignedTx = await txBuilder - .txOut(recipientAddress, [{ unit: "lovelace", quantity: "5000000" }]) - .metadataValue(674, { - msg: [ - "Invoice-No: 1234567890", - "Customer-No: 555-1234" - ] - }) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos) - .complete(); -``` - -Each message string must be at most 64 bytes when UTF-8 encoded. +import { keySigner, output } from "@meshsdk/core"; -### Custom Metadata - -Add any JSON-compatible metadata: +const built = await builder.build( + output({ address: recipient, value: { lovelace: 5_000_000n } }), + { payer: changeAddress }, // an address: no wallet needed +); -```tsx -const unsignedTx = await txBuilder - .metadataValue(customLabel, { - key: "value", - nested: { data: [1, 2, 3] } - }) - .txOut(address, amount) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos) - .complete(); +await built.sign({ signers: keySigner(process.env.TREASURY_SKEY!) }); // a private key +// or several signers, asked in order: +await built.sign({ signers: [wallet, keySigner(process.env.PARTNER_SKEY!)] }); +console.log(built.missing); // keys that have not signed yet ``` -## Transaction Validity +## Add More to a Transaction -### Set Expiration (TTL) +Add these parts to the list you give to `build()`. -Make a transaction invalid after a specific slot: +### Choose Inputs -```tsx -import { resolveSlotNo } from "@meshsdk/core"; - -// Transaction expires in 5 minutes -const expirationTime = new Date(Date.now() + 5 * 60 * 1000); -const slot = resolveSlotNo("mainnet", expirationTime.getTime()); - -const unsignedTx = await txBuilder - .txOut(address, amount) - .invalidHereafter(Number(slot)) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos) - .complete(); -``` - -### Set Start Time - -Make a transaction invalid before a specific slot: +The builder picks the payer's inputs. To spend a particular output, add a `spend.pubKey` part. To limit what the builder may pick, give `canSelect`. To replace the built-in selection, give `coinSelection: (need, candidates) => outRefs`, where each out ref names a candidate. ```tsx -const startTime = new Date(Date.now() + 10 * 60 * 1000); // 10 minutes from now -const startSlot = resolveSlotNo("mainnet", startTime.getTime()); - -const unsignedTx = await txBuilder - .txOut(address, amount) - .invalidBefore(Number(startSlot)) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos) - .complete(); +import { output, spend } from "@meshsdk/core"; + +const built = await builder.build( + [ + spend.pubKey({ utxo }), // an input you choose + output({ address: recipient, value: { lovelace: 5_000_000n } }), + ], + { payer: wallet, canSelect: (c) => c.value.lovelace > 5_000_000n }, +); ``` -## Required Signers +### Add a Message or Metadata -Specify required signers for smart contract transactions: +`message` writes a message under metadata label 674 (CIP-20, the transaction message standard). `metadata` writes any label. Text in `metadata` is limited to 64 bytes per string. `message` cuts a long text into lines for you. ```tsx -import { deserializeAddress } from "@meshsdk/core"; - -const { pubKeyHash } = deserializeAddress(walletAddress); +import { message, metadata, output } from "@meshsdk/core"; -const unsignedTx = await txBuilder - // ... transaction details - .requiredSignerHash(pubKeyHash) - .complete(); +const built = await builder.build( + [ + output({ address: recipient, value: { lovelace: 5_000_000n } }), + message({ text: "Invoice-No: 1234567890" }), + metadata({ metadataLabel: 1234n, value: { order: "42" } }), + ], + { payer: wallet }, +); ``` -## Network Configuration - -### Set Network +### Set the Validity -Configure the network for proper cost model calculation: +`validity` takes POSIX milliseconds: `from` and `until`. For slots, use `invalidBefore` and `invalidHereafter`. For "valid from now", leave `from` out. `build()` sets no deadline, so give `until` when you follow the transaction yourself. ```tsx -txBuilder.setNetwork("mainnet"); // or "testnet", "preview", "preprod" +import { output, validity } from "@meshsdk/core"; + +const built = await builder.build( + [ + output({ address: recipient, value: { lovelace: 5_000_000n } }), + validity({ until: Date.now() + 60 * 60 * 1000 }), // expires in one hour + ], + { payer: wallet }, +); ``` -### Custom Protocol Parameters +### Require a Signer -Use specific protocol parameters: +`guard.pubKey` names a key that must sign. Scripts see it among the signatories. Give its `address` or its `keyHash`. Keys needed for inputs, certificates and similar are worked out by the builder and listed in `built.signers`. ```tsx -const params = await provider.fetchProtocolParameters(); +import { guard, output } from "@meshsdk/core"; -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - params: params, -}); +const built = await builder.build( + [ + output({ address: recipient, value: { lovelace: 5_000_000n } }), + guard.pubKey({ address: partner }), + ], + { payer: wallet }, +); ``` -## Manual Fee Control - -Override automatic fee calculation: - -```tsx -const unsignedTx = await txBuilder - .txOut(address, amount) - .changeAddress(changeAddress) - .setFee("200000") // Set exact fee in lovelace - .complete(); -``` +## Plan Several Transactions -## Build with JSON +`plan()` takes named steps and sends them in order. Use it for several dependent transactions, for retries that cannot pay twice, or to wait for blocks. A plan never builds again, so repeating `run()` sends the same transactions. -Alternative method using a JSON object: +> **Note:** `plan()` needs a provider that returns block heights and, for a step that runs a Plutus script, the validity flag (whether the script passed). The plain `BlockfrostProvider` returns neither, so `plan()` throws `CANNOT_OBSERVE`. The package README (Providers and networks) shows a subclass that adds them. For a Plutus transaction, `awaitInclusion()` needs the validity flag too. `build()` needs neither. ```tsx -import { MeshTxBuilderBody } from "@meshsdk/core"; - -const meshTxBody: Partial = { - outputs: [ - { - address: recipientAddress, - amount: [{ unit: "lovelace", quantity: "5000000" }], - }, - ], - changeAddress: changeAddress, - extraInputs: utxos, - selectionConfig: { - threshold: "5000000", - strategy: "largestFirst", - includeTxFees: true, - }, -}; - -const unsignedTx = await txBuilder.complete(meshTxBody); -``` +import { output } from "@meshsdk/core"; -## Complete Example - -```tsx -import { - MeshTxBuilder, - BlockfrostProvider, - resolveSlotNo -} from "@meshsdk/core"; - -// Setup -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -// Get wallet data -const utxos = await wallet.getUtxos(); -const changeAddress = await wallet.getChangeAddress(); - -// Set expiration (5 minutes) -const expiration = new Date(Date.now() + 5 * 60 * 1000); -const expirationSlot = resolveSlotNo("preprod", expiration.getTime()); - -// Build transaction -const unsignedTx = await txBuilder - // Send 5 ADA to recipient - .txOut("addr_test1qz...", [{ unit: "lovelace", quantity: "5000000" }]) - // Send 3 ADA + token to another recipient - .txOut("addr_test1qr...", [ - { unit: "lovelace", quantity: "3000000" }, - { unit: "policyId...", quantity: "1" } - ]) - // Add transaction message - .metadataValue(674, { msg: ["Payment for services"] }) - // Set expiration - .invalidHereafter(Number(expirationSlot)) - // Configure change and UTXO selection - .changeAddress(changeAddress) - .selectUtxosFrom(utxos, "largestFirst", "5000000", true) - // Build the transaction - .complete(); - -// Sign and submit -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); - -console.log(`Transaction submitted: ${txHash}`); +const plan = await builder.plan( + { + first: output({ address: recipient, value: { lovelace: 5_000_000n } }), + second: output({ address: partner, value: { lovelace: 2_000_000n } }), + }, + { payer: wallet }, +); +await plan.run(); // signs, submits and waits for a block, step by step +console.log(plan.step("second").txHash); ``` -## Troubleshooting - -### "Insufficient funds" error -- Ensure UTXOs have enough ADA to cover outputs + fees + min UTxO values -- Check that `selectUtxosFrom` is provided with current UTXOs -- For native asset outputs, ensure minimum ADA (typically ~1.5 ADA) is included +## Handle Errors -### "Missing input" error -- The `fetcher` provider is required for automatic UTXO data fetching -- If using manual `txIn`, provide all four parameters (txHash, index, amount, address) +Every error is a `TxError` with a `code`. Check the code, not the message. `TxError.is` also types `error.details`. Build before the `try`, so that a retry calls `submit()` on the same `BuiltTx` and never builds again. -### Transaction too large -- Split into multiple transactions -- Reduce the number of outputs -- Use UTXO consolidation first - -### Invalid slot number -- Ensure you're using the correct network in `resolveSlotNo` -- Mainnet and testnets have different slot calculations +```tsx +import { output, TxError } from "@meshsdk/core"; -### Multi-sig transaction fails -- Ensure `partialSign: true` is set for all signers except the last -- Verify all required signers have signed -- Check that signing order doesn't matter (unless script requires specific order) +const built = await builder + .build( + output({ address: recipient, value: { lovelace: 5_000_000n } }), + { payer: wallet }, + ) + .catch((error) => { + if (TxError.is(error, "INSUFFICIENT_FUNDS")) { + console.log(error.details.unit, error.details.missing); + } + throw error; // nothing was sent + }); + +try { + await built.sign(); + await built.submit(); + await built.awaitInclusion(); +} catch (error) { + if (TxError.is(error, "SUBMIT_FAILED", "CONFIRM_TIMEOUT")) { + // the outcome is unknown: call submit() or awaitInclusion() again on this same built + } else throw error; +} +``` + +| Code | Meaning | Fix | +|------|---------|-----| +| `MISSING_PAYER` | `build()` got no `payer` | Pass `{ payer }` | +| `INSUFFICIENT_FUNDS` | the payer's UTxOs cannot pay | `error.details` names the unit and the amount missing | +| `OUTPUT_BELOW_MIN_COIN` | an output holds less lovelace than the ledger requires | Add lovelace, or leave `lovelace` out | +| `DUPLICATE_PART` | the same input, policy or voter twice, or a part that is held once given twice | Give each part once | +| `TX_TOO_LARGE` | the transaction is over the size limit | Split it into several transactions | +| `MISSING_PARAMETER` | no protocol parameters, cost models or deposits | Give a `provider`, or `params`, `costModels` or `deposits` | +| `NETWORK_MISMATCH` | an address, wallet or provider is on another network than `network` | Use one network everywhere | +| `MISSING_SIGNATURES` | a key has not signed, and nothing was sent | Name the signer; `built.missing` lists the keys | +| `SUBMIT_FAILED`, `CONFIRM_TIMEOUT` | the outcome is unknown | Call `submit()` or `awaitInclusion()` again on the same `BuiltTx` | +| `CANNOT_OBSERVE` | the provider returns no block heights or validity flag | See the Note under Plan Several Transactions | ## Related -- Minting Tokens - Mint native assets -- Smart Contracts - Interact with Plutus scripts -- Staking - Delegation and rewards -- Governance - Voting and proposals -- Blockfrost Provider - Provider setup -- Migrating to TxBuilder - Move to the new builder +- [Mint and Burn Assets](/apis/txbuilder/minting) - mint and burn with native and Plutus scripts +- [Smart Contracts](/apis/txbuilder/smart-contracts) - lock and unlock funds at a script +- [Staking Transactions](/apis/txbuilder/staking) - register, delegate and withdraw +- [Governance Transactions](/apis/txbuilder/governance) - DReps, votes and proposals +- [Migrating to TxBuilder](/apis/txbuilder/migration) - move from the `MeshTxBuilder` chain +- [Package README](https://github.com/MeshJS/mesh/tree/main/packages/mesh-transaction) - every part, option and error diff --git a/content/docs/apis/txbuilder/governance.mdx b/content/docs/apis/txbuilder/governance.mdx index a266482..1f0240f 100644 --- a/content/docs/apis/txbuilder/governance.mdx +++ b/content/docs/apis/txbuilder/governance.mdx @@ -1,994 +1,116 @@ --- title: "Governance Transactions" -description: "Participate in Cardano's on-chain governance through DRep delegation, registration, voting, and submitting governance action proposals." +description: "Register as a DRep, delegate your vote, vote on actions and submit proposals with TxBuilder." --- -import Link from "fumadocs-core/link"; - ## Overview -Cardano's on-chain governance system ([CIP-1694](https://github.com/cardano-foundation/CIPs/blob/master/CIP-1694/README.md)) enables the community to vote on proposals and protocol updates. Mesh SDK implements the [CIP-95](https://cips.cardano.org/cip/CIP-0095) Web-Wallet Bridge extension, allowing dApps to interact with governance features. You can delegate your voting power to Decentralized Representatives (DReps), register as a DRep yourself, vote on governance actions, and submit new governance action proposals. - -**When to use this:** -- Delegating your voting power to a DRep -- Registering as a DRep to represent other voters -- Voting on governance actions and protocol changes -- Submitting governance action proposals (info actions, parameter changes, treasury withdrawals, etc.) -- Building governance dashboards and tools -- Creating DRep management applications - -## Quick Start - -```tsx -import { MeshTxBuilder, BlockfrostProvider } from "@meshsdk/core"; - -// Initialize -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -// Get wallet data -const utxos = await wallet.getUtxos(); -const changeAddress = await wallet.getChangeAddress(); -const rewardAddresses = await wallet.getRewardAddresses(); -const rewardAddress = rewardAddresses[0]!; - -// Delegate to a DRep -txBuilder - .voteDelegationCertificate( - { dRepId: "drep1yv4uesaj92wk8ljlsh4p7jzndnzrflchaz5fzug3zxg4naqkpeas3" }, - rewardAddress - ) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos); - -const unsignedTx = await txBuilder.complete(); -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); -``` - -## API Reference - -### voteDelegationCertificate() - -Delegate voting power to a DRep. - -```tsx -.voteDelegationCertificate(drep: DRepId, rewardAddress: string) -``` - -| Parameter | Type | Description | -|-----------|------|-------------| -| `drep` | `DRepId` | DRep identifier object | -| `rewardAddress` | `string` | Your stake/reward address | - -The `DRepId` object can specify: -- `{ dRepId: "drep1..." }` - Delegate to a specific DRep -- `{ alwaysAbstain: true }` - Always abstain from voting -- `{ alwaysNoConfidence: true }` - Always vote no confidence - -### drepRegistrationCertificate() - -Register as a DRep. - -```tsx -.drepRegistrationCertificate(dRepId: string, anchor?: Anchor) -``` - -| Parameter | Type | Description | -|-----------|------|-------------| -| `dRepId` | `string` | Your DRep ID (from wallet) | -| `anchor` | `Anchor` | Optional metadata anchor | - -The `Anchor` object: -```tsx -{ - anchorUrl: string; // URL to metadata JSON - anchorDataHash: string; // Hash of metadata content -} -``` - -### drepUpdateCertificate() - -Update DRep metadata. - -```tsx -.drepUpdateCertificate(dRepId: string, anchor?: Anchor) -``` - -| Parameter | Type | Description | -|-----------|------|-------------| -| `dRepId` | `string` | Your DRep ID | -| `anchor` | `Anchor` | New metadata anchor | - -### drepDeregistrationCertificate() - -Retire as a DRep and reclaim deposit. - -```tsx -.drepDeregistrationCertificate(dRepId: string) -``` - -| Parameter | Type | Description | -|-----------|------|-------------| -| `dRepId` | `string` | Your DRep ID to retire | - -### vote() - -Cast a vote on a governance action. - -```tsx -.vote(voter: Voter, govActionId: GovActionId, votingProcedure: VotingProcedure) -``` - -| Parameter | Type | Description | -|-----------|------|-------------| -| `voter` | `Voter` | Voter identity | -| `govActionId` | `GovActionId` | Governance action reference | -| `votingProcedure` | `VotingProcedure` | Vote details | - -The `Voter` object: -```tsx -// DRep voter -{ type: "DRep", drepId: "drep1..." } - -// Stake pool operator -{ type: "StakePool", poolId: "pool1..." } - -// Constitutional committee member -{ type: "ConstitutionalCommittee", hotCred: "..." } -``` - -The `VotingProcedure` object: -```tsx -{ - voteKind: "Yes" | "No" | "Abstain"; - anchor?: { - anchorUrl: string; - anchorDataHash: string; - }; -} -``` - -### votePlutusScriptV3() - -Indicate voting with a Plutus script. - -```tsx -.votePlutusScriptV3() -``` - -### voteScript() - -Provide the voting script. - -```tsx -.voteScript(scriptCbor: string) -``` - -### voteRedeemerValue() - -Provide the redeemer for script-based voting. - -```tsx -.voteRedeemerValue(redeemer: Data | object | string, type?: "Mesh" | "CBOR" | "JSON", exUnits?: Budget) -``` - -### proposal() - -Submit a governance action proposal. Requires a deposit (returned when the action is resolved). - -```tsx -.proposal(governanceAction: GovernanceAction, anchor: Anchor, rewardAccount: string, deposit?: string) -``` - -| Parameter | Type | Description | -|-----------|------|-------------| -| `governanceAction` | `GovernanceAction` | The governance action to propose | -| `anchor` | `Anchor` | Proposal metadata anchor (URL + hash) | -| `rewardAccount` | `string` | Reward address for deposit return | -| `deposit` | `string` | Deposit amount in lovelace (defaults to `"100000000000"`, i.e. 100,000 ADA) | - -The `GovernanceAction` is a discriminated union with a `kind` and `action` field: - -```tsx -// Info action (no on-chain effect, used for polls/sentiment) -{ kind: "InfoAction", action: {} } - -// Protocol parameter change -{ - kind: "ParameterChangeAction", - action: { - govActionId?: { transactionId: string; govActionIndex: number }, - protocolParamUpdates: ProtocolParamUpdate, - policyHash?: { bytes: string }, - } -} - -// Treasury withdrawal -{ - kind: "TreasuryWithdrawalsAction", - action: { - withdrawals: Record, // reward address -> lovelace amount - policyHash?: { bytes: string }, - } -} - -// No confidence in current committee -{ - kind: "NoConfidenceAction", - action: { - govActionId?: { transactionId: string; govActionIndex: number }, - } -} - -// Update constitutional committee -{ - kind: "UpdateCommitteeAction", - action: { - govActionId?: { transactionId: string; govActionIndex: number }, - committee: { - members: Array<{ stakeCredential: Credential; termLimit: number }>, - quorumThreshold: { numerator: string; denominator: string }, - }, - membersToRemove: Credential[], - } -} - -// New constitution -{ - kind: "NewConstitutionAction", - action: { - govActionId?: { transactionId: string; govActionIndex: number }, - constitution: { - anchor: Anchor, - scriptHash?: { bytes: string }, - }, - } -} - -// Hard fork initiation -{ - kind: "HardForkInitiationAction", - action: { - govActionId?: { transactionId: string; govActionIndex: number }, - protocolVersion: { major: number; minor: number }, - } -} -``` - -The `Credential` type used in committee actions: -```tsx -{ type: "KeyHash", keyHash: string } -// or -{ type: "ScriptHash", scriptHash: string } -``` - -The `govActionId` field is optional and refers to the most recently enacted governance action of the same type that this proposal builds upon. It is required for action types that must chain from a previous action (parameter changes, hard forks, committee updates, no confidence, new constitution). - -### proposalScript() - -Attach a Plutus script witness to the proposal. - -```tsx -.proposalScript(scriptCbor: string, version: "V1" | "V2" | "V3") -``` - -| Parameter | Type | Description | -|-----------|------|-------------| -| `scriptCbor` | `string` | CBOR hex of the Plutus script | -| `version` | `LanguageVersion` | Plutus language version | - -### proposalTxInReference() - -Use a reference script for the proposal instead of providing it inline. - -```tsx -.proposalTxInReference(txHash: string, txIndex: number, scriptSize: string, scriptHash: string, version: "V1" | "V2" | "V3") -``` - -| Parameter | Type | Description | -|-----------|------|-------------| -| `txHash` | `string` | Transaction hash of the reference UTxO | -| `txIndex` | `number` | Transaction index of the reference UTxO | -| `scriptSize` | `string` | Size of the Plutus script in bytes | -| `scriptHash` | `string` | Script hash of the referenced script | -| `version` | `LanguageVersion` | Plutus language version | - -### proposalRedeemerValue() - -Provide the redeemer for a Plutus script proposal. - -```tsx -.proposalRedeemerValue(redeemer: Data | object | string, type?: "Mesh" | "CBOR" | "JSON", exUnits?: Budget) -``` - -| Parameter | Type | Description | -|-----------|------|-------------| -| `redeemer` | `Data \| object \| string` | Redeemer data | -| `type` | `string` | Data format type (default `"Mesh"`) | -| `exUnits` | `Budget` | Execution units budget (default `{ mem: 7_000_000, steps: 3_000_000_000 }`) | - -## Common Patterns - -### Delegate to a DRep - -Delegate your voting power to a registered DRep: - -```tsx -import { MeshTxBuilder, BlockfrostProvider } from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -const utxos = await wallet.getUtxos(); -const changeAddress = await wallet.getChangeAddress(); -const rewardAddresses = await wallet.getRewardAddresses(); -const rewardAddress = rewardAddresses[0]!; - -const dRepId = "drep1yv4uesaj92wk8ljlsh4p7jzndnzrflchaz5fzug3zxg4naqkpeas3"; - -txBuilder - .voteDelegationCertificate({ dRepId }, rewardAddress) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos); - -const unsignedTx = await txBuilder.complete(); -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); +Governance uses certificates, votes and proposals, passed as parts to `builder.build()`. A DRep (delegated representative) votes on behalf of the stake delegated to it. The DRep and proposal deposits are not in the protocol parameters, so the builder takes them from its `deposits` option, or from `deposit` on a part. Without them the build throws `MISSING_PARAMETER` (see [Handle Errors](/apis/txbuilder/basics#handle-errors)). -console.log(`Delegated to DRep: ${txHash}`); -``` - -### Delegate to Always Abstain - -Configure your stake to always abstain from voting: - -```tsx -import { MeshTxBuilder, BlockfrostProvider } from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -const utxos = await wallet.getUtxos(); -const changeAddress = await wallet.getChangeAddress(); -const rewardAddresses = await wallet.getRewardAddresses(); -const rewardAddress = rewardAddresses[0]!; - -txBuilder - .voteDelegationCertificate({ alwaysAbstain: true }, rewardAddress) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos); - -const unsignedTx = await txBuilder.complete(); -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); -``` - -### Register as a DRep - -Register yourself as a DRep with metadata: - -```tsx -import { MeshTxBuilder, BlockfrostProvider, hashDrepAnchor } from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -// Get DRep ID from wallet -const dRep = await wallet.getDRep(); -const dRepId = dRep.dRepIDCip105; - -// Prepare metadata anchor -const anchorUrl = "https://example.com/drep-metadata.jsonld"; -const anchorMetadata = { - "@context": { - "@language": "en", - "CIP100": "https://github.com/cardano-foundation/CIPs/blob/master/CIP-0100/README.md", - "CIP119": "https://github.com/cardano-foundation/CIPs/blob/master/CIP-0119/README.md", - "hashAlgorithm": "CIP100:hashAlgorithm", - "body": { "@id": "CIP119:body" }, - "givenName": "CIP119:givenName" - }, - "hashAlgorithm": "blake2b-256", - "body": { - "givenName": "My DRep Name" - } -}; -const anchorHash = hashDrepAnchor(anchorMetadata); - -// Get wallet data -const utxos = await wallet.getUtxos(); -const changeAddress = await wallet.getChangeAddress(); - -txBuilder - .drepRegistrationCertificate(dRepId, { - anchorUrl, - anchorDataHash: anchorHash, - }) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos); - -const unsignedTx = await txBuilder.complete(); -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); - -console.log(`DRep registered: ${txHash}`); -``` - -### Update DRep Metadata - -Update your DRep profile information: - -```tsx -import { MeshTxBuilder, BlockfrostProvider, hashDrepAnchor } from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -const dRep = await wallet.getDRep(); -const dRepId = dRep.dRepIDCip105; - -// New metadata -const anchorUrl = "https://example.com/drep-metadata-v2.jsonld"; -const anchorMetadata = { /* updated metadata */ }; -const anchorHash = hashDrepAnchor(anchorMetadata); +Examples stop at `build()`: call `built.sign()` and `built.submit()` as in [Transaction Basics](/apis/txbuilder/basics#build-sign-and-submit). They use `wallet` and `provider` from there, and these names, which your application defines: -const utxos = await wallet.getUtxos(); -const changeAddress = await wallet.getChangeAddress(); +- `builder` - a `TxBuilder` with the deposits of your network: `new TxBuilder({ network: "preprod", provider, deposits: { drepDeposit: 500_000_000n, govActionDeposit: 100_000_000_000n } })` +- `rewardAddress` - your stake address (`stake_test1...` on a test network, `stake1...` on mainnet) +- `drepId` - a DRep id (`drep1...`) +- `anchor` - `{ url, dataHash }`, where a metadata or rationale file is published. `hashDrepAnchor(json)` makes the hash. +- `actionTxHash` - the transaction hash of a governance action -txBuilder - .drepUpdateCertificate(dRepId, { - anchorUrl, - anchorDataHash: anchorHash, - }) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos); +| Task | Part | Signed by | +|------|------|-----------| +| Register, update or retire a DRep | `certificate.drepRegistration`, `drepUpdate`, `drepDeregistration` | the DRep key | +| Delegate your vote | `certificate.voteDelegation` | the stake key | +| Vote on an action | `vote` | the voter's key | +| Submit a proposal | `proposal.info`, `proposal.treasuryWithdrawals` and others | the payer | -const unsignedTx = await txBuilder.complete(); -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); +## Manage a DRep -console.log(`DRep updated: ${txHash}`); -``` - -### Retire as DRep - -Retire from being a DRep and reclaim your deposit: +Register with `certificate.drepRegistration`. `anchor` is optional, and the deposit is `drepDeposit`. Update the metadata with `certificate.drepUpdate`, giving it the `anchor` of the changed file: leave `anchor` out to clear it. Retire with `certificate.drepDeregistration`, which refunds `drepDeposit`. Pass `refund` if the deposit paid was another amount. The DRep key signs: a `MeshWallet` does it in `sign()`, and a browser wallet must be connected with the CIP-95 extension. ```tsx -import { MeshTxBuilder, BlockfrostProvider } from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -const dRep = await wallet.getDRep(); -const dRepId = dRep.dRepIDCip105; - -const utxos = await wallet.getUtxos(); -const changeAddress = await wallet.getChangeAddress(); - -txBuilder - .drepDeregistrationCertificate(dRepId) - .selectUtxosFrom(utxos) - .changeAddress(changeAddress); - -const unsignedTx = await txBuilder.complete(); -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); - -console.log(`DRep retired: ${txHash}`); -``` - -### Vote on Governance Action - -Cast a vote as a DRep: - -```tsx -import { MeshTxBuilder, BlockfrostProvider } from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -const dRep = await wallet.getDRep(); -const dRepId = dRep.dRepIDCip105; - -const utxos = await wallet.getUtxos(); -const changeAddress = await wallet.getChangeAddress(); - -// Governance action to vote on -const govActionTxHash = "aff2909f8175ee02a8c1bf96ff516685d25bf0c6b95aac91f4dfd53a5c0867cc"; -const govActionIndex = 0; - -txBuilder - .vote( - { - type: "DRep", - drepId: dRepId, - }, - { - txHash: govActionTxHash, - txIndex: govActionIndex, - }, - { - voteKind: "Yes", - } - ) - .selectUtxosFrom(utxos) - .changeAddress(changeAddress); - -const unsignedTx = await txBuilder.complete(); -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); - -console.log(`Vote cast: ${txHash}`); -``` - -### Vote with Rationale - -Include reasoning for your vote: - -```tsx -import { MeshTxBuilder, BlockfrostProvider, hashDrepAnchor } from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -const dRep = await wallet.getDRep(); -const dRepId = dRep.dRepIDCip105; - -const utxos = await wallet.getUtxos(); -const changeAddress = await wallet.getChangeAddress(); +import { certificate } from "@meshsdk/core"; -// Prepare vote rationale -const rationaleUrl = "https://example.com/vote-rationale.jsonld"; -const rationaleContent = { - rationale: "I support this proposal because...", - references: ["https://example.com/supporting-doc"], -}; -const rationaleHash = hashDrepAnchor(rationaleContent); - -txBuilder - .vote( - { - type: "DRep", - drepId: dRepId, - }, - { - txHash: "abc123...", - txIndex: 0, - }, - { - voteKind: "Yes", - anchor: { - anchorUrl: rationaleUrl, - anchorDataHash: rationaleHash, - }, - } - ) - .selectUtxosFrom(utxos) - .changeAddress(changeAddress); - -const unsignedTx = await txBuilder.complete(); -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); +const built = await builder.build( + certificate.drepRegistration({ drep: drepId, anchor }), + { payer: wallet }, +); +await built.sign(); // the payer signs; the DRep key too, if the wallet holds it +await built.submit(); +await built.awaitInclusion(); // waits until a block holds it ``` -### Vote with Plutus Script +## Delegate Your Vote -Vote using a Plutus script DRep: +A registered stake key delegates its voting power with `certificate.voteDelegation`. `drep` is a DRep id, `"alwaysAbstain"` or `"alwaysNoConfidence"`. To delegate to a pool and a DRep together, use `certificate.stakeAndVoteDelegation`. ```tsx -import { - MeshTxBuilder, - BlockfrostProvider, - resolveScriptHash, - resolveScriptHashDRepId, - applyCborEncoding -} from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -const utxos = await wallet.getUtxos(); -const collateral = await wallet.getCollateral(); -const changeAddress = await wallet.getChangeAddress(); +import { certificate } from "@meshsdk/core"; -// Your voting script -const votingScriptCbor = applyCborEncoding("your-voting-script-cbor"); -const scriptHash = resolveScriptHash(votingScriptCbor, "V3"); -const scriptDRepId = resolveScriptHashDRepId(scriptHash); - -txBuilder - .txIn( - utxos[0]!.input.txHash, - utxos[0]!.input.outputIndex, - utxos[0]!.output.amount, - utxos[0]!.output.address - ) - .txInCollateral( - collateral[0]!.input.txHash, - collateral[0]!.input.outputIndex, - collateral[0]!.output.amount, - collateral[0]!.output.address - ) - .votePlutusScriptV3() - .vote( - { - type: "DRep", - drepId: scriptDRepId, - }, - { - txHash: "abc123...", - txIndex: 0, - }, - { - voteKind: "Yes", - } - ) - .voteScript(votingScriptCbor) - .voteRedeemerValue("") - .changeAddress(changeAddress); - -const unsignedTx = await txBuilder.complete(); -const signedTx = await wallet.signTx(unsignedTx, true); -const txHash = await wallet.submitTx(signedTx); +const built = await builder.build( + certificate.voteDelegation({ stake: rewardAddress, drep: drepId }), + { payer: wallet }, +); ``` -### Submit an Info Action +## Vote on an Action -Submit an info action (used for polls and sentiment checks — has no on-chain effect): +All votes of one voter go in one `vote` part. `vote` is `"yes"`, `"no"` or `"abstain"`, and `anchor` points to your rationale. A voter can also be `{ pool }` or `{ committee }`. A script DRep adds a `witness`. ```tsx -import { MeshTxBuilder, BlockfrostProvider } from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -const utxos = await wallet.getUtxos(); -const changeAddress = await wallet.getChangeAddress(); -const rewardAddresses = await wallet.getRewardAddresses(); -const rewardAddress = rewardAddresses[0]!; +import { vote } from "@meshsdk/core"; -txBuilder - .proposal( - { - kind: "InfoAction", - action: {}, - }, - { - anchorUrl: "https://example.com/proposal.jsonld", - anchorDataHash: "a1b1c2d3e4f5...", - }, - rewardAddress - ) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos); - -const unsignedTx = await txBuilder.complete(); -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); - -console.log(`Info action submitted: ${txHash}`); +const built = await builder.build( + vote({ + voter: { drep: drepId }, + votes: [ + { action: { txHash: actionTxHash, index: 0 }, vote: "yes", anchor }, + ], + }), + { payer: wallet }, +); ``` -### Submit a Treasury Withdrawal +## Submit a Proposal -Propose a treasury withdrawal to one or more reward addresses: +`proposal.info` is a governance action with no effect on the chain, used as a poll. The deposit is `govActionDeposit`, or `deposit` on the part. It is paid from the payer's UTxOs and goes back to `rewardAccount` when the action ends. ```tsx -import { MeshTxBuilder, BlockfrostProvider } from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -const utxos = await wallet.getUtxos(); -const changeAddress = await wallet.getChangeAddress(); -const rewardAddresses = await wallet.getRewardAddresses(); -const rewardAddress = rewardAddresses[0]!; +import { proposal } from "@meshsdk/core"; -txBuilder - .proposal( - { - kind: "TreasuryWithdrawalsAction", - action: { - withdrawals: { - [rewardAddress]: "50000000000", // 50,000 ADA in lovelace - }, - }, - }, - { - anchorUrl: "https://example.com/treasury-proposal.jsonld", - anchorDataHash: "a1b1c2d3e4f5...", - }, - rewardAddress - ) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos); - -const unsignedTx = await txBuilder.complete(); -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); - -console.log(`Treasury withdrawal proposed: ${txHash}`); +const built = await builder.build( + proposal.info({ rewardAccount: rewardAddress, anchor }), + { payer: wallet }, +); ``` -### Submit a No Confidence Action +## Propose Other Actions -Propose a motion of no confidence in the current constitutional committee: +Each action takes `rewardAccount` and `anchor`, plus its own fields: -```tsx -import { MeshTxBuilder, BlockfrostProvider } from "@meshsdk/core"; +- `treasuryWithdrawals` - `withdrawals`, lovelace by receiving reward address +- `parameterChange` - `updates` +- `hardForkInitiation` - `protocolVersion` +- `updateCommittee` - `quorum`, and `add` and `remove` for members +- `newConstitution` - `constitution` +- `noConfidence` - nothing more -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -const utxos = await wallet.getUtxos(); -const changeAddress = await wallet.getChangeAddress(); -const rewardAddresses = await wallet.getRewardAddresses(); -const rewardAddress = rewardAddresses[0]!; - -txBuilder - .proposal( - { - kind: "NoConfidenceAction", - action: { - govActionId: { - transactionId: "previousNoConfidenceTxHash...", - govActionIndex: 0, - }, - }, - }, - { - anchorUrl: "https://example.com/no-confidence.jsonld", - anchorDataHash: "a1b1c2d3e4f5...", - }, - rewardAddress - ) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos); - -const unsignedTx = await txBuilder.complete(); -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); - -console.log(`No confidence action submitted: ${txHash}`); -``` - -## Complete Example - -This example demonstrates a complete DRep lifecycle: +`parameterChange` and `treasuryWithdrawals` take the constitution's `guardrail` script. Every action except `info` and `treasuryWithdrawals` takes `previous: { txHash, index }`, the action it follows. ```tsx -import { - MeshTxBuilder, - BlockfrostProvider, - hashDrepAnchor -} from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); - -function getTxBuilder() { - return new MeshTxBuilder({ - fetcher: provider, - verbose: true, - }); -} - -// Register as a DRep -async function registerDRep( - wallet: any, - name: string, - metadataUrl: string -) { - const txBuilder = getTxBuilder(); - - const dRep = await wallet.getDRep(); - const dRepId = dRep.dRepIDCip105; - - const metadata = { - "@context": { /* CIP-119 context */ }, - "body": { "givenName": name } - }; - const anchorHash = hashDrepAnchor(metadata); - - const utxos = await wallet.getUtxos(); - const changeAddress = await wallet.getChangeAddress(); - - txBuilder - .drepRegistrationCertificate(dRepId, { - anchorUrl: metadataUrl, - anchorDataHash: anchorHash, - }) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos); +import { proposal } from "@meshsdk/core"; - const unsignedTx = await txBuilder.complete(); - const signedTx = await wallet.signTx(unsignedTx); - return await wallet.submitTx(signedTx); -} - -// Vote on a governance action -async function castVote( - wallet: any, - govActionTxHash: string, - govActionIndex: number, - voteKind: "Yes" | "No" | "Abstain" -) { - const txBuilder = getTxBuilder(); - - const dRep = await wallet.getDRep(); - const dRepId = dRep.dRepIDCip105; - - const utxos = await wallet.getUtxos(); - const changeAddress = await wallet.getChangeAddress(); - - txBuilder - .vote( - { type: "DRep", drepId: dRepId }, - { txHash: govActionTxHash, txIndex: govActionIndex }, - { voteKind } - ) - .selectUtxosFrom(utxos) - .changeAddress(changeAddress); - - const unsignedTx = await txBuilder.complete(); - const signedTx = await wallet.signTx(unsignedTx); - return await wallet.submitTx(signedTx); -} - -// Delegate to a DRep -async function delegateToDRep(wallet: any, dRepId: string) { - const txBuilder = getTxBuilder(); - - const utxos = await wallet.getUtxos(); - const changeAddress = await wallet.getChangeAddress(); - const rewardAddresses = await wallet.getRewardAddresses(); - const rewardAddress = rewardAddresses[0]!; - - txBuilder - .voteDelegationCertificate({ dRepId }, rewardAddress) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos); - - const unsignedTx = await txBuilder.complete(); - const signedTx = await wallet.signTx(unsignedTx); - return await wallet.submitTx(signedTx); -} - -// Retire as DRep -async function retireDRep(wallet: any) { - const txBuilder = getTxBuilder(); - - const dRep = await wallet.getDRep(); - const dRepId = dRep.dRepIDCip105; - - const utxos = await wallet.getUtxos(); - const changeAddress = await wallet.getChangeAddress(); - - txBuilder - .drepDeregistrationCertificate(dRepId) - .selectUtxosFrom(utxos) - .changeAddress(changeAddress); - - const unsignedTx = await txBuilder.complete(); - const signedTx = await wallet.signTx(unsignedTx); - return await wallet.submitTx(signedTx); -} - -// Usage -async function main() { - // 1. Register as DRep - const regTx = await registerDRep( - wallet, - "Community DRep", - "https://example.com/metadata.jsonld" - ); - console.log(`Registered as DRep: ${regTx}`); - - // 2. Vote on proposals - const voteTx = await castVote( - wallet, - "proposal-tx-hash...", - 0, - "Yes" - ); - console.log(`Vote cast: ${voteTx}`); - - // 3. Others delegate to you - const delegateTx = await delegateToDRep( - otherWallet, - "drep1..." // Your DRep ID - ); - console.log(`Delegation received: ${delegateTx}`); - - // 4. Eventually retire - const retireTx = await retireDRep(wallet); - console.log(`Retired as DRep: ${retireTx}`); -} +const built = await builder.build( + proposal.treasuryWithdrawals({ + rewardAccount: rewardAddress, + anchor, + withdrawals: { [rewardAddress]: 50_000_000_000n }, + }), + { payer: wallet }, +); ``` -## Troubleshooting - -### "DRep not registered" error -- You must register as a DRep before voting -- Use `drepRegistrationCertificate()` first - -### "Invalid anchor hash" error -- The hash must match the content at the URL exactly -- Use `hashDrepAnchor()` to compute the correct hash -- Ensure the metadata file is publicly accessible - -### "Insufficient deposit" error -- DRep registration requires a deposit (check current protocol parameters) -- Ensure wallet has enough ADA for deposit + fees - -### "DRep inactive" error -- DReps must vote regularly to stay active -- Vote on governance actions or submit an update certificate - -### "Governance action not found" error -- Verify the transaction hash and index are correct -- The governance action may have already been resolved - -### "Invalid voter type" error -- Ensure the voter type matches your role (DRep, SPO, or CC) -- Use the correct identifier format for each type - -### "Insufficient deposit" for proposal -- Governance action proposals require a large deposit (check `govActionDeposit` in protocol parameters) -- The deposit is returned when the governance action is resolved (enacted, expired, or dropped) -- Ensure wallet has enough ADA for deposit + fees - -### "Missing proposal script information" error -- When using `proposalScript()` or `proposalTxInReference()`, ensure the script source is provided before calling `.complete()` -- For Plutus script proposals, a redeemer must also be provided via `proposalRedeemerValue()` - -## References - -- [CIP-1694: Cardano On-Chain Governance](https://github.com/cardano-foundation/CIPs/blob/master/CIP-1694/README.md) - The governance specification that defines DReps, voting, and governance actions -- [CIP-95: Web-Wallet Bridge for Conway Governance](https://cips.cardano.org/cip/CIP-0095) - The standard for wallet-dApp governance interaction -- [CIP-119: DRep Metadata Standard](https://github.com/cardano-foundation/CIPs/blob/master/CIP-0119/README.md) - Metadata standard for DRep registration -- [Cardano Developer Portal](https://developers.cardano.org) - Official Cardano development resources - ## Related -- Transaction Basics - Core transaction building -- Staking - Stake delegation -- CIP-1694 - Governance specification -- CIP-119 - DRep metadata standard +- [Staking Transactions](/apis/txbuilder/staking) - register a stake key, delegate and withdraw +- [Transaction Basics](/apis/txbuilder/basics) - the builder, the payer and signing +- [Migrating to TxBuilder](/apis/txbuilder/migration) - move from the `MeshTxBuilder` chain +- [Package README](https://github.com/MeshJS/mesh/tree/main/packages/mesh-transaction) - every part, option and error diff --git a/content/docs/apis/txbuilder/index.mdx b/content/docs/apis/txbuilder/index.mdx index ab6e01b..14f7005 100644 --- a/content/docs/apis/txbuilder/index.mdx +++ b/content/docs/apis/txbuilder/index.mdx @@ -1,6 +1,6 @@ --- title: "Cardano Transaction Builder" -description: "Build Cardano transactions with fine-grained control using low-level APIs." +description: "Build Cardano transactions from parts with TxBuilder: it selects inputs, adds change and sets the fee." icon: BanknotesIcon --- @@ -12,49 +12,45 @@ import { CardTitle, } from "@/components/ui/card"; -> **Note:** `MeshTxBuilder` is deprecated but still works. New code uses `TxBuilder`, which takes a list of parts instead of a chain of calls. See [Migrating to TxBuilder](/apis/txbuilder/migration). +> **Note:** Coming from `MeshTxBuilder`, the chain of calls? It is deprecated but still works. See [Migrating to TxBuilder](/apis/txbuilder/migration). ## Overview -`MeshTxBuilder` is a powerful, low-level API for constructing Cardano transactions. It provides complete control over every aspect of transaction building, from simple ADA transfers to complex smart contract interactions, staking operations, and governance actions. - -**When to use MeshTxBuilder:** -- Building custom transaction logic beyond standard transfers -- Creating multi-signature transactions -- Minting and burning native assets -- Interacting with Plutus smart contracts -- Managing stake delegation and rewards -- Participating in on-chain governance +`TxBuilder` builds a Cardano transaction from a list of parts, such as `output(...)` or `mint.native(...)`. You name a payer, and the builder selects inputs, adds change and sets the fee; for scripts it also adds collateral and execution units. Then you sign and submit. Examples use `wallet` (a [wallet](/apis/wallets): a `MeshWallet` or `BrowserWallet`) and `recipient` (an address) from your application. ## Quick Start ```tsx -import { MeshTxBuilder, BlockfrostProvider } from "@meshsdk/core"; +import { BlockfrostProvider, output, TxBuilder } from "@meshsdk/core"; -// Initialize provider and builder +// A provider reads the chain const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -// Get wallet data -const utxos = await wallet.getUtxos(); -const changeAddress = await wallet.getChangeAddress(); - -// Build a simple transfer -const unsignedTx = await txBuilder - .txOut("addr_test1qz...", [{ unit: "lovelace", quantity: "5000000" }]) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos) - .complete(); - -// Sign and submit -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); +const builder = new TxBuilder({ network: "preprod", provider }); + +// Build: the builder picks inputs, adds change and sets the fee +const built = await builder.build( + output({ address: recipient, value: { lovelace: 5_000_000n } }), // 5 ada + { payer: wallet }, +); + +await built.sign(); // the payer signs +await built.submit(); // sent through the provider +console.log(built.txHash); ``` -## Documentation +`TxBuilder` lives in `@meshsdk/transaction`, and `@meshsdk/core` re-exports it. Amounts are `bigint`. `built.tx` is the unsigned transaction as a hex string (CBOR). For other providers, see [Providers](/providers). + +## Which Part for What + +| Part | Use it to | +|------|-----------| +| `output`, `metadata`, `message`, `validity`, `guard.pubKey` | send assets, add metadata, set validity, require a signer | +| `mint.native`, `mint.plutus` | mint and burn assets | +| `spend.plutus`, `spend.native`, `referenceInput` | lock and spend at a script, read an output | +| `certificate.*`, `withdrawal.*` | stake, delegate and withdraw rewards | +| `vote`, `proposal.*` | take part in governance | + +## Pick a Task
{linksTxbuilder.map((card) => ( @@ -69,6 +65,8 @@ const txHash = await wallet.submitTx(signedTx); ## Related -- Transaction Parser - Parse and test transactions -- Providers - Blockchain data providers -- Wallets - Wallet integration options +- [Migrating to TxBuilder](/apis/txbuilder/migration) - move from the `MeshTxBuilder` chain +- [Transaction Parser](/apis/txparser) - parse and test transactions +- [Providers](/providers) - blockchain data providers +- [Wallets](/apis/wallets) - wallet integration options +- [Package README](https://github.com/MeshJS/mesh/tree/main/packages/mesh-transaction) - every part, option and error diff --git a/content/docs/apis/txbuilder/legacy/basics.mdx b/content/docs/apis/txbuilder/legacy/basics.mdx new file mode 100644 index 0000000..40ee2d0 --- /dev/null +++ b/content/docs/apis/txbuilder/legacy/basics.mdx @@ -0,0 +1,515 @@ +--- +title: "Transaction Builder Basics" +description: "Build and customize Cardano transactions with the MeshTxBuilder low-level API." +--- + +import Link from "fumadocs-core/link"; + +> **Deprecated:** `MeshTxBuilder` still works, but new code uses `TxBuilder`. See [Transaction Builder](/apis/txbuilder) and [Migrating to TxBuilder](/apis/txbuilder/migration). + +## Overview + +`MeshTxBuilder` is a powerful, low-level API for constructing Cardano transactions. It provides fine-grained control over every aspect of transaction building, from simple ADA transfers to complex multi-signature and smart contract interactions. + +**When to use MeshTxBuilder:** +- Building custom transaction logic beyond standard transfers +- Creating multi-signature transactions +- Interacting with Plutus smart contracts +- Optimizing transaction fees and execution units + +## Quick Start + +```tsx +import { MeshTxBuilder, BlockfrostProvider } from "@meshsdk/core"; + +// Initialize provider and builder +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +// Build a simple transfer +const unsignedTx = await txBuilder + .txOut("addr_test1qz...", [{ unit: "lovelace", quantity: "5000000" }]) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos) + .complete(); + +// Sign and submit +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); +``` + +## Configuration + +### Constructor Options + +```tsx +const txBuilder = new MeshTxBuilder({ + fetcher: provider, // Required for auto-fetching UTXO data + submitter: provider, // Optional: for direct submission via builder + evaluator: provider, // Optional: for script execution unit optimization + serializer: serializer, // Optional: custom serializer (default: CSLSerializer) + params: protocolParams, // Optional: custom protocol parameters + isHydra: false, // Optional: use Hydra protocol parameters + verbose: true, // Optional: enable detailed logging +}); +``` + +| Option | Type | Required | Description | +|--------|------|----------|-------------| +| `fetcher` | `IFetcher` | Recommended | Provider for fetching blockchain data | +| `submitter` | `ISubmitter` | No | Provider for submitting transactions | +| `evaluator` | `IEvaluator` | No | Provider for evaluating script execution | +| `serializer` | `IMeshTxSerializer` | No | Custom transaction serializer | +| `params` | `Partial` | No | Custom protocol parameters | +| `isHydra` | `boolean` | No | Enable Hydra-specific parameters | +| `verbose` | `boolean` | No | Enable detailed console logging | + +## Sending ADA + +### Basic Transfer + +Send ADA to a recipient address: + +```tsx +import { MeshTxBuilder, BlockfrostProvider } from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +// Get wallet data +const utxos = await wallet.getUtxos(); +const changeAddress = await wallet.getChangeAddress(); + +// Build transaction +const unsignedTx = await txBuilder + .txOut("addr_test1qz...", [{ unit: "lovelace", quantity: "5000000" }]) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos) + .complete(); + +// Sign and submit +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); +``` + +### Send Multiple Outputs + +Send to multiple recipients in a single transaction: + +```tsx +const unsignedTx = await txBuilder + .txOut("addr_test1qz...", [{ unit: "lovelace", quantity: "5000000" }]) + .txOut("addr_test1qr...", [{ unit: "lovelace", quantity: "3000000" }]) + .txOut("addr_test1qs...", [{ unit: "lovelace", quantity: "2000000" }]) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos) + .complete(); +``` + +### Send Native Assets + +Include native assets (tokens/NFTs) in the output: + +```tsx +const unsignedTx = await txBuilder + .txOut("addr_test1qz...", [ + { unit: "lovelace", quantity: "2000000" }, + { unit: "d9312da562da182b02322fd8acb536f37eb9d29fba7c49dc172555274d657368546f6b656e", quantity: "1" } + ]) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos) + .complete(); +``` + +## Input Selection + +### Automatic Selection + +Let Mesh automatically select UTXOs to cover the transaction: + +```tsx +const unsignedTx = await txBuilder + .txOut(recipientAddress, [{ unit: "lovelace", quantity: "5000000" }]) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos) + .complete(); +``` + +### Selection Strategies + +Configure how UTXOs are selected: + +```tsx +txBuilder.selectUtxosFrom( + utxos, // Available UTXOs + "largestFirst", // Selection strategy + "5000000", // Minimum threshold (lovelace) + true // Include transaction fees in calculation +); +``` + +| Strategy | Description | +|----------|-------------| +| `experimental` | Mesh's optimized selection algorithm | +| `keepRelevant` | Prefer UTXOs with relevant assets | +| `largestFirst` | Select largest UTXOs first | +| `largestFirstMultiAsset` | Optimized for transactions with multiple assets | + +### Manual Input Selection + +Explicitly specify which UTXOs to spend: + +```tsx +const unsignedTx = await txBuilder + .txIn( + "abc123...", // Transaction hash + 0, // Output index + [{ unit: "lovelace", quantity: "10000000" }], // Amount + "addr_test1qz..." // Address + ) + .txOut("addr_test1qr...", [{ unit: "lovelace", quantity: "5000000" }]) + .changeAddress(changeAddress) + .complete(); +``` + +## Multi-Signature Transactions + +Create transactions requiring multiple signatures: + +```tsx +import { MeshTxBuilder, ForgeScript, resolveScriptHash, stringToHex } from "@meshsdk/core"; +import { MeshCardanoHeadlessWallet, AddressType } from "@meshsdk/wallet"; + +// Create minting wallet +const mintingWallet = await MeshCardanoHeadlessWallet.fromMnemonic({ + networkId: 0, + walletAddressType: AddressType.Base, + fetcher: provider, + submitter: provider, + mnemonic: ["your", "mnemonic", "words", "..."], +}); + +// Create forging script +const forgingScript = ForgeScript.withOneSignature( + await mintingWallet.getChangeAddressBech32() +); + +const policyId = resolveScriptHash(forgingScript); +const assetName = "MeshToken"; + +// Get user wallet data +const address = (await wallet.getUsedAddresses())[0]; +const utxos = await wallet.getUtxos(); + +// Build multi-sig transaction +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +const unsignedTx = await txBuilder + .mint("1", policyId, stringToHex(assetName)) + .mintingScript(forgingScript) + .metadataValue(721, { + [policyId]: { + [assetName]: { name: "Mesh Token", image: "ipfs://..." } + } + }) + .changeAddress(address) + .selectUtxosFrom(utxos) + .complete(); + +// Sign with both wallets (partial signing) +const signedTx1 = await wallet.signTx(unsignedTx, true, false); +const signedTx2 = await mintingWallet.signTx(signedTx1, true, false); + +// Submit final transaction +const txHash = await wallet.submitTx(signedTx2); +``` + +## Native Script Multi-Sig + +Spend from a native script address requiring multiple signatures: + +```tsx +import { deserializeAddress, serializeNativeScript, NativeScript } from "@meshsdk/core"; + +// Get key hashes from addresses +const { pubKeyHash: keyHash1 } = deserializeAddress(walletAddress1); +const { pubKeyHash: keyHash2 } = deserializeAddress(walletAddress2); + +// Create native script requiring both signatures +const nativeScript: NativeScript = { + type: "all", + scripts: [ + { type: "sig", keyHash: keyHash1 }, + { type: "sig", keyHash: keyHash2 }, + ], +}; + +// Serialize script to get address +const { address: scriptAddress, scriptCbor } = serializeNativeScript(nativeScript); + +// Fetch UTXOs from script address +const scriptUtxos = await provider.fetchAddressUTxOs(scriptAddress); +const utxo = scriptUtxos[0]; + +// Build transaction spending from script +const unsignedTx = await txBuilder + .txIn( + utxo.input.txHash, + utxo.input.outputIndex, + utxo.output.amount, + utxo.output.address + ) + .txInScript(scriptCbor) + .txOut("addr_test1qz...", [{ unit: "lovelace", quantity: "2000000" }]) + .changeAddress(scriptAddress) + .selectUtxosFrom(scriptUtxos) + .complete(); + +// Both wallets must sign +const signedTx1 = await wallet1.signTx(unsignedTx, true, false); +const signedTx2 = await wallet2.signTx(signedTx1, true, false); +const txHash = await wallet1.submitTx(signedTx2); +``` + +## Transaction Metadata + +### Add Messages + +Attach messages to transactions using label 674 (CIP-20): + +```tsx +const unsignedTx = await txBuilder + .txOut(recipientAddress, [{ unit: "lovelace", quantity: "5000000" }]) + .metadataValue(674, { + msg: [ + "Invoice-No: 1234567890", + "Customer-No: 555-1234" + ] + }) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos) + .complete(); +``` + +Each message string must be at most 64 bytes when UTF-8 encoded. + +### Custom Metadata + +Add any JSON-compatible metadata: + +```tsx +const unsignedTx = await txBuilder + .metadataValue(customLabel, { + key: "value", + nested: { data: [1, 2, 3] } + }) + .txOut(address, amount) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos) + .complete(); +``` + +## Transaction Validity + +### Set Expiration (TTL) + +Make a transaction invalid after a specific slot: + +```tsx +import { resolveSlotNo } from "@meshsdk/core"; + +// Transaction expires in 5 minutes +const expirationTime = new Date(Date.now() + 5 * 60 * 1000); +const slot = resolveSlotNo("mainnet", expirationTime.getTime()); + +const unsignedTx = await txBuilder + .txOut(address, amount) + .invalidHereafter(Number(slot)) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos) + .complete(); +``` + +### Set Start Time + +Make a transaction invalid before a specific slot: + +```tsx +const startTime = new Date(Date.now() + 10 * 60 * 1000); // 10 minutes from now +const startSlot = resolveSlotNo("mainnet", startTime.getTime()); + +const unsignedTx = await txBuilder + .txOut(address, amount) + .invalidBefore(Number(startSlot)) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos) + .complete(); +``` + +## Required Signers + +Specify required signers for smart contract transactions: + +```tsx +import { deserializeAddress } from "@meshsdk/core"; + +const { pubKeyHash } = deserializeAddress(walletAddress); + +const unsignedTx = await txBuilder + // ... transaction details + .requiredSignerHash(pubKeyHash) + .complete(); +``` + +## Network Configuration + +### Set Network + +Configure the network for proper cost model calculation: + +```tsx +txBuilder.setNetwork("mainnet"); // or "testnet", "preview", "preprod" +``` + +### Custom Protocol Parameters + +Use specific protocol parameters: + +```tsx +const params = await provider.fetchProtocolParameters(); + +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + params: params, +}); +``` + +## Manual Fee Control + +Override automatic fee calculation: + +```tsx +const unsignedTx = await txBuilder + .txOut(address, amount) + .changeAddress(changeAddress) + .setFee("200000") // Set exact fee in lovelace + .complete(); +``` + +## Build with JSON + +Alternative method using a JSON object: + +```tsx +import { MeshTxBuilderBody } from "@meshsdk/core"; + +const meshTxBody: Partial = { + outputs: [ + { + address: recipientAddress, + amount: [{ unit: "lovelace", quantity: "5000000" }], + }, + ], + changeAddress: changeAddress, + extraInputs: utxos, + selectionConfig: { + threshold: "5000000", + strategy: "largestFirst", + includeTxFees: true, + }, +}; + +const unsignedTx = await txBuilder.complete(meshTxBody); +``` + +## Complete Example + +```tsx +import { + MeshTxBuilder, + BlockfrostProvider, + resolveSlotNo +} from "@meshsdk/core"; + +// Setup +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +// Get wallet data +const utxos = await wallet.getUtxos(); +const changeAddress = await wallet.getChangeAddress(); + +// Set expiration (5 minutes) +const expiration = new Date(Date.now() + 5 * 60 * 1000); +const expirationSlot = resolveSlotNo("preprod", expiration.getTime()); + +// Build transaction +const unsignedTx = await txBuilder + // Send 5 ADA to recipient + .txOut("addr_test1qz...", [{ unit: "lovelace", quantity: "5000000" }]) + // Send 3 ADA + token to another recipient + .txOut("addr_test1qr...", [ + { unit: "lovelace", quantity: "3000000" }, + { unit: "policyId...", quantity: "1" } + ]) + // Add transaction message + .metadataValue(674, { msg: ["Payment for services"] }) + // Set expiration + .invalidHereafter(Number(expirationSlot)) + // Configure change and UTXO selection + .changeAddress(changeAddress) + .selectUtxosFrom(utxos, "largestFirst", "5000000", true) + // Build the transaction + .complete(); + +// Sign and submit +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); + +console.log(`Transaction submitted: ${txHash}`); +``` + +## Troubleshooting + +### "Insufficient funds" error +- Ensure UTXOs have enough ADA to cover outputs + fees + min UTxO values +- Check that `selectUtxosFrom` is provided with current UTXOs +- For native asset outputs, ensure minimum ADA (typically ~1.5 ADA) is included + +### "Missing input" error +- The `fetcher` provider is required for automatic UTXO data fetching +- If using manual `txIn`, provide all four parameters (txHash, index, amount, address) + +### Transaction too large +- Split into multiple transactions +- Reduce the number of outputs +- Use UTXO consolidation first + +### Invalid slot number +- Ensure you're using the correct network in `resolveSlotNo` +- Mainnet and testnets have different slot calculations + +### Multi-sig transaction fails +- Ensure `partialSign: true` is set for all signers except the last +- Verify all required signers have signed +- Check that signing order doesn't matter (unless script requires specific order) + +## Related + +- Minting Tokens - Mint native assets +- Smart Contracts - Interact with Plutus scripts +- Staking - Delegation and rewards +- Governance - Voting and proposals +- Blockfrost Provider - Provider setup diff --git a/content/docs/apis/txbuilder/legacy/governance.mdx b/content/docs/apis/txbuilder/legacy/governance.mdx new file mode 100644 index 0000000..a0802f8 --- /dev/null +++ b/content/docs/apis/txbuilder/legacy/governance.mdx @@ -0,0 +1,996 @@ +--- +title: "Governance Transactions" +description: "Participate in Cardano's on-chain governance through DRep delegation, registration, voting, and submitting governance action proposals." +--- + +import Link from "fumadocs-core/link"; + +> **Deprecated:** `MeshTxBuilder` still works, but new code uses `TxBuilder`. See [Transaction Builder](/apis/txbuilder) and [Migrating to TxBuilder](/apis/txbuilder/migration). + +## Overview + +Cardano's on-chain governance system ([CIP-1694](https://github.com/cardano-foundation/CIPs/blob/master/CIP-1694/README.md)) enables the community to vote on proposals and protocol updates. Mesh SDK implements the [CIP-95](https://cips.cardano.org/cip/CIP-0095) Web-Wallet Bridge extension, allowing dApps to interact with governance features. You can delegate your voting power to Decentralized Representatives (DReps), register as a DRep yourself, vote on governance actions, and submit new governance action proposals. + +**When to use this:** +- Delegating your voting power to a DRep +- Registering as a DRep to represent other voters +- Voting on governance actions and protocol changes +- Submitting governance action proposals (info actions, parameter changes, treasury withdrawals, etc.) +- Building governance dashboards and tools +- Creating DRep management applications + +## Quick Start + +```tsx +import { MeshTxBuilder, BlockfrostProvider } from "@meshsdk/core"; + +// Initialize +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +// Get wallet data +const utxos = await wallet.getUtxos(); +const changeAddress = await wallet.getChangeAddress(); +const rewardAddresses = await wallet.getRewardAddresses(); +const rewardAddress = rewardAddresses[0]!; + +// Delegate to a DRep +txBuilder + .voteDelegationCertificate( + { dRepId: "drep1yv4uesaj92wk8ljlsh4p7jzndnzrflchaz5fzug3zxg4naqkpeas3" }, + rewardAddress + ) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos); + +const unsignedTx = await txBuilder.complete(); +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); +``` + +## API Reference + +### voteDelegationCertificate() + +Delegate voting power to a DRep. + +```tsx +.voteDelegationCertificate(drep: DRepId, rewardAddress: string) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `drep` | `DRepId` | DRep identifier object | +| `rewardAddress` | `string` | Your stake/reward address | + +The `DRepId` object can specify: +- `{ dRepId: "drep1..." }` - Delegate to a specific DRep +- `{ alwaysAbstain: true }` - Always abstain from voting +- `{ alwaysNoConfidence: true }` - Always vote no confidence + +### drepRegistrationCertificate() + +Register as a DRep. + +```tsx +.drepRegistrationCertificate(dRepId: string, anchor?: Anchor) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `dRepId` | `string` | Your DRep ID (from wallet) | +| `anchor` | `Anchor` | Optional metadata anchor | + +The `Anchor` object: +```tsx +{ + anchorUrl: string; // URL to metadata JSON + anchorDataHash: string; // Hash of metadata content +} +``` + +### drepUpdateCertificate() + +Update DRep metadata. + +```tsx +.drepUpdateCertificate(dRepId: string, anchor?: Anchor) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `dRepId` | `string` | Your DRep ID | +| `anchor` | `Anchor` | New metadata anchor | + +### drepDeregistrationCertificate() + +Retire as a DRep and reclaim deposit. + +```tsx +.drepDeregistrationCertificate(dRepId: string) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `dRepId` | `string` | Your DRep ID to retire | + +### vote() + +Cast a vote on a governance action. + +```tsx +.vote(voter: Voter, govActionId: GovActionId, votingProcedure: VotingProcedure) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `voter` | `Voter` | Voter identity | +| `govActionId` | `GovActionId` | Governance action reference | +| `votingProcedure` | `VotingProcedure` | Vote details | + +The `Voter` object: +```tsx +// DRep voter +{ type: "DRep", drepId: "drep1..." } + +// Stake pool operator +{ type: "StakePool", poolId: "pool1..." } + +// Constitutional committee member +{ type: "ConstitutionalCommittee", hotCred: "..." } +``` + +The `VotingProcedure` object: +```tsx +{ + voteKind: "Yes" | "No" | "Abstain"; + anchor?: { + anchorUrl: string; + anchorDataHash: string; + }; +} +``` + +### votePlutusScriptV3() + +Indicate voting with a Plutus script. + +```tsx +.votePlutusScriptV3() +``` + +### voteScript() + +Provide the voting script. + +```tsx +.voteScript(scriptCbor: string) +``` + +### voteRedeemerValue() + +Provide the redeemer for script-based voting. + +```tsx +.voteRedeemerValue(redeemer: Data | object | string, type?: "Mesh" | "CBOR" | "JSON", exUnits?: Budget) +``` + +### proposal() + +Submit a governance action proposal. Requires a deposit (returned when the action is resolved). + +```tsx +.proposal(governanceAction: GovernanceAction, anchor: Anchor, rewardAccount: string, deposit?: string) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `governanceAction` | `GovernanceAction` | The governance action to propose | +| `anchor` | `Anchor` | Proposal metadata anchor (URL + hash) | +| `rewardAccount` | `string` | Reward address for deposit return | +| `deposit` | `string` | Deposit amount in lovelace (defaults to `"100000000000"`, i.e. 100,000 ADA) | + +The `GovernanceAction` is a discriminated union with a `kind` and `action` field: + +```tsx +// Info action (no on-chain effect, used for polls/sentiment) +{ kind: "InfoAction", action: {} } + +// Protocol parameter change +{ + kind: "ParameterChangeAction", + action: { + govActionId?: { transactionId: string; govActionIndex: number }, + protocolParamUpdates: ProtocolParamUpdate, + policyHash?: { bytes: string }, + } +} + +// Treasury withdrawal +{ + kind: "TreasuryWithdrawalsAction", + action: { + withdrawals: Record, // reward address -> lovelace amount + policyHash?: { bytes: string }, + } +} + +// No confidence in current committee +{ + kind: "NoConfidenceAction", + action: { + govActionId?: { transactionId: string; govActionIndex: number }, + } +} + +// Update constitutional committee +{ + kind: "UpdateCommitteeAction", + action: { + govActionId?: { transactionId: string; govActionIndex: number }, + committee: { + members: Array<{ stakeCredential: Credential; termLimit: number }>, + quorumThreshold: { numerator: string; denominator: string }, + }, + membersToRemove: Credential[], + } +} + +// New constitution +{ + kind: "NewConstitutionAction", + action: { + govActionId?: { transactionId: string; govActionIndex: number }, + constitution: { + anchor: Anchor, + scriptHash?: { bytes: string }, + }, + } +} + +// Hard fork initiation +{ + kind: "HardForkInitiationAction", + action: { + govActionId?: { transactionId: string; govActionIndex: number }, + protocolVersion: { major: number; minor: number }, + } +} +``` + +The `Credential` type used in committee actions: +```tsx +{ type: "KeyHash", keyHash: string } +// or +{ type: "ScriptHash", scriptHash: string } +``` + +The `govActionId` field is optional and refers to the most recently enacted governance action of the same type that this proposal builds upon. It is required for action types that must chain from a previous action (parameter changes, hard forks, committee updates, no confidence, new constitution). + +### proposalScript() + +Attach a Plutus script witness to the proposal. + +```tsx +.proposalScript(scriptCbor: string, version: "V1" | "V2" | "V3") +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `scriptCbor` | `string` | CBOR hex of the Plutus script | +| `version` | `LanguageVersion` | Plutus language version | + +### proposalTxInReference() + +Use a reference script for the proposal instead of providing it inline. + +```tsx +.proposalTxInReference(txHash: string, txIndex: number, scriptSize: string, scriptHash: string, version: "V1" | "V2" | "V3") +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `txHash` | `string` | Transaction hash of the reference UTxO | +| `txIndex` | `number` | Transaction index of the reference UTxO | +| `scriptSize` | `string` | Size of the Plutus script in bytes | +| `scriptHash` | `string` | Script hash of the referenced script | +| `version` | `LanguageVersion` | Plutus language version | + +### proposalRedeemerValue() + +Provide the redeemer for a Plutus script proposal. + +```tsx +.proposalRedeemerValue(redeemer: Data | object | string, type?: "Mesh" | "CBOR" | "JSON", exUnits?: Budget) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `redeemer` | `Data \| object \| string` | Redeemer data | +| `type` | `string` | Data format type (default `"Mesh"`) | +| `exUnits` | `Budget` | Execution units budget (default `{ mem: 7_000_000, steps: 3_000_000_000 }`) | + +## Common Patterns + +### Delegate to a DRep + +Delegate your voting power to a registered DRep: + +```tsx +import { MeshTxBuilder, BlockfrostProvider } from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +const utxos = await wallet.getUtxos(); +const changeAddress = await wallet.getChangeAddress(); +const rewardAddresses = await wallet.getRewardAddresses(); +const rewardAddress = rewardAddresses[0]!; + +const dRepId = "drep1yv4uesaj92wk8ljlsh4p7jzndnzrflchaz5fzug3zxg4naqkpeas3"; + +txBuilder + .voteDelegationCertificate({ dRepId }, rewardAddress) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos); + +const unsignedTx = await txBuilder.complete(); +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); + +console.log(`Delegated to DRep: ${txHash}`); +``` + +### Delegate to Always Abstain + +Configure your stake to always abstain from voting: + +```tsx +import { MeshTxBuilder, BlockfrostProvider } from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +const utxos = await wallet.getUtxos(); +const changeAddress = await wallet.getChangeAddress(); +const rewardAddresses = await wallet.getRewardAddresses(); +const rewardAddress = rewardAddresses[0]!; + +txBuilder + .voteDelegationCertificate({ alwaysAbstain: true }, rewardAddress) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos); + +const unsignedTx = await txBuilder.complete(); +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); +``` + +### Register as a DRep + +Register yourself as a DRep with metadata: + +```tsx +import { MeshTxBuilder, BlockfrostProvider, hashDrepAnchor } from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +// Get DRep ID from wallet +const dRep = await wallet.getDRep(); +const dRepId = dRep.dRepIDCip105; + +// Prepare metadata anchor +const anchorUrl = "https://example.com/drep-metadata.jsonld"; +const anchorMetadata = { + "@context": { + "@language": "en", + "CIP100": "https://github.com/cardano-foundation/CIPs/blob/master/CIP-0100/README.md", + "CIP119": "https://github.com/cardano-foundation/CIPs/blob/master/CIP-0119/README.md", + "hashAlgorithm": "CIP100:hashAlgorithm", + "body": { "@id": "CIP119:body" }, + "givenName": "CIP119:givenName" + }, + "hashAlgorithm": "blake2b-256", + "body": { + "givenName": "My DRep Name" + } +}; +const anchorHash = hashDrepAnchor(anchorMetadata); + +// Get wallet data +const utxos = await wallet.getUtxos(); +const changeAddress = await wallet.getChangeAddress(); + +txBuilder + .drepRegistrationCertificate(dRepId, { + anchorUrl, + anchorDataHash: anchorHash, + }) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos); + +const unsignedTx = await txBuilder.complete(); +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); + +console.log(`DRep registered: ${txHash}`); +``` + +### Update DRep Metadata + +Update your DRep profile information: + +```tsx +import { MeshTxBuilder, BlockfrostProvider, hashDrepAnchor } from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +const dRep = await wallet.getDRep(); +const dRepId = dRep.dRepIDCip105; + +// New metadata +const anchorUrl = "https://example.com/drep-metadata-v2.jsonld"; +const anchorMetadata = { /* updated metadata */ }; +const anchorHash = hashDrepAnchor(anchorMetadata); + +const utxos = await wallet.getUtxos(); +const changeAddress = await wallet.getChangeAddress(); + +txBuilder + .drepUpdateCertificate(dRepId, { + anchorUrl, + anchorDataHash: anchorHash, + }) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos); + +const unsignedTx = await txBuilder.complete(); +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); + +console.log(`DRep updated: ${txHash}`); +``` + +### Retire as DRep + +Retire from being a DRep and reclaim your deposit: + +```tsx +import { MeshTxBuilder, BlockfrostProvider } from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +const dRep = await wallet.getDRep(); +const dRepId = dRep.dRepIDCip105; + +const utxos = await wallet.getUtxos(); +const changeAddress = await wallet.getChangeAddress(); + +txBuilder + .drepDeregistrationCertificate(dRepId) + .selectUtxosFrom(utxos) + .changeAddress(changeAddress); + +const unsignedTx = await txBuilder.complete(); +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); + +console.log(`DRep retired: ${txHash}`); +``` + +### Vote on Governance Action + +Cast a vote as a DRep: + +```tsx +import { MeshTxBuilder, BlockfrostProvider } from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +const dRep = await wallet.getDRep(); +const dRepId = dRep.dRepIDCip105; + +const utxos = await wallet.getUtxos(); +const changeAddress = await wallet.getChangeAddress(); + +// Governance action to vote on +const govActionTxHash = "aff2909f8175ee02a8c1bf96ff516685d25bf0c6b95aac91f4dfd53a5c0867cc"; +const govActionIndex = 0; + +txBuilder + .vote( + { + type: "DRep", + drepId: dRepId, + }, + { + txHash: govActionTxHash, + txIndex: govActionIndex, + }, + { + voteKind: "Yes", + } + ) + .selectUtxosFrom(utxos) + .changeAddress(changeAddress); + +const unsignedTx = await txBuilder.complete(); +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); + +console.log(`Vote cast: ${txHash}`); +``` + +### Vote with Rationale + +Include reasoning for your vote: + +```tsx +import { MeshTxBuilder, BlockfrostProvider, hashDrepAnchor } from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +const dRep = await wallet.getDRep(); +const dRepId = dRep.dRepIDCip105; + +const utxos = await wallet.getUtxos(); +const changeAddress = await wallet.getChangeAddress(); + +// Prepare vote rationale +const rationaleUrl = "https://example.com/vote-rationale.jsonld"; +const rationaleContent = { + rationale: "I support this proposal because...", + references: ["https://example.com/supporting-doc"], +}; +const rationaleHash = hashDrepAnchor(rationaleContent); + +txBuilder + .vote( + { + type: "DRep", + drepId: dRepId, + }, + { + txHash: "abc123...", + txIndex: 0, + }, + { + voteKind: "Yes", + anchor: { + anchorUrl: rationaleUrl, + anchorDataHash: rationaleHash, + }, + } + ) + .selectUtxosFrom(utxos) + .changeAddress(changeAddress); + +const unsignedTx = await txBuilder.complete(); +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); +``` + +### Vote with Plutus Script + +Vote using a Plutus script DRep: + +```tsx +import { + MeshTxBuilder, + BlockfrostProvider, + resolveScriptHash, + resolveScriptHashDRepId, + applyCborEncoding +} from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +const utxos = await wallet.getUtxos(); +const collateral = await wallet.getCollateral(); +const changeAddress = await wallet.getChangeAddress(); + +// Your voting script +const votingScriptCbor = applyCborEncoding("your-voting-script-cbor"); +const scriptHash = resolveScriptHash(votingScriptCbor, "V3"); +const scriptDRepId = resolveScriptHashDRepId(scriptHash); + +txBuilder + .txIn( + utxos[0]!.input.txHash, + utxos[0]!.input.outputIndex, + utxos[0]!.output.amount, + utxos[0]!.output.address + ) + .txInCollateral( + collateral[0]!.input.txHash, + collateral[0]!.input.outputIndex, + collateral[0]!.output.amount, + collateral[0]!.output.address + ) + .votePlutusScriptV3() + .vote( + { + type: "DRep", + drepId: scriptDRepId, + }, + { + txHash: "abc123...", + txIndex: 0, + }, + { + voteKind: "Yes", + } + ) + .voteScript(votingScriptCbor) + .voteRedeemerValue("") + .changeAddress(changeAddress); + +const unsignedTx = await txBuilder.complete(); +const signedTx = await wallet.signTx(unsignedTx, true); +const txHash = await wallet.submitTx(signedTx); +``` + +### Submit an Info Action + +Submit an info action (used for polls and sentiment checks — has no on-chain effect): + +```tsx +import { MeshTxBuilder, BlockfrostProvider } from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +const utxos = await wallet.getUtxos(); +const changeAddress = await wallet.getChangeAddress(); +const rewardAddresses = await wallet.getRewardAddresses(); +const rewardAddress = rewardAddresses[0]!; + +txBuilder + .proposal( + { + kind: "InfoAction", + action: {}, + }, + { + anchorUrl: "https://example.com/proposal.jsonld", + anchorDataHash: "a1b1c2d3e4f5...", + }, + rewardAddress + ) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos); + +const unsignedTx = await txBuilder.complete(); +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); + +console.log(`Info action submitted: ${txHash}`); +``` + +### Submit a Treasury Withdrawal + +Propose a treasury withdrawal to one or more reward addresses: + +```tsx +import { MeshTxBuilder, BlockfrostProvider } from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +const utxos = await wallet.getUtxos(); +const changeAddress = await wallet.getChangeAddress(); +const rewardAddresses = await wallet.getRewardAddresses(); +const rewardAddress = rewardAddresses[0]!; + +txBuilder + .proposal( + { + kind: "TreasuryWithdrawalsAction", + action: { + withdrawals: { + [rewardAddress]: "50000000000", // 50,000 ADA in lovelace + }, + }, + }, + { + anchorUrl: "https://example.com/treasury-proposal.jsonld", + anchorDataHash: "a1b1c2d3e4f5...", + }, + rewardAddress + ) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos); + +const unsignedTx = await txBuilder.complete(); +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); + +console.log(`Treasury withdrawal proposed: ${txHash}`); +``` + +### Submit a No Confidence Action + +Propose a motion of no confidence in the current constitutional committee: + +```tsx +import { MeshTxBuilder, BlockfrostProvider } from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +const utxos = await wallet.getUtxos(); +const changeAddress = await wallet.getChangeAddress(); +const rewardAddresses = await wallet.getRewardAddresses(); +const rewardAddress = rewardAddresses[0]!; + +txBuilder + .proposal( + { + kind: "NoConfidenceAction", + action: { + govActionId: { + transactionId: "previousNoConfidenceTxHash...", + govActionIndex: 0, + }, + }, + }, + { + anchorUrl: "https://example.com/no-confidence.jsonld", + anchorDataHash: "a1b1c2d3e4f5...", + }, + rewardAddress + ) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos); + +const unsignedTx = await txBuilder.complete(); +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); + +console.log(`No confidence action submitted: ${txHash}`); +``` + +## Complete Example + +This example demonstrates a complete DRep lifecycle: + +```tsx +import { + MeshTxBuilder, + BlockfrostProvider, + hashDrepAnchor +} from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); + +function getTxBuilder() { + return new MeshTxBuilder({ + fetcher: provider, + verbose: true, + }); +} + +// Register as a DRep +async function registerDRep( + wallet: any, + name: string, + metadataUrl: string +) { + const txBuilder = getTxBuilder(); + + const dRep = await wallet.getDRep(); + const dRepId = dRep.dRepIDCip105; + + const metadata = { + "@context": { /* CIP-119 context */ }, + "body": { "givenName": name } + }; + const anchorHash = hashDrepAnchor(metadata); + + const utxos = await wallet.getUtxos(); + const changeAddress = await wallet.getChangeAddress(); + + txBuilder + .drepRegistrationCertificate(dRepId, { + anchorUrl: metadataUrl, + anchorDataHash: anchorHash, + }) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos); + + const unsignedTx = await txBuilder.complete(); + const signedTx = await wallet.signTx(unsignedTx); + return await wallet.submitTx(signedTx); +} + +// Vote on a governance action +async function castVote( + wallet: any, + govActionTxHash: string, + govActionIndex: number, + voteKind: "Yes" | "No" | "Abstain" +) { + const txBuilder = getTxBuilder(); + + const dRep = await wallet.getDRep(); + const dRepId = dRep.dRepIDCip105; + + const utxos = await wallet.getUtxos(); + const changeAddress = await wallet.getChangeAddress(); + + txBuilder + .vote( + { type: "DRep", drepId: dRepId }, + { txHash: govActionTxHash, txIndex: govActionIndex }, + { voteKind } + ) + .selectUtxosFrom(utxos) + .changeAddress(changeAddress); + + const unsignedTx = await txBuilder.complete(); + const signedTx = await wallet.signTx(unsignedTx); + return await wallet.submitTx(signedTx); +} + +// Delegate to a DRep +async function delegateToDRep(wallet: any, dRepId: string) { + const txBuilder = getTxBuilder(); + + const utxos = await wallet.getUtxos(); + const changeAddress = await wallet.getChangeAddress(); + const rewardAddresses = await wallet.getRewardAddresses(); + const rewardAddress = rewardAddresses[0]!; + + txBuilder + .voteDelegationCertificate({ dRepId }, rewardAddress) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos); + + const unsignedTx = await txBuilder.complete(); + const signedTx = await wallet.signTx(unsignedTx); + return await wallet.submitTx(signedTx); +} + +// Retire as DRep +async function retireDRep(wallet: any) { + const txBuilder = getTxBuilder(); + + const dRep = await wallet.getDRep(); + const dRepId = dRep.dRepIDCip105; + + const utxos = await wallet.getUtxos(); + const changeAddress = await wallet.getChangeAddress(); + + txBuilder + .drepDeregistrationCertificate(dRepId) + .selectUtxosFrom(utxos) + .changeAddress(changeAddress); + + const unsignedTx = await txBuilder.complete(); + const signedTx = await wallet.signTx(unsignedTx); + return await wallet.submitTx(signedTx); +} + +// Usage +async function main() { + // 1. Register as DRep + const regTx = await registerDRep( + wallet, + "Community DRep", + "https://example.com/metadata.jsonld" + ); + console.log(`Registered as DRep: ${regTx}`); + + // 2. Vote on proposals + const voteTx = await castVote( + wallet, + "proposal-tx-hash...", + 0, + "Yes" + ); + console.log(`Vote cast: ${voteTx}`); + + // 3. Others delegate to you + const delegateTx = await delegateToDRep( + otherWallet, + "drep1..." // Your DRep ID + ); + console.log(`Delegation received: ${delegateTx}`); + + // 4. Eventually retire + const retireTx = await retireDRep(wallet); + console.log(`Retired as DRep: ${retireTx}`); +} +``` + +## Troubleshooting + +### "DRep not registered" error +- You must register as a DRep before voting +- Use `drepRegistrationCertificate()` first + +### "Invalid anchor hash" error +- The hash must match the content at the URL exactly +- Use `hashDrepAnchor()` to compute the correct hash +- Ensure the metadata file is publicly accessible + +### "Insufficient deposit" error +- DRep registration requires a deposit (check current protocol parameters) +- Ensure wallet has enough ADA for deposit + fees + +### "DRep inactive" error +- DReps must vote regularly to stay active +- Vote on governance actions or submit an update certificate + +### "Governance action not found" error +- Verify the transaction hash and index are correct +- The governance action may have already been resolved + +### "Invalid voter type" error +- Ensure the voter type matches your role (DRep, SPO, or CC) +- Use the correct identifier format for each type + +### "Insufficient deposit" for proposal +- Governance action proposals require a large deposit (check `govActionDeposit` in protocol parameters) +- The deposit is returned when the governance action is resolved (enacted, expired, or dropped) +- Ensure wallet has enough ADA for deposit + fees + +### "Missing proposal script information" error +- When using `proposalScript()` or `proposalTxInReference()`, ensure the script source is provided before calling `.complete()` +- For Plutus script proposals, a redeemer must also be provided via `proposalRedeemerValue()` + +## References + +- [CIP-1694: Cardano On-Chain Governance](https://github.com/cardano-foundation/CIPs/blob/master/CIP-1694/README.md) - The governance specification that defines DReps, voting, and governance actions +- [CIP-95: Web-Wallet Bridge for Conway Governance](https://cips.cardano.org/cip/CIP-0095) - The standard for wallet-dApp governance interaction +- [CIP-119: DRep Metadata Standard](https://github.com/cardano-foundation/CIPs/blob/master/CIP-0119/README.md) - Metadata standard for DRep registration +- [Cardano Developer Portal](https://developers.cardano.org) - Official Cardano development resources + +## Related + +- Transaction Basics - Core transaction building +- Staking - Stake delegation +- CIP-1694 - Governance specification +- CIP-119 - DRep metadata standard diff --git a/content/docs/apis/txbuilder/legacy/index.mdx b/content/docs/apis/txbuilder/legacy/index.mdx new file mode 100644 index 0000000..da0066a --- /dev/null +++ b/content/docs/apis/txbuilder/legacy/index.mdx @@ -0,0 +1,62 @@ +--- +title: "MeshTxBuilder (deprecated)" +description: "Build Cardano transactions with fine-grained control using low-level APIs." +--- + +import Link from "next/link"; + +> **Deprecated:** `MeshTxBuilder` still works, but new code uses `TxBuilder`. See [Transaction Builder](/apis/txbuilder) and [Migrating to TxBuilder](/apis/txbuilder/migration). + +## Overview + +`MeshTxBuilder` is a powerful, low-level API for constructing Cardano transactions. It provides complete control over every aspect of transaction building, from simple ADA transfers to complex smart contract interactions, staking operations, and governance actions. + +**When to use MeshTxBuilder:** +- Building custom transaction logic beyond standard transfers +- Creating multi-signature transactions +- Minting and burning native assets +- Interacting with Plutus smart contracts +- Managing stake delegation and rewards +- Participating in on-chain governance + +## Quick Start + +```tsx +import { MeshTxBuilder, BlockfrostProvider } from "@meshsdk/core"; + +// Initialize provider and builder +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +// Get wallet data +const utxos = await wallet.getUtxos(); +const changeAddress = await wallet.getChangeAddress(); + +// Build a simple transfer +const unsignedTx = await txBuilder + .txOut("addr_test1qz...", [{ unit: "lovelace", quantity: "5000000" }]) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos) + .complete(); + +// Sign and submit +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); +``` + +## Documentation + +- Transaction Basics +- Mint and Burn Assets +- Smart Contracts +- Staking Transactions +- Governance Transactions + +## Related + +- Transaction Parser - Parse and test transactions +- Providers - Blockchain data providers +- Wallets - Wallet integration options diff --git a/content/docs/apis/txbuilder/legacy/meta.json b/content/docs/apis/txbuilder/legacy/meta.json new file mode 100644 index 0000000..f54363c --- /dev/null +++ b/content/docs/apis/txbuilder/legacy/meta.json @@ -0,0 +1,5 @@ +{ + "title": "MeshTxBuilder (deprecated)", + "defaultOpen": false, + "pages": ["basics", "minting", "smart-contracts", "staking", "governance"] +} diff --git a/content/docs/apis/txbuilder/legacy/minting.mdx b/content/docs/apis/txbuilder/legacy/minting.mdx new file mode 100644 index 0000000..bc1fe65 --- /dev/null +++ b/content/docs/apis/txbuilder/legacy/minting.mdx @@ -0,0 +1,678 @@ +--- +title: "Minting and Burning Assets" +description: "Create and destroy native assets using Native Scripts and Plutus Scripts." +--- + +import Link from "fumadocs-core/link"; + +> **Deprecated:** `MeshTxBuilder` still works, but new code uses `TxBuilder`. See [Transaction Builder](/apis/txbuilder) and [Migrating to TxBuilder](/apis/txbuilder/migration). + +## Overview + +Minting creates new native assets on Cardano, while burning destroys existing ones. You can mint using Native Scripts (simple signature-based) or Plutus Scripts (programmable smart contracts). + +**When to use this:** +- Creating NFT collections +- Issuing fungible tokens +- Implementing tokenized loyalty programs +- Building CIP-68 compliant tokens with on-chain metadata +- Setting up royalty tokens for secondary market sales + +## Quick Start + +```tsx +import { + MeshTxBuilder, + BlockfrostProvider, + ForgeScript, + resolveScriptHash, + stringToHex +} from "@meshsdk/core"; + +// Initialize +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +// Get wallet data +const utxos = await wallet.getUtxos(); +const changeAddress = await wallet.getChangeAddress(); + +// Create minting script +const forgingScript = ForgeScript.withOneSignature(changeAddress); +const policyId = resolveScriptHash(forgingScript); +const tokenNameHex = stringToHex("MeshToken"); + +// Build mint transaction +const unsignedTx = await txBuilder + .mint("1", policyId, tokenNameHex) + .mintingScript(forgingScript) + .metadataValue(721, { + [policyId]: { + MeshToken: { + name: "Mesh Token", + image: "ipfs://QmRzicpReutwCkM6aotuKjErFCUD213DpwPq6ByuzMJaua", + } + } + }) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos) + .complete(); + +// Sign and submit +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); +``` + +## API Reference + +### mint() + +Specify the asset to mint or burn. + +```tsx +.mint(quantity: string, policyId: string, tokenNameHex: string) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `quantity` | `string` | Amount to mint (positive) or burn (negative) | +| `policyId` | `string` | Policy ID of the asset | +| `tokenNameHex` | `string` | Hex-encoded token name | + +### mintingScript() + +Provide the minting script. + +```tsx +.mintingScript(script: string | NativeScript) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `script` | `string \| NativeScript` | CBOR-encoded script or NativeScript object | + +### mintPlutusScriptV1() / V2() / V3() + +Indicate that a Plutus script will be used for minting. + +```tsx +.mintPlutusScriptV2() +``` + +### mintRedeemerValue() + +Provide the redeemer for Plutus script minting. + +```tsx +.mintRedeemerValue(redeemer: Data | object | string, type?: "Mesh" | "CBOR" | "JSON", exUnits?: Budget) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `redeemer` | `Data \| object \| string` | Redeemer data | +| `type` | `"Mesh" \| "CBOR" \| "JSON"` | Data format type (default: "Mesh") | +| `exUnits` | `Budget` | Optional execution units | + +### mintTxInReference() + +Reference an on-chain script instead of providing it inline. + +```tsx +.mintTxInReference(txHash: string, txIndex: number) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `txHash` | `string` | Transaction hash containing the reference script | +| `txIndex` | `number` | Output index of the reference script | + +### metadataValue() + +Attach metadata to the transaction. + +```tsx +.metadataValue(label: number, metadata: object) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `label` | `number` | Metadata label (721 for NFTs, 777 for royalties) | +| `metadata` | `object` | Metadata object | + +## Common Patterns + +### Mint with One Signature + +The simplest minting approach using a single wallet address: + +```tsx +import { + MeshTxBuilder, + BlockfrostProvider, + ForgeScript, + resolveScriptHash, + stringToHex +} from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +const utxos = await wallet.getUtxos(); +const changeAddress = await wallet.getChangeAddress(); + +// Create forging script from wallet address +const forgingScript = ForgeScript.withOneSignature(changeAddress); +const policyId = resolveScriptHash(forgingScript); +const tokenName = "MeshToken"; +const tokenNameHex = stringToHex(tokenName); + +// Define NFT metadata +const metadata = { + [policyId]: { + [tokenName]: { + name: "Mesh Token", + image: "ipfs://QmRzicpReutwCkM6aotuKjErFCUD213DpwPq6ByuzMJaua", + mediaType: "image/jpg", + description: "This NFT was minted by Mesh.", + } + } +}; + +const unsignedTx = await txBuilder + .mint("1", policyId, tokenNameHex) + .mintingScript(forgingScript) + .metadataValue(721, metadata) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos) + .complete(); + +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); +``` + +### Mint Multiple Assets + +Mint multiple tokens in a single transaction: + +```tsx +import { + MeshTxBuilder, + BlockfrostProvider, + ForgeScript, + resolveScriptHash, + stringToHex +} from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +const utxos = await wallet.getUtxos(); +const changeAddress = await wallet.getChangeAddress(); +const forgingScript = ForgeScript.withOneSignature(changeAddress); +const policyId = resolveScriptHash(forgingScript); + +// Build metadata for multiple tokens +const metadata: Record> = { [policyId]: {} }; + +for (let i = 1; i <= 3; i++) { + const tokenName = `MeshToken${i}`; + const tokenNameHex = stringToHex(tokenName); + + metadata[policyId][tokenName] = { + name: tokenName, + image: "ipfs://QmRzicpReutwCkM6aotuKjErFCUD213DpwPq6ByuzMJaua", + description: `Token #${i} from the Mesh collection`, + }; + + // Add mint instruction for each token + txBuilder.mint("1", policyId, tokenNameHex); + txBuilder.mintingScript(forgingScript); +} + +txBuilder + .metadataValue(721, metadata) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos); + +const unsignedTx = await txBuilder.complete(); +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); +``` + +### Burn Assets + +Burn assets by minting with a negative quantity: + +```tsx +import { + MeshTxBuilder, + BlockfrostProvider, + ForgeScript, + resolveScriptHash, + stringToHex +} from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +const utxos = await wallet.getUtxos(); +const changeAddress = await wallet.getChangeAddress(); + +// Use the same forging script that minted the asset +const forgingScript = ForgeScript.withOneSignature(changeAddress); +const policyId = resolveScriptHash(forgingScript); +const tokenNameHex = stringToHex("MeshToken"); + +// Burn by using negative quantity +const unsignedTx = await txBuilder + .mint("-1", policyId, tokenNameHex) + .mintingScript(forgingScript) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos) + .complete(); + +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); +``` + +### Mint with Native Script (Time-Locked) + +Create a time-locked minting policy: + +```tsx +import { + MeshTxBuilder, + BlockfrostProvider, + ForgeScript, + resolveScriptHash, + stringToHex, + deserializeAddress, + NativeScript +} from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +const utxos = await wallet.getUtxos(); +const changeAddress = await wallet.getChangeAddress(); +const { pubKeyHash: keyHash } = deserializeAddress(changeAddress); + +// Create time-locked native script +const nativeScript: NativeScript = { + type: "all", + scripts: [ + { + type: "before", + slot: "99999999", // Policy expires at this slot + }, + { + type: "sig", + keyHash: keyHash, + }, + ], +}; + +const forgingScript = ForgeScript.fromNativeScript(nativeScript); +const policyId = resolveScriptHash(forgingScript); +const tokenName = "TimeLocked"; +const tokenNameHex = stringToHex(tokenName); + +const metadata = { + [policyId]: { + [tokenName]: { + name: "Time-Locked Token", + image: "ipfs://QmRzicpReutwCkM6aotuKjErFCUD213DpwPq6ByuzMJaua", + } + } +}; + +const unsignedTx = await txBuilder + .mint("1", policyId, tokenNameHex) + .mintingScript(forgingScript) + .metadataValue(721, metadata) + .invalidHereafter(99999999) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos) + .complete(); + +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); +``` + +### Mint with Plutus Script + +Mint using a Plutus smart contract: + +```tsx +import { + MeshTxBuilder, + BlockfrostProvider, + resolveScriptHash, + stringToHex, + mConStr0, + UTxO +} from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +const utxos = await wallet.getUtxos(); +const collateral: UTxO = (await wallet.getCollateral())[0]!; +const changeAddress = await wallet.getChangeAddress(); + +// Your Plutus minting script CBOR +const plutusMintingScript = "your-script-cbor-here"; +const policyId = resolveScriptHash(plutusMintingScript, "V2"); +const tokenName = "PlutusToken"; +const tokenNameHex = stringToHex(tokenName); + +const metadata = { + [policyId]: { + [tokenName]: { + name: "Plutus Token", + image: "ipfs://QmRzicpReutwCkM6aotuKjErFCUD213DpwPq6ByuzMJaua", + } + } +}; + +const unsignedTx = await txBuilder + .mintPlutusScriptV2() + .mint("1", policyId, tokenNameHex) + .mintingScript(plutusMintingScript) + .mintRedeemerValue(mConStr0(["mesh"])) + .metadataValue(721, metadata) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos) + .txInCollateral( + collateral.input.txHash, + collateral.input.outputIndex, + collateral.output.amount, + collateral.output.address + ) + .complete(); + +const signedTx = await wallet.signTx(unsignedTx, true); +const txHash = await wallet.submitTx(signedTx); +``` + +### Mint CIP-68 Tokens + +Mint tokens with on-chain metadata using the CIP-68 standard: + +```tsx +import { + MeshTxBuilder, + BlockfrostProvider, + resolveScriptHash, + stringToHex, + mConStr0, + mTxOutRef, + applyParamsToScript, + serializePlutusScript, + metadataToCip68, + CIP68_100, + CIP68_222, + PlutusScript, + UTxO +} from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +const utxos = await wallet.getUtxos(); +const collateral: UTxO = (await wallet.getCollateral())[0]!; +const changeAddress = await wallet.getChangeAddress(); + +// Define user token metadata +const userTokenMetadata = { + name: "CIP68 Token", + image: "ipfs://QmRzicpReutwCkM6aotuKjErFCUD213DpwPq6ByuzMJaua", + mediaType: "image/jpg", + description: "A CIP-68 compliant token with on-chain metadata", +}; + +// Create always-succeed script for storing reference token +const alwaysSucceedScript: PlutusScript = { + code: "your-always-succeed-script-cbor", + version: "V1", +}; +const { address: scriptAddress } = serializePlutusScript(alwaysSucceedScript); + +// Create one-time minting policy (parameterized by UTxO) +const oneTimeMintingPolicy = "your-one-time-minting-policy-cbor"; +const scriptCode = applyParamsToScript(oneTimeMintingPolicy, [ + mTxOutRef(utxos[0]!.input.txHash, utxos[0]!.input.outputIndex), +]); + +const policyId = resolveScriptHash(scriptCode, "V2"); +const tokenName = "MyCIP68Token"; +const tokenNameHex = stringToHex(tokenName); + +const unsignedTx = await txBuilder + // Consume the UTxO used to parameterize the policy + .txIn( + utxos[0]!.input.txHash, + utxos[0]!.input.outputIndex, + utxos[0]!.output.amount, + utxos[0]!.output.address + ) + // Mint reference token (100 label) + .mintPlutusScriptV2() + .mint("1", policyId, CIP68_100(tokenNameHex)) + .mintingScript(scriptCode) + .mintRedeemerValue(mConStr0([])) + // Mint user token (222 label) + .mintPlutusScriptV2() + .mint("1", policyId, CIP68_222(tokenNameHex)) + .mintingScript(scriptCode) + .mintRedeemerValue(mConStr0([])) + // Send reference token to script address with metadata as datum + .txOut(scriptAddress, [ + { unit: policyId + CIP68_100(tokenNameHex), quantity: "1" }, + ]) + .txOutInlineDatumValue(metadataToCip68(userTokenMetadata)) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos) + .txInCollateral( + collateral.input.txHash, + collateral.input.outputIndex, + collateral.output.amount, + collateral.output.address + ) + .complete(); + +const signedTx = await wallet.signTx(unsignedTx, true); +const txHash = await wallet.submitTx(signedTx); +``` + +### Mint Royalty Token (CIP-27) + +Create a royalty token for secondary market sales: + +```tsx +import { + MeshTxBuilder, + BlockfrostProvider, + ForgeScript, + resolveScriptHash, + RoyaltiesStandard +} from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +const utxos = await wallet.getUtxos(); +const address = (await wallet.getUsedAddresses())[0]!; + +const forgingScript = ForgeScript.withOneSignature(address); +const policyId = resolveScriptHash(forgingScript); + +// Royalty metadata (CIP-27) +const royaltyMetadata: RoyaltiesStandard = { + rate: "0.05", // 5% royalty + address: "addr_test1qz...", // Royalty recipient address +}; + +const unsignedTx = await txBuilder + .mint("1", policyId, "") // Empty token name for royalty token + .mintingScript(forgingScript) + .metadataValue(777, royaltyMetadata) + .changeAddress(address) + .selectUtxosFrom(utxos) + .complete(); + +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); +``` + +## Complete Example + +This example demonstrates a complete NFT minting workflow: + +```tsx +import { + MeshTxBuilder, + BlockfrostProvider, + ForgeScript, + resolveScriptHash, + stringToHex, + deserializeAddress, + NativeScript +} from "@meshsdk/core"; + +async function mintNFTCollection( + wallet: any, + provider: BlockfrostProvider, + collectionSize: number +) { + const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, + }); + + // Get wallet data + const utxos = await wallet.getUtxos(); + const changeAddress = await wallet.getChangeAddress(); + const { pubKeyHash: keyHash } = deserializeAddress(changeAddress); + + // Create time-locked policy (expires in ~1 year) + const currentSlot = 100000000; // Get current slot from provider + const expirationSlot = currentSlot + 31536000; // ~1 year + + const nativeScript: NativeScript = { + type: "all", + scripts: [ + { type: "before", slot: expirationSlot.toString() }, + { type: "sig", keyHash: keyHash }, + ], + }; + + const forgingScript = ForgeScript.fromNativeScript(nativeScript); + const policyId = resolveScriptHash(forgingScript); + + // Build metadata for collection + const metadata: Record> = { [policyId]: {} }; + + for (let i = 1; i <= collectionSize; i++) { + const tokenName = `MyNFT${i.toString().padStart(4, "0")}`; + const tokenNameHex = stringToHex(tokenName); + + metadata[policyId][tokenName] = { + name: `My NFT #${i}`, + image: `ipfs://QmCollection.../${i}.png`, + mediaType: "image/png", + description: `NFT #${i} from My Collection`, + attributes: { + rarity: i <= 10 ? "Legendary" : i <= 50 ? "Rare" : "Common", + edition: i, + totalSupply: collectionSize, + }, + }; + + txBuilder.mint("1", policyId, tokenNameHex); + txBuilder.mintingScript(forgingScript); + } + + // Build transaction + txBuilder + .metadataValue(721, metadata) + .invalidHereafter(expirationSlot) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos); + + const unsignedTx = await txBuilder.complete(); + const signedTx = await wallet.signTx(unsignedTx); + const txHash = await wallet.submitTx(signedTx); + + return { + txHash, + policyId, + expirationSlot, + }; +} + +// Usage +const provider = new BlockfrostProvider(""); +const result = await mintNFTCollection(wallet, provider, 100); +console.log(`Minted collection with policy: ${result.policyId}`); +console.log(`Transaction: ${result.txHash}`); +``` + +## Troubleshooting + +### "Script hash mismatch" error +- Ensure the forging script matches the policy ID you're minting under +- For time-locked policies, verify the slot number matches exactly + +### "Insufficient collateral" for Plutus minting +- Provide collateral using `txInCollateral()` +- Collateral must be a pure ADA UTxO (no native assets) +- Collateral should be at least 5 ADA for most transactions + +### "Missing required signer" error +- For Native Scripts, ensure all required key hashes have signed +- Use `wallet.signTx(unsignedTx, true)` for partial signing in multi-sig scenarios + +### "Token already exists" for one-time policies +- One-time minting policies consume a specific UTxO +- That UTxO must exist and be unspent at transaction time + +### Metadata too large +- Keep metadata under 16KB total +- Use IPFS for large images and reference the CID +- Split large collections across multiple transactions + +### Time-locked policy expired +- Check the current slot number against your policy's expiration +- Use `invalidHereafter()` to match the policy's time constraint + +## Related + +- Transaction Basics - Core transaction building +- Smart Contracts - Plutus script interactions +- NFT Collection Guide - Step-by-step NFT tutorial +- Data Types - Working with Cardano data diff --git a/content/docs/apis/txbuilder/legacy/smart-contracts.mdx b/content/docs/apis/txbuilder/legacy/smart-contracts.mdx new file mode 100644 index 0000000..0e3f371 --- /dev/null +++ b/content/docs/apis/txbuilder/legacy/smart-contracts.mdx @@ -0,0 +1,708 @@ +--- +title: "Smart Contract Interactions" +description: "Lock, unlock, and interact with Plutus smart contracts on Cardano." +--- + +import Link from "fumadocs-core/link"; + +> **Deprecated:** `MeshTxBuilder` still works, but new code uses `TxBuilder`. See [Transaction Builder](/apis/txbuilder) and [Migrating to TxBuilder](/apis/txbuilder/migration). + +## Overview + +Smart contracts on Cardano are Plutus scripts that control how assets can be spent. You interact with them by locking assets at script addresses and unlocking them by providing valid datum and redeemer values. + +**When to use this:** +- Building decentralized applications (dApps) +- Creating escrow or vesting contracts +- Implementing decentralized exchanges +- Building NFT marketplaces +- Deploying on-chain validators + +## Quick Start + +```tsx +import { + MeshTxBuilder, + BlockfrostProvider, + serializePlutusScript, + PlutusScript +} from "@meshsdk/core"; + +// Initialize +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +// Define the Plutus script +const script: PlutusScript = { + code: "your-script-cbor-here", + version: "V2", +}; +const { address: scriptAddress } = serializePlutusScript(script); + +// Get wallet data +const utxos = await wallet.getUtxos(); +const changeAddress = await wallet.getChangeAddress(); + +// Lock assets at script address +const unsignedTx = await txBuilder + .txOut(scriptAddress, [{ unit: "lovelace", quantity: "10000000" }]) + .txOutInlineDatumValue("my-secret-datum") + .changeAddress(changeAddress) + .selectUtxosFrom(utxos) + .complete(); + +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); +``` + +## API Reference + +### Locking Assets + +#### txOut() + +Send assets to an address (including script addresses). + +```tsx +.txOut(address: string, amount: Asset[]) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `address` | `string` | Recipient address (can be a script address) | +| `amount` | `Asset[]` | Array of assets to send | + +#### txOutInlineDatumValue() + +Attach an inline datum to the output. + +```tsx +.txOutInlineDatumValue(datum: Data | object | string, type?: "Mesh" | "CBOR" | "JSON") +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `datum` | `Data \| object \| string` | Datum value | +| `type` | `"Mesh" \| "CBOR" \| "JSON"` | Data format (default: "Mesh") | + +#### txOutDatumHashValue() + +Attach a datum hash to the output (datum stored off-chain). + +```tsx +.txOutDatumHashValue(datum: Data | object | string, type?: "Mesh" | "CBOR" | "JSON") +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `datum` | `Data \| object \| string` | Datum value (hash will be computed) | +| `type` | `"Mesh" \| "CBOR" \| "JSON"` | Data format (default: "Mesh") | + +#### txOutReferenceScript() + +Attach a reference script to the output. + +```tsx +.txOutReferenceScript(scriptCbor: string, version?: LanguageVersion) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `scriptCbor` | `string` | CBOR-encoded script | +| `version` | `LanguageVersion` | Script version ("V1", "V2", "V3") | + +### Unlocking Assets + +#### spendingPlutusScriptV1() / V2() / V3() + +Indicate you are spending from a Plutus script. + +```tsx +.spendingPlutusScriptV2() +``` + +#### txIn() + +Specify the UTxO to spend. + +```tsx +.txIn(txHash: string, txIndex: number, amount?: Asset[], address?: string) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `txHash` | `string` | Transaction hash | +| `txIndex` | `number` | Output index | +| `amount` | `Asset[]` | Optional: Output amount | +| `address` | `string` | Optional: Output address | + +#### txInInlineDatumPresent() + +Indicate that the input has an inline datum. + +```tsx +.txInInlineDatumPresent() +``` + +#### txInDatumValue() + +Provide the datum for the input (when not inline). + +```tsx +.txInDatumValue(datum: Data | object | string, type?: "Mesh" | "CBOR" | "JSON") +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `datum` | `Data \| object \| string` | Datum value | +| `type` | `"Mesh" \| "CBOR" \| "JSON"` | Data format (default: "Mesh") | + +#### txInRedeemerValue() + +Provide the redeemer for the script. + +```tsx +.txInRedeemerValue(redeemer: Data | object | string, type?: "Mesh" | "CBOR" | "JSON", exUnits?: Budget) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `redeemer` | `Data \| object \| string` | Redeemer value | +| `type` | `"Mesh" \| "CBOR" \| "JSON"` | Data format (default: "Mesh") | +| `exUnits` | `Budget` | Optional execution units | + +#### txInScript() + +Provide the script for the input. + +```tsx +.txInScript(scriptCbor: string) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `scriptCbor` | `string` | CBOR-encoded Plutus script | + +#### spendingTxInReference() + +Reference an on-chain script instead of providing it inline. + +```tsx +.spendingTxInReference(txHash: string, txIndex: number, spendingScriptHash?: string) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `txHash` | `string` | Transaction hash containing reference script | +| `txIndex` | `number` | Output index | +| `spendingScriptHash` | `string` | Optional script hash for verification | + +### Collateral + +#### txInCollateral() + +Provide collateral for script execution. + +```tsx +.txInCollateral(txHash: string, txIndex: number, amount?: Asset[], address?: string) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `txHash` | `string` | Collateral UTxO transaction hash | +| `txIndex` | `number` | Output index | +| `amount` | `Asset[]` | Optional: UTxO amount | +| `address` | `string` | Optional: UTxO address | + +## Common Patterns + +### Lock Assets in a Script + +Send assets to a script address with an inline datum: + +```tsx +import { + MeshTxBuilder, + BlockfrostProvider, + serializePlutusScript, + PlutusScript +} from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +const utxos = await wallet.getUtxos(); +const changeAddress = await wallet.getChangeAddress(); + +// Define your Plutus script +const script: PlutusScript = { + code: "your-always-succeed-script-cbor", + version: "V2", +}; +const { address: scriptAddress } = serializePlutusScript(script); + +// Lock 10 ADA with a datum +const unsignedTx = await txBuilder + .txOut(scriptAddress, [{ unit: "lovelace", quantity: "10000000" }]) + .txOutInlineDatumValue("meshsecretcode") + .changeAddress(changeAddress) + .selectUtxosFrom(utxos) + .complete(); + +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); +``` + +### Lock with Datum Hash + +Lock assets using a datum hash instead of inline datum: + +```tsx +import { + MeshTxBuilder, + BlockfrostProvider, + serializePlutusScript, + PlutusScript +} from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +const utxos = await wallet.getUtxos(); +const changeAddress = await wallet.getChangeAddress(); + +const script: PlutusScript = { + code: "your-script-cbor", + version: "V2", +}; +const { address: scriptAddress } = serializePlutusScript(script); + +// Lock with datum hash (datum stored off-chain) +const unsignedTx = await txBuilder + .txOut(scriptAddress, [{ unit: "lovelace", quantity: "5000000" }]) + .txOutDatumHashValue("my-secret-datum") + .changeAddress(changeAddress) + .selectUtxosFrom(utxos) + .complete(); + +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); +``` + +### Unlock Assets from a Script + +Spend a UTxO from a script address: + +```tsx +import { + MeshTxBuilder, + BlockfrostProvider, + serializePlutusScript, + mConStr0, + PlutusScript +} from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +const utxos = await wallet.getUtxos(); +const collateral = await wallet.getCollateral(); +const changeAddress = await wallet.getChangeAddress(); + +// Define the script +const script: PlutusScript = { + code: "your-always-succeed-script-cbor", + version: "V2", +}; +const { address: scriptAddress } = serializePlutusScript(script); + +// Find the UTxO to unlock (in production, query from provider) +const scriptUtxos = await provider.fetchAddressUTxOs(scriptAddress); +const assetUtxo = scriptUtxos.find( + (utxo) => utxo.output.plutusData === "meshsecretcode" +); + +if (!assetUtxo) { + throw new Error("UTxO not found"); +} + +const unsignedTx = await txBuilder + .spendingPlutusScriptV2() + .txIn(assetUtxo.input.txHash, assetUtxo.input.outputIndex) + .txInInlineDatumPresent() + .txInRedeemerValue(mConStr0([])) + .txInScript(script.code) + .changeAddress(changeAddress) + .txInCollateral( + collateral[0]!.input.txHash, + collateral[0]!.input.outputIndex, + collateral[0]!.output.amount, + collateral[0]!.output.address + ) + .selectUtxosFrom(utxos) + .complete(); + +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); +``` + +### Unlock with Datum Hash + +When the UTxO was locked with a datum hash, you must provide the datum: + +```tsx +import { + MeshTxBuilder, + BlockfrostProvider, + serializePlutusScript, + mConStr0, + PlutusScript +} from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +const utxos = await wallet.getUtxos(); +const collateral = await wallet.getCollateral(); +const changeAddress = await wallet.getChangeAddress(); + +const script: PlutusScript = { + code: "your-script-cbor", + version: "V2", +}; + +// The UTxO to unlock +const assetUtxo = { + input: { txHash: "abc123...", outputIndex: 0 }, + output: { amount: [{ unit: "lovelace", quantity: "5000000" }], address: "..." } +}; + +const unsignedTx = await txBuilder + .spendingPlutusScriptV2() + .txIn(assetUtxo.input.txHash, assetUtxo.input.outputIndex) + .txInDatumValue("my-secret-datum") // Provide the original datum + .txInRedeemerValue(mConStr0([])) + .txInScript(script.code) + .changeAddress(changeAddress) + .txInCollateral( + collateral[0]!.input.txHash, + collateral[0]!.input.outputIndex, + collateral[0]!.output.amount, + collateral[0]!.output.address + ) + .selectUtxosFrom(utxos) + .complete(); + +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); +``` + +### Using Reference Scripts + +Reference scripts allow you to use a script stored on-chain, reducing transaction size and fees. + +#### Deploy a Reference Script + +First, send a reference script on-chain: + +```tsx +import { + MeshTxBuilder, + BlockfrostProvider +} from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +const utxos = await wallet.getUtxos(); +const changeAddress = await wallet.getChangeAddress(); + +const scriptCbor = "your-plutus-script-cbor"; + +// Send script on-chain (use an address you control) +const unsignedTx = await txBuilder + .txOut("addr_test1qz...", [{ unit: "lovelace", quantity: "10000000" }]) + .txOutReferenceScript(scriptCbor, "V2") + .changeAddress(changeAddress) + .selectUtxosFrom(utxos) + .complete(); + +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); + +// Save txHash and output index for future reference +console.log(`Reference script deployed at: ${txHash}#0`); +``` + +#### Use a Reference Script + +Spend using an on-chain reference script: + +```tsx +import { + MeshTxBuilder, + BlockfrostProvider, + mConStr0 +} from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +const utxos = await wallet.getUtxos(); +const collateral = await wallet.getCollateral(); +const changeAddress = await wallet.getChangeAddress(); + +// Reference script location +const refScriptTxHash = "abc123..."; +const refScriptTxIndex = 0; + +// UTxO to unlock +const assetUtxo = { + input: { txHash: "def456...", outputIndex: 0 }, + output: { amount: [{ unit: "lovelace", quantity: "5000000" }], address: "..." } +}; + +const unsignedTx = await txBuilder + .spendingPlutusScriptV2() + .txIn(assetUtxo.input.txHash, assetUtxo.input.outputIndex) + .txInInlineDatumPresent() + .txInRedeemerValue(mConStr0([])) + .spendingTxInReference(refScriptTxHash, refScriptTxIndex) // Use reference script + .changeAddress(changeAddress) + .txInCollateral( + collateral[0]!.input.txHash, + collateral[0]!.input.outputIndex, + collateral[0]!.output.amount, + collateral[0]!.output.address + ) + .selectUtxosFrom(utxos) + .complete(); + +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); +``` + +### Mint with Plutus Script + +Mint tokens using a Plutus minting policy: + +```tsx +import { + MeshTxBuilder, + BlockfrostProvider, + resolveScriptHash, + stringToHex, + mConStr0, + UTxO +} from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +const utxos = await wallet.getUtxos(); +const collateral: UTxO = (await wallet.getCollateral())[0]!; +const changeAddress = await wallet.getChangeAddress(); + +const plutusMintingScript = "your-minting-script-cbor"; +const policyId = resolveScriptHash(plutusMintingScript, "V2"); +const tokenName = "MyToken"; +const tokenNameHex = stringToHex(tokenName); + +const metadata = { + [policyId]: { + [tokenName]: { + name: "My Plutus Token", + image: "ipfs://...", + } + } +}; + +const unsignedTx = await txBuilder + .mintPlutusScriptV2() + .mint("1", policyId, tokenNameHex) + .mintingScript(plutusMintingScript) + .mintRedeemerValue(mConStr0(["mesh"])) + .metadataValue(721, metadata) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos) + .txInCollateral( + collateral.input.txHash, + collateral.input.outputIndex, + collateral.output.amount, + collateral.output.address + ) + .complete(); + +const signedTx = await wallet.signTx(unsignedTx, true); +const txHash = await wallet.submitTx(signedTx); +``` + +## Complete Example + +This example demonstrates a complete escrow workflow: + +```tsx +import { + MeshTxBuilder, + BlockfrostProvider, + serializePlutusScript, + deserializeAddress, + mConStr0, + PlutusScript, + UTxO +} from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); + +// Escrow script that releases funds when correct redeemer is provided +const escrowScript: PlutusScript = { + code: "your-escrow-script-cbor", + version: "V2", +}; +const { address: escrowAddress } = serializePlutusScript(escrowScript); + +// Step 1: Lock funds in escrow +async function createEscrow( + wallet: any, + amount: string, + beneficiary: string +) { + const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, + }); + + const utxos = await wallet.getUtxos(); + const changeAddress = await wallet.getChangeAddress(); + const { pubKeyHash } = deserializeAddress(beneficiary); + + // Lock funds with beneficiary's pubKeyHash as datum + const unsignedTx = await txBuilder + .txOut(escrowAddress, [{ unit: "lovelace", quantity: amount }]) + .txOutInlineDatumValue(pubKeyHash) + .changeAddress(changeAddress) + .selectUtxosFrom(utxos) + .complete(); + + const signedTx = await wallet.signTx(unsignedTx); + const txHash = await wallet.submitTx(signedTx); + + return txHash; +} + +// Step 2: Release funds from escrow +async function releaseEscrow( + wallet: any, + escrowUtxo: UTxO +) { + const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, + }); + + const utxos = await wallet.getUtxos(); + const collateral = await wallet.getCollateral(); + const changeAddress = await wallet.getChangeAddress(); + const { pubKeyHash } = deserializeAddress(changeAddress); + + const unsignedTx = await txBuilder + .spendingPlutusScriptV2() + .txIn(escrowUtxo.input.txHash, escrowUtxo.input.outputIndex) + .txInInlineDatumPresent() + .txInRedeemerValue(mConStr0([])) + .txInScript(escrowScript.code) + .requiredSignerHash(pubKeyHash) + .changeAddress(changeAddress) + .txInCollateral( + collateral[0]!.input.txHash, + collateral[0]!.input.outputIndex, + collateral[0]!.output.amount, + collateral[0]!.output.address + ) + .selectUtxosFrom(utxos) + .complete(); + + const signedTx = await wallet.signTx(unsignedTx, true); + const txHash = await wallet.submitTx(signedTx); + + return txHash; +} + +// Usage +const escrowTxHash = await createEscrow( + sellerWallet, + "50000000", // 50 ADA + buyerAddress +); +console.log(`Escrow created: ${escrowTxHash}`); + +// Later, buyer releases funds +const escrowUtxos = await provider.fetchAddressUTxOs(escrowAddress); +const myEscrow = escrowUtxos.find( + (utxo) => utxo.input.txHash === escrowTxHash +); + +const releaseTxHash = await releaseEscrow(buyerWallet, myEscrow!); +console.log(`Escrow released: ${releaseTxHash}`); +``` + +## Troubleshooting + +### "Script execution failed" error +- Verify the redeemer matches what the script expects +- Check that the datum is correct (inline vs hash) +- Ensure all required signers are included + +### "Missing collateral" error +- Provide collateral using `txInCollateral()` +- Collateral must be a pure ADA UTxO (no tokens) +- Recommended: at least 5 ADA for collateral + +### "Execution units exceeded" error +- The script is consuming too much resources +- Optimize your script or provide custom execution units +- Use `txInRedeemerValue(redeemer, "Mesh", { mem: X, steps: Y })` + +### "Datum hash mismatch" error +- When unlocking with datum hash, provide the exact original datum +- Ensure the datum type matches (Mesh, CBOR, or JSON) + +### "Reference script not found" error +- Verify the reference script UTxO still exists (not spent) +- Check the transaction hash and output index are correct +- Ensure the script version matches (V1, V2, or V3) + +### "Required signer missing" error +- Add `requiredSignerHash()` for scripts that check signatures +- Use partial signing: `wallet.signTx(unsignedTx, true)` + +## Related + +- Transaction Basics - Core transaction building +- Minting Assets - Plutus minting policies +- Data Types - Working with datum and redeemer +- Transaction Parser - Parse and test transactions diff --git a/content/docs/apis/txbuilder/legacy/staking.mdx b/content/docs/apis/txbuilder/legacy/staking.mdx new file mode 100644 index 0000000..53836db --- /dev/null +++ b/content/docs/apis/txbuilder/legacy/staking.mdx @@ -0,0 +1,591 @@ +--- +title: "Staking and Delegation" +description: "Delegate ADA to stake pools, register stake addresses, and withdraw staking rewards with TypeScript." +--- + +import Link from "fumadocs-core/link"; + +> **Deprecated:** `MeshTxBuilder` still works, but new code uses `TxBuilder`. See [Transaction Builder](/apis/txbuilder) and [Migrating to TxBuilder](/apis/txbuilder/migration). + +## Overview + +Staking allows you to delegate your ADA to stake pools and earn rewards. You can register stake addresses, delegate to pools, withdraw rewards, and deregister stake addresses using `MeshTxBuilder`. + +**When to use this:** +- Delegating ADA to earn staking rewards +- Building staking dashboards or portfolio trackers +- Creating delegation services +- Implementing stake pool operations +- Building "withdraw zero" validation patterns + +## Quick Start + +```tsx +import { + MeshTxBuilder, + BlockfrostProvider, + deserializePoolId +} from "@meshsdk/core"; + +// Initialize +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +// Get wallet data +const utxos = await wallet.getUtxos(); +const changeAddress = await wallet.getChangeAddress(); +const rewardAddresses = await wallet.getRewardAddresses(); +const rewardAddress = rewardAddresses[0]!; + +// Convert pool ID to hash +const poolIdHash = deserializePoolId( + "pool1pu5jlj4q9w9jlxeu370a3c9myx47md5j5m2str0naunn2q3lkdy" +); + +// Delegate to stake pool +const unsignedTx = await txBuilder + .delegateStakeCertificate(rewardAddress, poolIdHash) + .selectUtxosFrom(utxos) + .changeAddress(changeAddress) + .complete(); + +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); +``` + +## API Reference + +### registerStakeCertificate() + +Register a stake address on the blockchain (required before first delegation). + +```tsx +.registerStakeCertificate(rewardAddress: string) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `rewardAddress` | `string` | Bech32 reward address (stake...) | + +### delegateStakeCertificate() + +Delegate stake to a pool. + +```tsx +.delegateStakeCertificate(rewardAddress: string, poolIdHash: string) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `rewardAddress` | `string` | Bech32 reward address | +| `poolIdHash` | `string` | Deserialized pool ID hash | + +### deregisterStakeCertificate() + +Deregister a stake address and reclaim the deposit. + +```tsx +.deregisterStakeCertificate(rewardAddress: string) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `rewardAddress` | `string` | Bech32 reward address to deregister | + +### withdrawal() + +Withdraw staking rewards. + +```tsx +.withdrawal(rewardAddress: string, lovelace: string) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `rewardAddress` | `string` | Bech32 reward address | +| `lovelace` | `string` | Amount to withdraw in lovelace | + +### withdrawalPlutusScriptV1() / V2() / V3() + +Indicate withdrawal from a Plutus staking script. + +```tsx +.withdrawalPlutusScriptV2() +``` + +### withdrawalScript() + +Provide the staking script for script-based withdrawal. + +```tsx +.withdrawalScript(scriptCbor: string) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `scriptCbor` | `string` | CBOR-encoded staking script | + +### withdrawalRedeemerValue() + +Provide the redeemer for script-based withdrawal. + +```tsx +.withdrawalRedeemerValue(redeemer: Data | object | string, type?: "Mesh" | "CBOR" | "JSON", exUnits?: Budget) +``` + +| Parameter | Type | Description | +|-----------|------|-------------| +| `redeemer` | `Data \| object \| string` | Redeemer value | +| `type` | `"Mesh" \| "CBOR" \| "JSON"` | Data format (default: "Mesh") | +| `exUnits` | `Budget` | Optional execution units | + +## Common Patterns + +### Register and Delegate (First Time) + +Register a stake address and delegate in a single transaction: + +```tsx +import { + MeshTxBuilder, + BlockfrostProvider, + deserializePoolId +} from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +const utxos = await wallet.getUtxos(); +const changeAddress = await wallet.getChangeAddress(); +const rewardAddresses = await wallet.getRewardAddresses(); +const rewardAddress = rewardAddresses[0]!; + +// Convert bech32 pool ID to hash +const poolIdHash = deserializePoolId( + "pool1pu5jlj4q9w9jlxeu370a3c9myx47md5j5m2str0naunn2q3lkdy" +); + +// Register and delegate in one transaction +const unsignedTx = await txBuilder + .registerStakeCertificate(rewardAddress) + .delegateStakeCertificate(rewardAddress, poolIdHash) + .selectUtxosFrom(utxos) + .changeAddress(changeAddress) + .complete(); + +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); + +console.log(`Registered and delegated: ${txHash}`); +``` + +### Change Delegation + +Switch delegation to a different pool (no registration needed): + +```tsx +import { + MeshTxBuilder, + BlockfrostProvider, + deserializePoolId +} from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +const utxos = await wallet.getUtxos(); +const changeAddress = await wallet.getChangeAddress(); +const rewardAddresses = await wallet.getRewardAddresses(); +const rewardAddress = rewardAddresses[0]!; + +// New pool to delegate to +const newPoolIdHash = deserializePoolId( + "pool1z5uqdk7dzdxaae5633fqfcu2eqzy3a3rgtuvy087fdld7yws0xt" +); + +const unsignedTx = await txBuilder + .delegateStakeCertificate(rewardAddress, newPoolIdHash) + .selectUtxosFrom(utxos) + .changeAddress(changeAddress) + .complete(); + +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); + +console.log(`Delegation changed: ${txHash}`); +``` + +### Withdraw Rewards + +Withdraw accumulated staking rewards: + +```tsx +import { + MeshTxBuilder, + BlockfrostProvider +} from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +const utxos = await wallet.getUtxos(); +const changeAddress = await wallet.getChangeAddress(); +const rewardAddresses = await wallet.getRewardAddresses(); +const rewardAddress = rewardAddresses[0]!; + +// Query available rewards (in production) +// const accountInfo = await provider.fetchAccountInfo(rewardAddress); +// const withdrawableAmount = accountInfo.withdrawableAmount; + +const withdrawAmount = "5000000"; // 5 ADA in lovelace + +const unsignedTx = await txBuilder + .withdrawal(rewardAddress, withdrawAmount) + .selectUtxosFrom(utxos) + .changeAddress(changeAddress) + .complete(); + +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); + +console.log(`Rewards withdrawn: ${txHash}`); +``` + +### Deregister Stake Address + +Stop staking and reclaim the 2 ADA deposit: + +```tsx +import { + MeshTxBuilder, + BlockfrostProvider +} from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +const utxos = await wallet.getUtxos(); +const changeAddress = await wallet.getChangeAddress(); +const rewardAddresses = await wallet.getRewardAddresses(); +const rewardAddress = rewardAddresses[0]!; + +const unsignedTx = await txBuilder + .deregisterStakeCertificate(rewardAddress) + .selectUtxosFrom(utxos) + .changeAddress(changeAddress) + .complete(); + +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); + +console.log(`Stake deregistered, deposit reclaimed: ${txHash}`); +``` + +### Script Withdrawal + +Withdraw from a Plutus staking script: + +```tsx +import { + MeshTxBuilder, + BlockfrostProvider, + resolveScriptHash, + serializeRewardAddress, + deserializeAddress +} from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +const utxos = await wallet.getUtxos(); +const collateral = await wallet.getCollateral(); +const changeAddress = await wallet.getChangeAddress(); + +// Your staking script CBOR +const stakeScriptCbor = "your-stake-script-cbor"; + +// Derive reward address from script +const scriptHash = resolveScriptHash(stakeScriptCbor, "V2"); +const rewardAddress = serializeRewardAddress(scriptHash, true, 0); // testnet + +const withdrawAmount = "1000000"; // 1 ADA + +const unsignedTx = await txBuilder + .withdrawalPlutusScriptV2() + .withdrawal(rewardAddress, withdrawAmount) + .withdrawalScript(stakeScriptCbor) + .withdrawalRedeemerValue("") // Your redeemer + .selectUtxosFrom(utxos) + .changeAddress(changeAddress) + .txInCollateral( + collateral[0]!.input.txHash, + collateral[0]!.input.outputIndex, + collateral[0]!.output.amount, + collateral[0]!.output.address + ) + .complete(); + +const signedTx = await wallet.signTx(unsignedTx, true); +const txHash = await wallet.submitTx(signedTx); +``` + +### Withdraw Zero Pattern + +The "withdraw zero" pattern is used to prove control of a stake key without withdrawing rewards. This is commonly used in DeFi protocols for stake key validation. + +#### Step 1: Register Script Stake Key + +```tsx +import { + MeshTxBuilder, + BlockfrostProvider, + resolveScriptHash, + deserializeAddress +} from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +const utxos = await wallet.getUtxos(); +const changeAddress = await wallet.getChangeAddress(); +const { pubKeyHash } = deserializeAddress(changeAddress); + +// Parameterized staking script +const stakeScriptCbor = getAlwaysSucceedStakingScript(pubKeyHash); +const scriptHash = resolveScriptHash(stakeScriptCbor, "V2"); + +const unsignedTx = await txBuilder + .registerStakeCertificate(scriptHash) + .selectUtxosFrom(utxos) + .changeAddress(changeAddress) + .complete(); + +const signedTx = await wallet.signTx(unsignedTx, true); +const txHash = await wallet.submitTx(signedTx); + +console.log(`Script stake key registered: ${txHash}`); +``` + +#### Step 2: Withdraw Zero + +```tsx +import { + MeshTxBuilder, + BlockfrostProvider, + resolveScriptHash, + serializeRewardAddress, + deserializeAddress +} from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); +const txBuilder = new MeshTxBuilder({ + fetcher: provider, + verbose: true, +}); + +const utxos = await wallet.getUtxos(); +const collateral = await wallet.getCollateral(); +const changeAddress = await wallet.getChangeAddress(); +const { pubKeyHash } = deserializeAddress(changeAddress); + +const stakeScriptCbor = getAlwaysSucceedStakingScript(pubKeyHash); +const scriptHash = resolveScriptHash(stakeScriptCbor, "V2"); +const rewardAddress = serializeRewardAddress(scriptHash, true, 0); + +// Withdraw zero to trigger script validation +const unsignedTx = await txBuilder + .withdrawalPlutusScriptV2() + .withdrawal(rewardAddress, "0") // Zero withdrawal + .withdrawalScript(stakeScriptCbor) + .withdrawalRedeemerValue("") + .selectUtxosFrom(utxos) + .changeAddress(changeAddress) + .txInCollateral( + collateral[0]!.input.txHash, + collateral[0]!.input.outputIndex, + collateral[0]!.output.amount, + collateral[0]!.output.address + ) + .complete(); + +const signedTx = await wallet.signTx(unsignedTx, true); +const txHash = await wallet.submitTx(signedTx); + +console.log(`Withdraw zero completed: ${txHash}`); +``` + +## Complete Example + +This example demonstrates a complete staking management workflow: + +```tsx +import { + MeshTxBuilder, + BlockfrostProvider, + deserializePoolId +} from "@meshsdk/core"; + +const provider = new BlockfrostProvider(""); + +// Helper to create txBuilder +function getTxBuilder() { + return new MeshTxBuilder({ + fetcher: provider, + verbose: true, + }); +} + +// Register and delegate to a pool +async function startStaking(wallet: any, poolBech32: string) { + const txBuilder = getTxBuilder(); + + const utxos = await wallet.getUtxos(); + const changeAddress = await wallet.getChangeAddress(); + const rewardAddresses = await wallet.getRewardAddresses(); + const rewardAddress = rewardAddresses[0]!; + const poolIdHash = deserializePoolId(poolBech32); + + const unsignedTx = await txBuilder + .registerStakeCertificate(rewardAddress) + .delegateStakeCertificate(rewardAddress, poolIdHash) + .selectUtxosFrom(utxos) + .changeAddress(changeAddress) + .complete(); + + const signedTx = await wallet.signTx(unsignedTx); + return await wallet.submitTx(signedTx); +} + +// Change to a different pool +async function changePool(wallet: any, newPoolBech32: string) { + const txBuilder = getTxBuilder(); + + const utxos = await wallet.getUtxos(); + const changeAddress = await wallet.getChangeAddress(); + const rewardAddresses = await wallet.getRewardAddresses(); + const rewardAddress = rewardAddresses[0]!; + const poolIdHash = deserializePoolId(newPoolBech32); + + const unsignedTx = await txBuilder + .delegateStakeCertificate(rewardAddress, poolIdHash) + .selectUtxosFrom(utxos) + .changeAddress(changeAddress) + .complete(); + + const signedTx = await wallet.signTx(unsignedTx); + return await wallet.submitTx(signedTx); +} + +// Withdraw all rewards +async function withdrawRewards(wallet: any, amount: string) { + const txBuilder = getTxBuilder(); + + const utxos = await wallet.getUtxos(); + const changeAddress = await wallet.getChangeAddress(); + const rewardAddresses = await wallet.getRewardAddresses(); + const rewardAddress = rewardAddresses[0]!; + + const unsignedTx = await txBuilder + .withdrawal(rewardAddress, amount) + .selectUtxosFrom(utxos) + .changeAddress(changeAddress) + .complete(); + + const signedTx = await wallet.signTx(unsignedTx); + return await wallet.submitTx(signedTx); +} + +// Stop staking completely +async function stopStaking(wallet: any) { + const txBuilder = getTxBuilder(); + + const utxos = await wallet.getUtxos(); + const changeAddress = await wallet.getChangeAddress(); + const rewardAddresses = await wallet.getRewardAddresses(); + const rewardAddress = rewardAddresses[0]!; + + const unsignedTx = await txBuilder + .deregisterStakeCertificate(rewardAddress) + .selectUtxosFrom(utxos) + .changeAddress(changeAddress) + .complete(); + + const signedTx = await wallet.signTx(unsignedTx); + return await wallet.submitTx(signedTx); +} + +// Usage +const poolId = "pool1pu5jlj4q9w9jlxeu370a3c9myx47md5j5m2str0naunn2q3lkdy"; + +// Start staking +const startTxHash = await startStaking(wallet, poolId); +console.log(`Started staking: ${startTxHash}`); + +// Later, withdraw 10 ADA in rewards +const withdrawTxHash = await withdrawRewards(wallet, "10000000"); +console.log(`Withdrew rewards: ${withdrawTxHash}`); + +// Change to different pool +const newPoolId = "pool1z5uqdk7dzdxaae5633fqfcu2eqzy3a3rgtuvy087fdld7yws0xt"; +const changeTxHash = await changePool(wallet, newPoolId); +console.log(`Changed pool: ${changeTxHash}`); + +// Eventually, stop staking +const stopTxHash = await stopStaking(wallet); +console.log(`Stopped staking: ${stopTxHash}`); +``` + +## Troubleshooting + +### "Stake address not registered" error +- You must register a stake address before delegating +- Use `registerStakeCertificate()` first, or combine with delegation + +### "Pool not found" error +- Verify the pool ID is correct and the pool is active +- Use `deserializePoolId()` to convert bech32 pool IDs + +### "Insufficient funds for deposit" error +- Stake registration requires a 2 ADA deposit +- Ensure your wallet has enough ADA to cover the deposit plus fees + +### "Cannot withdraw more than available" error +- Query actual available rewards before withdrawing +- Use `provider.fetchAccountInfo(rewardAddress)` to check balance + +### "Stake address already registered" error +- Skip `registerStakeCertificate()` if already registered +- Query stake address status first to check registration + +### Script withdrawal fails +- Ensure the script stake key is registered first +- Provide valid collateral for Plutus script execution +- Check that the redeemer matches what the script expects + +## Related + +- Transaction Basics - Core transaction building +- Governance - DRep delegation and voting +- Providers - Query stake pool information +- Wallets - Get reward addresses diff --git a/content/docs/apis/txbuilder/meta.json b/content/docs/apis/txbuilder/meta.json index c814af7..59b6a47 100644 --- a/content/docs/apis/txbuilder/meta.json +++ b/content/docs/apis/txbuilder/meta.json @@ -1,5 +1,5 @@ { "title": "Transaction Builder", "icon": "BanknotesIcon", - "pages": ["basics", "minting", "smart-contracts", "staking", "governance", "migration"] -} \ No newline at end of file + "pages": ["basics", "minting", "smart-contracts", "staking", "governance", "migration", "legacy"] +} diff --git a/content/docs/apis/txbuilder/migration.mdx b/content/docs/apis/txbuilder/migration/index.mdx similarity index 100% rename from content/docs/apis/txbuilder/migration.mdx rename to content/docs/apis/txbuilder/migration/index.mdx diff --git a/content/docs/apis/txbuilder/minting.mdx b/content/docs/apis/txbuilder/minting.mdx index fe3b858..492ab8e 100644 --- a/content/docs/apis/txbuilder/minting.mdx +++ b/content/docs/apis/txbuilder/minting.mdx @@ -1,676 +1,229 @@ --- -title: "Minting and Burning Assets" -description: "Create and destroy native assets using Native Scripts and Plutus Scripts." +title: "Mint and Burn Assets" +description: "Mint and burn native assets with a native script or a Plutus script, and add NFT metadata." --- -import Link from "fumadocs-core/link"; - ## Overview -Minting creates new native assets on Cardano, while burning destroys existing ones. You can mint using Native Scripts (simple signature-based) or Plutus Scripts (programmable smart contracts). - -**When to use this:** -- Creating NFT collections -- Issuing fungible tokens -- Implementing tokenized loyalty programs -- Building CIP-68 compliant tokens with on-chain metadata -- Setting up royalty tokens for secondary market sales - -## Quick Start - -```tsx -import { - MeshTxBuilder, - BlockfrostProvider, - ForgeScript, - resolveScriptHash, - stringToHex -} from "@meshsdk/core"; - -// Initialize -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -// Get wallet data -const utxos = await wallet.getUtxos(); -const changeAddress = await wallet.getChangeAddress(); - -// Create minting script -const forgingScript = ForgeScript.withOneSignature(changeAddress); -const policyId = resolveScriptHash(forgingScript); -const tokenNameHex = stringToHex("MeshToken"); - -// Build mint transaction -const unsignedTx = await txBuilder - .mint("1", policyId, tokenNameHex) - .mintingScript(forgingScript) - .metadataValue(721, { - [policyId]: { - MeshToken: { - name: "Mesh Token", - image: "ipfs://QmRzicpReutwCkM6aotuKjErFCUD213DpwPq6ByuzMJaua", - } - } - }) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos) - .complete(); - -// Sign and submit -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); -``` - -## API Reference - -### mint() - -Specify the asset to mint or burn. - -```tsx -.mint(quantity: string, policyId: string, tokenNameHex: string) -``` - -| Parameter | Type | Description | -|-----------|------|-------------| -| `quantity` | `string` | Amount to mint (positive) or burn (negative) | -| `policyId` | `string` | Policy ID of the asset | -| `tokenNameHex` | `string` | Hex-encoded token name | - -### mintingScript() - -Provide the minting script. - -```tsx -.mintingScript(script: string | NativeScript) -``` - -| Parameter | Type | Description | -|-----------|------|-------------| -| `script` | `string \| NativeScript` | CBOR-encoded script or NativeScript object | - -### mintPlutusScriptV1() / V2() / V3() - -Indicate that a Plutus script will be used for minting. - -```tsx -.mintPlutusScriptV2() -``` - -### mintRedeemerValue() - -Provide the redeemer for Plutus script minting. +Minting is a part of the transaction: `mint.native` for a native script policy and `mint.plutus` for a Plutus policy. Quantities are `bigint`, and a negative quantity burns. -```tsx -.mintRedeemerValue(redeemer: Data | object | string, type?: "Mesh" | "CBOR" | "JSON", exUnits?: Budget) -``` +Examples stop at `build()`: call `built.sign()` and `built.submit()` as in [Transaction Basics](/apis/txbuilder/basics#build-sign-and-submit). They use `builder` and `wallet` from there, and these names, which your application defines: -| Parameter | Type | Description | -|-----------|------|-------------| -| `redeemer` | `Data \| object \| string` | Redeemer data | -| `type` | `"Mesh" \| "CBOR" \| "JSON"` | Data format type (default: "Mesh") | -| `exUnits` | `Budget` | Optional execution units | +- `changeAddress` - the wallet's address, from `await wallet.getChangeAddress()` +- `policyCode` - a Plutus minting policy as script CBOR: `applyCborEncoding(compiledCode)` of `@meshsdk/core`, the form `resolveScriptHash` takes +- `referenceAddress` - where CIP-68 reference tokens are kept +- `refTxHash` - the hash of a transaction that holds a script in one of its outputs -### mintTxInReference() +## Mint with a Native Script -Reference an on-chain script instead of providing it inline. +`ForgeScript.withOneSignature` makes a policy that only your key can use. Give it to `mint.native` with asset names in hex. The policy id comes from the script. ```tsx -.mintTxInReference(txHash: string, txIndex: number) -``` - -| Parameter | Type | Description | -|-----------|------|-------------| -| `txHash` | `string` | Transaction hash containing the reference script | -| `txIndex` | `number` | Output index of the reference script | - -### metadataValue() - -Attach metadata to the transaction. - -```tsx -.metadataValue(label: number, metadata: object) -``` +import { ForgeScript, mint, stringToHex } from "@meshsdk/core"; -| Parameter | Type | Description | -|-----------|------|-------------| -| `label` | `number` | Metadata label (721 for NFTs, 777 for royalties) | -| `metadata` | `object` | Metadata object | - -## Common Patterns - -### Mint with One Signature - -The simplest minting approach using a single wallet address: - -```tsx -import { - MeshTxBuilder, - BlockfrostProvider, - ForgeScript, - resolveScriptHash, - stringToHex -} from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -const utxos = await wallet.getUtxos(); -const changeAddress = await wallet.getChangeAddress(); - -// Create forging script from wallet address const forgingScript = ForgeScript.withOneSignature(changeAddress); -const policyId = resolveScriptHash(forgingScript); -const tokenName = "MeshToken"; -const tokenNameHex = stringToHex(tokenName); - -// Define NFT metadata -const metadata = { - [policyId]: { - [tokenName]: { - name: "Mesh Token", - image: "ipfs://QmRzicpReutwCkM6aotuKjErFCUD213DpwPq6ByuzMJaua", - mediaType: "image/jpg", - description: "This NFT was minted by Mesh.", - } - } -}; -const unsignedTx = await txBuilder - .mint("1", policyId, tokenNameHex) - .mintingScript(forgingScript) - .metadataValue(721, metadata) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos) - .complete(); - -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); +const built = await builder.build( + mint.native({ + script: forgingScript, + assets: { [stringToHex("MeshToken")]: 1n }, + }), + { payer: wallet }, +); ``` -### Mint Multiple Assets +### Mint Several Assets -Mint multiple tokens in a single transaction: +Put every asset of a policy in the `assets` of one part. A second part of the same policy is `DUPLICATE_PART` (see [Handle Errors](/apis/txbuilder/basics#handle-errors)). A quantity above `1n` makes a fungible token. A very large collection may not fit in one transaction (`TX_TOO_LARGE`): split it. ```tsx -import { - MeshTxBuilder, - BlockfrostProvider, - ForgeScript, - resolveScriptHash, - stringToHex -} from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); +import { ForgeScript, mint, stringToHex } from "@meshsdk/core"; -const utxos = await wallet.getUtxos(); -const changeAddress = await wallet.getChangeAddress(); const forgingScript = ForgeScript.withOneSignature(changeAddress); -const policyId = resolveScriptHash(forgingScript); - -// Build metadata for multiple tokens -const metadata: Record> = { [policyId]: {} }; - -for (let i = 1; i <= 3; i++) { - const tokenName = `MeshToken${i}`; - const tokenNameHex = stringToHex(tokenName); - - metadata[policyId][tokenName] = { - name: tokenName, - image: "ipfs://QmRzicpReutwCkM6aotuKjErFCUD213DpwPq6ByuzMJaua", - description: `Token #${i} from the Mesh collection`, - }; - - // Add mint instruction for each token - txBuilder.mint("1", policyId, tokenNameHex); - txBuilder.mintingScript(forgingScript); -} - -txBuilder - .metadataValue(721, metadata) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos); - -const unsignedTx = await txBuilder.complete(); -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); +const names = ["MeshToken1", "MeshToken2", "MeshToken3"]; + +const built = await builder.build( + mint.native({ + script: forgingScript, + assets: Object.fromEntries(names.map((name) => [stringToHex(name), 1n])), + }), + { payer: wallet }, +); ``` ### Burn Assets -Burn assets by minting with a negative quantity: +A negative quantity burns. Use the script of the policy that minted the tokens. The tokens must be in the payer's wallet. ```tsx -import { - MeshTxBuilder, - BlockfrostProvider, - ForgeScript, - resolveScriptHash, - stringToHex -} from "@meshsdk/core"; +import { ForgeScript, mint, stringToHex } from "@meshsdk/core"; -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -const utxos = await wallet.getUtxos(); -const changeAddress = await wallet.getChangeAddress(); - -// Use the same forging script that minted the asset const forgingScript = ForgeScript.withOneSignature(changeAddress); -const policyId = resolveScriptHash(forgingScript); -const tokenNameHex = stringToHex("MeshToken"); - -// Burn by using negative quantity -const unsignedTx = await txBuilder - .mint("-1", policyId, tokenNameHex) - .mintingScript(forgingScript) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos) - .complete(); - -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); + +const built = await builder.build( + mint.native({ + script: forgingScript, + assets: { [stringToHex("MeshToken")]: -1n }, + }), + { payer: wallet }, +); ``` -### Mint with Native Script (Time-Locked) +### Mint with a Time-Locked Policy -Create a time-locked minting policy: +`script` also takes a `NativeScript` object. This policy works only before a slot, so the transaction states the end of its validity with `validity()`. `builder.slotAt()` turns a time into a slot. ```tsx import { - MeshTxBuilder, - BlockfrostProvider, - ForgeScript, - resolveScriptHash, - stringToHex, deserializeAddress, - NativeScript + mint, + stringToHex, + validity, } from "@meshsdk/core"; +import type { NativeScript } from "@meshsdk/core"; -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -const utxos = await wallet.getUtxos(); -const changeAddress = await wallet.getChangeAddress(); -const { pubKeyHash: keyHash } = deserializeAddress(changeAddress); - -// Create time-locked native script -const nativeScript: NativeScript = { +const { pubKeyHash } = deserializeAddress(changeAddress); +const closes = builder.slotAt(Date.now() + 3_600_000); // a slot in an hour +const policy: NativeScript = { type: "all", scripts: [ - { - type: "before", - slot: "99999999", // Policy expires at this slot - }, - { - type: "sig", - keyHash: keyHash, - }, + { type: "before", slot: closes.toString() }, + { type: "sig", keyHash: pubKeyHash }, ], }; -const forgingScript = ForgeScript.fromNativeScript(nativeScript); -const policyId = resolveScriptHash(forgingScript); -const tokenName = "TimeLocked"; -const tokenNameHex = stringToHex(tokenName); - -const metadata = { - [policyId]: { - [tokenName]: { - name: "Time-Locked Token", - image: "ipfs://QmRzicpReutwCkM6aotuKjErFCUD213DpwPq6ByuzMJaua", - } - } -}; - -const unsignedTx = await txBuilder - .mint("1", policyId, tokenNameHex) - .mintingScript(forgingScript) - .metadataValue(721, metadata) - .invalidHereafter(99999999) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos) - .complete(); - -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); +const built = await builder.build( + [ + mint.native({ + script: policy, + assets: { [stringToHex("TimeLocked")]: 1n }, + }), + validity({ invalidHereafter: closes }), + ], + { payer: wallet }, +); ``` -### Mint with Plutus Script +## Add NFT Metadata -Mint using a Plutus smart contract: +CIP-25, the NFT metadata standard, keeps metadata under label 721, keyed by policy id and then by asset name as text. Add it with `metadata()`. Each text is at most 64 bytes, so split a longer one into a list of strings. ```tsx import { - MeshTxBuilder, - BlockfrostProvider, + ForgeScript, + metadata, + mint, resolveScriptHash, stringToHex, - mConStr0, - UTxO } from "@meshsdk/core"; -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -const utxos = await wallet.getUtxos(); -const collateral: UTxO = (await wallet.getCollateral())[0]!; -const changeAddress = await wallet.getChangeAddress(); - -// Your Plutus minting script CBOR -const plutusMintingScript = "your-script-cbor-here"; -const policyId = resolveScriptHash(plutusMintingScript, "V2"); -const tokenName = "PlutusToken"; -const tokenNameHex = stringToHex(tokenName); - -const metadata = { - [policyId]: { - [tokenName]: { - name: "Plutus Token", - image: "ipfs://QmRzicpReutwCkM6aotuKjErFCUD213DpwPq6ByuzMJaua", - } - } -}; +const forgingScript = ForgeScript.withOneSignature(changeAddress); +const policyId = resolveScriptHash(forgingScript); -const unsignedTx = await txBuilder - .mintPlutusScriptV2() - .mint("1", policyId, tokenNameHex) - .mintingScript(plutusMintingScript) - .mintRedeemerValue(mConStr0(["mesh"])) - .metadataValue(721, metadata) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos) - .txInCollateral( - collateral.input.txHash, - collateral.input.outputIndex, - collateral.output.amount, - collateral.output.address - ) - .complete(); - -const signedTx = await wallet.signTx(unsignedTx, true); -const txHash = await wallet.submitTx(signedTx); +const built = await builder.build( + [ + mint.native({ + script: forgingScript, + assets: { [stringToHex("MeshToken")]: 1n }, + }), + metadata({ + metadataLabel: 721n, + value: { + [policyId]: { + MeshToken: { + name: "Mesh Token", + image: "ipfs://QmRzicpReutwCkM6aotuKjErFCUD213DpwPq6ByuzMJaua", + mediaType: "image/jpg", + }, + }, + }, + }), + ], + { payer: wallet }, +); ``` -### Mint CIP-68 Tokens +A royalty token (CIP-27) has the empty asset name and its own entry: `mint.native({ script: forgingScript, assets: { "": 1n } })` with `metadata({ metadataLabel: 777n, value: { rate: "0.05", addr: [first64, rest] } })`. Split the address into strings of at most 64 bytes. -Mint tokens with on-chain metadata using the CIP-68 standard: +## Mint with a Plutus Script -```tsx -import { - MeshTxBuilder, - BlockfrostProvider, - resolveScriptHash, - stringToHex, - mConStr0, - mTxOutRef, - applyParamsToScript, - serializePlutusScript, - metadataToCip68, - CIP68_100, - CIP68_222, - PlutusScript, - UTxO -} from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -const utxos = await wallet.getUtxos(); -const collateral: UTxO = (await wallet.getCollateral())[0]!; -const changeAddress = await wallet.getChangeAddress(); - -// Define user token metadata -const userTokenMetadata = { - name: "CIP68 Token", - image: "ipfs://QmRzicpReutwCkM6aotuKjErFCUD213DpwPq6ByuzMJaua", - mediaType: "image/jpg", - description: "A CIP-68 compliant token with on-chain metadata", -}; - -// Create always-succeed script for storing reference token -const alwaysSucceedScript: PlutusScript = { - code: "your-always-succeed-script-cbor", - version: "V1", -}; -const { address: scriptAddress } = serializePlutusScript(alwaysSucceedScript); - -// Create one-time minting policy (parameterized by UTxO) -const oneTimeMintingPolicy = "your-one-time-minting-policy-cbor"; -const scriptCode = applyParamsToScript(oneTimeMintingPolicy, [ - mTxOutRef(utxos[0]!.input.txHash, utxos[0]!.input.outputIndex), -]); - -const policyId = resolveScriptHash(scriptCode, "V2"); -const tokenName = "MyCIP68Token"; -const tokenNameHex = stringToHex(tokenName); - -const unsignedTx = await txBuilder - // Consume the UTxO used to parameterize the policy - .txIn( - utxos[0]!.input.txHash, - utxos[0]!.input.outputIndex, - utxos[0]!.output.amount, - utxos[0]!.output.address - ) - // Mint reference token (100 label) - .mintPlutusScriptV2() - .mint("1", policyId, CIP68_100(tokenNameHex)) - .mintingScript(scriptCode) - .mintRedeemerValue(mConStr0([])) - // Mint user token (222 label) - .mintPlutusScriptV2() - .mint("1", policyId, CIP68_222(tokenNameHex)) - .mintingScript(scriptCode) - .mintRedeemerValue(mConStr0([])) - // Send reference token to script address with metadata as datum - .txOut(scriptAddress, [ - { unit: policyId + CIP68_100(tokenNameHex), quantity: "1" }, - ]) - .txOutInlineDatumValue(metadataToCip68(userTokenMetadata)) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos) - .txInCollateral( - collateral.input.txHash, - collateral.input.outputIndex, - collateral.output.amount, - collateral.output.address - ) - .complete(); - -const signedTx = await wallet.signTx(unsignedTx, true); -const txHash = await wallet.submitTx(signedTx); -``` - -### Mint Royalty Token (CIP-27) - -Create a royalty token for secondary market sales: +`mint.plutus` takes the script with its version, a redeemer (the data you give the script) and the assets. Burn the same way with a negative quantity. ```tsx -import { - MeshTxBuilder, - BlockfrostProvider, - ForgeScript, - resolveScriptHash, - RoyaltiesStandard -} from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -const utxos = await wallet.getUtxos(); -const address = (await wallet.getUsedAddresses())[0]!; - -const forgingScript = ForgeScript.withOneSignature(address); -const policyId = resolveScriptHash(forgingScript); - -// Royalty metadata (CIP-27) -const royaltyMetadata: RoyaltiesStandard = { - rate: "0.05", // 5% royalty - address: "addr_test1qz...", // Royalty recipient address -}; - -const unsignedTx = await txBuilder - .mint("1", policyId, "") // Empty token name for royalty token - .mintingScript(forgingScript) - .metadataValue(777, royaltyMetadata) - .changeAddress(address) - .selectUtxosFrom(utxos) - .complete(); - -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); +import { mConStr0, mint, stringToHex } from "@meshsdk/core"; + +const built = await builder.build( + mint.plutus({ + script: { code: policyCode, version: "V3" }, + redeemer: { data: mConStr0([]) }, + assets: { [stringToHex("MeshToken")]: 1n }, + }), + { payer: wallet }, +); ``` -## Complete Example +### Mint CIP-68 Tokens -This example demonstrates a complete NFT minting workflow: +CIP-68 keeps the metadata in an inline datum (data stored with an output). The reference token (100) and the user token (222) belong to one policy, so they are one part. Lock the reference token with the metadata as its datum; the user token goes to the payer's change. ```tsx import { - MeshTxBuilder, - BlockfrostProvider, - ForgeScript, + CIP68_100, + CIP68_222, + mConStr0, + metadataToCip68, + mint, + output, resolveScriptHash, stringToHex, - deserializeAddress, - NativeScript } from "@meshsdk/core"; -async function mintNFTCollection( - wallet: any, - provider: BlockfrostProvider, - collectionSize: number -) { - const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, - }); - - // Get wallet data - const utxos = await wallet.getUtxos(); - const changeAddress = await wallet.getChangeAddress(); - const { pubKeyHash: keyHash } = deserializeAddress(changeAddress); - - // Create time-locked policy (expires in ~1 year) - const currentSlot = 100000000; // Get current slot from provider - const expirationSlot = currentSlot + 31536000; // ~1 year - - const nativeScript: NativeScript = { - type: "all", - scripts: [ - { type: "before", slot: expirationSlot.toString() }, - { type: "sig", keyHash: keyHash }, - ], - }; - - const forgingScript = ForgeScript.fromNativeScript(nativeScript); - const policyId = resolveScriptHash(forgingScript); - - // Build metadata for collection - const metadata: Record> = { [policyId]: {} }; - - for (let i = 1; i <= collectionSize; i++) { - const tokenName = `MyNFT${i.toString().padStart(4, "0")}`; - const tokenNameHex = stringToHex(tokenName); - - metadata[policyId][tokenName] = { - name: `My NFT #${i}`, - image: `ipfs://QmCollection.../${i}.png`, - mediaType: "image/png", - description: `NFT #${i} from My Collection`, - attributes: { - rarity: i <= 10 ? "Legendary" : i <= 50 ? "Rare" : "Common", - edition: i, - totalSupply: collectionSize, +const nameHex = stringToHex("MyToken"); +const policyId = resolveScriptHash(policyCode, "V3"); + +const built = await builder.build( + [ + mint.plutus({ + script: { code: policyCode, version: "V3" }, + redeemer: { data: mConStr0([]) }, + assets: { [CIP68_100(nameHex)]: 1n, [CIP68_222(nameHex)]: 1n }, + }), + output({ + address: referenceAddress, + value: { [policyId + CIP68_100(nameHex)]: 1n }, + datum: { + type: "inline", + data: metadataToCip68({ name: "MyToken", image: "ipfs://..." }), }, - }; - - txBuilder.mint("1", policyId, tokenNameHex); - txBuilder.mintingScript(forgingScript); - } - - // Build transaction - txBuilder - .metadataValue(721, metadata) - .invalidHereafter(expirationSlot) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos); - - const unsignedTx = await txBuilder.complete(); - const signedTx = await wallet.signTx(unsignedTx); - const txHash = await wallet.submitTx(signedTx); - - return { - txHash, - policyId, - expirationSlot, - }; -} - -// Usage -const provider = new BlockfrostProvider(""); -const result = await mintNFTCollection(wallet, provider, 100); -console.log(`Minted collection with policy: ${result.policyId}`); -console.log(`Transaction: ${result.txHash}`); + }), + ], + { payer: wallet }, +); ``` -## Troubleshooting - -### "Script hash mismatch" error -- Ensure the forging script matches the policy ID you're minting under -- For time-locked policies, verify the slot number matches exactly - -### "Insufficient collateral" for Plutus minting -- Provide collateral using `txInCollateral()` -- Collateral must be a pure ADA UTxO (no native assets) -- Collateral should be at least 5 ADA for most transactions +### Mint with a Reference Script -### "Missing required signer" error -- For Native Scripts, ensure all required key hashes have signed -- Use `wallet.signTx(unsignedTx, true)` for partial signing in multi-sig scenarios +A reference script is a script stored in an output, so a transaction does not send its code again. Name that output instead of the code. The builder knows only the out ref, so give the policy id too. To put a script on chain, see [Smart Contracts](/apis/txbuilder/smart-contracts#deploy-and-use-a-reference-script). -### "Token already exists" for one-time policies -- One-time minting policies consume a specific UTxO -- That UTxO must exist and be unspent at transaction time - -### Metadata too large -- Keep metadata under 16KB total -- Use IPFS for large images and reference the CID -- Split large collections across multiple transactions - -### Time-locked policy expired -- Check the current slot number against your policy's expiration -- Use `invalidHereafter()` to match the policy's time constraint +```tsx +import { mConStr0, mint, resolveScriptHash, stringToHex } from "@meshsdk/core"; + +const built = await builder.build( + mint.plutus({ + script: { reference: { txHash: refTxHash, outputIndex: 0 }, version: "V3" }, + policyId: resolveScriptHash(policyCode, "V3"), + redeemer: { data: mConStr0([]) }, + assets: { [stringToHex("MeshToken")]: 1n }, + }), + { payer: wallet }, +); +``` ## Related -- Transaction Basics - Core transaction building -- Smart Contracts - Plutus script interactions -- NFT Collection Guide - Step-by-step NFT tutorial -- Data Types - Working with Cardano data +- [Transaction Basics](/apis/txbuilder/basics) - the builder, outputs, metadata and validity +- [Smart Contracts](/apis/txbuilder/smart-contracts) - lock and spend with Plutus scripts +- [Migrating to TxBuilder](/apis/txbuilder/migration) - move from the `MeshTxBuilder` chain +- [Data Types](/apis/data) - build datums and redeemers +- [Resolvers](/apis/utilities/resolvers) - policy ids and script hashes +- [Package README](https://github.com/MeshJS/mesh/tree/main/packages/mesh-transaction) - every part, option and error diff --git a/content/docs/apis/txbuilder/smart-contracts.mdx b/content/docs/apis/txbuilder/smart-contracts.mdx index e173400..23c9c22 100644 --- a/content/docs/apis/txbuilder/smart-contracts.mdx +++ b/content/docs/apis/txbuilder/smart-contracts.mdx @@ -1,706 +1,161 @@ --- -title: "Smart Contract Interactions" -description: "Lock, unlock, and interact with Plutus smart contracts on Cardano." +title: "Smart Contracts" +description: "Lock assets at a script address and spend them with a Plutus script, a reference script or a native script." --- -import Link from "fumadocs-core/link"; - ## Overview -Smart contracts on Cardano are Plutus scripts that control how assets can be spent. You interact with them by locking assets at script addresses and unlocking them by providing valid datum and redeemer values. - -**When to use this:** -- Building decentralized applications (dApps) -- Creating escrow or vesting contracts -- Implementing decentralized exchanges -- Building NFT marketplaces -- Deploying on-chain validators +A script holds assets through an ordinary `output` at its address, and a `spend.plutus` part unlocks them. The builder reads the datum from the output, adds collateral (ada the network can take if a script fails), evaluates execution units and orders inputs and redeemers. You do not set them. -## Quick Start +Examples stop at `build()`: call `built.sign()` and `built.submit()` as in [Transaction Basics](/apis/txbuilder/basics#build-sign-and-submit). They use `builder` and `wallet` from there, and these names, which your application defines: -```tsx -import { - MeshTxBuilder, - BlockfrostProvider, - serializePlutusScript, - PlutusScript -} from "@meshsdk/core"; - -// Initialize -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -// Define the Plutus script -const script: PlutusScript = { - code: "your-script-cbor-here", - version: "V2", -}; -const { address: scriptAddress } = serializePlutusScript(script); - -// Get wallet data -const utxos = await wallet.getUtxos(); -const changeAddress = await wallet.getChangeAddress(); - -// Lock assets at script address -const unsignedTx = await txBuilder - .txOut(scriptAddress, [{ unit: "lovelace", quantity: "10000000" }]) - .txOutInlineDatumValue("my-secret-datum") - .changeAddress(changeAddress) - .selectUtxosFrom(utxos) - .complete(); - -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); -``` +- `changeAddress` - the wallet's address, from `await wallet.getChangeAddress()` +- `script` - a Plutus script, `{ code, version }` +- `scriptUtxo` - an output locked at that script +- `nativeUtxo` - an output locked at a native script's address +- `refTxHash` - the hash of a transaction that holds a script in one of its outputs -## API Reference +## Lock Assets at a Script -### Locking Assets - -#### txOut() - -Send assets to an address (including script addresses). +A datum is data stored with an output so a script can read it. `builder.scriptAddress(script)` gives the script's address on the builder's network. Send assets there with an inline datum. For a datum hash use `datum: { type: "hash", data }`, and add `embed: true` to publish the datum with the transaction. ```tsx -.txOut(address: string, amount: Asset[]) -``` - -| Parameter | Type | Description | -|-----------|------|-------------| -| `address` | `string` | Recipient address (can be a script address) | -| `amount` | `Asset[]` | Array of assets to send | - -#### txOutInlineDatumValue() - -Attach an inline datum to the output. - -```tsx -.txOutInlineDatumValue(datum: Data | object | string, type?: "Mesh" | "CBOR" | "JSON") -``` - -| Parameter | Type | Description | -|-----------|------|-------------| -| `datum` | `Data \| object \| string` | Datum value | -| `type` | `"Mesh" \| "CBOR" \| "JSON"` | Data format (default: "Mesh") | - -#### txOutDatumHashValue() - -Attach a datum hash to the output (datum stored off-chain). - -```tsx -.txOutDatumHashValue(datum: Data | object | string, type?: "Mesh" | "CBOR" | "JSON") -``` - -| Parameter | Type | Description | -|-----------|------|-------------| -| `datum` | `Data \| object \| string` | Datum value (hash will be computed) | -| `type` | `"Mesh" \| "CBOR" \| "JSON"` | Data format (default: "Mesh") | - -#### txOutReferenceScript() - -Attach a reference script to the output. - -```tsx -.txOutReferenceScript(scriptCbor: string, version?: LanguageVersion) -``` +import { mConStr0, output } from "@meshsdk/core"; -| Parameter | Type | Description | -|-----------|------|-------------| -| `scriptCbor` | `string` | CBOR-encoded script | -| `version` | `LanguageVersion` | Script version ("V1", "V2", "V3") | - -### Unlocking Assets - -#### spendingPlutusScriptV1() / V2() / V3() - -Indicate you are spending from a Plutus script. - -```tsx -.spendingPlutusScriptV2() -``` - -#### txIn() - -Specify the UTxO to spend. - -```tsx -.txIn(txHash: string, txIndex: number, amount?: Asset[], address?: string) -``` - -| Parameter | Type | Description | -|-----------|------|-------------| -| `txHash` | `string` | Transaction hash | -| `txIndex` | `number` | Output index | -| `amount` | `Asset[]` | Optional: Output amount | -| `address` | `string` | Optional: Output address | - -#### txInInlineDatumPresent() - -Indicate that the input has an inline datum. - -```tsx -.txInInlineDatumPresent() -``` - -#### txInDatumValue() - -Provide the datum for the input (when not inline). - -```tsx -.txInDatumValue(datum: Data | object | string, type?: "Mesh" | "CBOR" | "JSON") +const built = await builder.build( + output({ + address: builder.scriptAddress(script), + value: { lovelace: 10_000_000n }, + datum: { type: "inline", data: mConStr0([]) }, + }), + { payer: wallet }, +); ``` -| Parameter | Type | Description | -|-----------|------|-------------| -| `datum` | `Data \| object \| string` | Datum value | -| `type` | `"Mesh" \| "CBOR" \| "JSON"` | Data format (default: "Mesh") | +## Spend from a Script -#### txInRedeemerValue() +Give `spend.plutus` the output, the script and a redeemer (the data you give the script when you spend). -Provide the redeemer for the script. +- Find the output with your provider's `fetchAddressUTxOs(address)`, or name it by `{ txHash, outputIndex }`. +- The datum is read from the output. For an output that holds only a datum hash, add `datum: { data }`. +- The assets go to the payer's change address unless an `output` part sends them elsewhere. +- The builder picks collateral. To choose it yourself, add a `collateral({ utxo })` part. The builder tops it up unless you pass `topUpCollateral: false`. ```tsx -.txInRedeemerValue(redeemer: Data | object | string, type?: "Mesh" | "CBOR" | "JSON", exUnits?: Budget) -``` - -| Parameter | Type | Description | -|-----------|------|-------------| -| `redeemer` | `Data \| object \| string` | Redeemer value | -| `type` | `"Mesh" \| "CBOR" \| "JSON"` | Data format (default: "Mesh") | -| `exUnits` | `Budget` | Optional execution units | +import { guard, mConStr0, spend } from "@meshsdk/core"; -#### txInScript() - -Provide the script for the input. - -```tsx -.txInScript(scriptCbor: string) +const built = await builder.build( + [ + spend.plutus({ + utxo: scriptUtxo, + script, + redeemer: { data: mConStr0([]) }, + }), + guard.pubKey({ address: changeAddress }), // for a script that checks a signer + ], + { payer: wallet }, +); ``` -| Parameter | Type | Description | -|-----------|------|-------------| -| `scriptCbor` | `string` | CBOR-encoded Plutus script | +## Deploy and Use a Reference Script -#### spendingTxInReference() +A reference script is a script stored in an output, so a transaction does not send its code again. Put one on chain by attaching it to an output with `scriptRef`. Leave `lovelace` out and the output holds the minimum it needs. Later, name that output in `script` instead of sending the code, and the builder adds it as a reference input. -Reference an on-chain script instead of providing it inline. +Lock the output at an address the payer does not pay from, or keep it out of selection with `canSelect: (c) => !c.script`. Otherwise a later build by the same payer can spend it. ```tsx -.spendingTxInReference(txHash: string, txIndex: number, spendingScriptHash?: string) -``` - -| Parameter | Type | Description | -|-----------|------|-------------| -| `txHash` | `string` | Transaction hash containing reference script | -| `txIndex` | `number` | Output index | -| `spendingScriptHash` | `string` | Optional script hash for verification | - -### Collateral +import { mConStr0, output, spend } from "@meshsdk/core"; -#### txInCollateral() - -Provide collateral for script execution. - -```tsx -.txInCollateral(txHash: string, txIndex: number, amount?: Asset[], address?: string) +const deploy = await builder.build( + output({ address: changeAddress, value: {}, scriptRef: script }), + { payer: wallet }, +); +// sign and submit deploy once; its txHash is the refTxHash below + +const built = await builder.build( + spend.plutus({ + utxo: scriptUtxo, + script: { reference: { txHash: refTxHash, outputIndex: 0 } }, + redeemer: { data: mConStr0([]) }, + }), + { payer: wallet, canSelect: (c) => !c.script }, +); ``` -| Parameter | Type | Description | -|-----------|------|-------------| -| `txHash` | `string` | Collateral UTxO transaction hash | -| `txIndex` | `number` | Output index | -| `amount` | `Asset[]` | Optional: UTxO amount | -| `address` | `string` | Optional: UTxO address | - -## Common Patterns +Minting works the same way: see [Mint and Burn Assets](/apis/txbuilder/minting#mint-with-a-reference-script). -### Lock Assets in a Script +## Read a Datum without Spending -Send assets to a script address with an inline datum: +A reference input lets scripts read an output, its datum and its reference script, without spending it. The builder never spends such an output for payment. An output the transaction also spends is not a reference input. ```tsx -import { - MeshTxBuilder, - BlockfrostProvider, - serializePlutusScript, - PlutusScript -} from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -const utxos = await wallet.getUtxos(); -const changeAddress = await wallet.getChangeAddress(); - -// Define your Plutus script -const script: PlutusScript = { - code: "your-always-succeed-script-cbor", - version: "V2", -}; -const { address: scriptAddress } = serializePlutusScript(script); - -// Lock 10 ADA with a datum -const unsignedTx = await txBuilder - .txOut(scriptAddress, [{ unit: "lovelace", quantity: "10000000" }]) - .txOutInlineDatumValue("meshsecretcode") - .changeAddress(changeAddress) - .selectUtxosFrom(utxos) - .complete(); - -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); -``` - -### Lock with Datum Hash - -Lock assets using a datum hash instead of inline datum: - -```tsx -import { - MeshTxBuilder, - BlockfrostProvider, - serializePlutusScript, - PlutusScript -} from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -const utxos = await wallet.getUtxos(); -const changeAddress = await wallet.getChangeAddress(); - -const script: PlutusScript = { - code: "your-script-cbor", - version: "V2", -}; -const { address: scriptAddress } = serializePlutusScript(script); - -// Lock with datum hash (datum stored off-chain) -const unsignedTx = await txBuilder - .txOut(scriptAddress, [{ unit: "lovelace", quantity: "5000000" }]) - .txOutDatumHashValue("my-secret-datum") - .changeAddress(changeAddress) - .selectUtxosFrom(utxos) - .complete(); - -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); -``` +import { mConStr0, referenceInput, spend } from "@meshsdk/core"; -### Unlock Assets from a Script - -Spend a UTxO from a script address: - -```tsx -import { - MeshTxBuilder, - BlockfrostProvider, - serializePlutusScript, - mConStr0, - PlutusScript -} from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -const utxos = await wallet.getUtxos(); -const collateral = await wallet.getCollateral(); -const changeAddress = await wallet.getChangeAddress(); - -// Define the script -const script: PlutusScript = { - code: "your-always-succeed-script-cbor", - version: "V2", -}; -const { address: scriptAddress } = serializePlutusScript(script); - -// Find the UTxO to unlock (in production, query from provider) -const scriptUtxos = await provider.fetchAddressUTxOs(scriptAddress); -const assetUtxo = scriptUtxos.find( - (utxo) => utxo.output.plutusData === "meshsecretcode" +const built = await builder.build( + [ + spend.plutus({ + utxo: scriptUtxo, + script, + redeemer: { data: mConStr0([]) }, + }), + referenceInput({ utxo: { txHash: refTxHash, outputIndex: 1 } }), + ], + { payer: wallet }, ); - -if (!assetUtxo) { - throw new Error("UTxO not found"); -} - -const unsignedTx = await txBuilder - .spendingPlutusScriptV2() - .txIn(assetUtxo.input.txHash, assetUtxo.input.outputIndex) - .txInInlineDatumPresent() - .txInRedeemerValue(mConStr0([])) - .txInScript(script.code) - .changeAddress(changeAddress) - .txInCollateral( - collateral[0]!.input.txHash, - collateral[0]!.input.outputIndex, - collateral[0]!.output.amount, - collateral[0]!.output.address - ) - .selectUtxosFrom(utxos) - .complete(); - -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); ``` -### Unlock with Datum Hash +## Spend from a Native Script -When the UTxO was locked with a datum hash, you must provide the datum: +`spend.native` takes a `NativeScript`, its CBOR or a reference. Native scripts need no redeemer and no collateral. The payer signs by default. Keys the script names that the payer does not hold go in `built.sign({ signers: [wallet, keySigner(key)] })`, and `built.missing` lists the keys that have not signed yet. ```tsx -import { - MeshTxBuilder, - BlockfrostProvider, - serializePlutusScript, - mConStr0, - PlutusScript -} from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -const utxos = await wallet.getUtxos(); -const collateral = await wallet.getCollateral(); -const changeAddress = await wallet.getChangeAddress(); - -const script: PlutusScript = { - code: "your-script-cbor", - version: "V2", -}; - -// The UTxO to unlock -const assetUtxo = { - input: { txHash: "abc123...", outputIndex: 0 }, - output: { amount: [{ unit: "lovelace", quantity: "5000000" }], address: "..." } -}; - -const unsignedTx = await txBuilder - .spendingPlutusScriptV2() - .txIn(assetUtxo.input.txHash, assetUtxo.input.outputIndex) - .txInDatumValue("my-secret-datum") // Provide the original datum - .txInRedeemerValue(mConStr0([])) - .txInScript(script.code) - .changeAddress(changeAddress) - .txInCollateral( - collateral[0]!.input.txHash, - collateral[0]!.input.outputIndex, - collateral[0]!.output.amount, - collateral[0]!.output.address - ) - .selectUtxosFrom(utxos) - .complete(); - -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); -``` - -### Using Reference Scripts +import { ForgeScript, spend } from "@meshsdk/core"; -Reference scripts allow you to use a script stored on-chain, reducing transaction size and fees. - -#### Deploy a Reference Script - -First, send a reference script on-chain: - -```tsx -import { - MeshTxBuilder, - BlockfrostProvider -} from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -const utxos = await wallet.getUtxos(); -const changeAddress = await wallet.getChangeAddress(); - -const scriptCbor = "your-plutus-script-cbor"; - -// Send script on-chain (use an address you control) -const unsignedTx = await txBuilder - .txOut("addr_test1qz...", [{ unit: "lovelace", quantity: "10000000" }]) - .txOutReferenceScript(scriptCbor, "V2") - .changeAddress(changeAddress) - .selectUtxosFrom(utxos) - .complete(); - -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); - -// Save txHash and output index for future reference -console.log(`Reference script deployed at: ${txHash}#0`); -``` - -#### Use a Reference Script - -Spend using an on-chain reference script: - -```tsx -import { - MeshTxBuilder, - BlockfrostProvider, - mConStr0 -} from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -const utxos = await wallet.getUtxos(); -const collateral = await wallet.getCollateral(); -const changeAddress = await wallet.getChangeAddress(); - -// Reference script location -const refScriptTxHash = "abc123..."; -const refScriptTxIndex = 0; - -// UTxO to unlock -const assetUtxo = { - input: { txHash: "def456...", outputIndex: 0 }, - output: { amount: [{ unit: "lovelace", quantity: "5000000" }], address: "..." } -}; - -const unsignedTx = await txBuilder - .spendingPlutusScriptV2() - .txIn(assetUtxo.input.txHash, assetUtxo.input.outputIndex) - .txInInlineDatumPresent() - .txInRedeemerValue(mConStr0([])) - .spendingTxInReference(refScriptTxHash, refScriptTxIndex) // Use reference script - .changeAddress(changeAddress) - .txInCollateral( - collateral[0]!.input.txHash, - collateral[0]!.input.outputIndex, - collateral[0]!.output.amount, - collateral[0]!.output.address - ) - .selectUtxosFrom(utxos) - .complete(); - -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); -``` - -### Mint with Plutus Script - -Mint tokens using a Plutus minting policy: - -```tsx -import { - MeshTxBuilder, - BlockfrostProvider, - resolveScriptHash, - stringToHex, - mConStr0, - UTxO -} from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -const utxos = await wallet.getUtxos(); -const collateral: UTxO = (await wallet.getCollateral())[0]!; -const changeAddress = await wallet.getChangeAddress(); - -const plutusMintingScript = "your-minting-script-cbor"; -const policyId = resolveScriptHash(plutusMintingScript, "V2"); -const tokenName = "MyToken"; -const tokenNameHex = stringToHex(tokenName); - -const metadata = { - [policyId]: { - [tokenName]: { - name: "My Plutus Token", - image: "ipfs://...", - } - } -}; - -const unsignedTx = await txBuilder - .mintPlutusScriptV2() - .mint("1", policyId, tokenNameHex) - .mintingScript(plutusMintingScript) - .mintRedeemerValue(mConStr0(["mesh"])) - .metadataValue(721, metadata) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos) - .txInCollateral( - collateral.input.txHash, - collateral.input.outputIndex, - collateral.output.amount, - collateral.output.address - ) - .complete(); - -const signedTx = await wallet.signTx(unsignedTx, true); -const txHash = await wallet.submitTx(signedTx); +const built = await builder.build( + spend.native({ + utxo: nativeUtxo, + script: ForgeScript.withOneSignature(changeAddress), + }), + { payer: wallet }, +); ``` -## Complete Example +## Lock and Unlock with a Plan -This example demonstrates a complete escrow workflow: +A plan sends several transactions in order, waits for each to land, and can be repeated safely. The unlock step names the output of the lock step by its label. The change of the lock step pays for the unlock. A plan needs a provider that returns block heights and the validity flag: see the [Note in Transaction Basics](/apis/txbuilder/basics#plan-several-transactions). ```tsx -import { - MeshTxBuilder, - BlockfrostProvider, - serializePlutusScript, - deserializeAddress, - mConStr0, - PlutusScript, - UTxO -} from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); - -// Escrow script that releases funds when correct redeemer is provided -const escrowScript: PlutusScript = { - code: "your-escrow-script-cbor", - version: "V2", -}; -const { address: escrowAddress } = serializePlutusScript(escrowScript); - -// Step 1: Lock funds in escrow -async function createEscrow( - wallet: any, - amount: string, - beneficiary: string -) { - const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, - }); - - const utxos = await wallet.getUtxos(); - const changeAddress = await wallet.getChangeAddress(); - const { pubKeyHash } = deserializeAddress(beneficiary); - - // Lock funds with beneficiary's pubKeyHash as datum - const unsignedTx = await txBuilder - .txOut(escrowAddress, [{ unit: "lovelace", quantity: amount }]) - .txOutInlineDatumValue(pubKeyHash) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos) - .complete(); - - const signedTx = await wallet.signTx(unsignedTx); - const txHash = await wallet.submitTx(signedTx); - - return txHash; -} - -// Step 2: Release funds from escrow -async function releaseEscrow( - wallet: any, - escrowUtxo: UTxO -) { - const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, - }); - - const utxos = await wallet.getUtxos(); - const collateral = await wallet.getCollateral(); - const changeAddress = await wallet.getChangeAddress(); - const { pubKeyHash } = deserializeAddress(changeAddress); - - const unsignedTx = await txBuilder - .spendingPlutusScriptV2() - .txIn(escrowUtxo.input.txHash, escrowUtxo.input.outputIndex) - .txInInlineDatumPresent() - .txInRedeemerValue(mConStr0([])) - .txInScript(escrowScript.code) - .requiredSignerHash(pubKeyHash) - .changeAddress(changeAddress) - .txInCollateral( - collateral[0]!.input.txHash, - collateral[0]!.input.outputIndex, - collateral[0]!.output.amount, - collateral[0]!.output.address - ) - .selectUtxosFrom(utxos) - .complete(); - - const signedTx = await wallet.signTx(unsignedTx, true); - const txHash = await wallet.submitTx(signedTx); - - return txHash; -} - -// Usage -const escrowTxHash = await createEscrow( - sellerWallet, - "50000000", // 50 ADA - buyerAddress -); -console.log(`Escrow created: ${escrowTxHash}`); +import { mConStr0, output, spend } from "@meshsdk/core"; -// Later, buyer releases funds -const escrowUtxos = await provider.fetchAddressUTxOs(escrowAddress); -const myEscrow = escrowUtxos.find( - (utxo) => utxo.input.txHash === escrowTxHash +const plan = await builder.plan( + { + lock: output({ + address: builder.scriptAddress(script), + value: { lovelace: 10_000_000n }, + datum: { type: "inline", data: mConStr0([]) }, + label: "vault", + }), + unlock: [ + spend.plutus({ + utxo: { step: "lock", output: "vault" }, + script, + redeemer: { data: mConStr0([]) }, + }), + spend.pubKey({ utxo: { step: "lock", change: true } }), + ], + }, + { payer: wallet }, ); - -const releaseTxHash = await releaseEscrow(buyerWallet, myEscrow!); -console.log(`Escrow released: ${releaseTxHash}`); +await plan.run(); // lock, a block, then unlock ``` -## Troubleshooting - -### "Script execution failed" error -- Verify the redeemer matches what the script expects -- Check that the datum is correct (inline vs hash) -- Ensure all required signers are included - -### "Missing collateral" error -- Provide collateral using `txInCollateral()` -- Collateral must be a pure ADA UTxO (no tokens) -- Recommended: at least 5 ADA for collateral - -### "Execution units exceeded" error -- The script is consuming too much resources -- Optimize your script or provide custom execution units -- Use `txInRedeemerValue(redeemer, "Mesh", { mem: X, steps: Y })` - -### "Datum hash mismatch" error -- When unlocking with datum hash, provide the exact original datum -- Ensure the datum type matches (Mesh, CBOR, or JSON) - -### "Reference script not found" error -- Verify the reference script UTxO still exists (not spent) -- Check the transaction hash and output index are correct -- Ensure the script version matches (V1, V2, or V3) - -### "Required signer missing" error -- Add `requiredSignerHash()` for scripts that check signatures -- Use partial signing: `wallet.signTx(unsignedTx, true)` - ## Related -- Transaction Basics - Core transaction building -- Minting Assets - Plutus minting policies -- Data Types - Working with datum and redeemer -- Transaction Parser - Parse and test transactions +- [Transaction Basics](/apis/txbuilder/basics) - the builder, outputs, signing and submitting +- [Mint and Burn Assets](/apis/txbuilder/minting) - native and Plutus minting policies +- [Staking Transactions](/apis/txbuilder/staking#withdraw-from-a-script) - scripts that run from withdrawals and certificates +- [Migrating to TxBuilder](/apis/txbuilder/migration) - move from the `MeshTxBuilder` chain +- [Data Types](/apis/data) - build datums and redeemers +- [Blueprints](/apis/utilities/blueprints) - get a script's code from a blueprint +- [Transaction Parser](/apis/txparser) - read and test transactions +- [Package README](https://github.com/MeshJS/mesh/tree/main/packages/mesh-transaction) - every part, option and error diff --git a/content/docs/apis/txbuilder/staking.mdx b/content/docs/apis/txbuilder/staking.mdx index d179015..b057540 100644 --- a/content/docs/apis/txbuilder/staking.mdx +++ b/content/docs/apis/txbuilder/staking.mdx @@ -1,589 +1,139 @@ --- -title: "Staking and Delegation" -description: "Delegate ADA to stake pools, register stake addresses, and withdraw staking rewards with TypeScript." +title: "Staking Transactions" +description: "Register a stake key, delegate to a pool, withdraw rewards and deregister with TxBuilder." --- -import Link from "fumadocs-core/link"; - ## Overview -Staking allows you to delegate your ADA to stake pools and earn rewards. You can register stake addresses, delegate to pools, withdraw rewards, and deregister stake addresses using `MeshTxBuilder`. - -**When to use this:** -- Delegating ADA to earn staking rewards -- Building staking dashboards or portfolio trackers -- Creating delegation services -- Implementing stake pool operations -- Building "withdraw zero" validation patterns - -## Quick Start - -```tsx -import { - MeshTxBuilder, - BlockfrostProvider, - deserializePoolId -} from "@meshsdk/core"; - -// Initialize -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -// Get wallet data -const utxos = await wallet.getUtxos(); -const changeAddress = await wallet.getChangeAddress(); -const rewardAddresses = await wallet.getRewardAddresses(); -const rewardAddress = rewardAddresses[0]!; - -// Convert pool ID to hash -const poolIdHash = deserializePoolId( - "pool1pu5jlj4q9w9jlxeu370a3c9myx47md5j5m2str0naunn2q3lkdy" -); - -// Delegate to stake pool -const unsignedTx = await txBuilder - .delegateStakeCertificate(rewardAddress, poolIdHash) - .selectUtxosFrom(utxos) - .changeAddress(changeAddress) - .complete(); - -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); -``` - -## API Reference - -### registerStakeCertificate() - -Register a stake address on the blockchain (required before first delegation). +Staking uses certificates and withdrawals, passed as parts to `builder.build()`. -```tsx -.registerStakeCertificate(rewardAddress: string) -``` +Examples stop at `build()`: call `built.sign()` and `built.submit()` as in [Transaction Basics](/apis/txbuilder/basics#build-sign-and-submit). They use `builder` and `wallet` from there, and these names, which your application defines: -| Parameter | Type | Description | -|-----------|------|-------------| -| `rewardAddress` | `string` | Bech32 reward address (stake...) | - -### delegateStakeCertificate() - -Delegate stake to a pool. - -```tsx -.delegateStakeCertificate(rewardAddress: string, poolIdHash: string) -``` +- `rewardAddress` - your stake address (`stake_test1...` on a test network, `stake1...` on mainnet) +- `poolId` - a pool id (`pool1...`) +- `stakeScript` - a Plutus staking script, `{ code, version }` +- `operatorKeyHash`, `vrfKeyHash`, `ownerKeyHash`, `metadataHash` - the values of your pool +- `operatorKey`, `epoch` - the pool's cold signing key and the retirement epoch -| Parameter | Type | Description | -|-----------|------|-------------| -| `rewardAddress` | `string` | Bech32 reward address | -| `poolIdHash` | `string` | Deserialized pool ID hash | +| Task | Part | Signed by | +|------|------|-----------| +| Register a stake key | `certificate.stakeRegistration` | the stake key | +| Delegate to a pool | `certificate.stakeDelegation` | the stake key | +| Withdraw rewards | `withdrawal.pubKey` | the stake key | +| Deregister a stake key | `certificate.stakeDeregistration` | the stake key | +| Register a pool | `certificate.poolRegistration` | the operator and owner keys | +| Retire a pool | `certificate.poolRetirement` | the operator key | -### deregisterStakeCertificate() +## Register and Delegate -Deregister a stake address and reclaim the deposit. +A stake key must be registered before it can delegate. List both certificates to do it in one transaction: they keep the order you give them. The deposit is the `keyDeposit` protocol parameter unless you pass `deposit`. `pool` is a bech32 pool id or the operator key hash. ```tsx -.deregisterStakeCertificate(rewardAddress: string) -``` - -| Parameter | Type | Description | -|-----------|------|-------------| -| `rewardAddress` | `string` | Bech32 reward address to deregister | - -### withdrawal() - -Withdraw staking rewards. +import { certificate } from "@meshsdk/core"; -```tsx -.withdrawal(rewardAddress: string, lovelace: string) +const built = await builder.build( + [ + certificate.stakeRegistration({ stake: rewardAddress }), + certificate.stakeDelegation({ stake: rewardAddress, pool: poolId }), + ], + { payer: wallet }, +); +await built.sign(); // the payer signs; the stake key too, if the wallet holds it +await built.submit(); +await built.awaitInclusion(); // waits until a block holds it ``` -| Parameter | Type | Description | -|-----------|------|-------------| -| `rewardAddress` | `string` | Bech32 reward address | -| `lovelace` | `string` | Amount to withdraw in lovelace | +If the wallet does not hold the stake key, pass the key as a signer: `built.sign({ signers: [wallet, keySigner()] })`. `built.missing` lists the keys that have not signed yet. `certificate.stakeDelegation` alone changes the delegation of a registered key, and `certificate.stakeRegistrationAndDelegation` does both in one certificate. -### withdrawalPlutusScriptV1() / V2() / V3() +## Withdraw Rewards -Indicate withdrawal from a Plutus staking script. +`amount` is the whole reward balance as a `bigint`. Use `"all"` to let the builder look it up through the provider. ```tsx -.withdrawalPlutusScriptV2() -``` - -### withdrawalScript() +import { withdrawal } from "@meshsdk/core"; -Provide the staking script for script-based withdrawal. - -```tsx -.withdrawalScript(scriptCbor: string) +const built = await builder.build( + withdrawal.pubKey({ rewardAddress, amount: "all" }), + { payer: wallet }, +); ``` -| Parameter | Type | Description | -|-----------|------|-------------| -| `scriptCbor` | `string` | CBOR-encoded staking script | +To state the amount yourself, write `amount: 5_000_000n`. It must equal the whole balance. -### withdrawalRedeemerValue() +## Deregister a Stake Key -Provide the redeemer for script-based withdrawal. +Deregistering refunds the deposit, which defaults to `keyDeposit`. Pass `refund` if the deposit paid was another amount. The reward balance must be empty, so withdraw it in the same transaction. ```tsx -.withdrawalRedeemerValue(redeemer: Data | object | string, type?: "Mesh" | "CBOR" | "JSON", exUnits?: Budget) -``` - -| Parameter | Type | Description | -|-----------|------|-------------| -| `redeemer` | `Data \| object \| string` | Redeemer value | -| `type` | `"Mesh" \| "CBOR" \| "JSON"` | Data format (default: "Mesh") | -| `exUnits` | `Budget` | Optional execution units | +import { certificate, withdrawal } from "@meshsdk/core"; -## Common Patterns - -### Register and Delegate (First Time) - -Register a stake address and delegate in a single transaction: - -```tsx -import { - MeshTxBuilder, - BlockfrostProvider, - deserializePoolId -} from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -const utxos = await wallet.getUtxos(); -const changeAddress = await wallet.getChangeAddress(); -const rewardAddresses = await wallet.getRewardAddresses(); -const rewardAddress = rewardAddresses[0]!; - -// Convert bech32 pool ID to hash -const poolIdHash = deserializePoolId( - "pool1pu5jlj4q9w9jlxeu370a3c9myx47md5j5m2str0naunn2q3lkdy" +const built = await builder.build( + [ + withdrawal.pubKey({ rewardAddress, amount: "all" }), + certificate.stakeDeregistration({ stake: rewardAddress }), + ], + { payer: wallet }, ); - -// Register and delegate in one transaction -const unsignedTx = await txBuilder - .registerStakeCertificate(rewardAddress) - .delegateStakeCertificate(rewardAddress, poolIdHash) - .selectUtxosFrom(utxos) - .changeAddress(changeAddress) - .complete(); - -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); - -console.log(`Registered and delegated: ${txHash}`); -``` - -### Change Delegation - -Switch delegation to a different pool (no registration needed): - -```tsx -import { - MeshTxBuilder, - BlockfrostProvider, - deserializePoolId -} from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -const utxos = await wallet.getUtxos(); -const changeAddress = await wallet.getChangeAddress(); -const rewardAddresses = await wallet.getRewardAddresses(); -const rewardAddress = rewardAddresses[0]!; - -// New pool to delegate to -const newPoolIdHash = deserializePoolId( - "pool1z5uqdk7dzdxaae5633fqfcu2eqzy3a3rgtuvy087fdld7yws0xt" -); - -const unsignedTx = await txBuilder - .delegateStakeCertificate(rewardAddress, newPoolIdHash) - .selectUtxosFrom(utxos) - .changeAddress(changeAddress) - .complete(); - -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); - -console.log(`Delegation changed: ${txHash}`); ``` -### Withdraw Rewards +## Withdraw from a Script -Withdraw accumulated staking rewards: +A stake address can be held by a Plutus script. Use `withdrawal.plutus` with the script and a redeemer (the data you give the script). Leave out `rewardAddress` and the builder derives the script's own address. An amount of `0n` runs the script without taking rewards, and works only while the reward balance is zero. To run the script whatever the balance, use `amount: "all"`. -```tsx -import { - MeshTxBuilder, - BlockfrostProvider -} from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -const utxos = await wallet.getUtxos(); -const changeAddress = await wallet.getChangeAddress(); -const rewardAddresses = await wallet.getRewardAddresses(); -const rewardAddress = rewardAddresses[0]!; - -// Query available rewards (in production) -// const accountInfo = await provider.fetchAccountInfo(rewardAddress); -// const withdrawableAmount = accountInfo.withdrawableAmount; - -const withdrawAmount = "5000000"; // 5 ADA in lovelace - -const unsignedTx = await txBuilder - .withdrawal(rewardAddress, withdrawAmount) - .selectUtxosFrom(utxos) - .changeAddress(changeAddress) - .complete(); - -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); - -console.log(`Rewards withdrawn: ${txHash}`); -``` - -### Deregister Stake Address - -Stop staking and reclaim the 2 ADA deposit: +A certificate of a script's stake address takes the script as its `witness`: `{ plutus, redeemer }`, which must be V3, or `{ native }`. For a native script, withdraw with `withdrawal.native`. ```tsx -import { - MeshTxBuilder, - BlockfrostProvider -} from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -const utxos = await wallet.getUtxos(); -const changeAddress = await wallet.getChangeAddress(); -const rewardAddresses = await wallet.getRewardAddresses(); -const rewardAddress = rewardAddresses[0]!; - -const unsignedTx = await txBuilder - .deregisterStakeCertificate(rewardAddress) - .selectUtxosFrom(utxos) - .changeAddress(changeAddress) - .complete(); - -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); - -console.log(`Stake deregistered, deposit reclaimed: ${txHash}`); -``` - -### Script Withdrawal +import { certificate, mConStr0, withdrawal } from "@meshsdk/core"; -Withdraw from a Plutus staking script: +const redeemer = { data: mConStr0([]) }; -```tsx -import { - MeshTxBuilder, - BlockfrostProvider, - resolveScriptHash, - serializeRewardAddress, - deserializeAddress -} from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -const utxos = await wallet.getUtxos(); -const collateral = await wallet.getCollateral(); -const changeAddress = await wallet.getChangeAddress(); - -// Your staking script CBOR -const stakeScriptCbor = "your-stake-script-cbor"; - -// Derive reward address from script -const scriptHash = resolveScriptHash(stakeScriptCbor, "V2"); -const rewardAddress = serializeRewardAddress(scriptHash, true, 0); // testnet - -const withdrawAmount = "1000000"; // 1 ADA - -const unsignedTx = await txBuilder - .withdrawalPlutusScriptV2() - .withdrawal(rewardAddress, withdrawAmount) - .withdrawalScript(stakeScriptCbor) - .withdrawalRedeemerValue("") // Your redeemer - .selectUtxosFrom(utxos) - .changeAddress(changeAddress) - .txInCollateral( - collateral[0]!.input.txHash, - collateral[0]!.input.outputIndex, - collateral[0]!.output.amount, - collateral[0]!.output.address - ) - .complete(); - -const signedTx = await wallet.signTx(unsignedTx, true); -const txHash = await wallet.submitTx(signedTx); +const built = await builder.build( + [ + withdrawal.plutus({ script: stakeScript, redeemer, amount: "all" }), + certificate.stakeDelegation({ + stake: builder.rewardAddress(stakeScript), + pool: poolId, + witness: { plutus: stakeScript, redeemer }, + }), + ], + { payer: wallet }, +); ``` -### Withdraw Zero Pattern +The script's stake address must be registered first, with `certificate.stakeRegistration` and the same `witness`. -The "withdraw zero" pattern is used to prove control of a stake key without withdrawing rewards. This is commonly used in DeFi protocols for stake key validation. +## Register a Pool -#### Step 1: Register Script Stake Key +A stake pool operator registers a pool with `certificate.poolRegistration`. `pledge` and `cost` are lovelace as text. `margin` is `[numerator, denominator]`. The operator and owner keys sign, so pass the operator key as a signer. A first registration pays the pool deposit. To update a pool that is already registered, list its operator key hash in the `registeredPools` option of `build()`, and no deposit is owed. ```tsx -import { - MeshTxBuilder, - BlockfrostProvider, - resolveScriptHash, - deserializeAddress -} from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -const utxos = await wallet.getUtxos(); -const changeAddress = await wallet.getChangeAddress(); -const { pubKeyHash } = deserializeAddress(changeAddress); - -// Parameterized staking script -const stakeScriptCbor = getAlwaysSucceedStakingScript(pubKeyHash); -const scriptHash = resolveScriptHash(stakeScriptCbor, "V2"); - -const unsignedTx = await txBuilder - .registerStakeCertificate(scriptHash) - .selectUtxosFrom(utxos) - .changeAddress(changeAddress) - .complete(); - -const signedTx = await wallet.signTx(unsignedTx, true); -const txHash = await wallet.submitTx(signedTx); - -console.log(`Script stake key registered: ${txHash}`); -``` - -#### Step 2: Withdraw Zero - -```tsx -import { - MeshTxBuilder, - BlockfrostProvider, - resolveScriptHash, - serializeRewardAddress, - deserializeAddress -} from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); - -const utxos = await wallet.getUtxos(); -const collateral = await wallet.getCollateral(); -const changeAddress = await wallet.getChangeAddress(); -const { pubKeyHash } = deserializeAddress(changeAddress); - -const stakeScriptCbor = getAlwaysSucceedStakingScript(pubKeyHash); -const scriptHash = resolveScriptHash(stakeScriptCbor, "V2"); -const rewardAddress = serializeRewardAddress(scriptHash, true, 0); - -// Withdraw zero to trigger script validation -const unsignedTx = await txBuilder - .withdrawalPlutusScriptV2() - .withdrawal(rewardAddress, "0") // Zero withdrawal - .withdrawalScript(stakeScriptCbor) - .withdrawalRedeemerValue("") - .selectUtxosFrom(utxos) - .changeAddress(changeAddress) - .txInCollateral( - collateral[0]!.input.txHash, - collateral[0]!.input.outputIndex, - collateral[0]!.output.amount, - collateral[0]!.output.address - ) - .complete(); - -const signedTx = await wallet.signTx(unsignedTx, true); -const txHash = await wallet.submitTx(signedTx); - -console.log(`Withdraw zero completed: ${txHash}`); -``` - -## Complete Example - -This example demonstrates a complete staking management workflow: +import { certificate, keySigner } from "@meshsdk/core"; -```tsx -import { - MeshTxBuilder, - BlockfrostProvider, - deserializePoolId -} from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); - -// Helper to create txBuilder -function getTxBuilder() { - return new MeshTxBuilder({ - fetcher: provider, - verbose: true, - }); -} - -// Register and delegate to a pool -async function startStaking(wallet: any, poolBech32: string) { - const txBuilder = getTxBuilder(); - - const utxos = await wallet.getUtxos(); - const changeAddress = await wallet.getChangeAddress(); - const rewardAddresses = await wallet.getRewardAddresses(); - const rewardAddress = rewardAddresses[0]!; - const poolIdHash = deserializePoolId(poolBech32); - - const unsignedTx = await txBuilder - .registerStakeCertificate(rewardAddress) - .delegateStakeCertificate(rewardAddress, poolIdHash) - .selectUtxosFrom(utxos) - .changeAddress(changeAddress) - .complete(); - - const signedTx = await wallet.signTx(unsignedTx); - return await wallet.submitTx(signedTx); -} - -// Change to a different pool -async function changePool(wallet: any, newPoolBech32: string) { - const txBuilder = getTxBuilder(); - - const utxos = await wallet.getUtxos(); - const changeAddress = await wallet.getChangeAddress(); - const rewardAddresses = await wallet.getRewardAddresses(); - const rewardAddress = rewardAddresses[0]!; - const poolIdHash = deserializePoolId(newPoolBech32); - - const unsignedTx = await txBuilder - .delegateStakeCertificate(rewardAddress, poolIdHash) - .selectUtxosFrom(utxos) - .changeAddress(changeAddress) - .complete(); - - const signedTx = await wallet.signTx(unsignedTx); - return await wallet.submitTx(signedTx); -} - -// Withdraw all rewards -async function withdrawRewards(wallet: any, amount: string) { - const txBuilder = getTxBuilder(); - - const utxos = await wallet.getUtxos(); - const changeAddress = await wallet.getChangeAddress(); - const rewardAddresses = await wallet.getRewardAddresses(); - const rewardAddress = rewardAddresses[0]!; - - const unsignedTx = await txBuilder - .withdrawal(rewardAddress, amount) - .selectUtxosFrom(utxos) - .changeAddress(changeAddress) - .complete(); - - const signedTx = await wallet.signTx(unsignedTx); - return await wallet.submitTx(signedTx); -} - -// Stop staking completely -async function stopStaking(wallet: any) { - const txBuilder = getTxBuilder(); - - const utxos = await wallet.getUtxos(); - const changeAddress = await wallet.getChangeAddress(); - const rewardAddresses = await wallet.getRewardAddresses(); - const rewardAddress = rewardAddresses[0]!; - - const unsignedTx = await txBuilder - .deregisterStakeCertificate(rewardAddress) - .selectUtxosFrom(utxos) - .changeAddress(changeAddress) - .complete(); - - const signedTx = await wallet.signTx(unsignedTx); - return await wallet.submitTx(signedTx); -} - -// Usage -const poolId = "pool1pu5jlj4q9w9jlxeu370a3c9myx47md5j5m2str0naunn2q3lkdy"; - -// Start staking -const startTxHash = await startStaking(wallet, poolId); -console.log(`Started staking: ${startTxHash}`); - -// Later, withdraw 10 ADA in rewards -const withdrawTxHash = await withdrawRewards(wallet, "10000000"); -console.log(`Withdrew rewards: ${withdrawTxHash}`); - -// Change to different pool -const newPoolId = "pool1z5uqdk7dzdxaae5633fqfcu2eqzy3a3rgtuvy087fdld7yws0xt"; -const changeTxHash = await changePool(wallet, newPoolId); -console.log(`Changed pool: ${changeTxHash}`); - -// Eventually, stop staking -const stopTxHash = await stopStaking(wallet); -console.log(`Stopped staking: ${stopTxHash}`); +const built = await builder.build( + certificate.poolRegistration({ + params: { + operator: operatorKeyHash, + vrfKeyHash, + pledge: "500000000", + cost: "340000000", + margin: [3, 100], + owners: [ownerKeyHash], + rewardAddress, + relays: [{ type: "SingleHostName", domainName: "relay.example.com", port: 3001 }], + metadata: { URL: "https://example.com/pool.json", hash: metadataHash }, + }, + }), + { payer: wallet }, +); +await built.sign({ signers: [wallet, keySigner(operatorKey)] }); ``` -## Troubleshooting - -### "Stake address not registered" error -- You must register a stake address before delegating -- Use `registerStakeCertificate()` first, or combine with delegation - -### "Pool not found" error -- Verify the pool ID is correct and the pool is active -- Use `deserializePoolId()` to convert bech32 pool IDs - -### "Insufficient funds for deposit" error -- Stake registration requires a 2 ADA deposit -- Ensure your wallet has enough ADA to cover the deposit plus fees - -### "Cannot withdraw more than available" error -- Query actual available rewards before withdrawing -- Use `provider.fetchAccountInfo(rewardAddress)` to check balance - -### "Stake address already registered" error -- Skip `registerStakeCertificate()` if already registered -- Query stake address status first to check registration - -### Script withdrawal fails -- Ensure the script stake key is registered first -- Provide valid collateral for Plutus script execution -- Check that the redeemer matches what the script expects +To retire the pool, use `certificate.poolRetirement({ pool: poolId, epoch })`. The pool retires at the start of that epoch, and the operator key signs, as above. ## Related -- Transaction Basics - Core transaction building -- Governance - DRep delegation and voting -- Providers - Query stake pool information -- Wallets - Get reward addresses +- [Transaction Basics](/apis/txbuilder/basics) - the builder, the payer and signing +- [Smart Contracts](/apis/txbuilder/smart-contracts) - Plutus scripts that spend and mint +- [Governance Transactions](/apis/txbuilder/governance) - DReps, voting and proposals +- [Migrating to TxBuilder](/apis/txbuilder/migration) - move from the `MeshTxBuilder` chain +- [Package README](https://github.com/MeshJS/mesh/tree/main/packages/mesh-transaction) - every part, option and error diff --git a/content/docs/apis/x402/withdrawal.mdx b/content/docs/apis/x402/withdrawal.mdx index c773724..a5bc0a7 100644 --- a/content/docs/apis/x402/withdrawal.mdx +++ b/content/docs/apis/x402/withdrawal.mdx @@ -17,7 +17,7 @@ x402 `/settle` is the incoming payment. Whether you then need a withdrawal depen ## Script (`script`) -x402 only checks that the lock went to **your** script, with the datum you declared. It never spends from it. Unlocking is a normal script spend you build for that contract ([MeshTxBuilder](/apis/txbuilder/smart-contract)): your redeemer, your validity window, your payouts. +x402 only checks that the lock went to **your** script, with the datum you declared. It never spends from it. Unlocking is a normal script spend you build for that contract ([TxBuilder](/apis/txbuilder/smart-contracts)): your redeemer, your validity window, your payouts. ```ts const unsigned = await new MeshTxBuilder({ fetcher: provider, evaluator: provider }) diff --git a/data/links-transactions.ts b/data/links-transactions.ts index 8993208..4c9131d 100644 --- a/data/links-transactions.ts +++ b/data/links-transactions.ts @@ -11,7 +11,7 @@ export const metaMinting = { desc: "Minting and burning assets with Native Script and Plutus Script", }; export const metaTransactionSmartContract = { - link: `/apis/txbuilder/smart-contract`, + link: `/apis/txbuilder/smart-contracts`, title: "Smart Contracts", desc: "Transactions to work with smart contracts", }; diff --git a/data/links-txbuilders.ts b/data/links-txbuilders.ts index e1af7be..844bdb4 100644 --- a/data/links-txbuilders.ts +++ b/data/links-txbuilders.ts @@ -3,27 +3,27 @@ import { BanknotesIcon } from "@heroicons/react/24/solid"; export const metaTxbuilderBasic = { link: `/apis/txbuilder/basics`, title: "Transaction Basics", - desc: "Working with transactions and their various options", + desc: "Payer, outputs, metadata, validity, signing and submitting", }; export const metaTxbuilderMinting = { link: `/apis/txbuilder/minting`, title: "Mint and Burn Assets", - desc: "Minting and burning assets with Native Script and Plutus Script", + desc: "Mint and burn assets with native and Plutus scripts", }; export const metaTxbuilderSmartContract = { - link: `/apis/txbuilder/smart-contract`, + link: `/apis/txbuilder/smart-contracts`, title: "Smart Contracts", - desc: "Transactions to work with smart contracts", + desc: "Lock, spend and read outputs at a script address", }; export const metaTxbuilderStaking = { link: `/apis/txbuilder/staking`, title: "Staking Transactions", - desc: "Transactions for delegating ADA and managing stake pools", + desc: "Register, delegate, withdraw and manage a pool", }; export const metaTxbuilderGovernance = { link: `/apis/txbuilder/governance`, title: "Governance Transactions", - desc: "Transactions for participating in Cardano's on-chain governance", + desc: "Register as a DRep, vote and submit proposals", }; export const metaTxbuilderMigration = { link: `/apis/txbuilder/migration`, @@ -42,7 +42,7 @@ export const linksTxbuilder = [ export const metaTxbuilder = { title: "Transaction Builder", - desc: "Build and sign Cardano transactions with automatic UTXO selection and fee calculation.", + desc: "Build and sign Cardano transactions with automatic UTxO selection and fee calculation.", link: "/apis/txbuilder", icon: BanknotesIcon, items: linksTxbuilder, From bbe74548afd1a7574b1dd64e6d35e781bcf380c8 Mon Sep 17 00:00:00 2001 From: lisicky Date: Sun, 22 Nov 2026 16:39:11 +0100 Subject: [PATCH 03/15] docs: migration in subpages --- .../docs/apis/txbuilder/migration/basics.mdx | 211 ++++++++++++++++ .../docs/apis/txbuilder/migration/errors.mdx | 145 +++++++++++ .../apis/txbuilder/migration/governance.mdx | 166 +++++++++++++ .../docs/apis/txbuilder/migration/index.mdx | 227 +++--------------- .../docs/apis/txbuilder/migration/meta.json | 4 + .../docs/apis/txbuilder/migration/minting.mdx | 183 ++++++++++++++ .../txbuilder/migration/smart-contracts.mdx | 195 +++++++++++++++ .../docs/apis/txbuilder/migration/staking.mdx | 146 +++++++++++ 8 files changed, 1088 insertions(+), 189 deletions(-) create mode 100644 content/docs/apis/txbuilder/migration/basics.mdx create mode 100644 content/docs/apis/txbuilder/migration/errors.mdx create mode 100644 content/docs/apis/txbuilder/migration/governance.mdx create mode 100644 content/docs/apis/txbuilder/migration/meta.json create mode 100644 content/docs/apis/txbuilder/migration/minting.mdx create mode 100644 content/docs/apis/txbuilder/migration/smart-contracts.mdx create mode 100644 content/docs/apis/txbuilder/migration/staking.mdx diff --git a/content/docs/apis/txbuilder/migration/basics.mdx b/content/docs/apis/txbuilder/migration/basics.mdx new file mode 100644 index 0000000..74c9c37 --- /dev/null +++ b/content/docs/apis/txbuilder/migration/basics.mdx @@ -0,0 +1,211 @@ +--- +title: "Migrate Transaction Basics" +description: "Move payments, metadata, validity, signers, signing and submitting from MeshTxBuilder to TxBuilder." +--- + +## Overview + +Payer, outputs, metadata and validity become parts, and signing and submitting move to `built`. This page moves them from [Transaction Builder Basics (MeshTxBuilder)](/apis/txbuilder/legacy/basics) to [Transaction Basics](/apis/txbuilder/basics). Names such as `wallet` and `builder` are explained in [Names in the Examples](/apis/txbuilder/migration#names-in-the-examples). + +## What Changes + +| Old | New | +|-----|-----| +| `new MeshTxBuilder({ fetcher: provider })`, one per transaction | `new TxBuilder({ network, provider })`, one for all. `network` is `"mainnet"`, `"preprod"`, `"preview"`, or `customNetwork(...)` for a devnet. | +| `.complete()` returns a CBOR string | `builder.build()` returns a `BuiltTx`. `built.tx` is the string. | +| `selectUtxosFrom(utxos)` | `{ payer }`. To limit or replace the built-in selection, use `canSelect` or `coinSelection`. | +| `.txIn(hash, index, amount, address)` | `spend.pubKey({ utxo })` | +| `.setFee("200000")` | the build option `fee: 200_000n` | +| `.signingKey(key)` and `.completeSigning()` | `built.sign({ signers: keySigner(key) })`. `key` is hex, bech32 such as `ed25519_sk`, or the `cborHex` of a key file. | +| `wallet.signTx(tx)` and `wallet.submitTx(signedTx)` | `built.sign()` and `built.submit()` | +| `.complete(meshTxBody)` | a list of parts. `MeshTxBuilderBody` is deprecated. | + +## Examples + +### Choose the Payer + +**Before:** + +```tsx +txBuilder.changeAddress(changeAddress).selectUtxosFrom(utxos); +``` + +**After:** + +```tsx +import { output } from "@meshsdk/core"; + +const pay = output({ address: recipient, value: { lovelace: 5_000_000n } }); + +await builder.build(pay, { payer: wallet }); // reads its UTxOs +await builder.build(pay, { payer: changeAddress }); // reads UTxOs through the provider +await builder.build(pay, { payer: { changeAddress, utxos } }); // reads nothing +``` + +The payer pays and gets the change, and without one `build()` throws `MISSING_PAYER`. The first example is on the [migration index](/apis/txbuilder/migration). + +### Send Lovelace and Assets + +**Before:** + +```tsx +const unsignedTx = await txBuilder + .txOut(recipient, [ + { unit: "lovelace", quantity: "2000000" }, + { unit, quantity: "1" }, + ]) + .txOut(partner, [{ unit: "lovelace", quantity: "3000000" }]) + .changeAddress(changeAddress).selectUtxosFrom(utxos).complete(); +``` + +**After:** + +```tsx +import { output } from "@meshsdk/core"; + +const built = await builder.build( + [ + output({ address: recipient, value: { lovelace: 2_000_000n, [unit]: 1n } }), + output({ address: partner, value: { lovelace: 3_000_000n } }), + ], + { payer: wallet }, +); +``` + +`value` maps `lovelace` and token units to `bigint`, and leaving `lovelace` out gives the output its minimum. Outputs keep their order, and a part that is `false`, `null` or `undefined` is skipped, so `condition && output(...)` works. + +### Add a Message or Metadata + +**Before:** + +```tsx +const unsignedTx = await txBuilder + .metadataValue(674, { msg: ["Invoice-No: 1234567890", "Customer-No: 555-1234"] }) + .metadataValue(1234, { order: "42" }) + .changeAddress(changeAddress).selectUtxosFrom(utxos).complete(); +``` + +**After:** + +```tsx +import { message, metadata } from "@meshsdk/core"; + +const built = await builder.build( + [ + message({ text: ["Invoice-No: 1234567890", "Customer-No: 555-1234"] }), + metadata({ metadataLabel: 1234n, value: { order: "42" } }), + ], + { payer: wallet }, +); +``` + +`message` is metadata label 674, and one label holds one entry, so do not also give `metadata` for 674. `message` cuts long text into lines, while a text over 64 bytes in `metadata` is `INVALID_DATA`. + +### Set the Validity and Require a Signer + +**Before:** + +```tsx +const untilSlot = resolveSlotNo("preprod", Date.now() + 60 * 60 * 1000); +const { pubKeyHash } = deserializeAddress(owner); + +const unsignedTx = await txBuilder + .txOut(recipient, [{ unit: "lovelace", quantity: "5000000" }]) + .invalidHereafter(Number(untilSlot)) + .requiredSignerHash(pubKeyHash) + .changeAddress(changeAddress).selectUtxosFrom(utxos).complete(); +``` + +**After:** + +```tsx +import { guard, output, validity } from "@meshsdk/core"; + +const built = await builder.build( + [ + output({ address: recipient, value: { lovelace: 5_000_000n } }), + validity({ until: Date.now() + 60 * 60_000 }), // expires in one hour + guard.pubKey({ address: owner }), // or { keyHash: pubKeyHash } + ], + { payer: wallet }, +); +``` + +`validity` takes milliseconds (`from` and `until`), so `resolveSlotNo` is not needed, and slots still work as `invalidBefore` and `invalidHereafter`. `build()` sets no deadline, so give `until` when the transaction must expire. + +### Build, Sign and Submit + +**Before:** + +```tsx +const signedTx = await wallet.signTx(unsignedTx); +const txHash = await wallet.submitTx(signedTx); +``` + +**After:** + +```tsx +await built.sign(); // the payer signs +await built.submit(); // through the provider +console.log(built.txHash); // known before signing +const { slot } = await built.awaitInclusion(); // found in a block +// to send through the wallet: await built.submit({ submitter: wallet }) +``` + +- `build()` signs and sends nothing, and `built.tx` is the string `complete()` returned. +- `sign()` is partial by default, so there is no flag. `submit()` sends the same bytes every time: repeat it to retry, and never build again. +- For several dependent transactions, or a payment to follow to `final` or keep across a crash, use `builder.plan()`. See [Plan Several Transactions](/apis/txbuilder/basics#plan-several-transactions). + +### Sign with a Key or Several Signers + +**Before:** + +```tsx +const signedTx1 = await wallet.signTx(unsignedTx, true); +const signedTx2 = await mintingWallet.signTx(signedTx1, true); +const txHash = await wallet.submitTx(signedTx2); +``` + +**After:** + +```tsx +await built.sign({ signers: [wallet, mintingWallet] }); +await built.submit(); +``` + +- Each signer is asked once, in order, for the keys still missing. A key from a file joins the list as `keySigner(key)`. +- `submit()` throws `MISSING_SIGNATURES` while `built.missing` is not empty. + +### Build Offline + +**Before:** + +```tsx +import { MeshTxBuilder } from "@meshsdk/core"; + +const offlineTxBuilder = new MeshTxBuilder({ params }); +const unsignedTx = await offlineTxBuilder + .txOut(recipient, [{ unit: "lovelace", quantity: "5000000" }]) + .changeAddress(changeAddress).selectUtxosFrom(utxos).complete(); +``` + +**After:** + +```tsx +import { output, TxBuilder } from "@meshsdk/core"; + +const offline = new TxBuilder({ network: "preprod", params, costModels }); // reads nothing +const built = await offline.build( + output({ address: recipient, value: { lovelace: 5_000_000n } }), + { payer: { changeAddress, utxos } }, +); +``` + +- Without a `provider`, give `params`, and `costModels` for a Plutus script, or the builder throws `MISSING_PARAMETER`. +- `params` must be a whole `Protocol`. The old builder filled missing fields with built-in values, and a partial object is `INVALID_OPTION`. +- `JSON.stringify(built)` saves the transaction, and `await builder.restore(JSON.parse(saved))` brings it back in another process. + +## Related + +- [Migrate Minting and Burning](/apis/txbuilder/migration/minting) - the next area +- [Migrating to TxBuilder](/apis/txbuilder/migration) - the four steps and the names diff --git a/content/docs/apis/txbuilder/migration/errors.mdx b/content/docs/apis/txbuilder/migration/errors.mdx new file mode 100644 index 0000000..a9b1200 --- /dev/null +++ b/content/docs/apis/txbuilder/migration/errors.mdx @@ -0,0 +1,145 @@ +--- +title: "Migration Errors and Differences" +description: "Error codes a migrated build may throw, and what changes if you keep MeshTxBuilder." +--- + +## Overview + +This page lists the error codes a migrated build may throw, and what changes if you keep `MeshTxBuilder`. The new builder's errors are also in [Handle Errors](/apis/txbuilder/basics#handle-errors), and the old builder's in [Transaction Builder Basics (MeshTxBuilder)](/apis/txbuilder/legacy/basics). Names such as `wallet` and `builder` are explained in [Names in the Examples](/apis/txbuilder/migration#names-in-the-examples). + +## Check the Code, Not the Message + +Every error is a `TxError` with a `code`. Old message text is gone, so code that matched on it must match on the code now. + +**Before:** + +```tsx +try { + await txBuilder + // ... the chain + .complete(); +} catch (error) { + if (error instanceof Error && error.message.startsWith("Evaluate redeemers failed")) { + console.log(error.message); + } else throw error; +} +``` + +**After:** + +```tsx +import { TxError } from "@meshsdk/core"; + +try { + const built = await builder.build(parts, { payer: wallet }); + await built.sign(); + await built.submit(); +} catch (error) { + if (TxError.is(error, "INSUFFICIENT_FUNDS")) { + console.log(error.details.unit, error.details.missing); // typed by the code + } else if (TxError.is(error, "EVALUATION_FAILED")) { + console.log(error.details.failures); + } else throw error; +} +``` + +`TxError.is` also checks errors from another copy of the package. These old messages now come as codes: + +| Old message | New code | +|-------------|----------| +| "Change address is not set, utxo selection cannot be done without this" | `MISSING_PAYER` | +| "Transaction information is incomplete while no fetcher instance is provided" | `MISSING_FETCHER` | +| "Couldn't find value information for txHash#txIndex" | `UTXO_NOT_FOUND` | +| "Evaluate redeemers failed" | `EVALUATION_FAILED` | + +## Error Codes + +### Setup + +| Code | Fix | +|------|-----| +| `MISSING_PAYER` | Pass `{ payer }` to `build()` or `plan()`. There is no default payer. | +| `INVALID_OPTION` | Use `"mainnet"`, `"preprod"`, `"preview"` or `customNetwork(...)` as `network`, and give a key through `keySigner(key)`. `error.details` names the option. | +| `MISSING_PARAMETER` | Give a `provider`, or `params` and `costModels`. For governance, give `deposits`. | +| `MISSING_FETCHER` | Give a `provider`, or pass UTxOs in full. | +| `NETWORK_MISMATCH` | An address, wallet or provider is on another network than `network`. | + +### Build + +| Code | Fix | +|------|-----| +| `INVALID_VALUE` | An amount in a record value, a mint, a withdrawal or a deposit is a string or a number. Use `bigint`: `5_000_000n`. An `Asset[]` value in `output` keeps its string quantities. It is thrown at the part call. | +| `INVALID_DATA` | Metadata text over 64 bytes, or a validity bound given two ways. Use `message({ text })`, which cuts long text. | +| `OUTPUT_BELOW_MIN_COIN` | Raise the output's lovelace, or leave `lovelace` out. `error.details` gives `coin` and `minCoin`. | +| `INSUFFICIENT_FUNDS` | The payer cannot cover it. `error.details` names the unit and the amount missing. | +| `INSUFFICIENT_COLLATERAL` | Drop `topUpCollateral: false`, or give a larger `collateral({ utxo })`. | +| `DUPLICATE_PART` | One mint part per policy, one `validity`, one `message`. The same input twice is also refused. | +| `UTXO_NOT_FOUND` | The output does not exist, is spent, or the provider has not seen it yet. Pass the UTxO in full, or use `knownUtxos`. | +| `WITNESS_MISMATCH` | Use `spend.plutus` or `spend.native` for a script output, and `spend.pubKey` for a key output. | +| `DATUM_MISMATCH` | The output holds a datum hash: pass `datum: { data }` with the datum it was locked with. Data given must hash to it, and for an inline datum leave `datum` out. | +| `EVALUATION_FAILED` | A script failed. Give each part a `label`: `error.details.failures` names the part. | +| `EXUNITS_TOO_LOW` | Leave `exUnits` out. The builder evaluates them. | +| `TX_TOO_LARGE` | Split the parts, for example into the steps of `builder.plan({ first: partsA, second: partsB }, { payer })`. | +| `FEE_TOO_LOW` | Drop the `fee` option, or give a higher one. A given fee is never raised. | + +### Sign and Submit + +| Code | Fix | +|------|-----| +| `MISSING_SIGNATURES` | A key has not signed. `built.missing` lists the keys, and a stake registration needs the stake key. Nothing was sent. | +| `MISSING_SUBMITTER` | Give the builder a `provider` or a `submitter`, or call `built.submit({ submitter: wallet })`. | +| `SIGN_DECLINED`, `SIGNER_FAILED` | The user declined, or the signer failed. After an account change, connect again and pass the new api as `signers`. | +| `SUBMIT_FAILED`, `CONFIRM_TIMEOUT` | The outcome is unknown. Repeat the same call on the same `BuiltTx`, and never build again. | +| `CANNOT_OBSERVE` | `plan()` needs block heights, and `awaitInclusion()` of a transaction that runs a Plutus script needs the provider's validity flag. The plain `BlockfrostProvider` gives neither. For a plain port use `build()`, `sign()` and `submit()`. | + +## If You Keep MeshTxBuilder + +`MeshTxBuilder` builds on `TxBuilder`. Its methods and signatures are kept, but the final CBOR may differ, and messages are not the old ones. + +### What Changes + +It throws where it used to return a transaction the ledger refuses: `OUTPUT_BELOW_MIN_COIN`, `FEE_TOO_LOW`, `NETWORK_MISMATCH`, `DATUM_MISMATCH`, `INVALID_DATA`. Other behavior differs as follows: + +| Behavior | `MeshTxBuilder` | `TxBuilder` | +|----------|-----------------|-------------| +| Network | Guessed from the fetcher, `setNetwork()` or the change address | `network` is required | +| Protocol parameters | Built-in values when nobody can be asked | `MISSING_PARAMETER` | +| Repeats | Exact repeats of one input merge, and so do `.mint(...)` calls of one policy. Two entries that differ in a field are `DUPLICATE_PART`. | `DUPLICATE_PART` | +| Collateral | Every Plutus transaction gets collateral, total collateral and a return. Collateral from `txInCollateral` is used as given: too small is `INSUFFICIENT_COLLATERAL`. | Topped up by default | +| Evaluation | With a fetcher and no `evaluator`, scripts run in a local evaluator. A script input the provider does not know yet is `UTXO_NOT_FOUND`: give it with `chainTx` or `inputForEvaluation`, or pass `evaluator: null`. With no evaluator, the redeemers keep the units of the calls. | Redeemer units are taken unchecked only with `evaluator: null` | + +- `serializer` and `selector` accept only Mesh's own. Anything else is `INVALID_OPTION` at construction. +- `completeSync()`, `completeUnbalanced()` and `completeUnbalancedSync()` read nothing. An input or collateral without amount or address, or a reference script without size, is `UNRESOLVED`. +- `reset()` also clears a fee set with `setFee()`. +- The deposit defaults and `registerStakeCertificate` also differ. See [Migrate Governance](/apis/txbuilder/migration/governance) and [Migrate Staking](/apis/txbuilder/migration/staking). + +On a test network, pass `network`, because a script transaction with a validity interval on a network nothing names is `EVALUATION_FAILED`: + +```tsx +import { MeshTxBuilder } from "@meshsdk/core"; + +const txBuilder = new MeshTxBuilder({ fetcher: provider, network: "preprod" }); // add network +``` + +### Removed and Deprecated Members + +These members are removed or deprecated: + +| Member | State | Replacement | +|--------|-------|-------------| +| `selectUtxos` | removed | `builder.build(parts, { payer })`: selection is the builder's | +| `updateByTxPrototype` | removed | `complete()` writes the body back | +| `getUtxosForSelection` | removed | `(await builder.readPayer(payer)).utxos`, or `selectUtxosFrom()` | +| `completeCostModels` | removed | the `costModels` option, or the provider | +| `evaluateRedeemers` | removed | the builder evaluates the balanced transaction. See the `evaluator` option. | +| `sortTxParts`, `sortInputs`, `sortMints`, `sortWithdrawals`, `sortVotes`, `sortProposals` | removed | the builder orders every item by the ledger's rules | +| the protected members, such as `completeTxParts` and `sanitizeOutputs` | removed | none | +| `calculateMinLovelaceForOutput`, `calculateFee`, `getActualFee`, `getTotalExecutionUnits` and the like | kept | for new code: `minCoin`, `minFee`, `built.fee` and `built.exUnits` | +| `txEvaluationMultiplier` | kept, deprecated | multiplies nothing | +| `MeshTxBuilderBody`, `emptyTxBuilderBody`, `cloneTxBuilderBody`, `serializeTxBody` | kept, deprecated | a list of parts | + +## Related + +- [Migrating to TxBuilder](/apis/txbuilder/migration) - the four steps and the names +- [Migrate Transaction Basics](/apis/txbuilder/migration/basics) - payer, outputs, signing and submitting +- [Package README](https://github.com/MeshJS/mesh/tree/main/packages/mesh-transaction) - every error code with its details diff --git a/content/docs/apis/txbuilder/migration/governance.mdx b/content/docs/apis/txbuilder/migration/governance.mdx new file mode 100644 index 0000000..98e088c --- /dev/null +++ b/content/docs/apis/txbuilder/migration/governance.mdx @@ -0,0 +1,166 @@ +--- +title: "Migrate Governance" +description: "Move DRep registration, vote delegation, votes, proposals and deposits from MeshTxBuilder to TxBuilder." +--- + +## Overview + +Each governance call becomes a `certificate.*`, `vote` or `proposal.*` part. This page moves them from [Governance Transactions (MeshTxBuilder)](/apis/txbuilder/legacy/governance) to [Governance Transactions](/apis/txbuilder/governance). Names such as `wallet` and `builder` are explained in [Names in the Examples](/apis/txbuilder/migration#names-in-the-examples). + +## What Changes + +| Old | New | +|-----|-----| +| `{ dRepId }`, `{ alwaysAbstain: null }`, `{ alwaysNoConfidence: null }` | `drepId`, `"alwaysAbstain"`, `"alwaysNoConfidence"` | +| `{ anchorUrl, anchorDataHash }` | `{ url, dataHash }` | +| voter `{ type: "DRep", drepId }`, `{ type: "StakingPool", keyHash }`, `{ type: "ConstitutionalCommittee", hotCred }` | `{ drep: drepId }`, `{ pool: keyHash }`, `{ committee: { type: "KEY", value: keyHash } }` (or `"SCRIPT"`, or a reward address) | +| credential `{ type: "KeyHash", keyHash }`, `{ type: "ScriptHash", scriptHash }` | `{ type: "KEY", value }`, `{ type: "SCRIPT", value }` | +| `{ voteKind: "Yes" }`, `"No"`, `"Abstain"` | `vote: "yes"`, `"no"`, `"abstain"` | +| governance action id `{ txHash, txIndex }` | `{ txHash, index }` | +| `.votePlutusScriptV3().vote(...).voteScript(code).voteRedeemerValue(r)` | `vote({ ..., witness: { plutus: { code, version: "V3" }, redeemer: { data: r } } })`. No `txIn` or collateral call. | +| `.drepUpdateCertificate(drepId, { anchorUrl, anchorDataHash })` | `certificate.drepUpdate({ drep: drepId, anchor })`. Leave out `anchor` to clear it. | +| `.drepDeregistrationCertificate(drepId)` | `certificate.drepDeregistration({ drep: drepId })`. The refund is `drepDeposit`, or `refund` if the deposit paid was another amount. | + +The DRep key signs DRep certificates and votes: a `MeshWallet` does, and a browser wallet must be connected with CIP-95. The stake key signs a vote delegation. See [Sign with a Key or Several Signers](/apis/txbuilder/migration/basics#sign-with-a-key-or-several-signers). + +## Examples + +### Delegate Your Vote + +**Before:** + +```tsx +const unsignedTx = await txBuilder + .voteDelegationCertificate({ dRepId: drepId }, rewardAddress) + .changeAddress(changeAddress).selectUtxosFrom(utxos).complete(); +``` + +**After:** + +```tsx +import { certificate } from "@meshsdk/core"; + +const built = await builder.build( + certificate.voteDelegation({ stake: rewardAddress, drep: drepId }), // or "alwaysAbstain" + { payer: wallet }, +); +``` + +`drep` is a DRep id, `"alwaysAbstain"` or `"alwaysNoConfidence"`. + +### Register as a DRep + +**Before:** + +```tsx +const unsignedTx = await txBuilder + .drepRegistrationCertificate(drepId, { + anchorUrl: anchor.url, + anchorDataHash: anchor.dataHash, + }) + .changeAddress(changeAddress).selectUtxosFrom(utxos).complete(); +``` + +**After:** + +```tsx +import { certificate } from "@meshsdk/core"; + +const built = await builder.build( + certificate.drepRegistration({ drep: drepId, anchor }), // the deposit is drepDeposit + { payer: wallet }, +); +``` + +`hashDrepAnchor` is unchanged. Updating and retiring a DRep are rows of [What Changes](#what-changes). + +### Set the Deposits + +**Before:** + +```tsx +// Left out, the deposit was 500 ADA for a DRep and 100,000 ADA for a proposal +txBuilder.drepRegistrationCertificate(drepId); +``` + +**After:** + +```tsx +import { TxBuilder } from "@meshsdk/core"; + +const builder = new TxBuilder({ + network: "preprod", + provider, + deposits: { drepDeposit: 500_000_000n, govActionDeposit: 100_000_000_000n }, +}); +``` + +The new parts have no default: without `deposits` on the builder or `deposit` on the part, the build throws `MISSING_PARAMETER`. Use the values of your network. + +### Vote on an Action + +**Before:** + +```tsx +const unsignedTx = await txBuilder + .vote( + { type: "DRep", drepId }, + { txHash: actionTx, txIndex: 0 }, + { voteKind: "Yes" }, + ) + .changeAddress(changeAddress).selectUtxosFrom(utxos).complete(); +``` + +**After:** + +```tsx +import { vote } from "@meshsdk/core"; + +const built = await builder.build( + vote({ + voter: { drep: drepId }, + votes: [{ action: { txHash: actionTx, index: 0 }, vote: "yes" }], // anchor: optional rationale + }), + { payer: wallet }, +); +``` + +One `vote` part holds all the votes of one voter. + +### Submit a Proposal + +**Before:** + +```tsx +const unsignedTx = await txBuilder + .proposal( + { kind: "InfoAction", action: {} }, + { anchorUrl: anchor.url, anchorDataHash: anchor.dataHash }, + rewardAddress, + ) + .changeAddress(changeAddress).selectUtxosFrom(utxos).complete(); +``` + +**After:** + +```tsx +import { proposal } from "@meshsdk/core"; + +const built = await builder.build( + proposal.info({ rewardAccount: rewardAddress, anchor }), + { payer: wallet }, +); +``` + +The deposit is `govActionDeposit`, or `deposit` on the part, and goes back to `rewardAccount`. The other actions keep their data and change shape: + +| Old | New | +|-----|-----| +| `TreasuryWithdrawalsAction` with `withdrawals: { [rewardAddress]: "50000000000" }` | `proposal.treasuryWithdrawals({ rewardAccount, anchor, withdrawals: { [rewardAddress]: 50_000_000_000n } })` | +| `NoConfidenceAction` with `govActionId: { transactionId, govActionIndex }` | `proposal.noConfidence({ rewardAccount, anchor, previous: { txHash, index } })` | +| `ParameterChangeAction`, `UpdateCommitteeAction`, `NewConstitutionAction`, `HardForkInitiationAction` | `proposal.parameterChange`, `proposal.updateCommittee`, `proposal.newConstitution`, `proposal.hardForkInitiation`. The old `govActionId` is `previous`. `updates` of a parameter change uses the ledger's snake_case names. | + +## Related + +- [Migration Errors and Differences](/apis/txbuilder/migration/errors) - the next page: error codes and what changes if you keep `MeshTxBuilder` +- [Migrating to TxBuilder](/apis/txbuilder/migration) - the four steps and the names diff --git a/content/docs/apis/txbuilder/migration/index.mdx b/content/docs/apis/txbuilder/migration/index.mdx index c7ad81d..04c68ed 100644 --- a/content/docs/apis/txbuilder/migration/index.mdx +++ b/content/docs/apis/txbuilder/migration/index.mdx @@ -5,22 +5,23 @@ description: "Move code from the deprecated MeshTxBuilder chain to TxBuilder par ## Overview -A transaction is now a list of parts, such as `output(...)` or `mint.native(...)`. Pass the list to `builder.build()`. The builder picks inputs, adds change and sets the fee. Then you sign and submit. `MeshTxBuilder` is deprecated but still works. All new names come from `@meshsdk/core`. +A transaction is now a list of parts, such as `output(...)` or `mint.native(...)`. You give the list and a payer to `builder.build()`, and the builder picks inputs, adds change and sets the fee. `MeshTxBuilder` is deprecated but still works. Import the new names from `@meshsdk/core`, which re-exports `@meshsdk/transaction`. -Even if you do not migrate, `MeshTxBuilder` now runs on `TxBuilder`, so it can throw `OUTPUT_BELOW_MIN_COIN`, `FEE_TOO_LOW`, `NETWORK_MISMATCH` and `DATUM_MISMATCH` where it used to return a transaction the ledger refused. +`ForgeScript`, `mConStr0`, `resolveScriptHash` and the other Data and script helpers do not change. Before blocks use them without an import. -To move a transaction: +## The Four Steps -1. Make one `TxBuilder`. -2. Turn each chain into parts. -3. Replace sign and submit. -4. Check error codes. +1. Make one `TxBuilder` with a `network` and a `provider`. See [Basics](/apis/txbuilder/migration/basics). +2. Turn each chain into a list of parts, one area at a time: + - [Basics](/apis/txbuilder/migration/basics) - payer, outputs, metadata, validity, signers, signing and submitting + - [Minting](/apis/txbuilder/migration/minting) - mint and burn with native and Plutus scripts + - [Smart Contracts](/apis/txbuilder/migration/smart-contracts) - lock funds at a script and spend from it + - [Staking](/apis/txbuilder/migration/staking) - register, delegate and withdraw + - [Governance](/apis/txbuilder/migration/governance) - DRep certificates, votes and proposals +3. Replace `signTx` and `submitTx` with `sign()` and `submit()`. See [Build, Sign and Submit](/apis/txbuilder/migration/basics#build-sign-and-submit). +4. Check the error codes. See [Migration Errors and Differences](/apis/txbuilder/migration/errors). -Examples assume `wallet`, `provider`, `utxos`, `changeAddress` and `recipient` exist. - -## What Changes - -### Before and After +## A Payment, Before and After **Before:** @@ -31,9 +32,7 @@ const txBuilder = new MeshTxBuilder({ fetcher: provider }); const unsignedTx = await txBuilder .txOut(recipient, [{ unit: "lovelace", quantity: "5000000" }]) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos) - .complete(); + .changeAddress(changeAddress).selectUtxosFrom(utxos).complete(); const signedTx = await wallet.signTx(unsignedTx); const txHash = await wallet.submitTx(signedTx); ``` @@ -54,192 +53,42 @@ await built.submit(); console.log(built.txHash); ``` -### Old to New +Three rules hold on every page: | Old | New | |-----|-----| -| `new MeshTxBuilder({ fetcher })`, one per transaction | `new TxBuilder({ network, provider })`. `network` is required. One builder serves every transaction. | -| `.txOut()`, `.mint()`, `.txIn()` in a chain | One part per call, in a list: `output`, `mint.native`, `spend.plutus`, ... | +| A chain: `.txOut()`, `.mint()`, `.txIn()` | A list of parts: `output`, `mint.native`, `spend.plutus`, ... | | `.changeAddress()` and `.selectUtxosFrom()` | `{ payer }`: a wallet, an address, or `{ changeAddress, utxos }` | -| `.complete()` returns a CBOR string | `builder.build()` returns a `BuiltTx`. `built.tx` is the string. | | Amounts as strings: `"5000000"` | Amounts as `bigint`: `5_000_000n` | -| `mintPlutusScriptV2()` and friends | Not needed. The version is in `script`. | -| `txInInlineDatumPresent()`, `txInCollateral()`, execution units | Not needed. The builder reads the datum, picks collateral and evaluates units. | -| `.mintPlutusScriptV2().mint(...).mintingScript(code).mintRedeemerValue(r)` | `mint.plutus({ script, redeemer: { data: r }, assets })` | -| `.metadataValue(674, { msg: [...] })` | `message({ text })`. For another label: `metadata({ metadataLabel: 721n, value })` | -| `.requiredSignerHash(hash)` | `guard.pubKey({ address })`, or `{ keyHash }` | -| `.invalidHereafter(slot)` | `validity({ until: ms })`. It takes milliseconds, so `resolveSlotNo` is not needed. Slots still work with `invalidBefore` and `invalidHereafter`. | -| `.voteDelegationCertificate(drep, address)` | `certificate.voteDelegation({ stake, drep })`. `drep` can be `"alwaysAbstain"`. | -| `.drepRegistrationCertificate(id, anchor)` | `certificate.drepRegistration({ drep, anchor, deposit })`. The old call assumed the deposit. Now give `deposit`, or `deposits` to `new TxBuilder`. | -| `wallet.signTx(tx)` and `wallet.signTx(tx, true)` | `built.sign()`. Signing is partial by default, so there is no flag. | -| `.signingKey(skey)` and `.completeSigning()` | `built.sign({ signers: keySigner(skey) })` | -| `wallet.submitTx(signedTx)` | `built.submit()`. The hash is `built.txHash`, known before signing. | - -## Examples - -### Mint and Burn with a Native Script - -**Before:** - -```tsx -const forgingScript = ForgeScript.withOneSignature(changeAddress); -const policyId = resolveScriptHash(forgingScript); - -const unsignedTx = await txBuilder - .mint("1", policyId, stringToHex("MeshToken")) // burn: "-1" - .mintingScript(forgingScript) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos) - .complete(); -``` - -**After:** - -```tsx -import { ForgeScript, mint, stringToHex } from "@meshsdk/core"; - -const forgingScript = ForgeScript.withOneSignature(changeAddress); -const tokenNameHex = stringToHex("MeshToken"); - -const built = await builder.build( - mint.native({ script: forgingScript, assets: { [tokenNameHex]: 1n } }), // burn: -1n - { payer: wallet }, -); -``` - -The policy id comes from the script. Use one mint part per policy and put every asset name in its `assets`: a second part of the same policy is `DUPLICATE_PART`. - -### Spend from a Plutus Script with a Reference Script - -**Before:** - -```tsx -const unsignedTx = await txBuilder - .spendingPlutusScriptV2() - .txIn(assetUtxo.input.txHash, assetUtxo.input.outputIndex) - .txInInlineDatumPresent() - .txInRedeemerValue(mConStr0([])) - .spendingTxInReference(refTxHash, 0) // the script sits in a reference output - .txInCollateral( - collateral.input.txHash, - collateral.input.outputIndex, - collateral.output.amount, - collateral.output.address, - ) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos) - .complete(); -``` - -**After:** - -```tsx -import { mConStr0, spend } from "@meshsdk/core"; - -const built = await builder.build( - spend.plutus({ - utxo: assetUtxo, - script: { reference: { txHash: refTxHash, outputIndex: 0 } }, - redeemer: { data: mConStr0([]) }, - }), - { payer: wallet }, -); -``` - -The builder reads the datum from the output, so `txInInlineDatumPresent()` is gone. For an output that holds a datum hash, add `datum: { data: myDatum }` where the old code called `txInDatumValue(myDatum)`. - -### Stake: Register, Delegate and Withdraw - -**Before:** - -```tsx -const poolId = "pool1pu5jlj4q9w9jlxeu370a3c9myx47md5j5m2str0naunn2q3lkdy"; - -const registerTx = await txBuilder - .registerStakeCertificate(rewardAddress) - .delegateStakeCertificate(rewardAddress, deserializePoolId(poolId)) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos) - .complete(); - -txBuilder.reset(); // one chain per transaction -const withdrawTx = await txBuilder - .withdrawal(rewardAddress, "5000000") - .changeAddress(changeAddress) - .selectUtxosFrom(utxos) - .complete(); -``` - -**After:** - -```tsx -import { certificate, withdrawal } from "@meshsdk/core"; - -const registerTx = await builder.build( - [ - certificate.stakeRegistration({ stake: rewardAddress }), - certificate.stakeDelegation({ stake: rewardAddress, pool: poolId }), - ], - { payer: wallet }, -); - -const withdrawTx = await builder.build( - withdrawal.pubKey({ rewardAddress, amount: 5_000_000n }), - { payer: wallet }, -); -``` - -> **Note:** `stakeRegistration` is not the old certificate. It states the deposit and the stake key must sign. - -Give the pool id as it is: no `deserializePoolId`. `amount` is a `bigint`, and it must be the whole reward balance. `amount: "all"` looks the balance up for you. - -## Signing and Submitting - -```tsx -// build(): wait for a block after submit() -const { slot } = await built.awaitInclusion(); - -// plan(): sign, submit and wait in one call -const plan = await builder.plan(parts, { payer: wallet }); -await plan.run(); -console.log(plan.step("main").txHash); -``` - -`plan()` sends several transactions in order and tracks each one. A one-to-one port only needs `build()`. - -**Remember:** - -- `submit()` goes through the provider, not the wallet. Pass `{ submitter: wallet }` to send through the wallet. -- Never rebuild a transaction to retry it. A new build may pick other inputs, and both could land. Call `submit()` again on the same `BuiltTx`. -- `plan()` needs a provider that returns block heights, and `awaitInclusion()` of a Plutus transaction needs the validity flag. The plain `BlockfrostProvider` has neither. - -## Troubleshooting -### If You Keep MeshTxBuilder +## If You Keep MeshTxBuilder -- Error messages differ from before, and so may the final CBOR. -- Every Plutus transaction gets collateral and a collateral return. Collateral from `txInCollateral` is used as given. -- On a test network, script transactions with a validity interval need `new MeshTxBuilder({ network: "preprod", fetcher })`. -- Internal helpers such as `selectUtxos` and `sortInputs` were removed. The builder does that work. +`MeshTxBuilder` now runs on `TxBuilder`, so it throws some errors where it used to return a transaction the ledger refused, such as `OUTPUT_BELOW_MIN_COIN` and `FEE_TOO_LOW`. See [If You Keep MeshTxBuilder](/apis/txbuilder/migration/errors#if-you-keep-meshtxbuilder). -### Error Codes +## Names in the Examples -Check the code, not the message: `TxError.is(error, "MISSING_SIGNATURES")`. +Your application defines these names. Every page of this guide uses them the same way. -| Code | Fix | -|------|-----| -| `MISSING_PAYER` | Pass `{ payer }` to `build()` or `plan()`. | -| `MISSING_PARAMETER` | Give a `provider`, or `params` and `costModels`. For governance, give `deposits`. | -| `OUTPUT_BELOW_MIN_COIN` | Raise the output's lovelace, or leave `lovelace` out. | -| `NETWORK_MISMATCH` | An address, wallet or provider is on another network than `network`. | -| `INSUFFICIENT_FUNDS` | The payer cannot cover it. `error.details` names the unit and the amount missing. | -| `DUPLICATE_PART` | One mint part per policy, one `validity`, one `message`. The same input twice is also refused. | -| `UTXO_NOT_FOUND` | The output does not exist, is spent, or the provider has not seen it yet. Pass the UTxO in full. | -| `MISSING_SIGNATURES` | A key has not signed. `built.missing` lists the keys. A stake registration needs the stake key. | -| `EVALUATION_FAILED` | A script failed. `error.details.failures` names the part and its label. | -| `CANNOT_OBSERVE` | `plan()` needs block heights. `awaitInclusion()` needs the transaction search and, for a Plutus transaction, the validity flag. `build()` and `submit()` need none of these. | +| Name | What it is | +|------|------------| +| `txBuilder` | the old builder: `new MeshTxBuilder({ fetcher: provider })` | +| `builder` | the new builder: `new TxBuilder({ network: "preprod", provider })` | +| `provider` | a provider, such as `BlockfrostProvider` | +| `wallet`, `mintingWallet`, `utxos`, `changeAddress` | wallets that sign (a `MeshWallet`, a `BrowserWallet` or a CIP-30 api), and the UTxOs and the change address of `wallet` | +| `recipient`, `partner`, `owner`, `rewardAddress` | addresses. `rewardAddress` is a stake address. | +| `assetUtxo`, `collateralUtxo` | UTxOs from a provider or a wallet | +| `script`, `policyCode` | a Plutus script (`{ code, version }`) and the CBOR of a policy script | +| `refTxHash` | the hash of a transaction that holds a reference script | +| `unit` | a token unit: policy id plus asset name in hex | +| `key` | the text of a signing key | +| `params`, `costModels` | protocol parameters and cost models | +| `drepId`, `poolId`, `actionTx`, `anchor` | a DRep id, a pool id, the transaction hash of a governance action, and an anchor `{ url, dataHash }` | +| `parts` | a list of parts | +| `built`, `unsignedTx` | the `BuiltTx` from `build()` and the string from `complete()`, where an example starts from them | ## Related +- [Cardano Transaction Builder](/apis/txbuilder) - the pages for `TxBuilder` +- [MeshTxBuilder (deprecated)](/apis/txbuilder/legacy) - the pages for `MeshTxBuilder` - [Skills](/ai/skills) - install the `mesh-tx-builder-migration` skill - [Package README](https://github.com/MeshJS/mesh/tree/main/packages/mesh-transaction) - the `@meshsdk/transaction` guide diff --git a/content/docs/apis/txbuilder/migration/meta.json b/content/docs/apis/txbuilder/migration/meta.json new file mode 100644 index 0000000..8568ad5 --- /dev/null +++ b/content/docs/apis/txbuilder/migration/meta.json @@ -0,0 +1,4 @@ +{ + "title": "Migrating to TxBuilder", + "pages": ["basics", "minting", "smart-contracts", "staking", "governance", "errors"] +} diff --git a/content/docs/apis/txbuilder/migration/minting.mdx b/content/docs/apis/txbuilder/migration/minting.mdx new file mode 100644 index 0000000..81aa0aa --- /dev/null +++ b/content/docs/apis/txbuilder/migration/minting.mdx @@ -0,0 +1,183 @@ +--- +title: "Migrate Minting and Burning" +description: "Move minting, burning and NFT metadata from the MeshTxBuilder chain to TxBuilder parts." +--- + +## Overview + +Each `.mint()` chain becomes one `mint.native` or `mint.plutus` part, and metadata is a part of its own. This page moves them from [Minting and Burning Assets (MeshTxBuilder)](/apis/txbuilder/legacy/minting) to [Mint and Burn Assets](/apis/txbuilder/minting). Names such as `wallet` and `builder` are explained in [Names in the Examples](/apis/txbuilder/migration#names-in-the-examples). + +## What Changes + +| Old | New | +|-----|-----| +| `.mint("1", policyId, nameHex).mintingScript(script)` | `mint.native({ script, assets: { [nameHex]: 1n } })` | +| `.mint("-1", policyId, nameHex)` | `assets: { [nameHex]: -1n }`. A negative quantity burns. | +| `.mintPlutusScriptV2().mint(...).mintingScript(code).mintRedeemerValue(r)` | `mint.plutus({ script: { code, version: "V2" }, redeemer: { data: r }, assets })` | +| `.mintTxInReference(hash, index)` | `script: { reference: { txHash, outputIndex } }` on `mint.plutus` | +| `.metadataValue(721, nft)` | `metadata({ metadataLabel: 721n, value: nft })`. The label is a `bigint`, and each text is at most 64 bytes. | + +## Examples + +### Mint with a Native Script + +**Before:** + +```tsx +const forgingScript = ForgeScript.withOneSignature(changeAddress); +const policyId = resolveScriptHash(forgingScript); +const tokenNameHex = stringToHex("MeshToken"); +const nft = { + [policyId]: { MeshToken: { name: "Mesh Token", image: "ipfs://..." } }, +}; + +const unsignedTx = await txBuilder + .mint("1", policyId, tokenNameHex) + .mintingScript(forgingScript) + .metadataValue(721, nft) + .changeAddress(changeAddress).selectUtxosFrom(utxos).complete(); +``` + +**After:** + +```tsx +import { + ForgeScript, + metadata, + mint, + resolveScriptHash, + stringToHex, +} from "@meshsdk/core"; + +const forgingScript = ForgeScript.withOneSignature(changeAddress); +const policyId = resolveScriptHash(forgingScript); +const tokenNameHex = stringToHex("MeshToken"); +const nft = { + [policyId]: { MeshToken: { name: "Mesh Token", image: "ipfs://..." } }, +}; + +const built = await builder.build( + [ + mint.native({ script: forgingScript, assets: { [tokenNameHex]: 1n } }), + metadata({ metadataLabel: 721n, value: nft }), + ], + { payer: wallet }, +); +``` + +The policy id comes from the script. To burn, give a negative quantity, `{ [tokenNameHex]: -1n }`, and the payer must hold the tokens. + +### Mint Several Assets + +**Before:** + +```tsx +const forgingScript = ForgeScript.withOneSignature(changeAddress); +const policyId = resolveScriptHash(forgingScript); + +for (const name of ["MeshToken1", "MeshToken2", "MeshToken3"]) { + txBuilder.mint("1", policyId, stringToHex(name)); + txBuilder.mintingScript(forgingScript); +} +const unsignedTx = await txBuilder + .changeAddress(changeAddress).selectUtxosFrom(utxos).complete(); +``` + +**After:** + +```tsx +import { ForgeScript, mint, stringToHex } from "@meshsdk/core"; + +const forgingScript = ForgeScript.withOneSignature(changeAddress); +const names = ["MeshToken1", "MeshToken2", "MeshToken3"]; + +const built = await builder.build( + mint.native({ + script: forgingScript, + assets: Object.fromEntries(names.map((name) => [stringToHex(name), 1n])), + }), + { payer: wallet }, +); +``` + +One part per policy: put every asset name in its `assets`, the two names of a CIP-68 pair too. A second part of the same policy is `DUPLICATE_PART`. + +### Mint with a Plutus Script + +**Before:** + +```tsx +const collateralUtxo = (await wallet.getCollateral())[0]!; +const policyId = resolveScriptHash(policyCode, "V2"); + +const unsignedTx = await txBuilder + .mintPlutusScriptV2() + .mint("1", policyId, stringToHex("MeshToken")) + .mintingScript(policyCode) + .mintRedeemerValue(mConStr0([])) + .txInCollateral( + collateralUtxo.input.txHash, + collateralUtxo.input.outputIndex, + collateralUtxo.output.amount, + collateralUtxo.output.address, + ) + .changeAddress(changeAddress).selectUtxosFrom(utxos).complete(); +``` + +**After:** + +```tsx +import { mConStr0, mint, stringToHex } from "@meshsdk/core"; + +const built = await builder.build( + mint.plutus({ + script: { code: policyCode, version: "V2" }, + redeemer: { data: mConStr0([]) }, + assets: { [stringToHex("MeshToken")]: 1n }, + }), + { payer: wallet }, +); +``` + +The version moves into `script`: `mintPlutusScriptV3()` becomes `version: "V3"`. The builder picks collateral and evaluates the script, so leave out the collateral call and the redeemer's `exUnits`. See [Choose the Collateral](/apis/txbuilder/migration/smart-contracts#choose-the-collateral). + +### Mint with a Reference Script + +**Before:** + +```tsx +const policyId = resolveScriptHash(policyCode, "V2"); + +const unsignedTx = await txBuilder + .mintPlutusScriptV2() + .mint("1", policyId, stringToHex("MeshToken")) + .mintTxInReference(refTxHash, 0) // the policy sits in a reference output + .mintRedeemerValue(mConStr0([])) + .changeAddress(changeAddress).selectUtxosFrom(utxos).complete(); +``` + +**After:** + +```tsx +import { mConStr0, mint, resolveScriptHash, stringToHex } from "@meshsdk/core"; + +const policyId = resolveScriptHash(policyCode, "V2"); + +const built = await builder.build( + mint.plutus({ + script: { reference: { txHash: refTxHash, outputIndex: 0 } }, + policyId, + redeemer: { data: mConStr0([]) }, + assets: { [stringToHex("MeshToken")]: 1n }, + }), + { payer: wallet }, +); +``` + +Give `policyId` when the script is given only by its transaction hash and output index. Its version and size are read from the output. + +## Related + +- [Migrate Smart Contracts](/apis/txbuilder/migration/smart-contracts) - the next area: lock and spend with Plutus scripts +- [Migrating to TxBuilder](/apis/txbuilder/migration) - the four steps and the names +- [Mint with a Time-Locked Policy](/apis/txbuilder/minting#mint-with-a-time-locked-policy) and [Mint CIP-68 Tokens](/apis/txbuilder/minting#mint-cip-68-tokens) - more recipes on the new page diff --git a/content/docs/apis/txbuilder/migration/smart-contracts.mdx b/content/docs/apis/txbuilder/migration/smart-contracts.mdx new file mode 100644 index 0000000..804ada4 --- /dev/null +++ b/content/docs/apis/txbuilder/migration/smart-contracts.mdx @@ -0,0 +1,195 @@ +--- +title: "Migrate Smart Contracts" +description: "Move locking, spending, reference scripts and collateral from MeshTxBuilder to TxBuilder parts." +--- + +## Overview + +A script chain of `txIn`, `txInScript`, `txInRedeemerValue` and friends becomes one `spend.plutus` part, and a lock is an ordinary `output` with a `datum`. This page moves them from [Smart Contract Interactions (MeshTxBuilder)](/apis/txbuilder/legacy/smart-contracts) to [Smart Contracts](/apis/txbuilder/smart-contracts). Names such as `wallet` and `builder` are explained in [Names in the Examples](/apis/txbuilder/migration#names-in-the-examples). + +## What Changes + +| Old | New | +|-----|-----| +| `.txOutInlineDatumValue(d)` | `datum: { type: "inline", data: d }` on `output` | +| `.txOutDatumHashValue(d)` | `datum: { type: "hash", data: d }` on `output`. Add `embed: true` for `txOutDatumEmbedValue`. | +| `.txOutReferenceScript(code, "V2")` | `scriptRef: { code, version: "V2" }` on `output` | +| `.spendingPlutusScriptV2().txIn(...).txInScript(code).txInRedeemerValue(r)` | `spend.plutus({ utxo, script: { code, version: "V2" }, redeemer: { data: r } })` | +| `.txInInlineDatumPresent()` | Not needed. The datum is read from the output. | +| `.txInDatumValue(d)` | `datum: { data: d }` on `spend.plutus`, for an output that holds a datum hash | +| `.txInCollateral(...)` | Not needed. The builder picks collateral. | + +## Examples + +### Lock Assets at a Script + +**Before:** + +```tsx +const { address: scriptAddress } = serializePlutusScript(script); + +const unsignedTx = await txBuilder + .txOut(scriptAddress, [{ unit: "lovelace", quantity: "10000000" }]) + .txOutInlineDatumValue(mConStr0([])) + .changeAddress(changeAddress).selectUtxosFrom(utxos).complete(); +``` + +**After:** + +```tsx +import { mConStr0, output } from "@meshsdk/core"; + +const built = await builder.build( + output({ + address: builder.scriptAddress(script), + value: { lovelace: 10_000_000n }, + datum: { type: "inline", data: mConStr0([]) }, + }), + { payer: wallet }, +); +``` + +`builder.scriptAddress(script)` gives the script's address on the builder's network. For a datum hash, write `type: "hash"` instead of `"inline"`. + +### Spend from a Script + +**Before:** + +```tsx +const unsignedTx = await txBuilder + .spendingPlutusScript(script.version) + .txIn(assetUtxo.input.txHash, assetUtxo.input.outputIndex) + .txInInlineDatumPresent() + .txInRedeemerValue(mConStr0([])) + .txInScript(script.code) + .changeAddress(changeAddress).selectUtxosFrom(utxos).complete(); +``` + +**After:** + +```tsx +import { mConStr0, spend } from "@meshsdk/core"; + +const built = await builder.build( + spend.plutus({ + utxo: assetUtxo, + script, + redeemer: { data: mConStr0([]) }, + }), + { payer: wallet }, +); +``` + +`script` is the `PlutusScript` (`{ code, version }`), so the version travels with it. The datum is read from the output; for a datum hash, add `datum: { data }` with the datum the output was locked with. + +### Use a Reference Script and a Reference Input + +**Before:** + +```tsx +const unsignedTx = await txBuilder + .spendingPlutusScriptV2() + .txIn(assetUtxo.input.txHash, assetUtxo.input.outputIndex) + .txInInlineDatumPresent() + .txInRedeemerValue(mConStr0([])) + .spendingTxInReference(refTxHash, 0) // the script sits in a reference output + .readOnlyTxInReference(refTxHash, 1) // a datum the script reads + .changeAddress(changeAddress).selectUtxosFrom(utxos).complete(); +``` + +**After:** + +```tsx +import { mConStr0, referenceInput, spend } from "@meshsdk/core"; + +const built = await builder.build( + [ + spend.plutus({ + utxo: assetUtxo, + script: { reference: { txHash: refTxHash, outputIndex: 0 } }, + redeemer: { data: mConStr0([]) }, + }), + referenceInput({ utxo: { txHash: refTxHash, outputIndex: 1 } }), + ], + { payer: wallet }, +); +``` + +The builder adds the output that holds the script itself and reads its version and size. `referenceInput` is only for reading an output, and an output the transaction also spends is never one. + +### Choose the Collateral + +**Before:** + +```tsx +const collateralUtxo = (await wallet.getCollateral())[0]!; + +txBuilder.txInCollateral( + collateralUtxo.input.txHash, + collateralUtxo.input.outputIndex, + collateralUtxo.output.amount, + collateralUtxo.output.address, +); +``` + +**After:** + +```tsx +import { collateral, mConStr0, spend } from "@meshsdk/core"; + +const collateralUtxo = (await wallet.getCollateral())[0]!; + +const built = await builder.build( + [ + spend.plutus({ utxo: assetUtxo, script, redeemer: { data: mConStr0([]) } }), + collateral({ utxo: collateralUtxo }), + ], + { payer: wallet }, +); +``` + +Collateral is automatic: leave it out and the builder picks it from the payer's UTxOs. Add `collateral` only to use a given UTxO, which the builder tops up when short unless you pass `topUpCollateral: false` to `build()`. + +### Spend from a Native Script + +**Before:** + +```tsx +const nativeScript = ForgeScript.withOneSignature(changeAddress); + +const unsignedTx = await txBuilder + .txIn( + assetUtxo.input.txHash, + assetUtxo.input.outputIndex, + assetUtxo.output.amount, + assetUtxo.output.address, + ) + .txInScript(nativeScript) + .txOut(recipient, [{ unit: "lovelace", quantity: "2000000" }]) + .changeAddress(changeAddress).selectUtxosFrom(utxos).complete(); +``` + +**After:** + +```tsx +import { ForgeScript, output, spend } from "@meshsdk/core"; + +const nativeScript = ForgeScript.withOneSignature(changeAddress); + +const built = await builder.build( + [ + spend.native({ utxo: assetUtxo, script: nativeScript }), + output({ address: recipient, value: { lovelace: 2_000_000n } }), + ], + { payer: wallet }, +); +``` + +- A native script needs no redeemer and no collateral. +- Keys the script names are asked of the signers: the payer in `built.sign()`, or those you name in `built.sign({ signers })`. `built.missing` does not list them, because the script decides which keys are enough, so check them yourself before `submit()`. + +## Related + +- [Migrate Staking](/apis/txbuilder/migration/staking) - the next area +- [Migrating to TxBuilder](/apis/txbuilder/migration) - the four steps and the names +- [Data Types](/apis/data) - build datums and redeemers diff --git a/content/docs/apis/txbuilder/migration/staking.mdx b/content/docs/apis/txbuilder/migration/staking.mdx new file mode 100644 index 0000000..3d201db --- /dev/null +++ b/content/docs/apis/txbuilder/migration/staking.mdx @@ -0,0 +1,146 @@ +--- +title: "Migrate Staking" +description: "Move stake key registration, delegation, withdrawals and deregistration from MeshTxBuilder to TxBuilder." +--- + +## Overview + +Each stake call becomes a `certificate.*` or `withdrawal.*` part. This page moves them from [Staking and Delegation (MeshTxBuilder)](/apis/txbuilder/legacy/staking) to [Staking Transactions](/apis/txbuilder/staking). Names such as `wallet` and `builder` are explained in [Names in the Examples](/apis/txbuilder/migration#names-in-the-examples). + +## What Changes + +| Old | New | +|-----|-----| +| `.registerStakeCertificate(rewardAddress)` | `certificate.stakeRegistration({ stake: rewardAddress })` | +| `.delegateStakeCertificate(rewardAddress, deserializePoolId(poolId))` | `certificate.stakeDelegation({ stake: rewardAddress, pool: poolId })` | +| `.withdrawal(rewardAddress, "5000000")` | `withdrawal.pubKey({ rewardAddress, amount: 5_000_000n })` | +| `.deregisterStakeCertificate(rewardAddress)` | `certificate.stakeDeregistration({ stake: rewardAddress })` | +| `.withdrawalPlutusScriptV2().withdrawal(a, c).withdrawalScript(code).withdrawalRedeemerValue(r)` | `withdrawal.plutus({ script: { code, version: "V2" }, redeemer: { data: r }, amount })` | +| `.registerPoolCertificate(params)`, `.retirePoolCertificate(pool, epoch)` | `certificate.poolRegistration({ params })`, `certificate.poolRetirement({ pool, epoch })` | + +## Examples + +### Register and Delegate + +**Before:** + +```tsx +const unsignedTx = await txBuilder + .registerStakeCertificate(rewardAddress) + .delegateStakeCertificate(rewardAddress, deserializePoolId(poolId)) + .changeAddress(changeAddress).selectUtxosFrom(utxos).complete(); +``` + +**After:** + +```tsx +import { certificate } from "@meshsdk/core"; + +const built = await builder.build( + [ + // leave out the registration if the key is already registered + certificate.stakeRegistration({ stake: rewardAddress }), + certificate.stakeDelegation({ stake: rewardAddress, pool: poolId }), + ], + { payer: wallet }, +); +await built.sign(); // the stake key signs too +await built.submit(); +``` + +`stakeRegistration` is not the old certificate: it states the deposit (`keyDeposit`, or `deposit`), and the stake key must sign (see [Sign with a Key or Several Signers](/apis/txbuilder/migration/basics#sign-with-a-key-or-several-signers)). Give `pool` as it is, with no `deserializePoolId`. + +### Withdraw Rewards + +**Before:** + +```tsx +const unsignedTx = await txBuilder + .withdrawal(rewardAddress, "5000000") + .changeAddress(changeAddress).selectUtxosFrom(utxos).complete(); +``` + +**After:** + +```tsx +import { withdrawal } from "@meshsdk/core"; + +const built = await builder.build( + withdrawal.pubKey({ rewardAddress, amount: 5_000_000n }), // or "all" + { payer: wallet }, +); +``` + +`amount` is a `bigint` and must be the whole reward balance. `"all"` reads the balance from the provider. + +### Deregister a Stake Key + +**Before:** + +```tsx +const unsignedTx = await txBuilder + .deregisterStakeCertificate(rewardAddress) + .changeAddress(changeAddress).selectUtxosFrom(utxos).complete(); +``` + +**After:** + +```tsx +import { certificate } from "@meshsdk/core"; + +const built = await builder.build( + certificate.stakeDeregistration({ stake: rewardAddress }), + { payer: wallet }, +); +``` + +The refund is `keyDeposit`, or `refund` if the deposit paid was another amount. The ledger refuses to deregister while rewards remain, so add `withdrawal.pubKey({ rewardAddress, amount: "all" })` to the same transaction. + +### Withdraw from a Script + +**Before:** + +```tsx +import { resolveScriptHash, serializeRewardAddress } from "@meshsdk/core"; + +const stakeScriptCbor = "your-stake-script-cbor"; +const scriptHash = resolveScriptHash(stakeScriptCbor, "V2"); +const rewardAddress = serializeRewardAddress(scriptHash, true, 0); // testnet + +const unsignedTx = await txBuilder + .withdrawalPlutusScriptV2() + .withdrawal(rewardAddress, "1000000") + .withdrawalScript(stakeScriptCbor) + .withdrawalRedeemerValue("") // your redeemer + .txInCollateral( + collateralUtxo.input.txHash, + collateralUtxo.input.outputIndex, + collateralUtxo.output.amount, + collateralUtxo.output.address, + ) + .changeAddress(changeAddress).selectUtxosFrom(utxos).complete(); +``` + +**After:** + +```tsx +import { withdrawal } from "@meshsdk/core"; + +const stakeScriptCbor = "your-stake-script-cbor"; + +const built = await builder.build( + withdrawal.plutus({ + script: { code: stakeScriptCbor, version: "V2" }, + redeemer: { data: "" }, // your redeemer + amount: 1_000_000n, // 0n is withdraw zero + }), + { payer: wallet }, +); +``` + +Leave out `rewardAddress`: the builder uses the script's own address, and picks collateral (see [Choose the Collateral](/apis/txbuilder/migration/smart-contracts#choose-the-collateral)). Register the script's stake credential first with `certificate.stakeRegistration` and a V3 `witness`, or with the deprecated `certificate.legacyStakeRegistration` for a V1 or V2 script. + +## Related + +- [Migrate Governance](/apis/txbuilder/migration/governance) - the next area: DReps, votes and proposals +- [Migrating to TxBuilder](/apis/txbuilder/migration) - the four steps and the names From 6718eab6d26bf74b7b0dd3298c0f90fb3878cf1b Mon Sep 17 00:00:00 2001 From: lisicky Date: Sun, 22 Nov 2026 19:15:44 +0100 Subject: [PATCH 04/15] docs: more Transaction Builder pages --- content/docs/apis/txbuilder/basics.mdx | 93 ++------ content/docs/apis/txbuilder/errors.mdx | 215 ++++++++++++++++++ content/docs/apis/txbuilder/governance.mdx | 12 +- content/docs/apis/txbuilder/index.mdx | 2 + content/docs/apis/txbuilder/meta.json | 25 +- content/docs/apis/txbuilder/minting.mdx | 53 ++--- content/docs/apis/txbuilder/networks.mdx | 108 +++++++++ content/docs/apis/txbuilder/offline.mdx | 182 +++++++++++++++ content/docs/apis/txbuilder/options.mdx | 130 +++++++++++ content/docs/apis/txbuilder/plans.mdx | 213 +++++++++++++++++ content/docs/apis/txbuilder/servers.mdx | 160 +++++++++++++ content/docs/apis/txbuilder/signing.mdx | 196 ++++++++++++++++ .../docs/apis/txbuilder/smart-contracts.mdx | 33 ++- content/docs/apis/txbuilder/staking.mdx | 16 +- content/docs/apis/txbuilder/testing.mdx | 172 ++++++++++++++ content/docs/apis/txbuilder/time.mdx | 133 +++++++++++ content/docs/apis/txbuilder/utxos.mdx | 190 ++++++++++++++++ data/links-txbuilders.ts | 62 ++++- 18 files changed, 1866 insertions(+), 129 deletions(-) create mode 100644 content/docs/apis/txbuilder/errors.mdx create mode 100644 content/docs/apis/txbuilder/networks.mdx create mode 100644 content/docs/apis/txbuilder/offline.mdx create mode 100644 content/docs/apis/txbuilder/options.mdx create mode 100644 content/docs/apis/txbuilder/plans.mdx create mode 100644 content/docs/apis/txbuilder/servers.mdx create mode 100644 content/docs/apis/txbuilder/signing.mdx create mode 100644 content/docs/apis/txbuilder/testing.mdx create mode 100644 content/docs/apis/txbuilder/time.mdx create mode 100644 content/docs/apis/txbuilder/utxos.mdx diff --git a/content/docs/apis/txbuilder/basics.mdx b/content/docs/apis/txbuilder/basics.mdx index a41aa7a..bee56ba 100644 --- a/content/docs/apis/txbuilder/basics.mdx +++ b/content/docs/apis/txbuilder/basics.mdx @@ -1,6 +1,6 @@ --- title: "Transaction Basics" -description: "Build, sign and submit a Cardano transaction with TxBuilder: payer, outputs, metadata, validity and signers." +description: "Build, sign and submit a Cardano transaction with TxBuilder: payer, outputs, metadata and required signers." --- ## Overview @@ -21,7 +21,7 @@ Examples use these names, which your application defines: `network` is required: `"mainnet"`, `"preprod"`, `"preview"`, or `customNetwork(...)` for a devnet. Give a `provider` to read from the chain. One builder serves every transaction. -To build offline, give `params` and `costModels` instead of a provider. Then name the payer as `{ changeAddress, utxos }`, and give any outputs that parts name by out ref in the `knownUtxos` build option. `params` and `costModels` also replace what a provider would read. +To build offline, give `params` and `costModels` instead of a provider, and your own UTxOs as the payer: see [Offline and CBOR](/apis/txbuilder/offline). Every option is in [Options](/apis/txbuilder/options). ```tsx import { TxBuilder } from "@meshsdk/core"; @@ -88,25 +88,9 @@ await built.submit({ submitter: wallet }); // the wallet sends it const { slot } = await built.awaitInclusion(); // found in a block ``` -Never rebuild a transaction to retry it: a new build may pick other inputs, and both could land. Call `submit()` again on the same `BuiltTx`. +Never rebuild a transaction to retry it: a new build may pick other inputs, and both could land. Call `submit()` again on the same `BuiltTx`. To change a built transaction, build again with the changed parts and do not send the first one: a built transaction is not edited. -### Sign with a Key or Several Signers - -`sign({ signers })` takes one signer or a list. A signer is a wallet, or `keySigner(key)`, where `key` is hex, bech32 (such as `ed25519_sk`) or the `cborHex` of a signing key file. Each signer is asked, in order, for the keys that are still missing. `built.missing` lists the keys that have not signed yet. - -```tsx -import { keySigner, output } from "@meshsdk/core"; - -const built = await builder.build( - output({ address: recipient, value: { lovelace: 5_000_000n } }), - { payer: changeAddress }, // an address: no wallet needed -); - -await built.sign({ signers: keySigner(process.env.TREASURY_SKEY!) }); // a private key -// or several signers, asked in order: -await built.sign({ signers: [wallet, keySigner(process.env.PARTNER_SKEY!)] }); -console.log(built.missing); // keys that have not signed yet -``` +To sign with a private key, with your own code or with several signers, see [Signing and Submitting](/apis/txbuilder/signing). ## Add More to a Transaction @@ -114,19 +98,7 @@ Add these parts to the list you give to `build()`. ### Choose Inputs -The builder picks the payer's inputs. To spend a particular output, add a `spend.pubKey` part. To limit what the builder may pick, give `canSelect`. To replace the built-in selection, give `coinSelection: (need, candidates) => outRefs`, where each out ref names a candidate. - -```tsx -import { output, spend } from "@meshsdk/core"; - -const built = await builder.build( - [ - spend.pubKey({ utxo }), // an input you choose - output({ address: recipient, value: { lovelace: 5_000_000n } }), - ], - { payer: wallet, canSelect: (c) => c.value.lovelace > 5_000_000n }, -); -``` +The builder picks the payer's inputs. To spend a particular output, add a `spend.pubKey({ utxo })` part. To limit or replace the choice, see [UTxOs and Inputs](/apis/txbuilder/utxos). ### Add a Message or Metadata @@ -147,19 +119,7 @@ const built = await builder.build( ### Set the Validity -`validity` takes POSIX milliseconds: `from` and `until`. For slots, use `invalidBefore` and `invalidHereafter`. For "valid from now", leave `from` out. `build()` sets no deadline, so give `until` when you follow the transaction yourself. - -```tsx -import { output, validity } from "@meshsdk/core"; - -const built = await builder.build( - [ - output({ address: recipient, value: { lovelace: 5_000_000n } }), - validity({ until: Date.now() + 60 * 60 * 1000 }), // expires in one hour - ], - { payer: wallet }, -); -``` +`validity({ until })` takes POSIX milliseconds, and `build()` sets no deadline, so give `until` when you follow the transaction yourself. For start times, slots and devnets, see [Time and Validity](/apis/txbuilder/time). ### Require a Signer @@ -179,27 +139,13 @@ const built = await builder.build( ## Plan Several Transactions -`plan()` takes named steps and sends them in order. Use it for several dependent transactions, for retries that cannot pay twice, or to wait for blocks. A plan never builds again, so repeating `run()` sends the same transactions. +`plan()` takes named steps and sends them in order. Use it for several dependent transactions, for retries that cannot pay twice, or to wait for blocks: see [Plans](/apis/txbuilder/plans). -> **Note:** `plan()` needs a provider that returns block heights and, for a step that runs a Plutus script, the validity flag (whether the script passed). The plain `BlockfrostProvider` returns neither, so `plan()` throws `CANNOT_OBSERVE`. The package README (Providers and networks) shows a subclass that adds them. For a Plutus transaction, `awaitInclusion()` needs the validity flag too. `build()` needs neither. - -```tsx -import { output } from "@meshsdk/core"; - -const plan = await builder.plan( - { - first: output({ address: recipient, value: { lovelace: 5_000_000n } }), - second: output({ address: partner, value: { lovelace: 2_000_000n } }), - }, - { payer: wallet }, -); -await plan.run(); // signs, submits and waits for a block, step by step -console.log(plan.step("second").txHash); -``` +> **Note:** `plan()` needs a provider that returns block heights and the validity flag. The plain `BlockfrostProvider` does not, and `plan()` throws `CANNOT_OBSERVE`: see [Providers and Networks](/apis/txbuilder/networks#use-blockfrost-for-plans). ## Handle Errors -Every error is a `TxError` with a `code`. Check the code, not the message. `TxError.is` also types `error.details`. Build before the `try`, so that a retry calls `submit()` on the same `BuiltTx` and never builds again. +Every error is a `TxError` with a `code`. Check the code, not the message. `TxError.is` also types `error.details`. Build before the `try`, so that a retry calls `submit()` on the same `BuiltTx` and never builds again. Every code, when it comes and which a retry can fix, is in [Errors](/apis/txbuilder/errors). ```tsx import { output, TxError } from "@meshsdk/core"; @@ -227,24 +173,11 @@ try { } ``` -| Code | Meaning | Fix | -|------|---------|-----| -| `MISSING_PAYER` | `build()` got no `payer` | Pass `{ payer }` | -| `INSUFFICIENT_FUNDS` | the payer's UTxOs cannot pay | `error.details` names the unit and the amount missing | -| `OUTPUT_BELOW_MIN_COIN` | an output holds less lovelace than the ledger requires | Add lovelace, or leave `lovelace` out | -| `DUPLICATE_PART` | the same input, policy or voter twice, or a part that is held once given twice | Give each part once | -| `TX_TOO_LARGE` | the transaction is over the size limit | Split it into several transactions | -| `MISSING_PARAMETER` | no protocol parameters, cost models or deposits | Give a `provider`, or `params`, `costModels` or `deposits` | -| `NETWORK_MISMATCH` | an address, wallet or provider is on another network than `network` | Use one network everywhere | -| `MISSING_SIGNATURES` | a key has not signed, and nothing was sent | Name the signer; `built.missing` lists the keys | -| `SUBMIT_FAILED`, `CONFIRM_TIMEOUT` | the outcome is unknown | Call `submit()` or `awaitInclusion()` again on the same `BuiltTx` | -| `CANNOT_OBSERVE` | the provider returns no block heights or validity flag | See the Note under Plan Several Transactions | - ## Related -- [Mint and Burn Assets](/apis/txbuilder/minting) - mint and burn with native and Plutus scripts -- [Smart Contracts](/apis/txbuilder/smart-contracts) - lock and unlock funds at a script -- [Staking Transactions](/apis/txbuilder/staking) - register, delegate and withdraw -- [Governance Transactions](/apis/txbuilder/governance) - DReps, votes and proposals +- [Signing and Submitting](/apis/txbuilder/signing) - keys, your own signer, several signers and retries +- [UTxOs and Inputs](/apis/txbuilder/utxos) - give, limit or chain UTxOs, and set collateral +- [Plans](/apis/txbuilder/plans) - send transactions in order +- [Errors](/apis/txbuilder/errors) - every code and which a retry can fix - [Migrating to TxBuilder](/apis/txbuilder/migration) - move from the `MeshTxBuilder` chain - [Package README](https://github.com/MeshJS/mesh/tree/main/packages/mesh-transaction) - every part, option and error diff --git a/content/docs/apis/txbuilder/errors.mdx b/content/docs/apis/txbuilder/errors.mdx new file mode 100644 index 0000000..56ddbcf --- /dev/null +++ b/content/docs/apis/txbuilder/errors.mdx @@ -0,0 +1,215 @@ +--- +title: "Errors" +description: "The error classes of TxBuilder, every code by when it comes, which ones a retry can fix, and the warnings of a build." +--- + +## Overview + +Every error of `TxBuilder` is a `TxError` with a `code`. Use it when a call throws, to see what to do, and to decide what a retry may repeat. It lists the classes, which errors a retry can fix, the codes by when they come, and the warnings of a build. For a first look, see [Handle Errors](/apis/txbuilder/basics#handle-errors). + +Examples use the names of [Transaction Basics](/apis/txbuilder/basics): `builder`, `wallet` and `recipient`. + +## Error Classes + +| Class | Thrown by | +|-------|-----------| +| `TxError` | The base of the others. `TxError.is(error)` is true for any error of the package | +| `TxPartError` | A part builder such as `output(...)`, at the call that made the part | +| `TxBuildError` | `build()` and `plan()`, when the parts cannot be built into a transaction, and for a bad option or argument | +| `TxPlanError` | Signing, submitting and waiting, from a `BuiltTx` or a `TxPlan`, and the plan store | + +Every error has a `code` and a `message`, and where they apply `part`, `label`, `details` and `cause` (the error it was raised from, such as the provider's). A `TxPlanError` of a plan also has `planId`, `status`, `step` and `txHash`. One of a `BuiltTx` has none of them. + +## Check a Code + +Check the code, not the message. `TxError.is(error, "CODE")` is true when the error has that code, and it types `error.details` for it. Give several codes to match any of them. `TxBuildError.is` and `TxPlanError.is` check one class. `TxPartError.is` is the same as `TxError.is`: tell a part error by its code. The check also works on an error made by another copy of the package. + +`details` holds data typed by the code, such as `unit` and `missing` for `INSUFFICIENT_FUNDS`. A code with no details has `details` undefined. The tables below name the useful ones. + +## Which Errors a Retry Can Fix + +`error.retryable` is `true` when the same call, repeated no earlier than `error.retryAfterMs` when that is set, is safe and may pass. Only these are retryable: + +| Code | Repeat | +|------|--------| +| `SUBMIT_FAILED` | `submit()` on the same `BuiltTx` (`run()` for a plan). It fails again after `unauthorized` until the key is fixed | +| `CONFIRM_TIMEOUT` | `awaitInclusion()` on the same `BuiltTx` (`run()` for a plan) | +| `NOT_YET_VALID` | The call that threw, after `retryAfterMs` (`details.waitMs`) | +| `CANNOT_OBSERVE` with `reason` `unconfirmed` | The call, after `retryAfterMs` (the builder's `pollMs`) | +| `STILL_LIVE` with `safeAfter` | `replan` or `add`, after `retryAfterMs` | + +Every other error needs a fix, not a retry. Never build again to retry a `SUBMIT_FAILED`, `REJECTED` or `CONFIRM_TIMEOUT`: [Transaction Basics](/apis/txbuilder/basics#build-sign-and-submit) says why. + +## Handle Errors Around Build and Submit + +Build errors are safe to fix and build again, because nothing was sent. After the build, retry only the same calls on the same `BuiltTx`. + +```tsx +import { output, TxError } from "@meshsdk/core"; + +async function pay() { + const built = await builder + .build( + output({ address: recipient, value: { lovelace: 5_000_000n } }), + { payer: wallet }, + ) + .catch((error) => { + if (TxError.is(error, "INSUFFICIENT_FUNDS")) { + console.log(error.details.unit, error.details.missing); + } + throw error; // nothing was sent + }); + await built.sign(); + + let sent = false; + for (let tries = 1; ; tries++) { + try { + if (!sent) await built.submit(); + sent = true; + return await built.awaitInclusion(); // found in a block + } catch (error) { + if (!TxError.is(error) || !error.retryable || tries === 3) throw error; + await new Promise((r) => setTimeout(r, error.retryAfterMs ?? 5_000)); + } + } +} +``` + +## Abort a Call + +A call that takes a `signal` throws `ABORTED` when it is aborted. What that leaves depends on the call: + +- `build()` and `plan()`: nothing was signed or sent. Build again if you still want it. +- `sign()`: the signatures already given stay. +- `submit()` and `run()`: bytes already handed to the submitter may land. Call the same `submit()` or `run()` again on the same object, and never build again. + +## Errors When Making a Part + +A part builder checks its arguments at once, so the error points at the line that made the part. None of these has `details`. + +| Code | What happened and what to do | +|------|------------------------------| +| `INVALID_OUT_REF` | A bad transaction hash or output index, or a UTxO given as text that is not its CBOR. Fix the out ref | +| `INVALID_ADDRESS` | An address that does not parse, or of the wrong kind for the part. Use a valid address | +| `INVALID_VALUE` | A malformed amount, unit or policy. Use `bigint` amounts and `policyId + assetNameHex` units | +| `INVALID_SCRIPT` | A script that does not parse, or a reference output with no suitable script. Check the script and the output it names | +| `INVALID_DATA` | Plutus data or a hash that does not parse, an inline datum that is not one item, or a validity time out of range | +| `WITNESS_MISMATCH` | A witness that cannot authorise its output, such as a key spend of a script output. Use `spend.plutus` or `spend.native` for scripts, `spend.pubKey` for keys | +| `DATUM_MISMATCH` | A datum choice that does not fit the output spent. Give the datum the output was locked with, and leave `datum` out for an inline datum | + +## Errors When Building + +`build()` and `plan()` throw these. Nothing was signed or sent, so fix the cause and build again. None of them is retryable. + +### Setup and Options + +| Code | What happened and what to do | +|------|------------------------------| +| `MISSING_PAYER` | There is no payer. Pass `{ payer }` | +| `MISSING_PARAMETER` | Parameters, cost models or deposits are not known. `details.parameter` says which. Give a `provider`, or `params`, `costModels` or `deposits` | +| `MISSING_FETCHER` | Something has to be read and there is no provider. Give a `provider`, or pass UTxOs in full | +| `MISSING_EVALUATOR` | Execution units are needed and there is no evaluator. Give an `evaluator` | +| `NETWORK_MISMATCH` | An address, wallet, provider or transaction is on another network than `network`. `details.expected` and `details.found` say where. Use one network | +| `INVALID_OPTION` | An option or argument is not accepted, or a member is unknown. `details.option` names it and `details.allowed` says what is accepted | +| `UNSUPPORTED_SERIALIZER` | The `serializer` cannot serialize a transaction prototype. Leave it out, or give one with `serializeTxPrototype` | +| `PROVIDER_FAILED` | A provider read failed. `details.operation` names it, and `error.cause` holds the provider's error | +| `WALLET_FAILED` | Reading the payer from a wallet failed. Check the wallet, or give `{ changeAddress, utxos }` | +| `INVALID_SELECTION` | `coinSelection` returned an out ref that is not a candidate. Return candidates only | +| `UNKNOWN_LABEL` | `outputOf` asked for a label no output has. `details.labels` lists them | +| `NOT_SERIALIZABLE` | A part holds a [redeemer function](/apis/txbuilder/smart-contracts#spend-from-a-script), so `toJSON()` and a plan on a builder with a store refuse it. Give the redeemer as data | + +### Parts and Inputs + +| Code | What happened and what to do | +|------|------------------------------| +| `UNRESOLVED` | A part still leaves something open, or links to an earlier step outside a plan. `details` lists the gaps of each part | +| `DUPLICATE_PART` | The same input, policy, reward account, voter or collateral input twice, or a part held once given twice. `details.item` names it | +| `UTXO_NOT_FOUND` | An output the transaction names does not exist, could not be read, or is spent by a transaction of `after`. Pass the UTxO in full, or use `knownUtxos` | +| `INVALID_REDEEMER` | A [redeemer function](/apis/txbuilder/smart-contracts#spend-from-a-script) threw, asked for an item the transaction does not hold, or returned data that is not Plutus data. `details.reason` says which | +| `INVALID_GUARD` | A `guard.pubKey` whose hash is the hash of one of the transaction's scripts. Name a key hash | +| `NATIVE_SCRIPT_UNREAD` | Only for a transaction built elsewhere: a native script whose keys the library does not read. `details.reason` is `depth`, `size` or `form` | + +### Funds, Fees and Size + +| Code | What happened and what to do | +|------|------------------------------| +| `INSUFFICIENT_FUNDS` | The payer's UTxOs cannot pay. `details.unit` and `details.missing` say what to add | +| `INSUFFICIENT_COLLATERAL` | No collateral, or not enough, can be put up (`details.required`, `details.available`). Fund the payer, or drop `topUpCollateral: false` | +| `INVALID_COLLATERAL` | Collateral inputs cannot cover the total, or with `collateralReturn: false` one holds a token. Give inputs with lovelace only | +| `OUTPUT_BELOW_MIN_COIN` | An output holds less lovelace than the ledger requires (`details.coin`, `details.minCoin`). Add lovelace, or leave `lovelace` out | +| `VALUE_TOO_LARGE` | An output's value is larger than `maxValSize`. Spread the assets over several outputs | +| `TX_TOO_LARGE` | Over `maxTxSize`. `details.cause` is `parts`, `selection` or `referenceScripts`. Split it into the steps of a plan | +| `FEE_TOO_LOW` | The `fee` you gave is below the minimum (`details.minFee`). Drop it, or give a higher one | +| `FEE_NOT_CONVERGED` | Balancing did not settle on a fee within its rounds. This is rare | + +### Scripts + +| Code | What happened and what to do | +|------|------------------------------| +| `EVALUATION_FAILED` | A script failed, or not every redeemer was priced. `details.failures` names each failed part, so give parts a `label` | +| `EXUNITS_TOO_LOW` | A script needs more units than its redeemer states (`details.needed`, `details.given`). Leave `exUnits` out | +| `EXUNITS_EXCEEDED` | The scripts need more units than a transaction may use. Spread them over the steps of a plan | +| `EVALUATION_NOT_CONVERGED` | Execution units did not settle within the evaluation rounds. This is rare | + +## Errors When Signing and Submitting + +These are `TxPlanError`s, from a `BuiltTx` or a plan. + +| Code | What happened and what to do | +|------|------------------------------| +| `SIGN_DECLINED` | The user declined to sign. Nothing changed, and asking again is your choice | +| `SIGNER_FAILED` | The signer failed, timed out or changed accounts (`details.reason`: `error`, `timeout`, `accountChanged`). After an account change, connect again and pass the new api as `signers` | +| `INVALID_WITNESS` | A witness that cannot be decoded or is not of this transaction. Sign the transaction of this build | +| `MISSING_SIGNATURES` | A key has not signed, or nobody can sign. Nothing was sent. `built.missing` lists the keys. Name a signer | +| `MISSING_SUBMITTER` | There is no submitter. Nothing was sent. Give a `provider` or a `submitter`, or call `built.submit({ submitter: wallet })` | +| `NOT_YET_VALID` | The lower bound of validity is ahead of the tip. Nothing was sent. Call again after `error.retryAfterMs` | +| `SUBMIT_FAILED` | The outcome is unknown: the bytes may have arrived. Call `submit()` again on the same `BuiltTx`. `details.reason` is `unavailable`, `rateLimited`, `unauthorized`, `refused` or `unknown`. After `unauthorized`, fix the API key first | +| `REJECTED` | The ledger refused the transaction and the provider does not find it. Do not retry a `BuiltTx`. The object does not know what another process sent: look for the transaction (`awaitInclusion()`) before you decide it did not land. A plan's `run()` sends the same bytes again | + +## Errors from Waiting and Plans + +These come from waiting for a block and from following a plan. + +| Code | What happened and what to do | +|------|------------------------------| +| `CONFIRM_TIMEOUT` | Not found in a block within `timeoutMs`. This does not mean "not paid". Call `awaitInclusion()` or `run()` again | +| `EXPIRED` | A step's end of validity and the margin have passed, and it is not on chain. The plan does not go on. Make a new plan for what is left with `plan.replan` | +| `SCRIPT_FAILED` | A step landed with a failed script, and its collateral was taken. The plan does not go on | +| `ORPHANED` | A step stands on a step that will not land, so it will not land either | +| `CANNOT_OBSERVE` | The provider cannot follow plans. `details.reason` is `noTip`, `noSearch`, `noDepth`, `noValidity` or `unconfirmed`. Use a provider that returns block heights and the validity flag | +| `INVALID_STATE` | The plan was stopped, replaced or is final, or a Plutus step would end past the horizon (`pastHorizon`: shorten `ttlMs`). `details.reason` says which | +| `STILL_LIVE` | A step that `replan` or `add` built could land beside an old transaction that may still land. Nothing was written. With `details.safeAfter`, call `replan` or `add` again after `retryAfterMs`. Without it, waiting does not help: an old transaction may still land, and your application decides how to pay what is left (see the package README) | + +The plan store raises these when a builder has a `store`: + +| Code | What happened and what to do | +|------|------------------------------| +| `MISSING_ID` | A plan on a builder with a `store` needs an `id` | +| `PLAN_EXISTS` | The `id` is already recorded with other parts or options, and nothing was written. Open the recorded plan with `builder.resume(id)`, or repeat the call with the same parts and options. A new `id` is a new order and pays again: use one only for a new payment | +| `PLAN_NOT_FOUND` | No record under the `id` | +| `MISSING_STORE` | `resume(id)` on a builder without a `store` | +| `VERSION_CONFLICT` | Another writer changed the record. Go on through `builder.resume(id)` | +| `STORE_FAILED` | The store threw, and a write may have passed. Go on through `builder.resume(id)` | + +## Build Warnings + +A warning does not stop a build. `built.warnings` lists them, each with a `code` and a `message`, and `part` and `label` when it is about a part. + +| Code | What it says | +|------|--------------| +| `VALID_FROM_FUTURE` | The lower bound of validity starts after the local clock | +| `COLLATERAL_FORFEITED` | The transaction has collateral and no collateral return, so all of it is at stake if a script fails. It comes with `collateralReturn: false` | +| `COLLATERAL_RETURN_ELSEWHERE` | Only from `fromCbor`: a collateral input belongs to another payment credential than the one the return pays, and that holder loses if a script fails | +| `FEE_ABOVE_MINIMUM` | The `fee` you gave is above the minimum | +| `NEVER_EXPIRES` | Only on a step of a plan that was given built: it has no end of validity | + +The lists of codes, reasons and warnings can grow, so keep a default branch when you switch on them. + +## Related + +- [Transaction Basics](/apis/txbuilder/basics) - build, sign and submit, and a first look at errors +- [Signing and Submitting](/apis/txbuilder/signing) - signers, submitters and safe retries +- [Plans](/apis/txbuilder/plans) - statuses, deadlines and what to do after a step fails +- [Options](/apis/txbuilder/options) - the options behind many of these codes +- [Migration Errors and Differences](/apis/txbuilder/migration/errors) - old messages and their new codes +- [Package README](https://github.com/MeshJS/mesh/tree/main/packages/mesh-transaction) - every code with its details diff --git a/content/docs/apis/txbuilder/governance.mdx b/content/docs/apis/txbuilder/governance.mdx index 1f0240f..604c7fa 100644 --- a/content/docs/apis/txbuilder/governance.mdx +++ b/content/docs/apis/txbuilder/governance.mdx @@ -5,7 +5,7 @@ description: "Register as a DRep, delegate your vote, vote on actions and submit ## Overview -Governance uses certificates, votes and proposals, passed as parts to `builder.build()`. A DRep (delegated representative) votes on behalf of the stake delegated to it. The DRep and proposal deposits are not in the protocol parameters, so the builder takes them from its `deposits` option, or from `deposit` on a part. Without them the build throws `MISSING_PARAMETER` (see [Handle Errors](/apis/txbuilder/basics#handle-errors)). +Governance uses certificates, votes and proposals, passed as parts to `builder.build()`. A DRep (delegated representative) votes on behalf of the stake delegated to it. The DRep and proposal deposits are not in the protocol parameters, so the builder takes them from its `deposits` option, or from `deposit` on a part. Without them the build throws `MISSING_PARAMETER` (see [Handle Errors](/apis/txbuilder/basics#handle-errors)). Use this page to act as a DRep, vote or propose. Examples stop at `build()`: call `built.sign()` and `built.submit()` as in [Transaction Basics](/apis/txbuilder/basics#build-sign-and-submit). They use `wallet` and `provider` from there, and these names, which your application defines: @@ -24,7 +24,10 @@ Examples stop at `build()`: call `built.sign()` and `built.submit()` as in [Tran ## Manage a DRep -Register with `certificate.drepRegistration`. `anchor` is optional, and the deposit is `drepDeposit`. Update the metadata with `certificate.drepUpdate`, giving it the `anchor` of the changed file: leave `anchor` out to clear it. Retire with `certificate.drepDeregistration`, which refunds `drepDeposit`. Pass `refund` if the deposit paid was another amount. The DRep key signs: a `MeshWallet` does it in `sign()`, and a browser wallet must be connected with the CIP-95 extension. +- Register: `certificate.drepRegistration`. `anchor` is optional, and the deposit is `drepDeposit`. +- Update: `certificate.drepUpdate`, with the `anchor` of the changed file. Leave `anchor` out to clear it. +- Retire: `certificate.drepDeregistration`, which refunds `drepDeposit`. Pass `refund` if the deposit paid was another amount. +- Signing: the DRep key signs. A `MeshWallet` does it in `sign()`, and a browser wallet must be connected with the CIP-95 extension. ```tsx import { certificate } from "@meshsdk/core"; @@ -33,9 +36,6 @@ const built = await builder.build( certificate.drepRegistration({ drep: drepId, anchor }), { payer: wallet }, ); -await built.sign(); // the payer signs; the DRep key too, if the wallet holds it -await built.submit(); -await built.awaitInclusion(); // waits until a block holds it ``` ## Delegate Your Vote @@ -112,5 +112,7 @@ const built = await builder.build( - [Staking Transactions](/apis/txbuilder/staking) - register a stake key, delegate and withdraw - [Transaction Basics](/apis/txbuilder/basics) - the builder, the payer and signing +- [Signing and Submitting](/apis/txbuilder/signing) - sign with a DRep key or several signers +- [Options](/apis/txbuilder/options) - the `deposits` option and the other options - [Migrating to TxBuilder](/apis/txbuilder/migration) - move from the `MeshTxBuilder` chain - [Package README](https://github.com/MeshJS/mesh/tree/main/packages/mesh-transaction) - every part, option and error diff --git a/content/docs/apis/txbuilder/index.mdx b/content/docs/apis/txbuilder/index.mdx index 14f7005..5fc774f 100644 --- a/content/docs/apis/txbuilder/index.mdx +++ b/content/docs/apis/txbuilder/index.mdx @@ -50,6 +50,8 @@ console.log(built.txHash); | `certificate.*`, `withdrawal.*` | stake, delegate and withdraw rewards | | `vote`, `proposal.*` | take part in governance | +For signing, UTxOs, time, plans, offline use, testing and errors, see the cards below. + ## Pick a Task
diff --git a/content/docs/apis/txbuilder/meta.json b/content/docs/apis/txbuilder/meta.json index 59b6a47..57221f4 100644 --- a/content/docs/apis/txbuilder/meta.json +++ b/content/docs/apis/txbuilder/meta.json @@ -1,5 +1,28 @@ { "title": "Transaction Builder", "icon": "BanknotesIcon", - "pages": ["basics", "minting", "smart-contracts", "staking", "governance", "migration", "legacy"] + "pages": [ + "basics", + "signing", + "utxos", + "time", + "---Plans and Servers---", + "plans", + "servers", + "---Scripts, Staking and Governance---", + "minting", + "smart-contracts", + "staking", + "governance", + "---Environments---", + "offline", + "testing", + "networks", + "---Reference---", + "options", + "errors", + "---Migration---", + "migration", + "legacy" + ] } diff --git a/content/docs/apis/txbuilder/minting.mdx b/content/docs/apis/txbuilder/minting.mdx index 492ab8e..084b914 100644 --- a/content/docs/apis/txbuilder/minting.mdx +++ b/content/docs/apis/txbuilder/minting.mdx @@ -5,11 +5,12 @@ description: "Mint and burn native assets with a native script or a Plutus scrip ## Overview -Minting is a part of the transaction: `mint.native` for a native script policy and `mint.plutus` for a Plutus policy. Quantities are `bigint`, and a negative quantity burns. +Minting is a part of the transaction: `mint.native` for a native script policy and `mint.plutus` for a Plutus policy. Quantities are `bigint`, and a negative quantity burns. Use this page to mint or burn tokens, with a native or a Plutus policy. Examples stop at `build()`: call `built.sign()` and `built.submit()` as in [Transaction Basics](/apis/txbuilder/basics#build-sign-and-submit). They use `builder` and `wallet` from there, and these names, which your application defines: - `changeAddress` - the wallet's address, from `await wallet.getChangeAddress()` +- `forgingScript` - the policy script of the first example, `ForgeScript.withOneSignature(changeAddress)` - `policyCode` - a Plutus minting policy as script CBOR: `applyCborEncoding(compiledCode)` of `@meshsdk/core`, the form `resolveScriptHash` takes - `referenceAddress` - where CIP-68 reference tokens are kept - `refTxHash` - the hash of a transaction that holds a script in one of its outputs @@ -37,9 +38,8 @@ const built = await builder.build( Put every asset of a policy in the `assets` of one part. A second part of the same policy is `DUPLICATE_PART` (see [Handle Errors](/apis/txbuilder/basics#handle-errors)). A quantity above `1n` makes a fungible token. A very large collection may not fit in one transaction (`TX_TOO_LARGE`): split it. ```tsx -import { ForgeScript, mint, stringToHex } from "@meshsdk/core"; +import { mint, stringToHex } from "@meshsdk/core"; -const forgingScript = ForgeScript.withOneSignature(changeAddress); const names = ["MeshToken1", "MeshToken2", "MeshToken3"]; const built = await builder.build( @@ -56,9 +56,7 @@ const built = await builder.build( A negative quantity burns. Use the script of the policy that minted the tokens. The tokens must be in the payer's wallet. ```tsx -import { ForgeScript, mint, stringToHex } from "@meshsdk/core"; - -const forgingScript = ForgeScript.withOneSignature(changeAddress); +import { mint, stringToHex } from "@meshsdk/core"; const built = await builder.build( mint.native({ @@ -74,12 +72,7 @@ const built = await builder.build( `script` also takes a `NativeScript` object. This policy works only before a slot, so the transaction states the end of its validity with `validity()`. `builder.slotAt()` turns a time into a slot. ```tsx -import { - deserializeAddress, - mint, - stringToHex, - validity, -} from "@meshsdk/core"; +import { deserializeAddress, mint, stringToHex, validity } from "@meshsdk/core"; import type { NativeScript } from "@meshsdk/core"; const { pubKeyHash } = deserializeAddress(changeAddress); @@ -109,15 +102,8 @@ const built = await builder.build( CIP-25, the NFT metadata standard, keeps metadata under label 721, keyed by policy id and then by asset name as text. Add it with `metadata()`. Each text is at most 64 bytes, so split a longer one into a list of strings. ```tsx -import { - ForgeScript, - metadata, - mint, - resolveScriptHash, - stringToHex, -} from "@meshsdk/core"; +import { metadata, mint, resolveScriptHash, stringToHex } from "@meshsdk/core"; -const forgingScript = ForgeScript.withOneSignature(changeAddress); const policyId = resolveScriptHash(forgingScript); const built = await builder.build( @@ -143,7 +129,20 @@ const built = await builder.build( ); ``` -A royalty token (CIP-27) has the empty asset name and its own entry: `mint.native({ script: forgingScript, assets: { "": 1n } })` with `metadata({ metadataLabel: 777n, value: { rate: "0.05", addr: [first64, rest] } })`. Split the address into strings of at most 64 bytes. +A royalty token (CIP-27) has the empty asset name and its own entry. Split the address into strings of at most 64 bytes. + +```tsx +import { metadata, mint } from "@meshsdk/core"; + +const royalty = [ + mint.native({ script: forgingScript, assets: { "": 1n } }), + metadata({ + metadataLabel: 777n, + value: { rate: "0.05", addr: [changeAddress.slice(0, 64), changeAddress.slice(64)] }, + }), +]; +const built = await builder.build(royalty, { payer: wallet }); +``` ## Mint with a Plutus Script @@ -168,14 +167,8 @@ CIP-68 keeps the metadata in an inline datum (data stored with an output). The r ```tsx import { - CIP68_100, - CIP68_222, - mConStr0, - metadataToCip68, - mint, - output, - resolveScriptHash, - stringToHex, + CIP68_100, CIP68_222, mConStr0, metadataToCip68, + mint, output, resolveScriptHash, stringToHex, } from "@meshsdk/core"; const nameHex = stringToHex("MyToken"); @@ -223,6 +216,8 @@ const built = await builder.build( - [Transaction Basics](/apis/txbuilder/basics) - the builder, outputs, metadata and validity - [Smart Contracts](/apis/txbuilder/smart-contracts) - lock and spend with Plutus scripts +- [Time and Validity](/apis/txbuilder/time) - end of validity for a time-locked policy +- [Signing and Submitting](/apis/txbuilder/signing) - sign with a policy key or several signers - [Migrating to TxBuilder](/apis/txbuilder/migration) - move from the `MeshTxBuilder` chain - [Data Types](/apis/data) - build datums and redeemers - [Resolvers](/apis/utilities/resolvers) - policy ids and script hashes diff --git a/content/docs/apis/txbuilder/networks.mdx b/content/docs/apis/txbuilder/networks.mdx new file mode 100644 index 0000000..08703cf --- /dev/null +++ b/content/docs/apis/txbuilder/networks.mdx @@ -0,0 +1,108 @@ +--- +title: "Providers and Networks" +description: "Choose the network, see what the builder asks a provider for, and add block heights to BlockfrostProvider for plans." +--- + +## Overview + +The builder reads the chain through a provider and checks every address, UTxO and wallet against its `network`. Use this page to pick the network, to see what a provider must give, to make plans work with Blockfrost, and to run on a devnet or a Hydra head. + +Examples use `builder`, `provider`, `wallet`, `recipient` and `changeAddress` from [Transaction Basics](/apis/txbuilder/basics). + +## Choose the Network + +`network` is required. A name that is none of these, `"testnet"` too, is `INVALID_OPTION`. The builder converts times to slots with the slot clock of its network: see `builder.slotAt(time)` and `builder.timeAt(slot)`. + +| `network` | For | +|-----------|-----| +| `"mainnet"` | Cardano mainnet | +| `"preprod"`, `"preview"` | the public test networks | +| `customNetwork({ systemStart, slotLengthMs, epochLength })` | a devnet: its clock is set up in [Time and Validity](/apis/txbuilder/time#a-devnet-clock) | + +An address, UTxO, wallet or provider on another network is `NETWORK_MISMATCH`. `details.expected` is the network of the builder, and `details.found` lists what disagrees, each with a `role` such as `payer`, `wallet`, `provider`, `utxo` or `output`. Use one network everywhere: in the builder, the wallet and the addresses. + +## What the Builder Asks a Provider + +A build reads only what it needs, and nothing at all when you give the data yourself (see [Offline and CBOR](/apis/txbuilder/offline)). + +| The builder needs | The provider answers | When | +|-------------------|----------------------|------| +| the payer's UTxOs | `fetchAddressUTxOs` | the payer is an address | +| an output named by out ref | `fetchUTxOs` | a part names an output you did not give in full | +| protocol parameters | `fetchProtocolParameters` | you gave no `params` | +| cost models | `fetchCostModels` | a script runs and you gave no `costModels` | +| a reward balance | `fetchAccountInfo` | a withdrawal with `amount: "all"` | +| the submission | `submitTx` | `submit()` or `run()`, unless a `submitter` is given | +| the search for a transaction | `fetchTxInfo` | `awaitInclusion()` and plans | +| the tip, with its block height | `fetchLatestBlock` | plans | + +A plan also needs the block height in the search answer and, for a step that runs a Plutus script, the validity flag `validContract`: it says whether the script passed. `awaitInclusion()` of a Plutus transaction needs the flag too. + +Reading and sending can be split: the `provider` reads and a `submitter` sends. The call's own `submitter` comes first, then the builder's, then the provider. + +```tsx +import { TxBuilder } from "@meshsdk/core"; + +const builder = new TxBuilder({ + network: "preprod", + provider, // reads + submitter: wallet, // sends +}); +``` + +## Use Blockfrost for Plans + +`BlockfrostProvider` works for `build()` and `submit()`. It returns neither block heights nor the validity flag, so `builder.plan()` throws `CANNOT_OBSERVE` before anything is signed. Until the provider returns them itself, give the builder this subclass. It is temporary: remove it when the provider does it for you. It costs one more request for each tip and each found step. + +```tsx +import type { BlockInfo, TransactionInfo } from "@meshsdk/core"; +import { BlockfrostProvider } from "@meshsdk/core"; + +/** BlockfrostProvider with the block heights and the validity flag that plans need */ +export class BlockfrostWithHeights extends BlockfrostProvider { + async fetchLatestBlock(): Promise { + const block = await super.fetchLatestBlock(); + const { height } = await this.get(`blocks/${block.hash}`); + return { ...block, height }; + } + + async fetchTxInfo(hash: string): Promise { + const info = await super.fetchTxInfo(hash); + const tx = await this.get(`txs/${hash}`); + return { + ...info, + blockHeight: tx.block_height, + validContract: tx.valid_contract, + }; + } +} + +const provider = new BlockfrostWithHeights(""); +``` + +`details.reason` of `CANNOT_OBSERVE` says what the provider lacks: `noTip`, `noSearch`, `noDepth` or `noValidity`. Plans work on `TxEmulator` and on Blockfrost with the subclass above. A provider that cannot search can still submit, as the builder's `submitter`, while another provider reads. + +## Run on a Devnet or a Hydra Head + +A devnet's genesis wallets and `topup` give UTxOs without a transaction, which the checks of a plan cannot find. Before the first plan and after each `topup`, have the wallet send its UTxOs to itself in an ordinary transaction. + +```tsx +const built = await builder.build([], { payer: wallet, sendAllTo: changeAddress }); +await built.sign(); +await built.submit(); +await built.awaitInclusion(); // then plans can find the UTxOs +``` + +A Hydra head has its own protocol parameters. Let the head's provider read them, or give them as `params` from the file the head was started with. Do not use placeholder zero values. A Plutus transaction carries a collateral input in a head too. + +## Related + +- [Transaction Basics](/apis/txbuilder/basics) - build, sign and submit +- [Plans](/apis/txbuilder/plans) - what plans need from a provider +- [Time and Validity](/apis/txbuilder/time) - convert times to slots and run on a devnet +- [Offline and CBOR](/apis/txbuilder/offline) - build without a provider +- [Testing on the Emulator](/apis/txbuilder/testing) - a local ledger as the provider +- [Errors](/apis/txbuilder/errors) - `NETWORK_MISMATCH`, `CANNOT_OBSERVE` and the other codes +- [Providers](/providers) - Blockfrost and other providers +- [Hydra](/providers/hydra) - the Hydra provider +- [Package README](https://github.com/MeshJS/mesh/tree/main/packages/mesh-transaction) - every part, option and error diff --git a/content/docs/apis/txbuilder/offline.mdx b/content/docs/apis/txbuilder/offline.mdx new file mode 100644 index 0000000..184c324 --- /dev/null +++ b/content/docs/apis/txbuilder/offline.mdx @@ -0,0 +1,182 @@ +--- +title: "Offline and CBOR" +description: "Build without a provider, save and restore a built transaction, read one made elsewhere, find who must sign, and assemble one by hand." +--- + +## Overview + +`TxBuilder` needs no network when you give it the parameters and UTxOs, and it reads and writes transactions as CBOR (the hex form wallets and nodes take). Use this for a cold signer, a transaction another party built, a build that is sent later, a test fixture, or to assemble and price a transaction by hand. + +Examples use `builder`, `wallet`, `provider`, `recipient`, `changeAddress`, `utxos`, `unit`, `params` and `costModels` from [Transaction Basics](/apis/txbuilder/basics), and these names, which your application defines: + +- `built` - the `BuiltTx` that an earlier example of the page makes +- `utxo` - an output the build spends, as a Mesh `UTxO` +- `tx` - a transaction as a CBOR hex string +- `spent` - the UTxOs that `tx` spends, as Mesh `UTxO`s + +## Build Offline + +Give the builder `params` and `costModels`, name the payer as `{ changeAddress, utxos }`, and give outputs that a part names by out ref in `knownUtxos`. Then a build reads nothing, and the same arguments give the same bytes and `txHash`. `builder.chain()` returns the network, parameters and cost models of an online builder as data you can save. + +```tsx +import { output, spend, TxBuilder, validity } from "@meshsdk/core"; + +// Online, once: save what a build reads from the chain +const snapshot = await builder.chain(); + +// Offline, later: nothing is read +const offline = new TxBuilder({ ...snapshot }); +const built = await offline.build( + [ + spend.pubKey({ utxo: utxo.input }), // named by out ref + output({ address: recipient, value: { lovelace: 3_000_000n } }), + validity({ until: Date.now() + 60 * 60 * 1000 }), // build() sets no deadline + ], + { payer: { changeAddress, utxos }, knownUtxos: [utxo] }, +); +``` + +## Save and Restore a Built Transaction + +`JSON.stringify(built)` writes the unsigned transaction with its data and the signatures held so far. `builder.restore(json)` reads it back, in this process or another. It makes no request: it checks that `txHash` is the hash of the body and verifies every signature. + +A builder without a provider can build and sign. To send, `submit()` needs a `submitter` (`MISSING_SUBMITTER`) or a provider, and `awaitInclusion()` needs a provider (`MISSING_FETCHER`). A restored object holds no payer, so name the signers. + +```tsx +import { keySigner, output, TxBuilder } from "@meshsdk/core"; + +const offline = new TxBuilder({ network: "preprod", params, costModels }); +const built = await offline.build( + output({ address: recipient, value: { lovelace: 3_000_000n } }), + { payer: { changeAddress, utxos } }, +); +await built.sign({ signers: keySigner(process.env.TREASURY_SKEY!) }); +const saved = JSON.stringify(built); // keep it in a file or a database + +// Later, in a process with a provider +const online = new TxBuilder({ network: "preprod", provider }); +const again = await online.restore(JSON.parse(saved)); +await again.submit(); // a lost answer: call it again, never build again +await again.awaitInclusion(); +``` + +A record that is not what `toJSON` wrote is `INVALID_OPTION`, one of another network is `NETWORK_MISMATCH`, and one in a format this library does not read is `INVALID_STATE`. A plan has its own record: give its JSON to `builder.resume`, not to `restore` ([Servers and Storage](/apis/txbuilder/servers)). + +## Read a Transaction Built Elsewhere + +`builder.fromCbor(tx, { knownUtxos })` makes a `BuiltTx` of a transaction that exists only as CBOR, such as one another party built for you to sign. Nothing is built or balanced: the body you sign is the one you were given, byte for byte. The UTxOs of its inputs come from `knownUtxos`, else from the provider. Without a provider, give them all. + +```tsx +const received = await builder.fromCbor(tx, { knownUtxos: spent }); +const { outputs, fee, missing, collateral, warnings } = received; // read before you sign +await received.sign({ signers: wallet }); // there is no payer: name who signs +await received.submit(); // MISSING_SIGNATURES while a key is missing +``` + +Before you sign a transaction someone else built: + +- `outputs` and `fee` say what leaves your wallet +- `missing` lists the keys that must still sign, each with its roles +- `collateral` and `warnings` tell what a failing script would cost: `COLLATERAL_FORFEITED` says there is no collateral return, and `COLLATERAL_RETURN_ELSEWHERE` says a collateral input's owner is not the one the return pays +- whoever submits can mark the transaction as failing, whatever its scripts do. Then its collateral inputs are spent, and only the collateral return is paid. Judge `collateral` (`total`, `return`) and `warnings` as money you may lose +- `knownUtxos` is your own data: never take it from the party that made the transaction + +`partialTx` is the transaction with the signatures held so far, for the next party to sign. + +### When fromCbor Refuses a Transaction + +Text that is not a transaction in CBOR, or a transaction over the `maxTxSize` of your `params` (16 384 bytes without them), is `INVALID_OPTION`, and one for another network is `NETWORK_MISMATCH`. A native script it runs that the library cannot read, so that the signers cannot be listed, is `NATIVE_SCRIPT_UNREAD`. `details.reason` is `"depth"`, `"size"` or `"form"`. + +```tsx +import { TxError } from "@meshsdk/core"; + +try { + await builder.fromCbor(tx, { knownUtxos: spent }); +} catch (error) { + if (TxError.is(error, "NATIVE_SCRIPT_UNREAD")) { + console.log(error.details.scriptHash, error.details.reason); // do not sign it + } else throw error; +} +``` + +## Find Who Must Sign + +`requiredSigners(tx, spent, { maxTxSize })` lists the keys a transaction needs, with no builder and no provider. `spent` holds the UTxO of every input and collateral input, and of the reference inputs that hold native scripts. A missing one is `UTXO_NOT_FOUND`. Set `maxTxSize` to that of your network's protocol parameters. + +```tsx +import { requiredSigners } from "@meshsdk/core"; + +const { keyHashes, keys } = requiredSigners(tx, spent, { + maxTxSize: params.maxTxSize, +}); +for (const key of keys) console.log(key.keyHash, key.roles); +``` + +## Low-Level Helpers + +Most builds never need these. They put a transaction together and price it by hand, with no builder doing the balancing. + +### Assemble Without Balancing + +`assembleTxPrototype(parts, { fee })` is the last step of `build()`. It puts complete parts together and does nothing else: it selects no inputs, adds no change and runs no script, so the balance and the fee are yours. It returns a `prototype`, the transaction as a value. A serializer turns that into CBOR, and `builder.fromCbor` makes a `BuiltTx` that signs and submits it. `minFee` gives the least fee, so you can check yours. + +```tsx +import { + assembleTxPrototype, + cst, + minFee, + output, + spend, + toUtxo, +} from "@meshsdk/core"; + +const fee = 200_000n; +const input = toUtxo(utxo); +const { prototype } = assembleTxPrototype( + [ + spend.pubKey({ utxo: input }), + output({ address: recipient, value: { lovelace: 5_000_000n } }), + output({ + address: changeAddress, + value: { lovelace: input.value.lovelace - 5_000_000n - fee }, + }), + ], + { fee }, +); +const least = minFee(prototype, { params, vkeyWitnesses: 1, inputs: [input] }); +if (fee < least) throw new Error(`the fee is below the minimum, ${least}`); +const tx = new cst.CardanoSDKSerializer().serializeTxPrototype(prototype); +const final = await builder.fromCbor(tx, { knownUtxos: [input] }); +await final.sign({ signers: wallet }); // an object of fromCbor holds no payer +await final.submit(); +``` + +### Price a Fee or an Output + +`minCoin(output(...), params)` is the least lovelace an output holds. `minFee(prototype, { params, vkeyWitnesses, inputs })` is the least fee a transaction takes once the given number of keys have signed. Both are pure functions. + +```tsx +import { minCoin, minFee, output } from "@meshsdk/core"; + +const part = output({ address: recipient, value: { [unit]: 1n } }); +console.log(minCoin(part, params)); // lovelace the output needs + +console.log( + minFee(built.prototype, { + params, + vkeyWitnesses: 1, + inputs: built.inputs, + }), +); +``` + +## Related + +- [Transaction Basics](/apis/txbuilder/basics) - build, sign and submit +- [Signing and Submitting](/apis/txbuilder/signing) - signers, submitters and several signers +- [UTxOs and Inputs](/apis/txbuilder/utxos) - give the builder UTxOs in any form +- [Plans](/apis/txbuilder/plans) - use a transaction built elsewhere as a step +- [Errors](/apis/txbuilder/errors) - every code, and what a retry may repeat +- [Testing on the Emulator](/apis/txbuilder/testing) - run builds against a local ledger +- [Providers and Networks](/apis/txbuilder/networks) - what the builder asks a provider for +- [Package README](https://github.com/MeshJS/mesh/tree/main/packages/mesh-transaction) - every part, option and error diff --git a/content/docs/apis/txbuilder/options.mdx b/content/docs/apis/txbuilder/options.mdx new file mode 100644 index 0000000..0583a89 --- /dev/null +++ b/content/docs/apis/txbuilder/options.mdx @@ -0,0 +1,130 @@ +--- +title: "Options" +description: "Every option of TxBuilder, build() and plan(), with what it does and its default." +--- + +## Overview + +Options live in three places: the builder (`new TxBuilder({...})`, set once), a build (`builder.build(parts, {...})`, set per call) and a plan (`builder.plan(steps, {...})`, which takes the build options too). Use this page to find a name and its default. The calls of a `BuiltTx` and of a plan (`sign`, `submit`, `awaitInclusion`, `run`, `add`, `replan`, `resume`) refuse an unknown member with `INVALID_OPTION`. The options of the builder, `build()` and `plan()` are checked by type only, so rely on TypeScript to catch a misspelled name. + +Examples use the names of [Transaction Basics](/apis/txbuilder/basics): `provider`, `wallet`, `recipient` and `builder`. + +## Builder Options + +Give these to `new TxBuilder({...})`. Only `network` is required. With neither a `provider` nor `params`, the constructor throws `MISSING_PARAMETER`: there are no built-in parameter values. + +| Option | What it does | Default | +|--------|--------------|---------| +| `network` | `"mainnet"`, `"preprod"`, `"preview"` or `customNetwork(...)` for a devnet. Every address, wallet and provider is checked against it | required | +| `provider` | Reads the chain: outputs, parameters, cost models, the payer's UTxOs. Plans also read the tip | none | +| `params` | Protocol parameters (a `Protocol`), used instead of reading them | read from the provider | +| `costModels` | Cost models by Plutus language, V1 first (`number[][]`), used instead of reading them | read from the provider | +| `deposits` | `drepDeposit` and `govActionDeposit`, which `Protocol` does not carry | none | +| `submitter` | Sends transactions in place of the provider | the provider | +| `evaluator` | Works out execution units. `null` turns it off, and then every redeemer needs its own units. `provider` evaluates through the provider | a local evaluator | +| `serializer` | An `IMeshTxSerializer` with `serializeTxPrototype` | the built-in encoder | +| `planDefaults` | Defaults of plans: `ttlMs`, `expiryMarginMs`, `confirmations`, `pollMs`, `resendMs`. See [Plan Options](#plan-options) | built-in values | +| `store` | A `TxPlanStore` that records every plan, so it can be resumed by its `id` | none: plans are not recorded | + +## Build Options + +Give these to `builder.build(parts, {...})`. + +### Payer and Inputs + +| Option | What it does | Default | +|--------|--------------|---------| +| `payer` | Who pays and gets the change: a wallet, an address, or `{ changeAddress, utxos }` | none: `MISSING_PAYER` | +| `canSelect` | `(utxo) => boolean`: which of the payer's UTxOs may be selected. Script-locked UTxOs and UTxOs the parts read are never selected | all selectable UTxOs | +| `coinSelection` | `(need, candidates) => outRefs`: replaces the built-in selection for this build | the built-in selection | +| `sendAllTo` | Spends every selectable UTxO and sends what is left to this address | none | +| `knownUtxos` | Outputs that parts name by out ref and the provider may not know yet | none | +| `after` | Transactions built before and not yet seen by the provider (a `BuiltTx`, a `TxPlan` or a list). Their inputs are not selected again, and their outputs can be spent | none | + +### Fee, Collateral and Keys + +| Option | What it does | Default | +|--------|--------------|---------| +| `fee` | A fee in lovelace (`bigint`) that goes into the body as given. Too low is `FEE_TOO_LOW`; above the minimum is the warning `FEE_ABOVE_MINIMUM` | worked out | +| `topUpCollateral` | `true`: collateral inputs you give that do not cover the collateral get more from the payer. `false`: they are used as given, and a shortfall is `INSUFFICIENT_COLLATERAL` | `true` | +| `collateralReturn` | `true`: the transaction states its total collateral and returns the rest. `false`: collateral inputs only, with all of their lovelace at stake (`COLLATERAL_FORFEITED`) | `true` | +| `extraKeyWitnesses` | A number: key witnesses expected beyond those the parts call for | none | +| `registeredPools` | Operator key hashes of pools that are already registered | none | + +### Control + +| Option | What it does | Default | +|--------|--------------|---------| +| `signal` | An `AbortSignal`. Aborting it ends the build with `ABORTED` | none | +| `trace` | Receives the steps of the build (`payer`, `fetched`, `round`, `evaluated`), for diagnostics | none | + +## Set Builder and Build Options + +Builder options go in the constructor, and build options in the second argument of `build()`. A build option applies to that call only. + +```tsx +import { output, TxBuilder } from "@meshsdk/core"; + +// Builder options: set once +const builder = new TxBuilder({ + network: "preprod", + provider, + planDefaults: { confirmations: 10 }, +}); + +// Build options: set per build +const built = await builder.build( + output({ address: recipient, value: { lovelace: 5_000_000n } }), + { + payer: wallet, + canSelect: (utxo) => utxo.value.lovelace > 3_000_000n, // skip small UTxOs + signal: AbortSignal.timeout(30_000), // give up after 30 seconds + }, +); +``` + +## Plan Options + +`builder.plan(steps, {...})` takes the build options and these. With named steps, give `sendAllTo` and `fee` inside the step. The three deadlines are worked out once, when the plan is made, and recorded in it. + +| Option | What it does | Default | +|--------|--------------|---------| +| `id` | Your id for the plan, shown as `plan.id`. Required on a builder with a `store` | none | +| `consolidate` | `true`: when a step's inputs do not fit one transaction, the plan adds consolidation steps before it. `{ maxSteps }` limits them (1 to 31). `false`: that step is `TX_TOO_LARGE` | `true`, up to 4 steps | +| `ttlMs` | How long a step is valid when its parts set no `validity({ until })`, and the time left to sign it | `600_000` (10 minutes) | +| `expiryMarginMs` | The wait after a step's end of validity before the plan calls it `expired` | `600_000` (10 minutes) | +| `confirmations` | Blocks on top of a step's block before it is `final` | `30` | + +`planDefaults` of the builder gives these three their defaults, and adds `pollMs` (`5_000`, the pause between two looks at the chain) and `resendMs` (`120_000`, how often the same bytes of a sent step go again while it is not found). + +`plan.run({...})` takes options of its own. They are never recorded in the plan. + +| Option | What it does | Default | +|--------|--------------|---------| +| `signers` | Who signs a step that still needs signatures | the payer | +| `submitter` | Who sends. A wallet sends only when it is given as a `submitter`, here or to the builder. The payer never sends by itself | the builder's `submitter`, else the provider | +| `waitFor` | How far `run()` goes: `"sent"`, `"included"` or `"final"` | `"included"` | +| `timeoutMs` | How long `run()` waits for a block, then `CONFIRM_TIMEOUT` | `120_000`; for `"final"`, `confirmations × 30_000 + 120_000` | +| `pollMs` | The pause between two looks at the chain | `planDefaults`, else `5_000` | +| `signal` | Aborts the call with `ABORTED` | none | + +```tsx +import { output } from "@meshsdk/core"; + +const plan = await builder.plan( + { pay: output({ address: recipient, value: { lovelace: 5_000_000n } }) }, + { payer: wallet, id: "payment-1", ttlMs: 20 * 60_000 }, // 20 minutes to sign +); +await plan.run({ waitFor: "final", timeoutMs: 30 * 60_000 }); +``` + +`built.sign({ signers, partial })`, `built.submit({ submitter })` and `built.awaitInclusion({ timeoutMs, pollMs })` take options too: see [Signing and Submitting](/apis/txbuilder/signing). + +## Related + +- [Transaction Basics](/apis/txbuilder/basics) - the builder, the payer, signing and submitting +- [Plans](/apis/txbuilder/plans) - how the plan options work together +- [Signing and Submitting](/apis/txbuilder/signing) - signers, submitters and partial signing +- [Errors](/apis/txbuilder/errors) - the error codes these options can raise +- [Migrating to TxBuilder](/apis/txbuilder/migration) - move from the `MeshTxBuilder` chain +- [Package README](https://github.com/MeshJS/mesh/tree/main/packages/mesh-transaction) - every option in full diff --git a/content/docs/apis/txbuilder/plans.mdx b/content/docs/apis/txbuilder/plans.mdx new file mode 100644 index 0000000..0bcace9 --- /dev/null +++ b/content/docs/apis/txbuilder/plans.mdx @@ -0,0 +1,213 @@ +--- +title: "Plans" +description: "Send one transaction or several in order with plan(): built once, never rebuilt, so every call can be repeated." +--- + +## Overview + +A plan is a group of transactions built at once and sent in order. `builder.plan()` builds all of them and signs and sends nothing. `plan.run()` then signs, sends and waits for each one in turn. A plan is never rebuilt, so any call can be repeated and sends the same bytes. Use one for transactions that depend on each other, for a retry that must not pay twice, or to wait for blocks. + +Examples use `builder`, `wallet`, `recipient` and `partner` from [Transaction Basics](/apis/txbuilder/basics), and these names, which your application defines: + +- `script` - a Plutus script, `{ code, version }` +- `partnerTx` - a transaction as CBOR hex that another party built +- `plan` - the plan made in Make and Run a Plan +- `provider` - a provider that returns block heights and the validity flag: see [Providers and Networks](/apis/txbuilder/networks#use-blockfrost-for-plans) + +## Make and Run a Plan + +`builder.plan(parts, { payer })` takes the same parts and payer as `build()`. A plan of one list of parts has one step, named `main`. `run()` signs it as the payer, sends it and waits until it is in a block. + +```tsx +import { output } from "@meshsdk/core"; + +const plan = await builder.plan( + output({ address: recipient, value: { lovelace: 5_000_000n } }), + { payer: wallet }, +); // built; nothing is signed or sent +await plan.run(); +console.log(plan.step("main").txHash, plan.status); +``` + +> **Note:** `plan()` needs a provider that returns block heights and the validity flag. The plain `BlockfrostProvider` does not, and `plan()` throws `CANNOT_OBSERVE` before anything is signed: see [Providers and Networks](/apis/txbuilder/networks#use-blockfrost-for-plans). `build()` needs neither. + +## Send Several Transactions + +Give named steps as an object. `run()` sends them one after another: + +- Order: the steps go in the order of the keys, and a step is sent only when every step before it is in a block. +- Names: a name is not empty, is not a whole number and does not start with `consolidate-`. A plan has at most 32 steps. +- Change: a step built from parts spends the change of the step before it, so it cannot land without it. +- Payer: a step may be `{ parts, payer }` to pay from another payer. That payer does not sign by default: name a signer for it in `run({ signers })`. + +```tsx +import { output } from "@meshsdk/core"; + +const plan = await builder.plan( + { + first: output({ address: recipient, value: { lovelace: 5_000_000n } }), + second: output({ address: partner, value: { lovelace: 2_000_000n } }), + }, + { payer: wallet }, +); // both are built; nothing is on chain yet +console.log(plan.fee, plan.steps.map((step) => step.standsOn)); // the fees of both; the steps each stands on +await plan.sign(); // signs every step before anything is sent +await plan.run(); // first, a block, then second +``` + +## Link Steps + +Where a part takes a UTxO (`spend.*`, `referenceInput`, `collateral`), it can name an output of an earlier step by a link. Nothing is looked up and no hash is written by hand. `{ step: "lock", output: "vault" }` names the output of the part labelled `vault`, and `{ step: "lock", output: 0 }` the output at that position. `{ step: "lock", change: true }` names every change output of that step, for `spend.pubKey`. Outside a plan a link is `UNRESOLVED`. For a step you already built, `outputOf(built, label)` gives its output to a later plan, as in `utxo: outputOf(plan.step("lock"), "vault")`. + +```tsx +import { mConStr0, output, spend } from "@meshsdk/core"; + +const plan = await builder.plan( + { + lock: output({ + address: builder.scriptAddress(script), + value: { lovelace: 10_000_000n }, + datum: { type: "inline", data: mConStr0([]) }, + label: "vault", // links name this output + }), + unlock: [ + spend.plutus({ + utxo: { step: "lock", output: "vault" }, + script, + redeemer: { data: mConStr0([]) }, + }), + spend.pubKey({ utxo: { step: "lock", change: true } }), // all the change of lock + output({ address: recipient, value: { lovelace: 4_000_000n } }), + ], + }, + { payer: wallet }, +); +await plan.run(); // lock, a block, then unlock +``` + +## Read the Statuses + +Every step has a status, and so does the plan. A payment is paid when its step is `final`. Release goods then, never at `included`, which a rollback can undo. A plan is not atomic: step one may be `final` while step two never lands, so read the status of each step. + +| Step | Meaning | +|------|---------| +| `built`, `signed` | signatures are missing; fully signed but not sent yet | +| `sent` | delivered: accepted, or the outcome is unknown | +| `rejected` | the ledger refused it, but it may still land: `run()` sends the same bytes again | +| `included` | in a block; a rollback can undo it | +| `final` | enough blocks on top (`confirmations`); never changes | +| `expired` | past its end of validity and the margin, and not found, though it is still looked for | +| `failed` | in a block with a failed script; its collateral is taken | +| `orphaned` | a step it stands on will not land | + +The plan is `pending` while it may still complete, `stopping` when it does not go on but a step may still land, `stopped` when it does not go on and, by what the chain shows, nothing more is expected to land, and `final` when every step is `final`. A later look can still find a step and move a `stopped` plan to `stopping` or `final`, so pay what is left only with `replan`. `plan.stop()` ends a plan: it signs and sends nothing more. + +```tsx +await plan.run({ waitFor: "final" }); // waits for `confirmations` blocks on top +console.log(plan.status, plan.steps.map((step) => `${step.name}: ${step.status}`)); // final when every payment is paid +``` + +## Add Steps to a Plan + +`plan.add(steps)` puts named steps at the end of a plan that is `pending`. It builds them at once, signs and sends nothing, and returns the plan. A `run()` that is going takes the new steps in their turn. The same call again builds nothing, so read `plan.status` after it. On a `final`, `stopping` or `stopped` plan it throws `INVALID_STATE`: new content for it is a new plan. + +```tsx +import { output } from "@meshsdk/core"; + +await plan.add({ + refund: output({ address: recipient, value: { lovelace: 2_000_000n } }), +}); // built now, paid by the plan's payer +if (plan.status === "pending") await plan.run(); +``` + +## Use a Transaction Built Elsewhere + +A step may be a transaction another party built: give it as a `BuiltTx` or as CBOR hex. A plan signs it as it signs its own steps: with the call's `signers`, or, when the call names none, with the plan's payer if it can sign. It keeps the witnesses the transaction came with. Read it first with [`builder.fromCbor()`](/apis/txbuilder/offline#read-a-transaction-built-elsewhere), which shows its outputs, fee and missing keys. Keep any key you do not want used on it out of the call's signers, and out of the payer when the call names none. + +```tsx +import { output } from "@meshsdk/core"; + +const swap = await builder.fromCbor(partnerTx); // read it first: outputs, fee, missing keys +const swapPlan = await builder.plan( + { + swap, + pay: output({ address: recipient, value: { lovelace: 1_000_000n } }), + }, + { payer: wallet }, // the wallet signs both +); +await swapPlan.run(); +``` + +## Set Deadlines and Waiting + +Three deadlines belong to the plan. They are taken from the plan's options, else from the builder's `planDefaults`, else the built-in values, and are fixed and recorded when the plan is made. The defaults are in [Options](/apis/txbuilder/options#plan-options). + +| Deadline | What it sets | +|----------|--------------| +| `ttlMs` | how long a step is valid, which is also the time left to sign it | +| `expiryMarginMs` | how long after its end of validity a step waits before it is `expired` | +| `confirmations` | blocks on top of a step's block before it is `final` | + +A step whose parts give `validity({ until })` keeps that end. A step that runs a Plutus script may not end past the network's horizon (36 hours on mainnet and preprod), else `INVALID_STATE`. `0` for `expiryMarginMs` and `confirmations` is for tests only. + +The waiting options belong to one call of `run()` and are never recorded: + +| Option | What it sets | +|--------|--------------| +| `waitFor` | how far `run()` goes: `"sent"`, `"included"` or `"final"` | +| `timeoutMs` | how long `run()` waits for a block, then `CONFIRM_TIMEOUT` | +| `pollMs` | the pause between two looks at the chain | + +`CONFIRM_TIMEOUT` is a wait, not a failure: call `run()` again. The builder's `planDefaults` sets the deadlines and `pollMs` for every plan it makes. + +```tsx +import { output } from "@meshsdk/core"; + +const slow = await builder.plan( + output({ address: recipient, value: { lovelace: 5_000_000n } }), + { payer: wallet, ttlMs: 1_200_000, confirmations: 180 }, // this plan only +); +await slow.run({ waitFor: "final", pollMs: 60_000 }); // this call only +``` + +## Handle a Step That Does Not Go Through + +`run()` throws `EXPIRED`, `SCRIPT_FAILED` or `ORPHANED` when a step will not land. The error names the step in `error.step`, and the plan does not go on. `plan.landed` lists the steps in a block, and `plan.rest` what is left. A plan in its place pays what is left: `plan.replan({ id })`. It marks the old plan first, never builds a `final` step again, and carries on a step that is in a block. Never call `builder.plan(plan.rest)`: nothing keeps that plan apart from the old one. + +```tsx +import { output, TxError } from "@meshsdk/core"; + +const plan = await builder.plan( + { + a: output({ address: recipient, value: { lovelace: 5_000_000n } }), + b: output({ address: partner, value: { lovelace: 3_000_000n } }), + }, + { id: "order-7", payer: wallet }, +); +try { + await plan.run(); +} catch (error) { + if (!TxError.is(error, "EXPIRED", "SCRIPT_FAILED", "ORPHANED")) throw error; + console.log(error.step, plan.landed.map((step) => step.name)); // b, and [a] +} +// later, once no step may still land outside a block +await plan.refresh(); // one look at the chain; it never signs or sends +if (plan.steps.some((step) => step.status === "failed")) { + console.error("give new steps: replan({ id, steps })", plan.id); +} else if (plan.live.length === 0 && plan.status !== "final") { + const next = await plan.replan({ id: plan.replacedBy ?? "order-7:2" }); + await next.run(); // pays what is left, once +} +``` + +`replan` may wait, with `CANNOT_OBSERVE` or `STILL_LIVE`, when an old transaction may still land: call it again later. The same call again returns the same plan. A step that failed its script needs new parts, so `replan` without `steps` refuses it: give them as `replan({ id, steps })`. + +## Related + +- [Transaction Basics](/apis/txbuilder/basics) - build, sign and submit one transaction +- [Servers and Storage](/apis/txbuilder/servers) - record plans so a server can restart and resume +- [Errors](/apis/txbuilder/errors#errors-from-waiting-and-plans) - the codes a plan throws +- [Options](/apis/txbuilder/options#plan-options) - every plan option with its default +- [UTxOs and Inputs](/apis/txbuilder/utxos#spend-many-small-utxos-with-a-plan) - consolidation steps for a wallet with many small UTxOs +- [Providers and Networks](/apis/txbuilder/networks#use-blockfrost-for-plans) - a provider that plans can use +- [Package README](https://github.com/MeshJS/mesh/tree/main/packages/mesh-transaction) - every plan option, status and error diff --git a/content/docs/apis/txbuilder/servers.mdx b/content/docs/apis/txbuilder/servers.mdx new file mode 100644 index 0000000..7f85990 --- /dev/null +++ b/content/docs/apis/txbuilder/servers.mdx @@ -0,0 +1,160 @@ +--- +title: "Servers and Storage" +description: "Record plans in a store so a server can restart, share work between instances and wait days for signatures." +--- + +## Overview + +A plan lives in its object unless the builder has a `store`. With a store every plan is recorded under an `id`, and any process can find it again with `builder.resume(id)`. Use it on a server, where a process can crash after sending, several instances share the work, or a signature takes days. Read [Plans](/apis/txbuilder/plans) first. + +Examples use `wallet`, `recipient` and `partner` from [Transaction Basics](/apis/txbuilder/basics), and these names, which your application defines: + +- `provider` - a provider that returns block heights and the validity flag: see [Providers and Networks](/apis/txbuilder/networks#use-blockfrost-for-plans) +- `store` - a `TxPlanStore`: `memoryPlanStore()` in tests, or your own (see [Write a Store](#write-a-store)) +- `builder` - a `TxBuilder` made with that `store`, as in the next section +- `userAddress` - the address of a user who signs in a browser +- `firstWitnessSet`, `secondWitnessSet` - witness sets as hex, from a wallet's `signTx(tx, true)` + +## Record Plans in a Store + +Give the builder a `store`. Every change is saved before the method returns: a new plan before it is returned, a delivery before the bytes leave. Without a store a plan lives in its object only. To keep it yourself, save `JSON.stringify(plan)` and give `JSON.parse(saved)` to `builder.resume`: a string is taken as an id. + +```tsx +import { memoryPlanStore, TxBuilder } from "@meshsdk/core"; + +const builder = new TxBuilder({ + network: "preprod", + provider, + store: memoryPlanStore(), // for tests; a server gives its own store +}); +``` + +> **Note:** A redeemer may be a function of the final transaction, as in [Spend from a Script](/apis/txbuilder/smart-contracts#spend-from-a-script). A function cannot be recorded, so `builder.plan()` on a builder with a store throws `NOT_SERIALIZABLE`. Use a second builder without a store for those plans: they live in memory and are lost with the process. + +## Use One Id for One Plan + +On a builder with a store every plan needs an `id` (`MISSING_ID`). The same id with the same steps and options returns the recorded plan and builds nothing, so a repeated request handler is safe. Other steps or options under a known id are `PLAN_EXISTS`, and nothing is written. A new id is a new order: the same steps under a new id are paid again. + +```tsx +import { output } from "@meshsdk/core"; + +const pay = output({ address: recipient, value: { lovelace: 5_000_000n } }); +const plan = await builder.plan(pay, { id: "order-7", payer: wallet }); +const again = await builder.plan(pay, { id: "order-7", payer: wallet }); // the recorded plan +const later = await builder.resume("order-7", { payer: wallet }); // from any instance +``` + +## Build Without Keys on a Server + +The server builds with the user's address as payer and returns the unsigned body. The user signs in the browser, and any instance adds the signature and sends. The store's compare-and-set makes several instances safe: two of them never record two plans under one `id`. + +```tsx +import { output } from "@meshsdk/core"; + +export async function buildPayment(orderId: string, lovelace: bigint) { + const plan = await builder.plan( + output({ address: recipient, value: { lovelace } }), + { id: orderId, payer: userAddress }, + ); // recorded before it returns + return { tx: plan.step("main").tx }; // the body without signatures +} + +// in the browser: const witnessSet = await api.signTx(tx, true); + +export async function submitPayment(orderId: string, witnessSet: string) { + const plan = await builder.resume(orderId); // any instance + await plan.addWitnesses(witnessSet); // INVALID_WITNESS when it is not of this body + await plan.run({ waitFor: "sent" }); // looks, records the delivery, then submits + return { orderId, txHash: plan.step("main").txHash }; // the hash never changes +} +``` + +The store does not keep plans with different ids apart. Payouts from one wallet on several instances may select the same UTxO, and one of them is refused. Give each instance its own UTxOs with `canSelect`, or send one payer's payouts one after another with `after`. + +## Resume After a Crash + +`run()` records a delivery as "outcome unknown" before the bytes leave. After a crash, resume the plan by its id and run it again: it sends the same bytes. `resume` reads the store only. It asks the chain nothing and does not call the payer, so give the payer again, and the `signers` and `submitter` in each `run()`. + +```tsx +const resumed = await builder.resume("payout-7", { payer: wallet }); // live objects are given again +await resumed.run({ waitFor: "final" }); // looks first; the same bytes go again if needed +``` + +| Crash | In the store | After `resume` | +|-------|--------------|----------------| +| before the delivery is recorded | `signed` | `run()`: the first delivery | +| after it, before the answer | `sent`, outcome unknown | `run()`: the same bytes | +| between signatures | the signatures received | `addWitnesses` with the rest | +| while `builder.plan()` builds | nothing, or the plan with nothing signed | the same `builder.plan()` call | + +## Collect Signatures Over Several Days + +Give the plan a long `ttlMs`. The unsigned body goes to every signer, and each witness set is added on any instance as it arrives. A body with some signatures may still land until its end of validity, since the others may sign it. A step that runs a Plutus script cannot be valid for days: its end may not pass the network's horizon (36 hours on mainnet and preprod). + +```tsx +import { guard, output } from "@meshsdk/core"; + +const plan = await builder.plan( + [ + output({ address: recipient, value: { lovelace: 50_000_000n } }), + guard.pubKey({ address: partner }), // a second key must sign + ], + { id: "payout-17", payer: userAddress, ttlMs: 3 * 86_400_000 }, // three days, recorded +); +const { tx } = plan.step("main"); // goes to both signers +const monday = await builder.resume("payout-17"); // any instance +await monday.addWitnesses(firstWitnessSet); // recorded; the partner is still missing +const wednesday = await builder.resume("payout-17"); +await wednesday.addWitnesses(secondWitnessSet); // now "signed" +await wednesday.run({ waitFor: "final" }); +``` + +## Reconcile Unfinished Plans + +Keep the id of every plan that is not `final` in your database, with the payout it pays. Write it before the plan's first `await`: a crash inside `run()` may come after the bytes have left. Remove it only when a plan of its line is `final`. A retried job uses the same id, never a fresh one. Once a minute and after a restart, run this pass. + +```tsx +// db is your database: openPlanIds() lists the ids of plans that are not final +for (const id of await db.openPlanIds()) { + try { + const plan = await builder.resume(id, { payer: wallet }); + await plan.refresh(); // one look at the chain; it never signs or sends + await plan.run({ waitFor: "sent" }); // what can be done at once + if (plan.status === "final") await db.close(id); // release the goods + } catch (error) { + console.error(id, error); // the next pass repeats the call + } +} +``` + +Errors with `retryable: true` are a wait, not a failure. With `waitFor: "sent"` each pass moves a plan one step on. A plan you stop on purpose with `stop()` does not leave the list by itself: remove its id yourself, for example with `db.close(id)`. Otherwise every pass reports it, and a pass that also calls `replan` pays what is left of it. + +When a step will not land, a plan in its place pays what is left. Add `replan` to the pass as [Handle a Step That Does Not Go Through](/apis/txbuilder/plans#handle-a-step-that-does-not-go-through) shows. A plan with a step that failed its script stays in the list until you give new `steps` to `replan({ id, steps })`. + +## Write a Store + +A `TxPlanStore` has two methods, `load` and `save`. A store must: + +- return from `load(id)` the record saved last, exactly as saved, or `undefined` (never `null`) +- make `save(json, expectedRev)` a compare-and-set: it writes only when the stored `rev` is `expectedRev` (0: when none is stored), and `json.rev` is `expectedRev + 1`. It returns `true` when written and `false` when another revision is stored. A throw means the write may have passed: `STORE_FAILED` +- keep the record as data, with no member of your own: `_id` or `updatedAt` inside it makes every read throw `INVALID_STATE`, so keep such columns beside it +- keep a record while its plan is not `final` + +A store without compare-and-set can record two plans under one `id`, and the library cannot detect it. In a browser, two tabs on one key are two writers: keep one plan to one tab. Run `checkPlanStore(store)` once when you set a store up. It checks two writers, a lost acknowledgement and a crash between a write and a send. + +```tsx +import { checkPlanStore } from "@meshsdk/core"; + +await checkPlanStore(store); // your own store, once, when you set it up +``` + +The package README has a store over a SQL database and one for a browser: see [Storage](https://github.com/MeshJS/mesh/tree/main/packages/mesh-transaction#storage). + +## Related + +- [Plans](/apis/txbuilder/plans) - statuses, links between steps, deadlines and replan +- [Signing and Submitting](/apis/txbuilder/signing#sign-in-turns) - witness sets from several parties +- [Errors](/apis/txbuilder/errors#errors-from-waiting-and-plans) - `PLAN_EXISTS`, `STORE_FAILED` and the other store codes +- [Testing on the Emulator](/apis/txbuilder/testing) - run plans against a local ledger, with `memoryPlanStore()` +- [Transaction Basics](/apis/txbuilder/basics) - build, sign and submit one transaction +- [Package README](https://github.com/MeshJS/mesh/tree/main/packages/mesh-transaction) - the plan record, other stores and every error diff --git a/content/docs/apis/txbuilder/signing.mdx b/content/docs/apis/txbuilder/signing.mdx new file mode 100644 index 0000000..c25529a --- /dev/null +++ b/content/docs/apis/txbuilder/signing.mdx @@ -0,0 +1,196 @@ +--- +title: "Signing and Submitting" +description: "Choose who pays, signs and submits a transaction: wallets, private keys, your own signer, several signers, and what to do when a step fails." +--- + +## Overview + +`build()` signs and sends nothing. You name who signs and who sends, one call at a time. This page is for when the payer's wallet is not the only signer, when a key lives in your own service, or when a call fails and you must retry safely. The basic path is in [Transaction Basics](/apis/txbuilder/basics#build-sign-and-submit). + +Examples use `builder`, `wallet`, `provider`, `changeAddress` and `recipient` from there, and these names, which your application defines: + +- `built` - the `BuiltTx` that an earlier example of the page makes +- `api` - a CIP-30 wallet api (the connection a browser wallet gives), from `window.cardano..enable()` +- `vault` - your own key service +- `witnessSet` - a witness set (the signatures of one party, as hex) made elsewhere +- `coldKey` - a signing key that never touches the building machine + +## Who Pays, Signs and Submits + +Each role is named at a different place. The builder keeps none of them. + +| Role | Named in | When it is not named | +|------|----------|----------------------| +| Payer: pays and gets the change | `payer` of `build()` | `MISSING_PAYER` | +| Signer | `signers` of `sign()` | the payer signs, if it can (a wallet); else `MISSING_SIGNATURES` | +| Submitter | `submitter` of `submit()`, else `submitter` of the builder | the provider; with none, `MISSING_SUBMITTER` | + +```tsx +import { output, TxBuilder } from "@meshsdk/core"; + +const built = await builder.build( + output({ address: recipient, value: { lovelace: 5_000_000n } }), + { payer: changeAddress }, // an address pays but cannot sign +); +await built.sign({ signers: wallet }); // the wallet signs +await built.submit({ submitter: wallet }); // the wallet sends +// A builder may hold a submitter for every call +const shop = new TxBuilder({ network: "preprod", provider, submitter: wallet }); +``` + +## Use a Browser Wallet + +A CIP-30 api is a payer and a signer. It submits only if it has `submitTx`, which `canSubmit(api)` checks. A `BrowserWallet` does all three without a check. A failed `submitTx` is `SUBMIT_FAILED`, and the wallet's code is in `details.walletCode`. For DRep keys, see [Governance Transactions](/apis/txbuilder/governance). + +```tsx +import { canSubmit, output } from "@meshsdk/core"; + +const built = await builder.build( + output({ address: recipient, value: { lovelace: 5_000_000n } }), + { payer: api }, // its address and UTxOs are read +); +await built.sign(); // the wallet signs +await built.submit(canSubmit(api) ? { submitter: api } : {}); // else the provider sends +``` + +## Sign with a Private Key + +`keySigner(key)` makes a signer of a key. A malformed key throws `INVALID_OPTION` from `keySigner` itself. The key stays inside: it is in no error and no JSON. + +| Key | Written as | +|-----|------------| +| Signing key, 32 bytes | hex; the `cborHex` of a signing key file (`5820...`); bech32 `ed25519_sk` or `_sk` | +| Extended signing key | hex of 64 bytes; the `cborHex` of an extended key file (`5880...`); bech32 `ed25519e_sk` (64 bytes) or `_xsk` (96 or 128 bytes) | + +`` is `addr`, `stake`, `drep`, `cc_cold`, `cc_hot`, `pool`, `addr_shared` or `stake_shared`. `policy_sk` works too, and `policy_xsk` does not. A mnemonic, a root key (`xprv`, `root_xsk`) or an account key (`acct_xsk`) needs a derivation path, so give it to a `MeshWallet`. + +```tsx +import { keySigner, output } from "@meshsdk/core"; + +const built = await builder.build( + output({ address: recipient, value: { lovelace: 5_000_000n } }), + { payer: changeAddress }, +); +await built.sign({ signers: keySigner(process.env.TREASURY_SKEY!) }); +``` + +## Sign with Your Own Code + +For a key service or a hardware module, give a signer of hashes: an object with `signTxHash`, or that function alone. It gets `txHash` (the hash of the transaction body) and `keys`, the keys still needed, each as `{ keyHash, roles }`. Answer `{ vkey, signature }` in hex for each key you hold, signing the 32 bytes of `txHash`, not its hex text. To decline, throw `TxPlanError("SIGN_DECLINED", reason)`. + +The roles say why a key is asked, for your own decision and display: + +- `"input"`, `"collateral"`, `"certificate"`, `"withdrawal"`, `"vote"`, `"proposal"`, `"guard"`, `"poolOwner"` - what the transaction needs the signature for +- `"nativeScript"` - a native script of the transaction names the key. Such a key alone need not sign: the script decides + +```tsx +import type { TxHashSigner } from "@meshsdk/core"; + +const service: TxHashSigner = { + async signTxHash({ txHash, keys }) { + const held = (keys ?? []).filter(({ keyHash }) => vault.has(keyHash)); + return Promise.all( + held.map(async ({ keyHash }) => ({ + vkey: vault.publicKey(keyHash), + signature: await vault.sign(keyHash, txHash), + })), + ); + }, +}; +await built.sign({ signers: service }); +``` + +## Sign with Several Signers + +`signers` takes a list. Each signer is asked, in order, for the keys that have not signed yet. `built.missing` lists the keys still without a signature, each with its `roles`. A missing key is no error by default, so parties can sign one after another. With `partial: false`, `sign()` throws `MISSING_SIGNATURES` if a key is still missing. `submit()` checks the same and sends nothing. + +```tsx +import { keySigner } from "@meshsdk/core"; + +await built.sign({ + signers: [wallet, keySigner(process.env.PARTNER_SKEY!)], + partial: false, // MISSING_SIGNATURES unless every key signed +}); +``` + +## Sign in Turns + +When another party signs in their own program, hand over `built.partialTx`: the transaction with the signatures held so far. What they return, a witness set or a signed transaction, goes to `addWitnesses()`. Every witness is checked against the body: one of another transaction is `INVALID_WITNESS`. The ledger refuses `partialTx` while a key is missing. + +```tsx +await built.sign(); // the payer signs +console.log(built.missing); // the partner's key, with its roles +const forPartner = built.partialTx; // goes to the partner, for example to a wallet's signTx(forPartner, true) +await built.addWitnesses(witnessSet); // what the partner returns +await built.submit(); +``` + +## Sign on a Cold Machine + +Send `built.tx` to a machine that holds the key and has no builder. `signWitnesses(signer, tx)` returns its witness set, and the building machine adds it. + +```tsx +import { keySigner, signWitnesses } from "@meshsdk/core"; + +const witnessSet = await signWitnesses(keySigner(coldKey), built.tx); // on the cold machine +await built.addWitnesses(witnessSet); // back on the building machine +await built.submit(); +``` + +## Submit and Wait + +`submit()` sends the same bytes every time it is called. `awaitInclusion()` looks for the transaction until the provider finds it in a block, and returns `{ txHash, slot, block, blockHeight }` as far as the provider gives them. That is one sighting, and a rollback can undo it. `sign()`, `submit()` and `awaitInclusion()` take a `signal` to stop their waiting. + +```tsx +await built.submit({ submitter: wallet }); // the call's, else the builder's, else the provider +const { slot } = await built.awaitInclusion({ timeoutMs: 10 * 60_000 }); // 120 000 by default +``` + +## When a Signer Refuses + +Nothing is sent while a signature is missing, and a refusal changes nothing. Ask again on the same `built`: the transaction and its `txHash` stay the same, so never build again for it. + +| Code | What to do | +|------|------------| +| [`SIGN_DECLINED`](/apis/txbuilder/errors#errors-when-signing-and-submitting) | Ask again, or drop the transaction | +| [`SIGNER_FAILED`](/apis/txbuilder/errors#errors-when-signing-and-submitting) | Connect again. With `details.reason` `"accountChanged"` the user must be back on the account that pays, as the transaction spends its UTxOs | +| [`MISSING_SIGNATURES`](/apis/txbuilder/errors#errors-when-signing-and-submitting) | Name more signers: `error.details.missing` lists the keys | + +```tsx +import { TxError } from "@meshsdk/core"; + +try { + await built.sign(); +} catch (error) { + if (!TxError.is(error, "SIGN_DECLINED")) throw error; // nothing was sent + await built.sign(); // ask again: the same transaction +} +``` + +## Retry Without Rebuilding + +Call `submit()` or `awaitInclusion()` again on the same `built`, and never build again ([why](/apis/txbuilder/basics#build-sign-and-submit)). [Errors](/apis/txbuilder/errors#handle-errors-around-build-and-submit) has a loop that does this. To survive a restart, save `JSON.stringify(built)` and bring it back with `builder.restore(JSON.parse(saved))`: see [Save and Restore](/apis/txbuilder/offline#save-and-restore-a-built-transaction). + +| Code | What to do | +|------|------------| +| [`SUBMIT_FAILED`](/apis/txbuilder/errors#errors-when-signing-and-submitting) | The outcome is unknown: `submit()` again, then look with `awaitInclusion()`. After `unauthorized`, fix the API key first | +| [`CONFIRM_TIMEOUT`](/apis/txbuilder/errors#errors-from-waiting-and-plans) | Not found in time, which is not "not paid": `awaitInclusion()` again | +| [`REJECTED`](/apis/txbuilder/errors#errors-when-signing-and-submitting) | No retry. Look for the transaction before you decide anything | + +```tsx +const saved = JSON.stringify(built); // in a file or a database +// after a restart, in a process that has a builder +const again = await builder.restore(JSON.parse(saved)); +await again.submit(); // the same bytes +``` + +## Related + +- [Transaction Basics](/apis/txbuilder/basics) - build, sign and submit in one path +- [Plans](/apis/txbuilder/plans) - send transactions in order, with retries that cannot pay twice +- [Offline and CBOR](/apis/txbuilder/offline) - save and restore, and sign on a cold machine +- [Errors](/apis/txbuilder/errors) - every code and which a retry can fix +- [UTxOs and Inputs](/apis/txbuilder/utxos) - choose what a transaction spends +- [Time and Validity](/apis/txbuilder/time) - give a transaction a deadline +- [Wallets](/apis/wallets) - `MeshWallet` and `BrowserWallet` +- [Package README](https://github.com/MeshJS/mesh/tree/main/packages/mesh-transaction) - every part, option and error diff --git a/content/docs/apis/txbuilder/smart-contracts.mdx b/content/docs/apis/txbuilder/smart-contracts.mdx index 23c9c22..7d381de 100644 --- a/content/docs/apis/txbuilder/smart-contracts.mdx +++ b/content/docs/apis/txbuilder/smart-contracts.mdx @@ -5,9 +5,9 @@ description: "Lock assets at a script address and spend them with a Plutus scrip ## Overview -A script holds assets through an ordinary `output` at its address, and a `spend.plutus` part unlocks them. The builder reads the datum from the output, adds collateral (ada the network can take if a script fails), evaluates execution units and orders inputs and redeemers. You do not set them. +A script holds assets through an ordinary `output` at its address, and a `spend.plutus` part unlocks them. The builder reads the datum from the output, adds collateral (ada the network can take if a script fails), evaluates execution units and orders inputs and redeemers. You do not set them. Use this page to lock funds at a script or to spend them. -Examples stop at `build()`: call `built.sign()` and `built.submit()` as in [Transaction Basics](/apis/txbuilder/basics#build-sign-and-submit). They use `builder` and `wallet` from there, and these names, which your application defines: +Examples stop at `build()`: call `built.sign()` and `built.submit()` as in [Transaction Basics](/apis/txbuilder/basics#build-sign-and-submit). They use `builder`, `wallet` and `recipient` from there, and these names, which your application defines: - `changeAddress` - the wallet's address, from `await wallet.getChangeAddress()` - `script` - a Plutus script, `{ code, version }` @@ -39,7 +39,7 @@ Give `spend.plutus` the output, the script and a redeemer (the data you give the - Find the output with your provider's `fetchAddressUTxOs(address)`, or name it by `{ txHash, outputIndex }`. - The datum is read from the output. For an output that holds only a datum hash, add `datum: { data }`. - The assets go to the payer's change address unless an `output` part sends them elsewhere. -- The builder picks collateral. To choose it yourself, add a `collateral({ utxo })` part. The builder tops it up unless you pass `topUpCollateral: false`. +- The builder picks collateral: see [Choose the Collateral](/apis/txbuilder/utxos#choose-the-collateral). ```tsx import { guard, mConStr0, spend } from "@meshsdk/core"; @@ -57,6 +57,24 @@ const built = await builder.build( ); ``` +A redeemer may be a function of the final transaction, for a script that wants positions. `tx.self` is the index of the spend itself, and `tx.output(label)` the index of the output with that label. Such a part cannot be recorded by a [plan store](/apis/txbuilder/servers). + +```tsx +import { mConStr0, output, spend } from "@meshsdk/core"; + +const built = await builder.build( + [ + spend.plutus({ + utxo: scriptUtxo, + script, + redeemer: { data: (tx) => mConStr0([tx.self, tx.output("payout")]) }, + }), + output({ address: recipient, value: { lovelace: 5_000_000n }, label: "payout" }), + ], + { payer: wallet }, +); +``` + ## Deploy and Use a Reference Script A reference script is a script stored in an output, so a transaction does not send its code again. Put one on chain by attaching it to an output with `scriptRef`. Leave `lovelace` out and the output holds the minimum it needs. Later, name that output in `script` instead of sending the code, and the builder adds it as a reference input. @@ -86,7 +104,7 @@ Minting works the same way: see [Mint and Burn Assets](/apis/txbuilder/minting#m ## Read a Datum without Spending -A reference input lets scripts read an output, its datum and its reference script, without spending it. The builder never spends such an output for payment. An output the transaction also spends is not a reference input. +A reference input lets scripts read an output, its datum and its reference script, without spending it. The rules for choosing one are in [Read an Output without Spending It](/apis/txbuilder/utxos#read-an-output-without-spending-it). ```tsx import { mConStr0, referenceInput, spend } from "@meshsdk/core"; @@ -122,7 +140,7 @@ const built = await builder.build( ## Lock and Unlock with a Plan -A plan sends several transactions in order, waits for each to land, and can be repeated safely. The unlock step names the output of the lock step by its label. The change of the lock step pays for the unlock. A plan needs a provider that returns block heights and the validity flag: see the [Note in Transaction Basics](/apis/txbuilder/basics#plan-several-transactions). +A [plan](/apis/txbuilder/plans) sends several transactions in order, waits for each to land, and can be repeated safely. The unlock step names the output of the lock step by its label. The change of the lock step pays for the unlock. A plan needs a provider that returns block heights and the validity flag: see [Providers and Networks](/apis/txbuilder/networks#use-blockfrost-for-plans). ```tsx import { mConStr0, output, spend } from "@meshsdk/core"; @@ -153,7 +171,10 @@ await plan.run(); // lock, a block, then unlock - [Transaction Basics](/apis/txbuilder/basics) - the builder, outputs, signing and submitting - [Mint and Burn Assets](/apis/txbuilder/minting) - native and Plutus minting policies -- [Staking Transactions](/apis/txbuilder/staking#withdraw-from-a-script) - scripts that run from withdrawals and certificates +- [UTxOs and Inputs](/apis/txbuilder/utxos) - read an output, choose collateral and inputs +- [Plans](/apis/txbuilder/plans) - lock and unlock in order, with links between steps +- [Testing on the Emulator](/apis/txbuilder/testing) - test that a script accepts and refuses +- [Staking Transactions](/apis/txbuilder/staking#use-a-script-as-the-stake-credential) - scripts that run from withdrawals and certificates - [Migrating to TxBuilder](/apis/txbuilder/migration) - move from the `MeshTxBuilder` chain - [Data Types](/apis/data) - build datums and redeemers - [Blueprints](/apis/utilities/blueprints) - get a script's code from a blueprint diff --git a/content/docs/apis/txbuilder/staking.mdx b/content/docs/apis/txbuilder/staking.mdx index b057540..5b8b313 100644 --- a/content/docs/apis/txbuilder/staking.mdx +++ b/content/docs/apis/txbuilder/staking.mdx @@ -5,7 +5,7 @@ description: "Register a stake key, delegate to a pool, withdraw rewards and der ## Overview -Staking uses certificates and withdrawals, passed as parts to `builder.build()`. +Staking uses certificates and withdrawals, passed as parts to `builder.build()`. Use this page to register a stake key, delegate, collect rewards or run a pool. Examples stop at `build()`: call `built.sign()` and `built.submit()` as in [Transaction Basics](/apis/txbuilder/basics#build-sign-and-submit). They use `builder` and `wallet` from there, and these names, which your application defines: @@ -38,9 +38,6 @@ const built = await builder.build( ], { payer: wallet }, ); -await built.sign(); // the payer signs; the stake key too, if the wallet holds it -await built.submit(); -await built.awaitInclusion(); // waits until a block holds it ``` If the wallet does not hold the stake key, pass the key as a signer: `built.sign({ signers: [wallet, keySigner()] })`. `built.missing` lists the keys that have not signed yet. `certificate.stakeDelegation` alone changes the delegation of a registered key, and `certificate.stakeRegistrationAndDelegation` does both in one certificate. @@ -76,11 +73,14 @@ const built = await builder.build( ); ``` -## Withdraw from a Script +## Use a Script as the Stake Credential -A stake address can be held by a Plutus script. Use `withdrawal.plutus` with the script and a redeemer (the data you give the script). Leave out `rewardAddress` and the builder derives the script's own address. An amount of `0n` runs the script without taking rewards, and works only while the reward balance is zero. To run the script whatever the balance, use `amount: "all"`. +A stake address can be held by a Plutus script: -A certificate of a script's stake address takes the script as its `witness`: `{ plutus, redeemer }`, which must be V3, or `{ native }`. For a native script, withdraw with `withdrawal.native`. +- Withdraw: use `withdrawal.plutus` with the script and a redeemer (the data you give the script). Leave out `rewardAddress` and the builder derives the script's own address. +- Amounts: `0n` runs the script without taking rewards, and works only while the reward balance is zero. To run the script whatever the balance, use `amount: "all"`. +- Certificate: a certificate of a script's stake address takes the script as its `witness`: `{ plutus, redeemer }`, which must be V3, or `{ native }`. +- Native script: withdraw with `withdrawal.native`. ```tsx import { certificate, mConStr0, withdrawal } from "@meshsdk/core"; @@ -135,5 +135,7 @@ To retire the pool, use `certificate.poolRetirement({ pool: poolId, epoch })`. T - [Transaction Basics](/apis/txbuilder/basics) - the builder, the payer and signing - [Smart Contracts](/apis/txbuilder/smart-contracts) - Plutus scripts that spend and mint - [Governance Transactions](/apis/txbuilder/governance) - DReps, voting and proposals +- [Signing and Submitting](/apis/txbuilder/signing) - sign with a stake key or a pool operator key +- [Options](/apis/txbuilder/options) - `registeredPools` and the other options - [Migrating to TxBuilder](/apis/txbuilder/migration) - move from the `MeshTxBuilder` chain - [Package README](https://github.com/MeshJS/mesh/tree/main/packages/mesh-transaction) - every part, option and error diff --git a/content/docs/apis/txbuilder/testing.mdx b/content/docs/apis/txbuilder/testing.mdx new file mode 100644 index 0000000..ccdcfcd --- /dev/null +++ b/content/docs/apis/txbuilder/testing.mdx @@ -0,0 +1,172 @@ +--- +title: "Testing on the Emulator" +description: "Run builds, plans and scripts against a local ledger whose clock moves only when your test moves it." +--- + +## Overview + +`TxEmulator` of `@meshsdk/tx-emulator` is a local Cardano ledger. It is a provider, a submitter and an evaluator, so a `TxBuilder` can use it in place of a chain. A transaction you submit changes the ledger for the next one, and the clock moves only when the test moves it. Use it for tests that must be fast and repeatable. Install it with `npm install @meshsdk/tx-emulator`. + +Examples use `recipient` and `partner` from [Transaction Basics](/apis/txbuilder/basics), and these names, which your application defines: + +- `validator` - a `TxValidator` of `@meshsdk/tx-emulator`: it decides whether a transaction is valid. See the [package README](https://github.com/MeshJS/mesh/tree/main/packages/mesh-tx-emulator) for the validators +- `words` - the mnemonic of a test wallet, as a list of words +- `script` - a Plutus script as `{ code, version }` +- `wallet`, `changeAddress`, `emulator` - made in the next section. `wallet` is a `MeshWallet` for the same network, and `changeAddress` is its address +- `builder`, `built` - made in Build and Submit on the Emulator + +## Create and Fund an Emulator + +`TxEmulator.create` needs the `validator`. `network` is mainnet by default: give the network of your builder. `fund(address, value)` adds one output with no datum and returns it. Its transaction hash comes from a counter, so it is the same on every run. To start with more state, `create` also takes `utxos`, `params` and `slot`. + +Make the wallet without a fetcher, so that the builder reads its UTxOs from the emulator. A wallet that reads UTxOs from a chain hands the builder outputs the emulator does not hold, and `submit()` is refused. + +```tsx +import { MeshWallet } from "@meshsdk/core"; +import { TxEmulator } from "@meshsdk/tx-emulator"; + +const wallet = new MeshWallet({ networkId: 0, key: { type: "mnemonic", words } }); +const changeAddress = await wallet.getChangeAddress(); +const emulator = await TxEmulator.create({ validator, network: "preprod" }); +emulator.fund(changeAddress, { lovelace: 100_000_000n }); +``` + +## Build and Submit on the Emulator + +Give the builder the emulator as its `provider`: it reads parameters, cost models and UTxOs from it and submits to it. The ledger checks the transaction and applies it, and `awaitInclusion()` finds it at once. + +```tsx +import { output, TxBuilder } from "@meshsdk/core"; + +const builder = new TxBuilder({ network: "preprod", provider: emulator }); +const built = await builder.build( + output({ address: recipient, value: { lovelace: 5_000_000n } }), + { payer: wallet }, +); +await built.sign(); +await built.submit(); // the ledger checks and applies it +const { slot } = await built.awaitInclusion(); +console.log(emulator.utxos({ address: recipient })); // the new output +``` + +### Check Without Submitting + +`emulator.simulate(tx)` reports what a signed transaction would do and changes nothing. An accepted one has the `fee` and the `redeemers`, and a refused one lists the `errors`. + +```tsx +const result = await emulator.simulate(built.signedTx!); +if (result.accepted) console.log(result.fee); // lovelace, as text +else console.log(result.errors.map((issue) => issue.message)); +``` + +## Move Time + +The clock moves forward only, and only through `advanceTo`: to a slot, to a time in POSIX milliseconds, or to the first slot of an epoch. `emulator.time` is the start of the current slot. A transaction whose `from` is still ahead is refused until you move the clock past it. + +```tsx +import { output, validity } from "@meshsdk/core"; + +const built = await builder.build( + [ + output({ address: recipient, value: { lovelace: 3_000_000n } }), + validity({ from: emulator.time + 3_600_000 }), // valid in an hour + ], + { payer: wallet }, +); +await built.sign(); +const early = await emulator.simulate(built.signedTx!); +emulator.advanceTo({ time: emulator.time + 3_700_000 }); +const late = await emulator.simulate(built.signedTx!); +console.log(early.accepted, late.accepted); // false true +``` + +## Run a Plan + +A plan waits for blocks and deadlines, which a test should not. In `planDefaults`, `confirmations: 0` makes a step `final` as soon as it is included, and `expiryMarginMs: 0` makes it `expired` right after its end of validity. A short `pollMs` (the pause between two looks at the chain) and `resendMs` (how often the same bytes of a sent step go again) keep the waiting short. Use them in tests only: see [Set Deadlines and Waiting](/apis/txbuilder/plans#set-deadlines-and-waiting). On a real chain keep the defaults. + +```tsx +import { output, TxBuilder } from "@meshsdk/core"; + +const builder = new TxBuilder({ + network: "preprod", + provider: emulator, + planDefaults: { + expiryMarginMs: 0, + confirmations: 0, + pollMs: 10, + resendMs: 10, + }, +}); +const plan = await builder.plan( + { + first: output({ address: recipient, value: { lovelace: 5_000_000n } }), + second: output({ address: partner, value: { lovelace: 2_000_000n } }), + }, + { payer: wallet }, +); +await plan.run({ waitFor: "final" }); +console.log(plan.status, plan.step("second").status); // final final +``` + +With the default `confirmations` (30), a step is `final` 30 slots after its block. Run the plan, call `emulator.advanceTo({ slot: emulator.slot + 30 })`, and run it again with `waitFor: "final"`. + +## Test That a Script Refuses + +A test can lock funds and try to spend them the wrong way. The builder runs a script while it builds, so a script that refuses fails the build as `EVALUATION_FAILED`, and the error names the part by its `label`. `outputOf(step, label)` names the locked output. Here `script` refuses the redeemer below, and `expect` is your test runner's. + +```tsx +import { mConStr0, output, outputOf, spend } from "@meshsdk/core"; + +const lock = await builder.plan( + output({ + address: builder.scriptAddress(script), + value: { lovelace: 10_000_000n }, + datum: { type: "inline", data: mConStr0([]) }, + label: "vault", + }), + { payer: wallet }, +); +await lock.run({ waitFor: "final" }); + +await expect( + builder.plan( + spend.plutus({ + utxo: outputOf(lock.step("main"), "vault"), + script, + redeemer: { data: mConStr0([1]) }, // the wrong redeemer + label: "unlock", + }), + { payer: wallet }, + ), +).rejects.toMatchObject({ code: "EVALUATION_FAILED", label: "unlock" }); +``` + +## Fork the Ledger + +`emulator.fork()` returns an independent copy of the whole ledger. The emulator has no rollbacks: to play one, keep a copy from before and switch to it. A builder on the copy sees the ledger as it was, and nothing it submits reaches the original. + +```tsx +import { output, TxBuilder } from "@meshsdk/core"; + +const branch = emulator.fork(); +const onBranch = new TxBuilder({ network: "preprod", provider: branch }); +const built = await onBranch.build( + output({ address: recipient, value: { lovelace: 1_000_000n } }), + { payer: wallet }, +); +await built.sign(); +await built.submit(); // only the copy changes +const onCopy = branch.utxos({ address: recipient }).length; +const onOriginal = emulator.utxos({ address: recipient }).length; +console.log(onCopy, onOriginal); // the copy has one more +``` + +## Related + +- [Transaction Basics](/apis/txbuilder/basics) - build, sign and submit +- [Plans](/apis/txbuilder/plans) - send transactions in order +- [Servers and Storage](/apis/txbuilder/servers) - record plans with `memoryPlanStore()` +- [Smart Contracts](/apis/txbuilder/smart-contracts) - lock and spend with Plutus scripts +- [Providers and Networks](/apis/txbuilder/networks) - the network option and what a provider must give +- [Offline and CBOR](/apis/txbuilder/offline) - build without a provider +- [Emulator README](https://github.com/MeshJS/mesh/tree/main/packages/mesh-tx-emulator) - validators, state, time and limits diff --git a/content/docs/apis/txbuilder/time.mdx b/content/docs/apis/txbuilder/time.mdx new file mode 100644 index 0000000..1cdbc71 --- /dev/null +++ b/content/docs/apis/txbuilder/time.mdx @@ -0,0 +1,133 @@ +--- +title: "Time and Validity" +description: "Limit when a transaction is valid, by time or by slot, convert between the two, and run on a devnet with its own clock." +--- + +## Overview + +A transaction can be valid only inside a window. The ledger counts that window in slots, and `TxBuilder` lets you write it in time or in slots. This page is for deadlines, time-locked scripts and devnets. The basic `validity` part is in [Transaction Basics](/apis/txbuilder/basics#set-the-validity). + +Examples use `builder`, `wallet` and `recipient` from there, and these names, which your application defines: + +- `deadline` - a deadline in POSIX milliseconds as a `bigint`, such as one read from a datum +- `systemStart` - the start time in your devnet's genesis file, as an ISO text, POSIX milliseconds or a `Date` +- `devnetProvider` - a provider of your devnet + +## Set an Expiry + +`validity({ until })` ends the window. Times are POSIX milliseconds, as a `number`, a `bigint` or a `Date`. `build()` sets no deadline, so give `until` when you follow the transaction yourself. Once it has passed, with a margin for rollbacks, the transaction cannot land. `built.validity` shows the slot and the time it became. A time that is not a whole number of milliseconds, or is before the network's clock starts, is `INVALID_DATA`. + +```tsx +import { output, validity } from "@meshsdk/core"; + +const built = await builder.build( + [ + output({ address: recipient, value: { lovelace: 5_000_000n } }), + validity({ until: new Date(Date.now() + 60 * 60 * 1000) }), // in one hour + ], + { payer: wallet }, +); +console.log(built.validity); // { invalidHereafter, until }: the slot, and the ms it starts at +``` + +## Set a Start Time + +`from` is the earliest time. For "valid from now", leave `from` out: `from: Date.now()` is valid from the next slot only, and nodes check the lower bound against their own, lagging, tip. Use `from` for a script that needs a time. One that needs its lower bound strictly after a deadline gets `from: deadline + 1n`. + +```tsx +import { output, validity } from "@meshsdk/core"; + +const built = await builder.build( + [ + output({ address: recipient, value: { lovelace: 5_000_000n } }), + validity({ from: deadline + 1n, until: deadline + 3_600_000n }), // just after the deadline, for an hour + ], + { payer: wallet }, +); +``` + +## Use Slots + +`invalidBefore` is the first slot the transaction is valid in, and `invalidHereafter` is the first slot it is no longer valid in. They take a `bigint` or a `number`. Give each bound one way only: `from` together with `invalidBefore` is `INVALID_DATA`, and so is a lower bound that is not before the upper one. + +```tsx +import { output, validity } from "@meshsdk/core"; + +const now = builder.slotAt(Date.now()); +const built = await builder.build( + [ + output({ address: recipient, value: { lovelace: 5_000_000n } }), + validity({ invalidBefore: now, invalidHereafter: now + 600 }), // ends 600 slots later + ], + { payer: wallet }, +); +``` + +## Convert Between Time and Slots + +These use the builder's network: + +- `builder.slotAt(time)` gives the slot that contains a time. +- `builder.slotAt(time, "up")` gives the first slot that starts at or after it. +- `builder.timeAt(slot)` gives the time a slot starts at. +- In `validity`, a time becomes a slot so that the interval a script sees lies within `[from, until]`: `from` becomes the first slot starting at or after it, and `until` the slot containing it. + +```tsx +const slot = builder.slotAt(Date.now() + 3_600_000); // the slot that contains a time in an hour +const startsAt = builder.timeAt(slot); // POSIX ms +const fromNow = builder.slotAt(Date.now(), "up"); // what `from: Date.now()` becomes +``` + +## Wait for a Start Time + +A start that is ahead of the local clock is the warning `VALID_FROM_FUTURE` in `built.warnings`, because nodes refuse the transaction until their tip reaches it. The `run()` of a [plan](/apis/txbuilder/plans) before the start throws `NOT_YET_VALID`, with the wait in `error.retryAfterMs`, and sends nothing. Wait and call `run()` again. A plan also sets an end of validity itself when your parts set none. + +```tsx +import { output, TxError, validity } from "@meshsdk/core"; + +const plan = await builder.plan( + [ + output({ address: recipient, value: { lovelace: 5_000_000n } }), + validity({ from: deadline + 1n }), + ], + { payer: wallet }, +); +try { + await plan.run(); +} catch (error) { + if (!TxError.is(error, "NOT_YET_VALID")) throw error; // before the start: nothing was sent + await new Promise((resolve) => setTimeout(resolve, error.retryAfterMs)); + await plan.run(); +} +``` + +## A Devnet Clock + +A devnet has its own slot clock. Describe it with `customNetwork`, from the genesis, and give that as `network`. `slotAt`, `timeAt` and every time in `validity` then follow it. `name`, `networkId`, `magic` and `zeroSlot` are optional. + +```tsx +import { customNetwork, TxBuilder } from "@meshsdk/core"; + +const devnet = new TxBuilder({ + network: customNetwork({ + systemStart, + slotLengthMs: 1_000, + epochLength: 500, + }), + provider: devnetProvider, +}); +console.log(devnet.slotAt(Date.now())); // a slot of the devnet's clock +``` + +## Related + +- [Transaction Basics](/apis/txbuilder/basics) - the builder and the other parts +- [Plans](/apis/txbuilder/plans) - send a transaction when its start has come, and follow its end +- [Smart Contracts](/apis/txbuilder/smart-contracts) - lock and spend with a script +- [Mint and Burn Assets](/apis/txbuilder/minting#mint-with-a-time-locked-policy) - a policy that works only before a slot +- [Signing and Submitting](/apis/txbuilder/signing) - sign, submit and retry +- [UTxOs and Inputs](/apis/txbuilder/utxos) - choose what a transaction spends +- [Testing on the Emulator](/apis/txbuilder/testing#move-time) - move the clock of a local ledger +- [Providers and Networks](/apis/txbuilder/networks) - the network and its slot clock +- [Errors](/apis/txbuilder/errors#build-warnings) - `VALID_FROM_FUTURE`, `NEVER_EXPIRES` and the other warnings +- [Package README](https://github.com/MeshJS/mesh/tree/main/packages/mesh-transaction) - every part, option and error diff --git a/content/docs/apis/txbuilder/utxos.mdx b/content/docs/apis/txbuilder/utxos.mdx new file mode 100644 index 0000000..9c31a4e --- /dev/null +++ b/content/docs/apis/txbuilder/utxos.mdx @@ -0,0 +1,190 @@ +--- +title: "UTxOs and Inputs" +description: "Give the builder UTxOs in any form, choose or limit the inputs it spends, chain transactions that are not on chain yet, and set collateral." +--- + +## Overview + +A UTxO (an unspent output: coins held at an address) is what a transaction spends. The builder reads the payer's UTxOs and picks the ones a payment needs. This page is for when you want to hand it UTxOs, limit or replace its choice, or build on a transaction that is not on chain yet. The basic parts are in [Transaction Basics](/apis/txbuilder/basics#choose-inputs). + +Examples use `builder`, `wallet`, `recipient`, `partner`, `changeAddress`, `utxo` and `utxos` from there, and these names, which your application defines: + +- `cborUtxo` - a UTxO as CBOR hex, as a CIP-30 wallet's `getUtxos()` returns it +- `refUtxo` - an output you only read, such as one that holds a datum +- `scriptUtxo`, `script` - an output locked at a Plutus script, and that script +- `collateralUtxo` - an output of the payer that holds lovelace alone +- `newAddress` - an address that gets everything in a send-all + +## The Forms of a UTxO + +Wherever the builder takes a UTxO, it takes any of these forms, and the same UTxO in each gives the same transaction. A bare out ref `{ txHash, outputIndex }` is looked up through the provider. Give the UTxO in full to spare the lookup. + +| Form | Comes from | +|------|------------| +| a Mesh `UTxO`, `{ input, output }` | a provider, a Mesh wallet, `TxEmulator` | +| CBOR hex of a transaction unspent output (the out ref and the output) | a CIP-30 wallet: `getUtxos`, `getCollateral` | +| a `Utxo`, the builder's own: `txHash`, `outputIndex`, `address`, `value` and, if held, `datum` and `script` | what the builder returns: `built.inputs`, `built.outputs`, `built.change` | + +```tsx +import { spend, toMeshUtxo, toUtxo } from "@meshsdk/core"; + +spend.pubKey({ utxo }); // a Mesh UTxO +spend.pubKey({ utxo: cborUtxo }); // CBOR from a wallet +spend.pubKey({ utxo: utxo.input }); // an out ref: looked up + +const own = toUtxo(utxo); // the builder's Utxo; value maps lovelace and units to bigint +console.log(own.txHash, own.value.lovelace); +const mesh = toMeshUtxo(own); // back to a Mesh UTxO, for an API that takes one +``` + +## Limit What the Builder May Pick + +To spend a particular output, add a `spend.pubKey` part, as in Transaction Basics. To keep some UTxOs out of the choice, give `canSelect`. It is asked about each of the payer's UTxOs, for payment and for collateral. Script-locked UTxOs and the ones parts read are never picked. An ada-only UTxO has one entry in `value`. + +```tsx +import { output } from "@meshsdk/core"; + +const built = await builder.build( + output({ address: recipient, value: { lovelace: 5_000_000n } }), + { + payer: wallet, + canSelect: (candidate) => Object.keys(candidate.value).length === 1, // ada-only: tokens stay put + }, +); +``` + +## Pick Inputs by Your Own Rule + +`coinSelection` replaces the built-in choice for one build. It gets `need` (`lovelace` always, a token only when it is short) and the candidates. It returns the candidates it picks, or their out refs. A name that is no candidate is `INVALID_SELECTION`. The change stays with the built-in rule. + +```tsx +import { output } from "@meshsdk/core"; + +const built = await builder.build( + output({ address: recipient, value: { lovelace: 5_000_000n } }), + { + payer: wallet, + coinSelection: (need, candidates) => { + let sum = 0n; + const smallestFirst = [...candidates].sort((a, b) => + Number(a.value.lovelace - b.value.lovelace), + ); + return smallestFirst.filter((candidate) => { + const short = sum < need.lovelace; + sum += candidate.value.lovelace; + return short; + }); + }, + }, +); +``` + +## Name Outputs the Provider Does Not Know + +A part may name an output by out ref that the provider cannot find yet, or that you build without a provider. Give the output in full in `knownUtxos`, in any form. Only the entries the parts name are read, and two entries for one out ref must hold the same. + +```tsx +import { output, spend } from "@meshsdk/core"; + +const built = await builder.build( + [ + spend.pubKey({ utxo: utxo.input }), // an out ref only + output({ address: recipient, value: { lovelace: 3_000_000n } }), + ], + { payer: { changeAddress, utxos }, knownUtxos: [utxo] }, // nothing is looked up +); +``` + +## Build on a Transaction Not Yet on Chain + +Give `after` a `BuiltTx`, a [plan](/apis/txbuilder/plans), or a list of them. The new build does not pick what they spend, it may pick their change at its change address, and it can name their outputs without a lookup. Without `after`, the second build may pick an input the first spends, and only the ledger catches it. Send them in order. + +```tsx +import { output } from "@meshsdk/core"; + +const first = await builder.build( + output({ address: recipient, value: { lovelace: 5_000_000n } }), + { payer: wallet }, +); +const second = await builder.build( + output({ address: partner, value: { lovelace: 2_000_000n } }), + { payer: wallet, after: first }, +); +for (const tx of [first, second]) { + await tx.sign(); + await tx.submit(); +} +``` + +## Spend Many Small UTxOs with a Plan + +A wallet with many small UTxOs may need more inputs than one transaction holds (`TX_TOO_LARGE`). A [plan](/apis/txbuilder/plans#make-and-run-a-plan) then adds consolidation steps before the step: transactions that merge the payer's UTxOs. `plan.steps` and `plan.fee` show them before anyone signs. There are at most 4 by default. `consolidate: { maxSteps }` (1 to 31) changes that, and `consolidate: false` keeps `TX_TOO_LARGE`. A plan needs a provider with block heights: see [Providers and Networks](/apis/txbuilder/networks#use-blockfrost-for-plans). + +```tsx +import { output } from "@meshsdk/core"; + +const plan = await builder.plan( + output({ address: recipient, value: { lovelace: 500_000_000n } }), + { payer: wallet, consolidate: { maxSteps: 6 } }, +); +console.log(plan.steps.map((step) => `${step.name}: ${step.kind}`), plan.fee); +await plan.run(); // consolidation steps first, then the payment +``` + +## Send Everything + +`sendAllTo` spends every selectable UTxO of the payer and sends what is left, after outputs, deposits and the fee, to one address. Tokens go with it, in several outputs if they are many. `canSelect` narrows what it takes. + +```tsx +const built = await builder.build([], { payer: wallet, sendAllTo: newAddress }); +``` + +## Read an Output without Spending It + +`referenceInput` lets the scripts of a transaction read an output, its datum and its reference script. An output read by several parts is one reference input. An output the transaction spends is never one, and the builder never spends an output a part only reads. `built.referenceInputs` lists them. A script that uses one is in [Smart Contracts](/apis/txbuilder/smart-contracts#read-a-datum-without-spending). + +```tsx +import { output, referenceInput } from "@meshsdk/core"; + +const built = await builder.build( + [ + referenceInput({ utxo: refUtxo }), + output({ address: recipient, value: { lovelace: 2_000_000n } }), + ], + { payer: wallet }, +); +console.log(built.referenceInputs.map((input) => input.outputIndex)); +``` + +## Choose the Collateral + +A Plutus transaction needs collateral: ada the network takes if a script fails. The builder picks it from the payer's key-locked UTxOs. If they do not cover it and the payer is a CIP-30 api with `getCollateral`, the builder asks the wallet once. To choose it yourself, add a `collateral` part, and use two build options to shape the rest. + +| Option | Default | Set to `false` | +|--------|---------|----------------| +| `topUpCollateral` | `true`: given collateral that falls short gets inputs from the payer | the given inputs are used as they are, and a shortfall is `INSUFFICIENT_COLLATERAL` | +| `collateralReturn` | `true`: the transaction returns the rest of the collateral | no return: all lovelace of the collateral inputs is at stake (`COLLATERAL_FORFEITED` in `built.warnings`). They must hold lovelace alone, or `INVALID_COLLATERAL` | + +```tsx +import { collateral, mConStr0, spend } from "@meshsdk/core"; + +const built = await builder.build( + [ + spend.plutus({ utxo: scriptUtxo, script, redeemer: { data: mConStr0([]) } }), + collateral({ utxo: collateralUtxo }), // key-locked, by you + ], + { payer: wallet, topUpCollateral: false }, +); +console.log(built.collateral); // { inputs, total, return? } +``` + +## Related + +- [Transaction Basics](/apis/txbuilder/basics) - the builder, outputs and the basic parts +- [Smart Contracts](/apis/txbuilder/smart-contracts) - spend from a script, reference scripts +- [Plans](/apis/txbuilder/plans) - send transactions in order, and consolidate a wallet +- [Signing and Submitting](/apis/txbuilder/signing) - signers, partial signing and retries +- [Errors](/apis/txbuilder/errors) - `INSUFFICIENT_FUNDS`, `INSUFFICIENT_COLLATERAL`, `TX_TOO_LARGE` and the other codes +- [Time and Validity](/apis/txbuilder/time) - validity by time and by slot +- [Providers](/providers) - read UTxOs from the chain +- [Package README](https://github.com/MeshJS/mesh/tree/main/packages/mesh-transaction) - every part, option and error diff --git a/data/links-txbuilders.ts b/data/links-txbuilders.ts index 844bdb4..c069af2 100644 --- a/data/links-txbuilders.ts +++ b/data/links-txbuilders.ts @@ -3,7 +3,22 @@ import { BanknotesIcon } from "@heroicons/react/24/solid"; export const metaTxbuilderBasic = { link: `/apis/txbuilder/basics`, title: "Transaction Basics", - desc: "Payer, outputs, metadata, validity, signing and submitting", + desc: "Payer, outputs, metadata, required signers and errors", +}; +export const metaTxbuilderSigning = { + link: `/apis/txbuilder/signing`, + title: "Signing and Submitting", + desc: "Wallets, keys, your own signer, and safe retries", +}; +export const metaTxbuilderUtxos = { + link: `/apis/txbuilder/utxos`, + title: "UTxOs and Inputs", + desc: "Give, limit and chain UTxOs, and set collateral", +}; +export const metaTxbuilderTime = { + link: `/apis/txbuilder/time`, + title: "Time and Validity", + desc: "Expiry, start time, slots and devnet clocks", }; export const metaTxbuilderMinting = { link: `/apis/txbuilder/minting`, @@ -25,6 +40,41 @@ export const metaTxbuilderGovernance = { title: "Governance Transactions", desc: "Register as a DRep, vote and submit proposals", }; +export const metaTxbuilderPlans = { + link: `/apis/txbuilder/plans`, + title: "Plans", + desc: "Send transactions in order, built once, never rebuilt", +}; +export const metaTxbuilderServers = { + link: `/apis/txbuilder/servers`, + title: "Servers and Storage", + desc: "Record plans so a server can restart and resume", +}; +export const metaTxbuilderOffline = { + link: `/apis/txbuilder/offline`, + title: "Offline and CBOR", + desc: "Build without a provider and work with CBOR", +}; +export const metaTxbuilderTesting = { + link: `/apis/txbuilder/testing`, + title: "Testing on the Emulator", + desc: "Test builds, plans and scripts on a local ledger", +}; +export const metaTxbuilderNetworks = { + link: `/apis/txbuilder/networks`, + title: "Providers and Networks", + desc: "Choose the network and see what a provider must give", +}; +export const metaTxbuilderOptions = { + link: `/apis/txbuilder/options`, + title: "Options", + desc: "Every option of TxBuilder, build() and plan()", +}; +export const metaTxbuilderErrors = { + link: `/apis/txbuilder/errors`, + title: "Errors", + desc: "Error codes by when they come, retries and warnings", +}; export const metaTxbuilderMigration = { link: `/apis/txbuilder/migration`, title: "Migrating to TxBuilder", @@ -33,10 +83,20 @@ export const metaTxbuilderMigration = { export const linksTxbuilder = [ metaTxbuilderBasic, + metaTxbuilderSigning, + metaTxbuilderUtxos, + metaTxbuilderTime, metaTxbuilderMinting, metaTxbuilderSmartContract, metaTxbuilderStaking, metaTxbuilderGovernance, + metaTxbuilderPlans, + metaTxbuilderServers, + metaTxbuilderOffline, + metaTxbuilderTesting, + metaTxbuilderNetworks, + metaTxbuilderOptions, + metaTxbuilderErrors, metaTxbuilderMigration, ]; From 10c4f92f84cd7849314d491895c11e5fccd85e2d Mon Sep 17 00:00:00 2001 From: lisicky Date: Sun, 22 Nov 2026 19:55:08 +0100 Subject: [PATCH 05/15] docs: plan status graphs --- components/txbuilder/plan-status-graph.tsx | 383 +++++++++++++++++++++ content/docs/apis/txbuilder/plans.mdx | 14 +- 2 files changed, 395 insertions(+), 2 deletions(-) create mode 100644 components/txbuilder/plan-status-graph.tsx diff --git a/components/txbuilder/plan-status-graph.tsx b/components/txbuilder/plan-status-graph.tsx new file mode 100644 index 0000000..dc1cead --- /dev/null +++ b/components/txbuilder/plan-status-graph.tsx @@ -0,0 +1,383 @@ +// State graphs for the statuses of a plan and of its steps. +// Hand-written SVG: colors come from the fumadocs theme classes and currentColor, +// so the graphs read in light and dark mode. + +type Kind = "call" | "chain"; + +const STEP_ARROW = "psg-step-arrow"; +const PLAN_ARROW = "psg-plan-arrow"; + +const BOX_W = 88; +const BOX_H = 36; +const GAP = 4; // distance between the two borders of a terminal status + +function Arrowhead({ id }: { id: string }) { + return ( + + + + ); +} + +function Status({ + cx, + cy, + label, + terminal = false, + w = BOX_W, +}: { + cx: number; + cy: number; + label: string; + terminal?: boolean; + w?: number; +}) { + const x = cx - w / 2; + const y = cy - BOX_H / 2; + return ( + + + {terminal && ( + + )} + + {label} + + + ); +} + +function Edge({ + d, + kind, + marker, + main = false, +}: { + d: string; + kind: Kind; + marker: string; + main?: boolean; // the usual path: a heavier line +}) { + return ( + + ); +} + +function Label({ + x, + y, + lines, + kind, + anchor = "middle", +}: { + x: number; + y: number; + lines: string[]; + kind: Kind; + anchor?: "start" | "middle" | "end"; +}) { + return ( + + {lines.map((line, i) => ( + + {line} + + ))} + + ); +} + +function Start({ x, y }: { x: number; y: number }) { + return ; +} + +function Legend({ + x, + y, + marker, + vertical = false, +}: { + x: number; + y: number; + marker: string; + vertical?: boolean; +}) { + // Horizontal: three items in a row. Vertical: three rows, 26 apart. + const at = (dx: number) => (vertical ? x : x + dx); + const row = (i: number) => (vertical ? y + i * 26 : y); + return ( + + + + a call + + + + what the chain shows + + + + + never changes + + + ); +} + +function Frame({ + children, + label, + note, +}: { + children: React.ReactNode; + label: string; + note: string; +}) { + // The svg keeps a 760px minimum so its text stays legible; the hint shows + // only when the column is narrower than that and the box scrolls. + return ( +
+
+ {children} +
+

+ Scroll sideways to see the whole graph. +

+

{note}

+
+ ); +} + +export function StepStatusGraph() { + // Main row: built, signed, sent, included, final. + const row = 150; + const x = { built: 76, signed: 264, sent: 452, included: 640, final: 840 }; + const half = BOX_W / 2; + // Dead statuses row. + const dead = 290; + const d = { orphaned: 170, expired: 310, failed: 452 }; + + return ( + + + Statuses of a step + + + + + {/* start */} + + + + + {/* usual path */} + + + + + + + + + + {/* sent and rejected */} + + + + + + {/* rolled back */} + + + + {/* dead statuses */} + + + will not land (dead) + + + + + + + + + + + + + {/* statuses */} + + + + + + + + + + + + + + ); +} + +export function PlanStatusGraph() { + const w = 96; + const half = w / 2; + const top = 60; + const mid = 190; + const x = { pending: 212, final: 790, stopping: 410, stopped: 690 }; + + return ( + + + Statuses of a plan + + + + + {/* start */} + + + + + {/* usual path */} + + + + {/* pending to stopping: a call */} + + + + {/* pending to stopping: a step will not land while another is not final yet */} + + + + {/* stopping to stopped */} + + + + {/* pending to stopped: a step will not land and every other step is final or dead */} + + + + {/* statuses */} + + + + + + + + + ); +} diff --git a/content/docs/apis/txbuilder/plans.mdx b/content/docs/apis/txbuilder/plans.mdx index 0bcace9..7d03b11 100644 --- a/content/docs/apis/txbuilder/plans.mdx +++ b/content/docs/apis/txbuilder/plans.mdx @@ -3,6 +3,8 @@ title: "Plans" description: "Send one transaction or several in order with plan(): built once, never rebuilt, so every call can be repeated." --- +import { StepStatusGraph, PlanStatusGraph } from "@/components/txbuilder/plan-status-graph"; + ## Overview A plan is a group of transactions built at once and sent in order. `builder.plan()` builds all of them and signs and sends nothing. `plan.run()` then signs, sends and waits for each one in turn. A plan is never rebuilt, so any call can be repeated and sends the same bytes. Use one for transactions that depend on each other, for a retry that must not pay twice, or to wait for blocks. @@ -89,10 +91,14 @@ await plan.run(); // lock, a block, then unlock Every step has a status, and so does the plan. A payment is paid when its step is `final`. Release goods then, never at `included`, which a rollback can undo. A plan is not atomic: step one may be `final` while step two never lands, so read the status of each step. +In the graph of a step, a solid arrow is a call and a dashed arrow is what the chain shows; the heavy line is the usual path, and a box with a double border never changes. + + + | Step | Meaning | |------|---------| | `built`, `signed` | signatures are missing; fully signed but not sent yet | -| `sent` | delivered: accepted, or the outcome is unknown | +| `sent` | delivered (accepted, or the outcome is unknown), or rolled back out of a block | | `rejected` | the ledger refused it, but it may still land: `run()` sends the same bytes again | | `included` | in a block; a rollback can undo it | | `final` | enough blocks on top (`confirmations`); never changes | @@ -100,7 +106,11 @@ Every step has a status, and so does the plan. A payment is paid when its step i | `failed` | in a block with a failed script; its collateral is taken | | `orphaned` | a step it stands on will not land | -The plan is `pending` while it may still complete, `stopping` when it does not go on but a step may still land, `stopped` when it does not go on and, by what the chain shows, nothing more is expected to land, and `final` when every step is `final`. A later look can still find a step and move a `stopped` plan to `stopping` or `final`, so pay what is left only with `replan`. `plan.stop()` ends a plan: it signs and sends nothing more. +The plan has its own status, drawn the same way: a solid arrow is a call, a dashed arrow is what the chain shows. + + + +The plan is `pending` while it may still complete; `stopping` when it does not go on but some step is neither `final` nor dead (`expired`, `failed` or `orphaned`), that is, it may still land or is in a block and not `final` yet; `stopped` when it does not go on and, by what the chain shows, nothing more is expected to land; and `final` when every step is `final`. A later look can still find a step and move a `stopped` plan to `stopping` or `final`, so pay what is left only with `replan`. `plan.stop()` ends a plan: it signs and sends nothing more. ```tsx await plan.run({ waitFor: "final" }); // waits for `confirmations` blocks on top From f7cc02a4e0eee3964eb6946a54f3a461a05e1eed Mon Sep 17 00:00:00 2001 From: lisicky Date: Sun, 22 Nov 2026 21:24:38 +0100 Subject: [PATCH 06/15] docs: consolidation steps --- content/docs/apis/txbuilder/errors.mdx | 4 ++- content/docs/apis/txbuilder/options.mdx | 2 +- content/docs/apis/txbuilder/plans.mdx | 43 +++++++++++++++++++++++-- content/docs/apis/txbuilder/utxos.mdx | 13 +------- 4 files changed, 46 insertions(+), 16 deletions(-) diff --git a/content/docs/apis/txbuilder/errors.mdx b/content/docs/apis/txbuilder/errors.mdx index 56ddbcf..616b83b 100644 --- a/content/docs/apis/txbuilder/errors.mdx +++ b/content/docs/apis/txbuilder/errors.mdx @@ -138,7 +138,7 @@ A part builder checks its arguments at once, so the error points at the line tha | `INVALID_COLLATERAL` | Collateral inputs cannot cover the total, or with `collateralReturn: false` one holds a token. Give inputs with lovelace only | | `OUTPUT_BELOW_MIN_COIN` | An output holds less lovelace than the ledger requires (`details.coin`, `details.minCoin`). Add lovelace, or leave `lovelace` out | | `VALUE_TOO_LARGE` | An output's value is larger than `maxValSize`. Spread the assets over several outputs | -| `TX_TOO_LARGE` | Over `maxTxSize`. `details.cause` is `parts`, `selection` or `referenceScripts`. Split it into the steps of a plan | +| `TX_TOO_LARGE` | Over `maxTxSize`. For `details.cause` `parts` or `referenceScripts`, split it into the steps of a plan. For `selection` (many small UTxOs), give the same parts to `builder.plan()`: it puts [consolidation steps](/apis/txbuilder/plans#consolidation-steps) before the step, unless the step has `sendAllTo` or the plan has `consolidate: false` | | `FEE_TOO_LOW` | The `fee` you gave is below the minimum (`details.minFee`). Drop it, or give a higher one | | `FEE_NOT_CONVERGED` | Balancing did not settle on a fee within its rounds. This is rare | @@ -203,6 +203,8 @@ A warning does not stop a build. `built.warnings` lists them, each with a `code` | `FEE_ABOVE_MINIMUM` | The `fee` you gave is above the minimum | | `NEVER_EXPIRES` | Only on a step of a plan that was given built: it has no end of validity | +A plan also tells a [`trace`](/apis/txbuilder/options#control) callback about events of its own, such as `{ type: "warning", code: "CONSOLIDATION_STEPS", steps, fee }`, sent when it puts in consolidation steps: see [Consolidation Steps](/apis/txbuilder/plans#consolidation-steps). + The lists of codes, reasons and warnings can grow, so keep a default branch when you switch on them. ## Related diff --git a/content/docs/apis/txbuilder/options.mdx b/content/docs/apis/txbuilder/options.mdx index 0583a89..512eee5 100644 --- a/content/docs/apis/txbuilder/options.mdx +++ b/content/docs/apis/txbuilder/options.mdx @@ -90,7 +90,7 @@ const built = await builder.build( | Option | What it does | Default | |--------|--------------|---------| | `id` | Your id for the plan, shown as `plan.id`. Required on a builder with a `store` | none | -| `consolidate` | `true`: when a step's inputs do not fit one transaction, the plan adds consolidation steps before it. `{ maxSteps }` limits them (1 to 31). `false`: that step is `TX_TOO_LARGE` | `true`, up to 4 steps | +| `consolidate` | `true`: when a step's inputs do not fit one transaction, the plan adds [consolidation steps](/apis/txbuilder/plans#consolidation-steps) before it. `{ maxSteps }` limits them (1 to 31). `false`: that step is `TX_TOO_LARGE` | `true`, up to 4 steps | | `ttlMs` | How long a step is valid when its parts set no `validity({ until })`, and the time left to sign it | `600_000` (10 minutes) | | `expiryMarginMs` | The wait after a step's end of validity before the plan calls it `expired` | `600_000` (10 minutes) | | `confirmations` | Blocks on top of a step's block before it is `final` | `30` | diff --git a/content/docs/apis/txbuilder/plans.mdx b/content/docs/apis/txbuilder/plans.mdx index 7d03b11..3a5fb47 100644 --- a/content/docs/apis/txbuilder/plans.mdx +++ b/content/docs/apis/txbuilder/plans.mdx @@ -130,6 +130,45 @@ await plan.add({ if (plan.status === "pending") await plan.run(); ``` +## Consolidation Steps + +A payer with many small UTxOs may need more inputs than one transaction holds. Then `build()` throws `TX_TOO_LARGE` with `details.cause` `"selection"`. Give the same parts to `builder.plan()`. It puts consolidation steps before the payment by itself, because `consolidate` is on by default. `plan.add()` and `plan.replan()` do the same for the steps they build. A plan needs a provider that returns block heights and the validity flag: see [Providers and Networks](/apis/txbuilder/networks#use-blockfrost-for-plans). + +Each consolidation step: + +- is named `consolidate-1`, `consolidate-2` and so on, with `kind` `"consolidation"`; +- spends as many of the payer's UTxOs as fit one transaction, and sends everything back to the payer; +- sets tokens the payment does not need aside in outputs of their own, and passes the rest on as change that the next step spends; +- is signed, sent and recorded like any step, and has its own [status](#read-the-statuses). [`plan.rest`](#handle-a-step-that-does-not-go-through) never lists it. + +```tsx +import { output } from "@meshsdk/core"; + +const plan = await builder.plan( + output({ address: recipient, value: { lovelace: 500_000_000n } }), + { payer: wallet }, // consolidation is on by default +); // built, consolidation steps first; nothing is signed or sent + +const extra = plan.steps.filter((step) => step.kind === "consolidation"); +console.log(extra.map((step) => step.name)); // ["consolidate-1", "consolidate-2"] +console.log(extra.reduce((sum, step) => sum + step.fee, 0n)); // what they cost, in lovelace +console.log(plan.fee); // every step, the payment included +await plan.run(); // consolidate-1, a block, consolidate-2, a block, then main +``` + +Nothing is signed or sent until `run()`, so read `plan.steps` first. A [`trace`](/apis/txbuilder/options#control) callback is also told `{ type: "warning", code: "CONSOLIDATION_STEPS", steps, fee }`: how many steps the call put in, and their fees together. + +What it costs: + +- Fees: each step pays its own fee from the payer's funds. If the wallet holds little more than the payment, the fees can make the plan `INSUFFICIENT_FUNDS`. The message says how many steps and what their fees come to. +- Time: `run()` waits for a block after each step, so the payment lands one block later for each. A wallet that asks you to approve each transaction asks once per step. +- One deadline: all steps end `ttlMs` (10 minutes by default) after the plan is built. Signing and landing all of them must fit: see [Set Deadlines and Waiting](#set-deadlines-and-waiting). +- Not atomic: if the plan stops after a consolidation step landed, the payer's UTxOs are merged and the payment is not made. Only the fees are spent. `plan.replan()` pays what is left: see [Handle a Step That Does Not Go Through](#handle-a-step-that-does-not-go-through). + +By default a plan makes at most 4 consolidation steps, those of `plan.add` counted. `consolidate: { maxSteps }` sets the limit from 1 to 31, and `consolidate: false` keeps `TX_TOO_LARGE`. Consolidation steps count toward the 32 steps of a plan. `TX_TOO_LARGE` is also thrown when the limit is reached, when the plan has no room for another step, or when a consolidation step cannot be built. An abort or a provider failure is thrown as it is. A step with `sendAllTo` is never consolidated. + +A token set aside by a consolidation step stays with the payer. A later step that needs it may spend that output. A later step of the same payer with `sendAllTo` takes the outputs of consolidation steps that are not `final` yet without asking `canSelect`. Once a consolidation step is `final`, its outputs are ordinary UTxOs of the payer, and a sweep takes them only where `canSelect` allows. The [package README](https://github.com/MeshJS/mesh/tree/main/packages/mesh-transaction) has the rules. + ## Use a Transaction Built Elsewhere A step may be a transaction another party built: give it as a `BuiltTx` or as CBOR hex. A plan signs it as it signs its own steps: with the call's `signers`, or, when the call names none, with the plan's payer if it can sign. It keeps the witnesses the transaction came with. Read it first with [`builder.fromCbor()`](/apis/txbuilder/offline#read-a-transaction-built-elsewhere), which shows its outputs, fee and missing keys. Keep any key you do not want used on it out of the call's signers, and out of the payer when the call names none. @@ -158,7 +197,7 @@ Three deadlines belong to the plan. They are taken from the plan's options, else | `expiryMarginMs` | how long after its end of validity a step waits before it is `expired` | | `confirmations` | blocks on top of a step's block before it is `final` | -A step whose parts give `validity({ until })` keeps that end. A step that runs a Plutus script may not end past the network's horizon (36 hours on mainnet and preprod), else `INVALID_STATE`. `0` for `expiryMarginMs` and `confirmations` is for tests only. +Every step whose parts give no `validity({ until })` ends at the same time, `ttlMs` after the plan is built. A step whose parts give `validity({ until })` keeps that end. A step that runs a Plutus script may not end past the network's horizon (36 hours on mainnet and preprod), else `INVALID_STATE`. `0` for `expiryMarginMs` and `confirmations` is for tests only. The waiting options belong to one call of `run()` and are never recorded: @@ -218,6 +257,6 @@ if (plan.steps.some((step) => step.status === "failed")) { - [Servers and Storage](/apis/txbuilder/servers) - record plans so a server can restart and resume - [Errors](/apis/txbuilder/errors#errors-from-waiting-and-plans) - the codes a plan throws - [Options](/apis/txbuilder/options#plan-options) - every plan option with its default -- [UTxOs and Inputs](/apis/txbuilder/utxos#spend-many-small-utxos-with-a-plan) - consolidation steps for a wallet with many small UTxOs +- [UTxOs and Inputs](/apis/txbuilder/utxos) - give UTxOs, limit what the builder picks, build on a transaction not yet on chain - [Providers and Networks](/apis/txbuilder/networks#use-blockfrost-for-plans) - a provider that plans can use - [Package README](https://github.com/MeshJS/mesh/tree/main/packages/mesh-transaction) - every plan option, status and error diff --git a/content/docs/apis/txbuilder/utxos.mdx b/content/docs/apis/txbuilder/utxos.mdx index 9c31a4e..f78af1b 100644 --- a/content/docs/apis/txbuilder/utxos.mdx +++ b/content/docs/apis/txbuilder/utxos.mdx @@ -118,18 +118,7 @@ for (const tx of [first, second]) { ## Spend Many Small UTxOs with a Plan -A wallet with many small UTxOs may need more inputs than one transaction holds (`TX_TOO_LARGE`). A [plan](/apis/txbuilder/plans#make-and-run-a-plan) then adds consolidation steps before the step: transactions that merge the payer's UTxOs. `plan.steps` and `plan.fee` show them before anyone signs. There are at most 4 by default. `consolidate: { maxSteps }` (1 to 31) changes that, and `consolidate: false` keeps `TX_TOO_LARGE`. A plan needs a provider with block heights: see [Providers and Networks](/apis/txbuilder/networks#use-blockfrost-for-plans). - -```tsx -import { output } from "@meshsdk/core"; - -const plan = await builder.plan( - output({ address: recipient, value: { lovelace: 500_000_000n } }), - { payer: wallet, consolidate: { maxSteps: 6 } }, -); -console.log(plan.steps.map((step) => `${step.name}: ${step.kind}`), plan.fee); -await plan.run(); // consolidation steps first, then the payment -``` +A wallet with many small UTxOs may need more inputs than one transaction holds, and `build()` throws `TX_TOO_LARGE`. Give the same parts to a [plan](/apis/txbuilder/plans). It puts consolidation steps before the payment, which merge the payer's UTxOs. Each costs a fee and a block of waiting. A step with `sendAllTo` is never consolidated. A plan needs a provider with block heights: see [Providers and Networks](/apis/txbuilder/networks#use-blockfrost-for-plans). [Consolidation Steps](/apis/txbuilder/plans#consolidation-steps) shows the steps and their fees before anything is signed, and how many a plan makes. ## Send Everything From b3182fb90ae8928dff7d7303dff1bb4b6e9044a2 Mon Sep 17 00:00:00 2001 From: lisicky Date: Sun, 22 Nov 2026 21:35:08 +0100 Subject: [PATCH 07/15] docs: a cold signer with sign() --- content/docs/apis/txbuilder/signing.mdx | 70 ++++++++++++++++++++++--- 1 file changed, 62 insertions(+), 8 deletions(-) diff --git a/content/docs/apis/txbuilder/signing.mdx b/content/docs/apis/txbuilder/signing.mdx index c25529a..3a92ef3 100644 --- a/content/docs/apis/txbuilder/signing.mdx +++ b/content/docs/apis/txbuilder/signing.mdx @@ -7,13 +7,15 @@ description: "Choose who pays, signs and submits a transaction: wallets, private `build()` signs and sends nothing. You name who signs and who sends, one call at a time. This page is for when the payer's wallet is not the only signer, when a key lives in your own service, or when a call fails and you must retry safely. The basic path is in [Transaction Basics](/apis/txbuilder/basics#build-sign-and-submit). -Examples use `builder`, `wallet`, `provider`, `changeAddress` and `recipient` from there, and these names, which your application defines: +Examples use `builder`, `wallet`, `provider`, `changeAddress`, `recipient` and `params` from there, and these names, which your application defines: - `built` - the `BuiltTx` that an earlier example of the page makes - `api` - a CIP-30 wallet api (the connection a browser wallet gives), from `window.cardano..enable()` - `vault` - your own key service - `witnessSet` - a witness set (the signatures of one party, as hex) made elsewhere - `coldKey` - a signing key that never touches the building machine +- `tx` - a transaction as a CBOR hex string, such as the `built.tx` that was sent to the cold machine +- `device` - your own link to a signing device: it has a `keyHash` (lower-case hex), and `sign(txHash)` signs the 32 bytes of the hash and returns `{ vkey, signature }` in hex ## Who Pays, Signs and Submits @@ -76,7 +78,7 @@ await built.sign({ signers: keySigner(process.env.TREASURY_SKEY!) }); ## Sign with Your Own Code -For a key service or a hardware module, give a signer of hashes: an object with `signTxHash`, or that function alone. It gets `txHash` (the hash of the transaction body) and `keys`, the keys still needed, each as `{ keyHash, roles }`. Answer `{ vkey, signature }` in hex for each key you hold, signing the 32 bytes of `txHash`, not its hex text. To decline, throw `TxPlanError("SIGN_DECLINED", reason)`. +For a key service or a hardware module, give a signer of hashes: an object with `signTxHash`, or that function alone. It gets `txHash` (the hash of the transaction body) and `keys`, the keys still needed, each as `{ keyHash, roles }`. Answer `{ vkey, signature }` in hex for each key you hold, signing the 32 bytes of `txHash`, not its hex text. To decline, throw `new TxPlanError("SIGN_DECLINED", reason)`. The roles say why a key is asked, for your own decision and display: @@ -127,16 +129,68 @@ await built.submit(); ## Sign on a Cold Machine -Send `built.tx` to a machine that holds the key and has no builder. `signWitnesses(signer, tx)` returns its witness set, and the building machine adds it. +With `keySigner(key)`, the key must be where `built` is: `await built.sign({ signers: keySigner(key) })`, as in [Sign with a Private Key](#sign-with-a-private-key). When the key is elsewhere, there are three ways. Pick by where the key is: -```tsx -import { keySigner, signWitnesses } from "@meshsdk/core"; +- On a machine that can run Mesh: [With Mesh on the Cold Machine](#with-mesh-on-the-cold-machine). You read what you sign. +- In a device or key service that the building machine can reach: [With a Signing Device](#with-a-signing-device). It signs the hash only. +- On a machine with no builder: [Without a Builder](#without-a-builder). It signs what it is given. + +A plan takes the same ways: `plan.step("main").tx` goes out, and `plan.addWitnesses(...)` takes back a witness set or a signed transaction. See [Plans](/apis/txbuilder/plans) and [Servers and Storage](/apis/txbuilder/servers#collect-signatures-over-several-days). + +### With Mesh on the Cold Machine + +Make the same kind of object there from the bytes. Two things go to the cold machine: the transaction and the UTxOs it names (its inputs, collateral inputs and reference inputs). One thing comes back: the signed transaction. + +The builder there needs no provider, but it needs the full `params`: save `(await builder.chain()).params` once online. `fromCbor` uses only their `maxTxSize`, but the builder checks them all. With no provider, `knownUtxos` must hold every UTxO the transaction names, else `MISSING_FETCHER`. -const witnessSet = await signWitnesses(keySigner(coldKey), built.tx); // on the cold machine -await built.addWitnesses(witnessSet); // back on the building machine +```tsx +import { keySigner, toMeshUtxo, TxBuilder } from "@meshsdk/core"; + +// On the building machine: send the transaction and the UTxOs it names +const named = [ + ...built.inputs, + ...built.referenceInputs, + ...(built.collateral?.inputs ?? []), +]; +const toCold = JSON.stringify({ tx: built.tx, utxos: named.map(toMeshUtxo) }); + +// On the cold machine +const sent = JSON.parse(toCold); +const cold = new TxBuilder({ network: "preprod", params }); +const received = await cold.fromCbor(sent.tx, { knownUtxos: sent.utxos }); +const { outputs, fee, missing, collateral, warnings } = received; // read before you sign +await received.sign({ signers: keySigner(coldKey) }); +console.log(received.missing); // empty when every key has signed +const signed = received.partialTx; // goes back to the building machine + +// Back on the building machine +await built.addWitnesses(signed); // a signed transaction or just its witness set await built.submit(); ``` +Read what the object shows first: the key signs the body as it is, whatever you were told. `outputs` and `fee` come from the bytes you hold. The UTxOs decide which keys are listed. Your own building machine is your own data. For a transaction another party built, look the UTxOs up yourself. [Read a Transaction Built Elsewhere](/apis/txbuilder/offline#read-a-transaction-built-elsewhere) lists what else to check, `collateral` and `warnings` among it. + +Send back `partialTx`. Once no key is missing it is `signedTx`. A key that no one asked for signs nothing and throws nothing, so look at `missing` before you send. + +### With a Signing Device + +Use this when the key sits in a device that the building machine reaches. Sign on the building machine, with a function that carries `txHash` to the device and returns its signatures. The request is the one of [Sign with Your Own Code](#sign-with-your-own-code). + +```tsx +await built.sign({ + signers: async ({ txHash, keys }) => { + if (!keys?.some(({ keyHash }) => keyHash === device.keyHash)) return []; // not its key + return [await device.sign(txHash)]; // { vkey, signature } in hex + }, +}); +``` + +The function may wait while a person carries the hash to the device. There is no deadline: pass a `signal` to stop waiting. You decide what the device gets. Here it sees only the hash, so it signs blind. The request also holds `tx`: pass it too, and the device can show what is paid. + +### Without a Builder + +A machine with no builder uses the lower layer: `signWitnesses(keySigner(coldKey), tx)` of `@meshsdk/core` returns a witness set, and `built.addWitnesses(witnessSet)` takes it. It signs what it is given and shows nothing of what the transaction pays. + ## Submit and Wait `submit()` sends the same bytes every time it is called. `awaitInclusion()` looks for the transaction until the provider finds it in a block, and returns `{ txHash, slot, block, blockHeight }` as far as the provider gives them. That is one sighting, and a rollback can undo it. `sign()`, `submit()` and `awaitInclusion()` take a `signal` to stop their waiting. @@ -188,7 +242,7 @@ await again.submit(); // the same bytes - [Transaction Basics](/apis/txbuilder/basics) - build, sign and submit in one path - [Plans](/apis/txbuilder/plans) - send transactions in order, with retries that cannot pay twice -- [Offline and CBOR](/apis/txbuilder/offline) - save and restore, and sign on a cold machine +- [Offline and CBOR](/apis/txbuilder/offline) - save and restore, and read a transaction built elsewhere - [Errors](/apis/txbuilder/errors) - every code and which a retry can fix - [UTxOs and Inputs](/apis/txbuilder/utxos) - choose what a transaction spends - [Time and Validity](/apis/txbuilder/time) - give a transaction a deadline From 8f5231ff8898610551dccc6355f95deb253bf2b8 Mon Sep 17 00:00:00 2001 From: lisicky Date: Sun, 22 Nov 2026 21:47:03 +0100 Subject: [PATCH 08/15] docs: how TxBuilder works --- components/txbuilder/builder-flow.tsx | 733 ++++++++++++++++++++++++++ content/docs/apis/txbuilder/index.mdx | 15 + 2 files changed, 748 insertions(+) create mode 100644 components/txbuilder/builder-flow.tsx diff --git a/components/txbuilder/builder-flow.tsx b/components/txbuilder/builder-flow.tsx new file mode 100644 index 0000000..ac9b090 --- /dev/null +++ b/components/txbuilder/builder-flow.tsx @@ -0,0 +1,733 @@ +"use client"; + +// A scheme of working with TxBuilder: every underlined name is a link to the page that explains it. +// Hand-written SVG in the look of plan-status-graph.tsx: colors come from the fumadocs +// theme classes and currentColor, so the scheme reads in light and dark mode. +// Two layouts of the same content: a wide one (left to right) and a narrow one (top to bottom) +// for a column under 600px, so a phone never has to scroll the scheme sideways. + +import Link from "next/link"; + +const B = "/apis/txbuilder"; + +const GAP = 4; // distance between the two borders of a terminal box +const TIP = 4; // the arrowhead tip lies this far beyond the end of its line +const END = 2 + TIP; // a line ends this far before the box it points at: air plus the arrowhead +const LINK = "group/link cursor-pointer outline-none"; // the focus ring is drawn by Ring +const BOX = "fill-fd-card stroke-fd-muted-foreground group-hover/link:fill-fd-accent group-hover/link:stroke-fd-foreground"; + +const WIDE_ARROW = "bf-arrow-wide"; +const NARROW_ARROW = "bf-arrow-narrow"; + +// ---------------------------------------------------------------- content, shared by both layouts + +type Part = { href: string; title: string; name: string; code: string[] }; +type Step = { + href: string; + title: string; + name: string; + code?: string; + codeSize?: number; + terminal?: boolean; + skipTab?: boolean; // goes where the box before it goes: out of the Tab order, still a link +}; +type Around = { href: string; title: string; names: string[]; codes: string[] }; + +const L = { + create: { href: `${B}/basics#create-a-builder`, title: "Create a builder (Transaction Basics)" }, + networks: { href: `${B}/networks`, title: "Networks and providers (Providers and Networks)" }, + offline: { + href: `${B}/offline#build-offline`, + title: + "Offline, no provider: params, costModels. Without a provider you can build and sign; plans and awaitInclusion() need one, and submit() needs a provider or a submitter (Offline and CBOR)", + }, + payer: { + href: `${B}/basics#choose-the-payer`, + title: "Who pays: the payer of each build() or plan(); the builder holds none (Transaction Basics)", + }, + signers: { + href: `${B}/signing#who-pays-signs-and-submits`, + title: + "Signers and submitter: signers are named in sign() or run(), the submitter in submit(), run() or on the builder (Signing and Submitting)", + }, + which: { href: `${B}#which-part-for-what`, title: "Which part for what (this page)" }, + provider: { + href: `${B}/networks#use-blockfrost-for-plans`, + title: + "Needs a provider with block heights: plan() reads the chain tip, so a builder without a provider cannot plan (Providers and Networks)", + }, + notLand: { + href: `${B}/plans#handle-a-step-that-does-not-go-through`, + title: "A step that does not land: replan() pays what is left (Plans)", + }, + store: { href: `${B}/servers#record-plans-in-a-store`, title: "Plans in a store, on a server (Servers and Storage)" }, +}; + +const PARTS: Part[] = [ + { href: `${B}/basics#send-lovelace-and-assets`, title: "Outputs: send lovelace and assets (Transaction Basics)", name: "Outputs", code: ["output"] }, + { href: `${B}/utxos`, title: "Inputs: give, limit and chain UTxOs (UTxOs and Inputs)", name: "Inputs", code: ["spend.pubKey"] }, + { href: `${B}/time`, title: "Time: expiry, start time and slots (Time and Validity)", name: "Time", code: ["validity"] }, + { href: `${B}/minting`, title: "Mint: mint and burn assets (Mint and Burn Assets)", name: "Mint", code: ["mint.native", "mint.plutus"] }, + { href: `${B}/smart-contracts`, title: "Scripts: lock, spend and read at a script (Smart Contracts)", name: "Scripts", code: ["spend.plutus", "spend.native"] }, + { href: `${B}/staking`, title: "Staking: register, delegate and withdraw (Staking Transactions)", name: "Staking", code: ["certificate.*", "withdrawal.*"] }, + { href: `${B}/governance`, title: "Governance: DReps, votes and proposals (Governance Transactions)", name: "Governance", code: ["vote", "proposal.*"] }, +]; + +const SIGNING = `${B}/signing#who-pays-signs-and-submits`; +const SUBMIT = `${B}/signing#submit-and-wait`; +const BUILD = `${B}/basics#build-sign-and-submit`; +const MAKE = `${B}/plans#make-and-run-a-plan`; +const STATUSES = `${B}/plans#read-the-statuses`; + +const ONE_TX: Step[] = [ + { href: BUILD, title: "Build: build() signs nothing and sends nothing (Transaction Basics)", name: "Build", code: "builder.build(parts, { payer })" }, + { href: BUILD, title: "Result: the BuiltTx that build() returns (Transaction Basics)", name: "Result", code: "BuiltTx", skipTab: true }, + { href: SIGNING, title: "Sign: sign() (Signing and Submitting)", name: "Sign", code: "sign()" }, + { href: SUBMIT, title: "Send: submit() (Signing and Submitting)", name: "Send", code: "submit()" }, + { + href: SUBMIT, + title: "Wait for a block: one sighting, a rollback can undo it; to follow a payment to final, use a plan (Signing and Submitting)", + name: "Wait", + code: "awaitInclusion()", + skipTab: true, + }, +]; + +const A_PLAN: Step[] = [ + { + href: MAKE, + title: + "Plan: one list of parts is one step, main; an object of named steps is several. plan() builds every step, sends nothing, and needs a provider that returns block heights (Plans)", + name: "Plan", + code: "builder.plan(parts, { payer })", + }, + { href: MAKE, title: "Result: the plan object (a TxPlan) that plan() returns, with run(), step() and status (Plans)", name: "Result", code: "TxPlan", skipTab: true }, + { href: MAKE, title: "Run: sign, send and wait until each step is in a block, included by default (Plans)", name: "Run", code: "run()", skipTab: true }, + { href: STATUSES, title: "Statuses: read the status of a plan and of its steps (Plans)", name: "Statuses", code: "plan.status" }, + { + href: STATUSES, + title: 'Final: run({ waitFor: "final" }) waits for confirmations; this status never changes (Plans)', + name: "Final", + code: 'waitFor: "final"', + codeSize: 12, + terminal: true, + skipTab: true, + }, +]; + +const AROUND: Around[] = [ + { + href: `${B}/offline#read-a-transaction-built-elsewhere`, + title: + "A transaction from elsewhere: fromCbor() and restore() give a BuiltTx to sign and submit, or a plan step; requiredSigners() lists its keys (Offline and CBOR)", + names: ["A transaction", "from elsewhere"], + codes: ["fromCbor, restore,", "requiredSigners"], + }, + { href: `${B}/testing`, title: "Tests with a local ledger (Testing on the Emulator)", names: ["Tests"], codes: ["TxEmulator"] }, + { href: `${B}/errors#check-a-code`, title: "Errors: TxError.is checks a code (Errors)", names: ["Errors"], codes: ["TxError.is"] }, + { href: `${B}/options`, title: "Options of the builder, build() and plan() (Options)", names: ["Options"], codes: ["new TxBuilder,", "build(), plan()"] }, + { href: `${B}/migration`, title: "Coming from MeshTxBuilder (Migrating to TxBuilder)", names: ["Coming from"], codes: ["MeshTxBuilder"] }, +]; + +const LABEL = + "Working with TxBuilder, step by step. 1: create a builder. 2: say who pays, for each call. 3: give the parts. Then 4: build one transaction, sign it, submit it and wait for a block, or 5: make a plan of one or several transactions, run it and read its statuses. 6: around the flow, a transaction from elsewhere, tests, errors, options and coming from MeshTxBuilder. Every underlined name is a link to the page that explains it."; + +// ---------------------------------------------------------------- drawing pieces + +function Arrowhead({ id }: { id: string }) { + // refX 6 of 10: the line ends under the head, the tip lies TIP beyond the end of the line + return ( + + + + ); +} + +function Edge({ d, marker, main = false }: { d: string; marker: string; main?: boolean }) { + // main: the usual path, a heavier line + return ; +} + +// Lines that stop short of the box they point at. +const hLine = (from: number, to: number, y: number) => `M ${from + 2} ${y} H ${to - END}`; +const vLine = (x: number, from: number, to: number) => `M ${x} ${from + 2} V ${to - END}`; +// From a vertical spine, round the corner and go right to a box. +const elbow = (spine: number, y0: number, cy: number, boxX: number) => + `M ${spine} ${y0} V ${cy - 12} Q ${spine} ${cy} ${spine + 12} ${cy} H ${boxX - END}`; + +// The focus ring: drawn only for keyboard focus, so it shows in every browser. +function Ring({ x, y, w, h, r = 6 }: { x: number; y: number; w: number; h: number; r?: number }) { + return ( + + ); +} + +// A link made of one line of words. `width` is the width of the text (measured in the +// browser), used for the focus ring and the hover area. +function TextLink({ + href, + title, + x, + y, + width, + anchor = "start", + fontSize = 13, + semibold = false, + children, +}: { + href: string; + title: string; + x: number; + y: number; // the middle line of the text + width: number; + anchor?: "start" | "end"; + fontSize?: number; + semibold?: boolean; + children: React.ReactNode; +}) { + const left = anchor === "end" ? x - width : x; + return ( + + {title} + + + + {children} + + + ); +} + +// A box that is one link: plain words (underlined) above the code names (monospace). +function NodeLink({ + href, + title, + x, + y, + w, + h, + names, + codes = [], + lh = 17, + codeSize = 13, + terminal = false, + skipTab = false, +}: { + href: string; + title: string; + x: number; + y: number; + w: number; + h: number; + names: string[]; + codes?: string[]; + lh?: number; + codeSize?: number; + terminal?: boolean; + skipTab?: boolean; +}) { + const cx = x + w / 2; + const lines = names.length + codes.length; + const first = y + (h - lines * lh) / 2 + lh / 2; + const pad = terminal ? GAP : 0; + return ( + + {title} + + {terminal && ( + + )} + {names.map((line, i) => ( + + {line} + + ))} + {codes.map((line, i) => ( + + {line} + + ))} + + + ); +} + +// A box of the narrow layout: the name on the left, the code on the right, one line. +function RowLink({ step, x, y, w, h }: { step: Step; x: number; y: number; w: number; h: number }) { + const cy = y + h / 2; + const pad = step.terminal ? GAP : 0; + return ( + + {step.title} + + {step.terminal && ( + + )} + + {step.name} + + {step.code && ( + + {step.code} + + )} + + + ); +} + +// The number of a step, in a ring. +function Badge({ cx, cy, n }: { cx: number; cy: number; n: number }) { + return ( + + + + {n} + + + ); +} + +function Legend({ x, y, marker }: { x: number; y: number; marker: string }) { + return ( + + + + usual path + + + + another path + + + ); +} + +function Caption({ x, y, children }: { x: number; y: number; children: React.ReactNode }) { + return ( + + {children} + + ); +} + +function Sub({ x, y, children }: { x: number; y: number; children: React.ReactNode }) { + return ( + + {children} + + ); +} + +function Frame({ children, note }: { children: React.ReactNode; note: string }) { + // The wide svg keeps a 760px minimum so its text stays legible. Under 600px the narrow + // svg takes its place; between the two the box scrolls and the hint shows. Keyboard focus + // scrolls the focused link into view, which the browser does not do for a link that is + // only partly visible. + return ( +
+
{ + if (e.target !== e.currentTarget) (e.target as Element).scrollIntoView?.({ block: "nearest", inline: "center" }); + }} + > + {children} +
+

+ Scroll sideways to see the whole scheme. The numbered list below has the same steps and links. +

+

{note}

+
+ ); +} + +// ---------------------------------------------------------------- the wide layout + +function WideScheme() { + const M = WIDE_ARROW; + // Geometry. Row 1: two boxes. Row 2: the parts. Then two lanes, notes, then the boxes around. + const row1 = { y: 16, h: 140 }; + const box1 = { x: 20, w: 410 }; + const box2 = { x: 470, w: 410 }; + const parts = { y: 196, h: 128 }; + const laneA = { cap: 356, y: 376, cy: 401 }; + const laneB = { cap: 458, y: 476, cy: 501 }; + const NH = 50; // height of a box in a lane + const spine = 40; + const notes = laneB.y + NH + 28; + const around = { cap: 598, y: 618, h: 80, w: 160 }; + // Columns of the lanes: x and width; the same for both lanes. + const col = [ + { x: 68, w: 258 }, + { x: 354, w: 84 }, + { x: 466, w: 84 }, + { x: 578, w: 108 }, + { x: 714, w: 150 }, + ]; + const last = col.length - 2; + const arrowsA = col.slice(0, -1).map((c, i) => hLine(c.x + c.w, col[i + 1].x, laneA.cy)); + const arrowsB = col.slice(0, -1).map((c, i) => hLine(c.x + c.w, col[i + 1].x - (i === last ? GAP : 0), laneB.cy)); + + return ( + + Working with TxBuilder + + + + + {/* arrows first, so the boxes sit on top of their ends */} + + + {/* from the parts to the two lanes */} + + + {arrowsA.map((d) => ( + + ))} + {arrowsB.map((d) => ( + + ))} + + {/* 1: create a builder */} + + Create a builder + + + + Create a builder + + + new TxBuilder({"{"} network, provider {"}"}) + + + Networks and providers + + + Offline, no provider: params, costModels + + + + {/* 2: who pays */} + + Who pays + + + + Who pays + + + {"{ payer }"} of each call: a wallet, an address, + + + or your own {"{ changeAddress, utxos }"} + + + Signers and submitter + + + + {/* 3: the parts */} + + + + Parts + + + one part or a list; the builder picks inputs, adds change and sets the fee + + + Which part for what + + {PARTS.map((c, i) => ( + + ))} + + {/* 4: one transaction */} + + + One transaction + + + build, sign and send; you follow the outcome + + + {ONE_TX.map((s, i) => ( + + ))} + + {/* 5: a plan */} + + + Or a plan + + + one or several transactions, sent in order, never rebuilt + + + Needs a provider with block heights + + {A_PLAN.map((s, i) => ( + + ))} + + A step that does not land: replan() + + + Plans in a store, on a server + + + {/* 6: around the flow */} + + + Around the flow + + {AROUND.map((a, i) => ( + + ))} + + ); +} + +// ---------------------------------------------------------------- the narrow layout + +function NarrowScheme() { + const M = NARROW_ARROW; + const W = 380; + const box = { x: 10, w: 360, h: 140 }; + const spine = 28; + const bx = 58; // the boxes of a lane + const bw = 302; + const RH = 32; // height of a row in a lane + const RG = 22; // distance between two rows + const rowY = (y0: number, i: number) => y0 + i * (RH + RG); + + const y1 = 10; + const y2 = y1 + box.h + 30; + const yParts = y2 + box.h + 30; + const partsH = 312; + const capA = yParts + partsH + 40; + const yA = capA + 42; + const endA = rowY(yA, 4) + RH; + const capB = endA + 44; + const yB = capB + 90; + const endB = rowY(yB, 4) + RH; + const yNotes = endB + 40; + const yLegend = yNotes + 52; + const capC = yLegend + 50; + const yC = capC + 24; + const cw = 175; + const heights = [58, 62, 62]; + const rowsC = [yC, yC + 58 + 10, yC + 58 + 10 + 62 + 10]; + const H = rowsC[2] + heights[2] + 16; + + const arrowsA = ONE_TX.slice(0, -1).map((_, i) => vLine(bx + bw / 2, rowY(yA, i) + RH, rowY(yA, i + 1))); + const arrowsB = A_PLAN.slice(0, -1).map((_, i) => vLine(bx + bw / 2, rowY(yB, i) + RH, rowY(yB, i + 1) - (i === 3 ? GAP : 0))); + const chipX = (i: number) => 19 + (i % 3) * 116; + const chipY = (i: number) => yParts + 88 + Math.floor(i / 3) * 72; + + return ( + + Working with TxBuilder + + + + + {/* arrows first, so the boxes sit on top of their ends */} + + + + + {arrowsA.map((d) => ( + + ))} + {arrowsB.map((d) => ( + + ))} + + {/* 1: create a builder */} + + Create a builder + + + + Create a builder + + + new TxBuilder({"{"} network, provider {"}"}) + + + Networks and providers + + + Offline, no provider: params, costModels + + + + {/* 2: who pays */} + + Who pays + + + + Who pays + + + {"{ payer }"} of each call: a wallet, an address, + + + or your own {"{ changeAddress, utxos }"} + + + Signers and submitter + + + + {/* 3: the parts */} + + + + Parts + + + Which part for what + + + one part or a list; the builder picks inputs, + + + adds change and sets the fee + + {PARTS.map((c, i) => ( + + ))} + + {/* 4: one transaction */} + + + One transaction + + + build, sign and send; you follow the outcome + + {ONE_TX.map((s, i) => ( + + ))} + + {/* 5: a plan */} + + + Or a plan + + + one or several transactions, + + + sent in order, never rebuilt + + + Needs a provider with block heights + + {A_PLAN.map((s, i) => ( + + ))} + + A step that does not land: replan() + + + Plans in a store, on a server + + + + {/* 6: around the flow */} + + + Around the flow + + {AROUND.map((a, i) => { + const first = i === 0; + const x = first ? 10 : 10 + ((i - 1) % 2) * (cw + 10); + const y = first ? rowsC[0] : rowsC[1 + Math.floor((i - 1) / 2)]; + const h = first ? heights[0] : heights[1]; + return ( + + ); + })} + + ); +} + +export function BuilderFlow() { + return ( + + + + + ); +} diff --git a/content/docs/apis/txbuilder/index.mdx b/content/docs/apis/txbuilder/index.mdx index 5fc774f..7223726 100644 --- a/content/docs/apis/txbuilder/index.mdx +++ b/content/docs/apis/txbuilder/index.mdx @@ -11,6 +11,7 @@ import { CardDescription, CardTitle, } from "@/components/ui/card"; +import { BuilderFlow } from "@/components/txbuilder/builder-flow"; > **Note:** Coming from `MeshTxBuilder`, the chain of calls? It is deprecated but still works. See [Migrating to TxBuilder](/apis/txbuilder/migration). @@ -40,12 +41,26 @@ console.log(built.txHash); `TxBuilder` lives in `@meshsdk/transaction`, and `@meshsdk/core` re-exports it. Amounts are `bigint`. `built.tx` is the unsigned transaction as a hex string (CBOR). For other providers, see [Providers](/providers). +## How It Works + +You make one builder; each `build()` or `plan()` call takes the parts and `{ payer }`. Build one transaction, or plan one or several. Every underlined name in the scheme is a link to the page that explains it. + + + +1. [Create a builder](/apis/txbuilder/basics#create-a-builder): `new TxBuilder({ network, provider })`; see [networks and providers](/apis/txbuilder/networks), and [offline use](/apis/txbuilder/offline#build-offline) without a provider (`params`, `costModels`), which can `build()` and sign but cannot plan. +2. [Choose who pays](/apis/txbuilder/basics#choose-the-payer): `{ payer }` is a wallet, an address or `{ changeAddress, utxos }`, given to each call; the payer signs by default. Name other [signers](/apis/txbuilder/signing#who-pays-signs-and-submits) in `sign()` or `run()`, and a submitter in `submit()`, `run()` or on the builder (else the provider sends). +3. Give the parts ([which part for what](/apis/txbuilder#which-part-for-what)): [outputs](/apis/txbuilder/basics#send-lovelace-and-assets), [inputs](/apis/txbuilder/utxos), [time](/apis/txbuilder/time), [mint](/apis/txbuilder/minting), [scripts](/apis/txbuilder/smart-contracts), [staking](/apis/txbuilder/staking) and [governance](/apis/txbuilder/governance). +4. One transaction: [`builder.build(parts, { payer })`](/apis/txbuilder/basics#build-sign-and-submit) returns a `BuiltTx`; then [`sign()`](/apis/txbuilder/signing#who-pays-signs-and-submits), [`submit()` and `awaitInclusion()`](/apis/txbuilder/signing#submit-and-wait), which waits for a block, not for `final`. +5. Or a plan of one or several transactions: [`builder.plan(parts, { payer })`](/apis/txbuilder/plans#make-and-run-a-plan) returns a `TxPlan` and needs a provider that returns block heights ([Use Blockfrost for Plans](/apis/txbuilder/networks#use-blockfrost-for-plans)); [`run()`](/apis/txbuilder/plans#make-and-run-a-plan) it (it returns at `included`), then `run({ waitFor: "final" })` or `refresh()` until the [statuses](/apis/txbuilder/plans#read-the-statuses) show `final`; [`replan()`](/apis/txbuilder/plans#handle-a-step-that-does-not-go-through) pays what is left after a step that did not land; on a server, keep plans [in a store](/apis/txbuilder/servers#record-plans-in-a-store). +6. Around the flow: a [transaction from elsewhere](/apis/txbuilder/offline#read-a-transaction-built-elsewhere) (`fromCbor` and `restore` give a `BuiltTx`; `requiredSigners` lists its keys), [tests](/apis/txbuilder/testing), [errors](/apis/txbuilder/errors#check-a-code) (`TxError.is`), [options](/apis/txbuilder/options), and [coming from `MeshTxBuilder`](/apis/txbuilder/migration). + ## Which Part for What | Part | Use it to | |------|-----------| | `output`, `metadata`, `message`, `validity`, `guard.pubKey` | send assets, add metadata, set validity, require a signer | | `mint.native`, `mint.plutus` | mint and burn assets | +| `spend.pubKey`, `collateral`, `collateralReturn` | spend a particular output, set the collateral | | `spend.plutus`, `spend.native`, `referenceInput` | lock and spend at a script, read an output | | `certificate.*`, `withdrawal.*` | stake, delegate and withdraw rewards | | `vote`, `proposal.*` | take part in governance | From f9a33d3fa9d6bce7669c13ad9a1d1478433ea788 Mon Sep 17 00:00:00 2001 From: lisicky Date: Sun, 22 Nov 2026 21:54:56 +0100 Subject: [PATCH 09/15] docs: certificates --- content/docs/apis/txbuilder/certificates.mdx | 299 +++++++++++++++++++ content/docs/apis/txbuilder/governance.mdx | 17 +- content/docs/apis/txbuilder/meta.json | 1 + content/docs/apis/txbuilder/staking.mdx | 22 +- data/links-txbuilders.ts | 8 +- 5 files changed, 334 insertions(+), 13 deletions(-) create mode 100644 content/docs/apis/txbuilder/certificates.mdx diff --git a/content/docs/apis/txbuilder/certificates.mdx b/content/docs/apis/txbuilder/certificates.mdx new file mode 100644 index 0000000..383466a --- /dev/null +++ b/content/docs/apis/txbuilder/certificates.mdx @@ -0,0 +1,299 @@ +--- +title: "Certificates" +description: "Every certificate part of TxBuilder: what it does, its deposit, who signs it, and how script credentials and legacy forms work." +--- + +## Overview + +A certificate is a part like any other. `certificate.stakeRegistration({ ... })` goes in the list you give to `builder.build()`. It changes what the chain records: a registered stake key, a delegation, a pool, a DRep. A withdrawal is different. It takes rewards out, and has its own part: see [Withdraw Rewards](/apis/txbuilder/staking#withdraw-rewards). + +There are 17 builders, in six groups: + +| Group | Builders | Use it to | +|-------|----------|-----------| +| [Stake key](#stake-key) | `stakeRegistration`, `stakeDeregistration` | register and deregister a stake key | +| [Delegation](#delegation) | `stakeDelegation`, `voteDelegation`, `stakeAndVoteDelegation`, three `...RegistrationAndDelegation` | delegate stake, vote, or both | +| [Pools](#pools) | `poolRegistration`, `poolRetirement` | run a pool | +| [DReps](#dreps) | `drepRegistration`, `drepUpdate`, `drepDeregistration` | act as a DRep | +| [Committee](#constitutional-committee) | `committeeHotAuth`, `committeeColdResign` | serve on the committee | +| [Legacy forms](#legacy-forms) | `legacyStakeRegistration`, `legacyStakeDeregistration` | old forms, not for new code | + +- Certificates keep the order you give them, because the order is part of the transaction. +- Some certificates take a deposit, and some give one back: see [Deposits](#deposits). +- A certificate is authorised by the key of its credential, or by its script: see [Who Signs](#who-signs). + +Examples stop at `build()`: call `built.sign()` and `built.submit()` as in [Transaction Basics](/apis/txbuilder/basics#build-sign-and-submit). They use `builder` and `wallet` from there, and these names, which your application defines: + +- `rewardAddress` - your stake address (`stake_test1...` on a test network, `stake1...` on mainnet) +- `poolId`, `drepId` - a pool id (`pool1...`) and a DRep id (`drep1...`) +- `anchor` - `{ url, dataHash }`, where a metadata or rationale file is published. `hashDrepAnchor(json)` makes the hash. +- `stakeScript` - a Plutus V3 staking script, `{ code, version }` +- `operatorKeyHash`, `vrfKeyHash`, `ownerKeyHash`, `metadataHash` - the values of your pool. `ownerKeyHash` is the stake key hash of a pool owner. +- `operatorKey`, `epoch` - the pool's cold signing key and the retirement epoch +- `coldKeyHash`, `hotKeyHash`, `coldKey` - the keys of a committee member + +These arguments mean the same in every builder: + +| Argument | Takes | +|----------|-------| +| `stake`, `cold`, `hot` | a reward address, or a credential `{ type: "KEY" \| "SCRIPT", value: <28-byte hash in hex> }` | +| `pool` | a pool id in bech32, or the operator key hash in hex | +| `drep` | a DRep id or a credential. A delegation also takes `"alwaysAbstain"` and `"alwaysNoConfidence"` | +| `anchor` | `{ url, dataHash }` | +| `deposit`, `refund` | lovelace as a `bigint`: see [Deposits](#deposits) | +| `witness` | the script of a script credential: see [Who Signs](#who-signs) | +| `label` | a name for the part, shown in errors about it | + +## Certificates by Group + +In every table, "signed by" means the key of the credential. A script credential is authorised by its script instead. The two legacy forms are in [Legacy Forms](#legacy-forms). + +### Stake Key + +Register a stake key before it delegates. Deregister it to get the deposit back. + +| Builder | What it does | Deposit | Signed by | +|---------|--------------|---------|-----------| +| `stakeRegistration` | Registers a stake key | pays `keyDeposit` | the stake key | +| `stakeDeregistration` | Deregisters a stake key | gets `keyDeposit` back | the stake key | + +```tsx +import { certificate } from "@meshsdk/core"; + +// Register: the deposit is the keyDeposit parameter +const register = await builder.build( + certificate.stakeRegistration({ stake: rewardAddress }), + { payer: wallet }, +); + +// Deregister: the refund is the keyDeposit parameter +const leave = await builder.build( + certificate.stakeDeregistration({ stake: rewardAddress }), + { payer: wallet }, +); +``` + +### Delegation + +Delegate stake to a pool, a vote to a DRep, or both. The last three builders also register the key, in the same certificate. + +| Builder | What it does | Deposit | Signed by | +|---------|--------------|---------|-----------| +| `stakeDelegation` | Delegates stake to a pool | none | the stake key | +| `voteDelegation` | Delegates the vote to a DRep | none | the stake key | +| `stakeAndVoteDelegation` | Does both | none | the stake key | +| `stakeRegistrationAndDelegation` | Registers the key, delegates stake | pays `keyDeposit` | the stake key | +| `voteRegistrationAndDelegation` | Registers the key, delegates the vote | pays `keyDeposit` | the stake key | +| `stakeVoteRegistrationAndDelegation` | Registers the key, delegates both | pays `keyDeposit` | the stake key | + +```tsx +import { certificate } from "@meshsdk/core"; + +// A registered key moves its stake to another pool +const move = await builder.build( + certificate.stakeDelegation({ stake: rewardAddress, pool: poolId }), + { payer: wallet }, +); + +// A new key registers, then delegates its stake and its vote +const join = await builder.build( + certificate.stakeVoteRegistrationAndDelegation({ + stake: rewardAddress, + pool: poolId, + drep: "alwaysAbstain", + }), + { payer: wallet }, +); +``` + +### Pools + +A stake pool operator registers a pool, updates it, and retires it. + +| Builder | What it does | Deposit | Signed by | +|---------|--------------|---------|-----------| +| `poolRegistration` | Registers a pool, or updates one | pays `poolDeposit`, none for an update | the operator key and every owner key | +| `poolRetirement` | Retires a pool at the start of an epoch | none in this transaction | the operator key | + +The deposit is `poolDeposit` from the protocol parameters (500 ADA on mainnet), so you give nothing. Sign with the wallet, the operator key and every owner key. An owner key the wallet holds signs with it. Add any other key with `keySigner(...)`. + +When a pool retires, the ledger returns `poolDeposit` to the pool's reward account at that epoch. If that account is not registered then, the deposit goes to the treasury. The retirement transaction itself has no refund. + +```tsx +import { certificate, keySigner } from "@meshsdk/core"; + +const register = await builder.build( + certificate.poolRegistration({ + params: { + operator: operatorKeyHash, + vrfKeyHash, + pledge: "500000000", // lovelace as text: 500 ADA + cost: "340000000", // lovelace as text: 340 ADA + margin: [3, 100], // 3 percent + owners: [ownerKeyHash], // stake key hashes + rewardAddress, + relays: [{ type: "SingleHostName", domainName: "relay.example.com", port: 3001 }], + metadata: { URL: "https://example.com/pool.json", hash: metadataHash }, + }, + }), + { payer: wallet }, // for an update, add registeredPools: [operatorKeyHash] +); +// The owner key signs too: add keySigner(ownerKey) if the wallet does not hold it +await register.sign({ signers: [wallet, keySigner(operatorKey)] }); + +const retire = await builder.build( + certificate.poolRetirement({ pool: poolId, epoch }), + { payer: wallet }, +); +``` + +### DReps + +A DRep (delegated representative) votes for the stake delegated to it. + +| Builder | What it does | Deposit | Signed by | +|---------|--------------|---------|-----------| +| `drepRegistration` | Registers a DRep, with an optional `anchor` | pays `drepDeposit` (you state it: see [Deposits](#deposits)) | the DRep key | +| `drepUpdate` | Changes the `anchor`. Leave it out to clear it | none | the DRep key | +| `drepDeregistration` | Retires a DRep | gets `drepDeposit` back | the DRep key | + +The deposit is not read from the chain. Give `deposit` on the part, or `drepDeposit` on the builder (500 ADA, `500_000_000n`, on mainnet). The DRep key signs. A `MeshWallet` that holds it signs in `built.sign()`, and a browser wallet needs CIP-95. If the key is not in the wallet, `built.missing` lists it. + +```tsx +import { certificate } from "@meshsdk/core"; + +// Register: state the deposit here, or set drepDeposit on the builder +const register = await builder.build( + certificate.drepRegistration({ drep: drepId, deposit: 500_000_000n, anchor }), + { payer: wallet }, +); + +// Retire: the refund is the deposit that was paid +const retire = await builder.build( + certificate.drepDeregistration({ drep: drepId, refund: 500_000_000n }), + { payer: wallet }, +); +``` + +### Constitutional Committee + +A committee member has a cold credential, and authorises a hot credential to vote for it. + +| Builder | What it does | Deposit | Signed by | +|---------|--------------|---------|-----------| +| `committeeHotAuth` | Authorises a hot credential for a member | none | the cold key | +| `committeeColdResign` | Resigns from the committee. `anchor` says why | none | the cold key | + +```tsx +import { certificate, keySigner } from "@meshsdk/core"; + +const cold = { type: "KEY", value: coldKeyHash } as const; + +// The cold key authorises the hot key +const auth = await builder.build( + certificate.committeeHotAuth({ cold, hot: { type: "KEY", value: hotKeyHash } }), + { payer: wallet }, +); +await auth.sign({ signers: [wallet, keySigner(coldKey)] }); + +// The cold key resigns +const resign = await builder.build( + certificate.committeeColdResign({ cold, anchor }), + { payer: wallet }, +); +``` + +## Deposits + +A deposit is paid when something is registered. A refund comes back when it is removed. The builder counts both when it balances, so you add no output for either. The other certificates have neither. + +| Certificate | Deposit | The amount comes from | +|-------------|---------|-----------------------| +| `stakeRegistration`, the three `...RegistrationAndDelegation` | pays | `deposit` on the part, else `keyDeposit` of the protocol parameters | +| `stakeDeregistration` | refund | `refund` on the part, else `keyDeposit` | +| `legacyStakeRegistration`, `legacyStakeDeregistration` | pays, refund | always `keyDeposit` | +| `poolRegistration` | pays, none for an update | `poolDeposit` of the protocol parameters | +| `drepRegistration` | pays | `deposit` on the part, else `drepDeposit` of the builder's `deposits` option | +| `drepDeregistration` | refund | `refund` on the part, else `drepDeposit` of `deposits` | + +The protocol parameters come from the provider, or from the builder's `params`. `drepDeposit` is a protocol parameter that Mesh's `Protocol` type does not carry, so it comes from the `deposits` option: `new TxBuilder({ ..., deposits: { drepDeposit: 500_000_000n } })`. A proposal works the same way, with `govActionDeposit`: see [Governance Transactions](/apis/txbuilder/governance#submit-a-proposal). + +- A `deposit` must equal the current parameter (`keyDeposit` or `drepDeposit`), or the node refuses the transaction. Pass it when the builder does not know the parameter, such as `drepDeposit` without the `deposits` option. +- A refund must be the deposit that was paid. If you paid another amount than the current parameter, pass `refund`. +- `poolRegistration` has no `deposit` argument. A pool in the `registeredPools` option of `build()` is an update, and an update pays none. +- If a certificate with a `deposit` or `refund` argument has neither the amount nor a known parameter, `build()` throws `MISSING_PARAMETER`. `details.parameter` says which: `"params"` or `"deposits"`. Give the amount on the part, or give the builder the option. +- `poolRegistration` and the legacy forms take `poolDeposit` or `keyDeposit` from the protocol parameters only, so give `params` that hold them (a provider does). + +## Who Signs + +The credential of a certificate decides what authorises it. + +| Credential | Authorised by | You give | +|------------|---------------|----------| +| A key | its signature | no `witness` | +| A native script | the script | `witness: { native: script }` | +| A Plutus script | the script, run with a redeemer | `witness: { plutus: script, redeemer }` | + +### Keys + +This is the usual case. + +- The builder works out which keys must sign. `built.missing` lists those that have not, each with its roles: `"certificate"` for the key of the credential, or the operator key of a pool, and `"poolOwner"` for each owner of a pool. +- The payer's wallet also signs for the inputs. A `MeshWallet` signs with the payment, stake and DRep keys it holds. A browser wallet must be connected with the CIP-95 extension to sign with a DRep key. +- Any other key, such as a pool operator key or a committee cold key, goes in as a signer: `built.sign({ signers: [wallet, keySigner(key)] })`. + +### Scripts + +- A key credential given a `witness`, and a script credential given none, are `WITNESS_MISMATCH`. So is a script whose hash is not the credential's. +- A Plutus script must be V3, except for `stakeDelegation` and `legacyStakeDeregistration`, which take any Plutus version. +- The redeemer's index is the place of the certificate among the transaction's certificates, in the order you give them. The builder sets it, and a redeemer function reads it as `tx.self`. + +```tsx +import { certificate, mConStr0 } from "@meshsdk/core"; +import type { NativeScript } from "@meshsdk/core"; + +const redeemer = { data: mConStr0([]) }; +const nativeScript: NativeScript = { type: "sig", keyHash: ownerKeyHash }; + +const built = await builder.build( + [ + // A Plutus script credential: the script runs with the redeemer + certificate.stakeRegistration({ + stake: builder.rewardAddress(stakeScript), + witness: { plutus: stakeScript, redeemer }, + }), + // A native script credential: the script is the witness + certificate.stakeRegistration({ + stake: builder.rewardAddress(nativeScript), + witness: { native: nativeScript }, + }), + ], + { payer: wallet }, +); +``` + +## Legacy Forms + +`certificate.legacyStakeRegistration` and `certificate.legacyStakeDeregistration` are the older certificates 0 and 1. They state no deposit or refund. Both are `@deprecated` and work only until the next ledger era. Write new code with `stakeRegistration` and `stakeDeregistration`. + +| Builder | What it does | Deposit | Signed by | Use instead | +|---------|--------------|---------|-----------|-------------| +| `legacyStakeRegistration` | Registers a stake key | pays `keyDeposit` | nobody: it takes no witness | `stakeRegistration` | +| `legacyStakeDeregistration` | Deregisters a stake key | gets `keyDeposit` back | the stake key | `stakeDeregistration` | + +The legacy deregistration always counts the current `keyDeposit` as its refund. If the deposit paid was another amount, use `stakeDeregistration` with `refund`. + +When you switch: + +- `stakeRegistration` needs the stake key's signature, or the script as `witness`. The legacy registration needs neither. +- `stakeDeregistration` takes a V3 script as witness. The legacy form takes any Plutus version. + +## Related + +- [Staking Transactions](/apis/txbuilder/staking) - register a stake key, delegate, withdraw rewards and run a pool +- [Governance Transactions](/apis/txbuilder/governance) - DReps, votes and proposals +- [Smart Contracts](/apis/txbuilder/smart-contracts) - the Plutus scripts a script credential runs +- [Signing and Submitting](/apis/txbuilder/signing#sign-with-a-private-key) - sign with a stake key, a pool operator key or a cold key +- [Options](/apis/txbuilder/options) - `deposits`, `registeredPools` and the other options +- [Errors](/apis/txbuilder/errors#setup-and-options) - `MISSING_PARAMETER`, and `WITNESS_MISMATCH` under [Errors When Making a Part](/apis/txbuilder/errors#errors-when-making-a-part) +- [Package README](https://github.com/MeshJS/mesh/tree/main/packages/mesh-transaction) - every part, option and error diff --git a/content/docs/apis/txbuilder/governance.mdx b/content/docs/apis/txbuilder/governance.mdx index 604c7fa..722f213 100644 --- a/content/docs/apis/txbuilder/governance.mdx +++ b/content/docs/apis/txbuilder/governance.mdx @@ -5,7 +5,11 @@ description: "Register as a DRep, delegate your vote, vote on actions and submit ## Overview -Governance uses certificates, votes and proposals, passed as parts to `builder.build()`. A DRep (delegated representative) votes on behalf of the stake delegated to it. The DRep and proposal deposits are not in the protocol parameters, so the builder takes them from its `deposits` option, or from `deposit` on a part. Without them the build throws `MISSING_PARAMETER` (see [Handle Errors](/apis/txbuilder/basics#handle-errors)). Use this page to act as a DRep, vote or propose. +Governance uses certificates, votes and proposals, passed as parts to `builder.build()`. A DRep (delegated representative) votes on behalf of the stake delegated to it. Use this page to act as a DRep, vote or propose. + +A certificate changes what the chain records, such as a DRep's registration or a vote delegation. Every certificate is in [Certificates](/apis/txbuilder/certificates). + +The DRep and proposal deposits are protocol parameters that Mesh's `Protocol` type does not carry, so the builder takes them from its `deposits` option, or from `deposit` on a part. Without them the build throws `MISSING_PARAMETER` (see [Deposits](/apis/txbuilder/certificates#deposits)). Examples stop at `build()`: call `built.sign()` and `built.submit()` as in [Transaction Basics](/apis/txbuilder/basics#build-sign-and-submit). They use `wallet` and `provider` from there, and these names, which your application defines: @@ -19,15 +23,17 @@ Examples stop at `build()`: call `built.sign()` and `built.submit()` as in [Tran |------|------|-----------| | Register, update or retire a DRep | `certificate.drepRegistration`, `drepUpdate`, `drepDeregistration` | the DRep key | | Delegate your vote | `certificate.voteDelegation` | the stake key | +| Authorise a hot key or resign from the committee | `certificate.committeeHotAuth`, `committeeColdResign` | the cold key | | Vote on an action | `vote` | the voter's key | | Submit a proposal | `proposal.info`, `proposal.treasuryWithdrawals` and others | the payer | ## Manage a DRep -- Register: `certificate.drepRegistration`. `anchor` is optional, and the deposit is `drepDeposit`. +- Register: `certificate.drepRegistration`. `anchor` is optional. - Update: `certificate.drepUpdate`, with the `anchor` of the changed file. Leave `anchor` out to clear it. -- Retire: `certificate.drepDeregistration`, which refunds `drepDeposit`. Pass `refund` if the deposit paid was another amount. -- Signing: the DRep key signs. A `MeshWallet` does it in `sign()`, and a browser wallet must be connected with the CIP-95 extension. +- Retire: `certificate.drepDeregistration`, which refunds the deposit. +- Deposit: `drepDeposit` from the builder, or `deposit` and `refund` on the part. See [Deposits](/apis/txbuilder/certificates#deposits). +- Signing: the DRep key signs, and a browser wallet must be connected with the CIP-95 extension. See [Who Signs](/apis/txbuilder/certificates#who-signs). ```tsx import { certificate } from "@meshsdk/core"; @@ -40,7 +46,7 @@ const built = await builder.build( ## Delegate Your Vote -A registered stake key delegates its voting power with `certificate.voteDelegation`. `drep` is a DRep id, `"alwaysAbstain"` or `"alwaysNoConfidence"`. To delegate to a pool and a DRep together, use `certificate.stakeAndVoteDelegation`. +A registered stake key delegates its voting power with `certificate.voteDelegation`. `drep` is a DRep id, `"alwaysAbstain"` or `"alwaysNoConfidence"`. To delegate to a pool and a DRep together, use `certificate.stakeAndVoteDelegation`. The combined builders are in [Delegation](/apis/txbuilder/certificates#delegation). ```tsx import { certificate } from "@meshsdk/core"; @@ -110,6 +116,7 @@ const built = await builder.build( ## Related +- [Certificates](/apis/txbuilder/certificates) - every certificate, its deposit and its signer - [Staking Transactions](/apis/txbuilder/staking) - register a stake key, delegate and withdraw - [Transaction Basics](/apis/txbuilder/basics) - the builder, the payer and signing - [Signing and Submitting](/apis/txbuilder/signing) - sign with a DRep key or several signers diff --git a/content/docs/apis/txbuilder/meta.json b/content/docs/apis/txbuilder/meta.json index 57221f4..1cf8355 100644 --- a/content/docs/apis/txbuilder/meta.json +++ b/content/docs/apis/txbuilder/meta.json @@ -14,6 +14,7 @@ "smart-contracts", "staking", "governance", + "certificates", "---Environments---", "offline", "testing", diff --git a/content/docs/apis/txbuilder/staking.mdx b/content/docs/apis/txbuilder/staking.mdx index 5b8b313..a60f48b 100644 --- a/content/docs/apis/txbuilder/staking.mdx +++ b/content/docs/apis/txbuilder/staking.mdx @@ -5,7 +5,14 @@ description: "Register a stake key, delegate to a pool, withdraw rewards and der ## Overview -Staking uses certificates and withdrawals, passed as parts to `builder.build()`. Use this page to register a stake key, delegate, collect rewards or run a pool. +Staking uses two kinds of part, passed to `builder.build()`: + +| Part | What it does | +|------|--------------| +| `withdrawal.*` | takes rewards out of a reward account | +| `certificate.*` | changes what the chain records: a stake key, a delegation, a pool | + +Use this page to register a stake key, delegate, collect rewards or run a pool. Every certificate, its deposit and its signer are in [Certificates](/apis/txbuilder/certificates). Examples stop at `build()`: call `built.sign()` and `built.submit()` as in [Transaction Basics](/apis/txbuilder/basics#build-sign-and-submit). They use `builder` and `wallet` from there, and these names, which your application defines: @@ -26,7 +33,7 @@ Examples stop at `build()`: call `built.sign()` and `built.submit()` as in [Tran ## Register and Delegate -A stake key must be registered before it can delegate. List both certificates to do it in one transaction: they keep the order you give them. The deposit is the `keyDeposit` protocol parameter unless you pass `deposit`. `pool` is a bech32 pool id or the operator key hash. +A stake key must be registered before it can delegate. List both certificates to do it in one transaction: they keep the order you give them. The deposit is `keyDeposit` from the protocol parameters, unless you pass `deposit`: see [Deposits](/apis/txbuilder/certificates#deposits). `pool` is a bech32 pool id or the operator key hash. ```tsx import { certificate } from "@meshsdk/core"; @@ -40,7 +47,7 @@ const built = await builder.build( ); ``` -If the wallet does not hold the stake key, pass the key as a signer: `built.sign({ signers: [wallet, keySigner()] })`. `built.missing` lists the keys that have not signed yet. `certificate.stakeDelegation` alone changes the delegation of a registered key, and `certificate.stakeRegistrationAndDelegation` does both in one certificate. +If the wallet does not hold the stake key, pass the key as a signer: `built.sign({ signers: [wallet, keySigner()] })`. `built.missing` lists the keys that have not signed yet: see [Who Signs](/apis/txbuilder/certificates#who-signs). `certificate.stakeDelegation` alone changes the delegation of a registered key, and `certificate.stakeRegistrationAndDelegation` does both in one certificate: see [Delegation](/apis/txbuilder/certificates#delegation). ## Withdraw Rewards @@ -59,7 +66,7 @@ To state the amount yourself, write `amount: 5_000_000n`. It must equal the whol ## Deregister a Stake Key -Deregistering refunds the deposit, which defaults to `keyDeposit`. Pass `refund` if the deposit paid was another amount. The reward balance must be empty, so withdraw it in the same transaction. +Deregistering refunds `keyDeposit`: see [Deposits](/apis/txbuilder/certificates#deposits). The reward balance must be empty, so withdraw it in the same transaction. ```tsx import { certificate, withdrawal } from "@meshsdk/core"; @@ -79,7 +86,7 @@ A stake address can be held by a Plutus script: - Withdraw: use `withdrawal.plutus` with the script and a redeemer (the data you give the script). Leave out `rewardAddress` and the builder derives the script's own address. - Amounts: `0n` runs the script without taking rewards, and works only while the reward balance is zero. To run the script whatever the balance, use `amount: "all"`. -- Certificate: a certificate of a script's stake address takes the script as its `witness`: `{ plutus, redeemer }`, which must be V3, or `{ native }`. +- Certificate: a certificate of a script's stake address takes the script as its `witness`. The rules are in [Who Signs](/apis/txbuilder/certificates#who-signs). - Native script: withdraw with `withdrawal.native`. ```tsx @@ -100,11 +107,11 @@ const built = await builder.build( ); ``` -The script's stake address must be registered first, with `certificate.stakeRegistration` and the same `witness`. +The script's stake address must be registered first, with `certificate.stakeRegistration` and the same `witness`, which must then be a V3 script. ## Register a Pool -A stake pool operator registers a pool with `certificate.poolRegistration`. `pledge` and `cost` are lovelace as text. `margin` is `[numerator, denominator]`. The operator and owner keys sign, so pass the operator key as a signer. A first registration pays the pool deposit. To update a pool that is already registered, list its operator key hash in the `registeredPools` option of `build()`, and no deposit is owed. +A stake pool operator registers a pool with `certificate.poolRegistration`. `pledge` and `cost` are lovelace as text. `margin` is `[numerator, denominator]`. The operator and owner keys sign, so pass the operator key as a signer, and any owner key the wallet does not hold. A first registration pays `poolDeposit` from the protocol parameters, an update pays none: see [Deposits](/apis/txbuilder/certificates#deposits). To update a pool that is already registered, list its operator key hash in the `registeredPools` option of `build()`. ```tsx import { certificate, keySigner } from "@meshsdk/core"; @@ -132,6 +139,7 @@ To retire the pool, use `certificate.poolRetirement({ pool: poolId, epoch })`. T ## Related +- [Certificates](/apis/txbuilder/certificates) - every certificate, its deposit and its signer - [Transaction Basics](/apis/txbuilder/basics) - the builder, the payer and signing - [Smart Contracts](/apis/txbuilder/smart-contracts) - Plutus scripts that spend and mint - [Governance Transactions](/apis/txbuilder/governance) - DReps, voting and proposals diff --git a/data/links-txbuilders.ts b/data/links-txbuilders.ts index c069af2..c05754b 100644 --- a/data/links-txbuilders.ts +++ b/data/links-txbuilders.ts @@ -33,13 +33,18 @@ export const metaTxbuilderSmartContract = { export const metaTxbuilderStaking = { link: `/apis/txbuilder/staking`, title: "Staking Transactions", - desc: "Register, delegate, withdraw and manage a pool", + desc: "Register, delegate, withdraw rewards and run a pool", }; export const metaTxbuilderGovernance = { link: `/apis/txbuilder/governance`, title: "Governance Transactions", desc: "Register as a DRep, vote and submit proposals", }; +export const metaTxbuilderCertificates = { + link: `/apis/txbuilder/certificates`, + title: "Certificates", + desc: "Every certificate: deposits, signers, scripts and legacy forms", +}; export const metaTxbuilderPlans = { link: `/apis/txbuilder/plans`, title: "Plans", @@ -90,6 +95,7 @@ export const linksTxbuilder = [ metaTxbuilderSmartContract, metaTxbuilderStaking, metaTxbuilderGovernance, + metaTxbuilderCertificates, metaTxbuilderPlans, metaTxbuilderServers, metaTxbuilderOffline, From 7f1d6bc23619782496d12c6079434c747214543e Mon Sep 17 00:00:00 2001 From: lisicky Date: Sun, 22 Nov 2026 22:05:38 +0100 Subject: [PATCH 10/15] docs: certificates apart from staking --- components/txbuilder/builder-flow.tsx | 34 +++++++++++++++++++++------ content/docs/apis/txbuilder/index.mdx | 5 ++-- content/docs/apis/txbuilder/meta.json | 2 +- data/links-txbuilders.ts | 2 +- 4 files changed, 32 insertions(+), 11 deletions(-) diff --git a/components/txbuilder/builder-flow.tsx b/components/txbuilder/builder-flow.tsx index ac9b090..b290310 100644 --- a/components/txbuilder/builder-flow.tsx +++ b/components/txbuilder/builder-flow.tsx @@ -69,7 +69,13 @@ const PARTS: Part[] = [ { href: `${B}/time`, title: "Time: expiry, start time and slots (Time and Validity)", name: "Time", code: ["validity"] }, { href: `${B}/minting`, title: "Mint: mint and burn assets (Mint and Burn Assets)", name: "Mint", code: ["mint.native", "mint.plutus"] }, { href: `${B}/smart-contracts`, title: "Scripts: lock, spend and read at a script (Smart Contracts)", name: "Scripts", code: ["spend.plutus", "spend.native"] }, - { href: `${B}/staking`, title: "Staking: register, delegate and withdraw (Staking Transactions)", name: "Staking", code: ["certificate.*", "withdrawal.*"] }, + { href: `${B}/staking`, title: "Staking: withdraw rewards; the page also walks through stake keys, delegation and pools (Staking Transactions)", name: "Staking", code: ["withdrawal.*"] }, + { + href: `${B}/certificates`, + title: "Certificates: what the chain records, such as stake keys, delegation of stake and votes, pools, DReps and the committee (Certificates)", + name: "Certificates", + code: ["certificate.*"], + }, { href: `${B}/governance`, title: "Governance: DReps, votes and proposals (Governance Transactions)", name: "Governance", code: ["vote", "proposal.*"] }, ]; @@ -381,13 +387,16 @@ function WideScheme() { const row1 = { y: 16, h: 140 }; const box1 = { x: 20, w: 410 }; const box2 = { x: 470, w: 410 }; - const parts = { y: 196, h: 128 }; - const laneA = { cap: 356, y: 376, cy: 401 }; - const laneB = { cap: 458, y: 476, cy: 501 }; + const parts = { y: 196, h: 200 }; // two rows of four chips + const chip = { x: 34, w: 202, step: 210, h: 64, y: 52, rowStep: 72, perRow: 4 }; + const base = parts.y + parts.h; // the lower edge of the parts: the lanes hang from it + const laneA = { cap: base + 32, y: base + 52, cy: base + 77 }; + const laneB = { cap: base + 134, y: base + 152, cy: base + 177 }; const NH = 50; // height of a box in a lane const spine = 40; const notes = laneB.y + NH + 28; - const around = { cap: 598, y: 618, h: 80, w: 160 }; + const around = { cap: notes + 44, y: notes + 64, h: 80, w: 160 }; + const H = around.y + around.h + 22; // the height of the drawing // Columns of the lanes: x and width; the same for both lanes. const col = [ { x: 68, w: 258 }, @@ -402,7 +411,7 @@ function WideScheme() { return ( {PARTS.map((c, i) => ( - + ))} {/* 4: one transaction */} diff --git a/content/docs/apis/txbuilder/index.mdx b/content/docs/apis/txbuilder/index.mdx index 7223726..0e2816a 100644 --- a/content/docs/apis/txbuilder/index.mdx +++ b/content/docs/apis/txbuilder/index.mdx @@ -49,7 +49,7 @@ You make one builder; each `build()` or `plan()` call takes the parts and `{ pay 1. [Create a builder](/apis/txbuilder/basics#create-a-builder): `new TxBuilder({ network, provider })`; see [networks and providers](/apis/txbuilder/networks), and [offline use](/apis/txbuilder/offline#build-offline) without a provider (`params`, `costModels`), which can `build()` and sign but cannot plan. 2. [Choose who pays](/apis/txbuilder/basics#choose-the-payer): `{ payer }` is a wallet, an address or `{ changeAddress, utxos }`, given to each call; the payer signs by default. Name other [signers](/apis/txbuilder/signing#who-pays-signs-and-submits) in `sign()` or `run()`, and a submitter in `submit()`, `run()` or on the builder (else the provider sends). -3. Give the parts ([which part for what](/apis/txbuilder#which-part-for-what)): [outputs](/apis/txbuilder/basics#send-lovelace-and-assets), [inputs](/apis/txbuilder/utxos), [time](/apis/txbuilder/time), [mint](/apis/txbuilder/minting), [scripts](/apis/txbuilder/smart-contracts), [staking](/apis/txbuilder/staking) and [governance](/apis/txbuilder/governance). +3. Give the parts ([which part for what](/apis/txbuilder#which-part-for-what)): [outputs](/apis/txbuilder/basics#send-lovelace-and-assets), [inputs](/apis/txbuilder/utxos), [time](/apis/txbuilder/time), [mint](/apis/txbuilder/minting), [scripts](/apis/txbuilder/smart-contracts), [staking](/apis/txbuilder/staking), [certificates](/apis/txbuilder/certificates) and [governance](/apis/txbuilder/governance). 4. One transaction: [`builder.build(parts, { payer })`](/apis/txbuilder/basics#build-sign-and-submit) returns a `BuiltTx`; then [`sign()`](/apis/txbuilder/signing#who-pays-signs-and-submits), [`submit()` and `awaitInclusion()`](/apis/txbuilder/signing#submit-and-wait), which waits for a block, not for `final`. 5. Or a plan of one or several transactions: [`builder.plan(parts, { payer })`](/apis/txbuilder/plans#make-and-run-a-plan) returns a `TxPlan` and needs a provider that returns block heights ([Use Blockfrost for Plans](/apis/txbuilder/networks#use-blockfrost-for-plans)); [`run()`](/apis/txbuilder/plans#make-and-run-a-plan) it (it returns at `included`), then `run({ waitFor: "final" })` or `refresh()` until the [statuses](/apis/txbuilder/plans#read-the-statuses) show `final`; [`replan()`](/apis/txbuilder/plans#handle-a-step-that-does-not-go-through) pays what is left after a step that did not land; on a server, keep plans [in a store](/apis/txbuilder/servers#record-plans-in-a-store). 6. Around the flow: a [transaction from elsewhere](/apis/txbuilder/offline#read-a-transaction-built-elsewhere) (`fromCbor` and `restore` give a `BuiltTx`; `requiredSigners` lists its keys), [tests](/apis/txbuilder/testing), [errors](/apis/txbuilder/errors#check-a-code) (`TxError.is`), [options](/apis/txbuilder/options), and [coming from `MeshTxBuilder`](/apis/txbuilder/migration). @@ -62,7 +62,8 @@ You make one builder; each `build()` or `plan()` call takes the parts and `{ pay | `mint.native`, `mint.plutus` | mint and burn assets | | `spend.pubKey`, `collateral`, `collateralReturn` | spend a particular output, set the collateral | | `spend.plutus`, `spend.native`, `referenceInput` | lock and spend at a script, read an output | -| `certificate.*`, `withdrawal.*` | stake, delegate and withdraw rewards | +| `withdrawal.*` | take staking rewards out | +| `certificate.*` | change what the chain records: stake keys, delegation of stake and votes, pools, DReps, the committee | | `vote`, `proposal.*` | take part in governance | For signing, UTxOs, time, plans, offline use, testing and errors, see the cards below. diff --git a/content/docs/apis/txbuilder/meta.json b/content/docs/apis/txbuilder/meta.json index 1cf8355..954ab0f 100644 --- a/content/docs/apis/txbuilder/meta.json +++ b/content/docs/apis/txbuilder/meta.json @@ -13,8 +13,8 @@ "minting", "smart-contracts", "staking", - "governance", "certificates", + "governance", "---Environments---", "offline", "testing", diff --git a/data/links-txbuilders.ts b/data/links-txbuilders.ts index c05754b..77741bd 100644 --- a/data/links-txbuilders.ts +++ b/data/links-txbuilders.ts @@ -94,8 +94,8 @@ export const linksTxbuilder = [ metaTxbuilderMinting, metaTxbuilderSmartContract, metaTxbuilderStaking, - metaTxbuilderGovernance, metaTxbuilderCertificates, + metaTxbuilderGovernance, metaTxbuilderPlans, metaTxbuilderServers, metaTxbuilderOffline, From 8960da051d71b3fc53d80699bd14b240c1f491ef Mon Sep 17 00:00:00 2001 From: lisicky Date: Sun, 22 Nov 2026 23:03:43 +0100 Subject: [PATCH 11/15] docs: diagram text on one baseline --- components/txbuilder/builder-flow.tsx | 332 ++++++++++++++------- components/txbuilder/plan-status-graph.tsx | 18 +- 2 files changed, 227 insertions(+), 123 deletions(-) diff --git a/components/txbuilder/builder-flow.tsx b/components/txbuilder/builder-flow.tsx index b290310..5588e7b 100644 --- a/components/txbuilder/builder-flow.tsx +++ b/components/txbuilder/builder-flow.tsx @@ -7,18 +7,37 @@ // for a column under 600px, so a phone never has to scroll the scheme sideways. import Link from "next/link"; +import { useLayoutEffect, useRef, useState } from "react"; const B = "/apis/txbuilder"; const GAP = 4; // distance between the two borders of a terminal box const TIP = 4; // the arrowhead tip lies this far beyond the end of its line const END = 2 + TIP; // a line ends this far before the box it points at: air plus the arrowhead +// Another path has a smaller head (7 long). Its colour is translucent in the dark theme, so the +// line stops where the head begins (they overlap by LAP, so no seam shows) instead of running +// under it: laid twice, the colour would show as a brighter patch inside the head. +const HEAD_THIN = 7; +const LAP = 0.5; +const END_THIN = 2 + HEAD_THIN - LAP; const LINK = "group/link cursor-pointer outline-none"; // the focus ring is drawn by Ring const BOX = "fill-fd-card stroke-fd-muted-foreground group-hover/link:fill-fd-accent group-hover/link:stroke-fd-foreground"; const WIDE_ARROW = "bf-arrow-wide"; const NARROW_ARROW = "bf-arrow-narrow"; +// Every text sits on the alphabetic baseline, never on dominant-baseline "central": WebKit works +// "central" out for each font, Chrome for each text element, so a line that mixes prose and code +// came out with its pieces at different heights. The y of a text names the middle of its line; +// the baseline lies 0.35em below it, in every engine. +const BASELINE = 0.35; +const lineBase = (mid: number, fs: number) => mid + BASELINE * fs; +const CAP = 15; // size of a caption and of the title of a box; the texts on its row share its baseline + +// Boxes 1 and 2 stand on one row grid, in both layouts: the title, row 1, row 2 and the link +// row are at the same height in both boxes. +const ROW = { title: 28, one: 58, two: 86, link: 114 }; + // ---------------------------------------------------------------- content, shared by both layouts type Part = { href: string; title: string; name: string; code: string[] }; @@ -140,26 +159,47 @@ const LABEL = // ---------------------------------------------------------------- drawing pieces -function Arrowhead({ id }: { id: string }) { - // refX 6 of 10: the line ends under the head, the tip lies TIP beyond the end of the line +function Arrowhead({ id, thin = false }: { id: string; thin?: boolean }) { + // The head of the usual path is 10 long and the line ends under it, the tip TIP beyond the + // end of the line. The head of another path is HEAD_THIN long and starts where its line ends. + // Each head has the colour of its line. + const size = thin ? HEAD_THIN : 10; return ( - - + + ); } +const thinId = (marker: string) => `${marker}-thin`; // the id of the smaller head of another path + function Edge({ d, marker, main = false }: { d: string; marker: string; main?: boolean }) { - // main: the usual path, a heavier line - return ; + // main: the usual path, a thick line in the text colour. Another path: a thin line in the + // muted colour of the captions, with a smaller head of the same colour. No dashes: in the + // status graphs a dashed line means what the chain shows. + return main ? ( + + ) : ( + + ); } // Lines that stop short of the box they point at. -const hLine = (from: number, to: number, y: number) => `M ${from + 2} ${y} H ${to - END}`; -const vLine = (x: number, from: number, to: number) => `M ${x} ${from + 2} V ${to - END}`; +// `end` is END, or END_THIN for another path. +const hLine = (from: number, to: number, y: number, end = END) => `M ${from + 2} ${y} H ${to - end}`; +const vLine = (x: number, from: number, to: number, end = END) => `M ${x} ${from + 2} V ${to - end}`; // From a vertical spine, round the corner and go right to a box. -const elbow = (spine: number, y0: number, cy: number, boxX: number) => - `M ${spine} ${y0} V ${cy - 12} Q ${spine} ${cy} ${spine + 12} ${cy} H ${boxX - END}`; +const elbow = (spine: number, y0: number, cy: number, boxX: number, end = END) => + `M ${spine} ${y0} V ${cy - 12} Q ${spine} ${cy} ${spine + 12} ${cy} H ${boxX - end}`; // The focus ring: drawn only for keyboard focus, so it shows in every browser. function Ring({ x, y, w, h, r = 6 }: { x: number; y: number; w: number; h: number; r?: number }) { @@ -176,6 +216,78 @@ function Ring({ x, y, w, h, r = 6 }: { x: number; y: number; w: number; h: numbe ); } +// The name of a link, underlined by a line of our own instead of text-decoration: Chrome breaks +// the decoration of SVG text beside every descender and ignores text-decoration-skip-ink there, +// and each engine puts it at another depth, so one name was underlined in three ways. The line +// is as long as the text (measured in the browser, again when the svg is shown or resized and +// when the fonts arrive), lies UNDERLINE of the font size below the baseline, and spans all the +// tspans of the name. Until it is measured (the server render, an svg that is hidden) the name +// carries the CSS underline, so it is never bare. `y` is the baseline. +const UNDERLINE = 0.25; +function LinkName({ + x, + y, + anchor = "start", + fontSize, + hover = false, + className, + children, +}: { + x: number; + y: number; + anchor?: "start" | "middle" | "end"; + fontSize: number; + hover?: boolean; // the line turns muted with the text, as the link is hovered + className: string; + children: React.ReactNode; +}) { + const ref = useRef(null); + const [span, setSpan] = useState<[number, number] | null>(null); + useLayoutEffect(() => { + const el = ref.current; + if (!el) return; + let alive = true; + const measure = () => { + if (!alive) return; + let next: [number, number] | null = null; + try { + const b = el.getBBox(); // zero while the svg is not displayed + if (b.width > 0) next = [b.x, b.x + b.width]; + } catch { + // an engine that cannot measure a hidden text: the CSS underline stays + } + setSpan((prev) => (prev && next && prev[0] === next[0] && prev[1] === next[1] ? prev : next)); + }; + measure(); + const svg = el.ownerSVGElement; + const observer = svg && typeof ResizeObserver !== "undefined" ? new ResizeObserver(measure) : null; + if (svg) observer?.observe(svg); + document.fonts?.ready.then(measure); + return () => { + alive = false; + observer?.disconnect(); + }; + }, [x, y, anchor, fontSize]); + const ly = y + UNDERLINE * fontSize; + return ( + <> + + {children} + + {span && ( + + )} + + ); +} + // A link made of one line of words. `width` is the width of the text (measured in the // browser), used for the focus ring and the hover area. function TextLink({ @@ -186,6 +298,7 @@ function TextLink({ width, anchor = "start", fontSize = 13, + lineFs, semibold = false, children, }: { @@ -196,6 +309,7 @@ function TextLink({ width: number; anchor?: "start" | "end"; fontSize?: number; + lineFs?: number; // the size of the biggest text on this row: its baseline is the baseline of the row semibold?: boolean; children: React.ReactNode; }) { @@ -205,16 +319,16 @@ function TextLink({ {title} - {children} - + ); } @@ -267,12 +381,12 @@ function NodeLink({ /> )} {names.map((line, i) => ( - + {line} - + ))} {codes.map((line, i) => ( - + {line} ))} @@ -300,11 +414,12 @@ function RowLink({ step, x, y, w, h }: { step: Step; x: number; y: number; w: nu className="fill-none stroke-fd-muted-foreground group-hover/link:stroke-fd-foreground" /> )} - + {/* the name and the code are one row: they stand on one baseline */} + {step.name} - + {step.code && ( - + {step.code} )} @@ -318,22 +433,23 @@ function Badge({ cx, cy, n }: { cx: number; cy: number; n: number }) { return ( - + {n} ); } -function Legend({ x, y, marker }: { x: number; y: number; marker: string }) { +// The two kinds of path, drawn as in the scheme. The arrows are at the middle of the row, the words stand on its baseline. +function Legend({ x, y, marker, lineFs = 13 }: { x: number; y: number; marker: string; lineFs?: number }) { return ( - + usual path - + another path @@ -342,15 +458,15 @@ function Legend({ x, y, marker }: { x: number; y: number; marker: string }) { function Caption({ x, y, children }: { x: number; y: number; children: React.ReactNode }) { return ( - + {children} ); } -function Sub({ x, y, children }: { x: number; y: number; children: React.ReactNode }) { +function Sub({ x, y, lineFs = 13, children }: { x: number; y: number; lineFs?: number; children: React.ReactNode }) { return ( - + {children} ); @@ -379,6 +495,56 @@ function Frame({ children, note }: { children: React.ReactNode; note: string }) ); } +// ---------------------------------------------------------------- boxes 1 and 2, the same in both layouts + +type Place = { x: number; y: number; w: number; h: number }; + +// 1: create a builder +function CreateBox({ x, y, w, h }: Place) { + return ( + + Create a builder + + + + Create a builder + + + new TxBuilder({"{"} network, provider {"}"}) + + + Networks and providers + + + Offline, no provider: params, costModels + + + ); +} + +// 2: who pays +function PayerBox({ x, y, w, h }: Place) { + return ( + + Who pays + + + + Who pays + + + {"{ payer }"} of each call: a wallet, an address, + + + or your own {"{ changeAddress, utxos }"} + + + Signers and submitter + + + ); +} + // ---------------------------------------------------------------- the wide layout function WideScheme() { @@ -407,7 +573,7 @@ function WideScheme() { ]; const last = col.length - 2; const arrowsA = col.slice(0, -1).map((c, i) => hLine(c.x + c.w, col[i + 1].x, laneA.cy)); - const arrowsB = col.slice(0, -1).map((c, i) => hLine(c.x + c.w, col[i + 1].x - (i === last ? GAP : 0), laneB.cy)); + const arrowsB = col.slice(0, -1).map((c, i) => hLine(c.x + c.w, col[i + 1].x - (i === last ? GAP : 0), laneB.cy, END_THIN)); return ( Working with TxBuilder + {/* arrows first, so the boxes sit on top of their ends */} {/* from the parts to the two lanes */} - + {arrowsA.map((d) => ( @@ -434,43 +601,9 @@ function WideScheme() { ))} - {/* 1: create a builder */} - - Create a builder - - - - Create a builder - - - new TxBuilder({"{"} network, provider {"}"}) - - - Networks and providers - - - Offline, no provider: params, costModels - - - - {/* 2: who pays */} - - Who pays - - - - Who pays - - - {"{ payer }"} of each call: a wallet, an address, - - - or your own {"{ changeAddress, utxos }"} - - - Signers and submitter - - + {/* 1: create a builder, 2: who pays */} + + {/* 3: the parts */} @@ -478,10 +611,10 @@ function WideScheme() { Parts - + one part or a list; the builder picks inputs, adds change and sets the fee - + Which part for what {PARTS.map((c, i) => ( @@ -504,10 +637,10 @@ function WideScheme() { One transaction - + build, sign and send; you follow the outcome - + {ONE_TX.map((s, i) => ( ))} @@ -517,10 +650,10 @@ function WideScheme() { Or a plan - + one or several transactions, sent in order, never rebuilt - + Needs a provider with block heights {A_PLAN.map((s, i) => ( @@ -548,7 +681,7 @@ function WideScheme() { {/* 6: around the flow */} - + Around the flow {AROUND.map((a, i) => ( @@ -591,7 +724,7 @@ function NarrowScheme() { const H = rowsC[2] + heights[2] + 16; const arrowsA = ONE_TX.slice(0, -1).map((_, i) => vLine(bx + bw / 2, rowY(yA, i) + RH, rowY(yA, i + 1))); - const arrowsB = A_PLAN.slice(0, -1).map((_, i) => vLine(bx + bw / 2, rowY(yB, i) + RH, rowY(yB, i + 1) - (i === 3 ? GAP : 0))); + const arrowsB = A_PLAN.slice(0, -1).map((_, i) => vLine(bx + bw / 2, rowY(yB, i) + RH, rowY(yB, i + 1) - (i === 3 ? GAP : 0), END_THIN)); const chipX = (i: number) => 19 + (i % 3) * 116; const chipY = (i: number) => yParts + 88 + Math.floor(i / 3) * 72; @@ -605,12 +738,13 @@ function NarrowScheme() { Working with TxBuilder + {/* arrows first, so the boxes sit on top of their ends */} - + {arrowsA.map((d) => ( @@ -619,43 +753,9 @@ function NarrowScheme() { ))} - {/* 1: create a builder */} - - Create a builder - - - - Create a builder - - - new TxBuilder({"{"} network, provider {"}"}) - - - Networks and providers - - - Offline, no provider: params, costModels - - - - {/* 2: who pays */} - - Who pays - - - - Who pays - - - {"{ payer }"} of each call: a wallet, an address, - - - or your own {"{ changeAddress, utxos }"} - - - Signers and submitter - - + {/* 1: create a builder, 2: who pays */} + + {/* 3: the parts */} @@ -663,7 +763,7 @@ function NarrowScheme() { Parts - + Which part for what @@ -715,7 +815,7 @@ function NarrowScheme() { {/* 6: around the flow */} - + Around the flow {AROUND.map((a, i) => { diff --git a/components/txbuilder/plan-status-graph.tsx b/components/txbuilder/plan-status-graph.tsx index dc1cead..a712330 100644 --- a/components/txbuilder/plan-status-graph.tsx +++ b/components/txbuilder/plan-status-graph.tsx @@ -11,6 +11,11 @@ const BOX_W = 88; const BOX_H = 36; const GAP = 4; // distance between the two borders of a terminal status +// Every text sits on the alphabetic baseline, never on dominant-baseline "central": WebKit +// and Chrome work "central" out differently, so the same label stood at different heights. +// The y of a text names the middle of its line; the baseline lies 0.35em below it. +const lineBase = (mid: number, fs: number) => mid + 0.35 * fs; + function Arrowhead({ id }: { id: string }) { return ( @@ -153,11 +157,11 @@ function Legend({ return ( - + a call - + what the chain shows - + never changes @@ -252,7 +256,7 @@ export function StepStatusGraph() {