@parity/product-sdk-contracts 0.0.0-dev.312.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.
- package/LICENSE +201 -0
- package/README.md +309 -0
- package/dist/chunk-2UN4YA25.js +53 -0
- package/dist/chunk-2UN4YA25.js.map +1 -0
- package/dist/codegen.d.ts +67 -0
- package/dist/codegen.js +83 -0
- package/dist/codegen.js.map +1 -0
- package/dist/index.d.ts +135 -0
- package/dist/index.js +630 -0
- package/dist/index.js.map +1 -0
- package/dist/pvm.d.ts +54 -0
- package/dist/pvm.js +3 -0
- package/dist/pvm.js.map +1 -0
- package/dist/testing.d.ts +85 -0
- package/dist/testing.js +99 -0
- package/dist/testing.js.map +1 -0
- package/dist/types-Dtu4IsSh.d.ts +552 -0
- package/package.json +57 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
# @parity/product-sdk-contracts
|
|
2
|
+
|
|
3
|
+
Typed contract interactions on Polkadot Asset Hub. Resolve deployed contracts from a `cdm.json` manifest (or directly from `cargo pvm-contract build` artefacts), get fully-typed handles for `query`, `tx`, and batched `prepare` calls — backed by `pallet-revive` via PAPI typed APIs, with viem providing the Solidity ABI codec.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pnpm add @parity/product-sdk-contracts
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Quick start (with cdm.json)
|
|
12
|
+
|
|
13
|
+
The `cdm.json` flow is the primary path. A `cdm.json` manifest in your project root pins each installed contract to an address + ABI; `ContractManager.fromClient(cdm, client, descriptor)` resolves them at runtime.
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { createChainClient } from "@parity/product-sdk-chain-client";
|
|
17
|
+
import { paseo_asset_hub } from "@parity/product-sdk-descriptors/paseo-asset-hub";
|
|
18
|
+
import { ContractManager } from "@parity/product-sdk-contracts";
|
|
19
|
+
import { SignerManager } from "@parity/product-sdk-signer";
|
|
20
|
+
import cdmJson from "./cdm.json";
|
|
21
|
+
|
|
22
|
+
const client = await createChainClient({
|
|
23
|
+
chains: { assetHub: paseo_asset_hub },
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
const signerManager = new SignerManager();
|
|
27
|
+
await signerManager.connect();
|
|
28
|
+
|
|
29
|
+
const manager = ContractManager.fromClient(cdmJson, client.raw.assetHub, paseo_asset_hub, {
|
|
30
|
+
signerManager,
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
// Resolve by library name — typed handle returned.
|
|
34
|
+
const registry = manager.getContract("@w3s/playground-registry");
|
|
35
|
+
|
|
36
|
+
// Read state
|
|
37
|
+
const { value } = await registry.publish.query("my-app00", "ipfs://...", 0);
|
|
38
|
+
|
|
39
|
+
// Submit a tx (uses signerManager's logged-in account)
|
|
40
|
+
await registry.publish.tx("my-app00", "ipfs://...", 0);
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## `ContractManager` API
|
|
44
|
+
|
|
45
|
+
### `ContractManager.fromClient(cdmJson, client, descriptor, options?)`
|
|
46
|
+
|
|
47
|
+
Synchronous factory. Builds a `ContractRuntime` internally that wires the typed API (for extrinsics + storage) and the unsafe API (for the `ReviveApi.call` dry-run, sidesteps compat-token drift when the descriptor lags a runtime upgrade) on the same `PolkadotClient`.
|
|
48
|
+
|
|
49
|
+
| Param | Type | Notes |
|
|
50
|
+
| --- | --- | --- |
|
|
51
|
+
| `cdmJson` | `CdmJson` | Imported `cdm.json` |
|
|
52
|
+
| `client` | `PolkadotClient` | E.g. `client.raw.assetHub` |
|
|
53
|
+
| `descriptor` | `ChainDefinition` | E.g. `paseo_asset_hub` from `@parity/product-sdk-descriptors` |
|
|
54
|
+
| `options.signerManager?` | `SignerManager` | Resolves signer + origin from the logged-in account |
|
|
55
|
+
| `options.defaultOrigin?` | `SS58String` | Static fallback origin for queries |
|
|
56
|
+
| `options.defaultSigner?` | `PolkadotSigner` | Static fallback signer for txs |
|
|
57
|
+
|
|
58
|
+
### `manager.getContract(library)`
|
|
59
|
+
|
|
60
|
+
Returns a typed `Contract<C>` handle. Each ABI method exposes:
|
|
61
|
+
|
|
62
|
+
- `.query(...args, opts?)` — read-only dry-run; returns `{ success, value, gasRequired }`
|
|
63
|
+
- `.tx(...args, opts?)` — sign, submit, and watch; resolves at best-block
|
|
64
|
+
- `.prepare(...args, opts?)` — batch-ready handle (see *Batching* below)
|
|
65
|
+
|
|
66
|
+
When codegen-generated types are present, the call is fully typed:
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
const registry = manager.getContract("@w3s/playground-registry");
|
|
70
|
+
// ^ autocompletes from cdm.json
|
|
71
|
+
await registry.publish.tx("domain", "ipfs://cid", 0);
|
|
72
|
+
// ^ method name typed
|
|
73
|
+
// ^ args typed
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Throws `ContractNotFoundError` if the library name isn't in the manifest.
|
|
77
|
+
|
|
78
|
+
### `manager.getAddress(library)`
|
|
79
|
+
|
|
80
|
+
Returns the on-chain address. Useful for logging or display.
|
|
81
|
+
|
|
82
|
+
### `manager.setDefaults(defaults)`
|
|
83
|
+
|
|
84
|
+
Update `origin`, `signer`, or `signerManager` after construction. Only the fields you pass are updated.
|
|
85
|
+
|
|
86
|
+
### `ContractManager.fromLive(cdmJson, runtime, options?)` / `fromLiveClient(cdmJson, client, descriptor, options?)`
|
|
87
|
+
|
|
88
|
+
**Async** factories. Like `fromClient`, but before constructing the manager they resolve each installed contract's address from the **live CDM registry** instead of trusting the address baked into `cdm.json`. ABIs still come from the installed snapshot — only addresses are refreshed. Dependencies requested as `"latest"` resolve the registry's latest address; pinned numeric dependencies resolve `getAddressAtVersion(...)` so the live address stays aligned with the installed ABI/version.
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
const manager = await ContractManager.fromLiveClient(cdmJson, client.raw.assetHub, paseo_asset_hub, {
|
|
92
|
+
signerManager,
|
|
93
|
+
// registryAddress?: HexString — defaults to cdmJson.registry
|
|
94
|
+
// libraries?: string[] — subset to resolve; defaults to every contract
|
|
95
|
+
// registryOrigin?: SS58String — origin for the registry dry-run; defaults to defaultOrigin
|
|
96
|
+
});
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
This path is **strict**: if `cdmJson.registry` (or `registryAddress`) is missing, or a contract isn't registered on-chain, or the registry query fails, the promise rejects with `ContractLiveAddressResolutionError` — it never silently falls back to the snapshot address. Use `fromClient` for snapshot-only behavior.
|
|
100
|
+
|
|
101
|
+
### `withLiveContractAddresses(cdmJson, runtime, options?)`
|
|
102
|
+
|
|
103
|
+
Standalone helper behind `fromLive`. Returns a **cloned** `cdm.json` whose contract addresses have been replaced with live registry addresses (the input is never mutated). Useful when you want the resolved manifest without immediately building a manager. Takes the same `LiveContractResolutionOptions` as `fromLive`.
|
|
104
|
+
|
|
105
|
+
## Signer / origin resolution
|
|
106
|
+
|
|
107
|
+
Order, highest wins:
|
|
108
|
+
|
|
109
|
+
1. Explicit `{ signer }` / `{ origin }` in the call options
|
|
110
|
+
2. `signerManager`'s currently selected account
|
|
111
|
+
3. Static `defaultSigner` / `defaultOrigin`
|
|
112
|
+
4. (Queries only) pallet-revive account fallback for the dry-run
|
|
113
|
+
|
|
114
|
+
Throws `ContractSignerMissingError` from `.tx()` if no signer is available. `.query()` and `.prepare()` never need a signer.
|
|
115
|
+
|
|
116
|
+
## Account mapping (`pallet-revive` prerequisite)
|
|
117
|
+
|
|
118
|
+
`pallet-revive` requires every signing SS58 account to have a registered `OriginalAccount` mapping to its derived H160 before `Revive.call` extrinsics from it are accepted. Call `ensureContractAccountMapped(runtime, address, signer)` once at app boot per signing account — it's idempotent (reads `Revive.OriginalAccount` first, short-circuits with `null` if already mapped) so the worst case is one extra storage read on every boot.
|
|
119
|
+
|
|
120
|
+
```ts
|
|
121
|
+
import { ensureContractAccountMapped } from "@parity/product-sdk-contracts";
|
|
122
|
+
|
|
123
|
+
await ensureContractAccountMapped(manager.getRuntime(), address, signer);
|
|
124
|
+
// safe to call manager.getContract(...).<method>.tx({ signer }) from here
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
Without this, every fresh-account `.tx()` fails the pre-flight dry-run with `AccountNotMapped` before signing.
|
|
128
|
+
|
|
129
|
+
## Dry-run preflight
|
|
130
|
+
|
|
131
|
+
Every `.tx()` runs a `ReviveApi.call` dry-run first to size `weight_limit` / `storage_deposit_limit` and to fail fast on revert, OOG, or `AccountNotMapped` before any signing happens. Throws `ContractDryRunFailedError` (with the chain's `dispatchError`) when the dry-run reports failure — caller pays no gas on a tx the chain already rejected. Pass both `gasLimit` and `storageDepositLimit` overrides on `TxOptions` to skip the dry-run entirely.
|
|
132
|
+
|
|
133
|
+
## Query block selection
|
|
134
|
+
|
|
135
|
+
`.query()` and the `.tx()` / `.prepare()` sizing dry-runs target best-block by default, matching `submitAndWatch`'s default resolution. This keeps reads consistent with the state a freshly-submitted transaction observes.
|
|
136
|
+
|
|
137
|
+
Override per call via `QueryOptions.at`, `TxOptions.at`, or `PrepareOptions.at` — each accepts `"best"`, `"finalized"`, or a block hash:
|
|
138
|
+
|
|
139
|
+
```ts
|
|
140
|
+
await counter.getCount.query(); // best-block (default)
|
|
141
|
+
await counter.getCount.query({ at: "finalized" }); // canonical, lagged
|
|
142
|
+
await counter.getCount.query({ at: blockHash }); // pin to a historical block
|
|
143
|
+
|
|
144
|
+
await counter.increment.tx({ at: "finalized" }); // size the dry-run against finalized
|
|
145
|
+
await counter.increment.prepare({ at: blockHash }); // pin the batched call's sizing dry-run
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
`.tx({ at })` / `.prepare({ at })` is a no-op when both `gasLimit` and `storageDepositLimit` overrides are supplied — the sizing dry-run is skipped entirely in that case.
|
|
149
|
+
|
|
150
|
+
Change the runtime default by passing `{ at }` to the factory:
|
|
151
|
+
|
|
152
|
+
```ts
|
|
153
|
+
const runtime = createContractRuntimeFromClient(client.raw.assetHub, paseo_asset_hub, {
|
|
154
|
+
at: "finalized", // read finalized state by default
|
|
155
|
+
});
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
## Batching with `.prepare()`
|
|
159
|
+
|
|
160
|
+
Use `.prepare()` to build `BatchableCall` handles consumable by `batchSubmitAndWatch` from `@parity/product-sdk-tx`. Combine multiple contract calls — or contract calls mixed with other Asset Hub transactions — into a single atomic `Utility.batch_all` extrinsic.
|
|
161
|
+
|
|
162
|
+
```ts
|
|
163
|
+
import { batchSubmitAndWatch } from "@parity/product-sdk-tx";
|
|
164
|
+
|
|
165
|
+
const a = registry.publish.prepare("app-one00", "ipfs://...", 0);
|
|
166
|
+
const b = registry.publish.prepare("app-two00", "ipfs://...", 0);
|
|
167
|
+
|
|
168
|
+
await batchSubmitAndWatch([a, b], client.raw.assetHub, signer);
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
**`.prepare()` doesn't require a signer.** The resolved origin is only used for the dry-run; the batch submission's signer is the dispatched origin at submission time.
|
|
172
|
+
|
|
173
|
+
`PrepareOptions` accepts: `origin`, `value`, `gasLimit`, `storageDepositLimit`. Signer and submission lifecycle options (`signer`, `waitFor`, etc.) are intentionally absent — those belong to the batch submit, not the individual prepared call.
|
|
174
|
+
|
|
175
|
+
## Without cdm.json — manual path
|
|
176
|
+
|
|
177
|
+
If you don't have a `cdm.json` (or want to test against a contract not yet in your manifest), use `createContract` / `createContractFromClient` with an explicit address and ABI:
|
|
178
|
+
|
|
179
|
+
```ts
|
|
180
|
+
import { createContractFromClient } from "@parity/product-sdk-contracts";
|
|
181
|
+
import { paseo_asset_hub } from "@parity/product-sdk-descriptors/paseo-asset-hub";
|
|
182
|
+
|
|
183
|
+
const counter = createContractFromClient(
|
|
184
|
+
client.raw.assetHub,
|
|
185
|
+
paseo_asset_hub,
|
|
186
|
+
"0xC472...",
|
|
187
|
+
counterAbi,
|
|
188
|
+
{ signerManager },
|
|
189
|
+
);
|
|
190
|
+
|
|
191
|
+
const { value } = await counter.getCount.query();
|
|
192
|
+
await counter.increment.tx();
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
`createContract` is the same but takes a pre-built `ContractRuntime` (from `createContractRuntime` / `createContractRuntimeFromClient`) instead of a raw `PolkadotClient` + descriptor. Use it when you want to share a single runtime across multiple contract handles or wire your own dry-run path.
|
|
196
|
+
|
|
197
|
+
For projects that build with `cargo pvm-contract` and don't want to maintain a `cdm.json`, the `@parity/product-sdk-contracts/pvm` subpath exports `parsePvmContractAbi`, `loadPvmContractAbi`, `loadPvmContractCode`, and `loadPvmContractArtifacts` — load the ABI (and bytecode for deployment) directly from the toolchain's `<name>.release.abi.json` / `<name>.release.polkavm` output.
|
|
198
|
+
|
|
199
|
+
## cdm.json schema
|
|
200
|
+
|
|
201
|
+
Top-level shape:
|
|
202
|
+
|
|
203
|
+
```jsonc
|
|
204
|
+
{
|
|
205
|
+
"registry": "0xf62c2ece29cd8df2e10040ecfa5a894a5c5d9cb0",
|
|
206
|
+
"dependencies": {
|
|
207
|
+
"@org/contract-name": "latest"
|
|
208
|
+
},
|
|
209
|
+
"contracts": {
|
|
210
|
+
"@org/contract-name": {
|
|
211
|
+
"version": 6,
|
|
212
|
+
"address": "0x4A37B123b0BA2A894cA5953f472264921d44e298",
|
|
213
|
+
"abi": [ /* Solidity-compatible ABI entries */ ]
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
`registry` is used by `ContractManager.fromLive(...)` / `withLiveContractAddresses(...)` to resolve current contract addresses from the live CDM registry. `ContractManager.fromClient(...)` uses the installed `contracts` snapshot directly.
|
|
220
|
+
|
|
221
|
+
A real-world example: [`paritytech/playground-cli/cdm.json`](https://github.com/paritytech/playground-cli/blob/main/cdm.json).
|
|
222
|
+
|
|
223
|
+
## Type generation
|
|
224
|
+
|
|
225
|
+
`generateContractTypes(...)` (from `@parity/product-sdk-contracts/codegen`) emits a `.d.ts` that augments the package's `Contracts` interface so `manager.getContract("@org/name")` returns a fully-typed handle:
|
|
226
|
+
|
|
227
|
+
```ts
|
|
228
|
+
import { generateContractTypes, resolveContractTypeInputs } from "@parity/product-sdk-contracts/codegen";
|
|
229
|
+
import { writeFileSync } from "node:fs";
|
|
230
|
+
|
|
231
|
+
// Mix inline ABIs (from your cdm.json) and cargo-pvm-contract build artefacts.
|
|
232
|
+
const resolved = await resolveContractTypeInputs([
|
|
233
|
+
{ library: "@example/counter", abiPath: "./target/counter.release.abi.json" },
|
|
234
|
+
{ library: "@example/inline", abi: inlineAbi },
|
|
235
|
+
]);
|
|
236
|
+
const src = generateContractTypes(resolved);
|
|
237
|
+
writeFileSync(".cdm/contracts.d.ts", src);
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
Wire `.cdm/contracts.d.ts` into your `tsconfig.json`'s `include` and the next time you call `getContract("@org/name")`, the method names, parameter types, and return types come straight from the ABI.
|
|
241
|
+
|
|
242
|
+
Without codegen, `getContract()` still works — methods are accessible but untyped (`Contract<ContractDef>`).
|
|
243
|
+
|
|
244
|
+
## Errors
|
|
245
|
+
|
|
246
|
+
| Error | When |
|
|
247
|
+
| --- | --- |
|
|
248
|
+
| `ContractNotFoundError` | `getContract(name)` and `name` isn't in the manifest |
|
|
249
|
+
| `ContractSignerMissingError` | `.tx()` called with no signer + no signerManager + no defaultSigner |
|
|
250
|
+
| `ContractLiveAddressResolutionError` | `fromLive(...)` / `withLiveContractAddresses(...)` couldn't resolve an address from the live CDM registry (no `registry` set, contract unregistered, or the registry query failed) |
|
|
251
|
+
| `ContractDryRunFailedError` | `.tx()` pre-flight `ReviveApi.call` reported failure — `dispatchError` carries the chain's encoded error (e.g. `ContractReverted`, `OutOfGas`, `AccountNotMapped`) |
|
|
252
|
+
| Generic | viem ABI decode failures, RPC errors, weight/storage-limit estimation failures — surface from the underlying PAPI typed API |
|
|
253
|
+
|
|
254
|
+
## Public API
|
|
255
|
+
|
|
256
|
+
```ts
|
|
257
|
+
// `@parity/product-sdk-contracts` (browser-safe runtime entry)
|
|
258
|
+
export {
|
|
259
|
+
ContractManager,
|
|
260
|
+
createContract,
|
|
261
|
+
createContractFromClient,
|
|
262
|
+
createContractRuntime,
|
|
263
|
+
createContractRuntimeFromClient,
|
|
264
|
+
withLiveContractAddresses,
|
|
265
|
+
ensureContractAccountMapped,
|
|
266
|
+
ContractError,
|
|
267
|
+
ContractSignerMissingError,
|
|
268
|
+
ContractNotFoundError,
|
|
269
|
+
ContractLiveAddressResolutionError,
|
|
270
|
+
ContractDryRunFailedError,
|
|
271
|
+
};
|
|
272
|
+
export type {
|
|
273
|
+
ContractRuntime,
|
|
274
|
+
ReviveTypedApi,
|
|
275
|
+
ReviveDryRunResult,
|
|
276
|
+
ReviveDryRunCall,
|
|
277
|
+
CdmJson,
|
|
278
|
+
CdmJsonContract,
|
|
279
|
+
CdmJsonDependencyVersion,
|
|
280
|
+
AbiParam,
|
|
281
|
+
AbiEntry,
|
|
282
|
+
Contract,
|
|
283
|
+
ContractDef,
|
|
284
|
+
Contracts,
|
|
285
|
+
QueryResult,
|
|
286
|
+
QueryOptions,
|
|
287
|
+
TxOptions,
|
|
288
|
+
TxResult,
|
|
289
|
+
PrepareOptions,
|
|
290
|
+
BatchableCall,
|
|
291
|
+
ContractDefaults,
|
|
292
|
+
ContractManagerOptions,
|
|
293
|
+
ContractOptions,
|
|
294
|
+
LiveContractResolutionOptions,
|
|
295
|
+
};
|
|
296
|
+
|
|
297
|
+
// `@parity/product-sdk-contracts/codegen` (Node-only — build tooling)
|
|
298
|
+
export { generateContractTypes, resolveContractTypeInputs };
|
|
299
|
+
export type { ContractTypeInput };
|
|
300
|
+
|
|
301
|
+
// `@parity/product-sdk-contracts/pvm` (Node-only — cargo-pvm-contract artefact loaders)
|
|
302
|
+
export {
|
|
303
|
+
parsePvmContractAbi,
|
|
304
|
+
loadPvmContractAbi,
|
|
305
|
+
loadPvmContractCode,
|
|
306
|
+
loadPvmContractArtifacts,
|
|
307
|
+
};
|
|
308
|
+
export type { PvmContractArtifacts };
|
|
309
|
+
```
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// src/pvm.ts
|
|
2
|
+
function parsePvmContractAbi(source) {
|
|
3
|
+
let value = source;
|
|
4
|
+
if (value instanceof Uint8Array) {
|
|
5
|
+
value = new TextDecoder().decode(value);
|
|
6
|
+
}
|
|
7
|
+
if (typeof value === "string") {
|
|
8
|
+
try {
|
|
9
|
+
value = JSON.parse(value);
|
|
10
|
+
} catch (cause) {
|
|
11
|
+
throw new Error("Invalid PVM ABI: not valid JSON", { cause });
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
if (value && typeof value === "object" && !Array.isArray(value) && "abi" in value) {
|
|
15
|
+
value = value.abi;
|
|
16
|
+
}
|
|
17
|
+
if (!Array.isArray(value)) {
|
|
18
|
+
throw new Error("Invalid PVM ABI: expected an array of ABI entries");
|
|
19
|
+
}
|
|
20
|
+
for (const entry of value) {
|
|
21
|
+
if (!entry || typeof entry !== "object" || typeof entry.type !== "string") {
|
|
22
|
+
throw new Error(
|
|
23
|
+
"Invalid PVM ABI: every entry must have a string `type` (function/event/constructor/...)"
|
|
24
|
+
);
|
|
25
|
+
}
|
|
26
|
+
const inputs = entry.inputs;
|
|
27
|
+
if (inputs !== void 0 && !Array.isArray(inputs)) {
|
|
28
|
+
throw new Error("Invalid PVM ABI: `inputs` must be an array when present");
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return value;
|
|
32
|
+
}
|
|
33
|
+
async function loadPvmContractAbi(path) {
|
|
34
|
+
const { readFile } = await import('fs/promises');
|
|
35
|
+
const buf = await readFile(path);
|
|
36
|
+
return parsePvmContractAbi(buf);
|
|
37
|
+
}
|
|
38
|
+
async function loadPvmContractCode(path) {
|
|
39
|
+
const { readFile } = await import('fs/promises');
|
|
40
|
+
const buf = await readFile(path);
|
|
41
|
+
return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
42
|
+
}
|
|
43
|
+
async function loadPvmContractArtifacts(basePath) {
|
|
44
|
+
const [abi, bytecode] = await Promise.all([
|
|
45
|
+
loadPvmContractAbi(`${basePath}.abi.json`),
|
|
46
|
+
loadPvmContractCode(`${basePath}.polkavm`)
|
|
47
|
+
]);
|
|
48
|
+
return { abi, bytecode };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export { loadPvmContractAbi, loadPvmContractArtifacts, loadPvmContractCode, parsePvmContractAbi };
|
|
52
|
+
//# sourceMappingURL=chunk-2UN4YA25.js.map
|
|
53
|
+
//# sourceMappingURL=chunk-2UN4YA25.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/pvm.ts"],"names":[],"mappings":";AAqBO,SAAS,oBAAoB,MAAA,EAA6B;AAC7D,EAAA,IAAI,KAAA,GAAiB,MAAA;AAErB,EAAA,IAAI,iBAAiB,UAAA,EAAY;AAC7B,IAAA,KAAA,GAAQ,IAAI,WAAA,EAAY,CAAE,MAAA,CAAO,KAAK,CAAA;AAAA,EAC1C;AACA,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC3B,IAAA,IAAI;AACA,MAAA,KAAA,GAAQ,IAAA,CAAK,MAAM,KAAK,CAAA;AAAA,IAC5B,SAAS,KAAA,EAAO;AACZ,MAAA,MAAM,IAAI,KAAA,CAAM,iCAAA,EAAmC,EAAE,OAAO,CAAA;AAAA,IAChE;AAAA,EACJ;AACA,EAAA,IAAI,KAAA,IAAS,OAAO,KAAA,KAAU,QAAA,IAAY,CAAC,MAAM,OAAA,CAAQ,KAAK,CAAA,IAAK,KAAA,IAAS,KAAA,EAAO;AAC/E,IAAA,KAAA,GAAS,KAAA,CAA2B,GAAA;AAAA,EACxC;AACA,EAAA,IAAI,CAAC,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA,EAAG;AACvB,IAAA,MAAM,IAAI,MAAM,mDAAmD,CAAA;AAAA,EACvE;AACA,EAAA,KAAA,MAAW,SAAS,KAAA,EAAO;AACvB,IAAA,IAAI,CAAC,SAAS,OAAO,KAAA,KAAU,YAAY,OAAQ,KAAA,CAAmB,SAAS,QAAA,EAAU;AACrF,MAAA,MAAM,IAAI,KAAA;AAAA,QACN;AAAA,OACJ;AAAA,IACJ;AACA,IAAA,MAAM,SAAU,KAAA,CAAmB,MAAA;AACnC,IAAA,IAAI,WAAW,MAAA,IAAa,CAAC,KAAA,CAAM,OAAA,CAAQ,MAAM,CAAA,EAAG;AAChD,MAAA,MAAM,IAAI,MAAM,yDAAyD,CAAA;AAAA,IAC7E;AAAA,EACJ;AACA,EAAA,OAAO,KAAA;AACX;AAOA,eAAsB,mBAAmB,IAAA,EAAmC;AACxE,EAAA,MAAM,EAAE,QAAA,EAAS,GAAI,MAAM,OAAO,aAAkB,CAAA;AACpD,EAAA,MAAM,GAAA,GAAM,MAAM,QAAA,CAAS,IAAI,CAAA;AAC/B,EAAA,OAAO,oBAAoB,GAAG,CAAA;AAClC;AAYA,eAAsB,oBAAoB,IAAA,EAAmC;AACzE,EAAA,MAAM,EAAE,QAAA,EAAS,GAAI,MAAM,OAAO,aAAkB,CAAA;AACpD,EAAA,MAAM,GAAA,GAAM,MAAM,QAAA,CAAS,IAAI,CAAA;AAC/B,EAAA,OAAO,IAAI,UAAA,CAAW,GAAA,CAAI,QAAQ,GAAA,CAAI,UAAA,EAAY,IAAI,UAAU,CAAA;AACpE;AAYA,eAAsB,yBAAyB,QAAA,EAAiD;AAC5F,EAAA,MAAM,CAAC,GAAA,EAAK,QAAQ,CAAA,GAAI,MAAM,QAAQ,GAAA,CAAI;AAAA,IACtC,kBAAA,CAAmB,CAAA,EAAG,QAAQ,CAAA,SAAA,CAAW,CAAA;AAAA,IACzC,mBAAA,CAAoB,CAAA,EAAG,QAAQ,CAAA,QAAA,CAAU;AAAA,GAC5C,CAAA;AACD,EAAA,OAAO,EAAE,KAAK,QAAA,EAAS;AAC3B","file":"chunk-2UN4YA25.js","sourcesContent":["// Copyright 2026 Parity Technologies (UK) Ltd.\n// SPDX-License-Identifier: Apache-2.0\nimport type { AbiEntry } from \"./types.js\";\n\n/** ABI + PolkaVM bytecode pair emitted by `cargo pvm-contract build`. */\nexport interface PvmContractArtifacts {\n abi: AbiEntry[];\n bytecode: Uint8Array;\n}\n\n/**\n * Parse an in-memory cargo-pvm-contract ABI artifact.\n *\n * Accepts the shapes the toolchain may produce or that products may pass:\n * - parsed JSON array — `AbiEntry[]`\n * - parsed JSON object with an `abi` property — `{ abi: AbiEntry[] }`\n * - JSON string of either of the above\n * - `Uint8Array` containing UTF-8 JSON of either of the above\n *\n * @throws if the input cannot be coerced to a non-empty `AbiEntry[]`.\n */\nexport function parsePvmContractAbi(source: unknown): AbiEntry[] {\n let value: unknown = source;\n\n if (value instanceof Uint8Array) {\n value = new TextDecoder().decode(value);\n }\n if (typeof value === \"string\") {\n try {\n value = JSON.parse(value);\n } catch (cause) {\n throw new Error(\"Invalid PVM ABI: not valid JSON\", { cause });\n }\n }\n if (value && typeof value === \"object\" && !Array.isArray(value) && \"abi\" in value) {\n value = (value as { abi: unknown }).abi;\n }\n if (!Array.isArray(value)) {\n throw new Error(\"Invalid PVM ABI: expected an array of ABI entries\");\n }\n for (const entry of value) {\n if (!entry || typeof entry !== \"object\" || typeof (entry as AbiEntry).type !== \"string\") {\n throw new Error(\n \"Invalid PVM ABI: every entry must have a string `type` (function/event/constructor/...)\",\n );\n }\n const inputs = (entry as AbiEntry).inputs;\n if (inputs !== undefined && !Array.isArray(inputs)) {\n throw new Error(\"Invalid PVM ABI: `inputs` must be an array when present\");\n }\n }\n return value as AbiEntry[];\n}\n\n/**\n * Read a cargo-pvm-contract ABI file from disk and parse it.\n *\n * Node-only. For browser/in-memory inputs use {@link parsePvmContractAbi}.\n */\nexport async function loadPvmContractAbi(path: string): Promise<AbiEntry[]> {\n const { readFile } = await import(\"node:fs/promises\");\n const buf = await readFile(path);\n return parsePvmContractAbi(buf);\n}\n\n/**\n * Read the `.polkavm` bytecode artifact produced by `cargo pvm-contract build`.\n *\n * Returned bytes are ready to hand to `Revive.instantiate_with_code` (or to\n * any future deploy helper layered on top of it). Use this when you already\n * have an ABI in hand (e.g. inline or fetched separately) and only need the\n * PolkaVM blob — otherwise prefer {@link loadPvmContractArtifacts}.\n *\n * Node-only.\n */\nexport async function loadPvmContractCode(path: string): Promise<Uint8Array> {\n const { readFile } = await import(\"node:fs/promises\");\n const buf = await readFile(path);\n return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);\n}\n\n/**\n * Read both the `.abi.json` and `.polkavm` artifacts produced by\n * `cargo pvm-contract build` for a given base path.\n *\n * `basePath` is the path prefix shared by both files — typically\n * `target/<name>.release`. The function reads `${basePath}.abi.json` and\n * `${basePath}.polkavm`.\n *\n * Node-only.\n */\nexport async function loadPvmContractArtifacts(basePath: string): Promise<PvmContractArtifacts> {\n const [abi, bytecode] = await Promise.all([\n loadPvmContractAbi(`${basePath}.abi.json`),\n loadPvmContractCode(`${basePath}.polkavm`),\n ]);\n return { abi, bytecode };\n}\n\nif (import.meta.vitest) {\n const { test, expect, describe, beforeAll, afterAll } = import.meta.vitest;\n\n const sampleAbi: AbiEntry[] = [\n { type: \"constructor\", inputs: [], stateMutability: \"nonpayable\" },\n {\n type: \"function\",\n name: \"increment\",\n inputs: [],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"get\",\n inputs: [],\n outputs: [{ name: \"\", type: \"uint32\" }],\n stateMutability: \"view\",\n },\n ];\n\n describe(\"parsePvmContractAbi\", () => {\n test(\"accepts a parsed AbiEntry[] array directly\", () => {\n expect(parsePvmContractAbi(sampleAbi)).toEqual(sampleAbi);\n });\n\n test(\"accepts a wrapped { abi } object\", () => {\n expect(parsePvmContractAbi({ abi: sampleAbi })).toEqual(sampleAbi);\n });\n\n test(\"accepts a JSON string of an array\", () => {\n expect(parsePvmContractAbi(JSON.stringify(sampleAbi))).toEqual(sampleAbi);\n });\n\n test(\"accepts a JSON string of a wrapped object\", () => {\n expect(parsePvmContractAbi(JSON.stringify({ abi: sampleAbi }))).toEqual(sampleAbi);\n });\n\n test(\"accepts a UTF-8 Uint8Array\", () => {\n const bytes = new TextEncoder().encode(JSON.stringify(sampleAbi));\n expect(parsePvmContractAbi(bytes)).toEqual(sampleAbi);\n });\n\n test(\"throws on invalid JSON string\", () => {\n expect(() => parsePvmContractAbi(\"{not json\")).toThrow(/not valid JSON/);\n });\n\n test(\"throws when input is not an array\", () => {\n expect(() => parsePvmContractAbi(42)).toThrow(/expected an array/);\n expect(() => parsePvmContractAbi({ foo: \"bar\" })).toThrow(/expected an array/);\n });\n\n test(\"throws when an entry is missing `type`\", () => {\n expect(() => parsePvmContractAbi([{ name: \"noType\" }])).toThrow(/string `type`/);\n });\n\n test(\"throws when `inputs` is not an array\", () => {\n expect(() =>\n parsePvmContractAbi([{ type: \"function\", inputs: \"not an array\" }]),\n ).toThrow(/`inputs` must be an array/);\n });\n\n test(\"treats null as invalid\", () => {\n expect(() => parsePvmContractAbi(null)).toThrow();\n });\n });\n\n describe(\"loadPvmContractAbi / loadPvmContractArtifacts\", () => {\n // Cover the Node-only filesystem helpers via a real tmpdir round-trip.\n // The cargo-pvm-contract toolchain emits files at\n // target/<name>.release.abi.json\n // target/<name>.release.polkavm\n // — we recreate that layout here.\n let dir = \"\";\n let base = \"\";\n let lonely = \"\";\n let badAbi = \"\";\n // Minimal PolkaVM magic (`PVM\\0`) is enough to exercise the path —\n // we don't validate bytecode contents in the loader.\n const fakeBytecode = new Uint8Array([0x50, 0x56, 0x4d, 0x00, 0x01, 0x02, 0x03]);\n\n beforeAll(async () => {\n const { mkdtempSync, writeFileSync } = await import(\"node:fs\");\n const { tmpdir } = await import(\"node:os\");\n const { join } = await import(\"node:path\");\n dir = mkdtempSync(join(tmpdir(), \"pvm-loader-test-\"));\n base = join(dir, \"counter.release\");\n lonely = join(dir, \"lonely.release\");\n badAbi = join(dir, \"bad.release\");\n writeFileSync(`${base}.abi.json`, JSON.stringify(sampleAbi));\n writeFileSync(`${base}.polkavm`, fakeBytecode);\n writeFileSync(`${lonely}.abi.json`, JSON.stringify(sampleAbi));\n writeFileSync(`${badAbi}.abi.json`, \"{not valid json\");\n });\n\n afterAll(async () => {\n const { rmSync } = await import(\"node:fs\");\n try {\n rmSync(dir, { recursive: true, force: true });\n } catch {\n /* ignore */\n }\n });\n\n test(\"loadPvmContractAbi parses a JSON file from disk\", async () => {\n const abi = await loadPvmContractAbi(`${base}.abi.json`);\n expect(abi).toEqual(sampleAbi);\n });\n\n test(\"loadPvmContractArtifacts reads abi + bytecode pair\", async () => {\n const out = await loadPvmContractArtifacts(base);\n expect(out.abi).toEqual(sampleAbi);\n expect(out.bytecode).toBeInstanceOf(Uint8Array);\n expect(Array.from(out.bytecode)).toEqual(Array.from(fakeBytecode));\n });\n\n test(\"loadPvmContractCode reads only the .polkavm blob\", async () => {\n const code = await loadPvmContractCode(`${base}.polkavm`);\n expect(code).toBeInstanceOf(Uint8Array);\n expect(Array.from(code)).toEqual(Array.from(fakeBytecode));\n });\n\n test(\"loadPvmContractAbi rejects a missing file\", async () => {\n await expect(loadPvmContractAbi(`${base}.does-not-exist`)).rejects.toThrow();\n });\n\n test(\"loadPvmContractArtifacts rejects when bytecode is missing\", async () => {\n // Only `${lonely}.abi.json` exists — `.polkavm` is absent.\n await expect(loadPvmContractArtifacts(lonely)).rejects.toThrow();\n });\n\n test(\"loadPvmContractAbi propagates parse errors with helpful message\", async () => {\n await expect(loadPvmContractAbi(`${badAbi}.abi.json`)).rejects.toThrow(\n /not valid JSON/,\n );\n });\n });\n}\n"]}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { A as AbiEntry } from './types-Dtu4IsSh.js';
|
|
2
|
+
import '@parity/result';
|
|
3
|
+
import '@parity/product-sdk-signer';
|
|
4
|
+
import '@parity/product-sdk-tx';
|
|
5
|
+
import 'polkadot-api';
|
|
6
|
+
import '@parity/product-sdk-errors';
|
|
7
|
+
|
|
8
|
+
/** A contract input to {@link generateContractTypes}: either an inline ABI or a `cargo-pvm-contract` artefact path. */
|
|
9
|
+
type ContractTypeInput = {
|
|
10
|
+
library: string;
|
|
11
|
+
abi: AbiEntry[];
|
|
12
|
+
} | {
|
|
13
|
+
library: string;
|
|
14
|
+
abiPath: string;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Resolve a heterogeneous list of {@link ContractTypeInput} entries into the
|
|
18
|
+
* `{ library, abi }` shape consumed by {@link generateContractTypes}. Reads any
|
|
19
|
+
* `abiPath` entries off disk via {@link loadPvmContractAbi} (Node only).
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* ```ts
|
|
23
|
+
* const resolved = await resolveContractTypeInputs([
|
|
24
|
+
* { library: "@example/counter", abiPath: "./target/counter.release.abi.json" },
|
|
25
|
+
* { library: "@example/inline", abi: counterAbi },
|
|
26
|
+
* ]);
|
|
27
|
+
* const src = generateContractTypes(resolved);
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
declare function resolveContractTypeInputs(inputs: readonly ContractTypeInput[]): Promise<{
|
|
31
|
+
library: string;
|
|
32
|
+
abi: AbiEntry[];
|
|
33
|
+
}[]>;
|
|
34
|
+
/**
|
|
35
|
+
* Generate a TypeScript module augmentation that extends the
|
|
36
|
+
* {@link Contracts} interface with typed method signatures for each
|
|
37
|
+
* installed contract.
|
|
38
|
+
*
|
|
39
|
+
* The output is written to `.cdm/contracts.d.ts` (or equivalent) and
|
|
40
|
+
* augments `"@parity/product-sdk-contracts"` so that
|
|
41
|
+
* `ContractManager.getContract()` returns fully-typed handles.
|
|
42
|
+
*
|
|
43
|
+
* Accepts `{ library, abi }` directly. To pull ABIs from
|
|
44
|
+
* `cargo-pvm-contract` build artefacts on disk, use
|
|
45
|
+
* {@link resolveContractTypeInputs} first.
|
|
46
|
+
*
|
|
47
|
+
* @example
|
|
48
|
+
* ```ts
|
|
49
|
+
* // Inline ABIs
|
|
50
|
+
* const src = generateContractTypes([
|
|
51
|
+
* { library: "@example/counter", abi },
|
|
52
|
+
* ]);
|
|
53
|
+
* writeFileSync(".cdm/contracts.d.ts", src);
|
|
54
|
+
*
|
|
55
|
+
* // From cargo-pvm-contract artefacts
|
|
56
|
+
* const resolved = await resolveContractTypeInputs([
|
|
57
|
+
* { library: "@example/counter", abiPath: "./target/counter.release.abi.json" },
|
|
58
|
+
* ]);
|
|
59
|
+
* writeFileSync(".cdm/contracts.d.ts", generateContractTypes(resolved));
|
|
60
|
+
* ```
|
|
61
|
+
*/
|
|
62
|
+
declare function generateContractTypes(contracts: {
|
|
63
|
+
library: string;
|
|
64
|
+
abi: AbiEntry[];
|
|
65
|
+
}[]): string;
|
|
66
|
+
|
|
67
|
+
export { type ContractTypeInput, generateContractTypes, resolveContractTypeInputs };
|