@openzeppelin/compact-deployer 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 (103) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +304 -0
  3. package/dist/config/compact-config.d.ts +31 -0
  4. package/dist/config/compact-config.js +123 -0
  5. package/dist/config/compact-config.js.map +1 -0
  6. package/dist/config/schema.d.ts +688 -0
  7. package/dist/config/schema.js +90 -0
  8. package/dist/config/schema.js.map +1 -0
  9. package/dist/deployer.d.ts +154 -0
  10. package/dist/deployer.js +916 -0
  11. package/dist/deployer.js.map +1 -0
  12. package/dist/deployments.d.ts +119 -0
  13. package/dist/deployments.js +144 -0
  14. package/dist/deployments.js.map +1 -0
  15. package/dist/errors.d.ts +94 -0
  16. package/dist/errors.js +124 -0
  17. package/dist/errors.js.map +1 -0
  18. package/dist/loaders/args.d.ts +22 -0
  19. package/dist/loaders/args.js +72 -0
  20. package/dist/loaders/args.js.map +1 -0
  21. package/dist/loaders/argv.d.ts +36 -0
  22. package/dist/loaders/argv.js +101 -0
  23. package/dist/loaders/argv.js.map +1 -0
  24. package/dist/loaders/artifact-path.d.ts +16 -0
  25. package/dist/loaders/artifact-path.js +35 -0
  26. package/dist/loaders/artifact-path.js.map +1 -0
  27. package/dist/loaders/artifact.d.ts +43 -0
  28. package/dist/loaders/artifact.js +115 -0
  29. package/dist/loaders/artifact.js.map +1 -0
  30. package/dist/loaders/constructor-meta.d.ts +17 -0
  31. package/dist/loaders/constructor-meta.js +99 -0
  32. package/dist/loaders/constructor-meta.js.map +1 -0
  33. package/dist/loaders/context.d.ts +14 -0
  34. package/dist/loaders/context.js +43 -0
  35. package/dist/loaders/context.js.map +1 -0
  36. package/dist/loaders/contract-resolve.d.ts +15 -0
  37. package/dist/loaders/contract-resolve.js +53 -0
  38. package/dist/loaders/contract-resolve.js.map +1 -0
  39. package/dist/loaders/init-state.d.ts +8 -0
  40. package/dist/loaders/init-state.js +37 -0
  41. package/dist/loaders/init-state.js.map +1 -0
  42. package/dist/loaders/ref-resolver.d.ts +8 -0
  43. package/dist/loaders/ref-resolver.js +27 -0
  44. package/dist/loaders/ref-resolver.js.map +1 -0
  45. package/dist/loaders/signing-key.d.ts +10 -0
  46. package/dist/loaders/signing-key.js +23 -0
  47. package/dist/loaders/signing-key.js.map +1 -0
  48. package/dist/providers/build.d.ts +20 -0
  49. package/dist/providers/build.js +41 -0
  50. package/dist/providers/build.js.map +1 -0
  51. package/dist/providers/network.d.ts +6 -0
  52. package/dist/providers/network.js +36 -0
  53. package/dist/providers/network.js.map +1 -0
  54. package/dist/providers/private-state-password.d.ts +12 -0
  55. package/dist/providers/private-state-password.js +27 -0
  56. package/dist/providers/private-state-password.js.map +1 -0
  57. package/dist/providers/proof-server.d.ts +29 -0
  58. package/dist/providers/proof-server.js +97 -0
  59. package/dist/providers/proof-server.js.map +1 -0
  60. package/dist/runDeploy.d.ts +167 -0
  61. package/dist/runDeploy.js +228 -0
  62. package/dist/runDeploy.js.map +1 -0
  63. package/dist/services/atomic-json.d.ts +7 -0
  64. package/dist/services/atomic-json.js +34 -0
  65. package/dist/services/atomic-json.js.map +1 -0
  66. package/dist/services/chain-state.d.ts +75 -0
  67. package/dist/services/chain-state.js +151 -0
  68. package/dist/services/chain-state.js.map +1 -0
  69. package/dist/services/contract-state.d.ts +29 -0
  70. package/dist/services/contract-state.js +54 -0
  71. package/dist/services/contract-state.js.map +1 -0
  72. package/dist/services/deploy-plan.d.ts +36 -0
  73. package/dist/services/deploy-plan.js +45 -0
  74. package/dist/services/deploy-plan.js.map +1 -0
  75. package/dist/services/deploy-tx.d.ts +189 -0
  76. package/dist/services/deploy-tx.js +297 -0
  77. package/dist/services/deploy-tx.js.map +1 -0
  78. package/dist/services/error-format.d.ts +10 -0
  79. package/dist/services/error-format.js +91 -0
  80. package/dist/services/error-format.js.map +1 -0
  81. package/dist/services/file-lock.d.ts +23 -0
  82. package/dist/services/file-lock.js +90 -0
  83. package/dist/services/file-lock.js.map +1 -0
  84. package/dist/services/maintenance-tx.d.ts +49 -0
  85. package/dist/services/maintenance-tx.js +43 -0
  86. package/dist/services/maintenance-tx.js.map +1 -0
  87. package/dist/services/wallet-cache.d.ts +99 -0
  88. package/dist/services/wallet-cache.js +239 -0
  89. package/dist/services/wallet-cache.js.map +1 -0
  90. package/dist/services/wallet-sync.d.ts +89 -0
  91. package/dist/services/wallet-sync.js +249 -0
  92. package/dist/services/wallet-sync.js.map +1 -0
  93. package/dist/wallet/handler.d.ts +64 -0
  94. package/dist/wallet/handler.js +151 -0
  95. package/dist/wallet/handler.js.map +1 -0
  96. package/dist/wallet/keystore.d.ts +55 -0
  97. package/dist/wallet/keystore.js +213 -0
  98. package/dist/wallet/keystore.js.map +1 -0
  99. package/dist/wallet/seeds.d.ts +41 -0
  100. package/dist/wallet/seeds.js +84 -0
  101. package/dist/wallet/seeds.js.map +1 -0
  102. package/package.json +133 -0
  103. package/proof-server.yml +16 -0
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Partitions a contract's circuits into deploy fragments. Fragment 0 rides the
3
+ * deploy tx; every later fragment becomes one batched verifier-key insert.
4
+ *
5
+ * The budget is always explicit or derived by halving on a rejection: the node
6
+ * cannot weigh a transaction before submission, so there is nothing to plan
7
+ * against.
8
+ *
9
+ * Pure: no clock, no randomness, no I/O, so a rerun after an interruption
10
+ * rebuilds the same plan.
11
+ */
12
+ /**
13
+ * Code-unit sort. `localeCompare` would reorder the same circuit list under a
14
+ * different `LANG`, and the fragment plan has to be reproducible across hosts.
15
+ */
16
+ export function sortCircuits(circuits) {
17
+ return [...circuits].sort();
18
+ }
19
+ /**
20
+ * Split sorted `circuits` into fragments of at most `budget`
21
+ * each. Validated at the edges (TOML schema, argv, `Deployer.prepare`), so
22
+ * `budget` is trusted to be an integer of at least one.
23
+ */
24
+ export function planFragments(circuits, budget) {
25
+ const sorted = sortCircuits(circuits);
26
+ const fragments = [];
27
+ for (let i = 0; i < sorted.length; i += budget) {
28
+ fragments.push({
29
+ index: fragments.length,
30
+ circuits: sorted.slice(i, i + budget),
31
+ });
32
+ }
33
+ return { circuits: sorted, fragments };
34
+ }
35
+ /** Artifact circuits absent from `onChain`, sorted. */
36
+ export function remaining(circuits, onChain) {
37
+ const present = new Set(onChain);
38
+ return sortCircuits(circuits).filter((c) => !present.has(c));
39
+ }
40
+ /** Circuits of `fragment` that are not yet on chain, in plan order. */
41
+ export function fragmentRemainder(fragment, onChain) {
42
+ const present = new Set(onChain);
43
+ return fragment.circuits.filter((c) => !present.has(c));
44
+ }
45
+ //# sourceMappingURL=deploy-plan.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deploy-plan.js","sourceRoot":"","sources":["../../src/services/deploy-plan.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAcH;;;GAGG;AACH,MAAM,UAAU,YAAY,CAAC,QAA2B;IACtD,OAAO,CAAC,GAAG,QAAQ,CAAC,CAAC,IAAI,EAAE,CAAC;AAC9B,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,aAAa,CAC3B,QAA2B,EAC3B,MAAc;IAEd,MAAM,MAAM,GAAG,YAAY,CAAC,QAAQ,CAAC,CAAC;IACtC,MAAM,SAAS,GAAe,EAAE,CAAC;IACjC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,IAAI,MAAM,EAAE,CAAC;QAC/C,SAAS,CAAC,IAAI,CAAC;YACb,KAAK,EAAE,SAAS,CAAC,MAAM;YACvB,QAAQ,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC;SACtC,CAAC,CAAC;IACL,CAAC;IACD,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC;AACzC,CAAC;AAED,uDAAuD;AACvD,MAAM,UAAU,SAAS,CACvB,QAA2B,EAC3B,OAA0B;IAE1B,MAAM,OAAO,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC;IACjC,OAAO,YAAY,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;AAC/D,CAAC;AAED,uEAAuE;AACvE,MAAM,UAAU,iBAAiB,CAC/B,QAAkB,EAClB,OAA0B;IAE1B,MAAM,OAAO,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC;IACjC,OAAO,QAAQ,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;AAC1D,CAAC"}
@@ -0,0 +1,189 @@
1
+ import { type ContractProviders, submitTxAsync } from '@midnight-ntwrk/midnight-js-contracts';
2
+ import { type FinalizedTxData, type PrivateStateProvider } from '@midnight-ntwrk/midnight-js-types';
3
+ import type { ContractConfig } from '../config/schema.ts';
4
+ import type { ConfirmedDeploymentRecord, PartialDeploymentRecord, PendingDeploymentRecord } from '../deployments.ts';
5
+ import type { Artifact } from '../loaders/artifact.ts';
6
+ /**
7
+ * Ceiling on the wait for finalization. The indexer stops reporting on a tx
8
+ * that never lands, and `watchForTxData` waits forever, so without a ceiling a
9
+ * dropped WebSocket hangs the CLI with no way out but Ctrl-C.
10
+ */
11
+ export declare const DEFAULT_TX_TIMEOUT_MS = 600000;
12
+ /** An unproven tx as `submitTxAsync` accepts it. */
13
+ export type UnprovenTx = Parameters<typeof submitTxAsync>[1]['unprovenTx'];
14
+ /** The signing key as the private-state store accepts it. */
15
+ type PersistedSigningKey = Parameters<PrivateStateProvider['setSigningKey']>[1];
16
+ /**
17
+ * The fields of a constructor result this package reads. Narrower than the
18
+ * SDK's own return type, which both builders satisfy structurally, so neither
19
+ * needs a cast.
20
+ */
21
+ interface UnsubmittedDeploy {
22
+ public: {
23
+ contractAddress: string;
24
+ };
25
+ private: {
26
+ unprovenTx: UnprovenTx;
27
+ signingKey: PersistedSigningKey;
28
+ initialPrivateState: unknown;
29
+ };
30
+ }
31
+ export interface SubmitDeployArgs {
32
+ providers: ContractProviders;
33
+ contractName: string;
34
+ contract: ContractConfig;
35
+ artifact: Artifact;
36
+ signingKey: string;
37
+ args: readonly unknown[];
38
+ initialPrivateState: unknown;
39
+ /**
40
+ * Circuits whose verifier keys ride the deploy tx. The artifact's full list
41
+ * takes the unmodified single-tx path; a subset prunes the constructor state
42
+ * and the rest arrive as maintenance updates.
43
+ */
44
+ circuits: readonly string[];
45
+ }
46
+ /**
47
+ * A deploy tx the node accepted. `address` and `txId` identify the contract
48
+ * before finalization, which is what makes a pending ledger record possible.
49
+ *
50
+ * `unsubmitted` carries the signing key and the initial private state. Never
51
+ * log or serialize it; {@link persistDeployPrivateState} is its only consumer.
52
+ */
53
+ export interface SubmittedDeploy {
54
+ address: string;
55
+ txId: string;
56
+ unsubmitted: UnsubmittedDeploy;
57
+ }
58
+ /**
59
+ * Build and submit the deploy tx, returning as soon as the node accepts it.
60
+ * Split from the wait for finalization so the caller can persist `txId`
61
+ * first; `deployContract` fuses the two and yields no identifier until the
62
+ * tx has already landed.
63
+ */
64
+ export declare function submitDeploy(submitArgs: SubmitDeployArgs): Promise<SubmittedDeploy>;
65
+ export interface AwaitDeployFinalizationArgs {
66
+ providers: ContractProviders;
67
+ contractName: string;
68
+ submitted: SubmittedDeploy;
69
+ txTimeoutMs: number;
70
+ /** The record this deploy wrote, which is what the operator has to act on. */
71
+ recovery: 'pending' | 'partial';
72
+ }
73
+ /**
74
+ * Wait for one transaction to land, capped at `txTimeoutMs`, rejecting
75
+ * any status other than `SucceedEntirely`.
76
+ *
77
+ * `fail` supplies the caller's error type, so the deploy tx and a fragment
78
+ * insert share the ceiling and the status rule while reporting differently.
79
+ */
80
+ export declare function awaitFinalization({ providers, txId, txTimeoutMs, fail, }: {
81
+ providers: ContractProviders;
82
+ txId: string;
83
+ txTimeoutMs: number;
84
+ fail: FinalizationFail;
85
+ }): Promise<FinalizedTxData>;
86
+ /**
87
+ * Settle the deploy transaction by address rather than by a recorded id.
88
+ *
89
+ * A `txId` read back from the deployments file may be corrupt, in which case a
90
+ * watch on it never returns, or may belong to a different contract, in which
91
+ * case it returns data that has nothing to do with this address.
92
+ */
93
+ export declare function awaitDeployTxData({ providers, address, txTimeoutMs, fail, }: {
94
+ providers: ContractProviders;
95
+ address: string;
96
+ txTimeoutMs: number;
97
+ fail: FinalizationFail;
98
+ }): Promise<FinalizedTxData>;
99
+ /**
100
+ * One wait, one ceiling, one `SucceedEntirely` rule. `fail` supplies
101
+ * the caller's error type and learns whether the ceiling was what stopped it,
102
+ * which is the difference between a transaction still in flight and one the
103
+ * node has ruled on.
104
+ */
105
+ type FinalizationFail = (reason: string, detail?: {
106
+ cause?: unknown;
107
+ timedOut?: boolean;
108
+ }) => Error;
109
+ /** Wait for the deploy tx to land. The pending record survives every failure. */
110
+ export declare function awaitDeployFinalization({ providers, contractName, submitted, txTimeoutMs, recovery, }: AwaitDeployFinalizationArgs): Promise<FinalizedTxData>;
111
+ export interface SubmitInsertArgs {
112
+ providers: ContractProviders;
113
+ contractName: string;
114
+ unprovenTx: UnprovenTx;
115
+ /** Circuits in this batch. Named in a block-limit refusal. */
116
+ circuits: readonly string[];
117
+ }
118
+ /**
119
+ * Submit one verifier-key insert, classifying a block-limit refusal the way
120
+ * {@link submitDeploy} does so the caller can halve the batch and retry.
121
+ */
122
+ export declare function submitInsert({ providers, contractName, unprovenTx, circuits, }: SubmitInsertArgs): Promise<string>;
123
+ export interface AwaitFragmentFinalizationArgs {
124
+ providers: ContractProviders;
125
+ address: string;
126
+ txId: string;
127
+ txTimeoutMs: number;
128
+ /** Reported in the error so a stopped run can be reconciled by hand. */
129
+ circuitsOnChain: readonly string[];
130
+ circuitsPending: readonly string[];
131
+ }
132
+ /**
133
+ * Wait for one transaction of a fragmented deploy to land, under the
134
+ * same ceiling and the same `SucceedEntirely` rule as the deploy tx. A partially
135
+ * applied update must not be treated as landed: verify would then be skipped
136
+ * for those circuits.
137
+ */
138
+ export declare function awaitFragmentFinalization({ providers, address, txId, txTimeoutMs, circuitsOnChain, circuitsPending, }: AwaitFragmentFinalizationArgs): Promise<FinalizedTxData>;
139
+ export interface PersistDeployPrivateStateArgs {
140
+ providers: ContractProviders;
141
+ contract: ContractConfig;
142
+ submitted: SubmittedDeploy;
143
+ }
144
+ /**
145
+ * Store the signing key and initial private state for the deployed
146
+ * address. Call only after a `SucceedEntirely` status: a rejected tx must not leave
147
+ * local state behind for a contract that does not exist.
148
+ */
149
+ export declare function persistDeployPrivateState({ providers, contract, submitted, }: PersistDeployPrivateStateArgs): Promise<void>;
150
+ /** Build `<explorer>/contracts/0x<address>`, or `''` when no explorer / no address. */
151
+ export declare function buildExplorerUrl(base: string | undefined, address: string): string;
152
+ export declare function toPendingRecord({ submitted, deployer, artifact, }: {
153
+ submitted: SubmittedDeploy;
154
+ deployer: string;
155
+ artifact: string;
156
+ }): PendingDeploymentRecord;
157
+ export interface ToPartialRecordArgs {
158
+ address: string;
159
+ /** The deploy tx, carried unchanged across every progress rewrite. */
160
+ txId: string;
161
+ deployer: string;
162
+ artifact: string;
163
+ /** The artifact's full circuit list. */
164
+ circuits: readonly string[];
165
+ /** From the most recent chain read. */
166
+ circuitsOnChain: readonly string[];
167
+ submittedAt?: string;
168
+ /** Deploy-tx identifiers, so a resume can promote without re-awaiting it. */
169
+ txHash?: string;
170
+ blockHeight?: number;
171
+ /** An insert submitted but never seen to land, and the circuits it carried. */
172
+ pendingTxId?: string;
173
+ pendingCircuits?: readonly string[];
174
+ }
175
+ /**
176
+ * Progress record for a fragmented deploy.
177
+ *
178
+ * `circuitsOnChain` must come from a chain read: a record built from the plan
179
+ * would claim circuits landed whose insert actually failed.
180
+ */
181
+ export declare function toPartialRecord({ address, txId, deployer, artifact, circuits, circuitsOnChain, submittedAt, txHash, blockHeight, pendingTxId, pendingCircuits, }: ToPartialRecordArgs): PartialDeploymentRecord;
182
+ export declare function toConfirmedRecord({ previous, txHash, blockHeight, }: {
183
+ /** The head this deploy wrote: `pending` for a single tx, `partial` for a split. */
184
+ previous: PendingDeploymentRecord | PartialDeploymentRecord;
185
+ /** From the deploy tx's finalization, or carried across a resume. */
186
+ txHash: string;
187
+ blockHeight: number;
188
+ }): ConfirmedDeploymentRecord;
189
+ export {};
@@ -0,0 +1,297 @@
1
+ import { ContractExecutable } from '@midnight-ntwrk/compact-js';
2
+ import { ContractDeploy, Intent, Transaction } from '@midnight-ntwrk/ledger-v8';
3
+ import { createUnprovenDeployTx, submitTxAsync, } from '@midnight-ntwrk/midnight-js-contracts';
4
+ import { getNetworkId } from '@midnight-ntwrk/midnight-js-network-id';
5
+ import { exitResultOrError, makeContractExecutableRuntime, SucceedEntirely, } from '@midnight-ntwrk/midnight-js-types';
6
+ import { parseCoinPublicKeyToHex, ttlOneHour, } from '@midnight-ntwrk/midnight-js-utils';
7
+ import { BlockLimitError, ConfigError, DeployError, DeployTxFailedError, FragmentDeployError, } from "../errors.js";
8
+ import { pruneState } from "./contract-state.js";
9
+ import { remaining, sortCircuits } from "./deploy-plan.js";
10
+ import { formatError } from "./error-format.js";
11
+ /**
12
+ * Ceiling on the wait for finalization. The indexer stops reporting on a tx
13
+ * that never lands, and `watchForTxData` waits forever, so without a ceiling a
14
+ * dropped WebSocket hangs the CLI with no way out but Ctrl-C.
15
+ */
16
+ export const DEFAULT_TX_TIMEOUT_MS = 600_000;
17
+ /**
18
+ * Whether a submission failure is the pool refusing an over-large extrinsic.
19
+ *
20
+ * The node returns `1010: Invalid Transaction: Transaction would exhaust the
21
+ * block limits`, and that text is the only signal the pool gives: midnight-node
22
+ * 0.22.2 exposes no `payment_queryInfo` and carries no transaction-payment
23
+ * pallet, so the transaction cannot be weighed before submission. Both halves
24
+ * are required, since other `1010` causes must stay ordinary tx failures.
25
+ */
26
+ function isBlockLimitRejection(error) {
27
+ const text = formatError(error);
28
+ return text.includes('1010') && /exhaust the block limits/i.test(text);
29
+ }
30
+ /**
31
+ * Build and submit the deploy tx, returning as soon as the node accepts it.
32
+ * Split from the wait for finalization so the caller can persist `txId`
33
+ * first; `deployContract` fuses the two and yields no identifier until the
34
+ * tx has already landed.
35
+ */
36
+ export async function submitDeploy(submitArgs) {
37
+ const { providers, contractName, artifact, circuits } = submitArgs;
38
+ const pruning = circuits.length < artifact.circuitNames.length;
39
+ try {
40
+ const unsubmitted = pruning
41
+ ? await buildPrunedDeploy(submitArgs)
42
+ : await buildFullDeploy(submitArgs);
43
+ const txId = await submitClassified(`Deploy of "${contractName}"`, circuits.length, () => submitTxAsync(providers, {
44
+ unprovenTx: unsubmitted.private.unprovenTx,
45
+ }));
46
+ return {
47
+ address: unsubmitted.public.contractAddress,
48
+ txId,
49
+ unsubmitted,
50
+ };
51
+ }
52
+ catch (e) {
53
+ // Our own gates already carry the right exit code and message.
54
+ if (e instanceof DeployError)
55
+ throw e;
56
+ throw new DeployTxFailedError(`Deploy of "${contractName}" failed: ${formatError(e)}`, { cause: e });
57
+ }
58
+ }
59
+ /**
60
+ * Run `submit`, turning the pool's refusal of an over-large extrinsic into a
61
+ * {@link BlockLimitError} the caller can halve on.
62
+ *
63
+ * This is the only place a refusal becomes halvable, so the deploy tx
64
+ * and every insert classify it identically.
65
+ */
66
+ async function submitClassified(what, size, submit) {
67
+ try {
68
+ return await submit();
69
+ }
70
+ catch (e) {
71
+ if (isBlockLimitRejection(e)) {
72
+ throw new BlockLimitError(`${what} was refused by the node as too large for one block at ${size} circuit(s): ${formatError(e)}`, { cause: e });
73
+ }
74
+ throw e;
75
+ }
76
+ }
77
+ /** Today's path, one tx carrying the constructor state and every verifier key. */
78
+ function buildFullDeploy({ providers, contract, artifact, signingKey, args, initialPrivateState, }) {
79
+ const base = {
80
+ compiledContract: artifact.compiledContract,
81
+ signingKey,
82
+ args,
83
+ };
84
+ const deployOptions = contract.private_state_id !== undefined
85
+ ? { ...base, initialPrivateState }
86
+ : base;
87
+ return createUnprovenDeployTx(providers, deployOptions);
88
+ }
89
+ /**
90
+ * Split path: run the constructor, keep only `circuits`' operations, and deploy
91
+ * that state.
92
+ *
93
+ * `createUnprovenDeployTx` fuses the constructor call and the tx assembly with
94
+ * no seam to prune between them, so this replicates its steps. The intent
95
+ * carries no Zswap offer, which is why a constructor that creates coins is
96
+ * refused rather than silently stripped.
97
+ */
98
+ async function buildPrunedDeploy({ providers, contractName, contract, artifact, signingKey, args, initialPrivateState, circuits, }) {
99
+ const executable = ContractExecutable.make(artifact.compiledContract);
100
+ const coinPublicKey = parseCoinPublicKeyToHex(providers.walletProvider.getCoinPublicKey(), getNetworkId());
101
+ const runtime = makeContractExecutableRuntime(providers.zkConfigProvider, {
102
+ coinPublicKey,
103
+ signingKey,
104
+ });
105
+ const privateStateIn = contract.private_state_id !== undefined ? initialPrivateState : undefined;
106
+ const constructed = exitResultOrError(await runtime.runPromiseExit(executable.initialize(privateStateIn, ...args)));
107
+ const { contractState } = constructed.public;
108
+ const { privateState, zswapLocalState } = constructed.private;
109
+ const coinCount = zswapLocalState.inputs.length + zswapLocalState.outputs.length;
110
+ if (coinCount > 0) {
111
+ // The split tx has no Zswap offer, so the constructor's coins would
112
+ // be lost. Deploy this contract in one tx or shrink it.
113
+ throw new ConfigError(`Constructor of "${contractName}" creates or spends ${coinCount} Zswap coin(s), which a fragmented deploy cannot carry. Remove circuits_per_tx, or deploy a contract small enough for a single tx.`);
114
+ }
115
+ const deploy = new ContractDeploy(pruneState({ state: contractState, keep: sortCircuits(circuits) }));
116
+ const unprovenTx = Transaction.fromParts(getNetworkId(), undefined, undefined, Intent.new(ttlOneHour()).addDeploy(deploy));
117
+ return {
118
+ public: { contractAddress: deploy.address },
119
+ private: {
120
+ unprovenTx,
121
+ signingKey: constructed.private.signingKey,
122
+ initialPrivateState: privateState,
123
+ },
124
+ };
125
+ }
126
+ /**
127
+ * Wait for one transaction to land, capped at `txTimeoutMs`, rejecting
128
+ * any status other than `SucceedEntirely`.
129
+ *
130
+ * `fail` supplies the caller's error type, so the deploy tx and a fragment
131
+ * insert share the ceiling and the status rule while reporting differently.
132
+ */
133
+ export async function awaitFinalization({ providers, txId, txTimeoutMs, fail, }) {
134
+ return settle(() => providers.publicDataProvider.watchForTxData(txId), txTimeoutMs, fail);
135
+ }
136
+ /**
137
+ * Settle the deploy transaction by address rather than by a recorded id.
138
+ *
139
+ * A `txId` read back from the deployments file may be corrupt, in which case a
140
+ * watch on it never returns, or may belong to a different contract, in which
141
+ * case it returns data that has nothing to do with this address.
142
+ */
143
+ export async function awaitDeployTxData({ providers, address, txTimeoutMs, fail, }) {
144
+ return settle(() => providers.publicDataProvider.watchForDeployTxData(address), txTimeoutMs, fail);
145
+ }
146
+ async function settle(watch, txTimeoutMs, fail) {
147
+ const finalized = await raceForTxData(watch, txTimeoutMs, () => fail(`no finalization within ${txTimeoutMs} ms`, { timedOut: true })).catch((e) => {
148
+ throw e instanceof DeployError ? e : fail(formatError(e), { cause: e });
149
+ });
150
+ if (finalized.status !== SucceedEntirely) {
151
+ throw fail(`the node reported status "${finalized.status}"`);
152
+ }
153
+ return finalized;
154
+ }
155
+ /** Wait for the deploy tx to land. The pending record survives every failure. */
156
+ export function awaitDeployFinalization({ providers, contractName, submitted, txTimeoutMs, recovery, }) {
157
+ const { address, txId } = submitted;
158
+ return awaitFinalization({
159
+ providers,
160
+ txId,
161
+ txTimeoutMs,
162
+ fail: (reason, detail) => unconfirmed({
163
+ contractName,
164
+ address,
165
+ txId,
166
+ reason,
167
+ recovery,
168
+ cause: detail?.cause,
169
+ }),
170
+ });
171
+ }
172
+ /**
173
+ * Submit one verifier-key insert, classifying a block-limit refusal the way
174
+ * {@link submitDeploy} does so the caller can halve the batch and retry.
175
+ */
176
+ export function submitInsert({ providers, contractName, unprovenTx, circuits, }) {
177
+ return submitClassified(`Verifier-key insert for "${contractName}"`, circuits.length, () => submitTxAsync(providers, { unprovenTx }));
178
+ }
179
+ /**
180
+ * Wait for one transaction of a fragmented deploy to land, under the
181
+ * same ceiling and the same `SucceedEntirely` rule as the deploy tx. A partially
182
+ * applied update must not be treated as landed: verify would then be skipped
183
+ * for those circuits.
184
+ */
185
+ export function awaitFragmentFinalization({ providers, address, txId, txTimeoutMs, circuitsOnChain, circuitsPending, }) {
186
+ return awaitFinalization({
187
+ providers,
188
+ txId,
189
+ txTimeoutMs,
190
+ fail: (reason, detail) => new FragmentDeployError({
191
+ address,
192
+ circuitsOnChain,
193
+ circuitsPending,
194
+ reason,
195
+ txId,
196
+ timedOut: detail?.timedOut,
197
+ }, detail?.cause !== undefined ? { cause: detail.cause } : undefined),
198
+ });
199
+ }
200
+ /**
201
+ * Store the signing key and initial private state for the deployed
202
+ * address. Call only after a `SucceedEntirely` status: a rejected tx must not leave
203
+ * local state behind for a contract that does not exist.
204
+ */
205
+ export async function persistDeployPrivateState({ providers, contract, submitted, }) {
206
+ const { address, unsubmitted } = submitted;
207
+ providers.privateStateProvider.setContractAddress(address);
208
+ if (contract.private_state_id !== undefined) {
209
+ await providers.privateStateProvider.set(contract.private_state_id, unsubmitted.private.initialPrivateState);
210
+ }
211
+ await providers.privateStateProvider.setSigningKey(address, unsubmitted.private.signingKey);
212
+ }
213
+ /** Build `<explorer>/contracts/0x<address>`, or `''` when no explorer / no address. */
214
+ export function buildExplorerUrl(base, address) {
215
+ if (!base || !address)
216
+ return '';
217
+ const trimmed = base.endsWith('/') ? base.slice(0, -1) : base;
218
+ const hex = address.startsWith('0x') ? address : `0x${address}`;
219
+ return `${trimmed}/contracts/${hex}`;
220
+ }
221
+ export function toPendingRecord({ submitted, deployer, artifact, }) {
222
+ return {
223
+ status: 'pending',
224
+ address: submitted.address,
225
+ txId: submitted.txId,
226
+ deployer,
227
+ artifact,
228
+ submittedAt: new Date().toISOString(),
229
+ };
230
+ }
231
+ /**
232
+ * Progress record for a fragmented deploy.
233
+ *
234
+ * `circuitsOnChain` must come from a chain read: a record built from the plan
235
+ * would claim circuits landed whose insert actually failed.
236
+ */
237
+ export function toPartialRecord({ address, txId, deployer, artifact, circuits, circuitsOnChain, submittedAt, txHash, blockHeight, pendingTxId, pendingCircuits, }) {
238
+ const all = sortCircuits(circuits);
239
+ const onChain = sortCircuits(circuitsOnChain);
240
+ // The two lists partition the artifact's circuits, so a chain read
241
+ // naming something the artifact does not have is a bug, not a user error.
242
+ const foreign = remaining(onChain, all);
243
+ if (foreign.length > 0) {
244
+ throw new DeployError(`Chain state at ${address} reports circuits absent from the artifact: ${foreign.join(', ')}.`);
245
+ }
246
+ return {
247
+ status: 'partial',
248
+ address,
249
+ txId,
250
+ deployer,
251
+ artifact,
252
+ circuitsOnChain: onChain,
253
+ circuitsPending: remaining(all, onChain),
254
+ submittedAt: submittedAt ?? new Date().toISOString(),
255
+ ...(txHash !== undefined ? { txHash } : {}),
256
+ ...(blockHeight !== undefined ? { blockHeight } : {}),
257
+ ...(pendingTxId !== undefined ? { pendingTxId, pendingCircuits } : {}),
258
+ };
259
+ }
260
+ export function toConfirmedRecord({ previous, txHash, blockHeight, }) {
261
+ return {
262
+ status: 'confirmed',
263
+ address: previous.address,
264
+ txId: previous.txId,
265
+ deployer: previous.deployer,
266
+ artifact: previous.artifact,
267
+ txHash,
268
+ blockHeight,
269
+ timestamp: new Date().toISOString(),
270
+ };
271
+ }
272
+ /**
273
+ * `watchForTxData` waits forever on a tx that never lands, so every wait needs
274
+ * a ceiling. `onTimeout` supplies the caller's error type.
275
+ */
276
+ function raceForTxData(watch, txTimeoutMs, onTimeout) {
277
+ let timer;
278
+ return Promise.race([
279
+ watch(),
280
+ new Promise((_resolve, reject) => {
281
+ timer = setTimeout(() => reject(onTimeout()), txTimeoutMs);
282
+ }),
283
+ ]).finally(() => clearTimeout(timer));
284
+ }
285
+ /** How to get out of a stopped deploy, which differs by the record it left. */
286
+ const RECOVERY = {
287
+ pending: 'The pending record in the deployments ledger is left in place; check the tx on chain, then re-run with --force to replace it.',
288
+ partial: 'The partial record in the deployments ledger is left in place; re-run the same deploy to resume, or pass --force to abandon the landed contract and deploy a new one.',
289
+ };
290
+ /**
291
+ * The tx is out of our hands and its ledger record survives, so the message has
292
+ * to carry every identifier needed to reconcile by hand.
293
+ */
294
+ function unconfirmed({ contractName, address, txId, reason, recovery, cause, }) {
295
+ return new DeployTxFailedError(`Deploy of "${contractName}" was submitted but not confirmed: ${reason}. address ${address}, txId ${txId}. ${RECOVERY[recovery]}`, cause !== undefined ? { cause } : undefined);
296
+ }
297
+ //# sourceMappingURL=deploy-tx.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deploy-tx.js","sourceRoot":"","sources":["../../src/services/deploy-tx.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AAChF,OAAO,EAEL,sBAAsB,EACtB,aAAa,GACd,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,YAAY,EAAE,MAAM,wCAAwC,CAAC;AACtE,OAAO,EACL,iBAAiB,EAEjB,6BAA6B,EAE7B,eAAe,GAChB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,uBAAuB,EACvB,UAAU,GACX,MAAM,mCAAmC,CAAC;AAO3C,OAAO,EACL,eAAe,EACf,WAAW,EACX,WAAW,EACX,mBAAmB,EACnB,mBAAmB,GACpB,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAEhD;;;;GAIG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,OAAO,CAAC;AAE7C;;;;;;;;GAQG;AACH,SAAS,qBAAqB,CAAC,KAAc;IAC3C,MAAM,IAAI,GAAG,WAAW,CAAC,KAAK,CAAC,CAAC;IAChC,OAAO,I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,CAAC,WAAW,EAAE;KACpC,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,SAAS,aAAa,CACpB,KAAqC,EACrC,WAAmB,EACnB,SAAsB;IAEtB,IAAI,KAAgD,CAAC;IACrD,OAAO,OAAO,CAAC,IAAI,CAAC;QAClB,KAAK,EAAE;QACP,IAAI,OAAO,CAAQ,CAAC,QAAQ,EAAE,MAAM,EAAE,EAAE;YACtC,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,SAAS,EAAE,CAAC,EAAE,WAAW,CAAC,CAAC;QAC7D,CAAC,CAAC;KACH,CAAC,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC;AACxC,CAAC;AAED,+EAA+E;AAC/E,MAAM,QAAQ,GAAG;IACf,OAAO,EACL,+HAA+H;IACjI,OAAO,EACL,uKAAuK;CACjK,CAAC;AAEX;;;GAGG;AACH,SAAS,WAAW,CAAC,EACnB,YAAY,EACZ,OAAO,EACP,IAAI,EACJ,MAAM,EACN,QAAQ,EACR,KAAK,GAQN;IACC,OAAO,IAAI,mBAAmB,CAC5B,cAAc,YAAY,sCAAsC,MAAM,aAAa,OAAO,UAAU,IAAI,KAAK,QAAQ,CAAC,QAAQ,CAAC,EAAE,EACjI,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,SAAS,CAC5C,CAAC;AACJ,CAAC"}
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Render an unknown thrown value as a log-safe one-liner.
3
+ *
4
+ * The wallet SDK rejects with effect-style tagged records
5
+ * (`{ _tag: 'Wallet.Sync', … }`) rather than `Error` instances, so the
6
+ * usual `(e as Error).message` yields `undefined` and `${e}` yields
7
+ * `[object Object]` — both erase the only diagnostic the user gets for a
8
+ * failed sync. Prefer `_tag` plus `message`/`cause`, else inspect.
9
+ */
10
+ export declare function formatError(error: unknown): string;
@@ -0,0 +1,91 @@
1
+ import { inspect } from 'node:util';
2
+ /** Cap on the inspect fallback so one wallet-SDK payload can't flood a log line. */
3
+ const MAX_SERIALIZED_LENGTH = 500;
4
+ /**
5
+ * `Runtime.FiberFailureCauseId` from `effect`, referenced by its registered
6
+ * symbol so this package needs no runtime dependency on `effect`.
7
+ */
8
+ const EFFECT_FIBER_FAILURE_CAUSE = Symbol.for('effect/Runtime/FiberFailure/Cause');
9
+ /**
10
+ * Render an unknown thrown value as a log-safe one-liner.
11
+ *
12
+ * The wallet SDK rejects with effect-style tagged records
13
+ * (`{ _tag: 'Wallet.Sync', … }`) rather than `Error` instances, so the
14
+ * usual `(e as Error).message` yields `undefined` and `${e}` yields
15
+ * `[object Object]` — both erase the only diagnostic the user gets for a
16
+ * failed sync. Prefer `_tag` plus `message`/`cause`, else inspect.
17
+ */
18
+ export function formatError(error) {
19
+ const fiberFailure = effectFailure(error);
20
+ if (fiberFailure !== undefined)
21
+ return formatError(fiberFailure);
22
+ if (error instanceof Error) {
23
+ if (error.cause === undefined)
24
+ return error.message;
25
+ // The wrapping layer's message is usually the generic half ("Deploy
26
+ // failed"); the cause carries the reason. Append it so one log line
27
+ // holds the whole chain. A layer that re-wrapped its own failure with
28
+ // `message: cause.message` contributes nothing, so keep only the deeper
29
+ // rendering.
30
+ const cause = formatError(error.cause);
31
+ return cause.startsWith(error.message)
32
+ ? cause
33
+ : `${error.message}: ${cause}`;
34
+ }
35
+ if (typeof error === 'string')
36
+ return error;
37
+ if (typeof error === 'object' && error !== null) {
38
+ const record = error;
39
+ const tag = typeof record._tag === 'string' ? record._tag : undefined;
40
+ const detail = typeof record.message === 'string' && record.message !== ''
41
+ ? record.message
42
+ : record.cause !== undefined
43
+ ? formatError(record.cause)
44
+ : undefined;
45
+ if (tag !== undefined) {
46
+ return `${tag}: ${detail ?? serialize(error)}`;
47
+ }
48
+ if (detail !== undefined)
49
+ return detail;
50
+ }
51
+ return serialize(error);
52
+ }
53
+ /**
54
+ * The failed value inside an Effect `FiberFailure`, or `undefined` for any
55
+ * other thrown value.
56
+ *
57
+ * `Effect.runPromise` rejects with a wrapper that copies only the squashed
58
+ * failure's `message` and leaves `cause` unset, so the wallet SDK's proving
59
+ * chain (`Wallet.Proving` → `ClientError` → the connection error naming the
60
+ * proof server) is reachable only through the cause symbol.
61
+ */
62
+ function effectFailure(error) {
63
+ if (typeof error !== 'object' || error === null)
64
+ return undefined;
65
+ const cause = error[EFFECT_FIBER_FAILURE_CAUSE];
66
+ if (typeof cause !== 'object' || cause === null)
67
+ return undefined;
68
+ const squashed = cause;
69
+ if (squashed._tag === 'Fail')
70
+ return squashed.error;
71
+ if (squashed._tag === 'Die')
72
+ return squashed.defect;
73
+ return undefined;
74
+ }
75
+ /**
76
+ * `util.inspect` with a length cap. Unlike `JSON.stringify` it renders
77
+ * `bigint` (wallet-SDK payloads carry balances and event ids as bigint)
78
+ * and marks circular references instead of throwing, so no try/catch or
79
+ * replacer is needed. `depth: 3` keeps a nested payload readable without
80
+ * dumping the whole graph.
81
+ */
82
+ function serialize(value) {
83
+ const out = inspect(value, {
84
+ depth: 3,
85
+ breakLength: Number.POSITIVE_INFINITY,
86
+ });
87
+ return out.length > MAX_SERIALIZED_LENGTH
88
+ ? `${out.slice(0, MAX_SERIALIZED_LENGTH)}…`
89
+ : out;
90
+ }
91
+ //# sourceMappingURL=error-format.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error-format.js","sourceRoot":"","sources":["../../src/services/error-format.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,oFAAoF;AACpF,MAAM,qBAAqB,GAAG,GAAG,CAAC;AAElC;;;GAGG;AACH,MAAM,0BAA0B,GAAG,MAAM,CAAC,GAAG,CAC3C,mCAAmC,CACpC,CAAC;AAEF;;;;;;;;GAQG;AACH,MAAM,UAAU,WAAW,CAAC,KAAc;IACxC,MAAM,YAAY,GAAG,aAAa,CAAC,KAAK,CAAC,CAAC;IAC1C,I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