Socket
Book a DemoInstallSign in
Socket

@keyban/sdk-base

Package Overview
Dependencies
Maintainers
3
Versions
22
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@keyban/sdk-base

Keyban Javascript SDK provides core functionalities for the MPC wallet solution, supporting web and Node.js apps with TypeScript, custom storage, and Ethereum blockchain integration.

latest
npmnpm
Version
0.12.1
Version published
Maintainers
3
Created
Source

Keyban JavaScript SDK

Overview

The Keyban JavaScript SDK provides the core functionality for Keyban's MPC wallet solution, simplifying the development of web and Node.js applications. It offers TypeScript-first APIs, client-share persistence hooks, network-specific helpers and GraphQL documents to integrate wallet features (balances, NFTs, transfers) into your app.

This README has been extended with a short API reference, GraphQL import hints, error handling guidance and a developer setup section to help integrators and contributors.

Key Features

  • TypeScript-first with full typings.
  • Client share persistence via a built-in provider (and ability to provide a custom ClientShareProvider).
  • Blockchain support: EVM (Ethereum Anvil, Polygon Amoy), Starknet (Devnet, Sepolia, Mainnet), and Stellar (Quickstart, Testnet, Mainnet).
  • ERC‑20 and NFT (ERC‑721/1155) transfer helpers where supported.
  • Exported GraphQL documents for queries/subscriptions.
  • Efficient bundling with tsup.

Installation

npm install @keyban/sdk-base

Quickstart

Initialize the client

import { KeybanClient, KeybanNetwork } from "@keyban/sdk-base";

const client = new KeybanClient({
  appId: "your-keyban-app-id",
  network: KeybanNetwork.EthereumAnvil,
});

Initialize and get an account

const account = await client.initialize();
console.log(account.address);

Common operations

  • Sign a message: account.signMessage('...').
  • Estimate fees: account.estimateTransfer(to).
  • Transfer native: account.transfer(to, value).
  • Transfer ERC-20: account.transferERC20({ contractAddress, to, value }).
  • Transfer NFT: account.transferNft({ contractAddress, to, tokenId, standard, value? }).

See examples below for full snippets.

Short API reference (essential types & signatures)

This is a short, high-level reference to the most commonly used types and functions. For the complete API please consult the generated docs or the TypeScript d.ts files in the package.

  • KeybanClient constructor:

    • new KeybanClient(config: { apiUrl?: string|URL; appId: string; clientShareProvider?: ClientShareProvider; network: KeybanNetwork; })
  • KeybanClient.prototype.initialize(): Promise<KeybanAccount>

  • KeybanAccount (abstract) — common methods:

    • transfer(to: string, value: bigint, fees?: FeeDetails): Promise<string>
    • transferERC20(params: TransferERC20Params): Promise<string>
    • transferNft(params: TransferNftParams): Promise<string>
    • estimateTransfer(to: string): Promise<FeesEstimation>
    • estimateERC20Transfer(params: EstimateERC20TransferParams): Promise<FeesEstimation>
    • estimateNftTransfer(params: EstimateNftTransferParams): Promise<FeesEstimation>
    • signMessage(message: string): Promise<string | string[]>
  • Balance / format:

    • type Balance = { raw: string | bigint; decimals?: number; symbol?: string; isNative?: boolean; isFees?: boolean; }
    • formatBalance(client: KeybanClient, balance: Balance, token?: KeybanToken): string
  • ClientShareProvider (custom storage):

    interface ClientShareProvider {
      get(key: string): Promise<string | null>;
      set(key: string, clientShare: string): Promise<void | unknown>;
    }
    
  • GraphQL exports (short list, imported from '@keyban/sdk-base/graphql'):

    • walletBalanceDocument
    • walletTokenBalancesDocument
    • tokenBalancesSubscriptionDocument
    • walletNftsDocument
    • nftBalancesSubscriptionDocument
    • (See package exports for the full list)

By default the SDK uses the built-in provider that persists client-share via Keyban's API. If you need to manage client shares yourself (for compliance, storage choice, or custom auth), implement ClientShareProvider:

Example:

