Skip to content

Commit

Permalink
➖ Remove buffer dependency
Browse files Browse the repository at this point in the history
  • Loading branch information
williamchong committed Dec 8, 2024
1 parent 19f0dd3 commit c7c5c80
Show file tree
Hide file tree
Showing 10 changed files with 37 additions and 26 deletions.
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@
"axios": "^1.6.0",
"bech32": "^2.0.0",
"bignumber.js": "^9.0.1",
"buffer": "^6.0.3",
"fast-json-stable-stringify": "^2.1.0"
}
}
12 changes: 12 additions & 0 deletions src/globalThis.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
declare let self: unknown | undefined;
declare let window: unknown | undefined;
// eslint-disable-next-line no-var, import/no-mutable-exports
var globalThis: any = (() => {
if (typeof globalThis !== 'undefined') return globalThis;
if (typeof self !== 'undefined') return self;
if (typeof window !== 'undefined') return window;
if (typeof global !== 'undefined') return global;
throw new Error('Unable to locate global object');
})();

export default globalThis;
6 changes: 3 additions & 3 deletions src/messages/iscn.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// eslint-disable-next-line import/no-extraneous-dependencies
import { EncodeObject } from '@cosmjs/proto-signing';
import { Buffer } from 'buffer/';
// eslint-disable-next-line import/no-extraneous-dependencies
import Long from 'long';
import { ISCNSignPayload, Stakeholder } from '../types';
import globalThis from '../globalThis';

