diff --git a/.lintstagedrc.json b/.lintstagedrc.json index cc9d9de8b..5cb5a2d55 100644 --- a/.lintstagedrc.json +++ b/.lintstagedrc.json @@ -1,3 +1,7 @@ { - "*.{js,jsx,ts,tsx}": ["prettier --write", "eslint --fix"] + "*.{js,jsx,ts,tsx,json}": ["prettier --write"], + "./apps/**/src/*.{js,jsx,ts,tsx}": ["eslint --fix --max-warnings=0"], + "./packages/**/src/*.{js,jsx,ts,tsx}": ["eslint --fix --max-warnings=0"], + "./storybook/src/*.{js,jsx,ts,tsx}": ["eslint --fix --max-warnings=0"], + "./e2e/src/*.{js,jsx,ts,tsx}": ["eslint --fix --max-warnings=0"] } diff --git a/apps/airdrop/package.json b/apps/airdrop/package.json index 079ee5afc..65cdd4a50 100644 --- a/apps/airdrop/package.json +++ b/apps/airdrop/package.json @@ -18,9 +18,6 @@ "lint:fix": "npx yarn lint -- --fix" }, "dependencies": { - "@namada/components": "0.2.1", - "@namada/hooks": "0.2.1", - "@namada/utils": "0.2.1", "buffer": "^6.0.3", "dompurify": "^3.0.2", "gsap": "^3.12.2", diff --git a/apps/extension/.release-it.cjs b/apps/extension/.release-it.cjs index b34860d84..9261789f6 100644 --- a/apps/extension/.release-it.cjs +++ b/apps/extension/.release-it.cjs @@ -2,11 +2,6 @@ const baseConfig = require("../../.release-it.base.cjs"); const config = { ...baseConfig, - hooks: { - "after:bump": [ - "yarn bump -p chains -p components -p crypto -p shared -p storage -p types -p utils", - ], - }, }; module.exports = config; diff --git a/apps/extension/package.json b/apps/extension/package.json index ab183442a..2e67dac5d 100644 --- a/apps/extension/package.json +++ b/apps/extension/package.json @@ -26,13 +26,14 @@ "start:chrome:proxy": "NAMADA_INTERFACE_PROXY=true yarn start:chrome", "start:firefox": "yarn clean:firefox && NODE_ENV=development TARGET=firefox yarn watch", "start:firefox:proxy": "NAMADA_INTERFACE_PROXY=true yarn start:firefox", - "test": "./scripts/build-node.sh && yarn jest --coverage", - "test:watch": "./scripts/build-node.sh && yarn jest --watchAll=true", + "test": "yarn wasm:build:test && yarn jest --coverage", + "test:watch": "yarn wasm:build:test && yarn jest --watchAll=true", "test:ci": "jest", "wasm:build": "node ./scripts/build.js --release", "wasm:build:multicore": "node ./scripts/build.js --release --multicore", "wasm:build:dev": "node ./scripts/build.js", - "wasm:build:dev:multicore": "node ./scripts/build.js --multicore" + "wasm:build:dev:multicore": "node ./scripts/build.js --multicore", + "wasm:build:test": "./scripts/build-test.sh" }, "dependencies": { "@cosmjs/encoding": "^0.29.0", @@ -40,13 +41,6 @@ "@ledgerhq/hw-transport": "^6.30.0", "@ledgerhq/hw-transport-webhid": "^6.28.0", "@ledgerhq/hw-transport-webusb": "^6.28.0", - "@namada/chains": "0.2.1", - "@namada/components": "0.2.1", - "@namada/crypto": "0.2.1", - "@namada/shared": "0.2.1", - "@namada/storage": "0.2.1", - "@namada/types": "0.2.1", - "@namada/utils": "0.2.1", "@zondax/ledger-namada": "^0.0.4", "bignumber.js": "^9.1.1", "buffer": "^6.0.3", @@ -65,7 +59,6 @@ }, "devDependencies": { "@babel/plugin-transform-modules-commonjs": "^7.20.11", - "@namada/config": "workspace:^", "@svgr/webpack": "^6.3.1", "@types/chrome": "^0.0.237", "@types/dompurify": "^3.0.2", diff --git a/apps/extension/scripts/build-node.sh b/apps/extension/scripts/build-test.sh similarity index 93% rename from apps/extension/scripts/build-node.sh rename to apps/extension/scripts/build-test.sh index 4a05807f0..4c5ab9a04 100755 --- a/apps/extension/scripts/build-node.sh +++ b/apps/extension/scripts/build-test.sh @@ -3,5 +3,5 @@ SCRIPT_DIR=$(cd "$(dirname "$0")"; pwd -P) PACKAGES_PATH="../../../packages" -cd "${SCRIPT_DIR}/${PACKAGES_PATH}/crypto" && yarn wasm:build:node -cd "${SCRIPT_DIR}/${PACKAGES_PATH}/shared" && yarn wasm:build:node +cd "${SCRIPT_DIR}/${PACKAGES_PATH}/crypto" && yarn wasm:build:node:dev +cd "${SCRIPT_DIR}/${PACKAGES_PATH}/shared" && yarn wasm:build:node:dev diff --git a/apps/extension/src/App/Accounts/AddAccount.tsx b/apps/extension/src/App/Accounts/AddAccount.tsx index 0b04f9960..7d7608378 100644 --- a/apps/extension/src/App/Accounts/AddAccount.tsx +++ b/apps/extension/src/App/Accounts/AddAccount.tsx @@ -4,8 +4,8 @@ import { useNavigate } from "react-router-dom"; import { chains } from "@namada/chains"; import { ActionButton, Input, Toggle } from "@namada/components"; +import { makeBip44Path } from "@namada/sdk/web"; import { AccountType, DerivedAccount } from "@namada/types"; -import { makeBip44Path } from "@namada/utils"; import { TopLevelRoute } from "App/types"; import { AddLedgerAccountMsg, DeriveAccountMsg } from "background/keyring"; diff --git a/apps/extension/src/Approvals/Approvals.tsx b/apps/extension/src/Approvals/Approvals.tsx index 05e1fd4cb..c43232691 100644 --- a/apps/extension/src/Approvals/Approvals.tsx +++ b/apps/extension/src/Approvals/Approvals.tsx @@ -2,7 +2,7 @@ import React, { useState } from "react"; import { Route, Routes } from "react-router-dom"; import { Container } from "@namada/components"; -import { TxType } from "@namada/shared"; +import { TxType } from "@namada/sdk/web"; import { AppHeader } from "App/Common/AppHeader"; import { TopLevelRoute } from "Approvals/types"; diff --git a/apps/extension/src/Approvals/ApproveTx/ApproveTx.tsx b/apps/extension/src/Approvals/ApproveTx/ApproveTx.tsx index 3d74cbd08..fcc78626d 100644 --- a/apps/extension/src/Approvals/ApproveTx/ApproveTx.tsx +++ b/apps/extension/src/Approvals/ApproveTx/ApproveTx.tsx @@ -3,7 +3,7 @@ import { useNavigate } from "react-router-dom"; import { ActionButton, Alert, Stack } from "@namada/components"; import { useSanitizedParams } from "@namada/hooks"; -import { TxType, TxTypeLabel } from "@namada/shared"; +import { TxType, TxTypeLabel } from "@namada/sdk/web"; import { AccountType, Tokens } from "@namada/types"; import { shortenAddress } from "@namada/utils"; import { ApprovalDetails } from "Approvals/Approvals"; diff --git a/apps/extension/src/Approvals/ApproveTx/ConfirmLedgerTx.tsx b/apps/extension/src/Approvals/ApproveTx/ConfirmLedgerTx.tsx index d651e49f0..3a2c86cfe 100644 --- a/apps/extension/src/Approvals/ApproveTx/ConfirmLedgerTx.tsx +++ b/apps/extension/src/Approvals/ApproveTx/ConfirmLedgerTx.tsx @@ -3,7 +3,7 @@ import BigNumber from "bignumber.js"; import { useCallback, useEffect, useState } from "react"; import { ActionButton, Alert, Stack } from "@namada/components"; -import { TxType, TxTypeLabel } from "@namada/shared"; +import { TxType, TxTypeLabel } from "@namada/sdk/web"; import { Message, TxMsgValue, TxProps } from "@namada/types"; import { LedgerError } from "@zondax/ledger-namada"; import { ApprovalDetails, Status } from "Approvals/Approvals"; diff --git a/apps/extension/src/Approvals/ApproveTx/ConfirmTx.tsx b/apps/extension/src/Approvals/ApproveTx/ConfirmTx.tsx index 59db79877..d8992c8a8 100644 --- a/apps/extension/src/Approvals/ApproveTx/ConfirmTx.tsx +++ b/apps/extension/src/Approvals/ApproveTx/ConfirmTx.tsx @@ -2,7 +2,7 @@ import { useCallback, useEffect, useState } from "react"; import { useNavigate } from "react-router-dom"; import { ActionButton, Alert, Input, Stack } from "@namada/components"; -import { SupportedTx, TxType, TxTypeLabel } from "@namada/shared"; +import { SupportedTx, TxType, TxTypeLabel } from "@namada/sdk/web"; import { shortenAddress } from "@namada/utils"; import { ApprovalDetails, Status } from "Approvals/Approvals"; import { SubmitApprovedTxMsg } from "background/approvals"; diff --git a/apps/extension/src/background/approvals/handler.test.ts b/apps/extension/src/background/approvals/handler.test.ts index f52ee8c4d..2f0531a04 100644 --- a/apps/extension/src/background/approvals/handler.test.ts +++ b/apps/extension/src/background/approvals/handler.test.ts @@ -1,5 +1,5 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ -import { TxType } from "@namada/shared"; +import { TxType } from "@namada/sdk/web"; import { AccountType } from "@namada/types"; import createMockInstance from "jest-create-mock-instance"; import { diff --git a/apps/extension/src/background/approvals/messages.test.ts b/apps/extension/src/background/approvals/messages.test.ts index 6ad25a4ef..b0cc87f09 100644 --- a/apps/extension/src/background/approvals/messages.test.ts +++ b/apps/extension/src/background/approvals/messages.test.ts @@ -1,5 +1,5 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ -import { TxType } from "@namada/shared"; +import { TxType } from "@namada/sdk/web"; import { ROUTE } from "./constants"; import { ConnectInterfaceResponseMsg, diff --git a/apps/extension/src/background/approvals/messages.ts b/apps/extension/src/background/approvals/messages.ts index 78fdf081a..ae1ca271e 100644 --- a/apps/extension/src/background/approvals/messages.ts +++ b/apps/extension/src/background/approvals/messages.ts @@ -1,4 +1,4 @@ -import { SupportedTx } from "@namada/shared"; +import { SupportedTx } from "@namada/sdk/web"; import { Message } from "router"; import { ROUTE } from "./constants"; diff --git a/apps/extension/src/background/approvals/service.test.ts b/apps/extension/src/background/approvals/service.test.ts index fff999816..831e3d48c 100644 --- a/apps/extension/src/background/approvals/service.test.ts +++ b/apps/extension/src/background/approvals/service.test.ts @@ -1,6 +1,6 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ import * as borsh from "@dao-xyz/borsh"; -import { TxType } from "@namada/shared"; +import { TxType } from "@namada/sdk/web"; import { AccountType, BondMsgValue, @@ -42,6 +42,13 @@ jest.mock("@namada/utils", () => { }; }); +// Because we run tests in node environment, we need to mock web-init as node-init +jest.mock( + "@namada/sdk/web-init", + () => () => + Promise.resolve(jest.requireActual("@namada/sdk/node-init").default()) +); + describe("approvals service", () => { let service: ApprovalsService; let keyRingService: jest.Mocked; diff --git a/apps/extension/src/background/approvals/service.ts b/apps/extension/src/background/approvals/service.ts index 61779ca44..c53f05b48 100644 --- a/apps/extension/src/background/approvals/service.ts +++ b/apps/extension/src/background/approvals/service.ts @@ -4,7 +4,7 @@ import BigNumber from "bignumber.js"; import { v4 as uuid } from "uuid"; import browser, { Windows } from "webextension-polyfill"; -import { SupportedTx, TxType } from "@namada/shared"; +import { SupportedTx, TxType } from "@namada/sdk/web"; import { KVStore } from "@namada/storage"; import { AccountType, diff --git a/apps/extension/src/background/approvals/types.ts b/apps/extension/src/background/approvals/types.ts index fffae64f7..d0f8f2377 100644 --- a/apps/extension/src/background/approvals/types.ts +++ b/apps/extension/src/background/approvals/types.ts @@ -1,4 +1,4 @@ -import { SupportedTx } from "@namada/shared"; +import { SupportedTx } from "@namada/sdk/web"; export type ApprovedOriginsStore = string[]; diff --git a/apps/extension/src/background/chains/service.ts b/apps/extension/src/background/chains/service.ts index edacfd31f..3c043d0f8 100644 --- a/apps/extension/src/background/chains/service.ts +++ b/apps/extension/src/background/chains/service.ts @@ -1,6 +1,6 @@ import { chains } from "@namada/chains"; -import { Query } from "@namada/shared"; import { Chain } from "@namada/types"; +import { SdkService } from "background/sdk"; import { ExtensionBroadcaster } from "extension"; import { LocalStorage } from "storage"; @@ -8,6 +8,7 @@ export const CHAINS_KEY = "chains"; export class ChainsService { constructor( + protected readonly sdkService: SdkService, protected readonly localStorage: LocalStorage, protected readonly broadcaster: ExtensionBroadcaster ) { @@ -16,9 +17,9 @@ export class ChainsService { } private async _queryNativeToken(chain: Chain): Promise { - const query = new Query(chain.rpc); try { - const nativeToken = await query.query_native_token(); + const nativeToken = await this.sdkService.getSdk().rpc.queryNativeToken(); + if (nativeToken) { chain.currency.address = nativeToken; } @@ -59,6 +60,8 @@ export class ChainsService { chainId, rpc: url, }; + + this.sdkService.syncChain(chain); await this.localStorage.setChain(await this._queryNativeToken(chain)); await this.broadcaster.updateNetwork(); } diff --git a/apps/extension/src/background/index.ts b/apps/extension/src/background/index.ts index 475d872f2..a1418bbd6 100644 --- a/apps/extension/src/background/index.ts +++ b/apps/extension/src/background/index.ts @@ -1,5 +1,3 @@ -import { init as initCrypto } from "@namada/crypto/src/init"; -import { init as initShared } from "@namada/shared/src/init"; import { ExtensionKVStore, IndexedDBKVStore, @@ -54,19 +52,12 @@ router.addGuard(ExtensionGuards.checkOriginIsValid); router.addGuard(ExtensionGuards.checkMessageIsInternal); const init = new Promise(async (resolve) => { - const cryptoWasm = await fetch("crypto.namada.wasm").then((wasm) => - wasm.arrayBuffer() - ); - const { memory: cryptoMemory } = await initCrypto(cryptoWasm); - - const sharedWasm = await fetch("shared.namada.wasm").then((wasm) => - wasm.arrayBuffer() - ); - await initShared(sharedWasm); - const routerId = await getNamadaRouterId(localStorage); const requester = new ExtensionRequester(messenger, routerId); const broadcaster = new ExtensionBroadcaster(localStorage, requester); + const sdkService = await SdkService.init(localStorage); + + const { cryptoMemory } = sdkService.getSdk(); const vaultService = new VaultService( vaultStorage, @@ -75,8 +66,11 @@ const init = new Promise(async (resolve) => { broadcaster ); await vaultService.initialize(); - const chainsService = new ChainsService(localStorage, broadcaster); - const sdkService = new SdkService(chainsService); + const chainsService = new ChainsService( + sdkService, + localStorage, + broadcaster + ); const keyRingService = new KeyRingService( vaultService, sdkService, @@ -84,7 +78,6 @@ const init = new Promise(async (resolve) => { utilityStore, localStorage, vaultStorage, - cryptoMemory, requester, broadcaster ); diff --git a/apps/extension/src/background/keyring/keyring.ts b/apps/extension/src/background/keyring/keyring.ts index d4b132166..6033d1f8f 100644 --- a/apps/extension/src/background/keyring/keyring.ts +++ b/apps/extension/src/background/keyring/keyring.ts @@ -1,24 +1,5 @@ import { deserialize } from "@dao-xyz/borsh"; -import { chains } from "@namada/chains"; -import { - HDWallet, - Mnemonic, - PhraseSize, - ShieldedHDWallet, - StringPointer, - VecU8Pointer, - readStringPointer, - readVecStringPointer, - readVecU8Pointer, -} from "@namada/crypto"; - -import { - Address, - ExtendedSpendingKey, - ExtendedViewingKey, - PaymentAddress, -} from "@namada/shared"; import { KVStore } from "@namada/storage"; import { AccountType, @@ -29,17 +10,12 @@ import { IbcTransferMsgValue, SignatureResponse, TransferMsgValue, + TxMsgValue, UnbondMsgValue, VoteProposalMsgValue, WithdrawMsgValue, } from "@namada/types"; -import { - Result, - assertNever, - makeBip44PathArray, - makeSaplingPathArray, - truncateInMiddle, -} from "@namada/utils"; +import { Result, assertNever, truncateInMiddle } from "@namada/utils"; import { AccountSecret, @@ -53,6 +29,7 @@ import { UtilityStore, } from "./types"; +import { PhraseSize } from "@namada/sdk/web"; import { SdkService } from "background/sdk"; import { VaultService } from "background/vault"; import { KeyStore, KeyStoreType, SensitiveType, VaultStorage } from "storage"; @@ -82,8 +59,7 @@ export class KeyRing { protected readonly vaultService: VaultService, protected readonly vaultStorage: VaultStorage, protected readonly sdkService: SdkService, - protected readonly utilityStore: KVStore, - protected readonly cryptoMemory: WebAssembly.Memory + protected readonly utilityStore: KVStore ) {} public get status(): KeyRingStatus { @@ -102,27 +78,18 @@ export class KeyRing { } public validateMnemonic(phrase: string): MnemonicValidationResponse { - const isValid = Mnemonic.validate(phrase); + const mnemonic = this.sdkService.getSdk().getMnemonic(); + const isValid = mnemonic.validateMnemonic(phrase); - try { - Mnemonic.from_phrase(phrase); - } catch (e) { - return { isValid, error: `${e}` }; - } - - return { isValid }; + return isValid; } // Return new mnemonic to client for validation public async generateMnemonic( size: PhraseSize = PhraseSize.N12 ): Promise { - const mnemonic = new Mnemonic(size); - const vecStringPointer = mnemonic.to_words(); - const words = readVecStringPointer(vecStringPointer, this.cryptoMemory); - - mnemonic.free(); - vecStringPointer.free(); + const mnemonic = this.sdkService.getSdk().getMnemonic(); + const words = mnemonic.generate(size); return words; } @@ -188,6 +155,7 @@ export class KeyRing { await this.vaultService.assertIsUnlocked(); const path = { account: 0, change: 0, index: 0 }; + const keys = this.sdkService.getSdk().getKeys(); const { sk, text, passphrase, accountType } = ((): { sk: string; @@ -198,23 +166,14 @@ export class KeyRing { switch (accountSecret.t) { case "Mnemonic": const phrase = accountSecret.seedPhrase.join(" "); - const mnemonic = Mnemonic.from_phrase(phrase); - const passphrase = new StringPointer(accountSecret.passphrase); - const seed = mnemonic.to_seed(passphrase); - const { coinType } = chains.namada.bip44; - const bip44Path = makeBip44PathArray(coinType, path); - const hdWallet = new HDWallet(seed); - const key = hdWallet.derive(new Uint32Array(bip44Path)); - const privateKeyStringPtr = key.to_hex(); - const sk = readStringPointer(privateKeyStringPtr, this.cryptoMemory); - - mnemonic.free(); - hdWallet.free(); - key.free(); - privateKeyStringPtr.free(); + const transparentKeys = keys.deriveFromMnemonic( + phrase, + path, + accountSecret.passphrase + ); return { - sk, + sk: transparentKeys.privateKey, text: phrase, passphrase: accountSecret.passphrase, accountType: AccountType.Mnemonic, @@ -235,9 +194,7 @@ export class KeyRing { } })(); - const addr = new Address(sk); - const address = addr.implicit(); - const publicKey = addr.public(); + const { address, publicKey } = keys.getAddress(sk); // Check whether keys already exist for this account const account = await this.queryAccountByAddress(address); @@ -276,17 +233,12 @@ export class KeyRing { } public deriveTransparentAccount( - seed: VecU8Pointer, + seed: Uint8Array, path: Bip44Path, parentId: string ): DerivedAccountInfo { - const { coinType } = chains.namada.bip44; - const derivationPath = makeBip44PathArray(coinType, path); - const hdWallet = new HDWallet(seed); - const key = hdWallet.derive(new Uint32Array(derivationPath)); - const privateKey = key.to_hex(); - const text = readStringPointer(privateKey, this.cryptoMemory); - const address = new Address(text).implicit(); + const keysNs = this.sdkService.getSdk().getKeys(); + const { address, privateKey } = keysNs.deriveFromSeed(seed, path); const { account, change, index } = path; const id = generateId( @@ -298,42 +250,26 @@ export class KeyRing { index ); - hdWallet.free(); - key.free(); - privateKey.free(); - return { address, owner: address, id, - text, + text: privateKey, }; } public deriveShieldedAccount( - seedPtr: VecU8Pointer, + seed: Uint8Array, path: Bip44Path, parentId: string ): DerivedAccountInfo { const { index } = path; const id = generateId(UUID_NAMESPACE, "shielded-account", parentId, index); - const derivationPath = makeSaplingPathArray(877, path.account); - const seed = readVecU8Pointer(seedPtr, this.cryptoMemory); - - const zip32 = new ShieldedHDWallet(seed); - const keys = zip32.derive(derivationPath); - - // Deserialize and encode keys and address - const extendedSpendingKey = new ExtendedSpendingKey(keys.xsk()); - const extendedViewingKey = new ExtendedViewingKey(keys.xfvk()); - const address = new PaymentAddress(keys.payment_address()).encode(); - const spendingKey = extendedSpendingKey.encode(); - const viewingKey = extendedViewingKey.encode(); - - zip32.free(); - keys.free(); - extendedViewingKey.free(); - extendedSpendingKey.free(); + const keysNs = this.sdkService.getSdk().getKeys(); + const { address, viewingKey, spendingKey } = keysNs.deriveShieldedFromSeed( + seed, + path + ); return { address, @@ -440,7 +376,7 @@ export class KeyRing { private async getParentSeed(): Promise<{ parentId: string; - seed: VecU8Pointer; + seed: Uint8Array; }> { const activeAccount = await this.getActiveAccount(); @@ -469,13 +405,9 @@ export class KeyRing { const { text, passphrase } = sensitiveData; - const mnemonic = Mnemonic.from_phrase(text); - const passphrasePtr = passphrase - ? new StringPointer(passphrase) - : undefined; + const mnemonicSdk = this.sdkService.getSdk().getMnemonic(); + const seed = mnemonicSdk.toSeed(text, passphrase); - const seed = mnemonic.to_seed(passphrasePtr); - mnemonic.free(); return { parentId, seed }; } catch (e) { console.error(e); @@ -523,10 +455,9 @@ export class KeyRing { } const deriveFn = ( - type === AccountType.PrivateKey - ? this.deriveTransparentAccount - : this.deriveShieldedAccount - ).bind(this); + type === AccountType.PrivateKey ? + this.deriveTransparentAccount + : this.deriveShieldedAccount).bind(this); const { seed, parentId } = await this.getParentSeed(); const info = deriveFn(seed, path, parentId); @@ -639,8 +570,6 @@ export class KeyRing { throw new Error(`Account for ${address} not found!`); } const { path } = accountStore; - const { coinType } = chains.namada.bip44; - const bip44Path = makeBip44PathArray(coinType, path); const sensitiveProps = await this.vaultService.reveal( @@ -656,38 +585,30 @@ export class KeyRing { if (account.public.type === AccountType.PrivateKey) { privateKey = secret; } else { - const mnemonic = Mnemonic.from_phrase(secret); - const passphrasePtr = - typeof passphrase === "string" - ? new StringPointer(passphrase) - : undefined; - - const seed = mnemonic.to_seed(passphrasePtr); - const hdWallet = new HDWallet(seed); - const key = hdWallet.derive(new Uint32Array(bip44Path)); - const privateKeyStringPtr = key.to_hex(); - privateKey = readStringPointer(privateKeyStringPtr, this.cryptoMemory); - - mnemonic.free(); - hdWallet.free(); - key.free(); - privateKeyStringPtr.free(); + const sdk = this.sdkService.getSdk(); + const mnemonic = sdk.getMnemonic(); + const seed = mnemonic.toSeed(secret, passphrase); + + const keys = this.sdkService.getSdk().getKeys(); + privateKey = keys.deriveFromSeed(seed, path).privateKey; } return privateKey; } - async submitBond(bondMsg: Uint8Array, txMsg: Uint8Array): Promise { + async submitBond(bondMsg: BondMsgValue, txMsg: TxMsgValue): Promise { await this.vaultService.assertIsUnlocked(); try { - const { source } = deserialize(Buffer.from(bondMsg), BondMsgValue); + const { source } = bondMsg; const signingKey = await this.getSigningKey(source); - const sdk = await this.sdkService.getSdk(); - await sdk.reveal_pk(signingKey, txMsg); + const sdk = this.sdkService.getSdk(); + const sdkTx = sdk.tx; + + await sdkTx.revealPk(signingKey, txMsg); - const builtTx = await sdk.build_bond(bondMsg, txMsg); - const txBytes = await sdk.sign_tx(builtTx, txMsg, signingKey); - const innerTxHash: string = await sdk.process_tx(txBytes, txMsg); + const builtTx = await sdkTx.buildBond(txMsg, bondMsg); + const signedTx = await sdkTx.signTx(builtTx, signingKey); + const innerTxHash: string = await sdk.rpc.broadcastTx(signedTx); return innerTxHash; } catch (e) { @@ -704,20 +625,20 @@ export class KeyRing { } async submitUnbond( - unbondMsg: Uint8Array, - txMsg: Uint8Array + unbondMsg: UnbondMsgValue, + txMsg: TxMsgValue ): Promise { await this.vaultService.assertIsUnlocked(); - const sdk = await this.sdkService.getSdk(); + const sdk = this.sdkService.getSdk(); try { - const { source } = deserialize(Buffer.from(unbondMsg), UnbondMsgValue); + const { source } = unbondMsg; const signingKey = await this.getSigningKey(source); - await sdk.reveal_pk(signingKey, txMsg); + await sdk.tx.revealPk(signingKey, txMsg); - const builtTx = await sdk.build_unbond(unbondMsg, txMsg); - const txBytes = await sdk.sign_tx(builtTx, txMsg, signingKey); - const innerTxHash: string = await sdk.process_tx(txBytes, txMsg); + const builtTx = await sdk.tx.buildUnbond(txMsg, unbondMsg); + const signedTx = await sdk.tx.signTx(builtTx, signingKey); + const innerTxHash: string = await sdk.rpc.broadcastTx(signedTx); return innerTxHash; } catch (e) { @@ -726,23 +647,20 @@ export class KeyRing { } async submitWithdraw( - withdrawMsg: Uint8Array, - txMsg: Uint8Array + withdrawMsg: WithdrawMsgValue, + txMsg: TxMsgValue ): Promise { await this.vaultService.assertIsUnlocked(); - const sdk = await this.sdkService.getSdk(); + const sdk = this.sdkService.getSdk(); try { - const { source } = deserialize( - Buffer.from(withdrawMsg), - WithdrawMsgValue - ); + const { source } = withdrawMsg; const signingKey = await this.getSigningKey(source); - await sdk.reveal_pk(signingKey, txMsg); + await sdk.tx.revealPk(signingKey, txMsg); - const builtTx = await sdk.build_withdraw(withdrawMsg, txMsg); - const txBytes = await sdk.sign_tx(builtTx, txMsg, signingKey); - const innerTxHash: string = await sdk.process_tx(txBytes, txMsg); + const builtTx = await sdk.tx.buildWithdraw(txMsg, withdrawMsg); + const signedTx = await sdk.tx.signTx(builtTx, signingKey); + const innerTxHash: string = await sdk.rpc.broadcastTx(signedTx); return innerTxHash; } catch (e) { @@ -751,24 +669,21 @@ export class KeyRing { } async submitVoteProposal( - voteProposalMsg: Uint8Array, - txMsg: Uint8Array + voteProposalMsg: VoteProposalMsgValue, + txMsg: TxMsgValue ): Promise { await this.vaultService.assertIsUnlocked(); - const sdk = await this.sdkService.getSdk(); + const sdk = this.sdkService.getSdk(); try { - const { signer } = deserialize( - Buffer.from(voteProposalMsg), - VoteProposalMsgValue - ); + const { signer } = voteProposalMsg; const signingKey = await this.getSigningKey(signer); - await sdk.reveal_pk(signingKey, txMsg); - - const builtTx = await sdk.build_vote_proposal(voteProposalMsg, txMsg); + await sdk.tx.revealPk(signingKey, txMsg); - const txBytes = await sdk.sign_tx(builtTx, txMsg, signingKey); - const innerTxHash: string = await sdk.process_tx(txBytes, txMsg); + const builtTx = await sdk.tx.buildVoteProposal(txMsg, voteProposalMsg); + const signedTx = await sdk.tx.signTx(builtTx, signingKey); + await sdk.rpc.broadcastTx(signedTx); + const innerTxHash: string = await sdk.rpc.broadcastTx(signedTx); return innerTxHash; } catch (e) { @@ -811,23 +726,20 @@ export class KeyRing { } async submitIbcTransfer( - ibcTransferMsg: Uint8Array, - txMsg: Uint8Array + ibcTransferMsg: IbcTransferMsgValue, + txMsg: TxMsgValue ): Promise { await this.vaultService.assertIsUnlocked(); - const sdk = await this.sdkService.getSdk(); + const sdk = this.sdkService.getSdk(); try { - const { source } = deserialize( - Buffer.from(ibcTransferMsg), - IbcTransferMsgValue - ); + const { source } = ibcTransferMsg; const signingKey = await this.getSigningKey(source); - await sdk.reveal_pk(signingKey, txMsg); + await sdk.tx.revealPk(signingKey, txMsg); - const builtTx = await sdk.build_ibc_transfer(ibcTransferMsg, txMsg); - const txBytes = await sdk.sign_tx(builtTx, txMsg, signingKey); - const innerTxHash: string = await sdk.process_tx(txBytes, txMsg); + const builtTx = await sdk.tx.buildIbcTransfer(txMsg, ibcTransferMsg); + const signedTx = await sdk.tx.signTx(builtTx, signingKey); + const innerTxHash: string = await sdk.rpc.broadcastTx(signedTx); return innerTxHash; } catch (e) { @@ -836,26 +748,23 @@ export class KeyRing { } async submitEthBridgeTransfer( - ethBridgeTransferMsg: Uint8Array, - txMsg: Uint8Array + ethBridgeTransferMsg: EthBridgeTransferMsgValue, + txMsg: TxMsgValue ): Promise { await this.vaultService.assertIsUnlocked(); - const sdk = await this.sdkService.getSdk(); + const sdk = this.sdkService.getSdk(); try { - const { sender } = deserialize( - Buffer.from(ethBridgeTransferMsg), - EthBridgeTransferMsgValue - ); + const { sender } = ethBridgeTransferMsg; const signingKey = await this.getSigningKey(sender); - await sdk.reveal_pk(signingKey, txMsg); + await sdk.tx.revealPk(signingKey, txMsg); - const builtTx = await sdk.build_eth_bridge_transfer( - ethBridgeTransferMsg, - txMsg + const builtTx = await sdk.tx.buildEthBridgeTransfer( + txMsg, + ethBridgeTransferMsg ); - const txBytes = await sdk.sign_tx(builtTx, txMsg, signingKey); - const innerTxHash: string = await sdk.process_tx(txBytes, txMsg); + const signedTx = await sdk.tx.signTx(builtTx, signingKey); + const innerTxHash: string = await sdk.rpc.broadcastTx(signedTx); return innerTxHash; } catch (e) { @@ -911,10 +820,10 @@ export class KeyRing { owner: string, tokens: string[] ): Promise<{ token: string; amount: string }[]> { - const query = await this.sdkService.getQuery(); + const query = this.sdkService.getSdk().rpc; try { - return (await query.query_balance(owner, tokens)).map( + return (await query.queryBalance(owner, tokens)).map( ([token, amount]: [string, string]) => { return { token, @@ -929,8 +838,8 @@ export class KeyRing { } async queryPublicKey(address: string): Promise { - const query = await this.sdkService.getQuery(); - return await query.query_public_key(address); + const query = this.sdkService.getSdk().rpc; + return await query.queryPublicKey(address); } async signArbitrary( @@ -940,8 +849,8 @@ export class KeyRing { await this.vaultService.assertIsUnlocked(); const key = await this.getSigningKey(signer); - const sdk = await this.sdkService.getSdk(); - const [hash, signature] = sdk.sign_arbitrary(key, data); + const sdk = this.sdkService.getSdk(); + const [hash, signature] = sdk.signing.signArbitrary(key, data); return { hash, signature }; } diff --git a/apps/extension/src/background/keyring/service.ts b/apps/extension/src/background/keyring/service.ts index 9c37c1ce6..5b3a60e50 100644 --- a/apps/extension/src/background/keyring/service.ts +++ b/apps/extension/src/background/keyring/service.ts @@ -1,13 +1,22 @@ import { fromBase64, fromHex } from "@cosmjs/encoding"; import { PhraseSize } from "@namada/crypto"; -import { public_key_to_bech32, Sdk, TxType } from "@namada/shared"; +import { publicKeyToBech32, TxType } from "@namada/sdk/web"; import { IndexedDBKVStore, KVStore } from "@namada/storage"; import { AccountType, Bip44Path, + BondMsgValue, DerivedAccount, + EthBridgeTransferMsgValue, + IbcTransferMsgValue, + Message, SignatureResponse, + TransferMsgValue, + TxMsgValue, + UnbondMsgValue, + VoteProposalMsgValue, + WithdrawMsgValue, } from "@namada/types"; import { Result, truncateInMiddle } from "@namada/utils"; @@ -54,7 +63,6 @@ export class KeyRingService { protected readonly utilityStore: KVStore, protected readonly localStorage: LocalStorage, protected readonly vaultStorage: VaultStorage, - protected readonly cryptoMemory: WebAssembly.Memory, protected readonly requester: ExtensionRequester, protected readonly broadcaster: ExtensionBroadcaster ) { @@ -62,8 +70,7 @@ export class KeyRingService { vaultService, vaultStorage, sdkService, - utilityStore, - cryptoMemory + utilityStore ); } @@ -98,7 +105,7 @@ export class KeyRingService { bip44Path: Bip44Path ): Promise { const publicKeyBytes = fromHex(publicKey); - const bech32PublicKey = public_key_to_bech32(publicKeyBytes); + const bech32PublicKey = publicKeyToBech32(publicKeyBytes); const account = await this._keyRing.queryAccountByAddress(address); if (account) { @@ -177,9 +184,12 @@ export class KeyRingService { ): Promise { await this.broadcaster.startTx(msgId, TxType.Bond); try { + const txMsgValue = Message.decode(fromBase64(txMsg), TxMsgValue); + const bondMsgValue = Message.decode(fromBase64(bondMsg), BondMsgValue); + const innerTxHash = await this._keyRing.submitBond( - fromBase64(bondMsg), - fromBase64(txMsg) + bondMsgValue, + txMsgValue ); await this.broadcaster.completeTx(msgId, TxType.Bond, true, innerTxHash); await this.broadcaster.updateStaking(); @@ -198,9 +208,15 @@ export class KeyRingService { ): Promise { await this.broadcaster.startTx(msgId, TxType.Unbond); try { - const innerTxHash = await this._keyRing.submitUnbond( + const txMsgValue = Message.decode(fromBase64(txMsg), TxMsgValue); + const unbondMsgValue = Message.decode( fromBase64(unbondMsg), - fromBase64(txMsg) + UnbondMsgValue + ); + + const innerTxHash = await this._keyRing.submitUnbond( + unbondMsgValue, + txMsgValue ); await this.broadcaster.completeTx( msgId, @@ -224,9 +240,15 @@ export class KeyRingService { ): Promise { await this.broadcaster.startTx(msgId, TxType.Withdraw); try { - const innerTxHash = await this._keyRing.submitWithdraw( + const txMsgValue = Message.decode(fromBase64(txMsg), TxMsgValue); + const withdrawMsgValue = Message.decode( fromBase64(withdrawMsg), - fromBase64(txMsg) + WithdrawMsgValue + ); + + const innerTxHash = await this._keyRing.submitWithdraw( + withdrawMsgValue, + txMsgValue ); await this.broadcaster.completeTx( msgId, @@ -250,9 +272,14 @@ export class KeyRingService { ): Promise { await this.broadcaster.startTx(msgId, TxType.VoteProposal); try { - const innerTxHash = await this._keyRing.submitVoteProposal( + const txMsgValue = Message.decode(fromBase64(txMsg), TxMsgValue); + const voteProposalMsgValue = Message.decode( fromBase64(voteProposalMsg), - fromBase64(txMsg) + VoteProposalMsgValue + ); + const innerTxHash = await this._keyRing.submitVoteProposal( + voteProposalMsgValue, + txMsgValue ); await this.broadcaster.completeTx( msgId, @@ -281,7 +308,7 @@ export class KeyRingService { ): Promise { const offscreenDocumentPath = "offscreen.html"; const routerId = await getNamadaRouterId(this.localStorage); - const rpc = await this.sdkService.getRpc(); + const { url: rpc } = this.sdkService.getSdk(); const { currency: { address: nativeToken = tokenAddress }, } = await this.chainsService.getChain(); @@ -290,11 +317,24 @@ export class KeyRingService { await createOffscreenWithTxWorker(offscreenDocumentPath); } + const txMsgValue = Message.decode(fromBase64(txMsg), TxMsgValue); + const transferMsgValue = Message.decode( + fromBase64(transferMsg), + TransferMsgValue + ); + const result = await chrome.runtime.sendMessage({ type: SUBMIT_TRANSFER_MSG_TYPE, target: OFFSCREEN_TARGET, routerId, - data: { transferMsg, txMsg, msgId, signingKey, rpc, nativeToken }, + data: { + transferMsg: transferMsgValue, + txMsg: txMsgValue, + msgId, + signingKey, + rpc, + nativeToken, + }, }); if (result?.error) { @@ -310,15 +350,20 @@ export class KeyRingService { msgId: string, signingKey: SigningKey ): Promise { - const rpc = await this.sdkService.getRpc(); + const { url: rpc } = this.sdkService.getSdk(); const { currency: { address: nativeToken = tokenAddress }, } = await this.chainsService.getChain(); + const txMsgValue = Message.decode(fromBase64(txMsg), TxMsgValue); + const transferMsgValue = Message.decode( + fromBase64(transferMsg), + TransferMsgValue + ); initSubmitTransferWebWorker( { - transferMsg, - txMsg, + transferMsg: transferMsgValue, + txMsg: txMsgValue, msgId, signingKey, rpc, @@ -376,12 +421,18 @@ export class KeyRingService { txMsg: string, msgId: string ): Promise { + const txMsgValue = Message.decode(fromBase64(txMsg), TxMsgValue); + const ibcTransferMsgValue = Message.decode( + fromBase64(ibcTransferMsg), + IbcTransferMsgValue + ); + await this.broadcaster.startTx(msgId, TxType.IBCTransfer); try { const innerTxHash = await this._keyRing.submitIbcTransfer( - fromBase64(ibcTransferMsg), - fromBase64(txMsg) + ibcTransferMsgValue, + txMsgValue ); await this.broadcaster.completeTx( msgId, @@ -407,12 +458,17 @@ export class KeyRingService { txMsg: string, msgId: string ): Promise { + const txMsgValue = Message.decode(fromBase64(txMsg), TxMsgValue); + const ethBridgeTransferMsgValue = Message.decode( + fromBase64(ethBridgeTransferMsg), + EthBridgeTransferMsgValue + ); await this.broadcaster.startTx(msgId, TxType.EthBridgeTransfer); try { const innerTxHash = await this._keyRing.submitEthBridgeTransfer( - fromBase64(ethBridgeTransferMsg), - fromBase64(txMsg) + ethBridgeTransferMsgValue, + txMsgValue ); await this.broadcaster.completeTx( msgId, @@ -475,11 +531,11 @@ export class KeyRingService { } async fetchAndStoreMaspParams(): Promise { - await Sdk.fetch_and_store_masp_params(); + await this.sdkService.getSdk().masp.fetchAndStoreMaspParams(); } async hasMaspParams(): Promise { - return Sdk.has_masp_params(); + return await this.sdkService.getSdk().masp.hasMaspParams(); } async shieldedSync(): Promise { @@ -487,8 +543,7 @@ export class KeyRingService { .filter((a) => a.public.type === AccountType.ShieldedKeys) .map((a) => a.public.owner); - const query = await this.sdkService.getQuery(); - await query.shielded_sync(vks); + await this.sdkService.getSdk().rpc.shieldedSync(vks); } async queryBalances( @@ -523,8 +578,8 @@ export class KeyRingService { hash: string, signature: string ): Promise { - const sdk = await this.sdkService.getSdk(); + const sdk = this.sdkService.getSdk(); - return sdk.verify_arbitrary(publicKey, hash, signature); + return sdk.signing.verifyArbitrary(publicKey, hash, signature); } } diff --git a/apps/extension/src/background/ledger/ledger.ts b/apps/extension/src/background/ledger/ledger.ts index 57abd5473..545a749c8 100644 --- a/apps/extension/src/background/ledger/ledger.ts +++ b/apps/extension/src/background/ledger/ledger.ts @@ -3,6 +3,7 @@ import Transport from "@ledgerhq/hw-transport"; import TransportHID from "@ledgerhq/hw-transport-webhid"; import TransportUSB from "@ledgerhq/hw-transport-webusb"; import { chains } from "@namada/chains"; +import { makeBip44Path } from "@namada/sdk/web"; import { LedgerError, NamadaApp, @@ -11,8 +12,6 @@ import { ResponseVersion, } from "@zondax/ledger-namada"; -import { makeBip44Path } from "@namada/utils"; - const { coinType } = chains.namada.bip44; export const initLedgerUSBTransport = async (): Promise => { diff --git a/apps/extension/src/background/ledger/messages.ts b/apps/extension/src/background/ledger/messages.ts index aca448e3b..971d99e40 100644 --- a/apps/extension/src/background/ledger/messages.ts +++ b/apps/extension/src/background/ledger/messages.ts @@ -1,4 +1,4 @@ -import { TxType } from "@namada/shared"; +import { TxType } from "@namada/sdk/web"; import { ResponseSign } from "@zondax/ledger-namada"; import { Message } from "router"; import { ROUTE } from "./constants"; diff --git a/apps/extension/src/background/ledger/service.ts b/apps/extension/src/background/ledger/service.ts index c07e4bf3c..1018872ac 100644 --- a/apps/extension/src/background/ledger/service.ts +++ b/apps/extension/src/background/ledger/service.ts @@ -3,16 +3,14 @@ import { deserialize } from "@dao-xyz/borsh"; import { ResponseSign } from "@zondax/ledger-namada"; import { chains } from "@namada/chains"; -import { TxType } from "@namada/shared"; +import { TxType, makeBip44Path } from "@namada/sdk/web"; import { KVStore } from "@namada/storage"; import { AccountType, TxMsgValue } from "@namada/types"; -import { makeBip44Path } from "@namada/utils"; import { TxStore } from "background/approvals"; import { KeyRingService } from "background/keyring"; import { SdkService } from "background/sdk"; import { ExtensionBroadcaster, ExtensionRequester } from "extension"; import { RevealedPKStorage, VaultStorage } from "storage"; -import { encodeSignature } from "utils"; export const LEDGERSTORE_KEY = "ledger-store"; @@ -55,8 +53,8 @@ export class LedgerService { throw new Error(`Returned Account is not a Ledger`); } - const sdk = await this.sdkService.getSdk(); - const builtTx = await sdk.build_tx( + const sdk = this.sdkService.getSdk(); + const builtTx = await sdk.tx.buildTxFromSerializedArgs( TxType.RevealPK, new Uint8Array(), // TODO: this is a dummy value. Is there a cleaner way? fromBase64(txMsg), @@ -64,7 +62,7 @@ export class LedgerService { ); const path = makeBip44Path(coinType, account.path); - return { bytes: builtTx.tx_bytes(), path }; + return { bytes: builtTx.toBytes(), path }; } catch (e) { console.warn(e); throw new Error(`${e}`); @@ -76,19 +74,17 @@ export class LedgerService { bytes: string, signatures: ResponseSign ): Promise { - const { signature } = signatures; - - if (!signature) { - throw new Error("Signature not provided"); - } - try { - // Serialize signatures - const sig = encodeSignature(signature); - - const sdk = await this.sdkService.getSdk(); - const signedTxBytes = await sdk.append_signature(fromBase64(bytes), sig); - await sdk.process_tx(signedTxBytes, fromBase64(txMsg)); + const sdk = this.sdkService.getSdk(); + const signedTxBytes = sdk.tx.appendSignature( + fromBase64(bytes), + signatures + ); + const signedTx = { + txMsg: fromBase64(txMsg), + tx: signedTxBytes, + }; + await sdk.rpc.broadcastTx(signedTx); } catch (e) { console.warn(e); } @@ -108,23 +104,18 @@ export class LedgerService { const { txMsg } = storeResult; - const { signature } = signatures; - - if (!signature) { - throw new Error("Signature not provided!"); - } - - // Serialize signatures - const sig = encodeSignature(signature); - await this.broadcaster.startTx(msgId, txType); - const sdk = await this.sdkService.getSdk(); + const sdk = this.sdkService.getSdk(); try { - const signedTxBytes = await sdk.append_signature(fromBase64(bytes), sig); - const innerTxHash: string = await sdk.process_tx( - signedTxBytes, - fromBase64(txMsg) + const signedTxBytes = sdk.tx.appendSignature( + fromBase64(bytes), + signatures ); + const signedTx = { + txMsg: fromBase64(txMsg), + tx: signedTxBytes, + }; + const innerTxHash = await sdk.rpc.broadcastTx(signedTx); // Clear pending tx if successful await this.txStore.set(msgId, null); @@ -174,8 +165,8 @@ export class LedgerService { throw new Error(`Ledger account not found for ${address}`); } - const sdk = await this.sdkService.getSdk(); - const builtTx = await sdk.build_tx( + const sdk = this.sdkService.getSdk(); + const builtTx = await sdk.tx.buildTxFromSerializedArgs( txType, fromBase64(specificMsg), fromBase64(txMsg), @@ -183,7 +174,7 @@ export class LedgerService { ); const path = makeBip44Path(coinType, account.path); - return { bytes: builtTx.tx_bytes(), path }; + return { bytes: builtTx.toBytes(), path }; } catch (e) { console.warn(e); throw new Error(`${e}`); diff --git a/apps/extension/src/background/sdk/service.ts b/apps/extension/src/background/sdk/service.ts index c75533698..7b7e449ce 100644 --- a/apps/extension/src/background/sdk/service.ts +++ b/apps/extension/src/background/sdk/service.ts @@ -1,34 +1,56 @@ -import { Query, Sdk } from "@namada/shared"; -import { ChainsService } from "background/chains"; +import { chains } from "@namada/chains"; +import { Sdk, getNativeToken, getSdk } from "@namada/sdk/web"; +import sdkInit from "@namada/sdk/web-init"; +import { Chain } from "@namada/types"; +import { LocalStorage } from "storage"; const { NAMADA_INTERFACE_NAMADA_TOKEN: - tokenAddress = "tnam1qxgfw7myv4dh0qna4hq0xdg6lx77fzl7dcem8h7e", + defaultTokenAddress = "tnam1qxgfw7myv4dh0qna4hq0xdg6lx77fzl7dcem8h7e", } = process.env; export class SdkService { - constructor(protected readonly chainsService: ChainsService) { } + private constructor( + private rpc: string, + private readonly token: string, + private readonly cryptoMemory: WebAssembly.Memory + ) {} - public async getRpc(): Promise { - // Pull chain config from store, as the RPC value may have changed: - const chain = await this.chainsService.getChain(); + static async init(localStorage: LocalStorage): Promise { + // Get stored chain + const chain = await localStorage.getChain(); + // If chain is not stored, use default chain information + const rpc = chain?.rpc || chains.namada.rpc; - if (!chain) { - throw new Error("No chain found!"); + const { cryptoMemory } = await sdkInit(); + + let tokenAddress = chain?.currency.address; + + if (!tokenAddress) { + try { + tokenAddress = await getNativeToken(rpc); + } catch (error) { + console.warn( + "Unable to query native token. Falling back to the default.", + error + ); + tokenAddress = defaultTokenAddress; + } } - const { rpc } = chain; - return rpc; - } - async getSdk(): Promise { - const rpc = await this.getRpc(); - const chain = await this.chainsService.getChain(); + return new SdkService(rpc, defaultTokenAddress, cryptoMemory); + } - return new Sdk(rpc, chain.currency.address || tokenAddress); + /** + * Sync the chain information after a network update + * + * @param {Chain} chain - Chain information + */ + syncChain(chain: Chain): void { + this.rpc = chain.rpc; } - async getQuery(): Promise { - const rpc = await this.getRpc(); - return new Query(rpc); + getSdk(): Sdk { + return getSdk(this.cryptoMemory, this.rpc, "NOT USED DB NAME", this.token); } } diff --git a/apps/extension/src/background/vault/tests/service.test.ts b/apps/extension/src/background/vault/tests/service.test.ts index a5b085847..d96d37240 100644 --- a/apps/extension/src/background/vault/tests/service.test.ts +++ b/apps/extension/src/background/vault/tests/service.test.ts @@ -10,6 +10,13 @@ import { SessionPassword } from "../types"; const cryptoMemory = require("@namada/crypto").__wasm.memory; jest.mock("webextension-polyfill", () => ({})); +// Because we run tests in node environment, we need to mock web-init as node-init +jest.mock( + "@namada/sdk/web-init", + () => () => + Promise.resolve(jest.requireActual("@namada/sdk/node-init").default()) +); + type VaultPublicObj = { id: string; alias: string }; type VaultSensitiveValue = { bar: string }; diff --git a/apps/extension/src/background/web-workers/submit-transfer-web-worker.ts b/apps/extension/src/background/web-workers/submit-transfer-web-worker.ts index 7b9a357f8..bb3a4aba1 100644 --- a/apps/extension/src/background/web-workers/submit-transfer-web-worker.ts +++ b/apps/extension/src/background/web-workers/submit-transfer-web-worker.ts @@ -1,8 +1,5 @@ -import { fromBase64 } from "@cosmjs/encoding"; -import { deserialize, serialize } from "@dao-xyz/borsh"; -import { Sdk } from "@namada/shared"; -import { initMulticore as initShared } from "@namada/shared/src/init"; -import { TxMsgValue } from "@namada/types"; +import { getSdk } from "@namada/sdk/web"; +import { initMulticore } from "@namada/sdk/web-init"; import { INIT_MSG, SubmitTransferMessageData, @@ -12,11 +9,7 @@ import { } from "./types"; (async function init() { - const sharedWasm = await fetch("shared.namada.wasm").then((wasm) => - wasm.arrayBuffer() - ); - await initShared(sharedWasm); - + const { cryptoMemory } = await initMulticore(); addEventListener( "message", async ({ data }: { data: SubmitTransferMessageData }) => { @@ -26,28 +19,23 @@ import { rpc, nativeToken, } = data; - let txMsg = fromBase64(data.txMsg); + const { txMsg, transferMsg } = data; - const sdk = new Sdk(rpc, nativeToken); - await sdk.load_masp_params(); + const sdk = getSdk(cryptoMemory, rpc, "NOT USED DB NAME", nativeToken); + await sdk.masp.loadMaspParams("TODO: not used for time being"); // For transparent transactions we have to reveal the public key. if (privateKey) { - await sdk.reveal_pk(privateKey, txMsg); + await sdk.tx.revealPk(privateKey, txMsg); // For transfers from masp source we unshield to pay the fee. // Because of that we have to pass spending key. } else if (xsk) { - const deserializedTxMsg = deserialize(Buffer.from(txMsg), TxMsgValue); - deserializedTxMsg.feeUnshield = xsk; - txMsg = serialize(deserializedTxMsg); + txMsg.feeUnshield = xsk; + transferMsg.source = xsk; } - const builtTx = await sdk.build_transfer( - fromBase64(data.transferMsg), - txMsg, - xsk - ); - const txBytes = await sdk.sign_tx(builtTx, txMsg, privateKey); - const innerTxHash: string = await sdk.process_tx(txBytes, txMsg); + const builtTx = await sdk.tx.buildTransfer(txMsg, data.transferMsg); + const signedTx = await sdk.tx.signTx(builtTx, privateKey); + const innerTxHash = await sdk.rpc.broadcastTx(signedTx); postMessage({ msgName: TRANSFER_SUCCESSFUL_MSG, diff --git a/apps/extension/src/background/web-workers/types.ts b/apps/extension/src/background/web-workers/types.ts index 88942169a..04cd0357a 100644 --- a/apps/extension/src/background/web-workers/types.ts +++ b/apps/extension/src/background/web-workers/types.ts @@ -1,3 +1,4 @@ +import { TransferMsgValue, TxMsgValue } from "@namada/types"; import { SigningKey } from "background/keyring"; export type SubmitTransferMessage = { @@ -8,8 +9,8 @@ export type SubmitTransferMessage = { }; export type SubmitTransferMessageData = { - transferMsg: string; - txMsg: string; + transferMsg: TransferMsgValue; + txMsg: TxMsgValue; msgId: string; signingKey: SigningKey; rpc: string; diff --git a/apps/extension/src/content/events.ts b/apps/extension/src/content/events.ts index 551133ea7..4d6e577a3 100644 --- a/apps/extension/src/content/events.ts +++ b/apps/extension/src/content/events.ts @@ -1,4 +1,4 @@ -import { TxType } from "@namada/shared"; +import { TxType } from "@namada/sdk/web"; import { Events } from "@namada/types"; import { LocalStorage } from "storage"; import { Message, Router, Routes } from "../router"; @@ -234,9 +234,9 @@ export function initEvents(router: Router, localStorage: LocalStorage): void { router.addHandler(Routes.InteractionForeground, async (_, msg) => { const clonedMsg = - typeof cloneInto !== "undefined" - ? cloneInto(msg, document.defaultView) - : msg; + typeof cloneInto !== "undefined" ? + cloneInto(msg, document.defaultView) + : msg; if (msg.constructor !== ConnectionRevokedEventMsg) { const approvedOrigins = (await localStorage.getApprovedOrigins()) || []; diff --git a/apps/extension/src/extension/ExtensionBroadcaster.ts b/apps/extension/src/extension/ExtensionBroadcaster.ts index edc41fdb6..b5be75c47 100644 --- a/apps/extension/src/extension/ExtensionBroadcaster.ts +++ b/apps/extension/src/extension/ExtensionBroadcaster.ts @@ -1,4 +1,4 @@ -import { TxType } from "@namada/shared"; +import { TxType } from "@namada/sdk/web"; import { AccountChangedEventMsg, ConnectionRevokedEventMsg, diff --git a/apps/extension/src/provider/Namada.test.ts b/apps/extension/src/provider/Namada.test.ts index da064a573..660977796 100644 --- a/apps/extension/src/provider/Namada.test.ts +++ b/apps/extension/src/provider/Namada.test.ts @@ -12,6 +12,13 @@ import { ACTIVE_ACCOUNT, keyStore, password } from "./data.mock"; // Needed for now as utils import webextension-polyfill directly jest.mock("webextension-polyfill", () => ({})); +// Because we run tests in node environment, we need to mock web-init as node-init +jest.mock( + "@namada/sdk/web-init", + () => () => + Promise.resolve(jest.requireActual("@namada/sdk/node-init").default()) +); + describe("Namada", () => { let namada: Namada; let vaultStorage: VaultStorage; diff --git a/apps/extension/src/provider/Signer.ts b/apps/extension/src/provider/Signer.ts index 71f439321..3a846abed 100644 --- a/apps/extension/src/provider/Signer.ts +++ b/apps/extension/src/provider/Signer.ts @@ -1,6 +1,6 @@ import { toBase64 } from "@cosmjs/encoding"; import { chains } from "@namada/chains"; -import { SupportedTx, TxType } from "@namada/shared"; +import { SupportedTx, TxType } from "@namada/sdk/web"; import { Account, AccountType, diff --git a/apps/extension/src/provider/messages.ts b/apps/extension/src/provider/messages.ts index f43f15d52..6476c7752 100644 --- a/apps/extension/src/provider/messages.ts +++ b/apps/extension/src/provider/messages.ts @@ -1,4 +1,4 @@ -import { SupportedTx } from "@namada/shared"; +import type { SupportedTx } from "@namada/sdk/web"; import { AccountType, Chain, diff --git a/apps/extension/src/storage/VaultStorage.test.ts b/apps/extension/src/storage/VaultStorage.test.ts index 3059dabdd..379d01331 100644 --- a/apps/extension/src/storage/VaultStorage.test.ts +++ b/apps/extension/src/storage/VaultStorage.test.ts @@ -5,6 +5,13 @@ import { KeyStore, VaultStorage } from "./VaultStorage"; jest.mock("webextension-polyfill", () => ({})); +// Because we run tests in node environment, we need to mock web-init as node-init +jest.mock( + "@namada/sdk/web-init", + () => () => + Promise.resolve(jest.requireActual("@namada/sdk/node-init").default()) +); + describe("VaultStorage", () => { let vaultStorage: VaultStorage; diff --git a/apps/extension/src/test/init.ts b/apps/extension/src/test/init.ts index f1c9f44a3..662e52998 100644 --- a/apps/extension/src/test/init.ts +++ b/apps/extension/src/test/init.ts @@ -95,8 +95,12 @@ export const init = async (): Promise<{ cryptoMemory ); await vaultService.initialize(); - const chainsService = new ChainsService(localStorage, broadcaster); - const sdkService = new SdkService(chainsService); + const sdkService = await SdkService.init(localStorage); + const chainsService = new ChainsService( + sdkService, + localStorage, + broadcaster + ); const keyRingService = new KeyRingService( vaultService, @@ -105,7 +109,6 @@ export const init = async (): Promise<{ utilityStore, localStorage, vaultStorage, - cryptoMemory, requester, broadcaster ); diff --git a/apps/extension/tsconfig.json b/apps/extension/tsconfig.json index df5420be5..c4969b402 100644 --- a/apps/extension/tsconfig.json +++ b/apps/extension/tsconfig.json @@ -22,5 +22,5 @@ }, "include": ["src/**/*.ts", "src/**/*.tsx"], "exclude": ["node_modules"], - "typeRoots": ["./node_modules/@types"] + "typeRoots": ["./node_modules/@types"], } diff --git a/apps/faucet/package.json b/apps/faucet/package.json index ac40aef38..c57e54ed9 100644 --- a/apps/faucet/package.json +++ b/apps/faucet/package.json @@ -17,10 +17,6 @@ }, "dependencies": { "@cosmjs/encoding": "^0.29.0", - "@namada/components": "0.2.1", - "@namada/hooks": "0.2.1", - "@namada/integrations": "0.2.1", - "@namada/utils": "0.2.1", "buffer": "^6.0.3", "dompurify": "^3.0.2", "node-forge": "^1.3.1", @@ -32,7 +28,6 @@ }, "devDependencies": { "@babel/plugin-transform-modules-commonjs": "^7.20.11", - "@namada/config": "workspace:^", "@svgr/webpack": "^6.3.1", "@types/dompurify": "^3.0.2", "@types/node-forge": "^1.3.6", diff --git a/apps/namada-interface/.release-it.cjs b/apps/namada-interface/.release-it.cjs index 5fa1e24da..9261789f6 100644 --- a/apps/namada-interface/.release-it.cjs +++ b/apps/namada-interface/.release-it.cjs @@ -2,9 +2,6 @@ const baseConfig = require("../../.release-it.base.cjs"); const config = { ...baseConfig, - hooks: { - "after:bump": ["yarn bump -p components -p hooks -p integrations -p utils"], - }, }; module.exports = config; diff --git a/apps/namada-interface/package.json b/apps/namada-interface/package.json index 144b5ec1a..c2dd1ab7f 100644 --- a/apps/namada-interface/package.json +++ b/apps/namada-interface/package.json @@ -7,10 +7,6 @@ "license": "MIT", "private": true, "dependencies": { - "@namada/components": "0.2.1", - "@namada/hooks": "0.2.1", - "@namada/integrations": "0.2.1", - "@namada/utils": "0.2.1", "@reduxjs/toolkit": "^1.8.0", "@types/react-paginate": "^7.1.2", "bignumber.js": "^9.1.1", @@ -55,9 +51,9 @@ "lint": "eslint src --ext .ts,.tsx", "lint:fix": "yarn lint -- --fix", "lint:ci": "yarn lint --max-warnings 0", - "test": "yarn wasm:build:node && yarn jest", - "test:watch": "yarn wasm:build:node && yarn jest --watchAll=true", - "test:coverage": "yarn wasm:build:node && yarn test --coverage", + "test": "yarn wasm:build:test && yarn jest", + "test:watch": "yarn wasm:build:test && yarn jest --watchAll=true", + "test:coverage": "yarn wasm:build:test && yarn test --coverage", "test:ci": "jest", "e2e-test": "PLAYWRIGHT_BASE_URL=http://localhost:3000 yarn playwright test", "e2e-test:headed": "PLAYWRIGHT_BASE_URL=http://localhost:3000 yarn playwright test --project=chromium --headed", @@ -66,7 +62,7 @@ "wasm:build:multicore": "node ./scripts/build.js --release --multicore", "wasm:build:dev": "node ./scripts/build.js", "wasm:build:dev:multicore": "node ./scripts/build.js --multicore", - "wasm:build:node": "./scripts/build-node.sh" + "wasm:build:test": "./scripts/build-test.sh" }, "browserslist": { "production": [ @@ -81,7 +77,6 @@ ] }, "devDependencies": { - "@namada/config": "workspace:^", "@playwright/test": "^1.24.1", "@svgr/webpack": "^6.5.1", "@testing-library/jest-dom": "^5.16.2", diff --git a/apps/namada-interface/scripts/build-node.sh b/apps/namada-interface/scripts/build-test.sh similarity index 93% rename from apps/namada-interface/scripts/build-node.sh rename to apps/namada-interface/scripts/build-test.sh index 4a05807f0..4c5ab9a04 100755 --- a/apps/namada-interface/scripts/build-node.sh +++ b/apps/namada-interface/scripts/build-test.sh @@ -3,5 +3,5 @@ SCRIPT_DIR=$(cd "$(dirname "$0")"; pwd -P) PACKAGES_PATH="../../../packages" -cd "${SCRIPT_DIR}/${PACKAGES_PATH}/crypto" && yarn wasm:build:node -cd "${SCRIPT_DIR}/${PACKAGES_PATH}/shared" && yarn wasm:build:node +cd "${SCRIPT_DIR}/${PACKAGES_PATH}/crypto" && yarn wasm:build:node:dev +cd "${SCRIPT_DIR}/${PACKAGES_PATH}/shared" && yarn wasm:build:node:dev diff --git a/e2e/package.json b/e2e/package.json index 28b72adc4..1e78c67b1 100644 --- a/e2e/package.json +++ b/e2e/package.json @@ -1,5 +1,5 @@ { - "name": "@anoma/e2e", + "name": "@namada/e2e", "version": "0.1.0", "description": "e2e tests for apps", "main": "src/index.ts", diff --git a/packages/chains/.release-it.cjs b/packages/chains/.release-it.cjs index 3cb963502..9261789f6 100644 --- a/packages/chains/.release-it.cjs +++ b/packages/chains/.release-it.cjs @@ -2,9 +2,6 @@ const baseConfig = require("../../.release-it.base.cjs"); const config = { ...baseConfig, - hooks: { - "after:bump": ["yarn bump -p types"], - }, }; module.exports = config; diff --git a/packages/chains/package.json b/packages/chains/package.json index f3ca56a56..2e0fbd874 100644 --- a/packages/chains/package.json +++ b/packages/chains/package.json @@ -9,17 +9,16 @@ "license": "MIT", "scripts": { "bump": "yarn workspace namada run bump --target packages/chains", - "prepublish": "npx rimraf ./dist && tsc --build", + "prepublish": "yarn && yarn build", + "build": "npx rimraf ./dist && tsc --build", "release": "yarn prepublish && release-it --verbose --ci", "release:dry-run": "yarn prepublish && release-it --verbose --dry-run --ci", "release:no-npm": "yarn prepublish && release-it --verbose --no-npm.publish --ci" }, "dependencies": { - "@namada/types": "0.2.1", "typescript": "^5.1.3" }, "devDependencies": { - "@namada/config": "workspace:^", "eslint": "^8.49.0", "eslint-config-prettier": "^8.8.0", "eslint-import-resolver-typescript": "^3.5.2", diff --git a/packages/components/.release-it.cjs b/packages/components/.release-it.cjs index 771227e96..9261789f6 100644 --- a/packages/components/.release-it.cjs +++ b/packages/components/.release-it.cjs @@ -2,9 +2,6 @@ const baseConfig = require("../../.release-it.base.cjs"); const config = { ...baseConfig, - hooks: { - "after:bump": ["yarn bump -p utils"], - }, }; module.exports = config; diff --git a/packages/components/package.json b/packages/components/package.json index 3ac0d83b5..3b43e926a 100644 --- a/packages/components/package.json +++ b/packages/components/package.json @@ -9,7 +9,8 @@ "license": "MIT", "scripts": { "bump": "yarn workspace namada run bump --target packages/components", - "prepublish": "npx rimraf ./dist && tsc --build", + "prepublish": "yarn && yarn build", + "build": "npx rimraf ./dist && tsc --build", "release": "yarn prepublish && release-it --verbose --ci", "release:dry-run": "yarn prepublish && release-it --verbose --dry-run --ci", "release:no-npm": "yarn prepublish && release-it --verbose --no-npm.publish --ci", @@ -18,7 +19,6 @@ "lint:ci": "yarn lint --max-warnings 0" }, "dependencies": { - "@namada/utils": "0.2.1", "clsx": "^2.0.0", "react": "^17.0.2", "react-icons": "^4.12.0", @@ -28,7 +28,6 @@ "typescript": "^5.1.3" }, "devDependencies": { - "@namada/config": "workspace:^", "@types/react": "^17.0.39", "@types/styled-components": "^5.1.26", "autoprefixer": "^10.4.16", diff --git a/packages/crypto/.eslintrc.js b/packages/crypto/.eslintrc.js new file mode 100644 index 000000000..8c1ab8812 --- /dev/null +++ b/packages/crypto/.eslintrc.js @@ -0,0 +1,3 @@ +module.exports = { + extends: require.resolve("@namada/config/eslint/index.js"), +}; diff --git a/packages/crypto/package.json b/packages/crypto/package.json index 19b6ae459..b9136acb6 100644 --- a/packages/crypto/package.json +++ b/packages/crypto/package.json @@ -8,17 +8,19 @@ "author": "Heliax Dev ", "license": "MIT", "scripts": { - "prepublish": "yarn wasm:build && tsc --build", + "prepublish": "yarn && yarn build", + "build": "yarn wasm:build && tsc --build", "release": "yarn prepublish && release-it --verbose --ci", "release:dry-run": "yarn prepublish && release-it --verbose --dry-run --ci", "release:no-npm": "yarn prepublish && release-it --verbose --no-npm.publish --ci", "wasm:build": "./scripts/build.sh --release", "wasm:build:dev": "./scripts/build.sh", - "wasm:build:node": "./scripts/build-test.sh", + "wasm:build:node": "./scripts/build-node.sh --release", + "wasm:build:node:dev": "./scripts/build-node.sh", "test": "yarn wasm:build:node && yarn jest", "test:watch": "yarn wasm:build:node && yarn test --watch", "test:ci": "jest", - "test-wasm:ci": "cd ./lib && wasm-pack test --node" + "test-wasm:ci": "cd ./lib && wasm-pack test --node -- --profile dev" }, "dependencies": { "typescript": "^5.1.3" diff --git a/packages/crypto/scripts/build-node.sh b/packages/crypto/scripts/build-node.sh new file mode 100755 index 000000000..adbfa5194 --- /dev/null +++ b/packages/crypto/scripts/build-node.sh @@ -0,0 +1,25 @@ +#!/bin/sh + +SCRIPT_DIR=$(cd "$(dirname "$0")"; pwd -P) + +path="" +profile="" + +if [ "$1" = "" ] +then + echo "Building \"crypto\" for nodejs in dev mode." + profile="--dev" + path="debug" +elif [ "$1" = "--release" ] +then + echo "Building \"crypto\" for nodejs in release mode." + profile="--release" + path="release" +else + echo "Unsupported build mode \"$1\"" + exit 1 +fi + +rm -rf dist && mkdir dist && mkdir dist/crypto + +wasm-pack build $SCRIPT_DIR/../lib $profile --target nodejs --out-dir $SCRIPT_DIR/../src/crypto diff --git a/packages/crypto/scripts/build-test.sh b/packages/crypto/scripts/build-test.sh deleted file mode 100755 index 313f84f3d..000000000 --- a/packages/crypto/scripts/build-test.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/sh - -SCRIPT_DIR=$(cd "$(dirname "$0")"; pwd -P) - -wasm-pack build $SCRIPT_DIR/../lib --dev --target nodejs --out-dir $SCRIPT_DIR/../src/crypto diff --git a/packages/crypto/scripts/build.sh b/packages/crypto/scripts/build.sh index 7c3b8dae9..35a64b8bc 100755 --- a/packages/crypto/scripts/build.sh +++ b/packages/crypto/scripts/build.sh @@ -7,12 +7,12 @@ profile="" if [ "$1" = "" ] then - echo "Building \"crypto\" in dev mode." + echo "Building \"crypto\" for web in dev mode." profile="--dev" path="debug" elif [ "$1" = "--release" ] then - echo "Building \"crypto\" in release mode." + echo "Building \"crypto\" for web in release mode." profile="--release" path="release" else diff --git a/packages/crypto/src/utils.ts b/packages/crypto/src/utils.ts index 9d4fd6447..26bec5a25 100644 --- a/packages/crypto/src/utils.ts +++ b/packages/crypto/src/utils.ts @@ -1,4 +1,4 @@ -import { VecU8Pointer, VecStringPointer, StringPointer } from "."; +import { StringPointer, VecStringPointer, VecU8Pointer } from "."; const decoder = new TextDecoder("utf-8", { ignoreBOM: true, fatal: true }); @@ -25,4 +25,4 @@ const readVecStringPointer = ( ); }; -export { readVecU8Pointer, readStringPointer, readVecStringPointer }; +export { readStringPointer, readVecStringPointer, readVecU8Pointer }; diff --git a/packages/hooks/.release-it.cjs b/packages/hooks/.release-it.cjs index af1295385..9261789f6 100644 --- a/packages/hooks/.release-it.cjs +++ b/packages/hooks/.release-it.cjs @@ -2,9 +2,6 @@ const baseConfig = require("../../.release-it.base.cjs"); const config = { ...baseConfig, - hooks: { - "after:bump": ["yarn bump -p chains -p types -p utils"], - }, }; module.exports = config; diff --git a/packages/hooks/package.json b/packages/hooks/package.json index 236edae90..c949fd4b2 100644 --- a/packages/hooks/package.json +++ b/packages/hooks/package.json @@ -9,7 +9,8 @@ "license": "MIT", "scripts": { "bump": "yarn workspace namada run bump --target packages/hooks", - "prepublish": "rimraf ./dist && tsc --build", + "prepublish": "yarn && yarn build", + "build": "rimraf ./dist && tsc --build", "release": "yarn prepublish && release-it --verbose --ci", "release:dry-run": "yarn prepublish && release-it --verbose --dry-run --ci", "release:no-npm": "yarn prepublish && release-it --verbose --no-npm.publish", @@ -18,14 +19,10 @@ "lint:ci": "yarn lint --max-warnings 0" }, "dependencies": { - "@namada/chains": "0.2.1", - "@namada/types": "0.2.1", - "@namada/utils": "0.2.1", "react": "^17.0.2", "typescript": "^5.1.3" }, "devDependencies": { - "@namada/config": "workspace:^", "@types/react": "^17.0.39", "eslint": "^8.49.0", "eslint-config-prettier": "^8.8.0", diff --git a/packages/integrations/.release-it.cjs b/packages/integrations/.release-it.cjs index eed19862d..9261789f6 100644 --- a/packages/integrations/.release-it.cjs +++ b/packages/integrations/.release-it.cjs @@ -2,9 +2,6 @@ const baseConfig = require("../../.release-it.base.cjs"); const config = { ...baseConfig, - hooks: { - "after:bump": ["yarn bump -p types -p utils"], - }, }; module.exports = config; diff --git a/packages/integrations/package.json b/packages/integrations/package.json index 8a45cd565..647e4df60 100644 --- a/packages/integrations/package.json +++ b/packages/integrations/package.json @@ -10,19 +10,19 @@ "private": true, "scripts": { "bump": "yarn workspace namada run bump --target packages/integrations", - "prepublish": "npx rimraf ./dist && tsc --build", + "prepublish": "yarn && yarn build", + "build": "npx rimraf ./dist && tsc --build", "release": "yarn prepublish && release-it --verbose --ci", "release:dry-run": "yarn prepublish && release-it --verbose --dry-run --ci", "release:no-npm": "yarn prepublish && release-it --verbose --no-npm.publish --ci", - "test": "yarn wasm:build && jest", - "test:watch": "yarn wasm:build && jest --watchAll", + "test": "jest", + "test:watch": "jest --watchAll", "test:ci": "jest", "lint": "eslint src --ext .ts", "lint:fix": "yarn lint -- --fix", "lint:ci": "yarn lint --max-warnings 0" }, "devDependencies": { - "@namada/config": "workspace:^", "@types/jest": "^28.1.8", "@types/node": "^18.7.13", "eslint": "^8.49.0", @@ -44,8 +44,6 @@ "@cosmjs/tendermint-rpc": "~0.29.5", "@keplr-wallet/types": "^0.10.19", "@metamask/providers": "^10.2.1", - "@namada/types": "0.2.1", - "@namada/utils": "0.2.1", "typescript": "^5.1.3" }, "files": [ diff --git a/packages/integrations/src/Namada.ts b/packages/integrations/src/Namada.ts index a1c10b166..ea1ba1563 100644 --- a/packages/integrations/src/Namada.ts +++ b/packages/integrations/src/Namada.ts @@ -90,7 +90,10 @@ export default class Namada implements Integration { // TODO: fix this return { - NAM: mapUndefined((amount) => new BigNumber(amount), balances[0].amount), + NAM: mapUndefined( + (amount) => new BigNumber(amount), + balances[0]?.amount || "0" + ), }; } diff --git a/packages/sdk/.eslintrc.js b/packages/sdk/.eslintrc.js index f38fea8f0..f857459c3 100644 --- a/packages/sdk/.eslintrc.js +++ b/packages/sdk/.eslintrc.js @@ -2,8 +2,22 @@ module.exports = { plugins: ["jsdoc"], extends: [ require.resolve("@namada/config/eslint/react.js"), - "plugin:jsdoc/recommended", + "plugin:jsdoc/recommended-typescript", ], + rules: { + "jsdoc/require-jsdoc": [ + "warn", + { + contexts: [ + "ClassDeclaration", + "ClassProperty", + "FunctionDeclaration", + "MethodDefinition", + ], + }, + ], + "jsdoc/require-returns-description": 0, + }, parserOptions: { ecmaVersion: 12, sourceType: "module", @@ -13,7 +27,7 @@ module.exports = { { files: ["*.ts", "*.tsx"], rules: { - "@typescript-eslint/no-floating-promises": ["warn"], + "@typescript-eslint/no-floating-promises": "warn", }, }, ], diff --git a/packages/sdk/.release-it.cjs b/packages/sdk/.release-it.cjs index eed19862d..f2bfb6cba 100644 --- a/packages/sdk/.release-it.cjs +++ b/packages/sdk/.release-it.cjs @@ -1,10 +1,5 @@ const baseConfig = require("../../.release-it.base.cjs"); -const config = { - ...baseConfig, - hooks: { - "after:bump": ["yarn bump -p types -p utils"], - }, -}; +const config = baseConfig; module.exports = config; diff --git a/packages/sdk/README.md b/packages/sdk/README.md index 7bda465e8..645688c65 100644 --- a/packages/sdk/README.md +++ b/packages/sdk/README.md @@ -5,48 +5,21 @@ Namada SDK package ## Development ```bash -# Build wasm for web for single core, release mode -yarn wasm:build +# Build wasm for single core, release mode +yarn wasm:build[:node] -# Build wasm for web for multicore, release mode -yarn wasm:build:multicore +# Build wasm for multicore, release mode +yarn wasm:build[:node]:multicore # Build wasm with debugging for single core -yarn wasm:build:dev +yarn wasm:build[:node]:dev # Build wasm with debugging for multicore -yarn wasm:build:dev:multicore - -# Build wasm for NodeJS -yarn wasm:build:node +yarn wasm:build[:node]:dev:multicore ``` ## Usage -```typescript -import { Sdk } from "@namada/sdk" - -// Initialize the Sdk in an async function -async function init(): Promise { - // Point to the RPC url of the ledger - const ledgerUrl = "http://localhost:27657"; - - const { tx, rpc } = await Sdk.init(ledgerUrl); - - // Build a transfer (see TxProps and TransferProps) - const transfer = tx.buildTransfer(txProps, transferProps, ""); - - // Note: If signing with a Ledger hardware wallet, you may access the transfer bytes with: - const bytes = transfer.toBytes(); // For Ledger hardware wallet signing - - // Sign this transaction using a secret key - const signedTx = tx.signTx(transfer, "); - - // Broadcast the signed transfer to the ledger - await rpc.broadcastTx(signedTx).catch((e) => console.error(`Unable to broadcast Tx: ${e}`)); -} - -init(); -``` +See [examples](../examples) For more information, read the [Specs](./docs/specs.md) or the [API](./docs/api.md) documentation. diff --git a/packages/sdk/docs/.nojekyll b/packages/sdk/docs/.nojekyll new file mode 100644 index 000000000..e2ac6616a --- /dev/null +++ b/packages/sdk/docs/.nojekyll @@ -0,0 +1 @@ +TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/packages/sdk/docs/README.md b/packages/sdk/docs/README.md new file mode 100644 index 000000000..01c7ea726 --- /dev/null +++ b/packages/sdk/docs/README.md @@ -0,0 +1,51 @@ +@namada/sdk / [Exports](modules.md) + +# sdk + +Namada SDK package + +## Development + +```bash +# Build wasm for single core, release mode +yarn wasm:build[:node] + +# Build wasm for multicore, release mode +yarn wasm:build[:node]:multicore + +# Build wasm with debugging for single core +yarn wasm:build[:node]:dev + +# Build wasm with debugging for multicore +yarn wasm:build[:node]:dev:multicore +``` + +## Usage + +```typescript +import { Sdk } from "@namada/sdk" + +// Initialize the Sdk in an async function +async function init(): Promise { + // Point to the RPC url of the ledger + const ledgerUrl = "http://localhost:27657"; + + const { tx, rpc } = await Sdk.init(ledgerUrl); + + // Build a transfer (see TxProps and TransferProps) + const transfer = tx.buildTransfer(txProps, transferProps, ""); + + // Note: If signing with a Ledger hardware wallet, you may access the transfer bytes with: + const bytes = transfer.toBytes(); // For Ledger hardware wallet signing + + // Sign this transaction using a secret key + const signedTx = tx.signTx(transfer, "); + + // Broadcast the signed transfer to the ledger + await rpc.broadcastTx(signedTx).catch((e) => console.error(`Unable to broadcast Tx: ${e}`)); +} + +init(); +``` + +For more information, read the [Specs](./docs/specs.md) or the [API](./docs/api.md) documentation. diff --git a/packages/sdk/docs/api.md b/packages/sdk/docs/api.md deleted file mode 100644 index 9b583aa63..000000000 --- a/packages/sdk/docs/api.md +++ /dev/null @@ -1,1053 +0,0 @@ -## Classes - -
-
Keys
-
-
Ledger
-

Functionality for interacting with NamadaApp for Ledger Hardware Wallets

-
Masp
-

Class representing utilities related to MASP

-
Mnemonic
-

Class for accessing mnemonic functionality from wasm

-
Rpc
-

API for executing RPC requests with Namada

-
Sdk
-

API for interacting with Namada SDK

-
Signing
-

Non-Tx signing functions

-
Tx
-

SDK functionality related to transactions

-
EncodedTx
-

Wrap results of tx building along with TxMsg

-
SignedTx
-
-
- -## Members - -
-
initLedgerUSBTransport ⇒ Transport
-

Initialize HID transport

-
EncodedTx
-

Wrap results of tx signing to simplify passing between Sdk functions

-
- -## Functions - -
-
initAsync(url, [token]) ⇒ Sdk
-

Returns an initialized Sdk class asynchronously. This is required to use -this library in web applications.

-
initSync(url, nativeToken) ⇒ Sdk
-

Initialize SDK for Node JS environments

-
initLedgerUSBTransport() ⇒ Transport
-

Initialize USB transport

-
- - - -## Keys -**Kind**: global class - -* [Keys](#Keys) - * [new Keys(cryptoMemory)](#new_Keys_new) - * [.getAddress(privateKey)](#Keys+getAddress) ⇒ - * [.fromPrivateKey(privateKey)](#Keys+fromPrivateKey) ⇒ - * [.deriveFromMnemonic(phrase, [path], [passphrase])](#Keys+deriveFromMnemonic) ⇒ - * [.deriveFromSeed(seed, [path])](#Keys+deriveFromSeed) ⇒ - * [.deriveShielded(seed, [path])](#Keys+deriveShielded) ⇒ - - - -### new Keys(cryptoMemory) - -| Param | Description | -| --- | --- | -| cryptoMemory |

Memory accessor for crypto lib

| - - - -### keys.getAddress(privateKey) ⇒ -

Get address and public key from private key

- -**Kind**: instance method of [Keys](#Keys) -**Returns**:

Address and public key

- -| Param | Description | -| --- | --- | -| privateKey |

Private key

| - - - -### keys.fromPrivateKey(privateKey) ⇒ -

Get transparent keys and address from private key

- -**Kind**: instance method of [Keys](#Keys) -**Returns**:

Keys and address

- -| Param | Description | -| --- | --- | -| privateKey |

Private key

| - - - -### keys.deriveFromMnemonic(phrase, [path], [passphrase]) ⇒ -

Derive transparent keys and address from a mnemonic and path

- -**Kind**: instance method of [Keys](#Keys) -**Returns**:

Keys and address

- -| Param | Description | -| --- | --- | -| phrase |

Mnemonic phrase

| -| [path] |

Bip44 path object

| -| [passphrase] |

Bip39 passphrase

| - - - -### keys.deriveFromSeed(seed, [path]) ⇒ -

Derive transparent keys and address from a seed and path

- -**Kind**: instance method of [Keys](#Keys) -**Returns**:

Keys and address

- -| Param | Description | -| --- | --- | -| seed |

Seed

| -| [path] |

Bip44 path object

| - - - -### keys.deriveShielded(seed, [path]) ⇒ -

Derive shielded keys and address from a seed and path

- -**Kind**: instance method of [Keys](#Keys) -**Returns**:

Shielded keys and address

- -| Param | Description | -| --- | --- | -| seed |

Seed

| -| [path] |

Bip44 path object

| - - - -## Ledger -

Functionality for interacting with NamadaApp for Ledger Hardware Wallets

- -**Kind**: global class - -* [Ledger](#Ledger) - * [new Ledger(namadaApp)](#new_Ledger_new) - * _instance_ - * [.status()](#Ledger+status) ⇒ LedgerStatus - * [.getAddressAndPublicKey([path])](#Ledger+getAddressAndPublicKey) ⇒ AddressAndPublicKey - * [.showAddressAndPublicKey([path])](#Ledger+showAddressAndPublicKey) ⇒ AddressAndPublicKey - * [.sign(tx, [path])](#Ledger+sign) ⇒ ResponseSign - * [.queryErrors()](#Ledger+queryErrors) ⇒ string - * [.closeTransport()](#Ledger+closeTransport) ⇒ void - * _static_ - * [.init([transport])](#Ledger.init) ⇒ [Ledger](#Ledger) - - - -### new Ledger(namadaApp) - -| Param | Type | Description | -| --- | --- | --- | -| namadaApp | NamadaApp |

Inititalized NamadaApp class from Zondax package

| - - - -### ledger.status() ⇒ LedgerStatus -

Return status and version info of initialized NamadaApp. -Throw exception if app is not initialized.

- -**Kind**: instance method of [Ledger](#Ledger) -**Returns**: LedgerStatus -

Version and info of NamadaApp

- - -### ledger.getAddressAndPublicKey([path]) ⇒ AddressAndPublicKey -

Get address and public key associated with optional path, otherwise, use default path -Throw exception if app is not initialized.

- -**Kind**: instance method of [Ledger](#Ledger) -**Returns**: AddressAndPublicKey -

Address and public key

- -| Param | Type | Description | -| --- | --- | --- | -| [path] | string |

Bip44 path for deriving key

| - - - -### ledger.showAddressAndPublicKey([path]) ⇒ AddressAndPublicKey -

Prompt user to get address and public key associated with optional path, otherwise, use default path. -Throw exception if app is not initialized.

- -**Kind**: instance method of [Ledger](#Ledger) -**Returns**: AddressAndPublicKey -

Address and public key

- -| Param | Type | Description | -| --- | --- | --- | -| [path] | string |

Bip44 path for deriving key

| - - - -### ledger.sign(tx, [path]) ⇒ ResponseSign -

Sign tx bytes with the key associated with the provided (or default) path. -Throw exception if app is not initialized.

- -**Kind**: instance method of [Ledger](#Ledger) -**Returns**: ResponseSign -

Response signature

- -| Param | Type | Description | -| --- | --- | --- | -| tx | Uint8Array |

tx data blob to sign

| -| [path] | string |

Bip44 path for signing account

| - - - -### ledger.queryErrors() ⇒ string -

Query status to determine if device has thrown an error. -Throw exception if app is not initialized.

- -**Kind**: instance method of [Ledger](#Ledger) -**Returns**: string -

Error message if error is found

- - -### ledger.closeTransport() ⇒ void -

Close the initialized transport, which may be needed if Ledger needs to be reinitialized due to error state -Throw exception if app is not initialized.

- -**Kind**: instance method of [Ledger](#Ledger) - - -### Ledger.init([transport]) ⇒ [Ledger](#Ledger) -

Initialize and return Ledger class instance with initialized Transport

- -**Kind**: static method of [Ledger](#Ledger) -**Returns**: [Ledger](#Ledger) -

Ledger class instance

- -| Param | Type | Description | -| --- | --- | --- | -| [transport] | Transport |

Ledger transport

| - - - -## Masp -

Class representing utilities related to MASP

- -**Kind**: global class - -* [Masp](#Masp) - * [new Masp(sdk)](#new_Masp_new) - * [.hasMaspParams()](#Masp+hasMaspParams) ⇒ Promise.<boolean> - * [.fetchAndStoreMaspParams()](#Masp+fetchAndStoreMaspParams) ⇒ void - * [.loadMaspParams()](#Masp+loadMaspParams) ⇒ void - * [.addSpendingKey(xsk, alias)](#Masp+addSpendingKey) ⇒ Promise.<void> - - - -### new Masp(sdk) - -| Param | Type | Description | -| --- | --- | --- | -| sdk | SdkWasm |

Instance of Sdk struct from wasm lib

| - - - -### masp.hasMaspParams() ⇒ Promise.<boolean> -

Check if SDK has MASP parameters loaded

- -**Kind**: instance method of [Masp](#Masp) -**Returns**: Promise.<boolean> -

True if MASP parameters are loaded

- - -### masp.fetchAndStoreMaspParams() ⇒ void -

Fetch MASP parameters and store them in SDK

- -**Kind**: instance method of [Masp](#Masp) - - -### masp.loadMaspParams() ⇒ void -

Load stored MASP params

- -**Kind**: instance method of [Masp](#Masp) - - -### masp.addSpendingKey(xsk, alias) ⇒ Promise.<void> -

Add spending key to SDK wallet

- -**Kind**: instance method of [Masp](#Masp) - -| Param | Type | Description | -| --- | --- | --- | -| xsk | string |

extended spending key

| -| alias | string |

alias for the key

| - - - -## Mnemonic -

Class for accessing mnemonic functionality from wasm

- -**Kind**: global class - -* [Mnemonic](#Mnemonic) - * [new Mnemonic(cryptoMemory)](#new_Mnemonic_new) - * [.generate([size])](#Mnemonic+generate) ⇒ Promise.<Array.<string>> - * [.toSeed(phrase, [passphrase])](#Mnemonic+toSeed) ⇒ Uint8Array - * [.validateMnemonic(phrase)](#Mnemonic+validateMnemonic) ⇒ void - - - -### new Mnemonic(cryptoMemory) - -| Param | Type | Description | -| --- | --- | --- | -| cryptoMemory | WebAssembly.Memory |

Memory accessor for crypto lib

| - - - -### mnemonic.generate([size]) ⇒ Promise.<Array.<string>> -

Generate a new 12 or 24 word mnemonic

- -**Kind**: instance method of [Mnemonic](#Mnemonic) -**Returns**: Promise.<Array.<string>> -

Promise that resolves to array of words

- -| Param | Type | Description | -| --- | --- | --- | -| [size] | PhraseSize |

Mnemonic length

| - - - -### mnemonic.toSeed(phrase, [passphrase]) ⇒ Uint8Array -

Convert mnemonic to seed bytes

- -**Kind**: instance method of [Mnemonic](#Mnemonic) -**Returns**: Uint8Array -

Seed bytes

- -| Param | Type | Description | -| --- | --- | --- | -| phrase | string |

Mnemonic phrase

| -| [passphrase] | string |

Bip39 passphrase

| - - - -### mnemonic.validateMnemonic(phrase) ⇒ void -

Validate a mnemonic string, raise an exception providing reason -for failure if invalid, otherwise return nothing

- -**Kind**: instance method of [Mnemonic](#Mnemonic) - -| Param | Type | Description | -| --- | --- | --- | -| phrase | string |

Mnemonic phrase

| - - - -## Rpc -

API for executing RPC requests with Namada

- -**Kind**: global class - -* [Rpc](#Rpc) - * [new Rpc(sdk, query)](#new_Rpc_new) - * [.queryBalance(owner, tokens)](#Rpc+queryBalance) ⇒ Balance - * [.queryNativeToken()](#Rpc+queryNativeToken) ⇒ string - * [.queryPublicKey(address)](#Rpc+queryPublicKey) ⇒ string \| null - * [.queryAllValidators()](#Rpc+queryAllValidators) ⇒ Array.<string> - * [.queryProposals()](#Rpc+queryProposals) ⇒ Array.<Proposal> - * [.queryTotalDelegations(owners, [epoch])](#Rpc+queryTotalDelegations) ⇒ Promise.<DelegationTotals> - * [.queryDelegatorsVotes(proposalId)](#Rpc+queryDelegatorsVotes) ⇒ Promise.<DelegatorsVotes> - * [.queryStakingTotals(owners)](#Rpc+queryStakingTotals) ⇒ Promise.<Array.<StakingTotals>> - * [.queryStakingPositions(owners)](#Rpc+queryStakingPositions) ⇒ Promise.<StakingPositions> - * [.queryTotalBonds(owner)](#Rpc+queryTotalBonds) ⇒ Promise.<number> - * [.querySignedBridgePool(owners)](#Rpc+querySignedBridgePool) ⇒ Promise.<Array.<TransferToEthereum>> - * [.queryGasCosts()](#Rpc+queryGasCosts) ⇒ Promise.<GasCosts> - * [.broadcastTx(signedTx)](#Rpc+broadcastTx) ⇒ void - - - -### new Rpc(sdk, query) - -| Param | Type | Description | -| --- | --- | --- | -| sdk | SdkWasm |

Instance of Sdk struct from wasm lib

| -| query | QueryWasm |

Instance of Query struct from wasm lib

| - - - -### rpc.queryBalance(owner, tokens) ⇒ Balance -

Query balances from chain

- -**Kind**: instance method of [Rpc](#Rpc) -**Returns**: Balance -

[[tokenAddress, amount]]

- -| Param | Type | Description | -| --- | --- | --- | -| owner | string |

Owner address

| -| tokens | Array.<string> |

Array of token addresses

| - - - -### rpc.queryNativeToken() ⇒ string -

Query native token from chain

- -**Kind**: instance method of [Rpc](#Rpc) -**Returns**: string -

Address of native token

- - -### rpc.queryPublicKey(address) ⇒ string \| null -

Query public key -Return string of public key if it has been revealed on chain, otherwise, return null

- -**Kind**: instance method of [Rpc](#Rpc) -**Returns**: string \| null -

String of public key if found

- -| Param | Type | Description | -| --- | --- | --- | -| address | string |

Address to query

| - - - -### rpc.queryAllValidators() ⇒ Array.<string> -

Query all validator addresses

- -**Kind**: instance method of [Rpc](#Rpc) -**Returns**: Array.<string> -

Array of all validator addresses

- - -### rpc.queryProposals() ⇒ Array.<Proposal> -

Query Proposals

- -**Kind**: instance method of [Rpc](#Rpc) -**Returns**: Array.<Proposal> -

List of the proposals

- - -### rpc.queryTotalDelegations(owners, [epoch]) ⇒ Promise.<DelegationTotals> -

Query total delegations

- -**Kind**: instance method of [Rpc](#Rpc) -**Returns**: Promise.<DelegationTotals> -

Promise resolving to total delegations

- -| Param | Type | Description | -| --- | --- | --- | -| owners | Array.<string> |

Array of owner addresses

| -| [epoch] | bigint |

delegations at epoch

| - - - -### rpc.queryDelegatorsVotes(proposalId) ⇒ Promise.<DelegatorsVotes> -

Query delegators votes

- -**Kind**: instance method of [Rpc](#Rpc) -**Returns**: Promise.<DelegatorsVotes> -

Promise resolving to delegators votes

- -| Param | Type | Description | -| --- | --- | --- | -| proposalId | bigint |

ID of the proposal

| - - - -### rpc.queryStakingTotals(owners) ⇒ Promise.<Array.<StakingTotals>> -

Query staking totals by owner addresses

- -**Kind**: instance method of [Rpc](#Rpc) -**Returns**: Promise.<Array.<StakingTotals>> -

Promise resolving to staking totals

- -| Param | Type | Description | -| --- | --- | --- | -| owners | Array.<string> |

Array of owner addresses

| - - - -### rpc.queryStakingPositions(owners) ⇒ Promise.<StakingPositions> -

Query bond and unbond details by owner addresses

- -**Kind**: instance method of [Rpc](#Rpc) -**Returns**: Promise.<StakingPositions> -

Promise resolving to staking positions

- -| Param | Type | Description | -| --- | --- | --- | -| owners | Array.<string> |

Array of owner addresses

| - - - -### rpc.queryTotalBonds(owner) ⇒ Promise.<number> -

Query total bonds by owner address

- -**Kind**: instance method of [Rpc](#Rpc) -**Returns**: Promise.<number> -

Total bonds amount

- -| Param | Type | Description | -| --- | --- | --- | -| owner | string |

Owner address

| - - - -### rpc.querySignedBridgePool(owners) ⇒ Promise.<Array.<TransferToEthereum>> -

Query pending transactions in the signed bridge pool

- -**Kind**: instance method of [Rpc](#Rpc) -**Returns**: Promise.<Array.<TransferToEthereum>> -

Promise resolving to pending ethereum transfers

- -| Param | Type | Description | -| --- | --- | --- | -| owners | Array.<string> |

Array of owner addresses

| - - - -### rpc.queryGasCosts() ⇒ Promise.<GasCosts> -

Query gas costs

- -**Kind**: instance method of [Rpc](#Rpc) -**Returns**: Promise.<GasCosts> -

[[tokenAddress, gasCost]]

- - -### rpc.broadcastTx(signedTx) ⇒ void -

Broadcast a Tx to the ledger

- -**Kind**: instance method of [Rpc](#Rpc) - -| Param | Type | Description | -| --- | --- | --- | -| signedTx | [SignedTx](#SignedTx) |

Transaction with signature

| - - - -## Sdk -

API for interacting with Namada SDK

- -**Kind**: global class - -* [Sdk](#Sdk) - * [new Sdk(sdk, query, cryptoMemory, url, nativeToken)](#new_Sdk_new) - * _instance_ - * [.rpc](#Sdk+rpc) ⇒ [Rpc](#Rpc) - * [.tx](#Sdk+tx) ⇒ [Tx](#Tx) - * [.mnemonic](#Sdk+mnemonic) ⇒ [Mnemonic](#Mnemonic) - * [.keys](#Sdk+keys) ⇒ [Keys](#Keys) - * [.signing](#Sdk+signing) ⇒ [Signing](#Signing) - * [.masp](#Sdk+masp) ⇒ [Masp](#Masp) - * [.getRpc()](#Sdk+getRpc) ⇒ [Rpc](#Rpc) - * [.getTx()](#Sdk+getTx) ⇒ [Tx](#Tx) - * [.getMnemonic()](#Sdk+getMnemonic) ⇒ [Mnemonic](#Mnemonic) - * [.getKeys()](#Sdk+getKeys) ⇒ [Keys](#Keys) - * [.getSigning()](#Sdk+getSigning) ⇒ [Signing](#Signing) - * [.getMasp()](#Sdk+getMasp) ⇒ [Masp](#Masp) - * [.initLedger([transport])](#Sdk+initLedger) ⇒ [Ledger](#Ledger) - * _static_ - * [.init(url, token)](#Sdk.init) ⇒ Promise.<SDK> - - - -### new Sdk(sdk, query, cryptoMemory, url, nativeToken) - -| Param | Type | Description | -| --- | --- | --- | -| sdk | SdkWasm |

Instance of Sdk struct from wasm lib

| -| query | QueryWasm |

Instance of Query struct from wasm lib

| -| cryptoMemory | WebAssembly.Memory |

Memory accessor for crypto lib

| -| url | string |

RPC url

| -| nativeToken | string |

Address of chain's native token

| - - - -### sdk.rpc ⇒ [Rpc](#Rpc) -

Define rpc getter to use with destructuring assignment

- -**Kind**: instance property of [Sdk](#Sdk) -**Returns**: [Rpc](#Rpc) -

rpc client

- - -### sdk.tx ⇒ [Tx](#Tx) -

Define tx getter to use with destructuring assignment

- -**Kind**: instance property of [Sdk](#Sdk) -**Returns**: [Tx](#Tx) -

tx-related functionality

- - -### sdk.mnemonic ⇒ [Mnemonic](#Mnemonic) -

Define mnemonic getter to use with destructuring assignment

- -**Kind**: instance property of [Sdk](#Sdk) -**Returns**: [Mnemonic](#Mnemonic) -

mnemonic-related functionality

- - -### sdk.keys ⇒ [Keys](#Keys) -

Define keys getter to use with destructuring assignment

- -**Kind**: instance property of [Sdk](#Sdk) -**Returns**: [Keys](#Keys) -

key-related functionality

- - -### sdk.signing ⇒ [Signing](#Signing) -

Define signing getter to use with destructuring assignment

- -**Kind**: instance property of [Sdk](#Sdk) -**Returns**: [Signing](#Signing) -

Non-Tx signing functionality

- - -### sdk.masp ⇒ [Masp](#Masp) -

Define signing getter to use with destructuring assignment

- -**Kind**: instance property of [Sdk](#Sdk) -**Returns**: [Masp](#Masp) -

Masp utilities for handling params

- - -### sdk.getRpc() ⇒ [Rpc](#Rpc) -

Return initialized Rpc class

- -**Kind**: instance method of [Sdk](#Sdk) -**Returns**: [Rpc](#Rpc) -

Namada RPC client

- - -### sdk.getTx() ⇒ [Tx](#Tx) -

Return initialized Tx class

- -**Kind**: instance method of [Sdk](#Sdk) -**Returns**: [Tx](#Tx) -

Tx-related functionality

- - -### sdk.getMnemonic() ⇒ [Mnemonic](#Mnemonic) -

Return initialized Mnemonic class

- -**Kind**: instance method of [Sdk](#Sdk) -**Returns**: [Mnemonic](#Mnemonic) -

mnemonic-related functionality

- - -### sdk.getKeys() ⇒ [Keys](#Keys) -

Return initialized Keys class

- -**Kind**: instance method of [Sdk](#Sdk) -**Returns**: [Keys](#Keys) -

key-related functionality

- - -### sdk.getSigning() ⇒ [Signing](#Signing) -

Return initialized Signing class

- -**Kind**: instance method of [Sdk](#Sdk) -**Returns**: [Signing](#Signing) -

Non-Tx signing functionality

- - -### sdk.getMasp() ⇒ [Masp](#Masp) -

Return initialized Masp class

- -**Kind**: instance method of [Sdk](#Sdk) -**Returns**: [Masp](#Masp) -

Masp utilities for handling params

- - -### sdk.initLedger([transport]) ⇒ [Ledger](#Ledger) -

Intialize Ledger class for use with NamadaApp

- -**Kind**: instance method of [Sdk](#Sdk) -**Returns**: [Ledger](#Ledger) -

Class for interacting with NamadaApp for Ledger Hardware Wallets

- -| Param | Type | Description | -| --- | --- | --- | -| [transport] | Transport |

Will default to USB transport if not specified

| - - - -### Sdk.init(url, token) ⇒ Promise.<SDK> -

Initialize Sdk for web applications

- -**Kind**: static method of [Sdk](#Sdk) -**Returns**: Promise.<SDK> -
    -
  • Sdk instance
  • -
- -| Param | Type | Description | -| --- | --- | --- | -| url | string |

node url

| -| token | string |

native token address

| - - - -## Signing -

Non-Tx signing functions

- -**Kind**: global class - -* [Signing](#Signing) - * [.signArbitrary(signingKey, data)](#Signing+signArbitrary) ⇒ Signature - * [.verifyArbitrary(publicKey, hash, signature)](#Signing+verifyArbitrary) ⇒ void - - - -### signing.signArbitrary(signingKey, data) ⇒ Signature -

Sign arbitrary data

- -**Kind**: instance method of [Signing](#Signing) -**Returns**: Signature -

hash and signature

- -| Param | Type | Description | -| --- | --- | --- | -| signingKey | string |

private key

| -| data | string |

data to sign

| - - - -### signing.verifyArbitrary(publicKey, hash, signature) ⇒ void -

Verify arbitrary signature. Will throw an error if the signature is invalid

- -**Kind**: instance method of [Signing](#Signing) - -| Param | Type | Description | -| --- | --- | --- | -| publicKey | string |

public key to verify with

| -| hash | string |

signed hash

| -| signature | signature |

Hex-encoded signature

| - - - -## Tx -

SDK functionality related to transactions

- -**Kind**: global class - -* [Tx](#Tx) - * [new Tx(sdk)](#new_Tx_new) - * [.buildTxFromSerializedArgs(txType, encodedSpecificTx, encodedTx, gasPayer)](#Tx+buildTxFromSerializedArgs) ⇒ [Promise.<EncodedTx>](#EncodedTx) - * [.buildTx(txType, txProps, props, [gasPayer])](#Tx+buildTx) ⇒ [Promise.<EncodedTx>](#EncodedTx) - * [.buildTransfer(txProps, transferProps, [gasPayer])](#Tx+buildTransfer) ⇒ [Promise.<EncodedTx>](#EncodedTx) - * [.buildRevealPk(txProps, publicKey)](#Tx+buildRevealPk) ⇒ [Promise.<EncodedTx>](#EncodedTx) - * [.buildBond(txProps, bondProps, [gasPayer])](#Tx+buildBond) ⇒ [Promise.<EncodedTx>](#EncodedTx) - * [.buildUnbond(txProps, unbondProps, [gasPayer])](#Tx+buildUnbond) ⇒ [Promise.<EncodedTx>](#EncodedTx) - * [.buildWithdraw(txProps, withdrawProps, [gasPayer])](#Tx+buildWithdraw) ⇒ [Promise.<EncodedTx>](#EncodedTx) - * [.buildIbcTransfer(txProps, ibcTransferProps, [gasPayer])](#Tx+buildIbcTransfer) ⇒ [Promise.<EncodedTx>](#EncodedTx) - * [.buildEthBridgeTransfer(txProps, ethBridgeTransferProps, [gasPayer])](#Tx+buildEthBridgeTransfer) ⇒ [Promise.<EncodedTx>](#EncodedTx) - * [.buildVoteProposal(txProps, voteProposalProps, [gasPayer])](#Tx+buildVoteProposal) ⇒ [Promise.<EncodedTx>](#EncodedTx) - * [.signTx(encodedTx, [signingKey])](#Tx+signTx) ⇒ [Promise.<SignedTx>](#SignedTx) - * [.revealPk(signingKey, txProps)](#Tx+revealPk) ⇒ Promise.<void> - * [.appendSignature(txBytes, ledgerSignatureResponse)](#Tx+appendSignature) ⇒ Uint8Array - * [.encodeTxArgs(txProps)](#Tx+encodeTxArgs) ⇒ Uint8Array - - - -### new Tx(sdk) - -| Param | Type | Description | -| --- | --- | --- | -| sdk | SdkWasm |

Instance of Sdk struct from wasm lib

| - - - -### tx.buildTxFromSerializedArgs(txType, encodedSpecificTx, encodedTx, gasPayer) ⇒ [Promise.<EncodedTx>](#EncodedTx) -

Build a transaction

- -**Kind**: instance method of [Tx](#Tx) -**Returns**: [Promise.<EncodedTx>](#EncodedTx) -

promise that resolves to an EncodedTx

- -| Param | Type | Description | -| --- | --- | --- | -| txType | TxType |

type of the transaction

| -| encodedSpecificTx | Uint8Array |

encoded specific transaction

| -| encodedTx | Uint8Array |

encoded transaction

| -| gasPayer | string |

address of the gas payer

| - - - -### tx.buildTx(txType, txProps, props, [gasPayer]) ⇒ [Promise.<EncodedTx>](#EncodedTx) -

Wrapper method to handle all supported Tx

- -**Kind**: instance method of [Tx](#Tx) -**Returns**: [Promise.<EncodedTx>](#EncodedTx) -

promise that resolves to an EncodedTx

- -| Param | Type | Description | -| --- | --- | --- | -| txType | TxType |

type of the transaction

| -| txProps | TxProps |

transaction properties

| -| props | unknown |

Props specific to type of Tx

| -| [gasPayer] | string |

optional gas payer, defaults to source or sender

| - - - -### tx.buildTransfer(txProps, transferProps, [gasPayer]) ⇒ [Promise.<EncodedTx>](#EncodedTx) -

Build Transfer Tx

- -**Kind**: instance method of [Tx](#Tx) -**Returns**: [Promise.<EncodedTx>](#EncodedTx) -

promise that resolves to an EncodedTx

- -| Param | Type | Description | -| --- | --- | --- | -| txProps | TxProps |

properties of the transaction

| -| transferProps | TransferProps |

properties of the transfer

| -| [gasPayer] | string |

optional gas payer, if not provided, defaults to transferProps.source

| - - - -### tx.buildRevealPk(txProps, publicKey) ⇒ [Promise.<EncodedTx>](#EncodedTx) -

Build RevealPK Tx

- -**Kind**: instance method of [Tx](#Tx) -**Returns**: [Promise.<EncodedTx>](#EncodedTx) -

promise that resolves to an EncodedTx

- -| Param | Type | Description | -| --- | --- | --- | -| txProps | TxProps |

properties of the transaction

| -| publicKey | string |

public key to reveal

| - - - -### tx.buildBond(txProps, bondProps, [gasPayer]) ⇒ [Promise.<EncodedTx>](#EncodedTx) -

Build Bond Tx

- -**Kind**: instance method of [Tx](#Tx) -**Returns**: [Promise.<EncodedTx>](#EncodedTx) -

promise that resolves to an EncodedTx

- -| Param | Type | Description | -| --- | --- | --- | -| txProps | TxProps |

properties of the transaction

| -| bondProps | BondProps |

properties of the bond tx

| -| [gasPayer] | string |

optional gas payer, if not provided, defaults to bondProps.source

| - - - -### tx.buildUnbond(txProps, unbondProps, [gasPayer]) ⇒ [Promise.<EncodedTx>](#EncodedTx) -

Build Unbond Tx

- -**Kind**: instance method of [Tx](#Tx) -**Returns**: [Promise.<EncodedTx>](#EncodedTx) -

promise that resolves to an EncodedTx

- -| Param | Type | Description | -| --- | --- | --- | -| txProps | TxProps |

properties of the transaction

| -| unbondProps | UnbondProps |

properties of the unbond tx

| -| [gasPayer] | string |

optional gas payer, if not provided, defaults to unbondProps.source

| - - - -### tx.buildWithdraw(txProps, withdrawProps, [gasPayer]) ⇒ [Promise.<EncodedTx>](#EncodedTx) -

Build Withdraw Tx

- -**Kind**: instance method of [Tx](#Tx) -**Returns**: [Promise.<EncodedTx>](#EncodedTx) -

promise that resolves to an EncodedTx

- -| Param | Type | Description | -| --- | --- | --- | -| txProps | TxProps |

properties of the transaction

| -| withdrawProps | WithdrawProps |

properties of the withdraw tx

| -| [gasPayer] | string |

optional gas payer, if not provided, defaults to withdrawProps.source

| - - - -### tx.buildIbcTransfer(txProps, ibcTransferProps, [gasPayer]) ⇒ [Promise.<EncodedTx>](#EncodedTx) -

Build Ibc Transfer Tx

- -**Kind**: instance method of [Tx](#Tx) -**Returns**: [Promise.<EncodedTx>](#EncodedTx) -

promise that resolves to an EncodedTx

- -| Param | Type | Description | -| --- | --- | --- | -| txProps | TxProps |

properties of the transaction

| -| ibcTransferProps | IbcTransferProps |

properties of the ibc transfer tx

| -| [gasPayer] | string |

optional gas payer, if not provided, defaults to ibcTransferProps.source

| - - - -### tx.buildEthBridgeTransfer(txProps, ethBridgeTransferProps, [gasPayer]) ⇒ [Promise.<EncodedTx>](#EncodedTx) -

Build Ethereum Bridge Transfer Tx

- -**Kind**: instance method of [Tx](#Tx) -**Returns**: [Promise.<EncodedTx>](#EncodedTx) -

promise that resolves to an EncodedTx

- -| Param | Type | Description | -| --- | --- | --- | -| txProps | TxProps |

properties of the transaction

| -| ethBridgeTransferProps | EthBridgeTransferProps |

properties of the eth bridge transfer tx

| -| [gasPayer] | string |

optional gas payer, if not provided, defaults to ethBridgeTransferProps.sender

| - - - -### tx.buildVoteProposal(txProps, voteProposalProps, [gasPayer]) ⇒ [Promise.<EncodedTx>](#EncodedTx) -

Built Vote Proposal Tx

- -**Kind**: instance method of [Tx](#Tx) -**Returns**: [Promise.<EncodedTx>](#EncodedTx) -

promise that resolves to an EncodedTx

- -| Param | Type | Description | -| --- | --- | --- | -| txProps | TxProps |

properties of the transaction

| -| voteProposalProps | VoteProposalProps |

properties of the vote proposal tx

| -| [gasPayer] | string |

optional gas payer, if not provided, defaults to voteProposalProps.signer

| - - - -### tx.signTx(encodedTx, [signingKey]) ⇒ [Promise.<SignedTx>](#SignedTx) -

Sign transaction

- -**Kind**: instance method of [Tx](#Tx) -**Returns**: [Promise.<SignedTx>](#SignedTx) -

promise that resolves to a SignedTx

- -| Param | Type | Description | -| --- | --- | --- | -| encodedTx | [EncodedTx](#EncodedTx) |

encoded transaction

| -| [signingKey] | string |

optional in the case of shielded tx

| - - - -### tx.revealPk(signingKey, txProps) ⇒ Promise.<void> -

Reveal Public Key using serialized Tx

- -**Kind**: instance method of [Tx](#Tx) - -| Param | Type | Description | -| --- | --- | --- | -| signingKey | string |

signing key

| -| txProps | TxProps |

properties of the transaction

| - - - -### tx.appendSignature(txBytes, ledgerSignatureResponse) ⇒ Uint8Array -

Append signature for transactions signed by Ledger Hardware Wallet

- -**Kind**: instance method of [Tx](#Tx) -**Returns**: Uint8Array -
    -
  • Serialized Tx bytes with signature appended
  • -
- -| Param | Type | Description | -| --- | --- | --- | -| txBytes | Uint8Array |

Serialized transaction

| -| ledgerSignatureResponse | ResponseSign |

Serialized signature as returned from Ledger

| - - - -### tx.encodeTxArgs(txProps) ⇒ Uint8Array -

Helper to encode Tx args given TxProps

- -**Kind**: instance method of [Tx](#Tx) -**Returns**: Uint8Array -

Serialized TxMsgValue

- -| Param | Type | Description | -| --- | --- | --- | -| txProps | TxProps |

properties of the transaction

| - - - -## EncodedTx -

Wrap results of tx building along with TxMsg

- -**Kind**: global class - -* [EncodedTx](#EncodedTx) - * [new EncodedTx(txMsg, tx)](#new_EncodedTx_new) - * [.toBytes()](#EncodedTx+toBytes) ⇒ Uint8Array - * [.free()](#EncodedTx+free) - - - -### new EncodedTx(txMsg, tx) -

Create an EncodedTx class

- - -| Param | Type | Description | -| --- | --- | --- | -| txMsg | Uint8Array |

Borsh-serialized transaction

| -| tx | BuiltTx |

Specific tx struct instance

| - - - -### encodedTx.toBytes() ⇒ Uint8Array -

Return serialized tx bytes for external signing. This will clear -the BuiltTx struct instance from wasm memory, then return the bytes.

- -**Kind**: instance method of [EncodedTx](#EncodedTx) -**Returns**: Uint8Array -

Serialized tx bytes

- - -### encodedTx.free() -

Clear tx bytes resource

- -**Kind**: instance method of [EncodedTx](#EncodedTx) - - -## SignedTx -**Kind**: global class - - -### new SignedTx(txMsg, tx) - -| Param | Type | Description | -| --- | --- | --- | -| txMsg | Uint8Array |

Serialized tx msg bytes

| -| tx | Uint8Array |

Serialized tx bytes

| - - - -## initLedgerUSBTransport ⇒ Transport -

Initialize HID transport

- -**Kind**: global variable -**Returns**: Transport -

Transport object

- - -## EncodedTx -

Wrap results of tx signing to simplify passing between Sdk functions

- -**Kind**: global variable - -* [EncodedTx](#EncodedTx) - * [new EncodedTx(txMsg, tx)](#new_EncodedTx_new) - * [.toBytes()](#EncodedTx+toBytes) ⇒ Uint8Array - * [.free()](#EncodedTx+free) - - - -### new EncodedTx(txMsg, tx) -

Create an EncodedTx class

- - -| Param | Type | Description | -| --- | --- | --- | -| txMsg | Uint8Array |

Borsh-serialized transaction

| -| tx | BuiltTx |

Specific tx struct instance

| - - - -### encodedTx.toBytes() ⇒ Uint8Array -

Return serialized tx bytes for external signing. This will clear -the BuiltTx struct instance from wasm memory, then return the bytes.

- -**Kind**: instance method of [EncodedTx](#EncodedTx) -**Returns**: Uint8Array -

Serialized tx bytes

- - -### encodedTx.free() -

Clear tx bytes resource

- -**Kind**: instance method of [EncodedTx](#EncodedTx) - - -## initAsync(url, [token]) ⇒ [Sdk](#Sdk) -

Returns an initialized Sdk class asynchronously. This is required to use -this library in web applications.

- -**Kind**: global function -**Returns**: [Sdk](#Sdk) -

Instance of initialized Sdk class

- -| Param | Type | Description | -| --- | --- | --- | -| url | string |

RPC url for use with SDK

| -| [token] | string |

Native token of the target chain, if not provided, an attempt to query it will be made

| - - - -## initSync(url, nativeToken) ⇒ [Sdk](#Sdk) -

Initialize SDK for Node JS environments

- -**Kind**: global function -**Returns**: [Sdk](#Sdk) -

SDK instance

- -| Param | Type | Description | -| --- | --- | --- | -| url | string |

URL of the node

| -| nativeToken | string |

Address of the native token

| - - - -## initLedgerUSBTransport() ⇒ Transport -

Initialize USB transport

- -**Kind**: global function -**Returns**: Transport -

Transport object

diff --git a/packages/sdk/docs/classes/EncodedTx.md b/packages/sdk/docs/classes/EncodedTx.md new file mode 100644 index 000000000..51e851381 --- /dev/null +++ b/packages/sdk/docs/classes/EncodedTx.md @@ -0,0 +1,103 @@ +[@namada/sdk](../README.md) / [Exports](../modules.md) / EncodedTx + +# Class: EncodedTx + +Wrap results of tx building along with TxMsg + +## Table of contents + +### Constructors + +- [constructor](EncodedTx.md#constructor) + +### Properties + +- [tx](EncodedTx.md#tx) +- [txMsg](EncodedTx.md#txmsg) + +### Methods + +- [free](EncodedTx.md#free) +- [toBytes](EncodedTx.md#tobytes) + +## Constructors + +### constructor + +• **new EncodedTx**(`txMsg`, `tx`): [`EncodedTx`](EncodedTx.md) + +Create an EncodedTx class + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `txMsg` | `Uint8Array` | Borsh-serialized transaction | +| `tx` | `BuiltTx` | Specific tx struct instance | + +#### Returns + +[`EncodedTx`](EncodedTx.md) + +#### Defined in + +[sdk/src/tx/types.ts:12](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/tx/types.ts#L12) + +## Properties + +### tx + +• `Readonly` **tx**: `BuiltTx` + +Specific tx struct instance + +#### Defined in + +[sdk/src/tx/types.ts:14](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/tx/types.ts#L14) + +___ + +### txMsg + +• `Readonly` **txMsg**: `Uint8Array` + +Borsh-serialized transaction + +#### Defined in + +[sdk/src/tx/types.ts:13](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/tx/types.ts#L13) + +## Methods + +### free + +â–¸ **free**(): `void` + +Clear tx bytes resource + +#### Returns + +`void` + +#### Defined in + +[sdk/src/tx/types.ts:31](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/tx/types.ts#L31) + +___ + +### toBytes + +â–¸ **toBytes**(): `Uint8Array` + +Return serialized tx bytes for external signing. This will clear +the BuiltTx struct instance from wasm memory, then return the bytes. + +#### Returns + +`Uint8Array` + +Serialized tx bytes + +#### Defined in + +[sdk/src/tx/types.ts:22](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/tx/types.ts#L22) diff --git a/packages/sdk/docs/classes/Ledger.md b/packages/sdk/docs/classes/Ledger.md new file mode 100644 index 000000000..81d596f0c --- /dev/null +++ b/packages/sdk/docs/classes/Ledger.md @@ -0,0 +1,228 @@ +[@namada/sdk](../README.md) / [Exports](../modules.md) / Ledger + +# Class: Ledger + +Functionality for interacting with NamadaApp for Ledger Hardware Wallets + +## Table of contents + +### Constructors + +- [constructor](Ledger.md#constructor) + +### Properties + +- [namadaApp](Ledger.md#namadaapp) + +### Methods + +- [closeTransport](Ledger.md#closetransport) +- [getAddressAndPublicKey](Ledger.md#getaddressandpublickey) +- [queryErrors](Ledger.md#queryerrors) +- [showAddressAndPublicKey](Ledger.md#showaddressandpublickey) +- [sign](Ledger.md#sign) +- [status](Ledger.md#status) +- [init](Ledger.md#init) + +## Constructors + +### constructor + +• **new Ledger**(`namadaApp`): [`Ledger`](Ledger.md) + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `namadaApp` | `NamadaApp` | Inititalized NamadaApp class from Zondax package | + +#### Returns + +[`Ledger`](Ledger.md) + +#### Defined in + +[sdk/src/ledger.ts:54](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/ledger.ts#L54) + +## Properties + +### namadaApp + +• `Readonly` **namadaApp**: `NamadaApp` + +Inititalized NamadaApp class from Zondax package + +#### Defined in + +[sdk/src/ledger.ts:54](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/ledger.ts#L54) + +## Methods + +### closeTransport + +â–¸ **closeTransport**(): `Promise`\<`void`\> + +Close the initialized transport, which may be needed if Ledger needs to be reinitialized due to error state +Throw exception if app is not initialized. + +#### Returns + +`Promise`\<`void`\> + +void + +**`Async`** + +#### Defined in + +[sdk/src/ledger.ts:176](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/ledger.ts#L176) + +___ + +### getAddressAndPublicKey + +â–¸ **getAddressAndPublicKey**(`path?`): `Promise`\<[`AddressAndPublicKey`](../modules.md#addressandpublickey)\> + +Get address and public key associated with optional path, otherwise, use default path +Throw exception if app is not initialized. + +#### Parameters + +| Name | Type | Default value | Description | +| :------ | :------ | :------ | :------ | +| `path?` | `string` | `DEFAULT_LEDGER_BIP44_PATH` | Bip44 path for deriving key | + +#### Returns + +`Promise`\<[`AddressAndPublicKey`](../modules.md#addressandpublickey)\> + +Address and public key + +**`Async`** + +#### Defined in + +[sdk/src/ledger.ts:97](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/ledger.ts#L97) + +___ + +### queryErrors + +â–¸ **queryErrors**(): `Promise`\<`string`\> + +Query status to determine if device has thrown an error. +Throw exception if app is not initialized. + +#### Returns + +`Promise`\<`string`\> + +Error message if error is found + +**`Async`** + +#### Defined in + +[sdk/src/ledger.ts:159](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/ledger.ts#L159) + +___ + +### showAddressAndPublicKey + +â–¸ **showAddressAndPublicKey**(`path?`): `Promise`\<[`AddressAndPublicKey`](../modules.md#addressandpublickey)\> + +Prompt user to get address and public key associated with optional path, otherwise, use default path. +Throw exception if app is not initialized. + +#### Parameters + +| Name | Type | Default value | Description | +| :------ | :------ | :------ | :------ | +| `path?` | `string` | `DEFAULT_LEDGER_BIP44_PATH` | Bip44 path for deriving key | + +#### Returns + +`Promise`\<[`AddressAndPublicKey`](../modules.md#addressandpublickey)\> + +Address and public key + +**`Async`** + +#### Defined in + +[sdk/src/ledger.ts:118](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/ledger.ts#L118) + +___ + +### sign + +â–¸ **sign**(`tx`, `path?`): `Promise`\<`ResponseSign`\> + +Sign tx bytes with the key associated with the provided (or default) path. +Throw exception if app is not initialized. + +#### Parameters + +| Name | Type | Default value | Description | +| :------ | :------ | :------ | :------ | +| `tx` | `Uint8Array` | `undefined` | tx data blob to sign | +| `path?` | `string` | `DEFAULT_LEDGER_BIP44_PATH` | Bip44 path for signing account | + +#### Returns + +`Promise`\<`ResponseSign`\> + +Response signature + +**`Async`** + +#### Defined in + +[sdk/src/ledger.ts:144](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/ledger.ts#L144) + +___ + +### status + +â–¸ **status**(): `Promise`\<[`LedgerStatus`](../modules.md#ledgerstatus)\> + +Return status and version info of initialized NamadaApp. +Throw exception if app is not initialized. + +#### Returns + +`Promise`\<[`LedgerStatus`](../modules.md#ledgerstatus)\> + +Version and info of NamadaApp + +**`Async`** + +#### Defined in + +[sdk/src/ledger.ts:80](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/ledger.ts#L80) + +___ + +### init + +â–¸ **init**(`transport?`): `Promise`\<[`Ledger`](Ledger.md)\> + +Initialize and return Ledger class instance with initialized Transport + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `transport?` | `default` | Ledger transport | + +#### Returns + +`Promise`\<[`Ledger`](Ledger.md)\> + +Ledger class instance + +**`Async`** + +#### Defined in + +[sdk/src/ledger.ts:62](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/ledger.ts#L62) diff --git a/packages/sdk/docs/classes/Rpc.md b/packages/sdk/docs/classes/Rpc.md new file mode 100644 index 000000000..fb83a9f52 --- /dev/null +++ b/packages/sdk/docs/classes/Rpc.md @@ -0,0 +1,413 @@ +[@namada/sdk](../README.md) / [Exports](../modules.md) / Rpc + +# Class: Rpc + +API for executing RPC requests with Namada + +## Table of contents + +### Constructors + +- [constructor](Rpc.md#constructor) + +### Properties + +- [query](Rpc.md#query) +- [sdk](Rpc.md#sdk) + +### Methods + +- [broadcastTx](Rpc.md#broadcasttx) +- [queryAllValidators](Rpc.md#queryallvalidators) +- [queryBalance](Rpc.md#querybalance) +- [queryDelegatorsVotes](Rpc.md#querydelegatorsvotes) +- [queryGasCosts](Rpc.md#querygascosts) +- [queryNativeToken](Rpc.md#querynativetoken) +- [queryProposals](Rpc.md#queryproposals) +- [queryPublicKey](Rpc.md#querypublickey) +- [querySignedBridgePool](Rpc.md#querysignedbridgepool) +- [queryStakingPositions](Rpc.md#querystakingpositions) +- [queryStakingTotals](Rpc.md#querystakingtotals) +- [queryTotalBonds](Rpc.md#querytotalbonds) +- [queryTotalDelegations](Rpc.md#querytotaldelegations) +- [shieldedSync](Rpc.md#shieldedsync) + +## Constructors + +### constructor + +• **new Rpc**(`sdk`, `query`): [`Rpc`](Rpc.md) + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `sdk` | `Sdk` | Instance of Sdk struct from wasm lib | +| `query` | `Query` | Instance of Query struct from wasm lib | + +#### Returns + +[`Rpc`](Rpc.md) + +#### Defined in + +[sdk/src/rpc/rpc.ts:31](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/rpc/rpc.ts#L31) + +## Properties + +### query + +• `Protected` `Readonly` **query**: `Query` + +Instance of Query struct from wasm lib + +#### Defined in + +[sdk/src/rpc/rpc.ts:33](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/rpc/rpc.ts#L33) + +___ + +### sdk + +• `Protected` `Readonly` **sdk**: `Sdk` + +Instance of Sdk struct from wasm lib + +#### Defined in + +[sdk/src/rpc/rpc.ts:32](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/rpc/rpc.ts#L32) + +## Methods + +### broadcastTx + +â–¸ **broadcastTx**(`signedTx`): `Promise`\<`string`\> + +Broadcast a Tx to the ledger + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `signedTx` | [`SignedTx`](SignedTx.md) | Transaction with signature | + +#### Returns + +`Promise`\<`string`\> + +void + +**`Async`** + +#### Defined in + +[sdk/src/rpc/rpc.ts:210](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/rpc/rpc.ts#L210) + +___ + +### queryAllValidators + +â–¸ **queryAllValidators**(): `Promise`\<`string`[]\> + +Query all validator addresses + +#### Returns + +`Promise`\<`string`[]\> + +Array of all validator addresses + +**`Async`** + +#### Defined in + +[sdk/src/rpc/rpc.ts:73](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/rpc/rpc.ts#L73) + +___ + +### queryBalance + +â–¸ **queryBalance**(`owner`, `tokens`): `Promise`\<[`Balance`](../modules.md#balance)\> + +Query balances from chain + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `owner` | `string` | Owner address | +| `tokens` | `string`[] | Array of token addresses | + +#### Returns + +`Promise`\<[`Balance`](../modules.md#balance)\> + +[[tokenAddress, amount]] + +**`Async`** + +#### Defined in + +[sdk/src/rpc/rpc.ts:43](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/rpc/rpc.ts#L43) + +___ + +### queryDelegatorsVotes + +â–¸ **queryDelegatorsVotes**(`proposalId`): `Promise`\<[`DelegatorsVotes`](../modules.md#delegatorsvotes)\> + +Query delegators votes + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `proposalId` | `bigint` | ID of the proposal | + +#### Returns + +`Promise`\<[`DelegatorsVotes`](../modules.md#delegatorsvotes)\> + +Promise resolving to delegators votes + +**`Async`** + +#### Defined in + +[sdk/src/rpc/rpc.ts:108](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/rpc/rpc.ts#L108) + +___ + +### queryGasCosts + +â–¸ **queryGasCosts**(): `Promise`\<`GasCosts`\> + +Query gas costs + +#### Returns + +`Promise`\<`GasCosts`\> + +[[tokenAddress, gasCost]] + +**`Async`** + +#### Defined in + +[sdk/src/rpc/rpc.ts:200](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/rpc/rpc.ts#L200) + +___ + +### queryNativeToken + +â–¸ **queryNativeToken**(): `Promise`\<`string`\> + +Query native token from chain + +#### Returns + +`Promise`\<`string`\> + +Address of native token + +**`Async`** + +#### Defined in + +[sdk/src/rpc/rpc.ts:52](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/rpc/rpc.ts#L52) + +___ + +### queryProposals + +â–¸ **queryProposals**(): `Promise`\<`Proposal`[]\> + +Query Proposals + +#### Returns + +`Promise`\<`Proposal`[]\> + +List of the proposals + +**`Async`** + +#### Defined in + +[sdk/src/rpc/rpc.ts:82](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/rpc/rpc.ts#L82) + +___ + +### queryPublicKey + +â–¸ **queryPublicKey**(`address`): `Promise`\<`undefined` \| `string`\> + +Query public key +Return string of public key if it has been revealed on chain, otherwise, return null + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `address` | `string` | Address to query | + +#### Returns + +`Promise`\<`undefined` \| `string`\> + +String of public key if found + +**`Async`** + +#### Defined in + +[sdk/src/rpc/rpc.ts:63](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/rpc/rpc.ts#L63) + +___ + +### querySignedBridgePool + +â–¸ **querySignedBridgePool**(`owners`): `Promise`\<`TransferToEthereum`[]\> + +Query pending transactions in the signed bridge pool + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `owners` | `string`[] | Array of owner addresses | + +#### Returns + +`Promise`\<`TransferToEthereum`[]\> + +Promise resolving to pending ethereum transfers + +**`Async`** + +#### Defined in + +[sdk/src/rpc/rpc.ts:191](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/rpc/rpc.ts#L191) + +___ + +### queryStakingPositions + +â–¸ **queryStakingPositions**(`owners`): `Promise`\<[`StakingPositions`](../modules.md#stakingpositions)\> + +Query bond and unbond details by owner addresses + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `owners` | `string`[] | Array of owner addresses | + +#### Returns + +`Promise`\<[`StakingPositions`](../modules.md#stakingpositions)\> + +Promise resolving to staking positions + +**`Async`** + +#### Defined in + +[sdk/src/rpc/rpc.ts:145](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/rpc/rpc.ts#L145) + +___ + +### queryStakingTotals + +â–¸ **queryStakingTotals**(`owners`): `Promise`\<[`StakingTotals`](../modules.md#stakingtotals)[]\> + +Query staking totals by owner addresses + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `owners` | `string`[] | Array of owner addresses | + +#### Returns + +`Promise`\<[`StakingTotals`](../modules.md#stakingtotals)[]\> + +Promise resolving to staking totals + +**`Async`** + +#### Defined in + +[sdk/src/rpc/rpc.ts:118](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/rpc/rpc.ts#L118) + +___ + +### queryTotalBonds + +â–¸ **queryTotalBonds**(`owner`): `Promise`\<`number`\> + +Query total bonds by owner address + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `owner` | `string` | Owner address | + +#### Returns + +`Promise`\<`number`\> + +Total bonds amount + +#### Defined in + +[sdk/src/rpc/rpc.ts:181](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/rpc/rpc.ts#L181) + +___ + +### queryTotalDelegations + +â–¸ **queryTotalDelegations**(`owners`, `epoch?`): `Promise`\<[`DelegationTotals`](../modules.md#delegationtotals)\> + +Query total delegations + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `owners` | `string`[] | Array of owner addresses | +| `epoch?` | `bigint` | delegations at epoch | + +#### Returns + +`Promise`\<[`DelegationTotals`](../modules.md#delegationtotals)\> + +Promise resolving to total delegations + +**`Async`** + +#### Defined in + +[sdk/src/rpc/rpc.ts:95](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/rpc/rpc.ts#L95) + +___ + +### shieldedSync + +â–¸ **shieldedSync**(`vks`): `Promise`\<`void`\> + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `vks` | `string`[] | + +#### Returns + +`Promise`\<`void`\> + +#### Defined in + +[sdk/src/rpc/rpc.ts:215](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/rpc/rpc.ts#L215) diff --git a/packages/sdk/docs/classes/Sdk.md b/packages/sdk/docs/classes/Sdk.md new file mode 100644 index 000000000..8ebd89ff8 --- /dev/null +++ b/packages/sdk/docs/classes/Sdk.md @@ -0,0 +1,364 @@ +[@namada/sdk](../README.md) / [Exports](../modules.md) / Sdk + +# Class: Sdk + +API for interacting with Namada SDK + +## Table of contents + +### Constructors + +- [constructor](Sdk.md#constructor) + +### Properties + +- [cryptoMemory](Sdk.md#cryptomemory) +- [nativeToken](Sdk.md#nativetoken) +- [query](Sdk.md#query) +- [sdk](Sdk.md#sdk) +- [url](Sdk.md#url) + +### Accessors + +- [keys](Sdk.md#keys) +- [masp](Sdk.md#masp) +- [mnemonic](Sdk.md#mnemonic) +- [rpc](Sdk.md#rpc) +- [signing](Sdk.md#signing) +- [tx](Sdk.md#tx) + +### Methods + +- [getKeys](Sdk.md#getkeys) +- [getMasp](Sdk.md#getmasp) +- [getMnemonic](Sdk.md#getmnemonic) +- [getRpc](Sdk.md#getrpc) +- [getSigning](Sdk.md#getsigning) +- [getTx](Sdk.md#gettx) +- [initLedger](Sdk.md#initledger) + +## Constructors + +### constructor + +• **new Sdk**(`sdk`, `query`, `cryptoMemory`, `url`, `nativeToken`): [`Sdk`](Sdk.md) + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `sdk` | `Sdk` | Instance of Sdk struct from wasm lib | +| `query` | `Query` | Instance of Query struct from wasm lib | +| `cryptoMemory` | `Memory` | Memory accessor for crypto lib | +| `url` | `string` | RPC url | +| `nativeToken` | `string` | Address of chain's native token | + +#### Returns + +[`Sdk`](Sdk.md) + +#### Defined in + +[sdk/src/sdk.ts:22](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/sdk.ts#L22) + +## Properties + +### cryptoMemory + +• `Readonly` **cryptoMemory**: `Memory` + +Memory accessor for crypto lib + +#### Defined in + +[sdk/src/sdk.ts:25](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/sdk.ts#L25) + +___ + +### nativeToken + +• `Readonly` **nativeToken**: `string` + +Address of chain's native token + +#### Defined in + +[sdk/src/sdk.ts:27](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/sdk.ts#L27) + +___ + +### query + +• `Protected` `Readonly` **query**: `Query` + +Instance of Query struct from wasm lib + +#### Defined in + +[sdk/src/sdk.ts:24](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/sdk.ts#L24) + +___ + +### sdk + +• `Protected` `Readonly` **sdk**: `Sdk` + +Instance of Sdk struct from wasm lib + +#### Defined in + +[sdk/src/sdk.ts:23](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/sdk.ts#L23) + +___ + +### url + +• `Readonly` **url**: `string` + +RPC url + +#### Defined in + +[sdk/src/sdk.ts:26](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/sdk.ts#L26) + +## Accessors + +### keys + +• `get` **keys**(): `Keys` + +Define keys getter to use with destructuring assignment + +#### Returns + +`Keys` + +key-related functionality + +#### Defined in + +[sdk/src/sdk.ts:115](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/sdk.ts#L115) + +___ + +### masp + +• `get` **masp**(): `Masp` + +Define signing getter to use with destructuring assignment + +#### Returns + +`Masp` + +Masp utilities for handling params + +#### Defined in + +[sdk/src/sdk.ts:131](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/sdk.ts#L131) + +___ + +### mnemonic + +• `get` **mnemonic**(): `Mnemonic` + +Define mnemonic getter to use with destructuring assignment + +#### Returns + +`Mnemonic` + +mnemonic-related functionality + +#### Defined in + +[sdk/src/sdk.ts:107](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/sdk.ts#L107) + +___ + +### rpc + +• `get` **rpc**(): [`Rpc`](Rpc.md) + +Define rpc getter to use with destructuring assignment + +#### Returns + +[`Rpc`](Rpc.md) + +rpc client + +#### Defined in + +[sdk/src/sdk.ts:91](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/sdk.ts#L91) + +___ + +### signing + +• `get` **signing**(): `Signing` + +Define signing getter to use with destructuring assignment + +#### Returns + +`Signing` + +Non-Tx signing functionality + +#### Defined in + +[sdk/src/sdk.ts:123](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/sdk.ts#L123) + +___ + +### tx + +• `get` **tx**(): `Tx` + +Define tx getter to use with destructuring assignment + +#### Returns + +`Tx` + +tx-related functionality + +#### Defined in + +[sdk/src/sdk.ts:99](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/sdk.ts#L99) + +## Methods + +### getKeys + +â–¸ **getKeys**(): `Keys` + +Return initialized Keys class + +#### Returns + +`Keys` + +key-related functionality + +#### Defined in + +[sdk/src/sdk.ts:57](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/sdk.ts#L57) + +___ + +### getMasp + +â–¸ **getMasp**(): `Masp` + +Return initialized Masp class + +#### Returns + +`Masp` + +Masp utilities for handling params + +#### Defined in + +[sdk/src/sdk.ts:73](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/sdk.ts#L73) + +___ + +### getMnemonic + +â–¸ **getMnemonic**(): `Mnemonic` + +Return initialized Mnemonic class + +#### Returns + +`Mnemonic` + +mnemonic-related functionality + +#### Defined in + +[sdk/src/sdk.ts:49](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/sdk.ts#L49) + +___ + +### getRpc + +â–¸ **getRpc**(): [`Rpc`](Rpc.md) + +Return initialized Rpc class + +#### Returns + +[`Rpc`](Rpc.md) + +Namada RPC client + +#### Defined in + +[sdk/src/sdk.ts:33](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/sdk.ts#L33) + +___ + +### getSigning + +â–¸ **getSigning**(): `Signing` + +Return initialized Signing class + +#### Returns + +`Signing` + +Non-Tx signing functionality + +#### Defined in + +[sdk/src/sdk.ts:65](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/sdk.ts#L65) + +___ + +### getTx + +â–¸ **getTx**(): `Tx` + +Return initialized Tx class + +#### Returns + +`Tx` + +Tx-related functionality + +#### Defined in + +[sdk/src/sdk.ts:41](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/sdk.ts#L41) + +___ + +### initLedger + +â–¸ **initLedger**(`transport?`): `Promise`\<[`Ledger`](Ledger.md)\> + +Intialize Ledger class for use with NamadaApp + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `transport?` | `default` | Will default to USB transport if not specified | + +#### Returns + +`Promise`\<[`Ledger`](Ledger.md)\> + +Class for interacting with NamadaApp for Ledger Hardware Wallets + +**`Async`** + +#### Defined in + +[sdk/src/sdk.ts:83](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/sdk.ts#L83) diff --git a/packages/sdk/docs/classes/SignedTx.md b/packages/sdk/docs/classes/SignedTx.md new file mode 100644 index 000000000..0f482659a --- /dev/null +++ b/packages/sdk/docs/classes/SignedTx.md @@ -0,0 +1,61 @@ +[@namada/sdk](../README.md) / [Exports](../modules.md) / SignedTx + +# Class: SignedTx + +Wrap results of tx signing to simplify passing between Sdk functions + +## Table of contents + +### Constructors + +- [constructor](SignedTx.md#constructor) + +### Properties + +- [tx](SignedTx.md#tx) +- [txMsg](SignedTx.md#txmsg) + +## Constructors + +### constructor + +• **new SignedTx**(`txMsg`, `tx`): [`SignedTx`](SignedTx.md) + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `txMsg` | `Uint8Array` | Serialized tx msg bytes | +| `tx` | `Uint8Array` | Serialized tx bytes | + +#### Returns + +[`SignedTx`](SignedTx.md) + +#### Defined in + +[sdk/src/tx/types.ts:44](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/tx/types.ts#L44) + +## Properties + +### tx + +• `Readonly` **tx**: `Uint8Array` + +Serialized tx bytes + +#### Defined in + +[sdk/src/tx/types.ts:48](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/tx/types.ts#L48) + +___ + +### txMsg + +• `Readonly` **txMsg**: `Uint8Array` + +Serialized tx msg bytes + +#### Defined in + +[sdk/src/tx/types.ts:46](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/tx/types.ts#L46) diff --git a/packages/sdk/docs/enums/PhraseSize.md b/packages/sdk/docs/enums/PhraseSize.md new file mode 100644 index 000000000..88f977740 --- /dev/null +++ b/packages/sdk/docs/enums/PhraseSize.md @@ -0,0 +1,30 @@ +[@namada/sdk](../README.md) / [Exports](../modules.md) / PhraseSize + +# Enumeration: PhraseSize + +## Table of contents + +### Enumeration Members + +- [N12](PhraseSize.md#n12) +- [N24](PhraseSize.md#n24) + +## Enumeration Members + +### N12 + +• **N12** = ``12`` + +#### Defined in + +crypto/src/crypto/crypto.d.ts:13 + +___ + +### N24 + +• **N24** = ``24`` + +#### Defined in + +crypto/src/crypto/crypto.d.ts:14 diff --git a/packages/sdk/docs/enums/TxType.md b/packages/sdk/docs/enums/TxType.md new file mode 100644 index 000000000..490951610 --- /dev/null +++ b/packages/sdk/docs/enums/TxType.md @@ -0,0 +1,96 @@ +[@namada/sdk](../README.md) / [Exports](../modules.md) / TxType + +# Enumeration: TxType + +## Table of contents + +### Enumeration Members + +- [Bond](TxType.md#bond) +- [EthBridgeTransfer](TxType.md#ethbridgetransfer) +- [IBCTransfer](TxType.md#ibctransfer) +- [RevealPK](TxType.md#revealpk) +- [Transfer](TxType.md#transfer) +- [Unbond](TxType.md#unbond) +- [VoteProposal](TxType.md#voteproposal) +- [Withdraw](TxType.md#withdraw) + +## Enumeration Members + +### Bond + +• **Bond** = ``1`` + +#### Defined in + +shared/src/shared/shared.d.ts:17 + +___ + +### EthBridgeTransfer + +• **EthBridgeTransfer** = ``6`` + +#### Defined in + +shared/src/shared/shared.d.ts:22 + +___ + +### IBCTransfer + +• **IBCTransfer** = ``5`` + +#### Defined in + +shared/src/shared/shared.d.ts:21 + +___ + +### RevealPK + +• **RevealPK** = ``7`` + +#### Defined in + +shared/src/shared/shared.d.ts:23 + +___ + +### Transfer + +• **Transfer** = ``4`` + +#### Defined in + +shared/src/shared/shared.d.ts:20 + +___ + +### Unbond + +• **Unbond** = ``2`` + +#### Defined in + +shared/src/shared/shared.d.ts:18 + +___ + +### VoteProposal + +• **VoteProposal** = ``8`` + +#### Defined in + +shared/src/shared/shared.d.ts:24 + +___ + +### Withdraw + +• **Withdraw** = ``3`` + +#### Defined in + +shared/src/shared/shared.d.ts:19 diff --git a/packages/sdk/docs/modules.md b/packages/sdk/docs/modules.md new file mode 100644 index 000000000..6db2f014c --- /dev/null +++ b/packages/sdk/docs/modules.md @@ -0,0 +1,335 @@ +[@namada/sdk](README.md) / Exports + +# @namada/sdk + +## Table of contents + +### Enumerations + +- [PhraseSize](enums/PhraseSize.md) +- [TxType](enums/TxType.md) + +### Classes + +- [EncodedTx](classes/EncodedTx.md) +- [Ledger](classes/Ledger.md) +- [Rpc](classes/Rpc.md) +- [Sdk](classes/Sdk.md) +- [SignedTx](classes/SignedTx.md) + +### Type Aliases + +- [Address](modules.md#address) +- [AddressAndPublicKey](modules.md#addressandpublickey) +- [Balance](modules.md#balance) +- [Bonds](modules.md#bonds) +- [DelegationTotals](modules.md#delegationtotals) +- [DelegatorsVotes](modules.md#delegatorsvotes) +- [LedgerStatus](modules.md#ledgerstatus) +- [ShieldedKeys](modules.md#shieldedkeys) +- [StakingPositions](modules.md#stakingpositions) +- [StakingTotals](modules.md#stakingtotals) +- [SupportedTx](modules.md#supportedtx) +- [TransparentKeys](modules.md#transparentkeys) +- [Unbonds](modules.md#unbonds) + +### Variables + +- [DEFAULT\_LEDGER\_BIP44\_PATH](modules.md#default_ledger_bip44_path) +- [TxTypeLabel](modules.md#txtypelabel) + +### Functions + +- [initLedgerHIDTransport](modules.md#initledgerhidtransport) +- [initLedgerUSBTransport](modules.md#initledgerusbtransport) +- [publicKeyToBech32](modules.md#publickeytobech32) + +## Type Aliases + +### Address + +Ƭ **Address**: `Object` + +Address and public key type + +#### Type declaration + +| Name | Type | +| :------ | :------ | +| `address` | `string` | +| `publicKey` | `string` | + +#### Defined in + +[sdk/src/keys/types.ts:4](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/keys/types.ts#L4) + +___ + +### AddressAndPublicKey + +Ƭ **AddressAndPublicKey**: `Object` + +#### Type declaration + +| Name | Type | +| :------ | :------ | +| `address` | `string` | +| `publicKey` | `string` | + +#### Defined in + +[sdk/src/ledger.ts:17](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/ledger.ts#L17) + +___ + +### Balance + +Ƭ **Balance**: [`string`, `string`][] + +Balance +[tokenAddress, amount][] + +#### Defined in + +[sdk/src/rpc/types.ts:69](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/rpc/types.ts#L69) + +___ + +### Bonds + +Ƭ **Bonds**: `Object` + +#### Type declaration + +| Name | Type | +| :------ | :------ | +| `amount` | `string` | +| `owner` | `string` | +| `startEpoch` | `string` | +| `validator` | `string` | + +#### Defined in + +[sdk/src/rpc/types.ts:27](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/rpc/types.ts#L27) + +___ + +### DelegationTotals + +Ƭ **DelegationTotals**: `Record`\<`string`, `number`\> + +DelegationTotals +Record + +#### Defined in + +[sdk/src/rpc/types.ts:51](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/rpc/types.ts#L51) + +___ + +### DelegatorsVotes + +Ƭ **DelegatorsVotes**: `Record`\<`string`, `boolean`\> + +Delegator Votes +Record + +#### Defined in + +[sdk/src/rpc/types.ts:57](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/rpc/types.ts#L57) + +___ + +### LedgerStatus + +Ƭ **LedgerStatus**: `Object` + +#### Type declaration + +| Name | Type | +| :------ | :------ | +| `info` | `ResponseAppInfo` | +| `version` | `ResponseVersion` | + +#### Defined in + +[sdk/src/ledger.ts:18](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/ledger.ts#L18) + +___ + +### ShieldedKeys + +Ƭ **ShieldedKeys**: `Object` + +Shielded keys and address + +#### Type declaration + +| Name | Type | +| :------ | :------ | +| `address` | `string` | +| `spendingKey` | `string` | +| `viewingKey` | `string` | + +#### Defined in + +[sdk/src/keys/types.ts:19](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/keys/types.ts#L19) + +___ + +### StakingPositions + +Ƭ **StakingPositions**: `Object` + +#### Type declaration + +| Name | Type | +| :------ | :------ | +| `bonds` | [`Bonds`](modules.md#bonds)[] | +| `unbonds` | [`Unbonds`](modules.md#unbonds)[] | + +#### Defined in + +[sdk/src/rpc/types.ts:42](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/rpc/types.ts#L42) + +___ + +### StakingTotals + +Ƭ **StakingTotals**: `Object` + +#### Type declaration + +| Name | Type | +| :------ | :------ | +| `bonds` | `string` | +| `owner` | `string` | +| `unbonds` | `string` | +| `validator` | `string` | +| `withdrawable` | `string` | + +#### Defined in + +[sdk/src/rpc/types.ts:19](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/rpc/types.ts#L19) + +___ + +### SupportedTx + +Ƭ **SupportedTx**: `Extract`\<[`TxType`](enums/TxType.md), [`Bond`](enums/TxType.md#bond) \| [`Unbond`](enums/TxType.md#unbond) \| [`Transfer`](enums/TxType.md#transfer) \| [`IBCTransfer`](enums/TxType.md#ibctransfer) \| [`EthBridgeTransfer`](enums/TxType.md#ethbridgetransfer) \| [`Withdraw`](enums/TxType.md#withdraw) \| [`VoteProposal`](enums/TxType.md#voteproposal)\> + +#### Defined in + +[shared/src/types.ts:3](https://github.com/anoma/namada-interface/blob/7542445f/packages/shared/src/types.ts#L3) + +___ + +### TransparentKeys + +Ƭ **TransparentKeys**: \{ `privateKey`: `string` } & [`Address`](modules.md#address) + +Public and private keypair with address + +#### Defined in + +[sdk/src/keys/types.ts:12](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/keys/types.ts#L12) + +___ + +### Unbonds + +Ƭ **Unbonds**: `Object` + +#### Type declaration + +| Name | Type | +| :------ | :------ | +| `amount` | `string` | +| `owner` | `string` | +| `startEpoch` | `string` | +| `validator` | `string` | +| `withdrawableEpoch` | `string` | + +#### Defined in + +[sdk/src/rpc/types.ts:34](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/rpc/types.ts#L34) + +## Variables + +### DEFAULT\_LEDGER\_BIP44\_PATH + +• `Const` **DEFAULT\_LEDGER\_BIP44\_PATH**: `string` + +#### Defined in + +[sdk/src/ledger.ts:41](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/ledger.ts#L41) + +___ + +### TxTypeLabel + +• `Const` **TxTypeLabel**: `Record`\<[`TxType`](enums/TxType.md), `TxLabel`\> + +#### Defined in + +[shared/src/types.ts:24](https://github.com/anoma/namada-interface/blob/7542445f/packages/shared/src/types.ts#L24) + +## Functions + +### initLedgerHIDTransport + +â–¸ **initLedgerHIDTransport**(): `Promise`\<`default`\> + +Initialize HID transport + +#### Returns + +`Promise`\<`default`\> + +Transport object + +**`Async`** + +#### Defined in + +[sdk/src/ledger.ts:37](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/ledger.ts#L37) + +___ + +### initLedgerUSBTransport + +â–¸ **initLedgerUSBTransport**(): `Promise`\<`default`\> + +Initialize USB transport + +#### Returns + +`Promise`\<`default`\> + +Transport object + +**`Async`** + +#### Defined in + +[sdk/src/ledger.ts:28](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/ledger.ts#L28) + +___ + +### publicKeyToBech32 + +â–¸ **publicKeyToBech32**(`publicKey`): `string` + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `publicKey` | `Uint8Array` | + +#### Returns + +`string` + +#### Defined in + +[sdk/src/keys/keys.ts:170](https://github.com/anoma/namada-interface/blob/7542445f/packages/sdk/src/keys/keys.ts#L170) diff --git a/packages/sdk/docs/specs.md b/packages/sdk/docs/specs.md deleted file mode 100644 index 4a88b9baa..000000000 --- a/packages/sdk/docs/specs.md +++ /dev/null @@ -1,110 +0,0 @@ -# @namada/sdk specs - -The `@namada/sdk` package is a wrapper library to provides an easy way to integrate with the `@namada/shared` WebAssembly Rust library. - -View the [API](./api.md) docs for specific information on API interfaces. - -## Table of Contents - -- [Basic Usage](#basic-usage) -- [Keys](#keys) -- [Rpc](#rpc) -- [Tx](#tx) -- [Ledger](#ledger) -- [Masp](#masp) -- [Mnemonic](#mnemonic) -- [Signing](#signing) - -## Basic Usage - -The initialization of the `Sdk` must happen asynchronously for web applications. - -In your application, you can initialize the Sdk with the following: - -```typescript -import { Sdk } from "@namada/sdk"; - -async function myApp() { - const rpcUrl = "http://localhost:27657"; - - // You can use deconstruction to access submodules - const { tx, keys, signing, mnemonic, keys } = await Sdk.init(rpcUrl); - - // ..... -} - -myApp(); -``` - -Alternatively, you can import the `initAsync` function, which will also return an instance of the SDK: - -```typescript -import { initAsync } from "@namada/sdk"; - -async function myApp() { - const rpcUrl = "http://localhost:27657"; - const sdk = await initAsync(rpcUrl); -} - -myApp(); -``` - -[ [Table of Contents](#table-of-contents) ] - -## Keys - -This module contains the functionality to generate transparent and shielded keys for Namada. - -More info _TBD_ - -[ [Table of Contents](#table-of-contents) ] - -## Rpc - -This module contains RPC queries for interacting with the chain, as well as Tx broadcasting. - -More info _TBD_ - -[ [Table of Contents](#table-of-contents) ] - -## Tx - -This module contains functionality for building and signing transactions. - -More info _TBD_ - -[ [Table of Contents](#table-of-contents) ] - -## Ledger - -This class provides functionality for interacting with `NamadaApp` for the Ledger Hardware Wallet. - -More info _TBD_ - -[ [Table of Contents](#table-of-contents) ] - -## Masp - -This module provides a few basic utilities for handling `Masp` params, as well as adding spending keys to the -wallet context. - -More info _TBD_ - -[ [Table of Contents](#table-of-contents) ] - -## Mnemonic - -This provides basic funcitonality for generating 12 or 24 word mnemonics, validating mnemonics, and generating -seeds from mnemonics. - -More info _TBD_ - -[ [Table of Contents](#table-of-contents) ] - -## Signing - -This class provides the functionality from our Rust library for signing and verifying arbitrary data. - -More info _TBD_ - -[ [Table of Contents](#table-of-contents) ] diff --git a/packages/sdk/examples/README.md b/packages/sdk/examples/README.md index a72130927..e50fd5ae7 100644 --- a/packages/sdk/examples/README.md +++ b/packages/sdk/examples/README.md @@ -2,7 +2,7 @@ ## How to run -1. In the root of the sdk package run: `yarn wasm:build:node` +1. In the root of the sdk package run: `yarn build` - this might take a while as we build wasms(web and node) in production mode 2. Run example :) ## Example commands diff --git a/packages/sdk/examples/queryBalance.ts b/packages/sdk/examples/queryBalance.ts index 48283ebee..4999456c3 100644 --- a/packages/sdk/examples/queryBalance.ts +++ b/packages/sdk/examples/queryBalance.ts @@ -1,11 +1,12 @@ -import initSync from "../src/initSync"; +import { getSdk } from "indexNode"; +import initSync from "../src/initNode"; /** * - * @param nodeUrl - * @param owner - * @param nativeToken - * @param token + * @param nodeUrl - URL of the node + * @param nativeToken - Native token of the chain + * @param owner - Address of the owner + * @param token - Token to query balance */ export const queryBalance = async ( nodeUrl: string, @@ -14,7 +15,8 @@ export const queryBalance = async ( token: string ): Promise => { try { - const sdk = initSync(nodeUrl, nativeToken); + const { cryptoMemory } = initSync(); + const sdk = await getSdk(cryptoMemory, nodeUrl, nativeToken); const [[t, a]] = await sdk.rpc.queryBalance(owner, [token]); console.log(`Balance for ${owner} - Token: ${t} - Amount: ${a}`); } catch (error) { diff --git a/packages/sdk/examples/submitTransfer.ts b/packages/sdk/examples/submitTransfer.ts index 2548dafe4..a17f473ab 100644 --- a/packages/sdk/examples/submitTransfer.ts +++ b/packages/sdk/examples/submitTransfer.ts @@ -1,6 +1,7 @@ import BigNumber from "bignumber.js"; -import initSync from "initSync"; +import { getSdk } from "indexNode"; +import initSync from "../src/initNode"; export const submitTransfer = async ( nodeUrl: string, @@ -35,7 +36,8 @@ export const submitTransfer = async ( }; try { - const sdk = initSync(nodeUrl, nativeToken); + const { cryptoMemory } = initSync(); + const sdk = await getSdk(cryptoMemory, nodeUrl, nativeToken); console.log("Revealing public key..."); await sdk.tx.revealPk(signingKey, txMsgValue); diff --git a/packages/sdk/jsdoc2md.json b/packages/sdk/jsdoc2md.json deleted file mode 100644 index 260e17008..000000000 --- a/packages/sdk/jsdoc2md.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "source": { - "includePattern": ".+\\.ts(doc|x)?$", - "excludePattern": ".+\\.(test|spec).ts" - }, - "plugins": ["plugins/markdown", "../../node_modules/jsdoc-babel"], - "babel": { - "extensions": ["ts"], - "ignore": ["**/*.(test|spec).ts"], - "babelrc": false, - "presets": [ - ["@babel/preset-env", { "targets": { "node": true } }], - "@babel/preset-typescript" - ], - "plugins": [ - "@babel/proposal-class-properties", - "@babel/proposal-object-rest-spread" - ] - } -} diff --git a/packages/sdk/package.json b/packages/sdk/package.json index fbf2a9e77..fedf994fe 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -2,25 +2,58 @@ "name": "@namada/sdk", "version": "0.2.4", "description": "Namada SDK package", - "main": "dist/index.js", - "types": "dist/index.d.ts", + "exports": { + "./web": { + "import": "./dist/web/sdk/src/indexWeb.js", + "types": "./dist/web/sdk/src/indexWeb.d.ts" + }, + "./web-init": { + "import": "./dist/web/sdk/src/initWeb.js", + "types": "./dist/web/sdk/src/initWeb.d.ts" + }, + "./node": { + "require": "./dist/node/sdk/src/indexNode.js", + "types": "./dist/node/sdk/src/indexNode.d.ts" + }, + "./node-init": { + "require": "./dist/node/sdk/src/initNode.js", + "types": "./dist/node/sdk/src/initNode.d.ts" + } + }, "repository": "https://github.com/anoma/namada-interface/", "author": "Heliax Dev ", "license": "MIT", + "scriptsComments": { + "prepublish": "We make focused install to make sure that we specified all required dependencies", + "wasm:node:cp": "We need to copy wasm to the shared in dist folder, so it can be imported correctly in node" + }, "scripts": { + "prepublish": "yarn workspaces focus @namada/sdk && yarn build", + "release": "yarn prepublish && release-it --verbose --ci", + "release:dry-run": "yarn prepublish && release-it --verbose --dry-run --ci", + "release:no-npm": "yarn prepublish && release-it --verbose --no-npm.publish --ci", + "prebuild": "rimraf ./dist", + "wasm:node:cp": "cp -r ../shared/src/shared/*.wasm ./dist/node/shared/src/shared && cp -r ../crypto/src/crypto/*.wasm ./dist/node/crypto/src/crypto", + "wasm:web:cp": "cp -r ../shared/src/shared/*.wasm ./dist && cp -r ../crypto/src/crypto/*.wasm ./dist", + "wasm:web:rename": "mv ./dist/shared_bg.wasm ./dist/shared.namada.wasm && mv ./dist/crypto_bg.wasm ./dist/crypto.namada.wasm", + "build:web": "yarn wasm:build && tspc -p tsconfig.web.json && yarn wasm:web:cp && yarn wasm:web:rename", + "build:node": "yarn wasm:build:node && tspc -p tsconfig.node.json && yarn wasm:node:cp", + "build": "yarn prebuild && yarn build:web && yarn build:node", "example": "ts-node -r tsconfig-paths/register ./examples/index.ts", "lint": "eslint src --ext .ts,.tsx", - "lint:fix": "yarn lint -- --fix", + "lint:fix": "yarn lint --fix", "lint:ci": "yarn lint --max-warnings 0", - "wasm:build": "node ./scripts/build.js --release", - "wasm:build:multicore": "node ./scripts/build.js --release --multicore", - "wasm:build:dev": "node ./scripts/build.js", - "wasm:build:dev:multicore": "node ./scripts/build.js --multicore", - "wasm:build:node": "./scripts/build-node.sh", - "build:docs": "npx jsdoc2md --files ./src/**/*.ts --configure ./jsdoc2md.json > ./docs/api.md", - "test": "./scripts/build-node.sh && yarn jest", - "test:cov": "./scripts/build-node.sh && yarn jest --coverage", - "test:watch": "./scripts/build-node.sh && yarn jest --watchAll=true", + "wasm:build": "node ./scripts/build.cjs --release", + "wasm:build:multicore": "node ./scripts/build.cjs --release --multicore", + "wasm:build:dev": "node ./scripts/build.cjs", + "wasm:build:dev:multicore": "node ./scripts/build.cjs --multicore", + "wasm:build:node": "node ./scripts/build.cjs --node --release", + "wasm:build:node:dev": "node ./scripts/build.cjs --node", + "wasm:build:node:dev:multicore": "node ./scripts/build.cjs --node --multicore", + "build:docs": "typedoc --plugin typedoc-plugin-markdown --out docs src/index.ts", + "test": "yarn wasm:build:node:dev && yarn jest", + "test:cov": "yarn wasm:build:node:dev && yarn jest --coverage", + "test:watch": "yarn wasm:build:node:dev && yarn jest --watchAll=true", "test:ci": "jest" }, "dependencies": { @@ -29,13 +62,10 @@ "@ledgerhq/hw-transport": "^6.30.0", "@ledgerhq/hw-transport-webhid": "^6.28.0", "@ledgerhq/hw-transport-webusb": "^6.28.0", - "@namada/chains": "0.2.1", - "@namada/crypto": "0.2.1", - "@namada/shared": "0.2.1", - "@namada/types": "0.2.1", - "@namada/utils": "0.2.1", "@zondax/ledger-namada": "^0.0.4", "bignumber.js": "^9.1.1", + "buffer": "^6.0.3", + "slip44": "^3.0.18", "typescript": "^5.1.3" }, "devDependencies": { @@ -62,7 +92,13 @@ "rimraf": "^5.0.5", "ts-jest": "^29.0.1", "ts-node": "^10.9.1", - "tsconfig-paths": "^4.2.0" + "ts-patch": "^3.1.2", + "tsconfig-paths": "^4.2.0", + "typedoc": "^0.25.12", + "typedoc-plugin-markdown": "^3.17.1", + "typescript-transform-paths": "^3.4.7", + "webpack": "^5.90.3", + "webpack-cli": "^5.1.4" }, "files": [ "dist/**/*.{js,ts,wasm}" diff --git a/packages/sdk/scripts/build-node.sh b/packages/sdk/scripts/build-node.sh deleted file mode 100755 index 4a05807f0..000000000 --- a/packages/sdk/scripts/build-node.sh +++ /dev/null @@ -1,7 +0,0 @@ -#!/bin/sh - -SCRIPT_DIR=$(cd "$(dirname "$0")"; pwd -P) -PACKAGES_PATH="../../../packages" - -cd "${SCRIPT_DIR}/${PACKAGES_PATH}/crypto" && yarn wasm:build:node -cd "${SCRIPT_DIR}/${PACKAGES_PATH}/shared" && yarn wasm:build:node diff --git a/packages/sdk/scripts/build.js b/packages/sdk/scripts/build.cjs similarity index 66% rename from packages/sdk/scripts/build.js rename to packages/sdk/scripts/build.cjs index cad439c9c..614adbaa4 100644 --- a/packages/sdk/scripts/build.js +++ b/packages/sdk/scripts/build.cjs @@ -5,11 +5,14 @@ const strippedArgs = new Set(args.map((arg) => arg.replace("--", ""))); const isRelease = strippedArgs.has("release"); const isMulticore = strippedArgs.has("multicore"); -const taskShared = `wasm:build${!isRelease ? ":dev" : ""}${ - isMulticore ? ":multicore" : "" -}`; +const isNode = strippedArgs.has("node"); +const taskShared = `wasm:build${isNode ? ":node" : ""}${ + !isRelease ? ":dev" : "" +}${isMulticore ? ":multicore" : ""}`; -const taskCrypto = `wasm:build${!isRelease ? ":dev" : ""}`; +const taskCrypto = `wasm:build${isNode ? ":node" : ""}${ + !isRelease ? ":dev" : "" +}`; spawnSync("yarn", ["workspace", "@namada/crypto", "run", taskCrypto], { stdio: "inherit", diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.ts index 71792f244..7bda8db6b 100644 --- a/packages/sdk/src/index.ts +++ b/packages/sdk/src/index.ts @@ -1,23 +1,6 @@ -import initAsync from "./initAsync"; -import { Sdk as SDK } from "./sdk"; - // Make Ledger available for direct-import as it is not dependent on Sdk initialization export * from "./ledger"; -// Wrap Sdk export so initialization can happen outside of -// class definition (for running tests using wasm built for Node JS) -export const Sdk = { - /** - * Initialize Sdk for web applications - * @param {string} url - node url - * @param {string} token - native token address - * @returns {Promise} - Sdk instance - */ - init: (url: string, token?: string): Promise => { - return initAsync(url, token); - }, -}; - // Export types export type { Address, ShieldedKeys, TransparentKeys } from "./keys"; export type { @@ -25,12 +8,17 @@ export type { Bonds, DelegationTotals, DelegatorsVotes, + Rpc, StakingPositions, StakingTotals, Unbonds, } from "./rpc"; -export { EncodedTx, SignedTx } from "./tx"; -// Export init functions for direct usage -export { default as initAsync } from "./initAsync"; -export { default as initSync } from "./initSync"; +export { EncodedTx, SignedTx, TxType, TxTypeLabel } from "./tx"; +export type { SupportedTx } from "./tx"; + +export { Sdk } from "./sdk"; + +export { publicKeyToBech32 } from "./keys"; + +export { PhraseSize } from "./mnemonic"; diff --git a/packages/sdk/src/indexNode.ts b/packages/sdk/src/indexNode.ts new file mode 100644 index 000000000..447e1f4eb --- /dev/null +++ b/packages/sdk/src/indexNode.ts @@ -0,0 +1,42 @@ +import { Query as QueryWasm, Sdk as SdkWasm } from "@namada/shared"; +import { webcrypto } from "node:crypto"; +import { Sdk } from "./sdk"; +export * from "./index"; +export * from "./utils"; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +(globalThis as any).crypto = webcrypto; + +/** + * Get the SDK instance + * @async + * @param cryptoMemory - WebAssembly.Memory of crypto package + * @param url - URL of the node + * @param storagePath - Path to store wallet files + * @param [token] - Native token of the chain + * @throws {Error} - Unable to Query native token + * @returns - Sdk instance + */ +export function getSdk( + cryptoMemory: WebAssembly.Memory, + url: string, + storagePath: string, + token: string +): Sdk { + // Instantiate QueryWasm + const query = new QueryWasm(url); + + // Instantiate SdkWasm + const sdk = new SdkWasm(url, token, storagePath); + return new Sdk(sdk, query, cryptoMemory, url, token); +} + +/** + * Query native token from the node + * @async + * @param rpc - URL of the node + * @returns + */ +export async function getNativeToken(rpc: string): Promise { + return await new QueryWasm(rpc).query_native_token(); +} diff --git a/packages/sdk/src/indexWeb.ts b/packages/sdk/src/indexWeb.ts new file mode 100644 index 000000000..4e7214822 --- /dev/null +++ b/packages/sdk/src/indexWeb.ts @@ -0,0 +1,38 @@ +import { Query as QueryWasm, Sdk as SdkWasm } from "@namada/shared"; +import { Sdk } from "./index"; +export * from "./index"; +export * from "./utils"; + +/** + * Get the SDK instance + * @async + * @param cryptoMemory - WebAssembly.Memory of crypto package + * @param url - URL of the node + * @param dbName - Name of the database for the serialized wallet + * @param [token] - Native token of the chain + * @throws {Error} - Unable to Query native token + * @returns - Sdk instance + */ +export function getSdk( + cryptoMemory: WebAssembly.Memory, + url: string, + dbName: string, + token: string +): Sdk { + // Instantiate QueryWasm + const query = new QueryWasm(url); + + // Instantiate SdkWasm + const sdk = new SdkWasm(url, token, dbName); + return new Sdk(sdk, query, cryptoMemory, url, token); +} + +/** + * Query native token from the node + * @async + * @param rpc - URL of the node + * @returns + */ +export async function getNativeToken(rpc: string): Promise { + return await new QueryWasm(rpc).query_native_token(); +} diff --git a/packages/sdk/src/initAsync.ts b/packages/sdk/src/initAsync.ts deleted file mode 100644 index d8d073f2f..000000000 --- a/packages/sdk/src/initAsync.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { init as initCrypto } from "@namada/crypto/src/init"; -import { Query as QueryWasm, Sdk as SdkWasm } from "@namada/shared"; -import { init as initShared } from "@namada/shared/src/init"; - -import { Sdk } from "sdk"; - -/** - * Returns an initialized Sdk class asynchronously. This is required to use - * this library in web applications. - * @async - * @param {string} url - RPC url for use with SDK - * @param {string} [token] - Native token of the target chain, if not provided, an attempt to query it will be made - * @returns {Sdk} Instance of initialized Sdk class - */ -export default async function initAsync( - url: string, - token?: string -): Promise { - // Load and initialize shared wasm - const sharedWasm = await fetch("shared.namada.wasm").then((wasm) => - wasm.arrayBuffer() - ); - await initShared(sharedWasm); - - // Load and initialize crypto wasm - const cryptoWasm = await fetch("crypto.namada.wasm").then((wasm) => - wasm.arrayBuffer() - ); - const { memory: cryptoMemory } = await initCrypto(cryptoWasm); - - // Instantiate QueryWasm - const query = new QueryWasm(url); - - let nativeToken: string = ""; - - // Token not provided, make an attempt to query it - if (!token) { - try { - const result = await query.query_native_token(); - nativeToken = result; - } catch (e) { - // Raise exception if query is required but native token cannot be determined - throw new Error(`Unable to Query native token! ${e}`); - } - } - - // Instantiate SdkWasm - const sdk = new SdkWasm(url, nativeToken); - return new Sdk(sdk, query, cryptoMemory, url, nativeToken); -} diff --git a/packages/sdk/src/initNode.ts b/packages/sdk/src/initNode.ts new file mode 100644 index 000000000..fe365c80c --- /dev/null +++ b/packages/sdk/src/initNode.ts @@ -0,0 +1,30 @@ +import * as crypto from "@namada/crypto"; +// We have to use relative improts here othewise ts-patch is getting confused and produces wrong paths after compialtion +import { initThreadPool } from "../../shared/src/init-thread-pool"; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const cryptoMemory = (crypto as any).__wasm.memory; + +/** + * Initialize the SDK memory + * @returns - The SDK crypto memory + */ +export default function init(): { + cryptoMemory: WebAssembly.Memory; +} { + return { cryptoMemory }; +} + +/** + * Initialize the SDK memory, with multicore support. + * If you built wasm without multicore support, this will work as regular init. + * @async + * @returns - The SDK crypto memory + */ +export async function initMulticore(): Promise<{ + cryptoMemory: WebAssembly.Memory; +}> { + const res = init(); + await initThreadPool(navigator.hardwareConcurrency); + return res; +} diff --git a/packages/sdk/src/initSync.ts b/packages/sdk/src/initSync.ts deleted file mode 100644 index 41bf806f3..000000000 --- a/packages/sdk/src/initSync.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { Query as QueryWasm, Sdk as SdkWasm } from "@namada/shared"; -import { Sdk } from "./sdk"; - -/* eslint-disable @typescript-eslint/no-var-requires */ -const cryptoMemory = require("@namada/crypto").__wasm.memory; - -/** - * Initialize SDK for Node JS environments - * @param {string} url - URL of the node - * @param {string} nativeToken - Address of the native token - * @returns {Sdk} SDK instance - */ -export default function initSync(url: string, nativeToken: string): Sdk { - const sdk = new SdkWasm(url, nativeToken); - const query = new QueryWasm(url); - return new Sdk(sdk, query, cryptoMemory, url, nativeToken); -} diff --git a/packages/sdk/src/initWeb.ts b/packages/sdk/src/initWeb.ts new file mode 100644 index 000000000..aeec903f3 --- /dev/null +++ b/packages/sdk/src/initWeb.ts @@ -0,0 +1,43 @@ +// We have to use relative improts here othewise ts-patch is getting confused and produces wrong paths after compialtion +import { init as initCrypto } from "../../crypto/src/init"; +import { init as initShared } from "../../shared/src/init"; +import { initThreadPool } from "../../shared/src/init-thread-pool"; + +/** + * Initialize the SDK memory + * @async + * @returns + + - The SDK crypto memory + */ +export default async function init(): Promise<{ + cryptoMemory: WebAssembly.Memory; +}> { + // Load and initialize shared wasm + const sharedWasm = await fetch("shared.namada.wasm").then((wasm) => + wasm.arrayBuffer() + ); + await initShared(sharedWasm); + + // Load and initialize crypto wasm + const cryptoWasm = await fetch("crypto.namada.wasm").then((wasm) => + wasm.arrayBuffer() + ); + const { memory: cryptoMemory } = await initCrypto(cryptoWasm); + + return { cryptoMemory }; +} + +/** + * Initialize the SDK memory, with multicore support. + * If you built wasm without multicore support, this will work as regular init. + * @async + * @returns - The SDK crypto memory + */ +export async function initMulticore(): Promise<{ + cryptoMemory: WebAssembly.Memory; +}> { + const res = await init(); + await initThreadPool(navigator.hardwareConcurrency); + return res; +} diff --git a/packages/sdk/src/keys/keys.ts b/packages/sdk/src/keys/keys.ts index 6bfabc57d..eb18137a3 100644 --- a/packages/sdk/src/keys/keys.ts +++ b/packages/sdk/src/keys/keys.ts @@ -11,9 +11,10 @@ import { ExtendedSpendingKey, ExtendedViewingKey, PaymentAddress, + public_key_to_bech32, } from "@namada/shared"; import { Bip44Path } from "@namada/types"; -import { makeBip44PathArray, makeSaplingPathArray } from "@namada/utils"; +import { makeBip44PathArray, makeSaplingPathArray } from "../utils"; import { Address, ShieldedKeys, TransparentKeys } from "./types"; const DEFAULT_PATH: Bip44Path = { @@ -22,16 +23,19 @@ const DEFAULT_PATH: Bip44Path = { index: 0, }; +/** + * Namespace for key related functions + */ export class Keys { /** - * @param {WebAssembly.Memory} cryptoMemory - Memory accessor for crypto lib + * @param cryptoMemory - Memory accessor for crypto lib */ constructor(protected readonly cryptoMemory: WebAssembly.Memory) {} /** * Get address and public key from private key - * @param {string} privateKey - Private key - * @returns {Address} Address and public key + * @param privateKey - Private key + * @returns Address and public key */ getAddress(privateKey: string): Address { const addr = new AddressWasm(privateKey); @@ -46,8 +50,8 @@ export class Keys { /** * Get transparent keys and address from private key - * @param {string} privateKey - Private key - * @returns {TransparentKeys} Keys and address + * @param privateKey - Private key + * @returns Keys and address */ fromPrivateKey(privateKey: string): TransparentKeys { return { @@ -58,10 +62,10 @@ export class Keys { /** * Derive transparent keys and address from a mnemonic and path - * @param {string} phrase - Mnemonic phrase - * @param {Bip44Path} [path] - Bip44 path object - * @param {string} [passphrase] - Bip39 passphrase - * @returns {TransparentKeys} Keys and address + * @param phrase - Mnemonic phrase + * @param [path] - Bip44 path object + * @param [passphrase] - Bip39 passphrase + * @returns Keys and address */ deriveFromMnemonic( phrase: string, @@ -70,9 +74,9 @@ export class Keys { ): TransparentKeys { const mnemonic = MnemonicWasm.from_phrase(phrase); const passphrasePtr = - typeof passphrase === "string" - ? new StringPointer(passphrase) - : undefined; + typeof passphrase === "string" ? + new StringPointer(passphrase) + : undefined; const seedPtr = mnemonic.to_seed(passphrasePtr); const hdWallet = new HDWallet(seedPtr); const bip44Path = makeBip44PathArray(chains.namada.bip44.coinType, path); @@ -97,9 +101,9 @@ export class Keys { /** * Derive transparent keys and address from a seed and path - * @param {Uint8Array} seed - Seed - * @param {Bip44Path} [path] - Bip44 path object - * @returns {TransparentKeys} Keys and address + * @param seed - Seed + * @param [path] - Bip44 path object + * @returns Keys and address */ deriveFromSeed( seed: Uint8Array, @@ -127,11 +131,11 @@ export class Keys { /** * Derive shielded keys and address from a seed and path - * @param {Uint8Array} seed - Seed - * @param {Bip44Path} [path] - Bip44 path object - * @returns {ShieldedKeys} Shielded keys and address + * @param seed - Seed + * @param [path] - Bip44 path object + * @returns Shielded keys and address */ - deriveShielded( + deriveShieldedFromSeed( seed: Uint8Array, path: Bip44Path = DEFAULT_PATH ): ShieldedKeys { @@ -164,3 +168,8 @@ export class Keys { }; } } + +//TODO: think where to put this function +export const publicKeyToBech32 = (publicKey: Uint8Array): string => { + return public_key_to_bech32(publicKey); +}; diff --git a/packages/sdk/src/ledger.ts b/packages/sdk/src/ledger.ts index 6119d5f4d..8d1edd7b6 100644 --- a/packages/sdk/src/ledger.ts +++ b/packages/sdk/src/ledger.ts @@ -10,8 +10,7 @@ import { ResponseSign, ResponseVersion, } from "@zondax/ledger-namada"; - -import { makeBip44Path } from "@namada/utils"; +import { makeBip44Path } from "./utils"; const { coinType } = chains.namada.bip44; @@ -24,7 +23,7 @@ export type LedgerStatus = { /** * Initialize USB transport * @async - * @returns {Transport} Transport object + * @returns Transport object */ export const initLedgerUSBTransport = async (): Promise => { return await TransportUSB.create(); @@ -33,7 +32,7 @@ export const initLedgerUSBTransport = async (): Promise => { /** * Initialize HID transport * @async - * @returns {Transport} Transport object + * @returns Transport object */ export const initLedgerHIDTransport = async (): Promise => { return await TransportHID.create(); @@ -50,15 +49,15 @@ export const DEFAULT_LEDGER_BIP44_PATH = makeBip44Path(coinType, { */ export class Ledger { /** - * @param {NamadaApp} namadaApp - Inititalized NamadaApp class from Zondax package + * @param namadaApp - Inititalized NamadaApp class from Zondax package */ private constructor(public readonly namadaApp: NamadaApp) {} /** * Initialize and return Ledger class instance with initialized Transport * @async - * @param {Transport} [transport] Ledger transport - * @returns {Ledger} Ledger class instance + * @param [transport] Ledger transport + * @returns Ledger class instance */ static async init(transport?: Transport): Promise { const initializedTransport = transport ?? (await initLedgerUSBTransport()); @@ -76,7 +75,7 @@ export class Ledger { * Return status and version info of initialized NamadaApp. * Throw exception if app is not initialized. * @async - * @returns {LedgerStatus} Version and info of NamadaApp + * @returns Version and info of NamadaApp */ public async status(): Promise { const version = await this.namadaApp.getVersion(); @@ -92,8 +91,8 @@ export class Ledger { * Get address and public key associated with optional path, otherwise, use default path * Throw exception if app is not initialized. * @async - * @param {string} [path] Bip44 path for deriving key - * @returns {AddressAndPublicKey} Address and public key + * @param [path] Bip44 path for deriving key + * @returns Address and public key */ public async getAddressAndPublicKey( path: string = DEFAULT_LEDGER_BIP44_PATH @@ -113,8 +112,8 @@ export class Ledger { * Prompt user to get address and public key associated with optional path, otherwise, use default path. * Throw exception if app is not initialized. * @async - * @param {string} [path] Bip44 path for deriving key - * @returns {AddressAndPublicKey} Address and public key + * @param [path] Bip44 path for deriving key + * @returns Address and public key */ public async showAddressAndPublicKey( path: string = DEFAULT_LEDGER_BIP44_PATH @@ -138,9 +137,9 @@ export class Ledger { * Sign tx bytes with the key associated with the provided (or default) path. * Throw exception if app is not initialized. * @async - * @param {Uint8Array} tx - tx data blob to sign - * @param {string} [path] Bip44 path for signing account - * @returns {ResponseSign} Response signature + * @param tx - tx data blob to sign + * @param [path] Bip44 path for signing account + * @returns Response signature */ public async sign( tx: Uint8Array, @@ -155,7 +154,7 @@ export class Ledger { * Query status to determine if device has thrown an error. * Throw exception if app is not initialized. * @async - * @returns {string} Error message if error is found + * @returns Error message if error is found */ public async queryErrors(): Promise { const { @@ -172,7 +171,7 @@ export class Ledger { * Close the initialized transport, which may be needed if Ledger needs to be reinitialized due to error state * Throw exception if app is not initialized. * @async - * @returns {void} + * @returns void */ public async closeTransport(): Promise { return await this.namadaApp.transport.close(); diff --git a/packages/sdk/src/masp.ts b/packages/sdk/src/masp.ts index 458c55ee4..d9d9459c1 100644 --- a/packages/sdk/src/masp.ts +++ b/packages/sdk/src/masp.ts @@ -5,14 +5,14 @@ import { Sdk as SdkWasm } from "@namada/shared"; */ export class Masp { /** - * @param {SdkWasm} sdk - Instance of Sdk struct from wasm lib + * @param sdk - Instance of Sdk struct from wasm lib */ constructor(protected readonly sdk: SdkWasm) {} /** * Check if SDK has MASP parameters loaded * @async - * @returns {Promise} True if MASP parameters are loaded + * @returns True if MASP parameters are loaded */ async hasMaspParams(): Promise { return await SdkWasm.has_masp_params(); @@ -21,7 +21,7 @@ export class Masp { /** * Fetch MASP parameters and store them in SDK * @async - * @returns {void} + * @returns void */ async fetchAndStoreMaspParams(): Promise { return await SdkWasm.fetch_and_store_masp_params(); @@ -29,19 +29,20 @@ export class Masp { /** * Load stored MASP params + * @param pathOrDbName - Path to stored MASP params(nodejs) or name of the database(browser) * @async - * @returns {void} + * @returns void */ - async loadMaspParams(): Promise { - return await this.sdk.load_masp_params(); + async loadMaspParams(pathOrDbName: string): Promise { + return await this.sdk.load_masp_params(pathOrDbName); } /** * Add spending key to SDK wallet * @async - * @param {string} xsk - extended spending key - * @param {string} alias - alias for the key - * @returns {Promise} + * @param xsk - extended spending key + * @param alias - alias for the key + * @returns void */ async addSpendingKey(xsk: string, alias: string): Promise { return await this.sdk.add_spending_key(xsk, alias); diff --git a/packages/sdk/src/mnemonic.ts b/packages/sdk/src/mnemonic.ts index b976e8197..2932c1882 100644 --- a/packages/sdk/src/mnemonic.ts +++ b/packages/sdk/src/mnemonic.ts @@ -6,20 +6,22 @@ import { readVecU8Pointer, } from "@namada/crypto"; +export { PhraseSize } from "@namada/crypto"; + /** * Class for accessing mnemonic functionality from wasm */ export class Mnemonic { /** - * @param {WebAssembly.Memory} cryptoMemory - Memory accessor for crypto lib + * @param cryptoMemory - Memory accessor for crypto lib */ constructor(protected readonly cryptoMemory: WebAssembly.Memory) {} /** * Generate a new 12 or 24 word mnemonic * @async - * @param {PhraseSize} [size] Mnemonic length - * @returns {Promise} Promise that resolves to array of words + * @param [size] Mnemonic length + * @returns Promise that resolves to array of words */ async generate(size: PhraseSize = PhraseSize.N12): Promise { const mnemonic = new MnemonicWasm(size); @@ -35,9 +37,9 @@ export class Mnemonic { /** * Convert mnemonic to seed bytes - * @param {string} phrase - Mnemonic phrase - * @param {string} [passphrase] Bip39 passphrase - * @returns {Uint8Array} Seed bytes + * @param phrase - Mnemonic phrase + * @param [passphrase] Bip39 passphrase + * @returns Seed bytes */ toSeed(phrase: string, passphrase?: string): Uint8Array { const mnemonic = MnemonicWasm.from_phrase(phrase); @@ -54,15 +56,18 @@ export class Mnemonic { /** * Validate a mnemonic string, raise an exception providing reason * for failure if invalid, otherwise return nothing - * @param {string} phrase - Mnemonic phrase - * @returns {void} + * @param phrase - Mnemonic phrase + * @returns Object with validation result and error message if invalid */ - validateMnemonic(phrase: string): void { + validateMnemonic(phrase: string): { isValid: boolean; error?: string } { + const isValid = MnemonicWasm.validate(phrase); try { MnemonicWasm.from_phrase(phrase); + + return { isValid }; } catch (e) { // Throw exception in order to provide reason to client - throw new Error(`${e}`); + return { isValid, error: `${e}` }; } } } diff --git a/packages/sdk/src/rpc/rpc.ts b/packages/sdk/src/rpc/rpc.ts index 5de103800..aaa7430e5 100644 --- a/packages/sdk/src/rpc/rpc.ts +++ b/packages/sdk/src/rpc/rpc.ts @@ -25,8 +25,8 @@ import { */ export class Rpc { /** - * @param {SdkWasm} sdk - Instance of Sdk struct from wasm lib - * @param {QueryWasm} query - Instance of Query struct from wasm lib + * @param sdk - Instance of Sdk struct from wasm lib + * @param query - Instance of Query struct from wasm lib */ constructor( protected readonly sdk: SdkWasm, @@ -36,9 +36,9 @@ export class Rpc { /** * Query balances from chain * @async - * @param {string} owner - Owner address - * @param {string[]} tokens - Array of token addresses - * @returns {Balance} [[tokenAddress, amount]] + * @param owner - Owner address + * @param tokens - Array of token addresses + * @returns [[tokenAddress, amount]] */ async queryBalance(owner: string, tokens: string[]): Promise { return await this.query.query_balance(owner, tokens); @@ -47,7 +47,7 @@ export class Rpc { /** * Query native token from chain * @async - * @returns {string} Address of native token + * @returns Address of native token */ async queryNativeToken(): Promise { return await this.query.query_native_token(); @@ -57,8 +57,8 @@ export class Rpc { * Query public key * Return string of public key if it has been revealed on chain, otherwise, return null * @async - * @param {string} address - Address to query - * @returns {string|null} String of public key if found + * @param address - Address to query + * @returns String of public key if found */ async queryPublicKey(address: string): Promise { const pk = await this.query.query_public_key(address); @@ -68,7 +68,7 @@ export class Rpc { /** * Query all validator addresses * @async - * @returns {string[]} Array of all validator addresses + * @returns Array of all validator addresses */ async queryAllValidators(): Promise { return await this.query.query_all_validator_addresses(); @@ -77,7 +77,7 @@ export class Rpc { /** * Query Proposals * @async - * @returns {Proposal[]} List of the proposals + * @returns List of the proposals */ async queryProposals(): Promise { const serializedProposals = await this.query.query_proposals(); @@ -88,9 +88,9 @@ export class Rpc { /** * Query total delegations * @async - * @param {string[]} owners - Array of owner addresses - * @param {bigint} [epoch] - delegations at epoch - * @returns {Promise} Promise resolving to total delegations + * @param owners - Array of owner addresses + * @param [epoch] - delegations at epoch + * @returns Promise resolving to total delegations */ async queryTotalDelegations( owners: string[], @@ -102,8 +102,8 @@ export class Rpc { /** * Query delegators votes * @async - * @param {bigint} proposalId - ID of the proposal - * @returns {Promise} Promise resolving to delegators votes + * @param proposalId - ID of the proposal + * @returns Promise resolving to delegators votes */ async queryDelegatorsVotes(proposalId: bigint): Promise { return await this.query.delegators_votes(proposalId); @@ -112,8 +112,8 @@ export class Rpc { /** * Query staking totals by owner addresses * @async - * @param {string[]} owners - Array of owner addresses - * @returns {Promise} Promise resolving to staking totals + * @param owners - Array of owner addresses + * @returns Promise resolving to staking totals */ async queryStakingTotals(owners: string[]): Promise { const stakingAmounts = await this.query.query_my_validators(owners); @@ -139,8 +139,8 @@ export class Rpc { /** * Query bond and unbond details by owner addresses * @async - * @param {string[]} owners - Array of owner addresses - * @returns {Promise} Promise resolving to staking positions + * @param owners - Array of owner addresses + * @returns Promise resolving to staking positions */ async queryStakingPositions(owners: string[]): Promise { const [bonds, unbonds]: [BondsResponse[], UnbondsResponse[]] = @@ -175,8 +175,8 @@ export class Rpc { /** * Query total bonds by owner address - * @param {string} owner - Owner address - * @returns {Promise} Total bonds amount + * @param owner - Owner address + * @returns Total bonds amount */ async queryTotalBonds(owner: string): Promise { return await this.query.query_total_bonds(owner); @@ -185,8 +185,8 @@ export class Rpc { /** * Query pending transactions in the signed bridge pool * @async - * @param {string[]} owners - Array of owner addresses - * @returns {Promise} Promise resolving to pending ethereum transfers + * @param owners - Array of owner addresses + * @returns Promise resolving to pending ethereum transfers */ async querySignedBridgePool(owners: string[]): Promise { return await this.query.query_signed_bridge_pool(owners); @@ -195,7 +195,7 @@ export class Rpc { /** * Query gas costs * @async - * @returns {Promise} [[tokenAddress, gasCost]] + * @returns [[tokenAddress, gasCost]] */ async queryGasCosts(): Promise { return await this.query.query_gas_costs(); @@ -204,11 +204,21 @@ export class Rpc { /** * Broadcast a Tx to the ledger * @async - * @param {SignedTx} signedTx - Transaction with signature - * @returns {void} + * @param signedTx - Transaction with signature + * @returns void */ - async broadcastTx(signedTx: SignedTx): Promise { + async broadcastTx(signedTx: SignedTx): Promise { const { txMsg, tx } = signedTx; - await this.sdk.process_tx(tx, txMsg); + return await this.sdk.process_tx(tx, txMsg); + } + + /** + * Sync the shielded context + * @async + * @param vks - Array of viewing keys + * @returns + */ + async shieldedSync(vks: string[]): Promise { + await this.query.shielded_sync(vks); } } diff --git a/packages/sdk/src/sdk.ts b/packages/sdk/src/sdk.ts index d22e3abf7..b49adbfba 100644 --- a/packages/sdk/src/sdk.ts +++ b/packages/sdk/src/sdk.ts @@ -13,22 +13,22 @@ import { Tx } from "./tx"; */ export class Sdk { /** - * @param {SdkWasm} sdk - Instance of Sdk struct from wasm lib - * @param {QueryWasm} query - Instance of Query struct from wasm lib - * @param {WebAssembly.Memory} cryptoMemory - Memory accessor for crypto lib - * @param {string} url - RPC url - * @param {string} nativeToken - Address of chain's native token + * @param sdk - Instance of Sdk struct from wasm lib + * @param query - Instance of Query struct from wasm lib + * @param cryptoMemory - Memory accessor for crypto lib + * @param url - RPC url + * @param nativeToken - Address of chain's native token */ constructor( protected readonly sdk: SdkWasm, protected readonly query: QueryWasm, - protected readonly cryptoMemory: WebAssembly.Memory, + public readonly cryptoMemory: WebAssembly.Memory, public readonly url: string, public readonly nativeToken: string ) {} /** * Return initialized Rpc class - * @returns {Rpc} Namada RPC client + * @returns Namada RPC client */ getRpc(): Rpc { return new Rpc(this.sdk, this.query); @@ -36,7 +36,7 @@ export class Sdk { /** * Return initialized Tx class - * @returns {Tx} Tx-related functionality + * @returns Tx-related functionality */ getTx(): Tx { return new Tx(this.sdk); @@ -44,7 +44,7 @@ export class Sdk { /** * Return initialized Mnemonic class - * @returns {Mnemonic} mnemonic-related functionality + * @returns mnemonic-related functionality */ getMnemonic(): Mnemonic { return new Mnemonic(this.cryptoMemory); @@ -52,7 +52,7 @@ export class Sdk { /** * Return initialized Keys class - * @returns {Keys} key-related functionality + * @returns key-related functionality */ getKeys(): Keys { return new Keys(this.cryptoMemory); @@ -60,7 +60,7 @@ export class Sdk { /** * Return initialized Signing class - * @returns {Signing} Non-Tx signing functionality + * @returns Non-Tx signing functionality */ getSigning(): Signing { return new Signing(this.sdk); @@ -68,7 +68,7 @@ export class Sdk { /** * Return initialized Masp class - * @returns {Masp} Masp utilities for handling params + * @returns Masp utilities for handling params */ getMasp(): Masp { return new Masp(this.sdk); @@ -77,8 +77,8 @@ export class Sdk { /** * Intialize Ledger class for use with NamadaApp * @async - * @param {Transport} [transport] - Will default to USB transport if not specified - * @returns {Ledger} Class for interacting with NamadaApp for Ledger Hardware Wallets + * @param [transport] - Will default to USB transport if not specified + * @returns Class for interacting with NamadaApp for Ledger Hardware Wallets */ async initLedger(transport?: Transport): Promise { return await Ledger.init(transport); @@ -86,7 +86,7 @@ export class Sdk { /** * Define rpc getter to use with destructuring assignment - * @returns {Rpc} rpc client + * @returns rpc client */ get rpc(): Rpc { return this.getRpc(); @@ -94,7 +94,7 @@ export class Sdk { /** * Define tx getter to use with destructuring assignment - * @returns {Tx} tx-related functionality + * @returns tx-related functionality */ get tx(): Tx { return this.getTx(); @@ -102,7 +102,7 @@ export class Sdk { /** * Define mnemonic getter to use with destructuring assignment - * @returns {Mnemonic} mnemonic-related functionality + * @returns mnemonic-related functionality */ get mnemonic(): Mnemonic { return this.getMnemonic(); @@ -110,7 +110,7 @@ export class Sdk { /** * Define keys getter to use with destructuring assignment - * @returns {Keys} key-related functionality + * @returns key-related functionality */ get keys(): Keys { return this.getKeys(); @@ -118,7 +118,7 @@ export class Sdk { /** * Define signing getter to use with destructuring assignment - * @returns {Signing} Non-Tx signing functionality + * @returns Non-Tx signing functionality */ get signing(): Signing { return this.getSigning(); @@ -126,7 +126,7 @@ export class Sdk { /** * Define signing getter to use with destructuring assignment - * @returns {Masp} Masp utilities for handling params + * @returns Masp utilities for handling params */ get masp(): Masp { return this.getMasp(); diff --git a/packages/sdk/src/signing.ts b/packages/sdk/src/signing.ts index 5d03a1965..9cf7d1f57 100644 --- a/packages/sdk/src/signing.ts +++ b/packages/sdk/src/signing.ts @@ -6,13 +6,17 @@ type Signature = [string, string]; * Non-Tx signing functions */ export class Signing { + /** + * Signing constructor + * @param sdk - Instance of Sdk struct from wasm lib + */ constructor(protected readonly sdk: SdkWasm) {} /** * Sign arbitrary data - * @param {string} signingKey - private key - * @param {string} data - data to sign - * @returns {Signature} hash and signature + * @param signingKey - private key + * @param data - data to sign + * @returns hash and signature */ signArbitrary(signingKey: string, data: string): Signature { return this.sdk.sign_arbitrary(signingKey, data); @@ -20,10 +24,10 @@ export class Signing { /** * Verify arbitrary signature. Will throw an error if the signature is invalid - * @param {string} publicKey - public key to verify with - * @param {string} hash - signed hash - * @param {signature} signature - Hex-encoded signature - * @returns {void} + * @param publicKey - public key to verify with + * @param hash - signed hash + * @param signature - Hex-encoded signature + * @returns void */ verifyArbitrary(publicKey: string, hash: string, signature: string): void { return this.sdk.verify_arbitrary(publicKey, hash, signature); diff --git a/packages/sdk/src/tests/initSdk.ts b/packages/sdk/src/tests/initSdk.ts index ebf8bbe9c..bf3716f88 100644 --- a/packages/sdk/src/tests/initSdk.ts +++ b/packages/sdk/src/tests/initSdk.ts @@ -1,8 +1,13 @@ -import initSync from "initSync"; +import { Query as QueryWasm, Sdk as SdkWasm } from "@namada/shared"; +import init from "../initNode"; import { Sdk } from "../sdk"; import { NATIVE_TOKEN as nativeToken, RPC_URL as rpcUrl } from "./data"; // Simplified wrapper to handle initializing SDK for tests export const initSdk = (): Sdk => { - return initSync(rpcUrl, nativeToken); + const { cryptoMemory } = init(); + const query = new QueryWasm(rpcUrl); + const sdk = new SdkWasm(rpcUrl, nativeToken, "some db name"); + + return new Sdk(sdk, query, cryptoMemory, rpcUrl, nativeToken); }; diff --git a/packages/sdk/src/tests/keys.test.ts b/packages/sdk/src/tests/keys.test.ts index 637ee4bdd..191d53ab1 100644 --- a/packages/sdk/src/tests/keys.test.ts +++ b/packages/sdk/src/tests/keys.test.ts @@ -21,7 +21,8 @@ describe("Keys", () => { const { keys, mnemonic } = initSdk(); const seed = mnemonic.toSeed(mnemonic1); - const { address, viewingKey, spendingKey } = keys.deriveShielded(seed); + const { address, viewingKey, spendingKey } = + keys.deriveShieldedFromSeed(seed); expect(address).toBe(shieldedAccount.paymentAddress); expect(viewingKey).toBe(shieldedAccount.viewingKey); diff --git a/packages/sdk/src/tx/tx.ts b/packages/sdk/src/tx/tx.ts index 70ad2660a..7b1df2fde 100644 --- a/packages/sdk/src/tx/tx.ts +++ b/packages/sdk/src/tx/tx.ts @@ -27,18 +27,18 @@ import { EncodedTx, SignedTx } from "./types"; */ export class Tx { /** - * @param {SdkWasm} sdk - Instance of Sdk struct from wasm lib + * @param sdk - Instance of Sdk struct from wasm lib */ constructor(protected readonly sdk: SdkWasm) {} /** * Build a transaction * @async - * @param {TxType} txType - type of the transaction - * @param {Uint8Array} encodedSpecificTx - encoded specific transaction - * @param {Uint8Array} encodedTx - encoded transaction - * @param {string} gasPayer - address of the gas payer - * @returns {Promise} promise that resolves to an EncodedTx + * @param txType - type of the transaction + * @param encodedSpecificTx - encoded specific transaction + * @param encodedTx - encoded transaction + * @param gasPayer - address of the gas payer + * @returns promise that resolves to an EncodedTx */ async buildTxFromSerializedArgs( txType: TxType, @@ -59,11 +59,11 @@ export class Tx { /** * Wrapper method to handle all supported Tx * @async - * @param {TxType} txType - type of the transaction - * @param {TxProps} txProps - transaction properties - * @param {unknown} props - Props specific to type of Tx - * @param {string} [gasPayer] - optional gas payer, defaults to source or sender - * @returns {Promise} promise that resolves to an EncodedTx + * @param txType - type of the transaction + * @param txProps - transaction properties + * @param props - Props specific to type of Tx + * @param [gasPayer] - optional gas payer, defaults to source or sender + * @returns promise that resolves to an EncodedTx */ async buildTx( txType: TxType, @@ -120,10 +120,10 @@ export class Tx { /** * Build Transfer Tx * @async - * @param {TxProps} txProps - properties of the transaction - * @param {TransferProps} transferProps - properties of the transfer - * @param {string} [gasPayer] - optional gas payer, if not provided, defaults to transferProps.source - * @returns {Promise} promise that resolves to an EncodedTx + * @param txProps - properties of the transaction + * @param transferProps - properties of the transfer + * @param [gasPayer] - optional gas payer, if not provided, defaults to transferProps.source + * @returns promise that resolves to an EncodedTx */ async buildTransfer( txProps: TxProps, @@ -148,9 +148,9 @@ export class Tx { /** * Build RevealPK Tx * @async - * @param {TxProps} txProps - properties of the transaction - * @param {string} publicKey - public key to reveal - * @returns {Promise} promise that resolves to an EncodedTx + * @param txProps - properties of the transaction + * @param publicKey - public key to reveal + * @returns promise that resolves to an EncodedTx */ async buildRevealPk(txProps: TxProps, publicKey: string): Promise { const encodedTx = this.encodeTxArgs(txProps); @@ -166,10 +166,10 @@ export class Tx { /** * Build Bond Tx * @async - * @param {TxProps} txProps - properties of the transaction - * @param {BondProps} bondProps - properties of the bond tx - * @param {string} [gasPayer] - optional gas payer, if not provided, defaults to bondProps.source - * @returns {Promise} promise that resolves to an EncodedTx + * @param txProps - properties of the transaction + * @param bondProps - properties of the bond tx + * @param [gasPayer] - optional gas payer, if not provided, defaults to bondProps.source + * @returns promise that resolves to an EncodedTx */ async buildBond( txProps: TxProps, @@ -191,10 +191,10 @@ export class Tx { /** * Build Unbond Tx * @async - * @param {TxProps} txProps - properties of the transaction - * @param {UnbondProps} unbondProps - properties of the unbond tx - * @param {string} [gasPayer] - optional gas payer, if not provided, defaults to unbondProps.source - * @returns {Promise} promise that resolves to an EncodedTx + * @param txProps - properties of the transaction + * @param unbondProps - properties of the unbond tx + * @param [gasPayer] - optional gas payer, if not provided, defaults to unbondProps.source + * @returns promise that resolves to an EncodedTx */ async buildUnbond( txProps: TxProps, @@ -216,10 +216,10 @@ export class Tx { /** * Build Withdraw Tx * @async - * @param {TxProps} txProps - properties of the transaction - * @param {WithdrawProps} withdrawProps - properties of the withdraw tx - * @param {string} [gasPayer] - optional gas payer, if not provided, defaults to withdrawProps.source - * @returns {Promise} promise that resolves to an EncodedTx + * @param txProps - properties of the transaction + * @param withdrawProps - properties of the withdraw tx + * @param [gasPayer] - optional gas payer, if not provided, defaults to withdrawProps.source + * @returns promise that resolves to an EncodedTx */ async buildWithdraw( txProps: TxProps, @@ -241,10 +241,10 @@ export class Tx { /** * Build Ibc Transfer Tx * @async - * @param {TxProps} txProps - properties of the transaction - * @param {IbcTransferProps} ibcTransferProps - properties of the ibc transfer tx - * @param {string} [gasPayer] - optional gas payer, if not provided, defaults to ibcTransferProps.source - * @returns {Promise} promise that resolves to an EncodedTx + * @param txProps - properties of the transaction + * @param ibcTransferProps - properties of the ibc transfer tx + * @param [gasPayer] - optional gas payer, if not provided, defaults to ibcTransferProps.source + * @returns promise that resolves to an EncodedTx */ async buildIbcTransfer( txProps: TxProps, @@ -268,10 +268,10 @@ export class Tx { /** * Build Ethereum Bridge Transfer Tx * @async - * @param {TxProps} txProps - properties of the transaction - * @param {EthBridgeTransferProps} ethBridgeTransferProps - properties of the eth bridge transfer tx - * @param {string} [gasPayer] - optional gas payer, if not provided, defaults to ethBridgeTransferProps.sender - * @returns {Promise} promise that resolves to an EncodedTx + * @param txProps - properties of the transaction + * @param ethBridgeTransferProps - properties of the eth bridge transfer tx + * @param [gasPayer] - optional gas payer, if not provided, defaults to ethBridgeTransferProps.sender + * @returns promise that resolves to an EncodedTx */ async buildEthBridgeTransfer( txProps: TxProps, @@ -295,10 +295,10 @@ export class Tx { /** * Built Vote Proposal Tx * @async - * @param {TxProps} txProps - properties of the transaction - * @param {VoteProposalProps} voteProposalProps - properties of the vote proposal tx - * @param {string} [gasPayer] - optional gas payer, if not provided, defaults to voteProposalProps.signer - * @returns {Promise} promise that resolves to an EncodedTx + * @param txProps - properties of the transaction + * @param voteProposalProps - properties of the vote proposal tx + * @param [gasPayer] - optional gas payer, if not provided, defaults to voteProposalProps.signer + * @returns promise that resolves to an EncodedTx */ async buildVoteProposal( txProps: TxProps, @@ -322,9 +322,9 @@ export class Tx { /** * Sign transaction * @async - * @param {EncodedTx} encodedTx - encoded transaction - * @param {string} [signingKey] - optional in the case of shielded tx - * @returns {Promise} promise that resolves to a SignedTx + * @param encodedTx - encoded transaction + * @param [signingKey] - optional in the case of shielded tx + * @returns promise that resolves to a SignedTx */ async signTx(encodedTx: EncodedTx, signingKey?: string): Promise { const { tx, txMsg } = encodedTx; @@ -336,9 +336,9 @@ export class Tx { /** * Reveal Public Key using serialized Tx * @async - * @param {string} signingKey - signing key - * @param {TxProps} txProps - properties of the transaction - * @returns {Promise} + * @param signingKey - signing key + * @param txProps - properties of the transaction + * @returns void */ async revealPk(signingKey: string, txProps: TxProps): Promise { const encodedTx = this.encodeTxArgs(txProps); @@ -347,9 +347,9 @@ export class Tx { /** * Append signature for transactions signed by Ledger Hardware Wallet - * @param {Uint8Array} txBytes - Serialized transaction - * @param {ResponseSign} ledgerSignatureResponse - Serialized signature as returned from Ledger - * @returns {Uint8Array} - Serialized Tx bytes with signature appended + * @param txBytes - Serialized transaction + * @param ledgerSignatureResponse - Serialized signature as returned from Ledger + * @returns - Serialized Tx bytes with signature appended */ appendSignature( txBytes: Uint8Array, @@ -389,8 +389,8 @@ export class Tx { /** * Helper to encode Tx args given TxProps - * @param {TxProps} txProps - properties of the transaction - * @returns {Uint8Array} Serialized TxMsgValue + * @param txProps - properties of the transaction + * @returns Serialized TxMsgValue */ encodeTxArgs(txProps: TxProps): Uint8Array { const txMsgValue = new TxMsgValue(txProps); diff --git a/packages/sdk/src/tx/types.ts b/packages/sdk/src/tx/types.ts index 3e0683a91..8c0d107dc 100644 --- a/packages/sdk/src/tx/types.ts +++ b/packages/sdk/src/tx/types.ts @@ -6,8 +6,8 @@ import { BuiltTx } from "@namada/shared"; export class EncodedTx { /** * Create an EncodedTx class - * @param {Uint8Array} txMsg - Borsh-serialized transaction - * @param {BuiltTx} tx - Specific tx struct instance + * @param txMsg - Borsh-serialized transaction + * @param tx - Specific tx struct instance */ constructor( public readonly txMsg: Uint8Array, @@ -17,7 +17,7 @@ export class EncodedTx { /** * Return serialized tx bytes for external signing. This will clear * the BuiltTx struct instance from wasm memory, then return the bytes. - * @returns {Uint8Array} Serialized tx bytes + * @returns Serialized tx bytes */ toBytes(): Uint8Array { const bytes = new Uint8Array(this.tx.tx_bytes()); @@ -38,8 +38,8 @@ export class EncodedTx { */ export class SignedTx { /** - * @param {Uint8Array} txMsg - Serialized tx msg bytes - * @param {Uint8Array} tx - Serialized tx bytes + * @param txMsg - Serialized tx msg bytes + * @param tx - Serialized tx bytes */ constructor( // Serialized TxMsg @@ -48,3 +48,6 @@ export class SignedTx { public readonly tx: Uint8Array ) {} } + +export { TxType, TxTypeLabel } from "@namada/shared"; +export type { SupportedTx } from "@namada/shared"; diff --git a/packages/sdk/src/utils.ts b/packages/sdk/src/utils.ts new file mode 100644 index 000000000..8a04839b1 --- /dev/null +++ b/packages/sdk/src/utils.ts @@ -0,0 +1,54 @@ +import { Bip44Path } from "@namada/types"; + +/** + * Return a properly formatted BIP-044 path array + * @param coinType - SLIP-044 Coin designation + * @param path - path object + * @returns BIP-044 path array + */ +export const makeBip44PathArray = ( + coinType: number, + path: Bip44Path +): Uint32Array => { + const { account, change, index } = path; + return new Uint32Array([44, coinType, account, change, index]); +}; + +/** + * Return a properly formatted BIP-044 path + * @param coinType - SLIP-044 Coin designation + * @param bip44Path - path object + * @returns BIP-044 path + */ +export const makeBip44Path = ( + coinType: number, + bip44Path: Bip44Path +): string => { + const { account, change, index } = bip44Path; + return `m/44'/${coinType}'/${account}'/${change}'/${index}'`; +}; + +/** + * Return a properly formatted Sapling path + * @param coinType - SLIP-044 Coin designation + * @param account - numbered from index + in sequentially increasing manner. Defined as in BIP 44 + * @returns Sapling path + */ +export const makeSaplingPath = (coinType: number, account: number): string => { + return `m/32'/${coinType}'/${account}'`; +}; + +/** + * Return a properly formatted Sapling path array + * @param coinType - SLIP-044 Coin designation + * @param account - numbered from index + in sequentially increasing manner. Defined as in BIP 44 + * @returns Sapling path array + */ +export const makeSaplingPathArray = ( + coinType: number, + account: number +): Uint32Array => { + return new Uint32Array([32, coinType, account]); +}; diff --git a/packages/sdk/tsconfig.json b/packages/sdk/tsconfig.json index af4106635..7dfd0d5d1 100644 --- a/packages/sdk/tsconfig.json +++ b/packages/sdk/tsconfig.json @@ -11,7 +11,7 @@ // "dom" is needed for WebAssembly typings "lib": ["esnext", "dom"], "module": "esnext", - "moduleResolution": "node", + "moduleResolution": "bundler", "noEmit": false, "noFallthroughCasesInSwitch": true, "resolveJsonModule": true, @@ -27,5 +27,5 @@ "compilerOptions": { "module": "commonjs" } - }, + } } diff --git a/packages/sdk/tsconfig.node.json b/packages/sdk/tsconfig.node.json new file mode 100644 index 000000000..f2e742612 --- /dev/null +++ b/packages/sdk/tsconfig.node.json @@ -0,0 +1,22 @@ +{ + "extends": "./tsconfig.json", + "include": ["src/indexNode.ts", "src/initNode.ts", "../shared/src/shared/**/*", "../crypto/src/crypto/**/*"], + "exclude": [ + "**/*.test.ts", + "node_modules", + "scripts" + ], + "compilerOptions": { + "declaration": true, + "outDir": "dist/node", + "module": "node16", + "moduleResolution": "node16", + "plugins": [ + // Transform paths in output .js files + { "transform": "typescript-transform-paths" }, + + // Transform paths in output .d.ts files (Include this line if you output declarations files) + { "transform": "typescript-transform-paths", "afterDeclarations": true } + ] + } +} diff --git a/packages/sdk/tsconfig.web.json b/packages/sdk/tsconfig.web.json new file mode 100644 index 000000000..9642c2549 --- /dev/null +++ b/packages/sdk/tsconfig.web.json @@ -0,0 +1,22 @@ +{ + "extends": "./tsconfig.json", + "include": ["src/indexWeb.ts", "src/initWeb.ts", "../shared/src/shared/**/*", "../crypto/src/crypto/**/*"], + "exclude": [ + "**/*.test.ts", + "node_modules", + "scripts" + ], + "compilerOptions": { + "declaration": true, + "outDir": "dist/web", + "module": "esnext", + "moduleResolution": "bundler", + "plugins": [ + // Transform paths in output .js files + { "transform": "typescript-transform-paths" }, + + // Transform paths in output .d.ts files (Include this line if you output declarations files) + { "transform": "typescript-transform-paths", "afterDeclarations": true } + ] + } +} diff --git a/packages/shared/.release-it.cjs b/packages/shared/.release-it.cjs index cfe746e21..f2bfb6cba 100644 --- a/packages/shared/.release-it.cjs +++ b/packages/shared/.release-it.cjs @@ -1,11 +1,5 @@ const baseConfig = require("../../.release-it.base.cjs"); -const config = { - ...baseConfig, - npm: { - ...baseConfig.npm, - publish: true, - }, -}; +const config = baseConfig; module.exports = config; diff --git a/packages/shared/lib/Cargo.lock b/packages/shared/lib/Cargo.lock index b705f08c8..bbbf9cbad 100644 --- a/packages/shared/lib/Cargo.lock +++ b/packages/shared/lib/Cargo.lock @@ -286,6 +286,12 @@ version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" +[[package]] +name = "bitflags" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1" + [[package]] name = "bitvec" version = "1.0.1" @@ -644,11 +650,21 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13418e745008f7349ec7e449155f419a61b92b58a99cc3616942b926825ec76b" +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "core-foundation-sys" -version = "0.8.4" +version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e496a50fda8aacccc86d7529e2c1e0892dbd0f898a6b5645b5561b89c3210efa" +checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f" [[package]] name = "cpufeatures" @@ -1044,7 +1060,7 @@ checksum = "136526188508e25c6fef639d7927dfb3e0e3084488bf202267829cf7fc23dbdd" dependencies = [ "errno-dragonfly", "libc", - "windows-sys", + "windows-sys 0.48.0", ] [[package]] @@ -1440,6 +1456,21 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + [[package]] name = "form_urlencoded" version = "1.2.0" @@ -1832,6 +1863,19 @@ dependencies = [ "want", ] +[[package]] +name = "hyper-tls" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6183ddfa99b85da61a140bea0efc93fdf56ceaa041b37d553518030827f9905" +dependencies = [ + "bytes", + "hyper", + "native-tls", + "tokio", + "tokio-native-tls", +] + [[package]] name = "iana-time-zone" version = "0.1.56" @@ -2449,7 +2493,7 @@ checksum = "eae7b9aee968036d54dce06cebaefd919e4472e753296daccd6d344e3e2df0c2" dependencies = [ "hermit-abi", "libc", - "windows-sys", + "windows-sys 0.48.0", ] [[package]] @@ -2699,7 +2743,7 @@ checksum = "927a765cd3fc26206e66b296465fa9d3e5ab003e651c1b3c060e7956d96b19d2" dependencies = [ "libc", "wasi 0.11.0+wasi-snapshot-preview1", - "windows-sys", + "windows-sys 0.48.0", ] [[package]] @@ -3179,6 +3223,24 @@ dependencies = [ "thiserror", ] +[[package]] +name = "native-tls" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07226173c32f2926027b63cce4bcd8076c3552846cbe7925f3aaffeac0a3b92e" +dependencies = [ + "lazy_static", + "libc", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework", + "security-framework-sys", + "tempfile", +] + [[package]] name = "nonempty" version = "0.7.0" @@ -3428,6 +3490,50 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "openssl" +version = "0.10.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95a0481286a310808298130d22dd1fef0fa571e05a8f44ec801801e84b216b1f" +dependencies = [ + "bitflags 2.5.0", + "cfg-if", + "foreign-types", + "libc", + "once_cell", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.39", +] + +[[package]] +name = "openssl-probe" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" + +[[package]] +name = "openssl-sys" +version = "0.9.101" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dda2b0f344e78efc2facf7d195d098df0dd72151b26ab98da807afc26c198dff" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + [[package]] name = "orion" version = "0.16.1" @@ -3501,7 +3607,7 @@ dependencies = [ "libc", "redox_syscall 0.3.5", "smallvec", - "windows-targets", + "windows-targets 0.48.0", ] [[package]] @@ -3689,6 +3795,12 @@ dependencies = [ "spki", ] +[[package]] +name = "pkg-config" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d231b230927b5e4ad203db57bbcbee2802f6bce620b1e4a9024a07d94e2907ec" + [[package]] name = "poly1305" version = "0.8.0" @@ -4026,7 +4138,7 @@ version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" dependencies = [ - "bitflags", + "bitflags 1.3.2", ] [[package]] @@ -4035,7 +4147,7 @@ version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "567664f262709473930a4bf9e51bf2ebf3348f2e748ccc50dea20646858f8f29" dependencies = [ - "bitflags", + "bitflags 1.3.2", ] [[package]] @@ -4080,9 +4192,9 @@ checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f" [[package]] name = "reqwest" -version = "0.11.20" +version = "0.11.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e9ad3fe7488d7e34558a2033d45a0c90b72d97b4f80705666fea71472e2e6a1" +checksum = "dd67538700a17451e7cba03ac727fb961abb7607553461627b97de0b89cf4a62" dependencies = [ "base64 0.21.3", "bytes", @@ -4093,17 +4205,23 @@ dependencies = [ "http", "http-body", "hyper", + "hyper-tls", "ipnet", "js-sys", "log", "mime", + "native-tls", "once_cell", "percent-encoding", "pin-project-lite", + "rustls-pemfile", "serde", "serde_json", "serde_urlencoded", + "sync_wrapper", + "system-configuration", "tokio", + "tokio-native-tls", "tower-service", "url", "wasm-bindgen", @@ -4204,12 +4322,21 @@ version = "0.37.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4d69718bf81c6127a49dc64e44a742e8bb9213c0ff8869a22c308f84c1d4ab06" dependencies = [ - "bitflags", + "bitflags 1.3.2", "errno", "io-lifetimes", "libc", "linux-raw-sys", - "windows-sys", + "windows-sys 0.48.0", +] + +[[package]] +name = "rustls-pemfile" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c74cae0a4cf6ccbbf5f359f08efdf8ee7e1dc532573bf0db71968cb56b1448c" +dependencies = [ + "base64 0.21.3", ] [[package]] @@ -4266,6 +4393,15 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "schannel" +version = "0.1.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbc91545643bcf3a0bbb6569265615222618bdf33ce4ffbbd13c4bbd4c093534" +dependencies = [ + "windows-sys 0.52.0", +] + [[package]] name = "scoped-tls" version = "1.0.1" @@ -4305,6 +4441,29 @@ dependencies = [ "zeroize", ] +[[package]] +name = "security-framework" +version = "2.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05b64fb303737d99b81884b2c63433e9ae28abebe5eb5045dcdd175dc2ecf4de" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e932934257d3b408ed8f30db49d85ea163bfe74961f017f405b025af298f0c7a" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "semver" version = "0.11.0" @@ -4494,6 +4653,7 @@ dependencies = [ "js-sys", "namada", "rand 0.8.5", + "reqwest", "rexie", "serde", "serde_json", @@ -4683,6 +4843,33 @@ dependencies = [ "syn 2.0.39", ] +[[package]] +name = "sync_wrapper" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2047c6ded9c721764247e62cd3b03c09ffc529b2ba5b10ec482ae507a4a70160" + +[[package]] +name = "system-configuration" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba3a3adc5c275d719af8cb4272ea1c4a6d668a777f37e115f6d11ddbc1c8e0e7" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75fb188eb626b924683e3b95e3a48e63551fcfb51949de2f06a9d91dbee93c9" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "tap" version = "1.0.1" @@ -4700,7 +4887,7 @@ dependencies = [ "fastrand", "redox_syscall 0.3.5", "rustix", - "windows-sys", + "windows-sys 0.48.0", ] [[package]] @@ -4954,7 +5141,7 @@ dependencies = [ "signal-hook-registry", "socket2", "tokio-macros", - "windows-sys", + "windows-sys 0.48.0", ] [[package]] @@ -4968,6 +5155,16 @@ dependencies = [ "syn 2.0.39", ] +[[package]] +name = "tokio-native-tls" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" +dependencies = [ + "native-tls", + "tokio", +] + [[package]] name = "tokio-util" version = "0.7.8" @@ -5191,6 +5388,12 @@ dependencies = [ "serde", ] +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + [[package]] name = "version_check" version = "0.9.4" @@ -5448,7 +5651,7 @@ version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e686886bc078bc1b0b600cac0147aadb815089b6e4da64016cbd754b6342700f" dependencies = [ - "windows-targets", + "windows-targets 0.48.0", ] [[package]] @@ -5457,7 +5660,16 @@ version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" dependencies = [ - "windows-targets", + "windows-targets 0.48.0", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.4", ] [[package]] @@ -5466,13 +5678,28 @@ version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b1eb6f0cd7c80c79759c929114ef071b87354ce476d9d94271031c0497adfd5" dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", + "windows_aarch64_gnullvm 0.48.0", + "windows_aarch64_msvc 0.48.0", + "windows_i686_gnu 0.48.0", + "windows_i686_msvc 0.48.0", + "windows_x86_64_gnu 0.48.0", + "windows_x86_64_gnullvm 0.48.0", + "windows_x86_64_msvc 0.48.0", +] + +[[package]] +name = "windows-targets" +version = "0.52.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dd37b7e5ab9018759f893a1952c9420d060016fc19a472b4bb20d1bdd694d1b" +dependencies = [ + "windows_aarch64_gnullvm 0.52.4", + "windows_aarch64_msvc 0.52.4", + "windows_i686_gnu 0.52.4", + "windows_i686_msvc 0.52.4", + "windows_x86_64_gnu 0.52.4", + "windows_x86_64_gnullvm 0.52.4", + "windows_x86_64_msvc 0.52.4", ] [[package]] @@ -5481,42 +5708,84 @@ version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "91ae572e1b79dba883e0d315474df7305d12f569b400fcf90581b06062f7e1bc" +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bcf46cf4c365c6f2d1cc93ce535f2c8b244591df96ceee75d8e83deb70a9cac9" + [[package]] name = "windows_aarch64_msvc" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b2ef27e0d7bdfcfc7b868b317c1d32c641a6fe4629c171b8928c7b08d98d7cf3" +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da9f259dd3bcf6990b55bffd094c4f7235817ba4ceebde8e6d11cd0c5633b675" + [[package]] name = "windows_i686_gnu" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "622a1962a7db830d6fd0a69683c80a18fda201879f0f447f065a3b7467daa241" +[[package]] +name = "windows_i686_gnu" +version = "0.52.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b474d8268f99e0995f25b9f095bc7434632601028cf86590aea5c8a5cb7801d3" + [[package]] name = "windows_i686_msvc" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4542c6e364ce21bf45d69fdd2a8e455fa38d316158cfd43b3ac1c5b1b19f8e00" +[[package]] +name = "windows_i686_msvc" +version = "0.52.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1515e9a29e5bed743cb4415a9ecf5dfca648ce85ee42e15873c3cd8610ff8e02" + [[package]] name = "windows_x86_64_gnu" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca2b8a661f7628cbd23440e50b05d705db3686f894fc9580820623656af974b1" +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5eee091590e89cc02ad514ffe3ead9eb6b660aedca2183455434b93546371a03" + [[package]] name = "windows_x86_64_gnullvm" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7896dbc1f41e08872e9d5e8f8baa8fdd2677f29468c4e156210174edc7f7b953" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ca79f2451b49fa9e2af39f0747fe999fcda4f5e241b2898624dca97a1f2177" + [[package]] name = "windows_x86_64_msvc" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a" +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32b752e52a2da0ddfbdbcc6fceadfeede4c939ed16d13e648833a61dfb611ed8" + [[package]] name = "winnow" version = "0.5.15" @@ -5533,7 +5802,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "524e57b2c537c0f9b1e69f1965311ec12182b4122e45035b1508cd24d2adadb1" dependencies = [ "cfg-if", - "windows-sys", + "windows-sys 0.48.0", ] [[package]] diff --git a/packages/shared/lib/Cargo.toml b/packages/shared/lib/Cargo.toml index d2f4416e3..ced09c11c 100644 --- a/packages/shared/lib/Cargo.toml +++ b/packages/shared/lib/Cargo.toml @@ -11,8 +11,11 @@ license = "MIT" crate-type = ["cdylib", "rlib"] [features] +default = [] dev = [] multicore = ["wasm-bindgen-rayon", "namada/multicore"] +nodejs = [] +web = [] [dependencies] async-trait = {version = "0.1.51"} @@ -34,6 +37,7 @@ wasm-bindgen-rayon = { version = "1.0", optional = true } console_error_panic_hook = "0.1.6" zeroize = "1.6.0" hex = "0.4.3" +reqwest = "0.11.25" [dependencies.web-sys] version = "0.3.4" diff --git a/packages/shared/lib/src/query.rs b/packages/shared/lib/src/query.rs index 7ea23be96..554d41491 100644 --- a/packages/shared/lib/src/query.rs +++ b/packages/shared/lib/src/query.rs @@ -266,7 +266,7 @@ impl Query { }) .collect(); - let mut shielded: ShieldedContext = ShieldedContext::default(); + let mut shielded: ShieldedContext = ShieldedContext::default(); let _ = shielded.load().await?; let _ = shielded @@ -305,7 +305,7 @@ impl Query { let viewing_key = ExtendedFullViewingKey::from(xvk).fvk.vk; // We are recreating shielded context to avoid multiple mutable borrows - let mut shielded: ShieldedContext = ShieldedContext::default(); + let mut shielded: ShieldedContext = ShieldedContext::default(); shielded.load().await?; let epoch = query_epoch(&self.client).await?; diff --git a/packages/shared/lib/src/rpc_client.rs b/packages/shared/lib/src/rpc_client.rs index 22e2a0f64..9ab08d8e0 100644 --- a/packages/shared/lib/src/rpc_client.rs +++ b/packages/shared/lib/src/rpc_client.rs @@ -134,6 +134,7 @@ impl Client for HttpClient { R: SimpleRequest, { let request_body = request.into_json(); + let response = self .fetch(&self.url[..], "POST", &request_body) .await diff --git a/packages/shared/lib/src/sdk/masp/masp_node.js b/packages/shared/lib/src/sdk/masp/masp_node.js new file mode 100644 index 000000000..78d096eea --- /dev/null +++ b/packages/shared/lib/src/sdk/masp/masp_node.js @@ -0,0 +1,22 @@ +const fs = require("node:fs"); + +export function writeFileSync(path, ui8a) { + fs.writeFileSync(path, Buffer.from(ui8a)); +} + +export function readFileSync(path) { + const buffer = fs.readFileSync(path).buffer; + return buffer; +} + +export function renameSync(pathA, pathB) { + fs.renameSync(pathA, pathB); +} + +export function unlinkSync(path) { + fs.unlinkSync(path); +} + +export function existsSync(path) { + return fs.existsSync(path); +} diff --git a/packages/shared/lib/src/sdk/masp/masp_node.rs b/packages/shared/lib/src/sdk/masp/masp_node.rs new file mode 100644 index 000000000..ec6f948c4 --- /dev/null +++ b/packages/shared/lib/src/sdk/masp/masp_node.rs @@ -0,0 +1,168 @@ +use async_trait::async_trait; +use namada::sdk::{ + borsh::{BorshDeserialize, BorshSerialize}, + masp::{ContextSyncStatus, ShieldedContext, ShieldedUtils}, + masp_proofs::prover::LocalTxProver, +}; +use wasm_bindgen::{prelude::wasm_bindgen, JsValue}; + +use std::path::PathBuf; + +use crate::utils::to_bytes; + +/// Spend circuit name +pub const SPEND_NAME: &str = "masp-spend.params"; +/// Output circuit name +pub const OUTPUT_NAME: &str = "masp-output.params"; +/// Convert circuit name +pub const CONVERT_NAME: &str = "masp-convert.params"; + +const FILE_NAME: &str = "shielded.dat"; +const TMP_FILE_NAME: &str = "shielded.tmp"; +const SPECULATIVE_FILE_NAME: &str = "speculative_shielded.dat"; +const SPECULATIVE_TMP_FILE_NAME: &str = "speculative_shielded.tmp"; + +/// Mostly copied from the Namada CLI + +#[derive(Default, Debug, BorshSerialize, BorshDeserialize, Clone)] +#[borsh(crate = "namada::core::borsh")] +pub struct NodeShieldedUtils { + #[borsh(skip)] + context_dir: PathBuf, +} + +impl NodeShieldedUtils { + pub async fn new(context_dir: &str) -> ShieldedContext { + let context_dir = PathBuf::from(context_dir); + + let spend_path = context_dir.join(SPEND_NAME); + let convert_path = context_dir.join(CONVERT_NAME); + let output_path = context_dir.join(OUTPUT_NAME); + + if !(file_exists(spend_path.clone()) + && file_exists(convert_path.clone()) + && file_exists(output_path.clone())) + { + Self::fetch_params(spend_path, SPEND_NAME).await; + Self::fetch_params(convert_path, CONVERT_NAME).await; + Self::fetch_params(output_path, OUTPUT_NAME).await; + } + + let sync_status = if std::fs::read(context_dir.join(SPECULATIVE_FILE_NAME)).is_ok() { + ContextSyncStatus::Speculative + } else { + ContextSyncStatus::Confirmed + }; + + let utils = Self { context_dir }; + + ShieldedContext { + utils, + sync_status, + ..Default::default() + } + } + + async fn fetch_params(path: PathBuf, name: &str) { + let path = path.to_str().unwrap(); + let response = reqwest::get(format!( + "https://github.com/anoma/masp-mpc/releases/download/namada-trusted-setup/{}", + name + )) + .await + .unwrap(); + let content: Vec = response.bytes().await.unwrap().into(); + let uint8_array = js_sys::Uint8Array::from(&content[..]); + write_file_sync(JsValue::from_str(path), uint8_array.into()).unwrap(); + } +} + +#[async_trait(?Send)] +impl ShieldedUtils for NodeShieldedUtils { + fn local_tx_prover(&self) -> LocalTxProver { + LocalTxProver::with_default_location().expect("unable to load MASP Parameters") + } + + async fn load( + &self, + ctx: &mut ShieldedContext, + force_confirmed: bool, + ) -> std::io::Result<()> { + let file_name = if force_confirmed { + FILE_NAME + } else { + match ctx.sync_status { + ContextSyncStatus::Confirmed => FILE_NAME, + ContextSyncStatus::Speculative => SPECULATIVE_FILE_NAME, + } + }; + + let path = path_buf_to_js_value(self.context_dir.join(file_name)); + //TODO: change to_bytes to sth more descripive, add "from_bytes" + let bytes = to_bytes(read_file_sync(path).unwrap().into()); + + *ctx = ShieldedContext { + utils: ctx.utils.clone(), + ..ShieldedContext::::deserialize(&mut &bytes[..])? + }; + Ok(()) + } + + async fn save(&self, ctx: &ShieldedContext) -> std::io::Result<()> { + let (tmp_file_name, file_name) = match ctx.sync_status { + ContextSyncStatus::Confirmed => (TMP_FILE_NAME, FILE_NAME), + ContextSyncStatus::Speculative => (SPECULATIVE_TMP_FILE_NAME, SPECULATIVE_FILE_NAME), + }; + + let tmp_path = path_buf_to_js_value(self.context_dir.join(tmp_file_name)); + { + let mut bytes = Vec::new(); + ctx.serialize(&mut bytes) + .expect("cannot serialize shielded context"); + let uint8_array = js_sys::Uint8Array::from(&bytes[..]); + + write_file_sync(tmp_path.clone(), uint8_array.into()).unwrap(); + } + + let new_path = path_buf_to_js_value(self.context_dir.join(file_name)); + renameSync(tmp_path, new_path).unwrap(); + + if let ContextSyncStatus::Confirmed = ctx.sync_status { + unlinkSync(path_buf_to_js_value( + self.context_dir.join(SPECULATIVE_FILE_NAME), + )) + .unwrap(); + } + + Ok(()) + } +} + +fn path_buf_to_js_value(path: PathBuf) -> JsValue { + JsValue::from_str(path.to_str().unwrap()) +} + +fn file_exists(path: PathBuf) -> bool { + exists_sync(path_buf_to_js_value(path)) + .unwrap() + .as_bool() + .unwrap() +} + +#[wasm_bindgen(module = "/src/sdk/masp/masp_node.js")] +extern "C" { + #[wasm_bindgen(catch, js_name = "writeFileSync")] + fn write_file_sync(path: JsValue, content: JsValue) -> Result; + + #[wasm_bindgen(catch, js_name = "readFileSync")] + fn read_file_sync(path: JsValue) -> Result; + + #[wasm_bindgen(catch, js_name = "renameSync")] + fn renameSync(pathA: JsValue, pathB: JsValue) -> Result; + + #[wasm_bindgen(catch, js_name = "unlinkSync")] + fn unlinkSync(path: JsValue) -> Result; + + #[wasm_bindgen(catch, js_name = "existsSync")] + fn exists_sync(path: JsValue) -> Result; +} diff --git a/packages/shared/lib/src/sdk/masp.rs b/packages/shared/lib/src/sdk/masp/masp_web.rs similarity index 100% rename from packages/shared/lib/src/sdk/masp.rs rename to packages/shared/lib/src/sdk/masp/masp_web.rs diff --git a/packages/shared/lib/src/sdk/masp/mod.rs b/packages/shared/lib/src/sdk/masp/mod.rs new file mode 100644 index 000000000..14445a91c --- /dev/null +++ b/packages/shared/lib/src/sdk/masp/mod.rs @@ -0,0 +1,11 @@ +#[cfg(feature = "web")] +mod masp_web; + +#[cfg(feature = "web")] +pub use masp_web::WebShieldedUtils as JSShieldedUtils; + +#[cfg(feature = "nodejs")] +mod masp_node; + +#[cfg(feature = "nodejs")] +pub use masp_node::NodeShieldedUtils as JSShieldedUtils; diff --git a/packages/shared/lib/src/sdk/mod.rs b/packages/shared/lib/src/sdk/mod.rs index a3302fcd3..6b089da25 100644 --- a/packages/shared/lib/src/sdk/mod.rs +++ b/packages/shared/lib/src/sdk/mod.rs @@ -1,11 +1,13 @@ +pub mod io; +pub mod masp; +mod signature; +mod tx; +mod wallet; + use self::io::WebIo; -use self::wallet::BrowserWalletUtils; use crate::rpc_client::HttpClient; +use crate::utils::set_panic_hook; use crate::utils::to_js_result; -use crate::{ - sdk::masp::WebShieldedUtils, - utils::{set_panic_hook, to_bytes}, -}; use js_sys::Uint8Array; use namada::address::Address; use namada::core::borsh::{self, BorshDeserialize}; @@ -27,11 +29,8 @@ use namada::tx::Tx; use std::str::FromStr; use wasm_bindgen::{prelude::wasm_bindgen, JsError, JsValue}; -pub mod io; -pub mod masp; -mod signature; -mod tx; -mod wallet; +#[cfg(feature = "web")] +use crate::utils::to_bytes; #[wasm_bindgen] #[derive(Copy, Clone, Debug)] @@ -62,7 +61,7 @@ impl BuiltTx { /// Represents the Sdk public API. #[wasm_bindgen] pub struct Sdk { - namada: NamadaImpl, + namada: NamadaImpl, } #[wasm_bindgen] @@ -70,12 +69,14 @@ pub struct Sdk { /// For more details, navigate to the corresponding modules. impl Sdk { #[wasm_bindgen(constructor)] - pub fn new(url: String, native_token: String) -> Self { + pub fn new(url: String, native_token: String, path_or_db_name: String) -> Self { set_panic_hook(); let client: HttpClient = HttpClient::new(url); - let wallet: Wallet = - Wallet::new(BrowserWalletUtils {}, Store::default()); - let shielded_ctx: ShieldedContext = ShieldedContext::default(); + let wallet: Wallet = Wallet::new( + wallet::JSWalletUtils::new_utils(&path_or_db_name), + Store::default(), + ); + let shielded_ctx: ShieldedContext = ShieldedContext::default(); let namada = NamadaImpl::native_new( client, @@ -100,7 +101,9 @@ impl Sdk { Ok(()) } - pub async fn load_masp_params(&mut self) -> Result<(), JsValue> { + #[cfg(feature = "web")] + pub async fn load_masp_params(&mut self, _db_name: JsValue) -> Result<(), JsValue> { + // _dn_name is not used in the web version for a time being let params = get_masp_params().await?; let params_iter = js_sys::try_iter(¶ms)?.ok_or_else(|| "Can't iterate over JsValue")?; let mut params_bytes = params_iter.map(|p| to_bytes(p.unwrap())); @@ -113,7 +116,17 @@ impl Sdk { assert_eq!(params_bytes.next(), None); let mut shielded = self.namada.shielded_mut().await; - *shielded = WebShieldedUtils::new(spend, output, convert).await?; + *shielded = masp::JSShieldedUtils::new(spend, output, convert).await?; + + Ok(()) + } + + #[cfg(feature = "nodejs")] + pub async fn load_masp_params(&mut self, context_dir: JsValue) -> Result<(), JsValue> { + let context_dir = context_dir.as_string().unwrap(); + + let mut shielded = self.namada.shielded_mut().await; + *shielded = masp::JSShieldedUtils::new(&context_dir).await; Ok(()) } @@ -206,7 +219,7 @@ impl Sdk { .await? } TxType::Transfer => { - self.build_transfer(specific_msg, tx_msg, None, Some(gas_payer)) + self.build_transfer(specific_msg, tx_msg, Some(gas_payer)) .await? } TxType::IBCTransfer => { @@ -263,10 +276,9 @@ impl Sdk { &mut self, transfer_msg: &[u8], tx_msg: &[u8], - xsk: Option, _gas_payer: Option, ) -> Result { - let mut args = tx::transfer_tx_args(transfer_msg, tx_msg, xsk.clone())?; + let mut args = tx::transfer_tx_args(transfer_msg, tx_msg)?; // TODO: this might not be needed. I will test it out in future match args.source { @@ -285,14 +297,11 @@ impl Sdk { &[], ) .await?; - } - } - // It's temporary solution to add xsk to wallet as xvk is queried when unshielding - // This will change in namada in the future - match xsk { - Some(xsk) => self.add_spending_key(&xsk, &"temp").await, - None => {} + // It's temporary solution to add xsk to wallet as xvk is queried when unshielding + // This will change in namada in the future + self.add_spending_key(&xsk.to_string(), "temp").await; + } } let (tx, signing_data, _) = build_transfer(&self.namada, &mut args).await?; diff --git a/packages/shared/lib/src/sdk/tx.rs b/packages/shared/lib/src/sdk/tx.rs index c65bfeda5..47ed55d55 100644 --- a/packages/shared/lib/src/sdk/tx.rs +++ b/packages/shared/lib/src/sdk/tx.rs @@ -218,11 +218,7 @@ pub struct SubmitTransferMsg { /// /// Returns JsError if the tx_msg can't be deserialized or /// Rust structs can't be created. -pub fn transfer_tx_args( - transfer_msg: &[u8], - tx_msg: &[u8], - xsk: Option, -) -> Result { +pub fn transfer_tx_args(transfer_msg: &[u8], tx_msg: &[u8]) -> Result { let transfer_msg = SubmitTransferMsg::try_from_slice(transfer_msg)?; let SubmitTransferMsg { source, @@ -234,9 +230,7 @@ pub fn transfer_tx_args( let source = match Address::from_str(&source) { Ok(v) => Ok(TransferSource::Address(v)), - Err(e1) => match ExtendedSpendingKey::from_str( - &xsk.expect("Extended spending key to be present, if address type is shielded."), - ) { + Err(e1) => match ExtendedSpendingKey::from_str(&source) { Ok(v) => Ok(TransferSource::ExtendedSpendingKey(v)), Err(e2) => Err(JsError::new(&format!( "Can't compute the transfer source. {}, {}", diff --git a/packages/shared/lib/src/sdk/wallet.rs b/packages/shared/lib/src/sdk/wallet/mod.rs similarity index 51% rename from packages/shared/lib/src/sdk/wallet.rs rename to packages/shared/lib/src/sdk/wallet/mod.rs index 0d7f9efad..3a804c4c0 100644 --- a/packages/shared/lib/src/sdk/wallet.rs +++ b/packages/shared/lib/src/sdk/wallet/mod.rs @@ -1,28 +1,20 @@ -use std::str::FromStr; - use namada::{ masp::ExtendedSpendingKey, - sdk::wallet::{alias::Alias, Wallet, WalletIo, WalletStorage}, + sdk::wallet::{alias::Alias, Wallet, WalletIo}, }; -use rand::rngs::OsRng; +use std::str::FromStr; -#[derive(Clone)] -pub struct BrowserWalletUtils {} +#[cfg(feature = "web")] +mod wallet_web; -impl WalletIo for BrowserWalletUtils { - type Rng = OsRng; -} +#[cfg(feature = "web")] +pub use wallet_web::BrowserWalletUtils as JSWalletUtils; -//TODO: check if we need to impl those -impl WalletStorage for BrowserWalletUtils { - fn save(&self, _wallet: &Wallet) -> Result<(), namada::sdk::wallet::LoadStoreError> { - todo!() - } +#[cfg(feature = "nodejs")] +mod wallet_node; - fn load(&self, _wallet: &mut Wallet) -> Result<(), namada::sdk::wallet::LoadStoreError> { - todo!() - } -} +#[cfg(feature = "nodejs")] +pub use wallet_node::NodeWalletUtils as JSWalletUtils; /// Adds spending key to the wallet. /// It's needed because we create addresses without using the Sdk. @@ -33,16 +25,19 @@ impl WalletStorage for BrowserWalletUtils { /// * `wallet` - Instance of a wallet struct. /// * `xsk` - String representing serialized ExtendedSpendingKey. /// * `alias` - Spending key alias. -pub fn add_spending_key(wallet: &mut Wallet, xsk: &str, alias: &str) { +pub fn add_spending_key(wallet: &mut Wallet, xsk: &str, alias: &str) { let xsk = ExtendedSpendingKey::from_str(xsk).expect("XSK deserialization failed."); let alias = Alias::from(alias); // xsk is decrypted outside of this wallet instance, so we specify None below if wallet .store_mut() - .insert_spending_key::(alias.clone(), xsk, None, None, true) + .insert_spending_key::(alias.clone(), xsk, None, None, true) .is_none() { panic!("Action cancelled, no changes persisted."); } } + + +//TODO: add more wallet functions diff --git a/packages/shared/lib/src/sdk/wallet/wallet_node.rs b/packages/shared/lib/src/sdk/wallet/wallet_node.rs new file mode 100644 index 000000000..4a6a1a854 --- /dev/null +++ b/packages/shared/lib/src/sdk/wallet/wallet_node.rs @@ -0,0 +1,90 @@ +use std::path::PathBuf; + +use namada::sdk::{ + borsh::{BorshDeserialize, BorshSerialize}, + wallet::{LoadStoreError, Store, Wallet, WalletIo, WalletStorage}, +}; +use rand::rngs::OsRng; +use wasm_bindgen::{prelude::wasm_bindgen, JsValue}; + +use crate::utils::to_bytes; + +#[derive(Debug, BorshSerialize, BorshDeserialize, Clone)] +#[borsh(crate = "namada::core::borsh")] +pub struct NodeWalletUtils { + #[borsh(skip)] + store_dir: PathBuf, +} + +impl NodeWalletUtils { + pub fn new_utils(store_dir: &str) -> Self { + let store_dir = PathBuf::from(store_dir); + Self { store_dir } + } +} + +impl WalletIo for NodeWalletUtils { + type Rng = OsRng; +} + +pub trait NodeWalletStorage: Clone { + fn store_dir(&self) -> &PathBuf; +} + +impl NodeWalletStorage for NodeWalletUtils { + fn store_dir(&self) -> &PathBuf { + &self.store_dir + } +} + +const FILE_NAME: &str = "wallet.toml"; + +impl WalletStorage for NodeWalletUtils { + fn save(&self, wallet: &Wallet) -> Result<(), namada::sdk::wallet::LoadStoreError> { + let data = wallet.store().encode(); + + let wallet_path = self.store_dir().join(FILE_NAME); + // Make sure the dir exists + let wallet_dir = wallet_path.parent().unwrap(); + let uint8_array = js_sys::Uint8Array::from(&data[..]); + + write_file_sync( + JsValue::from_str(wallet_dir.to_str().unwrap()), + uint8_array.into(), + ) + .unwrap(); + + Ok(()) + } + + fn load(&self, wallet: &mut Wallet) -> Result<(), namada::sdk::wallet::LoadStoreError> { + let wallet_file = self.store_dir().join(FILE_NAME); + + let stored_data: Vec = + to_bytes(read_file_sync(JsValue::from_str(wallet_file.to_str().unwrap())).unwrap()); + + let store = wallet.store_mut(); + + *store = Store::decode(stored_data).map_err(LoadStoreError::Decode)?; + + Ok(()) + } +} + +#[wasm_bindgen(module = "/src/sdk/masp/masp_node.js")] +extern "C" { + #[wasm_bindgen(catch, js_name = "writeFileSync")] + fn write_file_sync(path: JsValue, content: JsValue) -> Result; + + #[wasm_bindgen(catch, js_name = "readFileSync")] + fn read_file_sync(path: JsValue) -> Result; + + #[wasm_bindgen(catch, js_name = "renameSync")] + fn renameSync(pathA: JsValue, pathB: JsValue) -> Result; + + #[wasm_bindgen(catch, js_name = "unlinkSync")] + fn unlinkSync(path: JsValue) -> Result; + + #[wasm_bindgen(catch, js_name = "existsSync")] + fn exists_sync(path: JsValue) -> Result; +} diff --git a/packages/shared/lib/src/sdk/wallet/wallet_web.rs b/packages/shared/lib/src/sdk/wallet/wallet_web.rs new file mode 100644 index 000000000..e2b0c5460 --- /dev/null +++ b/packages/shared/lib/src/sdk/wallet/wallet_web.rs @@ -0,0 +1,35 @@ +use namada::sdk::{ + borsh::{BorshDeserialize, BorshSerialize}, + wallet::{Wallet, WalletIo, WalletStorage}, +}; +use rand::rngs::OsRng; + +#[derive(Debug, BorshSerialize, BorshDeserialize, Clone)] +#[borsh(crate = "namada::core::borsh")] +pub struct BrowserWalletUtils { + #[borsh(skip)] + _name: String, +} + +impl BrowserWalletUtils { + pub fn new_utils(name: &str) -> Self { + Self { + _name: name.to_string(), + } + } +} + +impl WalletIo for BrowserWalletUtils { + type Rng = OsRng; +} + +//TODO: check if we need to impl those +impl WalletStorage for BrowserWalletUtils { + fn save(&self, _wallet: &Wallet) -> Result<(), namada::sdk::wallet::LoadStoreError> { + todo!() + } + + fn load(&self, _wallet: &mut Wallet) -> Result<(), namada::sdk::wallet::LoadStoreError> { + todo!() + } +} diff --git a/packages/shared/package.json b/packages/shared/package.json index d284e46c4..2db1e2478 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -8,7 +8,8 @@ "author": "Heliax Dev ", "license": "MIT", "scripts": { - "prepublish": "yarn wasm:build && tsc --build", + "prepublish": "yarn && yarn build", + "build": "yarn wasm:build && tsc --build", "release": "yarn prepublish && release-it --verbose --ci", "release:dry-run": "yarn prepublish && release-it --verbose --dry-run --ci", "release:no-npm": "yarn prepublish && release-it --verbose --no-npm.publish --ci", @@ -16,8 +17,11 @@ "wasm:build:multicore": "node ./scripts/build.js --release --multicore", "wasm:build:dev": "node ./scripts/build.js", "wasm:build:dev:multicore": "node ./scripts/build.js --multicore", - "wasm:build:node": "./scripts/build-test.sh", - "test-wasm:ci": "cd ./lib && wasm-pack test --node" + "wasm:build:node": "node ./scripts/build.js --target nodejs --release", + "wasm:build:node:multicore": "node ./scripts/build.js --target nodejs --release --multicore", + "wasm:build:node:dev": "node ./scripts/build.js --target nodejs", + "wasm:build:node:dev:multicore": "node ./scripts/build.js --target node --multicore", + "test-wasm:ci": "cd ./lib && wasm-pack test --node -- --features dev,web --profile dev" }, "dependencies": { "@dao-xyz/borsh": "^5.1.5", diff --git a/packages/shared/scripts/build-test.sh b/packages/shared/scripts/build-test.sh deleted file mode 100755 index ea0e50046..000000000 --- a/packages/shared/scripts/build-test.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/sh - -SCRIPT_DIR=$(cd "$(dirname "$0")"; pwd -P) - -wasm-pack build $SCRIPT_DIR/../lib --dev --target nodejs --out-dir $SCRIPT_DIR/../src/shared -- --features dev diff --git a/packages/shared/scripts/build.js b/packages/shared/scripts/build.js index 5e8bb0e40..a67250eb8 100644 --- a/packages/shared/scripts/build.js +++ b/packages/shared/scripts/build.js @@ -1,7 +1,13 @@ const { parseArgs } = require("node:util"); const { spawnSync, execSync } = require("child_process"); +const targets = ["web", "nodejs"]; + const argsOptions = { + target: { + type: "string", + short: "t", + }, multicore: { type: "boolean", short: "m", @@ -11,21 +17,26 @@ const argsOptions = { short: "r", }, }; -const { multicore, release } = parseArgs({ +const { + multicore, + release, + target: maybeTarget, +} = parseArgs({ args: process.argv.slice(2), options: argsOptions, }).values; const mode = release ? "release" : "development"; const multicoreLabel = multicore ? "on" : "off"; +const target = targets.includes(maybeTarget) ? maybeTarget : "web"; execSync("rm -rf dist"); console.log( - `Building \"shared\" in ${mode} mode. Multicore is ${multicoreLabel}.` + `Building \"shared\" in ${mode} mode for ${target} target. Multicore is ${multicoreLabel}.` ); -const features = []; +const features = [target]; let profile = "--release"; if (multicore) { @@ -46,11 +57,11 @@ const { status } = spawnSync( `${__dirname}/../lib`, profile, `--target`, - `web`, + target, `--out-dir`, outDir, `--`, - features.length > 0 ? ["--features", features.join(",")].flat() : [], + ["--features", features.join(",")].flat(), multicore ? [`-Z`, `build-std=panic_abort,std`] : [], ].flat(), { diff --git a/packages/shared/src/init-thread-pool.ts b/packages/shared/src/init-thread-pool.ts new file mode 100644 index 000000000..d4b7e4288 --- /dev/null +++ b/packages/shared/src/init-thread-pool.ts @@ -0,0 +1 @@ +export { initThreadPool } from "./shared/shared"; diff --git a/packages/shared/src/init.ts b/packages/shared/src/init.ts index f6d4d4db2..806d6fe16 100644 --- a/packages/shared/src/init.ts +++ b/packages/shared/src/init.ts @@ -1,17 +1,5 @@ -import initWasm, { - InitInput, - InitOutput, - initThreadPool, -} from "./shared/shared"; +import initWasm, { InitInput, InitOutput } from "./shared/shared"; export const init: (wasm: InitInput) => Promise = async (wasm) => { return await initWasm(wasm); }; - -export const initMulticore: (wasm: InitInput) => Promise = async ( - wasm -) => { - const res = await initWasm(wasm); - await initThreadPool(navigator.hardwareConcurrency); - return res; -}; diff --git a/packages/storage/package.json b/packages/storage/package.json index 87fda6951..bcb1d1a6d 100644 --- a/packages/storage/package.json +++ b/packages/storage/package.json @@ -8,7 +8,8 @@ "author": "Heliax Dev ", "license": "MIT", "scripts": { - "prepublish": "npx rimraf ./dist && tsc --build", + "prepublish": "yarn && yarn build", + "build": "npx rimraf ./dist && tsc --build", "release": "yarn prepublish && release-it --verbose --ci", "release:dry-run": "yarn prepublish && release-it --verbose --dry-run --ci", "release:no-npm": "yarn prepublish && release-it --verbose --no-npm.publish --ci", @@ -20,7 +21,6 @@ "typescript": "^5.1.3" }, "devDependencies": { - "@namada/config": "workspace:^", "@types/firefox-webext-browser": "^94.0.1", "@types/jest": "^29.0.0", "eslint": "^8.49.0", diff --git a/packages/types/.release-it.cjs b/packages/types/.release-it.cjs index cfe746e21..f2bfb6cba 100644 --- a/packages/types/.release-it.cjs +++ b/packages/types/.release-it.cjs @@ -1,11 +1,5 @@ const baseConfig = require("../../.release-it.base.cjs"); -const config = { - ...baseConfig, - npm: { - ...baseConfig.npm, - publish: true, - }, -}; +const config = baseConfig; module.exports = config; diff --git a/packages/types/package.json b/packages/types/package.json index 994f01c5d..50153c3df 100644 --- a/packages/types/package.json +++ b/packages/types/package.json @@ -8,7 +8,8 @@ "author": "Heliax AG ", "license": "MIT", "scripts": { - "prepublish": "rimraf ./dist && tsc --build", + "prepublish": "yarn && yarn build", + "build": "rimraf ./dist && tsc --build", "release": "yarn prepublish && release-it --verbose --ci", "release:dry-run": "yarn prepublish && release-it --verbose --dry-run --ci", "release:no-npm": "yarn prepublish && release-it --verbose --no-npm.publish", @@ -24,7 +25,6 @@ }, "devDependencies": { "@babel/preset-env": "^7.23.8", - "@namada/config": "workspace:^", "@release-it/conventional-changelog": "^8.0.1", "eslint": "^8.49.0", "eslint-config-prettier": "^8.8.0", diff --git a/packages/types/src/tx/messages/index.ts b/packages/types/src/tx/messages/index.ts index 998cf6bdf..c98cf101f 100644 --- a/packages/types/src/tx/messages/index.ts +++ b/packages/types/src/tx/messages/index.ts @@ -3,7 +3,6 @@ import { Schema } from "../schema"; export interface IMessage { encode(value: T): Uint8Array; - decode(buffer: Uint8Array, parser: Constructor): T; } export class Message implements IMessage { @@ -15,7 +14,10 @@ export class Message implements IMessage { } } - public decode(buffer: Uint8Array, parser: Constructor): T { + public static decode( + buffer: Uint8Array, + parser: Constructor + ): T { try { return deserialize(Buffer.from(buffer), parser); } catch (e) { diff --git a/packages/utils/package.json b/packages/utils/package.json index cd1ddacc6..ca2f483ee 100644 --- a/packages/utils/package.json +++ b/packages/utils/package.json @@ -8,7 +8,8 @@ "author": "Heliax Dev ", "license": "MIT", "scripts": { - "prepublish": "npx rimraf ./dist && tsc --build", + "prepublish": "yarn && yarn build", + "build": "npx rimraf ./dist && tsc --build", "release": "yarn prepublish && release-it --verbose --ci", "release:dry-run": "yarn prepublish && release-it --verbose --dry-run --ci", "release:no-npm": "yarn prepublish && release-it --verbose --no-npm.publish --ci", @@ -26,7 +27,6 @@ "styled-components": "^5.3.5" }, "devDependencies": { - "@namada/config": "workspace:^", "@types/bs58": "^4.0.1", "@types/crypto-js": "^4.1.1", "@types/jest": "^28.1.8", diff --git a/packages/utils/src/helpers/index.ts b/packages/utils/src/helpers/index.ts index 41936ecfe..0bf4ca7d6 100644 --- a/packages/utils/src/helpers/index.ts +++ b/packages/utils/src/helpers/index.ts @@ -1,6 +1,5 @@ import { JsonRpcRequest } from "@cosmjs/json-rpc"; import { - Bip44Path, JsonCompatibleArray, JsonCompatibleDictionary, Tokens, @@ -179,63 +178,6 @@ export const Result = { }, }; -/** - * Return a properly formatted BIP-044 path - * - * @param {number} coinType - SLIP-044 Coin designation - * @param {Bip44Path} bip44Path - path object - * @returns {string} - */ -export const makeBip44Path = ( - coinType: number, - bip44Path: Bip44Path -): string => { - const { account, change, index } = bip44Path; - return `m/44'/${coinType}'/${account}'/${change}'/${index}'`; -}; - -/** - * Return a properly formatted Sapling path - * - * @param {number} coinType - SLIP-044 Coin designation - * @param {number} account - numbered from index - in sequentially increasing manner. Defined as in BIP 44 - * @returns {string} - */ -export const makeSaplingPath = (coinType: number, account: number): string => { - return `m/32'/${coinType}'/${account}'`; -}; - -/** - * Return a properly formatted BIP-044 path array - * - * @param {number} coinType - SLIP-044 Coin designation - * @param {Bip44Path} path - path object - * @returns {string} - */ -export const makeBip44PathArray = ( - coinType: number, - path: Bip44Path -): Uint32Array => { - const { account, change, index } = path; - return new Uint32Array([44, coinType, account, change, index]); -}; - -/** - * Return a properly formatted Sapling path array - * - * @param {number} coinType - SLIP-044 Coin designation - * @param {number} account - numbered from index - in sequentially increasing manner. Defined as in BIP 44 - * @returns {string} - */ -export const makeSaplingPathArray = ( - coinType: number, - account: number -): Uint32Array => { - return new Uint32Array([32, coinType, account]); -}; - /** * Pick object parameters */ diff --git a/scripts/build-test.sh b/scripts/build-test.sh index 638753f29..76907d6a0 100755 --- a/scripts/build-test.sh +++ b/scripts/build-test.sh @@ -2,5 +2,5 @@ SCRIPT_DIR=$(cd "$(dirname "$0")"; pwd -P) -cd $SCRIPT_DIR/../packages/crypto && yarn wasm:build:node -cd $SCRIPT_DIR/../packages/shared && yarn wasm:build:node +cd $SCRIPT_DIR/../packages/crypto && yarn wasm:build:node:dev +cd $SCRIPT_DIR/../packages/shared && yarn wasm:build:node:dev diff --git a/tsconfig.base.json b/tsconfig.base.json index 1ffd9ff1e..4324af771 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -7,6 +7,9 @@ "@namada/components": ["../../../packages/components/src"], "@namada/components/*": ["../../../packages/components/src/*"], + "@namada/config": ["../../../packages/config/src"], + "@namada/config/*": ["../../../packages/config/src/*"], + "@namada/crypto": ["../../../packages/crypto/src"], "@namada/crypto/*": ["../../../packages/crypto/src/*"], @@ -16,9 +19,6 @@ "@namada/integrations": ["../../../packages/integrations/src"], "@namada/integrations/*": ["../../../packages/integrations/src/*"], - "@namada/sdk": ["../../../packages/sdk/src"], - "@namada/sdk/*": ["../../../packages/sdk/src/*"], - "@namada/shared": ["../../../packages/shared/src"], "@namada/shared/*": ["../../../packages/shared/src/*"], @@ -29,7 +29,13 @@ "@namada/types/*": ["../../../packages/types/src/*"], "@namada/utils": ["../../../packages/utils/src"], - "@namada/utils/*": ["../../../packages/utils/src/*"] + "@namada/utils/*": ["../../../packages/utils/src/*"], + + "@namada/sdk/web": ["../../../packages/sdk/src/indexWeb.ts"], + "@namada/sdk/web-init": ["../../../packages/sdk/src/initWeb.ts"], + + "@namada/sdk/node": ["../../../packages/sdk/src/indexNode.ts"], + "@namada/sdk/node-init": ["../../../packages/sdk/src/initNode.ts"] } } } diff --git a/yarn.lock b/yarn.lock index 674899d04..50de280a8 100644 --- a/yarn.lock +++ b/yarn.lock @@ -45,28 +45,6 @@ __metadata: languageName: node linkType: hard -"@anoma/e2e@workspace:e2e": - version: 0.0.0-use.local - resolution: "@anoma/e2e@workspace:e2e" - dependencies: - "@types/jest": "npm:^29.0.0" - "@types/node": "npm:^20.4.2" - "@types/puppeteer": "npm:^7.0.4" - eslint: "npm:^8.49.0" - eslint-config-prettier: "npm:^8.8.0" - eslint-plugin-import: "npm:^2.27.5" - eslint-plugin-react: "npm:^7.33.0" - eslint-plugin-react-hooks: "npm:^4.6.0" - http-server: "npm:^14.1.1" - jest: "npm:^29.0.2" - jest-puppeteer: "npm:^9.0.0" - puppeteer: "npm:^20.8.2" - start-server-and-test: "npm:^2.0.0" - terminate: "npm:^2.6.1" - typescript: "npm:^5.1.3" - languageName: unknown - linkType: soft - "@apideck/better-ajv-errors@npm:^0.3.1": version: 0.3.3 resolution: "@apideck/better-ajv-errors@npm:0.3.3" @@ -7667,6 +7645,16 @@ __metadata: languageName: node linkType: hard +"@jridgewell/trace-mapping@npm:^0.3.20": + version: 0.3.25 + resolution: "@jridgewell/trace-mapping@npm:0.3.25" + dependencies: + "@jridgewell/resolve-uri": "npm:^3.1.0" + "@jridgewell/sourcemap-codec": "npm:^1.4.14" + checksum: 3d1ce6ebc69df9682a5a8896b414c6537e428a1d68b02fcc8363b04284a8ca0df04d0ee3013132252ab14f2527bc13bea6526a912ecb5658f0e39fd2860b4df4 + languageName: node + linkType: hard + "@jsdoc/salty@npm:^0.2.1": version: 0.2.7 resolution: "@jsdoc/salty@npm:0.2.7" @@ -7830,9 +7818,6 @@ __metadata: dependencies: "@babel/plugin-transform-modules-commonjs": "npm:^7.20.11" "@keplr-wallet/types": "npm:^0.10.19" - "@namada/components": "npm:0.2.1" - "@namada/hooks": "npm:0.2.1" - "@namada/utils": "npm:0.2.1" "@svgr/webpack": "npm:^6.3.1" "@types/dompurify": "npm:^3.0.2" "@types/lodash.groupby": "npm:^4.6.9" @@ -7864,12 +7849,10 @@ __metadata: languageName: unknown linkType: soft -"@namada/chains@npm:0.2.1, @namada/chains@workspace:packages/chains": +"@namada/chains@workspace:packages/chains": version: 0.0.0-use.local resolution: "@namada/chains@workspace:packages/chains" dependencies: - "@namada/config": "workspace:^" - "@namada/types": "npm:0.2.1" eslint: "npm:^8.49.0" eslint-config-prettier: "npm:^8.8.0" eslint-import-resolver-typescript: "npm:^3.5.2" @@ -7880,12 +7863,10 @@ __metadata: languageName: unknown linkType: soft -"@namada/components@npm:0.2.1, @namada/components@workspace:packages/components": +"@namada/components@workspace:packages/components": version: 0.0.0-use.local resolution: "@namada/components@workspace:packages/components" dependencies: - "@namada/config": "workspace:^" - "@namada/utils": "npm:0.2.1" "@types/react": "npm:^17.0.39" "@types/styled-components": "npm:^5.1.26" autoprefixer: "npm:^10.4.16" @@ -7907,7 +7888,7 @@ __metadata: languageName: unknown linkType: soft -"@namada/config@workspace:^, @namada/config@workspace:packages/config": +"@namada/config@workspace:packages/config": version: 0.0.0-use.local resolution: "@namada/config@workspace:packages/config" peerDependencies: @@ -7919,7 +7900,7 @@ __metadata: languageName: unknown linkType: soft -"@namada/crypto@npm:0.2.1, @namada/crypto@workspace:packages/crypto": +"@namada/crypto@workspace:packages/crypto": version: 0.0.0-use.local resolution: "@namada/crypto@workspace:packages/crypto" dependencies: @@ -7936,6 +7917,28 @@ __metadata: languageName: unknown linkType: soft +"@namada/e2e@workspace:e2e": + version: 0.0.0-use.local + resolution: "@namada/e2e@workspace:e2e" + dependencies: + "@types/jest": "npm:^29.0.0" + "@types/node": "npm:^20.4.2" + "@types/puppeteer": "npm:^7.0.4" + eslint: "npm:^8.49.0" + eslint-config-prettier: "npm:^8.8.0" + eslint-plugin-import: "npm:^2.27.5" + eslint-plugin-react: "npm:^7.33.0" + eslint-plugin-react-hooks: "npm:^4.6.0" + http-server: "npm:^14.1.1" + jest: "npm:^29.0.2" + jest-puppeteer: "npm:^9.0.0" + puppeteer: "npm:^20.8.2" + start-server-and-test: "npm:^2.0.0" + terminate: "npm:^2.6.1" + typescript: "npm:^5.1.3" + languageName: unknown + linkType: soft + "@namada/extension@workspace:apps/extension": version: 0.0.0-use.local resolution: "@namada/extension@workspace:apps/extension" @@ -7946,14 +7949,6 @@ __metadata: "@ledgerhq/hw-transport": "npm:^6.30.0" "@ledgerhq/hw-transport-webhid": "npm:^6.28.0" "@ledgerhq/hw-transport-webusb": "npm:^6.28.0" - "@namada/chains": "npm:0.2.1" - "@namada/components": "npm:0.2.1" - "@namada/config": "workspace:^" - "@namada/crypto": "npm:0.2.1" - "@namada/shared": "npm:0.2.1" - "@namada/storage": "npm:0.2.1" - "@namada/types": "npm:0.2.1" - "@namada/utils": "npm:0.2.1" "@svgr/webpack": "npm:^6.3.1" "@types/chrome": "npm:^0.0.237" "@types/dompurify": "npm:^3.0.2" @@ -8021,11 +8016,6 @@ __metadata: dependencies: "@babel/plugin-transform-modules-commonjs": "npm:^7.20.11" "@cosmjs/encoding": "npm:^0.29.0" - "@namada/components": "npm:0.2.1" - "@namada/config": "workspace:^" - "@namada/hooks": "npm:0.2.1" - "@namada/integrations": "npm:0.2.1" - "@namada/utils": "npm:0.2.1" "@svgr/webpack": "npm:^6.3.1" "@types/dompurify": "npm:^3.0.2" "@types/node-forge": "npm:^1.3.6" @@ -8061,14 +8051,10 @@ __metadata: languageName: unknown linkType: soft -"@namada/hooks@npm:0.2.1, @namada/hooks@workspace:packages/hooks": +"@namada/hooks@workspace:packages/hooks": version: 0.0.0-use.local resolution: "@namada/hooks@workspace:packages/hooks" dependencies: - "@namada/chains": "npm:0.2.1" - "@namada/config": "workspace:^" - "@namada/types": "npm:0.2.1" - "@namada/utils": "npm:0.2.1" "@types/react": "npm:^17.0.39" eslint: "npm:^8.49.0" eslint-config-prettier: "npm:^8.8.0" @@ -8081,7 +8067,7 @@ __metadata: languageName: unknown linkType: soft -"@namada/integrations@npm:0.2.1, @namada/integrations@workspace:packages/integrations": +"@namada/integrations@workspace:packages/integrations": version: 0.0.0-use.local resolution: "@namada/integrations@workspace:packages/integrations" dependencies: @@ -8091,9 +8077,6 @@ __metadata: "@cosmjs/tendermint-rpc": "npm:~0.29.5" "@keplr-wallet/types": "npm:^0.10.19" "@metamask/providers": "npm:^10.2.1" - "@namada/config": "workspace:^" - "@namada/types": "npm:0.2.1" - "@namada/utils": "npm:0.2.1" "@types/jest": "npm:^28.1.8" "@types/node": "npm:^18.7.13" eslint: "npm:^8.49.0" @@ -8115,11 +8098,6 @@ __metadata: version: 0.0.0-use.local resolution: "@namada/namada-interface@workspace:apps/namada-interface" dependencies: - "@namada/components": "npm:0.2.1" - "@namada/config": "workspace:^" - "@namada/hooks": "npm:0.2.1" - "@namada/integrations": "npm:0.2.1" - "@namada/utils": "npm:0.2.1" "@playwright/test": "npm:^1.24.1" "@reduxjs/toolkit": "npm:^1.8.0" "@svgr/webpack": "npm:^6.5.1" @@ -8209,17 +8187,13 @@ __metadata: "@ledgerhq/hw-transport": "npm:^6.30.0" "@ledgerhq/hw-transport-webhid": "npm:^6.28.0" "@ledgerhq/hw-transport-webusb": "npm:^6.28.0" - "@namada/chains": "npm:0.2.1" - "@namada/crypto": "npm:0.2.1" - "@namada/shared": "npm:0.2.1" - "@namada/types": "npm:0.2.1" - "@namada/utils": "npm:0.2.1" "@release-it/conventional-changelog": "npm:^8.0.1" "@types/jest": "npm:^29.0.3" "@types/node": "npm:^20.11.4" "@zondax/ledger-namada": "npm:^0.0.4" babel-jest: "npm:^29.0.3" bignumber.js: "npm:^9.1.1" + buffer: "npm:^6.0.3" eslint: "npm:^8.49.0" eslint-config-prettier: "npm:^8.8.0" eslint-import-resolver-typescript: "npm:^3.5.0" @@ -8231,14 +8205,21 @@ __metadata: jsdoc-babel: "npm:^0.5.0" release-it: "npm:^17.0.1" rimraf: "npm:^5.0.5" + slip44: "npm:^3.0.18" ts-jest: "npm:^29.0.1" ts-node: "npm:^10.9.1" + ts-patch: "npm:^3.1.2" tsconfig-paths: "npm:^4.2.0" + typedoc: "npm:^0.25.12" + typedoc-plugin-markdown: "npm:^3.17.1" typescript: "npm:^5.1.3" + typescript-transform-paths: "npm:^3.4.7" + webpack: "npm:^5.90.3" + webpack-cli: "npm:^5.1.4" languageName: unknown linkType: soft -"@namada/shared@npm:0.2.1, @namada/shared@workspace:packages/shared": +"@namada/shared@workspace:packages/shared": version: 0.0.0-use.local resolution: "@namada/shared@workspace:packages/shared" dependencies: @@ -8261,11 +8242,10 @@ __metadata: languageName: unknown linkType: soft -"@namada/storage@npm:0.2.1, @namada/storage@workspace:packages/storage": +"@namada/storage@workspace:packages/storage": version: 0.0.0-use.local resolution: "@namada/storage@workspace:packages/storage" dependencies: - "@namada/config": "workspace:^" "@types/firefox-webext-browser": "npm:^94.0.1" "@types/jest": "npm:^29.0.0" eslint: "npm:^8.49.0" @@ -8280,13 +8260,12 @@ __metadata: languageName: unknown linkType: soft -"@namada/types@npm:0.2.1, @namada/types@workspace:packages/types": +"@namada/types@workspace:packages/types": version: 0.0.0-use.local resolution: "@namada/types@workspace:packages/types" dependencies: "@babel/preset-env": "npm:^7.23.8" "@dao-xyz/borsh": "npm:^5.1.5" - "@namada/config": "workspace:^" "@release-it/conventional-changelog": "npm:^8.0.1" bignumber.js: "npm:^9.1.1" eslint: "npm:^8.49.0" @@ -8302,12 +8281,11 @@ __metadata: languageName: unknown linkType: soft -"@namada/utils@npm:0.2.1, @namada/utils@workspace:packages/utils": +"@namada/utils@workspace:packages/utils": version: 0.0.0-use.local resolution: "@namada/utils@workspace:packages/utils" dependencies: "@cosmjs/json-rpc": "npm:^0.27.1" - "@namada/config": "workspace:^" "@types/bs58": "npm:^4.0.1" "@types/crypto-js": "npm:^4.1.1" "@types/jest": "npm:^28.1.8" @@ -9776,7 +9754,7 @@ __metadata: languageName: node linkType: hard -"@types/estree@npm:^1.0.0": +"@types/estree@npm:^1.0.0, @types/estree@npm:^1.0.5": version: 1.0.5 resolution: "@types/estree@npm:1.0.5" checksum: b3b0e334288ddb407c7b3357ca67dbee75ee22db242ca7c56fe27db4e1a31989cb8af48a84dd401deb787fe10cc6b2ab1ee82dc4783be87ededbe3d53c79c70d @@ -10899,6 +10877,16 @@ __metadata: languageName: node linkType: hard +"@webassemblyjs/ast@npm:1.12.1, @webassemblyjs/ast@npm:^1.12.1": + version: 1.12.1 + resolution: "@webassemblyjs/ast@npm:1.12.1" + dependencies: + "@webassemblyjs/helper-numbers": "npm:1.11.6" + "@webassemblyjs/helper-wasm-bytecode": "npm:1.11.6" + checksum: ba7f2b96c6e67e249df6156d02c69eb5f1bd18d5005303cdc42accb053bebbbde673826e54db0437c9748e97abd218366a1d13fa46859b23cde611b6b409998c + languageName: node + linkType: hard + "@webassemblyjs/floating-point-hex-parser@npm:1.11.1": version: 1.11.1 resolution: "@webassemblyjs/floating-point-hex-parser@npm:1.11.1" @@ -10941,6 +10929,13 @@ __metadata: languageName: node linkType: hard +"@webassemblyjs/helper-buffer@npm:1.12.1": + version: 1.12.1 + resolution: "@webassemblyjs/helper-buffer@npm:1.12.1" + checksum: 0270724afb4601237410f7fd845ab58ccda1d5456a8783aadfb16eaaf3f2c9610c28e4a5bcb6ad880cde5183c82f7f116d5ccfc2310502439d33f14b6888b48a + languageName: node + linkType: hard + "@webassemblyjs/helper-numbers@npm:1.11.1": version: 1.11.1 resolution: "@webassemblyjs/helper-numbers@npm:1.11.1" @@ -11001,6 +10996,18 @@ __metadata: languageName: node linkType: hard +"@webassemblyjs/helper-wasm-section@npm:1.12.1": + version: 1.12.1 + resolution: "@webassemblyjs/helper-wasm-section@npm:1.12.1" + dependencies: + "@webassemblyjs/ast": "npm:1.12.1" + "@webassemblyjs/helper-buffer": "npm:1.12.1" + "@webassemblyjs/helper-wasm-bytecode": "npm:1.11.6" + "@webassemblyjs/wasm-gen": "npm:1.12.1" + checksum: 0546350724d285ae3c26e6fc444be4c3b5fb824f3be0ec8ceb474179dc3f4430336dd2e36a44b3e3a1a6815960e5eec98cd9b3a8ec66dc53d86daedd3296a6a2 + languageName: node + linkType: hard + "@webassemblyjs/ieee754@npm:1.11.1": version: 1.11.1 resolution: "@webassemblyjs/ieee754@npm:1.11.1" @@ -11083,6 +11090,22 @@ __metadata: languageName: node linkType: hard +"@webassemblyjs/wasm-edit@npm:^1.12.1": + version: 1.12.1 + resolution: "@webassemblyjs/wasm-edit@npm:1.12.1" + dependencies: + "@webassemblyjs/ast": "npm:1.12.1" + "@webassemblyjs/helper-buffer": "npm:1.12.1" + "@webassemblyjs/helper-wasm-bytecode": "npm:1.11.6" + "@webassemblyjs/helper-wasm-section": "npm:1.12.1" + "@webassemblyjs/wasm-gen": "npm:1.12.1" + "@webassemblyjs/wasm-opt": "npm:1.12.1" + "@webassemblyjs/wasm-parser": "npm:1.12.1" + "@webassemblyjs/wast-printer": "npm:1.12.1" + checksum: 972f5e6c522890743999e0ed45260aae728098801c6128856b310dd21f1ee63435fc7b518e30e0ba1cdafd0d1e38275829c1e4451c3536a1d9e726e07a5bba0b + languageName: node + linkType: hard + "@webassemblyjs/wasm-gen@npm:1.11.1": version: 1.11.1 resolution: "@webassemblyjs/wasm-gen@npm:1.11.1" @@ -11109,6 +11132,19 @@ __metadata: languageName: node linkType: hard +"@webassemblyjs/wasm-gen@npm:1.12.1": + version: 1.12.1 + resolution: "@webassemblyjs/wasm-gen@npm:1.12.1" + dependencies: + "@webassemblyjs/ast": "npm:1.12.1" + "@webassemblyjs/helper-wasm-bytecode": "npm:1.11.6" + "@webassemblyjs/ieee754": "npm:1.11.6" + "@webassemblyjs/leb128": "npm:1.11.6" + "@webassemblyjs/utf8": "npm:1.11.6" + checksum: 1e257288177af9fa34c69cab94f4d9036ebed611f77f3897c988874e75182eeeec759c79b89a7a49dd24624fc2d3d48d5580b62b67c4a1c9bfbdcd266b281c16 + languageName: node + linkType: hard + "@webassemblyjs/wasm-opt@npm:1.11.1": version: 1.11.1 resolution: "@webassemblyjs/wasm-opt@npm:1.11.1" @@ -11133,6 +11169,18 @@ __metadata: languageName: node linkType: hard +"@webassemblyjs/wasm-opt@npm:1.12.1": + version: 1.12.1 + resolution: "@webassemblyjs/wasm-opt@npm:1.12.1" + dependencies: + "@webassemblyjs/ast": "npm:1.12.1" + "@webassemblyjs/helper-buffer": "npm:1.12.1" + "@webassemblyjs/wasm-gen": "npm:1.12.1" + "@webassemblyjs/wasm-parser": "npm:1.12.1" + checksum: 992a45e1f1871033c36987459436ab4e6430642ca49328e6e32a13de9106fe69ae6c0ac27d7050efd76851e502d11cd1ac0e06b55655dfa889ad82f11a2712fb + languageName: node + linkType: hard + "@webassemblyjs/wasm-parser@npm:1.11.1": version: 1.11.1 resolution: "@webassemblyjs/wasm-parser@npm:1.11.1" @@ -11161,6 +11209,20 @@ __metadata: languageName: node linkType: hard +"@webassemblyjs/wasm-parser@npm:1.12.1, @webassemblyjs/wasm-parser@npm:^1.12.1": + version: 1.12.1 + resolution: "@webassemblyjs/wasm-parser@npm:1.12.1" + dependencies: + "@webassemblyjs/ast": "npm:1.12.1" + "@webassemblyjs/helper-api-error": "npm:1.11.6" + "@webassemblyjs/helper-wasm-bytecode": "npm:1.11.6" + "@webassemblyjs/ieee754": "npm:1.11.6" + "@webassemblyjs/leb128": "npm:1.11.6" + "@webassemblyjs/utf8": "npm:1.11.6" + checksum: e85cec1acad07e5eb65b92d37c8e6ca09c6ca50d7ca58803a1532b452c7321050a0328c49810c337cc2dfd100c5326a54d5ebd1aa5c339ebe6ef10c250323a0e + languageName: node + linkType: hard + "@webassemblyjs/wast-printer@npm:1.11.1": version: 1.11.1 resolution: "@webassemblyjs/wast-printer@npm:1.11.1" @@ -11181,6 +11243,16 @@ __metadata: languageName: node linkType: hard +"@webassemblyjs/wast-printer@npm:1.12.1": + version: 1.12.1 + resolution: "@webassemblyjs/wast-printer@npm:1.12.1" + dependencies: + "@webassemblyjs/ast": "npm:1.12.1" + "@xtuc/long": "npm:4.2.2" + checksum: 39bf746eb7a79aa69953f194943bbc43bebae98bd7cadd4d8bc8c0df470ca6bf9d2b789effaa180e900fab4e2691983c1f7d41571458bd2a26267f2f0c73705a + languageName: node + linkType: hard + "@webpack-cli/configtest@npm:^1.2.0": version: 1.2.0 resolution: "@webpack-cli/configtest@npm:1.2.0" @@ -11201,6 +11273,16 @@ __metadata: languageName: node linkType: hard +"@webpack-cli/configtest@npm:^2.1.1": + version: 2.1.1 + resolution: "@webpack-cli/configtest@npm:2.1.1" + peerDependencies: + webpack: 5.x.x + webpack-cli: 5.x.x + checksum: a8da1f15702cb289807da99235ed95326ed7dabeb1a36ca59bd3a5dbe6adcc946a9a2767936050fc4d5ed14efab0e5b5a641dfe8e3d862c36caa5791ac12759d + languageName: node + linkType: hard + "@webpack-cli/info@npm:^1.5.0": version: 1.5.0 resolution: "@webpack-cli/info@npm:1.5.0" @@ -11222,6 +11304,16 @@ __metadata: languageName: node linkType: hard +"@webpack-cli/info@npm:^2.0.2": + version: 2.0.2 + resolution: "@webpack-cli/info@npm:2.0.2" + peerDependencies: + webpack: 5.x.x + webpack-cli: 5.x.x + checksum: ca88a35604dc9aedac7c26e8f6793c5039dc1eea2b12a85fbfd669a5f21ecf9cf169d7fd157ea366a62666e3fa05b776306a96742ac61a9868f44fdce6b40f7d + languageName: node + linkType: hard + "@webpack-cli/serve@npm:^1.7.0": version: 1.7.0 resolution: "@webpack-cli/serve@npm:1.7.0" @@ -11247,6 +11339,19 @@ __metadata: languageName: node linkType: hard +"@webpack-cli/serve@npm:^2.0.5": + version: 2.0.5 + resolution: "@webpack-cli/serve@npm:2.0.5" + peerDependencies: + webpack: 5.x.x + webpack-cli: 5.x.x + peerDependenciesMeta: + webpack-dev-server: + optional: true + checksum: 36079d34971ff99a58b66b13f4184dcdd8617853c48cccdbc3f9ab7ea9e5d4fcf504e873c298ea7aa15e0b51ad2c4aee4d7a70bd7d9364e60f57b0eb93ca15fc + languageName: node + linkType: hard + "@xtuc/ieee754@npm:^1.2.0": version: 1.2.0 resolution: "@xtuc/ieee754@npm:1.2.0" @@ -11734,6 +11839,13 @@ __metadata: languageName: node linkType: hard +"ansi-sequence-parser@npm:^1.1.0": + version: 1.1.1 + resolution: "ansi-sequence-parser@npm:1.1.1" + checksum: ab2259ccf69f145ecf1418d4e71524158828f44afdf37c7536677871f4cebaa8b176fcb95de8f94a68129357dddc59586597da25f9d4ebf9968f6ef022bf0b31 + languageName: node + linkType: hard + "ansi-styles@npm:^3.2.0, ansi-styles@npm:^3.2.1": version: 3.2.1 resolution: "ansi-styles@npm:3.2.1" @@ -14181,6 +14293,13 @@ __metadata: languageName: node linkType: hard +"commander@npm:^10.0.1": + version: 10.0.1 + resolution: "commander@npm:10.0.1" + checksum: 53f33d8927758a911094adadda4b2cbac111a5b377d8706700587650fd8f45b0bbe336de4b5c3fe47fd61f420a3d9bd452b6e0e6e5600a7e74d7bf0174f6efe3 + languageName: node + linkType: hard + "commander@npm:^2.20.0, commander@npm:^2.6.0": version: 2.20.3 resolution: "commander@npm:2.20.3" @@ -16498,6 +16617,16 @@ __metadata: languageName: node linkType: hard +"enhanced-resolve@npm:^5.16.0": + version: 5.16.0 + resolution: "enhanced-resolve@npm:5.16.0" + dependencies: + graceful-fs: "npm:^4.2.4" + tapable: "npm:^2.2.0" + checksum: dd69669cbb638ccacefd03e04d5e195ee6a99b7f5f8012f86d2df7781834de357923e06064ea621137c4ce0b37cc12b872b4e6d1ac6ab15fe98e7f1dfbbb08c4 + languageName: node + linkType: hard + "entities@npm:^2.0.0": version: 2.2.0 resolution: "entities@npm:2.2.0" @@ -19367,7 +19496,7 @@ __metadata: languageName: node linkType: hard -"graceful-fs@npm:^4.1.9": +"graceful-fs@npm:^4.1.9, graceful-fs@npm:^4.2.11": version: 4.2.11 resolution: "graceful-fs@npm:4.2.11" checksum: 386d011a553e02bc594ac2ca0bd6d9e4c22d7fa8cfbfc448a6d148c59ea881b092db9dbe3547ae4b88e55f1b01f7c4a2ecc53b310c042793e63aa44cf6c257f2 @@ -24515,6 +24644,13 @@ __metadata: languageName: node linkType: hard +"jsonc-parser@npm:^3.2.0": + version: 3.2.1 + resolution: "jsonc-parser@npm:3.2.1" + checksum: ada66dec143d7f9cb0e2d0d29c69e9ce40d20f3a4cb96b0c6efb745025ac7f9ba647d7ac0990d0adfc37a2d2ae084a12009a9c833dbdbeadf648879a99b9df89 + languageName: node + linkType: hard + "jsonfile@npm:^4.0.0": version: 4.0.0 resolution: "jsonfile@npm:4.0.0" @@ -25260,6 +25396,13 @@ __metadata: languageName: node linkType: hard +"lunr@npm:^2.3.9": + version: 2.3.9 + resolution: "lunr@npm:2.3.9" + checksum: 77d7dbb4fbd602aac161e2b50887d8eda28c0fa3b799159cee380fbb311f1e614219126ecbbd2c3a9c685f1720a8109b3c1ca85cc893c39b6c9cc6a62a1d8a8b + languageName: node + linkType: hard + "luxon@npm:^3.0.1": version: 3.0.1 resolution: "luxon@npm:3.0.1" @@ -25387,7 +25530,7 @@ __metadata: languageName: node linkType: hard -"marked@npm:^4.0.10, marked@npm:^4.2.3": +"marked@npm:^4.0.10, marked@npm:^4.2.3, marked@npm:^4.3.0": version: 4.3.0 resolution: "marked@npm:4.3.0" bin: @@ -25652,7 +25795,7 @@ __metadata: languageName: node linkType: hard -"minimatch@npm:^9.0.1": +"minimatch@npm:^9.0.1, minimatch@npm:^9.0.3": version: 9.0.3 resolution: "minimatch@npm:9.0.3" dependencies: @@ -25675,7 +25818,7 @@ __metadata: languageName: node linkType: hard -"minimist@npm:^1.2.7": +"minimist@npm:^1.2.7, minimist@npm:^1.2.8": version: 1.2.8 resolution: "minimist@npm:1.2.8" checksum: 19d3fcdca050087b84c2029841a093691a91259a47def2f18222f41e7645a0b7c44ef4b40e88a1e58a40c84d2ef0ee6047c55594d298146d0eb3f6b737c20ce6 @@ -31402,6 +31545,18 @@ __metadata: languageName: node linkType: hard +"shiki@npm:^0.14.7": + version: 0.14.7 + resolution: "shiki@npm:0.14.7" + dependencies: + ansi-sequence-parser: "npm:^1.1.0" + jsonc-parser: "npm:^3.2.0" + vscode-oniguruma: "npm:^1.7.0" + vscode-textmate: "npm:^8.0.0" + checksum: 5c7fcbb870d0facccc7ae2f3410a28121f8e0b3f298e4e956de817ad6ab60a4c7e20a9184edfe50a93447addbb88b95b69e6ef88ac16ac6ca3e94c50771a6459 + languageName: node + linkType: hard + "side-channel@npm:^1.0.4": version: 1.0.4 resolution: "side-channel@npm:1.0.4" @@ -31537,6 +31692,13 @@ __metadata: languageName: node linkType: hard +"slip44@npm:^3.0.18": + version: 3.0.18 + resolution: "slip44@npm:3.0.18" + checksum: a274c30b0422a0c25fe84fb96b966b118ca6051bae2fbcc6d848690515ee1d2cb38059f0ea348011156f5fa7da5668380d22c5200f270e88801d346c213a47a7 + languageName: node + linkType: hard + "smart-buffer@npm:^4.2.0": version: 4.2.0 resolution: "smart-buffer@npm:4.2.0" @@ -32890,6 +33052,28 @@ __metadata: languageName: node linkType: hard +"terser-webpack-plugin@npm:^5.3.10": + version: 5.3.10 + resolution: "terser-webpack-plugin@npm:5.3.10" + dependencies: + "@jridgewell/trace-mapping": "npm:^0.3.20" + jest-worker: "npm:^27.4.5" + schema-utils: "npm:^3.1.1" + serialize-javascript: "npm:^6.0.1" + terser: "npm:^5.26.0" + peerDependencies: + webpack: ^5.1.0 + peerDependenciesMeta: + "@swc/core": + optional: true + esbuild: + optional: true + uglify-js: + optional: true + checksum: 66d1ed3174542560911cf96f4716aeea8d60e7caab212291705d50072b6ba844c7391442541b13c848684044042bea9ec87512b8506528c12854943da05faf91 + languageName: node + linkType: hard + "terser-webpack-plugin@npm:^5.3.7": version: 5.3.9 resolution: "terser-webpack-plugin@npm:5.3.9" @@ -32940,6 +33124,20 @@ __metadata: languageName: node linkType: hard +"terser@npm:^5.26.0": + version: 5.29.2 + resolution: "terser@npm:5.29.2" + dependencies: + "@jridgewell/source-map": "npm:^0.3.3" + acorn: "npm:^8.8.2" + commander: "npm:^2.20.0" + source-map-support: "npm:~0.5.20" + bin: + terser: bin/terser + checksum: a6f1e26725e3dc99943d7173a3fca8bee21418a3ff39f37053fecd6a988b5341432d535721642807e9c24604aff64410577e9aed3200d9345c89b176b0ba3d65 + languageName: node + linkType: hard + "test-exclude@npm:^6.0.0": version: 6.0.0 resolution: "test-exclude@npm:6.0.0" @@ -33460,6 +33658,23 @@ __metadata: languageName: node linkType: hard +"ts-patch@npm:^3.1.2": + version: 3.1.2 + resolution: "ts-patch@npm:3.1.2" + dependencies: + chalk: "npm:^4.1.2" + global-prefix: "npm:^3.0.0" + minimist: "npm:^1.2.8" + resolve: "npm:^1.22.2" + semver: "npm:^7.5.4" + strip-ansi: "npm:^6.0.1" + bin: + ts-patch: bin/ts-patch.js + tspc: bin/tspc.js + checksum: 773f55de5cae7592af85ba9216b8b5baee9cd440ac085466152bcce7fbcfaeab0f2774b013f97a399f833a4c409646acc9579d7bb6c1f9b969b08bc492038a56 + languageName: node + linkType: hard + "tsconfig-paths-webpack-plugin@npm:^4.1.0": version: 4.1.0 resolution: "tsconfig-paths-webpack-plugin@npm:4.1.0" @@ -33722,6 +33937,33 @@ __metadata: languageName: node linkType: hard +"typedoc-plugin-markdown@npm:^3.17.1": + version: 3.17.1 + resolution: "typedoc-plugin-markdown@npm:3.17.1" + dependencies: + handlebars: "npm:^4.7.7" + peerDependencies: + typedoc: ">=0.24.0" + checksum: 5c9322cd6b5218b1c8b18e6c9df45ad0f99dea9b9cee4006f1f286b04725db47e26856b3e07069beabbd65d8357da34563707d50027b19bb18fd3633a3591349 + languageName: node + linkType: hard + +"typedoc@npm:^0.25.12": + version: 0.25.12 + resolution: "typedoc@npm:0.25.12" + dependencies: + lunr: "npm:^2.3.9" + marked: "npm:^4.3.0" + minimatch: "npm:^9.0.3" + shiki: "npm:^0.14.7" + peerDependencies: + typescript: 4.6.x || 4.7.x || 4.8.x || 4.9.x || 5.0.x || 5.1.x || 5.2.x || 5.3.x || 5.4.x + bin: + typedoc: bin/typedoc + checksum: 35157a90954ed67243bc1ad430781de381431959c62e24f8a8688c4ebae62c2ee11d404002dfd43a0df3bf96721d94fce928423fe1f91f1ed40c99f29c5276aa + languageName: node + linkType: hard + "typescript-plugin-styled-components@npm:^2.0.0": version: 2.0.0 resolution: "typescript-plugin-styled-components@npm:2.0.0" @@ -33731,6 +33973,17 @@ __metadata: languageName: node linkType: hard +"typescript-transform-paths@npm:^3.4.7": + version: 3.4.7 + resolution: "typescript-transform-paths@npm:3.4.7" + dependencies: + minimatch: "npm:^3.0.4" + peerDependencies: + typescript: ">=3.6.5" + checksum: fc17c07caabab71702c236b52c7be6ffddfa5224949a1080e5e359d972c719d652a34ce1770aedd308a29afce87d9055ae43057d1041c81ab696d92bd945136e + languageName: node + linkType: hard + "typescript@npm:^5.1.3": version: 5.1.3 resolution: "typescript@npm:5.1.3" @@ -34283,6 +34536,20 @@ __metadata: languageName: node linkType: hard +"vscode-oniguruma@npm:^1.7.0": + version: 1.7.0 + resolution: "vscode-oniguruma@npm:1.7.0" + checksum: bef0073c665ddf8c86e51da94529c905856559e9aba97a9882f951acd572da560384775941ab6e7e8db94d9c578b25fefb951e4b73c37e8712e16b0231de2689 + languageName: node + linkType: hard + +"vscode-textmate@npm:^8.0.0": + version: 8.0.0 + resolution: "vscode-textmate@npm:8.0.0" + checksum: 836f7fe73fc94998a38ca193df48173a2b6eab08b4943d83c8cac9a2a0c3546cfdab4cf1b10b890ec4a4374c5bee03a885ef0e83e7fd2bd618cf00781c017c04 + languageName: node + linkType: hard + "w3c-hr-time@npm:^1.0.2": version: 1.0.2 resolution: "w3c-hr-time@npm:1.0.2" @@ -34388,6 +34655,16 @@ __metadata: languageName: node linkType: hard +"watchpack@npm:^2.4.1": + version: 2.4.1 + resolution: "watchpack@npm:2.4.1" + dependencies: + glob-to-regexp: "npm:^0.4.1" + graceful-fs: "npm:^4.1.2" + checksum: c694de0a61004e587a8a0fdc9cfec20ee692c52032d9ab2c2e99969a37fdab9e6e1bd3164ed506f9a13f7c83e65563d563e0d6b87358470cdb7309b83db78683 + languageName: node + linkType: hard + "wbuf@npm:^1.1.0, wbuf@npm:^1.7.3": version: 1.7.3 resolution: "wbuf@npm:1.7.3" @@ -34624,6 +34901,38 @@ __metadata: languageName: node linkType: hard +"webpack-cli@npm:^5.1.4": + version: 5.1.4 + resolution: "webpack-cli@npm:5.1.4" + dependencies: + "@discoveryjs/json-ext": "npm:^0.5.0" + "@webpack-cli/configtest": "npm:^2.1.1" + "@webpack-cli/info": "npm:^2.0.2" + "@webpack-cli/serve": "npm:^2.0.5" + colorette: "npm:^2.0.14" + commander: "npm:^10.0.1" + cross-spawn: "npm:^7.0.3" + envinfo: "npm:^7.7.3" + fastest-levenshtein: "npm:^1.0.12" + import-local: "npm:^3.0.2" + interpret: "npm:^3.1.1" + rechoir: "npm:^0.8.0" + webpack-merge: "npm:^5.7.3" + peerDependencies: + webpack: 5.x.x + peerDependenciesMeta: + "@webpack-cli/generators": + optional: true + webpack-bundle-analyzer: + optional: true + webpack-dev-server: + optional: true + bin: + webpack-cli: bin/cli.js + checksum: 4266909ae5e2e662c8790ac286e965b2c7fd5a4a2f07f48e28576234c9a5f631847ccddc18e1b3281c7b4be04a7ff4717d2636033a322dde13ac995fd0d9de10 + languageName: node + linkType: hard + "webpack-dev-middleware@npm:^5.3.1": version: 5.3.1 resolution: "webpack-dev-middleware@npm:5.3.1" @@ -34872,6 +35181,43 @@ __metadata: languageName: node linkType: hard +"webpack@npm:^5.90.3": + version: 5.91.0 + resolution: "webpack@npm:5.91.0" + dependencies: + "@types/eslint-scope": "npm:^3.7.3" + "@types/estree": "npm:^1.0.5" + "@webassemblyjs/ast": "npm:^1.12.1" + "@webassemblyjs/wasm-edit": "npm:^1.12.1" + "@webassemblyjs/wasm-parser": "npm:^1.12.1" + acorn: "npm:^8.7.1" + acorn-import-assertions: "npm:^1.9.0" + browserslist: "npm:^4.21.10" + chrome-trace-event: "npm:^1.0.2" + enhanced-resolve: "npm:^5.16.0" + es-module-lexer: "npm:^1.2.1" + eslint-scope: "npm:5.1.1" + events: "npm:^3.2.0" + glob-to-regexp: "npm:^0.4.1" + graceful-fs: "npm:^4.2.11" + json-parse-even-better-errors: "npm:^2.3.1" + loader-runner: "npm:^4.2.0" + mime-types: "npm:^2.1.27" + neo-async: "npm:^2.6.2" + schema-utils: "npm:^3.2.0" + tapable: "npm:^2.1.1" + terser-webpack-plugin: "npm:^5.3.10" + watchpack: "npm:^2.4.1" + webpack-sources: "npm:^3.2.3" + peerDependenciesMeta: + webpack-cli: + optional: true + bin: + webpack: bin/webpack.js + checksum: 74a3e0ea1c9a492accf035317f31769ffeaaab415811524b9f17bc7bf7012c5b6e1a9860df5ca6903f3ae2618727b801eb47d9351a2595dfffb25941d368b88c + languageName: node + linkType: hard + "webrtc-adapter@npm:^6.4.0": version: 6.4.8 resolution: "webrtc-adapter@npm:6.4.8"