### Code Examples and Patterns Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/SUMMARY.txt A collection of practical code examples and common usage patterns for the EAS SDK. ```APIDOC ## EAS SDK Code Examples and Patterns This section provides over 80 practical code examples demonstrating various ways to use the EAS SDK. ### Usage Examples Examples cover initialization, attestation creation (all variants), error handling, transaction management, batch operations, delegated operations, off-chain operations, and private data usage. ### Common Patterns Documentation for 25+ common patterns to help developers implement features efficiently. ``` -------------------------------- ### Get Attestation Usage Example Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/8-types-and-interfaces.md Demonstrates how to retrieve an attestation using its UID and log its creation and expiration times. ```typescript const attestation = await eas.getAttestation(uid); console.log(`Created: ${attestation.time}, Expires: ${attestation.expirationTime}`); ``` -------------------------------- ### Example Output for getSchema Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/README.md This is an example of the output structure returned by the `getSchema` function, showing the schema's UID, definition, resolver address, and revocability. ```json { uid: '0xYourSchemaUID', schema: 'bytes32 proposalId, bool vote', resolver: '0xResolverAddress', revocable: true } ``` -------------------------------- ### Install EAS SDK and ethers Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/README.md This command installs the EAS SDK along with the ethers.js library, which is a required dependency for interacting with Ethereum. ```bash npm install @ethereum-attestation-service/eas-sdk ethers ``` -------------------------------- ### Install EAS SDK with pnpm Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/README.md Install the EAS SDK using pnpm. This is a prerequisite for using the SDK in your project. ```sh pnpm add @ethereum-attestation-service/eas-sdk ``` -------------------------------- ### Install EAS SDK with npm Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/README.md Install the EAS SDK using npm. This is a prerequisite for using the SDK in your project. ```sh npm install @ethereum-attestation-service/eas-sdk ``` -------------------------------- ### Example Attestation Output Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/README.md This is an example of the attestation object returned by the getAttestation function, showing its properties. ```javascript { uid: '0x5134f511e0533f997e569dac711952dde21daf14b316f3cce23835defc82c065', schema: '0x27d06e3659317e9a4f8154d1e849eb53d43d91fb4f219884d1684f86d797804a', refUID: '0x0000000000000000000000000000000000000000000000000000000000000000', time: 1671219600, expirationTime: NO_EXPIRATION, revocationTime: 1671219636, recipient: '0xFD50b031E778fAb33DfD2Fc3Ca66a1EeF0652165', attester: '0x1e3de6aE412cA218FD2ae3379750388D414532dc', revocable: true, data: '0x0000000000000000000000000000000000000000000000000000000000000000' } ``` -------------------------------- ### Install EAS SDK with Yarn Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/README.md Install the EAS SDK using Yarn. This is a prerequisite for using the SDK in your project. ```sh yarn add @ethereum-attestation-service/eas-sdk ``` -------------------------------- ### Install ethers v6+ Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/9-errors-and-exceptions.md Upgrade the ethers library to version 6 or later to ensure compatibility with the EAS SDK. ```bash npm install ethers@^6.0.0 ``` -------------------------------- ### Create Off-Chain Attestation Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/README.md This example shows how to create and verify an off-chain attestation. This method does not record attestations on the blockchain but allows for signature verification. ```typescript const offchain = await eas.getOffchain(); const signedAttestation = await offchain.signOffchainAttestation( { schema: schemaUID, recipient: recipientAddress, time: BigInt(Math.floor(Date.now() / 1000)), expirationTime: NO_EXPIRATION, revocable: true, refUID: ZERO_BYTES32, data: encodedData }, signer ); // Verify the signature const isValid = offchain.verifyOffchainAttestationSignature( signerAddress, signedAttestation ); console.log('Off-chain attestation UID:', signedAttestation.uid); ``` -------------------------------- ### Transaction Flow Example Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/7-transaction-utilities.md Illustrates the typical steps involved in sending a transaction using the EAS SDK, from creation to result extraction. ```plaintext 1. Create transaction request eas.attest({...}) 2. (Optional) Estimate gas transaction.estimateGas() 3. Send and wait for mining transaction.wait(confirmations) 4. Extract results uid = result ``` -------------------------------- ### Import EAS SDK Components Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/0-index.md Import the main classes, constants, and types from the EAS SDK. Ensure you have the SDK installed. ```typescript // Main classes import { EAS, SchemaRegistry, SchemaEncoder, Offchain, PrivateData, EIP712Proxy } from '@ethereum-attestation-service/eas-sdk'; // Constants import { NO_EXPIRATION, ZERO_ADDRESS, ZERO_BYTES32 } from '@ethereum-attestation-service/eas-sdk'; // Types import { Attestation, AttestationRequest, SchemaRecord, OffchainAttestationVersion, SignedOffchainAttestation, MerkleValue, Signature } from '@ethereum-attestation-service/eas-sdk'; ``` -------------------------------- ### Connecting EAS with an ethers.js Signer Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/7-transaction-utilities.md Demonstrates how to connect the EAS SDK to an ethers.js signer for transaction submission. Ensure you have ethers.js installed and an initialized wallet. ```typescript import { ethers } from 'ethers'; const provider = ethers.getDefaultProvider('sepolia'); const signer = new ethers.Wallet(privateKey, provider); eas.connect(signer); ``` -------------------------------- ### Handle Transaction Confirmation Errors Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/9-errors-and-exceptions.md This example shows how to handle cases where a transaction does not produce a receipt, often indicating a failed transaction or network issue. It includes logic to check the transaction status on-chain if a confirmation error occurs. ```typescript try { const uid = await transaction.wait(); } catch (error) { if (error.message.includes('Unable to confirm')) { // Check transaction status on chain const receipt = await provider.getTransactionReceipt(txHash); if (receipt?.status === 0) { console.log('Transaction reverted'); } else { console.log('Transaction may still be pending'); } } } ``` -------------------------------- ### EAS SDK Initialization Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/SUMMARY.txt Demonstrates common patterns for initializing the EAS SDK. Ensure you have the necessary provider and chain ID configured. ```typescript import { EAS } from "@ethereum-attestation-service/eas.js"; // Example initialization with a provider and chain ID const eas = new EAS(provider, { chain: chainId, }); ``` -------------------------------- ### Initialize EAS SDK Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/README.md Import and initialize the EAS SDK with the contract address and connect a provider. Ensure you use a production-ready provider for live applications. ```javascript import { EAS, Offchain, SchemaEncoder, SchemaRegistry } from '@ethereum-attestation-service/eas-sdk'; import { ethers } from 'ethers'; export const EASContractAddress = '0xC2679fBD37d54388Ce493F1DB75320D236e1815e'; // Sepolia v0.26 // Initialize the SDK with the address of the EAS Schema contract address const eas = new EAS(EASContractAddress); // Gets a default provider (in production use something else like infura/alchemy) const provider = ethers.getDefaultProvider('sepolia'); // Connects an ethers style provider/signingProvider to perform read/write functions. // MUST be a signer to do write operations! eas.connect(provider); ``` -------------------------------- ### Get Delegated Helper Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/1-eas-core.md Retrieves the Delegated attestation helper. This is cached after the first call. ```typescript const delegated = await eas.getDelegated(); ``` -------------------------------- ### Get Offchain Helper Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/1-eas-core.md Retrieves the Offchain attestation helper. This is cached after the first call. ```typescript const offchain = await eas.getOffchain(); ``` -------------------------------- ### Connect to Supported Networks with ethers.js Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/10-configuration-and-constants.md Use `ethers.getDefaultProvider` for Sepolia and Mainnet, or `ethers.JsonRpcProvider` for other networks like Arbitrum, Optimism, or custom RPC endpoints. ```typescript import { ethers } from 'ethers'; // Sepolia testnet const provider = ethers.getDefaultProvider('sepolia'); // Mainnet const provider = ethers.getDefaultProvider('mainnet'); // Arbitrum const provider = new ethers.JsonRpcProvider('https://arb1.arbitrum.io/rpc'); // Optimism const provider = new ethers.JsonRpcProvider('https://mainnet.optimism.io'); // Custom RPC const provider = new ethers.JsonRpcProvider('https://custom-rpc-url'); ``` -------------------------------- ### Get Revocation Type Hash Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/1-eas-core.md Returns the EIP-712 type hash specifically for revocations. ```typescript const revokeTypeHash = await eas.getRevokeTypeHash(); ``` -------------------------------- ### Get Attestation Type Hash Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/1-eas-core.md Returns the EIP-712 type hash specifically for attestations. ```typescript const attestTypeHash = await eas.getAttestTypeHash(); ``` -------------------------------- ### Get EIP-712 Domain Separator Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/1-eas-core.md Returns the EIP-712 domain separator used for signatures. ```typescript const domainSeparator = await eas.getDomainSeparator(); ``` -------------------------------- ### Get Nonce for Address Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/1-eas-core.md Retrieves the current nonce for a given address, used in delegated operations. ```typescript const nonce = await eas.getNonce(address); ``` -------------------------------- ### Get Timestamp for Data Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/1-eas-core.md Retrieves the timestamp for a given bytes32 data. Returns 0 if not timestamped. ```typescript const timestamp = await eas.getTimestamp(data); ``` -------------------------------- ### Initialize SchemaRegistry with Signer Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/10-configuration-and-constants.md Create an instance of SchemaRegistry with the registry address and an optional signer. The signer is used for transaction signing. ```typescript import { SchemaRegistry } from '@ethereum-attestation-service/eas-sdk'; const schemaRegistry = new SchemaRegistry(registryAddress, { signer: signer }); ``` -------------------------------- ### Register and use a schema Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/3-schema-registry.md Demonstrates how to register a new schema using the SchemaRegistry and then use the obtained schema UID to create an attestation with the EAS contract. Requires connecting to the SchemaRegistry and EAS contracts with a signer. ```typescript import { SchemaRegistry, EAS, SchemaEncoder, NO_EXPIRATION } from '@ethereum-attestation-service/eas-sdk'; const schemaRegistry = new SchemaRegistry(registryAddress); schemaRegistry.connect(signer); // Register schema const schemaTx = await schemaRegistry.register({ schema: 'string name, uint256 age', revocable: true }); const schemaUID = await schemaTx.wait(); console.log('Schema registered:', schemaUID); // Now use it to create attestations const eas = new EAS(easAddress); eas.connect(signer); const schemaEncoder = new SchemaEncoder('string name, uint256 age'); const encodedData = schemaEncoder.encodeData([ { name: 'name', value: 'Alice', type: 'string' }, { name: 'age', value: 30, type: 'uint256' } ]); const attestationTx = await eas.attest({ schema: schemaUID, data: { recipient: recipientAddress, expirationTime: NO_EXPIRATION, revocable: true, data: encodedData } }); const attestationUID = await attestationTx.wait(); ``` -------------------------------- ### Get EAS Contract Version Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/1-eas-core.md Retrieve the deployed version of the EAS contract. This is useful for compatibility checks. ```typescript const version = await eas.getVersion(); console.log('EAS Version:', version); // e.g., "0.26" ``` -------------------------------- ### Instantiate Offchain with Version 1 Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/4-offchain.md Use this to specify an older version of off-chain attestations for legacy integrations. Ensure your configuration object is correctly set up. ```typescript const offchain = new Offchain(config, OffchainAttestationVersion.Version1); ``` -------------------------------- ### Get SchemaRegistry Version Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/3-schema-registry.md Retrieve the semantic version of the SchemaRegistry contract. This method does not require a connected signer. ```typescript const version = await schemaRegistry.getVersion(); console.log('SchemaRegistry Version:', version); ``` -------------------------------- ### Instantiate SchemaRegistry Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/3-schema-registry.md Create an instance of the SchemaRegistry class. Connect a signer for write operations. ```typescript import { SchemaRegistry } from '@ethereum-attestation-service/eas-sdk'; const schemaRegistryAddress = '0x0a7E2Ff54e76B8E6659aedc9103FB21c038050D0'; const schemaRegistry = new SchemaRegistry(schemaRegistryAddress); const signer = new ethers.Wallet(privateKey, provider); schemaRegistry.connect(signer); ``` -------------------------------- ### Creating an Attestation Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/SUMMARY.txt Shows how to create a basic attestation. This involves specifying the schema UID, recipient, data, and expiration. ```typescript const schemaUid = "0x..."; const recipient = "0x..."; const data = "0x..."; // Encoded data matching the schema const expiration = 0; // 0 for no expiration const tx = await eas.attest({ schema: schemaUid, data: { recipient: recipient, data: data, }, // expiration: expiration, // Optional: specify expiration time }); await tx.wait(); ``` -------------------------------- ### Get Off-chain Attestation Revocation Timestamp Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/1-eas-core.md Retrieves the revocation timestamp for an off-chain attestation. Returns 0 if not revoked. ```typescript const revocationTimestamp = await eas.getRevocationOffchain(user, uid); ``` -------------------------------- ### Get Schema UID Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/0-index.md Computes a bytes32 identifier for a schema based on the schema string, resolver, and revocability settings. ```typescript const schemaUID = SchemaRegistry.getSchemaUID(schema, resolver, revocable); ``` -------------------------------- ### Gas Optimization Tips Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/7-transaction-utilities.md Provides practical advice for optimizing gas usage when interacting with the blockchain via the EAS SDK. ```APIDOC ## Gas Optimization Tips 1. **Batch operations** — Use `multiAttest()` instead of multiple `attest()` calls 2. **Estimate first** — Check gas before sending if budget is tight 3. **Gas price** — Set appropriate `gasPrice` in overrides based on network conditions 4. **Delegate calls** — Use delegation if a relayer is paying ``` -------------------------------- ### Delegated Operations Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/0-index.md Workflow for performing delegated attestations, involving getting helpers, attester signing, and relayer submission. ```APIDOC ## EAS.getDelegated() ### Description Gets a helper for delegated operations. ### Method EAS.getDelegated ### Returns [See 1-eas-core.md#getdelegated] ``` ```APIDOC ## Delegated.signDelegatedAttestation() ### Description Attester signs a delegated attestation. ### Method Delegated.signDelegatedAttestation ### Returns [See 5-delegated-attestations.md#signdelegatedattestation] ``` ```APIDOC ## EAS.attestByDelegation() ### Description Relayer submits a delegated attestation. ### Method EAS.attestByDelegation ### Returns [See 1-eas-core.md#attestbydelegation] ``` ```APIDOC ## EAS.multiAttestByDelegation() ### Description Relayer submits multiple delegated attestations. ### Method EAS.multiAttestByDelegation ### Returns [See 1-eas-core.md#multiatestbydelegation] ``` -------------------------------- ### Initialize EAS with Options Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/10-configuration-and-constants.md Instantiate the EAS class with an address and optional configuration. Provide a signer for immediate transaction capabilities or connect one later. An EIP712Proxy can also be optionally included for delegated operations. ```typescript import { EAS } from '@ethereum-attestation-service/eas-sdk'; import { ethers } from 'ethers'; const provider = ethers.getDefaultProvider('sepolia'); const signer = new ethers.Wallet(privateKey, provider); // With options const eas = new EAS(easAddress, { signer: signer, proxy: eip712Proxy // Optional }); // Without options (connect later) const eas = new EAS(easAddress); eas.connect(signer); ``` -------------------------------- ### Batch Attestation Creation Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/SUMMARY.txt Demonstrates how to create multiple attestations in a single transaction for efficiency. This requires preparing an array of attestation requests. ```typescript const attestations = [ { schema: "0x...", data: { recipient: "0x...", data: "0x...", }, }, { schema: "0x...", data: { recipient: "0x...", data: "0x...", }, }, ]; const tx = await eas.attestBatch(attestations); await tx.wait(); ``` -------------------------------- ### Get Attestation UID Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/0-index.md Computes a deterministic bytes32 identifier for an attestation using its parameters. This UID uniquely identifies the attestation. ```typescript const uid = EAS.getAttestationUID( schema, recipient, attester, time, expirationTime, revocable, refUID, data, bump ); ``` -------------------------------- ### static verifyMultiProof(root, proof) Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/6-private-data.md Statically verifies if a given Merkle multi-proof is valid against a specified Merkle root. ```APIDOC ### `static verifyMultiProof(root: string, proof: MerkleMultiProof): boolean` Verifies that a multi-proof is valid for a given Merkle root. **Parameters:** #### Parameters - **root** (string) - Required - The Merkle root to verify against - **proof** (MerkleMultiProof) - Required - The proof to verify **Returns:** `boolean` — True if proof is valid, false otherwise ### Request Example ```typescript const isValid = PrivateData.verifyMultiProof(fullTree.root, multiProof); console.log('Proof is valid:', isValid); ``` ``` -------------------------------- ### Encode IPFS Hash to Bytes32 Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/2-schema-encoder.md Statically encodes an IPFS hash string (starting with 'Qm') into a bytes32 hexadecimal format. ```typescript const encoded = SchemaEncoder.encodeQmHash('QmZNzRdFJt2R9NLGNVKfDzHHFKqgRXWS5VZv4KGXJwCXz'); console.log(encoded); // 0x... ``` -------------------------------- ### SchemaRegistry Constructor Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/3-schema-registry.md Initializes a new SchemaRegistry instance. You can optionally connect a signer or provider for write operations during initialization or later using the `connect` method. ```APIDOC ## Constructor ```typescript constructor(address: string, options?: SchemaRegistryOptions) ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | address | string | Yes | — | The contract address of the SchemaRegistry | | options.signer | `TransactionSigner \| TransactionProvider` | No | undefined | A signer or provider for write operations | ### Example ```typescript import { SchemaRegistry } from '@ethereum-attestation-service/eas-sdk'; const schemaRegistryAddress = '0x0a7E2Ff54e76B8E6659aedc9103FB21c038050D0'; const schemaRegistry = new SchemaRegistry(schemaRegistryAddress); const signer = new ethers.Wallet(privateKey, provider); schemaRegistry.connect(signer); ``` ``` -------------------------------- ### Create On-Chain Attestation Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/README.md This snippet demonstrates how to create a basic on-chain attestation using the EAS SDK. Ensure you have set up your provider, signer, and EAS instance, and have encoded your data according to the schema. ```typescript import { EAS, SchemaEncoder, NO_EXPIRATION } from '@ethereum-attestation-service/eas-sdk'; import { ethers } from 'ethers'; // Setup const provider = ethers.getDefaultProvider('sepolia'); const signer = new ethers.Wallet(privateKey, provider); const eas = new EAS('0xC2679fBD37d54388Ce493F1DB75320D236e1815e'); eas.connect(signer); // Encode data const schemaEncoder = new SchemaEncoder('uint256 eventId, string title'); const encodedData = schemaEncoder.encodeData([ { name: 'eventId', value: 1, type: 'uint256' }, { name: 'title', value: 'My Event', type: 'string' } ]); // Create attestation const tx = await eas.attest({ schema: '0xb16fa048b0d597f5a821747eba64efa4762ee5143e9a80600d0005386edfc995', data: { recipient: '0xFD50b031E778fAb33DfD2Fc3Ca66a1EeF0652165', expirationTime: NO_EXPIRATION, revocable: true, data: encodedData } }); const uid = await tx.wait(); console.log('Attestation UID:', uid); ``` -------------------------------- ### Initialize EAS and SchemaRegistry Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/0-index.md Initialize the EAS and SchemaRegistry instances, connecting them to an ethers.js provider and signer. This is the first step before interacting with the EAS network. ```typescript import { EAS, SchemaRegistry } from '@ethereum-attestation-service/eas-sdk'; import { ethers } from 'ethers'; const provider = ethers.getDefaultProvider('sepolia'); const signer = new ethers.Wallet(privateKey, provider); const eas = new EAS('0xC2679fBD37d54388Ce493F1DB75320D236e1815e'); eas.connect(signer); const schemaRegistry = new SchemaRegistry('0x0a7E2Ff54e76B8E6659aedc9103FB21c038050D0'); schemaRegistry.connect(signer); ``` -------------------------------- ### Private Data Usage Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/SUMMARY.txt Provides an example of how to handle private data within attestations. This typically involves encryption and decryption steps. ```typescript // Assuming 'encryptedData' is obtained from a secure source const schemaUid = "0x..."; const recipient = "0x..."; const tx = await eas.attest({ schema: schemaUid, data: { recipient: recipient, data: encryptedData, // Use encrypted data }, }); await tx.wait(); // Later, to decrypt: // const decryptedData = await eas.decryptAttestationData(attestation); ``` -------------------------------- ### Configure Ethers Providers for Mainnet Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/10-configuration-and-constants.md Set up ethers providers for the Ethereum mainnet using different methods, including default, JSON RPC, Alchemy, or a local network. ```typescript import { ethers } from 'ethers'; // Default provider (uses Etherscan, Infura, Alchemy in fallback order) const provider = ethers.getDefaultProvider('mainnet'); // Specific provider const provider = new ethers.JsonRpcProvider('https://rpc.ankr.com/eth'); // With API key const provider = new ethers.AlchemyProvider('sepolia', apiKey); // Local network const provider = new ethers.JsonRpcProvider('http://localhost:8545'); ``` -------------------------------- ### Get Attestation by UID Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/README.md Retrieve an on-chain attestation using its unique identifier (UID). This function returns an object with attestation details. ```javascript import { EAS, NO_EXPIRATION } from '@ethereum-attestation-service/eas-sdk'; const eas = new EAS(EASContractAddress); eas.connect(provider); const uid = '0xff08bbf3d3e6e0992fc70ab9b9370416be59e87897c3d42b20549901d2cccc3e'; const attestation = await eas.getAttestation(uid); console.log(attestation); ``` -------------------------------- ### Share Selective Disclosure Proof Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/6-private-data.md Illustrates how to package private data, an attestation UID, and a selective disclosure proof for sharing with a recipient. The recipient can then verify the proof locally. ```typescript // Create attestation with Merkle root const fullTree = privateData.getFullTree(); // Later, prove only certain fields to a third party const multiProof = privateData.generateMultiProof([0, 2]); // name and verified const disclosure = { merkleRoot: fullTree.root, attestationUID: attestationUID, proof: multiProof, revealedData: multiProof.leaves }; // Share as JSON const json = JSON.stringify(disclosure); // Send to recipient... // Recipient can verify the proof const verified = PrivateData.verifyMultiProof( disclosure.merkleRoot, disclosure.proof ); ``` -------------------------------- ### Create and Verify Off-chain Attestation Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/4-offchain.md Demonstrates creating, signing, and verifying an off-chain attestation without an on-chain call. Ensure EAS contract address, provider, schema UID, recipient address, and signer are correctly configured. ```typescript import { EAS, NO_EXPIRATION, SchemaEncoder } from '@ethereum-attestation-service/eas-sdk'; const eas = new EAS(EASContractAddress); eas.connect(provider); const offchain = await eas.getOffchain(); // Create attestation const signedAttestation = await offchain.signOffchainAttestation( { schema: schemaUID, recipient: recipientAddress, time: BigInt(Math.floor(Date.now() / 1000)), expirationTime: NO_EXPIRATION, revocable: true, refUID: ZERO_BYTES32, data: encodedData }, signer ); // Verify without on-chain call const isValid = offchain.verifyOffchainAttestationSignature( await signer.getAddress(), signedAttestation ); console.log('Valid:', isValid); console.log('UID:', signedAttestation.uid); // Share the attestation JSON const attestationJSON = JSON.stringify(signedAttestation); ``` -------------------------------- ### Timestamp Arbitrary Data Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/README.md Use the `timestamp` function to create a timestamp for any piece of data. The data should be encoded appropriately, for example, using `ethers.encodeBytes32String`. ```javascript import { EAS } from '@ethereum-attestation-service/eas-sdk'; const eas = new EAS(EASContractAddress); eas.connect(provider); const data = ethers.encodeBytes32String('0x1234'); const transaction = await eas.timestamp(data); // Optional: Wait for transaction to be validated await transaction.wait(); ``` -------------------------------- ### Get Attestation by UID Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/1-eas-core.md Fetch the full details of an on-chain attestation using its unique identifier (UID). Ensure the UID is valid and exists. ```typescript const uid = '0x5134f511e0533f997e569dac711952dde21daf14b316f3cce23835defc82c065'; const attestation = await eas.getAttestation(uid); console.log(attestation); ``` -------------------------------- ### Configure Ethers Providers Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/10-configuration-and-constants.md Set up ethers providers for different network services like Alchemy, Infura, or the default provider. Ensure necessary API keys or environment variables are configured. ```typescript import { ethers } from 'ethers'; // Using Alchemy (set ALCHEMY_API_KEY env var) const provider = new ethers.AlchemyProvider('sepolia', process.env.ALCHEMY_API_KEY); // Using Infura (set INFURA_API_KEY env var) const provider = new ethers.InfuraProvider('sepolia', process.env.INFURA_API_KEY); // Using getDefaultProvider (requires ETHERSCAN_API_KEY for better results) const provider = ethers.getDefaultProvider('sepolia'); const signer = new ethers.Wallet(process.env.PRIVATE_KEY, provider); eas.connect(signer); ``` -------------------------------- ### Use Valid Offchain Attestation Versions Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/9-errors-and-exceptions.md When creating an Offchain instance, ensure you use a supported version. Versions greater than 2 are not supported. ```typescript const offchain = new Offchain(config, OffchainAttestationVersion.Version2); ``` -------------------------------- ### Get Full Merkle Tree from Private Data Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/README.md Retrieve the complete Merkle tree, including the root hash and all values with their associated salts, from a `PrivateData` instance. ```javascript const fullTree = privateData.getFullTree(); console.log('Merkle Root:', fullTree.root); ``` -------------------------------- ### Configure Ethers Signers Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/10-configuration-and-constants.md Create ethers signers from a private key, a mnemonic phrase, or an encrypted JSON keystore file. Ensure the provider is connected. ```typescript // From private key const signer = new ethers.Wallet(privateKey, provider); // From mnemonic const mnemonic = 'word word word ...'; const hdWallet = ethers.HDNodeWallet.fromMnemonic( ethers.Mnemonic.fromPhrase(mnemonic) ); const signer = hdWallet.connect(provider); // From encrypted JSON (keystore) const keystoreJson = require('./wallet.json'); const signer = await ethers.Wallet.fromEncryptedJson( JSON.stringify(keystoreJson), password, provider ); ``` -------------------------------- ### Get Schema Information using EAS SDK Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/README.md Retrieve schema details by its UID using the `getSchema` function. Connect your provider to the SchemaRegistry instance before querying. ```javascript import { SchemaRegistry } from "@ethereum-attestation-service/eas-sdk"; const schemaRegistryContractAddress = "0x0a7E2Ff54e76B8E6659aedc9103FB21c038050D0"; // Sepolia 0.26 const schemaRegistry = new SchemaRegistry(schemaRegistryContractAddress); schemaRegistry.connect(provider); const schemaUID = "0xYourSchemaUID"; const schemaRecord = await schemaRegistry.getSchema({ uid: schemaUID }); console.log(schemaRecord); ``` -------------------------------- ### Create Delegated Attestation (Sponsored) Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/README.md This snippet illustrates how to create a delegated attestation where the attester signs the attestation, and a relayer pays the gas fees to submit it. This is useful for sponsoring attestation creation for users. ```typescript const delegated = await eas.getDelegated(); // Attester signs const signature = await delegated.signDelegatedAttestation( { schema: schemaUID, recipient: recipientAddress, expirationTime: NO_EXPIRATION, revocable: true, refUID: ZERO_BYTES32, data: encodedData, deadline: NO_EXPIRATION, value: 0n }, signer ); // Relayer submits (different account, relayer pays gas) eas.connect(relayerSigner); const tx = await eas.attestByDelegation({ schema: schemaUID, data: { recipient: recipientAddress, expirationTime: NO_EXPIRATION, revocable: true, data: encodedData }, signature: signature.sig.signature, attester: signerAddress, deadline: NO_EXPIRATION }); const uid = await tx.wait(); ``` -------------------------------- ### Bytes32 String Representation in EAS SDK Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/8-types-and-interfaces.md Shows examples of fields that are represented as strings but are expected to be bytes32 hex values. This is common for identifiers like UIDs and hashes. ```typescript uid: string; // Actually a bytes32, e.g., "0x5134f511..." refUID: string; // bytes32 hex dataHash: string; // bytes32 hex ``` -------------------------------- ### Get Delegated Helper - EAS SDK Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/5-delegated-attestations.md Obtain an instance of the `Delegated` helper class from the EAS SDK. This class is used for EIP-712 signing of delegated attestations and revocations. ```typescript const delegated = await eas.getDelegated(); // or synchronously if already initialized: const delegated = eas.getDelegated(); ``` -------------------------------- ### Verify Offchain Attestation Onchain Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/9-errors-and-exceptions.md This snippet demonstrates how to sign an off-chain attestation and enable on-chain verification. It highlights common causes of verification failure, such as schema non-existence, invalid recipient addresses, or resolver rejections. ```typescript const signedAttestation = await offchain.signOffchainAttestation( { schema: schemaUID, recipient: recipientAddress, time: BigInt(Math.floor(Date.now() / 1000)), expirationTime: NO_EXPIRATION, revocable: true, refUID: ZERO_BYTES32, data: encodedData }, signer, { verifyOnchain: true } // Enable verification ); // Common causes: // - Schema doesn't exist // - Recipient address is invalid // - Resolver contract rejects the attestation // - Referenced attestation (refUID) doesn't exist ``` -------------------------------- ### Configure Off-chain Attestation Options Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/10-configuration-and-constants.md Set default options for off-chain attestations. `verifyOnchain` can be set to `false` for faster operations or `true` to simulate on-chain verification and catch errors early. ```typescript const DEFAULT_OFFCHAIN_ATTESTATION_OPTIONS = { verifyOnchain: false }; ``` -------------------------------- ### Reuse Provider and Signer Instances Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/10-configuration-and-constants.md For efficiency, reuse `provider` and `signer` instances across multiple EAS and SchemaRegistry operations. This avoids redundant setup and connection overhead. ```typescript // Reuse provider and signer instances const provider = ethers.getDefaultProvider('sepolia'); const signer = new ethers.Wallet(privateKey, provider); const eas = new EAS(easAddress); eas.connect(signer); // Reuse for multiple operations const schemaRegistry = new SchemaRegistry(registryAddress); schemaRegistry.connect(signer); // Same signer ``` -------------------------------- ### Wait for Transaction Confirmation and Check Status Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/7-transaction-utilities.md Waits for a transaction to be confirmed and checks its status. Access the transaction receipt to get details like block number and success status. ```typescript await transaction.wait(); if (transaction.receipt?.status === 1) { console.log('Transaction succeeded'); console.log('Block:', transaction.receipt.blockNumber); } ``` -------------------------------- ### Creating Attestations (Off-chain) Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/0-index.md Methods for signing and verifying off-chain attestations using the EAS SDK. ```APIDOC ## Offchain.signOffchainAttestation() ### Description Signs an off-chain attestation. ### Method Offchain.signOffchainAttestation ### Returns [See 4-offchain.md#signoffchainattestation] ``` ```APIDOC ## Offchain.verifyOffchainAttestationSignature() ### Description Verifies the signature of an off-chain attestation. ### Method Offchain.verifyOffchainAttestationSignature ### Returns [See 4-offchain.md#verifyoffchainattestation] ``` -------------------------------- ### Delegated Attestations Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/SUMMARY.txt Shows how to create attestations on behalf of another address using delegated permissions. This requires a signature from the delegator. ```typescript const schemaUid = "0x..."; const recipient = "0x..."; const data = "0x..."; const deadline = Math.floor(Date.now() / 1000) + 3600; // 1 hour from now const signature = await eas.signDelegatedAttestation({ schema: schemaUid, recipient: recipient, data: data, deadline: deadline, // ethstoreAddress: "0x...", // Optional: specify the EAS contract address }); const tx = await eas.attestDelegated({ schema: schemaUid, recipient: recipient, data: data, deadline: deadline, signature: signature, }); await tx.wait(); ``` -------------------------------- ### Get Full Merkle Tree Data Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/6-private-data.md Retrieve the complete Merkle tree, including the root hash and all values with their associated salts. This data is essential for generating proofs and for attestation encoding. ```typescript const fullTree = privateData.getFullTree(); console.log('Merkle Root:', fullTree.root); console.log('Values with Salts:', fullTree.values); // Use the root in an attestation const schemaEncoder = new SchemaEncoder('bytes32 privateData'); const encodedData = schemaEncoder.encodeData([ { name: 'privateData', value: fullTree.root, type: 'bytes32' } ]); ``` -------------------------------- ### Initialize EAS SDK Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/1-eas-core.md Instantiate the EAS class with the contract address and connect a provider for read-only operations. ```typescript import { EAS } from '@ethereum-attestation-service/eas-sdk'; import { ethers } from 'ethers'; const EASContractAddress = '0xC2679fBD37d54388Ce493F1DB75320D236e1815e'; const eas = new EAS(EASContractAddress); const provider = ethers.getDefaultProvider('sepolia'); eas.connect(provider); ``` -------------------------------- ### Timestamp Usage in EAS SDK Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/8-types-and-interfaces.md Demonstrates the representation of time values as Unix timestamps (seconds since epoch) in the EAS SDK. Includes examples for current time, no expiration, and specific revocation times. ```typescript time: BigInt(Math.floor(Date.now() / 1000)) expirationTime: 0n // No expiration revocationTime: 1671219636n ``` -------------------------------- ### Create an On-chain Attestation Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/0-index.md Encode attestation data using SchemaEncoder and then submit the attestation to the EAS network. This creates an on-chain record of the attestation. The transaction must be waited upon to get the attestation UID. ```typescript const schemaEncoder = new SchemaEncoder('uint256 id, string data'); const encodedData = schemaEncoder.encodeData([ { name: 'id', value: 1, type: 'uint256' }, { name: 'data', value: 'example', type: 'string' } ]); const tx = await eas.attest({ schema: '0xb16fa048b0d597f5a821747eba64efa4762ee5143e9a80600d0005386edfc995', data: { recipient: '0xFD50b031E778fAb33DfD2Fc3Ca66a1EeF0652165', expirationTime: 0n, revocable: true, data: encodedData } }); const uid = await tx.wait(); console.log('Attestation UID:', uid); ``` -------------------------------- ### Transaction Flow Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/7-transaction-utilities.md Illustrates the typical steps involved in creating, sending, and confirming a transaction using the EAS SDK. ```APIDOC ## Transaction Flow Diagram ``` 1. Create transaction request eas.attest({...}) 2. (Optional) Estimate gas transaction.estimateGas() 3. Send and wait for mining transaction.wait(confirmations) 4. Extract results uid = result ``` ``` -------------------------------- ### Generate Multi-Proof for Private Data Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/README.md Create a multi-proof from a `PrivateData` instance by specifying the indexes of the values you wish to include in the proof. This allows for selective disclosure. ```javascript const proofIndexes = [0, 2, 4]; // Proving name, isStudent, and dataHash const multiProof = privateData.generateMultiProof(proofIndexes); ``` -------------------------------- ### Configuration Types Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/8-types-and-interfaces.md Provides interfaces for configuring EAS, SchemaRegistry, and EIP712Proxy, including optional signer and proxy configurations. ```APIDOC ## Configuration Types ### `EASOptions` Options for EAS constructor. ```typescript interface EASOptions { signer?: TransactionSigner | TransactionProvider; proxy?: EIP712Proxy; } ``` ### `SchemaRegistryOptions` Options for SchemaRegistry constructor. ```typescript interface SchemaRegistryOptions { signer?: TransactionSigner | TransactionProvider; } ``` ### `EIP712ProxyOptions` Options for EIP712Proxy constructor. ```typescript interface EIP712ProxyOptions { signer?: TransactionSigner | TransactionProvider; } ``` ``` -------------------------------- ### Create Delegated Attestation Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/1-eas-core.md Use `attestByDelegation` to create an attestation using a pre-signed EIP-712 delegation. Requires a signer for transaction submission and the delegated signature from the attester. ```typescript const delegated = await eas.getDelegated(); const signer = new ethers.Wallet(privateKey, provider); const response = await delegated.signDelegatedAttestation({ schema: schemaUID, recipient: recipientAddress, expirationTime: 0n, revocable: true, refUID: ZERO_BYTES32, data: encodedData, deadline: 0n, value: 0n }, signer); const transaction = await eas.attestByDelegation({ schema: schemaUID, data: { recipient: recipientAddress, expirationTime: 0n, revocable: true, data: encodedData }, signature: response.signature, attester: await signer.getAddress(), deadline: 0n }); const uid = await transaction.wait(); ``` -------------------------------- ### PrivateData Constructor Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/6-private-data.md Initializes a new PrivateData instance with an array of data fields. Each field requires a type, name, and value. You can also provide pre-hashed values with salts using MerkleValueWithSalt. ```APIDOC ## Constructor ```typescript constructor(values: MerkleValue[] | MerkleValueWithSalt[]) ``` ### Parameters #### Parameters - **values** (MerkleValue[] | MerkleValueWithSalt[]) - Required - Array of data fields with types and values ### Request Example ```typescript import { PrivateData, MerkleValue } from '@ethereum-attestation-service/eas-sdk'; import { ethers } from 'ethers'; const values: MerkleValue[] = [ { type: 'string', name: 'name', value: 'Alice Johnson' }, { type: 'uint256', name: 'age', value: 28 }, { type: 'bool', name: 'isStudent', value: false }, { type: 'address', name: 'wallet', value: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e' }, { type: 'bytes32', name: 'dataHash', value: ethers.id('confidential information') } ]; const privateData = new PrivateData(values); ``` ``` -------------------------------- ### Batch register multiple schemas Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/3-schema-registry.md Shows how to register multiple schemas in a single operation by iterating through an array of schema definitions and registering each one sequentially. The UIDs of all registered schemas are collected and logged. ```typescript const schemas = [ { schema: 'uint256 id', revocable: true }, { schema: 'string name', revocable: false }, { schema: 'address wallet, uint256 balance', revocable: true } ]; const uids = []; for (const schemaData of schemas) { const tx = await schemaRegistry.register(schemaData); const uid = await tx.wait(); uids.push(uid); } console.log('Registered schemas:', uids); ``` -------------------------------- ### Fetch and Use Nonces for Batch Delegated Attestations Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/10-configuration-and-constants.md Fetch nonces manually for batch operations to optimize performance. Use incremental nonces when signing multiple delegated attestations in a batch. ```typescript const delegated = await eas.getDelegated(); let nonce = await eas.getNonce(attesterAddress); // Use incremental nonces for batch signing const sig1 = await delegated.signDelegatedAttestation({...}, signer, nonce); const sig2 = await delegated.signDelegatedAttestation({...}, signer, nonce + 1n); const sig3 = await delegated.signDelegatedAttestation({...}, signer, nonce + 2n); ``` -------------------------------- ### Generate Multi-Proof for Selected Fields Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/6-private-data.md Create a Merkle multi-proof for specific fields within the PrivateData tree by providing an array of their 0-indexed positions. The proof includes the selected leaves, the Merkle proof hashes, and proof flags. ```typescript // Prove only fields at indexes 0, 2, 4 (name, isStudent, dataHash) const multiProof = privateData.generateMultiProof([0, 2, 4]); console.log('Proved fields:', multiProof.leaves); console.log('Proof hashes:', multiProof.proof); ``` -------------------------------- ### generateMultiProof(indexes) Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/_autodocs/6-private-data.md Creates a Merkle multi-proof for a specified subset of fields within the PrivateData Merkle tree, allowing for selective disclosure. ```APIDOC ### `generateMultiProof(indexes: number[]): MerkleMultiProof` Generates a proof for a subset of fields, proving their inclusion in the tree. **Parameters:** #### Parameters - **indexes** (number[]) - Required - Array of field indexes to prove (0-indexed) **Returns:** `MerkleMultiProof` — Object containing: - `leaves` (Leaf[]) — The fields being proved (with types, names, values, salts) - `proof` (string[]) — Merkle proof hashes - `proofFlags` (boolean[]) — Flags indicating proof structure ### Request Example ```typescript // Prove only fields at indexes 0, 2, 4 (name, isStudent, dataHash) const multiProof = privateData.generateMultiProof([0, 2, 4]); console.log('Proved fields:', multiProof.leaves); console.log('Proof hashes:', multiProof.proof); ``` ``` -------------------------------- ### Create Onchain Attestation with EAS SDK Source: https://github.com/ethereum-attestation-service/eas-sdk/blob/master/README.md Use this snippet to create a single on-chain attestation. Ensure you have initialized EAS and connected a signer. The schemaUID and encoded data are required parameters. ```javascript import { EAS, NO_EXPIRATION, SchemaEncoder } from '@ethereum-attestation-service/eas-sdk'; const eas = new EAS(EASContractAddress); eas.connect(signer); // Initialize SchemaEncoder with the schema string const schemaEncoder = new SchemaEncoder('uint256 eventId, uint8 voteIndex'); const encodedData = schemaEncoder.encodeData([ { name: 'eventId', value: 1, type: 'uint256' }, { name: 'voteIndex', value: 1, type: 'uint8' } ]); const schemaUID = '0xb16fa048b0d597f5a821747eba64efa4762ee5143e9a80600d0005386edfc995'; const transaction = await eas.attest({ schema: schemaUID, data: { recipient: '0xFD50b031E778fAb33DfD2Fc3Ca66a1EeF0652165', expirationTime: NO_EXPIRATION, revocable: true, // Be aware that if your schema is not revocable, this MUST be false data: encodedData } }); // Estimate gas for the transaction before sending it const estimatedGas = await transaction.estimateGas(); console.log('Estimated gas:', estimatedGas.toString()); const newAttestationUID = await transaction.wait(); console.log('New attestation UID:', newAttestationUID); console.log('Transaction receipt:', transaction.receipt); ```