Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
dist/**
# upload fixtures — sample project trees used as test payloads, not real source
test/data/**
72 changes: 13 additions & 59 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ module.exports = {
parserOptions: {
sourceType: 'module',
ecmaVersion: 2018,
// required for the type-aware rules below (no-floating-promises / no-misused-promises)
project: ['./tsconfig.json', './tsconfig.test.json'],
tsconfigRootDir: __dirname,
},
env: {
jest: true,
Expand All @@ -13,77 +16,28 @@ module.exports = {
},
plugins: ['jest'],
rules: {
'array-bracket-newline': ['error', 'consistent'],
strict: ['error', 'safe'],
curly: 'error',
'block-scoped-var': 'error',
complexity: 'warn',
'default-case': 'error',
'dot-notation': 'warn',
// --- real bug protection only; formatting is left to Prettier and correctness to tsc ---
curly: ['error', 'multi-line'],
eqeqeq: 'error',
'guard-for-in': 'warn',
'linebreak-style': ['warn', 'unix'],
'no-alert': 'error',
'default-case': 'error',
'guard-for-in': 'error',
'no-case-declarations': 'error',
'no-console': 'error',
'no-constant-condition': 'error',
'no-div-regex': 'error',
'no-empty': 'warn',
'no-empty-pattern': 'error',
'no-implicit-coercion': 'error',
'prefer-arrow-callback': 'warn',
'no-labels': 'error',
'no-loop-func': 'error',
'no-nested-ternary': 'warn',
'no-script-url': 'error',
'no-warning-comments': 'warn',
'quote-props': ['error', 'as-needed'],
'require-yield': 'error',
'max-nested-callbacks': ['error', 4],
'max-depth': ['error', 4],
'require-await': 'error',
'space-before-function-paren': [
'error',
{
anonymous: 'never',
named: 'never',
asyncArrow: 'always',
},
],
'padding-line-between-statements': [
'error',
{ blankLine: 'always', prev: '*', next: 'if' },
{ blankLine: 'always', prev: '*', next: 'function' },
{ blankLine: 'always', prev: '*', next: 'return' },
],
'no-useless-constructor': 'off',
'no-dupe-class-members': 'off',
'no-unused-expressions': 'off',
curly: ['error', 'multi-line'],
'object-curly-spacing': ['error', 'always'],
'comma-dangle': ['error', 'always-multiline'],
'@typescript-eslint/no-useless-constructor': 'error',
'@typescript-eslint/no-unused-expressions': 'error',
'@typescript-eslint/member-delimiter-style': [
'error',
{
multiline: {
delimiter: 'none',
requireLast: true,
},
singleline: {
delimiter: 'comma',
requireLast: false,
},
},
],
// the headline reason to keep ESLint: tsc cannot catch these
'@typescript-eslint/no-floating-promises': 'error',
'@typescript-eslint/no-misused-promises': 'error',
},
overrides: [
{
files: ['*.spec.ts'],
// tests legitimately assert on values they have set up
files: ['test/**/*.ts'],
rules: {
// '@typescript-eslint/ban-ts-ignore': 'off',
'max-nested-callbacks': ['error', 10], // allow describe/it nesting
'@typescript-eslint/no-non-null-assertion': 'off',
},
},
],
Expand Down
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-jest": "^27.1.5",
"eslint-plugin-prettier": "^4.2.1",
"eslint-plugin-unused-imports": "^2.0.0",
"husky": "^4.3.6",
"jest": "^29.3.1",
"prettier": "^2.7.1",
Expand Down
5 changes: 3 additions & 2 deletions src/command/access/history.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,14 @@ export class History extends AccessCommand implements LeafCommand {
const accessHistory = new AccessHistory(this.commandConfig, this.console)
const events = accessHistory.getEvents(this.listName).sort((a, b) => b.createdAt - a.createdAt)

if (events.length === 0) {
const lastEvent = events[0]

if (!lastEvent) {
this.console.error(errorText(`Grantee list with name '${this.listName}' does not exist!`))

exit(1)
}

const lastEvent = events[0]
this.console.log(createKeyValue('Latest history address', lastEvent.historyAddress))
this.console.log(createKeyValue('Latest grantee list reference', lastEvent.granteeListRef))

Expand Down
4 changes: 4 additions & 0 deletions src/command/download.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ export class Download extends RootCommand implements LeafCommand {

if (this.manifestDownload.access) {
const [publisher, historyAddress] = this.manifestDownload.access.split(':')
if (!publisher || !historyAddress) {
this.console.error('Invalid access format. Expected format: publisher:historyAddress')
process.exit(1)
}
const responseAct = await this.bee.downloadFile(this.address.hash, this.manifestDownload.destination, {
actPublisher: publisher,
actHistoryAddress: historyAddress,
Expand Down
11 changes: 9 additions & 2 deletions src/command/feed/feed-command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export class FeedCommand extends RootCommand {
this.console.log(createKeyValue('Feed Manifest URL', manifestUrl))

if (this.qr) {
printQRCodeWithLabel(publicUrl(manifestUrl), 'QR for Manifest URL', this.console)
await printQRCodeWithLabel(publicUrl(manifestUrl), 'QR for Manifest URL', this.console)
}

this.console.quiet(manifest.toHex())
Expand Down Expand Up @@ -92,7 +92,14 @@ export class FeedCommand extends RootCommand {
this.identity = await pickIdentity(this.commandConfig, this.console)
}

return identities[this.identity]
const identity = identities[this.identity]

if (!identity) {
this.console.error('The provided identity does not exist.')
exit(1)
}

return identity
}

private async writeFeed(stamp: string, wallet: Wallet, topic: Topic, chunkReference: Reference): Promise<FeedInfo> {
Expand Down
2 changes: 1 addition & 1 deletion src/command/pinning/pinning-command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { exit } from 'process'
import { RootCommand } from '../root-command'

export class PinningCommand extends RootCommand {
protected async init(): Promise<void> {
protected override async init(): Promise<void> {
super.init()

if (await this.bee.isGateway()) {
Expand Down
2 changes: 1 addition & 1 deletion src/command/pss/pss-command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export class PssCommand extends RootCommand {
})
public topicString!: string

public init(): void {
public override init(): void {
super.init()

this.topic = Topic.fromString(this.topicString).toHex()
Expand Down
3 changes: 2 additions & 1 deletion src/command/root-command/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,8 @@ export class RootCommand {
const latestVersionCheck = getLatestVersionCheck(this.commandConfig)

if (latestVersionCheck === null) {
checkForUpdates(this.commandConfig)
// fire-and-forget: a version check must not block CLI startup; it swallows its own errors
void checkForUpdates(this.commandConfig)
} else if (latestVersionCheck.latestVersion !== PackageJson.version) {
this.console.log(
warningText(
Expand Down
4 changes: 2 additions & 2 deletions src/command/stake/recover.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@
const { signer } = await makeReadySigner(wallet.getPrivateKeyString(), this.jsonRpcUrl)
const contract = new Contract(address, abi, signer)

const isPaused = await contract.paused()
const isPaused = await contract.paused!()

Check warning on line 59 in src/command/stake/recover.ts

View workflow job for this annotation

GitHub Actions / check (18.x)

Forbidden non-null assertion

if (!isPaused) {
this.console.error('The contract is not paused. No need to recover xBZZ.')
Expand All @@ -65,6 +65,6 @@
}

this.console.log('Recovering xBZZ from paused staking contract...')
await contract.migrateStake()
await contract.migrateStake!()

Check warning on line 68 in src/command/stake/recover.ts

View workflow job for this annotation

GitHub Actions / check (18.x)

Forbidden non-null assertion
}
}
2 changes: 1 addition & 1 deletion src/command/upload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ export class Upload extends RootCommand implements LeafCommand {
}

if (this.qr) {
printQRCodeWithLabel(publicUrl(url), 'QR for URL', this.console)
await printQRCodeWithLabel(publicUrl(url), 'QR for URL', this.console)
}

if (this.usingACT()) {
Expand Down
4 changes: 2 additions & 2 deletions src/command/utility/create-batch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@

this.console.log(`Approving spending of ${cost.toDecimalString()} BZZ to ${wallet.address}`)
const tokenProxyContract = new Contract(Contracts.bzz, ABI.tokenProxy, signer)
const approve = await tokenProxyContract.approve(Contracts.postageStamp, cost.toPLURBigInt().toString(), {
const approve = await tokenProxyContract.approve!(Contracts.postageStamp, cost.toPLURBigInt().toString(), {

Check warning on line 68 in src/command/utility/create-batch.ts

View workflow job for this annotation

GitHub Actions / check (18.x)

Forbidden non-null assertion
gasLimit: 130_000,
type: 2,
maxFeePerGas: Numbers.make('2gwei'),
Expand All @@ -77,7 +77,7 @@
this.console.log(`Creating postage batch for ${wallet.address} with depth ${this.depth} and amount ${this.amount}`)
const postageStampContract = new Contract(Contracts.postageStamp, ABI.postageStamp, signer)
const createBatchArgs = [signer.address, this.amount, this.depth, 16, `0x${Strings.randomHex(64)}`, false]
const createBatch = await postageStampContract.createBatch(...createBatchArgs, {
const createBatch = await postageStampContract.createBatch!(...createBatchArgs, {

Check warning on line 80 in src/command/utility/create-batch.ts

View workflow job for this annotation

GitHub Actions / check (18.x)

Forbidden non-null assertion
gasLimit: 1_000_000,
type: 2,
maxFeePerGas: Numbers.make('3gwei'),
Expand Down
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ if (setDefaultResultOrder) {
setDefaultResultOrder('ipv4first')
}

cli({
// fire-and-forget entry point: cli() reports its own failures via the errorHandler above
void cli({
rootCommandClasses,
optionParameters,
printer,
Expand Down
2 changes: 1 addition & 1 deletion src/service/access/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export class AccessHistory {
public getLatestEvent(granteeListName: string): AccessHistoryEvent | null {
const events = this.getEvents(granteeListName).sort((a, b) => b.createdAt - a.createdAt)

return events.length > 0 ? events[0] : null
return events[0] ?? null
}

public getEventsByType(granteeListName: string, eventType: AccessHistoryOperation): AccessHistoryEvent[] {
Expand Down
4 changes: 2 additions & 2 deletions src/service/identity/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@ export function getPrintableIdentityType(type: IdentityType): string {
}
}

export function isSimpleWallet(wallet: IdentityWallet, identityType: IdentityType): wallet is SimpleWallet {
export function isSimpleWallet(_wallet: IdentityWallet, identityType: IdentityType): _wallet is SimpleWallet {
return identityType === IdentityType.simple
}

export function isV3Wallet(wallet: IdentityWallet, identityType: IdentityType): wallet is V3Keystore {
export function isV3Wallet(_wallet: IdentityWallet, identityType: IdentityType): _wallet is V3Keystore {
return identityType === IdentityType.v3
}

Expand Down
2 changes: 1 addition & 1 deletion src/service/stamp/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export async function pickStamp(bee: Bee, console: CommandLog): Promise<string>
const value = await console.promptList(choices, 'Please select a stamp for this action')
const [hex] = value.split(' ')

return hex
return hex ?? value
}

interface PrintStampSettings {
Expand Down
2 changes: 1 addition & 1 deletion src/utils/bzz-address.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export class BzzAddress {
throw new CommandLineError('Invalid BZZ path: cannot contain multiple continuous slashes')
}
const parts = url.split('/')
this.hash = parts[0].toLowerCase()
this.hash = (parts[0] ?? '').toLowerCase()

if (this.hash.startsWith('0x')) {
this.hash = this.hash.slice(2)
Expand Down
4 changes: 2 additions & 2 deletions src/utils/rpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
address = `0x${address}`
}
const contract = new Contract(tokenAddress, ABI.bzz, provider)
const balance = await contract.balanceOf(address)
const balance = await contract.balanceOf!(address)

Check warning on line 22 in src/utils/rpc.ts

View workflow job for this annotation

GitHub Actions / check (18.x)

Forbidden non-null assertion

return balance.toString()
}
Expand Down Expand Up @@ -99,7 +99,7 @@
}

const bzz = new Contract(Contracts.bzz, ABI.bzz, signer)
const transaction = await bzz.transfer(to, value, { gasPrice })
const transaction = await bzz.transfer!(to, value, { gasPrice })

Check warning on line 102 in src/utils/rpc.ts

View workflow job for this annotation

GitHub Actions / check (18.x)

Forbidden non-null assertion
const receipt = await transaction.wait(1)

if (receipt === null) {
Expand Down
5 changes: 2 additions & 3 deletions src/utils/text.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,11 @@ export function printDivided<T>(
printFn: (item: T, console: CommandLog) => void,
console: CommandLog,
): void {
for (let i = 0; i < items.length; i++) {
const item = items[i]
items.forEach((item, i) => {
printFn(item, console)

if (i !== items.length - 1) {
console.divider()
}
}
})
}
12 changes: 6 additions & 6 deletions test/command/addresses.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@ describeCommand(

it('should be splittable in quiet mode', async () => {
await invokeTestCli(['addresses', '-q'])
expect(consoleMessages[0].split(' ')[1]).toMatch(/[0-9a-f]{20}/i)
expect(consoleMessages[1].split(' ')[1]).toMatch(/[0-9a-f]{20}/i)
expect(consoleMessages[2].split(' ')[1]).toMatch(/[0-9a-f]{20}/i)
expect(consoleMessages[3].split(' ')[1]).toMatch(/[0-9a-f]{20}/i)
expect(consoleMessages[4].split(' ')[1]).toContain('/ip4/')
expect(consoleMessages[5].split(' ')[1]).toMatch(/[0-9a-f]{20}/i)
expect(consoleMessages[0]!.split(' ')[1]).toMatch(/[0-9a-f]{20}/i)
expect(consoleMessages[1]!.split(' ')[1]).toMatch(/[0-9a-f]{20}/i)
expect(consoleMessages[2]!.split(' ')[1]).toMatch(/[0-9a-f]{20}/i)
expect(consoleMessages[3]!.split(' ')[1]).toMatch(/[0-9a-f]{20}/i)
expect(consoleMessages[4]!.split(' ')[1]).toContain('/ip4/')
expect(consoleMessages[5]!.split(' ')[1]).toMatch(/[0-9a-f]{20}/i)
})
},
{ configFileName: 'addresses' },
Expand Down
2 changes: 1 addition & 1 deletion test/command/feed.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ describeCommand(
it('should print feed using address only', async () => {
// create identity
await invokeTestCli(['identity', 'create', 'test2', '--password', 'test'])
const address = getLastMessage().split(' ')[1]
const address = getLastMessage().split(' ')[1] ?? ''
// upload
await invokeTestCli([
'feed',
Expand Down
2 changes: 1 addition & 1 deletion test/command/manifest.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ expect.extend({
})

async function runAndGetManifest(argv: string[]): Promise<string> {
if (['create', 'add', 'sync', 'merge', 'remove'].includes(argv[1])) {
if (['create', 'add', 'sync', 'merge', 'remove'].includes(argv[1] ?? '')) {
argv = [...argv, ...getStampOption()]
}
const commandBuilder = await invokeTestCli(argv)
Expand Down
5 changes: 3 additions & 2 deletions test/command/pss.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ describeCommand('Test PSS command', ({ getNthLastMessage, getLastMessage }) => {
unlinkSync('test/testconfig/out.txt')
}
writeFileSync('test/testconfig/in.txt', 'Message in a file')
invokeTestCli([
// start the receiver listening, then send to trigger it, then await the receiver
const receivePromise = invokeTestCli([
'pss',
'receive',
'--topic-string',
Expand All @@ -68,7 +69,7 @@ describeCommand('Test PSS command', ({ getNthLastMessage, getLastMessage }) => {
'test/testconfig/in.txt',
...getStampOption(),
])
await System.sleepMillis(4000)
await receivePromise
expect(existsSync('test/testconfig/out.txt')).toBeTruthy()
const messageFromFile = readFileSync('test/testconfig/out.txt', 'ascii')
expect(messageFromFile).toBe('Message in a file')
Expand Down
8 changes: 4 additions & 4 deletions test/command/upload.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ describeCommand(
const uploadFolderPath = `${__dirname}/../testpage`
const commandBuilder = await invokeTestCli([commandKey, uploadFolderPath, ...getStampOption()])

expect(commandBuilder.initedCommands[0].command.name).toBe('upload')
const command = commandBuilder.initedCommands[0].command as Upload
expect(commandBuilder.initedCommands[0]!.command.name).toBe('upload')
const command = commandBuilder.initedCommands[0]!.command as Upload
expect(command.result.getOrThrow().toHex().length).toBe(64)
})

Expand All @@ -51,8 +51,8 @@ describeCommand(
const uploadFolderPath = `${__dirname}/../testpage/images/swarm.png`
const commandBuilder = await invokeTestCli([commandKey, uploadFolderPath, ...getStampOption()])

expect(commandBuilder.initedCommands[0].command.name).toBe('upload')
const command = commandBuilder.initedCommands[0].command as Upload
expect(commandBuilder.initedCommands[0]!.command.name).toBe('upload')
const command = commandBuilder.initedCommands[0]!.command as Upload
expect(command.result.getOrThrow().toHex().length).toBe(64)
})

Expand Down
Loading
Loading