Skip to content

Commit

Permalink
chore: Update type compilation (#71)
Browse files Browse the repository at this point in the history
* chore: converted WorkerMessageType enum to type

* fix: add dts rollup plugin to properly resolve types

* fix: types organization and aliasing

* chore: update docs with example types
  • Loading branch information
alexlwn123 authored Oct 4, 2024
1 parent 24d561f commit ae528a0
Show file tree
Hide file tree
Showing 26 changed files with 184 additions and 130 deletions.
3 changes: 2 additions & 1 deletion .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ packages/wasm-web/**
packages/wasm-bundler/**
examples/bare-js/**
tmp/**
*.html
*.html
packages/*/dist/**
10 changes: 7 additions & 3 deletions docs/core/FedimintWallet/BalanceService/getBalance.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,14 @@

Get the current balance of the wallet.

```ts
// const wallet = new FedimintWallet()
// wallet.open()
```ts twoslash
// @esModuleInterop
import { FedimintWallet } from '@fedimint/core-web'

const wallet = new FedimintWallet()
wallet.open()

// ---cut---
const mSats = await wallet.balance.getBalance()

// 1000 mSats = 1 satoshi
Expand Down
9 changes: 6 additions & 3 deletions docs/core/FedimintWallet/BalanceService/subscribeBalance.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@

Subscribe to balance updates as they occur.

```ts
// const wallet = new FedimintWallet()
// wallet.open()
```ts twoslash
import { FedimintWallet } from '@fedimint/core-web'

const wallet = new FedimintWallet()
wallet.open()

// ---cut---
const unsubscribe = wallet.balance.subscribeBalance((mSats) => {
console.log('Balance updated:', mSats)
// 1000 mSats = 1 satoshi
Expand Down
2 changes: 1 addition & 1 deletion examples/vite-core/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const useBalance = (checkIsOpen: () => void) => {
const [balance, setBalance] = useState(0)

useEffect(() => {
const unsubscribe = wallet.balance.subscribeBalance((balance: number) => {
const unsubscribe = wallet.balance.subscribeBalance((balance) => {
// checks if the wallet is open when the first
// subscription event fires.
// TODO: make a subscription to the wallet open status
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"private": true,
"type": "module",
"scripts": {
"build": "pnpm run --r --filter \"./packages/**\" build",
"build": "pnpm clean && pnpm run --r --filter \"./packages/**\" build",
"clean": "pnpm run --r --parallel clean && rm -rf packages/**/*.json.tmp",
"clean:deep": "rm -rf node_modules && pnpm run --r --parallel clean:deep",
"deps": "pnpx taze -r",
Expand Down
1 change: 1 addition & 0 deletions packages/core-web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"@rollup/plugin-typescript": "^11.1.6",
"@types/node": "^20.14.8",
"rollup": "^4.21.2",
"rollup-plugin-dts": "^6.1.1",
"rollup-plugin-typescript2": "^0.36.0",
"tslib": "^2.7.0",
"typescript": "^5.2.2"
Expand Down
6 changes: 6 additions & 0 deletions packages/core-web/rollup.config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/** @type {import('rollup').RollupOptions} */
import typescript from '@rollup/plugin-typescript'
import terser from '@rollup/plugin-terser'
import { dts } from 'rollup-plugin-dts'

export default [
{
Expand All @@ -16,4 +17,9 @@ export default [
plugins: [typescript(), terser()],
external: ['@fedimint/fedimint-client-wasm-bundler'],
},
{
input: './dist/dts/index.d.ts',
output: [{ file: 'dist/index.d.ts', format: 'es' }],
plugins: [dts()],
},
]
24 changes: 9 additions & 15 deletions packages/core-web/src/FedimintWallet.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { WorkerClient, WorkerMessageType } from './worker'
import { WorkerClient } from './worker'
import {
BalanceService,
MintService,
Expand All @@ -19,7 +19,7 @@ export class FedimintWallet {
public federation: FederationService
public recovery: RecoveryService

private _openPromise: Promise<void> | null = null
private _openPromise: Promise<void> | undefined = undefined
private _resolveOpen: () => void = () => {}
private _isOpen: boolean = false

Expand Down Expand Up @@ -85,12 +85,9 @@ export class FedimintWallet {
await this._client.initialize()
// TODO: Determine if this should be safe or throw
if (this._isOpen) throw new Error('The FedimintWallet is already open.')
const { success } = await this._client.sendSingleMessage(
WorkerMessageType.Open,
{
clientName,
},
)
const { success } = await this._client.sendSingleMessage<{
success: boolean
}>('open', { clientName })
if (success) {
this._isOpen = !!success
this._resolveOpen()
Expand All @@ -108,12 +105,9 @@ export class FedimintWallet {
throw new Error(
'The FedimintWallet is already open. You can only call `joinFederation` on closed clients.',
)
const response = await this._client.sendSingleMessage(
WorkerMessageType.Join,
{
inviteCode,
clientName,
},
const response = await this._client.sendSingleMessage<{ success: boolean }>(
'join',
{ inviteCode, clientName },
)
if (response.success) {
this._isOpen = true
Expand All @@ -126,7 +120,7 @@ export class FedimintWallet {
* After this call, the FedimintWallet instance should be discarded.
*/
async cleanup() {
this._openPromise = null
this._openPromise = undefined
this._isOpen = false
this._client.cleanup()
}
Expand Down
10 changes: 1 addition & 9 deletions packages/core-web/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,2 @@
export { FedimintWallet } from './FedimintWallet'
export type {
LightningGateway,
RouteHint,
FeeToAmount,
OutgoingLightningPayment,
PayType,
LnPayState,
CreateBolt11Response,
} from './types/wallet'
export type * from './types'
9 changes: 5 additions & 4 deletions packages/core-web/src/services/BalanceService.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { MSats } from '../types'
import { WorkerClient } from '../worker'

/**
Expand All @@ -9,19 +10,19 @@ export class BalanceService {
constructor(private client: WorkerClient) {}

/**
* Get the balance of the current wallet
* Get the balance of the current wallet in milli-satoshis (MSats)
*
* @example
* ```ts
* const balance = await wallet.balance.getBalance()
* ```
*/
async getBalance(): Promise<number> {
async getBalance(): Promise<MSats> {
return await this.client.rpcSingle('', 'get_balance', {})
}

/**
* Subscribe to the balance of the current wallet
* Subscribe to the balance of the current wallet in milli-satoshis (MSats)
*
* @example
* ```ts
Expand All @@ -34,7 +35,7 @@ export class BalanceService {
* ```
*/
subscribeBalance(
onSuccess: (balance: number) => void = () => {},
onSuccess: (balance: MSats) => void = () => {},
onError: (error: string) => void = () => {},
) {
const unsubscribe = this.client.rpcStream<string>(
Expand Down
2 changes: 1 addition & 1 deletion packages/core-web/src/services/FederationService.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { JSONValue } from '../types/wallet'
import type { JSONValue } from '../types'
import { WorkerClient } from '../worker'

export class FederationService {
Expand Down
12 changes: 12 additions & 0 deletions packages/core-web/src/services/LightningService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,18 @@ walletTest(
},
)

walletTest('createInvoice with expiry', async ({ wallet }) => {
expect(wallet).toBeDefined()
expect(wallet.isOpen()).toBe(true)

const invoice = await wallet.lightning.createInvoice(100, 'test', 1000, {})
expect(invoice).toBeDefined()
expect(invoice).toMatchObject({
invoice: expect.any(String),
operation_id: expect.any(String),
})
})

walletTest(
'listGateways should return a list of gateways',
async ({ wallet }) => {
Expand Down
13 changes: 7 additions & 6 deletions packages/core-web/src/services/LightningService.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
import { WorkerClient } from '../worker'
import {
import type {
CreateBolt11Response,
GatewayInfo,
JSONObject,
JSONValue,
LightningGateway,
LnPayState,
LnReceiveState,
MSats,
OutgoingLightningPayment,
} from '../types/wallet'
} from '../types'

export class LightningService {
constructor(private client: WorkerClient) {}

async createInvoiceWithGateway(
amount: number,
amount: MSats,
description: string,
expiryTime: number | null = null,
expiryTime: number | null = null, // in seconds
extraMeta: JSONObject = {},
gatewayInfo: GatewayInfo,
) {
Expand All @@ -30,9 +31,9 @@ export class LightningService {
}

async createInvoice(
amount: number,
amount: MSats,
description: string,
expiryTime: number | null = null,
expiryTime: number | null = null, // in seconds
extraMeta: JSONObject = {},
): Promise<CreateBolt11Response> {
await this.updateGatewayCache()
Expand Down
9 changes: 8 additions & 1 deletion packages/core-web/src/services/MintService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,18 @@ walletTest('redeemEcash should error on invalid ecash', async ({ wallet }) => {
})

walletTest(
'reissueExternalNotes should reissue external notes',
'reissueExternalNotes should throw if wallet is empty',
async ({ wallet }) => {
expect(wallet).toBeDefined()
expect(wallet.isOpen()).toBe(true)

await expect(wallet.mint.reissueExternalNotes('test')).rejects.toThrow()
},
)

walletTest('spendNotes should throw if wallet is empty', async ({ wallet }) => {
expect(wallet).toBeDefined()
expect(wallet.isOpen()).toBe(true)

await expect(wallet.mint.spendNotes(100)).rejects.toThrow()
})
11 changes: 6 additions & 5 deletions packages/core-web/src/services/MintService.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { WorkerClient } from '../worker'
import {
import type {
Duration,
JSONObject,
JSONValue,
MintSpendNotesResponse,
MSats,
ReissueExternalNotesState,
} from '../types/wallet'
} from '../types'

export class MintService {
constructor(private client: WorkerClient) {}
Expand Down Expand Up @@ -44,12 +45,12 @@ export class MintService {
}

async spendNotes(
minAmount: number,
minAmount: MSats,
// Tells the wallet to automatically try to cancel the spend if it hasn't completed
// after the specified number of milliseconds.
// If the receiver has already redeemed the notes at this time,
// the notes will not be cancelled
tryCancelAfter: number | Duration = 0,
tryCancelAfter: number | Duration = 0, // in seconds or Duration object
includeInvite: boolean = false,
extraMeta: JSONValue = {},
): Promise<MintSpendNotesResponse> {
Expand Down Expand Up @@ -77,7 +78,7 @@ export class MintService {
}
}

async validateNotes(oobNotes: string): Promise<number> {
async parseNotes(oobNotes: string): Promise<MSats> {
return await this.client.rpcSingle('mint', 'validate_notes', {
oob_notes: oobNotes,
})
Expand Down
2 changes: 1 addition & 1 deletion packages/core-web/src/services/RecoveryService.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { JSONValue } from '../types/wallet'
import type { JSONValue } from '../types'
import { WorkerClient } from '../worker'

export class RecoveryService {
Expand Down
3 changes: 3 additions & 0 deletions packages/core-web/src/types/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export * from './wallet'
export * from './utils'
export * from './worker'
25 changes: 25 additions & 0 deletions packages/core-web/src/types/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
type Alias<T> = T & {}
type Resolve<T> = T & unknown

type Seconds = Alias<number>
type Nanos = Alias<number>

type Duration = {
nanos: Nanos
secs: Seconds
}

type MSats = Alias<number>
type Sats = Alias<number>

type JSONValue =
| string
| number
| boolean
| null
| { [key: string]: JSONValue }
| JSONValue[]

type JSONObject = Record<string, JSONValue>

export { Alias, Resolve, Duration, MSats, Sats, JSONValue, JSONObject }
Loading

0 comments on commit ae528a0

Please sign in to comment.