Skip to content
Merged
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
4 changes: 2 additions & 2 deletions .github/workflows/check.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,15 @@ jobs:
uses: wagoid/commitlint-github-action@v2

- name: Code linting
run: npm run lint:check
run: npm run lint
env:
CI: true

- name: Dependency check
run: npm run depcheck

- name: Check typings
run: npm run check:types
run: npm run check

- name: Check build
run: npm run build
Expand Down
1 change: 0 additions & 1 deletion jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ export default async (): Promise<Config.InitialOptions> => {
Types.asString(process.env.JEST_BEE_FULL_URL, { name: 'JEST_BEE_FULL_URL' })
Types.asString(process.env.JEST_BEE_LIGHT_URL, { name: 'JEST_BEE_LIGHT_URL' })
Types.asString(process.env.JEST_BEE_ULTRA_LIGHT_URL, { name: 'JEST_BEE_ULTRA_LIGHT_URL' })
Types.asString(process.env.JEST_BEE_SECRET, { name: 'JEST_BEE_SECRET' })
Types.asHexString(process.env.JEST_FULL_BATCH_ID, { name: 'JEST_FULL_BATCH_ID', byteLength: 32 })
Types.asHexString(process.env.JEST_LIGHT_BATCH_ID, { name: 'JEST_LIGHT_BATCH_ID', byteLength: 32 })

Expand Down
5 changes: 2 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,8 @@
"build:types": "tsc --emitDeclarationOnly --declaration --outDir dist/types",
"build:browser": "webpack --progress",
"test": "jest --config=jest.config.ts --runInBand --verbose",
"check:types": "tsc --project tsconfig.test.json",
"lint": "eslint --fix \"src/**/*.ts\" \"test/**/*.ts\" && prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"lint:check": "eslint \"src/**/*.ts\" \"test/**/*.ts\" && prettier --check \"src/**/*.ts\" \"test/**/*.ts\"",
"check": "tsc --project tsconfig.test.json",
"lint": "eslint \"src/**/*.ts\" \"test/**/*.ts\" && prettier --check \"src/**/*.ts\" \"test/**/*.ts\"",
"depcheck": "depcheck ."
},
"dependencies": {
Expand Down
19 changes: 14 additions & 5 deletions src/bee.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,11 @@
*/
public readonly signer?: PrivateKey

/**
* Network on which the Bee node is running
*/
public readonly network: 'gnosis' | 'sepolia'

/**
* Options for making requests
* @private
Expand All @@ -171,6 +176,8 @@
this.signer = new PrivateKey(options.signer)
}

this.network = options?.network ?? 'gnosis'

this.requestOptions = {
baseURL: this.url,
timeout: options?.timeout ?? 0,
Expand Down Expand Up @@ -1035,6 +1042,7 @@
const signer = new PrivateKey(Binary.numberToUint256(start + i, 'BE'))
const socAddress = makeSOCAddress(identifier, signer.publicKey().address())
const actualProximity = 256 - Binary.proximity(socAddress.toUint8Array(), targetOverlay.toUint8Array(), 256)

if (actualProximity <= 256 - proximity) {
return signer
}
Expand Down Expand Up @@ -1456,7 +1464,7 @@
gasPrice?: NumberString | string | bigint,
options?: BeeRequestOptions,
): Promise<TransactionId> {
// TODO: check BZZ in tests

Check warning on line 1467 in src/bee.ts

View workflow job for this annotation

GitHub Actions / check (16.x)

Unexpected 'todo' comment: 'TODO: check BZZ in tests'
const amountString =
amount instanceof BZZ ? amount.toPLURString() : asNumberString(amount, { min: 1n, name: 'amount' })

Expand Down Expand Up @@ -1637,7 +1645,7 @@
requestOptions?: BeeRequestOptions,
): Promise<BatchId> {
const chainState = await this.getChainState(requestOptions)
const amount = getAmountForDuration(duration, chainState.currentPrice)
const amount = getAmountForDuration(duration, chainState.currentPrice, this.network === 'gnosis' ? 5 : 15)
const depth = getDepthForSize(size)

if (options) {
Expand All @@ -1649,7 +1657,7 @@

async getStorageCost(size: Size, duration: Duration, options?: BeeRequestOptions): Promise<BZZ> {
const chainState = await this.getChainState(options)
const amount = getAmountForDuration(duration, chainState.currentPrice)
const amount = getAmountForDuration(duration, chainState.currentPrice, this.network === 'gnosis' ? 5 : 15)
const depth = getDepthForSize(size)

return getStampCost(depth, amount)
Expand All @@ -1676,7 +1684,7 @@
) {
const batch = await this.getPostageBatch(postageBatchId, options)
const chainState = await this.getChainState(options)
const amount = getAmountForDuration(duration, chainState.currentPrice)
const amount = getAmountForDuration(duration, chainState.currentPrice, this.network === 'gnosis' ? 5 : 15)

return this.topUpBatch(batch.batchID, amount, options)
}
Expand All @@ -1689,7 +1697,7 @@
): Promise<BZZ> {
const batch = await this.getPostageBatch(postageBatchId, options)
const chainState = await this.getChainState(options)
const amount = getAmountForDuration(duration, chainState.currentPrice)
const amount = getAmountForDuration(duration, chainState.currentPrice, this.network === 'gnosis' ? 5 : 15)
const depth = getDepthForSize(size)

const currentValue = getStampCost(batch.depth, batch.amount)
Expand All @@ -1713,6 +1721,7 @@

const currentPaid = getStampCost(batch.depth, batch.amount)
const newPaid = getStampCost(depth, batch.amount)

return newPaid.minus(currentPaid)
}

Expand All @@ -1723,7 +1732,7 @@
): Promise<BZZ> {
const batch = await this.getPostageBatch(postageBatchId, options)
const chainState = await this.getChainState(options)
const amount = getAmountForDuration(duration, chainState.currentPrice)
const amount = getAmountForDuration(duration, chainState.currentPrice, this.network === 'gnosis' ? 5 : 15)

return getStampCost(batch.depth, amount)
}
Expand Down
1 change: 1 addition & 0 deletions src/feed/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@
if (data.length > 4096) {
const uploadResult = await bytes.upload(requestOptions, data, postageBatchId, options)
const rootChunk = await chunkAPI.download(requestOptions, uploadResult.reference)

return uploadSingleOwnerChunkWithWrappedChunk(
requestOptions,
signer,
Expand Down Expand Up @@ -165,7 +166,7 @@
}

export function makeFeedReader(requestOptions: BeeRequestOptions, topic: Topic, owner: EthAddress): FeedReader {
// TODO: remove after enough time has passed in deprecated version

Check warning on line 169 in src/feed/index.ts

View workflow job for this annotation

GitHub Actions / check (16.x)

Unexpected 'todo' comment: 'TODO: remove after enough time has...'
const download = async (options?: FeedUpdateOptions): Promise<FeedPayloadResult> => {
if (options?.index === undefined) {
return fetchLatestFeedUpdate(requestOptions, owner, topic)
Expand Down
1 change: 1 addition & 0 deletions src/manifest/manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,7 @@
requestOptions?: BeeRequestOptions,
): Promise<MantarayNode> {
const data = (await bee.downloadData(reference, options, requestOptions)).toUint8Array()

return this.unmarshalFromData(data)
}

Expand Down Expand Up @@ -290,7 +291,7 @@
) {
this.selfAddress = null
path = path instanceof Uint8Array ? path : ENCODER.encode(path)
// TODO: this should not be ignored

Check warning on line 294 in src/manifest/manifest.ts

View workflow job for this annotation

GitHub Actions / check (16.x)

Unexpected 'todo' comment: 'TODO: this should not be ignored'
// eslint-disable-next-line @typescript-eslint/no-this-alias
let tip: MantarayNode = this
while (path.length) {
Expand All @@ -306,7 +307,7 @@
}

if (!remainingPath.length) {
continue

Check warning on line 310 in src/manifest/manifest.ts

View workflow job for this annotation

GitHub Actions / check (16.x)

Unexpected use of continue statement
}

const newFork = new Fork(
Expand Down
1 change: 1 addition & 0 deletions src/stamper/stamper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export class Stamper {
const address = chunk.hash()
const bucket = Binary.uint16ToNumber(address, 'BE')
const height = this.buckets[bucket]

if (height >= this.maxSlot) {
throw Error('Bucket is full')
}
Expand Down
4 changes: 4 additions & 0 deletions src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,10 @@ export interface BeeOptions extends BeeRequestOptions {
* Signer object or private key of the Signer in form of either hex string or Uint8Array that will be default signer for the instance.
*/
signer?: PrivateKey | Uint8Array | string
/**
* Default gnosis when unspecified.
*/
network?: 'gnosis' | 'sepolia'
}

