@offckb/cli 0.1.0-rc2 → 0.1.0-rc4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +55 -16
  2. package/{docker → ckb}/devnet/specs/dev.toml +1 -1
  3. package/dist/cfg/const.d.ts +1 -0
  4. package/dist/cfg/const.js +4 -3
  5. package/dist/cfg/select.d.ts +1 -0
  6. package/dist/cfg/select.js +52 -0
  7. package/dist/cli.js +37 -19
  8. package/dist/cmd/build-lumos-config.d.ts +2 -2
  9. package/dist/cmd/build-lumos-config.js +92 -69
  10. package/dist/cmd/clean.d.ts +1 -0
  11. package/dist/cmd/clean.js +21 -0
  12. package/dist/cmd/genkey.js +3 -7
  13. package/dist/cmd/init-chain.js +1 -43
  14. package/dist/cmd/init.d.ts +1 -1
  15. package/dist/cmd/init.js +10 -4
  16. package/dist/util.d.ts +5 -0
  17. package/dist/util.js +101 -1
  18. package/package.json +8 -8
  19. package/templates/transfer/index.html +13 -0
  20. package/templates/transfer/index.tsx +89 -0
  21. package/templates/xudt/lib.ts +153 -0
  22. package/templates/xudt/package.json +29 -0
  23. package/templates/xudt/tsconfig.json +10 -0
  24. package/templates/xudt/yarn.lock +2315 -0
  25. package/docker/docker-compose.yml +0 -37
  26. /package/{docker → ckb}/devnet/check-ckb-started-successfully.sh +0 -0
  27. /package/{docker → ckb}/devnet/ckb-miner.toml +0 -0
  28. /package/{docker → ckb}/devnet/ckb.toml +0 -0
  29. /package/{docker → ckb}/devnet/default.db-options +0 -0
  30. /package/{docker → ckb}/devnet/specs/always_success +0 -0
  31. /package/{docker → ckb}/devnet/specs/anyone_can_pay +0 -0
  32. /package/{docker → ckb}/devnet/specs/omni_lock +0 -0
  33. /package/{docker → ckb}/devnet/specs/sudt +0 -0
  34. /package/{docker → ckb}/devnet/specs/xudt_rce +0 -0
  35. /package/{template → templates}/ckb.ts +0 -0
  36. /package/{template → templates}/config.json +0 -0
  37. /package/{template → templates/transfer}/lib.ts +0 -0
  38. /package/{template → templates/transfer}/package.json +0 -0
  39. /package/{template → templates/transfer}/tsconfig.json +0 -0
  40. /package/{template → templates/transfer}/yarn.lock +0 -0
  41. /package/{template → templates/xudt}/index.html +0 -0
  42. /package/{template → templates/xudt}/index.tsx +0 -0
package/dist/util.js CHANGED
@@ -22,9 +22,19 @@ var __importStar = (this && this.__importStar) || function (mod) {
22
22
  __setModuleDefault(result, mod);
23
23
  return result;
24
24
  };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
25
34
  Object.defineProperty(exports, "__esModule", { value: true });
26
- exports.isFolderExists = void 0;
35
+ exports.removeFolderSync = exports.copyRecursive = exports.copyFilesWithExclusion = exports.copyFileSync = exports.copyFolderSync = exports.isFolderExists = void 0;
27
36
  const fs = __importStar(require("fs"));