export function formatISCNPayload(payload: ISCNSignPayload, version = 1): {
recordNotes?: string;
Expand All @@ -25,7 +25,7 @@ export function formatISCNPayload(payload: ISCNSignPayload, version = 1): {
...data
} = payload;

const stakeholders = inputStakeholders.map((s: Stakeholder) => Buffer.from(
const stakeholders = inputStakeholders.map((s: Stakeholder) => globalThis.Buffer.from(
JSON.stringify(s),
'utf8',
));
Expand All @@ -45,7 +45,7 @@ export function formatISCNPayload(payload: ISCNSignPayload, version = 1): {
recordNotes,
contentFingerprints,
stakeholders,
contentMetadata: Buffer.from(JSON.stringify(contentMetadata), 'utf8'),
contentMetadata: globalThis.Buffer.from(JSON.stringify(contentMetadata), 'utf8'),
};
}

Expand Down
6 changes: 3 additions & 3 deletions src/messages/likenft.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { ClassConfig } from '@likecoin/iscn-message-types/dist/likechain/likenft
import { RoyaltyConfigInput } from '@likecoin/iscn-message-types/dist/likechain/likenft/v1/royalty_config';
// eslint-disable-next-line import/no-extraneous-dependencies
import Long from 'long';
import { Buffer } from 'buffer/';
import globalThis from '../globalThis';
import { MintNFTData, NewNFTClassData } from '../types';

export function formatMsgNewClass(
Expand All @@ -27,7 +27,7 @@ export function formatMsgNewClass(
description: nftClassData.description,
uri: nftClassData.uri,
uriHash: nftClassData.uriHash,
metadata: Buffer.from(JSON.stringify({
metadata: globalThis.Buffer.from(JSON.stringify({
...(nftClassData.metadata || {}),
}), 'utf8'),
config: classConfig || {
Expand Down Expand Up @@ -75,7 +75,7 @@ export function formatMsgMintNFT(
input: {
uri: nftData.uri,
uriHash: nftData.uriHash,
metadata: Buffer.from(JSON.stringify({
metadata: globalThis.Buffer.from(JSON.stringify({
...(nftData.metadata || {}),
}), 'utf8'),
},
Expand Down
12 changes: 6 additions & 6 deletions src/messages/parsing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { MsgGrant } from 'cosmjs-types/cosmos/authz/v1beta1/tx';
import { GenericAuthorization, Grant } from 'cosmjs-types/cosmos/authz/v1beta1/authz';
import { SendAuthorization } from 'cosmjs-types/cosmos/bank/v1beta1/authz';
import { StakeAuthorization } from 'cosmjs-types/cosmos/staking/v1beta1/authz';
import { Buffer } from 'buffer/';
import globalThis from '../globalThis';
import {
ISCNRecord, ISCNRecordData, LikeNFT, LikeNFTClass, ParsedISCNTx,
} from '../types';
Expand All @@ -30,12 +30,12 @@ export function parseISCNRecordFields(record: IscnRecord): ISCNRecordData {
...record,
stakeholders: stakeholders.map((s: Uint8Array) => {
if (s) {
const sString = Buffer.from(s).toString('utf-8');
const sString = globalThis.Buffer.from(s).toString('utf-8');
if (sString) return JSON.parse(sString);
}
return s;
}),
contentMetadata: JSON.parse(Buffer.from(contentMetadata).toString('utf-8')),
contentMetadata: JSON.parse(globalThis.Buffer.from(contentMetadata).toString('utf-8')),
};
}

Expand All @@ -44,7 +44,7 @@ export function parseNFTClassDataFields(record: Class): LikeNFTClass {
if (record.data && record.data.typeUrl === '/likechain.likenft.v1.ClassData') {
data = ClassData.decode(record.data.value);
if (data.metadata) {
const metadataString = Buffer.from(data.metadata).toString('utf-8');
const metadataString = globalThis.Buffer.from(data.metadata).toString('utf-8');
if (metadataString) {
data.metadata = JSON.parse(metadataString);
}
Expand All @@ -62,7 +62,7 @@ export function parseNFTDataFields(record: NFT): LikeNFT {
if (record.data && record.data.typeUrl === '/likechain.likenft.v1.NFTData') {
data = NFTData.decode(record.data.value);
if (data.metadata) {
const metadataString = Buffer.from(data.metadata).toString('utf-8');
const metadataString = globalThis.Buffer.from(data.metadata).toString('utf-8');
if (metadataString) {
data.metadata = JSON.parse(metadataString);
}
Expand Down Expand Up @@ -165,7 +165,7 @@ export function parseTxInfoFromIndexedTx(tx: IndexedTx): ParsedISCNTx {
export function parseISCNTxRecordFromQuery(records: QueryResponseRecord[]): ISCNRecord[] {
return records.map((r): ISCNRecord => {
const { data, ipld } = r;
const parsedData = JSON.parse(Buffer.from(data).toString('utf-8'));
const parsedData = JSON.parse(globalThis.Buffer.from(data).toString('utf-8'));
return {
ipld,
data: parsedData,
Expand Down
6 changes: 3 additions & 3 deletions src/nft/nftId.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ function calculateNFTClassId(
prefix: Uint8Array,
serial = 0,
): string {
const bytes = Buffer.concat([
const bytes = globalThis.Buffer.concat([
prefix,
Buffer.from(serial.toString(), 'utf8'),
globalThis.Buffer.from(serial.toString(), 'utf8'),
]);
const sha256 = createHash('sha256');
const hash = sha256.update(bytes).digest();
Expand All @@ -20,7 +20,7 @@ export function calculateNFTClassIdByISCNId(
numberOfExistingNFTClass = 0,
): string {
const iscnIdPrefix = getISCNPrefix(iscnId);
const prefix = Buffer.from(iscnIdPrefix, 'utf8');
const prefix = globalThis.Buffer.from(iscnIdPrefix, 'utf8');
return calculateNFTClassId(prefix, numberOfExistingNFTClass);
}

Expand Down
4 changes: 2 additions & 2 deletions src/tests/utils.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { createHash } from 'crypto';
// eslint-disable-next-line import/no-extraneous-dependencies
import { TxRaw } from 'cosmjs-types/cosmos/tx/v1beta1/tx';
import { Buffer } from 'buffer/';
import globalThis from '../globalThis';

export async function computeTransactionHash(signed: TxRaw): Promise<string> {
const tx = Uint8Array.from(TxRaw.encode(signed).finish());
const sha256 = createHash('sha256');
const txHash = sha256
.update(Buffer.from(tx.buffer))
.update(globalThis.Buffer.from(tx.buffer))
.digest('hex');
return txHash.toUpperCase();
}
Expand Down
6 changes: 3 additions & 3 deletions src/transactions/gas.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { StdFee } from '@cosmjs/stargate';
import BigNumber from 'bignumber.js';
import { Buffer } from 'buffer/';
import jsonStringify from 'fast-json-stable-stringify';
// eslint-disable-next-line import/no-extraneous-dependencies
import { EncodeObject } from '@cosmjs/proto-signing';
import globalThis from '../globalThis';
import {
GAS_ESTIMATOR_INTERCEPT,
GAS_ESTIMATOR_SLOPE,
Expand Down Expand Up @@ -57,7 +57,7 @@ export function estimateMsgTxGas(msg: EncodeObject, {
value,
memo, // directly append memo to object if exists, since we only need its length
};
const txBytes = Buffer.from(jsonStringify(obj), 'utf-8');
const txBytes = globalThis.Buffer.from(jsonStringify(obj), 'utf-8');
const byteSize = new BigNumber(txBytes.length);
const gasUsedEstimationBeforeBuffer = byteSize
.multipliedBy(GAS_ESTIMATOR_SLOPE)
Expand All @@ -76,7 +76,7 @@ export function estimateMsgsTxGas(messages: EncodeObject[], option: {
memo?: string,
gasMultiplier?: number,
}): StdFee {
const msgSizes = messages.map((m) => (Buffer.from(jsonStringify(m), 'utf-8').length));
const msgSizes = messages.map((m) => (globalThis.Buffer.from(jsonStringify(m), 'utf-8').length));
const maxIndex = msgSizes.reduce((acc, curr, index) => {
if (curr > msgSizes[acc]) return index;
return acc;
Expand Down
6 changes: 3 additions & 3 deletions src/transactions/iscn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import jsonStringify from 'fast-json-stable-stringify';
import BigNumber from 'bignumber.js';
import { StdFee } from '@cosmjs/stargate';
import { Coin } from 'cosmjs-types/cosmos/base/v1beta1/coin';
import { Buffer } from 'buffer/';
import globalThis from '../globalThis';

import {
ISCN_REGISTRY_NAME,
Expand Down Expand Up @@ -61,8 +61,8 @@ export async function estimateISCNTxFee(
'/': 'bahuaierav3bfvm4ytx7gvn4yqeu4piiocuvtvdpyyb5f6moxniwemae4tjyq',
};
}
const byteSize = Buffer.from(jsonStringify(obj), 'utf-8').length
+ Buffer.from(jsonStringify({ stakeholders: [], contentMetadata: {} }), 'utf-8').length
const byteSize = globalThis.Buffer.from(jsonStringify(obj), 'utf-8').length
+ globalThis.Buffer.from(jsonStringify({ stakeholders: [], contentMetadata: {} }), 'utf-8').length
+ stakeholders.reduce((acc, s) => acc + s.length, 0)
+ stakeholders.length
+ contentMetadata.length;
Expand Down
4 changes: 2 additions & 2 deletions src/transactions/nft.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import BigNumber from 'bignumber.js';
// eslint-disable-next-line import/no-extraneous-dependencies
import { EncodeObject } from '@cosmjs/proto-signing';
import { Coin } from 'cosmjs-types/cosmos/base/v1beta1/coin';
import { Buffer } from 'buffer/';
import globalThis from '../globalThis';

import { formatGasFee } from './gas';
import ISCNQueryClient from '../queryClient';
Expand All @@ -26,7 +26,7 @@ export async function estimateNFTTxFee(
value,
memo, // directly append memo to object if exists, since we only need its length
};
const txBytes = Buffer.from(jsonStringify(obj), 'utf-8');
const txBytes = globalThis.Buffer.from(jsonStringify(obj), 'utf-8');
const byteSize = new BigNumber(txBytes.length);
const feeAmount = new BigNumber(byteSize).multipliedBy(feePerByteAmount);
return {
Expand Down

0 comments on commit c7c5c80

Please sign in to comment.