@cantor8/wallet-connect-sdk 0.3.0-alpha.2 → 0.4.0

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.
package/README.md CHANGED
@@ -1,90 +1,185 @@
1
-
2
1
  # C8 Wallet Connect SDK
3
2
 
4
- Lightweight SDK for dApp developers to integrate the C8 Wallet via a popup window and postMessage communication.
3
+ Lightweight SDK for dApp developers to integrate the C8 Wallet via a popup window and `postMessage` communication.
4
+
5
+ ## Quick Start
5
6
 
6
- Quick start
7
+ ### Installation
8
+ ```shell
9
+ npm i @cantor8/wallet-connect-sdk
10
+ ```
7
11
 
12
+ Import the provider into your dApp:
13
+
14
+ ```ts
15
+ import { C8WalletProvider } from "./provider";
16
+ ```
8
17
 
9
18
  ## Configuration
10
19
 
11
- You can configure the provider construction:
20
+ Create a new provider instance:
12
21
 
13
- ```
22
+ ```ts
14
23
  const c8 = new C8WalletProvider({
15
- dappUrl: window.location.href,
16
- dappName: "Cantor8 Wallet Connect SDK Demo",
17
- network: "devnet"
24
+ dappUrl: window.location.href,
25
+ dappName: "Cantor8 Wallet Connect SDK Demo",
26
+ network: "devnet",
18
27
  });
