# Verification Layer SDK

## API Reference

### `submit`

Submits a proof to the batcher to be verified and returns an aligned verification data struct.

```rust
pub async fn submit(
    network: Network,
    verification_data: &VerificationData,
    max_fee: U256,
    wallet: Wallet<SigningKey>,
    nonce: U256,
) -> Result<AlignedVerificationData, errors::SubmitError>
```

#### Arguments

* `network` - The network on which the proof will be submitted (`devnet | sepolia | mainnet | hoodi`)
* `verification_data` - The verification data for the proof.
* `max_fee` - The maximum fee that the submitter is willing to pay for the proof verification.
* `wallet` - The wallet used to sign the proof. Should be using correct chain id. See `get_chain_id`.
* `nonce` - The nonce of the submitter address. See `get_nonce_from_ethereum`.

#### Returns

* `Result<AlignedVerificationData, SubmitError>` - An aligned verification data or an error.

#### Errors

* `MissingRequiredParameter` if the verification data vector is empty.
* `ProtocolVersionMismatch` if the version of the SDK is lower than the expected one.
* `UnexpectedBatcherResponse` if the batcher doesn't respond with the expected message.
* `SerializationError` if there is an error deserializing the message sent from the batcher.
* `WebSocketConnectionError` if there is an error connecting to the batcher.
* `WebSocketClosedUnexpectedlyError` if the connection with the batcher is closed unexpectedly.
* `InvalidSignature` if the signature is invalid.
* `InvalidNonce` if the nonce is invalid.
* `InvalidMaxFee` if the max fee is invalid.
* `InvalidProof` if the proof is invalid.
* `ProofTooLarge` if the proof is too large.
* `InsufficientBalance` if the sender balance is not enough or unlocked
* `ProofQueueFlushed` if there is an error in the batcher and the proof queue is flushed.
* `NotAContract(address)` if you are trying to send to an address that is not a contract. This generally occurs if you have misconfigured the `environment` parameter.
* `ProofReplaced` if the proof has been replaced.
* `GenericError` if the error doesn't match any of the previous ones.

### `submit_multiple`

Submits multiple proofs to the batcher to be verified and returns an aligned verification data array.

```rust
pub async fn submit_multiple(
    network: Network,
    verification_data: &[VerificationData],
    max_fee: U256,
    wallet: Wallet<SigningKey>,
    nonce: U256,
) -> Result<Vec<AlignedVerificationData>, errors::SubmitError>
```

#### Arguments

* `network` - The network on which the proof will be submitted (`devnet | sepolia | mainnet | hoodi`)
* `verification_data` - A verification data array.
* `max_fee` - The maximum fee that the submitter is willing to pay for the verification for each proof.
* `wallet` - The wallet used to sign the proof. Should be using correct chain id. See `get_chain_id`.
* `nonce` - The nonce of the submitter address. See `get_nonce_from_ethereum`.

#### Returns

* `Result<Vec<AlignedVerificationData>, SubmitError>` - An aligned verification data array or an error.

#### Errors

* `MissingRequiredParameter` if the verification data vector is empty.
* `ProtocolVersionMismatch` if the version of the SDK is lower than the expected one.
* `UnexpectedBatcherResponse` if the batcher doesn't respond with the expected message.
* `SerializationError` if there is an error deserializing the message sent from the batcher.
* `WebSocketConnectionError` if there is an error connecting to the batcher.
* `WebSocketClosedUnexpectedlyError` if the connection with the batcher is closed unexpectedly.
* `InvalidSignature` if the signature is invalid.
* `InvalidNonce` if the nonce is invalid.
* `InvalidMaxFee` if the max fee is invalid.
* `InvalidProof` if the proof is invalid.
* `ProofTooLarge` if the proof is too large.
* `InsufficientBalance` if the sender balance is not enough or unlocked
* `ProofQueueFlushed` if there is an error in the batcher and the proof queue is flushed.
* `ProofReplaced` if the proof has been replaced.
* `GenericError` if the error doesn't match any of the previous ones.

### `submit_and_wait_verification`

Submits a proof to the batcher to be verified, waits for the verification on ethereum and returns an aligned verification data struct.

```rust
pub async fn submit_and_wait_verification(
    eth_rpc_url: &str,
    network: Network,
    verification_data: &VerificationData,
    max_fee: U256,
    wallet: Wallet<SigningKey>,
    nonce: U256,
) -> Result<AlignedVerificationData, errors::SubmitError>
```

