ribbit-wallet-connect
Version:
Next-generation multi-chain wallet and payments app that makes crypto simple, secure, and usable in daily life.
63 lines (62 loc) • 2.45 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.WindowTransport = void 0;
const constants_1 = require("../core/constants");
class WindowTransport {
constructor() {
this.handlers = new Map();
this.onMessage = async (event) => {
const { method, payload } = event.data;
const handler = this.handlers.get(method);
if (handler) {
const result = await handler(payload);
window.postMessage({ method: `${method}_RESPONSE`, payload: result });
}
};
}
listen() {
window.addEventListener('message', this.onMessage);
}
registerHandler(method, handler) {
this.handlers.set(method, handler);
}
sendMessage(method, payload) {
var _a, _b, _c, _d;
const runtime = ((_a = window.chrome) === null || _a === void 0 ? void 0 : _a.runtime) ||
((_b = window.brave) === null || _b === void 0 ? void 0 : _b.runtime) ||
((_c = window.msBrowser) === null || _c === void 0 ? void 0 : _c.runtime) ||
((_d = window.browser) === null || _d === void 0 ? void 0 : _d.runtime);
if (!runtime)
return Promise.reject(new Error('Runtime not available'));
return new Promise((resolve) => {
try {
// Check if EXTENSION_ID is not null or undefined
if (!constants_1.EXTENSION_ID) {
resolve(false);
return;
}
// Send the actual method and payload, not just a ping
runtime.sendMessage(constants_1.EXTENSION_ID, { type: method, payload }, (response) => {
if (response) {
resolve(response);
}
else {
resolve(false);
}
});
// Add a timeout in case the message hangs
setTimeout(() => resolve(false), 500);
}
catch (err) {
if (err && typeof err === 'object' && 'message' in err) {
console.log('Extension not available:', err.message);
}
else {
console.log('Extension not available:', err);
}
resolve(false);
}
});
}
}
exports.WindowTransport = WindowTransport;