Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

➖ Remove buffer dependency #68

Merged
merged 2 commits into from
Dec 11, 2024
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
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,10 @@
"typescript": "^4.4.2"
},
"dependencies": {
"@likecoin/iscn-message-types": "0.0.7",
"@likecoin/iscn-message-types": "0.0.8",
"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 = (() => {

Check warning on line 4 in src/globalThis.ts

View workflow job for this annotation

GitHub Actions / build (16.x)

Unexpected any. Specify a different type
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 @@
...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 @@
recordNotes,
contentFingerprints,
stakeholders,
contentMetadata: Buffer.from(JSON.stringify(contentMetadata), 'utf8'),
contentMetadata: globalThis.Buffer.from(JSON.stringify(contentMetadata), 'utf8'),
};
}

Expand All @@ -58,7 +58,7 @@
value: {
from: senderAddress,
record,
} as any,

Check warning on line 61 in src/messages/iscn.ts

View workflow job for this annotation

GitHub Actions / build (16.x)

Unexpected any. Specify a different type
};
// field nonce: 0 will be ignored when Marshaling in Go
if (nonce) {
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
25 changes: 5 additions & 20 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -647,12 +647,10 @@
"@types/yargs" "^16.0.0"
chalk "^4.0.0"

"@likecoin/iscn-message-types@0.0.7":
version "0.0.7"
resolved "https://registry.yarnpkg.com/@likecoin/iscn-message-types/-/iscn-message-types-0.0.7.tgz#fde2693bb5c650932e62b30279458256c804eed9"
integrity sha512-xcYcFvvH2NXlalRwxRG/jrwbXWOPHQy1sVZRztuGcdFyssDTdF8YfAxN0wdMVhIuijdVzN7jSnOWRPX5Uch2qg==
dependencies:
buffer "^6.0.3"
"@likecoin/iscn-message-types@0.0.8":
version "0.0.8"
resolved "https://registry.yarnpkg.com/@likecoin/iscn-message-types/-/iscn-message-types-0.0.8.tgz#ade947c25a394b551cf981f0f72da6a0f712b6d7"
integrity sha512-4LMmzyb2EjYjb+zwPBCSTpkkh94ZDrZmZ92txbhYp/zOt0utBiMD6l1Q3hc8ygxwZCWV/3QUG6nnGbSP2ah15w==

"@noble/hashes@^1", "@noble/hashes@^1.0.0":
version "1.0.0"
Expand Down Expand Up @@ -1163,7 +1161,7 @@ balanced-match@^1.0.0:
resolved "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz"
integrity sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==

base64-js@^1.3.0, base64-js@^1.3.1:
base64-js@^1.3.0:
version "1.5.1"
resolved "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz"
integrity sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==
Expand Down Expand Up @@ -1248,14 +1246,6 @@ buffer-from@^1.0.0:
resolved "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz"
integrity sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==

buffer@^6.0.3:
version "6.0.3"
resolved "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz"
integrity sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==
dependencies:
base64-js "^1.3.1"
ieee754 "^1.2.1"

call-bind@^1.0.0, call-bind@^1.0.2:
version "1.0.2"
resolved "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz"
Expand Down Expand Up @@ -2152,11 +2142,6 @@ iconv-lite@0.4.24:
dependencies:
safer-buffer ">= 2.1.2 < 3"

ieee754@^1.2.1:
version "1.2.1"
resolved "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz"
integrity sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==

ignore@^4.0.6:
version "4.0.6"
resolved "https://registry.npmjs.org/ignore/-/ignore-4.0.6.tgz"
Expand Down
Loading