UNPKG

@zlattice/lattice-js

Version:

Lattice blockchain TypeScript SDK with dual module support (CJS + ESM)

54 lines 1.74 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AccountLockImpl = void 0; exports.newAccountLock = newAccountLock; const logger_1 = require("../logger.js"); const index_1 = require("../utils/index.js"); const neverthrow_1 = require("neverthrow"); /** * Account lock implementation */ class AccountLockImpl { constructor() { this.locks = new Map(); this.lockReleases = new Map(); } async obtain(chainId, address) { logger_1.log.debug(`obtain account lock, chainId: ${chainId}, address: ${address}`); const key = `${chainId}_${address}`; if (!this.locks.has(key)) { this.locks.set(key, new index_1.Mutex()); } const lock = this.locks.get(key); if (lock) { await lock.obtain().then((release) => { this.lockReleases.set(key, release); }); } } unlock(chainId, address) { logger_1.log.debug(`unlock account lock, chainId: ${chainId}, address: ${address}`); const key = `${chainId}_${address}`; const release = this.lockReleases.get(key); if (release) { release(); this.lockReleases.delete(key); } } withLock(chainId, address, block) { return neverthrow_1.ResultAsync.fromSafePromise(this.obtain(chainId, address).then(async () => { return await block().finally(() => { this.unlock(chainId, address); }); })); } } exports.AccountLockImpl = AccountLockImpl; /** * Create a new account lock * @returns Account lock instance */ function newAccountLock() { return new AccountLockImpl(); } //# sourceMappingURL=account_lock.js.map