@everyprotocol/every-cli 0.1.2 → 0.1.4
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/.every.toml +8 -10
- package/abis/ElementRegistry.json +1 -1
- package/abis/IObjectMinter.json +1 -1
- package/abis/IObjectMinterAdmin.json +1 -1
- package/abis/IOmniRegistry.json +1 -1
- package/abis/ISet.json +1 -1
- package/abis/ISetRegistry.json +1 -1
- package/abis/ISetRegistryAdmin.json +1 -1
- package/abis/KindRegistry.json +1 -1
- package/abis/ObjectMinter.json +1 -1
- package/abis/OmniRegistry.json +1 -1
- package/abis/SetRegistry.json +1 -1
- package/dist/abi.js +6 -0
- package/dist/cmdgen.js +51 -139
- package/dist/cmds/balance.js +43 -0
- package/dist/cmds/config.js +46 -0
- package/dist/cmds/kind.js +14 -0
- package/dist/cmds/matter.js +82 -0
- package/dist/cmds/minter.js +31 -0
- package/dist/cmds/object.js +175 -0
- package/dist/cmds/relation.js +16 -0
- package/dist/cmds/set.js +31 -0
- package/dist/cmds/unique.js +14 -0
- package/dist/cmds/universe.js +21 -0
- package/dist/cmds/value.js +14 -0
- package/dist/cmds/wallet.js +90 -0
- package/dist/commander-patch.js +64 -0
- package/dist/config.js +62 -51
- package/dist/ethereum.js +33 -0
- package/dist/from-opts.js +161 -0
- package/dist/index.js +2 -1
- package/dist/keystore.js +120 -0
- package/dist/logger.js +39 -0
- package/dist/parsers.js +59 -0
- package/dist/program.js +28 -39
- package/dist/substrate.js +63 -0
- package/dist/utils.js +150 -147
- package/package.json +4 -1
- package/dist/cmds.js +0 -132
- package/dist/matter.js +0 -152
- package/dist/mint.js +0 -64
- package/dist/relate.js +0 -104
- package/dist/wallet.js +0 -108
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { Command } from "commander";
|
|
2
|
+
import { abi } from "../abi.js";
|
|
3
|
+
import { getCommandGen, makeFuncName } from "../cmdgen.js";
|
|
4
|
+
const cmdGenConfig = {
|
|
5
|
+
getFuncName: (cmdName) => makeFuncName(cmdName, `unique`),
|
|
6
|
+
getAbiFuncs: (funcName) => abi.funcs.elemRegistry.filter((i) => i.name == funcName),
|
|
7
|
+
// eslint-disable-next-line
|
|
8
|
+
getAbiNonFuncs: (funcName) => abi.nonFuncs.elemRegistry,
|
|
9
|
+
// eslint-disable-next-line
|
|
10
|
+
getContract: (conf, args, abiFunc) => conf.contracts.ElementRegistry,
|
|
11
|
+
};
|
|
12
|
+
const cmdGen = getCommandGen(cmdGenConfig);
|
|
13
|
+
const subCmds = "register,upgrade,touch,transfer,owner,descriptor,snapshot".split(",");
|
|
14
|
+
export const uniqueCmd = new Command("unique").description("manage uniques").addCommands(subCmds.map(cmdGen));
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { Command } from "commander";
|
|
2
|
+
import "@polkadot/api-augment/substrate";
|
|
3
|
+
import { submitSubTxUI } from "../substrate.js";
|
|
4
|
+
import { network } from "../commander-patch.js";
|
|
5
|
+
import { parseAccountId, parseBigInt } from "../parsers.js";
|
|
6
|
+
import { Logger } from "../logger.js";
|
|
7
|
+
const universeStartCmd = new Command("start")
|
|
8
|
+
.description("Start a universe")
|
|
9
|
+
.argument("<universe>", "Universe ID", parseBigInt)
|
|
10
|
+
.argument("<horizon>", "Block number", parseBigInt)
|
|
11
|
+
.argument("<herald>", "Herald address (SS58 or 0x hex)", parseAccountId)
|
|
12
|
+
.addOption(network)
|
|
13
|
+
.addKeystoreOptions()
|
|
14
|
+
.addOutputOptions()
|
|
15
|
+
.subWriteAction(async function (api, pair, universe, horizon, herald) {
|
|
16
|
+
const call = api.tx.every.canonicalStart(universe, horizon, herald);
|
|
17
|
+
const tx = api.tx.sudo.sudo(call);
|
|
18
|
+
const console = new Logger(this.opts());
|
|
19
|
+
await submitSubTxUI(api, tx, pair, console);
|
|
20
|
+
});
|
|
21
|
+
export const universeCmd = new Command("universe").description("manage universes").addCommand(universeStartCmd);
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { Command } from "commander";
|
|
2
|
+
import { abi } from "../abi.js";
|
|
3
|
+
import { getCommandGen, makeFuncName } from "../cmdgen.js";
|
|
4
|
+
const cmdGenConfig = {
|
|
5
|
+
getFuncName: (cmdName) => makeFuncName(cmdName, `value`),
|
|
6
|
+
getAbiFuncs: (funcName) => abi.funcs.elemRegistry.filter((i) => i.name == funcName),
|
|
7
|
+
// eslint-disable-next-line
|
|
8
|
+
getAbiNonFuncs: (funcName) => abi.nonFuncs.elemRegistry,
|
|
9
|
+
// eslint-disable-next-line
|
|
10
|
+
getContract: (conf, args, abiFunc) => conf.contracts.ElementRegistry,
|
|
11
|
+
};
|
|
12
|
+
const cmdGen = getCommandGen(cmdGenConfig);
|
|
13
|
+
const subCmds = "register,upgrade,touch,transfer,owner,descriptor,snapshot".split(",");
|
|
14
|
+
export const valueCmd = new Command("value").description("manage values").addCommands(subCmds.map(cmdGen));
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { Command } from "commander";
|
|
2
|
+
import { Keyring } from "@polkadot/keyring";
|
|
3
|
+
import { mnemonicGenerate, cryptoWaitReady } from "@polkadot/util-crypto";
|
|
4
|
+
import { bytesToHex } from "viem";
|
|
5
|
+
import * as fs from "fs";
|
|
6
|
+
import { FromOpts } from "../from-opts.js";
|
|
7
|
+
import { saveJson } from "../utils.js";
|
|
8
|
+
const walletListCmd = new Command()
|
|
9
|
+
.name("list")
|
|
10
|
+
.description("List all wallets")
|
|
11
|
+
.option("-f, --foundry", "use foundry keystore directory (~/.foundry/keystores)")
|
|
12
|
+
.option("--dir <dir>", "specify a custom keystore directory")
|
|
13
|
+
.action(async (options) => {
|
|
14
|
+
const dir = FromOpts.getKeystoreDir(options);
|
|
15
|
+
const files = fs.readdirSync(dir);
|
|
16
|
+
files.forEach((file) => console.log(file));
|
|
17
|
+
});
|
|
18
|
+
const walletNewCmd = new Command()
|
|
19
|
+
.name("new")
|
|
20
|
+
.description("Generate a new wallet")
|
|
21
|
+
.option("-t, --type <type>", "key type (sr25519, ed25519, ethereum)", "sr25519")
|
|
22
|
+
.option("-p, --password <password>", "password to encrypt the keystore")
|
|
23
|
+
.option("-P, --password-file <file>", "password file")
|
|
24
|
+
.option("--dir <dir>", "specify keystore directory")
|
|
25
|
+
.argument("<name>", "name of the wallet")
|
|
26
|
+
.action(async (name, options) => {
|
|
27
|
+
const password = FromOpts.confirmPassword(options);
|
|
28
|
+
await cryptoWaitReady();
|
|
29
|
+
const keyring = new Keyring();
|
|
30
|
+
const mnemonic = mnemonicGenerate();
|
|
31
|
+
const pair = keyring.addFromUri(mnemonic, { name }, options.type);
|
|
32
|
+
const json = pair.toJson(password);
|
|
33
|
+
const dir = FromOpts.getKeystoreDir(options);
|
|
34
|
+
saveJson(json, dir, name);
|
|
35
|
+
});
|
|
36
|
+
const walletImportCmd = new Command()
|
|
37
|
+
.name("import")
|
|
38
|
+
.description("Import a wallet from a secrete URI")
|
|
39
|
+
.option("-t, --type <type>", "key type (sr25519, ed25519, ethereum)", "sr25519")
|
|
40
|
+
.option("-p, --password <password>", "password to encrypt the keystore")
|
|
41
|
+
.option("-P, --password-file <file>", "password file")
|
|
42
|
+
.option("--dir <dir>", "specify a custom keystore directory")
|
|
43
|
+
.option("-f, --foundry", "use foundry keystore directory (~/.foundry/keystores)")
|
|
44
|
+
.argument("<name>", "name of the wallet")
|
|
45
|
+
.argument("<suri>", "secret URI")
|
|
46
|
+
.action(async (name, suri, options) => {
|
|
47
|
+
const password = FromOpts.confirmPassword(options);
|
|
48
|
+
await cryptoWaitReady();
|
|
49
|
+
const keyring = new Keyring({ type: options.type });
|
|
50
|
+
const pair = keyring.addFromUri(suri);
|
|
51
|
+
const json = pair.toJson(password);
|
|
52
|
+
const dir = FromOpts.getKeystoreDir(options);
|
|
53
|
+
saveJson(json, dir, name);
|
|
54
|
+
});
|
|
55
|
+
const walletInspectCmd = new Command()
|
|
56
|
+
.name("inspect")
|
|
57
|
+
.description("Inspect a wallet")
|
|
58
|
+
.option("-t, --type <type>", "key type (sr25519, ed25519, ethereum)", "sr25519")
|
|
59
|
+
.option("-p, --password <password>", "password to decrypt the keystore")
|
|
60
|
+
.option("-P, --password-file <file>", "file containing the password")
|
|
61
|
+
.option("-x, --decrypt", "also decrypt the private key", false)
|
|
62
|
+
.option("--dir <dir>", "specify a custom keystore directory")
|
|
63
|
+
.option("-f, --foundry", "use foundry keystore directory (~/.foundry/keystores)")
|
|
64
|
+
.argument("<name>", "name of the wallet")
|
|
65
|
+
.action(async (name, options) => {
|
|
66
|
+
const keystore = await FromOpts.getKeystore(options, name);
|
|
67
|
+
const decoded = options.decrypt ? await keystore.privateKey() : undefined;
|
|
68
|
+
let dir = "~/.every/keystores";
|
|
69
|
+
if (options.foundry) {
|
|
70
|
+
dir = "~/.foundry/keystores";
|
|
71
|
+
}
|
|
72
|
+
else if (options.dir) {
|
|
73
|
+
dir = options.dir;
|
|
74
|
+
}
|
|
75
|
+
console.log(` Keystore: ${dir}/${name}`);
|
|
76
|
+
console.log(` Store Type: ${keystore.type()}`);
|
|
77
|
+
console.log(` Key Type: ${keystore.keyType()}`);
|
|
78
|
+
console.log(` Address: ${await keystore.address()}`);
|
|
79
|
+
console.log(` Public Key: ${bytesToHex(await keystore.publicKey())}`);
|
|
80
|
+
if (decoded) {
|
|
81
|
+
console.log(`Private Key: ${bytesToHex(decoded)}`);
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
export const walletCmd = new Command()
|
|
85
|
+
.name("wallet")
|
|
86
|
+
.description("manage wallets")
|
|
87
|
+
.addCommand(walletListCmd)
|
|
88
|
+
.addCommand(walletNewCmd)
|
|
89
|
+
.addCommand(walletImportCmd)
|
|
90
|
+
.addCommand(walletInspectCmd);
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { Command, Option } from "commander";
|
|
2
|
+
import { FromOpts } from "./from-opts.js";
|
|
3
|
+
export const account = new Option("-a, --account <account>", "Name of the keystore");
|
|
4
|
+
export const password = new Option("-p, --password [password]", "Password to decrypt the keystore");
|
|
5
|
+
export const passwordFile = new Option("-P, --password-file <file>", "File containing the keystore password");
|
|
6
|
+
export const privateKey = new Option("-k, --private-key <key>", "Private key to sign the transaction");
|
|
7
|
+
export const foundry = new Option("-f, --foundry", "Use foundry keystores (~/.foundry/keystores)");
|
|
8
|
+
export const universe = new Option("-u, --universe <universe>", "Universe name").default("anvil");
|
|
9
|
+
export const network = new Option("-n, --network <network>", "Network name").default("dev");
|
|
10
|
+
export const json = new Option("-j, --json [file]", "Output result as JSON to stdout or file, implies --quiet");
|
|
11
|
+
export const quiet = new Option("-q, --quiet", "Suppress info messages");
|
|
12
|
+
export const noQuiet = new Option("--no-quiet", "Force info messages even when --json is set");
|
|
13
|
+
export const keystoreOptions = [account, password, passwordFile, foundry];
|
|
14
|
+
export const outputOptions = [json, quiet, noQuiet];
|
|
15
|
+
export const writeOptions = [universe, account, password, passwordFile, foundry];
|
|
16
|
+
Command.prototype.addCommands = function (commands) {
|
|
17
|
+
commands.forEach((cmd) => this.addCommand(cmd));
|
|
18
|
+
return this;
|
|
19
|
+
};
|
|
20
|
+
Command.prototype.addArguments = function (arg) {
|
|
21
|
+
arg.forEach((arg) => this.addArgument(arg));
|
|
22
|
+
return this;
|
|
23
|
+
};
|
|
24
|
+
Command.prototype.addOptions = function (options) {
|
|
25
|
+
options.forEach((opt) => this.addOption(opt));
|
|
26
|
+
return this;
|
|
27
|
+
};
|
|
28
|
+
Command.prototype.addKeystoreOptions = function () {
|
|
29
|
+
return this.addOptions([account, password, passwordFile, foundry]);
|
|
30
|
+
};
|
|
31
|
+
Command.prototype.addOutputOptions = function () {
|
|
32
|
+
return this.addOptions([json, quiet, noQuiet]);
|
|
33
|
+
};
|
|
34
|
+
Command.prototype.addWriteOptions = function () {
|
|
35
|
+
return this.addKeystoreOptions().addOption(universe);
|
|
36
|
+
};
|
|
37
|
+
Command.prototype.subReadAction = function (fn) {
|
|
38
|
+
// eslint-disable-next-line
|
|
39
|
+
return this.action(async function (...args) {
|
|
40
|
+
const api = await FromOpts.getSubstrateApi(this.opts());
|
|
41
|
+
try {
|
|
42
|
+
return await fn.call(this, api, ...args);
|
|
43
|
+
}
|
|
44
|
+
finally {
|
|
45
|
+
await api.disconnect().catch(() => { });
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
};
|
|
49
|
+
Command.prototype.subWriteAction = function (fn) {
|
|
50
|
+
// eslint-disable-next-line
|
|
51
|
+
async function _action(...args) {
|
|
52
|
+
const opts = this.opts();
|
|
53
|
+
const api = await FromOpts.getSubstrateApi(opts);
|
|
54
|
+
try {
|
|
55
|
+
const keystore = await FromOpts.getKeystore(opts);
|
|
56
|
+
const pair = await keystore.pair();
|
|
57
|
+
return await fn.call(this, api, pair, ...args);
|
|
58
|
+
}
|
|
59
|
+
finally {
|
|
60
|
+
await api.disconnect().catch(() => { });
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return this.action(_action);
|
|
64
|
+
};
|
package/dist/config.js
CHANGED
|
@@ -1,61 +1,72 @@
|
|
|
1
1
|
import fs from "fs";
|
|
2
2
|
import path from "path";
|
|
3
3
|
import os from "os";
|
|
4
|
-
import
|
|
4
|
+
import * as TOML from "@iarna/toml";
|
|
5
|
+
import { z } from "zod";
|
|
5
6
|
import { __dirname } from "./utils.js";
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
7
|
+
export const ContractsSchema = z.object({
|
|
8
|
+
SetRegistry: z.string().regex(/^0x[0-9a-fA-F]{40}$/, "Must be an Ethereum address"),
|
|
9
|
+
OmniRegistry: z.string().regex(/^0x[0-9a-fA-F]{40}$/),
|
|
10
|
+
KindRegistry: z.string().regex(/^0x[0-9a-fA-F]{40}$/),
|
|
11
|
+
ElementRegistry: z.string().regex(/^0x[0-9a-fA-F]{40}$/),
|
|
12
|
+
ObjectMinter: z.string().regex(/^0x[0-9a-fA-F]{40}$/),
|
|
13
|
+
});
|
|
14
|
+
export const UniverseSchema = z.object({
|
|
15
|
+
id: z.number().int().nonnegative(),
|
|
16
|
+
rpc: z.string().url(),
|
|
17
|
+
explorer: z.string().url(),
|
|
18
|
+
observer: z.string(), // reference to an Observer key
|
|
19
|
+
contracts: ContractsSchema,
|
|
20
|
+
});
|
|
21
|
+
export const ObserverSchema = z.object({
|
|
22
|
+
rpc: z.string().url(),
|
|
23
|
+
explorer: z.string().url(),
|
|
24
|
+
gateway: z.string().url(),
|
|
25
|
+
});
|
|
26
|
+
export const ConfigSchema = z.object({
|
|
27
|
+
universes: z.record(UniverseSchema),
|
|
28
|
+
observers: z.record(ObserverSchema),
|
|
29
|
+
});
|
|
30
|
+
export function loadConfig(file) {
|
|
31
|
+
const text = fs.readFileSync(file, "utf8");
|
|
32
|
+
const raw = TOML.parse(text);
|
|
33
|
+
return ConfigSchema.parse(raw);
|
|
34
|
+
}
|
|
35
|
+
export function loadMergedConfig() {
|
|
36
|
+
const [config] = _loadMergedConfig();
|
|
37
|
+
return config;
|
|
17
38
|
}
|
|
18
|
-
function
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
]
|
|
26
|
-
const
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
// console.log(name, uni);
|
|
40
|
-
mergedConfig.universes[name] = {
|
|
41
|
-
name: name,
|
|
42
|
-
id: uni.id,
|
|
43
|
-
rpc: uni.rpc,
|
|
44
|
-
explorer: uni.explorer,
|
|
45
|
-
observer: uni.observer,
|
|
46
|
-
contracts: uni.contracts || {},
|
|
47
|
-
};
|
|
48
|
-
}
|
|
39
|
+
export function _loadMergedConfig() {
|
|
40
|
+
const search = [
|
|
41
|
+
...new Set([
|
|
42
|
+
path.resolve(__dirname, "../.every.toml"),
|
|
43
|
+
path.resolve(os.homedir(), ".every.toml"),
|
|
44
|
+
path.resolve(process.cwd(), ".every.toml"),
|
|
45
|
+
]),
|
|
46
|
+
];
|
|
47
|
+
const files = search.filter((f) => fs.existsSync(f));
|
|
48
|
+
if (files.length === 0) {
|
|
49
|
+
throw new Error(`No config file found. Searched in:\n ${search.join("\n ")}`);
|
|
50
|
+
}
|
|
51
|
+
const merged = { universes: {}, observers: {} };
|
|
52
|
+
for (const file of files) {
|
|
53
|
+
const raw = loadConfig(file);
|
|
54
|
+
if (raw.universes) {
|
|
55
|
+
for (const [name, uni] of Object.entries(raw.universes)) {
|
|
56
|
+
merged.universes[name] = {
|
|
57
|
+
...(merged.universes[name] ?? {}),
|
|
58
|
+
...uni, // shallow merge here
|
|
59
|
+
};
|
|
49
60
|
}
|
|
50
|
-
console.log(`Loaded configuration from ${configPath}`);
|
|
51
61
|
}
|
|
52
|
-
|
|
53
|
-
|
|
62
|
+
if (raw.observers) {
|
|
63
|
+
for (const [name, obs] of Object.entries(raw.observers)) {
|
|
64
|
+
merged.observers[name] = {
|
|
65
|
+
...(merged.observers[name] ?? {}),
|
|
66
|
+
...obs,
|
|
67
|
+
};
|
|
68
|
+
}
|
|
54
69
|
}
|
|
55
70
|
}
|
|
56
|
-
|
|
57
|
-
console.warn("No universe configurations found");
|
|
58
|
-
}
|
|
59
|
-
CONFIG_CACHED = mergedConfig;
|
|
60
|
-
return CONFIG_CACHED;
|
|
71
|
+
return [ConfigSchema.parse(merged), files];
|
|
61
72
|
}
|
package/dist/ethereum.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { parseEventLogs } from "viem";
|
|
2
|
+
import columnify from "columnify";
|
|
3
|
+
import { stringify as j11 } from "json11";
|
|
4
|
+
export async function submitSimulation(simulation, publicClient, walletClient, console) {
|
|
5
|
+
console.log("Transaction sending...");
|
|
6
|
+
const { request } = await publicClient.simulateContract(simulation);
|
|
7
|
+
const hash = await walletClient.writeContract(request);
|
|
8
|
+
console.log(`Transaction sent: ${hash}`);
|
|
9
|
+
console.log("Waiting for confirmation...");
|
|
10
|
+
const receipt = await publicClient.waitForTransactionReceipt({ hash });
|
|
11
|
+
console.log(`Confirmed in: block ${receipt.blockNumber}, hash ${receipt.blockHash}`);
|
|
12
|
+
const output = [];
|
|
13
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
14
|
+
const events = [];
|
|
15
|
+
if (receipt.logs && receipt.logs.length > 0) {
|
|
16
|
+
const parsedLogs = parseEventLogs({ abi: simulation.abi, logs: receipt.logs });
|
|
17
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
18
|
+
parsedLogs.forEach((log, i) => {
|
|
19
|
+
output.push([i, log.eventName, j11(log.args)]);
|
|
20
|
+
events.push({ name: log.eventName, data: log.args });
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
if (output.length > 0) {
|
|
24
|
+
console.log("Events emitted");
|
|
25
|
+
const termWidth = process.stdout.columns || 80;
|
|
26
|
+
const config = {
|
|
27
|
+
2: { maxWidth: Math.max(60, termWidth - 20) },
|
|
28
|
+
};
|
|
29
|
+
console.log(columnify(output, { showHeaders: false, truncateMarker: "", config }));
|
|
30
|
+
}
|
|
31
|
+
const result = { transaction: hash, block: { number: receipt.blockNumber, hash: receipt.blockHash }, events };
|
|
32
|
+
console.result(result);
|
|
33
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { bytesToHex, createPublicClient, createWalletClient, http } from "viem";
|
|
2
|
+
import fs from "fs";
|
|
3
|
+
import path from "path";
|
|
4
|
+
import { Wallet } from "ethers";
|
|
5
|
+
import { privateKeyToAccount } from "viem/accounts";
|
|
6
|
+
import promptSync from "prompt-sync";
|
|
7
|
+
import os from "os";
|
|
8
|
+
import { loadMergedConfig } from "./config.js";
|
|
9
|
+
import Keyring from "@polkadot/keyring";
|
|
10
|
+
import { UnifiedKeystore } from "./keystore.js";
|
|
11
|
+
import { decodePairFromJson, loadJson } from "./utils.js";
|
|
12
|
+
import { ApiPromise, WsProvider } from "@polkadot/api";
|
|
13
|
+
export const FromOpts = {
|
|
14
|
+
getKeystoreDir: function (opts) {
|
|
15
|
+
if (opts.foundry) {
|
|
16
|
+
return path.join(os.homedir(), ".foundry", "keystores");
|
|
17
|
+
}
|
|
18
|
+
if (opts.dir) {
|
|
19
|
+
return opts.dir;
|
|
20
|
+
}
|
|
21
|
+
return path.join(os.homedir(), ".every", "keystores");
|
|
22
|
+
},
|
|
23
|
+
getKeystoreFile: function (opts, name) {
|
|
24
|
+
const dir = FromOpts.getKeystoreDir(opts);
|
|
25
|
+
return path.join(dir, name);
|
|
26
|
+
},
|
|
27
|
+
getKeystore: async function (opts, account) {
|
|
28
|
+
const name = account ?? opts.account;
|
|
29
|
+
if (!name) {
|
|
30
|
+
throw new Error(`account not specified`);
|
|
31
|
+
}
|
|
32
|
+
const keyFile = FromOpts.getKeystoreFile(opts, account ?? opts.account);
|
|
33
|
+
const keyData = loadJson(keyFile);
|
|
34
|
+
const password = FromOpts.getPassword(opts);
|
|
35
|
+
const keystore = await UnifiedKeystore.fromJSON(keyData, password);
|
|
36
|
+
return keystore;
|
|
37
|
+
},
|
|
38
|
+
getPassword: function (opts) {
|
|
39
|
+
return opts.password
|
|
40
|
+
? opts.password
|
|
41
|
+
: opts.passwordFile
|
|
42
|
+
? fs.readFileSync(opts.passwordFile, "utf8").trim()
|
|
43
|
+
: promptSync({ sigint: true })("Enter keystore password: ", { echo: "" });
|
|
44
|
+
},
|
|
45
|
+
confirmPassword: function (opts) {
|
|
46
|
+
if (opts.password) {
|
|
47
|
+
return opts.password;
|
|
48
|
+
}
|
|
49
|
+
if (opts.passwordFile) {
|
|
50
|
+
return fs.readFileSync(opts.passwordFile, "utf8").trim();
|
|
51
|
+
}
|
|
52
|
+
const prompt = promptSync({ sigint: true });
|
|
53
|
+
const password = prompt("Enter keystore password: ", { echo: "" });
|
|
54
|
+
const confirmation = prompt("Re-enter to confirm: ", { echo: "" });
|
|
55
|
+
if (password !== confirmation) {
|
|
56
|
+
throw new Error(`Error: Passwords do not match`);
|
|
57
|
+
}
|
|
58
|
+
return password;
|
|
59
|
+
},
|
|
60
|
+
getUniverseConfig: function (opts) {
|
|
61
|
+
const config = loadMergedConfig();
|
|
62
|
+
const universeName = opts.universe;
|
|
63
|
+
const universe = config.universes[universeName];
|
|
64
|
+
if (!universe) {
|
|
65
|
+
const available = Object.keys(config.universes).join(", ");
|
|
66
|
+
throw new Error(`Universe "${universeName}" not found. Available: ${available}`);
|
|
67
|
+
}
|
|
68
|
+
return universe;
|
|
69
|
+
},
|
|
70
|
+
getObserverConfig: function (options) {
|
|
71
|
+
const conf = loadMergedConfig();
|
|
72
|
+
let observerName;
|
|
73
|
+
const DEFAULT_OBSERVER = "localnet";
|
|
74
|
+
if (options.network) {
|
|
75
|
+
observerName = options.network;
|
|
76
|
+
}
|
|
77
|
+
else if (options.universe) {
|
|
78
|
+
const universe = conf.universes[options.universe];
|
|
79
|
+
if (!universe) {
|
|
80
|
+
throw new Error(`Universe '${options.universe}' not found in config. Available: ${Object.keys(conf.universes).join(", ")}`);
|
|
81
|
+
}
|
|
82
|
+
observerName = universe.observer;
|
|
83
|
+
}
|
|
84
|
+
else {
|
|
85
|
+
observerName = DEFAULT_OBSERVER;
|
|
86
|
+
}
|
|
87
|
+
if (!observerName) {
|
|
88
|
+
throw new Error(`No observer resolved from options or config.`);
|
|
89
|
+
}
|
|
90
|
+
const observer = conf.observers[observerName];
|
|
91
|
+
if (!observer) {
|
|
92
|
+
throw new Error(`Observer '${observerName}' not found in config. Available: ${Object.keys(conf.observers).join(", ")}`);
|
|
93
|
+
}
|
|
94
|
+
return observer;
|
|
95
|
+
},
|
|
96
|
+
getPair: async function (opts) {
|
|
97
|
+
const keyFile = FromOpts.getKeystoreFile(opts, opts.account);
|
|
98
|
+
const keyData = loadJson(keyFile);
|
|
99
|
+
const keyring = new Keyring();
|
|
100
|
+
const pair = keyring.createFromJson(keyData);
|
|
101
|
+
if (pair.isLocked) {
|
|
102
|
+
const password = FromOpts.getPassword(opts);
|
|
103
|
+
pair.unlock(password);
|
|
104
|
+
}
|
|
105
|
+
return pair;
|
|
106
|
+
},
|
|
107
|
+
getPrivateKey: async function (opts) {
|
|
108
|
+
if (opts.privateKey) {
|
|
109
|
+
return opts.privateKey.startsWith("0x") ? opts.privateKey : `0x${opts.privateKey}`;
|
|
110
|
+
}
|
|
111
|
+
else if (opts.account) {
|
|
112
|
+
const keyFile = FromOpts.getKeystoreFile(opts, opts.account);
|
|
113
|
+
const keyData = loadJson(keyFile);
|
|
114
|
+
if (keyData.crypto || keyData.Crypto) {
|
|
115
|
+
// for Ethereum keystores
|
|
116
|
+
const password = FromOpts.getPassword(opts);
|
|
117
|
+
const wallet = await Wallet.fromEncryptedJson(JSON.stringify(keyData), password);
|
|
118
|
+
return wallet.privateKey;
|
|
119
|
+
}
|
|
120
|
+
else if (keyData.encoding || keyData.meta) {
|
|
121
|
+
// for Substrate keystores, must be ethereum type
|
|
122
|
+
if (keyData.meta?.isEthereum || keyData.meta?.type === "ethereum") {
|
|
123
|
+
const password = FromOpts.getPassword(opts);
|
|
124
|
+
const pair = decodePairFromJson(keyData, password);
|
|
125
|
+
return bytesToHex(pair.secretKey);
|
|
126
|
+
}
|
|
127
|
+
else {
|
|
128
|
+
throw new Error("Not an Ethereum account");
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
// Not supported for now
|
|
133
|
+
throw new Error("Unknown keystore format");
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
else {
|
|
137
|
+
throw new Error(`Neither account nor private key specified`);
|
|
138
|
+
}
|
|
139
|
+
},
|
|
140
|
+
toWriteEthereum: async function (opts) {
|
|
141
|
+
const conf = FromOpts.getUniverseConfig(opts);
|
|
142
|
+
const transport = http(conf.rpc);
|
|
143
|
+
const publicClient = createPublicClient({ transport });
|
|
144
|
+
const privateKey = await FromOpts.getPrivateKey(opts);
|
|
145
|
+
const account = privateKeyToAccount(privateKey);
|
|
146
|
+
const walletClient = createWalletClient({ account, transport });
|
|
147
|
+
return { publicClient, walletClient, conf };
|
|
148
|
+
},
|
|
149
|
+
toReadEthereum: function (opts) {
|
|
150
|
+
const conf = FromOpts.getUniverseConfig(opts);
|
|
151
|
+
const transport = http(conf.rpc);
|
|
152
|
+
const publicClient = createPublicClient({ transport });
|
|
153
|
+
return { publicClient, conf };
|
|
154
|
+
},
|
|
155
|
+
getSubstrateApi: async function (opts) {
|
|
156
|
+
const conf = FromOpts.getObserverConfig(opts);
|
|
157
|
+
const provider = new WsProvider(conf.rpc);
|
|
158
|
+
const api = await ApiPromise.create({ provider, noInitWarn: true });
|
|
159
|
+
return api;
|
|
160
|
+
},
|
|
161
|
+
};
|
package/dist/index.js
CHANGED
package/dist/keystore.js
ADDED
|
@@ -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
|
+
}
|