# Allo Sketchbook This document contains ideas for rethinking an Allo protocol from the ground up. ## Goals - A strategy should be as easy to deploy as an NFT (no dependencies on external contracts that needs to be deployed) - Extension and library contracts for gating, allocation and distribution methods, quadratic math, etc to enable composition of functionalities (similar to OpenZeppelin's wizard). - Audited functions for common operations that developers can safely use (quadratic math, simple payouts, etc). - Each recipient in a round is just an address that can represent anything from an EOA to a smart project account with ERC4337 using modules for extended functionalities (such as vesting and payment splitting) - Easy to extend and interact with other services such as Superfluid, EAS, Hedgey, MACI etc. - Rounds should be able to be funded via regular transactions (eg. directly from Coinbase to round address) ## Key Ideas - **Minimal core contracts** - a small interface that yields composability (like ERC20 or ERC721 but for Rounds). - **Indexer** - collects the data from all rounds and makes it queryable - **Powerful SDK with React Hooks** - simple to build front-facing app layers - **Transparent Project Registry** - each project is a smart account with capabilities (payment splitting, vesting, multi-sig, etc). The community can explore projects, their impact, their members, funding, capabilities etc. Owners can apply to new rounds. This is part of the app layer and could even be a separate app. ## Inspirations - OpenZeppelin (library functions + ERC20/721 + ownable & pausable modifiers) - EAS + GraphQL Indexer ## Architecture ### Protocol Layer The core of a funding protocol is to: fund a round with tokens, register recipients, allocate tokens to recipients, and distribute tokens to the recipients based on a calculation. The way these things happen might differ for different applications. - **Fund pool** - what tokens does the pool manage? - **Register recipient** - what are the requirements to enter the pool? - Check for EAS, ERC20, ERC721, Admin approval, ... - **Allocate** - how are tokens allocated to the recipients? - Direct, Quadratic Voting / Funding, OP RPGF3 Quorum, Streams, ... - **Distribute** - how are the tokens distributed? - Direct payout, MerkleTree claim, streams, ... Whenever these actions happen, an event is emitted (Fund, Register, Allocate, Distribute). An Indexer builds data from these events that can be queried from frontends or backends via a HTTP API. More info on the indexer is mentioned later in this document. Much like the ERC20 and ERC721, the core of Allo is simple. It describes a small set of functions and events and makes no assumptions on the implementations. This is powerful because it enables composability in the app layers. Aave and Uniswap works because all the ERC20 tokens share the same interface (transfer, balanceOf, allowance, approve). What could a Defi-like platform for Grants look like if they shared the same interface? In OpenZeppelin an ERC20 can easily be extended with the Ownable contract to provide rules for who owns the contract and how it is transfered to a new owner. There is also the ERC4626 Tokenized Vault that extends the functionality to mint shares whenever an underlying token is deposited. These are just some examples of the composability that can be enabled with clear distinctions of functionality. Read more about the OZ ERC20 and its extensions here: https://docs.openzeppelin.com/contracts/5.x/api/token/erc20 #### Core contracts The base contract only contains the bare essentials of what's needed to run a round. Rounds can be funded via simply transfering tokens to the contract or via a `fund` function. By allowing funding via simple transfers we open up for funding pools directly from a Coinbase account. Additionally, other smart contracts can be wired together to fund these pools. For example streaming into a Round. ```solidity interface IRound { // timestamps for application and voting period, etc uint64[] public phases; struct Metadata { uint8 protocol // http or ipfs string pointer // url or cid to information about the round } event Create(indexed address round); event Fund(indexed address token, uint256 amount); event Withdraw(indexed address token, uint256 amount); event Register(indexed address recipient, bytes data); event Allocate(indexed address recipient, uint256 amount, bytes data); event Distribute(indexed address recipient, uint256 amounts, bytes data); // Setup when deployed (token, phases, metadata, etc.) function init(bytes config) {} // Round Manangers function fund(address token, uint256 amount) {} function withdraw(address recipient, address token, uint256 amount) {} // Project Registration function register(address[] recipients, bytes data) external payable {} // Fund / Vote for project(s) function allocate(address[] recipients, uint256[] amounts, bytes data) external payable {} // Transfer tokens to projects (push or pull / direct or Merkle) function distribute(address[] recipients, uint256[] amounts, bytes data) external payable {} } ``` Sending an array of recipients and amounts gives great flexibility and removes any need for batch functions. Any additional data that might be needed for custom logic can be sent as an encoded data buffer. This data is also sent to the corresponding events. The data can then be decoded by the contract or frontend for custom functionality such as: - Register - Application metadata is sent and stored in the round - Allocate - Specific token address for multi-token rounds - Distribute - MerkleTree for participants to claim ##### Meta Transactions A suggestions is to not use `msg.sender` in any of the Round contracts but instead pass a `sender` parameter in the functions. This is to enable Meta Transactions. For example, a `RoundERC2771Context` contract could be written to forward transactions to the round. #### Indexer EAS has built a powerful indexer that makes it easy to build queries to find relevant data. An Allo indexer should be able to be decoupled from the app layer and answer questions like: - What rounds have a project/recipient participated in? - How much funding have a project accrued? From what strategies? - What rounds have pooled the most funds in the last year? - What new rounds can my project participate in? - ... #### Utility library There are also utility libaries with functionality to help with calculating quadratic math for example. ```solidity library QuadraticMath { struct VoteState {} function vote(address[] recipients, uint256[] votes, VoteState state) internal returns (VoteState next) {} } ``` #### SDK A powerful typescript SDK: - Calls contract methods and awaits the emitted events (instead of just returning when transaction is sent successfully) - Wraps ReactQuery (similar to what tRPC does) ```ts const round = await allo.round.deploy(strategy, config) // or const round = await allo.round.get(roundAddress) // All API also has ReactQuery wrappers (useQuery and useMutation) const { isLoading, mutate } = await round.fund.useMutation({ token, amount }, { onSuccess() { router.redirect(`/success`)} }) await round.register(projectAddress, applicationMetadata) await round.allocate(projectAddress, 10_000) ``` ### Project Registry There is no project registry. The registry is in the indexed data based from Register events. Each Project / Recipient is represented as an address. It's up to the project to choose what features it should have. Here are some examples of what a project could be: - An EOA - A Safe Multisig - An ERC4337 with modules for payment splitting, vesting The Project Registry is in the app layer and can be used by several other apps. Imagine a place where the project owner goes to: - Create / Deploy their project account - Add / Manage modules - List new rounds (via the Indexer) - Apply to rounds - Add updates and links With modules, rounds can be built to verify certain conditions about the project on-chain. For example: - Project must have recevied an attestation from a hackathon - Project must have a vesting period of 180 days The community can explore projects: - Project information and members - Added modules (payment splitting, vesting, etc) - See impact ### App Layer TBD ## Round Contract Examples #### Minimal Simple contract that transfer tokens to a collection recipients ```solidity contract MinimalRound is Round { function init(bytes config) { __Round_init(config); } function distribute(address[] recipients[], uint256[] amounts[]) external onlyRoundAdmin { Utils.iteratePayouts(recipients, amounts, this.payout) } function payout(address recipient, uint256 amount) { Tokens.transfer(recipient, amount); emit Distribute(recipient, amount); } ``` Interacting with the Round ```ts // First create a round with the strategy // (dev: what's the benefit of changing the roundAddress to a roundId? Is it about indexing to find rounds?) const roundId = await allo.createRound(roundAddress) // Define the distribution payouts const [recipients, amounts] = [["0x...", "vitalik.eth"], [10n, 10n]] // Fund the round // (dev: could the fund function keep track of all the tokens in the round? no need for poolAmount) // (dev: what's the biggest value of calling Allo contract rather than round contracts directly?) await allo.fund(roundId, tokenAddress, 10n) // Transfer the tokens await allo.distribute(roundId, recipients, amounts) ``` #### Gating Some rounds might want to be restricted in certain ways. For example what projects can register and who can allocate (vote and fund) the projects. This is done with small contracts with modifiers and helper functions similar to OpenZeppelin's Ownable or Pausable contracts. ```solidity contract GatedRound is Round, EASGate, NFTGate { function init(bytes config) { __EASGate_init(attester); __NFTGate_init(nftAddress); } // Only allow projects with an EAS Attestation function register(address recipient) onlyAttestation(recipient, attester, schemaId) {} // Only funders with an NFT can allocate function allocate(address recipient, uint256 amount) onlyNFT(recipient) {} // Or with 10 GTC function allocate(address recipient, uint256 amount) onlyERC20(gtcAddress, 10e18) {} ``` #### Quadratic Voting & Funding Library to help with calculations. These can be used across rounds. See below for examples. ```solidity library QVMath { struct State { uint8 voiceCredits; mapping(address => uint256) votes; mapping(address => uint256) voters; } function init(uint8 voiceCredits) returns(State state) {} function vote(address[] memory recipients, uint256[] memory votes, State storage state) {} function calcVotes(State state) {} } library QFMath { struct Donation { uint256 amount; address funder; } struct State { EnumerableSet.AddressSet recipients; mapping(address => Donation[]) donations; } function fund(address[] memory recipients, uint256[] memory votes, State storage state) {} function calcMatching(uint256 matchingAmount, State state) {} } ``` ##### Quadratic Voting Initialise with a set number of voiceCredits per voter. ```solidity contract QVRound is Round { QVMath.State private state; function init(bytes data) { uint8 _voiceCredits = abi.decode(data, (uint8)); state = QVMath.init(_voiceCredits); } function allocate(address[] recipients, uint256[] amounts) { // All the logic for keeping track of quadratic voting state is handled by the QVMath libratry QVMath.vote(recipients, amounts, state); } } contract QFRound is Round { QFMath.State private state; function allocate(address[] recipients, uint256[] amounts) { QVMath.fund(recipients, amounts, state); } function distribute() { uint256 matchingAmount = token.balanceOf(address(this)); (address[] recipients, uint256[] amounts) = QFMath.calcMatching(matchingAmount, state); // Loop recipients and transfer tokens Utils.iteratePayouts(recipients, amounts, this.payout) } function payout(address recipient, uint256 amount) { Tokens.transfer(recipient, amount); emit Distribute(recipient, amount); } } ``` #### Superfluid ```solidity contract StreamingRound is Round { uint32 public constant INDEX_ID = 0; ISuperToken private token; function init(bytes data) { _token = abi.decode(data, (address); token = ISuperToken(_token); token.createIndex(INDEX_ID); } function allocate(address recipient, uint256 amount, bytes data) { (, , uint256 currentUnitsHeld, ) = token.getSubscription(address(this), INDEX_ID,recipient); token.updateSubscriptionUnits(INDEX_ID, recipient, currentUnitsHeld + amount); } function distribute() { uint256 balance = token.balanceOf(address(this)); (uint256 actualDistributionAmount, ) = token.calculateDistribution(address(this), INDEX_ID, balance); token.distribute(INDEX_ID, actualDistributionAmount); } } ``` #### Superfluid QuadraticVoting Vote via QuadraticVoting and distribute in proportion to votes received by each project. ```solidity contract StreamingQFRound is Round { uint32 public constant INDEX_ID = 0; ISuperToken private token; QVMath.State private state; function init(bytes data) { (_token, _voiceCredits) = abi.decode(data, (address, uint256)); QVMath.init(_voiceCredits); token = ISuperToken(_token); token.createIndex(INDEX_ID); } function allocate(address[] recipients, uint256[] amounts, bytes data) { QVMath.vote(recipients, amounts, state); } function distribute() { (address[] recipients, uint256[] amounts) = QVMath.calcVotes(state); for (uint i = 0; i < recipients.length; i++) { token.updateSubscriptionUnits(INDEX_ID, recipients[i], amounts[i]); } uint256 balance = token.balanceOf(address(this)); (uint256 actualDistributionAmount, ) = token.calculateDistribution(address(this), INDEX_ID, balance); token.distribute(INDEX_ID, actualDistributionAmount); } } ``` #### Drips *More research into Drips protocol needed* ```solidity contract DripsRound is Round { function init(bytes config) { AddressDriver driver = IDriver(_dripsDriverAddress); } function distribute() { (address[] recipients, uint256[] amounts) = QVMath.calcVotes(state); Utils.iteratePayouts(recipients, amounts, this.payout) } function payout(address recipient, uint256 amount) { uint256 accountId = driver.calcAccountId(recipient); driver.give(accountId, token, amount); emit Distribute(recipient, amount); } } ``` #### MerklePayout ```solidity contract RoundMerklePayout is MerkleProof { bytes32 private root; // Set the MerkleRoot function distribute(bytes data) { // Decode bytes data root = decodedRoot; } // Participants call claim to pull their funds function claim(bytes32 memory proof, address recipient, uint256 amount) { bytes32 leaf = keccak256(bytes.concat(keccak256(abi.encode(recipient, amount)))); // verify proof and transfer tokens require(MerkleProof.verify(proof, root, leaf), "Invalid proof"); } } ``` #### Extensions Manual approval of registrants ```solidity abstract contract RoundApproveRegistrants is Round { function approve(address[] recipients) external onlyAdmin { for (uint i = 0; i < recipients.length; i++) { applicationStatus[recipients[i]] = Status.Approved; } } function register(address recipient, bytes data) { require(applicationStatus[recipient] == Status.Approved, "Recipient is not approved yet."); super.register(recipient, data); } } ``` All these examples can be seamlessly combined. For example: - Pick Gating (EAS, ERC20, ERC721, Manual Approval) - Pick Reward Token (ERC20, SuperToken) - Pick Allocation method (Direct, QV, QF, RetroFunding) - Pick Distribution method (Direct, Merkle) A Web UI wizard could do this visually. --- Rounds must be able to support: - Direct to contract incentives - Self curated registries ### Direct to Contract ```solidity contract DirectRound is Round { // Can be called by anyone to simply transfer tokens to function distribute(address[] recipients, uint256 amounts) { // Distribute to the grantee Utils.iteratePayouts(recipients, amounts, this.payout) } function payout(address recipient, uint256 amount, bytes data) { Tokens.transfer(recipient, amount, token); emit Distribute(recipient, amount); } } ``` ```solidity contract CuratedRegistry is Round { // Can be called by anyone to simply transfer tokens to function distribute(address[] recipients, uint256 amounts) { // Distribute to the grantee Utils.iteratePayouts(recipients, amounts, this.payout) } function payout(address recipient, uint256 amount, bytes data) { Tokens.transfer(recipient, amount, token); emit Distribute(recipient, amount); } } ``` --- Previous notes: - It needs to describe a minimal interface similar to an EIP for the functions and events (register, allocate, distribute). From these other infra can easily build on. - It needs to be as fun and easy to build as the open zeppelin libraries. It has extensions. - It needs audited functions for common operations that developers can safely use. - It needs to come with a set of base contracts. - It needs to be able to easily extend and interact with other services such as Superfluid, EAS, Hedgey etc. - It needs to support Account Abstraction and Trusted forwarder for meta tx. - It needs to come with a powerful indexer (like EAS) - it does not need to have opinions on the shape of a project, any address is a valid registration. It could however check the interface during registration to verify certain methods exist. So what are the base contracts for Grants Stack? - account abstraction or meta tx support - crosschain support What Allo2 tried to create with registry and approved strategies was not in the right layer. Those should be on the app layer and not the protocol layer. So what would that look like? It would mean the app layer would need to have additional contracts? There would need to be a way to create rounds. A round factory. The app layer might want to allow for other protocols to submit their own custom-made rounds. Wouldn't that just move the code from one place to another? True, but it would retain the flexibility in the protocol layer. The core would be there. The periphery in the app layer. The app chooses to approve the round contracts submitted (by Superfluid for example). How do create a protocol that can re-use the allocation methods for different integrations? Let's say Superfluid tokens. When allocate is called, it should start streaming tokens but it should do so in accordance to another function (QF, Direct). And with QF, there's that phase of additional funding based on what has been allocated already. Is that part of distribute? That means distribute is: - calculate any extra payouts based on previous allocation (is this a beforeDistribute hook?) - set the Merkle tree for claims or directly transfer to the recipients SuperQFRound: - init - set up the super token - allocate - allocateQF(recipient, amount) what does allocateQF actually do? allocateDirect, allocateQF Look deeper into the different calculations used by the allo2 contracts. Architecture: - protocol layer - core contracts for creating a round + helper contracts and functions + indexer - app layer - contract for round factory, determines the rules for how projects apply and manages crosschain + meta tx via helpers from protocol layer Is project registry another app layer? It's completely independent from the protocol layer (and app layer). It's its own product. It does however interface with the app (or protocol?) layer via round.register(projectAdress). It can also query the protocol layers indexer to find all the rounds, allocations, and distributions via the events (Register, Allocate, Distribute). Yes, it's another app layer. The project registry also queries common grants platforms and has interfaces so it knows how to apply to them). Finally, there's the checkout app. It handled connection of wallet and sending the transaction (that is contained in the URL). Here the user can also bridge and onramp fiat. The advantage of having this separate from the grants platform is that the project registry can also use it, and other upcoming gitcoin projects. It provides the infra for sending transactions. This means the app layer only has to encode the function data and create a checkout link to redirect the user to. A success url returns the user once the transaction succeeds. # Work-in-Progress Ideas - Project Registry - Programmable Project accounts - Projects should be a contract that can be upgraded and changed by the owners **independent of the grants protocol**. - Alchemy AccountKit (or Safe Smart Account + Modules) - Alchemy and Safe are trusted and has an existing ecosystem - Website - manage projects - Create and update project account (deploys smart account) - Add modules to account - payment splitting to team members + other projects - programatically funnel funds + verifiable by community - Apply for grants (Grants Stack, Giveth, ...) - A page shows upcoming rounds and ways to apply to them - research projects - previous rounds - see impact metrics - see project finances + where funds streams - project updates (socials, farcaster, blogs, ...) - Simple grants protocol - Simple and minimalistic - Core purpose of contract is - handling token transfers (fund pool + project + payout) - Each Round contract is in itself a Safe - Pull-based payouts (simpler + more secure) - Calculations happen off-chain and submits merkle tree for payouts - Easier to write strategies - Payouts can be verified by anyone based on chain events - Checkout ```mermaid sequenceDiagram Actor RoundManager Actor Grantee Actor Community Participant Registry Participant Allo Participant DistributionService Grantee->>+Registry: Deploy Safe Smart Account Registry-->>-Grantee: Project address RoundManager->>+Allo: Create round RoundManager-->>+Allo: Fund round Grantee->>Allo: Apply to round (project address) Community->>Allo: Vote for project RoundManager->>+DistributionService: Calculate DistributionService->>-Allo: Set Payout Merkle ``` Distribution Service - Query chain for events within start and end dates - Transfer ```solidity contract Round is AlloRound { constructor(config) { token = config.token; } /* Rounds can be funded. Meta transactions (_msgSender()) enables higher flexibility in how contracts are called. */ function fund(uint256 amount) external { transferFrom(_msgSender(), address(this), amount); } /* Once round is over, round manager sets merkle tree to enable payouts */ function setMerkle() external onlyRoundManager(_msgSender()) {} /* Transfer tokens to a projects smart account address */ function allocate(address project, uint256 amount, bytes metadata) external { transferFrom(_msgSender(), address, amount); emit Allocate(address, token, amount); } function distribute(bytes proof, address project, uint256 amount) { // verify(proof, project) transfer(project, amount); } } ```