Skip to content

Commit 81a5f7e

Browse files
ShookLyngsduanyytop
authored andcommittedMay 7, 2024
refactor: use eslint in packages/examples
1 parent c396b8e commit 81a5f7e

37 files changed

+206
-187
lines changed
 

‎.eslintrc.json

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
{
2+
"env": {
3+
"browser": true,
4+
"es2021": true
5+
},
6+
"extends": [
7+
"eslint:recommended",
8+
"plugin:@typescript-eslint/recommended"
9+
],
10+
"parser": "@typescript-eslint/parser",
11+
"parserOptions": {
12+
"ecmaVersion": "latest",
13+
"sourceType": "module"
14+
},
15+
"plugins": [
16+
"@typescript-eslint"
17+
],
18+
"rules": {
19+
}
20+
}

‎.github/workflows/test.yaml

+3-3
Original file line numberDiff line numberDiff line change
@@ -43,11 +43,11 @@ jobs:
4343
- name: Install dependencies
4444
run: pnpm i
4545

46-
- name: Lint packages
47-
run: pnpm lint:fix
48-
4946
- name: Build packages
5047
run: pnpm run build:packages
48+
49+
- name: Lint packages
50+
run: pnpm run lint:packages
5151

5252
- name: Run tests for packages
5353
run: pnpm run test:packages

‎.husky/pre-commit

+1-4
Original file line numberDiff line numberDiff line change
@@ -1,4 +1 @@
1-
#!/usr/bin/env sh
2-
. "$(dirname -- "$0")/_/husky.sh"
3-
4-
npx lint-staged
1+
pnpm exec lint-staged

‎examples/rgbpp/eslint.config.js

-6
This file was deleted.

‎examples/rgbpp/package.json

+3-5
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@
66
"type": "module",
77
"scripts": {
88
"format": "prettier --write '**/*.{js,ts}'",
9-
"lint:fix": "pnpm eslint . && prettier --check '**/*.{js,ts}'"
9+
"lint": "tsc && eslint . && prettier --check '**/*.{js,ts}'",
10+
"lint:fix": "tsc && eslint --fix --ext .js,.ts . && prettier --write '**/*.{js,ts}'"
1011
},
1112
"dependencies": {
1213
"@exact-realty/multipart-parser": "^1.0.13",
@@ -18,10 +19,7 @@
1819
"axios": "^1.6.8"
1920
},
2021
"devDependencies": {
21-
"@eslint/js": "^9.1.1",
2222
"@types/node": "^20.11.28",
23-
"eslint": "^8.56.0",
24-
"typescript": "^5.4.2",
25-
"typescript-eslint": "^7.7.1"
23+
"typescript": "^5.4.2"
2624
}
2725
}

‎examples/rgbpp/tsconfig.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
"composite": false,
88
"resolveJsonModule": true,
99
"strictNullChecks": true,
10+
"noEmit": true,
1011
"declaration": true,
1112
"declarationMap": true,
1213
"esModuleInterop": true,
@@ -18,7 +19,7 @@
1819
"noUnusedParameters": false,
1920
"preserveWatchOutput": true,
2021
"skipLibCheck": true,
21-
"strict": true,
22+
"strict": true
2223
},
2324
"include": ["local/**/*.ts", "queue/**/*.ts"],
2425
"exclude": ["node_modules"]

‎package.json

