# read-commitment-data Source: https://docs.echo.xyz/api-reference/read-commitment-data /openapi/sonar.json post /sonar/v1/public/read-commitment-data Read data derived from the commitments to a sale contract. This includes the 100 latest commitments for a given sale, the total commitment amount, and the number of unique commitments. For auction sales, the current clearing price is also returned. # Overview Source: https://docs.echo.xyz/index Sonar: Self-hosted, on-chain token sale infrastructure ## What is Sonar? Sonar is a self-hosted, on-chain token sale infrastructure that enables projects to run compliant token sales directly to their community. You sell directly to your community through your own website and channels. Sonar provides the backend infrastructure, smart contracts, and compliance tooling—you build the frontend experience. Funds are collected and held in a smart contract you own. Settlement and refunds happen on-chain, providing transparency and security. Sonar handles KYC/KYB verification, wallet screening, accreditation checks, and can enforce jurisdiction restrictions and regulatory requirements. The same core contract supports multiple sale types. You choose the pricing strategy and compliance configuration that fits your objectives, and you have full control over how commitments are allocated during settlement. *** ## How It Works 1. **You configure your sale** in the [Echo Founder Dashboard](https://app.echo.xyz/founder), setting [pricing](/sonar/planning/pricing-strategies), compliance rules, and limits. 2. **Investors visit your website** and connect their wallet. You build the frontend experience; Sonar provides the backend infrastructure and smart contracts. 3. **Investors verify their [entity's](/sonar/core-features/entities) identity** through Sonar's KYC/KYB process. 4. **Investors commit funds** to your sale. Sonar issues signed [purchase permits](/sonar/core-features/purchase-permits) that your contract validates before accepting commitments. 5. **You settle the sale** after the commitment phase closes. You determine how much of each participant's commitment to accept via the [Echo Founder Dashboard](https://app.echo.xyz/founder), and refunds are issued for any unaccepted funds. Understand the end-to-end sale process See the end-to-end purchase flow *** ## Getting Started Start with Planning Your Sale to understand your options for pricing, settlement, and configuration before handing off to your development team. Jump to Key Concepts to understand entities, wallets, and permits, then follow the Getting Started guide to begin your integration. *** ## Supported Networks Sonar supports most EVM networks. Contact [support@echo.xyz](mailto:support@echo.xyz) for specific network availability. *** ## Need Help? * Check our [FAQ section](/sonar/faq) for common questions * Contact [support@echo.xyz](mailto:support@echo.xyz) for technical assistance * Access the [Echo Founder Dashboard](https://app.echo.xyz/founder) to configure your sale # Authentication & OAuth Source: https://docs.echo.xyz/sonar/core-features/authentication OAuth 2.0 authentication for secure API access. ## Overview Sonar uses OAuth 2.0 with PKCE for secure authentication. Users sign in through Echo's OAuth flow to access their compliance entities and generate purchase permits. ## How It Works 1. **User clicks "Sign in with Sonar"** 2. **Redirected to Echo for authentication** 3. **User signs in or creates account** 4. **User authorizes your application to access their data** 5. **Redirected back to your app with auth code** 6. **Your app exchanges code for access token** 7. **Token used for API calls (entities, permits, etc.)** ```mermaid theme={null} sequenceDiagram participant Client as Your App participant Browser as User Browser participant EchoAuth as Echo Authorization Server participant EchoAPI as Echo API Server Note over Client, EchoAPI: OAuth 2.0 Authorization Code Flow with PKCE Client->>+Browser: 1. Initiate authorization request Browser->>+EchoAuth: 2. GET /oauth/authorize with parameters EchoAuth->>EchoAuth: 3. Authenticate user (if not logged in) EchoAuth->>-Browser: 4. Authorization code in redirect URI Browser->>-Client: 5. Receives authorization code Client->>+EchoAuth: 6. POST /oauth/token with code & code_verifier EchoAuth->>EchoAuth: 7. Validate code_verifier EchoAuth->>-Client: 8. Access token Client->>+EchoAPI: 9. Access protected resource with access token EchoAPI->>-Client: 10. Protected resource (e.g., verification status) ``` ## Authentication Configuration Your OAuth configuration is done through the Founder dashboard. You must configure the following: * **Redirect URIs**: A list of URIs that are valid for Sonar to redirect to after the authorization process. * **Scopes**: A list of scopes that the client can request from the user. * **Branding**: Upload logos and customize the OAuth experience. ### Redirect URIs When setting up your client, you can add one or more redirect URIs. These are the URIs that Sonar will redirect to after the authorization process. For local development, you must add the following redirect URI to your client, e.g.: * `http://localhost:3000/oauth/callback` URIs containing `localhost` or equivalent hostnames are only allowed in sales with test tenancy to minimize security risks. ### Scopes When setting up your client, you can choose which scopes are required for you app, and which are optional. The following scopes are available: * `read_entities`: Read entity information and eligibility status. * `sale_eligibility_check`: Check eligibility for sales. * `contact_email`: Access user's contact email. To run a sale, you must have the `read_entities` and `sale_eligibility_check` scopes, so these should be required. You can choose to add other scopes as either optional or required. For example, if you want to allow the user to share their email with you, you can add the `contact_email` scope as optional. If you want to require the user to share their email with you, you would add it as required. ### Branding You must supply two logos for the OAuth screen: one for the square logo, and one for the wide logo. An example of how the OAuth screen will look is shown below: OAuth Screen # Entities Source: https://docs.echo.xyz/sonar/core-features/entities Understanding compliance entities and verification requirements. ## Overview An **entity** represents the compliance identity that participates in token sales. Entities can be individuals or organizations that complete verification and maintain eligibility status for different sales. All purchase permits (and associated purchase limits) are tied to entities an entity and wallet. ## User vs Entity vs Wallet Sonar uses three distinct concepts that form a hierarchy: ``` User → Entity → Wallet ``` **Person** with a Sonar account * Authenticates via OAuth * Can manage one or more entities **Compliance identity** that participates in sales * Individual or organization * Completes KYC/KYB verification * Has eligibility status per sale **Blockchain address** linked to an entity * Used for actual purchases * Multiple wallets per entity allowed ### How They Relate A **user** is the person who logs in. After authentication, they can manage one or more **entities**. Each entity is a separate compliance identity with its own KYC/KYB verification. An entity can have multiple **wallets** linked to it for making purchases. **Example:** Alice has a personal entity for her own investments and also manages her company's entity. Her personal entity has two wallets linked (one on Ethereum mainnet, one on Arbitrum). When participating in a sale, she selects which entity to use, then can purchase from any wallet linked to that entity.

