diff --git a/.changeset/green-tables-carry.md b/.changeset/green-tables-carry.md new file mode 100644 index 0000000000000..fe9eb43e4f932 --- /dev/null +++ b/.changeset/green-tables-carry.md @@ -0,0 +1,15 @@ +--- +'@mysten/sui': minor +'@mysten/bcs': minor +--- + +Updated hex, base64, and base58 utility names for better consistency + +All existing methods will continue to work, but the following methods have been deprecated and replaced with methods with improved names: + +- `toHEX` -> `toHEX` +- `fromHEX` -> `fromHex` +- `toB64` -> `toBase64` +- `fromB64` -> `fromBase64` +- `toB58` -> `toBase58` +- `fromB58` -> `fromBase58` diff --git a/.changeset/thin-trees-learn.md b/.changeset/thin-trees-learn.md new file mode 100644 index 0000000000000..f7fa669362d99 --- /dev/null +++ b/.changeset/thin-trees-learn.md @@ -0,0 +1,5 @@ +--- +'@mysten/sui': minor +--- + +support Bech32 secrets in the Keypair.fromSecretKey methods diff --git a/apps/wallet/src/background/accounts/index.ts b/apps/wallet/src/background/accounts/index.ts index a8feb5089c961..a57b4f379cfbe 100644 --- a/apps/wallet/src/background/accounts/index.ts +++ b/apps/wallet/src/background/accounts/index.ts @@ -7,7 +7,7 @@ import { type MethodPayload, } from '_src/shared/messaging/messages/payloads/MethodPayload'; import { type WalletStatusChange } from '_src/shared/messaging/messages/payloads/wallet-status-change'; -import { fromB64 } from '@mysten/sui/utils'; +import { fromBase64 } from '@mysten/sui/utils'; import Dexie from 'dexie'; import { getAccountSourceByID } from '../account-sources'; @@ -236,7 +236,7 @@ export async function accountsHandleUIMessage(msg: Message, uiConnection: UiConn { type: 'method-payload', method: 'signDataResponse', - args: { signature: await account.signData(fromB64(data)) }, + args: { signature: await account.signData(fromBase64(data)) }, }, msg.id, ), diff --git a/apps/wallet/src/dapp-interface/WalletStandardInterface.ts b/apps/wallet/src/dapp-interface/WalletStandardInterface.ts index 739507c8b94c7..389dcc6dccb75 100644 --- a/apps/wallet/src/dapp-interface/WalletStandardInterface.ts +++ b/apps/wallet/src/dapp-interface/WalletStandardInterface.ts @@ -30,7 +30,7 @@ import { type SignMessageRequest } from '_src/shared/messaging/messages/payloads import { isWalletStatusChangePayload } from '_src/shared/messaging/messages/payloads/wallet-status-change'; import { bcs } from '@mysten/sui/bcs'; import { isTransaction } from '@mysten/sui/transactions'; -import { fromB64, toB64 } from '@mysten/sui/utils'; +import { fromBase64, toBase64 } from '@mysten/sui/utils'; import { ReadonlyWalletAccount, SUI_CHAINS, @@ -171,7 +171,7 @@ export class SuiWallet implements Wallet { new ReadonlyWalletAccount({ address, label: nickname || undefined, - publicKey: publicKey ? fromB64(publicKey) : new Uint8Array(), + publicKey: publicKey ? fromBase64(publicKey) : new Uint8Array(), chains: this.#activeChain ? [this.#activeChain] : [], features: ['sui:signAndExecuteTransaction'], }), @@ -334,7 +334,7 @@ export class SuiWallet implements Wallet { txSignatures: [signature], intentMessage: { value: bcsTransaction }, }, - ] = bcs.SenderSignedData.parse(fromB64(rawTransaction!)); + ] = bcs.SenderSignedData.parse(fromBase64(rawTransaction!)); const bytes = bcs.TransactionData.serialize(bcsTransaction).toBase64(); @@ -342,7 +342,7 @@ export class SuiWallet implements Wallet { digest, signature, bytes, - effects: toB64(new Uint8Array(rawEffects!)), + effects: toBase64(new Uint8Array(rawEffects!)), }; }, ); @@ -353,7 +353,7 @@ export class SuiWallet implements Wallet { this.#send({ type: 'sign-message-request', args: { - message: toB64(message), + message: toBase64(message), accountAddress: account.address, }, }), @@ -371,7 +371,7 @@ export class SuiWallet implements Wallet { this.#send({ type: 'sign-message-request', args: { - message: toB64(message), + message: toBase64(message), accountAddress: account.address, }, }), diff --git a/apps/wallet/src/shared/utils/from-exported-keypair.ts b/apps/wallet/src/shared/utils/from-exported-keypair.ts index 868a4cd62dfa5..e09927b161d27 100644 --- a/apps/wallet/src/shared/utils/from-exported-keypair.ts +++ b/apps/wallet/src/shared/utils/from-exported-keypair.ts @@ -10,7 +10,7 @@ import { import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519'; import { Secp256k1Keypair } from '@mysten/sui/keypairs/secp256k1'; import { Secp256r1Keypair } from '@mysten/sui/keypairs/secp256r1'; -import { fromB64 } from '@mysten/sui/utils'; +import { fromBase64 } from '@mysten/sui/utils'; /** * Wallet stored data might contain imported accounts with their keys stored in the previous format. @@ -31,7 +31,7 @@ export function fromExportedKeypair( if (!legacySupport) { throw new Error('Invalid type of secret key. A string value was expected.'); } - secretKey = fromB64(secret.privateKey); + secretKey = fromBase64(secret.privateKey); schema = secret.schema; } else { const decoded = decodeSuiPrivateKey(secret); diff --git a/apps/wallet/src/shared/utils/index.ts b/apps/wallet/src/shared/utils/index.ts index 04bdea8fbc6d7..c982ed4e9ae0a 100644 --- a/apps/wallet/src/shared/utils/index.ts +++ b/apps/wallet/src/shared/utils/index.ts @@ -4,7 +4,7 @@ import { useAppSelector } from '_hooks'; import { setAttributes } from '_src/shared/experimentation/features'; import { useGrowthBook } from '@growthbook/growthbook-react'; -import { fromB64, toB64 } from '@mysten/sui/utils'; +import { fromBase64, toBase64 } from '@mysten/sui/utils'; import * as Sentry from '@sentry/browser'; import { useEffect } from 'react'; import Browser from 'webextension-polyfill'; @@ -77,8 +77,8 @@ export function toSearchQueryString(searchParams: URLSearchParams) { } export function toUtf8OrB64(message: string | Uint8Array) { - const messageBytes = typeof message === 'string' ? fromB64(message) : message; - let messageToReturn: string = typeof message === 'string' ? message : toB64(message); + const messageBytes = typeof message === 'string' ? fromBase64(message) : message; + let messageToReturn: string = typeof message === 'string' ? message : toBase64(message); let type: 'utf8' | 'base64' = 'base64'; try { messageToReturn = new TextDecoder('utf8', { fatal: true }).decode(messageBytes); diff --git a/apps/wallet/src/ui/app/QredoSigner.ts b/apps/wallet/src/ui/app/QredoSigner.ts index 3858baefed41f..e50900a21040a 100644 --- a/apps/wallet/src/ui/app/QredoSigner.ts +++ b/apps/wallet/src/ui/app/QredoSigner.ts @@ -10,7 +10,7 @@ import { } from '_src/shared/qredo-api'; import { type SuiClient } from '@mysten/sui/client'; import { messageWithIntent } from '@mysten/sui/cryptography'; -import { toB64 } from '@mysten/sui/utils'; +import { toBase64 } from '@mysten/sui/utils'; import mitt from 'mitt'; import { WalletSigner } from './WalletSigner'; @@ -86,7 +86,7 @@ export class QredoSigner extends WalletSigner { clientIdentifier, ); return { - messageBytes: toB64(input.message), + messageBytes: toBase64(input.message), signature, }; }; @@ -98,7 +98,7 @@ export class QredoSigner extends WalletSigner { clientIdentifier, ); return { - transactionBlockBytes: toB64(transactionBlockBytes), + transactionBlockBytes: toBase64(transactionBlockBytes), signature, }; }; @@ -157,7 +157,7 @@ export class QredoSigner extends WalletSigner { throw new Error(`Unsupported network ${networkNames[this.#apiEnv]}`); } const qredoTransaction = await this.#qredoAPI.createTransaction({ - messageWithIntent: toB64(intent), + messageWithIntent: toBase64(intent), network: this.#network, broadcast, from: await this.getAddress(), diff --git a/apps/wallet/src/ui/app/WalletSigner.ts b/apps/wallet/src/ui/app/WalletSigner.ts index d5df590a6b0ab..43bde1409db61 100644 --- a/apps/wallet/src/ui/app/WalletSigner.ts +++ b/apps/wallet/src/ui/app/WalletSigner.ts @@ -11,7 +11,7 @@ import { } from '@mysten/sui/client'; import { messageWithIntent } from '@mysten/sui/cryptography'; import { isTransaction, type Transaction } from '@mysten/sui/transactions'; -import { fromB64, toB64 } from '@mysten/sui/utils'; +import { fromBase64, toBase64 } from '@mysten/sui/utils'; export type SignedTransaction = { transactionBlockBytes: string; @@ -43,7 +43,7 @@ export abstract class WalletSigner { ); return { - messageBytes: toB64(input.message), + messageBytes: toBase64(input.message), signature, }; } @@ -59,7 +59,7 @@ export abstract class WalletSigner { } if (typeof transactionBlock === 'string') { - return fromB64(transactionBlock); + return fromBase64(transactionBlock); } if (transactionBlock instanceof Uint8Array) { @@ -78,7 +78,7 @@ export abstract class WalletSigner { const signature = await this.signData(messageWithIntent('TransactionData', bytes)); return { - transactionBlockBytes: toB64(bytes), + transactionBlockBytes: toBase64(bytes), signature, }; } diff --git a/apps/wallet/src/ui/app/background-client/index.ts b/apps/wallet/src/ui/app/background-client/index.ts index 669dbcbcc1ae6..44ba8c295c0c2 100644 --- a/apps/wallet/src/ui/app/background-client/index.ts +++ b/apps/wallet/src/ui/app/background-client/index.ts @@ -31,7 +31,7 @@ import { import { type SignedMessage, type SignedTransaction } from '_src/ui/app/WalletSigner'; import type { AppDispatch } from '_store'; import { type SuiTransactionBlockResponse } from '@mysten/sui/client'; -import { toB64 } from '@mysten/sui/utils'; +import { toBase64 } from '@mysten/sui/utils'; import { type QueryKey } from '@tanstack/react-query'; import { lastValueFrom, map, take } from 'rxjs'; @@ -156,7 +156,7 @@ export class BackgroundClient { createMessage>({ type: 'method-payload', method: 'signData', - args: { data: toB64(data), id: addressOrID }, + args: { data: toBase64(data), id: addressOrID }, }), ).pipe( take(1), diff --git a/apps/wallet/src/ui/app/components/known-scam-overlay/useDappPreflight.ts b/apps/wallet/src/ui/app/components/known-scam-overlay/useDappPreflight.ts index 24e0ca0b9e6b5..02e556ec5a601 100644 --- a/apps/wallet/src/ui/app/components/known-scam-overlay/useDappPreflight.ts +++ b/apps/wallet/src/ui/app/components/known-scam-overlay/useDappPreflight.ts @@ -3,7 +3,7 @@ import { useAppsBackend } from '@mysten/core'; import { useSuiClient } from '@mysten/dapp-kit'; import { type Transaction } from '@mysten/sui/transactions'; -import { toB64 } from '@mysten/sui/utils'; +import { toBase64 } from '@mysten/sui/utils'; import { useQuery } from '@tanstack/react-query'; import { @@ -45,7 +45,7 @@ export function useDappPreflight({ if (requestType === RequestType.SIGN_TRANSACTION && transaction) { const transactionBytes = await transaction.build({ client }); - body.transactionBytes = toB64(transactionBytes); + body.transactionBytes = toBase64(transactionBytes); } return request( diff --git a/apps/wallet/src/ui/app/index.tsx b/apps/wallet/src/ui/app/index.tsx index 2c289f192bcef..2096bc3554589 100644 --- a/apps/wallet/src/ui/app/index.tsx +++ b/apps/wallet/src/ui/app/index.tsx @@ -8,7 +8,7 @@ import { setNavVisibility } from '_redux/slices/app'; import { isLedgerAccountSerializedUI } from '_src/background/accounts/LedgerAccount'; import { persistableStorage } from '_src/shared/analytics/amplitude'; import { type LedgerAccountsPublicKeys } from '_src/shared/messaging/messages/payloads/MethodPayload'; -import { toB64 } from '@mysten/sui/utils'; +import { toBase64 } from '@mysten/sui/utils'; import { useEffect, useMemo } from 'react'; import { Navigate, Outlet, Route, Routes, useLocation } from 'react-router-dom'; import { throttle } from 'throttle-debounce'; @@ -115,7 +115,7 @@ const App = () => { const { publicKey } = await suiLedgerClient.getPublicKey(derivationPath); publicKeysToStore.push({ accountID: id, - publicKey: toB64(publicKey), + publicKey: toBase64(publicKey), }); } catch (e) { // do nothing diff --git a/apps/wallet/src/ui/app/pages/approval-request/transaction-request/TransactionDetails/Command.tsx b/apps/wallet/src/ui/app/pages/approval-request/transaction-request/TransactionDetails/Command.tsx index 4ea1f50afa5b8..b232413b7ebce 100644 --- a/apps/wallet/src/ui/app/pages/approval-request/transaction-request/TransactionDetails/Command.tsx +++ b/apps/wallet/src/ui/app/pages/approval-request/transaction-request/TransactionDetails/Command.tsx @@ -4,7 +4,7 @@ import { Text } from '_src/ui/app/shared/text'; import { ChevronDown12, ChevronRight12 } from '@mysten/icons'; import { type Argument, type Commands, type TransactionData } from '@mysten/sui/transactions'; -import { toB64 } from '@mysten/sui/utils'; +import { toBase64 } from '@mysten/sui/utils'; import { useState } from 'react'; type TransactionType = TransactionData['commands'][0]; @@ -34,7 +34,7 @@ function convertCommandArgumentToString( if (Array.isArray(arg)) { // Publish transaction special casing: if (typeof arg[0] === 'number') { - return toB64(new Uint8Array(arg as number[])); + return toBase64(new Uint8Array(arg as number[])); } return `[${arg.map((argVal) => convertCommandArgumentToString(argVal)).join(', ')}]`; diff --git a/apps/wallet/src/ui/app/pages/home/transactions/QredoTransaction.tsx b/apps/wallet/src/ui/app/pages/home/transactions/QredoTransaction.tsx index 148498a8dbcb6..c82e076cf92e2 100644 --- a/apps/wallet/src/ui/app/pages/home/transactions/QredoTransaction.tsx +++ b/apps/wallet/src/ui/app/pages/home/transactions/QredoTransaction.tsx @@ -8,7 +8,7 @@ import { useGetQredoTransaction } from '_src/ui/app/hooks/useGetQredoTransaction import { Text } from '_src/ui/app/shared/text'; import { formatDate, useOnScreen } from '@mysten/core'; import { bcs } from '@mysten/sui/bcs'; -import { fromB64 } from '@mysten/sui/utils'; +import { fromBase64 } from '@mysten/sui/utils'; import { useMemo, useRef } from 'react'; export type QredoTransactionProps = { @@ -26,7 +26,7 @@ export function QredoTransaction({ qredoID, qredoTransactionID }: QredoTransacti }); const messageWithIntent = useMemo(() => { if (data?.MessageWithIntent) { - return fromB64(data.MessageWithIntent); + return fromBase64(data.MessageWithIntent); } return null; }, [data?.MessageWithIntent]); diff --git a/apps/wallet/src/ui/app/redux/slices/transaction-requests/index.ts b/apps/wallet/src/ui/app/redux/slices/transaction-requests/index.ts index 082ba7a8e6ab7..a1c50666bc480 100644 --- a/apps/wallet/src/ui/app/redux/slices/transaction-requests/index.ts +++ b/apps/wallet/src/ui/app/redux/slices/transaction-requests/index.ts @@ -12,7 +12,7 @@ import { import type { AppThunkConfig } from '_store/thunk-extras'; import { type SuiTransactionBlockResponse } from '@mysten/sui/client'; import { Transaction } from '@mysten/sui/transactions'; -import { fromB64 } from '@mysten/sui/utils'; +import { fromBase64 } from '@mysten/sui/utils'; import { createAsyncThunk, createEntityAdapter, createSlice } from '@reduxjs/toolkit'; import type { PayloadAction } from '@reduxjs/toolkit'; @@ -56,7 +56,7 @@ export const respondToTransactionRequest = createAsyncThunk< if (txRequest.tx.type === 'sign-message') { txResult = await signer.signMessage( { - message: fromB64(txRequest.tx.message), + message: fromBase64(txRequest.tx.message), }, clientIdentifier, ); diff --git a/dapps/multisig-toolkit/src/routes/signature-analyzer.tsx b/dapps/multisig-toolkit/src/routes/signature-analyzer.tsx index 756ee2afbc275..a0bb875de2067 100644 --- a/dapps/multisig-toolkit/src/routes/signature-analyzer.tsx +++ b/dapps/multisig-toolkit/src/routes/signature-analyzer.tsx @@ -3,7 +3,7 @@ import { parseSerializedSignature, PublicKey, SignatureScheme } from '@mysten/sui/cryptography'; import { parsePartialSignatures } from '@mysten/sui/multisig'; -import { toB64 } from '@mysten/sui/utils'; +import { toBase64 } from '@mysten/sui/utils'; import { publicKeyFromRawBytes } from '@mysten/sui/verify'; import { AlertCircle } from 'lucide-react'; import { useState } from 'react'; @@ -47,7 +47,7 @@ function Signature({ signature, index }: { signature: SignaturePubkeyPair; index { label: 'Signature Public Key', value: pubkey }, { label: 'Sui Format Public Key ( flag | pk )', value: pubkey_base64_sui_format }, { label: 'Sui Address', value: suiAddress }, - { label: 'Signature', value: toB64(signature.signature) }, + { label: 'Signature', value: toBase64(signature.signature) }, ]; return ( diff --git a/docs/content/concepts/sui-move-concepts/packages/custom-policies.mdx b/docs/content/concepts/sui-move-concepts/packages/custom-policies.mdx index a110819dbca0b..fd027049982dd 100644 --- a/docs/content/concepts/sui-move-concepts/packages/custom-policies.mdx +++ b/docs/content/concepts/sui-move-concepts/packages/custom-policies.mdx @@ -553,7 +553,7 @@ import { readFileSync } from 'fs'; import { homedir } from 'os'; import path from 'path'; import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519'; -import { fromB64 } from '@mysten/sui/utils'; +import { fromBase64 } from '@mysten/sui/utils'; const sender = execSync(`${SUI} client active-address`, { encoding: 'utf8' }).trim(); const signer = (() => { @@ -562,7 +562,7 @@ const signer = (() => { ); for (const priv of keystore) { - const raw = fromB64(priv); + const raw = fromBase64(priv); if (raw[0] !== 0) { continue; } @@ -648,7 +648,7 @@ import { fileURLToPath } from 'url'; import { getFullnodeUrl, SuiClient } from '@mysten/sui/client'; import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519'; import { Transaction } from '@mysten/sui/transactions'; -import { fromB64 } from '@mysten/sui/utils'; +import { fromBase64 } from '@mysten/sui/utils'; const SUI = 'sui'; const POLICY_PACKAGE_ID = ''; @@ -659,7 +659,7 @@ const signer = (() => { ); for (const priv of keystore) { - const raw = fromB64(priv); + const raw = fromBase64(priv); if (raw[0] !== 0) { continue; } @@ -888,7 +888,7 @@ import { fileURLToPath } from 'url'; import { getFullnodeUrl, SuiClient } from '@mysten/sui/client'; import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519'; import { Transaction, UpgradePolicy } from '@mysten/sui/transactions'; -import { fromB64 } from '@mysten/sui/utils'; +import { fromBase64 } from '@mysten/sui/utils'; const SUI = 'sui'; const POLICY_PACKAGE_ID = ''; @@ -901,7 +901,7 @@ const signer = (() => { ); for (const priv of keystore) { - const raw = fromB64(priv); + const raw = fromBase64(priv); if (raw[0] !== 0) { continue; } diff --git a/docs/content/guides/developer/app-examples/weather-oracle.mdx b/docs/content/guides/developer/app-examples/weather-oracle.mdx index 3a40d1b7f7a48..92b823191a85f 100644 --- a/docs/content/guides/developer/app-examples/weather-oracle.mdx +++ b/docs/content/guides/developer/app-examples/weather-oracle.mdx @@ -430,7 +430,9 @@ First, initialize your backend project. To do this, you need to follow these ste - Create a new file named `init.ts` ```typescript title='init.ts' -import { Connection, Ed25519Keypair, JsonRpcProvider, RawSigner, Transaction } from '@mysten/sui'; +import { SuiClient } from '@mysten/sui/client'; +import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519'; +import { Transaction } from '@mysten/sui/transactions'; import * as dotenv from 'dotenv'; import { City } from './city'; @@ -444,12 +446,9 @@ dotenv.config({ path: '../.env' }); const phrase = process.env.ADMIN_PHRASE; const fullnode = process.env.FULLNODE!; const keypair = Ed25519Keypair.deriveKeypair(phrase!); -const provider = new JsonRpcProvider( - new Connection({ - fullnode: fullnode, - }), -); -const signer = new RawSigner(keypair, provider); +const client = new SuiClient({ + url: fullnode, +}); const packageId = process.env.PACKAGE_ID; const adminCap = process.env.ADMIN_CAP_ID!; @@ -462,7 +461,7 @@ async function addCityWeather() { const cities: City[] = await getCities(); const thousandGeoNameIds = await get1000Geonameids(); - const weatherOracleDynamicFields = await getWeatherOracleDynamicFields(provider, weatherOracleId); + const weatherOracleDynamicFields = await getWeatherOracleDynamicFields(client, weatherOracleId); const geonames = weatherOracleDynamicFields.map(function (obj) { return obj.name; }); @@ -502,8 +501,9 @@ async function addCityWeather() { async function signAndExecuteTransaction(transaction: Transaction) { transaction.setGasBudget(5000000000); - await signer + await client .signAndExecuteTransaction({ + signer: keypair, transaction, requestType: 'WaitForLocalExecution', options: { @@ -521,12 +521,11 @@ addCityWeather(); The code of init.ts does the following: -- Imports the necessary modules and classes from the library, such as `Connection`, `Ed25519Keypair`, `JsonRpcProvider`, `RawSigner`, and `Transaction`. +- Imports the necessary modules and classes from the library, such as `Ed25519Keypair`, `SuiClient`, and `Transaction`. - Imports the `dotenv` module to load environment variables from a .env file. - Imports some custom modules and functions from the local files, such as `City`, `get1000Geonameids`, `getCities`, `getWeatherOracleDynamicFields`, and `logger`. - Derives a key pair from a phrase stored in the `ADMIN_PHRASE` environment variable. -- Creates a provider object that connects to a Full node specified by the `FULLNODE` environment variable. -- Creates a signer object that uses the key pair and the provider to sign and execute transactions on the blockchain. +- Creates a sui client object that connects to a Full node specified by the `FULLNODE` environment variable. - Reads some other environment variables, such as `PACKAGE_ID`, `ADMIN_CAP_ID`, `WEATHER_ORACLE_ID`, and `MODULE_NAME`, which are used to identify the weather oracle contract and its methods. - Defines a constant `NUMBER_OF_CITIES`, which is the number of cities to be added to the weather oracle in each batch. - Defines an async function `addCityWeather`, which does the following: @@ -542,7 +541,9 @@ The code of init.ts does the following: You have now initialized the `WeatherOracle` shared object. The next step is to learn how to update them every 10 minutes with the latest weather data from the OpenWeatherMap API. ```typescript title='index.ts' -import { Connection, Ed25519Keypair, JsonRpcProvider, RawSigner, Transaction } from '@mysten/sui'; +import { SuiClient } from '@mysten/sui/client'; +import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519'; +import { Transaction } from '@mysten/sui/transactions'; import * as dotenv from 'dotenv'; import { City } from './city'; @@ -556,12 +557,9 @@ dotenv.config({ path: '../.env' }); const phrase = process.env.ADMIN_PHRASE; const fullnode = process.env.FULLNODE!; const keypair = Ed25519Keypair.deriveKeypair(phrase!); -const provider = new JsonRpcProvider( - new Connection({ - fullnode: fullnode, - }), -); -const signer = new RawSigner(keypair, provider); +const client = new SuiClient({ + url: fullnode, +}); const packageId = process.env.PACKAGE_ID; const adminCap = process.env.ADMIN_CAP_ID!; @@ -593,7 +591,8 @@ async function performUpdates( let transaction = await getTransaction(chunk); try { - await signer.signAndExecuteTransaction({ + await client.signAndExecuteTransaction({ + signer: keypair, transaction, }); } catch (e) { @@ -649,7 +648,7 @@ async function run() { const weatherOracleDynamicFields: { name: number; objectId: string; - }[] = await getWeatherOracleDynamicFields(provider, weatherOracleId); + }[] = await getWeatherOracleDynamicFields(client, weatherOracleId); performUpdates(cities, weatherOracleDynamicFields); } @@ -658,12 +657,12 @@ run(); The code in index.ts does the following: -- Uses `dotenv` to load some environment variables from a `.env` file, such as `ADMIN_PHRASE`, `FULLNODE`, `PACKAGE_ID`, `ADMIN_CAP_ID`, `WEATHER_ORACLE_ID`, `APPID`, and `MODULE_NAME`. These variables are used to configure some parameters for the code, such as the key pair, the provider, the signer, and the target package and module. +- Uses `dotenv` to load some environment variables from a `.env` file, such as `ADMIN_PHRASE`, `FULLNODE`, `PACKAGE_ID`, `ADMIN_CAP_ID`, `WEATHER_ORACLE_ID`, `APPID`, and `MODULE_NAME`. These variables are used to configure some parameters for the code, such as the key pair, the client, and the target package and module. - Defines some constants, such as `CHUNK_SIZE`, `MS`, `MINUTE`, and `TEN_MINUTES`. These constants are used to control the frequency and size of the updates that the code performs. - Defines an async function called `performUpdates`, which takes two arguments: `cities` and `weatherOracleDynamicFields`. This function is the main logic of the code, and it does the following: - Filters the `cities` array based on the `weatherOracleDynamicFields` array, which contains the names and object IDs of the weather oracle dynamic fields that the code needs to update. - Loops through the filtered cities in chunks of `CHUNK_SIZE`, and for each chunk, it calls another async function called `getTransaction`, which returns a transaction block that contains the Move calls to update the weather oracle dynamic fields with the latest weather data from the OpenWeatherMap API. - - Tries to sign and execute the transaction block using the signer, and catches any errors that may occur. + - Tries to sign and execute the transaction block using the client and keypair, and catches any errors that may occur. - Calculates the time it took to perform the updates, and sets a timeout to call itself again after `TEN_MINUTES` minus the elapsed time. - The code defines another async function called `getTransaction`, which takes one argument: `cities`. This function does the following: - Creates a new transaction block object. @@ -672,7 +671,7 @@ The code in index.ts does the following: - Returns the transaction block object. - An async `run` function is defined, which does the following: - Calls another async function called `getCities`, which returns an array of city objects that contain information such as name, geoname id, latitude, and longitude. - - Calls another async function called `getWeatherOracleDynamicFields`, which takes the package id, the module name, and the signer as arguments, and returns an array of weather oracle dynamic field objects that contain information such as name and object id. + - Calls another async function called `getWeatherOracleDynamicFields`, which takes the package id, the module name, and the client as arguments, and returns an array of weather oracle dynamic field objects that contain information such as name and object id. - Calls the `performUpdates` function with the cities and weather oracle dynamic fields arrays as arguments. Congratulations, you completed the Sui Weather Oracle tutorial. You can carry the lessons learned here forward when building your next Sui project. diff --git a/docs/content/guides/developer/nft/asset-tokenization.mdx b/docs/content/guides/developer/nft/asset-tokenization.mdx index 4c16de2ef3da3..4c27ec6ea3a25 100644 --- a/docs/content/guides/developer/nft/asset-tokenization.mdx +++ b/docs/content/guides/developer/nft/asset-tokenization.mdx @@ -527,7 +527,7 @@ User->>User's Kiosk: Resolve Promise by returning Tokenized Asset X in user's Ki The following sequence diagram shows the burn flow and assumes that: -- Tokenized asset has already been minted by the creator of its type. +- Tokenized asset has already been minted by the creator of its type. - Tokenized asset is already placed and locked inside the user's Kiosk. - Everything is executed in the same PTB. @@ -908,7 +908,7 @@ Lastly, to deploy the changed template module, build and publish: const tx = new Transaction(); tx.setGasBudget(100000000); const [upgradeCap] = tx.publish({ - modules: [[...fromHEX(bytesToPublish)], [...fromHEX(genesis_bytecode)]], + modules: [[...fromHex(bytesToPublish)], [...fromHex(genesis_bytecode)]], dependencies: [ normalizeSuiObjectId("0x1"), normalizeSuiObjectId("0x2"), diff --git a/docs/content/guides/developer/sui-101/building-ptb.mdx b/docs/content/guides/developer/sui-101/building-ptb.mdx index ede87b1477098..55347e8d1bc0a 100644 --- a/docs/content/guides/developer/sui-101/building-ptb.mdx +++ b/docs/content/guides/developer/sui-101/building-ptb.mdx @@ -10,7 +10,7 @@ This example starts by constructing a PTB to send Sui. If you are familiar with ```ts import { Transaction } from '@mysten/sui/transactions'; -const txb = new Transaction(); +const tx = new Transaction(); ``` Using this, you can then add transactions to this PTB. @@ -18,10 +18,10 @@ Using this, you can then add transactions to this PTB. ```ts // Create a new coin with balance 100, based on the coins used as gas payment. // You can define any balance here. -const [coin] = txb.splitCoins(txb.gas, [txb.pure(100)]); +const [coin] = tx.splitCoins(tx.gas, [tx.pure(100)]); // Transfer the split coin to a specific address. -txb.transferObjects([coin], txb.pure('0xSomeSuiAddress')); +tx.transferObjects([coin], tx.pure('0xSomeSuiAddress')); ``` You can attach multiple transaction commands of the same type to a PTB as well. For example, to get a list of transfers, and iterate over them to transfer coins to each of them: @@ -35,24 +35,24 @@ interface Transfer { // Procure a list of some Sui transfers to make: const transfers: Transfer[] = getTransfers(); -const txb = new Transaction(); +const tx = new Transaction(); // First, split the gas coin into multiple coins: -const coins = txb.splitCoins( - txb.gas, - transfers.map((transfer) => txb.pure(transfer.amount)), +const coins = tx.splitCoins( + tx.gas, + transfers.map((transfer) => tx.pure(transfer.amount)), ); // Next, create a transfer transaction for each coin: transfers.forEach((transfer, index) => { - txb.transferObjects([coins[index]], txb.pure(transfer.to)); + tx.transferObjects([coins[index]], tx.pure(transfer.to)); }); ``` -After you have the PTB defined, you can directly execute it with a `signer` using `signAndExecuteTransaction`. +After you have the Transaction defined, you can directly execute it with a `SuiClient` and `KeyPair` using `client.signAndExecuteTransaction`. ```ts -signer.signAndExecuteTransaction({ transaction: txb }); +client.signAndExecuteTransaction({ signer: keypair, transaction: tx }); ``` ## Constructing inputs @@ -61,8 +61,8 @@ Inputs are how you provide external values to PTBs. For example, defining an amo There are currently two ways to define inputs: -- For objects: the `txb.object(objectId)` function is used to construct an input that contains an object reference. -- For pure values: the `txb.pure(value, type?)` function is used to construct an input for a non-object input. +- For objects: the `tx.object(objectId)` function is used to construct an input that contains an object reference. +- For pure values: the `tx.pure(value, type?)` function is used to construct an input for a non-object input. - If value is a `Uint8Array`, then the value is assumed to be raw bytes and is used directly. - If type is provided, it's used to generate the BCS serialization layout for the value. If not provided, the type is automatically determined based on the value. @@ -70,17 +70,17 @@ There are currently two ways to define inputs: Sui supports following transaction commands: -- `txb.splitCoins(coin, amounts)`: Creates new coins with the defined amounts, split from the provided coin. Returns the coins so that it can be used in subsequent transactions. - - Example: `txb.splitCoins(txb.gas, [txb.pure(100), txb.pure(200)])` -- `txb.mergeCoins(destinationCoin, sourceCoins)`: Merges the sourceCoins into the destinationCoin. - - Example: `txb.mergeCoins(txb.object(coin1), [txb.object(coin2), txb.object(coin3)])` -- `txb.transferObjects(objects, address)`: Transfers a list of objects to the specified address. - - Example: `txb.transferObjects([txb.object(thing1), txb.object(thing2)], txb.pure(myAddress))` -- `txb.moveCall({ target, arguments, typeArguments })`: Executes a Move call. Returns whatever the Sui Move call returns. - - Example: `txb.moveCall({ target: '0x2::devnet_nft::mint', arguments: [txb.pure(name), txb.pure(description), txb.pure(image)] })` -- `txb.makeMoveVec({ type, elements })`: Constructs a vector of objects that can be passed into a moveCall. This is required as there's no other way to define a vector as an input. - - Example: `txb.makeMoveVec({ elements: [txb.object(id1), txb.object(id2)] })` -- `txb.publish(modules, dependencies)`: Publishes a Move package. Returns the upgrade capability object. +- `tx.splitCoins(coin, amounts)`: Creates new coins with the defined amounts, split from the provided coin. Returns the coins so that it can be used in subsequent transactions. + - Example: `tx.splitCoins(tx.gas, [tx.pure(100), tx.pure(200)])` +- `tx.mergeCoins(destinationCoin, sourceCoins)`: Merges the sourceCoins into the destinationCoin. + - Example: `tx.mergeCoins(tx.object(coin1), [tx.object(coin2), tx.object(coin3)])` +- `tx.transferObjects(objects, address)`: Transfers a list of objects to the specified address. + - Example: `tx.transferObjects([tx.object(thing1), tx.object(thing2)], tx.pure(myAddress))` +- `tx.moveCall({ target, arguments, typeArguments })`: Executes a Move call. Returns whatever the Sui Move call returns. + - Example: `tx.moveCall({ target: '0x2::devnet_nft::mint', arguments: [tx.pure(name), tx.pure(description), tx.pure(image)] })` +- `tx.makeMoveVec({ type, elements })`: Constructs a vector of objects that can be passed into a moveCall. This is required as there's no other way to define a vector as an input. + - Example: `tx.makeMoveVec({ elements: [tx.object(id1), tx.object(id2)] })` +- `tx.publish(modules, dependencies)`: Publishes a Move package. Returns the upgrade capability object. ## Passing transaction results as arguments @@ -88,26 +88,26 @@ You can use the result of a transaction command as an argument in subsequent tra ```ts // Split a coin object off of the gas object: -const [coin] = txb.splitCoins(txb.gas, [txb.pure(100)]); +const [coin] = tx.splitCoins(tx.gas, [tx.pure(100)]); // Transfer the resulting coin object: -txb.transferObjects([coin], txb.pure(address)); +tx.transferObjects([coin], tx.pure(address)); ``` When a transaction command returns multiple results, you can access the result at a specific index either using destructuring, or array indexes. ```ts // Destructuring (preferred, as it gives you logical local names): -const [nft1, nft2] = txb.moveCall({ target: '0x2::nft::mint_many' }); -txb.transferObjects([nft1, nft2], txb.pure(address)); +const [nft1, nft2] = tx.moveCall({ target: '0x2::nft::mint_many' }); +tx.transferObjects([nft1, nft2], tx.pure(address)); // Array indexes: -const mintMany = txb.moveCall({ target: '0x2::nft::mint_many' }); -txb.transferObjects([mintMany[0], mintMany[1]], txb.pure(address)); +const mintMany = tx.moveCall({ target: '0x2::nft::mint_many' }); +tx.transferObjects([mintMany[0], mintMany[1]], tx.pure(address)); ``` ## Use the gas coin -With PTBs, you can use the gas payment coin to construct coins with a set balance using `splitCoin`. This is useful for Sui payments, and avoids the need for up-front coin selection. You can use `txb.gas` to access the gas coin in a PTB, and it is valid as input for any arguments; with the exception of `transferObjects`, `txb.gas` must be used by-reference. Practically speaking, this means you can also add to the gas coin with `mergeCoins` or borrow it for Move functions with `moveCall`. +With PTBs, you can use the gas payment coin to construct coins with a set balance using `splitCoin`. This is useful for Sui payments, and avoids the need for up-front coin selection. You can use `tx.gas` to access the gas coin in a PTB, and it is valid as input for any arguments; with the exception of `transferObjects`, `tx.gas` must be used by-reference. Practically speaking, this means you can also add to the gas coin with `mergeCoins` or borrow it for Move functions with `moveCall`. You can also transfer the gas coin using `transferObjects`, in the event that you want to transfer all of your coin balance to another address. @@ -122,11 +122,11 @@ You might need to explicitly call `setSender()` on the PTB to ensure that the `s ::: ```ts -const txb = new Transaction(); +const tx = new Transaction(); // ... add some transactions... -await txb.build({ provider }); +await tx.build({ provider }); ``` In most cases, building requires your JSON RPC provider to fully resolve input values. @@ -135,7 +135,7 @@ If you have PTB bytes, you can also convert them back into a `Transaction` class ```ts const bytes = getTransactionBytesFromSomewhere(); -const txb = Transaction.from(bytes); +const tx = Transaction.from(bytes); ``` ## Building offline @@ -146,13 +146,13 @@ In the event that you want to build a PTB offline (as in with no `provider` requ import { Inputs } from '@mysten/sui/transactions'; // For pure values: -txb.pure(pureValueAsBytes); +tx.pure(pureValueAsBytes); // For owned or immutable objects: -txb.object(Inputs.ObjectRef({ digest, objectId, version })); +tx.object(Inputs.ObjectRef({ digest, objectId, version })); // For shared objects: -txb.object(Inputs.SharedObjectRef({ objectId, initialSharedVersion, mutable })); +tx.object(Inputs.SharedObjectRef({ objectId, initialSharedVersion, mutable })); ``` You can then omit the `provider` object when calling `build` on the transaction. If there is any required data that is missing, this will throw an error. @@ -166,7 +166,7 @@ The new transaction builder comes with default behavior for all gas logic, inclu By default, the gas price is set to the reference gas price of the network. You can also explicitly set the gas price of the PTB by calling `setGasPrice` on the transaction builder. ```ts -txb.setGasPrice(gasPrice); +tx.setGasPrice(gasPrice); ``` ### Budget @@ -180,7 +180,7 @@ The gas budget is represented in Sui, and should take the gas price of the PTB i ::: ```ts -txb.setGasBudget(gasBudgetAmount); +tx.setGasBudget(gasBudgetAmount); ``` ### Gas payment @@ -192,14 +192,16 @@ The list of coins used as gas payment will be merged down into a single gas coin ```ts // NOTE: You need to ensure that the coins do not overlap with any // of the input objects for the PTB. -txb.setGasPayment([coin1, coin2]); +tx.setGasPayment([coin1, coin2]); ``` +Gas coins should be objects containing the coins objectId, version, and digest (ie `{ objectId: string, version: string | number, digest: string }`). + ### dApp / Wallet integration The Wallet Standard interface has been updated to support the `Transaction` kind directly. All `signTransaction` and `signAndExecuteTransaction` calls from dApps into wallets is expected to provide a `Transaction` class. This PTB class can then be serialized and sent to your wallet for execution. -To serialize a PTB for sending to a wallet, Sui recommends using the `txb.serialize()` function, which returns an opaque string representation of the PTB that can be passed from the wallet standard dApp context to your wallet. This can then be converted back into a `Transaction` using `Transaction.from()`. +To serialize a PTB for sending to a wallet, Sui recommends using the `tx.serialize()` function, which returns an opaque string representation of the PTB that can be passed from the wallet standard dApp context to your wallet. This can then be converted back into a `Transaction` using `Transaction.from()`. :::tip @@ -228,16 +230,16 @@ function handleSignRequest(input) { The PTB builder can support sponsored PTBs by using the `onlyTransactionKind` flag when building the PTB. ```ts -const txb = new Transaction(); +const tx = new Transaction(); // ... add some transactions... -const kindBytes = await txb.build({ provider, onlyTransactionKind: true }); +const kindBytes = await tx.build({ provider, onlyTransactionKind: true }); // Construct a sponsored transaction from the kind bytes: -const sponsoredTxb = Transaction.fromKind(kindBytes); +const sponsoredTx = Transaction.fromKind(kindBytes); // You can now set the sponsored transaction data that is required: -sponsoredTxb.setSender(sender); -sponsoredTxb.setGasOwner(sponsor); -sponsoredTxb.setGasPayment(sponsorCoins); +sponsoredTx.setSender(sender); +sponsoredTx.setGasOwner(sponsor); +sponsoredTx.setGasPayment(sponsorCoins); ``` diff --git a/docs/content/guides/developer/sui-101/sign-and-send-txn.mdx b/docs/content/guides/developer/sui-101/sign-and-send-txn.mdx index 60b11fd269ead..406da4557ecd1 100644 --- a/docs/content/guides/developer/sui-101/sign-and-send-txn.mdx +++ b/docs/content/guides/developer/sui-101/sign-and-send-txn.mdx @@ -40,7 +40,7 @@ The following examples demonstrate how to sign and execute transactions using Ru There are various ways to instantiate a key pair and to derive its public key and Sui address using the Sui TypeScript SDK. ```tsx -import { fromHEX } from '@mysten/bcs'; +import { fromHex } from '@mysten/bcs'; import { getFullnodeUrl, SuiClient } from '@mysten/sui/client'; import { type Keypair } from '@mysten/sui/cryptography'; import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519'; diff --git a/docs/content/standards/deepbookv2/routing-a-swap.mdx b/docs/content/standards/deepbookv2/routing-a-swap.mdx index 776efbb740157..b18ad0344182f 100644 --- a/docs/content/standards/deepbookv2/routing-a-swap.mdx +++ b/docs/content/standards/deepbookv2/routing-a-swap.mdx @@ -22,7 +22,7 @@ To use the smart routing functionality, one should first find the best route. Th public async findBestRoute(tokenInObject: string, tokenOut: string, amountIn: number): Promise { // const tokenTypeIn: string = convertToTokenType(tokenIn, this.records); // should get the tokenTypeIn from tokenInObject - const tokenInfo = await this.provider.getObject({ + const tokenInfo = await this.suiClient.getObject({ id: tokenInObject, options: { showType: true, @@ -159,9 +159,9 @@ public async placeMarketOrderWithSmartRouting( i += 1; } } - const r = await this.provider.dryRunTransactionBlock({ + const r = await this.suiClient.dryRunTransactionBlock({ transactionBlock: await overrides.txb.build({ - provider: this.provider, + client: this.suiClient, }), }); if (r.effects.status.status === 'success') { diff --git a/docs/content/standards/wallet-standard.mdx b/docs/content/standards/wallet-standard.mdx index 6ea35087b588a..98244e5227581 100644 --- a/docs/content/standards/wallet-standard.mdx +++ b/docs/content/standards/wallet-standard.mdx @@ -179,7 +179,7 @@ registerWallet(new YourWallet()); ### Best practices for efficient transaction execution -The Wallet standard has been updated from its original design to better support changes in the Sui ecosystem. For example, the GraphQL service was introduced after Mainnet launched. The `sui:signAndExecuteTransactionBlock` feature is closely tied to the JSON RPC options and data structures, so its continued maintenance becomes increasingly difficult as the GraphQL service becomes more ubiquitous. +The Wallet standard has been updated from its original design to better support changes in the Sui ecosystem. For example, the GraphQL service was introduced after Mainnet launched. The `sui:signAndExecuteTransactionBlock` feature is closely tied to the JSON RPC options and data structures, so its continued maintenance becomes increasingly difficult as the GraphQL service becomes more ubiquitous. Consequently, the Wallet standard introduced the `sui:signAndExecuteTransaction` feature. The features of this method are more useful, regardless of which API you use to execute transactions. This usefulness comes at the expense of flexibility in what `sui:signAndExecuteTransaction` returns. @@ -214,12 +214,12 @@ The Wallet standard includes features to help your apps interact with wallets. To query the installed wallets in a user's browser, use the `get` function of `getWallets`. ```tsx -import { getWallets } from "@mysten/wallet-standard"; +import { getWallets } from '@mysten/wallet-standard'; const availableWallets = getWallets().get(); ``` -The return from this call (`availableWallets` in the previous code) is an array of `Wallet` types. +The return from this call (`availableWallets` in the previous code) is an array of `Wallet` types. Use the `Wallet.icon` and `Wallet.name` attributes to display the wallet details on your web page. @@ -238,7 +238,7 @@ Connecting in the context of a wallet refers to a user that joins the web site f The feature that provides this functionality is called `standard:connect`. To connect using this feature, make the following call: ```tsx -wallet.features['standard:connect'].connect() // connect call +wallet.features['standard:connect'].connect(); // connect call ``` This call results in the wallet opening a pop-up dialog for the user to continue the connection process. @@ -277,8 +277,10 @@ client.executeTransactionBlock({ Your app then sends the transaction effects back to the wallet, which reports results to the user. The wallet expects the effects to be `b64` encoded. ```tsx +import { toBase64 } from '@mysten/sui/utils'; + wallet.features['sui:reportTransactionEffects'].reportTransactionEffects( - effects: Array.isArray(transactionResponse.effects) ? toB64( + effects: Array.isArray(transactionResponse.effects) ? toBase64( Uint8Array.from(transactionResponse.effects) : transactionResponse.effects, account: wallet.accounts[0], // for example chain: wallet.chains[0] @@ -309,7 +311,7 @@ The wallet standard only defines the change event that can apply to chains, feat To subscribe your apps to events with the following call: ```tsx -const unsubscribe = wallet.features['standard:events'].on ('change', callback); +const unsubscribe = wallet.features['standard:events'].on('change', callback); ``` This call returns a function that can be called to unsubscribe from listening to the events. diff --git a/examples/tic-tac-toe/ui/src/components/NewMultiSigGame.tsx b/examples/tic-tac-toe/ui/src/components/NewMultiSigGame.tsx index d1770005093ef..1bf7d988db16b 100644 --- a/examples/tic-tac-toe/ui/src/components/NewMultiSigGame.tsx +++ b/examples/tic-tac-toe/ui/src/components/NewMultiSigGame.tsx @@ -3,7 +3,7 @@ import { useCurrentAccount } from '@mysten/dapp-kit'; import { PublicKey } from '@mysten/sui/cryptography'; -import { fromB64, toB64 } from '@mysten/sui/utils'; +import { fromBase64, toBase64 } from '@mysten/sui/utils'; import { publicKeyFromRawBytes } from '@mysten/sui/verify'; import { ExclamationTriangleIcon } from '@radix-ui/react-icons'; import { Box, Button, Em, Flex, Separator, Spinner, Text, TextField } from '@radix-ui/themes'; @@ -50,7 +50,7 @@ export function NewMultiSigGame(): ReactElement { return ( <> - + { ); for (const priv of keystore) { - const raw = fromB64(priv); + const raw = fromBase64(priv); if (raw[0] !== 0) { continue; } diff --git a/sdk/bcs/README.md b/sdk/bcs/README.md index f203928d24aee..fe0715c83a3f3 100644 --- a/sdk/bcs/README.md +++ b/sdk/bcs/README.md @@ -16,12 +16,12 @@ npm i @mysten/bcs ## Quickstart ```ts -import { bcs } from '@mysten/bcs'; +import { bcs, fromHex, toHex } from '@mysten/bcs'; // define UID as a 32-byte array, then add a transform to/from hex strings const UID = bcs.fixedArray(32, bcs.u8()).transform({ - input: (id: string) => fromHEX(id), - output: (id) => toHEX(Uint8Array.from(id)), + input: (id: string) => fromHex(id), + output: (id) => toHex(Uint8Array.from(id)), }); const Coin = bcs.struct('Coin', { @@ -114,9 +114,9 @@ import { bcs } from '@mysten/bcs'; const intList = bcs.vector(bcs.u8()).serialize([1, 2, 3, 4, 5]).toBytes(); const stringList = bcs.vector(bcs.string()).serialize(['a', 'b', 'c']).toBytes(); -// Arrays -const intArray = bcs.array(4, bcs.u8()).serialize([1, 2, 3, 4]).toBytes(); -const stringArray = bcs.array(3, bcs.string()).serialize(['a', 'b', 'c']).toBytes(); +// Fixed length Arrays +const intArray = bcs.fixedArray(4, bcs.u8()).serialize([1, 2, 3, 4]).toBytes(); +const stringArray = bcs.fixedArray(3, bcs.string()).serialize(['a', 'b', 'c']).toBytes(); // Option const option = bcs.option(bcs.string()).serialize('some value').toBytes(); @@ -127,7 +127,7 @@ const MyEnum = bcs.enum('MyEnum', { NoType: null, Int: bcs.u8(), String: bcs.string(), - Array: bcs.array(3, bcs.u8()), + Array: bcs.fixedArray(3, bcs.u8()), }); const noTypeEnum = MyEnum.serialize({ NoType: null }).toBytes(); @@ -163,8 +163,8 @@ const map = bcs const parsedIntList = bcs.vector(bcs.u8()).parse(intList); const parsedStringList = bcs.vector(bcs.string()).parse(stringList); -// Arrays -const parsedIntArray = bcs.array(4, bcs.u8()).parse(intArray); +// Fixed length Arrays +const parsedIntArray = bcs.fixedArray(4, bcs.u8()).parse(intArray); // Option const parsedOption = bcs.option(bcs.string()).parse(option); @@ -242,10 +242,12 @@ represent an address as a hex string, but the BCS serialization format for addre array. To handle this, you can use the `transform` API to map between the two formats: ```ts +import { bcs, toHex } from '@mysten/bcs'; + const Address = bcs.bytes(32).transform({ // To change the input type, you need to provide a type definition for the input - input: (val: string) => fromHEX(val), - output: (val) => toHEX(val), + input: (val: string) => fromHex(val), + output: (val) => toHex(val), }); const serialized = Address.serialize('0x000000...').toBytes(); @@ -306,7 +308,7 @@ preserves type information for the serialized bytes, and can be used to get raw formats. ```ts -import { bcs, fromB58, fromB64, fromHex } from '@mysten/bcs'; +import { bcs, fromBase58, fromBase64, fromHex } from '@mysten/bcs'; const serializedString = bcs.string().serialize('this is a string'); @@ -323,8 +325,8 @@ const str1 = bcs.string().parse(bytes); // If your data is encoded as string, you need to convert it to Uint8Array first const str2 = bcs.string().parse(fromHex(hex)); -const str3 = bcs.string().parse(fromB64(base64)); -const str4 = bcs.string().parse(fromB58(base58)); +const str3 = bcs.string().parse(fromBase64(base64)); +const str4 = bcs.string().parse(fromBase58(base58)); console.assert((str1 == str2) == (str3 == str4), 'Result is the same'); ``` diff --git a/sdk/bcs/src/b58.ts b/sdk/bcs/src/b58.ts index 266c307641c9c..5c904c08975a6 100644 --- a/sdk/bcs/src/b58.ts +++ b/sdk/bcs/src/b58.ts @@ -3,5 +3,11 @@ import bs58 from 'bs58'; -export const toB58 = (buffer: Uint8Array) => bs58.encode(buffer); -export const fromB58 = (str: string) => bs58.decode(str); +export const toBase58 = (buffer: Uint8Array) => bs58.encode(buffer); +export const fromBase58 = (str: string) => bs58.decode(str); + +/** @deprecated use toBase58 instead */ +export const toB58 = toBase58; + +/** @deprecated use fromBase58 instead */ +export const fromB58 = fromBase58; diff --git a/sdk/bcs/src/b64.ts b/sdk/bcs/src/b64.ts index bae9797418529..837bff75175c9 100644 --- a/sdk/bcs/src/b64.ts +++ b/sdk/bcs/src/b64.ts @@ -1,12 +1,12 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -export function fromB64(base64String: string): Uint8Array { +export function fromBase64(base64String: string): Uint8Array { return Uint8Array.from(atob(base64String), (char) => char.charCodeAt(0)); } const CHUNK_SIZE = 8192; -export function toB64(bytes: Uint8Array): string { +export function toBase64(bytes: Uint8Array): string { // Special-case the simple case for speed's sake. if (bytes.length < CHUNK_SIZE) { return btoa(String.fromCharCode(...bytes)); @@ -20,3 +20,9 @@ export function toB64(bytes: Uint8Array): string { return btoa(output); } + +/** @deprecated use toBase64 instead */ +export const toB64 = toBase64; + +/** @deprecated use fromBase64 instead */ +export const fromB64 = fromBase64; diff --git a/sdk/bcs/src/bcs-type.ts b/sdk/bcs/src/bcs-type.ts index 788a8b0dd2bf7..5ab84d30ebc43 100644 --- a/sdk/bcs/src/bcs-type.ts +++ b/sdk/bcs/src/bcs-type.ts @@ -1,9 +1,9 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { fromB58, toB58 } from './b58.js'; -import { fromB64, toB64 } from './b64.js'; -import { fromHEX, toHEX } from './hex.js'; +import { fromBase58, toBase58 } from './b58.js'; +import { fromBase64, toBase64 } from './b64.js'; +import { fromHex, toHex } from './hex.js'; import { BcsReader } from './reader.js'; import { ulebEncode } from './uleb.js'; import type { BcsWriterOptions } from './writer.js'; @@ -68,15 +68,15 @@ export class BcsType { } fromHex(hex: string) { - return this.parse(fromHEX(hex)); + return this.parse(fromHex(hex)); } fromBase58(b64: string) { - return this.parse(fromB58(b64)); + return this.parse(fromBase58(b64)); } fromBase64(b64: string) { - return this.parse(fromB64(b64)); + return this.parse(fromBase64(b64)); } transform({ @@ -127,15 +127,15 @@ export class SerializedBcs { } toHex() { - return toHEX(this.#bytes); + return toHex(this.#bytes); } toBase64() { - return toB64(this.#bytes); + return toBase64(this.#bytes); } toBase58() { - return toB58(this.#bytes); + return toBase58(this.#bytes); } parse() { diff --git a/sdk/bcs/src/hex.ts b/sdk/bcs/src/hex.ts index 52ee08775e758..53d1620c17924 100644 --- a/sdk/bcs/src/hex.ts +++ b/sdk/bcs/src/hex.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -export function fromHEX(hexStr: string): Uint8Array { +export function fromHex(hexStr: string): Uint8Array { const normalized = hexStr.startsWith('0x') ? hexStr.slice(2) : hexStr; const padded = normalized.length % 2 === 0 ? normalized : `0${normalized}}`; const intArr = padded.match(/.{2}/g)?.map((byte) => parseInt(byte, 16)) ?? []; @@ -9,6 +9,12 @@ export function fromHEX(hexStr: string): Uint8Array { return Uint8Array.from(intArr); } -export function toHEX(bytes: Uint8Array): string { +export function toHex(bytes: Uint8Array): string { return bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), ''); } + +/** @deprecated use toHex instead */ +export const toHEX = toHex; + +/** @deprecated use fromHex instead */ +export const fromHEX = fromHex; diff --git a/sdk/bcs/src/index.ts b/sdk/bcs/src/index.ts index 3803c3c0d3a4c..9a24402c32d42 100644 --- a/sdk/bcs/src/index.ts +++ b/sdk/bcs/src/index.ts @@ -11,12 +11,12 @@ * @property {BcsReader} */ -import { fromB58, toB58 } from './b58.js'; -import { fromB64, toB64 } from './b64.js'; +import { fromB58, fromBase58, toB58, toBase58 } from './b58.js'; +import { fromB64, fromBase64, toB64, toBase64 } from './b64.js'; import type { BcsTypeOptions } from './bcs-type.js'; import { BcsType, isSerializedBcs, SerializedBcs } from './bcs-type.js'; import { bcs } from './bcs.js'; -import { fromHEX, toHEX } from './hex.js'; +import { fromHEX, fromHex, toHEX, toHex } from './hex.js'; import { BcsReader } from './reader.js'; import type { EnumInputShape, @@ -38,10 +38,16 @@ export { isSerializedBcs, toB58, fromB58, + toBase58, + fromBase58, toB64, fromB64, + toBase64, + fromBase64, fromHEX, toHEX, + toHex, + fromHex, encodeStr, decodeStr, splitGenericParameters, diff --git a/sdk/bcs/src/utils.ts b/sdk/bcs/src/utils.ts index b781c9ebc7c3b..3eb1e8b47de03 100644 --- a/sdk/bcs/src/utils.ts +++ b/sdk/bcs/src/utils.ts @@ -1,9 +1,9 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { fromB58, toB58 } from './b58.js'; -import { fromB64, toB64 } from './b64.js'; -import { fromHEX, toHEX } from './hex.js'; +import { fromBase58, toBase58 } from './b58.js'; +import { fromBase64, toBase64 } from './b64.js'; +import { fromHex, toHex } from './hex.js'; import type { Encoding } from './types.js'; /** @@ -16,11 +16,11 @@ import type { Encoding } from './types.js'; export function encodeStr(data: Uint8Array, encoding: Encoding): string { switch (encoding) { case 'base58': - return toB58(data); + return toBase58(data); case 'base64': - return toB64(data); + return toBase64(data); case 'hex': - return toHEX(data); + return toHex(data); default: throw new Error('Unsupported encoding, supported values are: base64, hex'); } @@ -36,11 +36,11 @@ export function encodeStr(data: Uint8Array, encoding: Encoding): string { export function decodeStr(data: string, encoding: Encoding): Uint8Array { switch (encoding) { case 'base58': - return fromB58(data); + return fromBase58(data); case 'base64': - return fromB64(data); + return fromBase64(data); case 'hex': - return fromHEX(data); + return fromHex(data); default: throw new Error('Unsupported encoding, supported values are: base64, hex'); } diff --git a/sdk/bcs/tests/bcs.test.ts b/sdk/bcs/tests/bcs.test.ts index 11e117781bec9..e1f6559898e35 100644 --- a/sdk/bcs/tests/bcs.test.ts +++ b/sdk/bcs/tests/bcs.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest'; -import { bcs, fromB64 } from './../src/index'; +import { bcs, fromBase64 } from './../src/index'; describe('BCS: Primitives', () => { it('should support growing size', () => { @@ -22,7 +22,7 @@ describe('BCS: Primitives', () => { const setBytes = Coin.serialize(expected, { initialSize: 1, maxSize: 1024 }); - expect(Coin.parse(fromB64(rustBcs))).toEqual(expected); + expect(Coin.parse(fromBase64(rustBcs))).toEqual(expected); expect(setBytes.toBase64()).toEqual(rustBcs); }); diff --git a/sdk/bcs/tests/builder.test.ts b/sdk/bcs/tests/builder.test.ts index 7e67e09ec2cff..b91962e096512 100644 --- a/sdk/bcs/tests/builder.test.ts +++ b/sdk/bcs/tests/builder.test.ts @@ -3,7 +3,7 @@ import { describe, expect, test } from 'vitest'; -import { BcsReader, BcsWriter, toB58, toB64, toHEX } from '../src'; +import { BcsReader, BcsWriter, toBase58, toBase64, toHex } from '../src'; import { BcsType } from '../src/bcs-type.js'; import { bcs } from '../src/bcs.js'; @@ -261,17 +261,17 @@ function testType( test(name, () => { const serialized = schema.serialize(value); const bytes = serialized.toBytes(); - expect(toHEX(bytes)).toBe(hex); + expect(toHex(bytes)).toBe(hex); expect(serialized.toHex()).toBe(hex); - expect(serialized.toBase64()).toBe(toB64(bytes)); - expect(serialized.toBase58()).toBe(toB58(bytes)); + expect(serialized.toBase64()).toBe(toBase64(bytes)); + expect(serialized.toBase58()).toBe(toBase58(bytes)); const deserialized = schema.parse(bytes); expect(deserialized).toEqual(expected); const writer = new BcsWriter({ initialSize: bytes.length }); schema.write(value, writer); - expect(toHEX(writer.toBytes())).toBe(hex); + expect(toHex(writer.toBytes())).toBe(hex); const reader = new BcsReader(bytes); diff --git a/sdk/bcs/tests/encodings.test.ts b/sdk/bcs/tests/encodings.test.ts index f60252088de4c..11c91b3fb2df8 100644 --- a/sdk/bcs/tests/encodings.test.ts +++ b/sdk/bcs/tests/encodings.test.ts @@ -3,38 +3,38 @@ import { describe, expect, it } from 'vitest'; -import { bcs, fromB58, fromB64, fromHEX, toHEX } from './../src/index'; +import { bcs, fromBase58, fromBase64, fromHex, toHex } from './../src/index'; describe('BCS: Encodings', () => { it('should de/ser hex, base58 and base64', () => { - expect(bcs.u8().parse(fromB64('AA=='))).toEqual(0); - expect(bcs.u8().parse(fromHEX('00'))).toEqual(0); - expect(bcs.u8().parse(fromB58('1'))).toEqual(0); + expect(bcs.u8().parse(fromBase64('AA=='))).toEqual(0); + expect(bcs.u8().parse(fromHex('00'))).toEqual(0); + expect(bcs.u8().parse(fromBase58('1'))).toEqual(0); const STR = 'this is a test string'; const str = bcs.string().serialize(STR); - expect(bcs.string().parse(fromB58(str.toBase58()))).toEqual(STR); - expect(bcs.string().parse(fromB64(str.toBase64()))).toEqual(STR); - expect(bcs.string().parse(fromHEX(str.toHex()))).toEqual(STR); + expect(bcs.string().parse(fromBase58(str.toBase58()))).toEqual(STR); + expect(bcs.string().parse(fromBase64(str.toBase64()))).toEqual(STR); + expect(bcs.string().parse(fromHex(str.toHex()))).toEqual(STR); }); it('should deserialize hex with leading 0s', () => { const addressLeading0 = 'a7429d7a356dd98f688f11a330a32e0a3cc1908734a8c5a5af98f34ec93df0c'; - expect(toHEX(Uint8Array.from([0, 1]))).toEqual('0001'); - expect(fromHEX('0x1')).toEqual(Uint8Array.from([1])); - expect(fromHEX('1')).toEqual(Uint8Array.from([1])); - expect(fromHEX('111')).toEqual(Uint8Array.from([1, 17])); - expect(fromHEX('001')).toEqual(Uint8Array.from([0, 1])); - expect(fromHEX('011')).toEqual(Uint8Array.from([0, 17])); - expect(fromHEX('0011')).toEqual(Uint8Array.from([0, 17])); - expect(fromHEX('0x0011')).toEqual(Uint8Array.from([0, 17])); - expect(fromHEX(addressLeading0)).toEqual( + expect(toHex(Uint8Array.from([0, 1]))).toEqual('0001'); + expect(fromHex('0x1')).toEqual(Uint8Array.from([1])); + expect(fromHex('1')).toEqual(Uint8Array.from([1])); + expect(fromHex('111')).toEqual(Uint8Array.from([1, 17])); + expect(fromHex('001')).toEqual(Uint8Array.from([0, 1])); + expect(fromHex('011')).toEqual(Uint8Array.from([0, 17])); + expect(fromHex('0011')).toEqual(Uint8Array.from([0, 17])); + expect(fromHex('0x0011')).toEqual(Uint8Array.from([0, 17])); + expect(fromHex(addressLeading0)).toEqual( Uint8Array.from([ 10, 116, 41, 215, 163, 86, 221, 152, 246, 136, 241, 26, 51, 10, 50, 224, 163, 204, 25, 8, 115, 74, 140, 90, 90, 249, 143, 52, 236, 147, 223, 12, ]), ); - expect(toHEX(fromHEX(addressLeading0))).toEqual(`0${addressLeading0}`); + expect(toHex(fromHex(addressLeading0))).toEqual(`0${addressLeading0}`); }); }); diff --git a/sdk/dapp-kit/src/hooks/wallet/useReportTransactionEffects.ts b/sdk/dapp-kit/src/hooks/wallet/useReportTransactionEffects.ts index c3dec6068b093..554d93f4fe3cd 100644 --- a/sdk/dapp-kit/src/hooks/wallet/useReportTransactionEffects.ts +++ b/sdk/dapp-kit/src/hooks/wallet/useReportTransactionEffects.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { toB64 } from '@mysten/sui/utils'; +import { toBase64 } from '@mysten/sui/utils'; import type { SuiReportTransactionEffectsInput } from '@mysten/wallet-standard'; import type { UseMutationOptions, UseMutationResult } from '@tanstack/react-query'; import { useMutation } from '@tanstack/react-query'; @@ -71,7 +71,7 @@ export function useReportTransactionEffects({ if (reportTransactionEffectsFeature) { return await reportTransactionEffectsFeature.reportTransactionEffects({ - effects: Array.isArray(effects) ? toB64(new Uint8Array(effects)) : effects, + effects: Array.isArray(effects) ? toBase64(new Uint8Array(effects)) : effects, account, chain: chain ?? currentWallet?.chains[0], }); diff --git a/sdk/dapp-kit/src/hooks/wallet/useSignAndExecuteTransaction.ts b/sdk/dapp-kit/src/hooks/wallet/useSignAndExecuteTransaction.ts index 4d65fc333f654..f09902e7e04c3 100644 --- a/sdk/dapp-kit/src/hooks/wallet/useSignAndExecuteTransaction.ts +++ b/sdk/dapp-kit/src/hooks/wallet/useSignAndExecuteTransaction.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import type { Transaction } from '@mysten/sui/transactions'; -import { toB64 } from '@mysten/sui/utils'; +import { toBase64 } from '@mysten/sui/utils'; import type { SuiSignAndExecuteTransactionInput, SuiSignAndExecuteTransactionOutput, @@ -100,7 +100,7 @@ export function useSignAndExecuteTransaction< return { digest, rawEffects, - effects: toB64(new Uint8Array(rawEffects!)), + effects: toBase64(new Uint8Array(rawEffects!)), bytes, signature, }; @@ -153,7 +153,7 @@ export function useSignAndExecuteTransaction< if ('effects' in result && result.effects?.bcs) { effects = result.effects.bcs; } else if ('rawEffects' in result) { - effects = toB64(new Uint8Array(result.rawEffects!)); + effects = toBase64(new Uint8Array(result.rawEffects!)); } else { throw new Error('Could not parse effects from transaction result.'); } diff --git a/sdk/dapp-kit/src/hooks/wallet/useUnsafeBurnerWallet.ts b/sdk/dapp-kit/src/hooks/wallet/useUnsafeBurnerWallet.ts index 69010e0485dd9..2c302bc29977d 100644 --- a/sdk/dapp-kit/src/hooks/wallet/useUnsafeBurnerWallet.ts +++ b/sdk/dapp-kit/src/hooks/wallet/useUnsafeBurnerWallet.ts @@ -4,7 +4,7 @@ import type { SuiClient } from '@mysten/sui/client'; import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519'; import { Transaction } from '@mysten/sui/transactions'; -import { toB64 } from '@mysten/sui/utils'; +import { toBase64 } from '@mysten/sui/utils'; import type { StandardConnectFeature, StandardConnectMethod, @@ -198,7 +198,7 @@ function registerUnsafeBurnerWallet(suiClient: SuiClient) { bytes, signature, digest, - effects: toB64(new Uint8Array(rawEffects!)), + effects: toBase64(new Uint8Array(rawEffects!)), }; }; } diff --git a/sdk/dapp-kit/test/hooks/useSignAndExecuteTransaction.test.tsx b/sdk/dapp-kit/test/hooks/useSignAndExecuteTransaction.test.tsx index f8a92a610272b..f220d4da0b474 100644 --- a/sdk/dapp-kit/test/hooks/useSignAndExecuteTransaction.test.tsx +++ b/sdk/dapp-kit/test/hooks/useSignAndExecuteTransaction.test.tsx @@ -7,7 +7,7 @@ import { Transaction } from '@mysten/sui/transactions'; import { act, renderHook, waitFor } from '@testing-library/react'; import { expect, type Mock } from 'vitest'; -import { toB58 } from '../../../bcs/dist/cjs/b58.js'; +import { toBase58 } from '../../../bcs/dist/cjs/b58.js'; import { WalletFeatureNotSupportedError, WalletNotConnectedError, @@ -154,7 +154,7 @@ describe('useSignAndExecuteTransaction', () => { const wrapper = createWalletProviderContextWrapper({}, suiClient); - const fakeDigest = toB58( + const fakeDigest = toBase58( new Uint8Array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, diff --git a/sdk/docs/pages/bcs/index.mdx b/sdk/docs/pages/bcs/index.mdx index ae8b9ec1b2dff..76479c8eec3a0 100644 --- a/sdk/docs/pages/bcs/index.mdx +++ b/sdk/docs/pages/bcs/index.mdx @@ -16,12 +16,12 @@ npm i @mysten/bcs ## Quickstart ```ts -import { bcs } from '@mysten/bcs'; +import { bcs, fromHex, toHex } from '@mysten/bcs'; // define UID as a 32-byte array, then add a transform to/from hex strings const UID = bcs.fixedArray(32, bcs.u8()).transform({ - input: (id: string) => fromHEX(id), - output: (id) => toHEX(Uint8Array.from(id)), + input: (id: string) => fromHex(id), + output: (id) => toHex(Uint8Array.from(id)), }); const Coin = bcs.struct('Coin', { @@ -114,9 +114,9 @@ import { bcs } from '@mysten/bcs'; const intList = bcs.vector(bcs.u8()).serialize([1, 2, 3, 4, 5]).toBytes(); const stringList = bcs.vector(bcs.string()).serialize(['a', 'b', 'c']).toBytes(); -// Arrays -const intArray = bcs.array(4, bcs.u8()).serialize([1, 2, 3, 4]).toBytes(); -const stringArray = bcs.array(3, bcs.string()).serialize(['a', 'b', 'c']).toBytes(); +// Fixed length Arrays +const intArray = bcs.fixedArray(4, bcs.u8()).serialize([1, 2, 3, 4]).toBytes(); +const stringArray = bcs.fixedArray(3, bcs.string()).serialize(['a', 'b', 'c']).toBytes(); // Option const option = bcs.option(bcs.string()).serialize('some value').toBytes(); @@ -127,7 +127,7 @@ const MyEnum = bcs.enum('MyEnum', { NoType: null, Int: bcs.u8(), String: bcs.string(), - Array: bcs.array(3, bcs.u8()), + Array: bcs.fixedArray(3, bcs.u8()), }); const noTypeEnum = MyEnum.serialize({ NoType: null }).toBytes(); @@ -163,8 +163,8 @@ const map = bcs const parsedIntList = bcs.vector(bcs.u8()).parse(intList); const parsedStringList = bcs.vector(bcs.string()).parse(stringList); -// Arrays -const parsedIntArray = bcs.array(4, bcs.u8()).parse(intArray); +// Fixed length Arrays +const parsedIntArray = bcs.fixedArray(4, bcs.u8()).parse(intArray); // Option const parsedOption = bcs.option(bcs.string()).parse(option); @@ -242,10 +242,12 @@ represent an address as a hex string, but the BCS serialization format for addre array. To handle this, you can use the `transform` API to map between the two formats: ```ts +import { bcs, fromHex, toHex } from '@mysten/bcs'; + const Address = bcs.bytes(32).transform({ // To change the input type, you need to provide a type definition for the input - input: (val: string) => fromHEX(val), - output: (val) => toHEX(val), + input: (val: string) => fromHex(val), + output: (val) => toHex(val), }); const serialized = Address.serialize('0x000000...').toBytes(); @@ -306,7 +308,7 @@ preserves type information for the serialized bytes, and can be used to get raw formats. ```ts -import { bcs, fromB58, fromB64, fromHex } from '@mysten/bcs'; +import { bcs, fromBase58, fromBase64, fromHex } from '@mysten/bcs'; const serializedString = bcs.string().serialize('this is a string'); @@ -323,8 +325,8 @@ const str1 = bcs.string().parse(bytes); // If your data is encoded as string, you need to convert it to Uint8Array first const str2 = bcs.string().parse(fromHex(hex)); -const str3 = bcs.string().parse(fromB64(base64)); -const str4 = bcs.string().parse(fromB58(base58)); +const str3 = bcs.string().parse(fromBase64(base64)); +const str4 = bcs.string().parse(fromBase58(base58)); console.assert((str1 == str2) == (str3 == str4), 'Result is the same'); ``` diff --git a/sdk/docs/pages/dapp-kit/wallet-hooks/useReportTransactionEffects.mdx b/sdk/docs/pages/dapp-kit/wallet-hooks/useReportTransactionEffects.mdx index 47b6f81012b1d..171d9b11e5594 100644 --- a/sdk/docs/pages/dapp-kit/wallet-hooks/useReportTransactionEffects.mdx +++ b/sdk/docs/pages/dapp-kit/wallet-hooks/useReportTransactionEffects.mdx @@ -14,7 +14,7 @@ import { useReportTransactionEffects, useSuiClient, } from '@mysten/dapp-kit'; -import { toB64 } from '@mysten/sui/utils'; +import { toBase64 } from '@mysten/sui/utils'; import { useState } from 'react'; function MyComponent() { diff --git a/sdk/docs/pages/dapp-kit/wallet-hooks/useSignTransaction.mdx b/sdk/docs/pages/dapp-kit/wallet-hooks/useSignTransaction.mdx index 546968ebb1ab1..ea27d51a6a6b4 100644 --- a/sdk/docs/pages/dapp-kit/wallet-hooks/useSignTransaction.mdx +++ b/sdk/docs/pages/dapp-kit/wallet-hooks/useSignTransaction.mdx @@ -12,7 +12,7 @@ import { useSignTransaction, useSuiClient, } from '@mysten/dapp-kit'; -import { toB64 } from '@mysten/sui/utils'; +import { toBase64 } from '@mysten/sui/utils'; import { useState } from 'react'; function MyComponent() { diff --git a/sdk/docs/pages/typescript/cryptography/keypairs.mdx b/sdk/docs/pages/typescript/cryptography/keypairs.mdx index b779184e20059..ba7c173b8f0c5 100644 --- a/sdk/docs/pages/typescript/cryptography/keypairs.mdx +++ b/sdk/docs/pages/typescript/cryptography/keypairs.mdx @@ -172,6 +172,21 @@ const keypair = Ed25519Keypair.fromSecretKey(secretKey); See [SIP-15](https://github.com/sui-foundation/sips/blob/main/sips/sip-15.md) for additional context and motivation. +If you know your keypair schema, you can use the `fromSecretKey` method of the appropriate keypair +to directly derive the keypair from the secret key. + +```typescript +const secretKey = 'suiprivkey1qzse89atw7d3zum8ujep76d2cxmgduyuast0y9fu23xcl0mpafgkktllhyc'; + +const keypair = Ed25519Keypair.fromSecretKey(secretKey); +``` + +You can also export a keypair to a Bech32 encoded secret key using the `getSecretKey` method. + +```typescript +const secretKey = keypair.getSecretKey(); +``` + ## Deriving a `Keypair` from a hex encoded secret key If you have an existing secret key formatted as a hex encoded string, you can derive a `Keypair` by diff --git a/sdk/docs/pages/typescript/cryptography/multisig.mdx b/sdk/docs/pages/typescript/cryptography/multisig.mdx index 51e042813f4c4..93e0c55213a72 100644 --- a/sdk/docs/pages/typescript/cryptography/multisig.mdx +++ b/sdk/docs/pages/typescript/cryptography/multisig.mdx @@ -142,7 +142,7 @@ const multisigAddress = multiSigPublicKey.toSuiAddress(); const zkLoginSig = getZkLoginSignature({ inputs: zkLoginInputs, maxEpoch: '2', - userSignature: fromB64(ephemeralSig), + userSignature: fromBase64(ephemeralSig), }); // a valid multisig with just the zklogin signature. diff --git a/sdk/docs/pages/typescript/owned-object-pool/overview.mdx b/sdk/docs/pages/typescript/owned-object-pool/overview.mdx index e0f5b66ab4bb6..9dd21a07e54a3 100644 --- a/sdk/docs/pages/typescript/owned-object-pool/overview.mdx +++ b/sdk/docs/pages/typescript/owned-object-pool/overview.mdx @@ -77,7 +77,7 @@ transaction. If you need SUI for a test network, you can import { SuiClient } from '@mysten/sui/client'; import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519'; import { Transaction } from '@mysten/sui/transactions'; -import { fromB64 } from '@mysten/sui/utils'; +import { fromBase64 } from '@mysten/sui/utils'; /* HERE ARE DEFINED THE PREPARATORY STEPS IF YOU WANT TO CODE ALONG*/ // Define the transaction @@ -92,7 +92,7 @@ function createPaymenttx(recipient: string): Transaction { } // Define your admin keypair and client const ADMIN_SECRET_KEY: string = ''; -const adminPrivateKeyArray = Uint8Array.from(Array.from(fromB64(ADMIN_SECRET_KEY))); +const adminPrivateKeyArray = Uint8Array.from(Array.from(fromBase64(ADMIN_SECRET_KEY))); const adminKeypair = Ed25519Keypair.fromSecretKey(adminPrivateKeyArray.slice(1)); const client = new SuiClient({ diff --git a/sdk/docs/pages/typescript/transaction-building/gas.mdx b/sdk/docs/pages/typescript/transaction-building/gas.mdx index b7b8bd145c9d9..96ab0c99bc8d5 100644 --- a/sdk/docs/pages/typescript/transaction-building/gas.mdx +++ b/sdk/docs/pages/typescript/transaction-building/gas.mdx @@ -54,3 +54,6 @@ will be the coin that all others are merged into. // of the input objects for the transaction tx.setGasPayment([coin1, coin2]); ``` + +Gas coins should be objects containing the coins objectId, version, and digest (ie +`{ objectId: string, version: string | number, digest: string }`). diff --git a/sdk/docs/pages/typescript/utils.mdx b/sdk/docs/pages/typescript/utils.mdx index dc5d3ee155e76..d738b1cafc82d 100644 --- a/sdk/docs/pages/typescript/utils.mdx +++ b/sdk/docs/pages/typescript/utils.mdx @@ -43,7 +43,7 @@ case, or exists on chain). The following methods are re-exported to help with converting between commonly used encodings -- `fromHEX`: Deserializes a hex string to a Uint8Array -- `toHEX`: Serializes a Uint8Array to a hex string -- `fromB64`: Deserializes a base64 string to a Uint8Array -- `toB64`: Serializes a Uint8Array to a base64 string +- `fromHex`: Deserializes a hex string to a Uint8Array +- `toHex`: Serializes a Uint8Array to a hex string +- `fromBase64`: Deserializes a base64 string to a Uint8Array +- `toBase64`: Serializes a Uint8Array to a base64 string diff --git a/sdk/enoki/src/EnokiFlow.ts b/sdk/enoki/src/EnokiFlow.ts index ad1bb67f04e0d..b2a00b5b77fb8 100644 --- a/sdk/enoki/src/EnokiFlow.ts +++ b/sdk/enoki/src/EnokiFlow.ts @@ -5,7 +5,7 @@ import type { SuiClient } from '@mysten/sui/client'; import { decodeSuiPrivateKey } from '@mysten/sui/cryptography'; import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519'; import type { Transaction } from '@mysten/sui/transactions'; -import { fromB64, toB64 } from '@mysten/sui/utils'; +import { fromBase64, toBase64 } from '@mysten/sui/utils'; import type { ZkLoginSignatureInputs } from '@mysten/sui/zklogin'; import { decodeJwt } from 'jose'; import type { WritableAtom } from 'nanostores'; @@ -163,7 +163,7 @@ export class EnokiFlow { expiresAt: estimatedExpiration, maxEpoch, randomness, - ephemeralKeyPair: toB64(decodeSuiPrivateKey(ephemeralKeyPair.getSecretKey()).secretKey), + ephemeralKeyPair: toBase64(decodeSuiPrivateKey(ephemeralKeyPair.getSecretKey()).secretKey), }); return oauthUrl; @@ -273,7 +273,7 @@ export class EnokiFlow { throw new Error('Missing required parameters for proof generation'); } - const ephemeralKeyPair = Ed25519Keypair.fromSecretKey(fromB64(zkp.ephemeralKeyPair)); + const ephemeralKeyPair = Ed25519Keypair.fromSecretKey(fromBase64(zkp.ephemeralKeyPair)); const proof = await this.#enokiClient.createZkLoginZkp({ network, @@ -311,7 +311,7 @@ export class EnokiFlow { address, maxEpoch: zkp.maxEpoch, proof: zkp.proof, - ephemeralKeypair: Ed25519Keypair.fromSecretKey(fromB64(zkp.ephemeralKeyPair)), + ephemeralKeypair: Ed25519Keypair.fromSecretKey(fromBase64(zkp.ephemeralKeyPair)), }); } @@ -338,7 +338,7 @@ export class EnokiFlow { return await this.#enokiClient.createSponsoredTransaction({ jwt: session.jwt, network, - transactionKindBytes: toB64(transactionKindBytes), + transactionKindBytes: toBase64(transactionKindBytes), }); } @@ -354,7 +354,7 @@ export class EnokiFlow { client: SuiClient; }) { const keypair = await this.getKeypair({ network }); - const userSignature = await keypair.signTransaction(fromB64(bytes)); + const userSignature = await keypair.signTransaction(fromBase64(bytes)); await this.#enokiClient.executeSponsoredTransaction({ digest, diff --git a/sdk/enoki/src/encryption.ts b/sdk/enoki/src/encryption.ts index 6a12071a0b79f..7f517af270946 100644 --- a/sdk/enoki/src/encryption.ts +++ b/sdk/enoki/src/encryption.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { fromB64, toB64 } from '@mysten/sui/utils'; +import { fromBase64, toBase64 } from '@mysten/sui/utils'; /** * An interface @@ -63,9 +63,9 @@ export function createDefaultEncryption(): Encryption { ); return JSON.stringify({ - payload: toB64(new Uint8Array(payload)), - iv: toB64(iv), - salt: toB64(salt), + payload: toBase64(new Uint8Array(payload)), + iv: toBase64(iv), + salt: toBase64(salt), } satisfies EncryptedJSON); }, async decrypt(password, data) { @@ -74,15 +74,15 @@ export function createDefaultEncryption(): Encryption { throw new Error('Invalid encrypted data'); } - const { derivedKey } = await keyFromPassword(password, fromB64(parsed.salt)); + const { derivedKey } = await keyFromPassword(password, fromBase64(parsed.salt)); const decryptedContent = await crypto.subtle.decrypt( { name: 'AES-GCM', - iv: fromB64(parsed.iv), + iv: fromBase64(parsed.iv), }, derivedKey, - fromB64(parsed.payload), + fromBase64(parsed.payload), ); return new TextDecoder().decode(decryptedContent); diff --git a/sdk/graphql-transport/src/mappers/bcs.ts b/sdk/graphql-transport/src/mappers/bcs.ts index 8c507ec5f07ba..8438155c20556 100644 --- a/sdk/graphql-transport/src/mappers/bcs.ts +++ b/sdk/graphql-transport/src/mappers/bcs.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { toB64 } from '@mysten/bcs'; +import { toBase64 } from '@mysten/bcs'; import type { BcsType } from '@mysten/bcs'; import { bcs } from '@mysten/sui/bcs'; @@ -57,5 +57,5 @@ export function layoutToBcs(layout: MoveTypeLayout): BcsType { export function mapJsonToBcs(json: unknown, layout: MoveTypeLayout) { const schema = layoutToBcs(layout); - return toB64(schema.serialize(json).toBytes()); + return toBase64(schema.serialize(json).toBytes()); } diff --git a/sdk/graphql-transport/src/mappers/transaction-block.ts b/sdk/graphql-transport/src/mappers/transaction-block.ts index 5dad4ae1036e1..5424ab058f458 100644 --- a/sdk/graphql-transport/src/mappers/transaction-block.ts +++ b/sdk/graphql-transport/src/mappers/transaction-block.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { fromB64, toB58 } from '@mysten/bcs'; +import { fromBase64, toBase58 } from '@mysten/bcs'; import { bcs } from '@mysten/sui/bcs'; import type { SuiArgument, @@ -47,7 +47,7 @@ export function mapGraphQLTransactionBlockToRpcTransactionBlock( ...(options?.showRawEffects ? { rawEffects: transactionBlock.effects?.bcs - ? Array.from(fromB64(transactionBlock.effects?.bcs)) + ? Array.from(fromBase64(transactionBlock.effects?.bcs)) : undefined, } : {}), @@ -73,7 +73,7 @@ export function mapGraphQLTransactionBlockToRpcTransactionBlock( transaction: transactionBlock.rawTransaction && mapTransactionBlockToInput( - bcs.SenderSignedData.parse(fromB64(transactionBlock.rawTransaction))[0], + bcs.SenderSignedData.parse(fromBase64(transactionBlock.rawTransaction))[0], ), } : {}), @@ -214,7 +214,7 @@ function mapTransactionInput(input: typeof bcs.CallArg.$inferType): SuiCallArg { if (input.Pure) { return { type: 'pure', - value: fromB64(input.Pure.bytes), + value: fromBase64(input.Pure.bytes), }; } @@ -340,13 +340,13 @@ function mapTransactionArgument(arg: typeof bcs.Argument.$inferType): SuiArgumen throw new Error(`Unknown argument type ${arg}`); } -const OBJECT_DIGEST_DELETED = toB58(Uint8Array.from({ length: 32 }, () => 99)); -const OBJECT_DIGEST_WRAPPED = toB58(Uint8Array.from({ length: 32 }, () => 88)); -const OBJECT_DIGEST_ZERO = toB58(Uint8Array.from({ length: 32 }, () => 0)); +const OBJECT_DIGEST_DELETED = toBase58(Uint8Array.from({ length: 32 }, () => 99)); +const OBJECT_DIGEST_WRAPPED = toBase58(Uint8Array.from({ length: 32 }, () => 88)); +const OBJECT_DIGEST_ZERO = toBase58(Uint8Array.from({ length: 32 }, () => 0)); const ADDRESS_ZERO = normalizeSuiAddress('0x0'); export function mapEffects(data: string): SuiTransactionBlockResponse['effects'] { - const effects = bcs.TransactionEffects.parse(fromB64(data)); + const effects = bcs.TransactionEffects.parse(fromBase64(data)); let effectsV1 = effects.V1; diff --git a/sdk/graphql-transport/src/methods.ts b/sdk/graphql-transport/src/methods.ts index 011e965897b84..006dbab71f7cd 100644 --- a/sdk/graphql-transport/src/methods.ts +++ b/sdk/graphql-transport/src/methods.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { fromB64, toB58 } from '@mysten/bcs'; +import { fromBase64, toBase58 } from '@mysten/bcs'; import type { MoveValue, ProtocolConfigValue, @@ -948,12 +948,12 @@ export const RPC_METHODS: { : { Result: ref.input.cmd, }, - Array.from(fromB64(ref.bcs)), + Array.from(fromBase64(ref.bcs)), toShortTypeString(ref.type.repr), ], ), returnValues: result.returnValues?.map((value) => [ - Array.from(fromB64(value.bcs)), + Array.from(fromBase64(value.bcs)), toShortTypeString(value.type.repr), ]), })), @@ -974,7 +974,7 @@ export const RPC_METHODS: { return { data: fields.map((field) => ({ - bcsName: field.name?.bcs && toB58(fromB64(field.name.bcs)), + bcsName: field.name?.bcs && toBase58(fromBase64(field.name.bcs)), digest: (field.value?.__typename === 'MoveObject' ? field.value.digest : undefined)!, name: { type: toShortTypeString(field.name?.type.repr)!, @@ -1077,7 +1077,7 @@ export const RPC_METHODS: { ); if (!effects?.transactionBlock) { - const tx = Transaction.from(fromB64(txBytes)); + const tx = Transaction.from(fromBase64(txBytes)); return { errors: errors ?? undefined, digest: await tx.getDigest() }; } @@ -1090,7 +1090,7 @@ export const RPC_METHODS: { ); }, async dryRunTransactionBlock(transport, [txBytes]) { - const tx = Transaction.from(fromB64(txBytes)); + const tx = Transaction.from(fromBase64(txBytes)); const { transaction, error } = await transport.graphqlQuery( { query: DryRunTransactionBlockDocument, diff --git a/sdk/kiosk/src/query/transfer-policy.ts b/sdk/kiosk/src/query/transfer-policy.ts index a2931f6e5caf8..7b3af43a447d4 100644 --- a/sdk/kiosk/src/query/transfer-policy.ts +++ b/sdk/kiosk/src/query/transfer-policy.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import type { SuiClient } from '@mysten/sui/client'; -import { fromB64, isValidSuiAddress } from '@mysten/sui/utils'; +import { fromBase64, isValidSuiAddress } from '@mysten/sui/utils'; import '../bcs.js'; @@ -50,7 +50,7 @@ export async function queryTransferPolicy( throw new Error(`Invalid policy: ${policy?.objectId}, expected object, got package`); } - const parsed = TransferPolicyType.parse(fromB64(policy.bcs.bcsBytes)); + const parsed = TransferPolicyType.parse(fromBase64(policy.bcs.bcsBytes)); return { id: policy?.objectId, diff --git a/sdk/kiosk/src/utils.ts b/sdk/kiosk/src/utils.ts index 3d8293c4e09a9..7c9eede989ffa 100644 --- a/sdk/kiosk/src/utils.ts +++ b/sdk/kiosk/src/utils.ts @@ -11,7 +11,7 @@ import type { SuiObjectResponse, } from '@mysten/sui/client'; import { - fromB64, + fromBase64, normalizeStructTag, normalizeSuiAddress, parseStructTag, @@ -34,7 +34,7 @@ export async function getKioskObject(client: SuiClient, id: string): Promise { }); function pokemonBytes() { - return fromHEX( + return fromHex( 'a11ceb0b060000000a01000202020403064b055139078a019b0108a5022006c5021e0ae302140cf702f7030dee0610000a000007000009000100000d00010000020201000008030400000b050100000506010000010607000004060700000c060700000e060700000f06070000060607000010060800000309050000070a050004060800060800020201030603030303030308020202020202020a0201080000010608000102010a02020708000301070800010104030303030553746174730661747461636b0664616d6167650b64656372656173655f687007646566656e7365026870056c6576656c086c6576656c5f7570036e65770f706879736963616c5f64616d6167650a706f6b656d6f6e5f7631077363616c696e670e7370656369616c5f61747461636b0e7370656369616c5f64616d6167650f7370656369616c5f646566656e73650573706565640574797065730000000000000000000000000000000000000000000000000000000000000000030800ca9a3b0000000003080000000000000000030801000000000000000002080503010204020c020e020f020602100a02000100000b320a0331d92604090a0331ff250c04050b090c040b04040e05140b01010b00010701270a023100240419051f0b01010b00010702270a00100014340b00100114340b01100214340b02340b03340700110202010100000b320a0331d92604090a0331ff250c04050b090c040b04040e05140b01010b00010701270a023100240419051f0b01010b00010702270a00100014340b00100314340b01100414340b02340b03340700110202020000000c2a0602000000000000000b0018060100000000000000180605000000000000001a060200000000000000160c070a050b01180b021a0c060b070b03180b06180632000000000000001a0602000000000000000a0518160c080a050b041806ff000000000000001a0c090b080b0918060100000000000000180b051a0203010000050d0b00340700180b010b020b030b040b050b060b071200020401000005020700020501000005040b00100514020601000005040b00100114020701000005040b00100214020801000005040b00100314020901000005040b00100414020a01000005040b00100614020b01000005040b00100014020c01000005040b00100714020d01000005140a010a0010051424040b0600000000000000000b000f051505130a001005140b01170b000f0515020e01000005090a001000143101160b000f0015020006000100020003000400000005000700', ); } function coinTemplateBytes() { - return fromHEX( + return fromHex( 'a11ceb0b060000000a01000c020c1e032a1c044608054e46079401a10108b50260069503390ace03050cd30329000e010b0206020f021002110002020001010701000002000c01000102030c01000104040200050507000009000100010a01040100020706070102030c0b01010c040d08090001030205030a030202080007080400010b02010800010805010b01010900010800070900020a020a020a020b01010805070804020b030109000b02010900010608040105010b03010800020900050c436f696e4d65746164617461064f7074696f6e0854454d504c4154450b5472656173757279436170095478436f6e746578740355726c04636f696e0f6372656174655f63757272656e63790b64756d6d795f6669656c6404696e6974046e6f6e65066f7074696f6e0f7075626c69635f7472616e736665720673656e6465720874656d706c617465087472616e736665720a74785f636f6e746578740375726c0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000020201060a020504544d504c0a020e0d54656d706c61746520436f696e0a021a1954656d706c61746520436f696e204465736372697074696f6e00020108010000000002130b00070007010702070338000a0138010c020a012e110438020b020b012e110438030200', ); } diff --git a/sdk/typescript/src/bcs/bcs.ts b/sdk/typescript/src/bcs/bcs.ts index 54a8b63e3468f..615d3f0bbf9d0 100644 --- a/sdk/typescript/src/bcs/bcs.ts +++ b/sdk/typescript/src/bcs/bcs.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import type { BcsType, BcsTypeOptions } from '@mysten/bcs'; -import { bcs, fromB58, fromB64, fromHEX, toB58, toB64, toHEX } from '@mysten/bcs'; +import { bcs, fromBase58, fromBase64, fromHex, toBase58, toBase64, toHex } from '@mysten/bcs'; import { isValidSuiAddress, normalizeSuiAddress, SUI_ADDRESS_LENGTH } from '../utils/sui-types.js'; import { TypeTagSerializer } from './type-tag-serializer.js'; @@ -29,22 +29,22 @@ function optionEnum>(type: T) { export const Address = bcs.bytes(SUI_ADDRESS_LENGTH).transform({ validate: (val) => { - const address = typeof val === 'string' ? val : toHEX(val); + const address = typeof val === 'string' ? val : toHex(val); if (!address || !isValidSuiAddress(normalizeSuiAddress(address))) { throw new Error(`Invalid Sui address ${address}`); } }, input: (val: string | Uint8Array) => - typeof val === 'string' ? fromHEX(normalizeSuiAddress(val)) : val, - output: (val) => normalizeSuiAddress(toHEX(val)), + typeof val === 'string' ? fromHex(normalizeSuiAddress(val)) : val, + output: (val) => normalizeSuiAddress(toHex(val)), }); export const ObjectDigest = bcs.vector(bcs.u8()).transform({ name: 'ObjectDigest', - input: (value: string) => fromB58(value), - output: (value) => toB58(new Uint8Array(value)), + input: (value: string) => fromBase58(value), + output: (value) => toBase58(new Uint8Array(value)), validate: (value) => { - if (fromB58(value).length !== 32) { + if (fromBase58(value).length !== 32) { throw new Error('ObjectDigest must be 32 bytes'); } }, @@ -71,8 +71,8 @@ export const ObjectArg = bcs.enum('ObjectArg', { export const CallArg = bcs.enum('CallArg', { Pure: bcs.struct('Pure', { bytes: bcs.vector(bcs.u8()).transform({ - input: (val: string | Uint8Array) => (typeof val === 'string' ? fromB64(val) : val), - output: (val) => toB64(new Uint8Array(val)), + input: (val: string | Uint8Array) => (typeof val === 'string' ? fromBase64(val) : val), + output: (val) => toBase64(new Uint8Array(val)), }), }), Object: ObjectArg, @@ -147,8 +147,8 @@ export const Command = bcs.enum('Command', { Publish: bcs.struct('Publish', { modules: bcs.vector( bcs.vector(bcs.u8()).transform({ - input: (val: string | Uint8Array) => (typeof val === 'string' ? fromB64(val) : val), - output: (val) => toB64(new Uint8Array(val)), + input: (val: string | Uint8Array) => (typeof val === 'string' ? fromBase64(val) : val), + output: (val) => toBase64(new Uint8Array(val)), }), ), dependencies: bcs.vector(Address), @@ -175,8 +175,8 @@ export const Command = bcs.enum('Command', { Upgrade: bcs.struct('Upgrade', { modules: bcs.vector( bcs.vector(bcs.u8()).transform({ - input: (val: string | Uint8Array) => (typeof val === 'string' ? fromB64(val) : val), - output: (val) => toB64(new Uint8Array(val)), + input: (val: string | Uint8Array) => (typeof val === 'string' ? fromBase64(val) : val), + output: (val) => toBase64(new Uint8Array(val)), }), ), dependencies: bcs.vector(Address), @@ -286,8 +286,8 @@ export const MultiSig = bcs.struct('MultiSig', { }); export const base64String = bcs.vector(bcs.u8()).transform({ - input: (val: string | Uint8Array) => (typeof val === 'string' ? fromB64(val) : val), - output: (val) => toB64(new Uint8Array(val)), + input: (val: string | Uint8Array) => (typeof val === 'string' ? fromBase64(val) : val), + output: (val) => toBase64(new Uint8Array(val)), }); export const SenderSignedTransaction = bcs.struct('SenderSignedTransaction', { diff --git a/sdk/typescript/src/client/client.ts b/sdk/typescript/src/client/client.ts index c425f9f3d2148..6ae32e9f513b5 100644 --- a/sdk/typescript/src/client/client.ts +++ b/sdk/typescript/src/client/client.ts @@ -1,6 +1,6 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { fromB58, toB64, toHEX } from '@mysten/bcs'; +import { fromBase58, toBase64, toHex } from '@mysten/bcs'; import type { Signer } from '../cryptography/index.js'; import type { Transaction } from '../transactions/index.js'; @@ -415,7 +415,7 @@ export class SuiClient { const result: SuiTransactionBlockResponse = await this.transport.request({ method: 'sui_executeTransactionBlock', params: [ - typeof transactionBlock === 'string' ? transactionBlock : toB64(transactionBlock), + typeof transactionBlock === 'string' ? transactionBlock : toBase64(transactionBlock), Array.isArray(signature) ? signature : [signature], options, ], @@ -580,7 +580,7 @@ export class SuiClient { let devInspectTxBytes; if (isTransaction(input.transactionBlock)) { input.transactionBlock.setSenderIfNotSet(input.sender); - devInspectTxBytes = toB64( + devInspectTxBytes = toBase64( await input.transactionBlock.build({ client: this, onlyTransactionKind: true, @@ -589,7 +589,7 @@ export class SuiClient { } else if (typeof input.transactionBlock === 'string') { devInspectTxBytes = input.transactionBlock; } else if (input.transactionBlock instanceof Uint8Array) { - devInspectTxBytes = toB64(input.transactionBlock); + devInspectTxBytes = toBase64(input.transactionBlock); } else { throw new Error('Unknown transaction block format.'); } @@ -611,7 +611,7 @@ export class SuiClient { params: [ typeof input.transactionBlock === 'string' ? input.transactionBlock - : toB64(input.transactionBlock), + : toBase64(input.transactionBlock), ], }); } @@ -743,8 +743,8 @@ export class SuiClient { // TODO: Migrate this to `sui_getChainIdentifier` once it is widely available. async getChainIdentifier(): Promise { const checkpoint = await this.getCheckpoint({ id: '0' }); - const bytes = fromB58(checkpoint.digest); - return toHEX(bytes.slice(0, 4)); + const bytes = fromBase58(checkpoint.digest); + return toHex(bytes.slice(0, 4)); } async resolveNameServiceAddress(input: ResolveNameServiceAddressParams): Promise { diff --git a/sdk/typescript/src/cryptography/keypair.ts b/sdk/typescript/src/cryptography/keypair.ts index 75aa3dcbb429a..bc04b940565dc 100644 --- a/sdk/typescript/src/cryptography/keypair.ts +++ b/sdk/typescript/src/cryptography/keypair.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { bcs, toB64 } from '@mysten/bcs'; +import { bcs, toBase64 } from '@mysten/bcs'; import { blake2b } from '@noble/hashes/blake2b'; import { bech32 } from 'bech32'; @@ -47,7 +47,7 @@ export abstract class Signer { return { signature, - bytes: toB64(bytes), + bytes: toBase64(bytes), }; } /** @@ -66,7 +66,7 @@ export abstract class Signer { ); return { - bytes: toB64(bytes), + bytes: toBase64(bytes), signature, }; } diff --git a/sdk/typescript/src/cryptography/mnemonics.ts b/sdk/typescript/src/cryptography/mnemonics.ts index 48544686c6c25..feb5aa2cd90a0 100644 --- a/sdk/typescript/src/cryptography/mnemonics.ts +++ b/sdk/typescript/src/cryptography/mnemonics.ts @@ -1,6 +1,6 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { toHEX } from '@mysten/bcs'; +import { toHex } from '@mysten/bcs'; import { mnemonicToSeedSync as bip39MnemonicToSeedSync } from '@scure/bip39'; /** @@ -45,5 +45,5 @@ export function mnemonicToSeed(mnemonics: string): Uint8Array { * @param mnemonics 12 words string split by spaces. */ export function mnemonicToSeedHex(mnemonics: string): string { - return toHEX(mnemonicToSeed(mnemonics)); + return toHex(mnemonicToSeed(mnemonics)); } diff --git a/sdk/typescript/src/cryptography/publickey.ts b/sdk/typescript/src/cryptography/publickey.ts index 41bb51ceae64d..c4ada671b3aa5 100644 --- a/sdk/typescript/src/cryptography/publickey.ts +++ b/sdk/typescript/src/cryptography/publickey.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { toB64 } from '@mysten/bcs'; +import { toBase64 } from '@mysten/bcs'; import { blake2b } from '@noble/hashes/blake2b'; import { bytesToHex } from '@noble/hashes/utils'; @@ -45,7 +45,7 @@ export abstract class PublicKey { * Return the base-64 representation of the public key */ toBase64() { - return toB64(this.toRawBytes()); + return toBase64(this.toRawBytes()); } toString(): never { @@ -61,7 +61,7 @@ export abstract class PublicKey { */ toSuiPublicKey(): string { const bytes = this.toSuiBytes(); - return toB64(bytes); + return toBase64(bytes); } verifyWithIntent( diff --git a/sdk/typescript/src/cryptography/signature.ts b/sdk/typescript/src/cryptography/signature.ts index ef586e73fad16..ed75a9f30e3fd 100644 --- a/sdk/typescript/src/cryptography/signature.ts +++ b/sdk/typescript/src/cryptography/signature.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { fromB64, toB64 } from '@mysten/bcs'; +import { fromBase64, toBase64 } from '@mysten/bcs'; import { bcs } from '../bcs/index.js'; import type { MultiSigStruct } from '../multisig/publickey.js'; @@ -42,14 +42,14 @@ export function toSerializedSignature({ serializedSignature.set([SIGNATURE_SCHEME_TO_FLAG[signatureScheme]]); serializedSignature.set(signature, 1); serializedSignature.set(pubKeyBytes, 1 + signature.length); - return toB64(serializedSignature); + return toBase64(serializedSignature); } /** * Decodes a serialized signature into its constituent components: the signature scheme, the actual signature, and the public key */ export function parseSerializedSignature(serializedSignature: string) { - const bytes = fromB64(serializedSignature); + const bytes = fromBase64(serializedSignature); const signatureScheme = SIGNATURE_FLAG_TO_SCHEME[bytes[0] as keyof typeof SIGNATURE_FLAG_TO_SCHEME]; diff --git a/sdk/typescript/src/keypairs/ed25519/ed25519-hd-key.ts b/sdk/typescript/src/keypairs/ed25519/ed25519-hd-key.ts index eb3f3bb6bf32b..daaadca91fb05 100644 --- a/sdk/typescript/src/keypairs/ed25519/ed25519-hd-key.ts +++ b/sdk/typescript/src/keypairs/ed25519/ed25519-hd-key.ts @@ -4,7 +4,7 @@ // This is adapted from https://github.com/alepop/ed25519-hd-key replacing create-hmac // with @noble/hashes to be browser compatible. -import { fromHEX } from '@mysten/bcs'; +import { fromHex } from '@mysten/bcs'; import { hmac } from '@noble/hashes/hmac'; import { sha512 } from '@noble/hashes/sha512'; import nacl from 'tweetnacl'; @@ -26,7 +26,7 @@ export const replaceDerive = (val: string): string => val.replace("'", ''); export const getMasterKeyFromSeed = (seed: Hex): Keys => { const h = hmac.create(sha512, ED25519_CURVE); - const I = h.update(fromHEX(seed)).digest(); + const I = h.update(fromHex(seed)).digest(); const IL = I.slice(0, 32); const IR = I.slice(32); return { diff --git a/sdk/typescript/src/keypairs/ed25519/keypair.ts b/sdk/typescript/src/keypairs/ed25519/keypair.ts index 9ebd3500bd208..e7102f1f49fac 100644 --- a/sdk/typescript/src/keypairs/ed25519/keypair.ts +++ b/sdk/typescript/src/keypairs/ed25519/keypair.ts @@ -3,7 +3,12 @@ import nacl from 'tweetnacl'; -import { encodeSuiPrivateKey, Keypair, PRIVATE_KEY_SIZE } from '../../cryptography/keypair.js'; +import { + decodeSuiPrivateKey, + encodeSuiPrivateKey, + Keypair, + PRIVATE_KEY_SIZE, +} from '../../cryptography/keypair.js'; import { isValidHardenedPath, mnemonicToSeedHex } from '../../cryptography/mnemonics.js'; import type { SignatureScheme } from '../../cryptography/signature-scheme.js'; import { derivePath } from './ed25519-hd-key.js'; @@ -63,13 +68,23 @@ export class Ed25519Keypair extends Keypair { * * @throws error if the provided secret key is invalid and validation is not skipped. * - * @param secretKey secret key byte array + * @param secretKey secret key as a byte array or Bech32 secret key string * @param options: skip secret key validation */ static fromSecretKey( - secretKey: Uint8Array, + secretKey: Uint8Array | string, options?: { skipValidation?: boolean }, ): Ed25519Keypair { + if (typeof secretKey === 'string') { + const decoded = decodeSuiPrivateKey(secretKey); + + if (decoded.schema !== 'ED25519') { + throw new Error(`Expected a ED25519 keypair, got ${decoded.schema}`); + } + + return this.fromSecretKey(decoded.secretKey, options); + } + const secretKeyLength = secretKey.length; if (secretKeyLength !== PRIVATE_KEY_SIZE) { throw new Error( diff --git a/sdk/typescript/src/keypairs/ed25519/publickey.ts b/sdk/typescript/src/keypairs/ed25519/publickey.ts index 519d041c32416..8afbfe454326e 100644 --- a/sdk/typescript/src/keypairs/ed25519/publickey.ts +++ b/sdk/typescript/src/keypairs/ed25519/publickey.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { fromB64 } from '@mysten/bcs'; +import { fromBase64 } from '@mysten/bcs'; import nacl from 'tweetnacl'; import type { PublicKeyInitData } from '../../cryptography/publickey.js'; @@ -26,7 +26,7 @@ export class Ed25519PublicKey extends PublicKey { super(); if (typeof value === 'string') { - this.data = fromB64(value); + this.data = fromBase64(value); } else if (value instanceof Uint8Array) { this.data = value; } else { diff --git a/sdk/typescript/src/keypairs/secp256k1/keypair.ts b/sdk/typescript/src/keypairs/secp256k1/keypair.ts index e469b518aba74..ef418553fdc19 100644 --- a/sdk/typescript/src/keypairs/secp256k1/keypair.ts +++ b/sdk/typescript/src/keypairs/secp256k1/keypair.ts @@ -7,7 +7,7 @@ import { sha256 } from '@noble/hashes/sha256'; import { bytesToHex } from '@noble/hashes/utils'; import { HDKey } from '@scure/bip32'; -import { encodeSuiPrivateKey, Keypair } from '../../cryptography/keypair.js'; +import { decodeSuiPrivateKey, encodeSuiPrivateKey, Keypair } from '../../cryptography/keypair.js'; import { isValidBIP32Path, mnemonicToSeed } from '../../cryptography/mnemonics.js'; import type { PublicKey } from '../../cryptography/publickey.js'; import type { SignatureScheme } from '../../cryptography/signature-scheme.js'; @@ -70,14 +70,24 @@ export class Secp256k1Keypair extends Keypair { * * @throws error if the provided secret key is invalid and validation is not skipped. * - * @param secretKey secret key byte array + * @param secretKey secret key byte array or Bech32 secret key string * @param options: skip secret key validation */ static fromSecretKey( - secretKey: Uint8Array, + secretKey: Uint8Array | string, options?: { skipValidation?: boolean }, ): Secp256k1Keypair { + if (typeof secretKey === 'string') { + const decoded = decodeSuiPrivateKey(secretKey); + + if (decoded.schema !== 'Secp256k1') { + throw new Error(`Expected a Secp256k1 keypair, got ${decoded.schema}`); + } + + return this.fromSecretKey(decoded.secretKey, options); + } + const publicKey: Uint8Array = secp256k1.getPublicKey(secretKey, true); if (!options || !options.skipValidation) { const encoder = new TextEncoder(); diff --git a/sdk/typescript/src/keypairs/secp256k1/publickey.ts b/sdk/typescript/src/keypairs/secp256k1/publickey.ts index 657b55a020e60..bd44844aa4db3 100644 --- a/sdk/typescript/src/keypairs/secp256k1/publickey.ts +++ b/sdk/typescript/src/keypairs/secp256k1/publickey.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { fromB64 } from '@mysten/bcs'; +import { fromBase64 } from '@mysten/bcs'; import { secp256k1 } from '@noble/curves/secp256k1'; import { sha256 } from '@noble/hashes/sha256'; @@ -27,7 +27,7 @@ export class Secp256k1PublicKey extends PublicKey { super(); if (typeof value === 'string') { - this.data = fromB64(value); + this.data = fromBase64(value); } else if (value instanceof Uint8Array) { this.data = value; } else { diff --git a/sdk/typescript/src/keypairs/secp256r1/keypair.ts b/sdk/typescript/src/keypairs/secp256r1/keypair.ts index 705fa8a6e9570..269ced2429c2d 100644 --- a/sdk/typescript/src/keypairs/secp256r1/keypair.ts +++ b/sdk/typescript/src/keypairs/secp256r1/keypair.ts @@ -7,7 +7,7 @@ import { sha256 } from '@noble/hashes/sha256'; import { bytesToHex } from '@noble/hashes/utils'; import { HDKey } from '@scure/bip32'; -import { encodeSuiPrivateKey, Keypair } from '../../cryptography/keypair.js'; +import { decodeSuiPrivateKey, encodeSuiPrivateKey, Keypair } from '../../cryptography/keypair.js'; import { isValidBIP32Path, mnemonicToSeed } from '../../cryptography/mnemonics.js'; import type { PublicKey } from '../../cryptography/publickey.js'; import type { SignatureScheme } from '../../cryptography/signature-scheme.js'; @@ -70,14 +70,24 @@ export class Secp256r1Keypair extends Keypair { * * @throws error if the provided secret key is invalid and validation is not skipped. * - * @param secretKey secret key byte array + * @param secretKey secret key byte array or Bech32 secret key string * @param options: skip secret key validation */ static fromSecretKey( - secretKey: Uint8Array, + secretKey: Uint8Array | string, options?: { skipValidation?: boolean }, ): Secp256r1Keypair { + if (typeof secretKey === 'string') { + const decoded = decodeSuiPrivateKey(secretKey); + + if (decoded.schema !== 'Secp256r1') { + throw new Error(`Expected a Secp256r1 keypair, got ${decoded.schema}`); + } + + return this.fromSecretKey(decoded.secretKey, options); + } + const publicKey: Uint8Array = secp256r1.getPublicKey(secretKey, true); if (!options || !options.skipValidation) { const encoder = new TextEncoder(); diff --git a/sdk/typescript/src/keypairs/secp256r1/publickey.ts b/sdk/typescript/src/keypairs/secp256r1/publickey.ts index a1cddbb8491e3..8cf11a9de89a5 100644 --- a/sdk/typescript/src/keypairs/secp256r1/publickey.ts +++ b/sdk/typescript/src/keypairs/secp256r1/publickey.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { fromB64 } from '@mysten/bcs'; +import { fromBase64 } from '@mysten/bcs'; import { secp256r1 } from '@noble/curves/p256'; import { sha256 } from '@noble/hashes/sha256'; @@ -27,7 +27,7 @@ export class Secp256r1PublicKey extends PublicKey { super(); if (typeof value === 'string') { - this.data = fromB64(value); + this.data = fromBase64(value); } else if (value instanceof Uint8Array) { this.data = value; } else { diff --git a/sdk/typescript/src/multisig/publickey.ts b/sdk/typescript/src/multisig/publickey.ts index ada52d8b15c41..b97ec9cce54b0 100644 --- a/sdk/typescript/src/multisig/publickey.ts +++ b/sdk/typescript/src/multisig/publickey.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { fromB64, toB64 } from '@mysten/bcs'; +import { fromBase64, toBase64 } from '@mysten/bcs'; import { blake2b } from '@noble/hashes/blake2b'; import { bytesToHex } from '@noble/hashes/utils'; @@ -81,7 +81,7 @@ export class MultiSigPublicKey extends PublicKey { super(); if (typeof value === 'string') { - this.rawBytes = fromB64(value); + this.rawBytes = fromBase64(value); this.multisigPublicKey = bcs.MultiSigPublicKey.parse(this.rawBytes); } else if (value instanceof Uint8Array) { @@ -306,7 +306,7 @@ export class MultiSigPublicKey extends PublicKey { let tmp = new Uint8Array(bytes.length + 1); tmp.set([SIGNATURE_SCHEME_TO_FLAG['MultiSig']]); tmp.set(bytes, 1); - return toB64(tmp); + return toBase64(tmp); } } diff --git a/sdk/typescript/src/multisig/signer.ts b/sdk/typescript/src/multisig/signer.ts index 7385ee1f851a7..0cd5719b194c9 100644 --- a/sdk/typescript/src/multisig/signer.ts +++ b/sdk/typescript/src/multisig/signer.ts @@ -1,6 +1,6 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { toB64 } from '@mysten/bcs'; +import { toBase64 } from '@mysten/bcs'; import type { SignatureScheme } from '../cryptography/index.js'; import { Signer } from '../cryptography/index.js'; @@ -73,7 +73,7 @@ export class MultiSigSigner extends Signer { return { signature, - bytes: toB64(bytes), + bytes: toBase64(bytes), }; } @@ -86,7 +86,7 @@ export class MultiSigSigner extends Signer { return { signature, - bytes: toB64(bytes), + bytes: toBase64(bytes), }; } } diff --git a/sdk/typescript/src/transactions/Commands.ts b/sdk/typescript/src/transactions/Commands.ts index 7021c07f075d5..7d8e658148280 100644 --- a/sdk/typescript/src/transactions/Commands.ts +++ b/sdk/typescript/src/transactions/Commands.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { toB64 } from '@mysten/bcs'; +import { toBase64 } from '@mysten/bcs'; import type { InferInput } from 'valibot'; import { parse } from 'valibot'; @@ -108,7 +108,7 @@ export const Commands = { $kind: 'Publish', Publish: { modules: modules.map((module) => - typeof module === 'string' ? module : toB64(new Uint8Array(module)), + typeof module === 'string' ? module : toBase64(new Uint8Array(module)), ), dependencies: dependencies.map((dep) => normalizeSuiObjectId(dep)), }, @@ -129,7 +129,7 @@ export const Commands = { $kind: 'Upgrade', Upgrade: { modules: modules.map((module) => - typeof module === 'string' ? module : toB64(new Uint8Array(module)), + typeof module === 'string' ? module : toBase64(new Uint8Array(module)), ), dependencies: dependencies.map((dep) => normalizeSuiObjectId(dep)), package: packageId, diff --git a/sdk/typescript/src/transactions/Inputs.ts b/sdk/typescript/src/transactions/Inputs.ts index 2abfb1482aa6b..d3e8281cf2d93 100644 --- a/sdk/typescript/src/transactions/Inputs.ts +++ b/sdk/typescript/src/transactions/Inputs.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { toB64 } from '@mysten/bcs'; +import { toBase64 } from '@mysten/bcs'; import type { SerializedBcs } from '@mysten/bcs'; import { normalizeSuiAddress } from '../utils/sui-types.js'; @@ -11,7 +11,7 @@ function Pure(data: Uint8Array | SerializedBcs): Extract Array.from(fromB64(mod))), + modules: command.Publish.modules.map((mod) => Array.from(fromBase64(mod))), dependencies: command.Publish.dependencies, }; } @@ -337,7 +337,7 @@ export function serializeV1TransactionData( if (command.Upgrade) { return { kind: 'Upgrade', - modules: command.Upgrade.modules.map((mod) => Array.from(fromB64(mod))), + modules: command.Upgrade.modules.map((mod) => Array.from(fromBase64(mod))), dependencies: command.Upgrade.dependencies, packageId: command.Upgrade.package, ticket: convertTransactionArgument(command.Upgrade.ticket, inputs), @@ -434,7 +434,7 @@ export function transactionDataFromV1(data: SerializedTransactionDataV1): Transa return { Pure: { - bytes: toB64(new Uint8Array(value.Pure)), + bytes: toBase64(new Uint8Array(value.Pure)), }, }; } @@ -491,7 +491,7 @@ export function transactionDataFromV1(data: SerializedTransactionDataV1): Transa case 'Publish': { return { Publish: { - modules: transaction.modules.map((mod) => toB64(Uint8Array.from(mod))), + modules: transaction.modules.map((mod) => toBase64(Uint8Array.from(mod))), dependencies: transaction.dependencies, }, }; @@ -515,7 +515,7 @@ export function transactionDataFromV1(data: SerializedTransactionDataV1): Transa case 'Upgrade': { return { Upgrade: { - modules: transaction.modules.map((mod) => toB64(Uint8Array.from(mod))), + modules: transaction.modules.map((mod) => toBase64(Uint8Array.from(mod))), dependencies: transaction.dependencies, package: transaction.packageId, ticket: parseV1TransactionArgument(transaction.ticket), diff --git a/sdk/typescript/src/transactions/executor/parallel.ts b/sdk/typescript/src/transactions/executor/parallel.ts index 72cf1100ba691..c6c73eae35439 100644 --- a/sdk/typescript/src/transactions/executor/parallel.ts +++ b/sdk/typescript/src/transactions/executor/parallel.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { toB64 } from '@mysten/bcs'; +import { toBase64 } from '@mysten/bcs'; import { bcs } from '../../bcs/index.js'; import type { SuiObjectRef } from '../../bcs/types.js'; @@ -266,7 +266,7 @@ export class ParallelTransactionExecutor { return { digest: results.digest, - effects: toB64(effectsBytes), + effects: toBase64(effectsBytes), data: results, }; } catch (error) { diff --git a/sdk/typescript/src/transactions/executor/serial.ts b/sdk/typescript/src/transactions/executor/serial.ts index ce81022cfa6ae..0e25ed95c0445 100644 --- a/sdk/typescript/src/transactions/executor/serial.ts +++ b/sdk/typescript/src/transactions/executor/serial.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { toB64 } from '@mysten/bcs'; +import { toBase64 } from '@mysten/bcs'; import { bcs } from '../../bcs/index.js'; import type { SuiClient, SuiTransactionBlockResponseOptions } from '../../client/index.js'; @@ -109,7 +109,7 @@ export class SerialTransactionExecutor { return { digest: results.digest, - effects: toB64(effectsBytes), + effects: toBase64(effectsBytes), data: results, }; }); diff --git a/sdk/typescript/src/utils/index.ts b/sdk/typescript/src/utils/index.ts index aa6bf138653fa..c85c9942ea75e 100644 --- a/sdk/typescript/src/utils/index.ts +++ b/sdk/typescript/src/utils/index.ts @@ -13,7 +13,18 @@ export { SUI_ADDRESS_LENGTH, } from './sui-types.js'; -export { fromB64, toB64, fromHEX, toHEX } from '@mysten/bcs'; +export { + fromB64, + toB64, + fromHEX, + toHex, + toHEX, + fromHex, + fromBase64, + toBase64, + fromBase58, + toBase58, +} from '@mysten/bcs'; export { isValidSuiNSName, normalizeSuiNSName } from './suins.js'; export { diff --git a/sdk/typescript/src/utils/sui-types.ts b/sdk/typescript/src/utils/sui-types.ts index 311269961a8bf..f8cb10b997136 100644 --- a/sdk/typescript/src/utils/sui-types.ts +++ b/sdk/typescript/src/utils/sui-types.ts @@ -1,14 +1,14 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { fromB58, splitGenericParameters } from '@mysten/bcs'; +import { fromBase58, splitGenericParameters } from '@mysten/bcs'; const TX_DIGEST_LENGTH = 32; /** Returns whether the tx digest is valid based on the serialization format */ export function isValidTransactionDigest(value: string): value is string { try { - const buffer = fromB58(value); + const buffer = fromBase58(value); return buffer.length === TX_DIGEST_LENGTH; } catch (e) { return false; diff --git a/sdk/typescript/src/verify/verify.ts b/sdk/typescript/src/verify/verify.ts index 7ba6fcf63a6ab..f4c3798a094fd 100644 --- a/sdk/typescript/src/verify/verify.ts +++ b/sdk/typescript/src/verify/verify.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { fromB64 } from '@mysten/bcs'; +import { fromBase64 } from '@mysten/bcs'; import type { PublicKey, SignatureFlag, SignatureScheme } from '../cryptography/index.js'; import { parseSerializedSignature, SIGNATURE_FLAG_TO_SCHEME } from '../cryptography/index.js'; @@ -107,7 +107,7 @@ export function publicKeyFromSuiBytes( publicKey: string | Uint8Array, options: { client?: SuiGraphQLClient } = {}, ) { - const bytes = typeof publicKey === 'string' ? fromB64(publicKey) : publicKey; + const bytes = typeof publicKey === 'string' ? fromBase64(publicKey) : publicKey; const signatureScheme = SIGNATURE_FLAG_TO_SCHEME[bytes[0] as SignatureFlag]; diff --git a/sdk/typescript/src/zklogin/publickey.ts b/sdk/typescript/src/zklogin/publickey.ts index d42afefb0559d..7eb23ffa23b0c 100644 --- a/sdk/typescript/src/zklogin/publickey.ts +++ b/sdk/typescript/src/zklogin/publickey.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { fromB64, toB64 } from '@mysten/bcs'; +import { fromBase64, toBase64 } from '@mysten/bcs'; import { PublicKey } from '../cryptography/publickey.js'; import type { PublicKeyInitData } from '../cryptography/publickey.js'; @@ -29,7 +29,7 @@ export class ZkLoginPublicIdentifier extends PublicKey { this.#client = client; if (typeof value === 'string') { - this.#data = fromB64(value); + this.#data = fromBase64(value); } else if (value instanceof Uint8Array) { this.#data = value; } else { @@ -74,7 +74,7 @@ export class ZkLoginPublicIdentifier extends PublicKey { return graphqlVerifyZkLoginSignature({ address: address, - bytes: toB64(message), + bytes: toBase64(message), signature: parsedSignature.serializedSignature, intentScope: 'PERSONAL_MESSAGE', client: this.#client, @@ -89,7 +89,7 @@ export class ZkLoginPublicIdentifier extends PublicKey { const address = new ZkLoginPublicIdentifier(parsedSignature.publicKey).toSuiAddress(); return graphqlVerifyZkLoginSignature({ address: address, - bytes: toB64(transaction), + bytes: toBase64(transaction), signature: parsedSignature.serializedSignature, intentScope: 'TRANSACTION_DATA', client: this.#client, @@ -164,7 +164,7 @@ async function graphqlVerifyZkLoginSignature({ } export function parseSerializedZkLoginSignature(signature: Uint8Array | string) { - const bytes = typeof signature === 'string' ? fromB64(signature) : signature; + const bytes = typeof signature === 'string' ? fromBase64(signature) : signature; if (bytes[0] !== SIGNATURE_SCHEME_TO_FLAG.ZkLogin) { throw new Error('Invalid signature scheme'); @@ -176,7 +176,7 @@ export function parseSerializedZkLoginSignature(signature: Uint8Array | string) const iss = extractClaimValue(issBase64Details, 'iss'); const publicIdentifer = toZkLoginPublicIdentifier(BigInt(addressSeed), iss); return { - serializedSignature: toB64(bytes), + serializedSignature: toBase64(bytes), signatureScheme: 'ZkLogin' as const, zkLogin: { inputs, diff --git a/sdk/typescript/src/zklogin/signature.ts b/sdk/typescript/src/zklogin/signature.ts index 732279b7062c5..04d8b0f1b46c0 100644 --- a/sdk/typescript/src/zklogin/signature.ts +++ b/sdk/typescript/src/zklogin/signature.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { fromB64, toB64 } from '@mysten/bcs'; +import { fromBase64, toBase64 } from '@mysten/bcs'; import { SIGNATURE_SCHEME_TO_FLAG } from '../cryptography/signature-scheme.js'; import type { ZkLoginSignature } from './bcs.js'; @@ -17,7 +17,8 @@ function getZkLoginSignatureBytes({ inputs, maxEpoch, userSignature }: ZkLoginSi { inputs, maxEpoch, - userSignature: typeof userSignature === 'string' ? fromB64(userSignature) : userSignature, + userSignature: + typeof userSignature === 'string' ? fromBase64(userSignature) : userSignature, }, { maxSize: 2048 }, ) @@ -29,9 +30,9 @@ export function getZkLoginSignature({ inputs, maxEpoch, userSignature }: ZkLogin const signatureBytes = new Uint8Array(bytes.length + 1); signatureBytes.set([SIGNATURE_SCHEME_TO_FLAG.ZkLogin]); signatureBytes.set(bytes, 1); - return toB64(signatureBytes); + return toBase64(signatureBytes); } export function parseZkLoginSignature(signature: string | Uint8Array) { - return zkLoginSignature.parse(typeof signature === 'string' ? fromB64(signature) : signature); + return zkLoginSignature.parse(typeof signature === 'string' ? fromBase64(signature) : signature); } diff --git a/sdk/typescript/test/e2e/coin-with-balance.test.ts b/sdk/typescript/test/e2e/coin-with-balance.test.ts index 0e15b69d954b8..5114b9c83286c 100644 --- a/sdk/typescript/test/e2e/coin-with-balance.test.ts +++ b/sdk/typescript/test/e2e/coin-with-balance.test.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { resolve } from 'path'; -import { fromHEX, toB64 } from '@mysten/bcs'; +import { fromHex, toBase64 } from '@mysten/bcs'; import { beforeAll, describe, expect, it } from 'vitest'; import { bcs } from '../../src/bcs'; @@ -57,7 +57,7 @@ describe('coinWithBalance', () => { inputs: [ { Pure: { - bytes: toB64(fromHEX(receiver.toSuiAddress())), + bytes: toBase64(fromHex(receiver.toSuiAddress())), }, }, ], @@ -107,12 +107,12 @@ describe('coinWithBalance', () => { inputs: [ { Pure: { - bytes: toB64(fromHEX(receiver.toSuiAddress())), + bytes: toBase64(fromHex(receiver.toSuiAddress())), }, }, { Pure: { - bytes: toB64(bcs.u64().serialize(12345).toBytes()), + bytes: toBase64(bcs.u64().serialize(12345).toBytes()), }, }, ], @@ -205,7 +205,7 @@ describe('coinWithBalance', () => { inputs: [ { Pure: { - bytes: toB64(fromHEX(receiver.toSuiAddress())), + bytes: toBase64(fromHex(receiver.toSuiAddress())), }, }, ], @@ -255,7 +255,7 @@ describe('coinWithBalance', () => { inputs: [ { Pure: { - bytes: toB64(fromHEX(receiver.toSuiAddress())), + bytes: toBase64(fromHex(receiver.toSuiAddress())), }, }, { @@ -265,7 +265,7 @@ describe('coinWithBalance', () => { }, { Pure: { - bytes: toB64(bcs.u64().serialize(1).toBytes()), + bytes: toBase64(bcs.u64().serialize(1).toBytes()), }, }, ], @@ -355,7 +355,7 @@ describe('coinWithBalance', () => { inputs: [ { Pure: { - bytes: toB64(fromHEX(receiver.toSuiAddress())), + bytes: toBase64(fromHex(receiver.toSuiAddress())), }, }, ], @@ -444,7 +444,7 @@ describe('coinWithBalance', () => { inputs: [ { Pure: { - bytes: toB64(fromHEX(receiver.toSuiAddress())), + bytes: toBase64(fromHex(receiver.toSuiAddress())), }, }, { @@ -454,22 +454,22 @@ describe('coinWithBalance', () => { }, { Pure: { - bytes: toB64(bcs.u64().serialize(1).toBytes()), + bytes: toBase64(bcs.u64().serialize(1).toBytes()), }, }, { Pure: { - bytes: toB64(bcs.u64().serialize(2).toBytes()), + bytes: toBase64(bcs.u64().serialize(2).toBytes()), }, }, { Pure: { - bytes: toB64(bcs.u64().serialize(3).toBytes()), + bytes: toBase64(bcs.u64().serialize(3).toBytes()), }, }, { Pure: { - bytes: toB64(bcs.u64().serialize(4).toBytes()), + bytes: toBase64(bcs.u64().serialize(4).toBytes()), }, }, ], diff --git a/sdk/typescript/test/e2e/keypairs.test.ts b/sdk/typescript/test/e2e/keypairs.test.ts index 77869d70d6a29..ed079065e0cf7 100644 --- a/sdk/typescript/test/e2e/keypairs.test.ts +++ b/sdk/typescript/test/e2e/keypairs.test.ts @@ -7,7 +7,7 @@ import { describe, expect, it } from 'vitest'; import { messageWithIntent, parseSerializedSignature } from '../../src/cryptography'; import { Ed25519Keypair } from '../../src/keypairs/ed25519'; import { Secp256k1Keypair } from '../../src/keypairs/secp256k1'; -import { fromB64, toB64 } from '../../src/utils'; +import { fromBase64, toBase64 } from '../../src/utils'; const TX_BYTES = 'AAACAQDMdYtdFSLGe6VbgpuIsMksv9Ypzpvkq2jiYq0hAjUpOQIAAAAAAAAAIHGwPza+lUm6RuJV1vn9pA4y0PwVT7k/KMMbUViQS5ydACAMVn/9+BYsttUa90vgGZRDuS6CPUumztJN5cbEY3l9RgEBAQEAAAEBAHUFfdk1Tg9l6STLBoSBJbbUuehTDUlLH7p81kpqCKsaBCiJ034Ac84f1oqgmpz79O8L/UeLNDUpOUMa+LadeX93AgAAAAAAAAAgs1e67e789jSlrzOJUXq0bb7Bn/hji+3F5UoMAbze595xCSZCVjU1ItUC9G7KQjygNiBbzZe8t7YLPjRAQyGTzAIAAAAAAAAAIAujHFcrkJJhZfCmxmCHsBWxj5xkviUqB479oupdgMZu07b+hkrjyvCcX50dO30v3PszXFj7+lCNTUTuE4UI3eoCAAAAAAAAACBIv39dyVELUFTkNv72mat5R1uHFkQdViikc1lTMiSVlOD+eESUq3neyciBatafk9dHuhhrS37RaSflqKwFlwzPAgAAAAAAAAAg8gqL3hCkAho8bb0PoqshJdqQFoRP8ZmQMZDFvsGBqa11BX3ZNU4PZekkywaEgSW21LnoUw1JSx+6fNZKagirGgEAAAAAAAAAKgQAAAAAAAAA'; @@ -69,11 +69,11 @@ const TEST_CASES_SECP256K1 = [ describe('Keypairs', () => { it('Ed25519 keypair signData', async () => { - const tx_bytes = fromB64(TX_BYTES); + const tx_bytes = fromBase64(TX_BYTES); const intentMessage = messageWithIntent('TransactionData', tx_bytes); const digest = blake2b(intentMessage, { dkLen: 32 }); - expect(toB64(digest)).toEqual(DIGEST); + expect(toBase64(digest)).toEqual(DIGEST); for (const t of TEST_CASES) { const keypair = Ed25519Keypair.deriveKeypair(t[0], DERIVATION_PATH); @@ -83,7 +83,7 @@ describe('Keypairs', () => { const { signature: serializedSignature } = await keypair.signTransaction(tx_bytes); const { signature } = parseSerializedSignature(serializedSignature); - expect(toB64(signature!)).toEqual(t[3]); + expect(toBase64(signature!)).toEqual(t[3]); const isValid = await keypair.getPublicKey().verifyTransaction(tx_bytes, serializedSignature); expect(isValid).toBeTruthy(); @@ -111,10 +111,10 @@ describe('Keypairs', () => { }); it('Secp256k1 keypair signData', async () => { - const tx_bytes = fromB64(TX_BYTES); + const tx_bytes = fromBase64(TX_BYTES); const intentMessage = messageWithIntent('TransactionData', tx_bytes); const digest = blake2b(intentMessage, { dkLen: 32 }); - expect(toB64(digest)).toEqual(DIGEST); + expect(toBase64(digest)).toEqual(DIGEST); for (const t of TEST_CASES_SECP256K1) { const keypair = Secp256k1Keypair.deriveKeypair(t[0], DERIVATION_PATH_SECP256K1); @@ -124,7 +124,7 @@ describe('Keypairs', () => { const { signature: serializedSignature } = await keypair.signTransaction(tx_bytes); const { signature } = parseSerializedSignature(serializedSignature); - expect(toB64(signature!)).toEqual(t[3]); + expect(toBase64(signature!)).toEqual(t[3]); const isValid = await keypair.getPublicKey().verifyTransaction(tx_bytes, serializedSignature); expect(isValid).toBeTruthy(); diff --git a/sdk/typescript/test/e2e/multisig.test.ts b/sdk/typescript/test/e2e/multisig.test.ts index 53a50966638f0..2863f976c4a8a 100644 --- a/sdk/typescript/test/e2e/multisig.test.ts +++ b/sdk/typescript/test/e2e/multisig.test.ts @@ -3,7 +3,7 @@ import { tmpdir } from 'os'; import path from 'path'; -import { fromB64 } from '@mysten/bcs'; +import { fromBase64 } from '@mysten/bcs'; import { describe, expect, it } from 'vitest'; import { decodeSuiPrivateKey } from '../../src/cryptography'; @@ -95,7 +95,7 @@ describe('MultiSig with zklogin signature', () => { const zkLoginSig = getZkLoginSignature({ inputs: zkLoginInputs, maxEpoch: '2', - userSignature: fromB64(ephemeralSig), + userSignature: fromBase64(ephemeralSig), }); // combine to multisig and execute the transaction. diff --git a/sdk/typescript/test/e2e/parallel-executor.test.ts b/sdk/typescript/test/e2e/parallel-executor.test.ts index 7d0d036fd4043..a6682bdf3a25c 100644 --- a/sdk/typescript/test/e2e/parallel-executor.test.ts +++ b/sdk/typescript/test/e2e/parallel-executor.test.ts @@ -13,38 +13,38 @@ import { setup, TestToolbox } from './utils/setup'; let toolbox: TestToolbox; let executor: ParallelTransactionExecutor; -beforeAll(async () => { - toolbox = await setup(); - - // Creates bear package - await toolbox.mintNft(); +describe('ParallelTransactionExecutor', { retry: 3 }, () => { + beforeAll(async () => { + toolbox = await setup(); - executor = new ParallelTransactionExecutor({ - client: toolbox.client, - signer: toolbox.keypair, - maxPoolSize: 3, - coinBatchSize: 2, - }); + // Creates bear package + await toolbox.mintNft(); - vi.spyOn(toolbox.client, 'multiGetObjects'); - vi.spyOn(toolbox.client, 'getCoins'); - vi.spyOn(toolbox.client, 'executeTransactionBlock'); -}); + executor = new ParallelTransactionExecutor({ + client: toolbox.client, + signer: toolbox.keypair, + maxPoolSize: 3, + coinBatchSize: 2, + }); -afterEach(async () => { - await executor.waitForLastTransaction(); -}); + vi.spyOn(toolbox.client, 'multiGetObjects'); + vi.spyOn(toolbox.client, 'getCoins'); + vi.spyOn(toolbox.client, 'executeTransactionBlock'); + }); -afterAll(() => { - vi.restoreAllMocks(); -}); + afterEach(async () => { + await executor.waitForLastTransaction(); + }); -describe('ParallelTransactionExecutor', { retry: 3 }, () => { beforeEach(async () => { await executor.resetCache(); vi.clearAllMocks(); }); + afterAll(() => { + vi.restoreAllMocks(); + }); + it('Executes multiple transactions in parallel', async () => { let concurrentRequests = 0; let maxConcurrentRequests = 0; diff --git a/sdk/typescript/test/e2e/receive-object.test.ts b/sdk/typescript/test/e2e/receive-object.test.ts index f7622e4fc13a3..799c2055c7c5a 100644 --- a/sdk/typescript/test/e2e/receive-object.test.ts +++ b/sdk/typescript/test/e2e/receive-object.test.ts @@ -18,7 +18,7 @@ function getOwnerAddress(o: OwnedObjectRef): string | undefined { } } -describe('Transfer to Object', () => { +describe('Transfer to Object', { retry: 3 }, () => { let toolbox: TestToolbox; let packageId: string; let parentObjectId: OwnedObjectRef; diff --git a/sdk/typescript/test/e2e/zklogin-signature.test.ts b/sdk/typescript/test/e2e/zklogin-signature.test.ts index 478b9e81f3631..0403160eaed39 100644 --- a/sdk/typescript/test/e2e/zklogin-signature.test.ts +++ b/sdk/typescript/test/e2e/zklogin-signature.test.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { fromB64 } from '@mysten/bcs'; +import { fromBase64 } from '@mysten/bcs'; import { describe, expect, it, test } from 'vitest'; import { SuiGraphQLClient } from '../../src/graphql'; @@ -50,10 +50,10 @@ const anEphemeralSignature = describe('zkLogin signature', () => { test('is parsed successfully', () => { - expect(parseZkLoginSignature(fromB64(aSignature).slice(1))).toMatchObject({ + expect(parseZkLoginSignature(fromBase64(aSignature).slice(1))).toMatchObject({ inputs: aSignatureInputs, maxEpoch: '174', - userSignature: fromB64(anEphemeralSignature), + userSignature: fromBase64(anEphemeralSignature), }); }); test('is serialized successfully', () => { @@ -61,7 +61,7 @@ describe('zkLogin signature', () => { getZkLoginSignature({ inputs: aSignatureInputs, maxEpoch: '174', - userSignature: fromB64(anEphemeralSignature), + userSignature: fromBase64(anEphemeralSignature), }), ).toBe(aSignature); }); @@ -81,7 +81,7 @@ describe('zkLogin signature', () => { }); // verifies ok bc max_epoch 3 is within upper bound. - let res = await pk.verifyPersonalMessage(fromB64(bytes), parsed.signature); + let res = await pk.verifyPersonalMessage(fromBase64(bytes), parsed.signature); expect(res).toBe(true); // test case generated from `sui keytool zk-login-insecure-sign-personal-message --data "hello" --max-epoch 100` @@ -89,7 +89,7 @@ describe('zkLogin signature', () => { let testSignature2 = 'BQNNMTU3MTEzMjIxMjQyNzE4OTQyODkwNzkwMzcyMTAyNzkxNDU1MzAxMTc4NzgxMDIyOTYzNzQ2Njk5MTE0NzU5MDY3ODYyNDYyNzQ2MTBNMTY2MDg4MjI5MjU0NDI1OTQyMjkxMjY4MDIzMzUyNDE3NDU3NTcwMDc0NjUxMjQ0MTI1OTczMTE2MDM5NzYwMTk2ODk0MzE5ODY5MDYBMQMCTTEzNDQ1MjU4Mzc0Mjk4MTE1MjAzMjEwODM4NzU1Nzk0MDExMTg1NDU0OTgzODgxMTg5OTYwNTQzODc5NjMzMDE5OTQxODEyMDk2MjYzTDE3Njk4NDE1NzUzNDg4NDgzOTEzMjMxMTA3NDMyNDkzMTkyOTAxMTEwNjY0NzE2OTkxMzQwNzY0NjExMzg2OTk5NDg1NDAyODA3MzgCTTE0ODU5NDk0ODMxNjI4MzQyMDEzMTM0NDA4NzAxMTIwNDUxMDI4MDkyMTg4MDAxMTMwOTkxNjkxMjAyNzMyMzA2NzcxODI4NTYxNzU0TTIwMzM1NDE4NjE3NzgyMzU5MTQ2NTg0NzcwNzM0MDcyMzI3NzYwMjAyNDYwMDE2NDY0NjAwNjQzMDA2Nzg5NzAyODg0MzQ1NTkzNjg5AgExATADTTE4Nzk4Mjk5MDAzOTAyMDI3MDcxNTg1ODY5MjY3MzYyOTc5ODUwOTExNzA3Nzk2MzU0NDQyMTY2NzEzOTcyNjQ2NzE2OTQ1OTgyMjM4TTEyMDExNjg0MjA0MDI0NTMxNzY2ODUxMTU0OTAyMzI5Njk4MDIwODQ3NTQ1NDU5NDk2MjA2MDI2NDg5MTE5MzUzODI4NTI2NTE5MzAwATEod2lhWE56SWpvaWFIUjBjSE02THk5dllYVjBhQzV6ZFdrdWFXOGlMQwI+ZXlKcmFXUWlPaUp6ZFdrdGEyVjVMV2xrSWl3aWRIbHdJam9pU2xkVUlpd2lZV3huSWpvaVVsTXlOVFlpZlFNMjA0MzUzNjY2MDAwMzYzNzU3NDU5MjU5NjM0NTY4NjEzMDc5MjUyMDk0NzAyMTkzMzQwMTg1NjQxNTgxNDg1NDQwMzYxOTYyODQ2NDJkAAAAAAAAAGEA+XrHUDMkMaPswTIFsqIgx3yX6j7IvU1T/1yzw4kjKwjgLL0ZtPQZjc2djX7Q9pFoBdObkSZ6JZ4epiOf05q4BrnG7hYw7z5xEUSmSNsGu7IoT3J0z77lP/zuUDzBpJIA'; let parsed2 = parseSerializedZkLoginSignature(testSignature2); - let res1 = await pk.verifyPersonalMessage(fromB64(bytes), parsed2.signature); + let res1 = await pk.verifyPersonalMessage(fromBase64(bytes), parsed2.signature); expect(res1).toBe(false); }, { @@ -114,7 +114,7 @@ describe('zkLogin signature', () => { }); // verifies ok bc max_epoch 5 is within upper bound. - let res = await pk.verifyTransaction(fromB64(bytes), parsed.signature); + let res = await pk.verifyTransaction(fromBase64(bytes), parsed.signature); expect(res).toBe(true); // fails to verify bc max_epoch 100 is too large. @@ -123,7 +123,7 @@ describe('zkLogin signature', () => { let testSignature2 = 'BQNLNjE1NDU3MTU5NjYwMDM3ODM1MTY2OTE1OTkwMzg1MjQ3NTkzMDg3NTk3NzM4Nzg2MzkxNjE3MTU4MDg1ODIzMTcyNjg4MzkyMjg3TTE0ODc4NTgwNDQ2ODcxNzE3Mzc2ODEwNjM5ODIxNDQxNDk5OTI0MDQxNjMwMzQ5MTExNTAwNzQzOTk2NTY0MzczNTU5NDU2NDg4NDY5ATEDAkwxOTI5MDM5OTU1Mjk3Njg0NzU0NDU5NDc2NzQwMzEyNjMzMDI0NTMwOTk2MjAwMzI3ODUxNzc2NDk5MTUyNjQ3MjUxMjQ1MzA3OTEwTDU4OTY0NzA0NDQyMTkyODA1MDYwNjM5MTI2NTMzODk1ODIyNzIzMDA4NDI0MjkwMDMxNTIxMjk2Njk3OTM1MTc2NTQ1NTczMDMyODcCTDcyOTk2ODY3MjgzOTc3MzQ3MDg3NjYzNDUzMjcwODc2ODc3MTgzOTU5MTQwNzkwMTc0MjIwOTUwNTkzNTg3MTcxMjg3MjA2Njk2OTFNMTAxNzIyNzE1ODY2OTc0MzY4MTU1MTQzOTcyMjkyMTgzMzUxMDg1NDY2NTEzNzI1MTI5MTE2NjI3NDcxNDg5MjU2NDY5OTk0NTQxMjYCATEBMANMNjMwNDA2MTEyMzQ1OTY1NjE5MzQ1ODAzOTA0MzExNTg0OTU2ODgwMDM1Njc5NTU5NTUxNTAwNDAwNTE1ODA3NDkxMTI5MzA3MDI0OEwyMjI2NTQ3MzA3NzY0MzE5NjA1NDgwMzk3NDE4MTM5MTEwODk5NDk2NTQxODM4MzM5OTU0MTkwMDQzOTc0ODQzNTAxNDUxNzc2Mzc5ATEod2lhWE56SWpvaWFIUjBjSE02THk5dllYVjBhQzV6ZFdrdWFXOGlMQwI+ZXlKcmFXUWlPaUp6ZFdrdGEyVjVMV2xrSWl3aWRIbHdJam9pU2xkVUlpd2lZV3huSWpvaVVsTXlOVFlpZlFNMjA0MzUzNjY2MDAwMzYzNzU3NDU5MjU5NjM0NTY4NjEzMDc5MjUyMDk0NzAyMTkzMzQwMTg1NjQxNTgxNDg1NDQwMzYxOTYyODQ2NDJkAAAAAAAAAGEAHvkRO3Mx6v8o57/BfVE/lOyy/XNNIo3I8elULrhPn0f2hENWzhvW+xEfPX0V4de38++4mYi7ctY8XNJmkBPODrnG7hYw7z5xEUSmSNsGu7IoT3J0z77lP/zuUDzBpJIA'; let parsed2 = parseSerializedZkLoginSignature(testSignature2); - let res1 = await pk.verifyPersonalMessage(fromB64(bytes2), parsed2.signature); + let res1 = await pk.verifyPersonalMessage(fromBase64(bytes2), parsed2.signature); expect(res1).toBe(false); }, { diff --git a/sdk/typescript/test/unit/arguments.test.ts b/sdk/typescript/test/unit/arguments.test.ts index 736b0be0eab50..2748d8f5b626d 100644 --- a/sdk/typescript/test/unit/arguments.test.ts +++ b/sdk/typescript/test/unit/arguments.test.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { toB58 } from '@mysten/bcs'; +import { toBase58 } from '@mysten/bcs'; import { describe, expect, it } from 'vitest'; import { Arguments, Transaction } from '../../src/transactions'; @@ -13,7 +13,7 @@ describe('Arguments helpers', () => { Arguments.receivingRef({ objectId: '1', version: '123', - digest: toB58(new Uint8Array(32).fill(0x1)), + digest: toBase58(new Uint8Array(32).fill(0x1)), }), Arguments.sharedObjectRef({ objectId: '2', @@ -23,7 +23,7 @@ describe('Arguments helpers', () => { Arguments.objectRef({ objectId: '3', version: '123', - digest: toB58(new Uint8Array(32).fill(0x1)), + digest: toBase58(new Uint8Array(32).fill(0x1)), }), Arguments.pure.address('0x2'), Arguments.object.system(), diff --git a/sdk/typescript/test/unit/cryptography/ed25519-keypair.test.ts b/sdk/typescript/test/unit/cryptography/ed25519-keypair.test.ts index de32c40114fd5..3f432401e900c 100644 --- a/sdk/typescript/test/unit/cryptography/ed25519-keypair.test.ts +++ b/sdk/typescript/test/unit/cryptography/ed25519-keypair.test.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { fromB64, toB58 } from '@mysten/bcs'; +import { fromBase64, toBase58 } from '@mysten/bcs'; import nacl from 'tweetnacl'; import { describe, expect, it } from 'vitest'; @@ -40,7 +40,7 @@ describe('ed25519-keypair', () => { }); it('create keypair from secret key', () => { - const secretKey = fromB64(VALID_SECRET_KEY); + const secretKey = fromBase64(VALID_SECRET_KEY); const keypair = Ed25519Keypair.fromSecretKey(secretKey); expect(keypair.getPublicKey().toBase64()).toEqual( 'Gy9JCW4+Xb0Pz6nAwM2S2as7IVRLNNXdSmXZi4eLmSI=', @@ -125,7 +125,7 @@ describe('ed25519-keypair', () => { { objectId: (Math.random() * 100000).toFixed(0).padEnd(64, '0'), version: String((Math.random() * 10000).toFixed(0)), - digest: toB58( + digest: toBase58( new Uint8Array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, diff --git a/sdk/typescript/test/unit/cryptography/keypair.test.ts b/sdk/typescript/test/unit/cryptography/keypair.test.ts index b3403ef2bef38..a7abf32ea6f39 100644 --- a/sdk/typescript/test/unit/cryptography/keypair.test.ts +++ b/sdk/typescript/test/unit/cryptography/keypair.test.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { toB64 } from '@mysten/bcs'; +import { toBase64 } from '@mysten/bcs'; import { beforeAll, describe, expect, it } from 'vitest'; import { bcs } from '../../../src/bcs/index.js'; @@ -50,19 +50,19 @@ describe('Keypair', () => { const sig2 = await k2.signWithIntent(data, 'TransactionData'); const sig3 = await k3.signWithIntent(bytes, 'PersonalMessage'); - expect(sig1.bytes).toEqual(toB64(bytes)); + expect(sig1.bytes).toEqual(toBase64(bytes)); expect(sig1.bytes).toEqual('CQAAAAVIZWxsbw=='); expect(sig1.signature).toEqual( 'ADXvYCSZk+ZtVL6VfB4+5zson++q0uWYINW4u1QKbbPisLUnNgYPFieiwXxp2SroKzqrULJOXdkPiDESw+IWJgVa4iC0svZel3wS7eYVef9RcLbCLABhaMN7XnxhrwGAgw==', ); - expect(sig2.bytes).toEqual(toB64(data)); + expect(sig2.bytes).toEqual(toBase64(data)); expect(sig2.bytes).toEqual('AAAABUhlbGxv'); expect(sig2.signature).toEqual( 'AdF5r9uq1AygqXu+WrGoe+fSVU2ld1F3lxTAcj9Uh38lR9j6trumZ7VPvIuzsnIlDqeiPKzo98KSVXy+AVraiKsCHRUjB8a3Kw7QQYsOcM2A5/UpW42G9XItP1IT+9I5TzY=', ); - expect(sig3.bytes).toEqual(toB64(bytes)); + expect(sig3.bytes).toEqual(toBase64(bytes)); expect(sig3.bytes).toEqual('CQAAAAVIZWxsbw=='); expect(sig3.signature).toEqual( 'Apd48/4qVHSja5u2i7ZxobPL6iTLulNIuCxbd5GhfWVvcd69k9BtIqpFGMYXYyn7zapyvnJbtUZsF2ILc7Rp/X0CJzIrOokaCigNa8H7LLsj0o9UkG/WQH9fdB9t71diYJo=', @@ -76,19 +76,19 @@ describe('Keypair', () => { const sig2 = await k2.signTransaction(data); const sig3 = await k3.signTransaction(data); - expect(sig1.bytes).toEqual(toB64(data)); + expect(sig1.bytes).toEqual(toBase64(data)); expect(sig1.bytes).toEqual('AAAABUhlbGxv'); expect(sig1.signature).toEqual( 'AKu3E+/SrcDpRHQYYljHAxkcUBzXHwkXtdi7X57rYd3f/VeckrWHfU6GgFiwFLEvLexGWNYPGSJKL12VJTCzFQpa4iC0svZel3wS7eYVef9RcLbCLABhaMN7XnxhrwGAgw==', ); - expect(sig2.bytes).toEqual(toB64(data)); + expect(sig2.bytes).toEqual(toBase64(data)); expect(sig2.bytes).toEqual('AAAABUhlbGxv'); expect(sig2.signature).toEqual( 'AdF5r9uq1AygqXu+WrGoe+fSVU2ld1F3lxTAcj9Uh38lR9j6trumZ7VPvIuzsnIlDqeiPKzo98KSVXy+AVraiKsCHRUjB8a3Kw7QQYsOcM2A5/UpW42G9XItP1IT+9I5TzY=', ); - expect(sig3.bytes).toEqual(toB64(data)); + expect(sig3.bytes).toEqual(toBase64(data)); expect(sig3.bytes).toEqual('AAAABUhlbGxv'); expect(sig3.signature).toEqual( 'AvKS25z99kTnsHe70qf2Dd9+Lz0DHTzM7cKFrMF47Z2RNy6qSFzOV87thExeKqug6VvEFiaqYhplx3fsT/rgk9kCJzIrOokaCigNa8H7LLsj0o9UkG/WQH9fdB9t71diYJo=', @@ -102,19 +102,19 @@ describe('Keypair', () => { const sig2 = await k2.signPersonalMessage(data); const sig3 = await k3.signPersonalMessage(data); - expect(sig1.bytes).toEqual(toB64(data)); + expect(sig1.bytes).toEqual(toBase64(data)); expect(sig1.bytes).toEqual('AAAABUhlbGxv'); expect(sig1.signature).toEqual( 'ADXvYCSZk+ZtVL6VfB4+5zson++q0uWYINW4u1QKbbPisLUnNgYPFieiwXxp2SroKzqrULJOXdkPiDESw+IWJgVa4iC0svZel3wS7eYVef9RcLbCLABhaMN7XnxhrwGAgw==', ); - expect(sig2.bytes).toEqual(toB64(data)); + expect(sig2.bytes).toEqual(toBase64(data)); expect(sig2.bytes).toEqual('AAAABUhlbGxv'); expect(sig2.signature).toEqual( 'AViWuVdzTX9lJ2DBIPd4YR2bqTHC07AC9NZ1vbA1k/YeeSCuH6Kd1g3izZB332JgLP7GxjppPmWk4GwNlvbH0vICHRUjB8a3Kw7QQYsOcM2A5/UpW42G9XItP1IT+9I5TzY=', ); - expect(sig3.bytes).toEqual(toB64(data)); + expect(sig3.bytes).toEqual(toBase64(data)); expect(sig3.bytes).toEqual('AAAABUhlbGxv'); expect(sig3.signature).toEqual( 'Apd48/4qVHSja5u2i7ZxobPL6iTLulNIuCxbd5GhfWVvcd69k9BtIqpFGMYXYyn7zapyvnJbtUZsF2ILc7Rp/X0CJzIrOokaCigNa8H7LLsj0o9UkG/WQH9fdB9t71diYJo=', diff --git a/sdk/typescript/test/unit/cryptography/multisig.publickey.test.ts b/sdk/typescript/test/unit/cryptography/multisig.publickey.test.ts index c9fde2c9b49d6..b122370b1a722 100644 --- a/sdk/typescript/test/unit/cryptography/multisig.publickey.test.ts +++ b/sdk/typescript/test/unit/cryptography/multisig.publickey.test.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { fromB64 } from '@mysten/bcs'; +import { fromBase64 } from '@mysten/bcs'; import { blake2b } from '@noble/hashes/blake2b'; import { bytesToHex } from '@noble/hashes/utils'; import { beforeAll, describe, expect, it } from 'vitest'; @@ -204,7 +204,7 @@ describe('Publickey', () => { const sig2 = await k2.signPersonalMessage(data); const multisig = multiSigPublicKey.combinePartialSignatures([sig1.signature, sig2.signature]); - const rawBytes = fromB64(multisig).slice(134); + const rawBytes = fromBase64(multisig).slice(134); expect(multiSigPublicKey.toRawBytes()).toEqual(rawBytes); expect(multiSigPublicKey.toRawBytes()).toEqual( @@ -356,7 +356,7 @@ describe('Publickey', () => { 'AwIANe9gJJmT5m1UvpV8Hj7nOyif76rS5Zgg1bi7VApts+KwtSc2Bg8WJ6LBfGnZKugrOqtQsk5d2Q+IMRLD4hYmBQFYlrlXc01/ZSdgwSD3eGEdm6kxwtOwAvTWdb2wNZP2Hnkgrh+indYN4s2Qd99iYCz+xsY6aT5lpOBsDZb2x9LyAwADAFriILSy9l6XfBLt5hV5/1FwtsIsAGFow3tefGGvAYCDAQECHRUjB8a3Kw7QQYsOcM2A5/UpW42G9XItP1IT+9I5TzYCAgInMis6iRoKKA1rwfssuyPSj1SQb9ZAf190H23vV2JgmgMDAA==', ); - const decoded = bcs.MultiSig.parse(fromB64(multisig).slice(1)); + const decoded = bcs.MultiSig.parse(fromBase64(multisig).slice(1)); expect(decoded).toEqual({ bitmap: 3, @@ -425,7 +425,7 @@ describe('Publickey', () => { const multisig = multiSigPublicKey.combinePartialSignatures([sig1.signature, sig2.signature]); - const bytes = fromB64(multisig); + const bytes = fromBase64(multisig); const multiSigStruct: MultiSigStruct = bcs.MultiSig.parse(bytes.slice(1)); const parsedPartialSignatures = parsePartialSignatures(multiSigStruct); diff --git a/sdk/typescript/test/unit/cryptography/multisig.test.ts b/sdk/typescript/test/unit/cryptography/multisig.test.ts index deb8066c1861a..9fc2ae848000c 100644 --- a/sdk/typescript/test/unit/cryptography/multisig.test.ts +++ b/sdk/typescript/test/unit/cryptography/multisig.test.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { fromB64, toB58, toB64 } from '@mysten/bcs'; +import { fromBase64, toBase58, toBase64 } from '@mysten/bcs'; import { beforeAll, describe, expect, it, test } from 'vitest'; import { bcs } from '../../../src/bcs'; @@ -50,7 +50,7 @@ describe('Multisig scenarios', () => { { objectId: (Math.random() * 100000).toFixed(0).padEnd(64, '0'), version: String((Math.random() * 10000).toFixed(0)), - digest: toB58( + digest: toBase58( new Uint8Array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, @@ -133,7 +133,7 @@ describe('Multisig scenarios', () => { tmp.set([SIGNATURE_SCHEME_TO_FLAG['MultiSig']]); tmp.set(bytes, 1); - const multisig = toB64(tmp); + const multisig = toBase64(tmp); expect(() => multiSigPublicKey.combinePartialSignatures([sig1.signature, sig3.signature]), @@ -198,7 +198,7 @@ describe('Multisig scenarios', () => { tmp.set([SIGNATURE_SCHEME_TO_FLAG['MultiSig']]); tmp.set(bytes, 1); - const multisig = toB64(tmp); + const multisig = toBase64(tmp); expect(() => multiSigPublicKey.combinePartialSignatures([sig2.signature, sig2.signature]), @@ -436,7 +436,7 @@ describe('Multisig address creation:', () => { '0xb9c0780a3943cde13a2409bf1a6f06ae60b0dff2b2f373260cf627aa4f43a588', ); const data = new Uint8Array( - fromB64( + fromBase64( 'AAABACACAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgEBAQABAAC5wHgKOUPN4TokCb8abwauYLDf8rLzcyYM9ieqT0OliAGbB4FfBEl+LgXSLKw6oGFBCyCGjMYZFUxCocYb6ZAnFwEAAAAAAAAAIJZw7UpW1XHubORIOaY8d2+WyBNwoJ+FEAxlsa7h7JHrucB4CjlDzeE6JAm/Gm8GrmCw3/Ky83MmDPYnqk9DpYgBAAAAAAAAABAnAAAAAAAAAA==', ), ); @@ -449,7 +449,7 @@ describe('Multisig address creation:', () => { 'AwIAcAEsWrZtlsE3AdGUKJAPag8Tu6HPfMW7gEemeneO9fmNGiJP/rDZu/tL75lr8A22eFDx9K2G1DL4v8XlmuTtCgOaBwUDTTE3MzE4MDg5MTI1OTUyNDIxNzM2MzQyMjYzNzE3OTMyNzE5NDM3NzE3ODQ0MjgyNDEwMTg3OTU3OTg0NzUxOTM5OTQyODk4MjUxMjUwTTExMzczOTY2NjQ1NDY5MTIyNTgyMDc0MDgyMjk1OTg1Mzg4MjU4ODQwNjgxNjE4MjY4NTkzOTc2Njk3MzI1ODkyMjgwOTE1NjgxMjA3ATEDAkw1OTM5ODcxMTQ3MzQ4ODM0OTk3MzYxNzIwMTIyMjM4OTgwMTc3MTUyMzAzMjc0MzExMDQ3MjQ5OTA1OTQyMzg0OTE1NzY4NjkwODk1TDQ1MzM1NjgyNzExMzQ3ODUyNzg3MzEyMzQ1NzAzNjE0ODI2NTE5OTY3NDA3OTE4ODgyODU4NjQ5NjY4ODQwMzI3MTcwNDk4MTE3MDgCTTEwNTY0Mzg3Mjg1MDcxNTU1NDY5NzUzOTkwNjYxNDEwODQwMTE4NjM1OTI1NDY2NTk3MDM3MDE4MDU4NzcwMDQxMzQ3NTE4NDYxMzY4TTEyNTk3MzIzNTQ3Mjc3NTc5MTQ0Njk4NDk2MzcyMjQyNjE1MzY4MDg1ODAxMzEzMzQzMTU1NzM1NTExMzMwMDAzODg0NzY3OTU3ODU0AgExATADTTE1NzkxNTg5NDcyNTU2ODI2MjYzMjMxNjQ0NzI4ODczMzM3NjI5MDE1MjY5OTg0Njk5NDA0MDczNjIzNjAzMzUyNTM3Njc4ODEzMTcxTDQ1NDc4NjY0OTkyNDg4ODE0NDk2NzYxNjExNTgwMjQ3NDgwNjA0ODUzNzMyNTAwMjk0MjM5MDQxMTMwMTc0MjI1MzkwMzcxNjI1MjcBMTF3aWFYTnpJam9pYUhSMGNITTZMeTlwWkM1MGQybDBZMmd1ZEhZdmIyRjFkR2d5SWl3AjJleUpoYkdjaU9pSlNVekkxTmlJc0luUjVjQ0k2SWtwWFZDSXNJbXRwWkNJNklqRWlmUU0yMDc5NDc4ODU1OTYyMDY2OTU5NjIwNjQ1NzAyMjk2NjE3Njk4NjY4ODcyNzg3NjEyODIyMzYyODExMzkxNjM4MDkyNzUwMjczNzkxMQoAAAAAAAAAYQAR6ZEOSb8am6giraofTNFOXN6N5etgegC1TsTKup7HNMtyZWPBn9WaDwPe+naJustyRgVE7K8umsX6h3Fa7UQMucbuFjDvPnERRKZI2wa7sihPcnTPvuU//O5QPMGkkgADAAIADX2rNYyNrapO+gBJp1sHQ2VVsQo2ghm7aA9wVxNJ13UBAzwbaHR0cHM6Ly9pZC50d2l0Y2gudHYvb2F1dGgyLflu6Eag/zG3tLd5CtZRYx9p1t34RovVSn/+uHFiYfcBAQA=', ); - const decoded = parsePartialSignatures(bcs.MultiSig.parse(fromB64(multisig).slice(1))); + const decoded = parsePartialSignatures(bcs.MultiSig.parse(fromBase64(multisig).slice(1))); expect(decoded).toEqual([ { signature: parseSerializedSignature(sig1.signature).signature, @@ -631,7 +631,7 @@ describe('MultisigKeypair', () => { { objectId: (Math.random() * 100000).toFixed(0).padEnd(64, '0'), version: String((Math.random() * 10000).toFixed(0)), - digest: toB58( + digest: toBase58( new Uint8Array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, diff --git a/sdk/typescript/test/unit/cryptography/publickey.test.ts b/sdk/typescript/test/unit/cryptography/publickey.test.ts index 1961a19af4043..b3cfe1ead7060 100644 --- a/sdk/typescript/test/unit/cryptography/publickey.test.ts +++ b/sdk/typescript/test/unit/cryptography/publickey.test.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { toB64 } from '@mysten/bcs'; +import { toBase64 } from '@mysten/bcs'; import { blake2b } from '@noble/hashes/blake2b'; import { bytesToHex } from '@noble/hashes/utils'; import { beforeAll, describe, expect, it } from 'vitest'; @@ -56,12 +56,12 @@ describe('Publickey', () => { }); it('`toBase64()` should return a valid base-64 representation', async () => { - expect(pk2.toBase64()).toEqual(toB64(pk2.toRawBytes())); + expect(pk2.toBase64()).toEqual(toBase64(pk2.toRawBytes())); expect(pk2.toBase64()).toEqual('Ah0VIwfGtysO0EGLDnDNgOf1KVuNhvVyLT9SE/vSOU82'); }); it('`toSuiPublicKey()` should return a valid sui representation', async () => { - expect(pk2.toSuiPublicKey()).toEqual(toB64(pk2.toSuiBytes())); + expect(pk2.toSuiPublicKey()).toEqual(toBase64(pk2.toSuiBytes())); expect(pk2.toSuiPublicKey()).toEqual('AQIdFSMHxrcrDtBBiw5wzYDn9SlbjYb1ci0/UhP70jlPNg=='); }); diff --git a/sdk/typescript/test/unit/cryptography/secp256k1-keypair.test.ts b/sdk/typescript/test/unit/cryptography/secp256k1-keypair.test.ts index 814eaacb624e0..f4290e3345552 100644 --- a/sdk/typescript/test/unit/cryptography/secp256k1-keypair.test.ts +++ b/sdk/typescript/test/unit/cryptography/secp256k1-keypair.test.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { fromB64, toB58, toB64 } from '@mysten/bcs'; +import { fromBase64, toBase58, toBase64 } from '@mysten/bcs'; import { secp256k1 } from '@noble/curves/secp256k1'; import { sha256 } from '@noble/hashes/sha256'; import { describe, expect, it } from 'vitest'; @@ -66,7 +66,7 @@ describe('secp256k1-keypair', () => { it('create keypair from secret key', () => { const secret_key = new Uint8Array(VALID_SECP256K1_SECRET_KEY); const pub_key = new Uint8Array(VALID_SECP256K1_PUBLIC_KEY); - let pub_key_base64 = toB64(pub_key); + let pub_key_base64 = toBase64(pub_key); const keypair = Secp256k1Keypair.fromSecretKey(secret_key); expect(keypair.getPublicKey().toRawBytes()).toEqual(new Uint8Array(pub_key)); expect(keypair.getPublicKey().toBase64()).toEqual(pub_key_base64); @@ -74,8 +74,8 @@ describe('secp256k1-keypair', () => { it('creating keypair from invalid secret key throws error', () => { const secret_key = new Uint8Array(INVALID_SECP256K1_SECRET_KEY); - let secret_key_base64 = toB64(secret_key); - const secretKey = fromB64(secret_key_base64); + let secret_key_base64 = toBase64(secret_key); + const secretKey = fromBase64(secret_key_base64); expect(() => { Secp256k1Keypair.fromSecretKey(secretKey); }).toThrow('private key must be 32 bytes, hex or bigint, not object'); @@ -169,7 +169,7 @@ describe('secp256k1-keypair', () => { { objectId: (Math.random() * 100000).toFixed(0).padEnd(64, '0'), version: String((Math.random() * 10000).toFixed(0)), - digest: toB58( + digest: toBase58( new Uint8Array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, diff --git a/sdk/typescript/test/unit/cryptography/secp256k1-publickey.test.ts b/sdk/typescript/test/unit/cryptography/secp256k1-publickey.test.ts index 6c887e8135b0e..c12821a40ed10 100644 --- a/sdk/typescript/test/unit/cryptography/secp256k1-publickey.test.ts +++ b/sdk/typescript/test/unit/cryptography/secp256k1-publickey.test.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { toB64, toHEX } from '@mysten/bcs'; +import { toBase64, toHex } from '@mysten/bcs'; import { describe, expect, it } from 'vitest'; import { Secp256k1PublicKey } from '../../../src/keypairs/secp256k1/publickey'; @@ -42,13 +42,13 @@ describe('Secp256k1PublicKey', () => { expect(() => { const invalid_pubkey_buffer = new Uint8Array(INVALID_SECP256K1_PUBLIC_KEY); - let invalid_pubkey_base64 = toB64(invalid_pubkey_buffer); + let invalid_pubkey_base64 = toBase64(invalid_pubkey_buffer); new Secp256k1PublicKey(invalid_pubkey_base64); }).toThrow(); expect(() => { const pubkey_buffer = new Uint8Array(VALID_SECP256K1_PUBLIC_KEY); - let wrong_encode = toHEX(pubkey_buffer); + let wrong_encode = toHex(pubkey_buffer); new Secp256k1PublicKey(wrong_encode); }).toThrow(); @@ -59,14 +59,14 @@ describe('Secp256k1PublicKey', () => { it('toBase64', () => { const pub_key = new Uint8Array(VALID_SECP256K1_PUBLIC_KEY); - let pub_key_base64 = toB64(pub_key); + let pub_key_base64 = toBase64(pub_key); const key = new Secp256k1PublicKey(pub_key_base64); expect(key.toBase64()).toEqual(pub_key_base64); }); it('toBuffer', () => { const pub_key = new Uint8Array(VALID_SECP256K1_PUBLIC_KEY); - let pub_key_base64 = toB64(pub_key); + let pub_key_base64 = toBase64(pub_key); const key = new Secp256k1PublicKey(pub_key_base64); expect(key.toRawBytes().length).toBe(33); expect(new Secp256k1PublicKey(key.toRawBytes()).equals(key)).toBe(true); diff --git a/sdk/typescript/test/unit/cryptography/secp256r1-keypair.test.ts b/sdk/typescript/test/unit/cryptography/secp256r1-keypair.test.ts index a94028e5652b3..e96b6d8832516 100644 --- a/sdk/typescript/test/unit/cryptography/secp256r1-keypair.test.ts +++ b/sdk/typescript/test/unit/cryptography/secp256r1-keypair.test.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { fromB64, toB58, toB64 } from '@mysten/bcs'; +import { fromBase64, toBase58, toBase64 } from '@mysten/bcs'; import { secp256r1 } from '@noble/curves/p256'; import { sha256 } from '@noble/hashes/sha256'; import { describe, expect, it } from 'vitest'; @@ -61,7 +61,7 @@ describe('secp256r1-keypair', () => { it('create keypair from secret key', () => { const secret_key = new Uint8Array(VALID_SECP256R1_SECRET_KEY); const pub_key = new Uint8Array(VALID_SECP256R1_PUBLIC_KEY); - let pub_key_base64 = toB64(pub_key); + let pub_key_base64 = toBase64(pub_key); const keypair = Secp256r1Keypair.fromSecretKey(secret_key); expect(keypair.getPublicKey().toRawBytes()).toEqual(new Uint8Array(pub_key)); expect(keypair.getPublicKey().toBase64()).toEqual(pub_key_base64); @@ -69,8 +69,8 @@ describe('secp256r1-keypair', () => { it('creating keypair from invalid secret key throws error', () => { const secret_key = new Uint8Array(INVALID_SECP256R1_SECRET_KEY); - let secret_key_base64 = toB64(secret_key); - const secretKey = fromB64(secret_key_base64); + let secret_key_base64 = toBase64(secret_key); + const secretKey = fromBase64(secret_key_base64); expect(() => { Secp256r1Keypair.fromSecretKey(secretKey); }).toThrow('private key must be 32 bytes, hex or bigint, not object'); @@ -164,7 +164,7 @@ describe('secp256r1-keypair', () => { { objectId: (Math.random() * 100000).toFixed(0).padEnd(64, '0'), version: String((Math.random() * 10000).toFixed(0)), - digest: toB58( + digest: toBase58( new Uint8Array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, diff --git a/sdk/typescript/test/unit/cryptography/secp256r1-publickey.test.ts b/sdk/typescript/test/unit/cryptography/secp256r1-publickey.test.ts index fc238799f2119..9bb7fc07f20f0 100644 --- a/sdk/typescript/test/unit/cryptography/secp256r1-publickey.test.ts +++ b/sdk/typescript/test/unit/cryptography/secp256r1-publickey.test.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { toB64, toHEX } from '@mysten/bcs'; +import { toBase64, toHex } from '@mysten/bcs'; import { describe, expect, it } from 'vitest'; import { Secp256r1PublicKey } from '../../../src/keypairs/secp256r1/publickey'; @@ -27,13 +27,13 @@ describe('Secp256r1PublicKey', () => { expect(() => { const invalid_pubkey_buffer = new Uint8Array(INVALID_SECP256R1_PUBLIC_KEY); - let invalid_pubkey_base64 = toB64(invalid_pubkey_buffer); + let invalid_pubkey_base64 = toBase64(invalid_pubkey_buffer); new Secp256r1PublicKey(invalid_pubkey_base64); }).toThrow(); expect(() => { const pubkey_buffer = new Uint8Array(VALID_SECP256R1_PUBLIC_KEY); - let wrong_encode = toHEX(pubkey_buffer); + let wrong_encode = toHex(pubkey_buffer); new Secp256r1PublicKey(wrong_encode); }).toThrow(); @@ -44,14 +44,14 @@ describe('Secp256r1PublicKey', () => { it('toBase64', () => { const pub_key = new Uint8Array(VALID_SECP256R1_PUBLIC_KEY); - let pub_key_base64 = toB64(pub_key); + let pub_key_base64 = toBase64(pub_key); const key = new Secp256r1PublicKey(pub_key_base64); expect(key.toBase64()).toEqual(pub_key_base64); }); it('toBuffer', () => { const pub_key = new Uint8Array(VALID_SECP256R1_PUBLIC_KEY); - let pub_key_base64 = toB64(pub_key); + let pub_key_base64 = toBase64(pub_key); const key = new Secp256r1PublicKey(pub_key_base64); expect(key.toRawBytes().length).toBe(33); expect(new Secp256r1PublicKey(key.toRawBytes()).equals(key)).toBe(true); diff --git a/sdk/typescript/test/unit/cryptography/signature.test.ts b/sdk/typescript/test/unit/cryptography/signature.test.ts index 11409936e59f7..1f2e3bdc4546b 100644 --- a/sdk/typescript/test/unit/cryptography/signature.test.ts +++ b/sdk/typescript/test/unit/cryptography/signature.test.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { fromB64, toB64 } from '@mysten/bcs'; +import { fromBase64, toBase64 } from '@mysten/bcs'; import { beforeAll, describe, expect, it } from 'vitest'; import { bcs } from '../../../src/bcs'; @@ -79,7 +79,7 @@ describe('Signature', () => { sig3.signature, ]); - const decoded = parsePartialSignatures(bcs.MultiSig.parse(fromB64(multisig).slice(1))); + const decoded = parsePartialSignatures(bcs.MultiSig.parse(fromBase64(multisig).slice(1))); const SerializeSignatureInput: SerializeSignatureInput[] = [ { @@ -125,7 +125,7 @@ describe('Signature', () => { const multisig = publicKey.combinePartialSignatures([sig1.signature]); - const decoded = parsePartialSignatures(bcs.MultiSig.parse(fromB64(multisig).slice(1))); + const decoded = parsePartialSignatures(bcs.MultiSig.parse(fromBase64(multisig).slice(1))); const SerializeSignatureInput: SerializeSignatureInput[] = [ { @@ -182,9 +182,9 @@ describe('Signature', () => { it('`parseSerializedSignature()` should handle unsupported schemes', async () => { const data = new Uint8Array([0, 0, 0, 5, 72, 101, 108, 108, 111]); const sig1 = await k1.signPersonalMessage(data); - const bytes = fromB64(sig1.signature); + const bytes = fromBase64(sig1.signature); bytes[0] = 0x06; - const invalidSignature = toB64(bytes); + const invalidSignature = toBase64(bytes); expect(() => parseSerializedSignature(invalidSignature)).toThrowError(); }); diff --git a/sdk/typescript/test/unit/object-inputs.test.ts b/sdk/typescript/test/unit/object-inputs.test.ts index ddde51d40331f..25d834c6065ad 100644 --- a/sdk/typescript/test/unit/object-inputs.test.ts +++ b/sdk/typescript/test/unit/object-inputs.test.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { toB58 } from '@mysten/bcs'; +import { toBase58 } from '@mysten/bcs'; import { describe, expect, it } from 'vitest'; import { Transaction } from '../../src/transactions'; @@ -17,7 +17,7 @@ describe('Transaction inputs', () => { tx.receivingRef({ objectId: '1', version: '123', - digest: toB58(new Uint8Array(32).fill(0x1)), + digest: toBase58(new Uint8Array(32).fill(0x1)), }), tx.sharedObjectRef({ objectId: '2', @@ -27,7 +27,7 @@ describe('Transaction inputs', () => { tx.objectRef({ objectId: '3', version: '123', - digest: toB58(new Uint8Array(32).fill(0x1)), + digest: toBase58(new Uint8Array(32).fill(0x1)), }), tx.pure.address('0x2'), tx.object.system(), diff --git a/sdk/typescript/test/unit/v1-json.test.ts b/sdk/typescript/test/unit/v1-json.test.ts index 7eb31dd1545f2..4886441718019 100644 --- a/sdk/typescript/test/unit/v1-json.test.ts +++ b/sdk/typescript/test/unit/v1-json.test.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { toB58 } from '@mysten/bcs'; +import { toBase58 } from '@mysten/bcs'; import { describe, expect, it } from 'vitest'; import { Inputs, Transaction } from '../../src/transactions'; @@ -18,7 +18,7 @@ describe('V1 JSON serialization', () => { Inputs.ReceivingRef({ objectId: '1', version: '123', - digest: toB58(new Uint8Array(32).fill(0x1)), + digest: toBase58(new Uint8Array(32).fill(0x1)), }), ), tx.object( @@ -32,7 +32,7 @@ describe('V1 JSON serialization', () => { Inputs.ObjectRef({ objectId: '3', version: '123', - digest: toB58(new Uint8Array(32).fill(0x1)), + digest: toBase58(new Uint8Array(32).fill(0x1)), }), ), tx.pure.address('0x2'), diff --git a/sdk/wallet-standard/src/wallet.ts b/sdk/wallet-standard/src/wallet.ts index 49ef020da9349..4ae52b9b94aa5 100644 --- a/sdk/wallet-standard/src/wallet.ts +++ b/sdk/wallet-standard/src/wallet.ts @@ -3,7 +3,7 @@ import { bcs } from '@mysten/sui/bcs'; import { Transaction } from '@mysten/sui/transactions'; -import { fromB64, toB64 } from '@mysten/sui/utils'; +import { fromBase64, toBase64 } from '@mysten/sui/utils'; import type { WalletWithFeatures } from '@wallet-standard/core'; import type { @@ -61,7 +61,7 @@ export async function signAndExecuteTransaction( txSignatures: [signature], intentMessage: { value: bcsTransaction }, }, - ] = bcs.SenderSignedData.parse(fromB64(rawTransaction!)); + ] = bcs.SenderSignedData.parse(fromBase64(rawTransaction!)); const bytes = bcs.TransactionData.serialize(bcsTransaction).toBase64(); @@ -69,7 +69,7 @@ export async function signAndExecuteTransaction( digest, signature, bytes, - effects: toB64(new Uint8Array(rawEffects!)), + effects: toBase64(new Uint8Array(rawEffects!)), }; } diff --git a/sdk/zklogin/src/nonce.ts b/sdk/zklogin/src/nonce.ts index 1a89c9175ffe3..f22ddc85f82d6 100644 --- a/sdk/zklogin/src/nonce.ts +++ b/sdk/zklogin/src/nonce.ts @@ -1,7 +1,7 @@ // Copyright (c) Mysten Labs, Inc. // SPDX-License-Identifier: Apache-2.0 -import { toHEX } from '@mysten/bcs'; +import { toHex } from '@mysten/bcs'; import type { PublicKey } from '@mysten/sui/cryptography'; import { toPaddedBigEndianBytes } from '@mysten/sui/zklogin'; import { randomBytes } from '@noble/hashes/utils'; @@ -12,7 +12,7 @@ import { poseidonHash } from './poseidon.js'; export const NONCE_LENGTH = 27; function toBigIntBE(bytes: Uint8Array) { - const hex = toHEX(bytes); + const hex = toHex(bytes); if (hex.length === 0) { return BigInt(0); } diff --git a/sdk/zksend/src/index.test.ts b/sdk/zksend/src/index.test.ts index 0d205fd0bde93..af219bbc0d07d 100644 --- a/sdk/zksend/src/index.test.ts +++ b/sdk/zksend/src/index.test.ts @@ -7,7 +7,7 @@ import { decodeSuiPrivateKey, Keypair } from '@mysten/sui/cryptography'; import { getFaucetHost, requestSuiFromFaucetV0 } from '@mysten/sui/faucet'; import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519'; import { Transaction } from '@mysten/sui/transactions'; -import { toB64 } from '@mysten/sui/utils'; +import { toBase64 } from '@mysten/sui/utils'; import { beforeAll, expect, test } from 'vitest'; import { getSentTransactionsWithLinks, ZkSendLink, ZkSendLinkBuilder } from './index.js'; @@ -481,7 +481,7 @@ describe('Non contract links', () => { expect(res.balanceChanges?.length).toEqual(2); const link2 = await ZkSendLink.fromUrl( - `https://zksend.con/claim#${toB64(decodeSuiPrivateKey(linkKp.getSecretKey()).secretKey)}`, + `https://zksend.con/claim#${toBase64(decodeSuiPrivateKey(linkKp.getSecretKey()).secretKey)}`, { contract: ZK_BAG_CONFIG, network: 'testnet', diff --git a/sdk/zksend/src/links/builder.ts b/sdk/zksend/src/links/builder.ts index d1c10feb40e12..6d08058092738 100644 --- a/sdk/zksend/src/links/builder.ts +++ b/sdk/zksend/src/links/builder.ts @@ -8,7 +8,7 @@ import type { Keypair, Signer } from '@mysten/sui/cryptography'; import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519'; import type { TransactionObjectArgument, TransactionObjectInput } from '@mysten/sui/transactions'; import { Transaction } from '@mysten/sui/transactions'; -import { normalizeStructTag, normalizeSuiAddress, SUI_TYPE_ARG, toB64 } from '@mysten/sui/utils'; +import { normalizeStructTag, normalizeSuiAddress, SUI_TYPE_ARG, toBase64 } from '@mysten/sui/utils'; import type { ZkBagContractOptions } from './zk-bag.js'; import { getContractIds, ZkBag } from './zk-bag.js'; @@ -106,7 +106,7 @@ export class ZkSendLinkBuilder { getLink(): string { const link = new URL(this.#host); link.pathname = this.#path; - link.hash = `${this.#contract ? '$' : ''}${toB64( + link.hash = `${this.#contract ? '$' : ''}${toBase64( decodeSuiPrivateKey(this.keypair.getSecretKey()).secretKey, )}`; diff --git a/sdk/zksend/src/links/claim.ts b/sdk/zksend/src/links/claim.ts index d80d6739bcfb2..1e1d2515a5f25 100644 --- a/sdk/zksend/src/links/claim.ts +++ b/sdk/zksend/src/links/claim.ts @@ -14,13 +14,13 @@ import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519'; import type { TransactionObjectArgument } from '@mysten/sui/transactions'; import { Transaction } from '@mysten/sui/transactions'; import { - fromB64, + fromBase64, normalizeStructTag, normalizeSuiAddress, normalizeSuiObjectId, parseStructTag, SUI_TYPE_ARG, - toB64, + toBase64, } from '@mysten/sui/utils'; import type { ZkSendLinkBuilderOptions } from './builder.js'; @@ -126,7 +126,7 @@ export class ZkSendLink { let link: ZkSendLink; if (isContractLink) { - const keypair = Ed25519Keypair.fromSecretKey(fromB64(parsed.hash.slice(2))); + const keypair = Ed25519Keypair.fromSecretKey(fromBase64(parsed.hash.slice(2))); link = new ZkSendLink({ ...options, keypair, @@ -137,7 +137,7 @@ export class ZkSendLink { }); } else { const keypair = Ed25519Keypair.fromSecretKey( - fromB64(isContractLink ? parsed.hash.slice(2) : parsed.hash.slice(1)), + fromBase64(isContractLink ? parsed.hash.slice(2) : parsed.hash.slice(1)), ); link = new ZkSendLink({ @@ -233,7 +233,7 @@ export class ZkSendLink { reclaim ? address : this.keypair!.toSuiAddress(), ); - const bytes = fromB64(sponsored.bytes); + const bytes = fromBase64(sponsored.bytes); const signature = sign ? await sign(bytes) : (await this.keypair!.signTransaction(bytes)).signature; @@ -546,7 +546,7 @@ export class ZkSendLink { network: this.#network, sender, claimer, - transactionBlockKindBytes: toB64( + transactionBlockKindBytes: toBase64( await tx.build({ onlyTransactionKind: true, client: this.#client, diff --git a/sdk/zksend/src/links/list-created-links.ts b/sdk/zksend/src/links/list-created-links.ts index 05a8f498e0046..aa8aa5864ab6f 100644 --- a/sdk/zksend/src/links/list-created-links.ts +++ b/sdk/zksend/src/links/list-created-links.ts @@ -5,7 +5,7 @@ import { bcs } from '@mysten/sui/bcs'; import type { SuiClient } from '@mysten/sui/client'; import { SuiGraphQLClient } from '@mysten/sui/graphql'; import { graphql } from '@mysten/sui/graphql/schemas/2024.4'; -import { fromB64, normalizeSuiAddress } from '@mysten/sui/utils'; +import { fromBase64, normalizeSuiAddress } from '@mysten/sui/utils'; import { ZkSendLink } from './claim.js'; import type { ZkBagContractOptions } from './zk-bag.js'; @@ -85,7 +85,7 @@ export async function listCreatedLinks({ return null; } - const kind = bcs.SenderSignedData.parse(fromB64(node.bcs))?.[0]?.intentMessage.value.V1 + const kind = bcs.SenderSignedData.parse(fromBase64(node.bcs))?.[0]?.intentMessage.value.V1 .kind; if (!kind.ProgrammableTransaction) { diff --git a/sdk/zksend/src/wallet/index.ts b/sdk/zksend/src/wallet/index.ts index 38496a2051bb1..cff4e1ec4a5ff 100644 --- a/sdk/zksend/src/wallet/index.ts +++ b/sdk/zksend/src/wallet/index.ts @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { Transaction } from '@mysten/sui/transactions'; -import { toB64 } from '@mysten/sui/utils'; +import { toBase64 } from '@mysten/sui/utils'; import type { StandardConnectFeature, StandardConnectMethod, @@ -170,7 +170,7 @@ export class StashedWallet implements Wallet { origin: this.#origin, network: this.#network, }); - const bytes = toB64(message); + const bytes = toBase64(message); const response = await popup.send({ type: 'sign-personal-message',