# Plutus : Plutus.V1.Ledger Essentials

### 📌 Table of Contents

1. 📁 What Is `Plutus.V1.Ledger`?
2. 🧱 Core Modules Breakdown
3. 📬 Working with Addresses
4. 🔐 Working with Signatures & Keys
5. 💰 Working with Values
6. 🧾 Working with Transactions
7. 🧪 Script Contexts & Purpose
8. 🛠 Utilities (Time, Interval, etc.)
9. 🧠 Glossary of Terms
10. 🧪 Validator Script Examples
11. 🔧 Typed Validator Wrappers
12. 🧪 Emulator Trace Integration

***

### 1️⃣ 📁 What Is `Plutus.V1.Ledger`?

`Plutus.V1.Ledger` is a collection of types and utilities from the **Plutus smart contract platform** used to build secure, type-safe smart contracts for Cardano. It includes definitions for:

* Addresses
* Transactions
* Values
* Script contexts
* Signatures and more

***

### 2️⃣ 🧱 Core Modules Breakdown

| Module                     | Purpose                                 |
| -------------------------- | --------------------------------------- |
| `Address`                  | Work with Cardano addresses             |
| `Value`                    | Represent and manipulate tokens         |
| `Tx`, `TxInfo`             | Transaction and transaction context     |
| `Scripts`, `ScriptContext` | For writing validators                  |
| `Contexts`                 | Access to signatures, redeemers, datums |
| `Interval`, `Slot`, `Time` | Handling time and validity ranges       |

***

### 3️⃣ 📬 Working with Addresses

```haskell
import Plutus.V1.Ledger.Address
```

* **`Address`** is either a public key hash or a script hash.
* Use `scriptHashAddress` to create an address from a validator script hash.

```haskell
scriptAddr :: ValidatorHash -> Address
scriptAddr = scriptHashAddress
```

***

### 4️⃣ 🔐 Working with Signatures & Keys

```haskell
import Plutus.V1.Ledger.Crypto
```

* **`PubKeyHash`**: Identifies wallets.
* **`txSignedBy :: TxInfo -> PubKeyHash -> Bool`** checks if a transaction is signed by a given key.

***

### 5️⃣ 💰 Working with Values

```haskell
import Plutus.V1.Ledger.Value
```

* **`Value`** is a map of `CurrencySymbol -> TokenName -> Amount`.
* Use `singleton` to construct a token bundle:

```haskell
ada :: Value
ada = lovelaceValueOf 5000000
```

* Combine values using `+`, `-`, or `valueOf`.

***

### 6️⃣ 🧾 Working with Transactions

```haskell
import Plutus.V1.Ledger.Tx
```

* **`TxInfo`** gives all information about the transaction.
* Key fields:
  * `txInfoInputs`, `txInfoOutputs`
  * `txInfoSignatories`
  * `txInfoValidRange`

Use it in validators:

```haskell
{-# INLINABLE mkValidator #-}
mkValidator :: () -> () -> ScriptContext -> Bool
mkValidator _ _ ctx = txSignedBy info somePkh
  where info = scriptContextTxInfo ctx
```

***

### 7️⃣ 🧪 Script Contexts & Purpose

```haskell
import Plutus.V1.Ledger.Contexts
```

* **`ScriptContext`**: Execution context of a Plutus script.
* **`ScriptPurpose`**: Why the script is running (e.g., Spending, Minting).

```haskell
data ScriptPurpose = Spending TxOutRef | Minting CurrencySymbol | ...
```

* Access redeemer with `findOwnInput`, `findDatum`, etc.

***

### 8️⃣ 🛠 Utilities (Time, Interval, etc.)

```haskell
import Plutus.V1.Ledger.Interval
import Plutus.V1.Ledger.Time
```

* Use **`POSIXTime`** and **`POSIXTimeRange`** for timelocks.
* Example:

```haskell
validBeforeDeadline :: POSIXTime -> ScriptContext -> Bool
validBeforeDeadline dl ctx = to dl `contains` txInfoValidRange info
  where info = scriptContextTxInfo ctx
```

***

### 9️⃣ 🧠 Glossary of Terms

| Term             | Description                                        |
| ---------------- | -------------------------------------------------- |
| `Address`        | Script or wallet hash for locking funds            |
| `Value`          | Multi-asset bundle of tokens                       |
| `TxInfo`         | Transaction information (inputs, signers, outputs) |
| `ScriptContext`  | Runtime context passed to validators               |
| `PubKeyHash`     | Hash of wallet public key                          |
| `CurrencySymbol` | Identifier for a token type                        |
| `TokenName`      | Token label (e.g., "MyCoin")                       |
| `POSIXTime`      | UTC time representation                            |
| `Validator`      | Script that determines if a transaction is allowed |

***

### 🔟 🧪 Validator Script Examples

#### 🔐 Signature Check Validator

```haskell
{-# INLINABLE mkSigValidator #-}
mkSigValidator :: PubKeyHash -> () -> () -> ScriptContext -> Bool
mkSigValidator pkh _ _ ctx = txSignedBy (scriptContextTxInfo ctx) pkh
```

#### ⏰ Timelock Validator

```haskell
{-# INLINABLE mkTimeValidator #-}
mkTimeValidator :: POSIXTime -> () -> () -> ScriptContext -> Bool
mkTimeValidator deadline _ _ ctx = from deadline `contains` txInfoValidRange (scriptContextTxInfo ctx)
```

#### 💸 Minimum ADA Sent to Address

```haskell
{-# INLINABLE mkPaymentValidator #-}
mkPaymentValidator :: Address -> () -> () -> ScriptContext -> Bool
mkPaymentValidator addr _ _ ctx =
  any (\o -> txOutAddress o == addr && lovelaceValueOf (txOutValue o) >= 1000000) $ txInfoOutputs (scriptContextTxInfo ctx)
```

***

### 1️⃣1️⃣ 🔧 Typed Validator Wrappers

```haskell
data Basic
instance Scripts.ValidatorTypes Basic where
    type instance DatumType Basic = ()
    type instance RedeemerType Basic = ()

typedSigValidator :: PubKeyHash -> Scripts.TypedValidator Basic
typedSigValidator pkh = Scripts.mkTypedValidator @Basic
  ($$(PlutusTx.compile [|| mkSigValidator ||]) `PlutusTx.applyCode` PlutusTx.liftCode pkh)
  $$(PlutusTx.compile [|| Scripts.wrapValidator ||])
```

***

### 1️⃣2️⃣ 🧪 Emulator Trace Integration

```haskell
emulatorTraceExample :: EmulatorTrace ()
emulatorTraceExample = do
  let pkh = mockWalletPaymentPubKeyHash $ knownWallet 1
      val = Scripts.validatorScript $ typedSigValidator pkh
      addr = scriptAddress val
  h1 <- activateContractWallet (knownWallet 1) endpoints
  callEndpoint @"lock" h1 (addr, 5000000)
  void $ Emulator.waitNSlots 1
```

Use this with endpoints for `lock`/`spend` via `submitTxConstraints`.

***

### ✅ Summary

The `Plutus.V1.Ledger` module is **your toolkit** for interacting with the Cardano ledger when writing smart contracts. It provides powerful primitives to:

* Read transaction data
* Check authorization
* Work with tokens and addresses
* Enforce timelocks and intervals
