@midnightntwrk/midnight-js-dapp-connector-proof-provider 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,187 @@
1
- # Temporary Holding Version
1
+ # DApp Connector Proof Provider
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
+ Providers that delegate to a DApp Connector wallet (for example Lace). Use this package when your dApp runs in a browser and the user's wallet proves, balances and submits transactions.
4
+
5
+ - `dappConnectorProofProvider` builds the `ProofProvider`.
6
+ - `dappConnectorWalletProviders` builds the `WalletProvider` and the `MidnightProvider`.
7
+
8
+ All three serve ledger 8 and ledger 9 transactions.
9
+
10
+ ## Installation
11
+
12
+ ```bash
13
+ yarn add @midnightntwrk/midnight-js-dapp-connector-proof-provider
14
+ ```
15
+
16
+ ## Quick Start
17
+
18
+ ```typescript
19
+ import { dappConnectorProofProvider } from '@midnightntwrk/midnight-js-dapp-connector-proof-provider';
20
+ import { LedgerTransaction } from '@midnightntwrk/midnight-js-types';
21
+ import { Transaction } from '@midnightntwrk/ledger-v9';
22
+
23
+ const proofProvider = await dappConnectorProofProvider(
24
+ walletConnectedAPI,
25
+ zkConfigProvider,
26
+ costModel
27
+ );
28
+
29
+ // A transaction is passed to a provider as a handle that carries its era.
30
+ // The proven handle comes back in the same era.
31
+ const unprovenTx = LedgerTransaction.seal('v9', 'Unproven', ledgerUnprovenTx);
32
+ const provenTx = await proofProvider.proveTx(unprovenTx);
33
+ const ledgerProvenTx = provenTx.deserialize({ v9: Transaction });
34
+ ```
35
+
36
+ ### Wallet and midnight providers
37
+
38
+ ```typescript
39
+ import { dappConnectorWalletProviders } from '@midnightntwrk/midnight-js-dapp-connector-proof-provider';
40
+
41
+ const { walletProvider, midnightProvider } = await dappConnectorWalletProviders(walletConnectedAPI);
42
+ ```
43
+
44
+ `walletConnectedAPI` is the `ConnectedAPI` the wallet returned from `connect`. The factory reads the shielded keys once, from `getShieldedAddresses`. `balanceTx` calls `balanceUnsealedTransaction` and `submitTx` calls `submitTransaction`.
45
+
46
+ The wallet runs its own copy of the ledger, so the transaction crosses as bytes: each handler serializes the transaction for the wallet, and `balanceTx` decodes the wallet's answer into the framework's ledger copy with `deserializeTransactionAtStage`. The era for that decode is the era of the handle you passed in, never a guess from the bytes.
47
+
48
+ **Known limit: no TTL.** The connector takes no TTL, so the `ttl` argument of `balanceTx` is not forwarded. The wallet picks the expiry, and `config.ttlSeconds` has no effect on the intents it adds. See [midnight-dapp-connector-api#102](https://github.com/midnightntwrk/midnight-dapp-connector-api/issues/102).
49
+
50
+ A wallet rejection (for example, the user declined) leaves `balanceTx` and `submitTx` unchanged, with the connector's own `code`. `deployContract` and the `callTx` functions wrap it in `ProviderFailedError`, and that copy does not keep the connector's `code`; it keeps only this framework's own codes.
51
+
52
+ These cases are refused:
53
+
54
+ - the wallet answer is not even-length hex without a `0x` prefix: `InvalidArgumentError`;
55
+ - the wallet answer is not a balanced transaction of the requested ledger: `PayloadNotATransactionError` (`MIDNIGHT_JS_P_PAYLOAD_NOT_A_TRANSACTION`);
56
+ - `submitTx` gets a transaction without an identifier: `InvalidArgumentError`. This is checked before anything is submitted.
57
+
58
+ ## Configuration
59
+
60
+ | Parameter | Required | Description |
61
+ | ------------------ | -------- | --------------------------------------------------- |
62
+ | `api` | ✓ | DApp Connector wallet API with proving capabilities |
63
+ | `zkConfigProvider` | ✓ | Provider for ZK configuration artifacts |
64
+ | `costModel` | ✓ | Cost model for transaction proving |
65
+
66
+ ## Architecture
67
+
68
+ This package provides two abstraction levels for wallet-delegated proof generation:
69
+
70
+ ```
71
+ ProofProvider (dappConnectorProofProvider) - Transaction-level
72
+ ↓ uses internally
73
+ ProvingProvider (dappConnectorProvingProvider) - Circuit-level
74
+ ↓ delegates to
75
+ DApp Connector Wallet (getProvingProvider)
76
+ ```
77
+
78
+ ### High-Level: Transaction Proving
79
+
80
+ Use `dappConnectorProofProvider` for most use cases. It wraps the wallet's proving capabilities with a cost model to handle complete transactions.
81
+
82
+ ```typescript
83
+ import { dappConnectorProofProvider } from '@midnightntwrk/midnight-js-dapp-connector-proof-provider';
84
+
85
+ const proofProvider = await dappConnectorProofProvider(
86
+ walletConnectedAPI,
87
+ zkConfigProvider,
88
+ costModel
89
+ );
90
+
91
+ const provenTx = await proofProvider.proveTx(unprovenTx);
92
+ ```
93
+
94
+ ### Low-Level: Circuit Proving
95
+
96
+ Use `dappConnectorProvingProvider` for advanced scenarios requiring direct access to the wallet's proving provider without cost model integration.
97
+
98
+ ```typescript
99
+ import { dappConnectorProvingProvider } from '@midnightntwrk/midnight-js-dapp-connector-proof-provider';
100
+
101
+ const provingProvider = await dappConnectorProvingProvider(
102
+ walletConnectedAPI,
103
+ zkConfigProvider
104
+ );
105
+ ```
106
+
107
+ ## API
108
+
109
+ ### ProofProvider (High-Level)
110
+
111
+ ```typescript
112
+ dappConnectorProofProvider<K extends string>(
113
+ api: DAppConnectorProvingAPI,
114
+ zkConfigProvider: ZKConfigProvider<K>,
115
+ costModel: CostModel
116
+ ): Promise<ProofProvider>
117
+ ```
118
+
119
+ Creates a `ProofProvider` that delegates proving to the wallet and applies the given cost model. The wallet's proving provider is obtained once during initialization and reused for all subsequent `proveTx` calls.
120
+
121
+ ### ProvingProvider (Low-Level)
122
+
123
+ ```typescript
124
+ dappConnectorProvingProvider<K extends string>(
125
+ api: DAppConnectorProvingAPI,
126
+ zkConfigProvider: ZKConfigProvider<K>
127
+ ): Promise<ProvingProvider>
128
+ ```
129
+
130
+ Obtains a `ProvingProvider` directly from the DApp Connector wallet. Extracts key material from the ZK config provider and passes it to the wallet's `getProvingProvider` method.
131
+
132
+ ### Wallet and midnight providers
133
+
134
+ ```typescript
135
+ dappConnectorWalletProviders(
136
+ api: DAppConnectorWalletAPI
137
+ ): Promise<{ walletProvider: WalletProvider; midnightProvider: MidnightProvider }>
138
+ ```
139
+
140
+ Creates a `WalletProvider` and a `MidnightProvider` that balance and submit through the wallet. Both have `supportedEras` `['v8', 'v9']`.
141
+
142
+ ### DAppConnectorWalletAPI
143
+
144
+ ```typescript
145
+ type DAppConnectorWalletAPI = Pick<
146
+ ConnectedAPI,
147
+ 'getShieldedAddresses' | 'balanceUnsealedTransaction' | 'submitTransaction'
148
+ >
149
+ ```
150
+
151
+ The methods `dappConnectorWalletProviders` needs. A test can pass an object with only these three.
152
+
153
+ ### DAppConnectorProvingAPI
154
+
155
+ ```typescript
156
+ type DAppConnectorProvingAPI = Pick<WalletConnectedAPI, 'getProvingProvider'>
157
+ ```
158
+
159
+ Minimal interface required from the DApp Connector wallet. Only the `getProvingProvider` method is needed, allowing loose coupling to the full wallet API.
160
+
161
+ ## Exports
162
+
163
+ ```typescript
164
+ import {
165
+ // High-level: Transaction proving
166
+ dappConnectorProofProvider,
167
+
168
+ // Low-level: Circuit proving
169
+ dappConnectorProvingProvider,
170
+ type DAppConnectorProvingAPI,
171
+
172
+ // Transaction balancing and submission
173
+ dappConnectorWalletProviders,
174
+ type DAppConnectorWalletAPI
175
+ } from '@midnightntwrk/midnight-js-dapp-connector-proof-provider';
176
+ ```
177
+
178
+ ## Resources
179
+
180
+ - [Midnight Network](https://midnight.network)
181
+ - [Developer Hub](https://midnight.network/developer-hub)
182
+
183
+ ## Terms & License
184
+
185
+ 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).
186
+
187
+ Licensed under [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0).
@@ -0,0 +1,108 @@
1
+ import { WalletConnectedAPI } from '@midnightntwrk/dapp-connector-api';
2
+ import { MidnightNetwork } from '@midnightntwrk/midnight-js-utils';
3
+ import { ProvingProvider, CostModel } from '@midnightntwrk/midnight-js-protocol/v9';
4
+ import { ZKConfigProvider, ZKConfigRegistry, ProofProvider, WalletProvider, MidnightProvider } from '@midnightntwrk/midnight-js-types';
5
+
6
+ /** The part of the DApp Connector's `ConnectedAPI` that {@link dappConnectorNetwork} calls. */
7
+ type DAppConnectorNetworkAPI = Pick<WalletConnectedAPI, 'getConfiguration'>;
8
+ /**
9
+ * Reads the network id and endpoints of a browser dApp from its DApp Connector wallet, so the dApp uses the
10
+ * network and the services the user picked in the wallet.
11
+ *
12
+ * @remarks
13
+ * The connector reports one node URI. A Substrate node serves HTTP and WebSocket on the same address, so the
14
+ * other node URL is the same URI with the matching scheme.
15
+ *
16
+ * @param api - The DApp Connector's `ConnectedAPI`, or any object with the method in {@link DAppConnectorNetworkAPI}.
17
+ * @throws InvalidArgumentError If the wallet's `networkId` is empty, or one of its URIs is not a URL of the
18
+ * expected scheme with a host. The message names the field, never its value, which can hold a token.
19
+ *
20
+ * @example
21
+ * ```typescript
22
+ * const network = await dappConnectorNetwork(connectedApi);
23
+ * const publicDataProvider = indexerPublicDataProvider(network.indexer);
24
+ * ```
25
+ */
26
+ declare const dappConnectorNetwork: (api: DAppConnectorNetworkAPI) => Promise<MidnightNetwork>;
27
+
28
+ /**
29
+ * Minimal interface required from the DApp Connector wallet.
30
+ *
31
+ * @remarks
32
+ * Picks only {@link WalletConnectedAPI.getProvingProvider | getProvingProvider} from the full
33
+ * wallet API, allowing loose coupling between the framework and the wallet implementation.
34
+ */
35
+ type DAppConnectorProvingAPI = Pick<WalletConnectedAPI, 'getProvingProvider'>;
36
+ /**
37
+ * Obtains a {@link ProvingProvider} from the DApp Connector wallet.
38
+ *
39
+ * @remarks
40
+ * Extracts key material from the given `zkConfigProvider` and passes it to the wallet's
41
+ * `getProvingProvider` method. Use this when you need direct, circuit-level access to the
42
+ * wallet's proving capabilities without cost model integration.
43
+ *
44
+ * @typeParam K - Union of circuit identifier strings defined by the contract.
45
+ * @param api - DApp Connector wallet API exposing `getProvingProvider`.
46
+ * @param zkConfigProvider - Provider that supplies ZK configuration artifacts and key material.
47
+ * @returns A {@link ProvingProvider} backed by the wallet.
48
+ */
49
+ declare const dappConnectorProvingProvider: <K extends string>(api: DAppConnectorProvingAPI, zkConfigProvider: ZKConfigProvider<K> | ZKConfigRegistry) => Promise<ProvingProvider>;
50
+
51
+ /**
52
+ * Creates a {@link ProofProvider} that delegates proving to a DApp Connector wallet.
53
+ *
54
+ * @remarks
55
+ * Combines a wallet-backed {@link dappConnectorProvingProvider} with the given `costModel`
56
+ * to produce a transaction-level proof provider. The wallet's proving provider is obtained
57
+ * once during initialization and reused for all subsequent `proveTx` calls.
58
+ *
59
+ * @typeParam K - Union of circuit identifier strings defined by the contract.
60
+ * @param api - DApp Connector wallet API exposing `getProvingProvider`.
61
+ * @param zkConfigProvider - A single {@link ZKConfigProvider} or a multi-source
62
+ * {@link ZKConfigRegistry} that supplies ZK configuration artifacts and key material. A registry is
63
+ * required to prove transactions that make cross-contract calls, which carry one proof per contract
64
+ * in the call tree.
65
+ * @param costModel - Cost model applied during transaction proving on the CURRENT ledger era.
66
+ *
67
+ * **Not consulted on the retained (`v8`) era**, which uses that era's own cost model instead. This
68
+ * is not an oversight and not a silent fallback: the retained ledger ships its own `CostModel`
69
+ * class and type-checks `prove()`'s argument against it across the WASM boundary, so the value
70
+ * passed here would be rejected outright. Pairing the transaction with its own era's model is the
71
+ * only correct pairing, so an override is not offered at all rather than offered and quietly
72
+ * ignored.
73
+ * @returns A {@link ProofProvider} whose `proveTx` method delegates to the wallet.
74
+ * @throws InvalidArgumentError raised by `proveTx`, before any proving starts, if
75
+ * `proveTxConfig.timeout` is set (including `0`): the wallet proving API takes no timeout.
76
+ */
77
+ declare const dappConnectorProofProvider: <K extends string>(api: DAppConnectorProvingAPI, zkConfigProvider: ZKConfigProvider<K> | ZKConfigRegistry, costModel: CostModel) => Promise<ProofProvider>;
78
+
79
+ /** The part of the DApp Connector's `ConnectedAPI` that {@link dappConnectorWalletProviders} calls. */
80
+ type DAppConnectorWalletAPI = Pick<WalletConnectedAPI, 'getShieldedAddresses' | 'balanceUnsealedTransaction' | 'submitTransaction'>;
81
+ /**
82
+ * Creates the {@link WalletProvider} and {@link MidnightProvider} of a browser dApp from a DApp Connector
83
+ * wallet, for ledger 8 and ledger 9 transactions.
84
+ *
85
+ * @remarks
86
+ * The shielded keys are read once, here. Balancing goes through `balanceUnsealedTransaction` and submission
87
+ * through `submitTransaction`. The connector takes no TTL, so the `ttl` argument of `balanceTx` is not
88
+ * forwarded and the wallet picks the expiry. See https://github.com/midnightntwrk/midnight-dapp-connector-api/issues/102
89
+ *
90
+ * A rejection from the wallet leaves these providers unchanged, with the connector's own `code`.
91
+ * `deployContract` and the `callTx` functions wrap it in `ProviderFailedError`, and that copy does not keep the
92
+ * connector's `code`; it keeps only this framework's own codes.
93
+ *
94
+ * @param api - The DApp Connector's `ConnectedAPI`, or any object with the methods in {@link DAppConnectorWalletAPI}.
95
+ * @returns The wallet provider and the midnight provider, both serving `v8` and `v9`.
96
+ * @throws InvalidArgumentError raised by `balanceTx` if the wallet answer is not even-length hex without a `0x`
97
+ * prefix, and by `submitTx`, before anything is submitted, if the transaction has no identifier.
98
+ * @throws PayloadNotATransactionError raised by `balanceTx` if the wallet answer is not a balanced transaction of
99
+ * the requested ledger.
100
+ * @throws Ledger8RuntimeMissingError raised by `balanceTx` on a ledger 8 request if the v8 runtime cannot be loaded.
101
+ */
102
+ declare const dappConnectorWalletProviders: (api: DAppConnectorWalletAPI) => Promise<{
103
+ walletProvider: WalletProvider;
104
+ midnightProvider: MidnightProvider;
105
+ }>;
106
+
107
+ export { dappConnectorNetwork, dappConnectorProofProvider, dappConnectorProvingProvider, dappConnectorWalletProviders };
108
+ export type { DAppConnectorNetworkAPI, DAppConnectorProvingAPI, DAppConnectorWalletAPI };
package/dist/index.js ADDED
@@ -0,0 +1,241 @@
1
+ import { InvalidArgumentError } from '@midnightntwrk/midnight-js-protocol/errors';
2
+ import { loadLedger8Protocol } from '@midnightntwrk/midnight-js-protocol';
3
+ import { proveLedger8Transaction } from '@midnightntwrk/midnight-js-protocol/prove';
4
+ import { Transaction } from '@midnightntwrk/midnight-js-protocol/v9';
5
+ import { ZKConfigRegistry, zkConfigToProvingKeyMaterial, createProofProviderFromHandlers, createWalletProviderFromHandlers, createMidnightProviderFromHandlers } from '@midnightntwrk/midnight-js-types';
6
+ import { deserializeTransactionAtStage } from '@midnightntwrk/midnight-js-protocol/transaction';
7
+
8
+ /*
9
+ * This file is part of midnight-js.
10
+ * Copyright (C) Midnight Foundation
11
+ * SPDX-License-Identifier: Apache-2.0
12
+ * Licensed under the Apache License, Version 2.0 (the "License");
13
+ * You may not use this file except in compliance with the License.
14
+ * You may obtain a copy of the License at
15
+ * http://www.apache.org/licenses/LICENSE-2.0
16
+ * Unless required by applicable law or agreed to in writing, software
17
+ * distributed under the License is distributed on an "AS IS" BASIS,
18
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ * See the License for the specific language governing permissions and
20
+ * limitations under the License.
21
+ */
22
+ const walletURL = (field, value, schemes) => {
23
+ const url = value.trim() === value && URL.canParse(value) ? new URL(value) : undefined;
24
+ if (url === undefined || !schemes.includes(url.protocol) || url.hostname === '') {
25
+ throw new InvalidArgumentError(`The wallet's ${field} must be a ${schemes.join(' or ')} URL with a host.`);
26
+ }
27
+ return url;
28
+ };
29
+ const nodeURLs = (substrateNodeUri) => {
30
+ const { protocol } = walletURL('substrateNodeUri', substrateNodeUri, ['http:', 'https:', 'ws:', 'wss:']);
31
+ const rest = substrateNodeUri.slice(protocol.length);
32
+ const secure = protocol === 'https:' || protocol === 'wss:';
33
+ return { nodeURL: `${secure ? 'https:' : 'http:'}${rest}`, nodeWsURL: `${secure ? 'wss:' : 'ws:'}${rest}` };
34
+ };
35
+ /**
36
+ * Reads the network id and endpoints of a browser dApp from its DApp Connector wallet, so the dApp uses the
37
+ * network and the services the user picked in the wallet.
38
+ *
39
+ * @remarks
40
+ * The connector reports one node URI. A Substrate node serves HTTP and WebSocket on the same address, so the
41
+ * other node URL is the same URI with the matching scheme.
42
+ *
43
+ * @param api - The DApp Connector's `ConnectedAPI`, or any object with the method in {@link DAppConnectorNetworkAPI}.
44
+ * @throws InvalidArgumentError If the wallet's `networkId` is empty, or one of its URIs is not a URL of the
45
+ * expected scheme with a host. The message names the field, never its value, which can hold a token.
46
+ *
47
+ * @example
48
+ * ```typescript
49
+ * const network = await dappConnectorNetwork(connectedApi);
50
+ * const publicDataProvider = indexerPublicDataProvider(network.indexer);
51
+ * ```
52
+ */
53
+ const dappConnectorNetwork = async (api) => {
54
+ const { networkId, indexerUri, indexerWsUri, substrateNodeUri } = await api.getConfiguration();
55
+ if (networkId === '' || networkId.trim() !== networkId) {
56
+ throw new InvalidArgumentError("The wallet's networkId must be a non-empty string without whitespace around it.");
57
+ }
58
+ walletURL('indexerUri', indexerUri, ['http:', 'https:']);
59
+ walletURL('indexerWsUri', indexerWsUri, ['ws:', 'wss:']);
60
+ return {
61
+ networkId,
62
+ indexer: { queryURL: indexerUri, subscriptionURL: indexerWsUri },
63
+ ...nodeURLs(substrateNodeUri)
64
+ };
65
+ };
66
+
67
+ /*
68
+ * This file is part of midnight-js.
69
+ * Copyright (C) Midnight Foundation
70
+ * SPDX-License-Identifier: Apache-2.0
71
+ * Licensed under the Apache License, Version 2.0 (the "License");
72
+ * You may not use this file except in compliance with the License.
73
+ * You may obtain a copy of the License at
74
+ * http://www.apache.org/licenses/LICENSE-2.0
75
+ * Unless required by applicable law or agreed to in writing, software
76
+ * distributed under the License is distributed on an "AS IS" BASIS,
77
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
78
+ * See the License for the specific language governing permissions and
79
+ * limitations under the License.
80
+ */
81
+ /**
82
+ * Obtains a {@link ProvingProvider} from the DApp Connector wallet.
83
+ *
84
+ * @remarks
85
+ * Extracts key material from the given `zkConfigProvider` and passes it to the wallet's
86
+ * `getProvingProvider` method. Use this when you need direct, circuit-level access to the
87
+ * wallet's proving capabilities without cost model integration.
88
+ *
89
+ * @typeParam K - Union of circuit identifier strings defined by the contract.
90
+ * @param api - DApp Connector wallet API exposing `getProvingProvider`.
91
+ * @param zkConfigProvider - Provider that supplies ZK configuration artifacts and key material.
92
+ * @returns A {@link ProvingProvider} backed by the wallet.
93
+ */
94
+ const dappConnectorProvingProvider = async (api, zkConfigProvider) => {
95
+ // The wallet round-trips each proof preimage's key location into this provider, so contract
96
+ // key locations must be resolved through the registry's verifier-key join.
97
+ const registry = zkConfigProvider instanceof ZKConfigRegistry ? zkConfigProvider : new ZKConfigRegistry([zkConfigProvider]);
98
+ const walletProvingProvider = await api.getProvingProvider(registry.asKeyMaterialProvider());
99
+ return {
100
+ check: (serializedPreimage, keyLocation) => walletProvingProvider.check(serializedPreimage, keyLocation),
101
+ prove: (serializedPreimage, keyLocation, overwriteBindingInput) => walletProvingProvider.prove(serializedPreimage, keyLocation, overwriteBindingInput),
102
+ async lookupKey(keyLocation) {
103
+ const resolved = await registry.resolveKeyLocation(keyLocation);
104
+ return resolved === undefined ? undefined : zkConfigToProvingKeyMaterial(resolved);
105
+ }
106
+ };
107
+ };
108
+
109
+ /*
110
+ * This file is part of midnight-js.
111
+ * Copyright (C) Midnight Foundation
112
+ * SPDX-License-Identifier: Apache-2.0
113
+ * Licensed under the Apache License, Version 2.0 (the "License");
114
+ * You may not use this file except in compliance with the License.
115
+ * You may obtain a copy of the License at
116
+ * http://www.apache.org/licenses/LICENSE-2.0
117
+ * Unless required by applicable law or agreed to in writing, software
118
+ * distributed under the License is distributed on an "AS IS" BASIS,
119
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
120
+ * See the License for the specific language governing permissions and
121
+ * limitations under the License.
122
+ */
123
+ const refuseTimeout = (config) => {
124
+ if (config?.timeout !== undefined) {
125
+ throw new InvalidArgumentError('proveTxConfig.timeout is not supported by dappConnectorProofProvider: the wallet proving API takes no timeout. ' +
126
+ 'See https://github.com/midnightntwrk/midnight-dapp-connector-api/issues/97');
127
+ }
128
+ };
129
+ /**
130
+ * Creates a {@link ProofProvider} that delegates proving to a DApp Connector wallet.
131
+ *
132
+ * @remarks
133
+ * Combines a wallet-backed {@link dappConnectorProvingProvider} with the given `costModel`
134
+ * to produce a transaction-level proof provider. The wallet's proving provider is obtained
135
+ * once during initialization and reused for all subsequent `proveTx` calls.
136
+ *
137
+ * @typeParam K - Union of circuit identifier strings defined by the contract.
138
+ * @param api - DApp Connector wallet API exposing `getProvingProvider`.
139
+ * @param zkConfigProvider - A single {@link ZKConfigProvider} or a multi-source
140
+ * {@link ZKConfigRegistry} that supplies ZK configuration artifacts and key material. A registry is
141
+ * required to prove transactions that make cross-contract calls, which carry one proof per contract
142
+ * in the call tree.
143
+ * @param costModel - Cost model applied during transaction proving on the CURRENT ledger era.
144
+ *
145
+ * **Not consulted on the retained (`v8`) era**, which uses that era's own cost model instead. This
146
+ * is not an oversight and not a silent fallback: the retained ledger ships its own `CostModel`
147
+ * class and type-checks `prove()`'s argument against it across the WASM boundary, so the value
148
+ * passed here would be rejected outright. Pairing the transaction with its own era's model is the
149
+ * only correct pairing, so an override is not offered at all rather than offered and quietly
150
+ * ignored.
151
+ * @returns A {@link ProofProvider} whose `proveTx` method delegates to the wallet.
152
+ * @throws InvalidArgumentError raised by `proveTx`, before any proving starts, if
153
+ * `proveTxConfig.timeout` is set (including `0`): the wallet proving API takes no timeout.
154
+ */
155
+ const dappConnectorProofProvider = async (api, zkConfigProvider, costModel) => {
156
+ const provingProvider = await dappConnectorProvingProvider(api, zkConfigProvider);
157
+ return createProofProviderFromHandlers({
158
+ // See the `costModel` parameter above for why the v8 handler does not take one.
159
+ v8: async (tx, config) => {
160
+ refuseTimeout(config);
161
+ return proveLedger8Transaction(tx.deserialize({ v8: (await loadLedger8Protocol()).Transaction }), provingProvider);
162
+ },
163
+ v9: (tx, config) => {
164
+ refuseTimeout(config);
165
+ return tx.deserialize({ v9: Transaction }).prove(provingProvider, costModel);
166
+ }
167
+ });
168
+ };
169
+
170
+ /*
171
+ * This file is part of midnight-js.
172
+ * Copyright (C) Midnight Foundation
173
+ * SPDX-License-Identifier: Apache-2.0
174
+ * Licensed under the Apache License, Version 2.0 (the "License");
175
+ * You may not use this file except in compliance with the License.
176
+ * You may obtain a copy of the License at
177
+ * http://www.apache.org/licenses/LICENSE-2.0
178
+ * Unless required by applicable law or agreed to in writing, software
179
+ * distributed under the License is distributed on an "AS IS" BASIS,
180
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
181
+ * See the License for the specific language governing permissions and
182
+ * limitations under the License.
183
+ */
184
+ const toHex = (bytes) => Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
185
+ const fromWalletHex = (hex) => {
186
+ if (hex.length % 2 !== 0 || !/^[0-9a-f]*$/i.test(hex)) {
187
+ throw new InvalidArgumentError(`The wallet returned a transaction that is not an even-length hex string without a 0x prefix (length ${hex.length}).`);
188
+ }
189
+ return Uint8Array.from({ length: hex.length / 2 }, (_, index) => parseInt(hex.slice(index * 2, index * 2 + 2), 16));
190
+ };
191
+ const firstIdentifier = (identifiers) => {
192
+ const [txId] = identifiers;
193
+ if (txId === undefined) {
194
+ throw new InvalidArgumentError('Refusing to submit a transaction without an identifier: it could not be tracked.');
195
+ }
196
+ return txId;
197
+ };
198
+ /**
199
+ * Creates the {@link WalletProvider} and {@link MidnightProvider} of a browser dApp from a DApp Connector
200
+ * wallet, for ledger 8 and ledger 9 transactions.
201
+ *
202
+ * @remarks
203
+ * The shielded keys are read once, here. Balancing goes through `balanceUnsealedTransaction` and submission
204
+ * through `submitTransaction`. The connector takes no TTL, so the `ttl` argument of `balanceTx` is not
205
+ * forwarded and the wallet picks the expiry. See https://github.com/midnightntwrk/midnight-dapp-connector-api/issues/102
206
+ *
207
+ * A rejection from the wallet leaves these providers unchanged, with the connector's own `code`.
208
+ * `deployContract` and the `callTx` functions wrap it in `ProviderFailedError`, and that copy does not keep the
209
+ * connector's `code`; it keeps only this framework's own codes.
210
+ *
211
+ * @param api - The DApp Connector's `ConnectedAPI`, or any object with the methods in {@link DAppConnectorWalletAPI}.
212
+ * @returns The wallet provider and the midnight provider, both serving `v8` and `v9`.
213
+ * @throws InvalidArgumentError raised by `balanceTx` if the wallet answer is not even-length hex without a `0x`
214
+ * prefix, and by `submitTx`, before anything is submitted, if the transaction has no identifier.
215
+ * @throws PayloadNotATransactionError raised by `balanceTx` if the wallet answer is not a balanced transaction of
216
+ * the requested ledger.
217
+ * @throws Ledger8RuntimeMissingError raised by `balanceTx` on a ledger 8 request if the v8 runtime cannot be loaded.
218
+ */
219
+ const dappConnectorWalletProviders = async (api) => {
220
+ const { shieldedCoinPublicKey, shieldedEncryptionPublicKey } = await api.getShieldedAddresses();
221
+ const balance = async (era, tx) => deserializeTransactionAtStage(era, 'Finalized', fromWalletHex((await api.balanceUnsealedTransaction(toHex(tx.serialize()))).tx));
222
+ const submit = async (tx) => {
223
+ const txId = firstIdentifier(tx.identifiers());
224
+ await api.submitTransaction(toHex(tx.serialize()));
225
+ return txId;
226
+ };
227
+ const walletProvider = createWalletProviderFromHandlers({
228
+ getCoinPublicKey: () => shieldedCoinPublicKey,
229
+ getEncryptionPublicKey: () => shieldedEncryptionPublicKey,
230
+ v8: (tx) => balance('v8', tx),
231
+ v9: (tx) => balance('v9', tx)
232
+ });
233
+ const midnightProvider = createMidnightProviderFromHandlers({
234
+ v8: async (tx) => submit(tx.deserialize({ v8: (await loadLedger8Protocol()).Transaction })),
235
+ v9: (tx) => submit(tx.deserialize({ v9: Transaction }))
236
+ });
237
+ return { walletProvider, midnightProvider };
238
+ };
239
+
240
+ export { dappConnectorNetwork, dappConnectorProofProvider, dappConnectorProvingProvider, dappConnectorWalletProviders };
241
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../src/dapp-connector-network.ts","../src/dapp-connector-proving-provider.ts","../src/dapp-connector-proof-provider.ts","../src/dapp-connector-wallet-providers.ts"],"sourcesContent":[null,null,null,null],"names":[],"mappings":";;;;;;;AAAA;;;;;;;;;;;;;AAaG;AASH,MAAM,SAAS,GAAG,CAA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C,KAAK,CAAC,EAAE,CAAC,SAAS,EAAE,CAAC,CAAC;AAClD,QAAA,OAAO,IAAI;AACb,IAAA,CAAC;IAED,MAAM,cAAc,GAAG,gCAAgC,CAAC;AACtD,QAAA,gBAAgB,EAAE,MAAM,qBAAqB;AAC7C,QAAA,sBAAsB,EAAE,MAAM,2BAA2B;QACzD,EAAE,EAAE,CAAC,EAAE,KAAK,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC;QAC7B,EAAE,EAAE,CAAC,EAAE,KAAK,OAAO,CAAC,IAAI,EAAE,EAAE;AAC7B,KAAA,CAAC;IAEF,MAAM,gBAAgB,GAAG,kCAAkC,CAAC;QAC1D,EAAE,EAAE,OAAO,EAAE,KAAK,MAAM,CAAC,EAAE,CAAC,WAAW,CAAC,EAAE,EAAE,EAAE,CAAC,MAAM,mBAAmB,EAAE,EAAE,WAAW,EAAE,CAAC,CAAC;AAC3F,QAAA,EAAE,EAAE,CAAC,EAAE,KAAK,MAAM,CAAC,EAAE,CAAC,WAAW,CAAC,EAAE,EAAE,EAAE,WAAW,EAAE,CAAC;AACvD,KAAA,CAAC;AAEF,IAAA,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE;AAC7C;;"}
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "@midnightntwrk/midnight-js-dapp-connector-proof-provider",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "5.0.1",
4
+ "type": "module",
5
+ "description": "Implementation of proof provider leveraging the DApp Connector's proving API",
6
+ "types": "dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "default": "./dist/index.js"
11
+ }
12
+ },
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/midnightntwrk/midnight-js.git",
16
+ "directory": "packages/dapp-connector-proof-provider"
17
+ },
18
+ "homepage": "https://github.com/midnightntwrk/midnight-js/tree/main/packages/dapp-connector-proof-provider#readme",
19
+ "bugs": {
20
+ "url": "https://github.com/midnightntwrk/midnight-js/issues"
21
+ },
22
+ "author": "Midnight Foundation",
23
+ "packageManager": "yarn@4.14.1",
24
+ "license": "Apache-2.0",
25
+ "scripts": {
26
+ "clean": "rm -rf dist tsconfig.build.tsbuildinfo .rollup.cache reports coverage",
27
+ "build": "rollup -c rollup.config.mjs",
28
+ "test": "vitest run"
29
+ },
30
+ "files": [
31
+ "dist/"
32
+ ],
33
+ "dependencies": {
34
+ "@midnightntwrk/dapp-connector-api": "4.1.0",
35
+ "@midnightntwrk/midnight-js-protocol": "5.0.1",
36
+ "@midnightntwrk/midnight-js-types": "5.0.1",
37
+ "@midnightntwrk/midnight-js-utils": "5.0.1"
38
+ },
39
+ "devDependencies": {
40
+ "rollup": "^4.60.4",
41
+ "vite": "^8.3.4",
42
+ "vitest": "^5.0.4"
43
+ },
44
+ "engines": {
45
+ "node": ">=22.12"
46
+ }
6
47
  }