### Install Clearsync Precision Package Source: https://github.com/layer-3/clearsync/blob/master/pkg/precision/README.md Install the precision package using go get. This command fetches and installs the package into your Go workspace. ```bash go get github.com/layer-3/clearsync/precision ``` -------------------------------- ### Install UserOp Golang Library Source: https://github.com/layer-3/clearsync/blob/master/pkg/userop/README.md Install the UserOp library in your Golang project using the go get command. ```bash go get github.com/layer-3/clearsync/pkg/userop ``` -------------------------------- ### Clearsync Configuration File Example Source: https://github.com/layer-3/clearsync/blob/master/docs/scripts/deploy_clearsync.md Defines the structure for the Clearsync deployment configuration file, specifying allocation addresses and ERC20 token details. ```json { "allocationAddresses": string[], "tokens": { [ { "name": string, "symbol": string, "decimals": number, } ] } } ``` -------------------------------- ### Driver Weights Configuration Example Source: https://github.com/layer-3/clearsync/blob/master/pkg/quotes/README.md An example configuration showing how weights are assigned to different trading drivers. These weights influence the index price calculation. ```plaintext driverWeights = [{Binance: 20}, {Uniswap: 10}, {Kraken: 15}] ``` -------------------------------- ### Example: Adding a new component Source: https://github.com/layer-3/clearsync/blob/master/docs/commit_practives.md When introducing a new component, omit the scope and include the component name in the description. This is for the initial addition of a component. ```txt feat: add tx modal component ``` -------------------------------- ### Example: Create Margin Channel Fixed Part Source: https://context7.com/layer-3/clearsync/llms.txt An example demonstrating the creation of the fixed part for a margin trading channel. Includes participant addresses, a channel nonce, the app definition address, and the challenge duration. ```Solidity // Example: Create margin channel fixed part FixedPart memory fixedPart = FixedPart({ participants: [brokerA, brokerB], channelNonce: uint256(keccak256(abi.encodePacked(block.timestamp))), appDefinition: marginAppAddress, challengeDuration: 86400 // 24 hours }); ``` -------------------------------- ### Load Configuration from Environment or File Source: https://context7.com/layer-3/clearsync/llms.txt Load Clearsync configuration from environment variables or a YAML file. Examples show common environment variable formats for drivers, RPC endpoints, and specific driver settings. ```go // Load config from environment variables config, err := quotes.NewConfigFromEnv() // Or from YAML file config, err := quotes.NewConfigFromFile("config.yaml") // Environment variable examples: // QUOTES_DRIVERS=binance,syncswap // QUOTES_RPC_ETHEREUM=https://eth-mainnet.g.alchemy.com/v2/key // QUOTES_RPC_LINEA=https://rpc.linea.build // QUOTES_BINANCE_BATCH_PERIOD=5s // QUOTES_UNISWAP_V3_FACTORY_ADDRESS=0x1F98431c8aD98523631AE4a59f267346ea31F984 ``` -------------------------------- ### VersionRequest Source: https://github.com/layer-3/clearsync/blob/master/docs/grpc/operator.proto.md Request to get the system version. ```APIDOC ## VersionRequest ### Description Request to retrieve the current version of the system. ``` -------------------------------- ### Hardhat Etherscan Plugin Configuration Source: https://github.com/layer-3/clearsync/blob/master/docs/scripts/deploy_clearsync.md Example configuration for the hardhat verify plugin, including API keys and custom chain definitions for local or private networks. ```typescript etherscan: { apiKey: { ... }, customChains: [ { network: 'network_name', chainId: 42, urls: { apiURL: 'https://my.nodescan/api/', browserURL: 'https://my.nodescan/', }, }, ], }, ``` -------------------------------- ### Hardhat Testing and Deployment Commands Source: https://context7.com/layer-3/clearsync/llms.txt Provides essential Hardhat commands for managing contract development, including installing dependencies, running tests, deploying to testnets, and verifying contracts on block explorers. ```bash # Install dependencies npm install # Run tests npx hardhat test # Deploy to testnet npx hardhat run scripts/deployContract.ts --network sepolia # Verify contract npx hardhat verify --network polygon 0xf81A43EBA92538B0323fCDb1A040F2183B352Ca3 ``` -------------------------------- ### Example: Modifying an existing component Source: https://github.com/layer-3/clearsync/blob/master/docs/commit_practives.md When modifying an existing component, use the scope to specify the component and subcomponent being changed. This ensures clarity for subsequent changes. ```txt fix(UI/tx modal): not closing on click ``` -------------------------------- ### Get or Create Ethereum Signer Source: https://github.com/layer-3/clearsync/blob/master/pkg/keystore/README.MD Generate or retrieve an Ethereum signer for transaction signing from an HdWallet instance. Requires a unique account index. ```go uniqueIndex := uint32(0) // Example index signer, err := hdWallet.GetOrCreateSigner(uniqueIndex) if err != nil { // handle error } // Use the signer for signing transactions ``` -------------------------------- ### Quote Driver Interface Definition Source: https://github.com/layer-3/clearsync/blob/master/docs/YIP/YIP-0002-price-index.md Defines the interface for a quote driver, which handles initialization, starting, subscribing to markets, and closing connections. It requires market data, trade events, output events, configuration, and a WebSocket dialer. ```go type Driver interface { Init(markets cache.Market, outbox chan trade.Event, output chan<- event.Event, config config.QuoteFeed, dialer client.WSDialer) error Start() error Subscribe(base, quote string) error Close() error } ``` -------------------------------- ### Project Setup: Avoid Custom Remappings Source: https://github.com/layer-3/clearsync/blob/master/contracts/solidity-style-guide.md Avoid defining custom remappings in your project's configuration. Forge automatically deduces standard remappings, and custom ones can complicate dependency management for others. ```rust forge-std/=lib/forge-std/src/ solmate/=lib/solmate/src/ ``` -------------------------------- ### Initialize UniversalSigVer Client Source: https://github.com/layer-3/clearsync/blob/master/pkg/universal_sigver/README.md Create a client for the Universal Signer Verifier package by providing an ethclient provider URL, configuration, and an optional EntryPoint contract address. If no EntryPoint address is provided, the default v0.6 address is used. ```go import ( "github.com/layer-3/clearsync/pkg/universal_sigver" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) func main() { providerURL := "wss://your-infura-url" config := universal_sigver.Config{/* build your config here */} entryPointAddress := common.Address{/* address of a pre-deployed EntryPoint contract */} sigver, err := universal_sigver.NewUniversalSigVer(providerURL, config, entryPointAddress) if err != nil { panic(err) } // Use verifier to verify signatures sigver.Verify(...) } ``` -------------------------------- ### Create UserOp Client Instance Source: https://github.com/layer-3/clearsync/blob/master/pkg/userop/README.md Instantiates a new UserOp client using the provided configuration struct. Handle potential errors during client creation. ```go import "github.com/layer-3/clearsync/pkg/userop" // Create a UserOp client client, err := userop.NewClient(exampleConfig) if err != nil { panic(errors.New("Error creating UserOp client:", err)) } ``` -------------------------------- ### Get Token Supply Cap Source: https://github.com/layer-3/clearsync/blob/master/docs/YellowToken.md Returns the maximum total supply allowed for the token. ```solidity function cap() external view returns (uint256) ``` -------------------------------- ### Get Vault Balance Source: https://github.com/layer-3/clearsync/blob/master/docs/interfaces/IVault.md Retrieves the balance of a specified token held by the caller in the Clearsync Vault. ```APIDOC ## GET /api/vault/balance ### Description Returns the balance of the specified token for the caller. ### Method GET ### Endpoint /api/vault/balance ### Parameters #### Query Parameters - **token** (address) - Required - The address of the token being queried. ### Request Example ``` GET /api/vault/balance?token=0x1234567890abcdef1234567890abcdef12345678 ``` ### Response #### Success Response (200) - **balance** (uint256) - The balance of the token held by the caller. #### Response Example ```json { "balance": "750000000000000000" } ``` ``` -------------------------------- ### Get Token Decimals Source: https://github.com/layer-3/clearsync/blob/master/docs/YellowToken.md Returns the number of decimals used for user representation, overriding the default ERC20 value of 18. ```solidity function decimals() public pure returns (uint8) ``` -------------------------------- ### Testing Events: Prefer vm.expectEmit() Source: https://github.com/layer-3/clearsync/blob/master/contracts/solidity-style-guide.md When testing events, prefer using `vm.expectEmit()` for conciseness and completeness. It is equivalent to `vm.expectEmit(true, true, true, true)`. ```solidity function test_transferFrom_emitsCorrectly() { vm.expectEmit(); emit IERC20.Transfer(from, to, 10); token.transferFrom(from, to, 10); } ``` -------------------------------- ### Deploy Any Contract Source: https://github.com/layer-3/clearsync/blob/master/docs/scripts/README.md Use this command to deploy any contract with source code in this repository. Ensure the network is configured in hardhat.config.ts. ```bash NAME= ARGS= npx hardhat run scripts/deployContract.ts --network ``` -------------------------------- ### Import Clearsync Precision Package in Go Source: https://github.com/layer-3/clearsync/blob/master/pkg/precision/README.md Import the necessary packages, including the Clearsync precision package and the shopspring/decimal library, into your Go code. ```go import ( "github.com/shopspring/decimal" "github.com/layer-3/clearsync/pkg/precision" ) ``` -------------------------------- ### Driver Interface Definition Source: https://github.com/layer-3/clearsync/blob/master/docs/YIP/YIP-0002-price-index.md Defines the interface for a price feed driver, outlining methods for initialization, starting, subscribing to markets, and closing the connection. ```APIDOC ## Driver Interface ### Description Defines the contract for a price feed driver, enabling interaction with market data sources. ### Interface ```go type Driver interface { Init(markets cache.Market, outbox chan trade.Event, output chan<- event.Event, config config.QuoteFeed, dialer client.WSDialer) error Start() error Subscribe(base, quote string) error Close() error } ``` ### Methods - **Init**: Initializes the driver with necessary dependencies like market data, event channels, configuration, and a WebSocket dialer. - **Start**: Starts the driver's operation, typically by connecting to data sources and beginning to process data. - **Subscribe**: Subscribes to price updates for a specific trading pair (base and quote currency). - **Close**: Shuts down the driver and releases any resources. ``` -------------------------------- ### Prepend Private Key to Command Source: https://github.com/layer-3/clearsync/blob/master/docs/scripts/README.md If not set in .env, prepend your private key to any command that requires authentication, except for verifications. ```bash PRIVATE_KEY=YOUR_PRIVATE_KEY ...command ``` -------------------------------- ### Trade Event Structure Example Source: https://github.com/layer-3/clearsync/blob/master/pkg/quotes/README.md Represents a single trade event received by the Quotes Service. Includes source, market, volume, and price information. ```plaintext Trade { Source: Binance Market: btcusdt Volume: 0.5 Price: 44000 } ``` -------------------------------- ### Testing with Hardhat Source: https://context7.com/layer-3/clearsync/llms.txt Instructions for setting up, running tests, deploying, and verifying contracts using Hardhat. ```APIDOC ## Testing with Hardhat ### Install Dependencies ```bash npm install ``` ### Run Tests ```bash npx hardhat test ``` ### Deploy to Testnet ```bash npx hardhat run scripts/deployContract.ts --network sepolia ``` ### Verify Contract ```bash npx hardhat verify --network polygon 0xf81A43EBA92538B0323fCDb1A040F2183B352Ca3 ``` ``` -------------------------------- ### Configure UserOp Client Source: https://github.com/layer-3/clearsync/blob/master/pkg/userop/README.md Defines the configuration struct for the UserOp client, specifying provider, bundler, wallet, paymaster, and gas settings. This is used when initializing the client. ```go var ( exampleConfig = userop.ClientConfig{ ProviderURL: "https://YOUR_PROVIDER_URL", BundlerURL: "https://YOUR_BUNDLER_URL", PollPeriod: 100 * time.Millisecond, EntryPoint: common.HexToAddress("ENTRY_POINT_ADDRESS"), SmartWallet: userop.SmartWalletConfig{ // Example of a Kernel Smart Wallet config with Kernel v2.2. Type: &userop.SmartWalletKernel, Factory: common.HexToAddress("0x5de4839a76cf55d0c90e2061ef4386d962E15ae3"), // Zerodev Kernel factory address: Logic: common.HexToAddress("0x0DA6a956B9488eD4dd761E59f52FDc6c8068E6B5"), // Zerodev Kernel implementation (logic) address: ECDSAValidator: common.HexToAddress("0xd9AB5096a832b9ce79914329DAEE236f8Eea0390"), }, Paymaster: userop.PaymasterConfig{ // Example of a Pimlico USDC.e ERC20 Paymaster config. Type: &userop.PaymasterPimlicoERC20, URL: "", // Pimlico ERC20 Paymaster does not require a URL. Address: common.HexToAddress("0xa683b47e447De6c8A007d9e294e87B6Db333Eb18"), PimlicoERC20: userop.PimlicoERC20Config{ VerificationGasOverhead: decimal.RequireFromString("10000"), // verification gas overhead to be added to user op verification gas limit }, }, Gas: userop.GasConfig{ // These are default values. MaxPriorityFeePerGasMultiplier: decimal.RequireFromString("1.13"), MaxFeePerGasMultiplier: decimal.RequireFromString("2"), }, } // wallet deployment options are used when creating a new user op for the smart wallet that is not deployed yet walletDeploymentOpts = &userop.WalletDeploymentOpts{ Owner: common.HexToAddress("YOUR_OWNER_ADDRESS"), Index: decimal.NewFromInt(0), } // You can set either of gas limits when creating an user op to override the bundler's estimation. // Or you can set all of them to disable the bundler's estimation. gasLimitOverrides = &userop.GasLimitOverrides{ CallGasLimit: big.NewInt(42), VerificationGasLimit: big.NewInt(42), PreVerificationGas: big.NewInt(42), } // signer is used to sign the user op upon creation exampleSigner = userop.SignerForKernel(must(crypto.HexToECDSA( "0xYOUR_PRIVATE_KEY"))) ) ``` -------------------------------- ### Order Imports Alphabetically Source: https://github.com/layer-3/clearsync/blob/master/contracts/solidity-style-guide.md Order imports alphabetically by file name for better organization and readability. ```solidity import {A} from './A.sol' import {B} from './B.sol' ``` ```solidity import {B} from './B.sol' import {A} from './A.sol' ``` -------------------------------- ### Get Token Balance from Vault Source: https://github.com/layer-3/clearsync/blob/master/docs/interfaces/IVault.md Use this function to retrieve the balance of a specific token held by the caller in the vault. This is a view function and does not cost gas to call. ```Solidity function getBalance(address token) external view returns (uint256) ``` -------------------------------- ### Create User Operation Source: https://github.com/layer-3/clearsync/blob/master/pkg/userop/README.md Use `client.NewUserOp` to create a new user operation. This function builds and fills all fields for a user operation, requiring the smart wallet address, a signer function, a list of calls, and optional wallet deployment options. ```go // NewUserOp builds a new UserOperation and fills all the fields. // // Parameters: // - ctx - is the context of the operation. // - smartWallet - is the address of the smart wallet that will execute the user operation. // - signer - is the signer function that will sign the user operation. // - calls - is the list of calls to be executed in the user operation. // - walletDeploymentOpts - are the options for the smart wallet deployment. Can be nil if the smart wallet is already deployed. // // Returns: // - UserOperation - user operation with all fields filled in. // - error - if failed to build the user operation. func (c *backend) NewUserOp( ctx context.Context, smartWallet common.Address, signer Signer, calls []Call, walletDeploymentOpts *WalletDeploymentOpts, ) (UserOperation, error) ``` ```go sender := common.HexToAddress("0xsmartWalletAddress") call := userop.Call{ To: common.HexToAddress("0xtoAddress"), Value: 1000000000000000000, // 1 ETH in wei } ctx := context.Background() userOp, err := client.NewUserOp(ctx, sender, signer, userop.Call[]{call}, nil) if err != nil { log.Fatal("Error creating User Operation:", err) } fmt.Printf("User Operation created: %v\n", userOp) ``` -------------------------------- ### Set .env file for Private Key Source: https://github.com/layer-3/clearsync/blob/master/docs/scripts/README.md Optionally, set your private key in the .env file to avoid prepending it to every command. This is useful for frequent script usage. ```bash PRIVATE_KEY=YOUR_PRIVATE_KEY ``` -------------------------------- ### Verify Any Contract Source: https://github.com/layer-3/clearsync/blob/master/docs/scripts/README.md Verify any contract with source code in this repository. For proxy contracts, use the implementation contract's source code. ```bash npx hardhat verify --contract ':' --network ``` -------------------------------- ### Create New HD Wallet from Seed Source: https://github.com/layer-3/clearsync/blob/master/pkg/keystore/README.MD Instantiate a new HdWallet using a secure seed string. Ensure the seed is not empty to avoid errors. ```go seed := "your secure seed here" hdWallet, err := keystore.NewHdWallet(seed) if err != nil { // handle error } ``` -------------------------------- ### Proposed Generalized PaymentMethod Interface in Go Source: https://github.com/layer-3/clearsync/blob/master/docs/YIP/YIP-0007-payment-method.md A simplified and generalized PaymentMethod interface focusing on core swap and withdrawal operations. This version aims for greater flexibility in implementing diverse payment methods. Use this when a more abstract approach to payment processing is desired. ```go type PaymentMethod interface { // Both parties deposit the assets, agree to swap them. // The swap is performed here, but assets are not yet delivered. Execute(clearingId ChannelID) error // Withdraw deposited assets if any error occurs prior to the swap // It's an async operation, so a subscribe on Withdraw event is needed. Revert(clearingId ChannelID) error // Both parties agree that the swap was successful, but assets are not yet delivered. // Deliver the swapped assets to the parties. Withdraw(clearingId ChannelID) error // Withdraw swapped assets without counter-party confirmation if any error occurs after the swap ForceWithdraw(clearingId ChannelID) error // Subscribe and invoke `handler` when a specified `role` has fully withdrawn the funds from the Payment SubscribeOnWithdraw(clearingCid ChannelID, role ProtocolIndex, handler func() error) error } ``` -------------------------------- ### Documenting Solidity Structs with NatSpec Source: https://github.com/layer-3/clearsync/blob/master/contracts/solidity-style-guide.md Use @notice for struct-level documentation and @dev for individual field descriptions within a struct. This enhances code clarity and maintainability. ```solidity /// @notice A struct describing an accounts position struct Position { /// @dev The unix timestamp (seconds) of the block when the position was created. uint created; /// @dev The amount of ETH in the position uint amount; } ``` -------------------------------- ### Hardhat Project Commands Source: https://github.com/layer-3/clearsync/blob/master/README.md Common commands for interacting with a Hardhat project, used for testing and deploying smart contracts. ```bash npx hardhat help ``` ```bash npx hardhat test ``` ```bash npx hardhat node ``` ```bash npx hardhat run scripts/deployContract.ts ``` -------------------------------- ### TestERC20 Constructor Source: https://github.com/layer-3/clearsync/blob/master/docs/test/TestERC20.md Initializes a new TestERC20 token with a name, symbol, and total supply cap. ```Solidity constructor(string name_, string symbol_, uint256 cap_) public ``` -------------------------------- ### Price Calculator Interface Source: https://github.com/layer-3/clearsync/blob/master/pkg/quotes/README.md Defines the interface for custom index price calculation strategies. Allows for flexible implementation of different calculation methods. ```go type priceCalculator interface { calculateIndexPrice(trade TradeEvent) (decimal.Decimal, bool) } ``` -------------------------------- ### Set .env file for Polygon Source: https://github.com/layer-3/clearsync/blob/master/docs/scripts/README.md Configure RPC endpoints and API keys for Polygon network in the .env file. Ensure your API key is correctly inserted. ```bash POLYGON_URL=https://polygon-mainnet.g.alchemy.com/v2/YOUR_API_KEY POLYGONSCAN_API_KEY=YOUR_API_KEY ``` -------------------------------- ### Create User Operation Source: https://github.com/layer-3/clearsync/blob/master/pkg/userop/README.md Creates a new user operation using `client.NewUserOp`, filling all necessary fields for execution. ```APIDOC ## POST /api/userop/create ### Description Builds a new UserOperation and fills all the fields. ### Method POST ### Endpoint /api/userop/create ### Parameters #### Request Body - **smartWallet** (common.Address) - Required - The address of the smart wallet that will execute the user operation. - **signer** (Signer) - Required - The signer function that will sign the user operation. - **calls** ([]Call) - Required - The list of calls to be executed in the user operation. - **walletDeploymentOpts** (*WalletDeploymentOpts) - Optional - Options for the smart wallet deployment. Can be nil if the smart wallet is already deployed. ### Request Example { "smartWallet": "0xsmartWalletAddress", "calls": [ { "to": "0xtoAddress", "value": "1000000000000000000" } ], "walletDeploymentOpts": null } ### Response #### Success Response (200) - **userOperation** (UserOperation) - The created user operation with all fields filled in. #### Response Example { "userOperation": { "sender": "0xsmartWalletAddress", "nonce": "0", "initCode": "", "callData": "...", "callGasLimit": "...", "verificationGasLimit": "...", "preVerificationGas": "...", "maxFeePerGas": "...", "maxPriorityFeePerGas": "...", "paymasterAndData": "", "signature": "" } } ``` -------------------------------- ### Encode and Decode IVoucherVoucher in Go Source: https://github.com/layer-3/clearsync/blob/master/pkg/voucher/README.md Demonstrates how to use the voucher package to encode an IVoucherVoucher structure into an ABI-encoded byte slice and then decode it back. Ensure necessary imports are present. ```go package main import ( "fmt" "log" "github.com/ethereum/go-ethereum/common" "github.com/layer-3/clearsync/pkg/abi/ivoucher" "github.com/layer-3/clearsync/pkg/voucher" ) func main() { v := ivoucher.IVoucherVoucher{ Target: common.HexToAddress("0xabc123abc123abc123abc123abc123abc123abc1"), Action: 3, Beneficiary: common.HexToAddress("0xdef456def456def456def456def456def456def4"), ExpireAt: 1715100785, ChainId: 59144, VoucherCodeHash: [32]byte{/*--snip--*/}, EncodedParams: []byte("paramData"), } // Encode encoded, err := voucher.Encode(v) if err != nil { log.Fatal("Failed to encode voucher: ", err) } fmt.Println("Encoded voucher:", common.Bytes2Hex(encoded)) // Decode decoded, err := voucher.Decode(encoded) if err != nil { log.Fatal("Failed to decode voucher:", err) return } fmt.Println("Result:", decoded) } ``` -------------------------------- ### UserOp Client Interface Definition Source: https://github.com/layer-3/clearsync/blob/master/pkg/userop/README.md Defines the interface for the UserOp client, which handles smart account information, user operation creation, and sending them to the bundler. ```go type Client interface { IsAccountDeployed(ctx context.Context, owner common.Address, index decimal.Decimal) (bool, error) GetAccountAddress(ctx context.Context, owner common.Address, index decimal.Decimal) (common.Address, error) NewUserOp( ctx context.Context, sender common.Address, signer Signer, calls []Call, walletDeploymentOpts *WalletDeploymentOpts, gasLimitOverrides *GasLimitOverrides, ) (UserOperation, error) SendUserOp(ctx context.Context, op UserOperation) (done <-chan Receipt, err error) } ``` -------------------------------- ### Deploy Clearsync Contracts Script Usage Source: https://github.com/layer-3/clearsync/blob/master/docs/scripts/deploy_clearsync.md Command to execute the Clearsync deployment script. Ensure the network name is configured in hardhat.config.ts. ```bash DEPLOYER_PRIV_KEY="0x..." STAGE= npx hardhat run scripts/deployClearsync.ts --network ``` -------------------------------- ### VersionResponse Source: https://github.com/layer-3/clearsync/blob/master/docs/grpc/operator.proto.md Response containing the system version. ```APIDOC ## VersionResponse ### Description Provides the version information of the system. ### Response #### Success Response (200) - **version** (string) - The version string of the system. ``` -------------------------------- ### Add Vesting Schedule Source: https://github.com/layer-3/clearsync/blob/master/docs/tasks/Vesting.md Use this command to add a single vesting schedule. Ensure the amount accounts for token decimals. ```bash npx hardhat addSchedule --amount --beneficiary --contract --duration --start --network ``` -------------------------------- ### Activate Token Source: https://github.com/layer-3/clearsync/blob/master/docs/YellowToken.md Activates the token by minting a specified amount to an account. Requires DEFAULT_ADMIN_ROLE and must be called only once. The premint amount must be between 0 and the supply cap. ```solidity function activate(uint256 premint, address account) external ``` -------------------------------- ### YellowToken Constructor Source: https://github.com/layer-3/clearsync/blob/master/docs/YellowToken.md Initializes the YellowToken with a name, symbol, and supply cap. Grants DEFAULT_ADMIN_ROLE and MINTER_ROLE to the deployer. ```solidity constructor(string name, string symbol, uint256 supplyCap) public ``` -------------------------------- ### Solidity Commenting Style Source: https://github.com/layer-3/clearsync/blob/master/contracts/solidity-style-guide.md Allows for commenting to group sections of code, but the ordering of functions must still be followed. ```solidity /// External Functions /// ``` ```solidity /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* VALIDATION OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ ``` -------------------------------- ### useVoucher Function Source: https://github.com/layer-3/clearsync/blob/master/docs/interfaces/IVoucher.md Enables the use of a single voucher signed by the backend to receive game items. Requires the voucher details and its signature. ```solidity function useVoucher(struct IVoucher.Voucher voucher, bytes signature) external ``` -------------------------------- ### TestERC20 Constructor Source: https://github.com/layer-3/clearsync/blob/master/docs/test/TestERC20.md Initializes the TestERC20 token with a name, symbol, and a maximum supply cap. ```APIDOC ## constructor TestERC20 ### Description Initializes the TestERC20 token with a name, symbol, and a maximum supply cap. ### Method constructor ### Parameters - **name_** (string) - Description for name_ - **symbol_** (string) - Description for symbol_ - **cap_** (uint256) - Description for cap_ ``` -------------------------------- ### useVouchers Function Source: https://github.com/layer-3/clearsync/blob/master/docs/interfaces/IVoucher.md Allows the batch use of multiple vouchers signed by the backend to claim game items. Requires an array of vouchers and a single signature. ```solidity function useVouchers(struct IVoucher.Voucher[] vouchers, bytes signature) external ``` -------------------------------- ### UserOp Client Interface Source: https://github.com/layer-3/clearsync/blob/master/pkg/userop/README.md The UserOp client interface provides access to all library functionalities, including checking smart account information, creating user operations, and sending them to the client bundler for execution. ```APIDOC ## UserOp Client Interface ### Description The UserOp client interface provides access to all library functionalities, including checking smart account information, creating user operations, and sending them to the client bundler for execution. ### Interface Definition ```go type Client interface { IsAccountDeployed(ctx context.Context, owner common.Address, index decimal.Decimal) (bool, error) GetAccountAddress(ctx context.Context, owner common.Address, index decimal.Decimal) (common.Address, error) NewUserOp( ctx context.Context, sender common.Address, signer Signer, calls []Call, walletDeploymentOpts *WalletDeploymentOpts, gasLimitOverrides *GasLimitOverrides, ) (UserOperation, error) SendUserOp(ctx context.Context, op UserOperation) (done <-chan Receipt, err error) } ``` ### Methods #### IsAccountDeployed Checks if a smart account is deployed. - **Parameters**: - `ctx` (context.Context) - The context for the request. - `owner` (common.Address) - The owner address of the smart account. - `index` (decimal.Decimal) - The index of the smart account. - **Returns**: - `bool` - True if the account is deployed, false otherwise. - `error` - An error if the operation fails. #### GetAccountAddress Retrieves the address of a smart account. - **Parameters**: - `ctx` (context.Context) - The context for the request. - `owner` (common.Address) - The owner address of the smart account. - `index` (decimal.Decimal) - The index of the smart account. - **Returns**: - `common.Address` - The address of the smart account. - `error` - An error if the operation fails. #### NewUserOp Creates a new user operation. - **Parameters**: - `ctx` (context.Context) - The context for the request. - `sender` (common.Address) - The sender address. - `signer` (Signer) - The signer for the operation. - `calls` ([]Call) - A list of calls to be included in the user operation. - `walletDeploymentOpts` (*WalletDeploymentOpts) - Options for wallet deployment. - `gasLimitOverrides` (*GasLimitOverrides) - Overrides for gas limits. - **Returns**: - `UserOperation` - The created user operation. - `error` - An error if the operation fails. #### SendUserOp Sends a user operation to the client bundler for execution. - **Parameters**: - `ctx` (context.Context) - The context for the request. - `op` (UserOperation) - The user operation to send. - **Returns**: - `<-chan Receipt` - A channel that receives the transaction receipt. - `error` - An error if the operation fails. ``` -------------------------------- ### Clearsync Deployment Output Interface Source: https://github.com/layer-3/clearsync/blob/master/docs/scripts/deploy_clearsync.md Defines the structure of the output file containing deployed contract addresses and token information. ```typescript interface Info { deployedContracts: DeployedContracts; tokenList: TokenList; } interface DeployedContracts { adjudicator: string; clearingApp: string; escrowApp: string; } interface TokenList { name: string; timestamp: string; tokens: Token[]; } interface Token { chainId: number; address: string; name: string; symbol: string; decimals: number; } ``` -------------------------------- ### Group Imports by Type Source: https://github.com/layer-3/clearsync/blob/master/contracts/solidity-style-guide.md Group imports by external and local, separated by a blank line. Test files have an additional group for `/test` imports. ```solidity import { Math } from '/solady/Math.sol'; import { MyHelper } from './MyHelper.sol'; ``` ```solidity import { Math } from '/solady/Math.sol'; import { MyHelper } from '../src/MyHelper.sol'; import { Mock } from './mocks/Mock.sol'; ``` ```solidity import { MyHelper } from './MyHelper.sol'; import { Math } from '/solady/Math.sol'; ``` ```solidity import { Math } from '/solady/Math.sol'; import { MyHelper } from './MyHelper.sol'; ``` -------------------------------- ### Add Multiple Vesting Schedules Source: https://github.com/layer-3/clearsync/blob/master/docs/tasks/Vesting.md Add multiple vesting schedules efficiently by providing a CSV file. The CSV file should not contain a header and follow the specified format. ```bash npx hardhat addSchedules --contract --src --network ``` ```csv beneficiary,amount,start,duration ``` -------------------------------- ### MarginAppV1 - Margin Trading State Channel App Source: https://context7.com/layer-3/clearsync/llms.txt Implements the state transition rules for margin trading channels, validating state updates and maintaining channel integrity through different states. ```APIDOC ## MarginAppV1 - Margin Trading State Channel App ### Description MarginAppV1 implements the state transition rules for margin trading channels. It validates state updates, ensuring collateral distribution changes are valid and maintains the integrity of the trading channel through prefund, postfund, margin call, and final states. ### Contract Definition ```solidity // SPDX-License-Identifier: MIT pragma solidity 0.8.22; // MarginAppV1 State Transitions: // 0 - prefund: Initial channel setup, unanimous consent required // 1 - postfund: Channel funded and ready for trading // 2+ - margin call: Collateral redistribution between parties // 3+ - final: Channel conclusion with isFinal=true contract MarginAppV1 is IForceMoveApp { // Validates state transitions for margin channels // Returns (true, "") if the candidate state is supported function stateIsSupported( FixedPart calldata fixedPart, RecoveredVariablePart[] calldata proof, RecoveredVariablePart calldata candidate ) external pure returns (bool, string memory) { // Requires exactly 2 participants require(fixedPart.participants.length == 2, 'only 2 participants supported'); // All state transitions require unanimous consent require(NitroUtils.getClaimedSignersNum(candidate.signedBy) == 2, '!unanimous'); // Validates outcome transitions maintain total collateral // Destinations cannot change, only amounts can be redistributed } } ``` ### Example Usage #### Create margin channel fixed part ```solidity // Example: Create margin channel fixed part FixedPart memory fixedPart = FixedPart({ participants: [brokerA, brokerB], channelNonce: uint256(keccak256(abi.encodePacked(block.timestamp))), appDefinition: marginAppAddress, challengeDuration: 86400 // 24 hours }); ``` ``` -------------------------------- ### Use Two-Step Ownership Transfer in Solidity Source: https://github.com/layer-3/clearsync/blob/master/contracts/solidity-development-practices.md Employ the two-step ownership transfer pattern for contract ownership changes. This pattern requires the new owner to explicitly accept the transfer, enhancing security by preventing accidental or malicious ownership changes. ```Solidity contract Token is Ownable2Step { ... } ``` ```Solidity contract Token is Ownable { ... } ``` -------------------------------- ### ERC-4337 User Operation Sequence Diagram Source: https://github.com/layer-3/clearsync/blob/master/docs/YIP/YIP-0010-smart-contract-based-channel-funding.md Illustrates the flow of a user operation in ERC-4337, from user creation to network execution, involving UserOperations, Bundler, Paymaster, and the Ethereum Network. This diagram helps understand the interaction between different components in the account abstraction process. ```mermaid sequenceDiagram participant User participant UserOperation participant Bundler participant Ethereum Network participant Paymaster User->>UserOperation: Create operation with action details UserOperation->>User: Sign operation User->>Bundler: Send signed UserOperation Bundler->>Paymaster: Request gas fee coverage for UserOperation Paymaster->>Bundler: Approve and provide fee Bundler->>Ethereum Network: Submit bundled UserOperations Ethereum Network->>User: Execute operation Ethereum Network->>Paymaster: Deduct gas fee ``` -------------------------------- ### Open Solidity Version Pragma Source: https://github.com/layer-3/clearsync/blob/master/contracts/solidity-style-guide.md Supporting contracts and libraries should have an open Pragma, compatible with the next major version, e.g., `^0.8.0`. ```solidity pragma solidity ^0.8.0; ``` -------------------------------- ### Use Named Imports Source: https://github.com/layer-3/clearsync/blob/master/contracts/solidity-style-guide.md Named imports clarify which specific components are being used and their origin. This is optional for test files. ```solidity import {Contract} from "./contract.sol" ``` ```solidity import "./contract.sol" ``` -------------------------------- ### Stream Real-time Trades from Multiple Exchanges Source: https://context7.com/layer-3/clearsync/llms.txt Use this to aggregate real-time trade data from various centralized and decentralized exchanges. Configure drivers, markets, and process incoming trade events. ```go package main import ( "context" "fmt" "time" "github.com/layer-3/clearsync/pkg/quotes" ) func main() { // Create trade event channel outbox := make(chan quotes.TradeEvent, 100) // Configure multiple price sources config := quotes.Config{ Drivers: []quotes.DriverType{ quotes.DriverBinance, quotes.DriverUniswapV3, }, Binance: quotes.BinanceConfig{ USDCtoUSDT: true, BatchPeriod: 5 * time.Second, }, UniswapV3: quotes.UniswapV3Config{ FactoryAddress: "0x1F98431c8aD98523631AE4a59f267346ea31F984", }, Rpc: quotes.RpcConfig{ Ethereum: "https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY", }, } // Create aggregated driver driver, err := quotes.NewDriver(config, outbox, nil, nil) if err != nil { panic(err) } // Start and subscribe to markets driver.Start() driver.Subscribe(quotes.NewMarket("btc", "usdt")) driver.Subscribe(quotes.NewMarket("eth", "usdc")) // Process incoming trades for trade := range outbox { fmt.Printf("[%s] %s: %s @ %s\n", trade.Source, trade.Market, trade.Amount, trade.Price, ) } } ``` -------------------------------- ### Define PaymentMethod Interface in Go Source: https://github.com/layer-3/clearsync/blob/master/docs/YIP/YIP-0007-payment-method.md Defines the core methods for a payment method, including initiation, preparation, execution, reversion, finalization, withdrawal, and subscription to withdrawal events. Use this interface to integrate payment logic into the clearing process. ```go type PaymentMethod interface { // Make sure that a payment method is ready, acquire the assets from each party Initiate(clearingId ChannelID, settlementLedger SettlementLedger, peer Peer) error // Parties agree that assets are deposited and ready to be swapped Prepare(clearingId ChannelID) error // Swap the assets Execute(clearingId ChannelID) error // Withdraw deposited assets if any error occurs prior to the swap // It's an async operation, so a subscribe on Withdraw event is needed. Revert(clearingId ChannelID) error // Parties confirm that the assets are swapped, but not yet delivered Finalize(clearingId ChannelID) error // Retrieve the assets Withdraw(clearingId ChannelID) error // Withdraw swapped assets without counter-party confirmation if any error occurs after the swap ForceWithdraw(clearingId ChannelID) error // Subscribe and invoke `handler` when a specified `role` has fully withdrawn the funds from the Payment SubscribeOnWithdraw(clearingCid ChannelID, role ProtocolIndex, handler func() error) error } ``` -------------------------------- ### Send User Operation to Bundler Source: https://github.com/layer-3/clearsync/blob/master/pkg/userop/README.md Use `client.SendUserOp` to send a user operation to the client bundler for execution. This function submits the operation and returns a channel to await the user operation's receipt. ```go type Receipt struct { UserOpHash common.Hash TxHash common.Hash Sender common.Address Nonce decimal.Decimal Success bool ActualGasCost decimal.Decimal ActualGasUsed decimal.Decimal RevertData []byte // non-empty if Success is false and EntryPoint was able to catch revert reason. } // SendUserOp submits a user operation to a bundler and returns a channel to await for the userOp receipt. // // Parameters: // - ctx - is the context of the operation. // - op - is the user operation to be sent. // // Returns: // - <-chan Receipt - a channel to await for the userOp receipt. // - error - if failed to send the user operation func SendUserOp(ctx context.Context, op UserOperation) (done <-chan Receipt, err error) ``` ```go ctx := context.Background() receiptChannel, err := client.SendUserOp(ctx, userOp) if err != nil { log.Fatal("Error sending User Operation to bundler:", err) } // Await the receipt from the channel result := <-receiptChannel fmt.Printf("User Operation result: %v\n", result) ``` -------------------------------- ### Encode and Decode Vouchers using Ethereum ABI Source: https://context7.com/layer-3/clearsync/llms.txt Utilize the voucher package for Ethereum ABI encoding and decoding of voucher structures. This is used for token claiming and rewards distribution. ```go package main import ( "fmt" "github.com/ethereum/go-ethereum/common" "github.com/layer-3/clearsync/pkg/abi/ivoucher" "github.com/layer-3/clearsync/pkg/voucher" ) func main() { // Create a voucher v := ivoucher.IVoucherVoucher{ Target: common.HexToAddress("0x2A8B51821884CF9A7ea1A24C72E46Ff52dCb4F16"), Action: 1, // Action type Beneficiary: common.HexToAddress("0x742d35Cc6634C0532925a3b844Bc9e7595f5fB35"), ExpireAt: 1735689600, // Unix timestamp ChainId: 137, // Polygon VoucherCodeHash: [32]byte{}, // Keccak256 of voucher code EncodedParams: []byte{}, // ABI-encoded parameters } // Encode voucher to bytes encoded, err := voucher.Encode(v) if err != nil { panic(err) } fmt.Printf("Encoded: 0x%x\n", encoded) // Decode voucher from bytes decoded, err := voucher.Decode(encoded) if err != nil { panic(err) } fmt.Printf("Target: %s\n", decoded.Target.Hex()) fmt.Printf("Beneficiary: %s\n", decoded.Beneficiary.Hex()) } ```