See [Entity Identifiers](#entity-identifiers) for details on the different ID types returned by the API.

## Wallet linking Wallets are linked to an entity **implicitly**. There is no separate "link wallet" step: a wallet becomes linked to the authenticated entity the first time you call [`generatePurchasePermit`](/sonar/core-features/purchase-permits) for it. The linking boundary works as follows: * **New wallet, verified entity.** When a verified entity generates a permit for a wallet that has never been associated with any entity, that wallet is auto-associated to the entity (as long as the entity is under its wallet allowance). It is not rejected. * **Wallet already linked to another entity.** A wallet that is already linked to a different entity is rejected. The offchain permit check acts as the first filter, and the `SettlementSale` contract enforces it onchain by reverting with `WalletTiedToAnotherEntity`. * **Wallet allowance.** Each entity can link up to `maxWalletsPerEntity` wallets — the default is **20**. The limit is configurable on request. See [`maxWalletsPerEntity`](/sonar/reference/contracts/settlement-sale#deployment-defaults) for details.

Eligibility and commitment limits are enforced **per entity** (tracked by `SaleSpecificEntityID`), never per wallet. A participant using multiple wallets shares a single entity-level limit, so extra wallets cannot be used to exceed it.

## Entity Lifecycle Entities progress through verification to determine their ability to participate in token sales. All modifications to the entity are done through the Sonar platform, and the user should be redirected there if they need to make changes. ### Setup States Entities move through several setup states as they progress through verification on the Sonar platform. Each state represents a specific stage in the KYC/KYB journey. These are the possible setup states an entity may have: | State | Value | Description | | - | - | - | | Not Started | `not-started` | The user has not started the setup process for the entity yet. | | In Progress | `in-progress` | The setup is in progress; the user should complete verification steps in the identity portal. | | Ready For Review | `ready-for-review` | The user has submitted all required information; the entity is awaiting compliance review. | | In Review | `in-review` | The compliance team is currently reviewing submitted information. | | Complete | `complete` | All required compliance steps are finished and setup is complete. | | Failure | `failure` | The setup failed due to issues the user can fix (for example, missing or invalid information). | | Failure (Final) | `failure-final` | The setup failed due to issues the user cannot fix (for example, a compliance roadblock). | | Technical Issue | `technical-issue` | The setup process encountered a technical issue; users should contact support. | > **Note:** Some setup states may require users to take specific actions, such as providing additional information or contacting support. ### Sale-Specific Eligibility Once verification is complete, entities are evaluated against each sale's specific requirements, and is one of the following states: | State | Value | Description | | - | - | - | | Eligible | `eligible` | The entity meets all sale requirements, has verified jurisdiction compliance, possesses an adequate accreditation level, and is allowed to generate purchase permits. | | Not Eligible | `not-eligible` | The entity does not meet sale requirements, such as having the wrong jurisdiction or accreditation, compliance issues have been identified, and purchase permits are blocked. | | Unknown | `unknown-setup-incomplete` | Setup is incomplete or required information is missing, so eligibility cannot be determined. The entity must complete verification first. | ## Entity Identifiers Sonar uses two different entity identifiers to provide privacy isolation at different levels. | Identifier | Scope | Stability | Use Case | | - | - | - | - | | **EntityID** | Per OAuth client | Stable across all sales for your project | API calls to Sonar backend | | **SaleSpecificEntityID** | Per sale | Stable across all clients for a given sale | Onchain operations and purchase permits | ### EntityID (Client-Scoped) When a user authenticates with your project via OAuth, Sonar returns an `EntityID` that is unique to your OAuth client. This ID: * Remains the same regardless of which sale the entity participates in through your project * Is different from the `EntityID` that another project would see for the same entity * Should be used for all Sonar API calls (e.g., `generatePurchasePermit`, `prePurchaseCheck`) This isolation means users cannot be correlated across different clients. ### SaleSpecificEntityID (Sale-Scoped) For onchain operations, Sonar provides a `SaleSpecificEntityID` that is unique to each sale. This ID: * Is included in purchase permits and recorded onchain by the sale contract * Remains the same for a given entity across all projects participating in the same sale * Is different for the same entity across different sales This design prevents cross-sale tracking. An observer cannot determine that the same entity participated in multiple sales by comparing onchain data. ### Which ID to use | Operation | ID to Use | | - | - | | Calling Sonar API endpoints | `EntityID` | | Reading commitment data from the contract | `SaleSpecificEntityID` | | Looking up allocations onchain | `SaleSpecificEntityID` | | Included in purchase permits | `SaleSpecificEntityID` | ## Testing Entity States During development, you can use your [test sales](/sonar/core-features/test-sales) to simulate different entity states without completing actual verification. Test sales allow you to override setup state, eligibility status, and failure reasons to test how your integration handles various scenarios. # Purchase Permits Source: https://docs.echo.xyz/sonar/core-features/purchase-permits Cryptographically signed authorizations that connect compliance verification to onchain purchases. ## Overview Purchase permits are signed messages that authorize specific wallet addresses to purchase tokens for verified entities. They serve as the bridge between Sonar's compliance verification and your onchain sale contract. Each permit proves that an entity has completed the required verification and is authorized to make a specific purchase with given funding bounds. ## Permit Architecture ```mermaid theme={null} sequenceDiagram participant F as Frontend participant S as Sonar API participant C as Contract F->>S: Request purchase permit S->>S: Verify entity eligibility and pre-purchase checks S->>S: Sign permit with private key S->>F: Return signed permit F->>C: Call contract with permit C->>C: Verify ECDSA signature C->>C: Execute purchase ``` Permits are **short-lived** (10 minutes) to ensure fresh compliance status. Participants can use multiple permits during a sale (e.g., to update bids in an auction), but each permit expires quickly to maintain security. ## Permit Structure Sonar sets different fields in the permit based on your sale configuration: ```typescript theme={null} { saleSpecificEntityID: "0x1234567890abcdef1234567890abcdef", saleUUID: "0xabcdef1234567890abcdef1234567890", wallet: "0x742d35Cc6364C0532d0ef6b1234567890abcdef", expiresAt: 1704067200, minAmount: 1000000000, maxAmount: 10000000000, minPrice: 1000000000, maxPrice: 10000000000, opensAt: 1704060000, closesAt: 1704153600, payload: "0x" } ``` ### Field Reference | Field | Description | | - | - | | `saleSpecificEntityID` | Sale-specific entity identifier. The same entity has different IDs across different sales for privacy. | | `saleUUID` | Your sale's unique identifier. The contract should verify this matches a hardcoded value. | | `wallet` | The authorized wallet address. The contract should verify this matches the transaction sender. | | `expiresAt` | Unix timestamp when the permit expires (10 minutes from issuance). The contract should verify this is in the future. | | `minAmount` | Minimum total commitment required from this entity. Set based on your sale's commitment limits. | | `maxAmount` | Maximum total commitment allowed for this entity. Used to enforce whale caps and per-entity limits. | | `minPrice` | Minimum bid price allowed (for auctions). For fixed-price sales, this equals the sale price. | | `maxPrice` | Maximum bid price allowed (for auctions). For fixed-price sales, this equals the sale price. | | `opensAt` | Unix timestamp when the permit becomes valid (inclusive). Enables time-gated access windows. | | `closesAt` | Unix timestamp when the permit stops being valid (exclusive). The contract should verify the current time is within `[opensAt, closesAt)`. | | `payload` | Additional data for custom logic (e.g., forced lockup preferences). | Price fields are denominated in the auction's [bid increment](/sonar/planning/pricing-strategies#auction-parameters). For example, if the bid increment is \$0.01, then a price of 100 represents a willingness to pay \$1.00. Limits are enforced at the **entity level**, not the wallet level. A participant using multiple wallets still has a single limit across all of them. Your contract should track commitments by `saleSpecificEntityID` and validate that the entity's total stays within the min/max bounds. ## Common Issues **Signature Verification Failures** Most permit issues stem from signature verification problems: 1. **Wrong signer address**: Ensure your contract has the correct Sonar signer address 2. **Struct encoding**: Permit structure must exactly match Solidity definition 3. **Sale UUID mismatch**: Verify your sale UUID matches exactly Debug by logging the recovered signer address in your contract. **Expiration Handling** Permits expire in 10 minutes: 1. **Generate permits just-in-time**: Don't fetch permits during page load 2. **Implement retry logic**: Regenerate expired permits automatically 3. **Handle expired permit errors gracefully**: Provide clear retry options ## See Also Learn how to validate permits in your custom sale contract Generate and use permits in your application Understanding entities and why limits are per-entity # Test Sales Source: https://docs.echo.xyz/sonar/core-features/test-sales You can use a test sale to test your app's integration with Sonar. ## Overview When your sale application is approved, a test sale will be created in addition to a production sale. Test sales are for for testing your app's integration with Sonar, including various failure/edge cases. Test sales differ from production sales in the following ways: * You are able to update settings at any time via the founder dashboard (production sales are locked after approval). * You are able to override the setup/eligibility state of your entities in order to test various failure scenarios. ### How to integrate with a test sale Test sales have a separate sale UUID and OAuth client UUID, which you will need to configure in your app. You can find the UUIDs in the Integration section of test sale settings in the [founder dashboard](https://app.echo.xyz/founder). More details on how to configure these settings in your app are in the [integration guides](/sonar/integration-guides/react#configuration). ### How to override entity state for a test sale You need to navigate to the Sonar entity management page for the test sale. You can either follow the link that you should have on your sale site, or click the preview link in the Integration section of test sale settings in the [founder dashboard](https://app.echo.xyz/founder). You will know you are on a test sale because a panel saying "Sale integration sandbox" will be visible. You can override entity state by clicking the "Overrides" link. Overrides link on test sale entity management page This will bring up a modal like this: Test sale entity management overrides modal Refer to our reference documentation for the meanings of each of these fields: * [Setup State](/sonar/reference/sonar-core#entitysetupstate) * [Eligibility Reasons](/sonar/reference/sonar-core#saleeligibility) * [Pre Purchase Check Failure Reason](/sonar/reference/sonar-core#prepurchasefailurereason) * **Country** - the entity's country of resience or incorporation. This can be useful for testing the experience for entities in blocked countries. ## Testing with multiple people Overrides are set per entity, so your whole team can test in parallel. Each teammate signs into the test sale via OAuth and gets their own entity. They then set Overrides on their own entity from the test sale's entity management page. This is not limited to people with founder dashboard access, and no real KYC is required. Anyone who can reach the test sale site can authenticate, create an entity, and apply Overrides to test their own commitment flow. ## Why a test commit is blocked without overrides If you do not set Overrides on a test sale, your entity uses your Echo account's real setup state and sale eligibility. If that account has not completed setup or is not eligible, the entity will not be ready to purchase (for example `readyToPurchase = false`), which blocks the commitment. To bypass this for integration testing, apply Overrides (for example, set the entity to "ready to purchase"). Your frontend should still handle [`PrePurchaseFailureReason`](/sonar/reference/sonar-core#prepurchasefailurereason) with the documented messages so you can verify the blocked-commitment experience too. ## Resetting a test sale There is no in-place reset for a test sale. Moving a test sale through its stages does not clear committed bids, allocations, or registered entities. To get a clean slate, redeploy the test sale contract. This is self-serve from the test sale settings in the [founder dashboard](https://app.echo.xyz/founder). You lose the previous contract's state, and the sale then points at the fresh contract. You can redeploy as many times as needed. # FAQ & Troubleshooting Source: https://docs.echo.xyz/sonar/faq Common questions and solutions for Sonar integration. ## Frequently Asked Questions ### Architecture & Responsibilities **Yes, exactly.** Sonar handles: * KYC/KYB verification and accreditation checks * OAuth authentication and entity management * Eligibility determination and allowlist management * Signing purchase permits Your project handles: * Smart contract implementation (only if using a [custom contract](/sonar/integration-guides/custom-contracts)) * Frontend user experience and wallet connection * Token economics, pricing, and vesting **Purchase Permit Flow:** 1. **User authenticates** with Sonar via OAuth 2. **Entity eligibility check**: your frontend calls Sonar API to verify the entity and wallet are eligible for the sale 3. **Pre-purchase validation**: check if entity is ready to purchase (no liveness check needed, etc.) 4. **Generate permit**: Sonar creates a signed permit 5. **Contract call**: your frontend passes the permit to your contract's purchase function 6. **Signature verification**: your contract verifies the permit was signed by Sonar's authorized signer **Key points:** * Permits are short-lived (10 minutes) for security * Include purchase limits (min/max purchase amounts) * Include price limits (min/max price - can beuseful when there is a dynamic pricing model, e.g. auctions) * Include payload (additional data from the Sonar backend - contact us if you need to use this) * Contain entity ID and wallet address binding * Prevent replay attacks with expiration and sale UUID **Purchase Limit Enforcement:** Sonar provides purchase limit data in purchase permits: * `maxAmount` - Maximum total this entity can purchase * `minAmount` - Minimum purchase amount required * `maxPrice` - Maximum price allowed (for auctions) * `minPrice` - Minimum price allowed (for auctions) **Your contract enforces these limits:** ```solidity theme={null} uint256 newTotal = entityState.amount + purchaseAmount; require(newTotal <= permit.maxAmount, "Exceeds purchase limit"); require(newTotal >= permit.minAmount, "Below minimum"); require(price <= permit.maxPrice, "Exceeds max price"); require(price >= permit.minPrice, "Below min price"); ``` ### Technical Implementation **Yes!** We provide: **JavaScript Libraries:** * `@echoxyz/sonar-core` - Low-level API client * `@echoxyz/sonar-react` - React hooks and providers **Example Applications:** * [Next.js EVM example](https://github.com/sunrisedotdev/sonar-example-nextjs) * [React EVM example](https://github.com/sunrisedotdev/sonar-example-react) * [Next.js SVM example](https://github.com/sunrisedotdev/sonar-example-nextjs-svm) * [React SVM example](https://github.com/sunrisedotdev/sonar-example-react-svm) * Shows OAuth flow, entity checking, purchase flow * Wagmi integration for wallet connection * Error handling and edge cases **Integration Guides:** * [Frontend-Only Integration](/sonar/integration-guides/frontend-only) - Using our React hooks * [Frontend Integration Overview](/sonar/integration-guides/frontend-overview) - Complete purchase flow **Quick Start:** ```bash theme={null} npm install @echoxyz/sonar-core @echoxyz/sonar-react ``` ## Common Issues & Solutions ### OAuth Integration **Solution:** 1. Ensure redirect URI in your code exactly matches the one configured in Sonar dashboard 2. Check for trailing slashes, http vs https, port numbers 3. For localhost development, use exact port - `http://localhost:3000/oauth/callback` **Common mistakes:** * `http://localhost:3000/oauth/callback/` (trailing slash) * `https://localhost:3000/oauth/callback` (https instead of http) * Using `127.0.0.1` instead of `localhost` **Check:** 1. OAuth Client UUID is correct for your environment (staging vs production) 2. Sale is approved and active in Sonar dashboard 3. OAuth client has correct scopes configured 4. Using correct API endpoints (staging vs production) **Scopes are configured in the dashboard based on your sale requirements:** * `read_entities` - Read entity information * `sale_eligibility_check` - Check purchase eligibility and generate permits * `contact_email` - Access user's contact email **Likely causes:** 1. System clock drift - ensure your server/client has correct time 2. Token storage issues - check localStorage/sessionStorage 3. CORS issues preventing token storage 4. Browser privacy settings blocking storage **Debug steps:** 1. Check browser dev tools → Application → Local Storage 2. Verify timestamps in JWT payload 3. Test in incognito mode to rule out extensions ### Entity & Eligibility Issues **Check entity state:** 1. Verify KYC/KYB is fully approved (not just submitted) 2. Check if entity meets sale requirements (accreditation, jurisdiction, etc.) 3. Verify sale configuration allows this entity type **Debug in Sonar dashboard:** 1. Check entity compliance status 2. Review sale configuration requirements 3. Test with different entity types ### Purchase Flow Issues **Permits expire in 10 minutes for security.** **Solutions:** 1. Generate permit immediately before contract call, not during page load 2. Implement retry logic that regenerates permits on expiration **Wallet screening can flag addresses with minimal exposure to risky entities.** **Solutions:** 1. Add the address to the allowlist on the **Wallet management** page of your sale dashboard 2. Loosen the action for the relevant risk level in **Sale settings → Wallet requirements** (e.g., allow medium-risk wallets) 3. The user can register a different wallet address 4. Contact support to review specific address flags **Prevention:** * Use fresh wallet addresses for token sales * Avoid addresses that received funds from exchanges or DeFi protocols ### Information to when contacting support When contacting [support@echo.xyz](mailto:support@echo.xyz), include: **Required:** * Your Sale UUID * Wallet addresses being tested * Exact error messages from browser console **Helpful:** * Screenshots of error states * Network tab showing API request/response * Smart contract address (if deployed) * Expected vs actual behavior ### Community Resources * **Example Application** - [sonar-example-nextjs](https://github.com/sunrisedotdev/sonar-example-nextjs) * **Integration Guides** - Start with [Getting Started](/sonar/getting-started) * **API Reference** - [Sonar Core Documentation](/sonar/reference/sonar-core) **Response Time** - We typically respond to integration questions within 24 hours during business days. For urgent production issues, mark your email as "URGENT" in the subject line. # Getting Started Source: https://docs.echo.xyz/sonar/getting-started Set up your project to integrate with Sonar for compliant token sales. ## Prerequisites Before integrating with Sonar, ensure you have: An approved application to use Sonar. [Apply here](https://app.echo.xyz/founder) if you haven't already. You will need to be able to create a website to integrate with Sonar. Understanding of your jurisdiction's securities laws and compliance requirements for token sales. ## Step 1 - Access the Founder Dashboard Once your application is approved, access the [Echo Founder Dashboard](https://app.echo.xyz/founder) to: 1. **Configure your sale**: Configure basic sale parameters 2. **Configure compliance settings**: Set KYC/KYB and accreditation requirements 3. **Get integration credentials**: Copy your Sale UUID and OAuth Client UUID from the integration section ## Step 2 - Configure Your Sale Settings In the founder dashboard, configure settings for your sale. You can change these later on if you need to. ## Step 3 - Sale Contract For standard sale configurations, **Sonar deploys and manages the sale contract for you**. This includes the [SettlementSale](/sonar/reference/contracts/settlement-sale) contract which supports both fixed-price and auction sales. If you have specific requirements that aren't covered by the standard contract, you can build a [custom contract](/sonar/integration-guides/custom-contracts) that validates Sonar purchase permits. Contract deployment is coordinated as part of your sale setup. Contact [support@echo.xyz](mailto:support@echo.xyz) if you have questions about your contract options. ## Step 4 - Setup your website The easiest way to get started is to clone one of our example websites: ```bash theme={null} git clone https://github.com/sunrisedotdev/sonar-example-nextjs ``` Copy or edit the `.env.local` file to set your sale UUID and OAuth client UUID. This template is configured to use Next.js, React, and Wagmi. It makes use of the `@echoxyz/sonar-core` and `@echoxyz/sonar-react` libraries to integrate Sonar. If you want to use a different framework, you can use the `@echoxyz/sonar-core` library directly. Alternatively, you can create your own website in any framework you like. * Wrap your app with the Sonar provider alongside your wallet provider * Create a page at your redirect URI to handle OAuth callbacks * Add authentication buttons to your app ## Step 5 - Test the Integration Make sure your website is configured and running. 1. **Test OAuth flow** * Click "Sign in with Sonar" * Complete authentication on Sonar * Verify you're redirected back successfully 2. **Check entity status** * Connect a wallet * Verify entity data loads correctly * Test with different wallet addresses ## Next Steps Now that you have basic integration working, choose your implementation path. ### Choose Your Integration Approach Simpler setup. OAuth tokens stored in browser. Good for most projects. More secure. Tokens managed server-side. Required if you need to fetch auction data (e.g., clearing price) from the backend API. ### Using a Custom Contract? Most projects use the standard [SettlementSale](/sonar/reference/contracts/settlement-sale) contract that Sonar deploys. If you have specific requirements: Build your own contract with Sonar permit validation ### Learn More Understand entities, permits, and the compliance flow ## Getting Help If you encounter issues during setup: * Check our [FAQ section](/sonar/faq) for common questions * Review the [example application](https://github.com/sunrisedotdev/sonar-example-nextjs) * Contact [support@echo.xyz](mailto:support@echo.xyz) for technical assistance # Custom Contracts Source: https://docs.echo.xyz/sonar/integration-guides/custom-contracts Build your own sale contract with Sonar purchase permit validation. ## Overview For most sales, Sonar deploys and manages the [SettlementSale](/sonar/reference/contracts/settlement-sale) contract for you. However, if you have specific requirements not covered by the standard contract, you can build a custom contract that integrates with Sonar's compliance infrastructure. ### When to Build a Custom Contract * You need custom onchain logic beyond what Sonar provides * You want to integrate token sale logic with other contract functionality * You have specific requirements for how commitments are structured * You want to extend the standard contract with additional features ### Deployment Models Sonar supports different levels of customization: | Model | Contract | Settlement | | - | - | - | | **Standard** | Sonar deploys SettlementSale | You determine allocations via the dashboard; Sonar syncs to contract | | **Fully Custom** | You deploy custom contract | You determine and write allocations directly to contract | ### The Core Integration Your custom contract must validate **purchase permits**—signed authorizations from Sonar that prove a wallet is eligible to participate. Sonar handles all compliance (KYC/KYB, accreditation, jurisdiction checks) and issues permits for eligible participants. The permit contains: * Entity identity and authorization proof * Purchase limits (min/max amounts) * Price limits (for auctions) * Expiration timestamp ## Purchase Permit Sonar generates permits with this structure (see also the [sonar contract repo](https://github.com/sunrisedotdev/sonar/blob/main/contracts/src/permits/PurchasePermitV3.sol)): ```solidity theme={null} struct PurchasePermitV3 { bytes16 saleSpecificEntityID; // Sale-specific entity identifier (same entity has different IDs per sale) bytes16 saleUUID; // Your Sale UUID address wallet; // Authorized wallet address uint64 expiresAt; // Unix timestamp expiration uint256 minAmount; // Minimum commitment amount uint256 maxAmount; // Maximum commitment amount uint64 minPrice; // Minimum bid price (for auctions) uint64 maxPrice; // Maximum bid price (for auctions) uint64 opensAt; // Unix timestamp when permit becomes valid (inclusive) uint64 closesAt; // Unix timestamp when permit stops being valid (exclusive) bytes payload; // Additional data (e.g., forcedLockup) } ``` ### Validation To ensure the validity of a purchase permit, you need to verify the following aspects (see also the [example implementation](#example-validation) below). Please make sure to **implement all of these checks** to ensure correct enforcement of the requirements of your sale. 1. The ECDSA signature was issued by the Sonar signer 2. The permit's sale UUID matches yours 3. The permit is not expired 4. The current time is within the permit's time window (`opensAt` \<= now \< `closesAt`) 5. The sender matches the wallet address in the permit 6. The commitment amount is within the minimum and maximum amount limits 7. The bid price is within the minimum and maximum price limits (for auctions) ### Example Validation These snippets are based on the [example sale contract](https://github.com/sunrisedotdev/sonar/blob/main/contracts/src/ExampleSale.sol). #### 1. Signature Verification You must verify that permits are signed by Sonar's authorized signer: ```solidity theme={null} // Grant this role to the signer address provided by Sonar bytes32 public constant PURCHASE_PERMIT_SIGNER_ROLE = keccak256("PURCHASE_PERMIT_SIGNER_ROLE"); // Verify signature in your purchase function address recoveredSigner = PurchasePermitV3Lib.recoverSigner(permit, signature); if (!hasRole(PURCHASE_PERMIT_SIGNER_ROLE, recoveredSigner)) { revert PurchasePermitUnauthorizedSigner(recoveredSigner); } ``` #### 2. Sale UUID Validation Prevent permit reuse across different sales: ```solidity theme={null} if (permit.saleUUID != saleUUID) { revert PurchasePermitSaleUUIDMismatch(permit.saleUUID, saleUUID); } ``` #### 3. Expiration Checks Permits have short expiration times: ```solidity theme={null} if (permit.expiresAt <= block.timestamp) { revert PurchasePermitExpired(); } ``` #### 4. Time Window Validation Permits include a time window during which they are valid for commitments: ```solidity theme={null} if (block.timestamp < permit.opensAt) { revert PurchasePermitNotYetValid(); } if (block.timestamp >= permit.closesAt) { revert PurchasePermitWindowClosed(); } ``` #### 5. Wallet Authorization Ensure the permit is used by the authorized wallet: ```solidity theme={null} if (permit.wallet != msg.sender) { revert PurchasePermitSenderMismatch(msg.sender, permit.wallet); } ``` ## Integration Patterns ### Wallet-Level Tracking (Basic) The example contract tracks purchases by wallet address: ```solidity theme={null} // Track amount purchased by each wallet mapping(address => uint256) public amountByAddress; function purchase(uint256 amount, /* permit params */) external { _validatePurchasePermit(purchasePermit, purchasePermitSignature); uint256 newTotalAmount = amountByAddress[msg.sender] + amount; // Validate purchase limits if (newTotalAmount < purchasePermit.minAmount) { revert AmountBelowMinimum(newTotalAmount, purchasePermit.minAmount); } if (newTotalAmount > purchasePermit.maxAmount) { revert AmountExceedsMaximum(newTotalAmount, purchasePermit.maxAmount); } amountByAddress[msg.sender] = newTotalAmount; } ``` ### Entity-Level Tracking One might want to additionally enforce limits by entity, across all wallets they can use: ```solidity theme={null} // Track amount purchased by each entity mapping(bytes16 => uint256) public amountByEntity; function purchase(uint256 amount, /* permit params */) external { _validatePurchasePermit(purchasePermit, purchasePermitSignature); bytes16 entityID = purchasePermit.saleSpecificEntityID; uint256 newTotalAmount = amountByEntity[entityID] + amount; if (newTotalAmount > purchasePermit.maxAmount) { revert AmountExceedsMaximum(newTotalAmount, purchasePermit.maxAmount); } amountByEntity[entityID] = newTotalAmount; } ``` ### Auction bid price validation If you are running a sale with a dynamic pricing model where the user can commit with a requested price (e.g. auctions), you should validate the bid price is within the minimum and maximum price limits. ```solidity theme={null} struct Bid { uint64 price; uint256 amount; } mapping(address => Bid) internal bidByAddress; function processBid(uint64 price, uint256 amount, /* permit params */) external { _validatePurchasePermit(purchasePermit, purchasePermitSignature); if (price > purchasePermit.maxPrice) { revert BidPriceExceedsMaxPrice(price, purchasePermit.maxPrice); } if (price < purchasePermit.minPrice) { revert BidPriceBelowMinPrice(price, purchasePermit.minPrice); } if (amount < purchasePermit.minAmount) { revert BidBelowMinAmount(amount, purchasePermit.minAmount); } if (amount > purchasePermit.maxAmount) { revert BidExceedsMaxAmount(amount, purchasePermit.maxAmount); } // Replace the existing bid bidByAddress[msg.sender] = Bid(price, amount); } ``` ## Getting the Signer Address Sonar signs all purchase permits using a global infrastructure key. When deploying your contract, grant the `PURCHASE_PERMIT_SIGNER_ROLE` to this address. **For EVM chains:** `0x9a1964e04d10ccfe1a9ce300d943f71c6e3ae24c` For other chains, contact [support@echo.xyz](mailto:support@echo.xyz) to get the correct signer address. The permit signer role is always held by Sonar's infrastructure. This ensures all purchase authorizations flow through Sonar's compliance verification, maintaining the integrity of the permit system. ## See Also Reference for the standard Sonar sale contract Generate and use purchase permits in your frontend Deep dive into permit structure and validation View the example sale contract on GitHub # Frontend-only Source: https://docs.echo.xyz/sonar/integration-guides/frontend-only Integrate Sonar into a React single page application with client-side token management. A complete working example using this integration approach. This guide covers integrating Sonar using the `@echoxyz/sonar-react` library. All authentication and API calls happen client-side, with tokens stored in browser storage. For apps with a backend, consider the [Frontend with Backend](/sonar/integration-guides/frontend-with-backend) approach for improved security. ## How it works ```mermaid theme={null} sequenceDiagram participant U as User participant B as Browser participant L as Sonar React Library participant E as Echo OAuth participant S as Sonar API participant C as Sale Contract Note over U,E: OAuth Authentication U->>B: Click "Connect with Sonar" B->>L: login() L->>L: Generate PKCE params L->>E: Redirect to OAuth E->>E: User authenticates E->>B: Redirect with code B->>L: completeOAuth() L->>E: Exchange code for tokens E->>L: Return tokens L->>L: Store in browser storage Note over U,S: Purchase Flow (example Sonar API call) U->>B: Click "Purchase" B->>L: generatePurchasePermit() L->>S: POST /purchase-permit S->>L: Return signed permit L->>B: Return permit Note over U,C: Contract Interaction B->>C: purchase(amount, permit, signature) C->>C: Verify permit signature C->>C: Execute purchase C->>B: Transaction receipt ``` ## Installation ```bash theme={null} npm install @echoxyz/sonar-core @echoxyz/sonar-react ``` ## Configuration Wrap your app in `SonarProvider`: ```tsx theme={null} import { SonarProvider } from "@echoxyz/sonar-react"; const sonarConfig = { clientUUID: "YOUR_OAUTH_CLIENT_UUID", redirectURI: "YOUR_REDIRECT_URI", }; function App() { return ( {/* Your application */} ); } ``` Find your OAuth client UUID and configure your redirect URI in the [Echo founder dashboard](https://app.echo.xyz/founder). ## Implementing the OAuth flow Sonar uses OAuth to allow users to authenticate and authorize your application to access their data. You will need buttons that allow users to login and logout from Sonar. Logging in will redirect the user to the Sonar site to login. If they haven’t yet authorized your application, they will be prompted to do so. ```tsx theme={null} import { useSonarAuth } from "@echoxyz/sonar-react"; function AuthButton() { const { login, authenticated, logout } = useSonarAuth(); const onClick = () => { if (authenticated) { logout(); return; } login(); }; return ( ); } ``` Sonar will redirect the user back to your application at your `redirectURI` with `code` and `state` querystring parameters. You will need a page at your `redirectURI` that will handle the OAuth callback. ```tsx theme={null} import { useEffect, useRef, useState } from "react"; import { useSonarAuth } from "@echoxyz/sonar-react"; export default function OAuthCallback() { const { authenticated, completeOAuth, ready } = useSonarAuth(); const oauthCompletionTriggered = useRef(false); const [oauthError, setOAuthError] = useState(null); const params = new URLSearchParams(window.location.search); const code = params.get("code"); const state = params.get("state"); // complete the oauth flow and exchange the code for an access token useEffect(() => { const processOAuthCallback = async () => { // the user is already authenticated, nothing to do if (!ready || authenticated || !code || !state) { return; } // ensuring the oauth completion isn't called multiple times // since subsequent ones are expected to fail if (oauthCompletionTriggered.current) { return; } oauthCompletionTriggered.current = true; try { await completeOAuth({ code, state }); } catch (err) { setOAuthError(err instanceof Error ? err.message : null); } }; processOAuthCallback(); }, [authenticated, completeOAuth, code, ready, state]); // redirect away from this page once the OAuth flow is complete useEffect(() => { if (!ready || !authenticated) { return; } window.location.href = "/"; }, [authenticated, ready]); // note you should also add a timeout to handle the case // where it takes too long for `authenticated` to be true if (oauthError) { return (

{oauthError}

); } return (

Connecting to Echo...

); } ``` ### Fetching the state of a user's Sonar entities You can fetch the state of a user's Sonar entities with the `useSonarEntities` hook. ```tsx theme={null} import { useSonarEntities } from "@echoxyz/sonar-react"; const SonarEntityPanel = () => { const { authenticated, loading, entities, error } = useSonarEntities({ // from the sale integration settings on the Echo founder dashboard saleUUID: "YOUR_SALE_UUID", }); if (!authenticated) { return

Connect your Sonar account to continue

; } if (loading) { return

Loading...

; } if (error) { return

Error: {error.message}

; } if (!entities || entities.length === 0) { return (

No entity found. Continue your setup{" "} on Sonar to continue.

); } return (
{entities.map((entity) => (
{entity.Label} {entity.EntitySetupState} {entity.EntitySaleEligibility}
))}
); }; ``` [Reference docs](../reference/sonar-react#usesonarentity) for the `useSonarEntity` hook. See the example app [EntityStateDescription](https://github.com/sunrisedotdev/sonar-example-react/blob/main/src/components/entity/EntityStateDescription.tsx) for more detail on how to interpret the state and display it to the user. ## Running pre-purchase checks Once the sale is live, you can use the `useSonarPurchase` hook to run pre-purchase checks. [Reference docs](../reference/sonar-react#usesonarpurchase) for the `useSonarPurchase` hook. If the entity is not ready to purchase, the reason why will be returned in the `failureReason` field. If a liveness check is required, the `livenessCheckURL` field will be returned and you should redirect the user to this URL to complete the liveness check. ```tsx theme={null} import { PrePurchaseFailureReason } from "@echoxyz/sonar-core"; import { useSonarPurchase, } from "@echoxyz/sonar-react"; function PrePurchaseStatusPanel({ entityID, walletAddress, }: { entityID: string; walletAddress: `0x${string}`; }) { const sonarPurchaser = useSonarPurchase({ saleUUID: "YOUR_SALE_UUID", entityID, walletAddress, }); if (sonarPurchaser.loading) { return

Loading...

; } if (sonarPurchaser.error) { return

Error: {sonarPurchaser.error.message}

; } return (
{sonarPurchaser.readyToPurchase && ( Ready to purchase! )} {!sonarPurchaser.readyToPurchase && sonarPurchaser.failureReason === PrePurchaseFailureReason.REQUIRES_LIVENESS && ( Complete liveness check to purchase )}
); } ``` See the example app [PurchaseCard](https://github.com/sunrisedotdev/sonar-example-react/blob/main/src/components/sale/PurchaseCard.tsx) for more detail on how to interpret the state and display it to the user. ## Generating a purchase permit to send to the sale contract If the entity is ready to purchase and you are running an onchain sale, you will need to: 1. Use the `generatePurchasePermit` function to fetch a signed purchase permit from Sonar 2. Construct a transaction including the purchase permit and have the user sign it 3. Send the transaction to the sale contract In this example we are going to use the [`wagmi`](https://wagmi.sh/) library. First, you will need to get a copy of the sale contract's ABI and include it in your project. If you are using the generic [SettlementSale](/sonar/reference/contracts/settlement-sale) contract, you can find the ABI [here](https://github.com/sunrisedotdev/sonar/blob/main/contracts/scripts/abis/SettlementSale.ts). Then, let's create a hook for managing the transaction lifecycle. ```tsx theme={null} import { GeneratePurchasePermitResponse } from "@echoxyz/sonar-core"; import { useCallback, useState } from "react"; import { useWriteContract, useWaitForTransactionReceipt } from "wagmi"; import { useConfig } from "wagmi"; import { simulateContract } from "wagmi/actions"; import { YourSaleContractABI } from "./YourSaleContractABI"; export const useSaleContract = () => { const { writeContractAsync } = useWriteContract(); const config = useConfig(); const [txHash, setTxHash] = useState<`0x${string}` | undefined>(undefined); // Track the state of the transaction receipt const { data: txReceipt, isFetching: awaitingTxReceipt, error: awaitingTxReceiptError, } = useWaitForTransactionReceipt({ hash: txHash, }); // This function is used to construct the transaction, // simulate it, and then submit it after the user has signed it const commitWithPermit = useCallback( async ({ purchasePermitResp, amount, }: { purchasePermitResp: GeneratePurchasePermitResponse; amount: bigint; }) => { if (!("MinPrice" in purchasePermitResp.PermitJSON)) { throw new Error("Invalid purchase permit response"); } const permit = purchasePermitResp.PermitJSON; // Your args might be different if you are not using the generic SettlementSale contract. // But the format of the purchase permit should be the same. const commitmentArgs = [ "PAYMENT_TOKEN_ADDRESS", { amount: amount, price: 0n, lockup: false }, { saleSpecificEntityID: permit.SaleSpecificEntityID, saleUUID: permit.SaleUUID, wallet: permit.Wallet, expiresAt: BigInt(permit.ExpiresAt), minAmount: BigInt(permit.MinAmount), maxAmount: BigInt(permit.MaxAmount), minPrice: BigInt(permit.MinPrice), maxPrice: BigInt(permit.MaxPrice), opensAt: BigInt(permit.OpensAt), closesAt: BigInt(permit.ClosesAt), payload: permit.Payload, }, purchasePermitResp.Signature, ] as const; // Assumes that the sender has already approved the sale contract to spend the token. // Note that the SettlementSale contract also provides the option of committing with an ERC20 permit (replaceBidWithPermit) const { request } = await simulateContract(config, { address: "YOUR_SALE_CONTRACT_ADDRESS", abi: YourSaleContractABI, functionName: "YOUR_PURCHASE_FUNCTION_NAME", // e.g. replaceBidWithApproval for the SettlementSale contract args: commitmentArgs, }); setTxHash( await writeContractAsync(request, { onError: (error: Error) => { throw error; }, }) ); }, [writeContractAsync, config] ); return { commitWithPermit, awaitingTxReceipt, txReceipt, awaitingTxReceiptError, }; }; ``` Then in a component, we can use this hook and call the returned `commitWithPermit` function as part of a button click handler. ```tsx theme={null} import { GeneratePurchasePermitResponse } from "@echoxyz/sonar-core"; import { useState } from "react"; import { useSaleContract } from "./useSaleContract"; function CommitPanel({ amount, generatePurchasePermit, // From the useSonarPurchase hook }: { amount: bigint; generatePurchasePermit: () => Promise; }) { const { commitWithPermit, awaitingTxReceipt, txReceipt, awaitingTxReceiptError, } = useSaleContract(); const [loading, setLoading] = useState(false); const [error, setError] = useState(undefined); const commit = async () => { setLoading(true); setError(undefined); try { const purchasePermitResp = await generatePurchasePermit(); await commitWithPermit({ purchasePermitResp: purchasePermitResp, amount: amount, }); } catch (error) { setError(error as Error); } finally { setLoading(false); } }; return (
{awaitingTxReceipt && !txReceipt && (

Waiting for transaction receipt...

)} {txReceipt?.status === "success" && (

Commitment successful

)} {txReceipt?.status === "reverted" && (

Commitment reverted

)} {error &&

{error.message}

} {awaitingTxReceiptError && (

{awaitingTxReceiptError.message}

)}
); } ``` If you are implementing your own contract, then you must validate that the purchase permit has been signed by Sonar and that the permit data is valid. See the [custom contracts guide](/sonar/integration-guides/custom-contracts) for more details. # Further reading ## Retrieving user investment history This is an optional feature for retrieving users past Echo private group investments. Once authenticated, you can retrieve a user's investment history using the `useEntityInvestmentHistory` hook. This shows all deals they've previously participated in, which can be useful if you are intending to give reputational boost/extra points if they have invested in a particulat deal. [Reference docs](../reference/sonar-react#useentityinvestmenthistory) for the `useEntityInvestmentHistory` hook. # Integration Overview Source: https://docs.echo.xyz/sonar/integration-guides/frontend-overview Choose the right frontend integration approach for your project. ## Prerequisites Before starting your integration: * Review [Key Concepts](/sonar/key-concepts) for an overview of Sonar's architecture * Read the [Technical Overview](/sonar/technical-overview) to understand the end-to-end purchase flow * Understand [Entities](/sonar/core-features/entities) to learn how users, entities, and wallets relate ## Integration Approaches Your frontend application orchestrates the complete purchase flow: user authentication, eligibility verification, requesting purchase permits, and submitting transactions onchain. Choose an approach based on your architecture. **Best for: SPAs without a backend** All authentication and API calls happen client-side using React hooks. Tokens are stored in browser storage. * Simpler to implement * Uses `@echoxyz/sonar-react` hooks * [Example app →](https://github.com/sunrisedotdev/sonar-example-react) **Best for: Apps that already have a backend** OAuth tokens are stored server-side and all Sonar API requests are proxied through your backend. * More secure (tokens never exposed to browser) * Automatic token refresh on server * [Example app →](https://github.com/sunrisedotdev/sonar-example-nextjs) ## Solana (SVM) If your sale runs on Solana, the Sonar API calls work the same way as in the guides above. Follow either approach for OAuth and entity management, then refer to the Solana guide for the chain-specific wallet adapter and transaction construction. Wallet adapter setup, PDA derivation, and `place_bid` transaction construction for Solana sales. * [Example app (React) →](https://github.com/sunrisedotdev/sonar-example-react-svm) * [Example app (Next.js) →](https://github.com/sunrisedotdev/sonar-example-nextjs-svm) ## Testing Your Integration Use [test sales](/sonar/core-features/test-sales) during development to simulate various entity states, including setup progress, eligibility status, and failure scenarios. Test sales allow you to verify your integration handles edge cases without completing actual verification. # Solana (SVM) Source: https://docs.echo.xyz/sonar/integration-guides/frontend-svm Integrate Sonar into a Solana application using the Solana wallet adapter. React SPA example using the Solana wallet adapter. Next.js example with server-side token management. This guide covers the Solana-specific parts of a Sonar integration. The Sonar API calls (authentication, entities, pre-purchase checks, purchase permits) work the same way as in the EVM guides. Only the wallet adapter and contract interaction differ. Follow the [Frontend-only guide](/sonar/integration-guides/frontend-only) for a React SPA, or the [Frontend with Backend guide](/sonar/integration-guides/frontend-with-backend) for Next.js, to handle Sonar OAuth and API calls. Then use this guide for the Solana transaction layer. ## Installation ```bash theme={null} npm install @echoxyz/sonar-core @echoxyz/sonar-react \ @solana/wallet-adapter-react @solana/wallet-adapter-react-ui \ @solana/web3.js @solana/spl-token \ @coral-xyz/anchor uuid ``` ## Provider setup Wrap your app with the Solana connection and wallet providers alongside `SonarProvider`: ```tsx theme={null} import { SonarProvider } from "@echoxyz/sonar-react"; import { ConnectionProvider, WalletProvider } from "@solana/wallet-adapter-react"; import { WalletModalProvider } from "@solana/wallet-adapter-react-ui"; import "@solana/wallet-adapter-react-ui/styles.css"; // RPC endpoint and program ID must target the same cluster const SOLANA_CLUSTERS = { mainnet: { // Public endpoint is rate-limited; replace with a private RPC URL for production rpcUrl: "https://api.mainnet-beta.solana.com", programId: "6RudLQPUCBssZiodR3q4PPLgYARNdZYM7HCtL6cZ9DyU", }, devnet: { rpcUrl: "https://api.devnet.solana.com", programId: "3XxHCh947y1PAMK5y8oecBtaLU7TtTj9r4yMYwzFbJYs", }, }; const { rpcUrl: RPC_URL, programId: PROGRAM_ID } = SOLANA_CLUSTERS.mainnet; function App() { return ( {/* Your application */} ); } ``` ## Configuration You'll need three sale-specific values alongside the standard Sonar config: | Variable | Description | | - | - | | `PROGRAM_ID` | The Sonar settlement sale program for your cluster (see below) | | `PAYMENT_TOKEN_MINT` | The SPL token mint address accepted as payment | | `SALE_UUID` | Your sale's UUID from the Echo founder dashboard | The settlement sale program is deployed at a different address on each cluster: | Cluster | Program ID | | - | - | | Mainnet (`sol`) | `6RudLQPUCBssZiodR3q4PPLgYARNdZYM7HCtL6cZ9DyU` | | Devnet (`soldev`) | `3XxHCh947y1PAMK5y8oecBtaLU7TtTj9r4yMYwzFbJYs` | Use the program ID that matches the cluster of your RPC endpoint. Pairing a mainnet RPC endpoint with the devnet program ID (or the reverse) causes transactions to fail. ## Committing funds to the sale Submitting a bid on Solana requires a two-instruction transaction: 1. An Ed25519 signature verification instruction (proving the purchase permit was signed by Sonar) 2. The `place_bid` program instruction Both instructions must be in the same transaction with the Ed25519 instruction immediately preceding `place_bid`. The program validates the permit signature via instruction introspection. ### Deriving PDAs The program uses Program Derived Addresses for all state. Derive these before building the transaction: ```ts theme={null} import { PublicKey } from "@solana/web3.js"; import { parse as uuidParse } from "uuid"; // IDs from the Sonar API may be 0x-prefixed or UUID-formatted function parseIdBytes(id: string): Uint8Array { const s = id.replace(/^0x/i, ""); return s.includes("-") ? uuidParse(s) : Buffer.from(s, "hex"); } const programPublicKey = new PublicKey(PROGRAM_ID); // Sale PDA — derived from the sale UUID const [salePDA] = PublicKey.findProgramAddressSync( [Buffer.from("settlement_sale"), Buffer.from(parseIdBytes(saleUUID))], programPublicKey ); // Entity state PDA — derived from the sale PDA and the sale-specific entity ID const [entityStatePDA] = PublicKey.findProgramAddressSync( [Buffer.from("entity_state"), salePDA.toBuffer(), Buffer.from(parseIdBytes(saleSpecificEntityID))], programPublicKey ); // Wallet binding PDA — derived from the sale PDA and the bidder's wallet const [walletBindingPDA] = PublicKey.findProgramAddressSync( [Buffer.from("wallet_binding"), salePDA.toBuffer(), wallet.publicKey.toBuffer()], programPublicKey ); ``` ### Encoding the permit The purchase permit must be Borsh-encoded using the program IDL to produce the message bytes for Ed25519 verification. Copy the IDL from the [example app](https://github.com/sunrisedotdev/sonar-example-react-svm/tree/main/src/idl) into your project. ```ts theme={null} import { BorshCoder, BN } from "@coral-xyz/anchor"; import { IDL } from "./idl/settlement_sale"; // permit is the PermitJSON field from Sonar's generatePurchasePermit response const permitData = { saleSpecificEntityId: parseIdBytes(permit.SaleSpecificEntityID), saleUuid: parseIdBytes(permit.SaleUUID), wallet: Array.from(new PublicKey(permit.Wallet).toBytes()), expiresAt: new BN(permit.ExpiresAt), minAmount: new BN(permit.MinAmount), maxAmount: new BN(permit.MaxAmount), minPrice: new BN(permit.MinPrice), maxPrice: new BN(permit.MaxPrice), opensAt: new BN(permit.OpensAt), closesAt: new BN(permit.ClosesAt), payload: Buffer.from(permit.Payload.replace(/^0x/, ""), "hex"), }; const coder = new BorshCoder(IDL); const messageBytes = coder.types.encode("purchasePermitV3", permitData); ``` ### Building and submitting the transaction ```ts theme={null} import { Ed25519Program, PublicKey, SYSVAR_INSTRUCTIONS_PUBKEY, SystemProgram, Transaction, } from "@solana/web3.js"; import { AnchorProvider, Program } from "@coral-xyz/anchor"; import { TOKEN_PROGRAM_ID, getAssociatedTokenAddressSync } from "@solana/spl-token"; const provider = new AnchorProvider(connection, wallet, { commitment: "confirmed" }); const program = new Program(IDL, provider); // Fetch the sale account to get the permit signer public key and vault address const saleAccount = await program.account.settlementSale.fetch(salePDA); // Ed25519 verify instruction — must immediately precede place_bid const ed25519Ix = Ed25519Program.createInstructionWithPublicKey({ publicKey: saleAccount.permitSigner.toBytes(), message: messageBytes, signature: Buffer.from(purchasePermitResp.Signature.replace(/^0x/, ""), "hex"), }); const bidderTokenAccount = getAssociatedTokenAddressSync( new PublicKey(PAYMENT_TOKEN_MINT), wallet.publicKey ); const placeBidIx = await program.methods .placeBid(permitData, new BN(amount.toString()), new BN(0), false) .accounts({ bidder: wallet.publicKey, sale: salePDA, entityState: entityStatePDA, walletBinding: walletBindingPDA, bidderTokenAccount, vault: saleAccount.vault, paymentTokenMint: new PublicKey(PAYMENT_TOKEN_MINT), tokenProgram: TOKEN_PROGRAM_ID, systemProgram: SystemProgram.programId, instructions: SYSVAR_INSTRUCTIONS_PUBKEY, }) .instruction(); const tx = new Transaction(); tx.add(ed25519Ix, placeBidIx); tx.feePayer = wallet.publicKey; const { blockhash } = await connection.getLatestBlockhash(); tx.recentBlockhash = blockhash; const signed = await wallet.signTransaction(tx); const sig = await connection.sendRawTransaction(signed.serialize()); await connection.confirmTransaction(sig, "confirmed"); ``` ## Reading committed amounts To show a participant their current committed amount, poll the `entityState` account: ```ts theme={null} const state = await program.account.entityState.fetchNullable(entityStatePDA); const committedAmount = state ? BigInt(state.currentAmount.toString()) : BigInt(0); ``` A `null` result means the entity hasn't placed a bid yet; treat the committed amount as zero. ## Further reading Program reference: PDAs, instructions, and account types React SPA auth and Sonar API patterns Next.js server-side auth patterns How Sonar authorizes participation # Frontend with Backend Source: https://docs.echo.xyz/sonar/integration-guides/frontend-with-backend Integrate a Next.js application with Sonar, using server-side token management for improved security. A complete Next.js implementation showing this integration approach. This guide covers integrating Sonar with a backend that stores OAuth tokens server-side. All Sonar API calls are made via server actions, so tokens never reach the browser. For SPAs without a backend, see the simpler [Frontend-only](/sonar/integration-guides/frontend-only) approach. ## Backend access model There is no server-side, shared, or dev API key. Every entity-scoped Sonar API call is authenticated with the end user's OAuth access token. This is the single most common misunderstanding when building a backend against Sonar. Entity-scoped data can only be read with the token of the user it belongs to. This includes: * Registration and KYC status * Eligibility and pre-purchase checks * Entity information * Generating purchase permits Because there is no shared key, your backend must persist each user's OAuth token and refresh it when it expires. See [Token storage](#token-storage) for persistence and [Defining server actions](#defining-server-actions) for the refresh flow (the [example app](https://github.com/sunrisedotdev/sonar-example-nextjs) demonstrates refreshing expired tokens). ### What needs a token, and what doesn't Committed amounts live on the sale contract and can be read directly from the chain without any token. See [Reading commitment data](/sonar/integration-guides/reading-commitment-data). Registration, KYC, and eligibility status are only available through the authenticated Sonar API, so they must be fetched per user with that user's (refreshed) token. See [Authentication](/sonar/core-features/authentication) for how tokens are obtained. ## How it works ```mermaid theme={null} sequenceDiagram participant U as User participant B as Browser participant Y as Your Server participant E as Echo OAuth participant S as Sonar API participant C as Sale Contract Note over U,E: OAuth Authentication U->>B: Click "Connect with Sonar" B->>Y: Server Action: getSonarAuthorizationUrl() Y->>Y: Generate PKCE params Y->>B: Return redirect URL B->>E: Navigate to OAuth E->>E: User authenticates E->>B: Redirect with code B->>Y: Server Action: handleSonarCallback(code, state) Y->>E: Exchange code for tokens E->>Y: Return tokens Y->>Y: Store tokens server-side Y->>B: Success Note over U,S: Purchase Flow (via Server Actions) U->>B: Click "Purchase" B->>Y: Server Action: generatePurchasePermit() Y->>Y: Refresh token if needed Y->>S: POST /purchase-permit S->>Y: Return signed permit Y->>B: Return permit Note over U,C: Contract Interaction B->>C: purchase(amount, permit, signature) C->>C: Verify permit signature C->>C: Execute purchase C->>B: Transaction receipt ``` ## Installation ```bash theme={null} npm install @echoxyz/sonar-core ``` Note: Unlike the frontend-only approach, you don't need `@echoxyz/sonar-react` since you'll be making API calls through your backend. ## Example storage interfaces ### Token storage You'll need a way to persist OAuth tokens on the server, keyed by user ID. In production, you should use a database. For demonstration purposes, the example below uses in-memory storage. ```typescript theme={null} // lib/token-store.ts export interface SonarTokens { accessToken: string; refreshToken: string; expiresAt: number; // Unix timestamp in seconds } /** * In-memory token store implementation. * Tokens are stored in a Map and will be lost on server restart. * This can be easily swapped for a database-backed implementation. */ class InMemoryTokenStore { private tokens: Map = new Map(); setTokens(userId: string, tokens: SonarTokens): void { this.tokens.set(userId, tokens); } getTokens(userId: string): SonarTokens | null { return this.tokens.get(userId) || null; } clearTokens(userId: string): void { this.tokens.delete(userId); } } // Singleton instance let tokenStoreInstance: InMemoryTokenStore | null = null; export function getTokenStore(): InMemoryTokenStore { if (!tokenStoreInstance) { tokenStoreInstance = new InMemoryTokenStore(); } return tokenStoreInstance; } ``` See the example app [token-store.ts](https://github.com/sunrisedotdev/sonar-example-nextjs/blob/main/src/lib/token-store.ts) for the full implementation. ### PKCE verifier storage During the OAuth flow, you need to store the PKCE code verifier between the initial redirect and the callback. This must be stored server-side and associated with the OAuth state parameter, along with the user ID to verify session consistency. ```typescript theme={null} // lib/pkce-store.ts interface PKCEEntry { userId: string; codeVerifier: string; } // WARNING: In-memory storage is for demonstration only. // In production, use a database or session storage. const pkceStore = new Map(); // Store the verifier and user ID when starting the OAuth flow export function setPKCEVerifier(state: string, userId: string, codeVerifier: string): void { pkceStore.set(state, { userId, codeVerifier }); } // Retrieve the verifier when completing the OAuth flow export function getPKCEVerifier(state: string): PKCEEntry | null { return pkceStore.get(state) || null; } // Clear the verifier after successful token exchange export function clearPKCEVerifier(state: string): void { pkceStore.delete(state); } ``` See the example app [pkce-store.ts](https://github.com/sunrisedotdev/sonar-example-nextjs/blob/main/src/lib/pkce-store.ts) for the full implementation with expiry handling. ## Implementing the OAuth flow The OAuth flow uses two server actions: one to generate the authorization URL, and one to handle the callback. The `createSonarClient` helper used below is defined in the [Server actions](#server-actions-for-sonar-api-requests) section. ### Starting the OAuth flow When the user clicks "Connect with Sonar", a server action generates the authorization URL with PKCE parameters: ```typescript theme={null} // app/actions/auth.ts "use server"; import { generatePKCEParams, buildAuthorizationUrl } from "@echoxyz/sonar-core"; import { getSession } from "@/lib/session"; import { setPKCEVerifier } from "@/lib/pkce-store"; /** * Generate Sonar OAuth authorization URL with PKCE */ export async function getSonarAuthorizationUrl(): Promise { const session = await getSession(); if (!session) { throw new Error("Unauthorized"); } // Generate PKCE parameters (code verifier, challenge, and state) const { codeVerifier, codeChallenge, state } = await generatePKCEParams(); // Store code verifier linked to state token (will be retrieved in callback) setPKCEVerifier(state, session.userId, codeVerifier); // Build the authorization URL const authorizationUrl = buildAuthorizationUrl({ clientUUID: "YOUR_OAUTH_CLIENT_UUID", redirectURI: "YOUR_REDIRECT_URI", state, codeChallenge, }); return authorizationUrl.toString(); } ``` ### Handling the OAuth callback After the user authenticates with Echo, they're redirected to a callback page. This page extracts the `code` and `state` parameters and calls a server action to complete the flow: ```typescript theme={null} // app/actions/auth.ts (continued) import { createSonarClient } from "@/lib/sonar"; import { getPKCEVerifier, clearPKCEVerifier } from "@/lib/pkce-store"; import { getTokenStore, SonarTokens } from "@/lib/token-store"; /** * Handle OAuth callback - exchange authorization code for tokens */ export async function handleSonarCallback(code: string, state: string): Promise { const session = await getSession(); if (!session) { throw new Error("Unauthorized: No active session"); } // Retrieve the PKCE verifier using the state token const stateData = getPKCEVerifier(state); if (!stateData) { throw new Error("Invalid state: OAuth state token not found or expired"); } // Verify the state belongs to the current session if (stateData.userId !== session.userId) { throw new Error("Invalid session: State token does not match current session"); } // Exchange the authorization code for tokens const client = createSonarClient(session.userId); const tokenData = await client.exchangeAuthorizationCode({ code, codeVerifier: stateData.codeVerifier, redirectURI: "YOUR_REDIRECT_URI", }); // Store the tokens const expiresAt = Math.floor(Date.now() / 1000) + tokenData.expires_in; const sonarTokens: SonarTokens = { accessToken: tokenData.access_token, refreshToken: tokenData.refresh_token, expiresAt, }; getTokenStore().setTokens(session.userId, sonarTokens); // Clean up the PKCE verifier clearPKCEVerifier(state); } /** * Disconnect Sonar account (remove stored tokens) */ export async function disconnectSonar(): Promise { const session = await getSession(); if (!session) { throw new Error("Unauthorized"); } getTokenStore().clearTokens(session.userId); } ``` The callback page itself is a client component that calls the server action: ```tsx theme={null} // app/oauth/callback/page.tsx "use client"; import { Suspense, useEffect, useState } from "react"; import { useSearchParams } from "next/navigation"; import { handleSonarCallback } from "@/app/actions/auth"; function OAuthCallbackContent() { const searchParams = useSearchParams(); const [error, setError] = useState(null); useEffect(() => { const processCallback = async () => { const code = searchParams.get("code"); const state = searchParams.get("state"); const oauthError = searchParams.get("error"); if (oauthError) { setError(`OAuth error: ${oauthError}`); return; } if (!code || !state) { setError("Missing authorization code or state"); return; } try { await handleSonarCallback(code, state); // Success - redirect to home window.location.href = "/"; } catch (err) { setError(err instanceof Error ? err.message : "Failed to process OAuth callback"); } }; processCallback(); }, [searchParams]); if (error) { return

