### Rust: Using Predefined Network Configurations for AlkahestClient Source: https://github.com/arkhai-io/alkahest/blob/main/sdks/rs/docs/CONFIG_MIGRATION.md Shows how to initialize an `AlkahestClient` with predefined network configurations in Rust. The 'before' example requires unwrapping Option types, whereas the 'after' example allows direct usage of predefined address constants for a cleaner approach. ```rust let config = DefaultExtensionConfig { arbiters_addresses: Some(BASE_SEPOLIA_ADDRESSES.arbiters_addresses.unwrap()), erc20_addresses: Some(BASE_SEPOLIA_ADDRESSES.erc20_addresses.unwrap()), // ... needed to handle Option and unwrap }; ``` ```rust // Direct usage - much cleaner! let client: DefaultAlkahestClient = AlkahestClient::new(private_key, rpc_url, Some(BASE_SEPOLIA_ADDRESSES)).await?; // Or for Filecoin let client: DefaultAlkahestClient = AlkahestClient::new(private_key, rpc_url, Some(FILECOIN_CALIBRATION_ADDRESSES)).await?; ``` -------------------------------- ### Rust: Creating AlkahestClient with Default Configuration Source: https://github.com/arkhai-io/alkahest/blob/main/sdks/rs/docs/CONFIG_MIGRATION.md Illustrates how to create an `AlkahestClient` with default configuration in Rust. The 'before' example shows initialization with `None` fields, while the 'after' examples demonstrate passing `None` directly or using `Default::default()` for cleaner instantiation. ```rust // Fields would be None, then unwrapped to Base Sepolia internally let config = DefaultExtensionConfig { arbiters_addresses: None, erc20_addresses: None, // ... all fields None }; let client = AlkahestClient::new(private_key, rpc_url, Some(config)).await?; ``` ```rust // Option 1: Pass None to use defaults let client: DefaultAlkahestClient = AlkahestClient::new(private_key, rpc_url, None).await?; // Option 2: Use Default::default() let client: DefaultAlkahestClient = AlkahestClient::new(private_key, rpc_url, Some(DefaultExtensionConfig::default())).await?; ``` -------------------------------- ### Rust: Creating Custom AlkahestClient Configuration Source: https://github.com/arkhai-io/alkahest/blob/main/sdks/rs/docs/CONFIG_MIGRATION.md Demonstrates creating a custom `AlkahestClient` configuration in Rust. The 'before' example uses `Some` and `None` for fields, while the 'after' example utilizes struct update syntax with `..` to merge custom values with default addresses, simplifying partial customization. ```rust let config = DefaultExtensionConfig { arbiters_addresses: Some(my_custom_arbiters), erc20_addresses: Some(my_custom_erc20), // Other fields might be None or Some(...) erc721_addresses: None, // Would fall back to Base Sepolia // ... }; ``` ```rust // Use struct update syntax for partial customization let config = DefaultExtensionConfig { arbiters_addresses: my_custom_arbiters, erc20_addresses: my_custom_erc20, // Use defaults for other fields ..BASE_SEPOLIA_ADDRESSES // or ..DefaultExtensionConfig::default() }; let client: DefaultAlkahestClient = AlkahestClient::new(private_key, rpc_url, Some(config)).await?; ``` -------------------------------- ### Rust: Updating Test Configurations for DefaultExtensionConfig Source: https://github.com/arkhai-io/alkahest/blob/main/sdks/rs/docs/CONFIG_MIGRATION.md Shows how to update test code in Rust when migrating `DefaultExtensionConfig`. The 'before' example initializes with `Some` for all fields, while the 'after' example directly initializes the fields without `Option`, reflecting the new non-Option structure. ```rust let addresses = DefaultExtensionConfig { arbiters_addresses: Some(ArbitersAddresses { eas: eas_address, // ... }), erc20_addresses: Some(Erc20Addresses { // ... }), // ... }; ``` ```rust let addresses = DefaultExtensionConfig { arbiters_addresses: ArbitersAddresses { eas: eas_address, // ... }, erc20_addresses: Erc20Addresses { // ... }, // ... }; ``` -------------------------------- ### Install Forge Standard Library Source: https://github.com/arkhai-io/alkahest/blob/main/contracts/lib/forge-std/README.md Command to install the Forge Standard Library using the Forge package manager. This is the first step to using the library in your Foundry projects. ```bash forge install foundry-rs/forge-std ``` -------------------------------- ### Install Dependencies using Bun Source: https://github.com/arkhai-io/alkahest/blob/main/contracts/script/utils/README.md Installs project dependencies using the Bun package manager. Ensure Bun is installed on your system before running this command. ```bash bun install ``` -------------------------------- ### Install Python SDK Source: https://github.com/arkhai-io/alkahest/blob/main/README.md This snippet shows how to install the Python SDK for Alkahest. It requires Python 3.10+ to be installed. Navigate to the Python SDK directory and install the package in editable mode. ```bash cd sdks/py pip install -e . ``` -------------------------------- ### Create Minimal AlkahestClient in Rust Source: https://github.com/arkhai-io/alkahest/blob/main/sdks/rs/docs/EXTENSION_SYSTEM.md Demonstrates the basic instantiation of an `AlkahestClient` in Rust without any extensions. This serves as the starting point for building a client with added functionalities. ```rust use alkahest_rs::AlkahestClient; let client = AlkahestClient::new( private_key, rpc_url ).await?; ``` -------------------------------- ### Build TypeScript SDK Source: https://github.com/arkhai-io/alkahest/blob/main/README.md This snippet outlines the steps to build the TypeScript SDK for Alkahest. It requires Node.js to be installed. Navigate to the TypeScript SDK directory, install dependencies, and run the build script. ```bash cd sdks/ts npm install npm run build ``` -------------------------------- ### Run Script using Bun Source: https://github.com/arkhai-io/alkahest/blob/main/contracts/script/utils/README.md Executes the main script (index.ts) using the Bun runtime. This command assumes dependencies have been installed. ```bash bun run index.ts ``` -------------------------------- ### Initialize AlkahestClient and Approve ERC20 Token (Python) Source: https://github.com/arkhai-io/alkahest/blob/main/sdks/py/README.md Demonstrates how to install the alkahest-py library, import the AlkahestClient, and instantiate it with private key and RPC URL. It then shows an asynchronous function to perform an ERC20 token approval, printing the resulting transaction hash. ```python from alkahest_py import AlkahestClient import asyncio client = AlkahestClient( "0xprivatekey", "https://rpc_url.com" ) async def main(): hash = client.erc20.approve( {"address": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", "value": 100}, "escrow", ) print(hash) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Initialize Alkahest Rust Client with Different Networks Source: https://github.com/arkhai-io/alkahest/blob/main/sdks/rs/docs/CONFIG_MIGRATION.md Shows how to initialize the Alkahest Rust client for Base Sepolia, Filecoin Calibration, and a custom configuration. It uses `DefaultAlkahestClient` and demonstrates passing different RPC endpoints and address configurations. Dependencies include `alkahest_rs` and `alloy`. ```rust use alkahest_rs::{ AlkahestClient, DefaultAlkahestClient, DefaultExtensionConfig, addresses::{BASE_SEPOLIA_ADDRESSES, FILECOIN_CALIBRATION_ADDRESSES}, }; use alloy::signers::local::PrivateKeySigner; #[tokio::main] async fn main() -> eyre::Result<()> { let private_key = PrivateKeySigner::random(); // Example 1: Use default (Base Sepolia) let client1: DefaultAlkahestClient = AlkahestClient::new(private_key.clone(), "https://sepolia.base.org", None).await?; // Example 2: Use Filecoin Calibration let client2: DefaultAlkahestClient = AlkahestClient::new( private_key.clone(), "https://api.calibration.node.glif.io/rpc/v1", Some(FILECOIN_CALIBRATION_ADDRESSES), ).await?; // Example 3: Custom configuration with some Filecoin addresses let custom_config = DefaultExtensionConfig { arbiters_addresses: FILECOIN_CALIBRATION_ADDRESSES.arbiters_addresses, erc20_addresses: FILECOIN_CALIBRATION_ADDRESSES.erc20_addresses, // Use Base Sepolia for the rest ..BASE_SEPOLIA_ADDRESSES }; let client3: DefaultAlkahestClient = AlkahestClient::new( private_key, "https://sepolia.base.org", Some(custom_config), ).await?; Ok(()) } ``` -------------------------------- ### Wire Asynchronous Oracle Components Together (TypeScript) Source: https://github.com/arkhai-io/alkahest/blob/main/docs/Writing Arbiters (pt 2 - Off-chain Oracles) (TypeScript).md This TypeScript function orchestrates the setup of an asynchronous oracle. It initializes shared state, starts the background worker, initiates the listener for arbiter events, and includes a placeholder for shutdown signal handling and cleanup. It requires an `AlkahestClient` instance. ```typescript async function runAsyncOracle(charlieClient: AlkahestClient) { // Step 4a: Initialize shared state const scheduler: SchedulerContext = { jobDb: new Map(), urlIndex: new Map(), waiters: [], }; schedulerContext = scheduler; // Map service URLs to fulfillment UIDs for lookup scheduler.urlIndex.set(serviceUrl, fulfillmentUid); // Step 4b: Start background worker const worker = startSchedulerWorker(scheduler, charlieClient.arbiters); // Step 4c: Start listener const listener = await charlieClient.arbiters.general.trustedOracle.listenAndArbitrate( // ... scheduling callback from Step 2 ... { mode: "unarbitrated" }, ); // Step 4d: Wait and cleanup // In production: keep running until shutdown signal await someShutdownSignal(); listener.unwatch(); worker.stop(); await worker.promise; schedulerContext = undefined; } ``` -------------------------------- ### Initialize AlkahestClient with All Base Extensions in Rust Source: https://github.com/arkhai-io/alkahest/blob/main/sdks/rs/docs/EXTENSION_SYSTEM.md Demonstrates initializing an `AlkahestClient` with all standard modules included using `with_base_extensions` in Rust. It shows usage with both default and custom configurations. ```rust use alkahest_rs::{AlkahestClient, DefaultExtensionConfig}; // Using default configuration (Base Sepolia) let client = AlkahestClient::with_base_extensions( private_key, rpc_url, None ).await?; // Using custom configuration let config = DefaultExtensionConfig { erc20_addresses: custom_erc20, erc721_addresses: custom_erc721, // ... other configurations }; let client = AlkahestClient::with_base_extensions( private_key, rpc_url, Some(config) ).await?; ``` -------------------------------- ### Set Theme and Initialize App (TypeScript) Source: https://github.com/arkhai-io/alkahest/blob/main/sdks/ts/docs/types/SignPermitProps.html This snippet demonstrates setting the theme from local storage or OS preference, hiding the body initially, and then showing the application page after a short delay. It handles potential app initialization logic. ```typescript localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => app ? app.showPage() : document.body.style.removeProperty("display"), 500) ``` -------------------------------- ### Create Direct Escrow with Custom Arbiter (Alice) Source: https://github.com/arkhai-io/alkahest/blob/main/docs/Escrow Flow (pt 1 - Token Trading).md Alice creates a direct escrow offering with a custom arbiter and demand. The `approve_and_create` function combines the approval and creation steps for flexibility in defining trade parameters. ```python # Can also use direct escrow/payment for custom demands (approve_and_create combines both steps) escrow = await alice_client.erc20.escrow.non_tierable.approve_and_create( {"address": usdc_token, "value": 1000000000}, {"arbiter": custom_arbiter, "demand": custom_demand}, 0 ) ``` -------------------------------- ### Example Usage of stdError for Expecting Reverts Source: https://github.com/arkhai-io/alkahest/blob/main/contracts/lib/forge-std/README.md Demonstrates how to use the stdError contract with Forge's `expectRevert` cheatcode to test for specific compiler builtin errors. This example shows testing an arithmetic error. ```solidity import "forge-std/Test.sol"; contract TestContract is Test { ErrorsTest test; function setUp() public { test = new ErrorsTest(); } function testExpectArithmetic() public { vm.expectRevert(stdError.arithmeticError); test.arithmeticError(10); } } contract ErrorsTest { function arithmeticError(uint256 a) public { uint256 a = a - 100; } } ``` -------------------------------- ### Configure Alkahest Client for Specific Networks in Rust Source: https://github.com/arkhai-io/alkahest/blob/main/sdks/rs/docs/EXTENSION_SYSTEM.md Shows how to initialize an `AlkahestClient` with pre-configured addresses for different networks, such as Base Sepolia and Filecoin Calibration. This simplifies network-specific setup by using provided constants. ```rust use alkahest_rs::addresses::{BASE_SEPOLIA_ADDRESSES, FILECOIN_CALIBRATION_ADDRESSES}; // Base Sepolia let client = AlkahestClient::with_base_extensions( private_key, rpc_url, Some(BASE_SEPOLIA_ADDRESSES) ).await?; // Filecoin Calibration let client = AlkahestClient::with_base_extensions( private_key, filecoin_rpc_url, Some(FILECOIN_CALIBRATION_ADDRESSES) ).await?; ``` -------------------------------- ### Initialize Theme and Show App (TypeScript) Source: https://github.com/arkhai-io/alkahest/blob/main/sdks/ts/docs/types/Erc721.html Initializes the document theme based on local storage and controls the initial display of the application. It sets the theme, hides the body, and then shows the app or removes the display property after a short delay. ```TypeScript document.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### Initialize Oracle Registry State (TypeScript) Source: https://github.com/arkhai-io/alkahest/blob/main/docs/Writing Arbiters (pt 2 - Off-chain Oracles) (TypeScript).md Initializes the oracle's internal state by populating the identity registry with known identities and their starting nonces. This function is intended to be run before the oracle listener starts processing requests. ```typescript async function runContextlessOracle(charlieClient: AlkahestClient) { // Step 2: Register known identities with starting nonces identityRegistry.set(identityAddress1, 0); identityRegistry.set(identityAddress2, 0); // In production: load from database // ... rest of oracle setup ... } ``` -------------------------------- ### Build Smart Contracts with Foundry Source: https://github.com/arkhai-io/alkahest/blob/main/README.md This snippet demonstrates how to build the Alkahest smart contracts using Foundry. It involves navigating to the contracts directory and executing the build command. Ensure Foundry is installed. ```bash cd contracts forge build ``` -------------------------------- ### getBlockTransactionCount Source: https://github.com/arkhai-io/alkahest/blob/main/sdks/ts/docs/functions/makeClient.html Gets the number of transactions in a block. ```APIDOC ## getBlockTransactionCount ### Description This method retrieves the number of transactions included in a specific block. ### Method GET ### Endpoint /getBlockTransactionCount ### Parameters #### Query Parameters - **args** (object) - Optional - Parameters for the transaction count request. ### Request Example ```json { "args": {} } ``` ### Response #### Success Response (200) - **number** (number) - The number of transactions in the block. #### Response Example ```json 100 ``` ``` -------------------------------- ### Create ERC-20 for ERC-20 Escrow with Permit (Alice) Source: https://github.com/arkhai-io/alkahest/blob/main/docs/Escrow Flow (pt 1 - Token Trading).md Alice creates an escrow offering for an ERC-20 for ERC-20 trade. The `permit_and_buy_erc20_for_erc20` function utilizes the permit mechanism for gasless approval of the ERC-20 tokens involved in the trade. ```python bid = {"address": usdc_token, "value": 1000} ask = {"address": eurc_token, "value": 900} # Alice creates escrow (permit handles approval) escrow = await alice_client.erc20.barter.permit_and_buy_erc20_for_erc20(bid, ask, 0) ``` -------------------------------- ### Get Balance Source: https://github.com/arkhai-io/alkahest/blob/main/sdks/ts/docs/functions/makeClient.html Retrieves the balance of an account. ```APIDOC ## GET /getBalance ### Description Retrieves the native currency balance of a specified account address. ### Method GET ### Endpoint /getBalance ### Parameters #### Query Parameters - **address** (string) - Required - The address of the account. - **chain** (Chain) - Optional - The chain to query the balance from. ### Response #### Success Response (200) - **balance** (bigint) - The balance of the account in the smallest unit of the native currency. #### Response Example ```json { "balance": 1000000000000000000n } ``` ``` -------------------------------- ### Get Block Source: https://github.com/arkhai-io/alkahest/blob/main/sdks/ts/docs/functions/makeClient.html Retrieves information about a specific block. ```APIDOC ## GET /getBlock ### Description Retrieves detailed information about a specific block on the blockchain, optionally including transactions. ### Method GET ### Endpoint /getBlock ### Parameters #### Query Parameters - **blockTag** (BlockTag) - Optional - The tag of the block to retrieve (e.g., "latest", "pending", or a block number). Defaults to "latest". - **includeTransactions** (boolean) - Optional - Whether to include transaction details in the response. Defaults to false. ### Response #### Success Response (200) - **blockInfo** (object) - An object containing detailed block information. - **baseFeePerGas** (bigint | null) - The base fee per gas. - **blobGasUsed** (bigint) - The amount of blob gas used. - **difficulty** (bigint) - The block difficulty. - **excessBlobGas** (bigint) - The excess blob gas. - **extraData** (string) - The extra data included in the block. - **gasLimit** (bigint) - The gas limit for the block. - **gasUsed** (bigint) - The amount of gas used in the block. - **hash** (string | null) - The hash of the block (null for pending blocks). - **logsBloom** (string | null) - The logs bloom filter (null for pending blocks). - **miner** (string) - The address of the miner. - **mixHash** (string) - The mix hash. - **nonce** (string | null) - The nonce (null for pending blocks). - **number** (bigint | null) - The block number (null for pending blocks). - **parentBeaconBlockRoot** (string) - The parent beacon block root. - **parentHash** (string) - The hash of the parent block. - **receiptsRoot** (string) - The root of the receipts. - **sealFields** (Array) - The seal fields. - **sha3Uncles** (string) - The SHA3 of the uncles. - **size** (bigint) - The size of the block. - **stateRoot** (string) - The root of the state. - **timestamp** (bigint) - The timestamp of the block. - **totalDifficulty** (bigint | null) - The total difficulty. - **transactions** (Array | null) - An array of transactions included in the block (if `includeTransactions` is true). #### Response Example ```json { "blockInfo": { "baseFeePerGas": 10000000000n, "blobGasUsed": 0n, "difficulty": 1234567890123456n, "excessBlobGas": 0n, "extraData": "0x...", "gasLimit": 30000000n, "gasUsed": 15000000n, "hash": "0x...", "logsBloom": "0x...", "miner": "0x...", "mixHash": "0x...", "nonce": "0x...", "number": 1234567n, "parentBeaconBlockRoot": "0x...", "parentHash": "0x...", "receiptsRoot": "0x...", "sealFields": ["0x..."], "sha3Uncles": "0x...", "size": 1234n, "stateRoot": "0x...", "timestamp": 1678886400n, "totalDifficulty": 1234567890123456n, "transactions": [ { "accessList": null, "authorizationList": null, "blobVersionedHashes": null, "blockHash": "0x...", "blockNumber": 1234567n, "chainId": 1, "from": "0x...", "gas": 21000n, "gasPrice": "10000000000", "hash": "0x...", "input": "0x", "maxFeePerBlobGas": null, "maxFeePerGas": null, "maxPriorityFeePerGas": null, "nonce": 0n, "r": "0x...", "s": "0x...", "to": "0x...", "transactionIndex": 0, "type": "legacy", "typeHex": "0x0", "v": 27n, "value": "1000000000000000000", "yParity": null } ] } } ``` ``` -------------------------------- ### Initialize Alkahest Client in Rust Source: https://github.com/arkhai-io/alkahest/blob/main/sdks/rs/README.md Demonstrates how to initialize an AlkahestClient using a private key and RPC URL. Currently, only Base Sepolia is supported, and the RPC URL must be a websocket connection (wss://...). ```rust use alkahest_rs::AlkahestClient; use std::env; pub async fn main() { let client = AlkahestClient::new( env::var("PRIVKEY")?.as_str(), env::var("RPC_URL")?.as_str(), None, ) .await?; } ``` -------------------------------- ### Get Transaction Receipt Source: https://github.com/arkhai-io/alkahest/blob/main/sdks/ts/docs/functions/makeClient.html Fetches the receipt for a given transaction. ```APIDOC ## POST /transactions/receipt ### Description Fetches the receipt for a given transaction. ### Method POST ### Endpoint `/transactions/receipt` ### Parameters #### Request Body - **args** (object) - Required - Parameters for fetching the transaction receipt. - **hash** (string) - Required - The hash of the transaction. ### Request Example ```json { "args": { "hash": "0xTransactionHash..." } } ``` ### Response #### Success Response (200) - **receipt** (object) - The transaction receipt object. (Structure depends on the specific blockchain and transaction type). #### Response Example ```json { "receipt": { "blockHash": "0xBlockHash...", "blockNumber": 12345, "contractAddress": null, "cumulativeGasUsed": 21000, "gasUsed": 21000, "logs": [], "logsBloom": "0x...", "status": "success", "to": "0xRecipientAddress...", "transactionHash": "0xTransactionHash...", "transactionIndex": 5 } } ``` ``` -------------------------------- ### Initialize Alkahest Client with Viem Source: https://github.com/arkhai-io/alkahest/blob/main/sdks/ts/docs/index.html Initializes an Alkahest client using Viem for account and chain management. Requires the Alkahest SDK and Viem to be installed. Currently supports only Base Sepolia chain. ```typescript import { makeClient } from "alkahest-ts"; import { privateKeyToAccount, nonceManager } from "viem/accounts"; import { baseSepolia } from "viem/chains"; const client = makeClient( privateKeyToAccount(process.env["PRIVKEY"] as `0x${string}`, { nonceManager, // automatic nonce management }), baseSepolia, process.env["RPC_URL"] as string, // RPC url for Base Sepolia ); ``` -------------------------------- ### Initialize Alkahest Client with Viem Source: https://github.com/arkhai-io/alkahest/blob/main/sdks/ts/README.md Initializes an Alkahest client using Viem. Requires a Viem wallet client configured with an account, chain (currently only Base Sepolia is supported), and transport. Automatic nonce management is included. ```typescript import { makeClient } from "alkahest-ts"; import { createWalletClient, http } from "viem"; import { privateKeyToAccount, nonceManager } from "viem/accounts"; import { baseSepolia } from "viem/chains"; const client = makeClient( createWalletClient({ account: privateKeyToAccount(process.env.PRIVKEY_ALICE as `0x${string}`, { nonceManager, // automatic nonce management }), chain: baseSepolia, transport: http(process.env.RPC_URL as string), // Base Sepolia RPC URL }), ); ``` -------------------------------- ### Get Transaction Source: https://github.com/arkhai-io/alkahest/blob/main/sdks/ts/docs/functions/makeClient.html Retrieves details for a specific transaction by its hash. ```APIDOC ## GET /getTransaction ### Description Retrieves details for a specific transaction by its hash. This endpoint provides comprehensive information about a transaction. ### Method GET ### Endpoint /getTransaction ### Parameters #### Query Parameters - **args** (GetTransactionParameters) - Required - Parameters including the transaction hash and optional block tag. - **blockTag** (BlockTag) - Optional - The block tag to specify which block's transaction to retrieve (e.g., 'latest', 'pending'). Defaults to 'latest'. ### Response #### Success Response (200) - **transaction** (object) - An object containing the transaction details. The structure varies based on the transaction type (legacy, EIP-1559, etc.) and whether it's pending or confirmed. #### Response Example (Legacy Transaction) ```json { "accessList": undefined, "authorizationList": undefined, "blobVersionedHashes": undefined, "blockHash": "0x...", "blockNumber": 12345, "chainId": 1, "from": "0x...", "gas": "0x...", "gasPrice": "0x...", "hash": "0x...", "input": "0x...", "maxFeePerBlobGas": undefined, "maxFeePerGas": undefined, "maxPriorityFeePerGas": undefined, "nonce": 0, "r": "0x...", "s": "0x...", "to": "0x...", "transactionIndex": 0, "type": "legacy", "typeHex": null, "v": "0x...", "value": "0x...", "yParity": undefined } ``` #### Response Example (EIP-1559 Transaction) ```json { "accessList": {}, "authorizationList": undefined, "blobVersionedHashes": undefined, "blockHash": "0x...", "blockNumber": 12345, "chainId": 1, "from": "0x...", "gas": "0x...", "gasPrice": "0x...", "hash": "0x...", "input": "0x...", "maxFeePerBlobGas": undefined, "maxFeePerGas": "0x...", "maxPriorityFeePerGas": "0x...", "nonce": 0, "r": "0x...", "s": "0x...", "to": "0x...", "transactionIndex": 0, "type": "eip1559", "typeHex": "0x2", "v": "0x1", "value": "0x...", "yParity": undefined } ``` ``` -------------------------------- ### Create Escrow (ERC-20 for ERC-721) using Barter Utils Source: https://github.com/arkhai-io/alkahest/blob/main/docs/Escrow Flow (pt 1 - Token Trading).md Demonstrates how Alice can create an escrow by offering an ERC-20 token in exchange for an ERC-721 token using the BarterUtils contract. It shows direct approval and the use of EIP-712 permits for gasless approval. ```solidity // Alice: Create escrow offering ERC-20 for ERC-721 using barter utils IERC20(usdcToken).approve(address(erc20BarterUtils), 1000e6); bytes32 escrowUid = erc20BarterUtils.buyErc721WithErc20( usdcToken, // bid token 1000e6, // bid amount erc721Token, // ask token 42, // ask token ID expiration ); // Or use permit for gasless approval (ERC-20 only) bytes32 escrowUid = erc20BarterUtils.permitAndBuyErc721WithErc20( usdcToken, 1000e6, erc721Token, 42, expiration, deadline, v, r, s // permit signature ); ``` ```typescript // Alice: Create escrow offering ERC-20 for ERC-721 (using permit for gasless approval) const { hash, attested } = await aliceClient.erc20.barter.permitAndBuyErc721WithErc20( { address: usdcToken, value: 1000000000n }, // bid { address: erc721Token, id: 42n }, // ask 0n, // no expiration ); // Can also use direct escrow/payment for custom demands (approveAndCreate combines both steps) const escrow = await aliceClient.erc20.escrow.nonTierable.approveAndCreate( { address: usdcToken, value: 1000000000n }, { arbiter: customArbiter, demand: customDemand }, 0n, ); ``` ```rust // Alice: Create escrow offering ERC-20 for ERC-721 (using permit for gasless approval) let bid = Erc20Data { address: usdc_token, value: U256::from(1000000000), }; let ask = Erc721Data { address: erc721_token, id: U256::from(42), }; let escrow_receipt = alice_client .erc20() .barter() .permit_and_buy_erc721_for_erc20(&bid, &ask, 0) .await?; let escrow_uid = DefaultAlkahestClient::get_attested_event(escrow_receipt)?.uid; // Can also use direct escrow/payment for custom demands (approve_and_create combines both steps) let escrow_receipt = alice_client .erc20() .escrow() .non_tierable() .approve_and_create( &bid, &ArbiterData { arbiter: custom_arbiter, demand: custom_demand, }, 0, ) .await?; ``` -------------------------------- ### Get Transaction Receipt Source: https://github.com/arkhai-io/alkahest/blob/main/sdks/ts/docs/functions/makeClient.html Retrieves the receipt for a given transaction. ```APIDOC ## GET /transactions/{transactionHash}/receipt ### Description Retrieves the receipt for a given transaction. ### Method GET ### Endpoint /transactions/{transactionHash}/receipt ### Parameters #### Path Parameters - **transactionHash** (string) - Required - The hash of the transaction. ### Request Example ```json { "transactionHash": "0xabc123..." } ``` ### Response #### Success Response (200) - **receipt** (object) - The transaction receipt object. Contains details like status, gas used, logs, etc. #### Response Example ```json { "receipt": { "status": "success", "gasUsed": 21000, "logs": [] } } ``` ``` -------------------------------- ### Get Transaction Confirmations Source: https://github.com/arkhai-io/alkahest/blob/main/sdks/ts/docs/functions/makeClient.html Fetches the number of confirmations for a given transaction. ```APIDOC ## POST /transactions/confirmations ### Description Fetches the number of confirmations for a given transaction. ### Method POST ### Endpoint `/transactions/confirmations` ### Parameters #### Request Body - **args** (object) - Required - Parameters for fetching transaction confirmations. - **hash** (string) - Required - The hash of the transaction. - **confirmsAtBlockTag** (string | number) - Optional - The block tag at which to check confirmations. ### Request Example ```json { "args": { "hash": "0xTransactionHash...", "confirmsAtBlockTag": "latest" } } ``` ### Response #### Success Response (200) - **confirmations** (bigint) - The number of confirmations for the transaction. #### Response Example ```json { "confirmations": 12n } ``` ``` -------------------------------- ### Get Proof Source: https://github.com/arkhai-io/alkahest/blob/main/sdks/ts/docs/functions/makeClient.html Retrieves a Merkle proof for a given transaction or state. ```APIDOC ## GET /getProof ### Description Retrieves a Merkle proof for a given transaction or state. This is essential for verifying the inclusion of data in a block. ### Method GET ### Endpoint /getProof ### Parameters #### Query Parameters - **args** (GetProofParameters) - Required - Parameters for generating the proof, typically including transaction hash or state key. ### Response #### Success Response (200) - **proof** (GetProofReturnType) - The Merkle proof data. #### Response Example ```json { "proof": [ "0x...", "0x..." ] } ``` ``` -------------------------------- ### Create ERC-20 for ERC-721 Escrow with Permit (Alice) Source: https://github.com/arkhai-io/alkahest/blob/main/docs/Escrow Flow (pt 1 - Token Trading).md Alice creates an escrow offering to buy an ERC-721 token using ERC-20 tokens. The `permit_and_buy_erc721_for_erc20` function handles the necessary approvals using the permit mechanism, allowing for gasless transactions. ```python bid = {"address": usdc_token, "value": 1000000000} ask = {"address": erc721_token, "id": 42} escrow = await alice_client.erc20.barter.permit_and_buy_erc721_for_erc20(bid, ask, 0) ``` -------------------------------- ### Get Gas Price Source: https://github.com/arkhai-io/alkahest/blob/main/sdks/ts/docs/functions/makeClient.html Fetches the current gas price on the network. ```APIDOC ## GET /getGasPrice ### Description Fetches the current gas price on the network. This is useful for estimating transaction costs. ### Method GET ### Endpoint /getGasPrice ### Parameters None ### Response #### Success Response (200) - **gasPrice** (bigint) - The current gas price in wei. #### Response Example ```json { "gasPrice": "100000000000" } ``` ``` -------------------------------- ### Get Transaction Count Source: https://github.com/arkhai-io/alkahest/blob/main/sdks/ts/docs/functions/makeClient.html Retrieves the transaction count for a given address. ```APIDOC ## GET /addresses/{address}/transaction-count ### Description Retrieves the transaction count for a given address. ### Method GET ### Endpoint /addresses/{address}/transaction-count ### Parameters #### Path Parameters - **address** (string) - Required - The address to retrieve the transaction count for. #### Query Parameters - **blockTag** (string) - Optional - The block tag to check the transaction count at (e.g., 'latest', 'earliest', 'pending'). ### Request Example ```json { "address": "0xabc123...", "blockTag": "latest" } ``` ### Response #### Success Response (200) - **transactionCount** (number) - The transaction count for the address. #### Response Example ```json { "transactionCount": 42 } ``` ``` -------------------------------- ### Python: Set up Oracle Listener and Cleanup Source: https://github.com/arkhai-io/alkahest/blob/main/docs/Writing Arbiters (pt 2 - Off-chain Oracles) (Python).md This Python code sets up an oracle listener that uses a decision function for validation and an optional callback for post-arbitration actions. It demonstrates how to initiate the listening process and includes cleanup for the identity registry. ```python # Assume oracle_client and identity_registry are defined elsewhere # from alkahest_py import ArbitrateOptions, ArbitrationMode # oracle_client = ... # identity_registry = {} # Define callback wrapper (client needs to be accessible) # The callback receives (attestation, demand) - we ignore demand for contextless validation def decision_function(attestation, demand): return verify_identity_decision(attestation, demand, oracle_client) def callback(decision): # Optional: called after arbitration is submitted on-chain # Useful for logging, notifications, or post-processing print(f"Arbitrated {decision.attestation.uid}: {decision.decision}") # Listen and validate async def listen_and_arbitrate(): options = ArbitrateOptions(ArbitrationMode.Unarbitrated) result = await oracle_client.oracle.listen_and_arbitrate_no_spawn( decision_function, callback, options, timeout_seconds=10.0 ) # Cleanup identity_registry.clear() # To run: # import asyncio # asyncio.run(listen_and_arbitrate()) ``` -------------------------------- ### Get Transaction Confirmations Source: https://github.com/arkhai-io/alkahest/blob/main/sdks/ts/docs/functions/makeClient.html Retrieves the number of confirmations for a given transaction. ```APIDOC ## GET /transactions/confirmations ### Description Retrieves the number of confirmations for a given transaction. ### Method GET ### Endpoint /transactions/confirmations ### Parameters #### Query Parameters - **transactionHash** (string) - Required - The hash of the transaction. - **blockTag** (string) - Optional - The block tag to check confirmations against (e.g., 'latest', 'earliest', 'pending'). ### Request Example ```json { "transactionHash": "0xabc123...", "blockTag": "latest" } ``` ### Response #### Success Response (200) - **confirmations** (bigint) - The number of confirmations for the transaction. #### Response Example ```json { "confirmations": 123 } ``` ``` -------------------------------- ### Test Smart Contracts with Foundry Source: https://github.com/arkhai-io/alkahest/blob/main/README.md This snippet shows how to run tests for the Alkahest smart contracts using Foundry. Navigate to the contracts directory and execute the test command. Foundry must be installed. ```bash cd contracts forge test ``` -------------------------------- ### Get Blob Base Fee Source: https://github.com/arkhai-io/alkahest/blob/main/sdks/ts/docs/functions/makeClient.html Retrieves the base fee for blob gas. ```APIDOC ## GET /getBlobBaseFee ### Description Retrieves the current base fee for blob gas, relevant for EIP-4844 transactions. ### Method GET ### Endpoint /getBlobBaseFee ### Response #### Success Response (200) - **blobBaseFee** (bigint) - The current base fee for blob gas. #### Response Example ```json { "blobBaseFee": 50000000000n } ``` ``` -------------------------------- ### Build Rust SDK Source: https://github.com/arkhai-io/alkahest/blob/main/README.md This snippet demonstrates how to build the Rust SDK for Alkahest. It requires the Rust toolchain to be installed. Navigate to the Rust SDK directory and execute the build command. ```bash cd sdks/rs cargo build ``` -------------------------------- ### Get Transaction Count Source: https://github.com/arkhai-io/alkahest/blob/main/sdks/ts/docs/functions/makeClient.html Retrieves the current transaction count for a given address. ```APIDOC ## POST /transactions/count ### Description Retrieves the current transaction count for a given address. ### Method POST ### Endpoint `/transactions/count` ### Parameters #### Request Body - **args** (object) - Required - Parameters for fetching the transaction count. - **address** (string) - Required - The address to query. - **blockTag** (string | number) - Optional - The block tag at which to query the transaction count. ### Request Example ```json { "args": { "address": "0xYourAddress...", "blockTag": "latest" } } ``` ### Response #### Success Response (200) - **count** (number) - The transaction count for the address. #### Response Example ```json { "count": 25 } ``` ``` -------------------------------- ### Get Storage At Source: https://github.com/arkhai-io/alkahest/blob/main/sdks/ts/docs/functions/makeClient.html Fetches the storage value at a specific storage slot for a given contract address. ```APIDOC ## GET /getStorageAt ### Description Fetches the storage value at a specific storage slot for a given contract address. This is useful for inspecting contract state. ### Method GET ### Endpoint /getStorageAt ### Parameters #### Query Parameters - **args** (GetStorageAtParameters) - Required - Parameters including the contract address and storage slot. ### Response #### Success Response (200) - **storageValue** (string) - The storage value in hexadecimal format. #### Response Example ```json { "storageValue": "0x..." } ``` ``` -------------------------------- ### permitAndBuyWithErc20 Source: https://github.com/arkhai-io/alkahest/blob/main/sdks/ts/docs/functions/makeClient.html Creates an escrow with ERC20 tokens using EIP-2612 permit. ```APIDOC ## POST /erc20/permitAndBuyWithErc20 ### Description Creates an escrow with ERC20 tokens using EIP-2612 permit. ### Method POST ### Endpoint /erc20/permitAndBuyWithErc20 ### Parameters #### Request Body - **price** (Erc20) - Required - The ERC20 token price. - **item** (Demand) - Required - The demand details. - **arbiter** (string) - The arbiter's address. - **demand** (string) - The encoded demand. - **expiration** (bigint) - Required - The expiration time for the permit. ### Request Example ```json { "price": {"address": "0x...", "value": 10n}, "item": {"arbiter": "0x...", "demand": "0x..."}, "expiration": 0n } ``` ### Response #### Success Response (200) - **attested** (object) - Attestation details. - **attester** (string) - The address of the attester. - **recipient** (string) - The recipient's address. - **schemaUID** (string) - The schema UID. - **uid** (string) - The unique identifier for the attestation. - **hash** (string) - The hash of the transaction. #### Response Example ```json { "attested": { "attester": "0x...", "recipient": "0x...", "schemaUID": "0x...", "uid": "0x..." }, "hash": "0x..." } ``` ``` -------------------------------- ### Get Gas Price Source: https://github.com/arkhai-io/alkahest/blob/main/sdks/ts/docs/functions/makeClient.html Retrieves the current gas price on the network. This is essential for estimating transaction fees. ```APIDOC ## GET /api/v1/gas/price ### Description Retrieves the current gas price on the network. This is essential for estimating transaction fees. ### Method GET ### Endpoint /api/v1/gas/price ### Response #### Success Response (200) - **gasPrice** (bigint) - The current gas price in Wei. #### Response Example ```json { "gasPrice": "100000000000" } ``` ``` -------------------------------- ### Get Transaction Source: https://github.com/arkhai-io/alkahest/blob/main/sdks/ts/docs/functions/makeClient.html Retrieves details for a specific transaction by its hash. Provides comprehensive information about a transaction's execution. ```APIDOC ## GET /api/v1/transactions/{hash} ### Description Retrieves details for a specific transaction by its hash. Provides comprehensive information about a transaction's execution. ### Method GET ### Endpoint /api/v1/transactions/{hash} ### Parameters #### Path Parameters - **hash** (string) - Required - The hash of the transaction to retrieve. #### Query Parameters - **blockTag** (BlockTag) - Optional - The block tag to specify which version of the transaction to retrieve (e.g., 'latest', 'pending'). Defaults to 'latest'. ### Response #### Success Response (200) - **Transaction** - An object containing the transaction details. The structure varies based on the transaction type (legacy, EIP-1559, etc.) and whether it's from a pending block. #### Response Example ```json { "blockHash": "0x...", "blockNumber": 12345, "chainId": 1, "from": "0x...", "gas": "0x5208", "gasPrice": "0x4a817c800", "hash": "0x...", "input": "0x...", "nonce": 0, "r": "0x...", "s": "0x...", "to": "0x...", "transactionIndex": 0, "type": "legacy", "typeHex": "0x0", "v": "0x1c", "value": "0xde0b6b3a7640000", "accessList": null } ``` ``` -------------------------------- ### Solidity: Logging with console.sol for Hardhat Compatibility Source: https://github.com/arkhai-io/alkahest/blob/main/contracts/lib/forge-std/README.md Shows how to use the standard `console.log` for logging, primarily for compatibility with Hardhat. Note that due to a known bug in `console.sol`, logs using `uint256` or `int256` types may not be properly decoded in Forge traces. It can be imported directly or indirectly via `forge-std/Test.sol`. ```solidity // import it indirectly via Test.sol import "forge-std/Test.sol"; // or directly import it import "forge-std/console.sol"; ... console.log(someValue); ``` -------------------------------- ### Get Proof Source: https://github.com/arkhai-io/alkahest/blob/main/sdks/ts/docs/functions/makeClient.html Retrieves a proof for a given transaction or state. This is commonly used in zero-knowledge proofs or state verification. ```APIDOC ## GET /api/v1/proof ### Description Retrieves a proof for a given transaction or state. This is commonly used in zero-knowledge proofs or state verification. ### Method GET ### Endpoint /api/v1/proof ### Parameters #### Query Parameters - **args** (GetProofParameters) - Required - Parameters for generating the proof. ### Response #### Success Response (200) - **GetProofReturnType** - The generated proof data. #### Response Example ```json { "proof": "0x..." } ``` ``` -------------------------------- ### Get Logs Source: https://github.com/arkhai-io/alkahest/blob/main/sdks/ts/docs/functions/makeClient.html Retrieves logs based on provided parameters, supporting various event and block filtering options. ```APIDOC ## GET /getLogs ### Description Retrieves logs based on provided parameters, supporting various event and block filtering options. This endpoint offers flexibility in querying blockchain event data. ### Method GET ### Endpoint /getLogs ### Parameters #### Query Parameters - **abiEvent** (AbiEvent) - Optional - The specific ABI event to filter logs by. - **abiEvents** (readonly AbiEvent[]) - Optional - An array of ABI events to filter logs by. - **strict** (boolean) - Optional - If true, enforces strict matching of event parameters. - **fromBlock** (bigint | BlockTag) - Optional - The starting block number or tag to filter logs from. - **toBlock** (bigint | BlockTag) - Optional - The ending block number or tag to filter logs up to. ### Response #### Success Response (200) - **logs** (Array) - An array of log objects matching the specified criteria. #### Response Example ```json { "logs": [ { "address": "0x...", "blockHash": "0x...", "blockNumber": 12345, "data": "0x...", "logIndex": 0, "removed": false, "topics": ["0x..."], "transactionHash": "0x...", "transactionIndex": 0 } ] } ``` ```