> For the complete documentation index, see [llms.txt](https://docs.stacks.co/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.stacks.co/cookbook/clarity/cryptography-and-security/generate-random-number.md).

# Generate random number

{% code fullWidth="false" expandable="true" %}

```clarity
(define-read-only (generate-random (block-height uint))
  (let (
    ;; Get block header hash
    (block-hash (unwrap! (get-stacks-block-info? id-header-hash block-height) (err u1001)))
    ;; Take a slice of the hash for randomness
    (hash-slice (unwrap-panic (slice? block-hash u16 u32)))
    ;; Convert to uint
    (random-value (buff-to-uint-be (unwrap-panic (as-max-len? hash-slice u16))))
  )
    (ok random-value)
  )
)

;; Generate random number in range
(define-read-only (random-in-range (block-height uint) (min uint) (max uint))
  (let (
    (random (try! (generate-random block-height)))
    (range (- max min))
  )
    (ok (+ min (mod random (+ u1 range))))
  )
)

;; Example: Random between 1-100
(random-in-range block-height u1 u100)
```

{% endcode %}

### Description

Create pseudo-random numbers using block hashes for randomness in smart contracts

### Use Cases

* Lottery and gaming contracts
* Random NFT trait generation
* Fair distribution mechanisms
* Random selection from lists

### Key Concepts

* **Block hashes** - Use historical block data as entropy source
* **Future blocks** - Cannot predict future block hashes
* **Commitment schemes** - Combine with commit-reveal for fairness
* Blockchain randomness is deterministic but unpredictable


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.stacks.co/cookbook/clarity/cryptography-and-security/generate-random-number.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