{error}

; } return

Connecting to Sonar...

; } export default function OAuthCallback() { return ( Loading...

}>
); } ``` See the example app [auth.ts](https://github.com/sunrisedotdev/sonar-example-nextjs/blob/main/src/app/actions/auth.ts) for the full implementation. ## Server actions for Sonar API requests All Sonar API requests go through server actions so that access tokens are never exposed to the browser. ### Sonar client factory Create helper functions to instantiate and refresh the Sonar client: ```typescript theme={null} // lib/sonar.ts import { getTokenStore, SonarTokens } from "@/lib/token-store"; import { createClient, SonarClient } from "@echoxyz/sonar-core"; /** * Create a SonarClient instance for a specific user. * Sets the access token from our server-side token store. */ export function createSonarClient(userId: string): SonarClient { const client = createClient({ onUnauthorized: () => { getTokenStore().clearTokens(userId); }, }); const tokens = getTokenStore().getTokens(userId); if (tokens?.accessToken) { client.setToken(tokens.accessToken); } return client; } ``` ### Defining server actions Create a `createSonarServerAction` wrapper that handles session authentication and automatic token refresh: ```typescript theme={null} // lib/sonar.ts (continued) import { getSession } from "@/lib/session"; type ServerActionHandler = (client: SonarClient, input: I) => Promise; /** * Creates a Sonar server action with authentication and automatic token refresh. */ export function createSonarServerAction( handler: ServerActionHandler ): (input: I) => Promise { return async (input: I) => { // Check session authentication const session = await getSession(); if (!session) { throw new Error("Unauthorized"); } // Get tokens from store let tokens = getTokenStore().getTokens(session.userId); if (!tokens) { throw new Error("Sonar account not connected"); } // Check if token needs refresh (within 5 minutes of expiry) const now = Math.floor(Date.now() / 1000); if (tokens.expiresAt - now < 300) { tokens = await refreshSonarToken(session.userId, tokens.refreshToken); getTokenStore().setTokens(session.userId, tokens); } const client = createSonarClient(session.userId); return handler(client, input); }; } /** * Refresh Sonar access token using refresh token. * NOTE: Consider how to prevent multiple concurrent refresh attempts for the * same user. The example app uses promise coalescing as one solution. */ export async function refreshSonarToken(userId: string, refreshToken: string): Promise { const client = createClient() const tokenData = await client.refreshToken({ refreshToken }); const expiresAt = Math.floor(Date.now() / 1000) + tokenData.expires_in; return { accessToken: tokenData.access_token, refreshToken: tokenData.refresh_token || refreshToken, expiresAt, }; } ``` With the wrapper in place, each server action is simple to define: ```typescript theme={null} // app/actions/sonar.ts "use server"; import { createSonarServerAction } from "@/lib/sonar"; import { ListAvailableEntitiesResponse, PrePurchaseCheckResponse, GeneratePurchasePermitResponse, APIError, } from "@echoxyz/sonar-core"; type ListAvailableEntitiesInput = { saleUUID: string }; /** * Fetch all entities for the authenticated user */ export const getEntities = createSonarServerAction( async (client, { saleUUID }) => { if (!saleUUID) { throw new Error("Missing saleUUID"); } return client.listAvailableEntities({ saleUUID }); } ); type PrePurchaseCheckInput = { saleUUID: string; entityID: string; walletAddress: string }; /** * Perform pre-purchase check for an entity */ export const prePurchaseCheck = createSonarServerAction< PrePurchaseCheckInput, PrePurchaseCheckResponse >(async (client, { saleUUID, entityID, walletAddress }) => { if (!saleUUID || !entityID || !walletAddress) { throw new Error("Missing required parameters"); } return client.prePurchaseCheck({ saleUUID, entityID, walletAddress }); }); type GeneratePurchasePermitInput = { saleUUID: string; entityID: string; walletAddress: string }; /** * Generate a purchase permit for an entity */ export const generatePurchasePermit = createSonarServerAction< GeneratePurchasePermitInput, GeneratePurchasePermitResponse >(async (client, { saleUUID, entityID, walletAddress }) => { if (!saleUUID || !entityID || !walletAddress) { throw new Error("Missing required parameters"); } return client.generatePurchasePermit({ saleUUID, entityID, walletAddress }); }); ``` See the example app [sonar.ts](https://github.com/sunrisedotdev/sonar-example-nextjs/blob/main/src/app/actions/sonar.ts) for the full implementation. ## Frontend implementation With the server actions in place, the client-side components can be implemented as follows: ### Authentication button The auth button calls the `getSonarAuthorizationUrl` server action and redirects to the returned URL: ```tsx theme={null} // components/SonarAuthButton.tsx "use client"; import { getSonarAuthorizationUrl, disconnectSonar } from "@/app/actions/auth"; export function SonarAuthButton({ sonarConnected }: { sonarConnected: boolean }) { const handleConnect = async () => { try { const url = await getSonarAuthorizationUrl(); window.location.href = url; } catch (error) { console.error("Failed to get Sonar authorization URL:", error); } }; const handleDisconnect = async () => { try { await disconnectSonar(); window.location.reload(); } catch (error) { console.error("Failed to disconnect Sonar:", error); } }; return ( ); } ``` ### Fetching the state of a user's Sonar entities For the other Sonar API calls, we recommend wrapping these in React hooks. Then these hooks can be called in a very similar way to if you were calling the Sonar API directly via the `@echoxyz/sonar-react` library. See [the frontend-only guide](/sonar/integration-guides/frontend-only#fetching-state-of-a-user’s-sonar-entities) for an example. ```typescript theme={null} // hooks/use-sonar-entities.ts "use client"; import { ListAvailableEntitiesResponse } from "@echoxyz/sonar-core"; import { saleUUID } from "@/lib/config"; import { useSonarQuery } from "./use-sonar-query"; import { getEntities } from "@/app/actions/sonar"; export function useSonarEntities() { const { loading, data, error } = useSonarQuery<{ saleUUID: string }, ListAvailableEntitiesResponse>(getEntities, { saleUUID, }); return { loading, entities: data?.Entities, error, }; } ``` ### Running pre-purchase checks and generating purchase permits Also create a hook for the purchase flow: ```typescript theme={null} // hooks/use-sonar-purchase.ts "use client"; import { useCallback, useState, useEffect } from "react"; import { prePurchaseCheck, generatePurchasePermit } from "@/app/actions/sonar"; import { GeneratePurchasePermitResponse, PrePurchaseFailureReason } from "@echoxyz/sonar-core"; export function useSonarPurchase(args: { saleUUID: string; entityID: string; walletAddress: string; }) { const [loading, setLoading] = useState(true); const [readyToPurchase, setReadyToPurchase] = useState(false); const [failureReason, setFailureReason] = useState(); const [error, setError] = useState(); useEffect(() => { const checkPurchase = async () => { setLoading(true); try { const result = await prePurchaseCheck(args); setReadyToPurchase(result.ReadyToPurchase); if (!result.ReadyToPurchase) { setFailureReason(result.FailureReason as PrePurchaseFailureReason); } } catch (err) { setError(err instanceof Error ? err : new Error(String(err))); } finally { setLoading(false); } }; checkPurchase(); }, [args.saleUUID, args.entityID, args.walletAddress]); const generatePermit = useCallback(async (): Promise => { return generatePurchasePermit(args); }, [args.saleUUID, args.entityID, args.walletAddress]); return { loading, readyToPurchase, failureReason, error, generatePurchasePermit: generatePermit }; } ``` ### Submitting the purchase transaction Once you have a purchase permit, submit it to your sale contract. This is the same as the frontend-only approach since the contract interaction happens directly from the browser—see [the frontend-only guide](/sonar/integration-guides/frontend-only#generating-a-purchase-permit-to-send-to-the-sale-contract) for the full implementation. # Reading Commitment Data Source: https://docs.echo.xyz/sonar/integration-guides/reading-commitment-data Display live commitment data and statistics on your sale page. This guide covers how to fetch and display commitment data for your sale, including total amounts committed, participant counts, and individual commitments. The commitment data API is public and does not require authentication, so you can display this information to all visitors. ## Use cases * Display the total amount committed to your sale * Show the number of unique participants * List recent commitments to create a live activity feed * For auctions: show the current estimated clearing price ## Data freshness and limits The commitment data API reads directly from the sale contract, but it is designed for displaying live sale activity rather than for reconciliation. Keep the following characteristics in mind: * **Caching:** Responses are cached for about a minute, so newly confirmed commitments may take up to that long to appear. * **Recent commitments only:** The `Commitments` array contains only the most recent 100 commitments. There is no pagination, so on larger sales this window will not include every commitment. * **Clearing price:** The auction clearing price is computed off-chain by Sonar. The `ClearingPriceNumerator` and `ClearingPriceDenominator` fields are the source of truth for it; it is not derived on-chain. For a complete or exact per-entity total (for example, on large sales, or when reconciling a specific entity's committed amount), read the committed amount directly from the sale contract rather than relying on the API's 100-record window. See [smart contract operations](../operations/smart-contract-operations) for how to query the contract directly. ### Polling, not webhooks There is no webhook or subscription for commitment updates. Polling the endpoint (or the `useCommitmentData` hook, which accepts a `pollingIntervalMs`) is the intended pattern for keeping displayed data fresh. ## Using the React hook The simplest way to fetch commitment data is with the `useCommitmentData` hook from `@echoxyz/sonar-react`. ```tsx theme={null} import { useCommitmentData } from "@echoxyz/sonar-react"; function CommitmentStats({ saleUUID }: { saleUUID: string }) { const { loading, commitmentData, error } = useCommitmentData({ saleUUID, pollingIntervalMs: 10000, // Poll every 10 seconds for updates }); if (loading && !commitmentData) { return

