# Kilnfold — engine and Ore interaction guide

BNB Smart Chain, chain ID 56 (`0x38`). This document describes contract behavior, not permission to spend a user's funds. Read and preview first; submit only within the wallet owner's authorization. No token approval or message signature is needed for minting, revealing or harvesting.

## Contracts and verification

- Unique engine (ERC-721) contract: `0x9DD6f32DD0dF65fc0736cED0e7b7BFea30158b53`. [Verify source](https://bscscan.com/address/0x9DD6f32DD0dF65fc0736cED0e7b7BFea30158b53#code).
- Reward (ERC-20) contract: `0xA1090CC393585bf19bc604AB36a9316DF83172E4`; resolve the authoritative address using `ORE()` on the engine. [Verify reward source](https://bscscan.com/address/0xA1090CC393585bf19bc604AB36a9316DF83172E4#code).
- The engine has no owner, admin, pause, upgrade, withdrawal or setter; `owner()` returns zero. `PROCEEDS_TO()` is immutable. Prices, supply and wallet ceilings are constants. Payment is forwarded and unused BNB returned in the same transaction; failed forwarding/refunding reverts the whole transaction. Unknown selectors revert `NoSuchEntry(bytes4)`.
- The reward has a fixed `ORE_LIMIT()`, immutable `SOURCE()` equal to the engine, and `owner()` zero. Only that source can mint it. No tax, blacklist, pause or upgrade. No pool is created.
- Addresses are final and deployed on BNB Smart Chain. Before transacting, independently match the addresses, chain, code and source.

## Read current state

Read `mintStartsAt()`, `mintEndsAt()`, `rigSaleOpen()`, `MAX_SUPPLY()`, `totalMinted()`, `MAX_PER_WALLET()`, `mintedBy(wallet)`, `rigRoomOf(wallet)`, `freeAvailable(wallet)`, `rigIdKey(wallet)`, `freeTaken(agentKey)`, `RIG_LIFE()`, `CLAIM_BATCH()`, `SEED_LAG()` and `HISTORY_SPAN()` from the engine. Use a common block tag for a consistent snapshot.

Minting is permitted at `mintStartsAt <= block.timestamp < mintEndsAt`, while supply and the caller's cumulative mint allowance remain. Opening and closing are deployment timestamp plus constructor durations. Minting opened at `2026-11-21 09:45:43 (UTC+8)`; read the getters for live values.

The wallet must hold an Agent ID. `rigIdKey(wallet)` returns `(key, ok)`; key is `uint256(keccak256(bytes(handle)))`, with ownership checked in `HOLDER_BOOK()`. Do not substitute a human-readable handle or a sequential NFT ID for this key. One free engine per Agent ID, not per day. Wallet mint allowance is cumulative, including the free engine; transferring engines away does not reset it. The gift variants still charge the caller's Agent ID and wallet allowance.

### Reference constants, always re-read getters

The reviewed source has `MAX_SUPPLY = 10,000`, `MAX_PER_WALLET = 30`, and tier prices `TIER_A_PRICE = 0.0003 BNB` (wallet engines 2–10), `TIER_B_PRICE = 0.0006` (11–20), `TIER_C_PRICE = 0.0009` (21–30). `unitPrice(n)` returns the paid price of position n; even n=1 returns tier A, so **never use unitPrice(1) to price a free engine**. Use `rigsCost`/`rigsForValue` and `freeAvailable`.

## Complete entry map

All entries are payable. All require the caller's own Agent ID, an open mint window and remaining allowances. Value-zero entry succeeds only when the Agent ID's free engine is still available.

| Full signature | Selector | Meaning |
|---|---|---|
| `mintFree(uint256)` | `0xa4146733` | Same value-settled mint entry. Argument must equal caller's validated `rigIdKey` key. Value 0 takes the unused free engine; with BNB it also buys paid extras. Free already used: paid purchases still work. |
| `mint()` | `0x1249c58b` | Free engine first if unused, then settle paid extras by value. |
| `claim()` | `0x4e71d92d` | Same mint entry; **not an Ore harvest**. |
| `freeMint()` | `0x5b70ea9f` | Same value-settled mint entry. |
| `mintFree()` | `0x8ab53447` | Same value-settled mint entry. |
| `claimFree()` | `0xf366afc9` | Same value-settled mint entry. |
| `publicMint()` | `0x26092b83` | Same value-settled mint entry. |
| `agentMint()` | `0x1be3587a` | Same value-settled mint entry. |
| `mint(uint256)` | `0xa0712d68` | Same; quantity is for quoting only, not a settlement limit. |
| `freeMint(uint256)` | `0x7c928fe9` | Same; quantity is not a settlement limit. |
| `mint(uint256,address)` | `0x94bf804d` | Same, engines go to recipient; caller's ID and allowance apply. |
| `mint(address)` | `0x6a627842` | Same recipient semantics, no quantity. |
| `receive()` (empty calldata) | — | Plain BNB transfer, same as `mint()`. |

`mint(address,uint256)` is not an engine entry. Unknown selectors, including wrong overload shapes, revert without keeping BNB. Do not send a plain transfer with a 21,000 gas limit: contract execution is required.

## Settlement follows payment value / 照付款金额成交

For value-settled entries: grant the free engine first when unused, then buy as many engines as the supplied BNB covers, walking the caller's tier ladder from the cheapest next position. Stop at remaining supply or cumulative wallet cap. Return fractional change and cap-truncated excess **to the caller in the same transaction**. Quantity arguments, including 0 or a value above the cap, do not constrain this settlement. The same rule applies to `mintFree(uint256)`; its argument validates identity, not quantity.

- `rigsCost(address wallet,uint256 qty) -> uint256 cost`: total cost of the quoted number of engines, free first if eligible. Validates quantity/supply/wallet room, but is not a sale-open or identity gate.
- `rigsForValue(address wallet,uint256 value) -> (uint256 rigs,uint256 cost,uint256 refund)`: value-settled result for the current state. Returns `(0,0,value)` when closed or without an Agent ID; **this is not a successful refundable transaction**. The real call would revert. A zero-rig result can also indicate exhausted allowances or an insufficient payment.
- After the free engine is used, value 0 reverts `FreeUsed(nextRigPrice)`; payment below one paid engine reverts `PaymentShort(price,sent)`. Other errors include `IdentityMissing`, `OutsideWindow`, `WalletFull`, `AllRigsTaken`, `WrongAgentId`, `ProceedsRejected` and `RigChangeFailed`.

Examples using the reference tier A price, ample supply and allowance:

1. Fresh Agent ID and wallet: `mint(uint256)(1)`, value `0.0006 BNB` -> 3 engines (free + 2 paid), no refund. The argument 1 does not cap delivery.
2. Wallet already has its free engine: `mint(uint256)(5)`, value `0.0009 BNB` -> 3 engines, no refund; fewer than the quoted quantity.
3. Same wallet: value `0.000300000000000001 BNB` -> 1 paid engine, refund 1 wei. Value `0.000299999999999999` -> `PaymentShort`. Value `0.0006` -> 2 paid engines.
4. `mintFree(uint256)(ownKey)`, value `0.0006 BNB`, fresh eligible wallet -> 3 engines (1 free + 2 paid), no refund. Once free is used, this same entry can still buy paid engines.
5. A wallet with 29 prior engines paying `0.0018 BNB` -> at most one tier C engine, refund `0.0009 BNB`. Check remaining supply as well.

Always re-read `rigsForValue` immediately before simulation and submission; a prior quote is not a reservation. The entry has no minimum-output or max-quantity guard. The UI rechecks the preview, but chain state can still change before mining.

## Ore, grades, reveal and harvesting

Each engine accumulates **this project's Ore token (KFLDO), not BNB**, per second from its mint timestamp until `bornAt + RIG_LIFE`. It stops accumulating at expiry; any unclaimed amount remains claimable by the current holder after the mint window closes. There is no BNB conversion, buyback, return or liquidity promise. Unclaimed production travels with a transferred engine.

Use `rigInfo(uint256) -> (uint8 grade,uint256 perDay,uint256 bornAt,uint256 minesUntil,uint256 pending)` and `oreDue(uint256)` for current quantities. The UI reads these rather than estimating elapsed rewards. `ratePerDay(uint8)` returns 18-decimal token units. Reviewed distribution: Basic 65% / 100 Ore per day; Boosted 25% / 220; Turbo 9% / 500; Apex 1% / 1,500. Weighted mean of a timely revealed draw is 180/day. Rates must be read from getters; probabilities are source thresholds, not a getter. An expired or unavailable historical seed defaults to Basic, not the mean.

Grades use the hash of mint block + `SEED_LAG()` (reviewed 2). The hash can be read starting from mint block +3. A block producer can slightly influence it. Grade 0 is Sealed, not a guaranteed production rate. `gradeRigs(uint256[])` is permissionless and records readable grades; each later mint also sweeps old engines (`SWEEP_STEPS()`, reviewed 4). No off-chain keeper is required.

`BLOCKHASH` covers 256 blocks; the historical hash contract at `HISTORY()` may extend this to `HISTORY_SPAN()` (reviewed 8,191). If the hash is too old, or after the native hash window the history contract has no code, the engine defaults to Basic (read ratePerDay(1), reviewed 100/day). A temporarily unreadable hash remains sealed. Reveal or claim while the hash is readable; no wall-clock window is guaranteed.

| Full signature | Selector | Value | Meaning |
|---|---|---|---|
| `claim(uint256)` | `0x379607f5` | 0 | Harvest one currently owned engine. **Not a free mint entry.** |
| `claim(uint256[])` | `0x6ba4c138` | 0 | Harvest a nonempty array up to `CLAIM_BATCH()` (reviewed 50). |
| `gradeRigs(uint256[])` | `0x3d2253a3` | 0 | Permissionless reveal, at most `CLAIM_BATCH()` IDs. |

Harvest/reveal contract fees are zero; network gas still applies. Both harvest overloads are payable for explicit rejection handling: a nonzero value reverts ClaimTakesNoValue(). Always send value 0. Check `ownerOf(id)` equals the sending wallet before harvesting. A nonowner gets `NotYourRig(id)`; a zero-total harvest gets `NothingToClaim()`. Use distinct IDs. `paidTo` prevents claiming the same elapsed time twice. Reward `ORE_LIMIT()` is currently 1 billion Ore; `RIG_LIFE <= MAX_LIFE` (60 days) bounds even 10,000 Apex engines to 900 million Ore. Resolve the reward through `ORE()`; its restricted `mint(address,uint256)` is not a buyer entry.

## Gas and execution sequence

1. Match actual contracts and chain. Read state and identity, then `rigsCost` and `rigsForValue` at a recent block.
2. Construct the exact overload and value. Use integer wei (1 BNB = 10^18 wei), never floating point.
3. `eth_call` from the real wallet with the same calldata and value. If it reverts, stop and read the error.
4. `eth_estimateGas` for that transaction. Starting recommendations from the contract notes: value-zero entries 300,000; paid or mixed mint of **actual n delivered engines** `260,000 + 55,000*n`; harvest n `150,000 + 14,000*n`.
5. Use `max(recommendation, ceil(estimate*1.2))`. Reveal has no separately measured fixed formula; estimate it. The UI uses a provisional floor `150,000 + 30,000*n`, then the same estimate margin. Mint sweeps have not been separately measured at their worst case; these are limits, not gas-cost guarantees.
6. Show full from/to, chain, value, actual engines, refund, calldata and gas limit. Recheck the account, chain and quote. Submit only the reviewed transaction; no approvals or message signatures.
7. A transaction hash means submitted, not successful. Check receipt `status=1`; re-read ownership and balances. A wallet or RPC rejection must not be reported as a purchase.

Example with an ethers-style contract object (use the actual address and verified ABI in `api.json`):

```js
const qty = 3n;
const value = await engine['rigsCost(address,uint256)'](wallet, qty);
const [n, spent, refund] = await engine['rigsForValue(address,uint256)'](wallet, value);
// Inspect n/spent/refund; simulate with the authorized wallet before any submission.
await engine['mint(uint256)'].staticCall(qty, {value});
// When authorized, use the reviewed calldata/value and estimated gasLimit.
// Harvest explicitly: engine['claim(uint256[])']([1n, 2n], {value: 0n, gasLimit}).
```

Copyable review request: “On BNB Smart Chain 56, inspect the engine at 0x9DD6f32DD0dF65fc0736cED0e7b7BFea30158b53 and its ORE() reward contract. Read identity, window, allowances, rigsCost and rigsForValue. Preview mint(uint256) using the quoted wei value, show actual engines, refund, full addresses, gas and any authority changes. Execute only if authorized and the preview still matches; request no token approval.”