#### Arguments

* `eth_rpc_url` - The URL of the Ethereum RPC node.
* `network` - The network on which the verification will be done (`devnet | sepolia | mainnet | hoodi`)
* `verification_data` - The verification data for the proof.
* `max_fee` - The maximum fee that the submitter is willing to pay for the proof verification.
* `wallet` - The wallet used to sign the proof. Should be using correct chain id. See `get_chain_id`.
* `nonce` - The nonce of the submitter address. See `get_nonce_from_ethereum`.

#### Returns

* `Result<AlignedVerificationData, SubmitError>` - An aligned verification data or an error.

#### Errors

* `MissingRequiredParameter` if the verification data vector is empty.
* `ProtocolVersionMismatch` if the version of the SDK is lower than the expected one.
* `UnexpectedBatcherResponse` if the batcher doesn't respond with the expected message.
* `SerializationError` if there is an error deserializing the message sent from the batcher.
* `WebSocketConnectionError` if there is an error connecting to the batcher.
* `WebSocketClosedUnexpectedlyError` if the connection with the batcher is closed unexpectedly.
* `EthereumProviderError` if there is an error in the connection with the RPC provider.
* `HexDecodingError` if there is an error decoding the Aligned service manager contract address.
* `BatchVerificationTimeout` if there is a timeout waiting for the batch verification.
* `InvalidSignature` if the signature is invalid.
* `InvalidNonce` if the nonce is invalid.
* `InvalidMaxFee` if the max fee is invalid.
* `InvalidProof` if the proof is invalid.
* `ProofTooLarge` if the proof is too large.
* `InsufficientBalance` if the sender balance is not enough or unlocked
* `ProofQueueFlushed` if there is an error in the batcher and the proof queue is flushed.
* `NotAContract(address)` if you are trying to send to an address that is not a contract. This generally occurs if you have misconfigured the `environment` parameter.
* `ProofReplaced` if the proof has been replaced.
* `GenericError` if the error doesn't match any of the previous ones.

### `submit_multiple_and_wait_verification`

Submits multiple proofs to the batcher for verification, waits for verification on Ethereum, and returns an array of `Result`s containing aligned verification data that indicates whether each proof was successfully submitted. If a timeout occurs while waiting for verification, an additional `Err` is appended to the end of the returned array.

```rust
pub async fn submit_multiple_and_wait_verification(
    eth_rpc_url: &str,
    network: Network,
    verification_data: &[VerificationData],
    max_fee: U256,
    wallet: Wallet<SigningKey>,
    nonce: U256
) -> Vec<Result<AlignedVerificationData, errors::SubmitError>>
```

#### Arguments

* `eth_rpc_url` - The URL of the Ethereum RPC node.
* `network` - The network on which the verification will be done (`devnet | sepolia | mainnet | hoodi`)
* `verification_data` - A verification data array.
* `max_fee` - The maximum fee that the submitter is willing to pay for the proof verification.
* `wallet` - The wallet used to sign the proof. Should be using correct chain id. See `get_chain_id`.
* `nonce` - The nonce of the submitter address. See `get_nonce_from_ethereum`.

#### Returns

* `Result<Vec<AlignedVerificationData>, SubmitError>` - An aligned verification data array or an error.

#### Errors

* `MissingRequiredParameter` if the verification data vector is empty.
* `ProtocolVersionMismatch` if the version of the SDK is lower than the expected one.
* `UnexpectedBatcherResponse` if the batcher doesn't respond with the expected message.
* `SerializationError` if there is an error deserializing the message sent from the batcher.
* `WebSocketConnectionError` if there is an error connecting to the batcher.
* `WebSocketClosedUnexpectedlyError` if the connection with the batcher is closed unexpectedly.
* `EthereumProviderError` if there is an error in the connection with the RPC provider.
* `HexDecodingError` if there is an error decoding the Aligned service manager contract address.
* `BatchVerificationTimeout` if there is a timeout waiting for the batch verification.
* `InvalidSignature` if the signature is invalid.
* `InvalidNonce` if the nonce is invalid.
* `InvalidMaxFee` if the max fee is invalid.
* `InvalidProof` if the proof is invalid.
* `ProofTooLarge` if the proof is too large.
* `InsufficientBalance` if the sender balance is not enough or unlocked
* `ProofQueueFlushed` if there is an error in the batcher and the proof queue is flushed.
* `NotAContract(address)` if you are trying to send to an address that is not a contract. This generally occurs if you have misconfigured the `environment` parameter.
* `ProofReplaced` if the proof has been replaced.
* `GenericError` if the error doesn't match any of the previous ones.

