# Write transactions

Every write is an Ethereum transaction to the Arkiv address that calls one function, `execute`. A call carries a batch of operations: creates, patches, extensions, ownership transfers and deletes. The node applies them in order, and either all of them apply or none do.

| Property | Value |
| --- | --- |
| Arkiv address | `0x4400000000000000000000000000000000000044`, on every Arkiv chain |
| Function | `execute((uint8 operation, bytes operationData)[] ops)` |
| Selector | `0x49650044` |
| Transaction value | `0` |

There’s no `arkiv_*` method for writes. Sign the transaction with any Ethereum library and send it with `eth_sendRawTransaction`.

## Operations

Each entry of `ops` is a tag and `operationData`, the `abi.encode` of the struct the tag selects:

```solidity
// 1: create
(uint128 salt, uint64 expiresAt, uint64 minLifetime,
  uint8 creationFlags, Attribute[] attributes)
// 2: patch
(bytes32 entityKey, Attribute[] mutations)
// 3: extend expiry
(bytes32 entityKey, uint64 expiresAt, uint64 minLifetime)
// 4: transfer ownership
(bytes32 entityKey, address newOwner)
// 5: delete
(bytes32 entityKey)
```

- **Create** doesn’t take a key. The node derives one, see [entity keys](#entity-keys)
- **Patch** changes only the attributes in `mutations` and leaves the others and the expiry as they are
- **Extend expiry** can’t move the expiry earlier. Extending to the current expiry changes nothing
- **Transfer ownership** can’t go to the zero address or the current owner

An operation that reverts reverts the whole batch. Each operation that applies emits one [event](#events).

## Attributes

An attribute is a name, a type and a value:

```solidity
struct Attribute { bytes32 name; uint8 typeId; bytes value; }
```

`name` is the ASCII name, left-aligned in 32 bytes and padded with zeros. It follows the [naming rules](https://stage.docs.arkiv.network/schemas/define/#naming-rules), and names that start with `$` are reserved.

The low 7 bits of `typeId` are the type. Bit 7, `0x80`, marks the attribute as indexed, so the node indexes it and queries can filter on it. An indexed `str` is `0x88`:

| `typeId` | Type | `value` |
| --- | --- | --- |
| `0` | Tombstone | Empty. Unsets the attribute in a patch |
| `1` | `bool` | 32 bytes, `0` or `1` |
| `2` | `i32` | 32 bytes, sign-extended |
| `3` | `u64` | 32 bytes |
| `4` | `u256` | 32 bytes |
| `5` | `dec` | 32 bytes, a signed integer of the value times 10^18 |
| `6` | Reserved | |
| `7` | `bytes` | Raw bytes, up to 128 KiB. Can’t be indexed |
| `8` | `str` | UTF-8, up to 128 bytes |
| `9` | `addr` | 32 bytes, the address right-aligned |
| `10` | `key` | 32 bytes, an entity key |

The 32-byte types use Solidity’s encoding of a single word. An attribute list must also follow these rules:

- Sorted in strictly ascending order by `name`, so each name appears once
- At most 32 attributes per operation
- Tombstones only in a patch

A [named schema](https://stage.docs.arkiv.network/schemas/define/#name-the-schema-after-your-project) tags each entity with an indexed `str` attribute, `arkiv.schema`. To write entities the SDK reads through that schema, include the tag.

## Expiry

Create and extend expiry carry two fields. The node resolves them to one block:

```text
expiry = max(expiresAt, currentBlock + minLifetime)
```

| You want | `expiresAt` | `minLifetime` |
| --- | --- | --- |
| A lifetime, such as 30 days | `0` | The lifetime in blocks: `1296000` |
| A deadline | The block | `0` |
| A deadline, but at least a lifetime | The block | The lifetime in blocks |

`currentBlock` is the block that includes the transaction, and a block takes 2 seconds. The expiry must be after `currentBlock` and at most 7,884,000 blocks past it, about 182.5 days. Anything else reverts.

## Creation flags

`creationFlags` is a bit field. It can’t change after the create:

| Bit | Flag |
| --- | --- |
| `0` | Read-only: the attributes can never change |
| `1` | Permissionless extension: any account can extend the expiry |
| `2` to `7` | Reserved, must be `0` |

## Entity keys

The node derives the key of a new entity from the chain, the owner, the owner’s entity nonce and the create’s salt:

```text
keccak256(abi.encodePacked(
  uint256 chainId, address arkiv, address owner, uint64 nonce, uint128 salt
))
```

A salt of `0` makes the key predictable to anyone. A random salt makes it predictable only to the creator.

The entity nonce counts the entities an account has created. It’s separate from the transaction nonce, and each create in a batch uses the next one. Read it with an `eth_call` of `entityNonce(address owner)`, selector `0x36917bfd`, on the Arkiv address. Set `OWNER` to the account’s address first:

```bash
curl "https://rpc.rabdi.db-chain.testnet.arkiv.network/$ARKIV_ACCESS_KEY" \
  -H "content-type: application/json" \
  --data @- <<EOF
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "eth_call",
  "params": [{
    "to": "0x4400000000000000000000000000000000000044",
    "data": "0x36917bfd000000000000000000000000${OWNER#0x}"
  }, "latest"]
}
EOF
```

<RpcTerms />

## Create an entity

This example builds the calldata of one create with [viem](https://viem.sh). The entity is a post of the `my-app.posts` schema, with three indexed attributes and two that aren’t. First, encode and sort the attributes:

```ts
import { type Hex, stringToHex, toHex } from "viem"

const INDEXED = 0x80
const attribute = (name: string, typeId: number, value: Hex) => ({
  name: toHex(name, { size: 32 }),
  typeId,
  value,
})
const score = 4_500_000_000_000_000_000n // 4.5 times 10^18

const attributes = [
  attribute("arkiv.schema", 8 | INDEXED, stringToHex("my-app.posts")),
  attribute("body", 7, stringToHex("My first entity.")),
  attribute("category", 8 | INDEXED, stringToHex("news")),
  attribute("score", 5 | INDEXED, toHex(score, { size: 32 })),
  attribute("title", 8, stringToHex("Hello, Arkiv")),
]
```

Then encode the create with a 30-day lifetime, and wrap it in an `execute` call:

```ts
import {
  encodeAbiParameters,
  encodeFunctionData,
  parseAbi,
  parseAbiParameters,
} from "viem"

const create = parseAbiParameters([
  "(uint128 salt, uint64 expiresAt, uint64 minLifetime, uint8 creationFlags,",
  "  (bytes32 name, uint8 typeId, bytes value)[] attributes)",
].join(""))
const operationData = encodeAbiParameters(create, [{
  salt: 0x1234n, // use 128 random bits
  expiresAt: 0n,
  minLifetime: 1_296_000n,
  creationFlags: 0,
  attributes,
}])

const data = encodeFunctionData({
  abi: parseAbi(["function execute((uint8, bytes)[] ops)"]),
  functionName: "execute",
  args: [[[1, operationData]]],
})
```

Send a transaction to the Arkiv address with `data` and a value of `0`. The receipt’s logs hold an `EntityCreated` event with the new key.

## Events

The Arkiv address emits one event per applied operation, in the order of the batch:

| Operation | Event |
| --- | --- |
| Create | `EntityCreated(bytes32 indexed entityKey, address indexed owner, uint64 expiresAt, uint8 creationFlags)` |
| Patch | `EntityPatched(bytes32 indexed entityKey, address indexed owner)` |
| Extend expiry | `ExpiryExtended(bytes32 indexed entityKey, address indexed owner, uint64 expiresAt)` |
| Transfer ownership | `OwnershipTransferred(bytes32 indexed entityKey, address indexed previousOwner, address indexed newOwner)` |
| Delete | `EntityDeleted(bytes32 indexed entityKey, address indexed owner)` |

`expiresAt` is the resolved expiry block. Read the events with `eth_getLogs` or `eth_subscribe`, filtered by the Arkiv address. A receipt doesn’t carry the keys `execute` returns, so read them from `EntityCreated`, or [predict them](#entity-keys).

## Errors

A failed operation reverts with an ABI-encoded custom error, which `eth_call` and `eth_estimateGas` also return:

| Error | When |
| --- | --- |
| `EmptyBatch()` | `ops` is empty |
| `InvalidOpType(uint8 operation)` | A tag isn’t 1 to 5 |
| `NonCanonicalOperationData(uint8 operation)` | `operationData` isn’t the standard ABI encoding of its struct |
| `AttributesNotSorted()` | The attributes aren’t strictly ascending by name |
| `TooManyAttributes(uint256 count, uint256 maxCount)` | An operation has more than 32 attributes |
| `EmptyMutations(bytes32 entityKey)` | A patch has no mutations |
| `TombstoneInCreate(bytes32 name)` | A create has a tombstone |
| `TombstoneValueNotEmpty(bytes32 name)` | A tombstone has a value |
| `SystemAttributeNotWritable(bytes32 name)` | A name starts with `$` |
| `InvalidValueType(bytes32 name, uint8 typeId)` | An unknown `typeId`, or a value that doesn’t fit its type |
| `Ident32Empty()` | A name is empty |
| `Ident32InvalidByte(uint256 position, bytes1 value)` | A name has a character the naming rules don’t allow |
| `EntityNotFound(bytes32 entityKey)` | No entity has the key |
| `EntityExpired(bytes32 entityKey, uint64 expiresAt)` | The entity has expired |
| `NotOwner(bytes32 entityKey, address caller, address owner)` | The sender doesn’t own the entity |
| `ReadOnlyEntity(bytes32 entityKey)` | A patch of a read-only entity |
| `ReservedCreationFlags(uint8 creationFlags)` | A reserved flag bit is set |
| `ExpiryDeadOnArrival(uint64 target, uint64 currentBlock)` | The expiry isn’t after the current block |
| `ExpiryBeyondMaxLifetime(uint64 target, uint64 currentBlock, uint64 maxLifetime)` | The expiry is more than `maxLifetime` blocks past the current block |
| `ExpiryNotExtended(bytes32 entityKey, uint64 newExpiresAt, uint64 currentExpiresAt)` | The new expiry is earlier than the current one |
| `TransferToZeroAddress(bytes32 entityKey)` | A transfer to the zero address |
| `TransferToSelf(bytes32 entityKey)` | A transfer to the current owner |