export interface GranteesResult {
Expand Down
1 change: 1 addition & 0 deletions src/utils/duration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ export class Duration {

private constructor(seconds: number) {
this.seconds = Math.ceil(seconds)

if (seconds <= 0) {
throw Error('Duration must be greater than 0')
}
Expand Down
1 change: 1 addition & 0 deletions src/utils/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export async function http<T>(options: BeeRequestOptions, config: AxiosRequestCo
const keys = Object.keys(requestConfig.params)
for (const key of keys) {
const value = requestConfig.params[key]

if (value === undefined) {
delete requestConfig.params[key]
}
Expand Down
1 change: 1 addition & 0 deletions src/utils/resource-locator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export class ResourceLocator {
if (Types.isString(this.raw) && this.raw.includes('.eth')) {
return this.raw
}

return new Reference(this.raw).toHex()
}
}
1 change: 1 addition & 0 deletions src/utils/size.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export class Size {

private constructor(bytes: number) {
this.bytes = Math.ceil(bytes)

if (bytes < 0) {
throw Error('Size must be at least 0')
}
Expand Down
4 changes: 2 additions & 2 deletions src/utils/stamps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ export function getStampCost(depth: number, amount: NumberString | string | bigi
export function getStampDuration(
amount: NumberString | string | bigint,
pricePerBlock: number,
blockTime = 5,
blockTime: number,
): Duration {
const amountBigInt = BigInt(asNumberString(amount))

Expand All @@ -121,7 +121,7 @@ export function getStampDuration(
* @param pricePerBlock The price per block in PLUR.
* @param blockTime The block time in seconds.
*/
export function getAmountForDuration(duration: Duration, pricePerBlock: number, blockTime = 5): bigint {
export function getAmountForDuration(duration: Duration, pricePerBlock: number, blockTime: number): bigint {
return (BigInt(duration.toSeconds()) / BigInt(blockTime)) * BigInt(pricePerBlock)
}

Expand Down
1 change: 1 addition & 0 deletions src/utils/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ export function isTag(value: unknown): value is Tag {
try {
const object = Types.asObject(value, { name: 'Tag' })
Types.asInteger(object.uid, { name: 'Tag.uid' })

return true
} catch {
return false
Expand Down
2 changes: 2 additions & 0 deletions src/utils/typed-bytes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import { Bytes } from './bytes'
import { convertCidToReference, convertReferenceToCid } from './cid'

// TODO: add JSdocs for each class

Check warning on line 5 in src/utils/typed-bytes.ts

View workflow job for this annotation

GitHub Actions / check (16.x)

Unexpected 'todo' comment: 'TODO: add JSdocs for each class'

const ENCODER = new TextEncoder()

Expand Down Expand Up @@ -103,6 +103,7 @@
static isValid(value: string): boolean {
try {
new Reference(value)

return true
} catch {
return false
Expand Down Expand Up @@ -180,6 +181,7 @@
isValid(digest: Uint8Array | string, expectedAddress: EthAddress | Uint8Array | string): boolean {
const publicKey = this.recoverPublicKey(digest)
const address = publicKey.address()

return address.equals(expectedAddress)
}
}
Expand Down
5 changes: 5 additions & 0 deletions src/utils/workaround.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,29 @@
// TODO: Remove this file after the issue is fixed

Check warning on line 1 in src/utils/workaround.ts

View workflow job for this annotation

GitHub Actions / check (16.x)

Unexpected 'todo' comment: 'TODO: Remove this file after the issue...'

export function normalizeBatchTTL(batchTTL: number) {
if (!Number.isInteger(batchTTL)) {
return 1
}

if (batchTTL < 1) {
return 1
}

if (batchTTL > 315569260) {
return 315569260
}

return batchTTL
}

export function normalizeCurrentPrice(currentPrice: number) {
if (!Number.isInteger(currentPrice)) {
return 24000
}

if (currentPrice < 24000) {
return 24000
}

return currentPrice
}
2 changes: 2 additions & 0 deletions test/integration/feed.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ test('POST feed (reader)', async () => {
await System.waitFor(
async () => {
const payload = (await feedReader.download()).payload.toUtf8()

return payload === 'Second update'
},
Dates.seconds(1),
Expand Down Expand Up @@ -59,6 +60,7 @@ test('POST feed (manifest)', async () => {
await System.waitFor(
async () => {
const payload = (await bee.downloadFile(manifest)).data.toUtf8()

return payload === 'Second update'
},
Dates.seconds(1),
Expand Down
4 changes: 3 additions & 1 deletion test/integration/stake.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,15 @@ test('POST stake', async () => {
return
}

let stakePreviously = await bee.getStake()
const stakePreviously = await bee.getStake()

let transactionId = await bee.depositStake('1')
expect(transactionId.toHex()).toHaveLength(64)

await System.waitFor(
async () => {
const stake = await bee.getStake()

return stake.eq(stakePreviously.plus('1'))
},
Dates.seconds(1),
Expand All @@ -39,6 +40,7 @@ test('POST stake', async () => {
await System.waitFor(
async () => {
const stake = await bee.getStake()

return stake.eq(stakePreviously.plus('2'))
},
Dates.seconds(1),
Expand Down
8 changes: 4 additions & 4 deletions test/integration/stamp.ux.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@
})

test('Utils.getAmountForDuration', () => {
expect(Utils.getAmountForDuration(Duration.fromHours(25), 24000)).toBe((414720000n / 24n) * 25n)
expect(Utils.getAmountForDuration(Duration.fromDays(1), 24000)).toBe(414720000n)
expect(Utils.getAmountForDuration(Duration.fromWeeks(1), 24000)).toBe(414720000n * 7n)
expect(Utils.getAmountForDuration(Duration.fromYears(1), 24000)).toBe(414720000n * 365n)
expect(Utils.getAmountForDuration(Duration.fromHours(25), 24000, 5)).toBe((414720000n / 24n) * 25n)
expect(Utils.getAmountForDuration(Duration.fromDays(1), 24000, 5)).toBe(414720000n)
expect(Utils.getAmountForDuration(Duration.fromWeeks(1), 24000, 5)).toBe(414720000n * 7n)
expect(Utils.getAmountForDuration(Duration.fromYears(1), 24000, 5)).toBe(414720000n * 365n)
})

test('bee.getStorageCost', async () => {
Expand Down Expand Up @@ -45,7 +45,7 @@
)
expect(cost.toSignificantDigits(3)).toBe('72.011')

await expect(() =>

Check failure on line 48 in test/integration/stamp.ux.spec.ts

View workflow job for this annotation

GitHub Actions / check (16.x)

Functions that return promises must be async
bee.getSizeExtensionCost(
'f8b2ad296d64824a8fe51a33ff15fe8668df13a20ad3d4eea4bb97ca600029aa',
Size.fromGigabytes(1),
Expand All @@ -72,7 +72,7 @@
await bee.extendStorageDuration(batchId, Duration.fromDays(1))
await bee.extendStorageSize(batchId, Size.fromGigabytes(8))
await bee.extendStorageSize(batchId, Size.fromGigabytes(24))
await expect(() => bee.extendStorageSize(batchId, Size.fromGigabytes(1))).rejects.toThrow(

Check failure on line 75 in test/integration/stamp.ux.spec.ts

View workflow job for this annotation

GitHub Actions / check (16.x)

Functions that return promises must be async
'New depth has to be greater than the original depth',
)
})
Expand Down
2 changes: 1 addition & 1 deletion test/integration/status.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ test('GET wallet', async () => {
}

const wallet = await bee.getWalletBalance()
expect(parseFloat(wallet.bzzBalance.toDecimalString())).toBeGreaterThan(150)
expect(parseFloat(wallet.bzzBalance.toDecimalString())).toBeGreaterThan(50)
expect(parseFloat(wallet.bzzBalance.toDecimalString())).toBeLessThan(200)
expect(parseFloat(wallet.nativeTokenBalance.toDecimalString())).toBeGreaterThan(4)
expect(parseFloat(wallet.nativeTokenBalance.toDecimalString())).toBeLessThan(5)
Expand Down
3 changes: 3 additions & 0 deletions test/mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,11 +92,14 @@ interface MockedCall {

export async function mocked(runnable: (bee: Bee) => Promise<void>): Promise<MockedCall[]> {
const calls: MockedCall[] = []

return new Promise(resolve => {
const server = createServer((req, res) => {
const identifier = (req.method || 'GET') + ' ' + (req.url || '/')
calls.push({ method: req.method || 'GET', url: req.url || '/', headers: req.headers })

const response = responses.get(identifier)

if (!response) {
res.end('Not found - ' + identifier)
}
Expand Down
6 changes: 4 additions & 2 deletions test/unit/utils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,10 @@ test('Utils.getStampMaximumCapacityBytes', () => {
})

test('Utils.getStampDuration', () => {
expect(Utils.getStampDuration(414720000n, 24000).toSeconds()).toBe(86400)
expect(Utils.getStampDuration(Utils.getAmountForDuration(Duration.fromDays(365), 24000), 24000).toDays()).toBe(365)
expect(Utils.getStampDuration(414720000n, 24000, 5).toSeconds()).toBe(86400)
expect(Utils.getStampDuration(Utils.getAmountForDuration(Duration.fromDays(365), 24000, 5), 24000, 5).toDays()).toBe(
365,
)
})

test('Utils.getStampUsage', () => {
Expand Down
7 changes: 2 additions & 5 deletions test/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,8 @@ export function makeBee() {
if (currentBeeMode() === 'dev') {
return new BeeDev('http://localhost:1633')
}
return new Bee(selectBeeUrl(), {
headers: {
authorization: Types.asString(process.env.JEST_BEE_SECRET),
},
})

return new Bee(selectBeeUrl())
}

export function batch() {
Expand Down
Loading