@claritydao/midnight-agora-sdk 0.2.0 → 1.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 (47) hide show
  1. package/README.md +58 -55
  2. package/dist/browser-providers.d.ts +24 -19
  3. package/dist/browser-providers.d.ts.map +1 -1
  4. package/dist/browser-providers.js +654 -139
  5. package/dist/browser-providers.js.map +1 -1
  6. package/dist/common-types.d.ts +13 -24
  7. package/dist/common-types.d.ts.map +1 -1
  8. package/dist/common-types.js +1 -1
  9. package/dist/common-types.js.map +1 -1
  10. package/dist/governor-api.d.ts +42 -17
  11. package/dist/governor-api.d.ts.map +1 -1
  12. package/dist/governor-api.js +233 -248
  13. package/dist/governor-api.js.map +1 -1
  14. package/dist/index.d.ts +11 -10
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +10 -9
  17. package/dist/index.js.map +1 -1
  18. package/dist/manager.d.ts +11 -11
  19. package/dist/manager.d.ts.map +1 -1
  20. package/dist/manager.js +17 -20
  21. package/dist/manager.js.map +1 -1
  22. package/dist/types.d.ts +9 -17
  23. package/dist/types.d.ts.map +1 -1
  24. package/dist/types.js.map +1 -1
  25. package/package.json +26 -26
  26. package/.prettierrc +0 -1
  27. package/LICENSE +0 -0
  28. package/eslint.config.mjs +0 -48
  29. package/src/browser-providers.ts +0 -278
  30. package/src/common-types.ts +0 -51
  31. package/src/errors.ts +0 -124
  32. package/src/governor-api.ts +0 -948
  33. package/src/index.ts +0 -51
  34. package/src/manager.ts +0 -205
  35. package/src/types.ts +0 -403
  36. package/src/utils/index.ts +0 -60
  37. package/src/validators.ts +0 -245
  38. package/test/README.md +0 -409
  39. package/test/errors.test.ts +0 -179
  40. package/test/integration/governor-api.test.ts +0 -370
  41. package/test/mocks/providers.ts +0 -130
  42. package/test/types.test.ts +0 -112
  43. package/test/utils.test.ts +0 -111
  44. package/test/validators.test.ts +0 -368
  45. package/test/wasm-init.test.ts +0 -132
  46. package/tsconfig.json +0 -18
  47. package/vitest.config.ts +0 -9