class MyClientShareProvider implements ClientShareProvider {
  async get(key: string): Promise<string | null> {
    const res = await fetch(`/api/clientShare?key=${encodeURIComponent(key)}`);
    if (!res.ok) return null;
    return res.text();
  }

  async set(key: string, clientShare: string): Promise<void> {
    const res = await fetch(`/api/clientShare`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: "Bearer ...",
      },
      body: JSON.stringify({ key, clientShare }),
    });
    if (!res.ok) throw new Error("failed to save client share");
  }
}

Security recommendations:

  • Protect the server endpoints with proper authentication and authorization.
  • Use per-user keys (not a single shared key) to isolate client-shares per account.
  • Record access logs and enable rotation/expiry for stored shares if applicable.
  • Never expose raw client shares in frontend logs or error messages.

GraphQL / Apollo notes

We export ready-to-use GraphQL documents. Typical imports:

import {
  walletBalanceDocument,
  walletTokenBalancesDocument,
} from "@keyban/sdk-base/graphql";

const { data } = await client.apolloClient.query({
  query: walletTokenBalancesDocument,
  variables: { walletId: account.address, first: 20 },
});

Pagination:

  • Use first + cursor after pattern returned by the documents.
  • Subscriptions: use the subscription documents (tokenBalancesSubscriptionDocument, nftBalancesSubscriptionDocument) to get real-time updates. Unsubscribe when no longer needed.

Error handling (common SDK errors)

The SDK exposes typed errors to help handling:

  • SdkError / SdkErrorTypes — domain errors (AddressInvalid, AmountInvalid, InsufficientFunds, NftNotFound, etc.)
  • CryptoError / CryptoErrorType — cryptographic failures (Encrypt, Decrypt, ImportKey, ...)
  • JwtError / JwtErrorType — token/parsing issues
  • IFrameApiError / IFrameApiErrorType

Example handling:

import { SdkError, SdkErrorTypes } from "@keyban/sdk-base";

try {
  await account.transfer(to, value);
} catch (err) {
  if (err instanceof SdkError) {
    if (err.type === SdkErrorTypes.InsufficientFunds) {
      // handle
    } else {
      console.error("SDK error:", err.message);
    }
  } else {
    console.error("Unexpected error:", err);
  }
}

Formatting balances & React helpers

  • Use formatBalance(client, balance, token?) for plain JS usage.
  • In React apps using the React SDK, prefer FormattedBalance component / useFormattedBalance hook from @keyban/sdk-react when rendering UI.

Supported blockchains — notes & fee units

Supported networks:

  • EVM: EthereumAnvil, PolygonAmoy — fees are EIP-1559 (maxFeePerGas/maxPriorityFeePerGas), fee unit: gwei (decimals: 9)
  • Starknet: Devnet/Sepolia/Mainnet — specific remark: Starknet fees and unit differ; check network docs
  • Stellar: Quickstart/Testnet/Mainnet — fees are expressed in stroops (1 stroop = 10^-7 XLM)

When switching networks be mindful of unit conversions (decimals) and fee formats.

Development

Quick developer commands:

  • Build the package:
    • npm run build
  • Run type checks:
    • npm run typecheck
  • Run tests:
    • npm test
  • Lint:
    • npm run lint

Local linking for app development:

  • Use your package manager's workspaces or npm pack / npm install ../path/to/packed.tgz to test local changes.
  • For monorepos using pnpm/workspaces: use pnpm -w install and workspace linking patterns as appropriate.

Compatibility & bundling

  • Node: modern LTS versions recommended (Node 18+).
  • Browser: built to be consumable by bundlers like Vite/webpack/rollup. When targeting browsers, ensure polyfills/shims for bigints if necessary in older environments.
  • Bundling: we use tsup for building distributable bundles — follow package build scripts in monorepo.

See also

  • React SDK: https://github.com/keyban-io/dap/tree/main/sdk/packages/sdk-react and docs at https://docs.keyban.io/api/sdk-react
  • Full API reference: https://docs.keyban.io/api/sdk-base/
  • GraphQL reference: check @keyban/sdk-base/graphql exports.

Keywords

polygon

FAQs

Package last updated on 04 Nov 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts