# @lightsparkdev/wallet-sdk

> Lightspark JS Wallet SDK

Latest version **0.13.3** (published 2024-09-24) · Apache-2.0 license · 0 weekly downloads

> **Deprecated.** This package is deprecated.

## Install

```sh
npm install @lightsparkdev/wallet-sdk
pnpm add @lightsparkdev/wallet-sdk
yarn add @lightsparkdev/wallet-sdk
bun add @lightsparkdev/wallet-sdk
```

## Health

**Score 10/100 (F)** — status: deprecated.

Negative: deprecated.

## Facts

| | |
|---|---|
| Version | 0.13.3 |
| Published | 2024-09-24 |
| First published | 2023-05-03 |
| Weekly downloads | 0 |
| License | Apache-2.0 |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Node | >=18 |
| Dependencies | 10 |
| Unpacked size | 1006.1 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 47 |
| Author | Lightspark Inc. |
| Maintainers | coreymartin, jeremyatlightspark |
| Keywords | lightspark, bitcoin, lightning, payments, typescript |

## Links

- npm: https://www.npmjs.com/package/@lightsparkdev/wallet-sdk
- Repository: https://github.com/lightsparkdev/js-sdk
- Issues: https://github.com/lightsparkdev/js-sdk/issues
- npm.io page: https://npm.io/package/@lightsparkdev/wallet-sdk

## Dependencies (10)