+9-3
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,10 @@
77
"scripts": {
88
"prepare": "husky",
99
"test:packages": "turbo run test --filter=./packages/*",
10-
"build": "turbo run build",
1110
"build:packages": "turbo run build --filter=./packages/*",
1211
"lint:fix": "turbo run lint:fix",
13-
"lint:fix-all": "prettier --write '{packages,apps, examples}/**/*.{js,jsx,ts,tsx,md,json}'",
12+
"lint:packages": "turbo run lint --filter=./{packages,examples}/*",
13+
"lint:fix-all": "prettier --write '{packages,apps,examples}/**/*.{js,jsx,ts,tsx,md,json}'",
1414
"clean": "turbo run clean",
1515
"clean:packages": "turbo run clean --filter=./packags/*",
1616
"clean:dependencies": "pnpm clean:sub-dependencies && rimraf node_modules",
@@ -20,6 +20,9 @@
2020
"devDependencies": {
2121
"@changesets/changelog-github": "^0.5.0",
2222
"@changesets/cli": "^2.27.1",
23+
"@typescript-eslint/eslint-plugin": "^7.8.0",
24+
"@typescript-eslint/parser": "^7.8.0",
25+
"eslint": "^8.56.0",
2326
"husky": "^9.0.11",
2427
"lint-staged": "^15.2.2",
2528
"prettier": "^3.2.5",
@@ -29,7 +32,10 @@
2932
"typescript": "^5.4.3"
3033
},
3134
"lint-staged": {
32-
"{packages,apps, examples}/**/*.{js,jsx,ts,tsx,md,json}": "prettier --ignore-unknown --write"
35+
"{packages,apps,examples}/**/*.{js,jsx,ts,tsx,md,json}": [
36+
"eslint --fix",
37+
"prettier --ignore-unknown --write"
38+
]
3339
},
3440
"packageManager": "^pnpm@8.0.0",
3541
"engines": {

‎packages/btc/package.json

+2-2
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44
"scripts": {
55
"test": "vitest",
66
"build": "tsc -p tsconfig.build.json",
7-
"lint": "prettier --check '{src,tests}/**/*.{js,jsx,ts,tsx}'",
8-
"lint:fix": "prettier --write '{src,tests}/**/*.{js,jsx,ts,tsx}'",
7+
"lint": "tsc && eslint --ext .js,.ts {src,tests}/** && prettier --check '{src,tests}/**/*.{js,ts}'",
8+
"lint:fix": "tsc && eslint --fix --ext .js,.ts {src,tests}/** && prettier --write '{src,tests}/**/*.{js,ts}'",
99
"clean": "pnpm run clean:cache & pnpm run clean:build",
1010
"clean:build": "rimraf lib && pnpm run clean:buildinfo",
1111
"clean:buildinfo": "rimraf tsconfig.*tsbuildinfo",

‎packages/btc/src/address.ts

+6-2
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,9 @@ export function decodeAddress(address: string): {
154154
dust: getAddressTypeDust(addressType),
155155
};
156156
}
157-
} catch (e) {}
157+
} catch (e) {
158+
// Do nothing (no need to throw here)
159+
}
158160
} else {
159161
try {
160162
decodeBase58 = bitcoin.address.fromBase58Check(address);
@@ -187,7 +189,9 @@ export function decodeAddress(address: string): {
187189
dust: getAddressTypeDust(addressType),
188190
};
189191
}
190-
} catch (e) {}
192+
} catch (e) {
193+
// Do nothing (no need to throw here)
194+
}
191195
}
192196