37
+ const path = __importStar(require("path"));
28
38
  function isFolderExists(folderPath) {
29
39
  try {
30
40
  // Check if the path exists
@@ -39,3 +49,93 @@ function isFolderExists(folderPath) {
39
49
  }
40
50
  }
41
51
  exports.isFolderExists = isFolderExists;
52
+ function copyFolderSync(source, destination) {
53
+ if (!fs.existsSync(destination)) {
54
+ fs.mkdirSync(destination);
55
+ }
56
+ const files = fs.readdirSync(source);
57
+ for (const file of files) {
58
+ const currentPath = path.join(source, file);
59
+ const destinationPath = path.join(destination, file);
60
+ if (fs.statSync(currentPath).isDirectory()) {
61
+ copyFolderSync(currentPath, destinationPath);
62
+ }
63
+ else {
64
+ fs.copyFileSync(currentPath, destinationPath);
65
+ }
66
+ }
67
+ }
68
+ exports.copyFolderSync = copyFolderSync;
69
+ function copyFileSync(source, target) {
70
+ let targetFile = target;
71
+ // If target is a directory, a new file with the same name will be created
72
+ if (fs.existsSync(target)) {
73
+ if (fs.lstatSync(target).isDirectory()) {
74
+ targetFile = path.join(target, path.basename(source));
75
+ }
76
+ }
77
+ fs.writeFileSync(targetFile, fs.readFileSync(source));
78
+ }
79
+ exports.copyFileSync = copyFileSync;
80
+ function copyFilesWithExclusion(sourceDir, destinationDir, excludedFolders) {
81
+ return __awaiter(this, void 0, void 0, function* () {
82
+ try {
83
+ // Ensure the destination directory exists
84
+ yield fs.promises.mkdir(destinationDir, { recursive: true });
85
+ // Start copying recursively from the source directory
86
+ yield copyRecursive(sourceDir, destinationDir, excludedFolders);
87
+ }
88
+ catch (error) {
89
+ console.error('An error occurred during copying files:', error);
90
+ }
91
+ });
92
+ }
93
+ exports.copyFilesWithExclusion = copyFilesWithExclusion;
94
+ // Function to recursively copy files and directories
95
+ function copyRecursive(source, destination, excludedFolders) {
96
+ return __awaiter(this, void 0, void 0, function* () {
97
+ // Get a list of all files and directories in the source directory
98
+ const files = yield fs.promises.readdir(source);
99
+ // Iterate through each file or directory
100
+ for (const file of files) {
101
+ const sourcePath = path.join(source, file);
102
+ const destPath = path.join(destination, file);
103
+ // Get the file's stats
104
+ const stats = yield fs.promises.stat(sourcePath);
105
+ // If it's a directory, recursively copy it (unless it's excluded)
106
+ if (stats.isDirectory()) {
107
+ if (excludedFolders.includes(file)) {
108
+ // Skipping directory: ${sourcePath}
109
+ }
110
+ else {
111
+ // Ensure destination directory exists before copying
112
+ yield fs.promises.mkdir(destPath, { recursive: true });
113
+ yield copyRecursive(sourcePath, destPath, excludedFolders);
114
+ }
115
+ }
116
+ else {
117
+ // Otherwise, copy the file
118
+ yield fs.promises.copyFile(sourcePath, destPath);
119
+ }
120
+ }
121
+ });
122
+ }
123
+ exports.copyRecursive = copyRecursive;
124
+ function removeFolderSync(folderPath) {
125
+ if (fs.existsSync(folderPath)) {
126
+ fs.readdirSync(folderPath).forEach((file) => {
127
+ const curPath = path.join(folderPath, file);
128
+ if (fs.lstatSync(curPath).isDirectory()) {
129
+ // Recursive call for directories
130
+ removeFolderSync(curPath);
131
+ }
132
+ else {
133
+ // Delete files
134
+ fs.unlinkSync(curPath);
135
+ }
136
+ });
137
+ // Remove the directory itself
138
+ fs.rmdirSync(folderPath);
139
+ }
140
+ }
141
+ exports.removeFolderSync = removeFolderSync;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@offckb/cli",
3
- "version": "0.1.0-rc2",
3
+ "version": "0.1.0-rc4",
4
4
  "description": "ckb development environment for professionals",
5
5
  "author": "Retric Su <retric@cryptape.com>",
6
6
  "license": "MIT",
@@ -15,8 +15,8 @@
15
15
  "files": [
16
16
  "dist",
17
17
  "account",
18
- "docker",
19
- "template"
18
+ "ckb",
19
+ "templates"
20
20
  ],
21
21
  "private": false,
22
22
  "publishConfig": {
@@ -26,10 +26,9 @@
26
26
  "build": "tsc",
27
27
  "start": "ts-node-dev --transpile-only src/cli.ts",
28
28
  "clean": "rm -rf ./target",
29
- "docker": "cd docker && docker-compose up",
30
- "lint": "eslint \"{src,template}/**/*.ts\" \"{src,template}/**/*.tsx\" --ignore-pattern 'node_modules/'",
31
- "lint:fix": "eslint \"{src,template}/**/*.ts\" \"{src,template}/**/*.tsx\" --ignore-pattern 'node_modules/' --fix",
32
- "fmt": "prettier --write '{src,template,account}/**/*.{js,jsx,ts,tsx,md,json}'"
29
+ "lint": "eslint \"{src,templates}/**/*.ts\" \"{src,templates}/**/*.tsx\" --ignore-pattern 'node_modules/'",
30
+ "lint:fix": "eslint \"{src,templates}/**/*.ts\" \"{src,templates}/**/*.tsx\" --ignore-pattern 'node_modules/' --fix",
31
+ "fmt": "prettier --write '{src,templates,account}/**/*.{js,jsx,ts,tsx,md,json}'"
33
32
  },
34
33
  "husky": {
35
34
  "hooks": {
@@ -37,7 +36,7 @@
37
36
  }
38
37
  },
39
38
  "lint-staged": {
40
- "{src,template,account}/**/*.{js,jsx,ts,tsx,md,json}": "prettier --ignore-unknown --write"
39
+ "{src,templates,account}/**/*.{js,jsx,ts,tsx,md,json}": "prettier --ignore-unknown --write"
41
40
  },
42
41
  "eslintConfig": {
43
42
  "extends": [
@@ -60,6 +59,7 @@
60
59
  },
61
60
  "dependencies": {
62
61
  "@ckb-lumos/lumos": "0.21.1",
62
+ "@inquirer/prompts": "^4.1.0",
63
63
  "adm-zip": "^0.5.10",
64
64
  "axios": "^1.6.7",
65
65
  "child_process": "^1.0.2",
@@ -0,0 +1,13 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />
6
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
+ <title>Transfer CKB</title>
8
+ </head>
9
+ <body>
10
+ <div id="root"></div>
11
+ <script src="index.tsx" type="module"></script>
12
+ </body>
13
+ </html>
@@ -0,0 +1,89 @@
1
+ import React, { useEffect, useState } from 'react';
2
+ import ReactDOM from 'react-dom';
3
+ import { Script } from '@ckb-lumos/lumos';
4
+ import { capacityOf, generateAccountFromPrivateKey, transfer } from './lib';
5
+
6
+ const app = document.getElementById('root');
7
+ ReactDOM.render(<App />, app);
8
+
9
+ export function App() {
10
+ const [privKey, setPrivKey] = useState('');
11
+ const [fromAddr, setFromAddr] = useState('');
12
+ const [fromLock, setFromLock] = useState<Script>();
13
+ const [balance, setBalance] = useState('0');
14
+
15
+ const [toAddr, setToAddr] = useState('');
16
+ const [amount, setAmount] = useState('');
17
+
18
+ useEffect(() => {
19
+ const updateFromInfo = async () => {
20
+ const { lockScript, address } = generateAccountFromPrivateKey(privKey);
21
+ const capacity = await capacityOf(address);
22
+ setFromAddr(address);
23
+ setFromLock(lockScript);
24
+ setBalance(capacity.toString());
25
+ };
26
+
27
+ if (privKey) {
28
+ updateFromInfo();
29
+ }
30
+ }, [privKey]);
31
+
32
+ const onInputPrivKey = (e: React.ChangeEvent<HTMLInputElement>) => {
33
+ // Regular expression to match a valid private key with "0x" prefix
34
+ const priv = e.target.value;
35
+ const privateKeyRegex = /^0x[0-9a-fA-F]{64}$/;
36
+
37
+ const isValid = privateKeyRegex.test(priv);
38
+ if (isValid) {
39
+ setPrivKey(priv);
40
+ } else {
41
+ alert(
42
+ `Invalid private key: must start with 0x and 32 bytes length. Ensure you're using a valid private key from the offckb accounts list.`,
43
+ );
44
+ }
45
+ };
46
+
47
+ const enabled = +amount > 6100000000 && +balance > +amount && toAddr.length > 0;
48
+ const amountTip =
49
+ amount.length > 0 && +amount < 6100000000 ? (
50
+ <span>
51
+ amount must larger than 6,100,000,000(61 CKB), see{' '}
52
+ <a href="https://medium.com/nervosnetwork/understanding-the-nervos-dao-and-cell-model-d68f38272c24">why</a>
53
+ </span>
54
+ ) : null;
55
+
56
+ return (
57
+ <div>
58
+ <h1>Transfer CKB between addresses</h1>
59
+ <label htmlFor="private-key">Private Key: </label>&nbsp;
60
+ <input id="private-key" type="text" onChange={onInputPrivKey} />
61
+ <ul>
62
+ <li>CKB Address: {fromAddr}</li>
63
+ <li>
64
+ Current lock script:
65
+ <pre>{JSON.stringify(fromLock, null, 2)}</pre>
66
+ </li>
67
+
68
+ <li>Total capacity: {(+balance).toLocaleString()}</li>
69
+ </ul>
70
+ <label htmlFor="to-address">Transfer to Address: </label>&nbsp;
71
+ <input id="to-address" type="text" onChange={(e) => setToAddr(e.target.value)} />
72
+ <br />
73
+ <label htmlFor="amount">Amount</label>
74
+ &nbsp;
75
+ <input id="amount" type="number" onChange={(e) => setAmount(e.target.value)} />
76
+ <small>Tx fee: 100,000 (0.001 CKB)</small>
77
+ <br />
78
+ <small style={{ color: 'red' }}>{amountTip}</small>
79
+ <br />
80
+ <br />
81
+ <button
82
+ disabled={!enabled}
83
+ onClick={() => transfer({ amount, from: fromAddr, to: toAddr, privKey }).catch(alert)}
84
+ >
85
+ Transfer
86
+ </button>
87
+ </div>
88
+ );
89
+ }
@@ -0,0 +1,153 @@
1
+ import { bytes } from '@ckb-lumos/codec';
2
+ import { helpers, Address, Script, hd, config, Cell, commons, WitnessArgs, BI } from '@ckb-lumos/lumos';
3
+ import { values, blockchain } from '@ckb-lumos/base';
4
+ import { indexer, lumosConfig, rpc } from './ckb';
5
+ const { ScriptValue } = values;
6
+
7
+ config.initializeConfig(lumosConfig);
8
+
9
+ type Account = {
10
+ lockScript: Script;
11
+ address: Address;
12
+ pubKey: string;
13
+ };
14
+ export const generateAccountFromPrivateKey = (privKey: string): Account => {
15
+ const pubKey = hd.key.privateToPublic(privKey);
16
+ const args = hd.key.publicKeyToBlake160(pubKey);
17
+ const template = lumosConfig.SCRIPTS['SECP256K1_BLAKE160']!;
18
+ const lockScript = {
19
+ codeHash: template.CODE_HASH,
20
+ hashType: template.HASH_TYPE,
21
+ args: args,
22
+ };
23
+ const address = helpers.encodeToAddress(lockScript, { config: lumosConfig });
24
+ return {
25
+ lockScript,
26
+ address,
27
+ pubKey,
28
+ };
29
+ };
30
+
31
+ export async function capacityOf(address: string): Promise<BI> {
32
+ const collector = indexer.collector({
33
+ lock: helpers.parseAddress(address, { config: lumosConfig }),
34
+ });
35
+
36
+ let balance = BI.from(0);
37
+ for await (const cell of collector.collect()) {
38
+ balance = balance.add(cell.cellOutput.capacity);
39
+ }
40
+
41
+ return balance;
42
+ }
43
+
44
+ interface Options {
45
+ from: string;
46
+ to: string;
47
+ amount: string;
48
+ privKey: string;
49
+ }
50
+
51
+ export async function transfer(options: Options): Promise<string> {
52
+ let txSkeleton = helpers.TransactionSkeleton({});
53
+ const fromScript = helpers.parseAddress(options.from, {
54
+ config: lumosConfig,
55
+ });
56
+ const toScript = helpers.parseAddress(options.to, { config: lumosConfig });
57
+
58
+ if (BI.from(options.amount).lt(BI.from('6100000000'))) {
59
+ throw new Error(
60
+ `every cell's capacity must be at least 61 CKB, see https://medium.com/nervosnetwork/understanding-the-nervos-dao-and-cell-model-d68f38272c24`,
61
+ );
62
+ }
63
+
64
+ // additional 0.001 ckb for tx fee
65
+ // the tx fee could calculated by tx size
66
+ // this is just a simple example
67
+ const neededCapacity = BI.from(options.amount).add(100000);
68
+ let collectedSum = BI.from(0);
69
+ const collected: Cell[] = [];
70
+ const collector = indexer.collector({ lock: fromScript, type: 'empty' });
71
+ for await (const cell of collector.collect()) {
72
+ collectedSum = collectedSum.add(cell.cellOutput.capacity);
73
+ collected.push(cell);
74
+ if (collectedSum >= neededCapacity) break;
75
+ }
76
+
77
+ if (collectedSum.lt(neededCapacity)) {
78
+ throw new Error(`Not enough CKB, ${collectedSum} < ${neededCapacity}`);
79
+ }
80
+
81
+ const transferOutput: Cell = {
82
+ cellOutput: {
83
+ capacity: BI.from(options.amount).toHexString(),
84
+ lock: toScript,
85
+ },
86
+ data: '0x',
87
+ };
88
+
89
+ const changeOutput: Cell = {
90
+ cellOutput: {
91
+ capacity: collectedSum.sub(neededCapacity).toHexString(),
92
+ lock: fromScript,
93
+ },
94
+ data: '0x',
95
+ };
96
+
97
+ txSkeleton = txSkeleton.update('inputs', (inputs) => inputs.push(...collected));
98
+ txSkeleton = txSkeleton.update('outputs', (outputs) => outputs.push(transferOutput, changeOutput));
99
+ txSkeleton = txSkeleton.update('cellDeps', (cellDeps) =>
100
+ cellDeps.push({
101
+ outPoint: {
102
+ txHash: lumosConfig.SCRIPTS.SECP256K1_BLAKE160.TX_HASH,
103
+ index: lumosConfig.SCRIPTS.SECP256K1_BLAKE160.INDEX,
104
+ },
105
+ depType: lumosConfig.SCRIPTS.SECP256K1_BLAKE160.DEP_TYPE,
106
+ }),
107
+ );
108
+
109
+ const firstIndex = txSkeleton
110
+ .get('inputs')
111
+ .findIndex((input) =>
112
+ new ScriptValue(input.cellOutput.lock, { validate: false }).equals(
113
+ new ScriptValue(fromScript, { validate: false }),
114
+ ),
115
+ );
116
+ if (firstIndex !== -1) {
117
+ while (firstIndex >= txSkeleton.get('witnesses').size) {
118
+ txSkeleton = txSkeleton.update('witnesses', (witnesses) => witnesses.push('0x'));
119
+ }
120
+ let witness: string = txSkeleton.get('witnesses').get(firstIndex)!;
121
+ const newWitnessArgs: WitnessArgs = {
122
+ /* 65-byte zeros in hex */
123
+ lock: '0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
124
+ };
125
+ if (witness !== '0x') {
126
+ const witnessArgs = blockchain.WitnessArgs.unpack(bytes.bytify(witness));
127
+ const lock = witnessArgs.lock;
128
+ if (!!lock && !!newWitnessArgs.lock && !bytes.equal(lock, newWitnessArgs.lock)) {
129
+ throw new Error('Lock field in first witness is set aside for signature!');
130
+ }
131
+ const inputType = witnessArgs.inputType;
132
+ if (inputType) {
133
+ newWitnessArgs.inputType = inputType;
134
+ }
135
+ const outputType = witnessArgs.outputType;
136
+ if (outputType) {
137
+ newWitnessArgs.outputType = outputType;
138
+ }
139
+ }
140
+ witness = bytes.hexify(blockchain.WitnessArgs.pack(newWitnessArgs));
141
+ txSkeleton = txSkeleton.update('witnesses', (witnesses) => witnesses.set(firstIndex, witness));
142
+ }
143
+
144
+ txSkeleton = commons.common.prepareSigningEntries(txSkeleton);
145
+ const message = txSkeleton.get('signingEntries').get(0)?.message;
146
+ const Sig = hd.key.signRecoverable(message!, options.privKey);
147
+ const tx = helpers.sealTransaction(txSkeleton, [Sig]);
148
+ const hash = await rpc.sendTransaction(tx, 'passthrough');
149
+ console.log('The transaction hash is', hash);
150
+ alert(`The transaction hash is ${hash}`);
151
+
152
+ return hash;
153
+ }
@@ -0,0 +1,29 @@
1
+ {
2
+ "name": "@offckb/lumos-scaffold",
3
+ "version": "0.1.0",
4
+ "description": "",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "start": "parcel index.html",
8
+ "lint": "tsc --noEmit"
9
+ },
10
+ "keywords": [],
11
+ "author": "",
12
+ "license": "MIT",
13
+ "dependencies": {
14
+ "@ckb-lumos/base": "0.21.1",
15
+ "@ckb-lumos/codec": "0.21.1",
16
+ "@ckb-lumos/lumos": "0.21.1",
17
+ "@types/react": "^18.0.25",
18
+ "@types/react-dom": "^18.0.9",
19
+ "react": "^18.2.0",
20
+ "react-dom": "^18.2.0"
21
+ },
22
+ "devDependencies": {
23
+ "crypto-browserify": "^3.12.0",
24
+ "parcel": "^2.9.3",
25
+ "path-browserify": "^1.0.0",
26
+ "process": "^0.11.10",
27
+ "stream-browserify": "^3.0.0"
28
+ }
29
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "compilerOptions": {
3
+ "lib": ["dom"],
4
+ "jsx": "react",
5
+ "module": "CommonJS",
6
+ "skipLibCheck": true,
7
+ "esModuleInterop": true,
8
+ "resolveJsonModule": true
9
+ }
10
+ }