@fedimint/core-web 0.0.2-alpha.2 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +55 -12
  3. package/dist/FedimintWallet.d.ts +68 -5
  4. package/dist/FedimintWallet.d.ts.map +1 -1
  5. package/dist/index.d.ts +2 -0
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +2 -3
  8. package/dist/index.js.map +1 -1
  9. package/dist/types/wallet.d.ts +87 -0
  10. package/dist/types/wallet.d.ts.map +1 -0
  11. package/dist/worker.js +2 -0
  12. package/dist/worker.js.map +1 -0
  13. package/node_modules/fedimint-client-wasm/fedimint_client_wasm.d.ts +49 -0
  14. package/node_modules/fedimint-client-wasm/fedimint_client_wasm.js +4 -0
  15. package/node_modules/fedimint-client-wasm/fedimint_client_wasm_bg.js +1411 -0
  16. package/node_modules/fedimint-client-wasm/fedimint_client_wasm_bg.wasm +0 -0
  17. package/node_modules/fedimint-client-wasm/package.json +26 -0
  18. package/package.json +15 -4
  19. package/src/FedimintWallet.ts +454 -81
  20. package/src/index.ts +19 -0
  21. package/src/types/wallet.ts +114 -0
  22. package/src/worker.js +80 -0
  23. package/wasm/fedimint_client_wasm.d.ts +44 -89
  24. package/wasm/fedimint_client_wasm.js +4 -1181
  25. package/wasm/fedimint_client_wasm_bg.js +1197 -659
  26. package/wasm/fedimint_client_wasm_bg.wasm +0 -0
  27. package/wasm/fedimint_client_wasm_bg.wasm.d.ts +108 -30
  28. package/wasm/package.json +26 -0
  29. package/dist/FedimintWallet.js +0 -106
  30. package/dist/FedimintWallet.js.map +0 -1
  31. package/dist/wasm.worker.d.ts +0 -1
  32. package/dist/wasm.worker.d.ts.map +0 -1
  33. package/dist/wasm.worker.js +0 -37
  34. package/dist/wasm.worker.js.map +0 -1
  35. package/src/vite-env.d.ts +0 -1
  36. package/src/wasm.worker.ts +0 -41
  37. package/wasm/README.md +0 -169
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 fedimint
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,38 +1,81 @@
1
1
  # @fedimint/core-web
2
2
 
3
- ### THIS IS A WORK IN PROGRESS AND NOT READY FOR USE
3
+ ### THIS IS A WORK IN PROGRESS AND NOT READY FOR SERIOUS USE
4
4
 
