@cardano-slips/flow 0.0.3 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +27 -0
  2. package/dist/address.d.ts +13 -0
  3. package/dist/address.d.ts.map +1 -0
  4. package/dist/address.js +54 -0
  5. package/dist/address.js.map +1 -0
  6. package/dist/balance-error.d.ts +48 -0
  7. package/dist/balance-error.d.ts.map +1 -0
  8. package/dist/balance-error.js +45 -0
  9. package/dist/balance-error.js.map +1 -0
  10. package/dist/balance.d.ts +54 -0
  11. package/dist/balance.d.ts.map +1 -0
  12. package/dist/balance.js +175 -0
  13. package/dist/balance.js.map +1 -0
  14. package/dist/cip30.d.ts +76 -0
  15. package/dist/cip30.d.ts.map +1 -0
  16. package/dist/cip30.js +69 -0
  17. package/dist/cip30.js.map +1 -0
  18. package/dist/complete-error.d.ts +50 -0
  19. package/dist/complete-error.d.ts.map +1 -0
  20. package/dist/complete-error.js +47 -0
  21. package/dist/complete-error.js.map +1 -0
  22. package/dist/complete.d.ts +58 -0
  23. package/dist/complete.d.ts.map +1 -0
  24. package/dist/complete.js +108 -0
  25. package/dist/complete.js.map +1 -0
  26. package/dist/connect.d.ts +45 -0
  27. package/dist/connect.d.ts.map +1 -0
  28. package/dist/connect.js +73 -0
  29. package/dist/connect.js.map +1 -0
  30. package/dist/discovery.d.ts +37 -0
  31. package/dist/discovery.d.ts.map +1 -0
  32. package/dist/discovery.js +71 -0
  33. package/dist/discovery.js.map +1 -0
  34. package/dist/index.d.ts +27 -7
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +15 -1
  37. package/dist/index.js.map +1 -1
  38. package/dist/registry.d.ts +18 -0
  39. package/dist/registry.d.ts.map +1 -0
  40. package/dist/registry.js +15 -0
  41. package/dist/registry.js.map +1 -0
  42. package/dist/resolve.d.ts +11 -0
  43. package/dist/resolve.d.ts.map +1 -0
  44. package/dist/resolve.js +21 -0
  45. package/dist/resolve.js.map +1 -0
  46. package/dist/sign-error.d.ts +62 -0
  47. package/dist/sign-error.d.ts.map +1 -0
  48. package/dist/sign-error.js +42 -0
  49. package/dist/sign-error.js.map +1 -0
  50. package/dist/sign.d.ts +38 -0
  51. package/dist/sign.d.ts.map +1 -0
  52. package/dist/sign.js +79 -0
  53. package/dist/sign.js.map +1 -0
  54. package/dist/tokens.css +133 -0
  55. package/dist/utxo.d.ts +16 -0
  56. package/dist/utxo.d.ts.map +1 -0
  57. package/dist/utxo.js +51 -0
  58. package/dist/utxo.js.map +1 -0
  59. package/dist/wallet-error.d.ts +48 -0
  60. package/dist/wallet-error.d.ts.map +1 -0
  61. package/dist/wallet-error.js +31 -0
  62. package/dist/wallet-error.js.map +1 -0
  63. package/dist/witness.d.ts +23 -0
  64. package/dist/witness.d.ts.map +1 -0
  65. package/dist/witness.js +101 -0
  66. package/dist/witness.js.map +1 -0
  67. package/package.json +10 -5
  68. package/src/address.ts +69 -0
  69. package/src/balance-error.ts +77 -0
  70. package/src/balance.ts +285 -0
  71. package/src/cip30.ts +113 -0
  72. package/src/complete-error.ts +83 -0
  73. package/src/complete.ts +198 -0
  74. package/src/connect.ts +136 -0
  75. package/src/discovery.ts +92 -0
  76. package/src/index.ts +37 -7
  77. package/src/registry.ts +32 -0
  78. package/src/resolve.ts +40 -0
  79. package/src/sign-error.ts +89 -0
  80. package/src/sign.ts +118 -0
  81. package/src/tokens.css +133 -0
  82. package/src/utxo.ts +70 -0
  83. package/src/wallet-error.ts +68 -0
  84. package/src/witness.ts +132 -0
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Display metadata for the wallets we know by name. Ours to maintain — the one
3
+ * cost ADR-0004 accepted — and deliberately thin: a key an entry does not cover
4
+ * still connects, using the name and icon the extension injects.
5
+ *
6
+ * `install` is the wallet's own home page rather than a store listing, because
7
+ * a store listing is per browser and goes stale on its own schedule.
8
+ */
9
+ export type KnownWallet = {
10
+ readonly key: string
11
+ readonly name: string
12
+ readonly install: string
13
+ /** A second key the same extension injects. Hidden while the primary is present. */
14
+ readonly aliasOf?: string
15
+ }
16
+
17
+ export const knownWallets: ReadonlyArray<KnownWallet> = [
18
+ { key: "lace", name: "Lace", install: "https://www.lace.io" },
19
+ { key: "eternl", name: "Eternl", install: "https://eternl.io" },
20
+ { key: "ccvault", name: "Eternl", install: "https://eternl.io", aliasOf: "eternl" },
21
+ { key: "vespr", name: "VESPR", install: "https://vespr.xyz" },
22
+ { key: "typhoncip30", name: "Typhon", install: "https://typhonwallet.io" },
23
+ { key: "nami", name: "Nami", install: "https://www.namiwallet.io" },
24
+ { key: "begin", name: "Begin", install: "https://begin.is" },
25
+ { key: "nufi", name: "NuFi", install: "https://nu.fi" },
26
+ { key: "gerowallet", name: "GeroWallet", install: "https://gerowallet.io" },
27
+ { key: "yoroi", name: "Yoroi", install: "https://yoroi-wallet.com" }
28
+ ]
29
+
30
+ const byKey = new Map(knownWallets.map((wallet) => [wallet.key, wallet]))
31
+
32
+ export const knownWallet = (key: string): KnownWallet | undefined => byKey.get(key)
package/src/resolve.ts ADDED
@@ -0,0 +1,40 @@
1
+ /**
2
+ * The wallet's own unspent outputs, in the form the verifier's derivation takes
3
+ * them. The engine is handed the value of every input the body spends because
4
+ * it never looks one up (invariant 1) — this is where the client, which does
5
+ * know, says so.
6
+ */
7
+ import type { MultiAsset, ResolvedInput } from "@cardano-slips/verifier"
8
+ import {
9
+ Address,
10
+ AssetName,
11
+ Assets,
12
+ MultiAsset as Multi,
13
+ PolicyId,
14
+ Schema,
15
+ TransactionHash
16
+ } from "@evolution-sdk/evolution"
17
+ import type { UTxO } from "@evolution-sdk/evolution"
18
+
19
+ const addressBytes = Schema.encodeSync(Address.FromBytes)
20
+
21
+ const multiAssetOf = (assets: Assets.Assets): MultiAsset => {
22
+ const held = Assets.getMultiAsset(assets)
23
+ if (held === undefined) return []
24
+ return Multi.getPolicyIds(held).map((policyId) => ({
25
+ policyId: PolicyId.toBytes(policyId),
26
+ assets: Multi.getAssetsByPolicy(held, policyId).map(([name, quantity]) => ({
27
+ name: AssetName.toBytes(name),
28
+ quantity
29
+ }))
30
+ }))
31
+ }
32
+
33
+ export const asResolvedInput = (utxo: UTxO.UTxO): ResolvedInput => ({
34
+ input: { transactionId: TransactionHash.toBytes(utxo.transactionId), index: utxo.index },
35
+ address: addressBytes(utxo.address),
36
+ value: { coin: Assets.lovelaceOf(utxo.assets), assets: multiAssetOf(utxo.assets) }
37
+ })
38
+
39
+ export const asResolvedInputs = (utxos: ReadonlyArray<UTxO.UTxO>): ReadonlyArray<ResolvedInput> =>
40
+ utxos.map(asResolvedInput)
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Why a transaction was not signed, or not submitted. One error, a closed set
3
+ * of refusals, because the client renders a state per refusal and a state
4
+ * nothing can produce is a screen nobody sees.
5
+ */
6
+ import { type ClientErrorCode } from "@cardano-slips/core"
7
+ import { Data } from "effect"
8
+
9
+ import { type Cip30ApiError } from "./cip30.js"
10
+
11
+ export type SignRefusal =
12
+ /** The bytes we hold are not a transaction these bytes can be read as. */
13
+ | "UnreadableTransaction"
14
+ /** This is not the body the effects were derived from, so nothing may be signed into it. */
15
+ | "WrongBody"
16
+ /** The person said no in the wallet. Not a fault. */
17
+ | "Declined"
18
+ /** The wallet tried to sign and could not, or rejected for a reason of its own. */
19
+ | "SignFailed"
20
+ /** What came back is not a witness set — a whole transaction included. */
21
+ | "UnreadableWitnesses"
22
+ /** The set carries script or datum material the body was never judged with. */
23
+ | "UnexpectedWitnessMaterial"
24
+ /** The set carries no signature, so assembling it would leave the transaction unsigned. */
25
+ | "NoWitnesses"
26
+ /** Submission failed because an input was spent between building and signing. */
27
+ | "InputsSpent"
28
+ /** The validity interval passed before the transaction reached the chain. */
29
+ | "IntervalPassed"
30
+ /** Submission failed for any other reason. */
31
+ | "SubmitFailed"
32
+ /** The wallet submitted, and named a transaction other than the one we assembled. */
33
+ | "WrongTransactionId"
34
+
35
+ /**
36
+ * Exhaustive by type: adding a refusal above without listing it here fails to
37
+ * compile, and `test/sign.test.ts` fails if any of them stops being reachable.
38
+ */
39
+ export const signRefusals: Readonly<Record<SignRefusal, true>> = {
40
+ UnreadableTransaction: true,
41
+ WrongBody: true,
42
+ Declined: true,
43
+ SignFailed: true,
44
+ UnreadableWitnesses: true,
45
+ UnexpectedWitnessMaterial: true,
46
+ NoWitnesses: true,
47
+ InputsSpent: true,
48
+ IntervalPassed: true,
49
+ SubmitFailed: true,
50
+ WrongTransactionId: true
51
+ }
52
+
53
+ /**
54
+ * Only the passed interval has a spec code, because only it is a failure of the
55
+ * exchange the spec describes — the intent outlived its own `validUntil`. The
56
+ * rest are states of a wallet or of the chain, and a protocol code on one of
57
+ * those would say the endpoint answered when nothing was ever asked of it
58
+ * (`wallet-error.ts` draws the same line).
59
+ */
60
+ export const slipErrorCodeFor = (refusal: SignRefusal): ClientErrorCode | undefined =>
61
+ refusal === "IntervalPassed" ? "INTENT_EXPIRED" : undefined
62
+
63
+ /** `cip30` is the wallet's own `{ code, info }`, kept so a decline stays distinguishable from a crash. */
64
+ export class SigningError extends Data.TaggedError("SigningError")<{
65
+ readonly refusal: SignRefusal
66
+ readonly detail: string
67
+ readonly cip30?: Cip30ApiError
68
+ readonly cause?: unknown
69
+ }> {
70
+ override get message(): string {
71
+ return this.detail
72
+ }
73
+
74
+ get code(): ClientErrorCode | undefined {
75
+ return slipErrorCodeFor(this.refusal)
76
+ }
77
+ }
78
+
79
+ export const refuse = (
80
+ refusal: SignRefusal,
81
+ detail: string,
82
+ extra: { readonly cip30?: Cip30ApiError; readonly cause?: unknown } = {}
83
+ ): SigningError =>
84
+ new SigningError({
85
+ refusal,
86
+ detail,
87
+ ...(extra.cip30 === undefined ? {} : { cip30: extra.cip30 }),
88
+ ...(extra.cause === undefined ? {} : { cause: extra.cause })
89
+ })
package/src/sign.ts ADDED
@@ -0,0 +1,118 @@
1
+ /**
2
+ * `signTx` → witness assembly → `submitTx`. CIP-30 returns a **witness set**,
3
+ * never a signed transaction (invariant 4), so the body a person was shown and
4
+ * the body that reaches the chain are joined here or nowhere.
5
+ */
6
+ import { Effect } from "effect"
7
+
8
+ import { type CborHex, type Cip30Api, readApiError, REFUSED, USER_DECLINED } from "./cip30.js"
9
+ import { refuse, type SigningError } from "./sign-error.js"
10
+ import { assembleWitnesses, requireSameBody } from "./witness.js"
11
+
12
+ export type SignRequest = {
13
+ readonly api: Cip30Api
14
+ /** The complete unsigned transaction. */
15
+ readonly transaction: CborHex
16
+ /**
17
+ * The id of the body the effects were derived from, from `transactionIdOf`.
18
+ * Required, not derived here: a signature is bound to the body a person was
19
+ * shown, and a function that recomputed the id from the bytes in front of it
20
+ * would bind it to whatever it was handed.
21
+ */
22
+ readonly transactionId: string
23
+ }
24
+
25
+ export type SignedTransaction = {
26
+ /** The body with the witnesses in it: what `submitTx` takes. */
27
+ readonly cbor: CborHex
28
+ /** Unchanged by signing, because witnesses live outside the body. */
29
+ readonly transactionId: string
30
+ }
31
+
32
+ /** What the wallet said, kept whole so a message names its own cause. */
33
+ const said = (cause: unknown): string => {
34
+ const error = readApiError(cause)
35
+ if (error === undefined) return String(cause)
36
+ return error.info === "" ? `code ${error.code}` : error.info
37
+ }
38
+
39
+ /**
40
+ * Signs, or says why not. Nothing is asked of the wallet until the transaction
41
+ * is known to be the one the effects were derived from.
42
+ */
43
+ export const signTransaction = ({
44
+ api,
45
+ transaction,
46
+ transactionId
47
+ }: SignRequest): Effect.Effect<SignedTransaction, SigningError> =>
48
+ Effect.gen(function* () {
49
+ yield* requireSameBody(transaction, transactionId)
50
+
51
+ const witnesses = yield* Effect.tryPromise({
52
+ // `partialSign: true`: the wallet signs what it holds keys for and leaves
53
+ // the rest, rather than refusing a transaction a co-signer completes.
54
+ try: () => api.signTx(transaction, true),
55
+ catch: (cause) => {
56
+ const error = readApiError(cause)
57
+ // `-3` is `APIError`'s refusal, which wallets send from `signTx` in
58
+ // practice even though CIP-30 numbers a decline `2` here.
59
+ if (error?.code === USER_DECLINED || error?.code === REFUSED) {
60
+ return refuse("Declined", "The signature was declined in the wallet.", { cip30: error, cause })
61
+ }
62
+ return refuse("SignFailed", `The wallet could not sign this transaction: ${said(cause)}`, {
63
+ ...(error === undefined ? {} : { cip30: error }),
64
+ cause
65
+ })
66
+ }
67
+ })
68
+
69
+ const cbor = yield* assembleWitnesses(transaction, witnesses, transactionId)
70
+ return { cbor, transactionId }
71
+ })
72
+
73
+ /** The ledger's own name for an input that is no longer there — what the rebuild path watches for. */
74
+ const spentInputs = /BadInputsUTxO/i
75
+
76
+ /** The ledger's name for a transaction that arrived outside its validity interval. */
77
+ const outsideInterval = /OutsideValidityInterval/i
78
+
79
+ const submissionFailure = (cause: unknown): SigningError => {
80
+ const error = readApiError(cause)
81
+ const detail = said(cause)
82
+ const extra = { ...(error === undefined ? {} : { cip30: error }), cause }
83
+
84
+ if (spentInputs.test(detail)) {
85
+ return refuse("InputsSpent", "The wallet's funds moved before this transaction reached the chain.", extra)
86
+ }
87
+ if (outsideInterval.test(detail)) {
88
+ return refuse("IntervalPassed", "This transaction expired before it reached the chain.", extra)
89
+ }
90
+ return refuse("SubmitFailed", `This transaction was not accepted: ${detail}`, extra)
91
+ }
92
+
93
+ /**
94
+ * Submits, and holds the wallet to the transaction it was given: an id other
95
+ * than the one we assembled is a receipt for something else, and showing it
96
+ * would tell a person their transaction is on the chain when another one is.
97
+ */
98
+ export const submitTransaction = (api: Cip30Api, signed: SignedTransaction): Effect.Effect<string, SigningError> =>
99
+ Effect.gen(function* () {
100
+ const returned = yield* Effect.tryPromise({
101
+ try: () => api.submitTx(signed.cbor),
102
+ catch: submissionFailure
103
+ })
104
+
105
+ // Typed to answer with the id and under no obligation to: reading a method
106
+ // off whatever it did answer would reach a person as a stack trace.
107
+ if (typeof returned !== "string") {
108
+ return yield* Effect.fail(refuse("WrongTransactionId", "The wallet did not name the transaction it submitted."))
109
+ }
110
+
111
+ if (returned.toLowerCase() !== signed.transactionId.toLowerCase()) {
112
+ return yield* Effect.fail(
113
+ refuse("WrongTransactionId", "The wallet submitted a different transaction from the one it was given.")
114
+ )
115
+ }
116
+
117
+ return signed.transactionId
118
+ })
package/src/tokens.css ADDED
@@ -0,0 +1,133 @@
1
+ /*
2
+ * Every colour, type role, step of spacing and radius the client uses, taken
3
+ * from `1 · Tokens` on the design sheet. This is the only file in the package
4
+ * that writes a colour — `test/no-hard-coded-colours.test.ts` fails if another
5
+ * one does, and `test/tokens.test.ts` re-runs the contrast audit against these
6
+ * values rather than trusting the numbers printed on the sheet.
7
+ *
8
+ * Scoped to a class, never `:root`: this ships into pages we do not own, and a
9
+ * package that writes tokens onto the document redefines whatever the host
10
+ * already called `--ink`. Put `slip-root` on the element that wraps the Slip.
11
+ *
12
+ * There is no reset here and no rule that selects an element. Nothing sets a
13
+ * font-family on anything — a component reads `var(--font-text)` — so a host
14
+ * page's own stack stays where it is until something of ours asks for a token.
15
+ *
16
+ * One theme. The sheet collapsed an earlier light/dark pair into a single
17
+ * ground that leans light, so there is no `data-theme` and no role that means
18
+ * two things. What carries the weight instead is that the three surface
19
+ * families are genuinely different surfaces:
20
+ *
21
+ * page / card the ordinary ground, and what lifts off it
22
+ * vault-* the transaction preview, on slate — the one grave surface,
23
+ * and the reason the rest can stay bright
24
+ * dark-* code blocks and the Open Graph card, fixed wherever they
25
+ * appear because neither sits on a ground we control
26
+ */
27
+
28
+ .slip-root {
29
+ color-scheme: light;
30
+
31
+ /* Surfaces. Depth is a border, never a shadow: there is no shadow token. */
32
+ --page: #ebeef8; /* never pure white */
33
+ --card: #fcfdff;
34
+ --subtle: rgba(90, 110, 205, 0.09); /* hover, chips */
35
+ --skeleton: rgba(90, 110, 205, 0.14);
36
+ --border: rgba(20, 26, 40, 0.13);
37
+ --divider: rgba(20, 26, 40, 0.1);
38
+
39
+ /* Ink */
40
+ --ink: #141a26;
41
+ --muted: #56628a;
42
+
43
+ /*
44
+ * The split rule: --accent-fill is a fill and never carries text below 24px.
45
+ * An accent-coloured word uses --accent-text. It clears AA on the vault and
46
+ * is still held to fills there, because the rule is about what the colour is
47
+ * for and not about the ratio it happens to reach.
48
+ */
49
+ --accent-fill: #728ef3;
50
+ --accent-text: #2f4bc4; /* links */
51
+ --accent-action: #4361e8; /* button background */
52
+ --accent-hover: #2f4bc4;
53
+ --accent-deep: #0c288d; /* headings */
54
+ --on-accent: #ffffff; /* anything drawn on --accent-action */
55
+ --focus: #4361e8;
56
+
57
+ /* Semantic, and rare. A page that colours everything says nothing. */
58
+ --pos: #1f7a5c; /* positive, refundable */
59
+ --warn: #8c5a12;
60
+ --bad: #b3261e;
61
+ --bad-tint: rgba(179, 38, 30, 0.06);
62
+ --bad-line: rgba(179, 38, 30, 0.24);
63
+ --warn-tint: rgba(233, 180, 76, 0.16);
64
+ --warn-line: rgba(233, 180, 76, 0.5);
65
+
66
+ /* The alternating rows of the effects list, on and off. */
67
+ --stripe-a: rgba(90, 110, 205, 0.16);
68
+ --stripe-b: rgba(90, 110, 205, 0.05);
69
+ --stripe-off-a: rgba(86, 98, 138, 0.12);
70
+ --stripe-off-b: rgba(86, 98, 138, 0.04);
71
+
72
+ /*
73
+ * The transaction preview. Its own family because it is the surface that
74
+ * judges the publisher, and `13 · Chrome rules` fixes it whoever hosts the
75
+ * page. Slate rather than black: it has to read as a distinct surface, not
76
+ * as a hole in the page.
77
+ */
78
+ --vault: #222b3d;
79
+ --vault-ink: #f5f7ff;
80
+ --vault-muted: #c3cdec;
81
+ --vault-surface: rgba(255, 255, 255, 0.09);
82
+ --vault-border: rgba(255, 255, 255, 0.16);
83
+ --vault-chip: rgba(168, 188, 255, 0.22);
84
+ --vault-rule: rgba(168, 188, 255, 0.7);
85
+ --vault-pos: #5fd1a6;
86
+ --vault-warn: #e9b44c;
87
+ --vault-bad: #ffa39b;
88
+ --vault-bad-tint: rgba(255, 163, 155, 0.1);
89
+ --vault-bad-line: rgba(255, 163, 155, 0.45);
90
+ --vault-bad-chip: rgba(255, 163, 155, 0.18);
91
+ --vault-warn-tint: rgba(233, 180, 76, 0.12);
92
+ --vault-warn-line: rgba(233, 180, 76, 0.5);
93
+
94
+ /*
95
+ * Code blocks in the docs and the Open Graph card. Both land on a ground we
96
+ * do not control — a reader's docs theme, someone else's timeline — so they
97
+ * carry their own and do not follow anything.
98
+ */
99
+ --dark-bg: #121721;
100
+ --dark-surface: rgba(255, 255, 255, 0.08);
101
+ --dark-text: #ffffff;
102
+ --dark-muted: #ccd6ff;
103
+
104
+ /* Type. Each stack ends in a generic family, so a missing webfont degrades. */
105
+ --font-display: Poppins, system-ui, sans-serif;
106
+ --font-text: Figtree, system-ui, sans-serif;
107
+ --font-mono: "IBM Plex Mono", ui-monospace, monospace;
108
+
109
+ /* Whole roles, so half a role cannot be applied without the other half. */
110
+ --type-h1: 700 44px/48px var(--font-display);
111
+ --type-h1-tracking: -0.01em;
112
+ --type-card-title: 700 18px/24px var(--font-display);
113
+ --type-numeral: 700 26px/32px var(--font-display); /* a figure is always Poppins 700 */
114
+ --type-body: 500 16px/24px var(--font-text);
115
+ --type-button: 500 14px/20px var(--font-text);
116
+ --type-button-tracking: 0.1px;
117
+ --type-label: 500 13px var(--font-text);
118
+ --type-mono: 400 12px/20px var(--font-mono); /* addresses, hashes, the tx block */
119
+
120
+ /* Spacing, on a 4px base. */
121
+ --space-4: 4px;
122
+ --space-8: 8px;
123
+ --space-12: 12px;
124
+ --space-16: 16px;
125
+ --space-20: 20px;
126
+ --space-24: 24px;
127
+ --space-32: 32px;
128
+ --space-48: 48px;
129
+
130
+ --radius-chip: 6px;
131
+ --radius-control: 8px;
132
+ --radius-card: 12px;
133
+ }
package/src/utxo.ts ADDED
@@ -0,0 +1,70 @@
1
+ /**
2
+ * CIP-30 hands unspent outputs back as CBOR hex; evolution-sdk's builder takes
3
+ * them typed. The SDK has this conversion — `cip30UtxoFromCBORHex` — but only
4
+ * behind an export path its manifest blocks, so it is the sixth gap of ADR-0004
5
+ * and belongs upstream rather than here.
6
+ */
7
+ import {
8
+ Address,
9
+ AddressEras,
10
+ Assets,
11
+ CBOR,
12
+ Schema,
13
+ Script,
14
+ TransactionInput,
15
+ TransactionOutput,
16
+ UTxO
17
+ } from "@evolution-sdk/evolution"
18
+ import { Either } from "effect"
19
+
20
+ import type { CborHex } from "./cip30.js"
21
+
22
+ /** The output's address is era-tagged and a UTxO's is not; the bytes are the same. */
23
+ const toAddressStructure = (tagged: AddressEras.AddressEras): Address.Address =>
24
+ Schema.decodeSync(Address.FromBytes)(Schema.encodeSync(AddressEras.FromBytes)(tagged))
25
+
26
+ const readOne = (hex: CborHex): UTxO.UTxO => {
27
+ const decoded = CBOR.fromCBORHex(hex)
28
+ if (!Array.isArray(decoded) || decoded.length !== 2) {
29
+ throw new Error("a CIP-30 unspent output is an input and an output, and this is neither")
30
+ }
31
+ const input = TransactionInput.fromCBORBytes(CBOR.toCBORBytes(decoded[0]))
32
+ const output = TransactionOutput.fromCBORBytes(CBOR.toCBORBytes(decoded[1]))
33
+ const amount = output.amount
34
+
35
+ return new UTxO.UTxO({
36
+ transactionId: input.transactionId,
37
+ index: input.index,
38
+ address: toAddressStructure(output.address),
39
+ assets:
40
+ amount._tag === "WithAssets"
41
+ ? Assets.withMultiAsset(amount.coin, amount.assets)
42
+ : Assets.fromLovelace(amount.coin),
43
+ // A Babbage output carries a datum option and a script; a Shelley one carries
44
+ // a datum hash, which is itself a valid datum option.
45
+ datumOption: output._tag === "BabbageTransactionOutput" ? output.datumOption : output.datumHash,
46
+ scriptRef:
47
+ output._tag === "BabbageTransactionOutput" && output.scriptRef
48
+ ? Script.fromCBOR(output.scriptRef.bytes)
49
+ : undefined
50
+ })
51
+ }
52
+
53
+ /**
54
+ * Reads what `getUtxos` returned. `Either` and not a throw: this runs on
55
+ * whatever a browser extension chose to send, and one unreadable entry must
56
+ * not take the page down.
57
+ */
58
+ export const readWalletUtxos = (hexes: ReadonlyArray<CborHex>): Either.Either<ReadonlyArray<UTxO.UTxO>, string> => {
59
+ const utxos: Array<UTxO.UTxO> = []
60
+ for (const [index, hex] of hexes.entries()) {
61
+ try {
62
+ utxos.push(readOne(hex))
63
+ } catch (cause) {
64
+ return Either.left(
65
+ `unspent output ${index} could not be read: ${cause instanceof Error ? cause.message : String(cause)}`
66
+ )
67
+ }
68
+ }
69
+ return Either.right(utxos)
70
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Why a wallet did not reach a usable connection. One error, a closed set of
3
+ * refusals, because the client renders a state per refusal and a state nothing
4
+ * can produce is a screen nobody sees.
5
+ */
6
+ import { type ClientErrorCode } from "@cardano-slips/core"
7
+ import { Data } from "effect"
8
+
9
+ import { type Cip30ApiError } from "./cip30.js"
10
+
11
+ export type ConnectRefusal =
12
+ /** Nothing is injected under this key. The wallet was uninstalled, or never there. */
13
+ | "NotInjected"
14
+ /** Something is under the key that does not implement the connector. */
15
+ | "NotCip30"
16
+ /** The person declined the connection — CIP-30 `APIError` `-3`. Not a fault. */
17
+ | "Refused"
18
+ /** `enable()` rejected for another reason, or returned something that is not the API. */
19
+ | "EnableFailed"
20
+ /** A question the wallet did not answer, or answered with something that is not what it claims. */
21
+ | "Unreadable"
22
+ /** The wallet is on a different network from the one the Slip declares. */
23
+ | "WrongNetwork"
24
+
25
+ /**
26
+ * Exhaustive by type: adding a refusal above without listing it here fails to
27
+ * compile, and `test/connect.test.ts` fails if any of them stops being reachable.
28
+ */
29
+ export const connectRefusals: Readonly<Record<ConnectRefusal, true>> = {
30
+ NotInjected: true,
31
+ NotCip30: true,
32
+ Refused: true,
33
+ EnableFailed: true,
34
+ Unreadable: true,
35
+ WrongNetwork: true
36
+ }
37
+
38
+ /**
39
+ * Only the network disagreement has a spec code, because only it is a failure
40
+ * of the exchange the spec describes. The rest are states of a browser
41
+ * extension, and dressing them in a protocol code would say the endpoint
42
+ * answered when nothing was ever sent.
43
+ */
44
+ export const slipErrorCodeFor = (refusal: ConnectRefusal): ClientErrorCode | undefined =>
45
+ refusal === "WrongNetwork" ? "WRONG_NETWORK" : undefined
46
+
47
+ /** `cip30` is the wallet's own `{ code, info }`, kept so a `-3` stays distinguishable from a crash. */
48
+ export class WalletConnectError extends Data.TaggedError("WalletConnectError")<{
49
+ readonly refusal: ConnectRefusal
50
+ readonly key: string
51
+ readonly detail: string
52
+ readonly cip30?: Cip30ApiError
53
+ }> {
54
+ override get message(): string {
55
+ return `${this.key}: ${this.detail}`
56
+ }
57
+
58
+ get code(): ClientErrorCode | undefined {
59
+ return slipErrorCodeFor(this.refusal)
60
+ }
61
+ }
62
+
63
+ export const refuse = (
64
+ refusal: ConnectRefusal,
65
+ key: string,
66
+ detail: string,
67
+ cip30?: Cip30ApiError
68
+ ): WalletConnectError => new WalletConnectError({ refusal, key, detail, ...(cip30 === undefined ? {} : { cip30 }) })
package/src/witness.ts ADDED
@@ -0,0 +1,132 @@
1
+ /**
2
+ * The transaction id, and the witnesses that may go into the body it names.
3
+ * Pure: nothing here talks to a wallet, so what assembly accepts can be stated
4
+ * as a rule rather than observed against an extension.
5
+ */
6
+ import { extractTransactionBody } from "@cardano-slips/verifier"
7
+ import { Transaction, TransactionWitnessSet } from "@evolution-sdk/evolution"
8
+ import { blake2b } from "@noble/hashes/blake2.js"
9
+ import { Effect, Either } from "effect"
10
+
11
+ import type { CborHex } from "./cip30.js"
12
+ import { refuse, type SigningError } from "./sign-error.js"
13
+
14
+ const hex = /^[0-9a-fA-F]*$/
15
+
16
+ const bytesOf = (value: CborHex): Uint8Array | undefined => {
17
+ if (value.length % 2 !== 0 || !hex.test(value)) return undefined
18
+ return Uint8Array.from({ length: value.length / 2 }, (_, index) =>
19
+ Number.parseInt(value.slice(index * 2, index * 2 + 2), 16)
20
+ )
21
+ }
22
+
23
+ const toHex = (bytes: Uint8Array): string => Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("")
24
+
25
+ /**
26
+ * BLAKE2b-256 over the body's original bytes, never a re-encode: this is the id
27
+ * the chain computes, and it is CIP-0186's commit — what binds a returned
28
+ * witness set to the body whose effects a person was shown.
29
+ */
30
+ export const transactionIdOf = (transaction: CborHex): Effect.Effect<string, SigningError> => {
31
+ const bytes = bytesOf(transaction)
32
+ if (bytes === undefined) {
33
+ return Effect.fail(refuse("UnreadableTransaction", "This transaction is not readable as CBOR."))
34
+ }
35
+ const body = extractTransactionBody(bytes)
36
+ if (Either.isLeft(body)) {
37
+ return Effect.fail(
38
+ refuse("UnreadableTransaction", `This transaction is not readable: ${body.left.message}`, { cause: body.left })
39
+ )
40
+ }
41
+ return Effect.succeed(toHex(blake2b(body.right.bodyBytes, { dkLen: 32 })))
42
+ }
43
+
44
+ /**
45
+ * What a version 1 transaction is never signed with. We build nothing that
46
+ * spends from a script, so any of these in a returned set is material the body
47
+ * was not judged with, and merging it would let a wallet add to a transaction
48
+ * after the moment it was shown.
49
+ */
50
+ const unexpected = (set: TransactionWitnessSet.TransactionWitnessSet): string | undefined => {
51
+ if ((set.nativeScripts ?? []).length > 0) return "native scripts"
52
+ if ((set.bootstrapWitnesses ?? []).length > 0) return "bootstrap witnesses"
53
+ if ((set.plutusV1Scripts ?? []).length > 0) return "Plutus v1 scripts"
54
+ if ((set.plutusV2Scripts ?? []).length > 0) return "Plutus v2 scripts"
55
+ if ((set.plutusV3Scripts ?? []).length > 0) return "Plutus v3 scripts"
56
+ if ((set.plutusData ?? []).length > 0) return "datums"
57
+ if (set.redeemers !== undefined) return "redeemers"
58
+ return undefined
59
+ }
60
+
61
+ const readWitnessSet = (witnesses: CborHex): Effect.Effect<TransactionWitnessSet.TransactionWitnessSet, SigningError> =>
62
+ Effect.try({
63
+ try: () => TransactionWitnessSet.fromCBORHex(witnesses),
64
+ catch: (cause) =>
65
+ refuse("UnreadableWitnesses", "The wallet answered with something that is not a witness set.", { cause })
66
+ })
67
+
68
+ /**
69
+ * Refuses unless this is the body the effects were derived from. Asked twice —
70
+ * before the wallet is given anything, and again as assembly begins — because
71
+ * either moment is one where the transaction can stop being the one on screen.
72
+ */
73
+ export const requireSameBody = (transaction: CborHex, transactionId: string): Effect.Effect<void, SigningError> =>
74
+ Effect.flatMap(transactionIdOf(transaction), (held) =>
75
+ held === transactionId
76
+ ? Effect.void
77
+ : Effect.fail(
78
+ refuse("WrongBody", "This is not the transaction the effects were derived from, so it will not be signed.")
79
+ )
80
+ )
81
+
82
+ /**
83
+ * Appends a returned witness set to the body it was asked for, or says why not.
84
+ * `transactionId` is the id the effects were derived from: witnesses go into
85
+ * that body or into none, which is what makes what a person was shown the thing
86
+ * they signed.
87
+ */
88
+ export const assembleWitnesses = (
89
+ transaction: CborHex,
90
+ witnesses: CborHex,
91
+ transactionId: string
92
+ ): Effect.Effect<CborHex, SigningError> =>
93
+ Effect.gen(function* () {
94
+ yield* requireSameBody(transaction, transactionId)
95
+
96
+ const set = yield* readWitnessSet(witnesses)
97
+
98
+ const material = unexpected(set)
99
+ if (material !== undefined) {
100
+ return yield* Effect.fail(
101
+ refuse(
102
+ "UnexpectedWitnessMaterial",
103
+ `The wallet answered with ${material}, which this transaction never asked for.`
104
+ )
105
+ )
106
+ }
107
+
108
+ // evolution-sdk returns the transaction untouched for an empty set, so
109
+ // without this an unsigned transaction would go to `submitTx` looking signed.
110
+ if ((set.vkeyWitnesses ?? []).length === 0) {
111
+ return yield* Effect.fail(refuse("NoWitnesses", "The wallet answered without a signature."))
112
+ }
113
+
114
+ // Appends to `vkeyWitnesses` and re-encodes from the format the transaction
115
+ // arrived in, so a co-signer's witness survives and the body keeps its bytes.
116
+ const assembled = yield* Effect.try({
117
+ try: () => Transaction.addVKeyWitnessesHex(transaction, witnesses),
118
+ catch: (cause) =>
119
+ refuse("UnreadableWitnesses", "The wallet's witnesses could not be assembled into the transaction.", { cause })
120
+ })
121
+
122
+ // The body is what the id is taken over, so an id that moved means the
123
+ // bytes moved — and the person would be signing something else.
124
+ const after = yield* transactionIdOf(assembled)
125
+ if (after !== transactionId) {
126
+ return yield* Effect.fail(
127
+ refuse("WrongBody", "Assembling the signature changed the transaction, so it will not be submitted.")
128
+ )
129
+ }
130
+
131
+ return assembled
132
+ })