### `is_proof_verified`

Checks if the proof has been verified with Aligned and is included in the batch on-chain.

```rust
pub async fn is_proof_verified(
    aligned_verification_data: AlignedVerificationData,
    network: Network,
    eth_rpc_url: &str
) -> Result<bool, errors::VerificationError>
```

#### Arguments

* `aligned_verification_data` - The aligned verification data obtained when submitting the proofs.
* `network` - The network on which the verification will be done (`devnet | sepolia | mainnet | hoodi`)
* `eth_rpc_url` - The URL of the Ethereum RPC node.

#### Returns

* `Result<bool, VerificationError>` - A boolean indicating whether the proof was verified on-chain and is included in the batch or an error.

#### Errors

* `EthereumProviderError` if there is an error in the connection with the RPC provider.
* `EthereumCallError` if there is an error in the Ethereum call.
* `HexDecodingError` if there is an error decoding the Aligned service manager contract address.

### `get_nonce_from_ethereum`

Returns the nonce for a given address in Ethereum from aligned payment service contract. Note that it might be out of sync if you recently sent proofs. For that see [`get_nonce_from_batcher`](#get_nonce_from_batcher)

```rust
pub async fn get_nonce_from_ethereum(
    eth_rpc_url: &str,
    submitter_addr: Address,
    network: Network,
) -> Result<U256, errors::NonceError>
```

#### Arguments

* `eth_rpc_url` - The URL of the Ethereum RPC node.
* `submitter_addr` - The user address for which the nonce will be retrieved.
* `network` - The network from which the nonce will be retrieved.

#### Returns

* `Result<U256, NonceError>` - The nonce to use or an error.

#### Errors

* `EthRpcError` if the batcher has an error in the Ethereum call when retrieving the nonce if not already cached.

### `get_nonce_from_batcher`

Returns the next nonce for a given address from the batcher.

You should prefer this method instead of [`get_nonce_from_ethereum`](#get_nonce_from_ethereum) if you have recently sent proofs, as the batcher proofs might not yet be on ethereum, producing an out-of-sync nonce with the payment service contract on ethereum

```rust
pub async fn get_nonce_from_batcher(
    network: Network,
    address: Address,
) -> Result<U256, GetNonceError> {
```

#### Arguments

* `network` - The network from which the nonce will be retrieved.
* `address` - The user address for which the nonce will be retrieved.

#### Returns

* `Result<U256, NonceError>` - The next nonce of the proof submitter account.

#### Errors

* `EthRpcError` if the batcher has an error in the Ethereum call when retrieving the nonce if not already cached.

### `get_last_max_fee`

Retrieves the `max_fee` of the proof with the highest nonce in the batcher queue for a given address.

This value represents the maximum fee limit that can be used when submitting the next proof. To increase the fee limit for a new proof, you must first bump the fee of the previous proofs queued in the batcher.

Read more here: <https://docs.alignedlayer.com/architecture/1\\_proof\\_verification\\_layer/1\\_batcher#max-fee-priority-queue>

```rust
pub async fn get_last_max_fee(
    network: Network,
    address: Address,
) -> Result<U256, GetLastMaxFeeError>
```

#### Arguments

* `network` - The network from which to retrieve the last `max_fee`.
* `address` - The user address whose last `max_fee` will be retrieved.

#### Returns

* `Result<U256, GetLastMaxFeeError>` - The `max_fee` of the proof with the highest nonce for the given user, or `U256::MAX` if the user has no proofs in the queue.

#### Errors

* `ConnectionFailed` if there is an error connecting to the batcher.
* `ProtocolMismatch` if the protocol version doesn't match.
* `SerializationError` if there is an error serializing/deserializing the message.
* `InvalidRequest` if the request is invalid.
* `UnexpectedResponse` if the batcher responds with an unexpected message.
* `GenericError` if the error doesn't match any of the previous ones.

#### Notes

* Returns `U256::MAX` (2^256 - 1) when no proofs are present in the queue for the user.

### `get_chain_id`

Returns the chain ID for a given rpc url.

Should be used before submitting proofs to the batcher.

```rust
pub async fn get_chain_id(
  eth_rpc_url: &str
) -> Result<u64, errors::ChainIdError>
```

#### Arguments

* `eth_rpc_url` - The URL of the Ethereum RPC node.

#### Returns

* `Result<u64, ChainIdError>` - The chain ID to use or an error.

#### Errors

* `EthereumProviderError` if there is an error in the connection with the RPC provider.
* `EthereumCallError` if there is an error in the Ethereum call.

Wallet chain ID needs to be set with:

```rust
wallet = wallet.with_chain_id(chain_id);
```

### `estimate_fee`

Estimates the fee the user would have to pay for submitting a proof to Aligned. Depending on the priority the user wants to have in the batch, the `estimate` parameter can be set.

```rust
pub async fn estimate_fee(
    eth_rpc_url: &str,
    fee_estimation_type: FeeEstimationType,
) -> Result<U256, errors::MaxFeeEstimateError>
```

#### Arguments

* `eth_rpc_url` - The URL of the Ethereum RPC node.
* `fee_estimation_type` - Enum specifying the type of price estimate: Default, Instant. Custom(usize)

#### Returns

* `Result<U256, MaxFeeEstimateError>` - the estimated `max_fee` depending on the batch inclusion preference of the user.

#### Errors

* `EthereumProviderError` if there is an error in the connection with the RPC provider.
* `EthereumCallError` if there is an error in the Ethereum call.

### `estimate_fee_per_proof_with_rpc`

Returns the `fee_per_proof` based on the current gas price for a batch compromised of `num_proofs_per_batch`

```rust
pub async fn estimate_fee_per_proof_with_rpc(
    num_proofs_in_batch: usize,
    eth_rpc_url: &str,
) -> Result<U256, errors::FeeEstimateError>
```

#### Arguments

* `num_proofs_in_batch` - number of proofs within a batch.
* `eth_rpc_url` - The URL of the users Ethereum RPC node.

#### Returns

* `Result<U256, errors::FeeEstimateError>` - The fee per proof of a batch as a `U256`.

#### Errors

-`EthereumProviderError` if there is an error in the connection with the RPC provider. -`EthereumGasPriceError` if there is an error retrieving the Ethereum gas price.

### `calculate_fee_per_proof_with_gas_price`

Calculates the fee per proof based on a given batch size and gas price. This is a pure calculation function that doesn't make any network calls.

```rust
pub fn calculate_fee_per_proof_with_gas_price(
    num_proofs_in_batch: usize, 
    gas_price: U256
) -> U256
```

#### Arguments

* `num_proofs_in_batch` - number of proofs within a batch.
* `gas_price` - Current gas price (in wei).

#### Returns

* `U256` - The estimated fee per individual proof (in wei).

#### Notes

This function is used internally by both `estimate_fee` and `estimate_fee_per_proof_with_rpc`. It performs the core fee calculation logic without any network dependencies.

### `deposit_to_aligned`

Funds the batcher payment service in name of the signer.

```rust
pub async fn deposit_to_aligned(
    amount: U256,
    signer: SignerMiddleware<Provider<Http>, LocalWallet>,
    network: Network,
) -> Result<ethers::types::TransactionReceipt, errors::PaymentError> {
```

#### Arguments

`amount` - The amount to be paid. `signer` - The signer middleware of the payer. `network` - The network on which the payment will be done.

#### Returns

The receipt of the payment transaction.

#### Errors

`SendError` if there is an error sending the transaction. `SubmitError` if there is an error submitting the transaction. `PaymentFailed` if the payment failed.

### `get_balance_in_aligned`

Queries a User's balance that was deposited in Aligned

```rust
pub async fn get_balance_in_aligned(
    user: Address,
    eth_rpc_url: &str,
    network: Network,
) -> Result<U256, errors::BalanceError> {
```

#### Arguments

`user` - The address of the user. `eth_rpc_url` - The URL of the Ethereum RPC node. `network` - The network on which the balance will be checked.

#### Returns

* `Result<U256, errors::BalanceError>` - The balance of the user in the payment service.

#### Errors

* `EthereumProviderError` if there is an error in the connection with the RPC provider.
* `EthereumCallError` if there is an error in the Ethereum call.

### `lock_balance_in_aligned`

Locks the balance of a user in the Aligned payment service.

```rust
pub async fn lock_balance_in_aligned(
    signer: &SignerMiddleware<Provider<Http>, LocalWallet>,
    network: Network,
) -> Result<ethers::types::TransactionReceipt, errors::PaymentError>
```

#### Arguments

* `signer` - The signer middleware containing the user's wallet and provider.
* `network` - The network on which the lock operation will be performed.

#### Returns

* `Result<ethers::types::TransactionReceipt, errors::PaymentError>` - The transaction receipt of the lock operation.

#### Description

This function locks the user's balance, preventing it from being withdrawn. Locked balances can be used for proof verification payments but cannot be withdrawn until they are unlocked using `unlock_balance_in_aligned` and the lock period expires.

#### Errors

* `SendError` if there is an error sending the transaction.
* `SubmitError` if there is an error submitting the transaction.

### `unlock_balance_in_aligned`

Unlocks the balance of a user in the Aligned payment service.

```rust
pub async fn unlock_balance_in_aligned(
    signer: &SignerMiddleware<Provider<Http>, LocalWallet>,
    network: Network,
) -> Result<ethers::types::TransactionReceipt, errors::PaymentError>
```

#### Arguments

* `signer` - The signer middleware containing the user's wallet and provider.
* `network` - The network on which the unlock operation will be performed.

#### Returns

* `Result<ethers::types::TransactionReceipt, errors::PaymentError>` - The transaction receipt of the unlock operation.

#### Description

This function initiates an unlock request for the user's balance. After calling this function, the user's balance will be locked for a certain period before it can be withdrawn. Use `get_unlock_block_time` to check when the balance can be withdrawn.

#### Errors

* `SendError` if there is an error sending the transaction.
* `SubmitError` if there is an error submitting the transaction.

### `get_unlock_block_time`

Returns the timestamp when a user's balance will be unlocked and available for withdrawal.

```rust
pub async fn get_unlock_block_time(
    user: Address,
    eth_rpc_url: &str,
    network: Network,
) -> Result<u64, errors::BalanceError>
```

#### Arguments

* `user` - The address of the user to check the unlock time for.
* `eth_rpc_url` - The URL of the Ethereum RPC node.
* `network` - The network on which to check the unlock time.

#### Returns

* `Result<u64, errors::BalanceError>` - The timestamp when the user's balance will be unlocked.

#### Description

After calling `unlock_balance_in_aligned`, users must wait for the lock period before they can withdraw their funds using `withdraw_balance_from_aligned`.

#### Errors

* `EthereumProviderError` if there is an error in the connection with the RPC provider.
* `EthereumCallError` if there is an error in the Ethereum call.

### `withdraw_balance_from_aligned`

Withdraws a specified amount from the user's balance in the Aligned payment service.

```rust
pub async fn withdraw_balance_from_aligned(
    signer: &SignerMiddleware<Provider<Http>, LocalWallet>,
    network: Network,
    amount: U256,
) -> Result<ethers::types::TransactionReceipt, errors::PaymentError>
```

#### Arguments

* `signer` - The signer middleware containing the user's wallet and provider.
* `network` - The network on which the withdrawal will be performed.
* `amount` - The amount to withdraw from the user's balance.

#### Returns

* `Result<ethers::types::TransactionReceipt, errors::PaymentError>` - The transaction receipt of the withdrawal operation.

#### Description

This function can only be called after the balance has been unlocked using `unlock_balance_in_aligned` and the lock period has expired. Use `get_unlock_block_time` to check when the withdrawal becomes available.

#### Errors

* `SendError` if there is an error sending the transaction.
* `SubmitError` if there is an error submitting the transaction.

### `get_vk_commitment`

Returns the commitment for the verification key, taking into account the corresponding proving system.

```rust
pub fn get_vk_commitment(
    verification_key_bytes: &[u8],
    proving_system: ProvingSystemId,
) -> [u8; 32]
```

#### Arguments

* `verification_key_bytes` - The serialized contents of the verification key.
* `proving_system` - The corresponding proving system ID.

#### Returns

* `[u8; 32]` - The commitment.

#### Errors

* None.

### `save_response`

Saves AlignedVerificationData in a file.

```rust
pub fn save_response(
    batch_inclusion_data_directory_path: PathBuf,
    aligned_verification_data: &AlignedVerificationData,
) -> Result<(), errors::FileError>
```

#### Arguments

-`batch_inclusion_data_directory_path` - The path of the directory where the data will be saved. -`aligned_verification_data` - The aligned verification data to be saved.

#### Returns

* `Result<(), errors::FileError>` - Ok if the data is saved successfully.

#### Errors

* `FileError` if there is an error writing the data to the file.


---

# Agent Instructions: 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:

```
GET https://docs.alignedlayer.com/guides/1.2_sdk_api_reference.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
