Skip to content

Commit

Permalink
fix(limit-order): limit max salt and amounts (#20)
Browse files Browse the repository at this point in the history
  • Loading branch information
vbrvk authored Apr 2, 2024
1 parent 7a831ab commit 231f7fe
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 4 deletions.
9 changes: 7 additions & 2 deletions src/limit-order/limit-order.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {AbiCoder} from 'ethers'
import {isHexString, UINT_160_MAX} from '@1inch/byte-utils'
import {isHexString, UINT_160_MAX, UINT_256_MAX} from '@1inch/byte-utils'
import assert from 'assert'
import {
buildOrderTypedData,
Expand All @@ -11,6 +11,7 @@ import {LimitOrderV4Struct, OrderInfoData} from './types'
import {MakerTraits} from './maker-traits'
import {Extension} from './extension'
import {Address} from '../address'
import {randBigInt} from '../utils/rand-bigint'

export class LimitOrder {
private static readonly Web3Type = `tuple(${[
Expand Down Expand Up @@ -54,6 +55,10 @@ export class LimitOrder {
this.receiver = orderInfo.receiver || Address.ZERO_ADDRESS
this.makerTraits = makerTraits

assert(this.salt <= UINT_256_MAX, 'salt too big')
assert(this.makingAmount <= UINT_256_MAX, 'makingAmount too big')
assert(this.takingAmount <= UINT_256_MAX, 'takingAmount too big')

if (!extension.isEmpty()) {
this.makerTraits.withExtension()
}
Expand All @@ -70,7 +75,7 @@ export class LimitOrder {
*/
static buildSalt(
extension: Extension,
baseSalt = BigInt(Math.round(Math.random() * Date.now()))
baseSalt = randBigInt((2n << 96n) - 1n)
): bigint {
if (extension.isEmpty()) {
return baseSalt
Expand Down
14 changes: 14 additions & 0 deletions src/utils/rand-bigint.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import {randBigInt} from './rand-bigint'

describe('randBigint', () => {
it('should generate rand bigint in correct interval', () => {
expect(randBigInt(1)).toBeGreaterThanOrEqual(0n)
expect(randBigInt(1)).toBeLessThanOrEqual(1n)

expect(randBigInt(10n)).toBeGreaterThanOrEqual(0)
expect(randBigInt(10n)).toBeLessThanOrEqual(10n)

expect(randBigInt(2n << 96n)).toBeGreaterThanOrEqual(0)
expect(randBigInt(2n << 96n)).toBeLessThanOrEqual(2n << 96n)
})
})
21 changes: 19 additions & 2 deletions src/utils/rand-bigint.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,20 @@
export function randBigInt(max: number): bigint {
return BigInt(Math.floor(Math.random() * max))
import {randomBytes} from 'ethers'

export function randBigInt(max: number | bigint): bigint {
let bytesCount = 0
max = BigInt(max) + 1n
let rest = max
while (rest) {
rest = rest >> 8n
bytesCount += 1
}

const bytes = randomBytes(bytesCount)

const val = bytes.reduce(
(acc, val, i) => acc + (BigInt(val) << BigInt(i * 8)),
0n
)

return val % max
}

0 comments on commit 231f7fe

Please sign in to comment.