@cantor8/wallet-connect-sdk 0.3.0 → 0.5.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 +102 -0
- package/dist/index.cjs +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/provider.d.ts +8 -2
- package/dist/session.d.ts +0 -1
- package/dist/transports/constants.d.ts +1 -0
- package/dist/types.d.ts +45 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -75,6 +75,48 @@ const res = await c8.send({
|
|
|
75
75
|
});
|
|
76
76
|
|
|
77
77
|
console.log("Send result", res); // { txId }
|
|
78
|
+
|
|
79
|
+
// Create a swap offer
|
|
80
|
+
const swapRes = await c8.createSwapOffer({
|
|
81
|
+
partyId: senderPartyId,
|
|
82
|
+
commandId: "command-" + Date.now(), // optional
|
|
83
|
+
swap: {
|
|
84
|
+
swapId: "swap-" + Date.now(),
|
|
85
|
+
acceptorPartyId: "Party::Acceptor",
|
|
86
|
+
creatorLegs: [
|
|
87
|
+
{
|
|
88
|
+
receiver: "Party::Acceptor",
|
|
89
|
+
instrument: {
|
|
90
|
+
admin: "Admin::Out",
|
|
91
|
+
id: senderHoldingInstrumentId,
|
|
92
|
+
},
|
|
93
|
+
amount: "1.0",
|
|
94
|
+
legId: "creator-leg-1",
|
|
95
|
+
reason: "Swap offer", // optional
|
|
96
|
+
},
|
|
97
|
+
],
|
|
98
|
+
acceptorLegs: [
|
|
99
|
+
{
|
|
100
|
+
receiver: senderPartyId,
|
|
101
|
+
instrument: {
|
|
102
|
+
admin: "Admin::In",
|
|
103
|
+
id: "Inst::In",
|
|
104
|
+
},
|
|
105
|
+
amount: "2.0",
|
|
106
|
+
legId: "acceptor-leg-1",
|
|
107
|
+
},
|
|
108
|
+
],
|
|
109
|
+
creatorTransferLegs: [],
|
|
110
|
+
settleBefore: new Date(Date.now() + 3600 * 1000).toISOString(),
|
|
111
|
+
meta: {},
|
|
112
|
+
},
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
console.log("Swap offer result", swapRes); // { txId }
|
|
116
|
+
|
|
117
|
+
// Sign an arbitrary string, optionally for a specific party
|
|
118
|
+
const signature = await c8.signMessage("Message to sign", senderPartyId);
|
|
119
|
+
console.log("Signature", signature);
|
|
78
120
|
```
|
|
79
121
|
|
|
80
122
|
## API Reference
|
|
@@ -89,6 +131,8 @@ console.log("Send result", res); // { txId }
|
|
|
89
131
|
| `getInstruments()` | None | `Promise<InstrumentListPayload>` |
|
|
90
132
|
| `getAccounts()` | `instrumentId?: string` | `Promise<AccountListPayload>` |
|
|
91
133
|
| `send()` | `input: SendInput` | `Promise<SubmitTransferResultPayload>` |
|
|
134
|
+
| `createSwapOffer()` | `input: { partyId, swap, commandId? }` | `Promise<SubmitTransferResultPayload>` |
|
|
135
|
+
| `signMessage()` | `message: string, partyId?: string` | `Promise<string>` |
|
|
92
136
|
| `signAndExecute()` | `input: SignAndExecuteInput` | `Promise<void>` |
|
|
93
137
|
| `checkTxStatusById()` | `input: { txId: string }` | `Promise<TransferStatusResponsePayload>` |
|
|
94
138
|
| `on()` | `event: T, cb: Listener<C8EventByType<T>>` | `() => boolean` |
|
|
@@ -106,6 +150,56 @@ console.log("Send result", res); // { txId }
|
|
|
106
150
|
}
|
|
107
151
|
```
|
|
108
152
|
|
|
153
|
+
### `createSwapOffer()` Input
|
|
154
|
+
|
|
155
|
+
```ts
|
|
156
|
+
{
|
|
157
|
+
partyId: string;
|
|
158
|
+
commandId?: string;
|
|
159
|
+
swap: {
|
|
160
|
+
swapId: string;
|
|
161
|
+
acceptorPartyId: string;
|
|
162
|
+
creatorLegs: Array<{
|
|
163
|
+
receiver: string;
|
|
164
|
+
instrument: {
|
|
165
|
+
admin: string;
|
|
166
|
+
id: string;
|
|
167
|
+
};
|
|
168
|
+
amount: string;
|
|
169
|
+
legId: string;
|
|
170
|
+
reason?: string;
|
|
171
|
+
}>;
|
|
172
|
+
acceptorLegs: Array<{
|
|
173
|
+
receiver: string;
|
|
174
|
+
instrument: {
|
|
175
|
+
admin: string;
|
|
176
|
+
id: string;
|
|
177
|
+
};
|
|
178
|
+
amount: string;
|
|
179
|
+
legId: string;
|
|
180
|
+
reason?: string;
|
|
181
|
+
}>;
|
|
182
|
+
creatorTransferLegs: Array<{
|
|
183
|
+
receiver: string;
|
|
184
|
+
instrument: {
|
|
185
|
+
admin: string;
|
|
186
|
+
id: string;
|
|
187
|
+
};
|
|
188
|
+
amount: string;
|
|
189
|
+
legId: string;
|
|
190
|
+
reason?: string;
|
|
191
|
+
}>;
|
|
192
|
+
settleBefore: string;
|
|
193
|
+
meta: Record<string, string>;
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
`partyId` identifies the party creating the offer. `acceptorPartyId` identifies
|
|
199
|
+
the party allowed to accept it. Amounts are decimal strings, and
|
|
200
|
+
`settleBefore` is an ISO 8601 timestamp. The method resolves to `{ txId }` after
|
|
201
|
+
the wallet submits the offer.
|
|
202
|
+
|
|
109
203
|
### `signAndExecute()` Input
|
|
110
204
|
|
|
111
205
|
```ts
|
|
@@ -118,6 +212,14 @@ console.log("Send result", res); // { txId }
|
|
|
118
212
|
}
|
|
119
213
|
```
|
|
120
214
|
|
|
215
|
+
### `signMessage()`
|
|
216
|
+
|
|
217
|
+
Signs an arbitrary string and returns its signature. The party ID is optional:
|
|
218
|
+
|
|
219
|
+
```ts
|
|
220
|
+
const signature = await c8.signMessage("Message to sign", partyId);
|
|
221
|
+
```
|
|
222
|
+
|
|
121
223
|
## Events Reference
|
|
122
224
|
|
|
123
225
|
Use `c8.on(eventType, callback)` to listen for changes emitted by the wallet.
|
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",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 v{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 I=Object.defineProperty,f=(e,t,s)=>((e,t,s)=>t in e?I(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 E{constructor(n,i,r=e){let a;switch(this.appName=n,this.appUrl=i,this.origin=r,f(this,"WINDOW_NAME","c8-wallet"),f(this,"WINDOW_WIDTH",475),f(this,"WINDOW_HEIGHT",762),f(this,"popup"),f(this,"sessionId",crypto.randomUUID()),f(this,"listening",!1),f(this,"walletReady",!1),f(this,"pending",new Map),f(this,"eventHandlers",new Set),f(this,"handshakeTimer"),f(this,"handshakeDeadline"),f(this,"closeWatcherTimer"),f(this,"pollingManager",g.getInstance()),f(this,"session",l.getInstance()),f(this,"initDeferred"),f(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 v(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,v,I;const f=crypto.randomUUID(),E=w();this.pending.set(f,E);try{if("connect"===e){if(this.session.getBearerToken())return this.handleResponse({kind:"response",id:f,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:f,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:f,result:{instruments:e}}),E.promise}if("getAccounts"===e){await this.handleAccountUpdate();const e=this.session.getAccounts();return this.handleResponse({kind:"response",id:f,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!=(v=null==(T=s.transfer)?void 0:T.created_at)?v:"",memo:null==(I=s.transfer)?void 0:I.reason}};this.handleResponse({kind:"response",id:f,result:e})}else this.handleResponse({kind:"response",id:f,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:f,result:null}),E.promise;const w={kind:"request",id:f,method:e,params:t,sessionId:this.sessionId};this.post(w)}catch(e){this.pending.delete(f),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(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 y=Object.defineProperty,k=(e,t,s)=>((e,t,s)=>t in e?y(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 E(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)}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=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)};
|
|
1
|
+
"use strict";const e="cantor8.tech",t="https://wallet.dev.digik.cantor8.tech",s="https://wallet-backend.dev.digik.cantor8.tech",n="https://wallet.cantor8.tech",i="https://wallet.main.digik.cantor8.tech";class r{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 a={TestCoin1:"TestCoin1",Amulet:"Canton Coin",CBTC:"CBTC",USDCx:"USDCx",CETH:"CETH"},o=e=>{var t;return"Amulet"===e?"Canton Coin":null!=(t=a[null!=e?e:""])?t:e},h={TestCoin1:"TestCoin1",Amulet:"CC",CBTC:"CBTC",USDCx:"USDCx"},d=e=>{var t;return"Amulet"===e?"CC":null!=(t=h[null!=e?e:""])?t:e};var c=Object.defineProperty,l=(e,t,s)=>((e,t,s)=>t in e?c(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);const u=class e{constructor(){l(this,"appName"),l(this,"accounts",[]),l(this,"instruments",[]),l(this,"authToken",null),l(this,"isConnected",!1),l(this,"expireAt",null),l(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.instruments=e.flatMap(e=>e.holdings.map(e=>({instrumentId:e.instrumentId,name:o(e.instrumentId),symbol:d(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.isConnected=!1,this.expireAt=null,this.disconnectTimeoutId&&(clearTimeout(this.disconnectTimeoutId),this.disconnectTimeoutId=null),r.removeItem(e.SESSION_KEY)}save(){r.setItem(e.SESSION_KEY,{authToken:this.authToken,accounts:this.accounts.map(({accountName:e,partyId:t,publicKey:s,validator:n})=>({accountName:e,partyId:t,publicKey:s,validator:n})),expireAt:this.expireAt})}setConnected(e){this.isConnected=e}getConnected(){return this.isConnected}hasStoredSession(){return!!r.getItem(e.SESSION_KEY)}load(){const t=r.getItem(e.SESSION_KEY);t&&(this.authToken=t.authToken,this.accounts=(t.accounts||[]).filter(e=>!!e.validator).map(e=>({...e,holdings:[]})),this.expireAt=t.expireAt||null)}};l(u,"instance"),l(u,"SESSION_KEY","c8-session");let p=u;var g=Object.defineProperty,m=(e,t,s)=>((e,t,s)=>t in e?g(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);const f=class e{constructor(e=5e3){this.pollingInterval=e,m(this,"events",new Map),m(this,"intervals",new Map),m(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);r.setItem(e.STORAGE_KEY,t)}restore(){const t=r.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(),r.removeItem(e.STORAGE_KEY)}getEvents(){return Array.from(this.events.values()).map(e=>e.event)}};m(f,"EVENT_TYPES",{RESTORE_SESSION:"RESTORE_SESSION",TRACK_TX_STATUS:"TRACK_TX_STATUS",UPDATE_ACCOUNT:"UPDATE_ACCOUNT"}),m(f,"type"),m(f,"instance"),m(f,"STORAGE_KEY","c8-polling-events"),m(f,"POLLING_TIMEOUT",3e5);let v=f;var w=Object.defineProperty;class T{constructor(e){((e,t,s)=>{((e,t,s)=>{t in e?w(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=p.getInstance().getBearerToken(),n=p.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 y=Object.defineProperty,k=(e,t,s)=>((e,t,s)=>t in e?y(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);function I(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}class E{constructor(e,r,a=t){let o;switch(this.appName=e,this.appUrl=r,this.origin=a,k(this,"WINDOW_NAME","c8-wallet"),k(this,"WINDOW_WIDTH",475),k(this,"WINDOW_HEIGHT",762),k(this,"popup"),k(this,"sessionId",crypto.randomUUID()),k(this,"listening",!1),k(this,"walletReady",!1),k(this,"pending",new Map),k(this,"eventHandlers",new Set),k(this,"handshakeTimer"),k(this,"handshakeDeadline"),k(this,"closeWatcherTimer"),k(this,"pollingManager",v.getInstance()),k(this,"session",p.getInstance()),k(this,"initDeferred"),k(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 t:o=s;break;case n:case i:o="https://wallet-backend.main.cantor8.tech";break;default:o=s}this.httpClient=new T(o),this.pollingManager.registerHandler(v.EVENT_TYPES.RESTORE_SESSION,this.handleRestoreSession),this.pollingManager.registerHandler(v.EVENT_TYPES.TRACK_TX_STATUS,this.handleTrackTxStatus),this.pollingManager.registerHandler(v.EVENT_TYPES.UPDATE_ACCOUNT,this.handleAccountUpdate),this.checkRestoreSession()}checkRestoreSession(){this.session.hasStoredSession()&&this.pollingManager.add(v.EVENT_TYPES.RESTORE_SESSION,{sessionId:this.sessionId})}async handleAccountUpdate(e){try{const e=await this.httpClient.getBalance();if(e&&e.holdings){const t=this.session.getAccounts().find(t=>t.partyId===e.party_id);if(!t)return!1;const s=[{accountName:t.accountName,partyId:e.party_id,publicKey:t.publicKey,validator:t.validator,holdings:Object.entries(e.holdings).map(([e,t])=>({instrumentId:e,balance:Number(t.balance),balanceUsd:Number(t.balance_usd)}))}];this.session.setAccounts(s),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(v.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=this.session.getAccounts().find(t=>t.partyId===e.party_id);if(!t)return!1;const s=[{accountName:t.accountName,partyId:e.party_id,publicKey:t.publicKey,validator:t.validator,holdings:Object.entries(e.holdings).map(([e,t])=>({instrumentId:e,balance:Number(t.balance),balanceUsd:Number(t.balance_usd)}))}];this.session.setAccounts(s),this.session.save(),this.session.setConnected(!0),this.emitSyntheticEvent({type:"connected"});const n=this.session.getExpireAt();return n&&this.scheduleDisconnect(n),!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=I()),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,g,m,f,v,w;const T=crypto.randomUUID(),y=I();this.pending.set(T,y);try{if("connect"===e){if(this.session.getBearerToken())return this.handleResponse({kind:"response",id:T,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")),"signMessage"===e&&(this.walletReady=!1,await this.init("confirmSignMessage")),"signAndExecute"===e&&(this.walletReady=!1,await this.init("signAndExecute")),"status"===e)return this.handleResponse({kind:"response",id:T,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:T,result:{instruments:e}}),y.promise}if("getAccounts"===e){await this.handleAccountUpdate();const e=this.session.getAccounts();return this.handleResponse({kind:"response",id:T,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!=(m=null==(g=s.transfer)?void 0:g.command_id)?m:"",created_at:null!=(v=null==(f=s.transfer)?void 0:f.created_at)?v:"",memo:null==(w=s.transfer)?void 0:w.reason}};this.handleResponse({kind:"response",id:T,result:e})}else this.handleResponse({kind:"response",id:T,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:T,result:null}),y.promise;const k={kind:"request",id:T,method:e,params:t,sessionId:this.sessionId};this.post(k)}catch(e){this.pending.delete(T),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(v.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 S=Object.defineProperty,A=(e,t,s)=>((e,t,s)=>t in e?S(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);function b(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}class D{constructor(e,t,s,n){this.appName=e,this.appUrl=t,this.targetOrigin=s,this.targetWindow=n,A(this,"sessionId",crypto.randomUUID()),A(this,"listening",!1),A(this,"walletReady",!1),A(this,"pending",new Map),A(this,"eventHandlers",new Set),A(this,"handshakeTimer"),A(this,"handshakeDeadline"),A(this,"initDeferred"),this.onWindowMessage=this.onWindowMessage.bind(this),this.attachListener()}async init(){if(!this.walletReady){if(this.initDeferred||(this.initDeferred=b()),this.listening||this.attachListener(),!this.targetWindow){const e=new Error("ThinTransport targetWindow is not available");throw this.rejectInit(e),e}return!this.walletReady&&null==this.handshakeTimer&&this.startHandshakeLoop(),this.initDeferred.promise}}destroy(){try{for(const e of this.eventHandlers)try{e({kind:"event",event:{type:"disconnected",reason:"destroyed"}})}catch{}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.walletReady=!1}catch(e){}}async request(e,t,s){if("connect"===e&&await this.init(),!this.targetWindow){const t=b();if("status"===e){const e=crypto.randomUUID();this.pending.set(e,t),this.handleResponse({kind:"response",id:e,result:{connected:!1,walletVersion:void 0}})}return t.promise}const n=crypto.randomUUID(),i={kind:"request",id:n,method:e,params:t,sessionId:this.sessionId},r=b();return this.pending.set(n,r),this.post(i),r.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.targetWindow)return;this.targetWindow.postMessage(e,this.targetOrigin)}catch(e){}}onWindowMessage(e){if(e.origin!==this.targetOrigin||e.source!==this.targetWindow)return;const t=e.data;if(t&&"object"==typeof t){if("event"===t.kind){for(const e of this.eventHandlers)e(t);return}if("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=Object.assign(new Error(e.error.message),{code:e.error.code,data:e.error.data});t.reject(s)}else t.resolve(e.result)}startHandshakeLoop(){this.handshakeDeadline=Date.now()+15e3;const e=()=>{if(!this.walletReady)return this.targetWindow?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(),void this.rejectInit(new Error("Target window unavailable before handshake")));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&&(this.initDeferred.reject(e),this.initDeferred=void 0)}}var _=Object.defineProperty,C=(e,t,s)=>((e,t,s)=>t in e?_(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);function N(t){try{const s=new URL(t).hostname;return s===e||s.endsWith(`.${e}`)}catch{return!1}}const O={uuid:"c8-wallet-connect",name:"C8 Wallet",icon:"",rdns:"tech.cantor8.wallet"},R="c8#provider_discovery";exports.C8WalletProvider=class{constructor(e){var s,r,a;C(this,"transport"),C(this,"listeners",{});const o=null!=(s=e.dappName)?s:document.title||"Unknown dApp",h=null!=(r=e.dappUrl)?r:location.origin,d=null!=(a=e.network)?a:"mainnet";let c;switch(d){case"devnet":c=t;break;case"testmainnet":c=i;break;case"mainnet":c=n;break;default:throw new Error("Unsupported network: "+d)}const l=function(){var e;if(window.parent===window)return;const t=null==(e=window.location.ancestorOrigins)?void 0:e[0];if(t&&N(t))return t;if(document.referrer)try{const e=new URL(document.referrer).origin;return N(e)?e:void 0}catch{return}}();this.transport=l?new D(o,h,l,window.parent):new E(o,h,c),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)}signMessage(e,t){return this.transport.request("signMessage",{message:e,partyId:t},!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=T,exports.LocalStorageHelper=r,exports.announceC8Provider=function(e){const t={info:O,provider:e()};window.dispatchEvent(new CustomEvent(R,{detail:t}))},exports.onC8ProviderDiscovered=function(e){const t=t=>{const s=t;s.detail&&e(s.detail.info,s.detail.provider)};return window.addEventListener(R,t),()=>window.removeEventListener(R,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",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 v{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 I=Object.defineProperty,f=(e,t,s)=>((e,t,s)=>t in e?I(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 E{constructor(n,i,r=e){let a;switch(this.appName=n,this.appUrl=i,this.origin=r,f(this,"WINDOW_NAME","c8-wallet"),f(this,"WINDOW_WIDTH",475),f(this,"WINDOW_HEIGHT",762),f(this,"popup"),f(this,"sessionId",crypto.randomUUID()),f(this,"listening",!1),f(this,"walletReady",!1),f(this,"pending",new Map),f(this,"eventHandlers",new Set),f(this,"handshakeTimer"),f(this,"handshakeDeadline"),f(this,"closeWatcherTimer"),f(this,"pollingManager",g.getInstance()),f(this,"session",l.getInstance()),f(this,"initDeferred"),f(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 v(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,v,I;const f=crypto.randomUUID(),E=w();this.pending.set(f,E);try{if("connect"===e){if(this.session.getBearerToken())return this.handleResponse({kind:"response",id:f,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:f,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:f,result:{instruments:e}}),E.promise}if("getAccounts"===e){await this.handleAccountUpdate();const e=this.session.getAccounts();return this.handleResponse({kind:"response",id:f,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!=(v=null==(T=s.transfer)?void 0:T.created_at)?v:"",memo:null==(I=s.transfer)?void 0:I.reason}};this.handleResponse({kind:"response",id:f,result:e})}else this.handleResponse({kind:"response",id:f,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:f,result:null}),E.promise;const w={kind:"request",id:f,method:e,params:t,sessionId:this.sessionId};this.post(w)}catch(e){this.pending.delete(f),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(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 y=Object.defineProperty,k=(e,t,s)=>((e,t,s)=>t in e?y(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 E(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)}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,v as HttpClient,n as LocalStorageHelper,C as announceC8Provider,_ as onC8ProviderDiscovered};
|
|
1
|
+
const e="cantor8.tech",t="https://wallet.dev.digik.cantor8.tech",s="https://wallet-backend.dev.digik.cantor8.tech",n="https://wallet.cantor8.tech",i="https://wallet.main.digik.cantor8.tech";class r{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 a={TestCoin1:"TestCoin1",Amulet:"Canton Coin",CBTC:"CBTC",USDCx:"USDCx",CETH:"CETH"},o=e=>{var t;return"Amulet"===e?"Canton Coin":null!=(t=a[null!=e?e:""])?t:e},h={TestCoin1:"TestCoin1",Amulet:"CC",CBTC:"CBTC",USDCx:"USDCx"},d=e=>{var t;return"Amulet"===e?"CC":null!=(t=h[null!=e?e:""])?t:e};var c=Object.defineProperty,l=(e,t,s)=>((e,t,s)=>t in e?c(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);const u=class e{constructor(){l(this,"appName"),l(this,"accounts",[]),l(this,"instruments",[]),l(this,"authToken",null),l(this,"isConnected",!1),l(this,"expireAt",null),l(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.instruments=e.flatMap(e=>e.holdings.map(e=>({instrumentId:e.instrumentId,name:o(e.instrumentId),symbol:d(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.isConnected=!1,this.expireAt=null,this.disconnectTimeoutId&&(clearTimeout(this.disconnectTimeoutId),this.disconnectTimeoutId=null),r.removeItem(e.SESSION_KEY)}save(){r.setItem(e.SESSION_KEY,{authToken:this.authToken,accounts:this.accounts.map(({accountName:e,partyId:t,publicKey:s,validator:n})=>({accountName:e,partyId:t,publicKey:s,validator:n})),expireAt:this.expireAt})}setConnected(e){this.isConnected=e}getConnected(){return this.isConnected}hasStoredSession(){return!!r.getItem(e.SESSION_KEY)}load(){const t=r.getItem(e.SESSION_KEY);t&&(this.authToken=t.authToken,this.accounts=(t.accounts||[]).filter(e=>!!e.validator).map(e=>({...e,holdings:[]})),this.expireAt=t.expireAt||null)}};l(u,"instance"),l(u,"SESSION_KEY","c8-session");let p=u;var g=Object.defineProperty,m=(e,t,s)=>((e,t,s)=>t in e?g(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);const f=class e{constructor(e=5e3){this.pollingInterval=e,m(this,"events",new Map),m(this,"intervals",new Map),m(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);r.setItem(e.STORAGE_KEY,t)}restore(){const t=r.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(),r.removeItem(e.STORAGE_KEY)}getEvents(){return Array.from(this.events.values()).map(e=>e.event)}};m(f,"EVENT_TYPES",{RESTORE_SESSION:"RESTORE_SESSION",TRACK_TX_STATUS:"TRACK_TX_STATUS",UPDATE_ACCOUNT:"UPDATE_ACCOUNT"}),m(f,"type"),m(f,"instance"),m(f,"STORAGE_KEY","c8-polling-events"),m(f,"POLLING_TIMEOUT",3e5);let v=f;var w=Object.defineProperty;class T{constructor(e){((e,t,s)=>{((e,t,s)=>{t in e?w(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=p.getInstance().getBearerToken(),n=p.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 y=Object.defineProperty,k=(e,t,s)=>((e,t,s)=>t in e?y(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);function I(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}class E{constructor(e,r,a=t){let o;switch(this.appName=e,this.appUrl=r,this.origin=a,k(this,"WINDOW_NAME","c8-wallet"),k(this,"WINDOW_WIDTH",475),k(this,"WINDOW_HEIGHT",762),k(this,"popup"),k(this,"sessionId",crypto.randomUUID()),k(this,"listening",!1),k(this,"walletReady",!1),k(this,"pending",new Map),k(this,"eventHandlers",new Set),k(this,"handshakeTimer"),k(this,"handshakeDeadline"),k(this,"closeWatcherTimer"),k(this,"pollingManager",v.getInstance()),k(this,"session",p.getInstance()),k(this,"initDeferred"),k(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 t:o=s;break;case n:case i:o="https://wallet-backend.main.cantor8.tech";break;default:o=s}this.httpClient=new T(o),this.pollingManager.registerHandler(v.EVENT_TYPES.RESTORE_SESSION,this.handleRestoreSession),this.pollingManager.registerHandler(v.EVENT_TYPES.TRACK_TX_STATUS,this.handleTrackTxStatus),this.pollingManager.registerHandler(v.EVENT_TYPES.UPDATE_ACCOUNT,this.handleAccountUpdate),this.checkRestoreSession()}checkRestoreSession(){this.session.hasStoredSession()&&this.pollingManager.add(v.EVENT_TYPES.RESTORE_SESSION,{sessionId:this.sessionId})}async handleAccountUpdate(e){try{const e=await this.httpClient.getBalance();if(e&&e.holdings){const t=this.session.getAccounts().find(t=>t.partyId===e.party_id);if(!t)return!1;const s=[{accountName:t.accountName,partyId:e.party_id,publicKey:t.publicKey,validator:t.validator,holdings:Object.entries(e.holdings).map(([e,t])=>({instrumentId:e,balance:Number(t.balance),balanceUsd:Number(t.balance_usd)}))}];this.session.setAccounts(s),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(v.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=this.session.getAccounts().find(t=>t.partyId===e.party_id);if(!t)return!1;const s=[{accountName:t.accountName,partyId:e.party_id,publicKey:t.publicKey,validator:t.validator,holdings:Object.entries(e.holdings).map(([e,t])=>({instrumentId:e,balance:Number(t.balance),balanceUsd:Number(t.balance_usd)}))}];this.session.setAccounts(s),this.session.save(),this.session.setConnected(!0),this.emitSyntheticEvent({type:"connected"});const n=this.session.getExpireAt();return n&&this.scheduleDisconnect(n),!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=I()),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,g,m,f,v,w;const T=crypto.randomUUID(),y=I();this.pending.set(T,y);try{if("connect"===e){if(this.session.getBearerToken())return this.handleResponse({kind:"response",id:T,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")),"signMessage"===e&&(this.walletReady=!1,await this.init("confirmSignMessage")),"signAndExecute"===e&&(this.walletReady=!1,await this.init("signAndExecute")),"status"===e)return this.handleResponse({kind:"response",id:T,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:T,result:{instruments:e}}),y.promise}if("getAccounts"===e){await this.handleAccountUpdate();const e=this.session.getAccounts();return this.handleResponse({kind:"response",id:T,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!=(m=null==(g=s.transfer)?void 0:g.command_id)?m:"",created_at:null!=(v=null==(f=s.transfer)?void 0:f.created_at)?v:"",memo:null==(w=s.transfer)?void 0:w.reason}};this.handleResponse({kind:"response",id:T,result:e})}else this.handleResponse({kind:"response",id:T,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:T,result:null}),y.promise;const k={kind:"request",id:T,method:e,params:t,sessionId:this.sessionId};this.post(k)}catch(e){this.pending.delete(T),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(v.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 S=Object.defineProperty,A=(e,t,s)=>((e,t,s)=>t in e?S(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);function b(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}class D{constructor(e,t,s,n){this.appName=e,this.appUrl=t,this.targetOrigin=s,this.targetWindow=n,A(this,"sessionId",crypto.randomUUID()),A(this,"listening",!1),A(this,"walletReady",!1),A(this,"pending",new Map),A(this,"eventHandlers",new Set),A(this,"handshakeTimer"),A(this,"handshakeDeadline"),A(this,"initDeferred"),this.onWindowMessage=this.onWindowMessage.bind(this),this.attachListener()}async init(){if(!this.walletReady){if(this.initDeferred||(this.initDeferred=b()),this.listening||this.attachListener(),!this.targetWindow){const e=new Error("ThinTransport targetWindow is not available");throw this.rejectInit(e),e}return!this.walletReady&&null==this.handshakeTimer&&this.startHandshakeLoop(),this.initDeferred.promise}}destroy(){try{for(const e of this.eventHandlers)try{e({kind:"event",event:{type:"disconnected",reason:"destroyed"}})}catch{}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.walletReady=!1}catch(e){}}async request(e,t,s){if("connect"===e&&await this.init(),!this.targetWindow){const t=b();if("status"===e){const e=crypto.randomUUID();this.pending.set(e,t),this.handleResponse({kind:"response",id:e,result:{connected:!1,walletVersion:void 0}})}return t.promise}const n=crypto.randomUUID(),i={kind:"request",id:n,method:e,params:t,sessionId:this.sessionId},r=b();return this.pending.set(n,r),this.post(i),r.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.targetWindow)return;this.targetWindow.postMessage(e,this.targetOrigin)}catch(e){}}onWindowMessage(e){if(e.origin!==this.targetOrigin||e.source!==this.targetWindow)return;const t=e.data;if(t&&"object"==typeof t){if("event"===t.kind){for(const e of this.eventHandlers)e(t);return}if("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=Object.assign(new Error(e.error.message),{code:e.error.code,data:e.error.data});t.reject(s)}else t.resolve(e.result)}startHandshakeLoop(){this.handshakeDeadline=Date.now()+15e3;const e=()=>{if(!this.walletReady)return this.targetWindow?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(),void this.rejectInit(new Error("Target window unavailable before handshake")));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&&(this.initDeferred.reject(e),this.initDeferred=void 0)}}var _=Object.defineProperty,C=(e,t,s)=>((e,t,s)=>t in e?_(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s)(e,"symbol"!=typeof t?t+"":t,s);function N(t){try{const s=new URL(t).hostname;return s===e||s.endsWith(`.${e}`)}catch{return!1}}class O{constructor(e){var s,r,a;C(this,"transport"),C(this,"listeners",{});const o=null!=(s=e.dappName)?s:document.title||"Unknown dApp",h=null!=(r=e.dappUrl)?r:location.origin,d=null!=(a=e.network)?a:"mainnet";let c;switch(d){case"devnet":c=t;break;case"testmainnet":c=i;break;case"mainnet":c=n;break;default:throw new Error("Unsupported network: "+d)}const l=function(){var e;if(window.parent===window)return;const t=null==(e=window.location.ancestorOrigins)?void 0:e[0];if(t&&N(t))return t;if(document.referrer)try{const e=new URL(document.referrer).origin;return N(e)?e:void 0}catch{return}}();this.transport=l?new D(o,h,l,window.parent):new E(o,h,c),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)}signMessage(e,t){return this.transport.request("signMessage",{message:e,partyId:t},!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 R={uuid:"c8-wallet-connect",name:"C8 Wallet",icon:"",rdns:"tech.cantor8.wallet"},U="c8#provider_discovery";function L(e){const t={info:R,provider:e()};window.dispatchEvent(new CustomEvent(U,{detail:t}))}function H(e){const t=t=>{const s=t;s.detail&&e(s.detail.info,s.detail.provider)};return window.addEventListener(U,t),()=>window.removeEventListener(U,t)}export{O as C8WalletProvider,T as HttpClient,r as LocalStorageHelper,L as announceC8Provider,H as onC8ProviderDiscovered};
|
package/dist/provider.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { C8EventByType, C8EventType, Listener } from "./types";
|
|
1
|
+
import { C8EventByType, C8EventType, Listener, MultiLegSwapSpecRequest } from "./types";
|
|
2
2
|
export declare class C8WalletProvider {
|
|
3
3
|
private transport;
|
|
4
4
|
private listeners;
|
|
5
5
|
constructor(opts: {
|
|
6
6
|
dappName: string;
|
|
7
7
|
dappUrl?: string;
|
|
8
|
-
network?: "devnet" | "mainnet";
|
|
8
|
+
network?: "devnet" | "testmainnet" | "mainnet";
|
|
9
9
|
});
|
|
10
10
|
connect(): Promise<void>;
|
|
11
11
|
disconnect(): Promise<void>;
|
|
@@ -23,6 +23,11 @@ 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
|
+
swap: MultiLegSwapSpecRequest;
|
|
29
|
+
commandId?: string;
|
|
30
|
+
}): Promise<import("./types").SubmitTransferResultPayload>;
|
|
26
31
|
signAndExecute(input: {
|
|
27
32
|
note: string;
|
|
28
33
|
partyId: string;
|
|
@@ -30,6 +35,7 @@ export declare class C8WalletProvider {
|
|
|
30
35
|
commandsJson: string;
|
|
31
36
|
disclosedContracts: string;
|
|
32
37
|
}): Promise<void>;
|
|
38
|
+
signMessage(message: string, partyId?: string): Promise<string>;
|
|
33
39
|
private signAndExecutePreparedTransfer;
|
|
34
40
|
private acknowledge;
|
|
35
41
|
checkTxStatusById(input: {
|
package/dist/session.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export declare const WALLET_ORIGIN_LOCAL = "http://localhost:8081";
|
|
2
|
+
export declare const WALLET_BASE_DOMAIN = "cantor8.tech";
|
|
2
3
|
export declare const WALLET_ORIGIN_DEVNET = "https://wallet.dev.digik.cantor8.tech";
|
|
3
4
|
export declare const WALLET_API_DEVNET = "https://wallet-backend.dev.digik.cantor8.tech";
|
|
4
5
|
export declare const WALLET_ORIGIN_MAINNET = "https://wallet.cantor8.tech";
|
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" | "signMessage" | "signAndExecute" | "signAndExecutePreparedTransfer" | "acknowledge" | "checkTxStatusById" | "createSwapOffer";
|
|
84
84
|
export interface WalletRequestPayloadMap {
|
|
85
85
|
connect: undefined;
|
|
86
86
|
disconnect: undefined;
|
|
@@ -97,6 +97,10 @@ export interface WalletRequestPayloadMap {
|
|
|
97
97
|
memo?: string;
|
|
98
98
|
metadata?: Record<string, string>;
|
|
99
99
|
};
|
|
100
|
+
signMessage: {
|
|
101
|
+
message: string;
|
|
102
|
+
partyId?: string;
|
|
103
|
+
};
|
|
100
104
|
signAndExecute: {
|
|
101
105
|
note: string;
|
|
102
106
|
partyId: string;
|
|
@@ -120,8 +124,40 @@ export interface WalletRequestPayloadMap {
|
|
|
120
124
|
checkTxStatusById: {
|
|
121
125
|
txId: string;
|
|
122
126
|
};
|
|
127
|
+
createSwapOffer: {
|
|
128
|
+
partyId: string;
|
|
129
|
+
swap: MultiLegSwapSpecRequest;
|
|
130
|
+
commandId?: string;
|
|
131
|
+
};
|
|
123
132
|
}
|
|
124
133
|
export type WalletRequestPayload<M extends WalletMethod> = WalletRequestPayloadMap[M];
|
|
134
|
+
export interface InstrumentId {
|
|
135
|
+
admin: string;
|
|
136
|
+
id: string;
|
|
137
|
+
}
|
|
138
|
+
export interface SwapLegRequest {
|
|
139
|
+
receiver: string;
|
|
140
|
+
instrument: InstrumentId;
|
|
141
|
+
amount: string;
|
|
142
|
+
legId: string;
|
|
143
|
+
reason?: string;
|
|
144
|
+
}
|
|
145
|
+
export interface SwapTransferLegRequest {
|
|
146
|
+
receiver: string;
|
|
147
|
+
instrument: InstrumentId;
|
|
148
|
+
amount: string;
|
|
149
|
+
legId: string;
|
|
150
|
+
reason?: string;
|
|
151
|
+
}
|
|
152
|
+
export interface MultiLegSwapSpecRequest {
|
|
153
|
+
swapId: string;
|
|
154
|
+
acceptorPartyId: string;
|
|
155
|
+
creatorLegs: SwapLegRequest[];
|
|
156
|
+
acceptorLegs: SwapLegRequest[];
|
|
157
|
+
creatorTransferLegs: SwapTransferLegRequest[];
|
|
158
|
+
settleBefore: string;
|
|
159
|
+
meta: Record<string, string>;
|
|
160
|
+
}
|
|
125
161
|
export interface TransferTransactionPayload {
|
|
126
162
|
senderPartyId: string;
|
|
127
163
|
receiverPartyId: string;
|
|
@@ -151,9 +187,15 @@ export interface AccountInfoHolding {
|
|
|
151
187
|
balance: number;
|
|
152
188
|
balanceUsd: number;
|
|
153
189
|
}
|
|
190
|
+
export interface ValidatorInfo {
|
|
191
|
+
id: string;
|
|
192
|
+
name: string;
|
|
193
|
+
}
|
|
154
194
|
export interface AccountInfoPayload {
|
|
155
195
|
accountName?: string;
|
|
156
196
|
partyId: string;
|
|
197
|
+
publicKey: string;
|
|
198
|
+
validator: ValidatorInfo;
|
|
157
199
|
holdings: AccountInfoHolding[];
|
|
158
200
|
}
|
|
159
201
|
export interface AccountListPayload {
|
|
@@ -195,12 +237,14 @@ export interface WalletResponsePayloadMap {
|
|
|
195
237
|
getInstruments: InstrumentListPayload;
|
|
196
238
|
getAccounts: AccountListPayload;
|
|
197
239
|
send: SubmitTransferResultPayload;
|
|
240
|
+
signMessage: string;
|
|
198
241
|
signAndExecute: void;
|
|
199
242
|
signAndExecutePreparedTransfer: SubmitTransferResultPayload;
|
|
200
243
|
acknowledge: {
|
|
201
244
|
success: boolean;
|
|
202
245
|
};
|
|
203
246
|
checkTxStatusById: TransferStatusResponsePayload;
|
|
247
|
+
createSwapOffer: SubmitTransferResultPayload;
|
|
204
248
|
}
|
|
205
249
|
export type WalletResponsePayload<M extends WalletMethod> = WalletResponsePayloadMap[M];
|
|
206
250
|
export type PollingHandler = (params: any) => Promise<boolean>;
|
package/package.json
CHANGED