Skip to content

Commit bb505db

Browse files
committed
Add lock for token allowance
1 parent 781b5b6 commit bb505db

File tree

1 file changed

+18
-5
lines changed

1 file changed

+18
-5
lines changed

codex/contracts/market.nim

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ type
2323
rewardRecipient: ?Address
2424
configuration: ?MarketplaceConfig
2525
requestCache: LruCache[string, StorageRequest]
26+
allowanceLock: AsyncLock
2627

2728
MarketSubscription = market.Subscription
2829
EventSubscription = ethers.Subscription
@@ -76,18 +77,30 @@ proc config(
7677

7778
return resolvedConfig
7879

80+
template withAllowanceLock*(market: OnChainMarket, body: untyped) =
81+
if market.allowanceLock.isNil:
82+
market.allowanceLock = newAsyncLock()
83+
await market.allowanceLock.acquire()
84+
try:
85+
body
86+
finally:
87+
try:
88+
market.allowanceLock.release()
89+
except AsyncLockError as error:
90+
raise newException(Defect, error.msg, error)
91+
7992
proc approveFunds(
8093
market: OnChainMarket, amount: UInt256
8194
) {.async: (raises: [CancelledError, MarketError]).} =
8295
debug "Approving tokens", amount
8396
convertEthersError("Failed to approve funds"):
8497
let tokenAddress = await market.contract.token()
8598
let token = Erc20Token.new(tokenAddress, market.signer)
86-
let currentAllowance =
87-
await token.allowance(await market.getSigner(), market.contract.address())
88-
discard await token
89-
.approve(market.contract.address(), currentAllowance + amount)
90-
.confirm(1)
99+
let owner = await market.signer.getAddress()
100+
let spender = market.contract.address
101+
market.withAllowanceLock:
102+
let allowance = await token.allowance(owner, spender)
103+
discard await token.approve(spender, allowance + amount).confirm(1)
91104

92105
method loadConfig*(
93106
market: OnChainMarket

0 commit comments

Comments
 (0)