Loading...

; } if (error) { return

Error loading commitment data: {error.message}

; } if (!commitmentData) { return null; } return (

Total Participants: {commitmentData.UniqueCommitmentCount}

Total Committed: {commitmentData.TotalCommitmentAmount}

); } ``` The hook supports optional polling to keep the data fresh. If `pollingIntervalMs` is not provided, the data is fetched once when the component mounts. [Reference docs](../reference/sonar-react#usecommitmentdata) for the `useCommitmentData` hook. ## Formatting amounts The `TotalCommitmentAmount` and individual commitment amounts are returned as strings in the payment token's smallest unit (e.g. USDC has 6 decimals, so the smallest unit is 1/1,000,000 of a USDC). Use `PaymentTokenDecimals` to format these values for display: ```tsx theme={null} function formatAmount(amount: string, decimals: number): string { const value = BigInt(amount); const divisor = BigInt(10 ** decimals); const integerPart = value / divisor; return `$${integerPart.toLocaleString()}`; } // Usage const formattedTotal = formatAmount( commitmentData.TotalCommitmentAmount, commitmentData.PaymentTokenDecimals ); ``` ## Displaying recent commitments The `Commitments` array contains individual commitments sorted by creation time (most recent first). Each commitment includes: * `SaleSpecificEntityID`: The entity that made the commitment * `CreatedAt`: When the commitment was made (ISO 8601 timestamp) * `Amounts`: Array of amounts committed per wallet and payment token ```tsx theme={null} import { useCommitmentData } from "@echoxyz/sonar-react"; import { Commitment, WalletTokenAmount } from "@echoxyz/sonar-core"; function calculateTotal(amounts: WalletTokenAmount[]): bigint { return amounts.reduce((sum, item) => sum + BigInt(item.Amount), BigInt(0)); } function formatTimestamp(timestamp: string): string { return new Date(timestamp).toLocaleString(undefined, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", }); } function RecentCommitments({ saleUUID }: { saleUUID: string }) { const { commitmentData } = useCommitmentData({ saleUUID, pollingIntervalMs: 10000, }); if (!commitmentData) { return null; } // Show the 10 most recent commitments const recentCommitments = commitmentData.Commitments.slice(0, 10); if (recentCommitments.length === 0) { return

No commitments yet

; } // Note the commitments also include the price, // which you might also want to display for auction sales. return (

