Skip to content

Commit 7cba162

Browse files
committed
chore: npm run lint:fix
Signed-off-by: Miroslav Bajtoš <oss@bajtos.net>
1 parent fb57c93 commit 7cba162

20 files changed

+339
-264
lines changed

.github/workflows/ci.yml

+3-2
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@ jobs:
88
runs-on: ubuntu-latest
99
steps:
1010
- uses: actions/checkout@v4
11-
- run: curl -L https://github.com/filecoin-station/zinnia/releases/download/${{ env.ZINNIA_VERSION }}/zinnia-linux-x64.tar.gz | tar -xz
11+
- run:
12+
curl -L https://github.com/filecoin-station/zinnia/releases/download/${{
13+
env.ZINNIA_VERSION }}/zinnia-linux-x64.tar.gz | tar -xz
1214
- run: ./zinnia run test.js
1315

1416
test-windows:
@@ -31,4 +33,3 @@ jobs:
3133
- uses: actions/setup-node@v4
3234
- run: npm ci
3335
- run: npm lint
34-

README.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
# spark
2+
23
SP Retrieval Checker Module
34

45
- [Roadmap](https://pl-strflt.notion.site/SPARK-Roadmap-ac729c11c49b409fbec54751d1bc6c8a)
@@ -33,5 +34,4 @@ $ ./release.sh 1.0.0
3334

3435
Use GitHub's changelog feature to fill out the release notes.
3536

36-
Publish the new release and let the CI/CD workflow upload the sources
37-
to IPFS & IPNS.
37+
Publish the new release and let the CI/CD workflow upload the sources to IPFS & IPNS.

deps.ts

+4-5
Original file line numberDiff line numberDiff line change
@@ -8,23 +8,22 @@
88
export { encodeHex } from 'https://deno.land/std@0.203.0/encoding/hex.ts'
99
export { decodeBase64 } from 'https://deno.land/std@0.203.0/encoding/base64.ts'
1010
export { decode as decodeVarint } from 'https://deno.land/x/varint@v2.0.0/varint.ts'
11-
export { retry } from 'https://deno.land/std@0.203.0/async/retry.ts';
12-
11+
export { retry } from 'https://deno.land/std@0.203.0/async/retry.ts'
1312

1413
// Deno Bundle does not support npm dependencies, we have to load them via CDN
15-
export { ethers } from "https://cdn.jsdelivr.net/npm/ethers@6.13.5/dist/ethers.min.js";
14+
export { ethers } from 'https://cdn.jsdelivr.net/npm/ethers@6.13.5/dist/ethers.min.js'
1615
export { CarBlockIterator } from 'https://cdn.skypack.dev/@ipld/car@5.3.2/?dts'
1716
export {
1817
UnsupportedHashError,
1918
HashMismatchError,
20-
validateBlock
19+
validateBlock,
2120
} from 'https://cdn.skypack.dev/@web3-storage/car-block-validator@1.2.0/?dts'
2221
// cdn.skypack.dev cannot resolve import from @noble/hashes
2322
// jsdelivr.net seems to work better, it's also recommended by drand-client
2423
export {
2524
fetchBeaconByTime,
2625
HttpChainClient,
27-
HttpCachingChain
26+
HttpCachingChain,
2827
} from 'https://cdn.jsdelivr.net/npm/drand-client@1.2.6/index.js/+esm'
2928

3029
export { assertOkResponse } from 'https://cdn.skypack.dev/assert-ok-response@1.0.0/?dts'

lib/activity-state.js

+3-3
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,18 @@
44
export class ActivityState {
55
#healthy = null
66

7-
onOutdatedClient () {
7+
onOutdatedClient() {
88
this.onError('SPARK is outdated. Please upgrade Filecoin Station to the latest version.')
99
}
1010

11-
onError (msg) {
11+
onError(msg) {
1212
if (this.#healthy === null || this.#healthy) {
1313
this.#healthy = false
1414
Zinnia.activity.error(msg ?? 'SPARK failed reporting retrieval')
1515
}
1616
}
1717

18-
onHealthy () {
18+
onHealthy() {
1919
if (this.#healthy === null) {
2020
this.#healthy = true
2121
Zinnia.activity.info('SPARK started reporting retrievals')

lib/drand-client.js

+5-8
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,4 @@
1-
import {
2-
fetchBeaconByTime,
3-
HttpChainClient,
4-
HttpCachingChain
5-
} from '../vendor/deno-deps.js'
1+
import { fetchBeaconByTime, HttpChainClient, HttpCachingChain } from '../vendor/deno-deps.js'
62

73
// See https://docs.filecoin.io/networks/mainnet#genesis
84
const FIL_MAINNET_GENESIS_TS = new Date('2020-08-24T22:00:00Z').getTime()
@@ -18,8 +14,9 @@ const DRAND_OPTIONS = {
1814
chainVerificationParams: {
1915
// quicknet
2016
chainHash: '52db9ba70e0cc0f6eaf7803dd07447a1f5477735fd3f661792ba94600c84e971',
21-
publicKey: '83cf0f2896adee7eb8b5f01fcad3912212c437e0073e911fb90022d3e760183c8c4b450b6a0a6c3ac6a5776a2d1064510d1fec758c921cc22b0e17e63aaf4bcb5ed66304de9cf809bd274ca73bab4af5a6e9c76a4bc09e76eae8991ef5ece45a'
22-
}
17+
publicKey:
18+
'83cf0f2896adee7eb8b5f01fcad3912212c437e0073e911fb90022d3e760183c8c4b450b6a0a6c3ac6a5776a2d1064510d1fec758c921cc22b0e17e63aaf4bcb5ed66304de9cf809bd274ca73bab4af5a6e9c76a4bc09e76eae8991ef5ece45a',
19+
},
2320
}
2421

2522
const DRAND_URL = `https://api2.drand.sh/${DRAND_OPTIONS.chainVerificationParams.chainHash}`
@@ -29,7 +26,7 @@ const client = new HttpChainClient(chain, DRAND_OPTIONS)
2926
/**
3027
* @param {number} roundStartEpoch
3128
*/
32-
export async function getRandomnessForSparkRound (roundStartEpoch) {
29+
export async function getRandomnessForSparkRound(roundStartEpoch) {
3330
const roundStartedAt = roundStartEpoch * FIL_MAINNET_BLOCK_TIME + FIL_MAINNET_GENESIS_TS
3431
const beacon = await fetchBeaconByTime(client, roundStartedAt)
3532
return beacon.randomness

lib/http-assertions.js

+7-4
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,14 @@ export { assertOkResponse } from '../vendor/deno-deps.js'
66
* @param {Response} res
77
* @param {string} [errorMsg]
88
*/
9-
export async function assertRedirectResponse (res, errorMsg) {
9+
export async function assertRedirectResponse(res, errorMsg) {
1010
if ([301, 302, 303, 304, 307, 308].includes(res.status)) {
1111
const location = res.headers.get('location')
1212
if (!location) {
13-
const msg = (errorMsg ? errorMsg + ' ' : '') +
13+
const msg =
14+
(errorMsg ? errorMsg + ' ' : '') +
1415
'The server response is missing the Location header. Headers found:\n' +
15-
Array.from(res.headers.keys()).join('\n')
16+
Array.from(res.headers.keys()).join('\n')
1617
throw new AssertionError(msg)
1718
}
1819
return
@@ -22,7 +23,9 @@ export async function assertRedirectResponse (res, errorMsg) {
2223
try {
2324
body = await res.text()
2425
} catch {}
25-
const err = new Error(`${errorMsg ?? 'Server did not respond with redirect'} (${res.status}): ${body?.trimEnd()}`)
26+
const err = new Error(
27+
`${errorMsg ?? 'Server did not respond with redirect'} (${res.status}): ${body?.trimEnd()}`,
28+
)
2629
err.statusCode = res.status
2730
err.serverMessage = body
2831
throw err

lib/ipni-client.js

+8-8
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import { decodeBase64, decodeVarint, pRetry, assertOkResponse } from '../vendor/
99
* provider?: { address: string; protocol: string };
1010
* }>}
1111
*/
12-
export async function queryTheIndex (cid, providerId) {
12+
export async function queryTheIndex(cid, providerId) {
1313
let providerResults
1414
try {
1515
providerResults = await pRetry(() => getRetrievalProviders(cid), {
@@ -20,13 +20,13 @@ export async function queryTheIndex (cid, providerId) {
2020
onFailedAttempt: (error) => {
2121
console.error(error)
2222
console.error('IPNI query failed, retrying...')
23-
}
23+
},
2424
})
2525
console.log('IPNI returned %s provider results', providerResults.length)
2626
} catch (err) {
2727
console.error('IPNI query failed.', err)
2828
return {
29-
indexerResult: typeof err.statusCode === 'number' ? `ERROR_${err.statusCode}` : 'ERROR_FETCH'
29+
indexerResult: typeof err.statusCode === 'number' ? `ERROR_${err.statusCode}` : 'ERROR_FETCH',
3030
}
3131
}
3232

@@ -39,7 +39,7 @@ export async function queryTheIndex (cid, providerId) {
3939
0x900: 'bitswap',
4040
0x910: 'graphsync',
4141
0x0920: 'http',
42-
4128768: 'graphsync'
42+
4128768: 'graphsync',
4343
}[protocolCode]
4444

4545
const address = p.Provider.Addrs[0]
@@ -49,14 +49,14 @@ export async function queryTheIndex (cid, providerId) {
4949
case 'http':
5050
return {
5151
indexerResult: 'OK',
52-
provider: { address, protocol }
52+
provider: { address, protocol },
5353
}
5454

5555
case 'graphsync':
5656
if (!graphsyncProvider) {
5757
graphsyncProvider = {
5858
address: `${address}/p2p/${p.Provider.ID}`,
59-
protocol
59+
protocol,
6060
}
6161
}
6262
}
@@ -65,15 +65,15 @@ export async function queryTheIndex (cid, providerId) {
6565
console.log('HTTP protocol is not advertised, falling back to Graphsync.')
6666
return {
6767
indexerResult: 'HTTP_NOT_ADVERTISED',
68-
provider: graphsyncProvider
68+
provider: graphsyncProvider,
6969
}
7070
}
7171

7272
console.log('All advertisements are from other miners or for unsupported protocols.')
7373
return { indexerResult: 'NO_VALID_ADVERTISEMENT' }
7474
}
7575

76-
async function getRetrievalProviders (cid) {
76+
async function getRetrievalProviders(cid) {
7777
const url = `https://cid.contact/cid/${encodeURIComponent(cid)}`
7878
const res = await fetch(url)
7979
await assertOkResponse(res)

lib/miner-info.js

+22-14
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,15 @@ import { getIndexProviderPeerIdFromSmartContract } from './smart-contract-client
88
* @param {function} [options.rpcFn]
99
* @returns {Promise<string>} The chain head Cid
1010
*/
11-
async function getChainHead ({ maxAttempts = 5, rpcFn } = {}) {
11+
async function getChainHead({ maxAttempts = 5, rpcFn } = {}) {
1212
try {
1313
const res = await retry(() => (rpcFn ?? rpc)('Filecoin.ChainHead'), {
1414
// The maximum amount of attempts until failure.
1515
maxAttempts,
1616
// The initial and minimum amount of milliseconds between attempts.
1717
minTimeout: 5_000,
1818
// How much to backoff after each retry.
19-
multiplier: 1.5
19+
multiplier: 1.5,
2020
})
2121
return res.Cids
2222
} catch (err) {
@@ -35,12 +35,15 @@ async function getChainHead ({ maxAttempts = 5, rpcFn } = {}) {
3535
* @param {number} [options.maxAttempts]
3636
* @returns {Promise<string>} Miner's PeerId, e.g. `12D3KooWMsPmAA65yHAHgbxgh7CPkEctJHZMeM3rAvoW8CZKxtpG`
3737
*/
38-
export async function getIndexProviderPeerId (minerId, { maxAttempts = 5, smartContract, rpcFn } = {}) {
38+
export async function getIndexProviderPeerId(
39+
minerId,
40+
{ maxAttempts = 5, smartContract, rpcFn } = {},
41+
) {
3942
try {
40-
// Make a concurrent request to both sources: FilecoinMinerInfo and smart contract
43+
// Make a concurrent request to both sources: FilecoinMinerInfo and smart contract
4144
const [minerInfoResult, contractResult] = await Promise.all([
4245
getIndexProviderPeerIdFromFilecoinMinerInfo(minerId, { maxAttempts, rpcFn }),
43-
getIndexProviderPeerIdFromSmartContract(minerId, { smartContract })
46+
getIndexProviderPeerIdFromSmartContract(minerId, { smartContract }),
4447
])
4548
// Check contract result first
4649
if (contractResult) {
@@ -55,11 +58,13 @@ export async function getIndexProviderPeerId (minerId, { maxAttempts = 5, smartC
5558
}
5659

5760
// Handle the case where both failed
58-
throw new Error(`Failed to obtain Miner's Index Provider PeerID.\nSmartContract query result: ${contractResult}\nStateMinerInfo query result: ${minerInfoResult}`)
61+
throw new Error(
62+
`Failed to obtain Miner's Index Provider PeerID.\nSmartContract query result: ${contractResult}\nStateMinerInfo query result: ${minerInfoResult}`,
63+
)
5964
} catch (error) {
6065
console.error('Error fetching PeerID:', error)
6166
throw Error(`Error fetching PeerID for miner ${minerId}.`, {
62-
cause: error
67+
cause: error,
6368
})
6469
}
6570
}
@@ -71,7 +76,10 @@ export async function getIndexProviderPeerId (minerId, { maxAttempts = 5, smartC
7176
* @param {function} [options.rpcFn]
7277
* @returns {Promise<string>} Miner's PeerId, e.g. `12D3KooWMsPmAA65yHAHgbxgh7CPkEctJHZMeM3rAvoW8CZKxtpG`
7378
*/
74-
export async function getIndexProviderPeerIdFromFilecoinMinerInfo (minerId, { maxAttempts = 5, rpcFn } = {}) {
79+
export async function getIndexProviderPeerIdFromFilecoinMinerInfo(
80+
minerId,
81+
{ maxAttempts = 5, rpcFn } = {},
82+
) {
7583
const chainHead = await getChainHead({ maxAttempts, rpcFn })
7684
try {
7785
const res = await retry(() => (rpcFn ?? rpc)('Filecoin.StateMinerInfo', minerId, chainHead), {
@@ -80,7 +88,7 @@ export async function getIndexProviderPeerIdFromFilecoinMinerInfo (minerId, { ma
8088
// The initial and minimum amount of milliseconds between attempts.
8189
minTimeout: 5_000,
8290
// How much to backoff after each retry.
83-
multiplier: 1.5
91+
multiplier: 1.5,
8492
})
8593
return res.PeerId
8694
} catch (err) {
@@ -97,23 +105,23 @@ export async function getIndexProviderPeerIdFromFilecoinMinerInfo (minerId, { ma
97105
* @param {string} method
98106
* @param {unknown[]} params
99107
*/
100-
async function rpc (method, ...params) {
108+
async function rpc(method, ...params) {
101109
const req = new Request(RPC_URL, {
102110
method: 'POST',
103111
headers: {
104112
'content-type': 'application/json',
105113
accepts: 'application/json',
106-
authorization: `Bearer ${RPC_AUTH}`
114+
authorization: `Bearer ${RPC_AUTH}`,
107115
},
108116
body: JSON.stringify({
109117
jsonrpc: '2.0',
110118
id: 1,
111119
method,
112-
params
113-
})
120+
params,
121+
}),
114122
})
115123
const res = await fetch(req, {
116-
signal: AbortSignal.timeout(60_000)
124+
signal: AbortSignal.timeout(60_000),
117125
})
118126

119127
if (!res.ok) {

lib/multiaddr.js

+16-19
Original file line numberDiff line numberDiff line change
@@ -2,48 +2,46 @@
22
* @param {string} addr Multiaddr, e.g. `/ip4/127.0.0.1/tcp/80/http`
33
* @returns {string} Parsed URI, e.g. `http://127.0.0.1:80`
44
*/
5-
export function multiaddrToHttpUrl (addr) {
5+
export function multiaddrToHttpUrl(addr) {
66
const [multiAddr, httpPathMultiAddr] = addr.split('/http-path')
77
const [, hostType, hostValue, ...multiAddrParts] = multiAddr.split('/')
88
let scheme, path, rest, port
99
if (addr.includes('/http-path')) {
10-
[scheme, ...rest] = multiAddrParts
10+
;[scheme, ...rest] = multiAddrParts
1111
try {
1212
// Remove leading slash and parse URI-encoded path
1313
// See https://github.com/multiformats/multiaddr/blob/cab92e8e6da2e70c5f1b8aa59976e71e6922b392/protocols/http-path.md#usage
1414
path = decodeURIComponent(httpPathMultiAddr.substring(1))
1515
} catch (err) {
1616
throw Object.assign(
1717
new Error(`Cannot parse "${addr}": unsupported http path`, { cause: err }),
18-
{ code: 'INVALID_HTTP_PATH' }
18+
{ code: 'INVALID_HTTP_PATH' },
1919
)
2020
} // Handle HTTP/HTTPs addresses using the default port
2121
} else if (multiAddrParts[0] === 'http' || multiAddrParts[0] === 'https') {
22-
[scheme, ...rest] = multiAddrParts
22+
;[scheme, ...rest] = multiAddrParts
2323
} else {
2424
let ipProtocol
2525
;[ipProtocol, port, scheme, ...rest] = multiAddrParts
2626

2727
if (ipProtocol !== 'tcp') {
2828
throw Object.assign(
2929
new Error(`Cannot parse "${addr}": unsupported protocol "${ipProtocol}"`),
30-
{ code: 'UNSUPPORTED_MULTIADDR_PROTO' }
30+
{ code: 'UNSUPPORTED_MULTIADDR_PROTO' },
3131
)
3232
}
3333
}
3434

3535
if (scheme !== 'http' && scheme !== 'https') {
36-
throw Object.assign(
37-
new Error(`Cannot parse "${addr}": unsupported scheme "${scheme}"`),
38-
{ code: 'UNSUPPORTED_MULTIADDR_SCHEME' }
39-
)
36+
throw Object.assign(new Error(`Cannot parse "${addr}": unsupported scheme "${scheme}"`), {
37+
code: 'UNSUPPORTED_MULTIADDR_SCHEME',
38+
})
4039
}
4140

4241
if (rest.length) {
43-
throw Object.assign(
44-
new Error(`Cannot parse "${addr}": too many parts`),
45-
{ code: 'MULTIADDR_HAS_TOO_MANY_PARTS' }
46-
)
42+
throw Object.assign(new Error(`Cannot parse "${addr}": too many parts`), {
43+
code: 'MULTIADDR_HAS_TOO_MANY_PARTS',
44+
})
4745
}
4846

4947
let url = `${scheme}://${getUriHost(hostType, hostValue)}`
@@ -52,7 +50,7 @@ export function multiaddrToHttpUrl (addr) {
5250
return url
5351
}
5452

55-
function getUriHost (hostType, hostValue) {
53+
function getUriHost(hostType, hostValue) {
5654
switch (hostType) {
5755
case 'ip4':
5856
case 'dns':
@@ -65,13 +63,12 @@ function getUriHost (hostType, hostValue) {
6563
return `[${hostValue}]`
6664
}
6765

68-
throw Object.assign(
69-
new Error(`Unsupported multiaddr host type "${hostType}"`),
70-
{ code: 'UNSUPPORTED_MULTIADDR_HOST_TYPE' }
71-
)
66+
throw Object.assign(new Error(`Unsupported multiaddr host type "${hostType}"`), {
67+
code: 'UNSUPPORTED_MULTIADDR_HOST_TYPE',
68+
})
7269
}
7370

74-
function getUriPort (scheme, port) {
71+
function getUriPort(scheme, port) {
7572
if (scheme === 'http' && port === '80') return ''
7673
if (scheme === 'https' && port === '443') return ''
7774
return `:${port}`

0 commit comments

Comments
 (0)