UNPKG

@zlattice/lattice-js

Version:

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

49 lines 1.51 kB
import { log } from "../logger.js"; import { Mutex } from "../utils/index.js"; import { ResultAsync } from "neverthrow"; /** * Account lock implementation */ export class AccountLockImpl { constructor() { this.locks = new Map(); this.lockReleases = new Map(); } async obtain(chainId, address) { log.debug(`obtain account lock, chainId: ${chainId}, address: ${address}`); const key = `${chainId}_${address}`; if (!this.locks.has(key)) { this.locks.set(key, new Mutex()); } const lock = this.locks.get(key); if (lock) { await lock.obtain().then((release) => { this.lockReleases.set(key, release); }); } } unlock(chainId, address) { 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 ResultAsync.fromSafePromise(this.obtain(chainId, address).then(async () => { return await block().finally(() => { this.unlock(chainId, address); }); })); } } /** * Create a new account lock * @returns Account lock instance */ export function newAccountLock() { return new AccountLockImpl(); } //# sourceMappingURL=account_lock.js.map