@@ -1,278 +0,0 @@
1
- import { type GovernorProviders, type GovernorCircuits } from "./common-types";
2
- import {
3
- concatMap,
4
- filter,
5
- firstValueFrom,
6
- interval,
7
- map,
8
- of,
9
- take,
10
- tap,
11
- throwError,
12
- timeout,
13
- catchError
14
- } from "rxjs";
15
- import { pipe as fnPipe } from "fp-ts/function";
16
- import { type Logger } from "pino";
17
- import {
18
- type InitialAPI,
19
- type ConnectedAPI,
20
- type Configuration
21
- } from "@midnight-ntwrk/dapp-connector-api";
22
- import { levelPrivateStateProvider } from "@midnight-ntwrk/midnight-js-level-private-state-provider";
23
- import { FetchZkConfigProvider } from "@midnight-ntwrk/midnight-js-fetch-zk-config-provider";
24
- import { httpClientProofProvider } from "@midnight-ntwrk/midnight-js-http-client-proof-provider";
25
- import { indexerPublicDataProvider } from "@midnight-ntwrk/midnight-js-indexer-public-data-provider";
26
- import {
27
- type BalancedProvingRecipe,
28
- type WalletProvider
29
- } from "@midnight-ntwrk/midnight-js-types";
30
- import type {
31
- ShieldedCoinInfo,
32
- UnprovenTransaction,
33
- TransactionId,
34
- FinalizedTransaction,
35
- CoinPublicKey,
36
- EncPublicKey
37
- } from "@midnight-ntwrk/ledger-v6";
38
- import semver from "semver";
39
- import {
40
- getNetworkId,
41
- setNetworkId
42
- } from "@midnight-ntwrk/midnight-js-network-id";
43
-
44
- // Helper functions for hex encoding/decoding
45
- const toHexString = (bytes: Uint8Array): string =>
46
- Array.from(bytes)
47
- .map((b) => b.toString(16).padStart(2, "0"))
48
- .join("");
49
-
50
- const _fromHexString = (hex: string): Uint8Array =>
51
- new Uint8Array(hex.match(/.{1,2}/g)!.map((byte) => parseInt(byte, 16)));
52
-
53
- /**
54
- * Initializes and returns the providers required for Governor contract interactions in a browser environment.
55
- *
56
- * @param logger The logger instance for logging.
57
- * @param networkId The network ID to connect to (e.g., 'testnet', 'mainnet').
58
- * @returns A promise that resolves to configured GovernorProviders.
59
- *
60
- * @remarks
61
- * This function connects to the Midnight Lace wallet extension and retrieves network configuration
62
- * from the wallet. The network ID is specified by the caller.
63
- */
64
- export const initializeProviders = async (
65
- logger: Logger,
66
- networkId: string = "testnet"
67
- ): Promise<GovernorProviders> => {
68
- const { wallet, config } = await connectToWallet(logger, networkId);
69
- const zkConfigPath = window.location.origin;
70
-
71
- logger.info(`Connecting to wallet with network ID: ${getNetworkId()}`);
72
-
73
- // Get wallet addresses
74
- const addresses = await wallet.getShieldedAddresses();
75
-
76
- // Create wallet provider first (needed for private state encryption)
77
- const walletProvider = createWalletProvider(wallet, addresses);
78
-
79
- return {
80
- privateStateProvider: levelPrivateStateProvider({
81
- privateStateStoreName: "governor-private-state",
82
- walletProvider: walletProvider
83
- }),
84
- zkConfigProvider: new FetchZkConfigProvider<GovernorCircuits>(
85
- zkConfigPath,
86
- fetch.bind(window)
87
- ),
88
- proofProvider: config.proverServerUri
89
- ? httpClientProofProvider(config.proverServerUri)
90
- : httpClientProofProvider(""), // Fallback - proving may be done by wallet
91
- publicDataProvider: indexerPublicDataProvider(
92
- config.indexerUri,
93
- config.indexerWsUri
94
- ),
95
- walletProvider,
96
- midnightProvider: {
97
- async submitTx(tx: FinalizedTransaction): Promise<TransactionId> {
98
- // Convert transaction to hex string for the connector API
99
- const serialized = tx.serialize();
100
- const hexString = toHexString(serialized);
101
- await wallet.submitTransaction(hexString);
102
- // Return the transaction hash as the ID
103
- return tx.transactionHash() as TransactionId;
104
- }
105
- }
106
- };
107
- };
108
-
109
- /**
110
- * Creates a WalletProvider from the connected wallet API.
111
- */
112
- const createWalletProvider = (
113
- wallet: ConnectedAPI,
114
- addresses: {
115
- shieldedCoinPublicKey: string;
116
- shieldedEncryptionPublicKey: string;
117
- }
118
- ): WalletProvider => {
119
- // Note: The bech32m addresses need to be converted to the expected key types
120
- // This conversion may need adjustment based on the actual key format expected
121
- const coinPublicKey =
122
- addresses.shieldedCoinPublicKey as unknown as CoinPublicKey;
123
- const encryptionPublicKey =
124
- addresses.shieldedEncryptionPublicKey as unknown as EncPublicKey;
125
-
126
- return {
127
- getCoinPublicKey(): CoinPublicKey {
128
- return coinPublicKey;
129
- },
130
- getEncryptionPublicKey(): EncPublicKey {
131
- return encryptionPublicKey;
132
- },
133
- async balanceTx(
134
- tx: UnprovenTransaction,
135
- _newCoins?: ShieldedCoinInfo[],
136
- _ttl?: Date
137
- ): Promise<BalancedProvingRecipe> {
138
- // Use the wallet's balancing capability
139
- // Convert Uint8Array to hex string for the connector API
140
- const serialized = tx.serialize();
141
- const hexString = toHexString(serialized);
142
- const _result = await wallet.balanceUnsealedTransaction(hexString);
143
-
144
- // The wallet returns a balanced transaction as a hex string
145
- // We need to convert it back and return as NothingToProve
146
- // Note: The actual deserialization may need the Transaction.deserialize with proper markers
147
- // For now, we return the original transaction as the wallet handles proving internally
148
- return {
149
- type: "NothingToProve" as const,
150
- transaction: tx // The wallet should have balanced this
151
- };
152
- }
153
- };
154
- };
155
-
156
- /**
157
- * Connects to the Midnight Lace wallet extension.
158
- *
159
- * @param logger The logger instance for logging.
160
- * @param networkId The network ID to connect to.
161
- * @returns A promise that resolves to the wallet API and configuration.
162
- */
163
- const connectToWallet = (
164
- logger: Logger,
165
- networkId: string
166
- ): Promise<{ wallet: ConnectedAPI; config: Configuration }> => {
167
- const COMPATIBLE_CONNECTOR_API_VERSION = "4.x";
168
-
169
- return firstValueFrom(
170
- fnPipe(
171
- interval(100),
172
- map(() => {
173
- // Find wallet in window.midnight
174
- const midnight = window.midnight;
175
- if (!midnight) return undefined;
176
-
177
- // The new API uses rdns keys instead of named keys like mnLace
178
- // Look for any available wallet
179
- const walletKeys = Object.keys(midnight).filter(
180
- (key) => key !== "addEventListener"
181
- );
182
- if (walletKeys.length === 0) return undefined;
183
-
184
- return midnight[walletKeys[0]] as InitialAPI | undefined;
185
- }),
186
- tap((connectorAPI) => {
187
- logger.info(connectorAPI, "Check for wallet connector API");
188
- }),
189
- filter((connectorAPI): connectorAPI is InitialAPI => !!connectorAPI),
190
- concatMap((connectorAPI) =>
191
- semver.satisfies(
192
- connectorAPI.apiVersion,
193
- COMPATIBLE_CONNECTOR_API_VERSION
194
- )
195
- ? of(connectorAPI)
196
- : throwError(() => {
197
- logger.error(
198
- {
199
- expected: COMPATIBLE_CONNECTOR_API_VERSION,
200
- actual: connectorAPI.apiVersion
201
- },
202
- "Incompatible version of wallet connector API"
203
- );
204
-
205
- return new Error(
206
- `Incompatible version of Midnight Lace wallet found. Require '${COMPATIBLE_CONNECTOR_API_VERSION}', got '${connectorAPI.apiVersion}'.`
207
- );
208
- })
209
- ),
210
- tap((connectorAPI) => {
211
- logger.info(
212
- connectorAPI,
213
- "Compatible wallet connector API found. Connecting."
214
- );
215
- }),
216
- take(1),
217
- timeout({
218
- first: 1_000,
219
- with: () =>
220
- throwError(() => {
221
- logger.error("Could not find wallet connector API");
222
-
223
- return new Error(
224
- "Could not find Midnight Lace wallet. Extension installed?"
225
- );
226
- })
227
- }),
228
- concatMap(async (connectorAPI) => {
229
- // Connect to the wallet with the specified network ID
230
- const connectedAPI = await connectorAPI.connect(networkId);
231
-
232
- // Set the network ID globally
233
- setNetworkId(networkId);
234
-
235
- logger.info("Connected to wallet");
236
-
237
- return { walletConnectorAPI: connectedAPI, connectorAPI };
238
- }),
239
- timeout({
240
- first: 30_000, // Increased timeout for user approval
241
- with: () =>
242
- throwError(() => {
243
- logger.error("Wallet connector API has failed to respond");
244
-
245
- return new Error(
246
- "Midnight Lace wallet has failed to respond. Extension enabled?"
247
- );
248
- })
249
- }),
250
- catchError((error, apis) =>
251
- error
252
- ? throwError(() => {
253
- logger.error("Unable to connect to wallet");
254
- return new Error(
255
- "Application is not authorized or connection failed"
256
- );
257
- })
258
- : apis
259
- ),
260
- concatMap(async ({ walletConnectorAPI }) => {
261
- const config = await walletConnectorAPI.getConfiguration();
262
-
263
- logger.info(
264
- "Connected to wallet connector API and retrieved service configuration"
265
- );
266
-
267
- return { wallet: walletConnectorAPI, config };
268
- })
269
- )
270
- );
271
- };
272
-
273
- // Extend Window interface for TypeScript
274
- declare global {
275
- interface Window {
276
- midnight?: Record<string, InitialAPI>;
277
- }
278
- }
@@ -1,51 +0,0 @@
1
- import type {
2
- ImpureCircuitId,
3
- MidnightProviders,
4
- Contract
5
- } from "@midnight-ntwrk/midnight-js-types";
6
- import type {
7
- DeployedContract,
8
- FoundContract
9
- } from "@midnight-ntwrk/midnight-js-contracts";
10
-
11
- // Use Contract type from midnight-js-types to avoid importing the actual Contract class
12
- // This prevents eager loading of the contract CJS module which requires WASM
13
- export type GovernorContract = Contract;
14
-
15
- export type GovernorCircuits = ImpureCircuitId<GovernorContract>;
16
-
17
- export const GovernorPrivateStateId = "governorPrivateState";
18
-
19
- // Define GovernorPrivateState type locally to avoid importing from contract module
20
- // which would trigger WASM initialization
21
- export type GovernorPrivateState = {
22
- secretKey: Uint8Array | null;
23
- currentTime: bigint;
24
- userStake: {
25
- amount: bigint;
26
- delegatedTo: Uint8Array;
27
- stakedAt: bigint;
28
- };
29
- votingHistory: any[];
30
- proposalHistory: any[];
31
- governanceConfig: {
32
- votingPeriod: bigint;
33
- quorumThreshold: bigint;
34
- proposalThreshold: bigint;
35
- proposalLifetime: bigint;
36
- executionDelay: bigint;
37
- gracePeriod: bigint;
38
- minStakeAmount: bigint;
39
- stakingPeriod: bigint;
40
- };
41
- };
42
-
43
- export type GovernorProviders = MidnightProviders<
44
- GovernorCircuits,
45
- typeof GovernorPrivateStateId,
46
- GovernorPrivateState
47
- >;
48
-
49
- export type DeployedGovernorContract =
50
- | DeployedContract<GovernorContract>
51
- | FoundContract<GovernorContract>;
package/src/errors.ts DELETED
@@ -1,124 +0,0 @@
1
- /**
2
- * Custom error classes for the Agora DAO Governor SDK.
3
- *
4
- * @module errors
5
- */
6
-
7
- /**
8
- * Base error class for all SDK errors.
9
- */
10
- export class GovernorSDKError extends Error {
11
- constructor(message: string) {
12
- super(message);
13
- this.name = "GovernorSDKError";
14
- Object.setPrototypeOf(this, GovernorSDKError.prototype);
15
- }
16
- }
17
-
18
- /**
19
- * Thrown when wallet is not connected.
20
- */
21
- export class WalletNotConnectedError extends GovernorSDKError {
22
- constructor() {
23
- super(
24
- "Wallet not connected. Please ensure Lace wallet is installed and connected."
25
- );
26
- this.name = "WalletNotConnectedError";
27
- Object.setPrototypeOf(this, WalletNotConnectedError.prototype);
28
- }
29
- }
30
-
31
- /**
32
- * Thrown when user has insufficient stake for an operation.
33
- */
34
- export class InsufficientStakeError extends GovernorSDKError {
35
- constructor(required: bigint, actual: bigint) {
36
- super(`Insufficient stake. Required: ${required}, Actual: ${actual}`);
37
- this.name = "InsufficientStakeError";
38
- Object.setPrototypeOf(this, InsufficientStakeError.prototype);
39
- }
40
- }
41
-
42
- /**
43
- * Thrown when a parameter is invalid.
44
- */
45
- export class InvalidParameterError extends GovernorSDKError {
46
- constructor(parameterName: string, reason: string) {
47
- super(`Invalid parameter '${parameterName}': ${reason}`);
48
- this.name = "InvalidParameterError";
49
- Object.setPrototypeOf(this, InvalidParameterError.prototype);
50
- }
51
- }
52
-
53
- /**
54
- * Thrown when a contract is not found at the specified address.
55
- */
56
- export class ContractNotFoundError extends GovernorSDKError {
57
- constructor(address: string) {
58
- super(`Contract not found at address: ${address}`);
59
- this.name = "ContractNotFoundError";
60
- Object.setPrototypeOf(this, ContractNotFoundError.prototype);
61
- }
62
- }
63
-
64
- /**
65
- * Thrown when a proposal is not found.
66
- */
67
- export class ProposalNotFoundError extends GovernorSDKError {
68
- constructor(proposalId: bigint) {
69
- super(`Proposal not found with ID: ${proposalId}`);
70
- this.name = "ProposalNotFoundError";
71
- Object.setPrototypeOf(this, ProposalNotFoundError.prototype);
72
- }
73
- }
74
-
75
- /**
76
- * Thrown when a transaction fails.
77
- */
78
- export class TransactionError extends GovernorSDKError {
79
- constructor(
80
- message: string,
81
- public readonly txHash?: string
82
- ) {
83
- super(
84
- `Transaction failed: ${message}${txHash ? ` (txHash: ${txHash})` : ""}`
85
- );
86
- this.name = "TransactionError";
87
- Object.setPrototypeOf(this, TransactionError.prototype);
88
- }
89
- }
90
-
91
- /**
92
- * Thrown when contract deployment fails.
93
- */
94
- export class DeploymentError extends GovernorSDKError {
95
- constructor(message: string) {
96
- super(`Contract deployment failed: ${message}`);
97
- this.name = "DeploymentError";
98
- Object.setPrototypeOf(this, DeploymentError.prototype);
99
- }
100
- }
101
-
102
- /**
103
- * Thrown when configuration is invalid.
104
- */
105
- export class InvalidConfigurationError extends GovernorSDKError {
106
- constructor(message: string) {
107
- super(`Invalid configuration: ${message}`);
108
- this.name = "InvalidConfigurationError";
109
- Object.setPrototypeOf(this, InvalidConfigurationError.prototype);
110
- }
111
- }
112
-
113
- /**
114
- * Thrown when network ID is not set.
115
- */
116
- export class NetworkNotConfiguredError extends GovernorSDKError {
117
- constructor() {
118
- super(
119
- "Network ID not configured. Set window.midnight.mnLace.networkId before initializing providers."
120
- );
121
- this.name = "NetworkNotConfiguredError";
122
- Object.setPrototypeOf(this, NetworkNotConfiguredError.prototype);
123
- }
124
- }