@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.
@@ -0,0 +1,83 @@
1
+ import { loadPvmContractAbi } from './chunk-2UN4YA25.js';
2
+
3
+ // src/codegen.ts
4
+ async function resolveContractTypeInputs(inputs) {
5
+ return Promise.all(
6
+ inputs.map(async (input) => {
7
+ if ("abi" in input) return { library: input.library, abi: input.abi };
8
+ return { library: input.library, abi: await loadPvmContractAbi(input.abiPath) };
9
+ })
10
+ );
11
+ }
12
+ function mapSolidityType(param) {
13
+ const t = param.type;
14
+ if (t.endsWith("[]")) {
15
+ const inner = { ...param, type: t.slice(0, -2) };
16
+ return `${mapSolidityType(inner)}[]`;
17
+ }
18
+ const fixedArrayMatch = t.match(/^(.+)\[(\d+)\]$/);
19
+ if (fixedArrayMatch) {
20
+ const inner = { ...param, type: fixedArrayMatch[1] };
21
+ return `${mapSolidityType(inner)}[]`;
22
+ }
23
+ if (t === "tuple" && param.components) {
24
+ const fields = param.components.map((c) => `${c.name}: ${mapSolidityType(c)}`);
25
+ return `{ ${fields.join("; ")} }`;
26
+ }
27
+ if (/^uint(8|16|32)$/.test(t)) return "number";
28
+ if (/^uint\d*$/.test(t)) return "bigint";
29
+ if (/^int(8|16|32)$/.test(t)) return "number";
30
+ if (/^int\d*$/.test(t)) return "bigint";
31
+ if (t === "address") return "HexString";
32
+ if (t === "bytes") return "HexString";
33
+ const bytesMatch = t.match(/^bytes(\d+)$/);
34
+ if (bytesMatch) return `SizedHex<${bytesMatch[1]}>`;
35
+ if (t === "bool") return "boolean";
36
+ if (t === "string") return "string";
37
+ return "unknown";
38
+ }
39
+ function generateMethodArgsType(inputs) {
40
+ if (inputs.length === 0) return "[]";
41
+ const parts = inputs.map((p) => `${p.name}: ${mapSolidityType(p)}`);
42
+ return `[${parts.join(", ")}]`;
43
+ }
44
+ function generateMethodResponseType(outputs) {
45
+ if (!outputs || outputs.length === 0) return "undefined";
46
+ if (outputs.length === 1) return mapSolidityType(outputs[0]);
47
+ const fields = outputs.map((o, i) => {
48
+ const name = o.name || `_${i}`;
49
+ return `${name}: ${mapSolidityType(o)}`;
50
+ });
51
+ return `{ ${fields.join("; ")} }`;
52
+ }
53
+ function generateContractTypes(contracts) {
54
+ const lines = [
55
+ "// Auto-generated by cdm install \u2014 do not edit",
56
+ 'import type { HexString, SizedHex } from "polkadot-api";',
57
+ "",
58
+ 'declare module "@parity/product-sdk-contracts" {',
59
+ " interface Contracts {"
60
+ ];
61
+ for (const contract of contracts) {
62
+ const methods = contract.abi.filter((e) => e.type === "function" && e.name);
63
+ lines.push(` "${contract.library}": {`);
64
+ lines.push(" methods: {");
65
+ for (const method of methods) {
66
+ const args = generateMethodArgsType(method.inputs);
67
+ const response = generateMethodResponseType(method.outputs);
68
+ lines.push(
69
+ ` ${method.name}: { args: ${args}; response: ${response} };`
70
+ );
71
+ }
72
+ lines.push(" };");
73
+ lines.push(" };");
74
+ }
75
+ lines.push(" }");
76
+ lines.push("}");
77
+ lines.push("");
78
+ return lines.join("\n");
79
+ }
80
+
81
+ export { generateContractTypes, resolveContractTypeInputs };
82
+ //# sourceMappingURL=codegen.js.map
83
+ //# sourceMappingURL=codegen.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/codegen.ts"],"names":[],"mappings":";;;AAwBA,eAAsB,0BAClB,MAAA,EAC+C;AAC/C,EAAA,OAAO,OAAA,CAAQ,GAAA;AAAA,IACX,MAAA,CAAO,GAAA,CAAI,OAAO,KAAA,KAAU;AACxB,MAAA,IAAI,KAAA,IAAS,OAAO,OAAO,EAAE,SAAS,KAAA,CAAM,OAAA,EAAS,GAAA,EAAK,KAAA,CAAM,GAAA,EAAI;AACpE,MAAA,OAAO,EAAE,SAAS,KAAA,CAAM,OAAA,EAAS,KAAK,MAAM,kBAAA,CAAmB,KAAA,CAAM,OAAO,CAAA,EAAE;AAAA,IAClF,CAAC;AAAA,GACL;A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":"codegen.js","sourcesContent":["// Copyright 2026 Parity Technologies (UK) Ltd.\n// SPDX-License-Identifier: Apache-2.0\nimport type { AbiEntry, AbiParam } from \"./types.js\";\nimport { loadPvmContractAbi } from \"./pvm.js\";\n\n/** A contract input to {@link generateContractTypes}: either an inline ABI or a `cargo-pvm-contract` artefact path. */\nexport type ContractTypeInput =\n | { library: string; abi: AbiEntry[] }\n | { library: string; abiPath: string };\n\n/**\n * Resolve a heterogeneous list of {@link ContractTypeInput} entries into the\n * `{ library, abi }` shape consumed by {@link generateContractTypes}. Reads any\n * `abiPath` entries off disk via {@link loadPvmContractAbi} (Node only).\n *\n * @example\n * ```ts\n * const resolved = await resolveContractTypeInputs([\n * { library: \"@example/counter\", abiPath: \"./target/counter.release.abi.json\" },\n * { library: \"@example/inline\", abi: counterAbi },\n * ]);\n * const src = generateContractTypes(resolved);\n * ```\n */\nexport async function resolveContractTypeInputs(\n inputs: readonly ContractTypeInput[],\n): Promise<{ library: string; abi: AbiEntry[] }[]> {\n return Promise.all(\n inputs.map(async (input) => {\n if (\"abi\" in input) return { library: input.library, abi: input.abi };\n return { library: input.library, abi: await loadPvmContractAbi(input.abiPath) };\n }),\n );\n}\n\n/** Map a Solidity ABI type to its TypeScript equivalent. */\nfunction mapSolidityType(param: AbiParam): string {\n const t = param.type;\n\n // Dynamic arrays — e.g. uint256[]\n if (t.endsWith(\"[]\")) {\n const inner = { ...param, type: t.slice(0, -2) };\n return `${mapSolidityType(inner)}[]`;\n }\n\n // Fixed-size arrays — e.g. uint256[3]\n const fixedArrayMatch = t.match(/^(.+)\\[(\\d+)\\]$/);\n if (fixedArrayMatch) {\n const inner = { ...param, type: fixedArrayMatch[1] };\n return `${mapSolidityType(inner)}[]`;\n }\n\n // Tuple\n if (t === \"tuple\" && param.components) {\n const fields = param.components.map((c) => `${c.name}: ${mapSolidityType(c)}`);\n return `{ ${fields.join(\"; \")} }`;\n }\n\n // Unsigned integers — uint8/16/32 fit in JS number\n if (/^uint(8|16|32)$/.test(t)) return \"number\";\n if (/^uint\\d*$/.test(t)) return \"bigint\";\n\n // Signed integers\n if (/^int(8|16|32)$/.test(t)) return \"number\";\n if (/^int\\d*$/.test(t)) return \"bigint\";\n\n // Address\n if (t === \"address\") return \"HexString\";\n\n // Bytes — viem's ABI codec accepts hex strings (`0x…`) for both\n // variable-length `bytes` and fixed-length `bytesN`. We surface\n // `SizedHex<N>` for the latter so consumers see the byte width at\n // compile time, even though the runtime check is just on the prefix.\n if (t === \"bytes\") return \"HexString\";\n const bytesMatch = t.match(/^bytes(\\d+)$/);\n if (bytesMatch) return `SizedHex<${bytesMatch[1]}>`;\n\n // Primitives\n if (t === \"bool\") return \"boolean\";\n if (t === \"string\") return \"string\";\n\n return \"unknown\";\n}\n\nfunction generateMethodArgsType(inputs: AbiParam[]): string {\n if (inputs.length === 0) return \"[]\";\n const parts = inputs.map((p) => `${p.name}: ${mapSolidityType(p)}`);\n return `[${parts.join(\", \")}]`;\n}\n\nfunction generateMethodResponseType(outputs: AbiParam[] | undefined): string {\n if (!outputs || outputs.length === 0) return \"undefined\";\n if (outputs.length === 1) return mapSolidityType(outputs[0]);\n const fields = outputs.map((o, i) => {\n const name = o.name || `_${i}`;\n return `${name}: ${mapSolidityType(o)}`;\n });\n return `{ ${fields.join(\"; \")} }`;\n}\n\n/**\n * Generate a TypeScript module augmentation that extends the\n * {@link Contracts} interface with typed method signatures for each\n * installed contract.\n *\n * The output is written to `.cdm/contracts.d.ts` (or equivalent) and\n * augments `\"@parity/product-sdk-contracts\"` so that\n * `ContractManager.getContract()` returns fully-typed handles.\n *\n * Accepts `{ library, abi }` directly. To pull ABIs from\n * `cargo-pvm-contract` build artefacts on disk, use\n * {@link resolveContractTypeInputs} first.\n *\n * @example\n * ```ts\n * // Inline ABIs\n * const src = generateContractTypes([\n * { library: \"@example/counter\", abi },\n * ]);\n * writeFileSync(\".cdm/contracts.d.ts\", src);\n *\n * // From cargo-pvm-contract artefacts\n * const resolved = await resolveContractTypeInputs([\n * { library: \"@example/counter\", abiPath: \"./target/counter.release.abi.json\" },\n * ]);\n * writeFileSync(\".cdm/contracts.d.ts\", generateContractTypes(resolved));\n * ```\n */\nexport function generateContractTypes(contracts: { library: string; abi: AbiEntry[] }[]): string {\n const lines: string[] = [\n \"// Auto-generated by cdm install — do not edit\",\n 'import type { HexString, SizedHex } from \"polkadot-api\";',\n \"\",\n 'declare module \"@parity/product-sdk-contracts\" {',\n \" interface Contracts {\",\n ];\n\n for (const contract of contracts) {\n const methods = contract.abi.filter((e) => e.type === \"function\" && e.name);\n lines.push(` \"${contract.library}\": {`);\n lines.push(\" methods: {\");\n for (const method of methods) {\n const args = generateMethodArgsType(method.inputs);\n const response = generateMethodResponseType(method.outputs);\n lines.push(\n ` ${method.name!}: { args: ${args}; response: ${response} };`,\n );\n }\n lines.push(\" };\");\n lines.push(\" };\");\n }\n\n lines.push(\" }\");\n lines.push(\"}\");\n lines.push(\"\");\n\n return lines.join(\"\\n\");\n}\n\nif (import.meta.vitest) {\n const { test, expect, describe } = import.meta.vitest;\n\n describe(\"mapSolidityType\", () => {\n const cases: [AbiParam, string][] = [\n [{ name: \"x\", type: \"uint8\" }, \"number\"],\n [{ name: \"x\", type: \"uint16\" }, \"number\"],\n [{ name: \"x\", type: \"uint32\" }, \"number\"],\n [{ name: \"x\", type: \"uint64\" }, \"bigint\"],\n [{ name: \"x\", type: \"uint128\" }, \"bigint\"],\n [{ name: \"x\", type: \"uint256\" }, \"bigint\"],\n [{ name: \"x\", type: \"int8\" }, \"number\"],\n [{ name: \"x\", type: \"int32\" }, \"number\"],\n [{ name: \"x\", type: \"int64\" }, \"bigint\"],\n [{ name: \"x\", type: \"int256\" }, \"bigint\"],\n [{ name: \"x\", type: \"address\" }, \"HexString\"],\n [{ name: \"x\", type: \"bool\" }, \"boolean\"],\n [{ name: \"x\", type: \"string\" }, \"string\"],\n [{ name: \"x\", type: \"bytes\" }, \"HexString\"],\n [{ name: \"x\", type: \"bytes32\" }, \"SizedHex<32>\"],\n [{ name: \"x\", type: \"bytes4\" }, \"SizedHex<4>\"],\n [{ name: \"x\", type: \"uint256[]\" }, \"bigint[]\"],\n [{ name: \"x\", type: \"address[]\" }, \"HexString[]\"],\n [{ name: \"x\", type: \"uint256[3]\" }, \"bigint[]\"],\n [{ name: \"x\", type: \"somethingWeird\" }, \"unknown\"],\n ];\n\n for (const [param, expected] of cases) {\n test(`${param.type} → ${expected}`, () => {\n expect(mapSolidityType(param)).toBe(expected);\n });\n }\n\n test(\"tuple with components\", () => {\n const param: AbiParam = {\n name: \"info\",\n type: \"tuple\",\n components: [\n { name: \"addr\", type: \"address\" },\n { name: \"amount\", type: \"uint256\" },\n ],\n };\n expect(mapSolidityType(param)).toBe(\"{ addr: HexString; amount: bigint }\");\n });\n\n test(\"nested array of tuples\", () => {\n const param: AbiParam = {\n name: \"items\",\n type: \"tuple[]\",\n components: [\n { name: \"id\", type: \"uint32\" },\n { name: \"name\", type: \"string\" },\n ],\n };\n expect(mapSolidityType(param)).toBe(\"{ id: number; name: string }[]\");\n });\n });\n\n describe(\"generateMethodArgsType\", () => {\n test(\"empty inputs\", () => {\n expect(generateMethodArgsType([])).toBe(\"[]\");\n });\n\n test(\"single input\", () => {\n expect(generateMethodArgsType([{ name: \"to\", type: \"address\" }])).toBe(\n \"[to: HexString]\",\n );\n });\n\n test(\"multiple inputs\", () => {\n const result = generateMethodArgsType([\n { name: \"to\", type: \"address\" },\n { name: \"amount\", type: \"uint256\" },\n ]);\n expect(result).toBe(\"[to: HexString, amount: bigint]\");\n });\n });\n\n describe(\"generateMethodResponseType\", () => {\n test(\"no outputs\", () => {\n expect(generateMethodResponseType(undefined)).toBe(\"undefined\");\n expect(generateMethodResponseType([])).toBe(\"undefined\");\n });\n\n test(\"single output\", () => {\n expect(generateMethodResponseType([{ name: \"\", type: \"uint32\" }])).toBe(\"number\");\n });\n\n test(\"multiple outputs\", () => {\n const result = generateMethodResponseType([\n { name: \"balance\", type: \"uint256\" },\n { name: \"nonce\", type: \"uint32\" },\n ]);\n expect(result).toBe(\"{ balance: bigint; nonce: number }\");\n });\n\n test(\"unnamed outputs get positional names\", () => {\n const result = generateMethodResponseType([\n { name: \"\", type: \"bool\" },\n { name: \"\", type: \"uint256\" },\n ]);\n expect(result).toBe(\"{ _0: boolean; _1: bigint }\");\n });\n });\n\n describe(\"generateContractTypes\", () => {\n test(\"generates valid module augmentation\", () => {\n const result = generateContractTypes([\n {\n library: \"@example/counter\",\n abi: [\n {\n type: \"constructor\",\n inputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"getCount\",\n inputs: [],\n outputs: [{ name: \"\", type: \"uint32\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"increment\",\n inputs: [],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n ],\n },\n ]);\n\n expect(result).toContain('declare module \"@parity/product-sdk-contracts\"');\n expect(result).toContain(\"interface Contracts\");\n expect(result).toContain('\"@example/counter\"');\n expect(result).toContain(\"getCount: { args: []; response: number };\");\n expect(result).toContain(\"increment: { args: []; response: undefined };\");\n // Should not include constructor\n expect(result).not.toContain(\"constructor\");\n });\n\n test(\"handles multiple contracts\", () => {\n const result = generateContractTypes([\n {\n library: \"@a/one\",\n abi: [\n {\n type: \"function\",\n name: \"foo\",\n inputs: [{ name: \"x\", type: \"uint256\" }],\n outputs: [{ name: \"\", type: \"bool\" }],\n },\n ],\n },\n {\n library: \"@b/two\",\n abi: [\n {\n type: \"function\",\n name: \"bar\",\n inputs: [],\n outputs: [{ name: \"\", type: \"address\" }],\n },\n ],\n },\n ]);\n\n expect(result).toContain('\"@a/one\"');\n expect(result).toContain('\"@b/two\"');\n expect(result).toContain(\"foo: { args: [x: bigint]; response: boolean };\");\n expect(result).toContain(\"bar: { args: []; response: HexString };\");\n });\n\n test(\"empty contracts list\", () => {\n const result = generateContractTypes([]);\n expect(result).toContain(\"interface Contracts {\");\n expect(result).toContain(\"}\");\n });\n\n test(\"includes polkadot-api type imports\", () => {\n const result = generateContractTypes([]);\n expect(result).toContain(\"import type { HexString, SizedHex }\");\n expect(result).toContain('from \"polkadot-api\"');\n });\n });\n\n describe(\"resolveContractTypeInputs\", () => {\n test(\"passes inline { library, abi } through unchanged\", async () => {\n const abi: AbiEntry[] = [\n {\n type: \"function\",\n name: \"foo\",\n inputs: [],\n outputs: [{ name: \"\", type: \"bool\" }],\n },\n ];\n const out = await resolveContractTypeInputs([{ library: \"@x/foo\", abi }]);\n expect(out).toEqual([{ library: \"@x/foo\", abi }]);\n });\n\n test(\"loads ABI from { abiPath } on disk\", async () => {\n const fs = await import(\"node:fs/promises\");\n const path = await import(\"node:path\");\n const os = await import(\"node:os\");\n const tmp = await fs.mkdtemp(path.join(os.tmpdir(), \"codegen-\"));\n const abi: AbiEntry[] = [\n {\n type: \"function\",\n name: \"ping\",\n inputs: [],\n outputs: [{ name: \"\", type: \"bool\" }],\n },\n ];\n const file = path.join(tmp, \"ping.release.abi.json\");\n await fs.writeFile(file, JSON.stringify(abi), \"utf8\");\n try {\n const out = await resolveContractTypeInputs([\n { library: \"@x/ping\", abiPath: file },\n ]);\n expect(out).toEqual([{ library: \"@x/ping\", abi }]);\n\n // And it composes with generateContractTypes end-to-end:\n const src = generateContractTypes(out);\n expect(src).toContain('\"@x/ping\"');\n expect(src).toContain(\"ping: { args: []; response: boolean };\");\n } finally {\n await fs.rm(tmp, { recursive: true, force: true });\n }\n });\n });\n}\n"]}
@@ -0,0 +1,135 @@
1
+ import { Result } from '@parity/result';
2
+ import { PolkadotClient, HexString, SS58String } from 'polkadot-api';
3
+ import { C as CdmJson, a as ContractRuntime, b as ContractManagerOptions, c as ContractDefaults, d as ContractRuntimeOptions, L as LiveContractResolutionOptions, e as ContractError, f as Contracts, g as Contract, h as ContractDef, A as AbiEntry, i as ContractOptions } from './types-Dtu4IsSh.js';
4
+ export { j as AbiParam, k as CdmJsonContract, l as CdmJsonDependencyVersion, m as ContractDryRunAt, n as ContractDryRunFailedError, o as ContractInvalidOriginError, p as ContractLiveAddressResolutionError, q as ContractNotFoundError, r as ContractRevertInfo, s as ContractRevertedError, t as ContractSignerMissingError, D as DecodedContractRevert, P as PrepareOptions, Q as QueryOptions, u as QueryResult, R as ReviveDryRunCall, v as ReviveDryRunCallOptions, w as ReviveDryRunResult, x as ReviveTypedApi, T as TxOptions, y as createContractRuntime, z as createContractRuntimeFromClient, B as ensureContractAccountMapped, E as isContractAccountMapped } from './types-Dtu4IsSh.js';
5
+ export { BatchableCall, TxResult } from '@parity/product-sdk-tx';
6
+ import '@parity/product-sdk-signer';
7
+ import '@parity/product-sdk-errors';
8
+
9
+ /**
10
+ * Return a cloned manifest whose installed contract addresses have been
11
+ * replaced by live addresses from the CDM registry.
12
+ *
13
+ * This is intentionally strict: if a requested library cannot be resolved from
14
+ * the registry, the result is `err`. Use `new ContractManager(...)` or
15
+ * `ContractManager.fromClient(...)` directly for snapshot-only behavior.
16
+ *
17
+ * @returns A {@link Result}: `ok(CdmJson)` with live addresses patched in, or
18
+ * `err(ContractError)` — a `ContractLiveAddressResolutionError` (missing
19
+ * contracts, no registry, or a lookup that failed / returned nothing) or a
20
+ * `ContractNotFoundError` (a requested library isn't installed).
21
+ */
22
+ declare function withLiveContractAddresses(cdmJson: CdmJson, runtime: ContractRuntime, options?: LiveContractResolutionOptions): Promise<Result<CdmJson, ContractError>>;
23
+ /**
24
+ * Manages typed contract interactions backed by a `cdm.json` manifest.
25
+ *
26
+ * Pass a `signerManager` (e.g. a `SignerManager` from `@parity/product-sdk-signer`)
27
+ * so the currently logged-in account is used automatically — no manual
28
+ * signer/origin wiring needed.
29
+ *
30
+ * @example
31
+ * ```ts
32
+ * import { createChainClient } from "@parity/product-sdk-chain-client";
33
+ * import { paseo_asset_hub } from "@parity/product-sdk-descriptors/paseo-asset-hub";
34
+ * import { ContractManager, createContractRuntime } from "@parity/product-sdk-contracts";
35
+ * import cdmJson from "./cdm.json";
36
+ *
37
+ * const client = await createChainClient({
38
+ * chains: { assetHub: paseo_asset_hub },
39
+ * });
40
+ * const runtime = createContractRuntime(client.assetHub);
41
+ * const manager = new ContractManager(cdmJson, runtime, {
42
+ * signerManager,
43
+ * });
44
+ *
45
+ * const counter = manager.getContract("@example/counter");
46
+ * const { value } = await counter.getCount.query();
47
+ * await counter.increment.tx();
48
+ * ```
49
+ */
50
+ declare class ContractManager {
51
+ private contracts;
52
+ private runtime;
53
+ private defaults;
54
+ constructor(cdmJson: CdmJson, runtime: ContractRuntime, options?: ContractManagerOptions);
55
+ /** Update the default origin, signer, or signerManager used by all contract handles. */
56
+ setDefaults(defaults: ContractDefaults): void;
57
+ /**
58
+ * Create a `ContractManager` from a raw `PolkadotClient`.
59
+ *
60
+ * Convenience factory: builds a `ContractRuntime` internally from the
61
+ * client's typed API. Requires that the chain's typed API exposes the
62
+ * `Revive` pallet and `ReviveApi` runtime API (Asset Hub Paseo /
63
+ * Polkadot / Kusama).
64
+ *
65
+ * @param cdmJson - The CDM manifest.
66
+ * @param client - A `PolkadotClient` for the chain where contracts are deployed.
67
+ * @param descriptor - The chain descriptor used to derive the typed API.
68
+ * @param options - Optional configuration (signerManager, defaults).
69
+ */
70
+ static fromClient<TDescriptor>(cdmJson: CdmJson, client: PolkadotClient, descriptor: TDescriptor, options?: ContractManagerOptions & ContractRuntimeOptions): ContractManager;
71
+ /**
72
+ * Create a manager after strictly resolving installed contract addresses
73
+ * from the live CDM registry. ABIs still come from the installed manifest.
74
+ */
75
+ static fromLive(cdmJson: CdmJson, runtime: ContractRuntime, options?: ContractManagerOptions & LiveContractResolutionOptions): Promise<Result<ContractManager, ContractError>>;
76
+ /**
77
+ * Convenience factory for {@link fromLive} when the caller has a raw
78
+ * `PolkadotClient` and descriptor.
79
+ */
80
+ static fromLiveClient<TDescriptor>(cdmJson: CdmJson, client: PolkadotClient, descriptor: TDescriptor, options?: ContractManagerOptions & ContractRuntimeOptions & LiveContractResolutionOptions): Promise<Result<ContractManager, ContractError>>;
81
+ private getContractData;
82
+ /**
83
+ * Get a typed contract handle.
84
+ *
85
+ * Each method on the returned object has `.query()` for read-only calls
86
+ * and `.tx()` for signed transactions. When codegen augments
87
+ * {@link Contracts}, passing a known library name returns a fully-typed
88
+ * handle. Without codegen the generic overload still works — methods are
89
+ * accessible but untyped.
90
+ */
91
+ getContract<K extends string & keyof Contracts>(library: K): Contract<Contracts[K]>;
92
+ getContract(library: string): Contract<ContractDef>;
93
+ /** Get the on-chain address of an installed contract. */
94
+ getAddress(library: string): HexString;
95
+ /**
96
+ * Get the underlying {@link ContractRuntime} backing this manager.
97
+ *
98
+ * Useful when a consumer needs to call helpers that take a runtime
99
+ * directly — most commonly {@link ensureContractAccountMapped} at app
100
+ * boot. Avoids the alternative of building a second runtime against the
101
+ * same client and descriptor.
102
+ */
103
+ getRuntime(): ContractRuntime;
104
+ }
105
+ /**
106
+ * Create a contract handle from a raw H160 address and ABI — no `cdm.json` needed.
107
+ *
108
+ * @example
109
+ * ```ts
110
+ * import { createContractRuntime, createContract } from "@parity/product-sdk-contracts";
111
+ *
112
+ * const runtime = createContractRuntime(client.assetHub);
113
+ * const counter = createContract(runtime, "0xC472...", abi, { signerManager });
114
+ * await counter.getCount.query();
115
+ * await counter.increment.tx();
116
+ * ```
117
+ */
118
+ declare function createContract(runtime: ContractRuntime, address: HexString, abi: AbiEntry[], options?: ContractOptions): Contract<ContractDef>;
119
+ /**
120
+ * Create a contract handle from a raw `PolkadotClient`, descriptor, address, and ABI.
121
+ *
122
+ * Convenience wrapper that builds the `ContractRuntime` from the client's
123
+ * typed API. The chain must expose `Revive` + `ReviveApi`.
124
+ *
125
+ * @example
126
+ * ```ts
127
+ * const counter = createContractFromClient(client, paseo_asset_hub, "0xC472...", abi);
128
+ * const { value } = await counter.getCount.query();
129
+ * ```
130
+ */
131
+ declare function createContractFromClient<TDescriptor>(client: PolkadotClient, descriptor: TDescriptor, address: HexString, abi: AbiEntry[], options?: ContractOptions & ContractRuntimeOptions): Contract<ContractDef>;
132
+
133
+ declare const QUERY_FALLBACK_ORIGIN: SS58String;
134
+
135
+ export { AbiEntry, CdmJson, Contract, ContractDef, ContractDefaults, ContractError, ContractManager, ContractManagerOptions, ContractOptions, ContractRuntime, ContractRuntimeOptions, Contracts, LiveContractResolutionOptions, QUERY_FALLBACK_ORIGIN, createContract, createContractFromClient, withLiveContractAddresses };