- [ws](https://npm.io/package/ws.md) ^8.12.1
- [dayjs](https://npm.io/package/dayjs.md) ^1.11.7
- [react](https://npm.io/package/react.md) ^18.2.0
- [dotenv](https://npm.io/package/dotenv.md) ^16.3.1
- [graphql](https://npm.io/package/graphql.md) ^16.6.0
- [graphql-ws](https://npm.io/package/graphql-ws.md) ^5.11.3
- [crypto-browserify](https://npm.io/package/crypto-browserify.md) ^3.12.0
- [zen-observable-ts](https://npm.io/package/zen-observable-ts.md) ^1.1.0
- [@lightsparkdev/core](https://npm.io/package/@lightsparkdev/core.md) 1.2.2
- [@react-native-async-storage/async-storage](https://npm.io/package/@react-native-async-storage/async-storage.md) ^1.18.1

## Alternatives

- [@openai/codex-sdk](https://npm.io/package/@openai/codex-sdk.md) — 731.4K weekly downloads
- [babel-plugin-transform-react-jsx](https://npm.io/package/babel-plugin-transform-react-jsx.md) — 565.0K weekly downloads
- [babel-helper-remove-or-void](https://npm.io/package/babel-helper-remove-or-void.md) — 508.5K weekly downloads
- [@pnpm/store-controller-types](https://npm.io/package/@pnpm/store-controller-types.md) — 186.9K weekly downloads
- [react-native-signature-canvas](https://npm.io/package/react-native-signature-canvas.md) — 155.6K weekly downloads

## Recent versions

- 0.13.3 (latest) — 2024-09-24
- 0.13.2 — 2024-08-16
- 0.13.1 — 2024-08-01
- 0.13.0 — 2024-08-01
- 0.12.15 — 2024-07-25
- 0.12.14 — 2024-07-12
- 0.12.13 — 2024-06-12
- 0.12.12 — 2024-06-04
- 0.12.11 — 2024-03-08
- 0.12.10 — 2024-03-08
- 0.12.9 — 2024-02-27
- 0.12.8 — 2024-02-12
- 0.12.6 — 2024-02-09
- 0.12.5 — 2024-02-01
- 0.12.4 — 2024-01-10
- … 65 more at https://npm.io/package/@lightsparkdev/wallet-sdk/versions

## README

# The Lightspark JS+TS Wallet SDK

![npm (scoped)](https://img.shields.io/npm/v/@lightsparkdev/wallet-sdk)

This is the Lightspark Typescript Wallet SDK, which can be used from a browser or React Native environment. See the examples directory for some examples of how to use it! If you're using this SDK with React, you might also want to check out our [react-wallet](../react-wallet/README.md) library, which wraps this SDK and provides some convenient React hooks.

## Getting started

To use the SDK, you'll need to install it from npm:

```bash
$ npm install @lightsparkdev/wallet-sdk
```

The first step is to create a LightsparkClient object, which is the main interaction point with the wallet sdk.

```typescript
import { LightsparkClient } from "@lightsparkdev/wallet-sdk";

const client = new LightsparkClient();
```

### Authentication via JWT

The current version of the SDK supports JWT authentication, which is intended for client-side use. To authenticate, you'll need to login using your lightspark account ID and
a JWT allocated for the user by your own server.

![jwt diagram](./docs-media/jwt-diagram.png)

First, you'll need to register your account public key with Lightspark. You can do this from the [Lightspark Account Settings page](https://app.lightspark.com/account#security). You'll need to provide the public key for the account you want to use to sign JWTs. You can manually generate a keypair using the _ES256_ algorithm, or install and use our [Wallet CLI](https://docs.lightspark.com/wallet-sdk/wallet-cli?language=Typescript) which can generate a new keypair for you:

```bash
lightspark-wallet init-env
```

This will prompt you for your account ID and generate a JWT signing keypair that is stored in an env file:

```bash
cat ~/.lightsparkenv
```

You can then copy the contents of the public key file into the "JWT Public Key" field on the API Tokens page. You'll also want to copy the private key into your server code (or rather in secret keystore or environment variable), so that you can use it to sign JWTs.

Next, you'll need to create a JWT for the user. You should expose an endpoint from your backend to create these tokens. For example, to create a JWT from a typescript+node server:

```typescript
import * as jwt from "jsonwebtoken";

// Create a JSON object that contains the claims for your JWT.
const claims = {
  aud: "https://api.lightspark.com",
  // Any unique identifier for the user.
  sub: "511c7eb8-9afe-4f69-989a-8d1113a33f3d",
  // True to use the test environment, false to use the production environment.
  test: true,
  iat: 1516239022,
  // Expriation time for the JWT.
  exp: 1799393363,
};

// Call the `sign()` method on the `jsonwebtoken` library, passing in the JSON object and your private key.
const token = jwt.sign(claims, "your private key");

// Now send the token back to the client so that they can use it to authenticate with the Lightspark SDK.
```

Now on the client, you can login using the JWT and your company's account ID from the account settings page:

```typescript
await client.loginWithJWT(ACCOUNT_ID, jwt, new LocalStorageJwtStorage());
```

You'll notice that this request takes a parameter which is an implementation of JwtStorage. This can be used to save credentials for the next time the app starts up. If you want to recover wallet credentials using saved JWT info, you can pass a JWT storage implementation to the client constructor. For example, if you've previously logged in using a `LocalStorageJwtStorage` implementation, you can recover the credentials at app startup like so:

```typescript
import {
  LightsparkClient,
  LocalStorageJwtStorage,
  CustomJwtAuthProvider,
} from "@lightsparkdev/wallet-sdk";

const jwtStorage = new LocalStorageJwtStorage();
const client = new LightsparkClient(new CustomJwtAuthProvider(jwtStorage));
```

### Deploying and initializing a wallet

![wallet state diagram](./docs-media/wallet-state-diagram.png)

When a user logs in for the first time, initially, their wallet will be in a `NOT_SETUP` status. You can identify this status by querying the current wallet:

```typescript
const wallet = await client.getCurrentWallet();
if (wallet.status === WalletStatus.NOT_SETUP) {
  // The wallet is not setup, so we need to deploy it.
}
```

To deploy the wallet, you'll need to call `client.deployWallet()` and then wait for the wallet's status to update to the DEPLOYED or FAILED status. You can do this either by polling the wallet, or by subscribing to wallet updates via the helper function which subscribes to status updates.

Here's an example which polls wallet state every 2 seconds:

```typescript
let wallet = await client.deployWallet();
while (
  wallet.status !== WalletStatus.DEPLOYED &&
  wallet.status !== WalletStatus.FAILED
) {
  await new Promise((resolve) => setTimeout(resolve, 2000));
  wallet = await client.getCurrentWallet();
}

// Now the wallet is either deployed or failed.
```

Alternatively, here's an example using the helper, `deployWalletAndAwaitDeployed`:

```typescript
const walletSatus = await client.deployWalletAndAwaitDeployed();
if (walletStatus === WalletStatus.DEPLOYED) {
  // The wallet is deployed!
} else {
  // The wallet failed to deploy.
}
```

Once the wallet is deployed, you can initialize it. However, first you'll need signing keys for the wallet to complete sensitive operations.

#### Key generation for the wallet

When initializing the wallet, you'll need to provide a public key for the wallet to use to sign transactions. Note that this _is not_ the same as your JWT signing key used above. It should be unique to each user's wallet. It is the responsibility of your application to safely store the keypair for the user. Losing the private key will result in the user losing access to their wallet. Currently, the wallet SDK only supports RSA-PSS keys, but we plan to support other key types in the future.

For convenience, the wallet SDK provides a `DefaultCrypto.generateSigningKeyPair()` method which can be used to generate a keypair. You can then store the keys however you'd like in your application code.

```typescript
import { DefaultCrypto } from "@lightsparkdev/core";

const keyPair = await DefaultCrypto.generateSigningKeyPair();
const signingWalletPublicKey = keyPair.publicKey;
const signingWalletPrivateKey = keyPair.privateKey;

const serializedPublicKeyBytes = await DefaultCrypto.serializeSigningKey(
  signingWalletPublicKey,
  "spki",
);
const serializedPrivateKeyBytes = await DefaultCrypto.serializeSigningKey(
  signingWalletPrivateKey,
  "pkcs8",
);
// Store the keys somewhere safe.
```

#### Initializing the wallet

Now that you've got keys, you can initialize the wallet! Just like when deploying, you can do this either by polling the wallet, or by subscribing to wallet updates via `client.initializeWalletAndAwaitReady`.

```typescript
let wallet = await client.initializeWallet(
  KeyType.RSA_OAEP,
  b64encode(serializedPublicKeyBytes),
  b64encode(serializedPrivateKeyBytes),
);
while (
  wallet.status !== WalletStatus.READY &&
  wallet.status !== WalletStatus.FAILED
) {
  await new Promise((resolve) => setTimeout(resolve, 2000));
  wallet = await client.getCurrentWallet();
}

// Now the wallet is either ready or failed.
```

Alternatively, here's an example using the helper, `initializeWalletAndAwaitReady`:

```typescript
const walletSatus = await client.initializeWalletAndAwaitReady(
  KeyType.RSA_OAEP,
  signingWalletPublicKey,
  signingWalletPrivateKey,
);
if (walletStatus === WalletStatus.READY) {
  // The wallet is initialized!
} else {
  // The wallet failed to initialize.
}
```

#### Unlock the wallet and make requests

When the wallet is in the READY state, you can make requests. However, in order to complete sensitive operations like sending payments, first you'll need to unlock the wallet using the private key you generated earlier.

```typescript
await client.loadWalletSigningKey(signingWalletPrivateKey);
```

Now you can make requests! For example, to create an invoice:

```typescript
const invoiceData = await client.createInvoice(
  /* amountMsats */: 100_000,
  /* memo */ "mmmmm pizza",
);
```

or pay an invoice:

```typescript
const payment = await client.payInvoice(
  /* encodedInvoice */ invoiceData.encodedPaymentRequest,
  /* maxFeesMsats */ 50_000,
);
```

For more examples, check out the [examples/node-scripts](./examples/node-scripts/) directory.

---
_Source: https://npm.io/package/@lightsparkdev/wallet-sdk · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
