Skip to content

Commit

Permalink
feat(deps): remove assert-browserify (#2389)
Browse files Browse the repository at this point in the history
Use if statements and manually error throwing to save 20kb gzipped.

BREAKING CHANGE: If you were catching AssertionError you need to change to Error.
  • Loading branch information
ckniffen committed Oct 5, 2023
1 parent 7ac59b9 commit 866c827
Show file tree
Hide file tree
Showing 14 changed files with 77 additions and 50 deletions.
6 changes: 2 additions & 4 deletions UNIQUE_SETUPS.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ To use `xrpl.js` with React, you need to install shims for core NodeJS modules.

```shell
npm install --save-dev \
assert \
buffer \
crypto-browserify \
process \
Expand All @@ -42,7 +41,6 @@ To use `xrpl.js` with React, you need to install shims for core NodeJS modules.
module.exports = function override(config) {
const fallback = config.resolve.fallback || {};
Object.assign(fallback, {
assert: require.resolve("assert"),
crypto: require.resolve("crypto-browserify"),
stream: require.resolve("stream-browserify"),
ws: require.resolve("xrpl/dist/npm/client/WSWrapper"),
Expand Down Expand Up @@ -119,7 +117,7 @@ Similar to above, to get xrpl.js to work with Vite you need to set up a couple a
2. Copy these settings into your `vite.config.ts` file.
```
```javascript
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { NodeGlobalsPolyfillPlugin } from "@esbuild-plugins/node-globals-polyfill";
Expand Down Expand Up @@ -163,7 +161,7 @@ resolve: {
3. Install the config dependencies and xrpl (e.g. using this command)
```
```shell
npm install --save-dev @esbuild-plugins/node-globals-polyfill \
rollup-plugin-polyfill-node \
&& npm install
Expand Down
13 changes: 6 additions & 7 deletions packages/ripple-address-codec/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import * as assert from 'assert'

import {
codec,
encodeSeed,
Expand Down Expand Up @@ -133,11 +131,12 @@ function tagFromBuffer(buf: Buffer): number | false {
// Little-endian to big-endian
return buf[23] + buf[24] * 0x100 + buf[25] * 0x10000 + buf[26] * 0x1000000
}
assert.strictEqual(flag, 0, 'flag must be zero to indicate no tag')
assert.ok(
Buffer.from('0000000000000000', 'hex').equals(buf.slice(23, 23 + 8)),
'remaining bytes must be zero',
)
if (flag !== 0) {
throw new Error('flag must be zero to indicate no tag')
}
if (!Buffer.from('0000000000000000', 'hex').equals(buf.slice(23, 23 + 8))) {
throw new Error('remaining bytes must be zero')
}
return false
}

Expand Down
4 changes: 3 additions & 1 deletion packages/ripple-binary-codec/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,13 @@
"test": "test"
},
"dependencies": {
"assert": "^2.0.0",
"buffer": "6.0.3",
"create-hash": "^1.2.0",
"ripple-address-codec": "^4.3.1"
},
"devDependencies": {
"assert": "^2.0.0"
},
"scripts": {
"build": "tsc -b && copyfiles ./src/enums/definitions.json ./dist/enums/",
"clean": "rm -rf ./dist && rm -rf tsconfig.tsbuildinfo",
Expand Down
33 changes: 24 additions & 9 deletions packages/ripple-binary-codec/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import * as assert from 'assert'
import { quality, binary, HashPrefix } from './coretypes'
import { decodeLedgerData } from './ledger-hashes'
import { ClaimObject } from './binary'
Expand Down Expand Up @@ -27,7 +26,9 @@ const {
* @returns the JSON representation of the transaction
*/
function decode(binary: string, definitions?: XrplDefinitionsBase): JsonObject {
assert.ok(typeof binary === 'string', 'binary must be a hex string')
if (typeof binary !== 'string') {
throw new Error('binary must be a hex string')
}
return binaryToJSON(binary, definitions)
}

Expand All @@ -40,7 +41,9 @@ function decode(binary: string, definitions?: XrplDefinitionsBase): JsonObject {
* @returns A hex-string of the encoded transaction
*/
function encode(json: object, definitions?: XrplDefinitionsBase): string {
assert.ok(typeof json === 'object')
if (typeof json !== 'object') {
throw new Error()
}
return serializeObject(json as JsonObject, { definitions })
.toString('hex')
.toUpperCase()
Expand All @@ -58,7 +61,9 @@ function encodeForSigning(
json: object,
definitions?: XrplDefinitionsBase,
): string {
assert.ok(typeof json === 'object')
if (typeof json !== 'object') {
throw new Error()
}
return signingData(json as JsonObject, HashPrefix.transactionSig, {
definitions,
})
Expand All @@ -75,7 +80,9 @@ function encodeForSigning(
* @returns a hex string of the encoded transaction
*/
function encodeForSigningClaim(json: object): string {
assert.ok(typeof json === 'object')
if (typeof json !== 'object') {
throw new Error()
}
return signingClaimData(json as ClaimObject)
.toString('hex')
.toUpperCase()
Expand All @@ -94,8 +101,12 @@ function encodeForMultisigning(
signer: string,
definitions?: XrplDefinitionsBase,
): string {
assert.ok(typeof json === 'object')
assert.equal(json['SigningPubKey'], '')
if (typeof json !== 'object') {
throw new Error()
}
if (json['SigningPubKey'] !== '') {
throw new Error()
}
const definitionsOpt = definitions ? { definitions } : undefined
return multiSigningData(json as JsonObject, signer, definitionsOpt)
.toString('hex')
Expand All @@ -109,7 +120,9 @@ function encodeForMultisigning(
* @returns a hex-string representing the quality
*/
function encodeQuality(value: string): string {
assert.ok(typeof value === 'string')
if (typeof value !== 'string') {
throw new Error()
}
return quality.encode(value).toString('hex').toUpperCase()
}

Expand All @@ -120,7 +133,9 @@ function encodeQuality(value: string): string {
* @returns a string representing the quality
*/
function decodeQuality(value: string): string {
assert.ok(typeof value === 'string')
if (typeof value !== 'string') {
throw new Error()
}
return quality.decode(value).toString()
}

Expand Down
17 changes: 12 additions & 5 deletions packages/ripple-binary-codec/src/ledger-hashes.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import * as assert from 'assert'
import { ShaMap, ShaMapNode, ShaMapLeaf } from './shamap'
import { HashPrefix } from './hash-prefixes'
import { Sha512Half } from './hashes'
Expand Down Expand Up @@ -45,7 +44,9 @@ interface transactionItemObject extends JsonObject {
function transactionItemizer(
json: transactionItemObject,
): [Hash256, ShaMapNode, undefined] {
assert.ok(json.hash)
if (!json.hash) {
throw new Error()
}
const index = Hash256.from(json.hash)
const item = {
hashPrefix() {
Expand Down Expand Up @@ -139,8 +140,12 @@ interface ledgerObject {
function ledgerHash(header: ledgerObject): Hash256 {
const hash = new Sha512Half()
hash.put(HashPrefix.ledgerHeader)
assert.ok(header.parent_close_time !== undefined)
assert.ok(header.close_flags !== undefined)
if (
header.parent_close_time === undefined ||
header.close_flags === undefined
) {
throw new Error()
}

UInt32.from<number>(header.ledger_index).toBytesSink(hash)
UInt64.from<bigint>(BigInt(String(header.total_coins))).toBytesSink(hash)
Expand All @@ -166,7 +171,9 @@ function decodeLedgerData(
binary: string,
definitions?: XrplDefinitionsBase,
): object {
assert.ok(typeof binary === 'string', 'binary must be a hex string')
if (typeof binary !== 'string') {
throw new Error('binary must be a hex string')
}
const parser = new BinaryParser(binary, definitions)
return {
ledger_index: parser.readUInt32(),
Expand Down
17 changes: 12 additions & 5 deletions packages/ripple-binary-codec/src/serdes/binary-parser.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import * as assert from 'assert'
import {
XrplDefinitionsBase,
DEFAULT_DEFINITIONS,
Expand Down Expand Up @@ -35,7 +34,9 @@ class BinaryParser {
* @returns The first byte of the BinaryParser
*/
peek(): number {
assert.ok(this.bytes.byteLength !== 0)
if (this.bytes.byteLength === 0) {
throw new Error()
}
return this.bytes[0]
}

Expand All @@ -45,7 +46,9 @@ class BinaryParser {
* @param n the number of bytes to skip
*/
skip(n: number): void {
assert.ok(n <= this.bytes.byteLength)
if (n > this.bytes.byteLength) {
throw new Error()
}
this.bytes = this.bytes.slice(n)
}

Expand All @@ -56,7 +59,9 @@ class BinaryParser {
* @return The bytes
*/
read(n: number): Buffer {
assert.ok(n <= this.bytes.byteLength)
if (n > this.bytes.byteLength) {
throw new Error()
}

const slice = this.bytes.slice(0, n)
this.skip(n)
Expand All @@ -70,7 +75,9 @@ class BinaryParser {
* @return The number represented by those bytes
*/
readUIntN(n: number): number {
assert.ok(0 < n && n <= 4, 'invalid n')
if (0 >= n && n > 4) {
throw new Error('invalid n')
}
return this.read(n).reduce((a, b) => (a << 8) | b) >>> 0
}

Expand Down
6 changes: 3 additions & 3 deletions packages/ripple-binary-codec/src/serdes/binary-serializer.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import * as assert from 'assert'
import { FieldInstance } from '../enums'
import { type SerializedType } from '../types/serialized-type'
import { Buffer } from 'buffer/'
Expand Down Expand Up @@ -132,8 +131,9 @@ class BinarySerializer {
isUnlModifyWorkaround = false,
): void {
const associatedValue = field.associatedType.from(value)
assert.ok(associatedValue.toBytesSink !== undefined)
assert.ok(field.name !== undefined)
if (associatedValue.toBytesSink === undefined || field.name === undefined) {
throw new Error()
}

this.sink.put(field.header)

Expand Down
5 changes: 3 additions & 2 deletions packages/ripple-binary-codec/src/shamap.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { strict as assert } from 'assert'
import { coreTypes } from './types'
import { HashPrefix } from './hash-prefixes'
import { Sha512Half } from './hashes'
Expand Down Expand Up @@ -160,7 +159,9 @@ class ShaMapInner extends ShaMapNode {
* @param leaf Leaf node to insert when branch doesn't exist
*/
addItem(index?: Hash256, item?: ShaMapNode, leaf?: ShaMapLeaf): void {
assert.ok(index !== undefined)
if (index === undefined) {
throw new Error()
}
if (index !== undefined) {
const nibble = index.nibblet(this.depth)
const existing = this.branches[nibble]
Expand Down
12 changes: 6 additions & 6 deletions packages/ripple-keypairs/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import * as assert from 'assert'
import brorand = require('brorand')
import * as hashjs from 'hash.js'
import * as elliptic from 'elliptic'
Expand All @@ -19,10 +18,9 @@ function generateSeed(
algorithm?: 'ed25519' | 'ecdsa-secp256k1'
} = {},
): string {
assert.ok(
!options.entropy || options.entropy.length >= 16,
'entropy too short',
)
if (!(!options.entropy || options.entropy.length >= 16)) {
throw new Error('entropy too short')
}
const entropy = options.entropy ? options.entropy.slice(0, 16) : brorand(16)
const type = options.algorithm === 'ed25519' ? 'ed25519' : 'secp256k1'
return addressCodec.encodeSeed(Buffer.from(entropy), type)
Expand Down Expand Up @@ -82,7 +80,9 @@ const ed25519 = {
sign(message, privateKey): string {
// caution: Ed25519.sign interprets all strings as hex, stripping
// any non-hex characters without warning
assert.ok(Array.isArray(message), 'message must be array of octets')
if (!Array.isArray(message)) {
throw new Error('message must be array of octets')
}
return bytesToHex(
Ed25519.sign(message, hexToBytes(privateKey).slice(1)).toBytes(),
)
Expand Down
5 changes: 3 additions & 2 deletions packages/ripple-keypairs/src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import * as assert from 'assert'
import * as hashjs from 'hash.js'
import BN = require('bn.js')

Expand All @@ -10,7 +9,9 @@ function bytesToHex(a: Iterable<number> | ArrayLike<number>): string {
}

function hexToBytes(a): number[] {
assert.ok(a.length % 2 === 0)
if (a.length % 2 !== 0) {
throw new Error()
}
// Special-case length zero to return [].
// BN.toArray intentionally returns [0] rather than [] for length zero,
// which may make sense for BigNum data, but not for byte strings.
Expand Down
1 change: 0 additions & 1 deletion packages/xrpl/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@
"devDependencies": {
"@geut/browser-node-core": "^2.0.13",
"@types/node": "^16.18.38",
"assert-browserify": "^2.0.0",
"browserify-fs": "^1.0.0",
"constants-browserify": "^1.0.0",
"https-browserify": "^1.0.0",
Expand Down
5 changes: 3 additions & 2 deletions packages/xrpl/src/client/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
/* eslint-disable jsdoc/require-jsdoc -- Request has many aliases, but they don't need unique docs */
/* eslint-disable @typescript-eslint/member-ordering -- TODO: remove when instance methods aren't members */
/* eslint-disable max-lines -- Client is a large file w/ lots of imports/exports */
import * as assert from 'assert'
import { EventEmitter } from 'events'

import { NotFoundError, ValidationError, XrplError } from '../errors'
Expand Down Expand Up @@ -157,7 +156,9 @@ function getCollectKeyFromCommand(command: string): string | null {
}

function clamp(value: number, min: number, max: number): number {
assert.ok(min <= max, 'Illegal clamp bounds')
if (min > max) {
throw new Error('Illegal clamp bounds')
}
return Math.min(Math.max(value, min), max)
}

Expand Down
2 changes: 0 additions & 2 deletions packages/xrpl/test/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,9 @@ function webpackForTest(testFileName) {
extensions: ['.ts', '.js', '.json'],
fallback: {
module: false,
assert: require.resolve('assert-browserify'),
constants: require.resolve('constants-browserify'),
fs: require.resolve('browserify-fs'),
buffer: require.resolve('buffer/'),
assert: require.resolve('assert/'),
stream: require.resolve('stream-browserify'),
crypto: require.resolve('crypto-browserify'),
path: require.resolve('path-browserify'),
Expand Down
1 change: 0 additions & 1 deletion packages/xrpl/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ function getDefaultConfiguration() {
symlinks: false,
fallback: {
buffer: require.resolve('buffer/'),
assert: require.resolve('assert/'),
stream: require.resolve('stream-browserify'),
crypto: require.resolve('crypto-browserify'),
},
Expand Down

0 comments on commit 866c827

Please sign in to comment.