@everyprotocol/every-cli 0.1.2 → 0.1.3

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/dist/abi.js CHANGED
@@ -31,6 +31,11 @@ export const abi = {
31
31
  "function mint(address to, address set, uint64 id, bytes memory data, bytes memory auth, uint32 policy) payable",
32
32
  ]),
33
33
  ...loadNonFuncAbiItems("ObjectMinter"),
34
+ ...loadNonFuncAbiItems("ISet"),
35
+ ],
36
+ create: [
37
+ ...parseAbi(["function create(address to, uint64 id0, bytes calldata data) payable"]),
38
+ ...loadNonFuncAbiItems("ISet"),
34
39
  ],
35
40
  relation: [
36
41
  ...parseAbi([
package/dist/config.js CHANGED
@@ -2,7 +2,93 @@ import fs from "fs";
2
2
  import path from "path";
3
3
  import os from "os";
4
4
  import { parse as parseTOML } from "@iarna/toml";
5
+ import * as TOML from "@iarna/toml";
5
6
  import { __dirname } from "./utils.js";
7
+ // export interface Universe {
8
+ // name: string;
9
+ // id: number;
10
+ // rpc: string;
11
+ // explorer: string;
12
+ // observer: string;
13
+ // contracts: {
14
+ // setRegistry: string;
15
+ // omniRegistry: string;
16
+ // kindRegistry: string;
17
+ // elementRegistry: string;
18
+ // objectMinter: string;
19
+ // };
20
+ // }
21
+ // export interface Observer {
22
+ // name: string;
23
+ // rpc: string;
24
+ // explorer: string;
25
+ // gateway: string;
26
+ // }
27
+ // export interface Config {
28
+ // universes: Record<string, Universe>;
29
+ // observers: Record<string, Observer>;
30
+ // }
31
+ import { z } from "zod";
32
+ export const ContractsSchema = z.object({
33
+ SetRegistry: z.string().regex(/^0x[0-9a-fA-F]{40}$/, "Must be an Ethereum address"),
34
+ OmniRegistry: z.string().regex(/^0x[0-9a-fA-F]{40}$/),
35
+ KindRegistry: z.string().regex(/^0x[0-9a-fA-F]{40}$/),
36
+ ElementRegistry: z.string().regex(/^0x[0-9a-fA-F]{40}$/),
37
+ ObjectMinter: z.string().regex(/^0x[0-9a-fA-F]{40}$/),
38
+ });
39
+ export const UniverseSchema = z.object({
40
+ id: z.number().int().nonnegative(),
41
+ rpc: z.string().url(),
42
+ explorer: z.string().url(),
43
+ observer: z.string(), // reference to an Observer key
44
+ contracts: ContractsSchema,
45
+ });
46
+ export const ObserverSchema = z.object({
47
+ rpc: z.string().url(),
48
+ explorer: z.string().url(),
49
+ gateway: z.string().url(),
50
+ });
51
+ export const ConfigSchema = z.object({
52
+ universes: z.record(UniverseSchema),
53
+ observers: z.record(ObserverSchema),
54
+ });
55
+ export function loadConfig(file) {
56
+ const text = fs.readFileSync(file, "utf8");
57
+ const raw = TOML.parse(text);
58
+ return ConfigSchema.parse(raw);
59
+ }
60
+ const configPaths = [
61
+ path.resolve(__dirname, "../.every.toml"),
62
+ path.resolve(os.homedir(), ".every.toml"),
63
+ path.resolve(process.cwd(), ".every.toml"),
64
+ ];
65
+ export function loadMergedConfig() {
66
+ const merged = { universes: {}, observers: {} };
67
+ const existingFiles = configPaths.filter((f) => fs.existsSync(f));
68
+ if (existingFiles.length === 0) {
69
+ throw new Error(`No config file found. Searched in:\n ${configPaths.join("\n ")}`);
70
+ }
71
+ for (const file of existingFiles) {
72
+ const raw = loadConfig(file);
73
+ if (raw.universes) {
74
+ for (const [name, uni] of Object.entries(raw.universes)) {
75
+ merged.universes[name] = {
76
+ ...(merged.universes[name] ?? {}),
77
+ ...uni, // shallow merge here
78
+ };
79
+ }
80
+ }
81
+ if (raw.observers) {
82
+ for (const [name, obs] of Object.entries(raw.observers)) {
83
+ merged.observers[name] = {
84
+ ...(merged.observers[name] ?? {}),
85
+ ...obs,
86
+ };
87
+ }
88
+ }
89
+ }
90
+ return ConfigSchema.parse(merged);
91
+ }
6
92
  // Cache
7
93
  let CONFIG_CACHED = null;
8
94
  export function getUniverseConfig(opts) {
@@ -0,0 +1,120 @@
1
+ import { Keyring } from "@polkadot/keyring";
2
+ import { u8aToHex, hexToU8a, isHex } from "@polkadot/util";
3
+ import { base64Decode, cryptoWaitReady } from "@polkadot/util-crypto";
4
+ import { privateKeyToAccount } from "viem/accounts";
5
+ import { Wallet } from "ethers";
6
+ import { decodePair } from "@polkadot/keyring/pair/decode";
7
+ function isSubstrateJson(obj) {
8
+ return !!obj?.encoded && !!obj?.encoding && !!obj?.encoding?.content;
9
+ }
10
+ function isWeb3V3Json(obj) {
11
+ return Number(obj?.version) === 3 && !!obj?.crypto;
12
+ }
13
+ function inferSubstrateKeyType(obj) {
14
+ const content = Array.isArray(obj.encoding.content) ? obj.encoding.content : [obj.encoding.content];
15
+ // Typical values: ["pkcs8","sr25519"] | ["pkcs8","ed25519"] | ["pkcs8","ecdsa"] | ["pkcs8","ethereum"]
16
+ if (content.includes("sr25519"))
17
+ return "sr25519";
18
+ if (content.includes("ed25519"))
19
+ return "ed25519";
20
+ if (content.includes("ecdsa"))
21
+ return "ecdsa";
22
+ if (content.includes("ethereum"))
23
+ return "ethereum";
24
+ // Default to sr25519 if not specified (common in older exports)
25
+ return "sr25519";
26
+ }
27
+ function decryptSubstrate(keystore, password = "") {
28
+ const encodedRaw = keystore.encoded;
29
+ const types = keystore.encoding.type;
30
+ const encodingTypes = Array.isArray(types) ? types : [types];
31
+ const encoded = isHex(encodedRaw) ? hexToU8a(encodedRaw) : base64Decode(encodedRaw);
32
+ const decoded = decodePair(password, encoded, encodingTypes /*eslint-disable-line @typescript-eslint/no-explicit-any*/);
33
+ return decoded.secretKey;
34
+ }
35
+ async function decryptWeb3V3(keystore, password = "") {
36
+ const w = await Wallet.fromEncryptedJson(JSON.stringify(keystore), password);
37
+ return hexToU8a(w.privateKey);
38
+ }
39
+ export class UnifiedKeystore {
40
+ _keystore;
41
+ _type;
42
+ _keyType;
43
+ _password;
44
+ _pair; // cached for all key types
45
+ _account; // cached for ethereum keys (viem)
46
+ _privateKey; // cached decrypted private key
47
+ constructor(type, keyType, keystore, password) {
48
+ this._keystore = keystore;
49
+ this._type = type;
50
+ this._keyType = keyType;
51
+ this._password = password;
52
+ }
53
+ static async fromJSON(keystore, password) {
54
+ await cryptoWaitReady();
55
+ const obj = typeof keystore === "string" ? JSON.parse(keystore) : keystore;
56
+ if (isSubstrateJson(obj)) {
57
+ const keyType = inferSubstrateKeyType(obj);
58
+ return new UnifiedKeystore("substrate", keyType, obj, password);
59
+ }
60
+ if (isWeb3V3Json(obj)) {
61
+ return new UnifiedKeystore("web3_v3", "ethereum", obj, password);
62
+ }
63
+ throw new Error("Unsupported keystore JSON: expected Substrate (pkcs8) or Web3 v3 keystore");
64
+ }
65
+ type() {
66
+ return this._type;
67
+ }
68
+ keyType() {
69
+ return this._keyType;
70
+ }
71
+ async address() {
72
+ return (await this.pair()).address;
73
+ }
74
+ async publicKey() {
75
+ return (await this.pair()).publicKey;
76
+ }
77
+ async privateKey() {
78
+ if (this._privateKey)
79
+ return this._privateKey;
80
+ if (this._type === "substrate") {
81
+ this._privateKey = decryptSubstrate(this._keystore, this._password ?? "");
82
+ }
83
+ else {
84
+ this._privateKey = await decryptWeb3V3(this._keystore, this._password ?? "");
85
+ }
86
+ return this._privateKey;
87
+ }
88
+ async pair() {
89
+ if (this._pair)
90
+ return this._pair;
91
+ const keyring = new Keyring({ type: this._keyType });
92
+ if (this._type === "substrate") {
93
+ const pair = keyring.addFromJson(this._keystore);
94
+ if (this._password !== undefined) {
95
+ try {
96
+ pair.unlock(this._password);
97
+ }
98
+ catch {
99
+ // If password is wrong/empty, leave it locked; address/publicKey still work.
100
+ }
101
+ }
102
+ this._pair = pair;
103
+ }
104
+ else {
105
+ const sk = await this.privateKey();
106
+ this._pair = keyring.addFromUri(u8aToHex(sk));
107
+ }
108
+ return this._pair;
109
+ }
110
+ async account() {
111
+ if (this._keyType !== "ethereum") {
112
+ throw new Error("accounts() is only available for ethereum keys");
113
+ }
114
+ if (this._account)
115
+ return this._account;
116
+ const sk = await this.privateKey();
117
+ this._account = privateKeyToAccount(u8aToHex(sk));
118
+ return this._account;
119
+ }
120
+ }
package/dist/matter.js CHANGED
@@ -3,51 +3,10 @@ import { ApiPromise, WsProvider } from "@polkadot/api";
3
3
  import "@polkadot/api-augment/substrate";
4
4
  import * as fs from "fs";
5
5
  import * as path from "path";
6
- import { getUniverseConfig } from "./config.js";
7
- import { getSubstrateAccountPair } from "./utils.js";
8
- import { decodeAddress } from "@polkadot/util-crypto";
9
- import { u8aFixLength } from "@polkadot/util";
10
- function createDeferred() {
11
- let resolve;
12
- let reject;
13
- const promise = new Promise((res, rej) => {
14
- resolve = res;
15
- reject = rej;
16
- });
17
- return { promise, resolve, reject };
18
- }
19
- async function submitTransaction(api, tx, pair) {
20
- // const pTxn = Promise.withResolvers<Transaction>();
21
- // const pReceipt = Promise.withResolvers<Receipt>();
22
- const pTxn = createDeferred();
23
- const pReceipt = createDeferred();
24
- const accountId = u8aFixLength(decodeAddress(pair.address), 256);
25
- const nonce = await api.rpc.system.accountNextIndex(accountId);
26
- const unsub = await tx.signAndSend(pair, { nonce }, ({ events = [], status, txHash, txIndex, blockNumber }) => {
27
- if (status.isReady) {
28
- pTxn.resolve({ txHash: txHash.toHex(), receipt: pReceipt.promise });
29
- }
30
- else if (status.isFinalized) {
31
- pReceipt.resolve({
32
- txHash: txHash.toHex(),
33
- blockHash: status.asFinalized.toHex(),
34
- txIndex,
35
- blockNumber,
36
- events: events,
37
- });
38
- unsub();
39
- }
40
- });
41
- return await pTxn.promise;
42
- }
43
- function findEvent(events, name) {
44
- for (const record of events) {
45
- if (record.event && record.event.method === name) {
46
- return record.event;
47
- }
48
- }
49
- return null;
50
- }
6
+ import { getObserverConfig, keystoreFromOptions } from "./utils.js";
7
+ import "./options.js";
8
+ import { findEvent, submitTransaction } from "./substrate.js";
9
+ import JSON5 from "json5";
51
10
  function guessContentType(filePath) {
52
11
  const ext = path.extname(filePath).toLowerCase();
53
12
  switch (ext) {
@@ -67,61 +26,43 @@ function guessContentType(filePath) {
67
26
  }
68
27
  }
69
28
  export function genMatterCommand() {
70
- const cmd = new Command().name("matter").description("Manage matters");
29
+ const cmd = new Command().name("matter").description("manage matters");
71
30
  cmd
72
31
  .command("register")
73
32
  .description("Register matter on the Substrate chain")
74
33
  .argument("<files...>", "Path to the file(s) containing the matter content")
75
34
  .option("-c, --content-type <type>", "Default content type")
76
35
  .option("-h, --hasher <number>", "Default hasher", "1")
77
- .option("-u, --universe <universe>", "Universe name", "local")
78
- .option("-a, --account <account>", "Name of the keystore to sign the transaction")
79
- .option("-p, --password [password]", "Password to decrypt the keystore")
80
- .option("--password-file <file>", "File containing the password to decrypt the keystore")
36
+ .option("-u, --universe <name>", "Universe name")
37
+ .option("-o, --observer <name>", "Observer name")
38
+ .accountOptions()
81
39
  .action(async (files, options) => {
82
40
  const materials = [];
83
41
  // Process each file argument
84
42
  for (const file of files) {
85
- let [filePath, hasher_, contentType] = file.split(":");
43
+ const [filePath, hasher_, contentType_] = file.split(":");
86
44
  const hasher = hasher_ ? Number(hasher_) : Number(options.hasher) || 1;
87
- if (!contentType) {
88
- if (options.contentType) {
89
- contentType = options.contentType;
90
- }
91
- else {
92
- contentType = guessContentType(filePath);
93
- }
94
- }
45
+ const contentType = contentType_ || options.contentType || guessContentType(filePath);
95
46
  materials.push({ filePath, hasher, contentType });
96
47
  }
97
- // Get universe configuration
98
- const conf = getUniverseConfig(options);
99
- if (!conf.observer.rpc) {
100
- throw new Error("pre_rpc_url not configured in universe");
101
- }
102
- // Get account pair for signing
103
- if (!options.account) {
104
- throw new Error("Account must be specified with --account");
105
- }
106
- // const keystorePath = resolveKeystoreFile(options.account, options);
107
- // const keystore = loadKeystore(keystorePath);
108
- // const password = getPassword(options);
109
- const accountPair = getSubstrateAccountPair(options);
48
+ const conf = getObserverConfig(options);
49
+ const keystore = await keystoreFromOptions(options);
50
+ const pair = await keystore.pair();
110
51
  // Connect to the Substrate node
111
- console.log(`Connecting to ${conf.observer.rpc}...`);
112
- const provider = new WsProvider(conf.observer.rpc);
52
+ // console.log(`Connecting to ${conf.rpc}...`);
53
+ const provider = new WsProvider(conf.rpc);
113
54
  const api = await ApiPromise.create({ provider });
114
55
  await api.isReady;
115
- console.log("Connected to Substrate node");
56
+ // console.log("Connected to Substrate node");
116
57
  const txns = [];
117
58
  // Submit transactions for each material
118
59
  for (const { filePath, hasher, contentType } of materials) {
119
60
  console.log(`Processing ${filePath}: content-type=${contentType}, hasher=${hasher}`);
120
61
  const content = fs.readFileSync(filePath);
121
62
  const contentRaw = api.createType("Raw", content, content.length);
122
- const call = api.tx.matter.register(hasher, contentType, contentRaw);
63
+ const call = api.tx.every.matterRegister(hasher, contentType, contentRaw);
123
64
  console.log(`Submitting transaction for ${filePath}...`);
124
- const txn = await submitTransaction(api, call, accountPair);
65
+ const txn = await submitTransaction(api, call, pair);
125
66
  console.log(`Transaction submitted: ${txn.txHash}`);
126
67
  txns.push({ txn, filePath });
127
68
  }
@@ -134,15 +75,18 @@ export function genMatterCommand() {
134
75
  const hash = event.data[0].toString();
135
76
  console.log(`${filePath} finalized in block ${receipt.blockHash}`);
136
77
  console.log(` Matter hash: ${hash}`);
137
- if (conf.observer.gateway) {
138
- console.log(` Preimage: ${conf.observer.gateway}/m/${hash}`);
78
+ if (conf.gateway) {
79
+ console.log(` Preimage: ${conf.gateway}/m/${hash}`);
139
80
  }
140
- if (conf.observer.explorer) {
141
- console.log(` Transaction: ${conf.observer.explorer}/extrinsic/${receipt.blockNumber}-${receipt.txIndex}`);
81
+ if (conf.explorer) {
82
+ // console.log(` Transaction: ${conf.explorer}/extrinsic/${receipt.blockNumber}-${receipt.txIndex}`);
142
83
  }
143
84
  }
144
85
  else {
145
86
  console.log(`${filePath} finalized, but no MaterialAdded event found`);
87
+ for (const { event } of receipt.events) {
88
+ console.log(`${event.method.padEnd(20)}`, JSON5.stringify(event.data.toHuman()));
89
+ }
146
90
  }
147
91
  }
148
92
  await api.disconnect();
package/dist/mint.js CHANGED
@@ -7,13 +7,14 @@ import { abi } from "./abi.js";
7
7
  export function genMintCommand() {
8
8
  const cmd = new Command()
9
9
  .name("mint")
10
- .description("Mint an object via ObjectMinter")
11
- .option("--auth <data>", "authorization data, if needed for a permissioned mint", "0x")
12
- .option("--policy <index>", "the index number of the mint policy", "0")
10
+ .description("Mint an object via the object minter or directly from the set")
11
+ .option("--to <address>", "specify the recipient")
13
12
  .option("--value <amount>", "the amount of ETH to send together", "0")
13
+ .option("--auth <data>", "authorization data for a permissioned mint", "0x")
14
+ .option("--policy <index>", "the index number of the mint policy", "0")
15
+ .option("--no-minter", "mint directly from set contract instead of using ObjectMinter")
14
16
  .argument("<sid>", "scoped object ID, in form of set.id (e.g., 17.1)")
15
- .argument("<to>", "address of the recipient")
16
- .argument("[data]", "additional mint data", "0x")
17
+ .argument("[data]", "additional input data", "0x")
17
18
  .action(action);
18
19
  defaultWriteFunctionOptions().forEach((option) => cmd.addOption(option));
19
20
  return cmd;
@@ -22,7 +23,6 @@ async function action() {
22
23
  const opts = this.opts();
23
24
  const args0 = this.args;
24
25
  const conf = getUniverseConfig(opts);
25
- const objectMinter = conf.contracts["ObjectMinter"];
26
26
  const setRegistry = conf.contracts["SetRegistry"];
27
27
  const { publicClient, walletClient } = await getClientsEth(conf, opts);
28
28
  const account = walletClient.account;
@@ -34,28 +34,42 @@ async function action() {
34
34
  args: [BigInt(set)],
35
35
  }));
36
36
  const value = parseUnits(opts.value || "0", 18);
37
- const { request } = await publicClient.simulateContract({
38
- address: objectMinter,
39
- abi: abi.mint,
40
- functionName: "mint",
41
- args: [
42
- args0[1],
43
- setContract,
44
- BigInt(id),
45
- (args0[2] || "0x"),
46
- opts.auth || "0x",
47
- Number(opts.policy || "0"),
48
- ],
49
- account,
50
- value,
51
- });
52
- const hash = await walletClient.writeContract(request);
37
+ // Use the provided recipient address or default to the sender's address
38
+ const recipientAddress = (opts.to || account.address);
39
+ const mintData = (args0[1] || "0x");
40
+ let hash;
41
+ if (opts.minter) {
42
+ // Mint via ObjectMinter
43
+ const objectMinter = conf.contracts["ObjectMinter"];
44
+ const { request } = await publicClient.simulateContract({
45
+ address: objectMinter,
46
+ abi: abi.mint,
47
+ functionName: "mint",
48
+ args: [recipientAddress, setContract, BigInt(id), mintData, opts.auth || "0x", Number(opts.policy || "0")],
49
+ account,
50
+ value,
51
+ });
52
+ hash = await walletClient.writeContract(request);
53
+ }
54
+ else {
55
+ // Mint directly from set contract
56
+ const { request } = await publicClient.simulateContract({
57
+ address: setContract,
58
+ abi: abi.create,
59
+ functionName: "create",
60
+ args: [recipientAddress, BigInt(id), mintData],
61
+ account,
62
+ value,
63
+ });
64
+ hash = await walletClient.writeContract(request);
65
+ }
53
66
  console.log(`Transaction sent: ${hash}`);
54
67
  console.log("Transaction mining...");
55
68
  const receipt = await publicClient.waitForTransactionReceipt({ hash });
56
69
  console.log("Transaction mined");
57
70
  if (receipt.logs && receipt.logs.length > 0) {
58
- const parsedLogs = parseEventLogs({ abi: abi.mint, logs: receipt.logs });
71
+ const abiToUse = opts.minter ? abi.mint : abi.create;
72
+ const parsedLogs = parseEventLogs({ abi: abiToUse, logs: receipt.logs });
59
73
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
60
74
  parsedLogs.forEach((log) => {
61
75
  console.log(" - Event", log.eventName, stringify(log.args));
@@ -0,0 +1,26 @@
1
+ import { Command, Option } from "commander";
2
+ export const optRpcUrl = new Option("--rpc-url <url>", "RPC endpoint URL");
3
+ export const optChainId = new Option("--chain-id <id>", "Chain ID").argParser(Number);
4
+ export const optPkey = new Option("--private-key <hex>", "Sender private key");
5
+ export const optFrom = new Option("--from <address>", "Sender address");
6
+ export const optDerivePath = new Option("--path <hd>", "Derivation path (HD)");
7
+ export const optVerbose = new Option("-v, --verbose", "Enable verbose logging");
8
+ export const optSilent = new Option("--silent", "Suppress output");
9
+ export const optAccount = new Option("-a, --account <account>", "Name of the keystore");
10
+ export const optPassword = new Option("-p, --password [password]", "Password to decrypt the keystore");
11
+ export const optPasswordFile = new Option("--password-file <file>", "File containing the keystore password");
12
+ export const optFoundry = new Option("-f, --foundry", "use foundry keystores (~/.foundry/keystores)");
13
+ export const accountOptions = [optAccount, optPassword, optPasswordFile, optFoundry];
14
+ Command.prototype.useOptions = function (options) {
15
+ options.forEach((o) => this.addOption(o));
16
+ return this;
17
+ };
18
+ // (Command.prototype as unknown as Command).networkOptions = function () {
19
+ // return (this as Command).useOptions(networkGroup);
20
+ // };
21
+ Command.prototype.accountOptions = function () {
22
+ return this.useOptions(accountOptions);
23
+ };
24
+ // (Command.prototype as unknown as Command).commonOptions = function () {
25
+ // return (this as Command).useOptions(commonGroup);
26
+ // };
package/dist/program.js CHANGED
@@ -2,7 +2,7 @@ import { Command } from "commander";
2
2
  import { generateCommands } from "./cmdgen.js";
3
3
  import { RenamingCommand } from "./cmds.js";
4
4
  import { version } from "./utils.js";
5
- import { genWalletCommands } from "./wallet.js";
5
+ import { walletCmd } from "./wallet.js";
6
6
  import { genMatterCommand } from "./matter.js";
7
7
  function buildProgram() {
8
8
  const subCmds = generateCommands();
@@ -19,7 +19,7 @@ function buildProgram() {
19
19
  .description("create and interact with objects")
20
20
  .addCommands(subCmds.object);
21
21
  const mintPolicyCmd = new RenamingCommand()
22
- .name("mintpolicy")
22
+ .name("minter")
23
23
  .description("manage mint policies")
24
24
  .addCommands(subCmds.mintpolicy);
25
25
  const program = new Command()
@@ -27,15 +27,15 @@ function buildProgram() {
27
27
  .description("CLI for interacting with Every Protocol")
28
28
  .version(version())
29
29
  .showHelpAfterError(true);
30
- program.addCommand(kindCmd);
30
+ program.addCommand(genMatterCommand());
31
31
  program.addCommand(setCmd);
32
+ program.addCommand(kindCmd);
32
33
  program.addCommand(relationCmd);
33
- program.addCommand(uniqueCmd);
34
34
  program.addCommand(valueCmd);
35
+ program.addCommand(uniqueCmd);
35
36
  program.addCommand(objectCmd);
36
37
  program.addCommand(mintPolicyCmd);
37
- program.addCommand(genWalletCommands());
38
- program.addCommand(genMatterCommand());
38
+ program.addCommand(walletCmd);
39
39
  return program;
40
40
  }
41
41
  export const program = buildProgram();
@@ -0,0 +1,57 @@
1
+ import "@polkadot/api-augment/substrate";
2
+ import { decodeAddress } from "@polkadot/util-crypto";
3
+ import { u8aFixLength } from "@polkadot/util";
4
+ import "./options.js";
5
+ function createDeferred() {
6
+ let resolve;
7
+ let reject;
8
+ const promise = new Promise((res, rej) => {
9
+ resolve = res;
10
+ reject = rej;
11
+ });
12
+ return { promise, resolve, reject };
13
+ }
14
+ export async function submitTransaction(api, tx, pair) {
15
+ // const pTxn = Promise.withResolvers<Transaction>();
16
+ // const pReceipt = Promise.withResolvers<Receipt>();
17
+ const pTxn = createDeferred();
18
+ const pReceipt = createDeferred();
19
+ const accountId = u8aFixLength(decodeAddress(pair.address), 256);
20
+ const nonce = await api.rpc.system.accountNextIndex(accountId);
21
+ const unsub = await tx.signAndSend(pair, { nonce }, (result) => {
22
+ const { status, txHash, events, dispatchError } = result;
23
+ if (dispatchError) {
24
+ if (dispatchError.isModule) {
25
+ const meta = api.registry.findMetaError(dispatchError.asModule);
26
+ const msg = `${meta.section}.${meta.name}${meta.docs.length ? `: ${meta.docs.join(" ")}` : ""}`;
27
+ unsub();
28
+ pReceipt.reject(new Error(`DispatchError: ${msg}`));
29
+ }
30
+ else {
31
+ unsub();
32
+ pReceipt.reject(new Error(dispatchError.toString()));
33
+ }
34
+ }
35
+ if (status.isReady) {
36
+ pTxn.resolve({ txHash: txHash.toHex(), receipt: pReceipt.promise });
37
+ }
38
+ if (status.isFinalized) {
39
+ unsub();
40
+ pReceipt.resolve({
41
+ txHash: txHash.toHex(),
42
+ blockHash: status.asFinalized.toHex(),
43
+ events: events,
44
+ result,
45
+ });
46
+ }
47
+ });
48
+ return await pTxn.promise;
49
+ }
50
+ export function findEvent(events, name) {
51
+ for (const record of events) {
52
+ if (record.event && record.event.method === name) {
53
+ return record.event;
54
+ }
55
+ }
56
+ return undefined;
57
+ }
package/dist/utils.js CHANGED
@@ -11,7 +11,9 @@ import { fileURLToPath } from "url";
11
11
  import { isHex, hexToU8a } from "@polkadot/util";
12
12
  import { base64Decode } from "@polkadot/util-crypto/base64";
13
13
  import { decodePair } from "@polkadot/keyring/pair/decode";
14
+ import { loadMergedConfig } from "./config.js";
14
15
  import Keyring from "@polkadot/keyring";
16
+ import { UnifiedKeystore } from "./keystore.js";
15
17
  export const __dirname = path.dirname(fileURLToPath(import.meta.url));
16
18
  export function version() {
17
19
  const pkgPath = path.resolve(__dirname, "../package.json");
@@ -179,3 +181,42 @@ export function getSubstrateAccountPair(flags) {
179
181
  }
180
182
  return pair;
181
183
  }
184
+ export async function keystoreFromOptions(options) {
185
+ if (!options.account) {
186
+ throw new Error("Account must be specified with --account");
187
+ }
188
+ return keystoreFromAccount(options.account, options);
189
+ }
190
+ export async function keystoreFromAccount(account, options) {
191
+ const file = resolveKeystoreFile(account, options);
192
+ const keyData = loadKeystore(file);
193
+ const password = getPassword(options);
194
+ const keystore = await UnifiedKeystore.fromJSON(keyData, password);
195
+ return keystore;
196
+ }
197
+ export function getObserverConfig(options) {
198
+ const conf = loadMergedConfig();
199
+ let observerName;
200
+ const DEFAULT_OBSERVER = "localnet";
201
+ if (options.observer) {
202
+ observerName = options.observer;
203
+ }
204
+ else if (options.universe) {
205
+ const universe = conf.universes[options.universe];
206
+ if (!universe) {
207
+ throw new Error(`Universe '${options.universe}' not found in config. Available: ${Object.keys(conf.universes).join(", ")}`);
208
+ }
209
+ observerName = universe.observer;
210
+ }
211
+ else {
212
+ observerName = DEFAULT_OBSERVER;
213
+ }
214
+ if (!observerName) {
215
+ throw new Error(`No observer resolved from options or config.`);
216
+ }
217
+ const observer = conf.observers[observerName];
218
+ if (!observer) {
219
+ throw new Error(`Observer '${observerName}' not found in config. Available: ${Object.keys(conf.observers).join(", ")}`);
220
+ }
221
+ return observer;
222
+ }