diff --git a/components/txbuilder/builder-flow.tsx b/components/txbuilder/builder-flow.tsx new file mode 100644 index 0000000..5588e7b --- /dev/null +++ b/components/txbuilder/builder-flow.tsx @@ -0,0 +1,853 @@ +"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"; +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[] }; +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: 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.*"] }, +]; + +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, 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 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. +// `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, 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 }) { + return ( + + ); +} + +// 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({ + href, + title, + x, + y, + width, + anchor = "start", + fontSize = 13, + lineFs, + semibold = false, + children, +}: { + href: string; + title: string; + x: number; + y: number; // the middle line of the text + 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; +}) { + 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 && ( + + )} + {/* the name and the code are one row: they stand on one baseline */} + + {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} + + + ); +} + +// 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 + + + ); +} + +function Caption({ x, y, children }: { x: number; y: number; children: React.ReactNode }) { + return ( + + {children} + + ); +} + +function Sub({ x, y, lineFs = 13, children }: { x: number; y: number; lineFs?: 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}

+
+ ); +} + +// ---------------------------------------------------------------- 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() { + 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: 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: 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 }, + { 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, 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) => ( + + ))} + {arrowsB.map((d) => ( + + ))} + + {/* 1: create a builder, 2: who pays */} + + + + {/* 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), END_THIN)); + 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, 2: who pays */} + + + + {/* 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/components/txbuilder/plan-status-graph.tsx b/components/txbuilder/plan-status-graph.tsx new file mode 100644 index 0000000..a712330 --- /dev/null +++ b/components/txbuilder/plan-status-graph.tsx @@ -0,0 +1,387 @@ +// 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 + +// 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 ( + + + + ); +} + +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/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 "); -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, and your own UTxOs as the payer: see [Offline and CBOR](/apis/txbuilder/offline). Every option is in [Options](/apis/txbuilder/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 | +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 -); -``` - -| 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: +import { output } from "@meshsdk/core"; -```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 }, +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 ], -}; - -// 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); + { payer: wallet }, +); ``` -## Transaction Metadata +## Build, Sign and Submit -### Add Messages - -Attach messages to transactions using label 674 (CIP-20): +`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 - .txOut(recipientAddress, [{ unit: "lovelace", quantity: "5000000" }]) - .metadataValue(674, { - msg: [ - "Invoice-No: 1234567890", - "Customer-No: 555-1234" - ] - }) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos) - .complete(); -``` +import { output } from "@meshsdk/core"; -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(); +const built = await builder.build( + output({ address: recipient, value: { lovelace: 5_000_000n } }), + { payer: wallet }, +); +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 ``` -## Transaction Validity +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. -### Set Expiration (TTL) +To sign with a private key, with your own code or with several signers, see [Signing and Submitting](/apis/txbuilder/signing). -Make a transaction invalid after a specific slot: +## Add More to a Transaction -```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 +Add these parts to the list you give to `build()`. -Make a transaction invalid before a specific slot: +### Choose Inputs -```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(); -``` +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). -## 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"; +import { message, metadata, output } from "@meshsdk/core"; -const { pubKeyHash } = deserializeAddress(walletAddress); - -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 the Validity -### Set Network +`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). -Configure the network for proper cost model calculation: +### Require a Signer -```tsx -txBuilder.setNetwork("mainnet"); // or "testnet", "preview", "preprod" -``` - -### Custom Protocol Parameters - -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 +## Plan Several Transactions -Override automatic fee calculation: +`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). -```tsx -const unsignedTx = await txBuilder - .txOut(address, amount) - .changeAddress(changeAddress) - .setFee("200000") // Set exact fee in lovelace - .complete(); -``` +> **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). -## Build with JSON +## Handle Errors -Alternative method using a JSON object: +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 { 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, TxError } from "@meshsdk/core"; -## Complete Example +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 + }); -```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}`); +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; +} ``` -## 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 +- [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/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/cookbook/index.mdx b/content/docs/apis/txbuilder/cookbook/index.mdx new file mode 100644 index 0000000..85de972 --- /dev/null +++ b/content/docs/apis/txbuilder/cookbook/index.mdx @@ -0,0 +1,74 @@ +--- +title: "Cookbook" +description: "Complete TxBuilder recipes to copy: payments, tokens, scripts, shared signing, servers, staking, governance and tests." +--- + +## Overview + +Each recipe is one complete example for one job, where the task pages explain one part at a time. Recipes take the safe path: a transaction is built once and a retry is the same call on the same object, a transaction from another party is read before you sign it, and transactions that depend on each other go through a plan, or are chained with `after`. A plan is not atomic: a step may land while the next never does, so read the status of each step. + +## Before you start + +Recipes use the names below, and a builder made like this: + +```tsx +import { TxBuilder } from "@meshsdk/core"; + +const builder = new TxBuilder({ network: "preprod", provider }); +``` + +`plan()` needs a provider that returns block heights and the validity flag. The plain `BlockfrostProvider` does not, and `plan()` throws `CANNOT_OBSERVE`: see [Use Blockfrost for Plans](/apis/txbuilder/networks#use-blockfrost-for-plans). `run()` returns when the transaction is in a block. Add `{ waitFor: "final" }` before you release goods or ship an order: see [Read the Statuses](/apis/txbuilder/plans#read-the-statuses). + +| Name | What it is | +|------|------------| +| `builder`, `provider` | the builder above, and the provider it reads through | +| `wallet`, `partnerWallet` | the `MeshWallet` that pays, and the wallet of the other party | +| `changeAddress`, `recipient`, `partner` | addresses: the wallet's own, a payee, the other party's | +| `unit` | a policy id plus an asset name in hex | +| `script` | a Plutus script, `{ code, version }` | +| `store`, `db` | a plan store, and your own list of open payouts: see [Server Recipes](/apis/txbuilder/cookbook/servers) | +| `validator`, `words` | the emulator's `TxValidator`, and a test wallet's mnemonic: see [Test Recipes](/apis/txbuilder/cookbook/testing) | + +## Payments + +- [Pay from a Browser Wallet](/apis/txbuilder/cookbook/payments#pay-from-a-browser-wallet) - a user signs in a CIP-30 wallet, and a closed window changes nothing +- [Pay Many Recipients](/apis/txbuilder/cookbook/payments#pay-many-recipients) - a payroll cut into batches, as the steps of one plan +- [Send a Whole Wallet to a New Address](/apis/txbuilder/cookbook/payments#send-a-whole-wallet-to-a-new-address) - ada and tokens, less the fee, in one transaction +- [Chain Payments Without Waiting](/apis/txbuilder/cookbook/payments#chain-payments-without-waiting) - build each payment on the one before and send them in a row +- [Make an Offer That Expires](/apis/txbuilder/cookbook/payments#make-an-offer-that-expires) - sign a payment the recipient may send until its deadline + +## Tokens and NFTs + +- [Mint an NFT Collection](/apis/txbuilder/cookbook/tokens#mint-an-nft-collection) - CIP-25 metadata under a native policy that closes +- [Mint a CIP-68 Token](/apis/txbuilder/cookbook/tokens#mint-a-cip-68-token) - a reference token that holds the metadata, and a user token +- [Burn Tokens](/apis/txbuilder/cookbook/tokens#burn-tokens) - a negative quantity under the policy that minted them + +## Scripts + +- [Vest Funds and Claim Them Later](/apis/txbuilder/cookbook/scripts#vest-funds-and-claim-them-later) - lock funds until a deadline, then unlock them +- [Hold a Payment in Escrow](/apis/txbuilder/cookbook/scripts#hold-a-payment-in-escrow) - lock funds under a datum and spend them with a redeemer +- [Deploy a Script Once and Use It by Reference](/apis/txbuilder/cookbook/scripts#deploy-a-script-once-and-use-it-by-reference) - store a script in an output and name it instead of sending its code + +## Several Parties + +- [Share a Wallet with a Native Script](/apis/txbuilder/cookbook/parties#share-a-wallet-with-a-native-script) - funds that two keys control +- [Check a Partner's Swap Before You Sign](/apis/txbuilder/cookbook/parties#check-a-partners-swap-before-you-sign) - read a partner's transaction and sign it only if it is the deal +- [Build Online, Sign on a Cold Machine](/apis/txbuilder/cookbook/parties#build-online-sign-on-a-cold-machine) - build online and sign where the key lives + +## Server Recipes + +- [Take a Payment on a Server](/apis/txbuilder/cookbook/servers#take-a-payment-on-a-server) - build for a user, collect the signature and send +- [Finish Payouts After a Restart](/apis/txbuilder/cookbook/servers#finish-payouts-after-a-restart) - a pass that finds every open payout and finishes it + +## Staking and Governance + +- [Register and Delegate in One Transaction](/apis/txbuilder/cookbook/staking-governance#register-and-delegate-in-one-transaction) - a stake key registered, delegated to a pool and its vote delegated +- [Withdraw All Rewards](/apis/txbuilder/cookbook/staking-governance#withdraw-all-rewards) - take out the whole reward balance +- [Stop Staking and Take the Deposit Back](/apis/txbuilder/cookbook/staking-governance#stop-staking-and-take-the-deposit-back) - deregister a stake key and withdraw its rewards in one transaction +- [Become a DRep and Vote](/apis/txbuilder/cookbook/staking-governance#become-a-drep-and-vote) - register a DRep and cast a vote + +## Test Recipes + +- [Test a Payment Plan on the Emulator](/apis/txbuilder/cookbook/testing#test-a-payment-plan-on-the-emulator) - a plan run to final, and the balances +- [Test That a Payout Finishes After a Restart](/apis/txbuilder/cookbook/testing#test-that-a-payout-finishes-after-a-restart) - drop the builder after a send, resume the plan on a new one, and pay once +- [Test an Expected Error](/apis/txbuilder/cookbook/testing#test-an-expected-error) - check the code of a refused build diff --git a/content/docs/apis/txbuilder/cookbook/meta.json b/content/docs/apis/txbuilder/cookbook/meta.json new file mode 100644 index 0000000..8beb04f --- /dev/null +++ b/content/docs/apis/txbuilder/cookbook/meta.json @@ -0,0 +1,12 @@ +{ + "title": "Cookbook", + "pages": [ + "payments", + "tokens", + "scripts", + "parties", + "servers", + "staking-governance", + "testing" + ] +} diff --git a/content/docs/apis/txbuilder/cookbook/parties.mdx b/content/docs/apis/txbuilder/cookbook/parties.mdx new file mode 100644 index 0000000..e7ce97c --- /dev/null +++ b/content/docs/apis/txbuilder/cookbook/parties.mdx @@ -0,0 +1,175 @@ +--- +title: "Several Parties" +description: "Share a wallet with a native script, check a swap another party built before you sign it, and sign on a cold machine." +--- + +## Overview + +Three recipes for transactions that more than one party touches: a wallet two keys share, a swap you check before you sign, and a key that signs on a cold machine. Whenever a transaction comes from someone else, you read it before you sign it. Names as in [Before you start](/apis/txbuilder/cookbook#before-you-start), plus `sharedUtxo`, `partnerTx`, `coldAddress`, `coldKey` and `coldTx`. + +## Share a Wallet with a Native Script + +Use this for funds that need two keys, such as a joint account: one party builds the spend and signs its part, and the other checks it, signs and sends it. `partnerWallet` is the other party's wallet, `partner` its address, and `sharedUtxo` an output at the shared address. + +```tsx +import { deserializeAddress, guard, output, spend } from "@meshsdk/core"; +import type { NativeScript } from "@meshsdk/core"; + +const keyOf = (address: string) => deserializeAddress(address).pubKeyHash; +// 2 of 2: both keys must sign. For 2 of 3, use { type: "atLeast", required: 2, scripts } +const shared: NativeScript = { + type: "all", + scripts: [ + { type: "sig", keyHash: keyOf(changeAddress) }, + { type: "sig", keyHash: keyOf(partner) }, + ], +}; +const sharedAddress = builder.scriptAddress(shared); + +// Party one builds the spend and signs its part +const built = await builder.build( + [ + spend.native({ utxo: sharedUtxo, script: shared }), + output({ address: recipient, value: { lovelace: 20_000_000n } }), + guard.pubKey({ address: partner }), // so that `missing` lists the other key + ], + { payer: sharedAddress }, // the change goes back to the shared address +); +await built.sign({ signers: wallet }); +const forPartner = built.partialTx; // any channel carries it + +// Party two reads it and signs only the agreed spend +const received = await builder.fromCbor(forPartner); // its inputs come from the provider +const sum = (list: { address: string; value: Record }[]) => { + const total = new Map(); + for (const { address, value } of list) + if (address === sharedAddress) + for (const [name, quantity] of Object.entries(value)) + total.set(name, (total.get(name) ?? 0n) + quantity); + return total; +}; +const [taken, back] = [sum(received.inputs), sum(received.outputs)]; +const lost = (name: string) => (taken.get(name) ?? 0n) - (back.get(name) ?? 0n); +const agreed = + // nothing goes elsewhere + received.outputs.every( + ({ address }) => address === sharedAddress || address === recipient, + ) && + lost("lovelace") <= 21_000_000n && // the 20 ada, and at most 1 ada of fee + // no token leaves + [...taken.keys()].every((name) => name === "lovelace" || lost(name) <= 0n) && + received.collateral === undefined && // no script runs, so nothing is forfeited + received.missing.every(({ keyHash }) => keyHash === keyOf(partner)); // only your key is left +if (!agreed) throw new Error("not the agreed spend: do not sign"); + +await received.sign({ signers: partnerWallet }); +await received.submit(); +await received.awaitInclusion(); +``` + +- In a 2-of-2 account the second signature is the only control, so party two checks where the funds go and what they cost before signing: see [Read a Transaction Built Elsewhere](/apis/txbuilder/offline#read-a-transaction-built-elsewhere). +- `missing` never lists a native script's keys: the script decides. `guard.pubKey` names the other party, so `missing` lists its key and `submit()` refuses until it has signed: see [Sign in Turns](/apis/txbuilder/signing#sign-in-turns). +- `spend.native` needs no redeemer and no collateral. For 2 of 3, guard the partner you agreed to sign with: see [Spend from a Native Script](/apis/txbuilder/smart-contracts#spend-from-a-native-script). + +## Check a Partner's Swap Before You Sign + +Use this when a partner builds a transaction and you only sign it: you read what it takes from you and gives to you, and sign only when it is the deal. `partnerTx` is the partner's transaction as CBOR hex, and `unit` the token you are to receive for at most 20 ada. + +```tsx +import { deserializeAddress } from "@meshsdk/core"; + +const mine = deserializeAddress(changeAddress).pubKeyHash; +const received = await builder.fromCbor(partnerTx); // its inputs come from your provider + +// What the transaction gives to your key, less what it takes from it, per unit. +// Every address of your key counts, not only the change address +const ours = ({ address }: { address: string }) => { + try { + return deserializeAddress(address).pubKeyHash === mine; + } catch { + return false; // not a key address + } +}; +const net = new Map(); +const count = ( + list: { address: string; value: Record }[], + sign: bigint, +) => { + for (const { value } of list.filter(ours)) + for (const [name, quantity] of Object.entries(value)) + net.set(name, (net.get(name) ?? 0n) + sign * quantity); +}; +count(received.outputs, 1n); +count(received.inputs, -1n); + +const agreed = + net.get(unit) === 1n && // 1: you receive the token + (net.get("lovelace") ?? 0n) >= -20_000_000n && // 2: and give at most 20 ada + [...net].every(([name, n]) => name === "lovelace" || n >= 0n) && // 3: no other token leaves + received.missing.every(({ keyHash }) => keyHash === mine) && // 4: only your key is left + received.collateral === undefined && // 5: no script runs, so nothing is forfeited + received.warnings.length === 0; // 6: nothing unusual +if (!agreed) throw new Error("not the agreed swap: do not sign"); + +await received.sign({ signers: wallet }); // a transaction read from CBOR has no payer +await received.submit(); +await received.awaitInclusion(); +``` + +- `fromCbor` builds nothing, so you sign the body byte for byte. The check counts every unit at every address of your key, so a swap that takes a token, or spends an output at another address of your key, fails it: see [Read a Transaction Built Elsewhere](/apis/txbuilder/offline#read-a-transaction-built-elsewhere). +- Its inputs come from your provider. With `knownUtxos` give only your own data, never what the partner says: see [Name Outputs the Provider Does Not Know](/apis/txbuilder/utxos#name-outputs-the-provider-does-not-know). +- To send it with a payment of your own, make it a step of a plan: `builder.plan({ swap: received, pay }, { payer: wallet })`. See [Use a Transaction Built Elsewhere](/apis/txbuilder/plans#use-a-transaction-built-elsewhere). + +## Build Online, Sign on a Cold Machine + +Use this when the key lives on a machine with no network: the online machine builds, the cold machine reads and signs, and the signed transaction comes back to be sent. `coldAddress` is the address the cold key controls, and `coldKey` is that key, which never leaves the cold machine. + +```tsx +import { keySigner, output, toMeshUtxo, TxBuilder } from "@meshsdk/core"; + +// On the online machine: build with the cold address as the payer. Nothing is signed +const built = await builder.build( + output({ address: recipient, value: { lovelace: 5_000_000n } }), + { payer: coldAddress }, +); +const named = [ + ...built.inputs, + ...built.referenceInputs, + ...(built.collateral?.inputs ?? []), +]; +const toCold = JSON.stringify({ tx: built.tx, utxos: named.map(toMeshUtxo) }); + +// On the cold machine: no provider, no parameters, only the network +const sent = JSON.parse(toCold); +const cold = new TxBuilder({ network: "preprod" }); +const received = await cold.fromCbor(sent.tx, { knownUtxos: sent.utxos }); +console.log(received.outputs, received.fee, received.missing); // read what you sign +await received.sign({ signers: keySigner(coldKey) }); +const signed = received.partialTx; // carry it back + +// Back on the online machine +await built.addWitnesses(signed); +await built.submit(); +await built.awaitInclusion(); +``` + +- The cold builder needs its network alone. With no provider, `knownUtxos` must hold every UTxO the transaction names: see [With Mesh on the Cold Machine](/apis/txbuilder/signing#with-mesh-on-the-cold-machine). +- The key signs the body whatever you were told: read `outputs`, `fee` and `missing` first: see [Read a Transaction Built Elsewhere](/apis/txbuilder/offline#read-a-transaction-built-elsewhere). +- For the JSON of the build, a signing device, or a machine with no builder, see [Sign on a Cold Machine](/apis/txbuilder/signing#sign-on-a-cold-machine). + +If the cold machine gets only the transaction, `coldTx` (`built.tx`), it can sign without looking. It shows `outputs` and `fee` and nothing of the inputs, and it keeps every witness that verifies, so a key the fee was not priced for can make the node refuse the transaction: see [Sign Without Looking](/apis/txbuilder/signing#sign-without-looking). + +```tsx +import { keySigner, TxBuilder } from "@meshsdk/core"; + +const cold = new TxBuilder({ network: "preprod" }); +const unseen = await cold.fromCbor(coldTx, { blind: true }); // no UTxOs, no provider +await unseen.sign({ signers: keySigner(coldKey) }); +const signed = unseen.partialTx; // carry it back: built.addWitnesses(signed) +``` + +## Related + +- [Signing and Submitting](/apis/txbuilder/signing) - signers, signing in turns and the cold machine +- [Offline and CBOR](/apis/txbuilder/offline) - read a transaction built elsewhere, save and restore +- [Smart Contracts](/apis/txbuilder/smart-contracts) - spend from a native script diff --git a/content/docs/apis/txbuilder/cookbook/payments.mdx b/content/docs/apis/txbuilder/cookbook/payments.mdx new file mode 100644 index 0000000..d4384d3 --- /dev/null +++ b/content/docs/apis/txbuilder/cookbook/payments.mdx @@ -0,0 +1,148 @@ +--- +title: "Payments" +description: "Pay from a browser wallet, pay many recipients, send a whole wallet, chain payments and make an offer that expires." +--- + +## Overview + +Five payment recipes: a browser wallet pays, a payroll goes out in batches, a whole wallet moves to a new address, payments are chained without waiting, and an offer expires. Names as in [Before you start](/apis/txbuilder/cookbook#before-you-start), plus `payouts` and `newAddress`. + +## Pay from a Browser Wallet + +Use this when a user connects a CIP-30 wallet in your dApp and pays. The plan is built first, so a closed wallet window changes nothing. + +```tsx +import { BrowserWallet, output, TxError } from "@meshsdk/core"; + +const wallet = await BrowserWallet.enable("eternl"); // the wallet the user picked +const plan = await builder.plan( + output({ address: recipient, value: { lovelace: 5_000_000n } }), + { payer: wallet }, +); // built; nothing is signed or sent + +try { + await plan.run({ submitter: wallet }); // the wallet asks the user, then sends + console.log(plan.step("main").txHash, plan.status); +} catch (error) { + if (!TxError.is(error, "SIGN_DECLINED")) throw error; + // the user said no and nothing was sent: call run() again to ask once more, or plan.stop() +} +``` + +- A refusal is `SIGN_DECLINED` and changes nothing, so the same transaction can be asked for again: see [When a Signer Refuses](/apis/txbuilder/signing#when-a-signer-refuses). +- `submitter: wallet` sends through the wallet. Leave it out and the provider sends: see [Use a Browser Wallet](/apis/txbuilder/signing#use-a-browser-wallet). + +## Pay Many Recipients + +Use this for a payroll or any list of payouts: a transaction holds a limited number of outputs, so the list is cut into batches, each a step of one plan. `payouts` is your list, each `{ address, lovelace }`. + +```tsx +import { output } from "@meshsdk/core"; + +const size = 100; // outputs in one transaction +const steps: Record[]> = {}; +for (let i = 0; i < payouts.length; i += size) { + steps[`batch-${i / size + 1}`] = payouts + .slice(i, i + size) + .map(({ address, lovelace }) => output({ address, value: { lovelace } })); +} +const plan = await builder.plan(steps, { + payer: wallet, + ttlMs: (Object.keys(steps).length + 10) * 60_000, // one deadline for every batch +}); +console.log(plan.steps.length, plan.fee); // the batches, and the fees of all + +await plan.run(); // a batch, a block, the next batch +for (const step of plan.steps) console.log(step.name, step.status); +``` + +- A step is sent when the one before it is in a block, and it spends that step's change: see [Send Several Transactions](/apis/txbuilder/plans#send-several-transactions). +- A plan is not atomic. If a batch does not land, `plan.landed` lists the batches that did, and `plan.replan({ id })` pays only what is left: see [Handle a Step That Does Not Go Through](/apis/txbuilder/plans#handle-a-step-that-does-not-go-through). +- A plan has at most 32 steps, and its steps share one deadline, so give `ttlMs` a minute for each batch. For a longer list, make several plans one after the other: see [Set Deadlines and Waiting](/apis/txbuilder/plans#set-deadlines-and-waiting). + +## Send a Whole Wallet to a New Address + +Use this to move everything a wallet holds, ada and tokens, to `newAddress`, such as a new wallet. The fee comes out of the total, and an output that holds a deployed script stays where it is. + +```tsx +const plan = await builder.plan([], { + payer: wallet, + sendAllTo: newAddress, // every selectable UTxO, less the fee, to one address + canSelect: (candidate) => !candidate.script, // leave reference scripts where they are +}); + +const { outputs, fee } = plan.step("main"); +console.log(fee, outputs.map(({ address, value }) => [address, value])); // read it first +await plan.run(); +``` + +- It moves UTxOs, not rewards. Withdraw them first: see [Withdraw Rewards](/apis/txbuilder/staking#withdraw-rewards). +- Without `canSelect` a UTxO that holds a deployed script goes too: see [Send Everything](/apis/txbuilder/utxos#send-everything). +- A sweep is never consolidated. A wallet with more UTxOs than one transaction holds is `TX_TOO_LARGE`: narrow it with `canSelect` and sweep again. See [Consolidation Steps](/apis/txbuilder/plans#consolidation-steps). + +## Chain Payments Without Waiting + +Use this to send several payments in a row without waiting for a block between them. Each build is told about the ones before it, so it picks other inputs and may spend their change. + +```tsx +import { output, validity } from "@meshsdk/core"; +import type { BuiltTx } from "@meshsdk/core"; + +const ends = validity({ until: Date.now() + 30 * 60_000 }); // build() sets no deadline: give one +const queue: BuiltTx[] = []; +for (const [address, lovelace] of [ + [recipient, 5_000_000n], + [partner, 2_000_000n], + [recipient, 1_000_000n], +] as const) { + queue.push( + await builder.build([output({ address, value: { lovelace } }), ends], { + payer: wallet, + after: queue, // not the inputs of the earlier ones; their change is allowed + }), + ); +} + +for (const built of queue) { + await built.sign(); + await built.submit(); // in the order they were built +} +await Promise.all(queue.map((built) => built.awaitInclusion())); +``` + +- `after` keeps a build off the inputs of the others and lets it name their outputs: see [Build on a Transaction Not Yet on Chain](/apis/txbuilder/utxos#build-on-a-transaction-not-yet-on-chain). +- Build one after another, as the loop does: builds started at the same time do not know about each other. Another program spending from the same wallet is not known either: give each its own UTxOs with [`canSelect`](/apis/txbuilder/utxos#limit-what-the-builder-may-pick). +- A retry is `submit()` again on the same object, never a new build: see [Retry Without Rebuilding](/apis/txbuilder/signing#retry-without-rebuilding). +- If one payment does not land, the ones built on its change cannot land either. Once its `until` has passed, build them again: see [Set an Expiry](/apis/txbuilder/time#set-an-expiry). + +## Make an Offer That Expires + +Use this to sign a payment and hand it to the recipient, who may send it until it expires. The plan sets the deadline and follows the outcome, so you know when the funds are yours again. + +```tsx +import { output } from "@meshsdk/core"; + +const offer = await builder.plan( + output({ address: recipient, value: { lovelace: 50_000_000n } }), + { payer: wallet, ttlMs: 3_600_000 }, // valid for one hour +); +await offer.sign(); // signed by you, not sent +const { signedTx } = offer.step("main"); // give it to the recipient +console.log(new Date(offer.until!)); // the last moment it can land +const saved = JSON.stringify(offer); // keep it: it brings the plan back after a restart + +// Later: what became of the offer? +const back = await builder.resume(JSON.parse(saved), { payer: wallet }); +await back.refresh(); // one look at the chain; it never signs or sends +console.log(back.step("main").status); // included or final: taken. expired: it cannot land +``` + +- The deadline is in the signed bytes: after it the ledger refuses the transaction. The plan calls it `expired` once a margin for rollbacks has passed too: see [Set Deadlines and Waiting](/apis/txbuilder/plans#set-deadlines-and-waiting). +- Until it expires the offer may still land, so keep other payments off its inputs with `after: offer`. Once `expired`, `back.replan({ id })` builds it again: see [Handle a Step That Does Not Go Through](/apis/txbuilder/plans#handle-a-step-that-does-not-go-through). +- A plan lives in its object. To find it by an id instead, make it with an `id` on a builder with a `store`, and call `builder.resume(id, { payer: wallet })`: see [Record Plans in a Store](/apis/txbuilder/servers#record-plans-in-a-store). + +## Related + +- [Plans](/apis/txbuilder/plans) - steps, statuses, deadlines and replan +- [Signing and Submitting](/apis/txbuilder/signing) - wallets, keys and safe retries +- [UTxOs and Inputs](/apis/txbuilder/utxos) - `canSelect`, `after` and `sendAllTo` diff --git a/content/docs/apis/txbuilder/cookbook/scripts.mdx b/content/docs/apis/txbuilder/cookbook/scripts.mdx new file mode 100644 index 0000000..73e96d4 --- /dev/null +++ b/content/docs/apis/txbuilder/cookbook/scripts.mdx @@ -0,0 +1,173 @@ +--- +title: "Scripts" +description: "Lock funds until a deadline, hold a payment in escrow, and deploy a script once to use it by reference." +--- + +## Overview + +Three script recipes: funds that vest on a date, a payment held in escrow, and a script stored on chain once. They assume a compiled validator that accepts the datum and redeemer shown. Names as in [Before you start](/apis/txbuilder/cookbook#before-you-start), where `script` is its `{ code, version }`, plus `vault` for the last recipe. + +## Vest Funds and Claim Them Later + +Use this to pay someone after a date: the owner locks ada at a vesting script, and the beneficiary claims it once the deadline has passed. `script` is your vesting validator, whose datum holds the deadline in POSIX milliseconds and the key hashes of the owner and the beneficiary, and `partnerWallet` is the beneficiary's wallet. + +```tsx +import { guard, mConStr0, output, outputOf, spend, validity } from "@meshsdk/core"; + +// The owner locks 10 ada under a datum with the deadline and both key hashes, +// as deserializeAddress(address).pubKeyHash gives them +export async function lockFunds(deadline: bigint, owner: string, beneficiary: string) { + const lock = await builder.plan( + output({ + address: builder.scriptAddress(script), + value: { lovelace: 10_000_000n }, + datum: { type: "inline", data: mConStr0([deadline, owner, beneficiary]) }, + label: "vesting", + }), + { payer: wallet }, + ); // built; nothing is signed or sent + await lock.run(); + const { txHash, outputIndex } = outputOf(lock.step("main"), "vesting"); + return { txHash, outputIndex }; // keep it: the claim names this output +} + +// The beneficiary claims it from the first moment after the deadline, from anywhere +export async function claim( + vesting: { txHash: string; outputIndex: number }, + deadline: bigint, +) { + const plan = await builder.plan( + [ + spend.plutus({ utxo: vesting, script, redeemer: { data: mConStr0([]) } }), + guard.pubKey({ address: partner }), + validity({ from: deadline + 1n }), + ], + { payer: partnerWallet }, + ); + // Before the deadline this is NOT_YET_VALID: nothing is sent, so call claim again later + await plan.run(); + return plan.status; +} +``` + +- A script sees its interval inside `[from, until]`, so a validator that needs a lower bound after the deadline gets `from: deadline + 1n`: see [Set a Start Time](/apis/txbuilder/time#set-a-start-time). +- `NOT_YET_VALID` is a wait, not a failure: nothing was sent, and `error.retryAfterMs` says how long. For a deadline days away, build the claim when it is near: see [Wait for a Start Time](/apis/txbuilder/time#wait-for-a-start-time). +- `outputOf(plan.step("main"), "vesting")` names the locked output by its label: see [Link Steps](/apis/txbuilder/plans#link-steps). + +## Hold a Payment in Escrow + +Use this to hold a payment until both sides are satisfied: the buyer locks the price under a datum that names both parties, and one spend ends it, as a release to the seller or a refund to the buyer. `script` accepts a release signed by the buyer and a refund signed by the seller, and `partnerWallet` is the seller's wallet. + +```tsx +import { + deserializeAddress, + guard, + mConStr0, + mConStr1, + output, + outputOf, + spend, +} from "@meshsdk/core"; + +const buyer = deserializeAddress(changeAddress).pubKeyHash; +const seller = deserializeAddress(partner).pubKeyHash; +const price = 20_000_000n; + +// The buyer locks the price. The datum names both parties +export async function lockPrice() { + const lock = await builder.plan( + output({ + address: builder.scriptAddress(script), + value: { lovelace: price }, + datum: { type: "inline", data: mConStr0([buyer, seller]) }, + label: "escrow", + }), + { payer: wallet }, + ); + await lock.run(); + const { txHash, outputIndex } = outputOf(lock.step("main"), "escrow"); + return { txHash, outputIndex }; // keep it: the settlement names this output +} + +// One spend, two outcomes. Release: the buyer signs and the seller is paid. +// Refund: the seller signs and the buyer is paid back +const outcomes = { + release: { redeemer: mConStr0([]), to: partner, signer: buyer, payer: wallet }, + refund: { + redeemer: mConStr1([]), + to: changeAddress, + signer: seller, + payer: partnerWallet, + }, +}; + +export async function settle( + escrow: { txHash: string; outputIndex: number }, + outcome: keyof typeof outcomes, +) { + const o = outcomes[outcome]; + const plan = await builder.plan( + [ + spend.plutus({ + utxo: escrow, + script, + redeemer: { data: o.redeemer }, + label: outcome, + }), + output({ address: o.to, value: { lovelace: price } }), + guard.pubKey({ keyHash: o.signer }), + ], + { payer: o.payer }, + ); + await plan.run({ waitFor: "final" }); // release the goods now + return plan.status; +} +// const escrow = await lockPrice(); await settle(escrow, "release"); // or "refund" +``` + +- The constructor of the redeemer picks the action: `mConStr0([])` releases and `mConStr1([])` refunds: see [Spend from a Script](/apis/txbuilder/smart-contracts#spend-from-a-script). +- `guard.pubKey` requires a key's signature and shows it to the script. The payer signs by default, so the buyer's wallet pays a release and the seller's a refund: see [Require a Signer](/apis/txbuilder/basics#require-a-signer). +- The locked output is spent once, so only one outcome can happen. Keep its out ref, and act on the status of the plan: see [Read the Statuses](/apis/txbuilder/plans#read-the-statuses). + +## Deploy a Script Once and Use It by Reference + +Use this for a script that is large or spent often: put it on chain once, and every transaction then names the output that holds it instead of carrying its bytes. `script` is your Plutus script, and `vault` an output already locked at it. + +```tsx +import { mConStr0, output, outputOf, spend } from "@meshsdk/core"; + +// Once: put the script on chain, in an output of your own +const setup = await builder.plan( + output({ + address: changeAddress, + value: {}, // the output holds the minimum it needs + scriptRef: script, + label: "code", + }), + { payer: wallet }, +); +await setup.run(); +const code = outputOf(setup.step("main"), "code"); // keep this out ref: it is the script's home + +// Every use: name the output that holds the script, and keep it out of the selection +const use = await builder.plan( + spend.plutus({ + utxo: vault, + script: { reference: code }, + redeemer: { data: mConStr0([]) }, + }), + { payer: wallet, canSelect: (candidate) => !candidate.script }, +); +console.log(use.step("main").referenceInputs.length); // 1: the output that holds the script +await use.run(); +``` + +- `scriptRef` stores the script in an output, and an empty `value` gives it the minimum it needs: see [Deploy and Use a Reference Script](/apis/txbuilder/smart-contracts#deploy-and-use-a-reference-script). +- The holder sits at your own address, so `canSelect` keeps later builds from spending it: see [Limit What the Builder May Pick](/apis/txbuilder/utxos#limit-what-the-builder-may-pick). +- The builder adds the holder as a reference input and never spends it, so the transaction carries no script bytes: see [Read an Output without Spending It](/apis/txbuilder/utxos#read-an-output-without-spending-it). + +## Related + +- [Smart Contracts](/apis/txbuilder/smart-contracts) - lock, spend and read with Plutus and native scripts +- [Time and Validity](/apis/txbuilder/time) - deadlines, start times and the clock +- [UTxOs and Inputs](/apis/txbuilder/utxos) - choose, limit and read outputs diff --git a/content/docs/apis/txbuilder/cookbook/servers.mdx b/content/docs/apis/txbuilder/cookbook/servers.mdx new file mode 100644 index 0000000..dac6eff --- /dev/null +++ b/content/docs/apis/txbuilder/cookbook/servers.mdx @@ -0,0 +1,103 @@ +--- +title: "Server Recipes" +description: "Take a payment without holding a key, and finish payouts after a crash or a restart." +--- + +## Overview + +Two recipes for a server that sends transactions: a payment the user signs in a browser, and payouts that finish after a restart. Names as in [Before you start](/apis/txbuilder/cookbook#before-you-start), where `builder` is a `TxBuilder` made with your `store`. `memoryPlanStore()` loses its plans when the process ends, so for a database write a `TxPlanStore` of two methods: see [Write a Store](/apis/txbuilder/servers#write-a-store). + +## Take a Payment on a Server + +Use this to take a payment without holding a key: the server builds the transaction for the user's address, the user's wallet signs it in the browser, and any instance sends it. One id for one order means that a repeated request never pays twice. + +```tsx +import { output } from "@meshsdk/core"; + +// Request 1: build the payment, record it under the order's id, return the unsigned body +export async function startOrder( + orderId: string, + userAddress: string, + lovelace: bigint, +) { + const plan = await builder.plan( + output({ address: recipient, value: { lovelace } }), + { id: orderId, payer: userAddress }, + ); // recorded before it returns; a repeated request gets the recorded plan + return { tx: plan.step("main").tx }; +} + +// Request 2: the browser signed with signTx(tx, true) and sends the witness set +export async function payOrder(orderId: string, witnessSet: string) { + const plan = await builder.resume(orderId); // from any instance + await plan.addWitnesses(witnessSet); // INVALID_WITNESS when it is not of this body + await plan.run({ waitFor: "sent" }); // sends it and waits for no block + return { txHash: plan.step("main").txHash }; +} + +// A job, or a webhook: ship the order only when this is true +export async function isPaid(orderId: string) { + const plan = await builder.resume(orderId); + await plan.refresh(); // one look at the chain; it needs no payer and sends nothing + return plan.status === "final"; +} +``` + +- One id is one order: the same id with the same steps returns the recorded plan, and a new id is paid again: see [Use One Id for One Plan](/apis/txbuilder/servers#use-one-id-for-one-plan). +- The user's address is the payer and the wallet signs in the browser, so the server holds no key: see [Build Without Keys on a Server](/apis/txbuilder/servers#build-without-keys-on-a-server). +- Ship at `final`, never at `included`, which a rollback can undo. A plan that is `stopped` expired unsigned: start a new order under a new id. See [Read the Statuses](/apis/txbuilder/plans#read-the-statuses). + +## Finish Payouts After a Restart + +Use this for payouts your wallet makes, which must survive a crash: a plan records its delivery before the bytes leave, so after a restart the same `payout` call finds the plan and sends the same bytes if they are needed, never a new transaction. `db` is your list of open payouts: `open(id, payout)`, `close(id)` and `list()`. + +```tsx +import { output } from "@meshsdk/core"; +import type { TxPlan } from "@meshsdk/core"; + +// Follow a plan to the plan in its place; when nothing may still land and a step is left, +// make that plan once +async function latest(first: TxPlan) { + let plan = first; + await plan.refresh(); // one look at the chain; it never signs or sends + let made = false; + while ( + plan.status !== "final" && + (plan.replacedBy !== undefined || + (!made && plan.live.length === 0 && plan.landed.length < plan.steps.length)) + ) { + made ||= plan.replacedBy === undefined; + plan = await plan.replan({ id: plan.replacedBy ?? `${plan.id}:next` }); + await plan.refresh(); + } + return plan; +} + +// One id for one payout: a retried job, or a restart, is the same call +export async function payout(id: string, to: string, lovelace: bigint) { + await db.open(id, { to, lovelace }); // before the plan's first await + const recorded = await builder.plan( + output({ address: to, value: { lovelace } }), + { id, payer: wallet }, + ); // the recorded plan, or a new one + const plan = await latest(recorded); + await plan.run({ waitFor: "sent" }); // what can be done at once + if (plan.status === "final") await db.close(id); // release the goods +} + +// At start-up, and once a minute: every open payout, each on its own +for (const { id, to, lovelace } of await db.list()) { + // a call that failed is repeated by the next pass + await payout(id, to, lovelace).catch((error) => console.error(id, error)); +} +``` + +- With `waitFor: "sent"` each pass moves a plan one step on, and a call that failed with a wait is repeated by the next pass: see [Set Deadlines and Waiting](/apis/txbuilder/plans#set-deadlines-and-waiting). +- `replan` pays what is left, once. Never call `builder.plan(plan.rest)`: see [Handle a Step That Does Not Go Through](/apis/txbuilder/plans#handle-a-step-that-does-not-go-through). +- Plans of one payer built together compete for the same UTxOs. Give a later plan `after: earlier`, or build them one after another, else the second waits out its deadline before `replan` pays it: see [Build on a Transaction Not Yet on Chain](/apis/txbuilder/utxos#build-on-a-transaction-not-yet-on-chain). + +## Related + +- [Servers and Storage](/apis/txbuilder/servers) - stores, ids, signatures over several days and writing a store +- [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 diff --git a/content/docs/apis/txbuilder/cookbook/staking-governance.mdx b/content/docs/apis/txbuilder/cookbook/staking-governance.mdx new file mode 100644 index 0000000..e5cbe49 --- /dev/null +++ b/content/docs/apis/txbuilder/cookbook/staking-governance.mdx @@ -0,0 +1,113 @@ +--- +title: "Staking and Governance" +description: "Complete examples that delegate a stake key, withdraw its rewards and register a DRep who votes." +--- + +## Overview + +Four recipes for stake and vote: a stake key registered and delegated, the whole reward balance withdrawn, a stake key deregistered, and a DRep registered who votes. Names as in [Before you start](/apis/txbuilder/cookbook#before-you-start), plus `rewardAddress`, `poolId`, `drepId` and `actionTxHash`. + +## Register and Delegate in One Transaction + +Use this when a wallet stakes for the first time. One transaction registers its stake key `rewardAddress`, delegates it to the pool `poolId` and delegates its vote, which the ledger asks for before the key can withdraw rewards. + +```tsx +import { certificate } from "@meshsdk/core"; + +const built = await builder.build( + [ + certificate.stakeRegistration({ stake: rewardAddress }), // pays the key deposit + certificate.stakeDelegation({ stake: rewardAddress, pool: poolId }), + certificate.voteDelegation({ stake: rewardAddress, drep: "alwaysAbstain" }), + ], + { payer: wallet }, +); // nothing is signed or sent yet +await built.sign(); // the wallet signs with its payment and stake keys +await built.submit(); +await built.awaitInclusion(); +``` + +- The deposit is paid by the registration and counted in the balance, so you add no output: see [Deposits](/apis/txbuilder/certificates#deposits). +- A `MeshWallet` signs with its stake key. If the wallet does not hold it, name another signer: see [Who Signs](/apis/txbuilder/certificates#who-signs). +- After `SUBMIT_FAILED` or `CONFIRM_TIMEOUT` the outcome is unknown: repeat `submit()` or `awaitInclusion()` on the same `built`, and never build again: see [Retry Without Rebuilding](/apis/txbuilder/signing#retry-without-rebuilding). + +## Withdraw All Rewards + +Use this to collect the whole reward balance of `rewardAddress`. With `amount: "all"` the builder reads the balance through the provider and the rewards arrive as change, and reading it first skips a transaction when there is nothing to collect. + +```tsx +import { withdrawal } from "@meshsdk/core"; + +const { rewards } = await provider.fetchAccountInfo(rewardAddress); + +if (BigInt(rewards) > 0n) { + const built = await builder.build( + withdrawal.pubKey({ rewardAddress, amount: "all" }), // the balance is looked up + { payer: wallet }, + ); + await built.sign(); // the wallet signs, with the stake key the withdrawal needs + await built.submit(); + await built.awaitInclusion(); +} +``` + +- A stated amount must equal the whole balance, which is why `"all"` is the safe way: see [Withdraw Rewards](/apis/txbuilder/staking#withdraw-rewards). +- The ledger refuses a withdrawal from a stake key that has delegated its vote to no DRep. Delegate it first, as the recipe above does: see [Delegate Your Vote](/apis/txbuilder/governance#delegate-your-vote). +- With a zero balance `"all"` still builds, as a withdrawal of `0n`, and pays a fee, so the check above saves it: see [Withdraw Rewards](/apis/txbuilder/staking#withdraw-rewards). + +## Stop Staking and Take the Deposit Back + +Use this to deregister the stake key `rewardAddress` and get its key deposit back. The reward balance must be empty first, so the same transaction withdraws it. + +```tsx +import { certificate, withdrawal } from "@meshsdk/core"; + +const built = await builder.build( + [ + withdrawal.pubKey({ rewardAddress, amount: "all" }), // the balance must be empty + certificate.stakeDeregistration({ stake: rewardAddress }), // refunds the key deposit + ], + { payer: wallet }, +); +await built.sign(); // the wallet signs with the stake key both parts need +await built.submit(); +await built.awaitInclusion(); +``` + +- The refund is the `keyDeposit` parameter. If the key was registered with another deposit, give `refund` on the part: see [Deposits](/apis/txbuilder/certificates#deposits). +- A reward balance that is not empty makes the ledger refuse the deregistration: see [Deregister a Stake Key](/apis/txbuilder/staking#deregister-a-stake-key). +- To stake again, register and delegate the key anew: see [Register and Delegate](/apis/txbuilder/staking#register-and-delegate). + +## Become a DRep and Vote + +Use this to vote with your own DRep `drepId` on the governance action that the transaction `actionTxHash` proposed. A DRep must be registered before it votes, so the two transactions are the steps of one plan, which waits for the registration to be in a block and never builds either again. + +```tsx +import { certificate, vote } from "@meshsdk/core"; + +const plan = await builder.plan( + { + register: certificate.drepRegistration({ + drep: drepId, + deposit: 500_000_000n, // the DRep deposit, returned when the DRep retires + }), + vote: vote({ + voter: { drep: drepId }, + votes: [{ action: { txHash: actionTxHash, index: 0 }, vote: "yes" }], + }), + }, + { payer: wallet }, // the wallet holds the DRep key and signs both steps +); // both are built; nothing is signed or sent +await plan.run(); // register, a block, then vote +console.log(plan.step("vote").status, plan.status); +``` + +- The `deposit` must equal the current DRep deposit. Pass it on the part, or give the builder `deposits: { drepDeposit }`: see [Deposits](/apis/txbuilder/certificates#deposits). +- A plan is not atomic. A vote the ledger refuses makes `run()` throw `REJECTED`, the DRep stays registered, and `plan.landed` lists the step that landed: see [Handle a Step That Does Not Go Through](/apis/txbuilder/plans#handle-a-step-that-does-not-go-through). +- A `MeshWallet` signs with its DRep key. A browser wallet must be connected with the CIP-95 extension: see [Who Signs](/apis/txbuilder/certificates#who-signs). + +## Related + +- [Staking Transactions](/apis/txbuilder/staking) - every staking part and who signs it +- [Governance Transactions](/apis/txbuilder/governance) - DReps, votes and proposals +- [Certificates](/apis/txbuilder/certificates) - every certificate, its deposit and its signer diff --git a/content/docs/apis/txbuilder/cookbook/testing.mdx b/content/docs/apis/txbuilder/cookbook/testing.mdx new file mode 100644 index 0000000..cc8cca7 --- /dev/null +++ b/content/docs/apis/txbuilder/cookbook/testing.mdx @@ -0,0 +1,120 @@ +--- +title: "Test Recipes" +description: "Complete jest tests that run a payment plan to final and check an expected error on the emulator." +--- + +## Overview + +Three tests on the `TxEmulator` of `@meshsdk/tx-emulator` (`npm install @meshsdk/tx-emulator`): a payment plan run to `final`, a payout that finishes after a restart, and a payment the wallet cannot afford. Names as in [Before you start](/apis/txbuilder/cookbook#before-you-start), plus `it` and `expect` from jest. + +## Test a Payment Plan on the Emulator + +Use this for a test of a whole flow, a plan sent to its end and the balances afterwards, with a `setup()` that the other tests of this page share. `validator` is the `TxValidator` of the emulator and `words` the mnemonic of a test wallet, as in [Testing on the Emulator](/apis/txbuilder/testing#create-and-fund-an-emulator). + +```tsx +import { MeshWallet, output, TxBuilder } from "@meshsdk/core"; +import { TxEmulator } from "@meshsdk/tx-emulator"; + +const planDefaults = { expiryMarginMs: 0, confirmations: 0, pollMs: 10, resendMs: 10 }; + +async function setup() { + const emulator = await TxEmulator.create({ validator, network: "preprod" }); + const wallet = new MeshWallet({ + networkId: 0, + key: { type: "mnemonic", words }, + }); + emulator.fund(await wallet.getChangeAddress(), { lovelace: 100_000_000n }); + const builder = new TxBuilder({ network: "preprod", provider: emulator, planDefaults }); + return { emulator, wallet, builder }; +} + +const lovelaceOf = (emulator: TxEmulator, address: string) => + emulator + .utxos({ address }) + .flatMap((utxo) => utxo.output.amount) + .filter((asset) => asset.unit === "lovelace") + .reduce((sum, asset) => sum + BigInt(asset.quantity), 0n); + +it("pays the recipient and ends final", async () => { + const { emulator, wallet, builder } = await setup(); + emulator.fund(recipient, { lovelace: 10_000_000n }); + const plan = await builder.plan( + { pay: output({ address: recipient, value: { lovelace: 25_000_000n } }) }, + { payer: wallet }, + ); + await plan.run({ waitFor: "final" }); + + expect(plan.status).toBe("final"); + expect(lovelaceOf(emulator, recipient)).toBe(35_000_000n); + expect(lovelaceOf(emulator, await wallet.getChangeAddress())).toBe(75_000_000n - plan.fee); +}); +``` + +- `fund` adds an output to the ledger. The wallet has no fetcher, so the builder reads its UTxOs from the emulator: see [Create and Fund an Emulator](/apis/txbuilder/testing#create-and-fund-an-emulator). +- The `planDefaults` make a step `final` as soon as it is included and keep the waiting short. Use them in tests only: see [Run a Plan](/apis/txbuilder/testing#run-a-plan). +- The payer holds its funds less the payment and `plan.fee`, the fees of every step: see [Send Several Transactions](/apis/txbuilder/plans#send-several-transactions). + +## Test That a Payout Finishes After a Restart + +Use this to test server code that resumes plans: the first builder sends a payout and is dropped, and a second builder on the same store finds the plan, finishes it and pays once. It adds a test to the file above, so it uses `setup` and `planDefaults`. + +```tsx +import { memoryPlanStore, output, TxBuilder } from "@meshsdk/core"; + +it("finishes a payout after a restart without paying twice", async () => { + const { emulator, wallet } = await setup(); + const options = { + network: "preprod", + provider: emulator, + store: memoryPlanStore(), + planDefaults, + } as const; + + const before = new TxBuilder(options); + const plan = await before.plan( + output({ address: recipient, value: { lovelace: 5_000_000n } }), + { id: "payout-1", payer: wallet }, + ); + await plan.run({ waitFor: "sent" }); // the bytes left; the process dies here + + const after = new TxBuilder(options); // a new instance on the same store + const resumed = await after.resume("payout-1", { payer: wallet }); + await resumed.run({ waitFor: "final" }); // looks first: the same bytes, never a new transaction + expect(resumed.status).toBe("final"); + expect(resumed.step("main").txHash).toBe(plan.step("main").txHash); + expect(emulator.utxos({ address: recipient })).toHaveLength(1); // paid once +}); +``` + +- `resume` reads the store only and does not call the payer, so give the payer again: see [Resume After a Crash](/apis/txbuilder/servers#resume-after-a-crash). +- `memoryPlanStore()` is for tests: a real server writes its own store: see [Write a Store](/apis/txbuilder/servers#write-a-store). +- The same `id` with the same steps is the same plan, so a retried job pays once: see [Use One Id for One Plan](/apis/txbuilder/servers#use-one-id-for-one-plan). + +## Test an Expected Error + +Use this to check that a mistake fails the way you expect: `build()` throws before anything is signed or sent, and the test checks the code. It adds a test to the file above, so it uses `setup`. + +```tsx +import { output } from "@meshsdk/core"; + +it("refuses a payment the wallet cannot afford", async () => { + const { emulator, wallet, builder } = await setup(); + await expect( + builder.build( + output({ address: recipient, value: { lovelace: 500_000_000n } }), + { payer: wallet }, + ), + ).rejects.toMatchObject({ code: "INSUFFICIENT_FUNDS", details: { unit: "lovelace" } }); + expect(emulator.utxos({ address: recipient })).toHaveLength(0); // nothing was sent +}); +``` + +- Code that reads `error.details` checks the code with `TxError.is(error, "INSUFFICIENT_FUNDS")`, which also types them: see [Check a Code](/apis/txbuilder/errors#check-a-code). +- A build error means nothing was sent, so a test may fund the wallet and build again: see [Handle Errors Around Build and Submit](/apis/txbuilder/errors#handle-errors-around-build-and-submit). +- Every code with what it means is in [Funds, Fees and Size](/apis/txbuilder/errors#funds-fees-and-size), and the other groups follow it. + +## Related + +- [Testing on the Emulator](/apis/txbuilder/testing) - validators, time, forks and scripts that refuse +- [Plans](/apis/txbuilder/plans) - send transactions in order +- [Errors](/apis/txbuilder/errors) - every code and which a retry can fix diff --git a/content/docs/apis/txbuilder/cookbook/tokens.mdx b/content/docs/apis/txbuilder/cookbook/tokens.mdx new file mode 100644 index 0000000..2025f8a --- /dev/null +++ b/content/docs/apis/txbuilder/cookbook/tokens.mdx @@ -0,0 +1,144 @@ +--- +title: "Tokens and NFTs" +description: "Mint an NFT collection with CIP-25 metadata, mint a CIP-68 token and burn tokens." +--- + +## Overview + +Three token recipes: an NFT collection under a policy that closes, a CIP-68 token with a reference token for its metadata, and a burn. Names as in [Before you start](/apis/txbuilder/cookbook#before-you-start), plus `items`, `policyCode` and `referenceAddress`. + +## Mint an NFT Collection + +Use this to mint a fixed set of NFTs with CIP-25 metadata, under a policy that needs your signature and works only before a slot, so after that slot nobody can mint under it again, you included. `items` is your own list, each `{ name, image }`, and the NFTs go to your wallet. + +```tsx +import { + deserializeAddress, + metadata, + mint, + resolveNativeScriptHash, + stringToHex, + validity, +} from "@meshsdk/core"; +import type { NativeScript } from "@meshsdk/core"; + +const { pubKeyHash } = deserializeAddress(changeAddress); +const closes = builder.slotAt(Date.now() + 3_600_000); // the policy closes in an hour +const policy: NativeScript = { + type: "all", + scripts: [ + { type: "sig", keyHash: pubKeyHash }, + { type: "before", slot: closes.toString() }, + ], +}; +const policyId = resolveNativeScriptHash(policy); + +const plan = await builder.plan( + [ + mint.native({ + script: policy, + assets: Object.fromEntries(items.map(({ name }) => [stringToHex(name), 1n])), + }), + metadata({ + metadataLabel: 721n, + value: { + [policyId]: Object.fromEntries( + items.map(({ name, image }) => [ + name, + { name: `Mesh ${name}`, image, mediaType: "image/png" }, + ]), + ), + }, + }), + validity({ invalidHereafter: closes }), // lands before the policy closes + ], + { payer: wallet }, +); // built; nothing is signed or sent +await plan.run(); +``` + +- The policy has two rules: your key signs, and the slot has not passed. Once `closes` is past no transaction can mint under it, so the supply is fixed: see [Mint with a Time-Locked Policy](/apis/txbuilder/minting#mint-with-a-time-locked-policy). +- CIP-25 metadata sits under label 721, by policy id and then asset name. Each text is at most 64 bytes: see [Add NFT Metadata](/apis/txbuilder/minting#add-nft-metadata). +- While the policy is open, a second build mints the same names again. A collection too large for one transaction (`TX_TOO_LARGE`) is one step per batch, each with the same `validity`: see [Mint Several Assets](/apis/txbuilder/minting#mint-several-assets). + +## Mint a CIP-68 Token + +Use this for a token whose metadata you can change later: CIP-68 keeps it in the inline datum of a reference token held at `referenceAddress`, while the user token goes to `recipient`. `policyCode` is your Plutus minting policy, one that accepts the redeemer below and lets both tokens be minted in one transaction. + +```tsx +import { + CIP68_100, + CIP68_222, + mConStr0, + metadataToCip68, + mint, + output, + resolveScriptHash, + stringToHex, +} from "@meshsdk/core"; + +const nameHex = stringToHex("MyToken"); +const policyId = resolveScriptHash(policyCode, "V3"); + +const plan = await builder.plan( + [ + 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 }, // the reference token + datum: { + type: "inline", + data: metadataToCip68({ + name: "MyToken", + image: "ipfs://QmRzicpReutwCkM6aotuKjErFCUD213DpwPq6ByuzMJaua", + }), + }, + }), + output({ + address: recipient, + value: { [policyId + CIP68_222(nameHex)]: 1n }, // the user token + }), + ], + { payer: wallet }, +); +await plan.run(); +``` + +- Both tokens belong to one policy, so they are one `mint` part. `CIP68_100` and `CIP68_222` add the label to the name: see [Mint CIP-68 Tokens](/apis/txbuilder/minting#mint-cip-68-tokens). +- Keep the reference token at a script address whose validator lets your key update it. To change the metadata, spend it with `spend.plutus` and send it back with a new datum: see [Spend from a Script](/apis/txbuilder/smart-contracts#spend-from-a-script). At a key address of yours, keep it out of every later build with `canSelect`. +- The policy runs while the plan is built. A policy that refuses fails with `EVALUATION_FAILED` and nothing is sent: see [Test That a Script Refuses](/apis/txbuilder/testing#test-that-a-script-refuses). + +## Burn Tokens + +Use this to burn five of the tokens of `unit`, which your wallet holds. A burn is a mint with a negative quantity, under the policy that minted them. + +```tsx +import { ForgeScript, mint, resolveScriptHash } from "@meshsdk/core"; + +const forgingScript = ForgeScript.withOneSignature(changeAddress); // the policy that minted them +const policyId = resolveScriptHash(forgingScript); +if (!unit.startsWith(policyId)) throw new Error("not a token of this policy"); + +const plan = await builder.plan( + mint.native({ + script: forgingScript, + assets: { [unit.slice(policyId.length)]: -5n }, // negative: burn + }), + { payer: wallet }, +); +await plan.run(); +``` + +- The tokens must be in the payer's wallet, else `INSUFFICIENT_FUNDS`: see [Burn Assets](/apis/txbuilder/minting#burn-assets). +- A burn runs the policy too. Your key must sign, and the time-locked policy of the collection above cannot burn after its slot: see [Mint with a Time-Locked Policy](/apis/txbuilder/minting#mint-with-a-time-locked-policy). +- A Plutus policy burns the same way, with a negative quantity and a redeemer: see [Mint with a Plutus Script](/apis/txbuilder/minting#mint-with-a-plutus-script). + +## Related + +- [Mint and Burn Assets](/apis/txbuilder/minting) - native and Plutus policies, metadata and reference scripts +- [Plans](/apis/txbuilder/plans) - steps, statuses and deadlines +- [Time and Validity](/apis/txbuilder/time) - slots and the end of validity diff --git a/content/docs/apis/txbuilder/errors.mdx b/content/docs/apis/txbuilder/errors.mdx new file mode 100644 index 0000000..de42681 --- /dev/null +++ b/content/docs/apis/txbuilder/errors.mdx @@ -0,0 +1,224 @@ +--- +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. The call that needs them throws, not the constructor. `details.parameter` says which: `"params"`, `"costModels"` or `"deposits"`. 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 | + +`MISSING_PARAMETER` comes from these places: + +- A builder given its `network` alone is made without error and reads and signs. `build()`, `plan()`, `chain()` and a plan's `add` and `replan` throw it at the call, with `details.parameter` `"params"`. Give the builder a `provider` or `params`: see [A Builder with a Network Alone](/apis/txbuilder/offline#a-builder-with-a-network-alone). +- The provider's protocol parameters could not be read, came back empty or lack a field a build reads (`"params"`). When the read failed, `error.cause` holds the provider's error. +- A build that runs a Plutus script, or `chain()`, has no cost models: there are none, or the provider could not read them, and then `error.cause` holds why (`"costModels"`). +- A deposit is not known. A governance deposit is not given (`"deposits"`). Or the parameters lack the field that gives the amount (`"params"`, and the message names the field): `keyDeposit` for a stake registration or deregistration that states no amount and for a legacy stake certificate (`legacyStakeRegistration`, `legacyStakeDeregistration`), `poolDeposit` for a first `poolRegistration`. These throw before anything is selected. See [Deposits](/apis/txbuilder/certificates#deposits). + +### 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`. 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 | + +### 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 | + +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 + +- [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 a266482..722f213 100644 --- a/content/docs/apis/txbuilder/governance.mdx +++ b/content/docs/apis/txbuilder/governance.mdx @@ -1,994 +1,125 @@ --- 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); +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. -const unsignedTx = await txBuilder.complete(); -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); +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). -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, -}); +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)). -const utxos = await wallet.getUtxos(); -const changeAddress = await wallet.getChangeAddress(); -const rewardAddresses = await wallet.getRewardAddresses(); -const rewardAddress = rewardAddresses[0]!; +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: -txBuilder - .voteDelegationCertificate({ alwaysAbstain: true }, rewardAddress) - .changeAddress(changeAddress) - .selectUtxosFrom(utxos); +- `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 -const unsignedTx = await txBuilder.complete(); -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); -``` +| 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 | +| 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 | -### Register as a DRep +## Manage a DRep -Register yourself as a DRep with metadata: +- 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 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 { MeshTxBuilder, BlockfrostProvider, hashDrepAnchor } from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); +import { certificate } from "@meshsdk/core"; -// 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}`); +const built = await builder.build( + certificate.drepRegistration({ drep: drepId, anchor }), + { payer: wallet }, +); ``` -### Update DRep Metadata +## Delegate Your Vote -Update your DRep profile information: +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 { 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); +import { certificate } from "@meshsdk/core"; -const unsignedTx = await txBuilder.complete(); -const signedTx = await wallet.signTx(unsignedTx); -const txHash = await wallet.submitTx(signedTx); - -console.log(`DRep retired: ${txHash}`); +const built = await builder.build( + certificate.voteDelegation({ stake: rewardAddress, drep: drepId }), + { payer: wallet }, +); ``` -### Vote on Governance Action +## Vote on an Action -Cast a vote as a DRep: +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 dRep = await wallet.getDRep(); -const dRepId = dRep.dRepIDCip105; - -const utxos = await wallet.getUtxos(); -const changeAddress = await wallet.getChangeAddress(); +import { vote } from "@meshsdk/core"; -// 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}`); +const built = await builder.build( + vote({ + voter: { drep: drepId }, + votes: [ + { action: { txHash: actionTxHash, index: 0 }, vote: "yes", anchor }, + ], + }), + { payer: wallet }, +); ``` -### Vote with Rationale +## Submit a Proposal -Include reasoning for your vote: +`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, hashDrepAnchor } from "@meshsdk/core"; - -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); +import { proposal } from "@meshsdk/core"; -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); +const built = await builder.build( + proposal.info({ rewardAccount: rewardAddress, anchor }), + { payer: wallet }, +); ``` -### Vote with Plutus Script - -Vote using a Plutus script DRep: - -```tsx -import { - MeshTxBuilder, - BlockfrostProvider, - resolveScriptHash, - resolveScriptHashDRepId, - applyCborEncoding -} from "@meshsdk/core"; +## Propose Other Actions -const provider = new BlockfrostProvider(""); -const txBuilder = new MeshTxBuilder({ - fetcher: provider, - verbose: true, -}); +Each action takes `rewardAccount` and `anchor`, plus its own fields: -const utxos = await wallet.getUtxos(); -const collateral = await wallet.getCollateral(); -const changeAddress = await wallet.getChangeAddress(); +- `treasuryWithdrawals` - `withdrawals`, lovelace by receiving reward address +- `parameterChange` - `updates` +- `hardForkInitiation` - `protocolVersion` +- `updateCommittee` - `quorum`, and `add` and `remove` for members +- `newConstitution` - `constitution` +- `noConfidence` - nothing more -// 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): +`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 } 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: "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( + proposal.treasuryWithdrawals({ + rewardAccount: rewardAddress, + anchor, + withdrawals: { [rewardAddress]: 50_000_000_000n }, + }), + { payer: wallet }, +); ``` -### 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 +- [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 +- [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 de58ac0..0e2816a 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 --- @@ -11,48 +11,64 @@ import { CardDescription, CardTitle, } from "@/components/ui/card"; +import { BuilderFlow } from "@/components/txbuilder/builder-flow"; -## Overview +> **Note:** Coming from `MeshTxBuilder`, the chain of calls? It is deprecated but still works. See [Migrating to TxBuilder](/apis/txbuilder/migration). -`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. +## Overview -**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). + +## 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), [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). + +## 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 | +| `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. + +## Pick a Task
{linksTxbuilder.map((card) => ( @@ -67,6 +83,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 d43a6ec..b465453 100644 --- a/content/docs/apis/txbuilder/meta.json +++ b/content/docs/apis/txbuilder/meta.json @@ -1,5 +1,31 @@ { "title": "Transaction Builder", "icon": "BanknotesIcon", - "pages": ["basics", "minting", "smart-contracts", "staking", "governance"] -} \ No newline at end of file + "pages": [ + "basics", + "signing", + "utxos", + "time", + "---Plans and Servers---", + "plans", + "servers", + "---Scripts, Staking and Governance---", + "minting", + "smart-contracts", + "staking", + "certificates", + "governance", + "---Examples---", + "cookbook", + "---Environments---", + "offline", + "testing", + "networks", + "---Reference---", + "options", + "errors", + "---Migration---", + "migration", + "legacy" + ] +} diff --git a/content/docs/apis/txbuilder/migration/basics.mdx b/content/docs/apis/txbuilder/migration/basics.mdx new file mode 100644 index 0000000..dc66269 --- /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 `build()` 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 new file mode 100644 index 0000000..04c68ed --- /dev/null +++ b/content/docs/apis/txbuilder/migration/index.mdx @@ -0,0 +1,94 @@ +--- +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(...)`. 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`. + +`ForgeScript`, `mConStr0`, `resolveScriptHash` and the other Data and script helpers do not change. Before blocks use them without an import. + +## The Four Steps + +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). + +## A Payment, 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); +``` + +Three rules hold on every page: + +| Old | New | +|-----|-----| +| 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 }` | +| Amounts as strings: `"5000000"` | Amounts as `bigint`: `5_000_000n` | + +## If You Keep MeshTxBuilder + +`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). + +## Names in the Examples + +Your application defines these names. Every page of this guide uses them the same way. + +| 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 diff --git a/content/docs/apis/txbuilder/minting.mdx b/content/docs/apis/txbuilder/minting.mdx index fe3b858..084b914 100644 --- a/content/docs/apis/txbuilder/minting.mdx +++ b/content/docs/apis/txbuilder/minting.mdx @@ -1,676 +1,224 @@ --- -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. +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. -```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 | +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: -### metadataValue() +- `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 -Attach metadata to the transaction. +## Mint with a Native Script -```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: +`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 -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(); - -// 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, -}); - -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); +import { mint, stringToHex } from "@meshsdk/core"; - metadata[policyId][tokenName] = { - name: tokenName, - image: "ipfs://QmRzicpReutwCkM6aotuKjErFCUD213DpwPq6ByuzMJaua", - description: `Token #${i} from the Mesh collection`, - }; +const names = ["MeshToken1", "MeshToken2", "MeshToken3"]; - // 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 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"; - -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); +import { mint, stringToHex } from "@meshsdk/core"; + +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 -} from "@meshsdk/core"; +import { deserializeAddress, 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, - resolveScriptHash, - stringToHex, - mConStr0, - UTxO -} from "@meshsdk/core"; +import { metadata, mint, resolveScriptHash, stringToHex } 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 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 - -Mint tokens with on-chain metadata using the CIP-68 standard: +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 { - 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); +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 Royalty Token (CIP-27) +## Mint with a Plutus Script -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, - resolveScriptHash, - stringToHex, - deserializeAddress, - NativeScript + CIP68_100, CIP68_222, mConStr0, metadataToCip68, + mint, output, resolveScriptHash, stringToHex, } 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 - -### "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 +### Mint with 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 +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). -### 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 +- [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 +- [Package README](https://github.com/MeshJS/mesh/tree/main/packages/mesh-transaction) - every part, option and error 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..ea4da6a --- /dev/null +++ b/content/docs/apis/txbuilder/offline.mdx @@ -0,0 +1,218 @@ +--- +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. + +To build, a builder needs a `provider` or `params`. Given its `network` alone, `new TxBuilder({ network: "preprod" })` reads and signs a transaction that exists already: see [A Builder with a Network Alone](#a-builder-with-a-network-alone). + +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 +- `coldKey` - a signing key that never touches the building machine +- `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] }, +); +``` + +### A Builder with a Network Alone + +A builder with neither `provider` nor `params` builds nothing, and it is made without error. `build()`, `plan()`, `chain()` and a plan's `add` and `replan` throw `MISSING_PARAMETER` (`details.parameter` is `"params"`) at the call. What needs no chain works on it: `fromCbor` with `knownUtxos` or `blind`, `restore`, `resume`, and the calls of the objects they make. It is the builder of a cold machine: see [Sign on a Cold Machine](/apis/txbuilder/signing#sign-on-a-cold-machine). + +```tsx +import { TxBuilder } from "@meshsdk/core"; + +const cold = new TxBuilder({ network: "preprod" }); // reads and signs, builds nothing +``` + +## 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 sign, and build too when it has `params`. 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; +} +``` + +## Read a Transaction Blind + +A machine that only signs, a cold machine or a key service, may read a transaction from its bytes alone: `builder.fromCbor(tx, { blind: true })`. It asks no provider and reads no UTxO, so a builder with a network alone does it. It returns a `BlindTx`, not a `BuiltTx`. + +```tsx +import { keySigner, TxBuilder } from "@meshsdk/core"; + +const cold = new TxBuilder({ network: "preprod" }); // no provider, no parameters +const unseen = await cold.fromCbor(tx, { blind: true }); // with knownUtxos: INVALID_OPTION +const { outputs, fee, validity } = unseen; // what the bytes show +await unseen.sign({ signers: keySigner(coldKey) }); // signers are required: there is no payer +const next = unseen.partialTx; // to the next party, or unseen.submit() through a submitter +``` + +A `BlindTx` has `tx`, `txHash`, `network`, `fee`, `outputs`, `validity` and `redeemers`, the keys that signed (`signedKeyHashes`) and `partialTx`. It does not show what the inputs hold or whose they are, which keys must sign, or what is at stake as collateral. It has no `missing` and no `signedTx`. + +- `sign({ signers })` asks each signer with no list of keys (a wallet chooses its keys itself), and keeps every witness that verifies against the body, of a key the transaction does not need too. A witness the fee was not priced for makes the transaction larger than its fee pays for, and the node can refuse it. +- `addWitnesses`, `submit` and `awaitInclusion` work as on a `BuiltTx`. `submit()` sends `partialTx`, and the ledger judges whether a key is missing. +- It has no JSON, `restore` does not read it, and a plan or `after` refuses it with `INVALID_OPTION`. Read the transaction again from its `partialTx` when you need it again. +- The bytes are read within the size and form limits of [When fromCbor Refuses a Transaction](#when-fromcbor-refuses-a-transaction), `NETWORK_MISMATCH` applies, and a witness in them that does not verify against the body is `INVALID_WITNESS`. What needs the UTxOs (`NATIVE_SCRIPT_UNREAD`, the reference-script bound) is not checked. + +Read the transaction with `knownUtxos` where what the inputs hold matters, such as a transaction another party built for you to sign. For signing with it on a cold machine, see [Sign Without Looking](/apis/txbuilder/signing#sign-without-looking). + +## 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, several signers and a cold machine +- [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..46b2955 --- /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, and a builder with a `network` alone is made. With neither a `provider` nor `params`, it reads and signs only: `build()`, `plan()`, `chain()` and a plan's `add` and `replan` throw `MISSING_PARAMETER` at the call, since there are no built-in parameter values. See [A Builder with a Network Alone](/apis/txbuilder/offline#a-builder-with-a-network-alone). + +| 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; with no provider either, `MISSING_PARAMETER` at the call that needs them | +| `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](/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` | + +`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..3a5fb47 --- /dev/null +++ b/content/docs/apis/txbuilder/plans.mdx @@ -0,0 +1,262 @@ +--- +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. + +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. + +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), 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 | +| `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 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 +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(); +``` + +## 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. + +```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` | + +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: + +| 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) - 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/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..61e8eda --- /dev/null +++ b/content/docs/apis/txbuilder/signing.mdx @@ -0,0 +1,300 @@ +--- +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 +- `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 + +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 `new 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 + +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, a cold machine that runs Mesh needs only `new TxBuilder({ network: "preprod" })`: no provider and no parameters. It reads and signs, and it builds nothing: `build()`, `plan()` and `chain()` there throw `MISSING_PARAMETER`. Pick by what that machine can see: + +- [From the JSON of the Build](#from-the-json-of-the-build): it gets the record of the build, and sees its data. +- [With Mesh on the Cold Machine](#with-mesh-on-the-cold-machine): it gets the transaction and its UTxOs, and reads the transaction itself. +- [Sign Without Looking](#sign-without-looking): it gets the transaction alone, and signs it. +- [With a Signing Device](#with-a-signing-device): the key sits in a device that the building machine reaches. It signs the hash. +- [Without a Builder](#without-a-builder): a machine with no builder signs what it is given. + +A plan takes the ways that carry the transaction: `plan.step("main").tx` goes out, and `plan.addWitnesses(...)` takes back a witness set or a signed transaction. A plan's JSON goes to `resume`, not to `restore`. See [Plans](/apis/txbuilder/plans) and [Servers and Storage](/apis/txbuilder/servers#collect-signatures-over-several-days). + +### From the JSON of the Build + +`JSON.stringify(built)` holds the unsigned transaction with its data and the signatures so far. `restore` makes the same kind of object of it on the cold machine, and the cold key signs. + +```tsx +import { keySigner, TxBuilder } from "@meshsdk/core"; + +// On the building machine +const toCold = JSON.stringify(built); + +// On the cold machine +const cold = new TxBuilder({ network: "preprod" }); +const received = await cold.restore(JSON.parse(toCold)); +console.log(received.outputs, received.fee, received.missing); // read before you sign +await received.sign({ signers: keySigner(coldKey) }); // a restored object has no payer +const signed = received.partialTx; // goes back to the building machine + +// Back on the building machine +await built.addWitnesses(signed); +await built.submit(); +``` + +`restore` makes no request. It checks that `txHash` is the hash of the body and verifies every signature, and takes the rest of the record as written. So `outputs`, `fee` and `missing` are what your own building machine wrote. Use this for your own record. For a transaction another party built, read the bytes: [With Mesh on the Cold Machine](#with-mesh-on-the-cold-machine). + +### With Mesh on the Cold Machine + +Read the bytes there with `fromCbor`. 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. + +With no provider, `knownUtxos` must hold every UTxO the transaction names, else `MISSING_FETCHER`. + +```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" }); +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. + +### Sign Without Looking + +When the cold machine has only the transaction, not the UTxOs of its inputs, it can read the transaction blind. `fromCbor(tx, { blind: true })` reads the bytes alone, asks no provider and returns a `BlindTx`. + +```tsx +import { keySigner, TxBuilder } from "@meshsdk/core"; + +// On the cold machine: the transaction alone +const cold = new TxBuilder({ network: "preprod" }); +const unseen = await cold.fromCbor(tx, { blind: true }); +console.log(unseen.outputs, unseen.fee); // what the bytes show +await unseen.sign({ signers: keySigner(coldKey) }); // signers are required: there is no payer +console.log(unseen.signedKeyHashes); // the keys that signed +const signed = unseen.partialTx; // goes back to the building machine + +// Back on the building machine +await built.addWitnesses(signed); +await built.submit(); +``` + +> **Note:** A `BlindTx` shows nothing of what the inputs hold, whose they are or which keys must sign, so it cannot say what the transaction takes from you. It keeps every witness that verifies against the body, of a key the transaction does not need too, and a witness the fee was not priced for can make the node refuse the transaction. + +It shows `tx`, `txHash`, `fee`, `outputs`, `validity` and `redeemers`, which are those of the bytes you sign (`network` is the builder's), so read `outputs` and `fee` first. `sign()` asks each signer with no list of keys. `addWitnesses`, `submit` and `awaitInclusion` work as on a `BuiltTx`, but `submit()` sends `partialTx` unchecked: the ledger judges whether a key is missing. It has no JSON, `restore` does not read it, and a plan or `after` refuses it. With `knownUtxos` beside `blind: true`, `fromCbor` throws `INVALID_OPTION`: see [Read a Transaction Blind](/apis/txbuilder/offline#read-a-transaction-blind). + +### 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 && !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. The request also holds `tx`: pass it too, and the device can show what is paid. A `BlindTx` asks with no `keys`, so the function signs with what its device holds. + +### 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. + +```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 read a transaction built elsewhere, blind or not +- [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 e173400..fca3bb6 100644 --- a/content/docs/apis/txbuilder/smart-contracts.mdx +++ b/content/docs/apis/txbuilder/smart-contracts.mdx @@ -1,706 +1,182 @@ --- -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 - -## 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() +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. -Attach an inline datum to the output. - -```tsx -.txOutInlineDatumValue(datum: Data | object | string, type?: "Mesh" | "CBOR" | "JSON") -``` +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: -| Parameter | Type | Description | -|-----------|------|-------------| -| `datum` | `Data \| object \| string` | Datum value | -| `type` | `"Mesh" \| "CBOR" \| "JSON"` | Data format (default: "Mesh") | +- `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 -#### txOutDatumHashValue() +## Lock Assets at a Script -Attach a datum hash to the output (datum stored off-chain). +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 -.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() +import { mConStr0, output } from "@meshsdk/core"; -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) +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 | -|-----------|------|-------------| -| `txHash` | `string` | Transaction hash | -| `txIndex` | `number` | Output index | -| `amount` | `Asset[]` | Optional: Output amount | -| `address` | `string` | Optional: Output address | +## Spend from a Script -#### txInInlineDatumPresent() +Give `spend.plutus` the output, the script and a redeemer (the data you give the script when you spend). -Indicate that the input has an inline datum. +- 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: see [Choose the Collateral](/apis/txbuilder/utxos#choose-the-collateral). ```tsx -.txInInlineDatumPresent() -``` - -#### txInDatumValue() - -Provide the datum for the input (when not inline). +import { guard, mConStr0, spend } from "@meshsdk/core"; -```tsx -.txInDatumValue(datum: Data | object | string, type?: "Mesh" | "CBOR" | "JSON") +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 | -|-----------|------|-------------| -| `datum` | `Data \| object \| string` | Datum value | -| `type` | `"Mesh" \| "CBOR" \| "JSON"` | Data format (default: "Mesh") | - -#### txInRedeemerValue() - -Provide the redeemer for the script. +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 -.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. +import { mConStr0, output, spend } from "@meshsdk/core"; -```tsx -.txInScript(scriptCbor: string) +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 }, +); ``` -| 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 - -#### txInCollateral() +import { mConStr0, output, spend } from "@meshsdk/core"; -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 - -### Lock Assets in a Script +Minting works the same way: see [Mint and Burn Assets](/apis/txbuilder/minting#mint-with-a-reference-script). -Send assets to a script address with an inline datum: +## Read an Output by Reference -```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: +A reference input puts an output into the transaction without spending it: it has no redeemer, runs no script of its own, and stays where it is. A Plutus script sees it in its context among the reference inputs, with its address, value and datum, so it can read data published there, such as an oracle price or a configuration. That datum belongs to the reference input, not to the output being spent, which has its own. Of a reference script held there, the context shows only its hash, not the script. The rules for choosing one are in [Read an Output without Spending It](/apis/txbuilder/utxos#read-an-output-without-spending-it). ```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 +import { mConStr0, referenceInput, spend } from "@meshsdk/core"; -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 - -Reference scripts allow you to use a script stored on-chain, reducing transaction size and fees. +import { ForgeScript, spend } from "@meshsdk/core"; -#### 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](/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 { - 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 +- [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 +- [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..a60f48b 100644 --- a/content/docs/apis/txbuilder/staking.mdx +++ b/content/docs/apis/txbuilder/staking.mdx @@ -1,589 +1,149 @@ --- -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 +Staking uses two kinds of part, passed to `builder.build()`: -### registerStakeCertificate() +| 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 | -Register a stake address on the blockchain (required before first delegation). +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). -```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...) | +- `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 -### delegateStakeCertificate() +| 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 | -Delegate stake to a pool. +## Register and Delegate -```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. +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 -.deregisterStakeCertificate(rewardAddress: string) -``` +import { certificate } from "@meshsdk/core"; -| Parameter | Type | Description | -|-----------|------|-------------| -| `rewardAddress` | `string` | Bech32 reward address to deregister | - -### withdrawal() - -Withdraw staking rewards. - -```tsx -.withdrawal(rewardAddress: string, lovelace: string) +const built = await builder.build( + [ + certificate.stakeRegistration({ stake: rewardAddress }), + certificate.stakeDelegation({ stake: rewardAddress, pool: poolId }), + ], + { payer: wallet }, +); ``` -| 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: 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). -### 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 `keyDeposit`: see [Deposits](/apis/txbuilder/certificates#deposits). 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 | - -## Common Patterns +import { certificate, withdrawal } from "@meshsdk/core"; -### 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): +## Use a Script as the Stake Credential -```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}`); -``` +A stake address can be held by a Plutus script: -### 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: +- 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`. The rules are in [Who Signs](/apis/txbuilder/certificates#who-signs). +- 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`, which must then be a V3 script. -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, 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 { - 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 +- [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 +- [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..c3a0791 --- /dev/null +++ b/content/docs/apis/txbuilder/utxos.mdx @@ -0,0 +1,179 @@ +--- +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, 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 + +`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` puts an output into the transaction without spending it: a Plutus script sees its address, value and datum, and of its reference script only the hash. 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-an-output-by-reference). + +```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/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 bafcaf4..e05fc84 100644 --- a/data/links-txbuilders.ts +++ b/data/links-txbuilders.ts @@ -3,40 +3,118 @@ 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, 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`, 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 rewards and run 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 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", + 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 metaTxbuilderCookbook = { + link: `/apis/txbuilder/cookbook`, + title: "Cookbook", + desc: "Complete recipes to copy: pay, mint, lock, co-sign, run a server", +}; +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", + desc: "Move from the MeshTxBuilder chain to TxBuilder parts", }; export const linksTxbuilder = [ metaTxbuilderBasic, + metaTxbuilderSigning, + metaTxbuilderUtxos, + metaTxbuilderTime, metaTxbuilderMinting, metaTxbuilderSmartContract, metaTxbuilderStaking, + metaTxbuilderCertificates, metaTxbuilderGovernance, + metaTxbuilderPlans, + metaTxbuilderServers, + metaTxbuilderCookbook, + metaTxbuilderOffline, + metaTxbuilderTesting, + metaTxbuilderNetworks, + metaTxbuilderOptions, + metaTxbuilderErrors, + metaTxbuilderMigration, ]; 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,