Recent Commitments

    {recentCommitments.map((commitment) => { const total = calculateTotal(commitment.Amounts); const formatted = formatAmount( total.toString(), commitmentData.PaymentTokenDecimals ); return (
  • {formatted} - {formatTimestamp(commitment.CreatedAt)}
  • ); })}
); } function formatAmount(amount: string, decimals: number): string { const value = BigInt(amount); const divisor = BigInt(10 ** decimals); const integerPart = value / divisor; return `$${integerPart.toLocaleString()}`; } ``` ## Auction clearing price For English auction sales, the response includes the current estimated clearing price: * `ClearingPriceNumerator` and `ClearingPriceDenominator`: The clearing price as a fraction (in smallest units of the payment token per smallest unit of the offered token) * `ClearingPriceMicroUSD`: The clearing price in micro-USD (1 USD = 1,000,000 micro-USD) per human-readable offered token The clearing price is recalculated as new bids come in and represents the price that all winning bidders would pay if the auction ended at that moment. The `ClearingPriceMicroUSD` field is convenient for display purposes, but may lose precision. For machine-readable use cases (e.g., passing to a contract or performing calculations), use the `ClearingPriceNumerator` and `ClearingPriceDenominator` fraction instead. ```tsx theme={null} function AuctionClearingPrice({ saleUUID }: { saleUUID: string }) { const { commitmentData } = useCommitmentData({ saleUUID, pollingIntervalMs: 5000, // More frequent polling during an auction }); if (!commitmentData?.ClearingPriceMicroUSD) { return null; } // Convert micro-USD to dollars for display const priceInDollars = Number(commitmentData.ClearingPriceMicroUSD) / 1_000_000; return (

Estimated Clearing Price: ${priceInDollars.toFixed(4)}

); } ``` ## Using the core library directly If you're not using React, you can call the API directly using `SonarClient`: ```typescript theme={null} import { createClient } from "@echoxyz/sonar-core"; const client = createClient(); const commitmentData = await client.readCommitmentData({ saleUUID: "YOUR_SALE_UUID", }); console.log(`Total committed: ${commitmentData.TotalCommitmentAmount}`); console.log(`Participants: ${commitmentData.UniqueCommitmentCount}`); ``` [Reference docs](../reference/sonar-core#readcommitmentdata) for the `readCommitmentData` function. ## API reference For more details on the response format and available fields, see: * [readCommitmentData](../reference/sonar-core#readcommitmentdata) - Core library function * [useCommitmentData](../reference/sonar-react#usecommitmentdata) - React hook * [ReadCommitmentData API](/api-reference/readcommitmentdata) - HTTP API reference # Key Concepts Source: https://docs.echo.xyz/sonar/key-concepts Essential concepts for understanding how Sonar works and implementing successful integrations. ## Core Components Sonar connects three key concepts to enable compliant token sales: **The compliance identity** an individual or organization that completes KYC/KYB verification and receives eligibility to participate in sales. **The authorization permit** signed proof that a wallet can purchase on behalf of an eligible, verified entity. ## How It Works Sonar bridges compliance verification and onchain execution through **purchase permits**, signed proofs that a verified entity that passes all eligibility check as defined by the sale. ### The Purchase Flow 1. **Entity Verification**: Users complete KYC/KYB and receive verified entity status 2. **Purchase Authorization**: Sonar generates signed permits for eligible purchases 3. **Onchain Execution**: Your smart contract validates permits and executes purchases Purchase permits are short-lived (10 minutes), sale-specific, and tied to both the entity and wallet address for maximum security. ## Offchain Mechanism Architecture A critical aspect of Sonar's design is that **pricing and settlement logic runs offchain** in Sonar's backend, not in the smart contract. The smart contract serves as an **escrow and record-keeping mechanism**: * Records committed funds and bid data * Validates purchase permits * Stores final allocations * Processes refunds and proceeds This separation provides flexibility to change pricing and settlement strategies without modifying contracts, while maintaining the security of on-chain fund custody. ## Terminology Understanding the terminology used throughout the documentation: | Term | Definition | | - | - | | **Commitment** | Funds pledged by a participant during the sale. General term for any sale type. | | **Bid** | A commitment that includes a price (used in auctions). Contains both amount and price. | | **Allocation** | The portion of a participant's commitment that is accepted after settlement. | | **Refund** | The portion of a participant's commitment that is returned (commitment minus allocation). | ## Compliance & Security Sonar handles the complex compliance requirements automatically: * **KYC/KYB Verification**: Entities complete identity verification appropriate for their jurisdiction * **Risk Screening**: All wallet addresses are screened against sanctions lists and high-risk activity * **Purchase Limits**: Flexible purchase limits for different entity types * **Continuous Monitoring**: Compliance checking throughout the sale process ## Sale Lifecycle Token sales progress through five distinct phases: 1. **Setup** - Configure sale parameters, deploy contracts, integrate frontend 2. **Commitment Phase** - Users commit funds, Sonar issues purchase permits 3. **Cancellation Phase** (optional) - Cooling-off period for regulatory compliance 4. **Settlement Phase** - Compute final allocations and record on-chain 5. **Distribution** - Deliver tokens and process refunds See the complete end-to-end sale process with timing and responsibilities # Smart Contract Operations Source: https://docs.echo.xyz/sonar/operations/smart-contract-operations How to manage sale stages, set allocations, process refunds, and withdraw proceeds on the SettlementSale contract After a sale's commitment phase closes, you'll need to finalize allocations, process refunds, and withdraw proceeds. This page describes both the available tooling and the underlying contract functions. This can be done through the Founder Dashboard, but we also provide scripts to perform these operations manually (e.g. if you haven't granted the Sonar backend the necessary roles). ## Available Scripts Sonar provides TypeScript scripts to manage common post-commitment operations. For full usage instructions, CSV formats, and all available options, see the [Contract Scripts README](https://github.com/sunrisedotdev/sonar/blob/main/contracts/scripts/README.md). | Script | Purpose | | - | - | | `commitment-data-csv` | Export all commitment data from the sale contract to a CSV | | `set-allocations` | Set accepted allocation amounts for each entity's wallets | | `process-refunds` | Refund the difference between committed and accepted amounts | ## Typical Workflow 1. **Export commitments** from the contract to analyze bids 2. **Prepare allocations** by creating a CSV with accepted amounts 3. **Validate allocations** using dry-run mode 4. **Submit allocations** to the contract *** ## Contract Function Reference The following functions are available on the [`SettlementSale`](/sonar/reference/contracts/settlement-sale) contract. Functions marked **Sonar-managed** are called by the Sonar backend automatically; you don't need to call them unless you're operating independently. ### Stage Transitions #### `openCommitment()` **Role required**: `SALE_MANAGER_ROLE` | **Stage**: `PreOpen` Transitions the contract to `Commitment`, enabling participants to submit bids. Called automatically by Sonar after deployment. #### `openCancellation()` **Role required**: `SALE_MANAGER_ROLE` | **Stage**: `Commitment` Transitions to `Cancellation`, allowing participants to cancel their bids and receive immediate refunds. This stage is optional. Skip it by calling `openSettlement()` directly from `Commitment` if no cancellation period is needed. #### `openSettlement()` **Role required**: `SALE_MANAGER_ROLE` | **Stage**: `Commitment` or `Cancellation` Transitions to `Settlement`. Once settlement opens, no further cancellations are possible. #### `finalizeSettlement(uint256 expectedTotalAcceptedAmount)` **Role required**: `SETTLEMENT_FINALIZER_ROLE` | **Stage**: `Settlement` Finalizes settlement and transitions to `Done`. The `expectedTotalAcceptedAmount` must exactly match `totalAcceptedAmount()`. This acts as a sanity check to ensure all allocations are correct before closing settlement. Verify `totalAcceptedAmount()` matches your expected total before calling this. The check is exact and the call will revert if there's any discrepancy. *** ### Settlement #### `setAllocations(Allocation[] allocations, bool allowOverwrite)` **Role required**: `SETTLER_ROLE` | **Stage**: `Settlement` | **Sonar-managed** Records the accepted amounts per wallet per payment token. Each `Allocation` specifies: | Field | Type | Description | | - | - | - | | `saleSpecificEntityID` | `bytes16` | The [sale-specific ID](/sonar/core-features/entities#entity-identifiers) for the entity whose wallet is being allocated | | `wallet` | `address` | The wallet address to allocate | | `token` | `address` | The payment token address | | `acceptedAmount` | `uint256` | The accepted amount for this wallet and token | * Accepted amount cannot exceed the wallet's committed amount for that token * Unset allocations are implicitly zero * Set `allowOverwrite=true` to modify a previously set allocation; otherwise the call reverts if a non-zero allocation already exists * Emits `AllocationSet` for each entry The settler must explicitly set each wallet+token pair. Sonar handles this automatically, but if you hold the `SETTLER_ROLE` you can run settlement independently. *** ### Refunds #### `processRefunds(bytes16[] saleSpecificEntityIDs, bool skipAlreadyRefunded)` **Role required**: `REFUNDER_ROLE` | **Stage**: `Done` | **Sonar-managed** Processes refunds for a batch of entities. For each entity, transfers the difference between committed and accepted amounts back to each wallet, per payment token. * `saleSpecificEntityIDs`: array of [sale-specific entity IDs](/sonar/core-features/entities#sale-specific-entityid-sale-scoped) to refund * `skipAlreadyRefunded`: if `true`, skips already-refunded entities; if `false`, reverts if any entity was already refunded * Emits `WalletRefunded` per wallet+token transfer and `EntityRefunded` for the entity total Sonar processes refunds automatically. You can also run refunds yourself if you hold the `REFUNDER_ROLE`. *** ### Withdrawals #### `withdraw()` **Role required**: `DEFAULT_ADMIN_ROLE` | **Stage**: `Done` Withdraws all remaining accepted token balances to the `proceedsReceiver`. Safe to call multiple times; only transfers what hasn't been withdrawn yet. Emits `ProceedsWithdrawn` per token. #### `withdrawPartial(IERC20 token, uint256 amount)` **Role required**: `DEFAULT_ADMIN_ROLE` | **Stage**: `Done` Withdraws a specific amount of a specific token to the `proceedsReceiver`. Useful for test withdrawals or incremental processing. Reverts if `amount` exceeds the available (accepted minus already withdrawn) balance for that token. *** ### Operational Controls #### `pause()` **Role required**: `PAUSER_ROLE` Immediately halts all external user-facing functions (bidding, cancellations, refund claims). State and funds are unchanged. Use in emergencies such as suspicious activity, offchain system issues, or payment token depeg. #### `setPaused(bool isPaused)` **Role required**: `SALE_MANAGER_ROLE` Pauses or unpauses the contract. Use to unpause after a `pause()` call. #### `setClaimRefundEnabled(bool enabled)` **Role required**: `SALE_MANAGER_ROLE` Enables or disables self-service refund claiming by participants. If disabled, only addresses with `REFUNDER_ROLE` can process refunds. #### `setReduceCommitmentEnabled(bool enabled)` **Role required**: `SALE_MANAGER_ROLE` Enables or disables partial commitment reduction via `reduceCommitment()` during the Cancellation stage. Full cancellation via `cancelBid()` is always available regardless of this setting. #### `setProceedsReceiver(address newProceedsReceiver)` **Role required**: `DEFAULT_ADMIN_ROLE` Updates the address that receives sale proceeds on withdrawal. Verify this is correct before calling `withdraw()`. Only affects future withdrawals. #### `setMaxWalletsPerEntity(uint8 max)` **Role required**: `SALE_MANAGER_ROLE` Updates the maximum number of wallet addresses a single entity can use. Must be greater than zero. Entities that have already registered more wallets than the new limit are unaffected. *** ### Role Management #### `grantRole(bytes32 role, address account)` **Role required**: `DEFAULT_ADMIN_ROLE` Grants a role to an address. Takes effect immediately. Common uses: granting additional hot wallets `PAUSER_ROLE` for emergency response, or granting a hardware wallet `SALE_MANAGER_ROLE` for stage transitions. #### `revokeRole(bytes32 role, address account)` **Role required**: `DEFAULT_ADMIN_ROLE` Revokes a role from an address. Review and revoke unused role grants after deployment. *** ### Emergency Operations The following functions are for exceptional circumstances only. Consult the Sonar team before using them. #### `unsafeSetStage(Stage newStage)` **Role required**: `DEFAULT_ADMIN_ROLE` Forces the contract into any stage, bypassing all normal validation. Use only if the contract is stuck in an unexpected state or there's a critical security issue. Can cause accounting inconsistencies if used carelessly. #### `forceReduceCommitment(WalletTokenAmount[] reductions)` **Role required**: `COMMITMENT_REDUCER_ROLE` Reduces wallet commitments bypassing stage and pause restrictions. Correctly updates all accounting state (committed/cancelled amounts, bid totals, global counters). Prefer this over `recoverTokens()` for committed payment tokens. #### `recoverTokens(IERC20 token, uint256 amount, address to)` **Role required**: `TOKEN_RECOVERER_ROLE` Transfers any ERC20 token from the contract to a specified address. Intended for recovering tokens sent to the contract by mistake. Prefer `forceReduceCommitment()` for committed payment tokens, since it correctly updates accounting state. This role is not granted at deployment. Only grant it if you have a specific recovery need. *** ## Monitoring Use these view functions to track contract state: | Function | Description | | - | - | | `stage()` | Current sale stage. Check before calling any stage transition to confirm the contract is in the expected state. | | `paymentTokens()` | Configured payment token addresses. Useful to verify token configuration after deployment. | | `totalCommittedAmount()` | Total committed across all entities and tokens. Check during or after commitment to track overall participation. | | `totalCommittedAmountByToken()` | Per-token breakdown of commitments. | | `totalAcceptedAmount()` | Total accepted (proceeds) across all tokens. Check this before calling `finalizeSettlement()` — the expected amount must match exactly or the call reverts. | | `totalAcceptedAmountByToken()` | Per-token breakdown of accepted amounts. | | `totalCancelledAmount()` | Total cancelled during the Cancellation stage across all tokens. | | `totalCancelledAmountByToken()` | Per-token breakdown of cancellations. | | `totalRefundedAmount()` | Total refunded across all tokens. Check after processing refunds to verify all refunds have been issued. | | `totalRefundedAmountByToken()` | Per-token breakdown of refunds. | | `withdrawnAmount()` | Total proceeds already withdrawn. Check before and after calling `withdraw()` to confirm the expected amounts were transferred. | | `withdrawnAmountByToken()` | Per-token breakdown of withdrawn proceeds. | | `numEntities()` | Number of participating entities. Useful for understanding participation scale and for paginating through entities with `entitiesIn()`. | | `entityAt(index)` | Sale-specific entity ID at a given index. | | `entitiesIn(from, to)` | Sale-specific entity IDs in an index range. Use with `numEntities()` to paginate through all participants. | | `entityStatesByIDs(saleSpecificEntityIDs)` | Full entity state including all wallet states. Use to inspect specific entities' commitments, allocations, and refund status. | | `entityStatesIn(from, to)` | Entity states in an index range. Use to export or audit all entity states in bulk. | | `walletStatesByAddresses(addresses)` | Committed and accepted amounts per token for wallets. Use to debug or verify specific participants' state. | | `paused()` | Whether the contract is paused. | | `claimRefundEnabled()` | Whether self-service refund claiming is enabled. | | `reduceCommitmentEnabled()` | Whether partial commitment reduction is enabled during the Cancellation stage. | | `proceedsReceiver()` | Address that will receive proceeds. Verify this is correct before calling `withdraw()`. | | `maxWalletsPerEntity()` | Maximum wallets per entity. | *** ## See Also Contract overview, roles, and key concepts How allocations are computed offchain # Compliance Capabilities Source: https://docs.echo.xyz/sonar/planning/compliance-overview Overview of Sonar's compliance features for token sales ## Overview Sonar provides compliance infrastructure to help you run regulated token sales. This page summarizes the available capabilities; see the linked technical documentation for implementation details. All compliance settings are configured in the Echo Founder Dashboard when setting up your sale. ## Identity Verification ### KYC (Know Your Customer) Individual participants complete identity verification through Sonar's KYC flow. ### KYB (Know Your Business) Organizational participants (companies, DAOs, funds) can complete business verification to participate on behalf of their entity. Technical details on entity states and verification flow ## Accreditation For sales requiring accredited investors (e.g., US Reg D offerings), Sonar can verify accreditation status. ### Verification Methods | Method | Description | | - | - | | **Professional attestation** | Letter from CPA, attorney, or other qualified professional | | **Net worth (on-chain)** | Verification using only on-chain assets plus liability statement | | **Net worth** | Verification using on-chain and off-chain assets with supporting documentation | | **Income** | Income documentation (tax returns, pay stubs, etc.) | | **Professional credentials** | Verification via professional license (e.g., Series 7, CRD number) | ## Geographic Restrictions Block participation from specific jurisdictions (e.g., OFAC-sanctioned countries). ## Wallet Risk Screening Screen participant wallets for risk indicators before allowing participation. Sonar screens for: * Sanctioned entities * High-risk addresses * Illicit activity indicators Choose blocking actions per wallet risk level ## Purchase Limits Enforce minimum and maximum commitment amounts per entity. Limits are enforced at the entity level, so participants cannot circumvent them by using multiple wallets. How limits are enforced through permits ## Next Steps All sale configuration options including compliance settings How compliance checks fit into the sale process # Configuration Options Source: https://docs.echo.xyz/sonar/planning/configuration-options All the options available when setting up your token sale ## Overview Sonar provides extensive configuration options to customize your sale. These are configured in the [Echo Founder Dashboard](https://app.echo.xyz/founder) before your sale launches. *** ## Offered Token The "offered token" is the token that will be sold in the sale. | Parameter | Description | | - | - | | **Total amount** | The total amount of tokens to be sold in the sale (the user representation - i.e. `totalUnitAmount / 10^decimals`) | | **Decimals** | The number of [decimals](https://eips.ethereum.org/EIPS/eip-20#decimals) of the token | ## Sale Timeline | Option | Description | | - | - | | **Registration opens** | When investors can begin setting up their Sonar entities and verifying eligibility. Investors can register until the commitment period ends. | | **Commitment start** | When the commitment phase begins and investors can submit commitments | | **Commitment end** | When the commitment period automatically ends | Note that there are other phases like "cancellation" and "settlement" that you will transition to manually. You can read more about the complete sale lifecycle on the [Sale Lifecycle](/sonar/planning/sale-lifecycle) page. ## Chain & payment tokens | Option | Description | | - | - | | **Chain** | Which chain the sale runs on. A sale runs on a single chain, accepting payments across multiple chains in one sale is not supported. | | **Payment tokens** | Which tokens can be used for payment (e.g., USDC, USDT, or other ERC-20 tokens) | Sonar supports both EVM and SVM chains. Currently supported chains include Ethereum, Base, and [Monad](https://monad.xyz) (EVM), and Solana (SVM). Monad is the most recent addition. Payment tokens vary by chain. On Monad, the available payment tokens are: | Network | Payment tokens | | - | - | | **Mainnet** | USDC and USDT0 | | **Testnet** | USDC only | Contact [support@echo.xyz](mailto:support@echo.xyz) for specific network availability. ## Sale Mechanics Choose how your token price is determined: [fixed price](/sonar/planning/pricing-strategies#fixed-price-sale) or [English auction](/sonar/planning/pricing-strategies#english-auction). Each strategy has its own price parameters configured in the Founder Dashboard. See [Pricing Strategies](/sonar/planning/pricing-strategies) for details on each option and its configuration. ## Enhanced Security | Option | Description | | - | - | | **Facial recognition on suspected fraud** | When enabled, investors flagged for possible fraud are required to pass a facial recognition (liveness) check at the time of purchase | ## Contract Addresses | Option | Description | | - | - | | **Proceeds receiver address** | The destination wallet for all accepted commitments. After settlement, sale proceeds are withdrawn to this address. | | **Contract admin address** | The wallet that will have full administrative access (`DEFAULT_ADMIN_ROLE`) to your sale contract. | See [Roles & Permissions](/sonar/reference/contracts/settlement-sale#roles--permissions) for details on the admin role and other contract roles. ## Commitment Limits Limits are enforced at the entity level, not the wallet level—so a participant can't circumvent limits by using multiple wallets. | Parameter | Description | | - | - | | **Minimum commitment** | Smallest amount an entity can commit (e.g., \$100) | | **Maximum commitment** | Largest amount an entity can commit—use this as a whale cap to limit large participants | See [Purchase Permits](/sonar/core-features/purchase-permits) for implementation details on how limits are enforced. ## Compliance Options ### Geographic Restrictions | Option | Description | | - | - | | **Blocked jurisdictions** | Countries where participation is not allowed (e.g., sanctioned countries, OFAC list) | ### Wallet Screening | Option | Description | | - | - | | **Wallet risk screening** | Screen wallets for risk indicators before allowing participation | You can configure thresholds for direct and indirect exposure to flagged addresses. See [Wallet Risk Screening](/sonar/planning/wallet-risk-screening) for details on risk groups and configuration. ### US Participants | Option | Description | | - | - | | **US accreditation checks** | Verification that US participants meet accredited investor requirements (including option for on-chain net worth checks) | | **Forced lockup for US investors** | When enabled, US investors are required to lock up their tokens for a period of time. See [Lockup & Vesting](/sonar/planning/lockup-vesting) for details. | ## Advanced | Option | Description | | - | - | | **Custom contracts** | For unique requirements, Sonar can support custom smart contract implementations tailored to your specific needs | ## Next Steps Begin your technical integration Understand the end-to-end sale process # Lockup & Vesting Source: https://docs.echo.xyz/sonar/planning/lockup-vesting How lockup preferences are recorded with commitments and how to enforce lockup for US investors. ## Overview Sonar does **not** handle token distribution—this is handled separately by your team. Consider partnering with [Liquifi](https://liquifi.finance) for token management and distribution. But Sonar does support recording lockup preferences which you can take into account during token distribution. ## Lockup Preferences If you are using the default [SettlementSale](/sonar/reference/contracts/settlement-sale) contract, commitments can set a **lockup flag**. This flag is recorded against the commitment onchain. Your sale site will need to support users opting in to lock up their tokens, and include the selection when submitting commitments to the contract. ## Forced Lockup for US Investors For regulatory reasons, you may need to require all US investors to lock up their tokens. Sonar supports this through a configuration in the Founder Dashboard. ### Configuring Forced Lockup In the **Localization** settings (under the USA section), enable **"Add a forced vesting lockup for all American investors"**. When enabled, the SettlementSale contract will reject commitments from US entities that don't have the lockup flag set. ### Frontend Implementation When forced lockup is enabled for US investors, your sale site needs to: 1. **Detect US investors** - Check the `InvestingRegion` field in [`EntityDetails`](/sonar/reference/sonar-core#investingregion) (returned by [`readEntity`](/sonar/reference/sonar-core#readentity)). A value of `us` indicates a US-based entity. 2. **Set the lockup flag** - Ensure that commitments from US entities always have lockup enabled. The contract will reject commitments otherwise. 3. **Communicate to users** - Display clear messaging to US investors that their tokens will be subject to a lockup period. ## Next Steps Learn about the permit payload and how lockup flags are transmitted View all sale configuration options # Planning Your Sale Source: https://docs.echo.xyz/sonar/planning/overview Key decisions for configuring your Sonar token sale ## Overview When configuring a Sonar sale, you make two independent decisions: 1. **Pricing Strategy**: How is the token price determined? 2. **Settlement**: How are tokens allocated if demand exceeds supply? ## Pricing Strategies Sonar supports two pricing strategies: | Use Case | Pricing strategy | Result | | - | - | - | | Community sale, predictable experience | Fixed Price | Everyone pays the same price | | Price discovery | English Auction | Market determines price via competitive bidding | ## What Sonar Does vs What You Do | Responsibility | Sonar | Your Team | | - | - | - | | KYC/KYB verification | ✓ | | | Wallet risk screening | ✓ | | | Purchase permit issuance | ✓ | | | Smart contract deployment | ✓ (standard configs) | Custom only | | Settlement computation | | ✓ | | Frontend/website | | ✓ | | Token distribution | | ✓ | | Vesting/lockup enforcement | | ✓ | Sonar handles the sale infrastructure: collecting funds, enforcing compliance, and processing refunds. You decide how to allocate commitments, and Sonar syncs those decisions to the contract. Token distribution to buyers is a separate process managed by your team after the sale. ## Next Steps Fixed price vs English auction How settlement works after the commitment phase # Pricing Strategies Source: https://docs.echo.xyz/sonar/planning/pricing-strategies How the token price is determined for your sale ## Overview When configuring a Sonar sale, you choose a pricing strategy that determines how your token price is set. This decision is independent of how you [settle](/sonar/planning/settlement-strategies) your sale. *** ## Fixed Price Sale The simplest option. You set a fixed token price upfront, and participants commit funds at that price. ### How It Works 1. You announce the token price (e.g., \$0.50 per token) 2. Participants commit funds during the sale window 3. If total commitments exceed the tokens available, you decide how to [allocate](/sonar/planning/settlement-strategies) among participants during settlement 4. Participants receive tokens at the fixed price; any excess funds are refunded ### When to Use * You want a simple, predictable experience for participants * Price has already been determined through other means (e.g., prior funding rounds) * You want to minimize complexity for your community *** ## English Auction A competitive bidding mechanism where participants submit bids specifying both a price they're willing to pay and an amount. Everyone that bid a price at or above the "clearing price" is successful and pays that same price at the end of the auction. ### How It Works 1. Participants submit bids with a price and amount (e.g., "I'll pay up to \$0.75/token for \$10,000 worth of tokens") 2. Bids can be revised upward during the auction (price and amount can only increase, not decrease) 3. During the auction, Sonar continuously computes and publishes the estimated clearing price based on current bids (see below for more details) 4. All bids at or above the clearing price are successful 5. Everyone pays the clearing price at the end, regardless of what they bid 6. Excess funds are refunded #### Clearing Price Calculation The clearing price is determined by starting at the highest bid price and iterating downward in bid increment steps. At each price step, the total amount of USD committed at or above that price is determined. The highest price at which the combined commitments are sufficient to buy all available tokens becomes the clearing price. #### Example Assume selling **1,000,000 TOK** with a bid increment of **\$0.01/TOK**. Four participants submit bids: | Participant | Amount | Bid Price | | - | - | - | | Alice | \$10,000 | \$0.10/TOK | | Bob | \$15,000 | \$0.05/TOK | | Charlie | \$20,000 | \$0.05/TOK | | Eve | \$10,000 | \$0.01/TOK | To find the clearing price, start at the highest bid (\$0.10/TOK) and iterate downward by \$0.01/TOK: 1. **\$0.10/TOK** -- Only Alice qualifies. Total USD: \$10,000. Tokens needed: \$10,000 / \$0.10/TOK = 100,000 TOK. Not enough demand (100,000 TOK \< 1,000,000 TOK). 2. **\$0.09/TOK through \$0.06/TOK** -- Still only Alice qualifies. Not enough demand at any of these prices. 3. **\$0.05/TOK** -- Alice, Bob, and Charlie all qualify. Total USD: \$45,000. Tokens needed: \$45,000 / \$0.05/TOK = 900,000 TOK. Still not enough (900,000 TOK \< 1,000,000 TOK). 4. **\$0.04/TOK** -- Alice, Bob, and Charlie still qualify. Total USD: \$45,000. Tokens needed: \$45,000 / \$0.04/TOK = 1,125,000 TOK. **This exceeds the supply, so the clearing price is \$0.04/TOK.** **Outcome:** At \$0.04, Alice, Bob, and Charlie together demand 1,125,000 TOK but only 1,000,000 are available. The sale is oversubscribed, so you decide how to [allocate](/sonar/planning/settlement-strategies) the 1,000,000 tokens among successful bidders during settlement. Excess funds are refunded. | Participant | Bid Price | Result | Refund | | - | - | - | - | | Alice | \$0.10 | Successful (bid >= \$0.04) | Partial (from oversubscription) | | Bob | \$0.05 | Successful (bid >= \$0.04) | Partial (from oversubscription) | | Charlie | \$0.05 | Successful (bid >= \$0.04) | Partial (from oversubscription) | | Eve | \$0.01 | Unsuccessful (bid \< \$0.04) | \$10,000 (full) | All successful participants pay the same clearing price of \$0.04/TOK. Eve's bid was below the clearing price, so she receives a full refund. ### Auction Parameters | Parameter | Description | | - | - | | **Bid increment** | The minimum price step for bids and clearing price calculation. Bids must be in multiples of the increment (e.g., with a \$0.01 increment, \$0.05 and \$0.06 are valid but \$0.055 is not) | | **Minimum price (starting price)** | The auction starts at this price. No bids are accepted below it | | **Maximum price (cap)** | The highest bid price accepted. No bids above this price | The bid increment should strike a balance between flexibility and meaningfulness. If it's too small, participants can outbid each other by trivial amounts without any practical difference in price. If it's too large, price resolution suffers and the clearing price becomes imprecise. As a rule of thumb, we recommend setting increments so that there are roughly 100 steps between your minimum and maximum price. Setting a floor and ceiling creates competitive bidding within a defined range. If demand is strong enough that the clearing price would exceed your maximum, everyone pays the maximum price and you decide how to allocate among participants during settlement. ### When to Use * You want the market to discover a fair price * You're comfortable with price uncertainty * You want to reward participants who value the tokens most highly **Everyone pays the same price.** This eliminates "winner's curse" anxiety—participants can bid their true maximum willingness to pay without worrying about overpaying relative to others. *** ## Next Steps How to determine and finalize allocations View all sale configuration options # Sale Lifecycle Source: https://docs.echo.xyz/sonar/planning/sale-lifecycle The end-to-end process of running a token sale with Sonar ## Overview A Sonar sale progresses through several phases, from initial setup through to final distribution. Understanding this lifecycle helps you plan your sale timeline and set expectations with participants. *** ## Phase 1: Setup Before your sale opens: * **Configure sale parameters**: Define your target raise amount, token price or auction parameters, and sale configuration in the [Echo Founder Dashboard](https://app.echo.xyz/founder) * **Set compliance requirements**: Specify geographic restrictions, accreditation requirements, and commitment limits * **Smart contract deployment**: For standard configurations, Sonar deploys the sale contract to your chosen blockchain (e.g., Ethereum, Base). Your project owns and controls the contract. * **Integrate with your frontend**: Connect your website to Sonar's APIs and the sale contract For custom requirements beyond the standard configuration options, contact [support@echo.xyz](mailto:support@echo.xyz) to discuss your needs. *** ## Phase 2: Onboarding / Commitment Phase Once the sale opens: * **Participants register**: Users authenticate through Sonar. Existing verified users who meet your requirements can participate immediately; new users complete KYC/KYB verification * **Participants commit funds**: Users connect their wallet and commit funds (e.g., USDC, USDT) to the smart contract * **Purchase permits authorize participation**: Sonar issues signed permits that enforce your compliance rules at the contract level * **Commitments can be updated**: Participants can increase their commitment during the sale (amounts can only go up, not down) The commitment phase runs until either a specified timestamp is reached or you manually close the sale. *** ## Phase 3: Cancellation Phase (Optional) Some sales include an optional cancellation window between the commitment phase and settlement: * **Preliminary allocations are shown**: Based on the commitments received, preliminary allocations are calculated and displayed to participants * **Participants can review and cancel**: Participants see their expected allocation and can choose to cancel their commitment if unsatisfied * **Cancellations receive immediate refunds**: Participants who cancel receive their full commitment back * **Window closes**: After the cancellation period ends, remaining commitments are locked and proceed to settlement This phase might be relevant for regulatory compliance in certain jurisdictions. By default, preliminary allocations shown during cancellation are not recomputed as participants cancel. If you need dynamic recomputation during the cancellation phase, contact [support@echo.xyz](mailto:support@echo.xyz) before your sale launches. *** ## Phase 4: Settlement Phase After the commitment phase closes (or after the cancellation window, if applicable), you determine how to allocate the committed funds. This is done through the [Echo Founder Dashboard](https://app.echo.xyz/founder): 1. **Download** a CSV of all committed amounts from the dashboard 2. **Decide** how much of each participant's commitment to accept (your allocation logic — see [Settlement Strategies](/sonar/planning/settlement-strategies) for common approaches) 3. **Upload** the completed CSV back to the dashboard 4. **Sync** the allocations to the smart contract 5. **Finalize** the accepted amounts on-chain, locking them in 6. **Process refunds** for any committed amounts that were not accepted. Refunds can be pushed back to investors' wallets by the refunder role, or you can enable self-service claiming so participants claim refunds themselves (this requires a UI on your sale site and must be explicitly enabled on the contract) 7. **Withdraw sale proceeds** to a wallet you control For custom contracts (not Sonar's standard SettlementSale), allocations need to be set directly against the contract by your team. *** ## Phase 5: Distribution After settlement is finalized: * **You distribute tokens**: Token distribution happens outside the sale contract. You send tokens to participants based on their final allocations, which may include vesting schedules, lockup enforcement, or claim mechanisms Sonar handles the sale infrastructure—collecting funds, enforcing compliance, and processing refunds. You determine allocations via the dashboard, and Sonar syncs them to the contract. Token distribution to buyers is a separate process managed by your team after the sale. Sonar partners with [Liquifi](https://liquifi.finance) to offer a solution for token management and distribution and can help you with this. *** ## Next Steps Choose how your token price is determined How to compute and finalize allocations View all available sale configuration options Begin your technical integration # Settlement Strategies Source: https://docs.echo.xyz/sonar/planning/settlement-strategies How tokens are allocated when demand exceeds supply ## Overview When a sale is oversubscribed (more demand than tokens available), you need to decide how tokens are allocated among participants. Specifically, you determine how much of each participant's commitment is accepted (used to purchase tokens) and how much is refunded. Sonar does not provide off-the-shelf settlement computation — you implement the allocation logic yourself. The sections below describe common approaches at a high level to help you decide on a strategy. This decision is independent of your [pricing strategy](/sonar/planning/pricing-strategies). *** ## Pro-Rata Allocation Every participant's commitment is scaled down by the same percentage so that total allocations match the available supply. ### How It Works * If 2M is committed but only 1M worth of tokens are available, everyone receives 50% of their commitment * The remainder is refunded ### Example | | Value | | - | - | | Tokens available | 1,000,000 worth | | Total commitments | 2,000,000 (2x oversubscribed) | | Alice commits | 100,000 | | Alice receives | 50,000 allocation (50%) | | Alice refunded | 50,000 | ### Pros * Simple and easy to understand * Everyone gets something * Larger participants receive larger allocations (which may attract institutional interest) * No FOMO—timing doesn't matter ### Cons * Can be gamed by participants who overcommit to secure a larger share * Small participants may end up with very small allocations in highly oversubscribed sales *** ## Iterative Fill (Bottom-Up) This strategy prioritizes filling more participants by ensuring everyone receives at least a minimum allocation before distributing the remainder. ### How It Works 1. Participants are placed in a random order 2. Each participant is allocated the minimum commitment amount (e.g., 200) 3. The process repeats, adding another minimum increment to each participant who committed more 4. This continues until all available tokens are allocated ### Example | Participant | Committed | Allocated | | - | - | - | | 1,000 small participants | 200 each | 200 each (full) | | 1,000 medium participants | 400 each | 400 each (full) | | 1 large participant | 1,000,000 | 400,000 (partial) | With 1,000,000 available and minimum commitment of 200: * Small participants: fully filled at 200 * Medium participants: fully filled at 400 * Large participant: receives 400,000 (remaining supply) ### Pros * More participants end up with meaningful allocations * Reduces the advantage of large participants * No incentive to overcommit ### Cons * More complex for participants to understand * May be less attractive to large investors seeking significant allocations * In highly oversubscribed sales, some participants may receive reduced allocations *** ## First-Come First-Served Commitments are accepted in the order they are received until supply is exhausted. Early participants receive guaranteed allocations. ### How It Works 1. Participants submit commitments during the sale 2. Commitments are queued in the order received 3. When the sale closes, allocations are assigned in queue order until supply runs out 4. If a participant cancels during the cancellation phase, their spot is freed and the next commitments in the queue move up ### Example | Position | Participant | Committed | Allocated | | - | - | - | - | | 1 | Alice | 200,000 | 200,000 (full) | | 2 | Bob | 300,000 | 300,000 (full) | | 3 | Carol | 400,000 | 400,000 (full) | | 4 | Dave | 500,000 | 100,000 (partial—supply exhausted) | | 5 | Eve | 200,000 | 0 (no supply remaining) | With 1,000,000 available, the first three participants are fully filled, Dave receives a partial allocation, and Eve receives nothing. ### Pros * Clear, predictable rules—early participants get priority * Strong incentive for early commitment * Full allocations for successful participants (no scaling down) ### Cons * Creates urgency/FOMO at sale opening * Discriminates against participants in unfavorable timezones * Concentrates traffic at sale opening, increasing infrastructure load * Late participants may receive nothing * Rewards speed over conviction (smaller early commits beat larger late commits) *** ## Custom Allocation You can implement any allocation logic that fits your sale objectives. For example, you might factor in external data such as testnet participation, community contributions, or Discord activity. *** ## Next Steps Choose how your token price is determined View all sale configuration options # Wallet Risk Screening Source: https://docs.echo.xyz/sonar/planning/wallet-risk-screening Configure how wallets are screened for risk and what happens at each risk level. ## Overview Sonar screens every wallet address for exposure to risky on-chain activity. Each wallet is assigned a **risk level** (Low, Medium, or High), and you decide in the Echo Founder Dashboard what happens at each level. Screening runs automatically: * When a participant **registers a wallet** to their entity * **Before each purchase** is permitted ## Enabling Wallet Screening 1. Open your sale in the [Echo Founder Dashboard](https://echo.xyz). 2. Go to **Sale settings → Wallet requirements**. 3. Toggle on **Require AML (Anti-Money Laundering) checks**. Once enabled, you configure one action per risk level. ## Risk Levels | Risk level | What it means | | - | - | | **Low** | No meaningful indicators of risky activity — usage appears typical. | | **Medium** | Noticeable exposure to higher-risk services (e.g., gambling, no-KYC exchanges, instant coin swaps), making problematic funds more likely than usual. | | **High** | Direct or recent links to known bad actors or obfuscation services (e.g., scams, theft, ransomware, darknet markets, mixers), pointing to a higher likelihood of tainted funds. | ## Actions Per Risk Level For each risk level, choose one of three actions: | Action | Effect | | - | - | | **No blocking** | The wallet and the investor remain eligible. | | **Block wallet only** | The specific wallet cannot be used to purchase, but the entity can still participate with other registered wallets. | | **Block entity** | The entity is completely blocked from investing, regardless of which wallet it uses. | **Default configuration:** * Low risk → No blocking * Medium risk → Block wallet only * High risk → Block entity Choose "Block entity" for risk levels where you want to prevent circumvention — blocking only the wallet lets a flagged participant simply register a different wallet. ## Wallet Management The **Wallet management** page in your sale dashboard gives you two tools: **Wallet checker** Check the eligibility status of any specific wallet address against your current risk settings before or during the sale. **Allowlist** Add wallet addresses that should remain eligible even if they would otherwise be blocked by your risk settings. Allowlisted wallets bypass automated screening entirely — useful for treasury addresses or known partners. You can add and remove allowlisted addresses yourself at any time; no support request needed. ## See Also Common questions about blocked wallets How risk screening affects permit generation # SettlementSale Source: https://docs.echo.xyz/sonar/reference/contracts/settlement-sale Reference for the standard Sonar sale contract supporting fixed-price and auction sales. ## Overview `SettlementSale` is Sonar's standard smart contract for token sales. It supports fixed-price sales and English auctions. Participants commit funds onchain during the commitment stage; clearing mechanics and final allocations are computed offchain by Sonar and recorded onchain during settlement. The contract acts as an escrow: funds are held onchain and can only flow to the proceeds receiver (accepted amounts) or back to participants (refunds). With the exception of emergency token recovery, no other outflows are possible. For standard sale configurations, Sonar deploys and manages this contract for you. You only need to deploy your own contract if you have [custom requirements](/sonar/integration-guides/custom-contracts). **Source code**: [SettlementSale.sol](https://github.com/sunrisedotdev/sonar/blob/main/contracts/src/SettlementSale.sol) *** ## Deployment You can deploy a `SettlementSale` contract via the [Founder Dashboard](https://app.echo.xyz/founder). Before deploying, you must have configured the following in the sale's general settings: * Chain and payment tokens * Proceeds receiver address: the address that will receive the sale proceeds * Contract admin address: see [Roles & Permissions](#roles--permissions) for details Contract deployments work differently depending on sale type: * **Test sales**: deploy via the Dashboard or Integration page. Can be redeployed at any time. * **Production sales**: deploy via the Dashboard. This action is irreversible. ### Deployment Defaults When Sonar deploys a `SettlementSale`, the following is set at initialization: | Parameter | Default | | - | - | | `claimRefundEnabled` | `false`. Only the `REFUNDER_ROLE` can process refunds. Can be changed to `true` after deployment to allow participants to self-claim via `claimRefund()`. | | `reduceCommitmentEnabled` | `false`. Participants can only fully cancel via `cancelBid()`. Can be changed to `true` after deployment to allow partial reductions via `reduceCommitment()`. | | `maxWalletsPerEntity` | `20` | Sonar opens the commitment stage automatically after deployment via a separate `openCommitment()` transaction. By the time the deployment is announced as live, the contract will already be in the Commitment stage. ### Initial Role Grants The following roles are granted at initialization. The admin address receives all operational roles. Sonar uses two distinct addresses: a management wallet (for operational roles) and a separate signing key (for signing purchase permits). See [Roles & Permissions](#roles--permissions) for details on each role. | Role | Admin (project multisig) | Sonar management wallet | Sonar signing key | | - | :-: | :-: | :-: | | `DEFAULT_ADMIN_ROLE` | ✓ | — | — | | `SALE_MANAGER_ROLE` | ✓ | ✓ | — | | `SETTLER_ROLE` | ✓ | ✓ | — | | `SETTLEMENT_FINALIZER_ROLE` | ✓ | — | — | | `PAUSER_ROLE` | ✓ | ✓ | — | | `REFUNDER_ROLE` | ✓ | ✓ | — | | `PURCHASE_PERMIT_SIGNER_ROLE` | — | — | ✓ | | `COMMITMENT_REDUCER_ROLE` | — | — | — | | `TOKEN_RECOVERER_ROLE` | — | — | — | `COMMITMENT_REDUCER_ROLE` and `TOKEN_RECOVERER_ROLE` are not granted at deployment. They can be granted by the admin if explicitly required. Additional project team wallets can be granted roles after deployment via `grantRole()` (requires `DEFAULT_ADMIN_ROLE`). *** ## Sale Stages The contract progresses through the following stages: ```mermaid theme={null} stateDiagram-v2 [*] --> Commitment Commitment --> Cancellation Commitment --> Settlement Cancellation --> Settlement Settlement --> Done Done --> [*] ``` Sales start directly in the Commitment stage by default (Sonar opens commitment immediately after deployment). The PreOpen stage exists but is not used in standard deployments. ### Commitment The active commitment phase where participants submit bids. * Participants with valid purchase permits can submit bids via `replaceBidWithPermit()` (single transaction, recommended) or `replaceBidWithApproval()` (requires prior ERC20 approval) * Bids specify price, amount, and lockup preference * Each new bid replaces the previous bid for the same entity * Bids can only increase: amounts and prices cannot be lowered; lockup cannot be disabled once set * Bids are only accepted within the `opensAt`/`closesAt` window defined in the purchase permit * Forced lockup can be required for specific entities via the purchase permit **Transitions to**: Cancellation or Settlement ### Cancellation Optional cooling-off period (e.g., for EU regulatory requirements). * Participants can fully cancel their bids via `cancelBid()` and receive an immediate refund of all unaccepted committed amounts across all their wallets * If `reduceCommitmentEnabled` is set, participants can partially reduce specific wallet/token commitments via `reduceCommitment()` without fully cancelling * Preliminary allocations are computed offchain and communicated to participants * Once a bid is fully cancelled it cannot be reinstated **Transitions to**: Settlement ### Settlement Final allocations are computed offchain and recorded onchain. * The settler role records accepted amounts per wallet and payment token via `setAllocations()` * Accepted amounts cannot exceed a wallet's committed amount for that token * Settlement is finalized by the settlement finalizer role via `finalizeSettlement()` **Transitions to**: Done ### Done Sale is complete. Refunds and proceeds are processed. * Refunds equal the committed amount minus the accepted allocation, calculated separately per wallet per payment token * Participants can claim their own refunds if `claimRefundEnabled` is true, otherwise the refunder role processes them * Proceeds (accepted amounts) are withdrawn to the designated receiver via `withdraw()` or `withdrawPartial()` *** ## Roles & Permissions The contract uses role-based access control. Multiple addresses can hold each role. ### `DEFAULT_ADMIN_ROLE` Full control over the contract, including role management, proceeds withdrawal, updating the proceeds receiver, and emergency stage override. **Granted to Sonar at deployment**: No. **Recommended wallet**: Multisig with at least a 2-of-3 threshold. This role controls funds and role management. ### `SALE_MANAGER_ROLE` Manages stage transitions and operational parameters (pause/unpause, claim refund toggle, max wallets limit). **Granted to Sonar at deployment**: Yes. **Recommended wallet**: Hardware wallet. Stage transitions are time-sensitive and a hardware wallet avoids multisig coordination delays. ### `SETTLER_ROLE` Records final allocations during the Settlement stage. **Granted to Sonar at deployment**: Yes. **Recommended wallet**: Software wallet. Settlement is run by Sonar, but a project-controlled wallet provides a backup. ### `SETTLEMENT_FINALIZER_ROLE` Finalizes settlement and transitions to Done, validating the total accepted amount. **Granted to Sonar at deployment**: No. **Recommended wallet**: Same multisig as `DEFAULT_ADMIN_ROLE`. Finalizing settlement is a high-stakes one-time action. ### `PAUSER_ROLE` Emergency pause that immediately halts all external user-facing functions. **Granted to Sonar at deployment**: Yes. **Recommended wallet**: One or more software wallets held by on-call team members. Speed is critical for an emergency pause. ### `REFUNDER_ROLE` Processes refunds for participants during the Done stage. **Granted to Sonar at deployment**: Yes. **Recommended wallet**: Software wallet. Refunds are run by Sonar, but a project-controlled wallet provides a backup. ### `PURCHASE_PERMIT_SIGNER_ROLE` Signs purchase permits that authorize participation. Must only ever be held by Sonar. Do not grant this to any other address. **Granted to Sonar at deployment**: Yes. ### `COMMITMENT_REDUCER_ROLE` Force-reduces wallet commitments via `forceReduceCommitment()`, bypassing stage and pause restrictions. Correctly updates all accounting state. **Granted at deployment**: No. Only grant if you need to adjust commitments outside the normal Cancellation stage flow. ### `TOKEN_RECOVERER_ROLE` Emergency recovery of tokens sent to the contract. **Granted at deployment**: No. Only grant to a multisig if an actual recovery situation arises. Prefer `forceReduceCommitment()` for committed payment tokens. The project always retains `DEFAULT_ADMIN_ROLE` and full control over the contract, including the ability to grant and revoke all other roles. Sonar holds `PURCHASE_PERMIT_SIGNER_ROLE` exclusively to authorize eligible participants. *** ## Key Concepts ### Bids Each entity has a single active bid containing: | Field | Description | | - | - | | `price` | The maximum price the entity is willing to pay (for auctions) | | `amount` | Total commitment amount across all payment tokens and wallets | | `lockup` | Whether the entity opts for token lockup ([general information on lockup](/sonar/planning/lockup-vesting)) | The `price` is denominated in the auction's [bid increment](/sonar/planning/pricing-strategies#auction-parameters). For example, if the bid increment is \$0.01, then a price of 100 represents a willingness to pay \$1.00. **Bid constraints**: * Amounts can only increase, never decrease * Prices can only increase, never decrease * Lockup can be enabled but not disabled once set * Forced lockup can be required for specific entities via the purchase permit ### Entity vs Wallet * **Entity**: A compliance identity (individual or organization) verified by Sonar, identified by a `bytes16` entity ID * **Wallet**: A blockchain address used to commit funds One entity can use multiple wallets (up to `maxWalletsPerEntity`), but each wallet is tied to exactly one entity. The active bid and refund eligibility are tracked at the entity level. Committed amounts, accepted allocations, and refunds are tracked at the wallet level per payment token. ### Entity State Each entity has the following state tracked onchain: | Field | Description | | - | - | | `bidTimestamp` | Timestamp of the last bid placed by this entity | | `refunded` | Whether the entity has been refunded (prevents double refunding) | | `currentBid` | The entity's current active bid (price, amount, lockup) | | `wallets` | All wallet addresses associated with this entity | Each wallet tracks: | Field | Description | | - | - | | `committedAmountByToken` | Amount committed per payment token by this wallet | | `cancelledAmountByToken` | Amount cancelled per payment token by this wallet (during Cancellation stage) | | `acceptedAmountByToken` | Accepted allocation per payment token for this wallet (set during Settlement) | The refund for a wallet per token is `committedAmountByToken[token] - acceptedAmountByToken[token]`. Use `entityStatesByIDs(entityIDs)` to read full entity state including all wallet states. ### Multi-Token Support The contract accepts multiple payment tokens (e.g., USDC and USDT): * All tokens must have the same number of decimals and are assumed to maintain 1:1 value parity * Commitments, allocations, and refunds are tracked separately per token * Each bid transaction uses a single payment token * Allocations are set per wallet per token during settlement Not compatible with rebasing tokens (e.g., stETH) or fee-on-transfer tokens. Using incompatible tokens will result in incorrect accounting and potential loss of funds. If a payment token depegs, the sale should be paused immediately using `pause()` for further assessment. *** ## Security Considerations * **Audit role assignments** before and after deployment. Verify all role holders are correct and revoke any that are no longer needed. * **Grant `PAUSER_ROLE` to hot wallets** for fast emergency response. A multisig is too slow if you need to halt the contract quickly. * **Simulate contract operations** using tools like Tenderly before executing onchain, especially for settlement and withdrawal. * **Verify `proceedsReceiver`** before calling `withdraw()`. Use `setProceedsReceiver()` to update if needed. * **`PURCHASE_PERMIT_SIGNER_ROLE` must only be held by Sonar.** Granting it to any other address would allow unauthorized participants to bypass eligibility checks. * **`TOKEN_RECOVERER_ROLE` should not be granted by default.** The contract is designed so that tokens can only leave as refunds or proceeds withdrawals. Only grant this role if an actual recovery situation arises. *** ## When to Use Use `SettlementSale` when: * Running a fixed-price sale with pro-rata or iterative fill settlement * Running an English auction * You need offchain settlement computation * Standard Sonar compliance and permit validation is sufficient Consider a [custom contract](/sonar/integration-guides/custom-contracts) when: * You need first-come first-served with on-chain ordering * You have custom allocation logic * You need multiple commitments per entity (increase and decrease) *** ## See Also Function reference and operational procedures Build your own contract with Sonar permit validation How allocations are computed How permits authorize participation End-to-end sale process # SettlementSale (SVM) Source: https://docs.echo.xyz/sonar/reference/contracts/settlement-sale-svm Reference for the Sonar settlement sale program on Solana. ## Overview The Sonar settlement sale program is an Anchor-based Solana program for token sales. It follows the same commitment, cancellation, and settlement lifecycle as the EVM [SettlementSale](/sonar/reference/contracts/settlement-sale) contract, adapted for Solana's account model. Participants commit SPL tokens during the commitment stage. Clearing mechanics and final allocations are computed offchain by Sonar; accepted amounts and refunds are settled onchain. For standard sale configurations, Sonar deploys and manages this program for you. **Program IDs**: | Cluster | Program ID | | - | - | | Mainnet (`sol`) | `6RudLQPUCBssZiodR3q4PPLgYARNdZYM7HCtL6cZ9DyU` | | Devnet (`soldev`) | `3XxHCh947y1PAMK5y8oecBtaLU7TtTj9r4yMYwzFbJYs` | Use the program ID that matches the cluster your RPC endpoint connects to. **Source code**: [solana/](https://github.com/sunrisedotdev/sonar/tree/main/solana) *** ## Program Derived Addresses All program state lives in PDAs. Seeds use raw bytes — not the UUID string representation. | Account | Seeds | Description | | - | - | - | | `SettlementSale` | `["settlement_sale", sale_uuid]` | Top-level sale state | | `EntityState` | `["entity_state", sale_pda, entity_id]` | Per-entity commitment state | | `WalletBinding` | `["wallet_binding", sale_pda, bidder_pubkey]` | Binds a wallet to an entity | | Vault | `["vault", sale_pda]` | Holds committed SPL tokens | `sale_uuid` and `entity_id` are 16-byte raw UUID values. Entity IDs from the Sonar API may arrive as `0x`-prefixed hex or UUID-formatted strings. Strip the `0x` prefix; if hyphens are present, parse as a UUID, otherwise decode as raw hex. *** ## Instructions ### `place_bid` Places or updates a bid. Handles first bids and bid increases with the same call. The instruction verifies the purchase permit signature via instruction introspection of the Ed25519 program. The Ed25519 verify instruction must be the immediately preceding instruction in the same transaction. See the [integration guide](/sonar/integration-guides/frontend-svm#committing-funds-to-the-sale) for a complete code example. **Arguments:** | Argument | Type | Description | | - | - | - | | `permit` | [`PurchasePermitV3`](#purchasepermitv3-type) | Borsh-encoded permit from Sonar's API | | `amount` | `u64` | Payment tokens to commit, in the token's base unit | | `price` | `u64` | Bid price (for auctions; pass `0` for fixed-price sales) | | `lockup` | `bool` | Whether the entity opts into token lockup | **Accounts:** | Account | Writable | Signer | Description | | - | :-: | :-: | - | | `bidder` | Yes | Yes | The participant's wallet | | `sale` | Yes | No | The `SettlementSale` PDA | | `entity_state` | Yes | No | The `EntityState` PDA for this entity | | `wallet_binding` | Yes | No | The `WalletBinding` PDA for this wallet | | `bidder_token_account` | Yes | No | Bidder's associated token account for the payment mint | | `vault` | Yes | No | The vault PDA that holds committed tokens | | `payment_token_mint` | No | No | The payment SPL token mint | | `token_program` | No | No | SPL Token program | | `system_program` | No | No | System program | | `instructions` | No | No | `Sysvar1nstructions` — required for Ed25519 introspection | **Bid constraints:** * Amount can only increase, never decrease * Price can only increase, never decrease * Lockup can be enabled but not disabled once set * The permit must not be expired and the current time must fall within the `opens_at`/`closes_at` window * The bidder's wallet must match the wallet encoded in the permit *** ## Account Types ### `SettlementSale` Top-level sale configuration and state. Fetch this account to retrieve `permit_signer` and `vault` before constructing a transaction. | Field | Type | Description | | - | - | - | | `sale_uuid` | `[u8; 16]` | The sale UUID (used as a PDA seed) | | `permit_signer` | `PublicKey` | Ed25519 public key that signs purchase permits | | `vault` | `PublicKey` | The vault token account address | | `payment_token_mint` | `PublicKey` | The accepted payment SPL token mint | | `stage` | `SaleStage` | Current sale stage | | `paused` | `bool` | Whether the sale is currently paused | ### `EntityState` Per-entity commitment state. One account per entity per sale. Created on the entity's first bid. | Field | Type | Description | | - | - | - | | `entity_id` | `[u8; 16]` | The sale-specific entity ID | | `current_amount` | `u64` | Total tokens committed by this entity | | `current_price` | `u64` | Current bid price | | `lockup` | `bool` | Whether the entity has opted into lockup | | `refunded` | `bool` | Whether this entity has been refunded | Use `program.account.entityState.fetchNullable(entityStatePDA)` to read commitment progress. A `null` result means no bid has been placed; treat `current_amount` as zero. ### `WalletBinding` Associates a bidder wallet with an entity. Created on the wallet's first bid; one wallet is bound to exactly one entity per sale. | Field | Type | Description | | - | - | - | | `entity_id` | `[u8; 16]` | The entity this wallet is bound to | | `sale` | `PublicKey` | The `SettlementSale` PDA | *** ## Sale Stages The program follows the same stage progression as the EVM contract: ```mermaid theme={null} stateDiagram-v2 [*] --> Commitment Commitment --> Cancellation Commitment --> Settlement Cancellation --> Settlement Settlement --> Done Done --> [*] ``` Stage transitions are managed by Sonar. Participants can call `place_bid` during the Commitment stage, cancel during the Cancellation stage, and claim refunds when available. Settlement and pushed refunds are handled by Sonar. *** ## Roles & Permissions The SVM program uses a bitmask-based role system. Each sale has a single **admin** wallet (set at initialization) with full authority, plus granular roles that can be granted to operator wallets via `grant_role`. The admin implicitly bypasses all role checks — it can call any instruction without an explicit role grant. ### Admin Full control over the sale. The admin can call any role-gated instruction and is the only wallet that can: * Grant and revoke roles (`grant_role`, `revoke_role`) * Withdraw proceeds (`withdraw`, `withdraw_partial`) * Change the proceeds receiver (`set_proceeds_receiver`) * Transfer admin authority (`propose_authority` / `accept_authority`) Admin authority is transferred via a two-step process: the current admin calls `propose_authority` to nominate a new wallet, then the new wallet calls `accept_authority`. Until accepted, the original admin retains full control. **Held by**: The project (set at initialization). **Recommended wallet**: Multisig. This role controls funds and role management. ### `Manager` Manages stage transitions and operational parameters. **Instructions**: | Instruction | Description | | - | - | | `open_commitment` | Transitions from PreOpen to Commitment | | `open_cancellation` | Transitions from Commitment to Cancellation | | `open_settlement` | Transitions from Commitment or Cancellation to Settlement | | `set_paused` | Pauses or unpauses the sale | | `set_claim_refund_enabled` | Enables or disables self-service refund claims | | `set_reduce_commitment_enabled` | Enables or disables partial commitment reduction | | `set_max_wallets_per_entity` | Updates the per-entity wallet limit | **Granted to Sonar at deployment**: Yes. **Recommended wallet**: Hardware wallet. Stage transitions are time-sensitive and a hardware wallet avoids multisig coordination delays. ### `Settler` Records final allocations during the Settlement stage. **Instructions**: | Instruction | Description | | - | - | | `set_allocation` | Sets the accepted amount for a wallet | **Granted to Sonar at deployment**: Yes. **Recommended wallet**: Software wallet. Settlement is run by Sonar, but a project-controlled wallet provides a backup. ### `SettlementFinalizer` Finalizes settlement, transitioning the sale from Settlement to Done. The caller provides an `expected_total_accepted` value as a sanity check. **Instructions**: | Instruction | Description | | - | - | | `finalize_settlement` | Validates total accepted amount and transitions to Done | **Granted to Sonar at deployment**: No. **Recommended wallet**: Same multisig as admin. Finalizing settlement is a high-stakes one-time action. ### `Pauser` Emergency pause that immediately halts all user-facing instructions. The `Pauser` role can only pause the sale — unpausing requires the `Manager` role. **Instructions**: | Instruction | Description | | - | - | | `set_paused(true)` | Pauses the sale | **Granted to Sonar at deployment**: Yes. **Recommended wallet**: One or more software wallets held by on-call team members. Speed is critical for an emergency pause. ### `Refunder` Processes refunds for participants during the Done stage. **Instructions**: | Instruction | Description | | - | - | | `process_refund` | Pushes a refund to a specific wallet | **Granted to Sonar at deployment**: Yes. **Recommended wallet**: Software wallet. Refunds are run by Sonar, but a project-controlled wallet provides a backup. ### `permit_signer` Not a grantable role — this is the Ed25519 public key stored on the sale account that verifies purchase permit signatures. It is set at initialization and controlled by Sonar. See [Permit Signing](#permit-signing) for details. ### Initial Role Grants The following roles are granted at initialization. The admin receives implicit access to all operations. Sonar uses two distinct addresses: a management wallet (for operational roles) and a separate signing key (for purchase permits). See the role descriptions above for details on each role. | Role | Admin (project) | Sonar management wallet | Sonar signing key | | - | :-: | :-: | :-: | | Admin | ✓ | — | — | | `Manager` | ✓ | ✓ | — | | `Settler` | ✓ | ✓ | — | | `SettlementFinalizer` | ✓ | — | — | | `Pauser` | ✓ | ✓ | — | | `Refunder` | ✓ | ✓ | — | | `permit_signer` | — | — | ✓ | Additional project team wallets can be granted roles after deployment via `grant_role` (requires admin). ### Public Instructions (No Role Required) The following instructions can be called by any wallet: | Instruction | Stage | Description | | - | - | - | | `place_bid` | Commitment | Commit funds (requires a valid purchase permit) | | `cancel_bid` | Cancellation | Cancel a bid and reclaim committed funds | | `reduce_commitment` | Cancellation | Partially reduce a commitment (if enabled) | | `claim_refund` | Done | Claim a refund for unaccepted funds (if enabled) | The project always retains admin authority and full control over the sale, including the ability to grant and revoke all roles. Sonar holds the `permit_signer` key exclusively to authorize eligible participants. *** ## Permit Signing Solana sales use Ed25519 signatures rather than the ECDSA signatures used by EVM sales. The permit is Borsh-encoded using the `PurchasePermitV3` type from the program IDL. The `permit_signer` field on the `SettlementSale` account holds the Ed25519 public key used to verify permits. This key is controlled by Sonar. ### `PurchasePermitV3` type | Field | Type | Description | | - | - | - | | `sale_specific_entity_id` | `[u8; 16]` | Sale-specific entity ID | | `sale_uuid` | `[u8; 16]` | Sale UUID | | `wallet` | `[u8; 32]` | Bidder's wallet public key bytes | | `expires_at` | `i64` | Unix timestamp when the permit expires | | `min_amount` | `u64` | Minimum commitment amount | | `max_amount` | `u64` | Maximum commitment amount | | `min_price` | `u64` | Minimum bid price | | `max_price` | `u64` | Maximum bid price | | `opens_at` | `i64` | Unix timestamp when the permit becomes valid | | `closes_at` | `i64` | Unix timestamp when the permit closes | | `payload` | `bytes` | Arbitrary payload (may be empty) | *** ## See Also Step-by-step Solana integration guide with code examples EVM equivalent contract reference How Sonar authorizes participation End-to-end sale process # @echoxyz/sonar-core Source: https://docs.echo.xyz/sonar/reference/sonar-core Low level library for interacting with the Sonar API. This reference is not fully comprehensive yet, but includes docs on the more nuanced parts of the API like how to interpret the fields in [`EntityDetails`](#entitydetails). ## `SonarClient` functions All functions can throw an [`APIError`](#apierror). ### `readEntity` Reads an entity's details by entity ID. This function is expected to throw a [`APIError`](#apierror) with `status` 404 if the entity is not found. **Arguments** | Name | Type | Description | | - | - | - | | `saleUUID` | `string` | The UUID of the sale to get entity details for. | | `entitID` | `string` \| `undefined` | The entity ID of the entity to get details for. | | `walletAddress` | `string` \| `undefined` | The wallet address of the entity to get details for. *Only used for a wallet linking feature, enabled for niche use-cases on request.* | **Returns** `ReadEntityResponse` | Field | Type | Description | | - | - | - | | `Entity` | [`EntityDetails`](#entitydetails) | The entity details. | ### `listAvailableEntities` Lists all available entities for the authenticated user. **Arguments** | Name | Type | Description | | - | - | - | | `saleUUID` | `string` | The UUID of the sale to list entities for. | **Returns** `ListAvailableEntitiesResponse` | Field | Type | Description | | - | - | - | | `Entities` | [`EntityDetails`](#entitydetails)\[] | The list of entities. | ### `myProfile` Fetches the authenticated user's profile information. **Arguments** None. **Returns** `MyProfileResponse` | Field | Type | Description | | - | - | - | | `EntityID` | `string` | The entity ID of the authenticated user. | | `EmailAddress` | `string` \| `undefined` | The email address of the authenticated user, if available. | ### `readEntityInvestmentHistory` Fetches the authenticated user's investment history, showing all Echo private group investments they have participated in. **Arguments** None. **Returns** `EntityInvestmentHistoryResponse` | Field | Type | Description | | - | - | - | | `Investments` | [`EntityInvestment`](#entityinvestment)\[] | Array of investments made by the user. | `EntityInvestment` | Field | Type | Description | | - | - | - | | `CompanyName` | `string` | The name of the company invested in. | | `Round` | `string` | The funding round name (e.g., "Series A", "Seed"). | | `InvestedOn` | `string` | ISO 8601 timestamp of when the investment was made. | **Example** ```typescript theme={null} const investmentHistory = await client.readEntityInvestmentHistory(); console.log(`Found ${investmentHistory.Investments.length} investments`); investmentHistory.Investments.forEach((investment) => { console.log(`${investment.CompanyName} - ${investment.Round}`); console.log(`Invested on: ${new Date(investment.InvestedOn).toLocaleDateString()}`); }); ``` ### `fetchLimits` Fetches the commitment limits for a wallet in a sale. Use this to display the minimum and maximum commitment amounts to users. **Arguments** | Name | Type | Description | | - | - | - | | `saleUUID` | `string` | The UUID of the sale to fetch limits for. | | `walletAddress` | `string` | The wallet address to fetch limits for. | **Returns** `LimitsResponse` | Field | Type | Description | | - | - | - | | `HasCustomCommitmentAmountLimit` | `boolean` | Whether the entity has custom commitment limits (as opposed to default sale-wide limits). | | `MinCommitmentAmount` | `string` | The minimum commitment amount, expressed in payment token units. | | `MaxCommitmentAmount` | `string` | The maximum commitment amount, expressed in payment token units. | ### `prePurchaseCheck` Should be called at the start of the purchase flow to check whether there are any preconditions to purchase. **Arguments** | Name | Type | Description | | - | - | - | | `saleUUID` | `string` | The UUID of the sale to run the pre-purchase check for. | | `entityID` | `string` | The ID of the entity to run the pre-purchase check for. | | `walletAddress` | `string` | The wallet address of the entity to run the pre-purchase check for. | **Returns** `PrePurchaseCheckResponse` | Field | Type | Description | | - | - | - | | `ReadyToPurchase` | `boolean` | Whether the entity is ready to purchase. | | `FailureReason` | [`PrePurchaseFailureReason`](#prepurchasefailurereason) | Populated if the entity is not ready to purchase. | | `LivenessCheckURL` | `string` | URL to link the user to so that they can complete a liveness check on the Sonar site. Populated if the FailureReason is `requires-liveness`. | ### `readCommitmentData` Fetches commitment data for a sale. This is a public API endpoint that does not require authentication. **Arguments** | Name | Type | Description | | - | - | - | | `saleUUID` | `string` | The UUID of the sale to fetch commitment data for. | **Returns** `ReadCommitmentDataResponse` | Field | Type | Description | | - | - | - | | `TotalCommitmentAmount` | `string` | The total commitment amount in the smallest payment token units as a number string. | | `ClearingPriceNumerator` | `string` \| `undefined` | For auctions only: the numerator of the clearing price as a number string. | | `ClearingPriceDenominator` | `string` \| `undefined` | For auctions only: the denominator of the clearing price as a number string. | | `ClearingPriceMicroUSD` | `string` \| `undefined` | For auctions only: the clearing price expressed in micro-USD (1 USD = 1,000,000 micro-USD) as a number string. | | `PaymentTokenDecimals` | `number` | The decimals of the payment token used in the sale. | | `OfferedTokenDecimals` | `number` \| `undefined` | The decimals of the token being offered, if configured. | | `UniqueCommitmentCount` | `number` | The number of unique commitments made to the sale. | | `Commitments` | [`Commitment`](#commitment)`[]` | Array of individual commitments, sorted by creation time descending. | For auctions, the clearing price is expressed in terms of a `ClearingPriceNumerator` and `ClearingPriceDenominator` fraction. The clearing price is in smallest units of the payment token per smallest unit of the offered token. You can divide the `ClearingPriceNumerator` by the `ClearingPriceDenominator` to get the price in decimal format, but you might lose precision. The `ClearingPriceMicroUSD` field is provided for convenience to avoid the need to divide the numerator and denominator. It is only set if the sale is using an auction pricing strategy and the payment token is a USD stablecoin and the offered token decimals are configured. It contains the current clearing price in micro-USD for one human-readable offered token (1 human-readable token = 10^`OfferedTokenDecimals` smallest units). Warning: this could lose precision, so `ClearingPriceNumerator` and `ClearingPriceDenominator` should be used as the machine-readable value. ### `generatePurchasePermit` For onchain sales, `generatePurchasePermit` should be called as part of the purchase flow to generate a purchase permit to pass to the sale contract. The permit is signed by Sonar, and the contract will need to verify the signature as well as the permit data. **Arguments** | Name | Type | Description | | - | - | - | | `saleUUID` | `string` | The UUID of the sale to generate the purchase permit for. | | `entityID` | `string` | The ID of the entity to generate the purchase permit for. | | `walletAddress` | `string` | The wallet address of the entity to generate the purchase permit for. | **Returns** `GeneratePurchasePermitResponse` | Field | Type | Description | | - | - | - | | `PermitJSON` | [`PurchasePermitV2`](#purchasepermitv2) \| [`PurchasePermitV3`](#purchasepermitv3) | The purchase permit data. The version depends on sale configuration. | | `Signature` | `string` | The signature of the purchase permit. | ## Core types ### `EntityDetails` | Field | Type | Description | | - | - | - | | `Label` | `string` | Display name of the entity - for organizations, this will be the name of the organization, for users this will be the string "Yourself" because we do not share their real name. | | `EntityID` | `string` | Used to lookup information by entity in the Sonar API. This ID is stable across sales for the querying oauth client. | | `SaleSpecificEntityID` | `0x${string}` | Used to lookup information by entity on the sale contract. This ID is stable across clients for a given sale. | | `EntityType` | `"user"` \| `"organization"` | The type of the entity. | | `EntitySetupState` | [`EntitySetupState`](#entitysetupstate) | The setup state of the entity. You can just check for `EntitySetupState.COMPLETE`, and link to the Sonar site if it's incomplete. Optional: if you want to show more fine-grained information, see the [EntitySetupState](#entitysetupstate) docs for suggested messages. | | `SaleEligibility` | [`SaleEligibility`](#saleeligibility) | The eligibility state of the entity for the sale. | | `InvestingRegion` | [`InvestingRegion`](#investingregion) | The investing region of the entity. | ### `MyProfileResponse` | Field | Type | Description | | - | - | - | | `EntityID` | `string` | The entity ID of the authenticated user. | | `EmailAddress` | `string` \| `undefined` | The email address of the authenticated user, if available. | ### `EntitySetupState` Enum with possible values: **`not-started`** * The entity has not started the setup process. The user should be linked to the Sonar site to continue. * Suggested message: "Entity not ready to invest — Please complete the entity setup process." **`in-progress`** * The entity has started the setup process, but it is not yet in review. The user should be linked to the Sonar site to continue. * Suggested message: "Entity not ready to invest — Please complete the entity setup process." **`ready-for-review`** * The entity has completed all current steps of the setup process and is ready to submit their data for review. The user should be linked to the Sonar site to continue. * Suggested message: "Entity not ready to invest — Please complete the entity setup process." **`in-review`** * The Sonar team is reviewing the entity. * Suggested message: "Entity not ready to invest — Please wait for the review to finish before you can make investments." **`failure`** * There is a problem with the entity setup. The user should be linked to the Sonar site so they can address the issues. * Suggested message: "Entity not ready to invest — Review your entity status in Sonar." **`failure-final`** * There is a problem with the entity setup, and the user is not able to address the issues. * Suggested message: "Entity not ready to invest — Review your entity status in Sonar." **`technical-issue`** * The setup is in a known technical issue state and we want the user to contact support if this happens. * Suggested message: "There’s an issue with your account — Please contact Sonar support to resolve it." **`complete`** * The entity has completed the setup process. * Suggested message: depends on the [SaleEligibility](#saleeligibility) value. ### `SaleEligibility` Once the entity has completed setup, you should check whether they are currently eligible for the sale. Possible values: **`eligible`** * The entity has completed setup and is eligible for the sale. * Suggested message: "Your entity is ready to participate in the sale." **`not-eligible`** * If the entity doesn’t meet sale requirements (e.g. resident of a blocked jurisdiction or accredited). * Suggested message: "Entity not qualified to invest." **`unknown-setup-incomplete`** * We don't know whether the entity is eligible yet because they have not completed setup. * Suggested message: depends on the [EntitySetupState](#entitysetupstate) value. ### `InvestingRegion` This can be useful if there are additional sale conditions that apply to US/EU entities, and you want to display this to users in the UI. Enum with possible values: **`unknown`** * We don't currently know the entity's region. This is only expected to be the case before KYC/KYB is completed. **`us`** * The entity is located in the United States. **`eu`** * The entity is located in the European Union. **`other`** * The entity is located in another region. ### `PrePurchaseFailureReason` Enum with possible values: **`unknown`** * We don't know why the entity is not ready to purchase. This is not expected to happen. * Suggested message: "An unknown error occurred — Please try again or contact support." **`wallet-risk`** * The wallet does not meet the configured risk thresholds. * Suggested message: "The connected wallet is not eligible for this sale. Connect a different wallet." **`max-wallets-used`** * The entity has reached the maximum number of wallets allowed for this sale. * Suggested message: "Maximum number of wallets reached — This entity can’t use the connected wallet. Use a previous wallet." **`requires-liveness`** * The entity requires a liveness check. * This is an expected case and the UI should not show an error; the UI should redirect the user to the `LivenessCheckURL` to complete a liveness check. **`sale-not-active`** * The sale is not currently in a state where purchases are allowed. * Suggested message: "The sale is not currently active." **`wallet-not-linked`** * The connected wallet is not linked to the entity. This suggests there is a bug on your sale website because the entity ID should be looked up from the currently connected wallet address. **`outside-time-window`** * The current time is outside the sale's configured commitment window. * Suggested message: "The sale is not currently accepting commitments." ### `PurchasePermitV3` The current permit version with time-gated access support. | Field | Type | Description | | - | - | - | | `SaleSpecificEntityID` | `0x${string}` | The sale-specific entity ID that the permit belongs to. | | `SaleUUID` | `0x${string}` | The sale UUID that the permit belongs to, in hex format. The contract should verify this matches a hardcoded sale UUID. | | `Wallet` | `0x${string}` | The wallet address. The sale contract should verify this matches the sender address. | | `ExpiresAt` | `number` | Number representing the number of seconds since the Unix epoch. The sale contract should verify this is in the future. | | `MinAmount` | `string` | The minimum amount the entity is allowed to commit. | | `MaxAmount` | `string` | The maximum amount the entity is allowed to commit. | | `MinPrice` | `number` | The minimum price the entity is allowed to bid at (for auctions). | | `MaxPrice` | `number` | The maximum price the entity is allowed to bid at (for auctions). | | `OpensAt` | `number` | Unix timestamp when the permit becomes valid (inclusive). | | `ClosesAt` | `number` | Unix timestamp when the permit stops being valid (exclusive). | | `Payload` | `0x${string}` | Contains arbitrary custom data (e.g., forced lockup preferences). | ### `PurchasePermitV2` Legacy permit version without time-gated access. New sales should use V3. | Field | Type | Description | | - | - | - | | `SaleSpecificEntityID` | `0x${string}` | The sale-specific entity ID that the permit belongs to. | | `SaleUUID` | `0x${string}` | The sale UUID that the permit belongs to, in hex format. The contract should verify this matches a hardcoded sale UUID. | | `Wallet` | `0x${string}` | The wallet address. The sale contract should verify this matches the sender address. | | `ExpiresAt` | `number` | Number representing the number of seconds since the Unix epoch. The sale contract should verify this is in the future. | | `MinAmount` | `string` | The minimum amount the entity is allowed to commit. | | `MaxAmount` | `string` | The maximum amount the entity is allowed to commit. | | `MinPrice` | `number` | The minimum price the entity is allowed to bid at (for auctions). | | `MaxPrice` | `number` | The maximum price the entity is allowed to bid at (for auctions). | | `Payload` | `0x${string}` | Contains arbitrary custom data (e.g., forced lockup preferences). | ### `Commitment` Represents a single commitment made to a sale. | Field | Type | Description | | - | - | - | | `CommitmentID` | `0x${string}` | Unique identifier for this commitment. | | `SaleSpecificEntityID` | `0x${string}` | The sale-specific entity ID that made the commitment. | | `PriceNumerator` | `string` | The numerator of the commitment price. | | `PriceDenominator` | `string` | The denominator of the bid price fraction. | | `PriceMicroUSD` | `string` \| `undefined` | The bid price expressed in micro USD. | | `Amounts` | [`WalletTokenAmount`](#wallettokenamount)`[]` | Array of amounts committed per wallet and token. | | `CreatedAt` | `string` | ISO 8601 timestamp of when the commitment was created. | | `ExtraRaw` | `0x${string}` | Hex-encoded raw `extraData` field from the [ICommitmentDataReader](https://github.com/sunrisedotdev/sonar/blob/main/contracts/src/interfaces/ICommitmentDataReader.sol) interface. | | `ExtraDataParsed` | `unknown` | Populated if our backend knows how to parse the `extraData` field. | The commitment price is only of interest for variable price sales - like auctions. It is expressed in terms of a `PriceNumerator` and `PriceDenominator` fraction. The price is in smallest units of the payment token per smallest unit of the offered token. You can divide the `PriceNumerator` by the `PriceDenominator` to get the price in decimal format, but you might lose precision. The `PriceMicroUSD` field is provided for convenience to avoid the need to divide the numerator and denominator. It is only set if the payment token is a USD stablecoin and the offered token decimals are configured. It contains the current commitment price in micro-USD for one human-readable offered token (1 human-readable token = 10^`OfferedTokenDecimals` smallest units). Warning: this could lose precision, so `PriceNumerator` and `PriceDenominator` should be used as the machine-readable value. ### `WalletTokenAmount` Represents an amount committed from a specific wallet using a specific token. | Field | Type | Description | | - | - | - | | `Wallet` | `0x${string}` | The wallet address that made this part of the commitment. | | `Token` | `0x${string}` | The payment token address used. | | `Amount` | `string` | The amount committed in token units. | ### `APIError` Thrown if the Sonar API responds with a non-2xx status code or the response body fails to parse. Expected cases will be mentioned in the relevant function docs. Suggested message for unexpected errors: "Failed to load your data — Please try again or contact Sonar support." | Field | Type | Description | | - | - | - | | `status` | `number` | The HTTP status code. | | `code` | `string` \| `undefined` | A textual error code returned by the Sonar API. `undefined` if the response body fails to parse. | | `details` | `any` \| `undefined` | The response body, if present. | # @echoxyz/sonar-react Source: https://docs.echo.xyz/sonar/reference/sonar-react Higher level react hooks for interacting with the Sonar API. This library provides higher level React hooks to abstract some of the state management for you. You will still need to use the [`@echoxyz/sonar-core`](./sonar-core.mdx) library for some parts of the integration, and to import types. ## Hooks ### `useSonarAuth` A hook to handle the OAuth flow for the user. **Returns** | Field | Type | Description | | - | - | - | | `authenticated` | `boolean` | Whether the user is authenticated. | | `login` | `() => void` | Redirect the user to Sonar to login and authorize your application. | | `token` | `string` \| `undefined` | The OAuth token for the user. | | `completeOAuth` | `(args: { code: string; state: string }) => Promise` | Call this in your OAuth callback handler to complete the OAuth flow and exchange the code for an access token. | | `logout` | `() => void` | Call this to logout the user. | ### `useSonarClient` A hook to get a reference to the underlying `SonarClient` from the [`@echoxyz/sonar-core`](./sonar-core.mdx) library. **Returns** | Field | Type | Description | | - | - | - | | `client` | `SonarClient` | The underlying `SonarClient`. | ### `useSonarEntity` A hook to fetch the state of a user's Sonar entity based on their connected wallet address. The hook will only start loading once the `entityID` or `walletAddress` is defined. **Arguments** | Name | Type | Description | | - | - | - | | `saleUUID` | `string` | The UUID of the sale to get entity details for. | | `entityID` | `string` \| `undefined` | The entity ID of the entity to get details for. | | `walletAddress` | `string` \| `undefined` | The wallet address of the entity to get details for. *Only used for a wallet linking feature, enabled for niche use-cases on request.* | **Returns** | Field | Type | Description | | - | - | - | | `authenticated` | `boolean` | Whether the user is authenticated. | | `loading` | `boolean` | Whether the hook is loading. | | `entity` | [`EntityDetails`](./sonar-core#entitydetails) \| `undefined` | The state of the user's Sonar entity. This can be `undefined` even if the user is not authenticated - see note about 404 errors in [`readentity`](./sonar-core.mdx#readentity) docs. | | `error` | `Error` \| `undefined` | Populated if the entity failed to load. | ### `useSonarEntities` A hook to list all available entities for the authenticated user. **Arguments** | Name | Type | Description | | - | - | - | | `saleUUID` | `string` | The UUID of the sale to list entities for. | **Returns** | Field | Type | Description | | - | - | - | | `authenticated` | `boolean` | Whether the user is authenticated. | | `loading` | `boolean` | Whether the hook is loading. | | `entities` | [`EntityDetails`](./sonar-core#entitydetails)`[]` \| `undefined` | The state of the user's Sonar entities. | | `error` | `Error` \| `undefined` | Populated if the entity failed to load. | ### `useSonarPurchase` A hook to run pre-purchase checks and return functions required to complete the purchase flow. **Arguments** | Name | Type | Description | | - | - | - | | `saleUUID` | `string` | The UUID of the sale to run pre-purchase checks against the entity for. | | `entityID` | `string` | The UUID of the entity to run pre-purchase checks for. | | `walletAddress` | `string` | The wallet address of the entity to run pre-purchase checks for. | **Returns** | Name | Type | Description | | - | - | - | | `loading` | boolean | Whether the pre-purchase checks are loading. | | `readyToPurchase` | boolean | Whether the entity is ready to purchase. | | `error` | `Error` \| `undefined` | Populated if the pre-purchase checks failed to run. | | `failureReason` | [`PrePurchaseFailureReason`](./sonar-core#prepurchasefailurereason) \| `undefined` | Populated if the entity is not ready to purchase. | | `livenessCheckURL` | `string` \| `undefined` | URL to link the user to so that they can complete a liveness check on the Sonar site. Populated if the `failureReason` is `requires-liveness`. | | `generatePurchasePermit` | `() => Promise` \| `undefined` | Function to generate a purchase permit to pass to the sale contract when purchasing tokens. Populated if the `readyToPurchase` is true. | ### `useSonarProfile` A hook to fetch the authenticated user's profile information. **Returns** | Field | Type | Description | | - | - | - | | `authenticated` | `boolean` | Whether the user is authenticated. | | `loading` | `boolean` | Whether the profile is loading. | | `profile` | [`MyProfileResponse`](./sonar-core#myprofile) \| `undefined` | The authenticated user's profile containing their entity ID and email address. | | `error` | `Error` \| `undefined` | Populated if the profile failed to load. | ### `useEntityInvestmentHistory` A hook to fetch the authenticated user's investment history, showing all Echo private group investments they have participated in. This automatically fetches when the user is authenticated and resets when they log out. **Returns** | Field | Type | Description | | - | - | - | | `authenticated` | `boolean` | Whether the user is authenticated. | | `loading` | `boolean` | Whether the investment history is loading. | | `investmentHistory` | [`EntityInvestmentHistoryResponse`](./sonar-core#readentityinvestmenthistory) \| `undefined` | The user's investment history containing an array of investments. | | `error` | `Error` \| `undefined` | Populated if the investment history failed to load. | **Example** ```tsx theme={null} import { useEntityInvestmentHistory } from '@echoxyz/sonar-react'; function InvestmentHistoryList() { const { loading, investmentHistory, error } = useEntityInvestmentHistory(); if (loading) { return
Loading your investment history...
; } if (error) { return
Error loading investments: {error.message}
; } if (!investmentHistory?.Investments.length) { return
No investments yet
; } return (

Your Investment History

    {investmentHistory.Investments.map((investment, index) => (
  • {investment.CompanyName} - {investment.Round}
    Invested on: {new Date(investment.InvestedOn).toLocaleDateString()}
  • ))}
); } ``` ### `useCommitmentData` A hook to fetch commitment data for a sale, with optional polling for live updates. This calls a public API endpoint, so the client does not need to be authenticated. **Arguments** | Name | Type | Description | | - | - | - | | `saleUUID` | `string` | The UUID of the sale to fetch commitment data for. | | `pollingIntervalMs` | `number` \| `undefined` | Optional polling interval in milliseconds. Must be at least 1000ms. If not provided, the data is fetched once on mount. | **Returns** | Field | Type | Description | | - | - | - | | `loading` | `boolean` | Whether the commitment data is loading. | | `commitmentData` | [`ReadCommitmentDataResponse`](./sonar-core#readcommitmentdata) \| `undefined` | The commitment data for the sale. | | `error` | `Error` \| `undefined` | Populated if the commitment data failed to load. | # Technical Overview Source: https://docs.echo.xyz/sonar/technical-overview How users participate in a Sonar-powered token sale ## Architecture Sonar Architecture Sonar sits between your frontend application and your on-chain sale contract, handling compliance verification and authorization. Your project always owns the contract — Sonar never holds administrative keys. *** ## Onboarding and Purchase Flow This is the end-to-end flow for a user participating in a token sale. ```mermaid theme={null} flowchart TD A[User arrives at sale page] --> B[Connect wallet & sign in with Sonar] B --> C{Entity linked & setup complete?} C -->|No| D[Redirect to Sonar platform] D --> E[Complete onboarding on Sonar] E --> F[Return to sale page] F --> C C -->|Yes| G{Eligible for this sale?} G -->|No| H[Show ineligibility reason] G -->|Yes| I[Generate purchase permit] I --> J[Submit transaction to contract] J --> K[Commitment confirmed] ``` ### 1. User Arrives at Sale Page The user lands on your sale page. Display sale information (timing, pricing, terms) and prompt them to connect. ### 2. Connect Wallet and Sign In with Sonar The user connects their wallet and authenticates with Sonar via OAuth. These can happen in either order. * **Wallet connection**: Use a standard wallet library (wagmi, ethers, etc.) * **Sonar authentication**: [OAuth 2.0 PKCE flow](/sonar/core-features/authentication) redirects to Sonar, then back to your site ### 3. Check Entity Status Once authenticated, your application queries Sonar's API to check: * Which entities are linked to the authenticated user * Whether each entity's `EntitySetupState` is `complete` If no entity is found or setup is incomplete, redirect the user to complete onboarding: ``` https://app.echo.xyz/sonar/{saleUUID}/home ``` See [Entity Setup States](/sonar/core-features/entities#entity-setup-states) for all possible states and what they mean. ### 4. Complete Onboarding on Sonar Users complete their verification on the Sonar platform. This includes: * KYC (individuals) or KYB (organizations) verification * Accreditation verification (if required by the sale) The specific requirements are configured in the [Echo Founder Dashboard](https://app.echo.xyz/founder) based on your sale's compliance needs. Once complete, the user returns to your sale page. ### 5. Verify Eligibility With onboarding complete, check that the entity meets this sale's specific requirements (jurisdiction, accreditation level, etc.). The entity's eligibility status is returned when you fetch entity state. If not eligible, display a message explaining they don't meet the sale requirements. See [Sale-Specific Eligibility](/sonar/core-features/entities#sale-specific-eligibility) for details on each state, and the [frontend integration guide](/sonar/integration-guides/frontend-overview) for implementation examples. If the entity is eligible, run a [pre-purchase check](/sonar/integration-guides/frontend-only#running-pre-purchase-checks) before generating a permit. This validates that the entity is ready to purchase (e.g. checking if a liveness verification is required). ### 6. Commit Funds When the user is ready to purchase: 1. **Generate a [purchase permit](/sonar/core-features/purchase-permits)** from Sonar's API. The permit is a signed authorization containing purchase limits, price bounds, and expiration. 2. **Submit the transaction** to the sale contract with the permit and signature. See the [SettlementSale contract](/sonar/reference/contracts/settlement-sale) for a reference to our standard sale contract. 3. **Contract validates** the permit signature and records the commitment. ## Next steps Get started with code examples for different frontend architectures