@midnightntwrk/midnight-js-contracts 0.0.0-stage → 5.0.1

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.
package/README.md CHANGED
@@ -1,3 +1,428 @@
1
- # Temporary Holding Version
1
+ # Contracts
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Utilities for deploying and interacting with Midnight smart contracts.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ yarn add @midnightntwrk/midnight-js-contracts
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```typescript
14
+ import { deployContract, findDeployedContract } from '@midnightntwrk/midnight-js-contracts';
15
+
16
+ // Deploy a new contract
17
+ const deployed = await deployContract(providers, {
18
+ compiledContract: myContract,
19
+ privateStateId: 'my-state',
20
+ initialPrivateState: { counter: 0n }
21
+ });
22
+
23
+ // Call a circuit on the deployed contract
24
+ const result = await deployed.callTx.myCircuit({ arg: 'value' });
25
+
26
+ // Find an existing deployed contract
27
+ const found = await findDeployedContract(providers, {
28
+ compiledContract: myContract,
29
+ contractAddress: '0x...',
30
+ privateStateId: 'my-state'
31
+ });
32
+ ```
33
+
34
+ ## API
35
+
36
+ ### deployContract
37
+
38
+ Creates and submits a contract deployment transaction.
39
+
40
+ ```typescript
41
+ const deployed = await deployContract(providers, {
42
+ compiledContract, // Compiled Compact contract
43
+ privateStateId, // ID for storing private state (optional for stateless contracts)
44
+ initialPrivateState, // Initial private state (optional for stateless contracts)
45
+ signingKey // Contract maintenance authority key (optional, auto-generated if omitted)
46
+ });
47
+ ```
48
+
49
+ Returns a `DeployedContract` with:
50
+ - `deployTxData` - Deployment transaction data
51
+ - `callTx` - Interface for calling contract circuits
52
+ - `circuitMaintenanceTx` - Interface for circuit maintenance operations
53
+ - `contractMaintenanceTx` - Interface for contract maintenance operations
54
+
55
+ ### findDeployedContract
56
+
57
+ Finds an existing deployed contract by address.
58
+
59
+ ```typescript
60
+ const found = await findDeployedContract(providers, {
61
+ compiledContract, // Compiled Compact contract
62
+ contractAddress, // Address of deployed contract
63
+ privateStateId, // ID for retrieving/storing private state (optional)
64
+ initialPrivateState, // Private state to store (optional, uses existing if omitted)
65
+ signingKey // Maintenance authority key (optional, auto-generated if needed)
66
+ });
67
+ ```
68
+
69
+ ### Transaction Submission
70
+
71
+ ```typescript
72
+ import { submitCallTx, submitDeployTx, submitTx } from '@midnightntwrk/midnight-js-contracts';
73
+
74
+ // Submit a call transaction
75
+ await submitCallTx(providers, callOptions);
76
+
77
+ // Submit a deploy transaction (routes on the contract's era, like deployContract)
78
+ await submitDeployTx(providers, deployOptions);
79
+
80
+ // Generic transaction submission. Pass a transaction handle; it carries the era
81
+ // that wrote the transaction. submitTx reads the network's current ledger version and
82
+ // accepts only a transaction of that era.
83
+ const unprovenTx = LedgerTransaction.seal('v9', 'Unproven', ledgerUnprovenTx);
84
+ const record = await submitTx(providers, { unprovenTx });
85
+
86
+ // The record's tx is a FinalizedTx handle of the record's era. Decode it with
87
+ // your own ledger copy (Transaction from @midnightntwrk/ledger-v9).
88
+ if (record.era === 'v9') {
89
+ const finalized = record.tx.deserialize({ v9: Transaction });
90
+ }
91
+ ```
92
+
93
+ `LedgerTransaction` comes from `@midnightntwrk/midnight-js-types`. A handle you
94
+ get from `createUnprovenCallTx` or `createUnprovenDeployTx`
95
+ (`result.private.unprovenTx`) is already sealed, so you pass it on as it is.
96
+
97
+ `submitTx` reads the network's current ledger version once. The transaction's era must match it:
98
+
99
+ | input | network | what happens |
100
+ |---|---|---|
101
+ | v9 | v9 | proved, balanced and submitted as v9 handles |
102
+ | v8 | v8 | proved, balanced and submitted as v8 handles |
103
+ | v8 | v9 | refused with `EraMismatchError` before proving: the v9 ledger cannot read a v8 transaction |
104
+ | v9 | v8 | refused with `EraMismatchError` before proving |
105
+
106
+ It returns `FinalizedTxRead`, tagged with the era of the block that recorded the transaction.
107
+
108
+ ### Low-level functions per ledger era
109
+
110
+ The low-level functions build a transaction without submitting it, or deploy and wait. Each
111
+ unprefixed name routes on the era the contract's artifacts declare; the per-era functions serve
112
+ one era only and refuse the other with `EraMismatchError` (`reason: 'contract-era-unsupported'`).
113
+
114
+ | Router | Ledger 9 | Ledger 8 |
115
+ |---|---|---|
116
+ | `createUnprovenCallTx` | `createLedger9UnprovenCallTx` | `createLedger8UnprovenCallTx` |
117
+ | `createUnprovenCallTxFromInitialStates` | `createLedger9UnprovenCallTxFromInitialStates` | `createLedger8UnprovenCallTxFromInitialStates` |
118
+ | `createUnprovenDeployTx` | `createLedger9UnprovenDeployTx` | `createLedger8UnprovenDeployTx` |
119
+ | `createUnprovenDeployTxFromVerifierKeys` | `createLedger9UnprovenDeployTxFromVerifierKeys` | `createLedger8UnprovenDeployTxFromVerifierKeys` |
120
+ | `submitDeployTx` | `submitLedger9DeployTx` | `submitLedger8DeployTx` |
121
+
122
+ A builder stores nothing. Submit what it built with `submitTx`, and store the private state
123
+ yourself once the transaction is final:
124
+
125
+ ```typescript
126
+ const built = await createUnprovenCallTx(providers, callOptions);
127
+ // After the fork a ledger 8 call builds a ledger 9 transaction; the handle says which.
128
+ const record = await submitTx(providers, { unprovenTx: built.private.unprovenTx });
129
+ if (record.status === 'SucceedEntirely') {
130
+ await providers.privateStateProvider
131
+ .forContract(callOptions.contractAddress)
132
+ .set(privateStateId, built.private.nextPrivateState);
133
+ }
134
+ ```
135
+
136
+ Ledger 8 differences: a ledger 8 deploy works only before the fork; a ledger 8 call joins a scoped
137
+ transaction only before the fork; `createLedger8UnprovenCallTxFromInitialStates` takes the head era as well as
138
+ the states, because the fork translates a ledger 8 contract's state into a ledger 9 one.
139
+
140
+ Both eras' `FromInitialStates` builders take the states as a read returns them. Pass
141
+ `read.contractState`, `read.zswapChainState` (ledger 9 only) and `read.ledgerParameters` as they
142
+ are; do not decode them first. Each is a serialized state that carries the `era` of the ledger that
143
+ wrote it:
144
+
145
+ ```typescript
146
+ const read = await providers.publicDataProvider.queryZSwapAndContractState(contractAddress);
147
+ if (read !== null) {
148
+ const built = await createUnprovenCallTxFromInitialStates(
149
+ providers.zkConfigProvider,
150
+ {
151
+ compiledContract,
152
+ contractAddress,
153
+ circuitId: 'increment',
154
+ coinPublicKey,
155
+ initialContractState: read.contractState,
156
+ initialZswapChainState: read.zswapChainState,
157
+ ledgerParameters: read.ledgerParameters,
158
+ config: providers.config
159
+ },
160
+ walletEncryptionPublicKey
161
+ );
162
+ }
163
+ ```
164
+
165
+ A ledger 9 call refuses a contract state the v8 ledger wrote (`EraMismatchError`, reason
166
+ `'ledger8-contract-state-unsupported'`), and v8 ledger parameters or a v8 zswap chain state, or a
167
+ value that is not a serialized state (`InvalidArgumentError`).
168
+
169
+ ### Maintenance Operations
170
+
171
+ ```typescript
172
+ import {
173
+ submitInsertVerifierKeyTx,
174
+ submitRemoveVerifierKeyTx,
175
+ submitReplaceAuthorityTx
176
+ } from '@midnightntwrk/midnight-js-contracts';
177
+
178
+ // Remove the verifier key a circuit holds, then insert one
179
+ await submitRemoveVerifierKeyTx(providers, compiledContract, contractAddress, 'increment');
180
+ const inserted = await submitInsertVerifierKeyTx(providers, compiledContract, contractAddress, 'increment', newVk);
181
+ inserted.public.status; // every result is { era, public }
182
+
183
+ // Replace contract maintenance authority; the new key is stored once the chain records it
184
+ await submitReplaceAuthorityTx(providers, compiledContract, contractAddress)(newSigningKey);
185
+ ```
186
+
187
+ All three take either era's artifact. A ledger 8 artifact maintains a contract
188
+ only before the fork and answers `{ era: 'v8', public: Ledger8FinalizedTxData }`;
189
+ after the fork it is refused with `EraMismatchError` (reason `'ledger8-maintenance-on-ledger9-network'`), and the
190
+ same function with the recompiled ledger 9 artifact maintains the migrated
191
+ contract with the same stored key.
192
+
193
+ ### State Queries
194
+
195
+ ```typescript
196
+ import { getPublicStates, getStates, getUnshieldedBalances } from '@midnightntwrk/midnight-js-contracts';
197
+
198
+ // Get contract states (public + private)
199
+ const states = await getStates(
200
+ providers.publicDataProvider,
201
+ providers.privateStateProvider,
202
+ contractAddress,
203
+ privateStateId
204
+ );
205
+
206
+ // Get public states only
207
+ const publicStates = await getPublicStates(providers.publicDataProvider, contractAddress);
208
+
209
+ // Get unshielded token balances
210
+ const balances = await getUnshieldedBalances(providers.publicDataProvider, contractAddress);
211
+ ```
212
+
213
+ `getStates` and `getPublicStates` return the public states as bytes: each of
214
+ `contractState`, `zswapChainState` and `ledgerParameters` is a serialized state
215
+ (`SerializedContractState`, `SerializedZswapChainState`, `SerializedLedgerParameters`)
216
+ with the `era` of the ledger that wrote it. Decode one with your own
217
+ runtime — the one your contract was compiled against — so your contract's
218
+ `ledger()` accepts the result:
219
+
220
+ ```typescript
221
+ import { ContractState } from '@midnight-ntwrk/compact-runtime';
222
+ import { ledger } from './managed/counter/contract/index.js';
223
+
224
+ // Throws SerializedStateDecoderMissingError if the state was written by the v8 ledger.
225
+ const counter = ledger(publicStates.contractState.deserialize({ v9: ContractState }).data);
226
+ ```
227
+
228
+ A contract that may predate the fork passes a decoder per era: `v8` with the
229
+ `ContractState` of the ledger 8 runtime, `v9` with the current one. See the indexer provider's
230
+ README, "Reading a contract that may predate the fork", for a contract compiled
231
+ with the ledger 8 toolchain.
232
+
233
+ ### Transaction Interfaces
234
+
235
+ ```typescript
236
+ import {
237
+ createCircuitCallTxInterface,
238
+ createCircuitMaintenanceTxInterface,
239
+ createContractMaintenanceTxInterface
240
+ } from '@midnightntwrk/midnight-js-contracts';
241
+ ```
242
+
243
+ Each factory takes a ledger 8 or a ledger 9 contract and builds the interface for that contract's era:
244
+
245
+ ```typescript
246
+ const callTx = createCircuitCallTxInterface(providers, compiledContract, contractAddress, privateStateId);
247
+ await callTx.increment();
248
+ ```
249
+
250
+ ### Utility Functions
251
+
252
+ ```typescript
253
+ import { verifierKeysEqual, verifyContractState } from '@midnightntwrk/midnight-js-contracts';
254
+
255
+ // Compare verifier keys
256
+ const equal = verifierKeysEqual(keyA, keyB);
257
+
258
+ // Verify contract state matches expected verifier keys. It takes the state a read returns,
259
+ // of either era, and is async: a v8 state loads the ledger 8 runtime to be decoded.
260
+ const read = await providers.publicDataProvider.queryContractState(contractAddress);
261
+ if (read !== null) {
262
+ await verifyContractState(verifierKeys, read.contractState, contractAddress);
263
+ }
264
+ ```
265
+
266
+ A mismatch throws `ContractTypeError`. Its message lists the circuits; the deployed state is on
267
+ `error.contractState`, a `SerializedContractState` of either era. Decode it with your own runtime of
268
+ `error.contractState.era` to inspect it.
269
+
270
+ The deploy and found handles carry the deploy-time state the same way, in both eras:
271
+ `deployTxData.public.initialContractState` is a `SerializedContractState`. Decode it with your own
272
+ runtime, for example `deployTxData.public.initialContractState.deserialize({ v9: ContractState })`,
273
+ and use `serialize()` for the bytes.
274
+
275
+ ## Providers
276
+
277
+ Contract operations require a `ContractProviders` object (alias for `MidnightProviders`):
278
+
279
+ ```typescript
280
+ type ContractProviders = {
281
+ privateStateProvider: PrivateStateProvider; // Private state storage
282
+ publicDataProvider: PublicDataProvider; // Blockchain data queries
283
+ zkConfigProvider: ZKConfigProvider; // ZK proving configuration
284
+ proofProvider: ProofProvider; // ZK proof generation
285
+ walletProvider: WalletProvider; // Transaction balancing
286
+ midnightProvider: MidnightProvider; // Transaction submission
287
+ config: MidnightConfig; // Network id and transaction TTL
288
+ loggerProvider?: LoggerProvider; // Optional logging
289
+ };
290
+ ```
291
+
292
+ ## Type Names and Ledger Eras
293
+
294
+ A flat name such as `FoundContract<C>` picks the ledger 8 or ledger 9 variant
295
+ from the contract type, so `FoundContract<typeof MyContract>` is always the
296
+ type of the toolchain that compiled `MyContract`. The entry points return the
297
+ era-named type: `Ledger9FoundContract<C>` or `Ledger8FoundContract<C>`.
298
+
299
+ In generic code the contract is unknown, so name the era:
300
+
301
+ ```typescript
302
+ const read = <C extends Contract.Any, PCK extends Contract.ProvableCircuitId<C>>(
303
+ data: Ledger9FinalizedCallTxData<C, PCK>
304
+ ) => data.public;
305
+ ```
306
+
307
+ To accept a call of any contract in either era, use `AnyFinalizedCallTxData`
308
+ or `AnySubmittedCallTx`. Their `result` and `nextPrivateState` are `unknown`;
309
+ narrow on `era` or with `isLedger8Result`:
310
+
311
+ ```typescript
312
+ const onCall = (result: AnyFinalizedCallTxData) =>
313
+ isLedger8Result(result) ? result.public.txId : result.public.logEvents;
314
+ ```
315
+
316
+ A flat name with no contract parameter is the union of every era:
317
+ `FinalizedMaintenanceTxData`, `AnyContract`. For a handle, name both contracts: `FoundContract<MyContract | MyLedger8Contract>`.
318
+
319
+ ## Exports
320
+
321
+ ```typescript
322
+ import {
323
+ // Deployment
324
+ deployContract,
325
+ DeployContractOptions,
326
+ DeployedContract,
327
+
328
+ // Finding contracts
329
+ findDeployedContract,
330
+ FindDeployedContractOptions,
331
+ FoundContract,
332
+
333
+ // Transaction submission
334
+ submitCallTx,
335
+ submitDeployTx,
336
+ submitTx,
337
+ submitInsertVerifierKeyTx,
338
+ submitRemoveVerifierKeyTx,
339
+ submitReplaceAuthorityTx,
340
+
341
+ // State queries
342
+ getStates,
343
+ getPublicStates,
344
+ getUnshieldedBalances,
345
+
346
+ // Transaction interfaces
347
+ createCircuitCallTxInterface,
348
+ createCircuitMaintenanceTxInterface,
349
+ createContractMaintenanceTxInterface,
350
+ CircuitCallTxInterface,
351
+ Ledger9CircuitMaintenanceTxInterface,
352
+ Ledger9ContractMaintenanceTxInterface,
353
+
354
+ // Utilities
355
+ verifierKeysEqual,
356
+ verifyContractState,
357
+
358
+ // Types
359
+ ContractProviders,
360
+ Ledger9CallOptions,
361
+ Ledger9CallResult,
362
+ FinalizedDeployTxData,
363
+ UnsubmittedCallTxData,
364
+ Ledger9UnsubmittedDeployTxData,
365
+
366
+ // Errors
367
+ ContractTypeError,
368
+ EraInvariantViolationError,
369
+ TxFailedError
370
+ } from '@midnightntwrk/midnight-js-contracts';
371
+ ```
372
+
373
+ ## Handling Errors
374
+
375
+ One class covers one fault. A field on it says which case it was.
376
+
377
+ ```typescript
378
+ import { EraMismatchError, TxFailedError } from '@midnightntwrk/midnight-js-contracts';
379
+
380
+ try {
381
+ await submitCallTx(providers, options);
382
+ } catch (error) {
383
+ if (error instanceof TxFailedError) {
384
+ // error.operation is 'call', 'deploy', 'insert-verifier-key', 'remove-verifier-key' or 'replace-authority'.
385
+ // error.record is what the chain recorded, in either era. The message names the status,
386
+ // the transaction and the failed segments; read every other field from the record.
387
+ } else if (error instanceof EraMismatchError) {
388
+ // error.reason says which era mistake it was.
389
+ }
390
+ throw error;
391
+ }
392
+ ```
393
+
394
+ `TxFailedError.signingKey` is set after a failed deploy or replacement. Keep the key. It is not
395
+ enumerable, so object spread, `JSON.stringify` and a logger that serializes the properties of an error
396
+ leave it out.
397
+
398
+ ## Architecture Documents
399
+
400
+ The reasoning behind this package's shape lives in `docs/`, not in the source
401
+ docstrings. Each file is registered with TypeDoc through `projectDocuments`, so
402
+ it is a page in the generated API reference and `@see {@link Title}` in a
403
+ docstring resolves to it.
404
+
405
+ | Document | What it explains |
406
+ |---|---|
407
+ | [Overload typing](./docs/overload-typing.md) | Why the retained-era contract types are hand-written, what discriminates the two toolchain eras, how openness is expressed without `any`, and why overload order is load-bearing |
408
+ | [Era dispatch](./docs/era-dispatch.md) | How an operation's pipeline era and the network's ledger version are each established, why the artifact check is structural rather than branded, and which pairings may run |
409
+ | [Verification path](./docs/verification-path.md) | What the pre-proving verifier-key check buys, and why routing on key generation is unavailable rather than unimplemented |
410
+ | [Keep-state pipeline](./docs/keep-state-pipeline.md) | The order one retained-era operation runs in, the two composition paths, per-recipient shielded encryption, provider-failure sanitization, and why a retained-era deploy is refused |
411
+ | [Fork crossed during an operation](./docs/stale-head-remediation.md) | How a submit rejection is told apart from a fork crossing, the two-step remediation it carries, and which scope a contract-scoped transaction runs on each side of the fork |
412
+ | [Breadcrumbs](./docs/breadcrumbs.md) | Which era decisions reach the log and which deliberately do not, the four network version readings and their provenance, the privacy rule, and the one fault that is swallowed |
413
+ | [Error taxonomy](./docs/error-taxonomy.md) | Which class to catch across both eras, how the ledger 8 names are used, the code every class registers, the four refusals that fire before a caller pays, and the after-submission region the signing key rides through |
414
+
415
+ Docstrings in `src/` carry the API contract: what a symbol does, its
416
+ parameters, what it returns and what it throws. Anything that answers "why is
417
+ it built this way" belongs in a document above, stated once.
418
+
419
+ ## Resources
420
+
421
+ - [Midnight Network](https://midnight.network)
422
+ - [Developer Hub](https://midnight.network/developer-hub)
423
+
424
+ ## Terms & License
425
+
426
+ By using this package, you agree to [Midnight's Terms and Conditions](https://midnight.network/static/terms.pdf) and [Privacy Policy](https://midnight.network/static/privacy-policy.pdf).
427
+
428
+ Licensed under [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0).