@cardano-slips/flow 0.1.0 → 0.3.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 (113) hide show
  1. package/README.md +53 -9
  2. package/dist/address.d.ts +12 -0
  3. package/dist/address.d.ts.map +1 -1
  4. package/dist/address.js +43 -0
  5. package/dist/address.js.map +1 -1
  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/card.css +492 -0
  15. package/dist/card.d.ts +41 -0
  16. package/dist/card.d.ts.map +1 -0
  17. package/dist/card.js +69 -0
  18. package/dist/card.js.map +1 -0
  19. package/dist/cip30.d.ts +10 -0
  20. package/dist/cip30.d.ts.map +1 -1
  21. package/dist/cip30.js +16 -0
  22. package/dist/cip30.js.map +1 -1
  23. package/dist/complete-error.d.ts +57 -0
  24. package/dist/complete-error.d.ts.map +1 -0
  25. package/dist/complete-error.js +52 -0
  26. package/dist/complete-error.js.map +1 -0
  27. package/dist/complete.d.ts +77 -0
  28. package/dist/complete.d.ts.map +1 -0
  29. package/dist/complete.js +182 -0
  30. package/dist/complete.js.map +1 -0
  31. package/dist/derived.d.ts +8 -0
  32. package/dist/derived.d.ts.map +1 -0
  33. package/dist/derived.js +2 -0
  34. package/dist/derived.js.map +1 -0
  35. package/dist/effects-panel.d.ts +37 -0
  36. package/dist/effects-panel.d.ts.map +1 -0
  37. package/dist/effects-panel.js +64 -0
  38. package/dist/effects-panel.js.map +1 -0
  39. package/dist/effects.css +629 -0
  40. package/dist/exchange.d.ts +54 -0
  41. package/dist/exchange.d.ts.map +1 -0
  42. package/dist/exchange.js +136 -0
  43. package/dist/exchange.js.map +1 -0
  44. package/dist/explain.d.ts +39 -0
  45. package/dist/explain.d.ts.map +1 -0
  46. package/dist/explain.js +172 -0
  47. package/dist/explain.js.map +1 -0
  48. package/dist/index.d.ts +34 -3
  49. package/dist/index.d.ts.map +1 -1
  50. package/dist/index.js +19 -2
  51. package/dist/index.js.map +1 -1
  52. package/dist/ledger.d.ts +74 -0
  53. package/dist/ledger.d.ts.map +1 -0
  54. package/dist/ledger.js +402 -0
  55. package/dist/ledger.js.map +1 -0
  56. package/dist/outcome-panel.d.ts +63 -0
  57. package/dist/outcome-panel.d.ts.map +1 -0
  58. package/dist/outcome-panel.js +40 -0
  59. package/dist/outcome-panel.js.map +1 -0
  60. package/dist/parameter-form.d.ts +26 -0
  61. package/dist/parameter-form.d.ts.map +1 -0
  62. package/dist/parameter-form.js +42 -0
  63. package/dist/parameter-form.js.map +1 -0
  64. package/dist/resolve.d.ts +11 -0
  65. package/dist/resolve.d.ts.map +1 -0
  66. package/dist/resolve.js +21 -0
  67. package/dist/resolve.js.map +1 -0
  68. package/dist/sign-error.d.ts +62 -0
  69. package/dist/sign-error.d.ts.map +1 -0
  70. package/dist/sign-error.js +42 -0
  71. package/dist/sign-error.js.map +1 -0
  72. package/dist/sign.d.ts +38 -0
  73. package/dist/sign.d.ts.map +1 -0
  74. package/dist/sign.js +79 -0
  75. package/dist/sign.js.map +1 -0
  76. package/dist/slip-card.d.ts +55 -0
  77. package/dist/slip-card.d.ts.map +1 -0
  78. package/dist/slip-card.js +89 -0
  79. package/dist/slip-card.js.map +1 -0
  80. package/dist/tokens.css +97 -123
  81. package/dist/utxo.d.ts +16 -0
  82. package/dist/utxo.d.ts.map +1 -0
  83. package/dist/utxo.js +51 -0
  84. package/dist/utxo.js.map +1 -0
  85. package/dist/witness.d.ts +23 -0
  86. package/dist/witness.d.ts.map +1 -0
  87. package/dist/witness.js +101 -0
  88. package/dist/witness.js.map +1 -0
  89. package/package.json +13 -6
  90. package/src/address.ts +53 -0
  91. package/src/balance-error.ts +77 -0
  92. package/src/balance.ts +285 -0
  93. package/src/card.css +492 -0
  94. package/src/card.ts +86 -0
  95. package/src/cip30.ts +19 -0
  96. package/src/complete-error.ts +95 -0
  97. package/src/complete.ts +307 -0
  98. package/src/derived.ts +8 -0
  99. package/src/effects-panel.tsx +386 -0
  100. package/src/effects.css +629 -0
  101. package/src/exchange.ts +212 -0
  102. package/src/explain.ts +211 -0
  103. package/src/index.ts +64 -3
  104. package/src/ledger.ts +503 -0
  105. package/src/outcome-panel.tsx +263 -0
  106. package/src/parameter-form.tsx +138 -0
  107. package/src/resolve.ts +40 -0
  108. package/src/sign-error.ts +89 -0
  109. package/src/sign.ts +118 -0
  110. package/src/slip-card.tsx +244 -0
  111. package/src/tokens.css +97 -123
  112. package/src/utxo.ts +70 -0
  113. package/src/witness.ts +132 -0
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Why an intent did not become a transaction. Every refusal carries a spec
3
+ * error code, because each one is a failure of the exchange the spec describes
4
+ * rather than a state of a browser extension (`wallet-error.ts` is the other
5
+ * half, and deliberately has refusals that carry no code).
6
+ */
7
+ import { type ClientErrorCode } from "@cardano-slips/core"
8
+ import { Data } from "effect"
9
+
10
+ export type BalanceRefusal =
11
+ /** `validUntil` has already passed. A fresh POST returns a fresh intent. */
12
+ | "IntentExpired"
13
+ /** An address in the intent encodes a different network from the Slip's. */
14
+ | "ForeignAddress"
15
+ /** A certificate or withdrawal needs the wallet's stake credential and the address carries none. */
16
+ | "NoStakeCredential"
17
+ /** The change address the wallet gave is not an address these bytes can be read as. */
18
+ | "UnreadableChangeAddress"
19
+ /** The intent withdraws rewards and nobody said what the reward balance is. */
20
+ | "RewardBalanceUnknown"
21
+ /** The wallet cannot cover the intent, the minimum ADA its outputs require, and the fee. */
22
+ | "InsufficientFunds"
23
+ /** The intent cannot be built into a valid transaction for any other reason. */
24
+ | "CannotBalance"
25
+
26
+ /**
27
+ * Exhaustive by type: adding a refusal above without listing it here fails to
28
+ * compile, and `test/balance.test.ts` fails if any of them stops being reachable.
29
+ */
30
+ export const balanceRefusals: Readonly<Record<BalanceRefusal, true>> = {
31
+ IntentExpired: true,
32
+ ForeignAddress: true,
33
+ NoStakeCredential: true,
34
+ UnreadableChangeAddress: true,
35
+ RewardBalanceUnknown: true,
36
+ InsufficientFunds: true,
37
+ CannotBalance: true
38
+ }
39
+
40
+ /**
41
+ * A wrong-network address is `MALFORMED_RESPONSE` and not `WRONG_NETWORK`:
42
+ * the latter is a disagreement the person can act on by switching wallets, and
43
+ * an endpoint that sent an address on another chain is not one of those.
44
+ */
45
+ export const slipErrorCodeFor = (refusal: BalanceRefusal): ClientErrorCode => {
46
+ switch (refusal) {
47
+ case "IntentExpired":
48
+ return "INTENT_EXPIRED"
49
+ case "ForeignAddress":
50
+ return "MALFORMED_RESPONSE"
51
+ case "InsufficientFunds":
52
+ return "INSUFFICIENT_FUNDS"
53
+ case "NoStakeCredential":
54
+ case "UnreadableChangeAddress":
55
+ case "RewardBalanceUnknown":
56
+ case "CannotBalance":
57
+ return "CANNOT_BALANCE"
58
+ }
59
+ }
60
+
61
+ /** `cause` keeps what evolution-sdk said, so a build failure stays diagnosable. */
62
+ export class BalanceError extends Data.TaggedError("BalanceError")<{
63
+ readonly refusal: BalanceRefusal
64
+ readonly detail: string
65
+ readonly cause?: unknown
66
+ }> {
67
+ override get message(): string {
68
+ return this.detail
69
+ }
70
+
71
+ get code(): ClientErrorCode {
72
+ return slipErrorCodeFor(this.refusal)
73
+ }
74
+ }
75
+
76
+ export const refuse = (refusal: BalanceRefusal, detail: string, cause?: unknown): BalanceError =>
77
+ new BalanceError({ refusal, detail, ...(cause === undefined ? {} : { cause }) })
package/src/balance.ts ADDED
@@ -0,0 +1,285 @@
1
+ /**
2
+ * The privacy-preserving heart of Mode A: the endpoint's half-transaction
3
+ * becomes a whole one here, against unspent outputs it never sees (ADR-0002).
4
+ *
5
+ * Every term arrives as an argument — unspent outputs, protocol parameters, the
6
+ * reward balance, the clock — for the same reason the verifier takes its five:
7
+ * a balancer that fetched them could be made slow, made to fail, or made to
8
+ * answer wrongly by whoever answered.
9
+ */
10
+ import { addressIsOnNetwork, type Certificate, type Intent, type Network, type Output } from "@cardano-slips/core"
11
+ import type { ProtocolParameters } from "@cardano-slips/verifier"
12
+ import {
13
+ Address,
14
+ Assets,
15
+ DRep,
16
+ mainnet,
17
+ PoolKeyHash,
18
+ preprod,
19
+ preview,
20
+ Schema,
21
+ type SlotConfig,
22
+ Transaction,
23
+ type UTxO
24
+ } from "@evolution-sdk/evolution"
25
+ import {
26
+ makeTxBuilder,
27
+ type ProtocolParameters as BuilderParameters,
28
+ type ReadOnlyTransactionBuilder
29
+ } from "@evolution-sdk/evolution/sdk/builders/TransactionBuilder"
30
+ import { Effect } from "effect"
31
+
32
+ import { type BalanceError, refuse } from "./balance-error.js"
33
+ import type { CborHex } from "./cip30.js"
34
+
35
+ /**
36
+ * The verifier's parameters plus the one bound the builder needs and the gate
37
+ * does not. One vocabulary across both halves: the figures that balance a
38
+ * transaction are the figures it will be judged against.
39
+ */
40
+ export type BalancingParameters = ProtocolParameters & {
41
+ /** `maxTxSize`: the byte ceiling a built transaction must fit under. */
42
+ readonly maxTxSize: number
43
+ }
44
+
45
+ export type BalanceInputs = {
46
+ readonly intent: Intent
47
+ /** The Slip's network. Every address in the intent is held to it. */
48
+ readonly network: Network
49
+ /** Bech32, from the connected wallet. Change returns here. */
50
+ readonly changeAddress: string
51
+ readonly utxos: ReadonlyArray<UTxO.UTxO>
52
+ readonly parameters: BalancingParameters
53
+ /**
54
+ * The whole balance of the wallet's own reward account, required when the
55
+ * intent withdraws rewards. The ledger accepts one figure and only one, and
56
+ * no CIP-30 method answers it.
57
+ */
58
+ readonly rewardBalance?: bigint
59
+ /** Unix milliseconds. Handed in, so an expiry is decided by one clock and not two. */
60
+ readonly now: number
61
+ }
62
+
63
+ export type BalancedTransaction = {
64
+ /** The complete unsigned transaction: what `verifier` decodes and the wallet signs. */
65
+ readonly cbor: CborHex
66
+ readonly fee: bigint
67
+ /** The slot the body expires at, for the rebuild path to watch. */
68
+ readonly ttl: bigint
69
+ }
70
+
71
+ const chains = { mainnet, preprod, preview }
72
+
73
+ /**
74
+ * The slot mapping comes from the parameters rather than from the chain preset:
75
+ * the client converts `validUntil` to a slot and the gate converts that slot
76
+ * back to a time, and two mappings would put an honest transaction outside its
77
+ * own declared window.
78
+ */
79
+ const slotConfigOf = ({ slots }: BalancingParameters): SlotConfig.SlotConfig => ({
80
+ zeroTime: slots.time,
81
+ zeroSlot: slots.slot,
82
+ slotLength: Number(slots.slotLength)
83
+ })
84
+
85
+ const builderParameters = (parameters: BalancingParameters): BuilderParameters => ({
86
+ minFeeCoefficient: parameters.minFeeCoefficient,
87
+ minFeeConstant: parameters.minFeeConstant,
88
+ coinsPerUtxoByte: parameters.coinsPerUtxoByte,
89
+ maxTxSize: parameters.maxTxSize
90
+ })
91
+
92
+ /**
93
+ * What the builder reads for a certificate's deposit. The script fields are
94
+ * zeroed rather than guessed: version 1 builds no transaction that spends from
95
+ * a script, so a cost model here would be a figure nothing computes from.
96
+ */
97
+ const depositParameters = (parameters: BalancingParameters) => ({
98
+ minFeeA: Number(parameters.minFeeCoefficient),
99
+ minFeeB: Number(parameters.minFeeConstant),
100
+ maxTxSize: parameters.maxTxSize,
101
+ maxValSize: 0,
102
+ keyDeposit: parameters.stakeDeposit,
103
+ poolDeposit: parameters.poolDeposit,
104
+ drepDeposit: parameters.drepDeposit,
105
+ govActionDeposit: parameters.governanceActionDeposit,
106
+ priceMem: 0,
107
+ priceStep: 0,
108
+ maxTxExMem: 0n,
109
+ maxTxExSteps: 0n,
110
+ coinsPerUtxoByte: parameters.coinsPerUtxoByte,
111
+ collateralPercentage: 0,
112
+ maxCollateralInputs: 0,
113
+ minFeeRefScriptCostPerByte: 0,
114
+ costModels: { PlutusV1: {}, PlutusV2: {}, PlutusV3: {} }
115
+ })
116
+
117
+ const assetsOf = (output: Output): Assets.Assets =>
118
+ (output.assets ?? []).reduce(
119
+ (assets, asset) => Assets.addByHex(assets, asset.policyId, asset.assetName, BigInt(asset.quantity)),
120
+ Assets.fromLovelace(BigInt(output.lovelace))
121
+ )
122
+
123
+ /**
124
+ * `Schema.decodeSync(FromBech32)` and not `DRep.fromBech32`: the SDK's
125
+ * declarations carry that function and the shipped module does not export it,
126
+ * so calling it compiles and throws. The seventh gap of ADR-0004.
127
+ */
128
+ const drepFromBech32 = Schema.decodeSync(DRep.FromBech32)
129
+
130
+ const drepOf = (declared: Certificate & { readonly type: "voteDelegation" }): DRep.DRep => {
131
+ if (declared.drep === "abstain") return DRep.alwaysAbstain()
132
+ if (declared.drep === "noConfidence") return DRep.alwaysNoConfidence()
133
+ return drepFromBech32(declared.drep)
134
+ }
135
+
136
+ /**
137
+ * The Conway forms throughout. The legacy pair encodes no deposit and no
138
+ * refund, and evolution-sdk's builder therefore leaves both out of the balance —
139
+ * a transaction the ledger rejects, because consumed and produced no longer
140
+ * agree. The stated deposit is the protocol parameter exactly, which is what
141
+ * the ledger charges and what the gate holds it to (ADR-0013).
142
+ */
143
+ const applyCertificate = (
144
+ builder: ReadOnlyTransactionBuilder,
145
+ declared: Certificate,
146
+ stakeCredential: StakeCredential
147
+ ): ReadOnlyTransactionBuilder => {
148
+ switch (declared.type) {
149
+ case "stakeRegistration":
150
+ return builder.registerStake({ stakeCredential })
151
+ case "stakeDeregistration":
152
+ return builder.deregisterStake({ stakeCredential })
153
+ case "stakeDelegation":
154
+ return builder.delegateToPool({ stakeCredential, poolKeyHash: PoolKeyHash.fromBech32(declared.poolId) })
155
+ case "voteDelegation":
156
+ return builder.delegateToDRep({ stakeCredential, drep: drepOf(declared) })
157
+ }
158
+ }
159
+
160
+ /** The staking half of a base address — what every certificate and withdrawal here acts on. */
161
+ type StakeCredential = NonNullable<Address.Address["stakingCredential"]>
162
+
163
+ /**
164
+ * What the transaction does to the wallet's own stake credential, gathered
165
+ * once so the credential is proved present before the builder runs rather than
166
+ * asserted inside it.
167
+ */
168
+ type StakeActions = {
169
+ readonly credential: StakeCredential
170
+ readonly certificates: ReadonlyArray<Certificate>
171
+ /** The whole reward balance, or `null` where the intent withdraws nothing. */
172
+ readonly withdrawal: bigint | null
173
+ }
174
+
175
+ const actsOnStake = (intent: Intent): boolean =>
176
+ (intent.certificates ?? []).length > 0 || intent.withdrawRewards === true
177
+
178
+ /** The two sites evolution-sdk reports a shortfall from, neither of which carries a structured cause. */
179
+ const isShortfall = (message: string): boolean =>
180
+ message.startsWith("Coin selection failed") || message.includes("Insufficient funds to cover")
181
+
182
+ const readFailure = (cause: unknown): BalanceError => {
183
+ const message = cause instanceof Error ? cause.message : String(cause)
184
+ return isShortfall(message)
185
+ ? refuse("InsufficientFunds", "This wallet does not hold enough to cover the transaction and its fee.", cause)
186
+ : refuse("CannotBalance", `This intent could not be built into a transaction: ${message}`, cause)
187
+ }
188
+
189
+ /**
190
+ * Builds the transaction, or says why not. Nothing here asks the network
191
+ * anything, and nothing describing what the wallet holds leaves this function.
192
+ */
193
+ export const balanceIntent = (inputs: BalanceInputs): Effect.Effect<BalancedTransaction, BalanceError> =>
194
+ Effect.gen(function* () {
195
+ const { changeAddress, intent, network, parameters, utxos } = inputs
196
+
197
+ const validUntil = Date.parse(intent.validUntil)
198
+ if (validUntil <= inputs.now) {
199
+ return yield* Effect.fail(refuse("IntentExpired", "This request expired while it was open. Ask for a fresh one."))
200
+ }
201
+
202
+ for (const output of intent.outputs ?? []) {
203
+ if (!addressIsOnNetwork(output.address, network)) {
204
+ return yield* Effect.fail(
205
+ refuse("ForeignAddress", `This Slip is on ${network} and it asks to pay an address on another network.`)
206
+ )
207
+ }
208
+ }
209
+
210
+ // Inside the error channel, not thrown past it: the signature promises a
211
+ // `BalanceError` and a defect here would reach a person as a stack trace.
212
+ const change = yield* Effect.try({
213
+ try: () => Address.fromBech32(changeAddress),
214
+ catch: (cause) =>
215
+ refuse("UnreadableChangeAddress", "This wallet's change address could not be read as an address.", cause)
216
+ })
217
+ const credential = change.stakingCredential
218
+ if (actsOnStake(intent) && credential === undefined) {
219
+ return yield* Effect.fail(
220
+ refuse("NoStakeCredential", "This action acts on a stake credential and this wallet's address carries none.")
221
+ )
222
+ }
223
+
224
+ if (intent.withdrawRewards === true && inputs.rewardBalance === undefined) {
225
+ return yield* Effect.fail(
226
+ refuse("RewardBalanceUnknown", "The reward balance to withdraw is not known, so this cannot be built.")
227
+ )
228
+ }
229
+
230
+ const stake: StakeActions | null =
231
+ credential === undefined
232
+ ? null
233
+ : {
234
+ credential,
235
+ certificates: intent.certificates ?? [],
236
+ withdrawal: intent.withdrawRewards === true ? (inputs.rewardBalance ?? 0n) : null
237
+ }
238
+
239
+ const built = yield* Effect.tryPromise({
240
+ try: async () => {
241
+ let builder: ReadOnlyTransactionBuilder = makeTxBuilder({ chain: chains[network] })
242
+
243
+ for (const output of intent.outputs ?? []) {
244
+ // Declared lovelace is a floor: `autoMinUtxo` raises an output that
245
+ // cannot pay for its own bytes, and the difference is shown to the
246
+ // person as the client's own adjustment rather than folded in.
247
+ builder = builder.payToAddress({ address: Address.fromBech32(output.address), assets: assetsOf(output) })
248
+ }
249
+
250
+ if (stake !== null) {
251
+ for (const declared of stake.certificates) builder = applyCertificate(builder, declared, stake.credential)
252
+ if (stake.withdrawal !== null) {
253
+ builder = builder.withdraw({ stakeCredential: stake.credential, amount: stake.withdrawal })
254
+ }
255
+ }
256
+
257
+ // Never after `validUntil`, which is the whole of what the spec fixes here.
258
+ builder = builder.setValidity({ to: BigInt(validUntil) })
259
+
260
+ return await builder.build({
261
+ changeAddress: change,
262
+ availableUtxos: utxos,
263
+ protocolParameters: builderParameters(parameters),
264
+ fullProtocolParameters: depositParameters(parameters),
265
+ slotConfig: slotConfigOf(parameters),
266
+ autoMinUtxo: true,
267
+ // Leftover too small to become change would otherwise be paid as fee —
268
+ // lovelace leaving the wallet that nothing on screen accounted for.
269
+ onInsufficientChange: "error"
270
+ })
271
+ },
272
+ catch: readFailure
273
+ })
274
+
275
+ const transaction = yield* Effect.tryPromise({ try: () => built.toTransaction(), catch: readFailure })
276
+
277
+ const ttl = transaction.body.ttl
278
+ if (ttl === undefined) {
279
+ // We asked for an interval; a body without one could be submitted after
280
+ // `validUntil`, which is the one thing the spec forbids outright here.
281
+ return yield* Effect.fail(refuse("CannotBalance", "The built transaction carries no expiry, and it must."))
282
+ }
283
+
284
+ return { cbor: Transaction.toCBORHex(transaction), fee: transaction.body.fee, ttl }
285
+ })