5
- This package provides a typescript interface for the Fedimint client in the browser
5
+ This package provides a typescript interface for a fedimint client in the browser.
6
+
7
+ It contains the wasm-pack output of the rust-based [fedimint client](https://github.com/fedimint/fedimint/tree/master/fedimint-client-wasm).
8
+
9
+ ## Key Features:
10
+
11
+ - **WebAssembly-powered Client**: Exposes the robust, fault-tolerant fedimint-client (built in Rust) via WebAssembly. Lazy-Loads within a web worker for performance.
12
+ - **eCash Payments**: Includes support for joining federations, sending/receiving eCash, and managing balances.
13
+ - **Lightning Payments**: Ships with zero-setup Lightning Network payments.
14
+ - 🛠️ **State Management**: Handles the complex state management and storage challenges for browser wallets.
15
+ - 🤫 **Privacy Included**: Offers a privacy-centric wallet by default.
16
+ - ⚙️ **Framework Agnostic**: Designed as a "core" library compatible with vanilla JavaScript, laying the groundwork for future framework-specific packages.
6
17
 
7
18
  ## Installation
8
19
 
9
- ```sh
20
+ ```bash
21
+ // npm or yarn or pnpm
10
22
  pnpm add @fedimint/core-web
11
23
  ```
12
24
 
25
+ ## Setup
26
+
27
+ This package relies on the wasm binary to be bundled with your application. You will likely need to update your bundler's or framework's configuration to load the wasm file. Setup guides for popular frameworks are coming soon.
28
+
29
+ See the `vite.config.ts` file in the [vite-core example](../../examples/vite-core/vite.config.ts) for an example of configuring wasm within a web-worker using Vite.
30
+
13
31
  ## Usage
14
32
 
15
33
  ```ts
16
34
  import { FedimintWallet } from '@fedimint/core-web'
17
35
 
18
- // federation invite code
19
- const inviteCode = 'fed11qgqpw9thwvaz7t...'
36
+ // Create the Wallet client
37
+ const wallet = new FedimintWallet()
20
38
 
21
- // This should be called only once
22
- await FedimintWallet.initFedimint()
39
+ // This should be called only once in the application
40
+ // lifecycle. It will automatically load your saved
41
+ // wallet state from previous sessions.
42
+ await wallet.open()
23
43
 
24
- const wallet = await FedimintWallet.joinFederation(inviteCode)
44
+ // Joining a Federation
25
45
 
26
- // Get Wallet Balance
46
+ // You can't join a federation
47
+ // if your wallet is already open
48
+ if (!wallet.isOpen()) {
49
+ // Check out [bitcoin mints](https://bitcoinmints.com/?tab=mints&showFedimint=true) for
50
+ // a list of federations with public invite codes.
51
+ const inviteCode = 'fed11qgqpw9thwvaz7t...'
52
+
53
+ await wallet.joinFederation(inviteCode)
54
+ // After you've joined a federation, your federation state
55
+ // will be stored in the browser. Future calls to `open()`
56
+ // will automatically load your saved federation.
57
+ }
58
+
59
+ // Get Wallet Balance (sync)
27
60
  const balance = await wallet.getBalance()
28
61
 
62
+ // Subscribe to Balance Updates
63
+ const unsubscribe = wallet.subscribeBalance((balance: number) => {
64
+ console.log('updated balance', balance)
65
+ })
66
+ // Make sure to call `unsubscribe()` when you're done
67
+
29
68
  // Receive Ecash Payments
30
69
  await wallet.reissueNotes('A11qgqpw9thwvaz7t...')
31
70
 
32
71
  // Pay Lightning Invoice
33
- await wallet.payInvoice('lnbc...')
72
+ await wallet.payBolt11Invoice('lnbc...')
34
73
  ```
35
74
 
36
- ## Check out the example
75
+ ### Check out the example
76
+
77
+ - Vite + React: [`examples/vite-core`](../../examples/vite-core/README.md) [(demo)](https://fedimint.github.io/fedimint-web-sdk/)
78
+
79
+ ### Resources
37
80
 
38
- [`examples/vite-core`](../examples/vite-core/README.md)
81
+ - [Bitcoin Mints](https://bitcoinmints.com/?tab=mints&showFedimint=true) - list of public federations with invite codes
@@ -1,19 +1,82 @@
1
+ import { JSONValue, JSONObject, LightningGateway, OutgoingLightningPayment, LnPayState, LnReceiveState, CreateBolt11Response, GatewayInfo, CancelFunction } from './types/wallet';
1
2
  export declare class FedimintWallet {
2
- private _fed;
3
+ private worker;
3
4
  private initPromise;
4
5
  private openPromise;
5
6
  private resolveOpen;
6
- constructor(lazy?: boolean);
7
+ private _isOpen;
8
+ private requestCounter;
9
+ private requestCallbacks;
10
+ constructor(lazy?: boolean, open?: boolean);
11
+ waitForOpen(): Promise<void>;
12
+ private getNextRequestId;
13
+ private sendSingleMessage;
7
14
  initialize(): Promise<void>;
8
- open(clientName?: string): Promise<boolean>;
15
+ private handleWorkerMessage;
16
+ open(clientName?: string): Promise<any>;
9
17
  joinFederation(inviteCode: string, clientName?: string): Promise<void>;
18
+ /**
19
+ * @summary Initiates an RPC stream with the specified module and method.
20
+ *
21
+ * @description
22
+ * This function sets up an RPC stream by sending a request to a worker and
23
+ * handling responses asynchronously. It ensures that unsubscription is handled
24
+ * correctly, even if the unsubscribe function is called before the subscription
25
+ * is fully established, by deferring the unsubscription attempt using `setTimeout`.
26
+ *
27
+ * The function operates in a non-blocking manner, leveraging Promises to manage
28
+ * asynchronous operations and callbacks to handle responses.
29
+ *
30
+ *
31
+ * @template Response - The expected type of the successful response.
32
+ * @template Body - The type of the request body.
33
+ * @param module - The module kind to interact with.
34
+ * @param method - The method name to invoke on the module.
35
+ * @param body - The request payload.
36
+ * @param onSuccess - Callback invoked with the response data on success.
37
+ * @param onError - Callback invoked with error information if an error occurs.
38
+ * @param onEnd - Optional callback invoked when the stream ends.
39
+ * @returns A function that can be called to cancel the subscription.
40
+ *
41
+ */
10
42
  private _rpcStream;
43
+ private _rpcStreamInner;
11
44
  private _rpcSingle;
12
45
  getBalance(): Promise<number>;
13
- payInvoice(invoice: string): Promise<void>;
14
46
  redeemEcash(notes: string): Promise<void>;
47
+ reissueExternalNotes(oobNotes: string, extraMeta: JSONObject): Promise<string>;
48
+ subscribeReissueExternalNotes(operationId: string, onSuccess?: (state: JSONValue) => void, onError?: (error: string) => void): CancelFunction;
49
+ spendNotes(minAmount: number, tryCancelAfter: number, includeInvite: boolean, extraMeta: JSONValue): Promise<JSONValue>;
50
+ validateNotes(oobNotes: string): Promise<number>;
51
+ tryCancelSpendNotes(operationId: string): Promise<void>;
52
+ subscribeSpendNotes(operationId: string, onSuccess?: (state: JSONValue) => void, onError?: (error: string) => void): CancelFunction;
53
+ awaitSpendOobRefund(operationId: string): Promise<JSONValue>;
54
+ /**
55
+ * This should ONLY be called when UNLOADING the wallet client.
56
+ * After this call, the FedimintWallet instance should be discarded.
57
+ */
15
58
  cleanup(): Promise<void>;
16
59
  isOpen(): boolean;
17
- subscribeBalance(callback: (balance: number) => void): () => void;
60
+ getConfig(): Promise<JSONValue>;
61
+ getFederationId(): Promise<string>;
62
+ getInviteCode(peer: number): Promise<string | null>;
63
+ listOperations(): Promise<JSONValue[]>;
64
+ hasPendingRecoveries(): Promise<boolean>;
65
+ waitForAllRecoveries(): Promise<void>;
66
+ subscribeBalance(onSuccess?: (balance: number) => void, onError?: (error: string) => void): CancelFunction;
67
+ subscribeToRecoveryProgress(onSuccess?: (progress: {
68
+ module_id: number;
69
+ progress: JSONValue;
70
+ }) => void, onError?: (error: string) => void): CancelFunction;
71
+ createBolt11InvoiceWithGateway(amount: number, description: string, expiryTime: (number | null) | undefined, extraMeta: JSONObject | undefined, gatewayInfo: GatewayInfo): Promise<JSONValue>;
72
+ createBolt11Invoice(amount: number, description: string, expiryTime?: number | null, extraMeta?: JSONObject): Promise<CreateBolt11Response>;
73
+ payBolt11InvoiceWithGateway(invoice: string, gatewayInfo: GatewayInfo, extraMeta?: JSONObject): Promise<JSONValue>;
74
+ _getDefaultGatewayInfo(): Promise<LightningGateway>;
75
+ payBolt11Invoice(invoice: string, extraMeta?: JSONObject): Promise<OutgoingLightningPayment>;
76
+ subscribeLnPay(operationId: string, onSuccess?: (state: LnPayState) => void, onError?: (error: string) => void): CancelFunction;
77
+ subscribeLnReceive(operationId: string, onSuccess?: (state: LnReceiveState) => void, onError?: (error: string) => void): CancelFunction;
78
+ getGateway(gatewayId?: string | null, forceInternal?: boolean): Promise<LightningGateway | null>;
79
+ listGateways(): Promise<LightningGateway[]>;
80
+ updateGatewayCache(): Promise<void>;
18
81
  }
19
82
  //# sourceMappingURL=FedimintWallet.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"FedimintWallet.d.ts","sourceRoot":"","sources":["../src/FedimintWallet.ts"],"names":[],"mappings":"AAkBA,qBAAa,cAAc;IACzB,OAAO,CAAC,IAAI,CAA0B;IACtC,OAAO,CAAC,WAAW,CAA6B;IAChD,OAAO,CAAC,WAAW,CAA6B;IAChD,OAAO,CAAC,WAAW,CAAuB;gBAG9B,IAAI,GAAE,OAAe;IAS3B,UAAU;IASV,IAAI,CAAC,UAAU,GAAE,MAA4B;IAU7C,cAAc,CAClB,UAAU,EAAE,MAAM,EAClB,UAAU,GAAE,MAA4B;YAQ5B,UAAU;YAWV,UAAU;IAiBlB,UAAU,IAAI,OAAO,CAAC,MAAM,CAAC;IAM7B,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,I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AE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAe;IAYvC,8BAA8B,CAClC,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,MAAM,EACnB,UAAU,GAAE,MAAM,GAAG,IAAI,aAAO,EAChC,SAAS,EAAE,UAAU,YAAK,EAC1B,WAAW,EAAE,WAAW;IAWpB,mBAAmB,CACvB,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,MAAM,EACnB,UAAU,GAAE,MAAM,GAAG,IAAW,EAChC,SAAS,GAAE,UAAe,GACzB,OAAO,CAAC,oBAAoB,CAAC;IAY1B,2BAA2B,CAC/B,OAAO,EAAE,MAAM,EACf,WAAW,EAAE,WAAW,EACxB,SAAS,GAAE,UAAe;IAStB,sBAAsB,IAAI,OAAO,CAAC,gBAAgB,CAAC;IAKnD,gBAAgB,CACpB,OAAO,EAAE,MAAM,EACf,SAAS,GAAE,UAAe,GACzB,OAAO,CAAC,wBAAwB,CAAC;IAUpC,cAAc,CACZ,WAAW,EAAE,MAAM,EACnB,SAAS,GAAE,CAAC,KAAK,EAAE,UAAU,KAAK,IAAe,EACjD,OAAO,GAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAe;IAa7C,kBAAkB,CAChB,WAAW,EAAE,MAAM,EACnB,SAAS,GAAE,CAAC,KAAK,EAAE,cAAc,KAAK,IAAe,EACrD,OAAO,GAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAe;IAavC,UAAU,CACd,SAAS,GAAE,MAAM,GAAG,IAAW,EAC/B,aAAa,GAAE,OAAe,GAC7B,OAAO,CAAC,gBAAgB,GAAG,IAAI,CAAC;IAO7B,YAAY,IAAI,OAAO,CAAC,gBAAgB,EAAE,CAAC;IAI3C,kBAAkB,IAAI,OAAO,CAAC,IAAI,CAAC;CAI1C"}
package/dist/index.d.ts CHANGED
@@ -1,3 +1,5 @@
1
1
  import { FedimintWallet } from './FedimintWallet.js';
2
+ import { LightningGateway, RouteHint, FeeToAmount, OutgoingLightningPayment, PayType, LnPayState, CreateBolt11Response } from './types/wallet.js';
2
3
  export { FedimintWallet };
4
+ export type { LightningGateway, RouteHint, FeeToAmount, OutgoingLightningPayment, PayType, LnPayState, CreateBolt11Response, };
3
5
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAA;AAEpD,OAAO,EAAE,cAAc,EAAE,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAA;AACpD,OAAO,EACL,gBAAgB,EAChB,SAAS,EACT,WAAW,EACX,wBAAwB,EACxB,OAAO,EACP,UAAU,EACV,oBAAoB,EACrB,MAAM,mBAAmB,CAAA;AAE1B,OAAO,EAAE,cAAc,EAAE,CAAA;AAEzB,YAAY,EACV,gBAAgB,EAChB,SAAS,EACT,WAAW,EACX,wBAAwB,EACxB,OAAO,EACP,UAAU,EACV,oBAAoB,GACrB,CAAA"}
package/dist/index.js CHANGED
@@ -1,3 +1,2 @@
1
- import { FedimintWallet } from './FedimintWallet.js';
2
- export { FedimintWallet };
3
- //# sourceMappingURL=index.js.map
1
+ const e="fm-default";class t{constructor(e=!1,t=!0){this.worker=null,this.initPromise=null,this.resolveOpen=()=>{},this._isOpen=!1,this.requestCounter=0,this.requestCallbacks=new Map,this.openPromise=new Promise((e=>{this.resolveOpen=e})),e||this.initialize()}async waitForOpen(){if(!this._isOpen)return this.openPromise}getNextRequestId(){return++this.requestCounter}sendSingleMessage(e,t){return new Promise(((i,a)=>{const s=this.getNextRequestId();this.requestCallbacks.set(s,(e=>{this.requestCallbacks.delete(s),e.data?i(e.data):e.error&&a(e.error)}));try{this.worker.postMessage({type:e,payload:t,requestId:s})}catch(e){a(e)}}))}initialize(){return this.initPromise||(this.worker=new Worker(new URL("./worker.js",import.meta.url)),this.worker.onmessage=this.handleWorkerMessage.bind(this),this.initPromise=this.sendSingleMessage("init")),this.initPromise}handleWorkerMessage(e){const{type:t,requestId:i,...a}=e.data,s=this.requestCallbacks.get(i);s&&s(a)}async open(t=e){if(await this.initialize(),this._isOpen)throw new Error("The FedimintWallet is already open. You can only call `FedimintWallet.open on closed clients.`");const{success:i}=await this.sendSingleMessage("open",{clientName:t});return i&&(this._isOpen=!!i,this.resolveOpen()),i}async joinFederation(t,i=e){if(await this.initialize(),this._isOpen)throw new Error("Failed to Join Federation. You have already joined a federation, and you can only join one federation per wallet.");(await this.sendSingleMessage("join",{inviteCode:t,clientName:i})).success&&(this._isOpen=!0)}_rpcStream(e,t,i,a,s,n=()=>{}){const r=this.getNextRequestId();let o=()=>{},c=!1;const l=new Promise((e=>{o=()=>{c?e():setTimeout((()=>o()),0)}}));return this._rpcStreamInner(r,e,t,i,a,s,n,l).then((()=>{c=!0})),o}async _rpcStreamInner(e,t,i,a,s,n,r=()=>{},o){if(await this.openPromise,!this.worker||!this._isOpen)throw new Error("FedimintWallet is not open");this.requestCallbacks.set(e,(t=>{void 0!==t.error?n(t.error):void 0!==t.data?s(t.data):void 0!==t.end&&(this.requestCallbacks.delete(e),r())})),this.worker.postMessage({type:"rpc",payload:{module:t,method:i,body:a},requestId:e}),o.then((()=>{console.trace("UNSUBSCRIBING",e),this.worker?.postMessage({type:"unsubscribe",requestId:e}),this.requestCallbacks.delete(e)}))}async _rpcSingle(e,t,i){return new Promise(((a,s)=>{this._rpcStream(e,t,i,a,s)}))}async getBalance(){return await this._rpcSingle("","get_balance",{})}async redeemEcash(e){await this._rpcSingle("mint","reissue_external_notes",{oob_notes:e,extra_meta:null})}async reissueExternalNotes(e,t){return await this._rpcSingle("mint","reissue_external_notes",{oob_notes:e,extra_meta:t})}subscribeReissueExternalNotes(e,t=()=>{},i=()=>{}){return this._rpcStream("mint","subscribe_reissue_external_notes",{operation_id:e},(e=>t(e)),i)}async spendNotes(e,t,i,a){return await this._rpcSingle("mint","spend_notes",{min_amount:e,try_cancel_after:t,include_invite:i,extra_meta:a})}async validateNotes(e){return await this._rpcSingle("mint","validate_notes",{oob_notes:e})}async tryCancelSpendNotes(e){await this._rpcSingle("mint","try_cancel_spend_notes",{operation_id:e})}subscribeSpendNotes(e,t=()=>{},i=()=>{}){return this._rpcStream("mint","subscribe_spend_notes",{operation_id:e},(e=>t(e)),i)}async awaitSpendOobRefund(e){return await this._rpcSingle("mint","await_spend_oob_refund",{operation_id:e})}async cleanup(){this.worker?.terminate(),this.worker=null,this.openPromise=Promise.resolve(),this.requestCallbacks.clear()}isOpen(){return null!==this.worker&&this._isOpen}async getConfig(){return await this._rpcSingle("","get_config",{})}async getFederationId(){return await this._rpcSingle("","get_federation_id",{})}async getInviteCode(e){return await this._rpcSingle("","get_invite_code",{peer:e})}async listOperations(){return await this._rpcSingle("","list_operations",{})}async hasPendingRecoveries(){return await this._rpcSingle("","has_pending_recoveries",{})}async waitForAllRecoveries(){await this._rpcSingle("","wait_for_all_recoveries",{})}subscribeBalance(e=()=>{},t=()=>{}){return this._rpcStream("","subscribe_balance_changes",{},(t=>e(parseInt(t))),t)}subscribeToRecoveryProgress(e=()=>{},t=()=>{}){return this._rpcStream("","subscribe_to_recovery_progress",{},e,t)}async createBolt11InvoiceWithGateway(e,t,i=null,a={},s){return await this._rpcSingle("ln","create_bolt11_invoice",{amount:e,description:t,expiry_time:i,extra_meta:a,gateway:s})}async createBolt11Invoice(e,t,i=null,a={}){await this.updateGatewayCache();const s=await this._getDefaultGatewayInfo();return await this._rpcSingle("ln","create_bolt11_invoice",{amount:e,description:t,expiry_time:i,extra_meta:a,gateway:s.info})}async payBolt11InvoiceWithGateway(e,t,i={}){return await this._rpcSingle("ln","pay_bolt11_invoice",{maybe_gateway:t,invoice:e,extra_meta:i})}async _getDefaultGatewayInfo(){return(await this.listGateways())[0]}async payBolt11Invoice(e,t={}){await this.updateGatewayCache();const i=await this._getDefaultGatewayInfo();return await this._rpcSingle("ln","pay_bolt11_invoice",{maybe_gateway:i.info,invoice:e,extra_meta:t})}subscribeLnPay(e,t=()=>{},i=()=>{}){return this._rpcStream("ln","subscribe_ln_pay",{operation_id:e},t,i)}subscribeLnReceive(e,t=()=>{},i=()=>{}){return this._rpcStream("ln","subscribe_ln_receive",{operation_id:e},t,i)}async getGateway(e=null,t=!1){return await this._rpcSingle("ln","get_gateway",{gateway_id:e,force_internal:t})}async listGateways(){return await this._rpcSingle("ln","list_gateways",{})}async updateGatewayCache(){console.trace("Updating gateway cache"),await this._rpcSingle("ln","update_gateway_cache",{})}}export{t as FedimintWallet};
2
+ //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAA;AAEpD,OAAO,EAAE,cAAc,EAAE,CAAA"}
1
+ {"version":3,"file":"index.js","sources":["../src/FedimintWallet.ts"],"sourcesContent":[null],"names":["DEFAULT_CLIENT_NAME","FedimintWallet","constructor","lazy","open","this","worker","initPromise","resolveOpen","_isOpen","requestCounter","requestCallbacks","Map","openPromise","Promise","resolve","initialize","waitForOpen","getNextRequestId","sendSingleMessage","type","payload","reject","requestId","set","data","delete","error","postMessage","e","Worker","URL","url","onmessage","handleWorkerMessage","bind","event","streamCallback","get","clientName","Error","success","joinFederation","inviteCode","_rpcStream","module","method","body","onSuccess","onError","onEnd","unsubscribe","isSubscribed","unsubscribePromise","setTimeout","_rpcStreamInner","then","response","undefined","end","console","trace","_rpcSingle","getBalance","redeemEcash","notes","oob_notes","extra_meta","reissueExternalNotes","oobNotes","extraMeta","subscribeReissueExternalNotes","operationId","operation_id","res","spendNotes","minAmount","tryCancelAfter","includeInvite","min_amount","try_cancel_after","include_invite","validateNotes","tryCancelSpendNotes","subscribeSpendNotes","awaitSpendOobRefund","cleanup","terminate","clear","isOpen","getConfig","getFederationId","getInviteCode","peer","listOperations","hasPendingRecoveries","waitForAllRecoveries","subscribeBalance","parseInt","subscribeToRecoveryProgress","createBolt11InvoiceWithGateway","amount","description","expiryTime","gatewayInfo","expiry_time","gateway","createBolt11Invoice","updateGatewayCache","_getDefaultGatewayInfo","info","payBolt11InvoiceWithGateway","invoice","maybe_gateway","listGateways","payBolt11Invoice","subscribeLnPay","subscribeLnReceive","getGateway","gatewayId","forceInternal","gateway_id","force_internal"],"mappings":"AAeA,MAAMA,EAAsB,mBAEfC,EASX,WAAAC,CAAYC,GAAgB,EAAOC,GAAgB,GAR3CC,KAAMC,OAAkB,KACxBD,KAAWE,YAAyB,KAEpCF,KAAAG,YAA0B,OAC1BH,KAAOI,SAAY,EACnBJ,KAAcK,eAAW,EACzBL,KAAAM,iBAAsD,IAAIC,IAGhEP,KAAKQ,YAAc,IAAIC,SAASC,IAC9BV,KAAKG,YAAcO,CAAO,IAExBZ,GACJE,KAAKW,YACN,CAED,iBAAMC,GACJ,IAAIZ,KAAKI,QACT,OAAOJ,KAAKQ,WACb,CAEO,gBAAAK,GACN,QAASb,KAAKK,cACf,CAIO,iBAAAS,CAAkBC,EAAcC,GACtC,OAAO,IAAIP,SAAQ,CAACC,EAASO,KAC3B,MAAMC,EAAYlB,KAAKa,mBACvBb,KAAKM,iBAAiBa,IAAID,GAAYE,IACpCpB,KAAKM,iBAAiBe,OAAOH,GACzBE,EAAKA,KAAMV,EAAQU,EAAKA,MACnBA,EAAKE,OAAOL,EAAOG,EAAKE,MAAM,IAEzC,IACEtB,KAAKC,OAAQsB,YAAY,CAAER,OAAMC,UAASE,aAC3C,CAAC,MAAOM,GACPP,EAAOO,EACR,IAEJ,CAGD,UAAAb,GACE,OAAIX,KAAKE,cACTF,KAAKC,OAAS,IAAIwB,OAAO,IAAIC,IAAI,0BAA2BC,MAC5D3B,KAAKC,OAAO2B,UAAY5B,KAAK6B,oBAAoBC,KAAK9B,MACtDA,KAAKE,YAAcF,KAAKc,kBAAkB,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ElBjE,KAAKuG,qBACX,MAAMF,QAAgBrG,KAAKwG,yBAC3B,aAAaxG,KAAKyD,WAAW,KAAM,wBAAyB,CAC1DuC,SACAC,cACAG,YAAaF,EACbpC,WAAYG,EACZoC,QAASA,EAAQI,MAEpB,CAED,iCAAMC,CACJC,EACAR,EACAlC,EAAwB,CAAA,GAExB,aAAajE,KAAKyD,WAAW,KAAM,qBAAsB,CACvDmD,cAAeT,EACfQ,UACA7C,WAAYG,GAEf,CAED,4BAAMuC,GAEJ,aADuBxG,KAAK6G,gBACZ,EACjB,CAED,sBAAMC,CACJH,EACA1C,EAAwB,UAElBjE,KAAKuG,qBACX,MAAMF,QAAgBrG,KAAKwG,yBAC3B,aAAaxG,KAAKyD,WAAW,KAAM,qBAAsB,CACvDmD,cAAeP,EAAQI,KACvBE,UACA7C,WAAYG,GAEf,CAED,cAAA8C,CACE5C,EACAxB,EAAyC,OACzCC,EAAmC,QAUnC,OARoB5C,KAAKuC,WACvB,KACA,mBACA,CAAE6B,aAAcD,GAChBxB,EACAC,EAIH,CAED,kBAAAoE,CACE7C,EACAxB,EAA6C,OAC7CC,EAAmC,QAUnC,OARoB5C,KAAKuC,WACvB,KACA,uBACA,CAAE6B,aAAcD,GAChBxB,EACAC,EAIH,CAED,gBAAMqE,CACJC,EAA2B,KAC3BC,GAAyB,GAEzB,aAAanH,KAAKyD,WAAW,KAAM,cAAe,CAChD2D,WAAYF,EACZG,eAAgBF,GAEnB,CAED,kBAAMN,GACJ,aAAa7G,KAAKyD,WAAW,KAAM,gBAAiB,CAAE,EACvD,CAED,wBAAM8C,GACJhD,QAAQC,MAAM,gCACRxD,KAAKyD,WAAW,KAAM,uBAAwB,CAAE,EACvD"}
@@ -0,0 +1,87 @@
1
+ declare const MODULE_KINDS: readonly ["", "ln", "mint"];
2
+ type ModuleKind = (typeof MODULE_KINDS)[number];
3
+ type JSONValue = string | number | boolean | null | {
4
+ [key: string]: JSONValue;
5
+ } | JSONValue[];
6
+ type JSONObject = Record<string, JSONValue>;
7
+ type GatewayInfo = {
8
+ gateway_id: string;
9
+ api: string;
10
+ node_pub_key: string;
11
+ federation_index: number;
12
+ route_hints: RouteHint[];
13
+ fees: FeeToAmount;
14
+ };
15
+ type LightningGateway = {
16
+ info: GatewayInfo;
17
+ vetted: boolean;
18
+ ttl: {
19
+ nanos: number;
20
+ secs: number;
21
+ };
22
+ };
23
+ type RouteHint = {};
24
+ type FeeToAmount = {};
25
+ type OutgoingLightningPayment = {
26
+ payment_type: PayType;
27
+ contract_id: string;
28
+ fee: number;
29
+ };
30
+ type PayType = {
31
+ type: 'Internal' | 'Lightning';
32
+ operation_id: string;
33
+ };
34
+ type LnPayState = 'Created' | 'Canceled' | {
35
+ Funded: {
36
+ block_height: number;
37
+ };
38
+ } | {
39
+ WaitingForRefund: {
40
+ error_reason: string;
41
+ };
42
+ } | 'AwaitingChange' | {
43
+ Success: {
44
+ preimage: string;
45
+ };
46
+ } | {
47
+ Refunded: {
48
+ gateway_error: string;
49
+ };
50
+ } | {
51
+ UnexpectedError: {
52
+ error_message: string;
53
+ };
54
+ };
55
+ type LnReceiveState = 'Created' | {
56
+ WaitingForPayment: {
57
+ invoice: string;
58
+ timeout: number;
59
+ };
60
+ } | {
61
+ Canceled: {
62
+ reason: string;
63
+ };
64
+ } | 'Funded' | 'AwaitingFunds' | 'Claimed';
65
+ type CreateBolt11Response = {
66
+ operation_id: string;
67
+ invoice: string;
68
+ };
69
+ type StreamError = {
70
+ error: string;
71
+ data: never;
72
+ end: never;
73
+ };
74
+ type StreamSuccess<T extends JSONValue> = {
75
+ data: T;
76
+ error: never;
77
+ end: never;
78
+ };
79
+ type StreamEnd = {
80
+ end: string;
81
+ data: never;
82
+ error: never;
83
+ };
84
+ type StreamResult<T extends JSONValue> = StreamSuccess<T> | StreamError | StreamEnd;
85
+ type CancelFunction = () => void;
86
+ export { JSONValue, JSONObject, LightningGateway, RouteHint, FeeToAmount, OutgoingLightningPayment, PayType, LnPayState, LnReceiveState, CreateBolt11Response, GatewayInfo, StreamError, StreamSuccess, StreamResult, ModuleKind, CancelFunction, };
87
+ //# sourceMappingURL=wallet.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wallet.d.ts","sourceRoot":"","sources":["../../src/types/wallet.ts"],"names":[],"mappings":"AAAA,QAAA,MAAM,YAAY,6BAA8B,CAAA;AAChD,KAAK,UAAU,GAAG,CAAC,OAAO,YAAY,CAAC,CAAC,MAAM,CAAC,CAAA;AAC/C,KAAK,SAAS,GACV,MAAM,GACN,MAAM,GACN,OAAO,GACP,IAAI,GACJ;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE,GAC5B,SAAS,EAAE,CAAA;AAEf,KAAK,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAA;AAE3C,KAAK,WAAW,GAAG;IACjB,UAAU,EAAE,MAAM,CAAA;IAClB,GAAG,EAAE,MAAM,CAAA;IACX,YAAY,EAAE,MAAM,CAAA;IACpB,gBAAgB,EAAE,MAAM,CAAA;IACxB,WAAW,EAAE,SAAS,EAAE,CAAA;IACxB,IAAI,EAAE,WAAW,CAAA;CAClB,CAAA;AACD,KAAK,gBAAgB,GAAG;IACtB,IAAI,EAAE,WAAW,CAAA;IACjB,MAAM,EAAE,OAAO,CAAA;IACf,GAAG,EAAE;QACH,KAAK,EAAE,MAAM,CAAA;QACb,IAAI,EAAE,MAAM,CAAA;KACb,CAAA;CACF,CAAA;AAED,KAAK,SAAS,GAAG,EAEhB,CAAA;AAED,KAAK,WAAW,GAAG,EAElB,CAAA;AAED,KAAK,wBAAwB,GAAG;IAC9B,YAAY,EAAE,OAAO,CAAA;IACrB,WAAW,EAAE,MAAM,CAAA;IACnB,GAAG,EAAE,MAAM,CAAA;CACZ,CAAA;AAED,KAAK,OAAO,GAAG;IACb,IAAI,EAAE,UAAU,GAAG,WAAW,CAAA;IAC9B,YAAY,EAAE,MAAM,CAAA;CACrB,CAAA;AAED,KAAK,UA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ACX,SAAS,CAAA;AAEb,KAAK,cAAc,GAAG,MAAM,IAAI,CAAA;AAEhC,OAAO,EACL,SAAS,EACT,UAAU,EACV,gBAAgB,EAChB,SAAS,EACT,WAAW,EACX,wBAAwB,EACxB,OAAO,EACP,UAAU,EACV,cAAc,EACd,oBAAoB,EACpB,WAAW,EACX,WAAW,EACX,aAAa,EACb,YAAY,EACZ,UAAU,EACV,cAAc,GACf,CAAA"}
package/dist/worker.js ADDED
@@ -0,0 +1,2 @@
1
+ let e=null,s=null;const t=new Map;self.onmessage=async n=>{const{type:a,payload:o,requestId:r}=n.data;if("init"===a)e=(await import("fedimint-client-wasm")).WasmClient,self.postMessage({type:"initialized",data:{},requestId:r});else if("open"===a){const{clientName:t}=o;s=await e.open(t)||null,self.postMessage({type:"open",data:{success:!!s},requestId:r})}else if("join"===a){const{inviteCode:t,clientName:n}=o;try{s=await e.join_federation(n,t),self.postMessage({type:"join",data:{success:!!s},requestId:r})}catch(e){self.postMessage({type:"error",error:e.message,requestId:r})}}else if("rpc"===a){const{module:e,method:n,body:a}=o;if(!s)return void self.postMessage({type:"error",error:"WasmClient not initialized",requestId:r});const i=await s.rpc(e,n,JSON.stringify(a),(e=>{const s=JSON.parse(e);if(self.postMessage({type:"rpcResponse",requestId:r,...s}),void 0===s.end)return;const n=t.get(r);n?.free()}));t.set(r,i)}else if("unsubscribe"===a){const e=t.get(r);e&&(e.cancel(),e.free(),t.delete(r))}else self.postMessage({type:"error",error:"Unknown message type",requestId:r})};
2
+ //# sourceMappingURL=worker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker.js","sources":["../src/worker.js"],"sourcesContent":["// import { WasmClient } from '../wasm/fedimint_client_wasm.js'\n// import { WasmClient } from 'fedimint-client-wasm'\n// import wasm from '../wasm/fedimint_client_wasm_bg.wasm'\n\nlet WasmClient = null\nlet client = null\n\nconst streamCancelMap = new Map()\n\nconst handleFree = (requestId) => {\n streamCancelMap.delete(requestId)\n}\n\nself.onmessage = async (event) => {\n const { type, payload, requestId } = event.data\n\n if (type === 'init') {\n WasmClient = (await import('fedimint-client-wasm')).WasmClient\n self.postMessage({ type: 'initialized', data: {}, requestId })\n } else if (type === 'open') {\n const { clientName } = payload\n client = (await WasmClient.open(clientName)) || null\n self.postMessage({\n type: 'open',\n data: { success: !!client },\n requestId,\n })\n } else if (type === 'join') {\n const { inviteCode, clientName: joinClientName } = payload\n try {\n client = await WasmClient.join_federation(joinClientName, inviteCode)\n self.postMessage({\n type: 'join',\n data: { success: !!client },\n requestId,\n })\n } catch (e) {\n self.postMessage({ type: 'error', error: e.message, requestId })\n }\n } else if (type === 'rpc') {\n const { module, method, body } = payload\n if (!client) {\n self.postMessage({\n type: 'error',\n error: 'WasmClient not initialized',\n requestId,\n })\n return\n }\n const rpcHandle = await client.rpc(\n module,\n method,\n JSON.stringify(body),\n (res) => {\n const data = JSON.parse(res)\n self.postMessage({ type: 'rpcResponse', requestId, ...data })\n\n if (data.end === undefined) return\n\n // Handle stream ending\n const handle = streamCancelMap.get(requestId)\n handle?.free()\n },\n )\n streamCancelMap.set(requestId, rpcHandle)\n } else if (type === 'unsubscribe') {\n const rpcHandle = streamCancelMap.get(requestId)\n if (rpcHandle) {\n rpcHandle.cancel()\n rpcHandle.free()\n streamCancelMap.delete(requestId)\n }\n } else {\n self.postMessage({\n type: 'error',\n error: 'Unknown message type',\n requestId,\n })\n }\n}\n"],"names":["WasmClient","client","streamCancelMap","Map","self","onmessage","async","event","type","payload","requestId","data","import","postMessage","clientName","open","success","inviteCode","joinClientName","join_federation","e","error","message","module","method","body","rpcHandle","rpc","JSON","stringify","res","parse","undefined","end","handle","get","free","set","cancel","delete"],"mappings":"AAIA,IAAIA,EAAa,KACbC,EAAS,KAEb,MAAMC,EAAkB,IAAIC,IAM5BC,KAAKC,UAAYC,MAAOC,IACtB,MAAMC,KAAEA,EAAIC,QAAEA,EAAOC,UAAEA,GAAcH,EAAMI,KAE3C,GAAa,SAATH,EACFR,SAAoBY,OAAO,y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+ export class RpcHandle {
6
+ free(): void
7
+ /**
8
+ */
9
+ cancel(): void
10
+ }
11
+ /**
12
+ */
13
+ export class WasmClient {
14
+ free(): void
15
+ /**
16
+ * Open fedimint client with already joined federation.
17
+ *
18
+ * After you have joined a federation, you can reopen the fedimint client
19
+ * with same client_name. Opening client with same name at same time is
20
+ * not supported. You can close the current client by calling
21
+ * `client.free()`. NOTE: The client will remain active until all the
22
+ * running rpc calls have finished.
23
+ * @param {string} client_name
24
+ * @returns {Promise<WasmClient | undefined>}
25
+ */
26
+ static open(client_name: string): Promise<WasmClient | undefined>
27
+ /**
28
+ * Open a fedimint client by join a federation.
29
+ * @param {string} client_name
30
+ * @param {string} invite_code
31
+ * @returns {Promise<WasmClient>}
32
+ */
33
+ static join_federation(
34
+ client_name: string,
35
+ invite_code: string,
36
+ ): Promise<WasmClient>
37
+ /**
38
+ * Call a fedimint client rpc the responses are returned using `cb`
39
+ * callback. Each rpc call *can* return multiple responses by calling
40
+ * `cb` multiple times. The returned RpcHandle can be used to cancel the
41
+ * operation.
42
+ * @param {string} module
43
+ * @param {string} method
44
+ * @param {string} payload
45
+ * @param {Function} cb
46
+ * @returns {RpcHandle}
47
+ */
48
+ rpc(module: string, method: string, payload: string, cb: Function): RpcHandle
49
+ }
@@ -0,0 +1,4 @@
1
+ import * as wasm from './fedimint_client_wasm_bg.wasm'
2
+ import { __wbg_set_wasm } from './fedimint_client_wasm_bg.js'
3
+ __wbg_set_wasm(wasm)
4
+ export * from './fedimint_client_wasm_bg.js'