@bugbytes/hapi-connect
Version:
Lightweight HashConnect Browser Side Client Library
61 lines • 2.8 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.HashConnectCachedClient = exports.DEFAULT_CACHE_KEY = void 0;
const client_1 = require("./client");
const util_1 = require("./util");
exports.DEFAULT_CACHE_KEY = "hashconnect.data";
class HashConnectCachedClient {
_cacheKey;
_client;
_connection;
constructor(cacheKey = exports.DEFAULT_CACHE_KEY) {
const value = localStorage.getItem(cacheKey);
const connection = !!value ? JSON.parse(value) : {};
if (!connection.topic || !connection.secret || !connection.pairedWallet) {
connection.topic = (0, util_1.createRandomId)();
connection.secret = (0, util_1.createRandomId)();
connection.pairedWallet = undefined;
localStorage.setItem(cacheKey, JSON.stringify(connection));
}
const client = new client_1.HashConnectClient();
client.connect(connection.topic, connection.secret);
this._cacheKey = cacheKey;
this._connection = connection;
this._client = client;
}
get cacheKey() {
return this._cacheKey;
}
get pairedWallet() {
return this._connection.pairedWallet;
}
openPairRequest(name, description, network) {
this.closeWallet();
const cachedRequestTopic = this._connection.topic;
const pairingString = (0, client_1.createParingString)(this._connection.topic, this._connection.secret, name, description, network);
const pairCompleted = this._client.waitForPairing(cachedRequestTopic).then((metadata) => {
// Check that we have a response for the latest paring request.
if (cachedRequestTopic === this._connection.topic) {
this._connection.pairedWallet = metadata;
localStorage?.setItem(this._cacheKey, JSON.stringify(this._connection));
}
return metadata;
});
return { pairingString, pairCompleted };
}
closeWallet() {
if (this._connection.pairedWallet) {
this._connection.topic = (0, util_1.createRandomId)();
this._connection.secret = (0, util_1.createRandomId)();
this._connection.pairedWallet = undefined;
localStorage?.setItem(this._cacheKey, JSON.stringify(this._connection));
this._client = new client_1.HashConnectClient();
this._client.connect(this._connection.topic, this._connection.secret);
}
}
sendTransaction(transaction, returnTransaction = false) {
return this._client.sendTransaction(this._connection.topic, transaction, this._connection.pairedWallet.accountIds[0], returnTransaction);
}
}
exports.HashConnectCachedClient = HashConnectCachedClient;
//# sourceMappingURL=cache.js.map