Skip to content

Commit 356f127

Browse files
authored
Browser-compatibility (#2072)
* fs, buffer and bytes for browser * node version 2.1.1 * Revert "node version 2.1.1" This reverts commit 45edc08.
1 parent d67535f commit 356f127

7 files changed

Lines changed: 44 additions & 23 deletions

File tree

src/config/ConfigHelper.ts

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
// eslint-disable-next-line import/no-named-default
22
import { default as DefaultContractsAddresses } from '@oceanprotocol/contracts/addresses/address.json'
3-
import fs from 'fs'
43
import { Config } from '.'
54
import { LoggerInstance } from '../utils/Logger.js'
65

@@ -273,14 +272,15 @@ export class ConfigHelper {
273272
return null
274273
}
275274

276-
let addresses
275+
let addresses = null
277276
try {
278-
addresses = process.env.ADDRESS_FILE
279-
? JSON.parse(
280-
// eslint-disable-next-line security/detect-non-literal-fs-filename
281-
fs.readFileSync(process.env.ADDRESS_FILE, 'utf8')
282-
)
283-
: null
277+
if (typeof window === 'undefined' && process.env.ADDRESS_FILE) {
278+
// Node.js only: read custom address file from filesystem
279+
// eslint-disable-next-line @typescript-eslint/no-require-imports
280+
const fs = require('fs')
281+
// eslint-disable-next-line security/detect-non-literal-fs-filename
282+
addresses = JSON.parse(fs.readFileSync(process.env.ADDRESS_FILE, 'utf8'))
283+
}
284284
} catch (e) {
285285
console.log(e)
286286
addresses = null

src/services/providers/P2pProvider.ts

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { multiaddr, type Multiaddr } from '@multiformats/multiaddr'
1414
import { Signer } from 'ethers'
1515
import { sleep } from '../../utils/General.js'
1616
import { LoggerInstance } from '../../utils/Logger.js'
17+
import { concatUint8Arrays } from '../../utils/bytes.js'
1718
import type { Connection, Stream } from '@libp2p/interface'
1819
import {
1920
StorageObject,
@@ -209,10 +210,10 @@ export class P2pProvider {
209210
}
210211
}
211212
if (val?.type === 'Buffer' && Array.isArray(val.data)) {
212-
return Buffer.from(val.data).toString()
213+
return new TextDecoder().decode(new Uint8Array(val.data))
213214
}
214-
if (val instanceof Uint8Array || Buffer.isBuffer(val)) {
215-
return Buffer.from(val).toString()
215+
if (val instanceof Uint8Array) {
216+
return new TextDecoder().decode(val)
216217
}
217218
return val
218219
}
@@ -977,23 +978,23 @@ export class P2pProvider {
977978
}
978979

979980
// Collect binary file data. If the first frame wasn't a status JSON, it's data.
980-
const chunks: Buffer[] = status === null ? [Buffer.from(firstBytes)] : []
981+
const chunks: Uint8Array[] = status === null ? [new Uint8Array(firstBytes)] : []
981982
try {
982983
while (true) {
983984
const chunk = await lp.read({
984985
signal: AbortSignal.timeout(
985986
this.p2pConfig.dialTimeout ?? DEFAULT_DIAL_TIMEOUT_MS
986987
)
987988
})
988-
chunks.push(Buffer.from(this.toUint8Array(chunk)))
989+
chunks.push(new Uint8Array(this.toUint8Array(chunk)))
989990
}
990991
} catch (e) {
991992
if (!(e instanceof UnexpectedEOFError)) {
992993
throw e
993994
}
994995
}
995996

996-
const combined = Buffer.concat(chunks)
997+
const combined = concatUint8Arrays(chunks)
997998
return {
998999
data: combined.buffer.slice(
9991000
combined.byteOffset,

src/utils/Addresses.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import { ethers, Signer } from 'ethers'
22
import { NftFactory } from '../contracts/NFTFactory.js'
3-
import fs from 'fs'
43
// eslint-disable-next-line import/no-named-default
54
import ERC20Template from '@oceanprotocol/contracts/artifacts/contracts/interfaces/IERC20Template.sol/IERC20Template.json'
65
// eslint-disable-next-line import/no-named-default, prettier/prettier
@@ -12,7 +11,10 @@ import { default as Addresses } from '@oceanprotocol/contracts/addresses/address
1211
*/
1312
export function getOceanArtifactsAddresses(): any {
1413
try {
15-
if (process.env.ADDRESS_FILE) {
14+
if (typeof window === 'undefined' && process.env.ADDRESS_FILE) {
15+
// Node.js only: read custom address file from filesystem
16+
// eslint-disable-next-line @typescript-eslint/no-require-imports
17+
const fs = require('fs')
1618
// eslint-disable-next-line security/detect-non-literal-fs-filename
1719
const data = fs.readFileSync(process.env.ADDRESS_FILE, 'utf8')
1820
return JSON.parse(data)

src/utils/Assets.ts

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { ethers, hexlify, Signer, toBeHex, toUtf8Bytes } from 'ethers'
22
import { ConfigHelper } from '../../src/config/index.js'
3-
import { createHash } from 'crypto'
3+
import SHA256 from 'crypto-js/sha256.js'
44
import { Aquarius } from '../services/Aquarius.js'
55
import { NftFactory } from '../contracts/NFTFactory.js'
66
import { Nft } from '../contracts/NFT.js'
@@ -240,9 +240,8 @@ export async function createAsset(
240240
flags = 2
241241
} else {
242242
const stringDDO = JSON.stringify(ddo)
243-
const bytes = Buffer.from(stringDDO)
244-
metadata = hexlify(bytes)
245-
metadataHash = '0x' + createHash('sha256').update(metadata).digest('hex')
243+
metadata = hexlify(toUtf8Bytes(stringDDO))
244+
metadataHash = '0x' + SHA256(metadata).toString()
246245
flags = 0
247246
}
248247

src/utils/bytes.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// no 0x prefix
2+
export function bytesToHex(bytes: Uint8Array): string {
3+
return Array.from(bytes)
4+
.map((b) => b.toString(16).padStart(2, '0'))
5+
.join('')
6+
}
7+
8+
export function concatUint8Arrays(arrays: Uint8Array[]): Uint8Array {
9+
const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0)
10+
const result = new Uint8Array(totalLength)
11+
let offset = 0
12+
for (const arr of arrays) {
13+
result.set(arr, offset)
14+
offset += arr.length
15+
}
16+
return result
17+
}

src/utils/eciesencrypt.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { encrypt, PublicKey } from 'eciesjs'
2+
import { bytesToHex } from './bytes.js'
23

34
type PublicKeyInput = string | Uint8Array | number[] | Record<number, number>
45

@@ -18,7 +19,7 @@ function normalizePublicKey(publicKey: PublicKeyInput): string {
1819
.map((key) => publicKey[Number(key)])
1920
)
2021

21-
return `0x${Buffer.from(bytes).toString('hex')}`
22+
return `0x${bytesToHex(bytes)}`
2223
}
2324

2425
/**
@@ -31,9 +32,9 @@ function normalizePublicKey(publicKey: PublicKeyInput): string {
3132
export function eciesencrypt(publicKey: PublicKeyInput, content: string) {
3233
// Encrypt using ECIES
3334
const key = PublicKey.fromHex(normalizePublicKey(publicKey))
34-
const encrypted = encrypt(key.toHex(), Buffer.from(content))
35+
const encrypted = encrypt(key.toHex(), new TextEncoder().encode(content))
3536

3637
// Convert to hex string
37-
const encryptedHex = Buffer.from(encrypted).toString('hex')
38+
const encryptedHex = bytesToHex(new Uint8Array(encrypted))
3839
return encryptedHex
3940
}

src/utils/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,4 @@ export * from './ProviderErrors.js'
1212
export * from './OrderUtils.js'
1313
export * from './Assets.js'
1414
export * from './Addresses.js'
15+
export * from './bytes.js'

0 commit comments

Comments
 (0)