@cantor8/wallet-connect-sdk 0.4.0 → 0.5.1
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 +86 -20
- package/dist/index.cjs +1 -1
- package/dist/index.esm.js +1 -1
- package/dist/provider.d.ts +4 -12
- package/dist/session.d.ts +0 -1
- package/dist/transports/constants.d.ts +2 -1
- package/dist/types.d.ts +40 -11
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -79,18 +79,44 @@ console.log("Send result", res); // { txId }
|
|
|
79
79
|
// Create a swap offer
|
|
80
80
|
const swapRes = await c8.createSwapOffer({
|
|
81
81
|
partyId: senderPartyId,
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
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
|
+
},
|
|
91
113
|
});
|
|
92
114
|
|
|
93
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);
|
|
94
120
|
```
|
|
95
121
|
|
|
96
122
|
## API Reference
|
|
@@ -105,7 +131,8 @@ console.log("Swap offer result", swapRes); // { txId }
|
|
|
105
131
|
| `getInstruments()` | None | `Promise<InstrumentListPayload>` |
|
|
106
132
|
| `getAccounts()` | `instrumentId?: string` | `Promise<AccountListPayload>` |
|
|
107
133
|
| `send()` | `input: SendInput` | `Promise<SubmitTransferResultPayload>` |
|
|
108
|
-
| `createSwapOffer()` | `input:
|
|
134
|
+
| `createSwapOffer()` | `input: { partyId, swap, commandId? }` | `Promise<SubmitTransferResultPayload>` |
|
|
135
|
+
| `signMessage()` | `message: string, partyId?: string` | `Promise<string>` |
|
|
109
136
|
| `signAndExecute()` | `input: SignAndExecuteInput` | `Promise<void>` |
|
|
110
137
|
| `checkTxStatusById()` | `input: { txId: string }` | `Promise<TransferStatusResponsePayload>` |
|
|
111
138
|
| `on()` | `event: T, cb: Listener<C8EventByType<T>>` | `() => boolean` |
|
|
@@ -128,20 +155,51 @@ console.log("Swap offer result", swapRes); // { txId }
|
|
|
128
155
|
```ts
|
|
129
156
|
{
|
|
130
157
|
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
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
|
+
};
|
|
142
195
|
}
|
|
143
196
|
```
|
|
144
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
|
+
|
|
145
203
|
### `signAndExecute()` Input
|
|
146
204
|
|
|
147
205
|
```ts
|
|
@@ -154,6 +212,14 @@ console.log("Swap offer result", swapRes); // { txId }
|
|
|
154
212
|
}
|
|
155
213
|
```
|
|
156
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
|
+
|
|
157
223
|
## Events Reference
|
|
158
224
|
|
|
159
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 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)};
|
|
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.digik.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 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};
|
|
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.digik.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>;
|
|
@@ -25,16 +25,7 @@ export declare class C8WalletProvider {
|
|
|
25
25
|
}): Promise<import("./types").SubmitTransferResultPayload>;
|
|
26
26
|
createSwapOffer(input: {
|
|
27
27
|
partyId: string;
|
|
28
|
-
|
|
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;
|
|
28
|
+
swap: MultiLegSwapSpecRequest;
|
|
38
29
|
commandId?: string;
|
|
39
30
|
}): Promise<import("./types").SubmitTransferResultPayload>;
|
|
40
31
|
signAndExecute(input: {
|
|
@@ -44,6 +35,7 @@ export declare class C8WalletProvider {
|
|
|
44
35
|
commandsJson: string;
|
|
45
36
|
disclosedContracts: string;
|
|
46
37
|
}): Promise<void>;
|
|
38
|
+
signMessage(message: string, partyId?: string): Promise<string>;
|
|
47
39
|
private signAndExecutePreparedTransfer;
|
|
48
40
|
private acknowledge;
|
|
49
41
|
checkTxStatusById(input: {
|
package/dist/session.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
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";
|
|
5
|
-
export declare const WALLET_API_MAINNET = "https://wallet-backend.main.cantor8.tech";
|
|
6
|
+
export declare const WALLET_API_MAINNET = "https://wallet-backend.main.digik.cantor8.tech";
|
|
6
7
|
export declare const WALLET_ORIGIN_TEST_MAINNET = "https://wallet.main.digik.cantor8.tech";
|
|
7
8
|
export declare const WALLET_EMBED_URL = "/embedded";
|
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" | "createSwapOffer";
|
|
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;
|
|
@@ -122,20 +126,38 @@ export interface WalletRequestPayloadMap {
|
|
|
122
126
|
};
|
|
123
127
|
createSwapOffer: {
|
|
124
128
|
partyId: string;
|
|
125
|
-
|
|
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;
|
|
129
|
+
swap: MultiLegSwapSpecRequest;
|
|
135
130
|
commandId?: string;
|
|
136
131
|
};
|
|
137
132
|
}
|
|
138
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
|
+
}
|
|
139
161
|
export interface TransferTransactionPayload {
|
|
140
162
|
senderPartyId: string;
|
|
141
163
|
receiverPartyId: string;
|
|
@@ -165,9 +187,15 @@ export interface AccountInfoHolding {
|
|
|
165
187
|
balance: number;
|
|
166
188
|
balanceUsd: number;
|
|
167
189
|
}
|
|
190
|
+
export interface ValidatorInfo {
|
|
191
|
+
id: string;
|
|
192
|
+
name: string;
|
|
193
|
+
}
|
|
168
194
|
export interface AccountInfoPayload {
|
|
169
195
|
accountName?: string;
|
|
170
196
|
partyId: string;
|
|
197
|
+
publicKey: string;
|
|
198
|
+
validator: ValidatorInfo;
|
|
171
199
|
holdings: AccountInfoHolding[];
|
|
172
200
|
}
|
|
173
201
|
export interface AccountListPayload {
|
|
@@ -209,6 +237,7 @@ export interface WalletResponsePayloadMap {
|
|
|
209
237
|
getInstruments: InstrumentListPayload;
|
|
210
238
|
getAccounts: AccountListPayload;
|
|
211
239
|
send: SubmitTransferResultPayload;
|
|
240
|
+
signMessage: string;
|
|
212
241
|
signAndExecute: void;
|
|
213
242
|
signAndExecutePreparedTransfer: SubmitTransferResultPayload;
|
|
214
243
|
acknowledge: {
|
package/package.json
CHANGED