193197
return {

‎packages/btc/src/query/source.ts

+1-7
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,4 @@
1-
import {
2-
BtcApiRecommendedFeeRates,
3-
BtcApiUtxoParams,
4-
BtcAssetsApi,
5-
BtcAssetsApiError,
6-
ErrorCodes as ServiceErrorCodes,
7-
} from '@rgbpp-sdk/service';
1+
import { BtcApiUtxoParams, BtcAssetsApi, BtcAssetsApiError, ErrorCodes as ServiceErrorCodes } from '@rgbpp-sdk/service';
82
import { Output, Utxo } from '../transaction/utxo';
93
import { NetworkType } from '../preset/types';
104
import { ErrorCodes, TxBuildError } from '../error';

‎packages/btc/src/transaction/build.ts

+14-9
Original file line numberDiff line numberDiff line change
@@ -157,9 +157,17 @@ export class TxBuilder {
157157
// otherwise use the average fee rate from the DataSource
158158
const currentFeeRate = feeRate ?? this.feeRate ?? averageFeeRate!;
159159

160-
let currentFee: number = 0;
161-
let previousFee: number = 0;
162-
while (true) {
160+
let currentFee = 0;
161+
let previousFee = 0;
162+
let isLoopedOnce = false;
163+
let isFeeExpected = false;
164+
while (!isFeeExpected) {
165+
if (isLoopedOnce) {
166+
previousFee = currentFee;
167+
this.inputs = clone(originalInputs);
168+
this.outputs = clone(originalOutputs);
169+
}
170+
163171
const { needCollect, needReturn, inputsTotal } = this.summary();
164172
const safeToProcess = inputsTotal > 0 || previousFee > 0;
165173
const returnAmount = needReturn - previousFee;
@@ -186,13 +194,10 @@ export class TxBuilder {
186194

187195
const addressType = getAddressType(address);
188196
currentFee = await this.calculateFee(addressType, currentFeeRate);
189-
if ([-1, 0, 1].includes(currentFee - previousFee)) {
190-
break;
197+
isFeeExpected = [-1, 0, 1].includes(currentFee - previousFee);
198+
if (!isLoopedOnce) {
199+
isLoopedOnce = true;
191200
}
192-
193-
previousFee = currentFee;
194-
this.inputs = clone(originalInputs);
195-
this.outputs = clone(originalOutputs);
196201
}
197202

198203
return {

‎packages/btc/src/transaction/embed.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,8 @@ export function opReturnScriptPubKeyToData(script: Buffer): Buffer {
3333
throw TxBuildError.withComment(ErrorCodes.UNSUPPORTED_OP_RETURN_SCRIPT, script.toString('hex'));
3434
}
3535

36-
const [_op, data] = bitcoin.script.decompile(script)!;
37-
return data as Buffer;
36+
const res = bitcoin.script.decompile(script)!;
37+
return res[1] as Buffer;
3838
}
3939

4040
/**

‎packages/btc/src/utils.ts

+7-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
import { bitcoin, ecc, ECPair } from './bitcoin';
22
import { bytes } from '@ckb-lumos/codec';
33

4+
interface TweakableSigner extends bitcoin.Signer {
5+
privateKey?: Buffer;
6+
}
7+
48
const textEncoder = new TextEncoder();
59

610
export function toXOnly(pubKey: Buffer): Buffer {
@@ -11,14 +15,14 @@ function tapTweakHash(publicKey: Buffer, hash: Buffer | undefined): Buffer {
1115
return bitcoin.crypto.taggedHash('TapTweak', Buffer.concat(hash ? [publicKey, hash] : [publicKey]));
1216
}
1317

14-
export function tweakSigner<T extends bitcoin.Signer>(
18+
export function tweakSigner<T extends TweakableSigner>(
1519
signer: T,
1620
options?: {
1721
network?: bitcoin.Network;
1822
tweakHash?: Buffer;
1923
},
2024
): bitcoin.Signer {
21-
let privateKey: Uint8Array | undefined = (signer as any).privateKey;
25+
let privateKey: Uint8Array | undefined = signer.privateKey ? new Uint8Array(signer.privateKey) : undefined;
2226
if (!privateKey) {
2327
throw new Error('Private key is required for tweaking signer!');
2428
}
@@ -54,7 +58,7 @@ export function remove0x(hex: string): string {
5458
* utf8ToBuffer('hello') // => Uint8Array(5) [ 104, 101, 108, 108, 111 ]
5559
*/
5660
export function utf8ToBuffer(text: string): Uint8Array {
57-
let result = text.trim();
61+
const result = text.trim();
5862
if (result.startsWith('0x')) {
5963
return bytes.bytify(result);
6064
}

‎packages/btc/tests/DataSource.test.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { describe, expect, it } from 'vitest';
2-
import { service, source } from './shared/env';
2+
import { source } from './shared/env';
33
import { ErrorCodes } from '../src';
44

55
describe('DataSource', { retry: 3 }, () => {

‎packages/ckb/example/launch.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -36,15 +36,15 @@ const launchRgbppAsset = async () => {
3636
});
3737

3838
const emptyWitness = { lock: '', inputType: '', outputType: '' };
39-
let unsignedTx: CKBComponents.RawTransactionToSign = {
39+
const unsignedTx: CKBComponents.RawTransactionToSign = {
4040
...ckbRawTx,
4141
cellDeps: [...ckbRawTx.cellDeps, getSecp256k1CellDep(false)],
4242
witnesses: [emptyWitness, ...ckbRawTx.witnesses.slice(1)],
4343
};
4444

4545
const signedTx = collector.getCkb().signTransaction(LAUNCH_SECP256K1_PRIVATE_KEY)(unsignedTx);
4646

47-
let txHash = await collector.getCkb().rpc.sendTransaction(signedTx, 'passthrough');
47+
const txHash = await collector.getCkb().rpc.sendTransaction(signedTx, 'passthrough');
4848
console.info(`Rgbpp asset has been jumping from CKB to BTC and tx hash is ${txHash}`);
4949
};
5050

‎packages/ckb/package.json

+2-2
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44
"scripts": {
55
"test": "vitest",
66
"build": "tsc -p tsconfig.build.json",
7-
"lint": "prettier --check 'src/**/*.{js,jsx,ts,tsx}'",
8-
"lint:fix": "prettier --write 'src/**/*.{js,jsx,ts,tsx}'",
7+
"lint": "tsc && eslint --ext .ts {src,example}/* && prettier --check '{src,example}/**/*.{js,ts}'",
8+
"lint:fix": "tsc && eslint --fix --ext .ts {src,example}/* && prettier --write '{src,example}/**/*.{js,ts}'",
99
"splitCells": "npx ts-node example/paymaster.ts",
1010
"clean": "pnpm run clean:cache & pnpm run clean:build",
1111
"clean:build": "rimraf lib && pnpm run clean:buildinfo",

‎packages/ckb/src/collector/index.ts

+9-9
Original file line numberDiff line numberDiff line change
@@ -37,12 +37,12 @@ export class Collector {
3737
isDataMustBeEmpty?: boolean;
3838
outputCapacityRange?: Hex[];
3939
}): Promise<IndexerCell[] | undefined> {
40-
let param: any = {
40+
let param: unknown = {
4141
script_search_mode: 'exact',
4242
};
4343
if (lock) {
4444
param = {
45-
...param,
45+
...param!,
4646
script: parseScript(lock),
4747
script_type: 'lock',
4848
filter: {
@@ -53,19 +53,19 @@ export class Collector {
5353
};
5454
} else if (type) {
5555
param = {
56-
...param,
56+
...param!,
5757
script: parseScript(type),
5858
script_type: 'type',
5959
};
6060
}
61-
let payload = {
61+
const payload = {
6262
id: Math.floor(Math.random() * 100000),
6363
jsonrpc: '2.0',
6464
method: 'get_cells',
6565
params: [param, 'asc', '0x3E8'],
6666
};
6767
const body = JSON.stringify(payload, null, ' ');
68-
let response = (
68+
const response = (
6969
await axios({
7070
method: 'post',
7171
url: this.ckbIndexerUrl,
@@ -86,9 +86,9 @@ export class Collector {
8686

8787
collectInputs(liveCells: IndexerCell[], needCapacity: bigint, fee: bigint, config?: CollectConfig): CollectResult {
8888
const changeCapacity = config?.minCapacity ?? MIN_CAPACITY;
89-
let inputs: CKBComponents.CellInput[] = [];
89+
const inputs: CKBComponents.CellInput[] = [];
9090
let sumInputsCapacity = BigInt(0);
91-
for (let cell of liveCells) {
91+
for (const cell of liveCells) {
9292
inputs.push({
9393
previousOutput: {
9494
txHash: cell.outPoint.txHash,
@@ -109,11 +109,11 @@ export class Collector {
109109
}
110110

111111
collectUdtInputs({ liveCells, needAmount }: { liveCells: IndexerCell[]; needAmount: bigint }): CollectUdtResult {
112-
let inputs: CKBComponents.CellInput[] = [];
112+
const inputs: CKBComponents.CellInput[] = [];
113113
let sumInputsCapacity = BigInt(0);
114114
let sumAmount = BigInt(0);
115115
const isRgbppLock = liveCells.length > 0 && isRgbppLockCellIgnoreChain(liveCells[0].output);
116-
for (let cell of liveCells) {
116+
for (const cell of liveCells) {
117117
inputs.push({
118118
previousOutput: {
119119
txHash: cell.outPoint.txHash,

‎packages/ckb/src/paymaster/index.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ export const splitMultiCellsWithSecp256k1 = async ({
2929

3030
const cellCapacity = BigInt(capacityWithCKB) * CKB_UNIT;
3131
const needCapacity = cellCapacity * BigInt(cellAmount);
32-
let txFee = MAX_FEE;
32+
const txFee = MAX_FEE;
3333
const { inputs, sumInputsCapacity } = collector.collectInputs(emptyCells, needCapacity, txFee, {
3434
minCapacity: SECP256K1_MIN_CAPACITY,
3535
});

‎packages/ckb/src/rgbpp/btc-time.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ export const signBtcTimeCellSpentTx = async ({
157157
const changeCapacity = BigInt(emptyCells[0].output.capacity) - estimatedTxFee;
158158
rawTx.outputs[0].capacity = append0x(changeCapacity.toString(16));
159159

160-
let keyMap = new Map<string, string>();
160+
const keyMap = new Map<string, string>();
161161
keyMap.set(scriptToHash(masterLock), secp256k1PrivateKey);
162162
keyMap.set(scriptToHash(getBtcTimeLockScript(isMainnet)), '');
163163

0 commit comments

Comments
 (0)
Please sign in to comment.