@etherspot/prime-sdk
Version:
Etherspot Prime (Account Abstraction) SDK
95 lines (94 loc) • 3.41 kB
JavaScript
;
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.StateService = void 0;
const class_transformer_1 = require("class-transformer");
const rxjs_1 = require("rxjs");
const operators_1 = require("rxjs/operators");
const common_1 = require("../common");
const classes_1 = require("./classes");
class StateService extends common_1.Service {
constructor(options = {}) {
super();
this.options = options;
this.state$ = new rxjs_1.BehaviorSubject(null);
}
get state() {
return this.state$.value;
}
get wallet$() {
return this.services.walletService.wallet$;
}
get wallet() {
return this.services.walletService.wallet;
}
get EOAAddress$() {
return this.services.walletService.EOAAddress$;
}
get EOAAddress() {
return this.services.walletService.EOAAddress;
}
get network() {
return this.services.networkService.network;
}
get network$() {
return this.services.networkService.network$;
}
restore(state) {
if (state) {
state = (0, class_transformer_1.plainToClass)(classes_1.State, state);
}
return this;
}
onInit() {
const { storage } = this.options || {};
const { walletService: { wallet$, wallet }, networkService: { network$, network }, } = this.services;
const callback = () => {
this.addSubscriptions((0, rxjs_1.combineLatest)([
wallet$,
network$,
])
.pipe((0, operators_1.map)(([wallet, network,]) => ({
wallet,
network,
})))
.subscribe(this.state$), !storage
? null
: this.state$
.pipe((0, operators_1.filter)((state) => state &&
state.wallet &&
state.wallet.address &&
state.network &&
state.network.name &&
true), (0, operators_1.tap)((state) => {
const { wallet, network } = state, storageState = __rest(state, ["wallet", "network"]);
this.error$.catch(() => storage.setState(wallet.address, network.name, storageState));
}))
.subscribe());
};
if (storage) {
this.error$.catch(async () => {
const EOAAddress = wallet && wallet.address ? wallet.address : null;
const networkName = network && network.name ? network.name : null;
if (EOAAddress && networkName) {
const state = await storage.getState(EOAAddress, networkName);
this.restore(state);
}
}, callback);
}
else {
callback();
}
}
}
exports.StateService = StateService;