19
28
  ```
20
29
 
21
- Sign up for events:
30
+ ## Events
22
31
 
23
- ```
24
- c8.on('connected', (e) => console.log('Connected', e));
25
- c8.on('disconnected', (e) => console.log('Disconnected', e));
26
- c8.on('accountChanged', (e) => console.log('account's balance changed', e));
27
- c8.on('txInitiated', (e) => console.log('TX initiated', e));
28
- c8.on('txChanged', (e) => console.log('TX changed', e));
29
- ```
30
-
31
- Basic usage
32
+ You can subscribe to wallet events using `c8.on()`:
32
33
 
34
+ ```ts
35
+ c8.on("connected", (e) => console.log("Connected", e));
36
+ c8.on("disconnected", (e) => console.log("Disconnected", e));
37
+ c8.on("accountChanged", (e) => console.log("Account's balance changed", e));
38
+ c8.on("txInitiated", (e) => console.log("TX initiated", e));
39
+ c8.on("txChanged", (e) => console.log("TX changed", e));
33
40
  ```
34
- const c8 = new C8WalletProvider({
35
- dappUrl: window.location.href,
36
- dappName: "Cantor8 Wallet Connect SDK Demo",
37
- network: "devnet"
41
+
42
+ ## Basic Usage
43
+
44
+ ```ts
45
+ const c8 = new C8WalletProvider({
46
+ dappUrl: window.location.href,
47
+ dappName: "Cantor8 Wallet Connect SDK Demo",
48
+ network: "devnet",
38
49
  });
39
50
 
40
51
  await c8.connect();
41
52
 
42
53
  // Instruments list type: InstrumentListPayload
43
54
  const instruments = await c8.getInstruments();
44
- console.log('Instruments', instruments);
55
+ console.log("Instruments", instruments);
45
56
 
46
57
  const firstInstrumentId = instruments.instruments[0]?.instrumentId;
47
58
 
48
59
  // Accounts list type: AccountListPayload
49
- const accounts = await wallet.getAccounts(firstInstrumentId);
50
- console.log('Accounts', accounts);
60
+ const accounts = await c8.getAccounts(firstInstrumentId);
61
+ console.log("Accounts", accounts);
51
62
 
52
63
  const senderPartyId = accounts.accounts[0]?.partyId;
53
- const senderHoldingInstrumentId = accounts.accounts[0]?.holdings[0]?.instrumentId || firstInstrumentId;
64
+
65
+ const senderHoldingInstrumentId =
66
+ accounts.accounts[0]?.holdings[0]?.instrumentId || firstInstrumentId;
54
67
 
55
68
  // Submit a transfer
56
69
  // SubmitTransferResultPayload
57
70
  const res = await c8.send({
58
- senderPartyId,
59
- instrumentId: senderHoldingInstrumentId,
60
- amount: 1.23,
61
- receiverPartyId: 'Party::Receiver',
71
+ senderPartyId,
72
+ instrumentId: senderHoldingInstrumentId,
73
+ amount: 1.23,
74
+ receiverPartyId: "Party::Receiver",
75
+ });
76
+
77
+ console.log("Send result", res); // { txId }
78
+
79
+ // Create a swap offer
80
+ const swapRes = await c8.createSwapOffer({
81
+ partyId: senderPartyId,
82
+ swapId: "swap-" + Date.now(),
83
+ acceptorPartyId: "Party::Acceptor",
84
+ instrumentOutId: senderHoldingInstrumentId,
85
+ instrumentOutAdmin: "Admin::Out",
86
+ amountOut: "1.0",
87
+ instrumentInId: "Inst::In",
88
+ instrumentInAdmin: "Admin::In",
89
+ amountIn: "2.0",
90
+ settleBefore: new Date(Date.now() + 3600 * 1000).toISOString(),
62
91
  });
63
- console.log('Send result', res); // { txId }
92
+
93
+ console.log("Swap offer result", swapRes); // { txId }
64
94
  ```
95
+
65
96
  ## API Reference
66
97
 
67
- #### Public API (Provider)
98
+ ### Public API: `C8WalletProvider`
99
+
100
+ | Method | Parameters | Return Type |
101
+ | --------------------- | ------------------------------------------ | --------------------------------------------------------- |
102
+ | `connect()` | None | `Promise<void>` |
103
+ | `disconnect()` | None | `Promise<void>` |
104
+ | `status()` | None | `Promise<{ connected: boolean; walletVersion?: string }>` |
105
+ | `getInstruments()` | None | `Promise<InstrumentListPayload>` |
106
+ | `getAccounts()` | `instrumentId?: string` | `Promise<AccountListPayload>` |
107
+ | `send()` | `input: SendInput` | `Promise<SubmitTransferResultPayload>` |
108
+ | `createSwapOffer()` | `input: CreateSwapOfferInput` | `Promise<SubmitTransferResultPayload>` |
109
+ | `signAndExecute()` | `input: SignAndExecuteInput` | `Promise<void>` |
110
+ | `checkTxStatusById()` | `input: { txId: string }` | `Promise<TransferStatusResponsePayload>` |
111
+ | `on()` | `event: T, cb: Listener<C8EventByType<T>>` | `() => boolean` |
112
+
113
+ ### `send()` Input
114
+
115
+ ```ts
116
+ {
117
+ senderPartyId: string;
118
+ instrumentId: string;
119
+ amount: number;
120
+ receiverPartyId: string;
121
+ memo?: string;
122
+ metadata?: Record<string, string>;
123
+ }
124
+ ```
68
125
 
69
- | |
70
- | :-------- |
71
- | `connect(): Promise<void>` |
72
- | `disconnect(): Promise<void>` |
73
- | `status(): Promise<{connected: boolean, walletVersion?: string}>` |
74
- | `getInstruments(): Promise<InstrumentListPayload>` |
75
- | `getAccounts(instrumentId?: string): Promise<AccountListPayload>` |
76
- | `send(input: {senderPartyId: string, instrumentId: string, amount: number, receiverPartyId: string, memo?: string, metadata?: Record<string, string>}): Promise<SubmitTransferResultPayload>` |
77
- | `checkTxStatusById(input: {partyId: string, txId: string}): Promise<TransferStatusResponsePayload>` |
126
+ ### `createSwapOffer()` Input
127
+
128
+ ```ts
129
+ {
130
+ partyId: string;
131
+ swapId: string;
132
+ acceptorPartyId: string;
133
+ instrumentOutId: string;
134
+ instrumentOutAdmin: string;
135
+ amountOut: string;
136
+ instrumentInId: string;
137
+ instrumentInAdmin: string;
138
+ amountIn: string;
139
+ settleBefore: string;
140
+ metaJson?: string;
141
+ commandId?: string;
142
+ }
143
+ ```
144
+
145
+ ### `signAndExecute()` Input
146
+
147
+ ```ts
148
+ {
149
+ note: string;
150
+ partyId: string;
151
+ commandId: string;
152
+ commandsJson: string;
153
+ disclosedContracts: string;
154
+ }
155
+ ```
78
156
 
79
- #### Events
157
+ ## Events Reference
80
158
 
81
- | |
82
- | :-------- |
83
- | `connected` |
84
- | `disconnected` |
85
- | `accountChanged` |
86
- | `txInitiated` |
87
- | `txChanged` |
159
+ Use `c8.on(eventType, callback)` to listen for changes emitted by the wallet.
88
160
 
161
+ | Event Type | Payload Properties | Description |
162
+ | ------------------- | --------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
163
+ | `connected` | `meta?: Json` | Fired when the wallet successfully connects. |
164
+ | `disconnected` | `reason?: string`, `meta?: Json` | Fired when the session disconnects. |
165
+ | `txInitiated` | `txId?: string`, `meta?: Json` | Fired when a transaction request is initiated. |
166
+ | `txChanged` | `txId: string`, `status: "pending" \| "confirmed" \| "failed" \| string`, `meta?: Json` | Fired when a transaction's completion status updates. |
167
+ | `accountChanged` | `accounts: AccountInfoPayload[]`, `meta?: Json` | Fired when internal account asset holdings scale or modify. |
168
+ | `themeChanged` | `theme: "dark" \| "light"`, `meta?: Json` | Fired when the wallet interface changes its UI display theme. |
169
+ | `operationCanceled` | `reason: string`, `meta?: Json` | Fired when an action or modal interface is explicitly rejected by the user. |
170
+
171
+ ## Unsubscribing from Events
172
+
173
+ The `on()` method returns an unsubscribe function:
174
+
175
+ ```ts
176
+ const unsubscribe = c8.on("connected", (event) => {
177
+ console.log("Connected", event);
178
+ });
179
+
180
+ unsubscribe();
181
+ ```
89
182
 
183
+ ## License
90
184
 
185
+ MIT
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";const e="https://wallet.dev.digik.cantor8.tech",t="https://wallet-backend.dev.digik.cantor8.tech";class s{static getItem(e){try{const t=localStorage.getItem(e);return t?JSON.parse(t):null}catch(e){return null}}static setItem(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(e){}}static removeItem(e){try{localStorage.removeItem(e)}catch(e){}}}const n={TestCoin1:"TestCoin1",Amulet:"Canton Coin",CBTC:"CBTC",USDCx:"USDCx",CETH:"CETH"},i=e=>{var t;return"Amulet"===e?"Canton Coin":null!=(t=n[null!=e?e:""])?t:e},r={TestCoin1:"TestCoin1",Amulet:"CC",CBTC:"CBTC",USDCx:"USDCx"},a=e=>{var t;return"Amulet"===e?"CC":null!=(t=r[null!=e?e:""])?t:e};var o=Object.defineProperty,h=(e,t,s)=>((e,t,s)=>t in e?o(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);const d=class e{constructor(){h(this,"appName"),h(this,"accounts",[]),h(this,"instruments",[]),h(this,"partyIds",[]),h(this,"authToken",null),h(this,"isConnected",!1),h(this,"expireAt",null),h(this,"disconnectTimeoutId",null),this.load()}static getInstance(){return e.instance||(e.instance=new e),e.instance}setAppName(e){this.appName=e}getAppName(){return this.appName}setInstruments(e){this.instruments=e}getInstruments(){return this.instruments}setAccounts(e){this.accounts=e,this.partyIds=e.map(e=>e.partyId),this.instruments=e.flatMap(e=>e.holdings.map(e=>({instrumentId:e.instrumentId,name:i(e.instrumentId),symbol:a(e.instrumentId)})))}getAccounts(){return this.accounts}setBearerToken(e,t){this.authToken=e,this.isConnected=!0,this.expireAt=t}getExpireAt(){return this.expireAt}setDisconnectTimeoutId(e){this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),this.disconnectTimeoutId=e}getDisconnectTimeoutId(){return this.disconnectTimeoutId}getBearerToken(){return this.authToken}clear(){this.accounts=[],this.instruments=[],this.authToken=null,this.partyIds=[],this.isConnected=!1,this.expireAt=null,this.disconnectTimeoutId&&(clearTimeout(this.disconnectTimeoutId),this.disconnectTimeoutId=null),s.removeItem(e.SESSION_KEY)}save(){s.setItem(e.SESSION_KEY,{authToken:this.authToken,partyIds:this.partyIds,expireAt:this.expireAt})}setConnected(e){this.isConnected=e}getConnected(){return this.isConnected}hasStoredSession(){return!!s.getItem(e.SESSION_KEY)}load(){const t=s.getItem(e.SESSION_KEY);t&&(this.authToken=t.authToken,this.partyIds=t.partyIds||[],this.expireAt=t.expireAt||null)}};h(d,"instance"),h(d,"SESSION_KEY","c8-session");let c=d;var l=Object.defineProperty,u=(e,t,s)=>((e,t,s)=>t in e?l(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);const p=class e{constructor(e=5e3){this.pollingInterval=e,u(this,"events",new Map),u(this,"intervals",new Map),u(this,"handlerRegistry",new Map),this.restore()}static getInstance(t=5e3){return e.instance||(e.instance=new e(t)),e.instance}registerHandler(e,t){this.handlerRegistry.set(e,t),this.events.forEach((s,n)=>{s.event.type===e&&(this.stopPolling(n),s.handler=t,this.startPolling(n))})}add(e,t){const s=btoa(`${e}-${JSON.stringify(t)}`);this.events.has(s)&&this.remove(s);const n=this.handlerRegistry.get(e);if(!n)return;const i={key:s,type:e,params:t,createdAt:Date.now()};this.events.set(s,{event:i,handler:n}),this.persist(),this.startPolling(s)}remove(e){this.stopPolling(e),this.events.delete(e),this.persist()}startPolling(t){const s=this.events.get(t);if(!s)return;const{event:n,handler:i}=s,r=async()=>{try{if(n.createdAt&&Date.now()-n.createdAt>e.POLLING_TIMEOUT)return void this.remove(t);await i(n.params)&&this.remove(t)}catch(e){}};r();const a=window.setInterval(r,this.pollingInterval);this.intervals.set(t,a)}stopPolling(e){const t=this.intervals.get(e);void 0!==t&&(window.clearInterval(t),this.intervals.delete(e))}persist(){const t=Array.from(this.events.values()).map(e=>e.event);s.setItem(e.STORAGE_KEY,t)}restore(){const t=s.getItem(e.STORAGE_KEY);if(t&&Array.isArray(t)){const s=Date.now();t.forEach(t=>{if(t.createdAt&&s-t.createdAt>e.POLLING_TIMEOUT)return;const n=this.handlerRegistry.get(t.key);n?(this.events.set(t.key,{event:t,handler:n}),this.startPolling(t.key)):this.events.set(t.key,{event:t,handler:async()=>!1})})}}clear(){this.events.clear(),this.intervals.forEach(e=>window.clearInterval(e)),this.intervals.clear(),this.persist(),s.removeItem(e.STORAGE_KEY)}getEvents(){return Array.from(this.events.values()).map(e=>e.event)}};u(p,"EVENT_TYPES",{RESTORE_SESSION:"RESTORE_SESSION",TRACK_TX_STATUS:"TRACK_TX_STATUS",UPDATE_ACCOUNT:"UPDATE_ACCOUNT"}),u(p,"type"),u(p,"instance"),u(p,"STORAGE_KEY","c8-polling-events"),u(p,"POLLING_TIMEOUT",3e5);let m=p;var g=Object.defineProperty;class v{constructor(e){((e,t,s)=>{((e,t,s)=>{t in e?g(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s})(e,t+"",s)})(this,"baseUrl"),this.baseUrl=e.endsWith("/")?e.slice(0,-1):e}async request(e,t={}){const s=c.getInstance().getBearerToken(),n=c.getInstance().getAppName(),i=new Headers(t.headers);s&&(i.set("Authorization",`Bearer ${s}`),i.set("X-App-Name",null!=n?n:"Unknown App")),i.set("x-feat-decimals","1");const r=await fetch(`${this.baseUrl}${e}`,{...t,headers:i});if(!r.ok)throw new Error(`HTTP error! status: ${r.status}`);return await r.json()}async getBalance(){return this.request("/api/balance")}async getTransferStatus(e){return this.request(`/api/transfer/status?command_id=${e}`)}}var T=Object.defineProperty,I=(e,t,s)=>((e,t,s)=>t in e?T(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);function f(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}class w{constructor(s,n,i=e){let r;switch(this.appName=s,this.appUrl=n,this.origin=i,I(this,"WINDOW_NAME","c8-wallet"),I(this,"WINDOW_WIDTH",475),I(this,"WINDOW_HEIGHT",762),I(this,"popup"),I(this,"sessionId",crypto.randomUUID()),I(this,"listening",!1),I(this,"walletReady",!1),I(this,"pending",new Map),I(this,"eventHandlers",new Set),I(this,"handshakeTimer"),I(this,"handshakeDeadline"),I(this,"closeWatcherTimer"),I(this,"pollingManager",m.getInstance()),I(this,"session",c.getInstance()),I(this,"initDeferred"),I(this,"httpClient"),this.onWindowMessage=this.onWindowMessage.bind(this),this.handleRestoreSession=this.handleRestoreSession.bind(this),this.handleTrackTxStatus=this.handleTrackTxStatus.bind(this),this.handleAccountUpdate=this.handleAccountUpdate.bind(this),this.session.setAppName(this.appName),this.attachListener(),this.origin){case e:r=t;break;case"https://wallet.cantor8.tech":case"https://wallet.main.digik.cantor8.tech":r="https://wallet-backend.main.cantor8.tech";break;default:r=t}this.httpClient=new v(r),this.pollingManager.registerHandler(m.EVENT_TYPES.RESTORE_SESSION,this.handleRestoreSession),this.pollingManager.registerHandler(m.EVENT_TYPES.TRACK_TX_STATUS,this.handleTrackTxStatus),this.pollingManager.registerHandler(m.EVENT_TYPES.UPDATE_ACCOUNT,this.handleAccountUpdate),this.checkRestoreSession()}checkRestoreSession(){this.session.hasStoredSession()&&this.pollingManager.add(m.EVENT_TYPES.RESTORE_SESSION,{sessionId:this.sessionId})}async handleAccountUpdate(e){try{const e=await this.httpClient.getBalance();if(e&&e.holdings){const t=[{partyId:e.party_id,holdings:Object.entries(e.holdings).map(([e,t])=>({instrumentId:e,balance:Number(t.balance),balanceUsd:Number(t.balance_usd)}))}];this.session.setAccounts(t),this.session.save()}return!0}catch(e){e instanceof Error&&e.message.includes("401")&&this.destroy()}return!1}async getTransferStatusById(e){try{const t=await this.httpClient.getTransferStatus(e);let s;switch(t.status){case"success":s="confirmed";break;case"failed":s="failed";break;default:s="pending"}return t.status=s,t}catch(e){return e instanceof Error&&e.message.includes("401")&&this.destroy(),null}}async handleTrackTxStatus(e){try{const t=await this.httpClient.getTransferStatus(e.txId);if(e.status!==t.status){let s;switch(t.status){case"success":s="confirmed";break;case"failed":s="failed";break;default:s="pending"}return this.emitSyntheticEvent({type:"txChanged",txId:e.txId,status:s}),e.status=t.status,this.pollingManager.persist(),"pending"!==t.status&&this.pollingManager.add(m.EVENT_TYPES.UPDATE_ACCOUNT,{txId:e.txId}),"success"===t.status||"failed"===t.status}}catch(t){if(t instanceof Error&&(t.message.includes("401")&&this.destroy(),t.message.includes("404")))return this.emitSyntheticEvent({type:"txChanged",txId:e.txId,status:"failed"}),!0}return!1}async handleRestoreSession(e){try{const e=await this.httpClient.getBalance();if(e&&e.holdings){const t=[{partyId:e.party_id,holdings:Object.entries(e.holdings).map(([e,t])=>({instrumentId:e,balance:Number(t.balance),balanceUsd:Number(t.balance_usd)}))}];this.session.setAccounts(t),this.session.save(),this.session.setConnected(!0),this.emitSyntheticEvent({type:"connected"});const s=this.session.getExpireAt();return s&&this.scheduleDisconnect(s),!0}}catch(e){e instanceof Error&&e.message.includes("401")&&this.destroy()}return!1}get WALLET_EMBEDDED(){return`${this.origin}/embedded/`}async init(e){var t;if(void 0!==this.popup&&(null==(t=this.popup)||!t.closed))return;if(this.initDeferred||(this.initDeferred=f()),this.listening||this.attachListener(),this.popup&&!this.popup.closed)return this.popup.focus(),null==this.handshakeTimer&&this.startHandshakeLoop(),this.initDeferred.promise;const s=new URL(null!=e?e:"",this.WALLET_EMBEDDED);if(this.popup=window.open(s,this.WINDOW_NAME,`width=${this.WINDOW_WIDTH},height=${this.WINDOW_HEIGHT}`),!this.popup){const e=new Error("Failed to open popup window");Object.assign(e,{code:"POPUP_BLOCKED",message:"browser blocked the popup window"}),this.rejectInit(e)}return this.startHandshakeLoop(),this.initDeferred.promise}emitSyntheticEvent(e){for(const t of this.eventHandlers)try{t({kind:"event",event:e})}catch(e){}}scheduleDisconnect(e){if(!e)return;const t=e-Date.now();if(t>0){const e=setTimeout(()=>{this.destroy("authToken expired")},t);this.session.setDisconnectTimeoutId(e)}else this.destroy("authToken expired")}destroy(e="destroyed"){try{this.emitSyntheticEvent({type:"disconnected",reason:e}),this.detachListener(),this.clearHandshakeLoop(),this.initDeferred&&(this.initDeferred.reject(new Error("Transport destroyed")),this.initDeferred=void 0);for(const[,e]of this.pending)e.reject(new Error("Transport destroyed"));this.pending.clear(),this.popup&&!this.popup.closed&&this.popup.close(),this.popup=void 0,this.walletReady=!1,this.session.clear(),this.pollingManager.clear()}catch(e){}}async request(e,t,s){var n,i,r,a,o,h,d,c,l,u,p,m,g,v,T,I;const w=crypto.randomUUID(),E=f();this.pending.set(w,E);try{if("connect"===e){if(this.session.getBearerToken())return this.handleResponse({kind:"response",id:w,result:null}),E.promise;this.session.getBearerToken()||(this.walletReady=!1),await this.init()}if("send"===e&&(this.walletReady=!1,await this.init("confirmTransaction")),"signAndExecute"===e&&(this.walletReady=!1,await this.init("signAndExecute")),"status"===e)return this.handleResponse({kind:"response",id:w,result:{connected:this.session.getConnected(),walletVersion:void 0}}),E.promise;if(s&&(null==(n=this.popup)||n.focus()),"getInstruments"===e){const e=this.session.getInstruments();return this.handleResponse({kind:"response",id:w,result:{instruments:e}}),E.promise}if("getAccounts"===e){await this.handleAccountUpdate();const e=this.session.getAccounts();return this.handleResponse({kind:"response",id:w,result:{accounts:e}}),E.promise}if("checkTxStatusById"===e){const e=t,s=await this.getTransferStatusById(null==e?void 0:e.txId);if(s){const e={status:s.status,transfer:{senderPartyId:null!=(r=null==(i=s.transfer)?void 0:i.party_id)?r:"",receiverPartyId:null!=(o=null==(a=s.transfer)?void 0:a.party_id2)?o:"",amount:Number(null!=(d=null==(h=s.transfer)?void 0:h.amount)?d:"0"),networkFees:Number(null!=(l=null==(c=s.transfer)?void 0:c.network_fees)?l:"0"),instrumentId:null!=(p=null==(u=s.transfer)?void 0:u.instrument_id)?p:"",txId:null!=(g=null==(m=s.transfer)?void 0:m.command_id)?g:"",created_at:null!=(T=null==(v=s.transfer)?void 0:v.created_at)?T:"",memo:null==(I=s.transfer)?void 0:I.reason}};this.handleResponse({kind:"response",id:w,result:e})}else this.handleResponse({kind:"response",id:w,error:{code:"FAILED_TO_FETCH_TRANSFER_STATUS",message:"Failed to fetch transfer status"}});return E.promise}if("disconnect"===e)return this.handleResponse({kind:"response",id:w,result:null}),E.promise;const f={kind:"request",id:w,method:e,params:t,sessionId:this.sessionId};this.post(f)}catch(e){this.pending.delete(w),E.reject(e)}return E.promise}onEvent(e){return this.eventHandlers.add(e),()=>{this.eventHandlers.delete(e)}}attachListener(){this.listening||(window.addEventListener("message",this.onWindowMessage),this.listening=!0)}detachListener(){this.listening&&(window.removeEventListener("message",this.onWindowMessage),this.listening=!1)}post(e){try{if(!this.popup||this.popup.closed)return;this.popup.postMessage(e,this.origin)}catch(e){}}onWindowMessage(e){if(e.origin!==this.origin)return;const t=e.data;if(t&&"object"==typeof t){if("event"===t.kind){for(const e of this.eventHandlers)"txInitiated"===t.event.type&&this.pollingManager.add(m.EVENT_TYPES.TRACK_TX_STATUS,{txId:t.event.txId,status:"initiated"}),e(t);return}if("internal_event"===t.kind)return void this.pollingManager.add(t.event.type,{wop:"wopwop"});if("auth-flow"===t.kind&&(this.session.setBearerToken(t.token,t.expireAt),this.session.setAccounts(t.accounts),this.session.setInstruments(t.instruments),this.session.save(),this.scheduleDisconnect(t.expireAt)),"handshake-ack"===t.kind&&t.ok)return void this.handleHandshakeAck();"response"===t.kind&&this.handleResponse(t)}}handleHandshakeAck(){this.walletReady=!0,this.clearHandshakeLoop(),this.initDeferred&&(this.initDeferred.resolve(),this.initDeferred=void 0)}handleResponse(e){const t=this.pending.get(e.id);if(t)if(this.pending.delete(e.id),e.error){const s=new Error(e.error.message||"Unknown Error");Object.assign(s,{code:e.error.code,data:e.error.data}),t.reject(s)}else t.resolve(e.result)}startHandshakeLoop(){this.handshakeDeadline=Date.now()+55e3;const e=()=>{if(!this.walletReady)return!this.popup||this.popup.closed?(this.clearHandshakeLoop(),void this.rejectInit(new Error("Popup closed before handshake"))):this.handshakeDeadline&&Date.now()>this.handshakeDeadline?(this.clearHandshakeLoop(),void this.rejectInit(new Error("Handshake timed out"))):void this.post({kind:"handshake",sdkVersion:"0.0.0",sessionId:this.sessionId,dapp:{name:this.appName,url:this.appUrl}});this.clearHandshakeLoop()};e(),this.handshakeTimer=window.setInterval(e,300)}clearHandshakeLoop(){null!=this.handshakeTimer&&(clearInterval(this.handshakeTimer),this.handshakeTimer=void 0),this.handshakeDeadline=void 0}rejectInit(e){this.initDeferred&&(Object.assign(e,{code:"INITIALIZATION_FAILED",message:e.message}),this.initDeferred.reject(e),this.initDeferred=void 0)}startPopupClosedWatcher(){const e=this.popup;if(!e)return;const t=window.setInterval(()=>{(!e||e.closed)&&(clearInterval(t),this.destroy())},300);this.closeWatcherTimer=t}}var E=Object.defineProperty,y=(e,t,s)=>((e,t,s)=>t in e?E(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);const k={uuid:"c8-wallet-connect",name:"C8 Wallet",icon:"",rdns:"tech.cantor8.wallet"},S="c8#provider_discovery";exports.C8WalletProvider=class{constructor(t){var s,n,i;y(this,"transport"),y(this,"listeners",{});const r=null!=(s=t.dappName)?s:document.title||"Unknown dApp",a=null!=(n=t.dappUrl)?n:location.origin,o=null!=(i=t.network)?i:"mainnet";let h;if("devnet"!==o)throw new Error("Only devnet network is supported right now");if("devnet"!==o)throw new Error("Unsupported network: "+o);h=e,this.transport=new w(r,a,h),this.transport.onEvent(e=>{"event"===e.kind&&this.emit(e.event.type,e.event)})}async connect(){await this.transport.request("connect",void 0,!0)}async disconnect(){try{await this.transport.request("disconnect"),this.transport.destroy()}catch(e){}}status(){return this.transport.request("status")}getInstruments(){return this.transport.request("getInstruments")}getAccounts(e){return this.transport.request("getAccounts",{instrumentId:e})}send(e){return this.transport.request("send",e,!0)}signAndExecute(e){return this.transport.request("signAndExecute",e,!0)}signAndExecutePreparedTransfer(e){return this.transport.request("signAndExecutePreparedTransfer",e,!0)}acknowledge(e){return this.transport.request("acknowledge",e,!0)}checkTxStatusById(e){return this.transport.request("checkTxStatusById",e)}on(e,t){return this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(t),()=>this.listeners[e].delete(t)}emit(e,t){var s;for(const n of null!=(s=this.listeners[e])?s:[])n(t)}},exports.HttpClient=v,exports.LocalStorageHelper=s,exports.announceC8Provider=function(e){const t={info:k,provider:e()};window.dispatchEvent(new CustomEvent(S,{detail:t}))},exports.onC8ProviderDiscovered=function(e){const t=t=>{const s=t;s.detail&&e(s.detail.info,s.detail.provider)};return window.addEventListener(S,t),()=>window.removeEventListener(S,t)};
1
+ "use strict";const e="https://wallet.dev.digik.cantor8.tech",t="https://wallet-backend.dev.digik.cantor8.tech",s="https://wallet.cantor8.tech";class n{static getItem(e){try{const t=localStorage.getItem(e);return t?JSON.parse(t):null}catch(e){return null}}static setItem(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(e){}}static removeItem(e){try{localStorage.removeItem(e)}catch(e){}}}const i={TestCoin1:"TestCoin1",Amulet:"Canton Coin",CBTC:"CBTC",USDCx:"USDCx",CETH:"CETH"},r=e=>{var t;return"Amulet"===e?"Canton Coin":null!=(t=i[null!=e?e:""])?t:e},a={TestCoin1:"TestCoin1",Amulet:"CC",CBTC:"CBTC",USDCx:"USDCx"},o=e=>{var t;return"Amulet"===e?"CC":null!=(t=a[null!=e?e:""])?t:e};var h=Object.defineProperty,d=(e,t,s)=>((e,t,s)=>t in e?h(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);const c=class e{constructor(){d(this,"appName"),d(this,"accounts",[]),d(this,"instruments",[]),d(this,"partyIds",[]),d(this,"authToken",null),d(this,"isConnected",!1),d(this,"expireAt",null),d(this,"disconnectTimeoutId",null),this.load()}static getInstance(){return e.instance||(e.instance=new e),e.instance}setAppName(e){this.appName=e}getAppName(){return this.appName}setInstruments(e){this.instruments=e}getInstruments(){return this.instruments}setAccounts(e){this.accounts=e,this.partyIds=e.map(e=>e.partyId),this.instruments=e.flatMap(e=>e.holdings.map(e=>({instrumentId:e.instrumentId,name:r(e.instrumentId),symbol:o(e.instrumentId)})))}getAccounts(){return this.accounts}setBearerToken(e,t){this.authToken=e,this.isConnected=!0,this.expireAt=t}getExpireAt(){return this.expireAt}setDisconnectTimeoutId(e){this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),this.disconnectTimeoutId=e}getDisconnectTimeoutId(){return this.disconnectTimeoutId}getBearerToken(){return this.authToken}clear(){this.accounts=[],this.instruments=[],this.authToken=null,this.partyIds=[],this.isConnected=!1,this.expireAt=null,this.disconnectTimeoutId&&(clearTimeout(this.disconnectTimeoutId),this.disconnectTimeoutId=null),n.removeItem(e.SESSION_KEY)}save(){n.setItem(e.SESSION_KEY,{authToken:this.authToken,partyIds:this.partyIds,expireAt:this.expireAt})}setConnected(e){this.isConnected=e}getConnected(){return this.isConnected}hasStoredSession(){return!!n.getItem(e.SESSION_KEY)}load(){const t=n.getItem(e.SESSION_KEY);t&&(this.authToken=t.authToken,this.partyIds=t.partyIds||[],this.expireAt=t.expireAt||null)}};d(c,"instance"),d(c,"SESSION_KEY","c8-session");let l=c;var u=Object.defineProperty,p=(e,t,s)=>((e,t,s)=>t in e?u(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);const m=class e{constructor(e=5e3){this.pollingInterval=e,p(this,"events",new Map),p(this,"intervals",new Map),p(this,"handlerRegistry",new Map),this.restore()}static getInstance(t=5e3){return e.instance||(e.instance=new e(t)),e.instance}registerHandler(e,t){this.handlerRegistry.set(e,t),this.events.forEach((s,n)=>{s.event.type===e&&(this.stopPolling(n),s.handler=t,this.startPolling(n))})}add(e,t){const s=btoa(`${e}-${JSON.stringify(t)}`);this.events.has(s)&&this.remove(s);const n=this.handlerRegistry.get(e);if(!n)return;const i={key:s,type:e,params:t,createdAt:Date.now()};this.events.set(s,{event:i,handler:n}),this.persist(),this.startPolling(s)}remove(e){this.stopPolling(e),this.events.delete(e),this.persist()}startPolling(t){const s=this.events.get(t);if(!s)return;const{event:n,handler:i}=s,r=async()=>{try{if(n.createdAt&&Date.now()-n.createdAt>e.POLLING_TIMEOUT)return void this.remove(t);await i(n.params)&&this.remove(t)}catch(e){}};r();const a=window.setInterval(r,this.pollingInterval);this.intervals.set(t,a)}stopPolling(e){const t=this.intervals.get(e);void 0!==t&&(window.clearInterval(t),this.intervals.delete(e))}persist(){const t=Array.from(this.events.values()).map(e=>e.event);n.setItem(e.STORAGE_KEY,t)}restore(){const t=n.getItem(e.STORAGE_KEY);if(t&&Array.isArray(t)){const s=Date.now();t.forEach(t=>{if(t.createdAt&&s-t.createdAt>e.POLLING_TIMEOUT)return;const n=this.handlerRegistry.get(t.key);n?(this.events.set(t.key,{event:t,handler:n}),this.startPolling(t.key)):this.events.set(t.key,{event:t,handler:async()=>!1})})}}clear(){this.events.clear(),this.intervals.forEach(e=>window.clearInterval(e)),this.intervals.clear(),this.persist(),n.removeItem(e.STORAGE_KEY)}getEvents(){return Array.from(this.events.values()).map(e=>e.event)}};p(m,"EVENT_TYPES",{RESTORE_SESSION:"RESTORE_SESSION",TRACK_TX_STATUS:"TRACK_TX_STATUS",UPDATE_ACCOUNT:"UPDATE_ACCOUNT"}),p(m,"type"),p(m,"instance"),p(m,"STORAGE_KEY","c8-polling-events"),p(m,"POLLING_TIMEOUT",3e5);let g=m;var T=Object.defineProperty;class f{constructor(e){((e,t,s)=>{((e,t,s)=>{t in e?T(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s})(e,t+"",s)})(this,"baseUrl"),this.baseUrl=e.endsWith("/")?e.slice(0,-1):e}async request(e,t={}){const s=l.getInstance().getBearerToken(),n=l.getInstance().getAppName(),i=new Headers(t.headers);s&&(i.set("Authorization",`Bearer ${s}`),i.set("X-App-Name",null!=n?n:"Unknown App")),i.set("x-feat-decimals","1");const r=await fetch(`${this.baseUrl}${e}`,{...t,headers:i});if(!r.ok)throw new Error(`HTTP error! status: ${r.status}`);return await r.json()}async getBalance(){return this.request("/api/balance")}async getTransferStatus(e){return this.request(`/api/transfer/status?command_id=${e}`)}}var v=Object.defineProperty,I=(e,t,s)=>((e,t,s)=>t in e?v(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);function w(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}class y{constructor(n,i,r=e){let a;switch(this.appName=n,this.appUrl=i,this.origin=r,I(this,"WINDOW_NAME","c8-wallet"),I(this,"WINDOW_WIDTH",475),I(this,"WINDOW_HEIGHT",762),I(this,"popup"),I(this,"sessionId",crypto.randomUUID()),I(this,"listening",!1),I(this,"walletReady",!1),I(this,"pending",new Map),I(this,"eventHandlers",new Set),I(this,"handshakeTimer"),I(this,"handshakeDeadline"),I(this,"closeWatcherTimer"),I(this,"pollingManager",g.getInstance()),I(this,"session",l.getInstance()),I(this,"initDeferred"),I(this,"httpClient"),this.onWindowMessage=this.onWindowMessage.bind(this),this.handleRestoreSession=this.handleRestoreSession.bind(this),this.handleTrackTxStatus=this.handleTrackTxStatus.bind(this),this.handleAccountUpdate=this.handleAccountUpdate.bind(this),this.session.setAppName(this.appName),this.attachListener(),this.origin){case e:a=t;break;case s:case"https://wallet.main.digik.cantor8.tech":a="https://wallet-backend.main.cantor8.tech";break;default:a=t}this.httpClient=new f(a),this.pollingManager.registerHandler(g.EVENT_TYPES.RESTORE_SESSION,this.handleRestoreSession),this.pollingManager.registerHandler(g.EVENT_TYPES.TRACK_TX_STATUS,this.handleTrackTxStatus),this.pollingManager.registerHandler(g.EVENT_TYPES.UPDATE_ACCOUNT,this.handleAccountUpdate),this.checkRestoreSession()}checkRestoreSession(){this.session.hasStoredSession()&&this.pollingManager.add(g.EVENT_TYPES.RESTORE_SESSION,{sessionId:this.sessionId})}async handleAccountUpdate(e){try{const e=await this.httpClient.getBalance();if(e&&e.holdings){const t=[{partyId:e.party_id,holdings:Object.entries(e.holdings).map(([e,t])=>({instrumentId:e,balance:Number(t.balance),balanceUsd:Number(t.balance_usd)}))}];this.session.setAccounts(t),this.session.save()}return!0}catch(e){e instanceof Error&&e.message.includes("401")&&this.destroy()}return!1}async getTransferStatusById(e){try{const t=await this.httpClient.getTransferStatus(e);let s;switch(t.status){case"success":s="confirmed";break;case"failed":s="failed";break;default:s="pending"}return t.status=s,t}catch(e){return e instanceof Error&&e.message.includes("401")&&this.destroy(),null}}async handleTrackTxStatus(e){try{const t=await this.httpClient.getTransferStatus(e.txId);if(e.status!==t.status){let s;switch(t.status){case"success":s="confirmed";break;case"failed":s="failed";break;default:s="pending"}return this.emitSyntheticEvent({type:"txChanged",txId:e.txId,status:s}),e.status=t.status,this.pollingManager.persist(),"pending"!==t.status&&this.pollingManager.add(g.EVENT_TYPES.UPDATE_ACCOUNT,{txId:e.txId}),"success"===t.status||"failed"===t.status}}catch(t){if(t instanceof Error&&(t.message.includes("401")&&this.destroy(),t.message.includes("404")))return this.emitSyntheticEvent({type:"txChanged",txId:e.txId,status:"failed"}),!0}return!1}async handleRestoreSession(e){try{const e=await this.httpClient.getBalance();if(e&&e.holdings){const t=[{partyId:e.party_id,holdings:Object.entries(e.holdings).map(([e,t])=>({instrumentId:e,balance:Number(t.balance),balanceUsd:Number(t.balance_usd)}))}];this.session.setAccounts(t),this.session.save(),this.session.setConnected(!0),this.emitSyntheticEvent({type:"connected"});const s=this.session.getExpireAt();return s&&this.scheduleDisconnect(s),!0}}catch(e){e instanceof Error&&e.message.includes("401")&&this.destroy()}return!1}get WALLET_EMBEDDED(){return`${this.origin}/embedded/`}async init(e){var t;if(void 0!==this.popup&&(null==(t=this.popup)||!t.closed))return;if(this.initDeferred||(this.initDeferred=w()),this.listening||this.attachListener(),this.popup&&!this.popup.closed)return this.popup.focus(),null==this.handshakeTimer&&this.startHandshakeLoop(),this.initDeferred.promise;const s=new URL(null!=e?e:"",this.WALLET_EMBEDDED);if(this.popup=window.open(s,this.WINDOW_NAME,`width=${this.WINDOW_WIDTH},height=${this.WINDOW_HEIGHT}`),!this.popup){const e=new Error("Failed to open popup window");Object.assign(e,{code:"POPUP_BLOCKED",message:"browser blocked the popup window"}),this.rejectInit(e)}return this.startHandshakeLoop(),this.initDeferred.promise}emitSyntheticEvent(e){for(const t of this.eventHandlers)try{t({kind:"event",event:e})}catch(e){}}scheduleDisconnect(e){if(!e)return;const t=e-Date.now();if(t>0){const e=setTimeout(()=>{this.destroy("authToken expired")},t);this.session.setDisconnectTimeoutId(e)}else this.destroy("authToken expired")}destroy(e="destroyed"){try{this.emitSyntheticEvent({type:"disconnected",reason:e}),this.detachListener(),this.clearHandshakeLoop(),this.initDeferred&&(this.initDeferred.reject(new Error("Transport destroyed")),this.initDeferred=void 0);for(const[,e]of this.pending)e.reject(new Error("Transport destroyed"));this.pending.clear(),this.popup&&!this.popup.closed&&this.popup.close(),this.popup=void 0,this.walletReady=!1,this.session.clear(),this.pollingManager.clear()}catch(e){}}async request(e,t,s){var n,i,r,a,o,h,d,c,l,u,p,m,g,T,f,v;const I=crypto.randomUUID(),y=w();this.pending.set(I,y);try{if("connect"===e){if(this.session.getBearerToken())return this.handleResponse({kind:"response",id:I,result:null}),y.promise;this.session.getBearerToken()||(this.walletReady=!1),await this.init()}if("send"===e&&(this.walletReady=!1,await this.init("confirmTransaction")),"createSwapOffer"===e&&(this.walletReady=!1,await this.init("confirmSwapOffer")),"signAndExecute"===e&&(this.walletReady=!1,await this.init("signAndExecute")),"status"===e)return this.handleResponse({kind:"response",id:I,result:{connected:this.session.getConnected(),walletVersion:void 0}}),y.promise;if(s&&(null==(n=this.popup)||n.focus()),"getInstruments"===e){const e=this.session.getInstruments();return this.handleResponse({kind:"response",id:I,result:{instruments:e}}),y.promise}if("getAccounts"===e){await this.handleAccountUpdate();const e=this.session.getAccounts();return this.handleResponse({kind:"response",id:I,result:{accounts:e}}),y.promise}if("checkTxStatusById"===e){const e=t,s=await this.getTransferStatusById(null==e?void 0:e.txId);if(s){const e={status:s.status,transfer:{senderPartyId:null!=(r=null==(i=s.transfer)?void 0:i.party_id)?r:"",receiverPartyId:null!=(o=null==(a=s.transfer)?void 0:a.party_id2)?o:"",amount:Number(null!=(d=null==(h=s.transfer)?void 0:h.amount)?d:"0"),networkFees:Number(null!=(l=null==(c=s.transfer)?void 0:c.network_fees)?l:"0"),instrumentId:null!=(p=null==(u=s.transfer)?void 0:u.instrument_id)?p:"",txId:null!=(g=null==(m=s.transfer)?void 0:m.command_id)?g:"",created_at:null!=(f=null==(T=s.transfer)?void 0:T.created_at)?f:"",memo:null==(v=s.transfer)?void 0:v.reason}};this.handleResponse({kind:"response",id:I,result:e})}else this.handleResponse({kind:"response",id:I,error:{code:"FAILED_TO_FETCH_TRANSFER_STATUS",message:"Failed to fetch transfer status"}});return y.promise}if("disconnect"===e)return this.handleResponse({kind:"response",id:I,result:null}),y.promise;const w={kind:"request",id:I,method:e,params:t,sessionId:this.sessionId};this.post(w)}catch(e){this.pending.delete(I),y.reject(e)}return y.promise}onEvent(e){return this.eventHandlers.add(e),()=>{this.eventHandlers.delete(e)}}attachListener(){this.listening||(window.addEventListener("message",this.onWindowMessage),this.listening=!0)}detachListener(){this.listening&&(window.removeEventListener("message",this.onWindowMessage),this.listening=!1)}post(e){try{if(!this.popup||this.popup.closed)return;this.popup.postMessage(e,this.origin)}catch(e){}}onWindowMessage(e){if(e.origin!==this.origin)return;const t=e.data;if(t&&"object"==typeof t){if("event"===t.kind){for(const e of this.eventHandlers)"txInitiated"===t.event.type&&this.pollingManager.add(g.EVENT_TYPES.TRACK_TX_STATUS,{txId:t.event.txId,status:"initiated"}),e(t);return}if("internal_event"===t.kind)return void this.pollingManager.add(t.event.type,{wop:"wopwop"});if("auth-flow"===t.kind&&(this.session.setBearerToken(t.token,t.expireAt),this.session.setAccounts(t.accounts),this.session.setInstruments(t.instruments),this.session.save(),this.scheduleDisconnect(t.expireAt)),"handshake-ack"===t.kind&&t.ok)return void this.handleHandshakeAck();"response"===t.kind&&this.handleResponse(t)}}handleHandshakeAck(){this.walletReady=!0,this.clearHandshakeLoop(),this.initDeferred&&(this.initDeferred.resolve(),this.initDeferred=void 0)}handleResponse(e){const t=this.pending.get(e.id);if(t)if(this.pending.delete(e.id),e.error){const s=new Error(e.error.message||"Unknown Error");Object.assign(s,{code:e.error.code,data:e.error.data}),t.reject(s)}else t.resolve(e.result)}startHandshakeLoop(){this.handshakeDeadline=Date.now()+55e3;const e=()=>{if(!this.walletReady)return!this.popup||this.popup.closed?(this.clearHandshakeLoop(),void this.rejectInit(new Error("Popup closed before handshake"))):this.handshakeDeadline&&Date.now()>this.handshakeDeadline?(this.clearHandshakeLoop(),void this.rejectInit(new Error("Handshake timed out"))):void this.post({kind:"handshake",sdkVersion:"0.0.0",sessionId:this.sessionId,dapp:{name:this.appName,url:this.appUrl}});this.clearHandshakeLoop()};e(),this.handshakeTimer=window.setInterval(e,300)}clearHandshakeLoop(){null!=this.handshakeTimer&&(clearInterval(this.handshakeTimer),this.handshakeTimer=void 0),this.handshakeDeadline=void 0}rejectInit(e){this.initDeferred&&(Object.assign(e,{code:"INITIALIZATION_FAILED",message:e.message}),this.initDeferred.reject(e),this.initDeferred=void 0)}startPopupClosedWatcher(){const e=this.popup;if(!e)return;const t=window.setInterval(()=>{(!e||e.closed)&&(clearInterval(t),this.destroy())},300);this.closeWatcherTimer=t}}var E=Object.defineProperty,k=(e,t,s)=>((e,t,s)=>t in e?E(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);const S={uuid:"c8-wallet-connect",name:"C8 Wallet",icon:"",rdns:"tech.cantor8.wallet"},A="c8#provider_discovery";exports.C8WalletProvider=class{constructor(t){var n,i,r;k(this,"transport"),k(this,"listeners",{});const a=null!=(n=t.dappName)?n:document.title||"Unknown dApp",o=null!=(i=t.dappUrl)?i:location.origin,h=null!=(r=t.network)?r:"mainnet";let d;switch(h){case"devnet":d=e;break;case"mainnet":d=s;break;default:throw new Error("Unsupported network: "+h)}this.transport=new y(a,o,d),this.transport.onEvent(e=>{"event"===e.kind&&this.emit(e.event.type,e.event)})}async connect(){await this.transport.request("connect",void 0,!0)}async disconnect(){try{await this.transport.request("disconnect"),this.transport.destroy()}catch(e){}}status(){return this.transport.request("status")}getInstruments(){return this.transport.request("getInstruments")}getAccounts(e){return this.transport.request("getAccounts",{instrumentId:e})}send(e){return this.transport.request("send",e,!0)}createSwapOffer(e){return this.transport.request("createSwapOffer",e,!0)}signAndExecute(e){return this.transport.request("signAndExecute",e,!0)}signAndExecutePreparedTransfer(e){return this.transport.request("signAndExecutePreparedTransfer",e,!0)}acknowledge(e){return this.transport.request("acknowledge",e,!0)}checkTxStatusById(e){return this.transport.request("checkTxStatusById",e)}on(e,t){return this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(t),()=>this.listeners[e].delete(t)}emit(e,t){var s;for(const n of null!=(s=this.listeners[e])?s:[])n(t)}},exports.HttpClient=f,exports.LocalStorageHelper=n,exports.announceC8Provider=function(e){const t={info:S,provider:e()};window.dispatchEvent(new CustomEvent(A,{detail:t}))},exports.onC8ProviderDiscovered=function(e){const t=t=>{const s=t;s.detail&&e(s.detail.info,s.detail.provider)};return window.addEventListener(A,t),()=>window.removeEventListener(A,t)};
package/dist/index.esm.js CHANGED
@@ -1 +1 @@
1
- const e="https://wallet.dev.digik.cantor8.tech",t="https://wallet-backend.dev.digik.cantor8.tech";class s{static getItem(e){try{const t=localStorage.getItem(e);return t?JSON.parse(t):null}catch(e){return null}}static setItem(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(e){}}static removeItem(e){try{localStorage.removeItem(e)}catch(e){}}}const n={TestCoin1:"TestCoin1",Amulet:"Canton Coin",CBTC:"CBTC",USDCx:"USDCx",CETH:"CETH"},i=e=>{var t;return"Amulet"===e?"Canton Coin":null!=(t=n[null!=e?e:""])?t:e},r={TestCoin1:"TestCoin1",Amulet:"CC",CBTC:"CBTC",USDCx:"USDCx"},a=e=>{var t;return"Amulet"===e?"CC":null!=(t=r[null!=e?e:""])?t:e};var o=Object.defineProperty,h=(e,t,s)=>((e,t,s)=>t in e?o(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);const d=class e{constructor(){h(this,"appName"),h(this,"accounts",[]),h(this,"instruments",[]),h(this,"partyIds",[]),h(this,"authToken",null),h(this,"isConnected",!1),h(this,"expireAt",null),h(this,"disconnectTimeoutId",null),this.load()}static getInstance(){return e.instance||(e.instance=new e),e.instance}setAppName(e){this.appName=e}getAppName(){return this.appName}setInstruments(e){this.instruments=e}getInstruments(){return this.instruments}setAccounts(e){this.accounts=e,this.partyIds=e.map(e=>e.partyId),this.instruments=e.flatMap(e=>e.holdings.map(e=>({instrumentId:e.instrumentId,name:i(e.instrumentId),symbol:a(e.instrumentId)})))}getAccounts(){return this.accounts}setBearerToken(e,t){this.authToken=e,this.isConnected=!0,this.expireAt=t}getExpireAt(){return this.expireAt}setDisconnectTimeoutId(e){this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),this.disconnectTimeoutId=e}getDisconnectTimeoutId(){return this.disconnectTimeoutId}getBearerToken(){return this.authToken}clear(){this.accounts=[],this.instruments=[],this.authToken=null,this.partyIds=[],this.isConnected=!1,this.expireAt=null,this.disconnectTimeoutId&&(clearTimeout(this.disconnectTimeoutId),this.disconnectTimeoutId=null),s.removeItem(e.SESSION_KEY)}save(){s.setItem(e.SESSION_KEY,{authToken:this.authToken,partyIds:this.partyIds,expireAt:this.expireAt})}setConnected(e){this.isConnected=e}getConnected(){return this.isConnected}hasStoredSession(){return!!s.getItem(e.SESSION_KEY)}load(){const t=s.getItem(e.SESSION_KEY);t&&(this.authToken=t.authToken,this.partyIds=t.partyIds||[],this.expireAt=t.expireAt||null)}};h(d,"instance"),h(d,"SESSION_KEY","c8-session");let c=d;var l=Object.defineProperty,u=(e,t,s)=>((e,t,s)=>t in e?l(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);const p=class e{constructor(e=5e3){this.pollingInterval=e,u(this,"events",new Map),u(this,"intervals",new Map),u(this,"handlerRegistry",new Map),this.restore()}static getInstance(t=5e3){return e.instance||(e.instance=new e(t)),e.instance}registerHandler(e,t){this.handlerRegistry.set(e,t),this.events.forEach((s,n)=>{s.event.type===e&&(this.stopPolling(n),s.handler=t,this.startPolling(n))})}add(e,t){const s=btoa(`${e}-${JSON.stringify(t)}`);this.events.has(s)&&this.remove(s);const n=this.handlerRegistry.get(e);if(!n)return;const i={key:s,type:e,params:t,createdAt:Date.now()};this.events.set(s,{event:i,handler:n}),this.persist(),this.startPolling(s)}remove(e){this.stopPolling(e),this.events.delete(e),this.persist()}startPolling(t){const s=this.events.get(t);if(!s)return;const{event:n,handler:i}=s,r=async()=>{try{if(n.createdAt&&Date.now()-n.createdAt>e.POLLING_TIMEOUT)return void this.remove(t);await i(n.params)&&this.remove(t)}catch(e){}};r();const a=window.setInterval(r,this.pollingInterval);this.intervals.set(t,a)}stopPolling(e){const t=this.intervals.get(e);void 0!==t&&(window.clearInterval(t),this.intervals.delete(e))}persist(){const t=Array.from(this.events.values()).map(e=>e.event);s.setItem(e.STORAGE_KEY,t)}restore(){const t=s.getItem(e.STORAGE_KEY);if(t&&Array.isArray(t)){const s=Date.now();t.forEach(t=>{if(t.createdAt&&s-t.createdAt>e.POLLING_TIMEOUT)return;const n=this.handlerRegistry.get(t.key);n?(this.events.set(t.key,{event:t,handler:n}),this.startPolling(t.key)):this.events.set(t.key,{event:t,handler:async()=>!1})})}}clear(){this.events.clear(),this.intervals.forEach(e=>window.clearInterval(e)),this.intervals.clear(),this.persist(),s.removeItem(e.STORAGE_KEY)}getEvents(){return Array.from(this.events.values()).map(e=>e.event)}};u(p,"EVENT_TYPES",{RESTORE_SESSION:"RESTORE_SESSION",TRACK_TX_STATUS:"TRACK_TX_STATUS",UPDATE_ACCOUNT:"UPDATE_ACCOUNT"}),u(p,"type"),u(p,"instance"),u(p,"STORAGE_KEY","c8-polling-events"),u(p,"POLLING_TIMEOUT",3e5);let m=p;var g=Object.defineProperty;class v{constructor(e){((e,t,s)=>{((e,t,s)=>{t in e?g(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s})(e,t+"",s)})(this,"baseUrl"),this.baseUrl=e.endsWith("/")?e.slice(0,-1):e}async request(e,t={}){const s=c.getInstance().getBearerToken(),n=c.getInstance().getAppName(),i=new Headers(t.headers);s&&(i.set("Authorization",`Bearer ${s}`),i.set("X-App-Name",null!=n?n:"Unknown App")),i.set("x-feat-decimals","1");const r=await fetch(`${this.baseUrl}${e}`,{...t,headers:i});if(!r.ok)throw new Error(`HTTP error! status: ${r.status}`);return await r.json()}async getBalance(){return this.request("/api/balance")}async getTransferStatus(e){return this.request(`/api/transfer/status?command_id=${e}`)}}var T=Object.defineProperty,I=(e,t,s)=>((e,t,s)=>t in e?T(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);function f(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}class w{constructor(s,n,i=e){let r;switch(this.appName=s,this.appUrl=n,this.origin=i,I(this,"WINDOW_NAME","c8-wallet"),I(this,"WINDOW_WIDTH",475),I(this,"WINDOW_HEIGHT",762),I(this,"popup"),I(this,"sessionId",crypto.randomUUID()),I(this,"listening",!1),I(this,"walletReady",!1),I(this,"pending",new Map),I(this,"eventHandlers",new Set),I(this,"handshakeTimer"),I(this,"handshakeDeadline"),I(this,"closeWatcherTimer"),I(this,"pollingManager",m.getInstance()),I(this,"session",c.getInstance()),I(this,"initDeferred"),I(this,"httpClient"),this.onWindowMessage=this.onWindowMessage.bind(this),this.handleRestoreSession=this.handleRestoreSession.bind(this),this.handleTrackTxStatus=this.handleTrackTxStatus.bind(this),this.handleAccountUpdate=this.handleAccountUpdate.bind(this),this.session.setAppName(this.appName),this.attachListener(),this.origin){case e:r=t;break;case"https://wallet.cantor8.tech":case"https://wallet.main.digik.cantor8.tech":r="https://wallet-backend.main.cantor8.tech";break;default:r=t}this.httpClient=new v(r),this.pollingManager.registerHandler(m.EVENT_TYPES.RESTORE_SESSION,this.handleRestoreSession),this.pollingManager.registerHandler(m.EVENT_TYPES.TRACK_TX_STATUS,this.handleTrackTxStatus),this.pollingManager.registerHandler(m.EVENT_TYPES.UPDATE_ACCOUNT,this.handleAccountUpdate),this.checkRestoreSession()}checkRestoreSession(){this.session.hasStoredSession()&&this.pollingManager.add(m.EVENT_TYPES.RESTORE_SESSION,{sessionId:this.sessionId})}async handleAccountUpdate(e){try{const e=await this.httpClient.getBalance();if(e&&e.holdings){const t=[{partyId:e.party_id,holdings:Object.entries(e.holdings).map(([e,t])=>({instrumentId:e,balance:Number(t.balance),balanceUsd:Number(t.balance_usd)}))}];this.session.setAccounts(t),this.session.save()}return!0}catch(e){e instanceof Error&&e.message.includes("401")&&this.destroy()}return!1}async getTransferStatusById(e){try{const t=await this.httpClient.getTransferStatus(e);let s;switch(t.status){case"success":s="confirmed";break;case"failed":s="failed";break;default:s="pending"}return t.status=s,t}catch(e){return e instanceof Error&&e.message.includes("401")&&this.destroy(),null}}async handleTrackTxStatus(e){try{const t=await this.httpClient.getTransferStatus(e.txId);if(e.status!==t.status){let s;switch(t.status){case"success":s="confirmed";break;case"failed":s="failed";break;default:s="pending"}return this.emitSyntheticEvent({type:"txChanged",txId:e.txId,status:s}),e.status=t.status,this.pollingManager.persist(),"pending"!==t.status&&this.pollingManager.add(m.EVENT_TYPES.UPDATE_ACCOUNT,{txId:e.txId}),"success"===t.status||"failed"===t.status}}catch(t){if(t instanceof Error&&(t.message.includes("401")&&this.destroy(),t.message.includes("404")))return this.emitSyntheticEvent({type:"txChanged",txId:e.txId,status:"failed"}),!0}return!1}async handleRestoreSession(e){try{const e=await this.httpClient.getBalance();if(e&&e.holdings){const t=[{partyId:e.party_id,holdings:Object.entries(e.holdings).map(([e,t])=>({instrumentId:e,balance:Number(t.balance),balanceUsd:Number(t.balance_usd)}))}];this.session.setAccounts(t),this.session.save(),this.session.setConnected(!0),this.emitSyntheticEvent({type:"connected"});const s=this.session.getExpireAt();return s&&this.scheduleDisconnect(s),!0}}catch(e){e instanceof Error&&e.message.includes("401")&&this.destroy()}return!1}get WALLET_EMBEDDED(){return`${this.origin}/embedded/`}async init(e){var t;if(void 0!==this.popup&&(null==(t=this.popup)||!t.closed))return;if(this.initDeferred||(this.initDeferred=f()),this.listening||this.attachListener(),this.popup&&!this.popup.closed)return this.popup.focus(),null==this.handshakeTimer&&this.startHandshakeLoop(),this.initDeferred.promise;const s=new URL(null!=e?e:"",this.WALLET_EMBEDDED);if(this.popup=window.open(s,this.WINDOW_NAME,`width=${this.WINDOW_WIDTH},height=${this.WINDOW_HEIGHT}`),!this.popup){const e=new Error("Failed to open popup window");Object.assign(e,{code:"POPUP_BLOCKED",message:"browser blocked the popup window"}),this.rejectInit(e)}return this.startHandshakeLoop(),this.initDeferred.promise}emitSyntheticEvent(e){for(const t of this.eventHandlers)try{t({kind:"event",event:e})}catch(e){}}scheduleDisconnect(e){if(!e)return;const t=e-Date.now();if(t>0){const e=setTimeout(()=>{this.destroy("authToken expired")},t);this.session.setDisconnectTimeoutId(e)}else this.destroy("authToken expired")}destroy(e="destroyed"){try{this.emitSyntheticEvent({type:"disconnected",reason:e}),this.detachListener(),this.clearHandshakeLoop(),this.initDeferred&&(this.initDeferred.reject(new Error("Transport destroyed")),this.initDeferred=void 0);for(const[,e]of this.pending)e.reject(new Error("Transport destroyed"));this.pending.clear(),this.popup&&!this.popup.closed&&this.popup.close(),this.popup=void 0,this.walletReady=!1,this.session.clear(),this.pollingManager.clear()}catch(e){}}async request(e,t,s){var n,i,r,a,o,h,d,c,l,u,p,m,g,v,T,I;const w=crypto.randomUUID(),E=f();this.pending.set(w,E);try{if("connect"===e){if(this.session.getBearerToken())return this.handleResponse({kind:"response",id:w,result:null}),E.promise;this.session.getBearerToken()||(this.walletReady=!1),await this.init()}if("send"===e&&(this.walletReady=!1,await this.init("confirmTransaction")),"signAndExecute"===e&&(this.walletReady=!1,await this.init("signAndExecute")),"status"===e)return this.handleResponse({kind:"response",id:w,result:{connected:this.session.getConnected(),walletVersion:void 0}}),E.promise;if(s&&(null==(n=this.popup)||n.focus()),"getInstruments"===e){const e=this.session.getInstruments();return this.handleResponse({kind:"response",id:w,result:{instruments:e}}),E.promise}if("getAccounts"===e){await this.handleAccountUpdate();const e=this.session.getAccounts();return this.handleResponse({kind:"response",id:w,result:{accounts:e}}),E.promise}if("checkTxStatusById"===e){const e=t,s=await this.getTransferStatusById(null==e?void 0:e.txId);if(s){const e={status:s.status,transfer:{senderPartyId:null!=(r=null==(i=s.transfer)?void 0:i.party_id)?r:"",receiverPartyId:null!=(o=null==(a=s.transfer)?void 0:a.party_id2)?o:"",amount:Number(null!=(d=null==(h=s.transfer)?void 0:h.amount)?d:"0"),networkFees:Number(null!=(l=null==(c=s.transfer)?void 0:c.network_fees)?l:"0"),instrumentId:null!=(p=null==(u=s.transfer)?void 0:u.instrument_id)?p:"",txId:null!=(g=null==(m=s.transfer)?void 0:m.command_id)?g:"",created_at:null!=(T=null==(v=s.transfer)?void 0:v.created_at)?T:"",memo:null==(I=s.transfer)?void 0:I.reason}};this.handleResponse({kind:"response",id:w,result:e})}else this.handleResponse({kind:"response",id:w,error:{code:"FAILED_TO_FETCH_TRANSFER_STATUS",message:"Failed to fetch transfer status"}});return E.promise}if("disconnect"===e)return this.handleResponse({kind:"response",id:w,result:null}),E.promise;const f={kind:"request",id:w,method:e,params:t,sessionId:this.sessionId};this.post(f)}catch(e){this.pending.delete(w),E.reject(e)}return E.promise}onEvent(e){return this.eventHandlers.add(e),()=>{this.eventHandlers.delete(e)}}attachListener(){this.listening||(window.addEventListener("message",this.onWindowMessage),this.listening=!0)}detachListener(){this.listening&&(window.removeEventListener("message",this.onWindowMessage),this.listening=!1)}post(e){try{if(!this.popup||this.popup.closed)return;this.popup.postMessage(e,this.origin)}catch(e){}}onWindowMessage(e){if(e.origin!==this.origin)return;const t=e.data;if(t&&"object"==typeof t){if("event"===t.kind){for(const e of this.eventHandlers)"txInitiated"===t.event.type&&this.pollingManager.add(m.EVENT_TYPES.TRACK_TX_STATUS,{txId:t.event.txId,status:"initiated"}),e(t);return}if("internal_event"===t.kind)return void this.pollingManager.add(t.event.type,{wop:"wopwop"});if("auth-flow"===t.kind&&(this.session.setBearerToken(t.token,t.expireAt),this.session.setAccounts(t.accounts),this.session.setInstruments(t.instruments),this.session.save(),this.scheduleDisconnect(t.expireAt)),"handshake-ack"===t.kind&&t.ok)return void this.handleHandshakeAck();"response"===t.kind&&this.handleResponse(t)}}handleHandshakeAck(){this.walletReady=!0,this.clearHandshakeLoop(),this.initDeferred&&(this.initDeferred.resolve(),this.initDeferred=void 0)}handleResponse(e){const t=this.pending.get(e.id);if(t)if(this.pending.delete(e.id),e.error){const s=new Error(e.error.message||"Unknown Error");Object.assign(s,{code:e.error.code,data:e.error.data}),t.reject(s)}else t.resolve(e.result)}startHandshakeLoop(){this.handshakeDeadline=Date.now()+55e3;const e=()=>{if(!this.walletReady)return!this.popup||this.popup.closed?(this.clearHandshakeLoop(),void this.rejectInit(new Error("Popup closed before handshake"))):this.handshakeDeadline&&Date.now()>this.handshakeDeadline?(this.clearHandshakeLoop(),void this.rejectInit(new Error("Handshake timed out"))):void this.post({kind:"handshake",sdkVersion:"0.0.0",sessionId:this.sessionId,dapp:{name:this.appName,url:this.appUrl}});this.clearHandshakeLoop()};e(),this.handshakeTimer=window.setInterval(e,300)}clearHandshakeLoop(){null!=this.handshakeTimer&&(clearInterval(this.handshakeTimer),this.handshakeTimer=void 0),this.handshakeDeadline=void 0}rejectInit(e){this.initDeferred&&(Object.assign(e,{code:"INITIALIZATION_FAILED",message:e.message}),this.initDeferred.reject(e),this.initDeferred=void 0)}startPopupClosedWatcher(){const e=this.popup;if(!e)return;const t=window.setInterval(()=>{(!e||e.closed)&&(clearInterval(t),this.destroy())},300);this.closeWatcherTimer=t}}var E=Object.defineProperty,y=(e,t,s)=>((e,t,s)=>t in e?E(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class k{constructor(t){var s,n,i;y(this,"transport"),y(this,"listeners",{});const r=null!=(s=t.dappName)?s:document.title||"Unknown dApp",a=null!=(n=t.dappUrl)?n:location.origin,o=null!=(i=t.network)?i:"mainnet";let h;if("devnet"!==o)throw new Error("Only devnet network is supported right now");if("devnet"!==o)throw new Error("Unsupported network: "+o);h=e,this.transport=new w(r,a,h),this.transport.onEvent(e=>{"event"===e.kind&&this.emit(e.event.type,e.event)})}async connect(){await this.transport.request("connect",void 0,!0)}async disconnect(){try{await this.transport.request("disconnect"),this.transport.destroy()}catch(e){}}status(){return this.transport.request("status")}getInstruments(){return this.transport.request("getInstruments")}getAccounts(e){return this.transport.request("getAccounts",{instrumentId:e})}send(e){return this.transport.request("send",e,!0)}signAndExecute(e){return this.transport.request("signAndExecute",e,!0)}signAndExecutePreparedTransfer(e){return this.transport.request("signAndExecutePreparedTransfer",e,!0)}acknowledge(e){return this.transport.request("acknowledge",e,!0)}checkTxStatusById(e){return this.transport.request("checkTxStatusById",e)}on(e,t){return this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(t),()=>this.listeners[e].delete(t)}emit(e,t){var s;for(const n of null!=(s=this.listeners[e])?s:[])n(t)}}const S={uuid:"c8-wallet-connect",name:"C8 Wallet",icon:"",rdns:"tech.cantor8.wallet"},A="c8#provider_discovery";function b(e){const t={info:S,provider:e()};window.dispatchEvent(new CustomEvent(A,{detail:t}))}function C(e){const t=t=>{const s=t;s.detail&&e(s.detail.info,s.detail.provider)};return window.addEventListener(A,t),()=>window.removeEventListener(A,t)}export{k as C8WalletProvider,v as HttpClient,s as LocalStorageHelper,b as announceC8Provider,C as onC8ProviderDiscovered};
1
+ const e="https://wallet.dev.digik.cantor8.tech",t="https://wallet-backend.dev.digik.cantor8.tech",s="https://wallet.cantor8.tech";class n{static getItem(e){try{const t=localStorage.getItem(e);return t?JSON.parse(t):null}catch(e){return null}}static setItem(e,t){try{localStorage.setItem(e,JSON.stringify(t))}catch(e){}}static removeItem(e){try{localStorage.removeItem(e)}catch(e){}}}const i={TestCoin1:"TestCoin1",Amulet:"Canton Coin",CBTC:"CBTC",USDCx:"USDCx",CETH:"CETH"},r=e=>{var t;return"Amulet"===e?"Canton Coin":null!=(t=i[null!=e?e:""])?t:e},a={TestCoin1:"TestCoin1",Amulet:"CC",CBTC:"CBTC",USDCx:"USDCx"},o=e=>{var t;return"Amulet"===e?"CC":null!=(t=a[null!=e?e:""])?t:e};var h=Object.defineProperty,d=(e,t,s)=>((e,t,s)=>t in e?h(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);const c=class e{constructor(){d(this,"appName"),d(this,"accounts",[]),d(this,"instruments",[]),d(this,"partyIds",[]),d(this,"authToken",null),d(this,"isConnected",!1),d(this,"expireAt",null),d(this,"disconnectTimeoutId",null),this.load()}static getInstance(){return e.instance||(e.instance=new e),e.instance}setAppName(e){this.appName=e}getAppName(){return this.appName}setInstruments(e){this.instruments=e}getInstruments(){return this.instruments}setAccounts(e){this.accounts=e,this.partyIds=e.map(e=>e.partyId),this.instruments=e.flatMap(e=>e.holdings.map(e=>({instrumentId:e.instrumentId,name:r(e.instrumentId),symbol:o(e.instrumentId)})))}getAccounts(){return this.accounts}setBearerToken(e,t){this.authToken=e,this.isConnected=!0,this.expireAt=t}getExpireAt(){return this.expireAt}setDisconnectTimeoutId(e){this.disconnectTimeoutId&&clearTimeout(this.disconnectTimeoutId),this.disconnectTimeoutId=e}getDisconnectTimeoutId(){return this.disconnectTimeoutId}getBearerToken(){return this.authToken}clear(){this.accounts=[],this.instruments=[],this.authToken=null,this.partyIds=[],this.isConnected=!1,this.expireAt=null,this.disconnectTimeoutId&&(clearTimeout(this.disconnectTimeoutId),this.disconnectTimeoutId=null),n.removeItem(e.SESSION_KEY)}save(){n.setItem(e.SESSION_KEY,{authToken:this.authToken,partyIds:this.partyIds,expireAt:this.expireAt})}setConnected(e){this.isConnected=e}getConnected(){return this.isConnected}hasStoredSession(){return!!n.getItem(e.SESSION_KEY)}load(){const t=n.getItem(e.SESSION_KEY);t&&(this.authToken=t.authToken,this.partyIds=t.partyIds||[],this.expireAt=t.expireAt||null)}};d(c,"instance"),d(c,"SESSION_KEY","c8-session");let l=c;var u=Object.defineProperty,p=(e,t,s)=>((e,t,s)=>t in e?u(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);const m=class e{constructor(e=5e3){this.pollingInterval=e,p(this,"events",new Map),p(this,"intervals",new Map),p(this,"handlerRegistry",new Map),this.restore()}static getInstance(t=5e3){return e.instance||(e.instance=new e(t)),e.instance}registerHandler(e,t){this.handlerRegistry.set(e,t),this.events.forEach((s,n)=>{s.event.type===e&&(this.stopPolling(n),s.handler=t,this.startPolling(n))})}add(e,t){const s=btoa(`${e}-${JSON.stringify(t)}`);this.events.has(s)&&this.remove(s);const n=this.handlerRegistry.get(e);if(!n)return;const i={key:s,type:e,params:t,createdAt:Date.now()};this.events.set(s,{event:i,handler:n}),this.persist(),this.startPolling(s)}remove(e){this.stopPolling(e),this.events.delete(e),this.persist()}startPolling(t){const s=this.events.get(t);if(!s)return;const{event:n,handler:i}=s,r=async()=>{try{if(n.createdAt&&Date.now()-n.createdAt>e.POLLING_TIMEOUT)return void this.remove(t);await i(n.params)&&this.remove(t)}catch(e){}};r();const a=window.setInterval(r,this.pollingInterval);this.intervals.set(t,a)}stopPolling(e){const t=this.intervals.get(e);void 0!==t&&(window.clearInterval(t),this.intervals.delete(e))}persist(){const t=Array.from(this.events.values()).map(e=>e.event);n.setItem(e.STORAGE_KEY,t)}restore(){const t=n.getItem(e.STORAGE_KEY);if(t&&Array.isArray(t)){const s=Date.now();t.forEach(t=>{if(t.createdAt&&s-t.createdAt>e.POLLING_TIMEOUT)return;const n=this.handlerRegistry.get(t.key);n?(this.events.set(t.key,{event:t,handler:n}),this.startPolling(t.key)):this.events.set(t.key,{event:t,handler:async()=>!1})})}}clear(){this.events.clear(),this.intervals.forEach(e=>window.clearInterval(e)),this.intervals.clear(),this.persist(),n.removeItem(e.STORAGE_KEY)}getEvents(){return Array.from(this.events.values()).map(e=>e.event)}};p(m,"EVENT_TYPES",{RESTORE_SESSION:"RESTORE_SESSION",TRACK_TX_STATUS:"TRACK_TX_STATUS",UPDATE_ACCOUNT:"UPDATE_ACCOUNT"}),p(m,"type"),p(m,"instance"),p(m,"STORAGE_KEY","c8-polling-events"),p(m,"POLLING_TIMEOUT",3e5);let g=m;var T=Object.defineProperty;class f{constructor(e){((e,t,s)=>{((e,t,s)=>{t in e?T(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s})(e,t+"",s)})(this,"baseUrl"),this.baseUrl=e.endsWith("/")?e.slice(0,-1):e}async request(e,t={}){const s=l.getInstance().getBearerToken(),n=l.getInstance().getAppName(),i=new Headers(t.headers);s&&(i.set("Authorization",`Bearer ${s}`),i.set("X-App-Name",null!=n?n:"Unknown App")),i.set("x-feat-decimals","1");const r=await fetch(`${this.baseUrl}${e}`,{...t,headers:i});if(!r.ok)throw new Error(`HTTP error! status: ${r.status}`);return await r.json()}async getBalance(){return this.request("/api/balance")}async getTransferStatus(e){return this.request(`/api/transfer/status?command_id=${e}`)}}var v=Object.defineProperty,I=(e,t,s)=>((e,t,s)=>t in e?v(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);function w(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}class y{constructor(n,i,r=e){let a;switch(this.appName=n,this.appUrl=i,this.origin=r,I(this,"WINDOW_NAME","c8-wallet"),I(this,"WINDOW_WIDTH",475),I(this,"WINDOW_HEIGHT",762),I(this,"popup"),I(this,"sessionId",crypto.randomUUID()),I(this,"listening",!1),I(this,"walletReady",!1),I(this,"pending",new Map),I(this,"eventHandlers",new Set),I(this,"handshakeTimer"),I(this,"handshakeDeadline"),I(this,"closeWatcherTimer"),I(this,"pollingManager",g.getInstance()),I(this,"session",l.getInstance()),I(this,"initDeferred"),I(this,"httpClient"),this.onWindowMessage=this.onWindowMessage.bind(this),this.handleRestoreSession=this.handleRestoreSession.bind(this),this.handleTrackTxStatus=this.handleTrackTxStatus.bind(this),this.handleAccountUpdate=this.handleAccountUpdate.bind(this),this.session.setAppName(this.appName),this.attachListener(),this.origin){case e:a=t;break;case s:case"https://wallet.main.digik.cantor8.tech":a="https://wallet-backend.main.cantor8.tech";break;default:a=t}this.httpClient=new f(a),this.pollingManager.registerHandler(g.EVENT_TYPES.RESTORE_SESSION,this.handleRestoreSession),this.pollingManager.registerHandler(g.EVENT_TYPES.TRACK_TX_STATUS,this.handleTrackTxStatus),this.pollingManager.registerHandler(g.EVENT_TYPES.UPDATE_ACCOUNT,this.handleAccountUpdate),this.checkRestoreSession()}checkRestoreSession(){this.session.hasStoredSession()&&this.pollingManager.add(g.EVENT_TYPES.RESTORE_SESSION,{sessionId:this.sessionId})}async handleAccountUpdate(e){try{const e=await this.httpClient.getBalance();if(e&&e.holdings){const t=[{partyId:e.party_id,holdings:Object.entries(e.holdings).map(([e,t])=>({instrumentId:e,balance:Number(t.balance),balanceUsd:Number(t.balance_usd)}))}];this.session.setAccounts(t),this.session.save()}return!0}catch(e){e instanceof Error&&e.message.includes("401")&&this.destroy()}return!1}async getTransferStatusById(e){try{const t=await this.httpClient.getTransferStatus(e);let s;switch(t.status){case"success":s="confirmed";break;case"failed":s="failed";break;default:s="pending"}return t.status=s,t}catch(e){return e instanceof Error&&e.message.includes("401")&&this.destroy(),null}}async handleTrackTxStatus(e){try{const t=await this.httpClient.getTransferStatus(e.txId);if(e.status!==t.status){let s;switch(t.status){case"success":s="confirmed";break;case"failed":s="failed";break;default:s="pending"}return this.emitSyntheticEvent({type:"txChanged",txId:e.txId,status:s}),e.status=t.status,this.pollingManager.persist(),"pending"!==t.status&&this.pollingManager.add(g.EVENT_TYPES.UPDATE_ACCOUNT,{txId:e.txId}),"success"===t.status||"failed"===t.status}}catch(t){if(t instanceof Error&&(t.message.includes("401")&&this.destroy(),t.message.includes("404")))return this.emitSyntheticEvent({type:"txChanged",txId:e.txId,status:"failed"}),!0}return!1}async handleRestoreSession(e){try{const e=await this.httpClient.getBalance();if(e&&e.holdings){const t=[{partyId:e.party_id,holdings:Object.entries(e.holdings).map(([e,t])=>({instrumentId:e,balance:Number(t.balance),balanceUsd:Number(t.balance_usd)}))}];this.session.setAccounts(t),this.session.save(),this.session.setConnected(!0),this.emitSyntheticEvent({type:"connected"});const s=this.session.getExpireAt();return s&&this.scheduleDisconnect(s),!0}}catch(e){e instanceof Error&&e.message.includes("401")&&this.destroy()}return!1}get WALLET_EMBEDDED(){return`${this.origin}/embedded/`}async init(e){var t;if(void 0!==this.popup&&(null==(t=this.popup)||!t.closed))return;if(this.initDeferred||(this.initDeferred=w()),this.listening||this.attachListener(),this.popup&&!this.popup.closed)return this.popup.focus(),null==this.handshakeTimer&&this.startHandshakeLoop(),this.initDeferred.promise;const s=new URL(null!=e?e:"",this.WALLET_EMBEDDED);if(this.popup=window.open(s,this.WINDOW_NAME,`width=${this.WINDOW_WIDTH},height=${this.WINDOW_HEIGHT}`),!this.popup){const e=new Error("Failed to open popup window");Object.assign(e,{code:"POPUP_BLOCKED",message:"browser blocked the popup window"}),this.rejectInit(e)}return this.startHandshakeLoop(),this.initDeferred.promise}emitSyntheticEvent(e){for(const t of this.eventHandlers)try{t({kind:"event",event:e})}catch(e){}}scheduleDisconnect(e){if(!e)return;const t=e-Date.now();if(t>0){const e=setTimeout(()=>{this.destroy("authToken expired")},t);this.session.setDisconnectTimeoutId(e)}else this.destroy("authToken expired")}destroy(e="destroyed"){try{this.emitSyntheticEvent({type:"disconnected",reason:e}),this.detachListener(),this.clearHandshakeLoop(),this.initDeferred&&(this.initDeferred.reject(new Error("Transport destroyed")),this.initDeferred=void 0);for(const[,e]of this.pending)e.reject(new Error("Transport destroyed"));this.pending.clear(),this.popup&&!this.popup.closed&&this.popup.close(),this.popup=void 0,this.walletReady=!1,this.session.clear(),this.pollingManager.clear()}catch(e){}}async request(e,t,s){var n,i,r,a,o,h,d,c,l,u,p,m,g,T,f,v;const I=crypto.randomUUID(),y=w();this.pending.set(I,y);try{if("connect"===e){if(this.session.getBearerToken())return this.handleResponse({kind:"response",id:I,result:null}),y.promise;this.session.getBearerToken()||(this.walletReady=!1),await this.init()}if("send"===e&&(this.walletReady=!1,await this.init("confirmTransaction")),"createSwapOffer"===e&&(this.walletReady=!1,await this.init("confirmSwapOffer")),"signAndExecute"===e&&(this.walletReady=!1,await this.init("signAndExecute")),"status"===e)return this.handleResponse({kind:"response",id:I,result:{connected:this.session.getConnected(),walletVersion:void 0}}),y.promise;if(s&&(null==(n=this.popup)||n.focus()),"getInstruments"===e){const e=this.session.getInstruments();return this.handleResponse({kind:"response",id:I,result:{instruments:e}}),y.promise}if("getAccounts"===e){await this.handleAccountUpdate();const e=this.session.getAccounts();return this.handleResponse({kind:"response",id:I,result:{accounts:e}}),y.promise}if("checkTxStatusById"===e){const e=t,s=await this.getTransferStatusById(null==e?void 0:e.txId);if(s){const e={status:s.status,transfer:{senderPartyId:null!=(r=null==(i=s.transfer)?void 0:i.party_id)?r:"",receiverPartyId:null!=(o=null==(a=s.transfer)?void 0:a.party_id2)?o:"",amount:Number(null!=(d=null==(h=s.transfer)?void 0:h.amount)?d:"0"),networkFees:Number(null!=(l=null==(c=s.transfer)?void 0:c.network_fees)?l:"0"),instrumentId:null!=(p=null==(u=s.transfer)?void 0:u.instrument_id)?p:"",txId:null!=(g=null==(m=s.transfer)?void 0:m.command_id)?g:"",created_at:null!=(f=null==(T=s.transfer)?void 0:T.created_at)?f:"",memo:null==(v=s.transfer)?void 0:v.reason}};this.handleResponse({kind:"response",id:I,result:e})}else this.handleResponse({kind:"response",id:I,error:{code:"FAILED_TO_FETCH_TRANSFER_STATUS",message:"Failed to fetch transfer status"}});return y.promise}if("disconnect"===e)return this.handleResponse({kind:"response",id:I,result:null}),y.promise;const w={kind:"request",id:I,method:e,params:t,sessionId:this.sessionId};this.post(w)}catch(e){this.pending.delete(I),y.reject(e)}return y.promise}onEvent(e){return this.eventHandlers.add(e),()=>{this.eventHandlers.delete(e)}}attachListener(){this.listening||(window.addEventListener("message",this.onWindowMessage),this.listening=!0)}detachListener(){this.listening&&(window.removeEventListener("message",this.onWindowMessage),this.listening=!1)}post(e){try{if(!this.popup||this.popup.closed)return;this.popup.postMessage(e,this.origin)}catch(e){}}onWindowMessage(e){if(e.origin!==this.origin)return;const t=e.data;if(t&&"object"==typeof t){if("event"===t.kind){for(const e of this.eventHandlers)"txInitiated"===t.event.type&&this.pollingManager.add(g.EVENT_TYPES.TRACK_TX_STATUS,{txId:t.event.txId,status:"initiated"}),e(t);return}if("internal_event"===t.kind)return void this.pollingManager.add(t.event.type,{wop:"wopwop"});if("auth-flow"===t.kind&&(this.session.setBearerToken(t.token,t.expireAt),this.session.setAccounts(t.accounts),this.session.setInstruments(t.instruments),this.session.save(),this.scheduleDisconnect(t.expireAt)),"handshake-ack"===t.kind&&t.ok)return void this.handleHandshakeAck();"response"===t.kind&&this.handleResponse(t)}}handleHandshakeAck(){this.walletReady=!0,this.clearHandshakeLoop(),this.initDeferred&&(this.initDeferred.resolve(),this.initDeferred=void 0)}handleResponse(e){const t=this.pending.get(e.id);if(t)if(this.pending.delete(e.id),e.error){const s=new Error(e.error.message||"Unknown Error");Object.assign(s,{code:e.error.code,data:e.error.data}),t.reject(s)}else t.resolve(e.result)}startHandshakeLoop(){this.handshakeDeadline=Date.now()+55e3;const e=()=>{if(!this.walletReady)return!this.popup||this.popup.closed?(this.clearHandshakeLoop(),void this.rejectInit(new Error("Popup closed before handshake"))):this.handshakeDeadline&&Date.now()>this.handshakeDeadline?(this.clearHandshakeLoop(),void this.rejectInit(new Error("Handshake timed out"))):void this.post({kind:"handshake",sdkVersion:"0.0.0",sessionId:this.sessionId,dapp:{name:this.appName,url:this.appUrl}});this.clearHandshakeLoop()};e(),this.handshakeTimer=window.setInterval(e,300)}clearHandshakeLoop(){null!=this.handshakeTimer&&(clearInterval(this.handshakeTimer),this.handshakeTimer=void 0),this.handshakeDeadline=void 0}rejectInit(e){this.initDeferred&&(Object.assign(e,{code:"INITIALIZATION_FAILED",message:e.message}),this.initDeferred.reject(e),this.initDeferred=void 0)}startPopupClosedWatcher(){const e=this.popup;if(!e)return;const t=window.setInterval(()=>{(!e||e.closed)&&(clearInterval(t),this.destroy())},300);this.closeWatcherTimer=t}}var E=Object.defineProperty,k=(e,t,s)=>((e,t,s)=>t in e?E(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);class S{constructor(t){var n,i,r;k(this,"transport"),k(this,"listeners",{});const a=null!=(n=t.dappName)?n:document.title||"Unknown dApp",o=null!=(i=t.dappUrl)?i:location.origin,h=null!=(r=t.network)?r:"mainnet";let d;switch(h){case"devnet":d=e;break;case"mainnet":d=s;break;default:throw new Error("Unsupported network: "+h)}this.transport=new y(a,o,d),this.transport.onEvent(e=>{"event"===e.kind&&this.emit(e.event.type,e.event)})}async connect(){await this.transport.request("connect",void 0,!0)}async disconnect(){try{await this.transport.request("disconnect"),this.transport.destroy()}catch(e){}}status(){return this.transport.request("status")}getInstruments(){return this.transport.request("getInstruments")}getAccounts(e){return this.transport.request("getAccounts",{instrumentId:e})}send(e){return this.transport.request("send",e,!0)}createSwapOffer(e){return this.transport.request("createSwapOffer",e,!0)}signAndExecute(e){return this.transport.request("signAndExecute",e,!0)}signAndExecutePreparedTransfer(e){return this.transport.request("signAndExecutePreparedTransfer",e,!0)}acknowledge(e){return this.transport.request("acknowledge",e,!0)}checkTxStatusById(e){return this.transport.request("checkTxStatusById",e)}on(e,t){return this.listeners[e]||(this.listeners[e]=new Set),this.listeners[e].add(t),()=>this.listeners[e].delete(t)}emit(e,t){var s;for(const n of null!=(s=this.listeners[e])?s:[])n(t)}}const A={uuid:"c8-wallet-connect",name:"C8 Wallet",icon:"",rdns:"tech.cantor8.wallet"},b="c8#provider_discovery";function C(e){const t={info:A,provider:e()};window.dispatchEvent(new CustomEvent(b,{detail:t}))}function _(e){const t=t=>{const s=t;s.detail&&e(s.detail.info,s.detail.provider)};return window.addEventListener(b,t),()=>window.removeEventListener(b,t)}export{S as C8WalletProvider,f as HttpClient,n as LocalStorageHelper,C as announceC8Provider,_ as onC8ProviderDiscovered};
@@ -5,7 +5,7 @@ export declare class C8WalletProvider {
5
5
  constructor(opts: {
6
6
  dappName: string;
7
7
  dappUrl?: string;
8
- network?: "devnet" | "mainnet" | "local";
8
+ network?: "devnet" | "mainnet";
9
9
  });
10
10
  connect(): Promise<void>;
11
11
  disconnect(): Promise<void>;
@@ -23,6 +23,20 @@ export declare class C8WalletProvider {
23
23
  memo?: string;
24
24
  metadata?: Record<string, string>;
25
25
  }): Promise<import("./types").SubmitTransferResultPayload>;
26
+ createSwapOffer(input: {
27
+ partyId: string;
28
+ swapId: string;
29
+ acceptorPartyId: string;
30
+ instrumentOutId: string;
31
+ instrumentOutAdmin: string;
32
+ amountOut: string;
33
+ instrumentInId: string;
34
+ instrumentInAdmin: string;
35
+ amountIn: string;
36
+ settleBefore: string;
37
+ metaJson?: string;
38
+ commandId?: string;
39
+ }): Promise<import("./types").SubmitTransferResultPayload>;
26
40
  signAndExecute(input: {
27
41
  note: string;
28
42
  partyId: string;
package/dist/types.d.ts CHANGED
@@ -80,7 +80,7 @@ export type InboundMessage = {
80
80
  payload: any;
81
81
  };
82
82
  };
83
- export type WalletMethod = "connect" | "disconnect" | "status" | "getInstruments" | "getAccounts" | "send" | "signAndExecute" | "signAndExecutePreparedTransfer" | "acknowledge" | "checkTxStatusById";
83
+ export type WalletMethod = "connect" | "disconnect" | "status" | "getInstruments" | "getAccounts" | "send" | "signAndExecute" | "signAndExecutePreparedTransfer" | "acknowledge" | "checkTxStatusById" | "createSwapOffer";
84
84
  export interface WalletRequestPayloadMap {
85
85
  connect: undefined;
86
86
  disconnect: undefined;
@@ -102,7 +102,7 @@ export interface WalletRequestPayloadMap {
102
102
  partyId: string;
103
103
  commandId: string;
104
104
  commandsJson: string;
105
- disclosedContracts: string;
105
+ disclosedContracts?: string;
106
106
  };
107
107
  signAndExecutePreparedTransfer: {
108
108
  partyId: string;
@@ -120,6 +120,20 @@ export interface WalletRequestPayloadMap {
120
120
  checkTxStatusById: {
121
121
  txId: string;
122
122
  };
123
+ createSwapOffer: {
124
+ partyId: string;
125
+ swapId: string;
126
+ acceptorPartyId: string;
127
+ instrumentOutId: string;
128
+ instrumentOutAdmin: string;
129
+ amountOut: string;
130
+ instrumentInId: string;
131
+ instrumentInAdmin: string;
132
+ amountIn: string;
133
+ settleBefore: string;
134
+ metaJson?: string;
135
+ commandId?: string;
136
+ };
123
137
  }
124
138
  export type WalletRequestPayload<M extends WalletMethod> = WalletRequestPayloadMap[M];
125
139
  export interface TransferTransactionPayload {
@@ -201,6 +215,7 @@ export interface WalletResponsePayloadMap {
201
215
  success: boolean;
202
216
  };
203
217
  checkTxStatusById: TransferStatusResponsePayload;
218
+ createSwapOffer: SubmitTransferResultPayload;
204
219
  }
205
220
  export type WalletResponsePayload<M extends WalletMethod> = WalletResponsePayloadMap[M];
206
221
  export type PollingHandler = (params: any) => Promise<boolean>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cantor8/wallet-connect-sdk",
3
- "version": "0.3.0-alpha.2",
3
+ "version": "0.4.0",
4
4
  "description": "C8 Wallet Connect SDK for dApp developers: postMessage API to interact with C8 Wallet.",
5
5
  "author": "C8 / Cantor8",
6
6
  "license": "MIT",