├── .gitignore ├── README.md ├── assets ├── architecture.jpg └── demo.gif ├── copilot ├── async_util.py ├── config.py ├── data │ ├── contract.csv │ ├── erc20.csv │ ├── loader.py │ ├── loader.test.py │ ├── protocol.csv │ └── protocols.yaml ├── greet.py ├── index.py ├── method_search_engine │ ├── .gitattributes │ ├── embedding_generator.py │ ├── engine.py │ ├── engine.test.py │ ├── index.json │ ├── query_template.txt │ └── steps_input.yaml ├── pipeline.py ├── pipeline.test.py ├── program_generator │ ├── program.py │ ├── steps_template.txt │ └── tests │ │ ├── pgt_combo.txt │ │ ├── program.py │ │ ├── program_combo.py │ │ ├── program_swap_ETHUNI.py │ │ └── program_swap_USDCETH.py └── task_interpreter │ ├── data.json │ ├── index.py │ ├── interpreter-input-template.txt │ ├── task_interpreter.py │ └── task_interpreter.test.py ├── docs ├── aave-docs-v2 │ ├── README.md │ ├── SUMMARY.md │ ├── change-from-v1-to-v2.md │ ├── deployed-contracts │ │ ├── amm-market.md │ │ ├── avalanche-market.md │ │ ├── deployed-contracts.md │ │ ├── matic-polygon-market.md │ │ └── permission-ed-markets.md │ ├── getting-started │ │ ├── gas-limits.md │ │ ├── sdks.md │ │ └── using-graphql.md │ ├── glossary.md │ ├── guides │ │ ├── ampl-asset-listing.md │ │ ├── apy-and-apr.md │ │ ├── credit-delegation.md │ │ ├── flash-loans │ │ │ ├── README.md │ │ │ └── iflashloanreceiver.md │ │ ├── liquidations.md │ │ ├── liquidity-mining.md │ │ └── troubleshooting-errors.md │ ├── protocol-governance │ │ ├── governance │ │ │ ├── README.md │ │ │ └── propose-your-token-as-new-aave-asset.md │ │ └── staking-aave.md │ └── the-core-protocol │ │ ├── aave-token.md │ │ ├── addresses-provider-registry │ │ ├── README.md │ │ └── ilendingpooladdressesproviderregistry.md │ │ ├── addresses-provider │ │ ├── README.md │ │ └── ilendingpooladdressesprovider.md │ │ ├── atokens │ │ ├── README.md │ │ └── iatoken.md │ │ ├── debt-tokens │ │ ├── README.md │ │ ├── istabledebttoken.md │ │ └── ivariabledebttoken.md │ │ ├── lendingpool │ │ ├── README.md │ │ └── ilendingpool.md │ │ ├── price-oracle │ │ ├── README.md │ │ └── ipriceoracle.md │ │ ├── protocol-data-provider │ │ ├── README.md │ │ └── iprotocoldataprovider.md │ │ ├── protocol-overview.md │ │ └── weth-gateway │ │ ├── README.md │ │ └── iwethgateway.md ├── aave-docs-v3 │ ├── README.md │ ├── SUMMARY.md │ ├── core-contracts │ │ ├── aaveoracle.md │ │ ├── aaveprotocoldataprovider.md │ │ ├── aclmanager.md │ │ ├── pool.md │ │ ├── pooladdressesprovider.md │ │ ├── pooladdressesproviderregistry.md │ │ ├── poolconfigurator.md │ │ └── priceoraclesentinel.md │ ├── deployed-contracts │ │ ├── deployed-contracts.md │ │ ├── security-and-audits.md │ │ ├── v3-mainnet │ │ │ ├── README.md │ │ │ ├── arbitrum.md │ │ │ ├── avalanche.md │ │ │ ├── fantom.md │ │ │ ├── harmony.md │ │ │ ├── optimism.md │ │ │ └── polygon.md │ │ └── v3-testnet-addresses.md │ ├── getting-started │ │ ├── contracts-overview.md │ │ ├── l2-optimization │ │ │ ├── README.md │ │ │ ├── l2encoder.md │ │ │ └── l2pool.md │ │ └── protocol-feature-summary.md │ ├── guides │ │ ├── credit-delegation.md │ │ ├── flash-loans.md │ │ ├── governance-guide │ │ │ ├── README.md │ │ │ ├── asset-listing.md │ │ │ ├── parametertuning.md │ │ │ ├── permissions.md │ │ │ └── rewards.md │ │ ├── liquidations.md │ │ ├── testing-guide.md │ │ └── troubleshooting-errors.md │ ├── periphery-contracts │ │ ├── rewardscontroller.md │ │ ├── uiincentivedataproviderv3.md │ │ ├── uipooldataproviderv3.md │ │ ├── walletbalanceprovider.md │ │ └── wethgateway.md │ ├── protocol-feature-summary.md │ ├── tokens │ │ ├── atoken.md │ │ ├── debttoken.md │ │ ├── delegationawareatoken.md │ │ └── treasury_and_staking.md │ └── whats-new │ │ ├── efficiency-mode-emode.md │ │ ├── isolation-mode.md │ │ ├── multiple-rewards-and-claim.md │ │ ├── portal.md │ │ ├── repay-with-atokens.md │ │ ├── siloed-borrowing.md │ │ └── supply-borrow-caps.md ├── curve-docs │ ├── dao-fees.rst │ ├── dao-gauges-sidechain.rst │ ├── dao-gauges.rst │ ├── dao-overview.rst │ ├── dao-ownership.rst │ ├── dao-vecrv.rst │ ├── dao-voting.rst │ ├── exchange-cross-asset-swaps.rst │ ├── exchange-deposits.rst │ ├── exchange-lp-tokens.rst │ ├── exchange-overview.rst │ ├── exchange-pools.rst │ ├── factory-deployer.rst │ ├── factory-deposits.rst │ ├── factory-migrator.rst │ ├── factory-oracles.rst │ ├── factory-overview.rst │ ├── factory-pools.rst │ ├── guide-code-style.rst │ ├── guide-general.rst │ ├── guide-overview.rst │ ├── guide-testing.rst │ ├── index.rst │ ├── ref-addresses.rst │ ├── ref-glossary.rst │ ├── registry-address-provider.rst │ ├── registry-exchanges.rst │ ├── registry-overview.rst │ ├── registry-pool-info.rst │ ├── registry-registry.rst │ └── toctree.rst ├── move_to_trash.sh ├── uniswap-contracts │ ├── glossary.md │ ├── permit2 │ │ ├── overview.md │ │ └── reference │ │ │ ├── allowance-transfer.md │ │ │ └── signature-transfer.md │ ├── universal-router │ │ ├── 01-overview.md │ │ └── 02-technical-reference.md │ ├── v1 │ │ ├── guides │ │ │ ├── 01-connect-to-uniswap.md │ │ │ ├── 02-pool-liquidity.md │ │ │ ├── 03-trade-tokens.md │ │ │ ├── 04-custom-linking.md │ │ │ ├── 05-iframe-integration.md │ │ │ └── 06-token-listing.md │ │ ├── overview.md │ │ └── reference │ │ │ ├── 01-factory.md │ │ │ ├── 02-exchange.md │ │ │ └── 03-interfaces.md │ ├── v2 │ │ ├── concepts │ │ │ ├── 01-protocol-overview │ │ │ │ ├── 01-how-uniswap-works.md │ │ │ │ ├── 02-ecosystem-participants.md │ │ │ │ ├── 03-smart-contracts.md │ │ │ │ └── 04-glossary.md │ │ │ ├── 02-core-concepts │ │ │ │ ├── 01-swaps.md │ │ │ │ ├── 02-pools.md │ │ │ │ ├── 03-flash-swaps.md │ │ │ │ └── 04-oracles.md │ │ │ └── 03-advanced-topics │ │ │ │ ├── 01-fees.md │ │ │ │ ├── 02-pricing.md │ │ │ │ ├── 03-understanding-returns.md │ │ │ │ ├── 04-security.md │ │ │ │ ├── 05-math.md │ │ │ │ └── 06-research.md │ │ ├── guides │ │ │ ├── interface-integration │ │ │ │ ├── 01-using-the-api.md │ │ │ │ ├── 02-custom-interface-linking.md │ │ │ │ └── 03-iframe-integration.mdx │ │ │ └── smart-contract-integration │ │ │ │ ├── 01-quick-start.md │ │ │ │ ├── 02-trading-from-a-smart-contract.md │ │ │ │ ├── 03-providing-liquidity.md │ │ │ │ ├── 04-building-an-oracle.md │ │ │ │ ├── 05-using-flash-swaps.md │ │ │ │ ├── 06-getting-pair-addresses.md │ │ │ │ └── 07-supporting-meta-transactions.md │ │ ├── overview.md │ │ └── reference │ │ │ ├── API │ │ │ ├── 01-overview.md │ │ │ ├── 02-entities.md │ │ │ └── 03-queries.md │ │ │ ├── Governance │ │ │ └── governance-reference.md │ │ │ └── smart-contracts │ │ │ ├── 01-factory.md │ │ │ ├── 02-pair.md │ │ │ ├── 03-pair-erc-20.md │ │ │ ├── 04-library.md │ │ │ ├── 05-router01.md │ │ │ ├── 06-router02.md │ │ │ └── 07-common-errors.md │ └── v3 │ │ ├── guides │ │ ├── flash-integrations │ │ │ ├── Inheritance-constructors.md │ │ │ ├── calling-flash.md │ │ │ ├── final-contract.md │ │ │ └── flash-callback.md │ │ ├── governance │ │ │ └── license-modifications.md │ │ ├── liquidity-mining │ │ │ └── overview.md │ │ ├── local-environment.mdx │ │ ├── providing-liquidity │ │ │ ├── collect-fees.md │ │ │ ├── decrease-liquidity.md │ │ │ ├── increase-liquidity.md │ │ │ ├── mint-a-new-position.md │ │ │ ├── setting-up-your-contract.md │ │ │ └── the-full-contract.md │ │ └── swaps │ │ │ ├── multihop-swaps.md │ │ │ └── single-swaps.md │ │ ├── overview.md │ │ └── reference │ │ ├── Deployments.md │ │ ├── core │ │ ├── UniswapV3Factory.md │ │ ├── UniswapV3Pool.md │ │ ├── UniswapV3PoolDeployer.md │ │ ├── interfaces │ │ │ ├── IERC20Minimal.md │ │ │ ├── IUniswapV3Factory.md │ │ │ ├── IUniswapV3Pool.md │ │ │ ├── IUniswapV3PoolDeployer.md │ │ │ ├── callback │ │ │ │ ├── IUniswapV3FlashCallback.md │ │ │ │ ├── IUniswapV3MintCallback.md │ │ │ │ └── IUniswapV3SwapCallback.md │ │ │ └── pool │ │ │ │ ├── IUniswapV3PoolActions.md │ │ │ │ ├── IUniswapV3PoolDerivedState.md │ │ │ │ ├── IUniswapV3PoolEvents.md │ │ │ │ ├── IUniswapV3PoolImmutables.md │ │ │ │ ├── IUniswapV3PoolOwnerActions.md │ │ │ │ └── IUniswapV3PoolState.md │ │ └── libraries │ │ │ ├── BitMath.md │ │ │ ├── FixedPoint128.md │ │ │ ├── FixedPoint96.md │ │ │ ├── FullMath.md │ │ │ ├── LiquidityMath.md │ │ │ ├── LowGasSafeMath.md │ │ │ ├── Oracle.md │ │ │ ├── Position.md │ │ │ ├── SafeCast.md │ │ │ ├── SecondsOutside.md │ │ │ ├── SqrtPriceMath.md │ │ │ ├── SwapMath.md │ │ │ ├── Tick.md │ │ │ ├── TickBitmap.md │ │ │ ├── TickMath.md │ │ │ ├── TransferHelper.md │ │ │ └── UnsafeMath.md │ │ ├── error-codes.md │ │ ├── governance │ │ └── overview.md │ │ ├── overview.md │ │ └── periphery │ │ ├── NonfungiblePositionManager.md │ │ ├── NonfungibleTokenPositionDescriptor.md │ │ ├── SwapRouter.md │ │ ├── V3Migrator.md │ │ ├── base │ │ ├── BlockTimestamp.md │ │ ├── ERC721Permit.md │ │ ├── LiquidityManagement.md │ │ ├── Multicall.md │ │ ├── PeripheryImmutableState.md │ │ ├── PeripheryPayments.md │ │ ├── PeripheryPaymentsWithFee.md │ │ ├── PoolInitializer.md │ │ └── SelfPermit.md │ │ ├── interfaces │ │ ├── IERC20Metadata.md │ │ ├── IERC721Permit.md │ │ ├── IMulticall.md │ │ ├── INonfungiblePositionManager.md │ │ ├── INonfungibleTokenPositionDescriptor.md │ │ ├── IPeripheryImmutableState.md │ │ ├── IPeripheryPayments.md │ │ ├── IPeripheryPaymentsWithFee.md │ │ ├── IPoolInitializer.md │ │ ├── IQuoter.md │ │ ├── IQuoterV2.md │ │ ├── ISelfPermit.md │ │ ├── ISwapRouter.md │ │ ├── ITickLens.md │ │ ├── IV3Migrator.md │ │ └── external │ │ │ ├── IERC1271.md │ │ │ ├── IERC20PermitAllowed.md │ │ │ └── IWETH9.md │ │ ├── lens │ │ ├── Quoter.md │ │ ├── QuoterV2.md │ │ └── TickLens.md │ │ ├── libraries │ │ ├── Base64.md │ │ ├── BytesLib.md │ │ ├── CallbackValidation.md │ │ ├── ChainId.md │ │ ├── HexStrings.md │ │ ├── LiquidityAmounts.md │ │ ├── NFTDescriptor.md │ │ ├── NFTSVG.md │ │ ├── OracleLibrary.md │ │ ├── Path.md │ │ ├── PoolAddress.md │ │ ├── PoolTicksCounter.md │ │ ├── PositionKey.md │ │ ├── TokenRatioSortOrder.md │ │ ├── TransferHelper.md │ │ └── WeightedOracleLibrary.md │ │ ├── staker │ │ ├── Design.md │ │ ├── UniswapV3Staker.md │ │ ├── interfaces │ │ │ └── IUniswapV3Staker.md │ │ └── libraries │ │ │ ├── IncentiveId.md │ │ │ ├── NFTPositionInfo.md │ │ │ └── RewardMath.md │ │ └── test │ │ ├── Base64Test.md │ │ ├── LiquidityAmountsTest.md │ │ ├── MockTimeNonfungiblePositionManager.md │ │ ├── MockTimeSwapRouter.md │ │ ├── NFTDescriptorTest.md │ │ ├── PathTest.md │ │ ├── PeripheryImmutableStateTest.md │ │ ├── PoolAddressTest.md │ │ ├── SelfPermitTest.md │ │ ├── TestCallbackValidation.md │ │ ├── TestERC20.md │ │ ├── TestERC20Metadata.md │ │ ├── TestERC20PermitAllowed.md │ │ ├── TestMulticall.md │ │ ├── TestPositionNFTOwner.md │ │ ├── TestUniswapV3Callee.md │ │ └── TickLensTest.md └── web3-py-docs │ ├── abi_types.rst │ ├── code_of_conduct.rst │ ├── constants.rst │ ├── contributing.rst │ ├── ens.rst │ ├── ens_overview.rst │ ├── ethpm.rst │ ├── examples.rst │ ├── filters.rst │ ├── gas_price.rst │ ├── index.rst │ ├── internals.rst │ ├── middleware.rst │ ├── node.rst │ ├── overview.rst │ ├── providers.rst │ ├── quickstart.rst │ ├── releases.rst │ ├── troubleshooting.rst │ ├── web3.beacon.rst │ ├── web3.contract.rst │ ├── web3.eth.account.rst │ ├── web3.eth.rst │ ├── web3.geth.rst │ ├── web3.main.rst │ ├── web3.miner.rst │ ├── web3.net.rst │ ├── web3.pm.rst │ └── web3.utils.rst ├── poetry.lock ├── pyproject.toml └── scripts ├── get_address_abi.py └── proxy_check.py /.gitignore: -------------------------------------------------------------------------------- 1 | .env 2 | __pycache__ 3 | .vscode -------------------------------------------------------------------------------- /assets/architecture.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Auto3-io/web3-copilot/42cda49b5de9357e28c46e9c96f758f8b4ad7395/assets/architecture.jpg -------------------------------------------------------------------------------- /assets/demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Auto3-io/web3-copilot/42cda49b5de9357e28c46e9c96f758f8b4ad7395/assets/demo.gif -------------------------------------------------------------------------------- /copilot/async_util.py: -------------------------------------------------------------------------------- 1 | """Async utils.""" 2 | import asyncio 3 | from typing import Any, Coroutine, List 4 | 5 | 6 | def run_async_tasks(tasks: List[Coroutine]) -> List[Any]: 7 | """Run a list of async tasks.""" 8 | 9 | async def _gather() -> List[Any]: 10 | return await asyncio.gather(*tasks) 11 | 12 | outputs: List[Any] = asyncio.run(_gather()) 13 | return outputs 14 | 15 | -------------------------------------------------------------------------------- /copilot/config.py: -------------------------------------------------------------------------------- 1 | import promptlayer 2 | import os 3 | import sys 4 | import openai as the_real_openai 5 | from dotenv import load_dotenv 6 | from langchain.chat_models import PromptLayerChatOpenAI, ChatOpenAI as RealChatOpenAI 7 | 8 | load_dotenv() 9 | 10 | user_prompt_layer = False 11 | 12 | openai = promptlayer.openai 13 | ChatOpenAI = PromptLayerChatOpenAI 14 | 15 | try: 16 | promptlayer.api_key = os.environ['PROMPTLAYER_API_KEY'] 17 | print("promptlayer is enabled") 18 | user_prompt_layer = True 19 | except KeyError: 20 | pass 21 | 22 | 23 | try: 24 | if not user_prompt_layer: 25 | ChatOpenAI = RealChatOpenAI 26 | openai = the_real_openai 27 | openai.api_key = os.environ['OPENAI_API_KEY'] 28 | except KeyError: 29 | print('[error]: `OPENAI_API_KEY` environment variable required') 30 | sys.exit(1) 31 | 32 | __all__ = ['openai', 'user_prompt_layer', 'ChatOpenAI'] 33 | -------------------------------------------------------------------------------- /copilot/data/loader.test.py: -------------------------------------------------------------------------------- 1 | from copilot.data.loader import get_erc20_address, get_contract_address, contract_df 2 | 3 | 4 | def test_erc20_get_address(): 5 | token_name = 'USDT' 6 | chain_name = 'ethereum' 7 | address = get_erc20_address(token_name, chain_name) 8 | assert address == '0xdac17f958d2ee523a2206206994597c13d831ec7' 9 | 10 | def test_contract_address(): 11 | contract_name = 'SwapRouter' 12 | address = get_contract_address('UniswapV3', 'Ethereum', contract_name) 13 | assert address == '0xE592427A0AEce92De3Edee1F18E0157C05861564' 14 | 15 | address = get_contract_address('UniswapV2', 'Ethereum', "UniswapV2Router02") 16 | 17 | def test_get_protocols(): 18 | protocols = contract_df.get_protocols('Ethereum') 19 | print(protocols) 20 | -------------------------------------------------------------------------------- /copilot/greet.py: -------------------------------------------------------------------------------- 1 | """Send greetings.""" 2 | 3 | import click 4 | from copilot.pipeline import pipeline 5 | 6 | 7 | @click.command() 8 | @click.option("--input", "-i", type=str) 9 | def run(input): 10 | pipeline(input) 11 | -------------------------------------------------------------------------------- /copilot/index.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Auto3-io/web3-copilot/42cda49b5de9357e28c46e9c96f758f8b4ad7395/copilot/index.py -------------------------------------------------------------------------------- /copilot/method_search_engine/.gitattributes: -------------------------------------------------------------------------------- 1 | index.json filter=lfs diff=lfs merge=lfs -text 2 | -------------------------------------------------------------------------------- /copilot/method_search_engine/embedding_generator.py: -------------------------------------------------------------------------------- 1 | from llama_index import GPTTreeIndex, SimpleDirectoryReader, LLMPredictor, ServiceContext, PromptHelper, SummaryPrompt, GPTSimpleVectorIndex 2 | from langchain.chat_models import PromptLayerChatOpenAI 3 | from pathlib import Path 4 | 5 | import nest_asyncio 6 | # nest_asyncio.apply() 7 | 8 | doc_dir = (Path(__file__) / '../../../docs').resolve() 9 | 10 | 11 | documents = SimpleDirectoryReader( 12 | str(doc_dir), exclude=['*.sh'], recursive=True).load_data() 13 | 14 | llm_predictor = LLMPredictor(llm=PromptLayerChatOpenAI( 15 | temperature=0, model_name="gpt-3.5-turbo", max_tokens=1024)) 16 | 17 | 18 | max_input_size = 3070 19 | num_output = 1024 20 | max_chunk_overlap = 4 21 | prompt_helper = PromptHelper(max_input_size, num_output, max_chunk_overlap) 22 | service_context = ServiceContext.from_defaults( 23 | llm_predictor=llm_predictor, prompt_helper=prompt_helper, chunk_size_limit=512) 24 | 25 | SUMMARY_PROMPT = ( 26 | "Write a summary of the following. Try to use only the " 27 | "information provided. Try to include as many key details as possible." 28 | "For method and its signature. You should keep signature with name and type at least." 29 | "And give a clear and precise guide of how to use it.\n" 30 | "\n" 31 | "\n" 32 | "{context_str}\n" 33 | "\n" 34 | "\n" 35 | 'SUMMARY:"""\n' 36 | ) 37 | 38 | # index = GPTTreeIndex.from_documents( 39 | # documents, summary_template=SummaryPrompt(SUMMARY_PROMPT), service_context=service_context, num_children=3, use_async=True) 40 | index = GPTSimpleVectorIndex.load_from_disk('./index.json') 41 | index = GPTSimpleVectorIndex.from_documents(documents, service_context=service_context) 42 | 43 | index.save_to_disk('./index.json') 44 | 45 | -------------------------------------------------------------------------------- /copilot/method_search_engine/engine.test.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | import yaml 3 | from pprint import pprint 4 | 5 | from copilot.method_search_engine.engine import search_engine 6 | 7 | import nest_asyncio 8 | nest_asyncio.apply() 9 | 10 | p = Path(__file__).with_name('steps_input.yaml') 11 | with p.open('r') as f: 12 | steps = yaml.safe_load(f.read())['steps'] 13 | 14 | outputs = search_engine([step['action'] for step in steps]) 15 | 16 | pprint(outputs) 17 | -------------------------------------------------------------------------------- /copilot/method_search_engine/index.json: -------------------------------------------------------------------------------- 1 | version https://git-lfs.github.com/spec/v1 2 | oid sha256:f8d45c7231ff519367e80623e996fe0109c91e5e5dd5a31087207a2875222e7f 3 | size 189342251 4 | -------------------------------------------------------------------------------- /copilot/method_search_engine/query_template.txt: -------------------------------------------------------------------------------- 1 | I need to find smart contract methods that can help me {{ action }}. Please show me relevant methods and usage guide for them. 2 | -------------------------------------------------------------------------------- /copilot/method_search_engine/steps_input.yaml: -------------------------------------------------------------------------------- 1 | steps: 2 | - id: 1 3 | action: "Swap 1000 USDC for ETH on Uniswap" 4 | protocol: 5 | name: "Uniswap" 6 | description: "A decentralized exchange protocol for token swaps." 7 | chain: "Ethereum" 8 | tokens: 9 | - name: "USDC" 10 | chain: "Ethereum" 11 | - name: "ETH" 12 | chain: "Ethereum" 13 | notes: "The source of USDC can be the user balance or obtained from a previous operation." 14 | - id: 2 15 | action: "Send half of the ETH to 0x123" 16 | tokens: 17 | - name: "ETH" 18 | chain: "Ethereum" 19 | notes: "The destination address can be replaced with the actual receiving address." 20 | - id: 3 21 | action: "Deposit the other half of the ETH to Aave" 22 | protocol: 23 | name: "Aave" 24 | description: "A decentralized non-custodial liquidity market protocol." 25 | chain: "Ethereum" 26 | tokens: 27 | - name: "ETH" 28 | chain: "Ethereum" 29 | - name: "aETH" 30 | chain: "Ethereum" 31 | notes: "The resulting token from the Aave deposit is aETH, which represents the deposited ETH with interest. This operation requires the user to have already approved Aave to spend their ETH on their behalf." 32 | -------------------------------------------------------------------------------- /copilot/pipeline.py: -------------------------------------------------------------------------------- 1 | import click 2 | import yaml 3 | 4 | from copilot.data.loader import get_contract_address, get_erc20_address 5 | from copilot.method_search_engine.engine import search_engine 6 | from copilot.program_generator.program import program_generator 7 | from copilot.task_interpreter.task_interpreter import task_interpreter 8 | 9 | 10 | def pipeline(input): 11 | click.echo('Strat interpreter user task: {}'.format(input)) 12 | steps_raw = task_interpreter(input) 13 | steps = yaml.safe_load(steps_raw.content)['steps'] 14 | 15 | tokens = {} 16 | tokens = { 17 | token_name: token_address 18 | for step in steps 19 | for token_name, token_address in get_tokens_from_step(step, tokens).items() 20 | } 21 | 22 | for step in steps: 23 | if not step['action']: 24 | raise Exception("No action in step: {}".format(step)) 25 | 26 | click.echo('\nStart searching methods: {}'.format( 27 | [step['action'] for step in steps])) 28 | summarized_steps = search_engine([step['action'] for step in steps]) 29 | click.echo('\nFinish searching methods') 30 | 31 | if len(steps) != len(summarized_steps): 32 | raise Exception("Step count not match") 33 | 34 | to_program_steps = [] 35 | for i in range(len(summarized_steps)): 36 | raw_step = summarized_steps[i].response 37 | print('\n Step {}:\n {}'.format(i, raw_step)) 38 | 39 | new_step = yaml.safe_load((raw_step)) 40 | new_step['action'] = steps[i]['action'] 41 | for method in new_step['methods']: 42 | for contract in method['needed_contracts']: 43 | contract['address'] = get_contract_address( 44 | contract['protocol'], contract['chain'], contract['contract']) 45 | print("Find contract address: {}:{}({}), {} \n".format( 46 | contract['protocol'], contract['contract'], contract['chain'], contract['address'])) 47 | to_program_steps.append(new_step) 48 | 49 | program = program_generator(to_program_steps, tokens) 50 | return program 51 | 52 | # TODO: save an run on vm 53 | # file_path = os.path.join('./', 'tmp_code.py') 54 | # with open(file_path, 'w') as file: 55 | # file.write(program.content) 56 | 57 | 58 | def get_tokens_from_step(step, tokens): 59 | if 'tokens' in step: 60 | return { 61 | token['name']: get_erc20_address( 62 | str(token['name']).upper(), str(token['chain']).lower() 63 | ) 64 | for token in step['tokens'] if token['name'] not in tokens 65 | } 66 | return {} 67 | -------------------------------------------------------------------------------- /copilot/pipeline.test.py: -------------------------------------------------------------------------------- 1 | from copilot.pipeline import pipeline 2 | 3 | pipeline('swap 1000 USDC for ETH') 4 | -------------------------------------------------------------------------------- /copilot/program_generator/program.py: -------------------------------------------------------------------------------- 1 | import promptlayer 2 | import os 3 | 4 | from copilot.config import ChatOpenAI 5 | from langchain.callbacks.base import CallbackManager 6 | from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler 7 | from pathlib import Path 8 | import jinja2 9 | 10 | from langchain.schema import ( 11 | HumanMessage, 12 | SystemMessage 13 | ) 14 | 15 | 16 | def program_generator(steps, tokens): 17 | p = Path(__file__).with_name('./steps_template.txt') 18 | with p.open('r') as f: 19 | user_content_template_content = f.read() 20 | 21 | user_template = jinja2.Template(user_content_template_content) 22 | output = user_template.render(steps=steps, tokens=tokens) 23 | 24 | chat_args = {'streaming': True, 'callback_manager': CallbackManager([StreamingStdOutCallbackHandler()]), 'verbose': True, 'temperature': 0} 25 | 26 | if os.getenv('PROMPTLAYER_API_KEY') is not None: 27 | chat_args['pl_tags'] = ['program_generator'] 28 | 29 | chat = ChatOpenAI(**chat_args) 30 | 31 | print("\nProgram instructions: \n") 32 | print(output) 33 | 34 | messages = [ 35 | SystemMessage( 36 | content=f'Generate a Python PROGRAM to accomplish the following on-chain operations: (Do not include any additional information besides program.)'), 37 | HumanMessage( 38 | content=output 39 | ) 40 | ] 41 | resp = chat(messages) 42 | return resp 43 | 44 | 45 | __all__ = ['program_generator'] 46 | -------------------------------------------------------------------------------- /copilot/program_generator/tests/program.py: -------------------------------------------------------------------------------- 1 | import promptlayer 2 | import os 3 | import copilot.config 4 | 5 | 6 | user_content = ''' 7 | 1. Swap 1000 USDC for ETH using Uniswap on Ethereum: 8 | - Contract address: 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D 9 | - Method: swapExactTokensForTokens 10 | - ABI: '{"inputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint256","name":"amountOutMin","type":"uint256"},{"internalType":"address[]","name":"path","type":"address[]"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapExactTokensForTokens","outputs":[{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"}' 11 | - Documentation: Swaps an exact amount of input tokens for as many output tokens as possible... 12 | - Additional check: allowance 13 | - ABI: {...} 14 | - Documentation: Returns the remaining number of tokens that spender will be allowed to spend on behalf of owner... 15 | - Additional action: approve 16 | - ABI: {...} 17 | - Documentation: Approves a specified address to spend a specified amount of tokens on the caller's behalf... 18 | 19 | 2. Send half of the acquired ETH to 0x123: 20 | - Contract address: 0xETH... 21 | - Method: transfer 22 | - ABI: {...} 23 | - Documentation: Transfers tokens from the sender's account to the specified address... 24 | 25 | 3. Deposit the rest of the ETH to Aave: 26 | - Contract address: 0x67890... 27 | - Method: deposit 28 | - ABI: '{"anonymous":false,"inputs":[{"indexed":false,"name":"_reserve","type":"address"},{"indexed":false,"name":"_user","type":"address"},{"indexed":false,"name":"_amount","type":"uint256"}],"name":"Deposit","type":"event","signature":"0x5548c837ab068cf56a2c2479df0882a4922fd203edb7517321831d95078c5f62"}' 29 | - Documentation: Deposits an asset into the protocol to start earning interest... 30 | - Additional check: allowance 31 | - ABI: {...} 32 | - Documentation: Returns the remaining number of tokens that 33 | - Additional action: approve 34 | - ABI: {...} 35 | - Documentation: Approves a specified address to spend a specified amount of tokens on the caller's behalf... 36 | 37 | Related ERC20: 38 | 1. USDC 39 | - Address: 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 40 | ''' 41 | 42 | 43 | openai.ChatCompletion.create( 44 | model="code-davinci-002", 45 | messages=[ 46 | {"role": "system", "content": "Generate a Python program to accomplish the following on-chain operations:"}, 47 | {"role": "user", "content": user_content}, 48 | ], 49 | pl_tags=["program"] 50 | ) 51 | -------------------------------------------------------------------------------- /copilot/program_generator/tests/program_combo.py: -------------------------------------------------------------------------------- 1 | import promptlayer 2 | import os 3 | from langchain.chat_models import PromptLayerChatOpenAI 4 | from langchain.callbacks.base import CallbackManager 5 | from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler 6 | from pathlib import Path 7 | 8 | from langchain.schema import ( 9 | HumanMessage, 10 | SystemMessage 11 | ) 12 | 13 | promptlayer.api_key = os.environ['PROMPT_API_KEY'] 14 | 15 | # Swap out your 'import openai' 16 | openai = promptlayer.openai 17 | openai.api_key = os.environ['OPENAI_API_KEY'] 18 | 19 | def program_generator(): 20 | p = Path(__file__).with_name('./pgt_combo.txt') 21 | with p.open('r') as f: 22 | user_content_template_content = f.read() 23 | 24 | chat = PromptLayerChatOpenAI(streaming=True, callback_manager=CallbackManager( 25 | [StreamingStdOutCallbackHandler()]), verbose=True, temperature=0, pl_tags=['program_swap_transfer']) 26 | 27 | messages = [ 28 | SystemMessage( 29 | content=f'Generate a Python program to accomplish the following on-chain operations:'), 30 | HumanMessage( 31 | content=user_content_template_content 32 | ) 33 | ] 34 | resp = chat(messages) 35 | return resp 36 | 37 | program_generator() 38 | -------------------------------------------------------------------------------- /copilot/program_generator/tests/program_swap_ETHUNI.py: -------------------------------------------------------------------------------- 1 | import promptlayer 2 | import os 3 | promptlayer.api_key = os.environ['PROMPT_API_KEY'] 4 | 5 | # Swap out your 'import openai' 6 | openai = promptlayer.openai 7 | openai.api_key = os.environ['OPENAI_API_KEY'] 8 | 9 | user_content = ''' 10 | 1. Swap 0.01 ETH for UNI using Uniswap on Ethereum: 11 | - Contract address: 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D 12 | - Method: swapETHForExactTokens 13 | - ABI: '[{"inputs":[{"internalType":"uint256","name":"amountOutMin","type":"uint256"},{"internalType":"address[]","name":"path","type":"address[]"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapExactETHForTokens","outputs":[{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"stateMutability":"payable","type":"function"}]' 14 | - Documentation: Swaps an exact amount of input tokens for as many output tokens as possible... 15 | 16 | Related ERC20: 17 | 1. UNI (0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984) 18 | 2. WETH (0xB4FBF271143F4FBf7B91A5ded31805e42b2208d6) 19 | 20 | Note: 21 | - the path from USDC to ETH is [USDC, WETH] 22 | - "nonce": w3.eth.getTransactionCount(account.address) 23 | - gas_price = w3.toWei("300", "gwei") 24 | - if token_amount needed, decimals = token_in.functions.decimals().call(), and token_amount_in_wei = int(amount * (10**decimals)) 25 | - if eth_amount needed, eth_amount_in_wei = int(amount_in * (10**18)) 26 | - use buildTransaction method to generate a transaction 27 | ''' 28 | 29 | 30 | openai.ChatCompletion.create( 31 | model="gpt-3.5-turbo", 32 | messages=[ 33 | {"role": "system", "content": "Generate a Python program to accomplish the following on-chain operations:"}, 34 | {"role": "user", "content": user_content}, 35 | ], 36 | temperature = 0, 37 | pl_tags=["program_swap_ETHUNI"] 38 | ) 39 | -------------------------------------------------------------------------------- /copilot/program_generator/tests/program_swap_USDCETH.py: -------------------------------------------------------------------------------- 1 | import promptlayer 2 | import os 3 | promptlayer.api_key = os.environ['PROMPT_API_KEY'] 4 | 5 | # Swap out your 'import openai' 6 | openai = promptlayer.openai 7 | openai.api_key = os.environ['OPENAI_API_KEY'] 8 | 9 | user_content = ''' 10 | 1. Swap 1000 USDC for ETH using Uniswap on Ethereum: 11 | - Contract address: 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D 12 | - Method: swapExactTokensForETH 13 | - ABI: '[{"inputs":[{"internalType":"uint256","name":"amountIn","type":"uint256"},{"internalType":"uint256","name":"amountOutMin","type":"uint256"},{"internalType":"address[]","name":"path","type":"address[]"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"name":"swapExactTokensForETH","outputs":[{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"stateMutability":"nonpayable","type":"function"}]' 14 | - Documentation: Swaps an exact amount of input tokens for as many output tokens as possible... 15 | - Additional check: allowance 16 | - ABI: '[{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"}]' 17 | - Documentation: Returns the remaining number of tokens that spender will be allowed to spend on behalf of owner... 18 | - Additional action: approve 19 | - ABI: '[{"constant":false,"inputs":[{"name":"guy","type":"address"},{"name":"wad","type":"uint256"}],"name":"approve","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"}]' 20 | - Documentation: Approves a specified address to spend a specified amount of tokens on the caller's behalf... 21 | 22 | Related ERC20: 23 | 1. USDC (0x65aFADD39029741B3b8f0756952C74678c9cEC93) 24 | 2. WETH (0xB4FBF271143F4FBf7B91A5ded31805e42b2208d6) 25 | 26 | Note: 27 | - the path from USDC to ETH is [USDC, WETH] 28 | - "nonce": w3.eth.getTransactionCount(account.address) 29 | - gas_price = w3.toWei("300", "gwei") 30 | - if token_amount needed, decimals = token_in.functions.decimals().call(), and token_amount_in_wei = int(amount * (10**decimals)) 31 | - if eth_amount needed, eth_amount_in_wei = int(amount_in * (10**18)) 32 | - use buildTransaction method to generate a transaction 33 | ''' 34 | 35 | 36 | openai.ChatCompletion.create( 37 | model="gpt-3.5-turbo", 38 | messages=[ 39 | {"role": "system", "content": "Generate a Python program to accomplish the following on-chain operations:"}, 40 | {"role": "user", "content": user_content}, 41 | ], 42 | temperature = 0, 43 | pl_tags=["program_swap"] 44 | ) 45 | -------------------------------------------------------------------------------- /copilot/task_interpreter/data.json: -------------------------------------------------------------------------------- 1 | { 2 | "protocols": [ 3 | { 4 | "name": "Uniswap", 5 | "description": "A decentralized exchange protocol for token swaps", 6 | "chains": [ 7 | "Ethereum", 8 | "Optimism" 9 | ] 10 | }, 11 | { 12 | "name": "Aave", 13 | "description": "A decentralized non-custodial liquidity market protocol", 14 | "chains": [ 15 | "Ethereum", 16 | "Polygon" 17 | ] 18 | } 19 | ], 20 | "tokens": [ 21 | { 22 | "type": "ERC20", 23 | "name": "USD Coin", 24 | "symbol": "USDC", 25 | "chains": [ 26 | "Ethereum", 27 | "Polygon" 28 | ] 29 | } 30 | ] 31 | } -------------------------------------------------------------------------------- /copilot/task_interpreter/index.py: -------------------------------------------------------------------------------- 1 | from .task_interpreter import task_interpreter 2 | 3 | __all__ = ["task_interpreter"] -------------------------------------------------------------------------------- /copilot/task_interpreter/interpreter-input-template.txt: -------------------------------------------------------------------------------- 1 | Protocols you can access: 2 | {% for protocol in protocols -%} 3 | - {{ protocol.name }} ({{ ', '.join(protocol.chains) }}): {{ protocol.description }} 4 | {% endfor %} 5 | 6 | You must output a pure YAML and the schema must be: 7 | - steps: list 8 | - id 9 | - action 10 | - protocol (if needed) 11 | - name 12 | - description 13 | - chain (where the action happend) 14 | - tokens: list 15 | - name 16 | - chain 17 | - notes 18 | 19 | Output example 1 (You must output the following format.): 20 | steps: 21 | - id: 1 22 | action: "A Action to do something" 23 | protocol: 24 | name: "XXXX" 25 | description: "A protocol introduction for this action." 26 | chain: "Ethereum" 27 | tokens: 28 | - name: "USDC" 29 | chain: "Ethereum" 30 | - name: "ETH" 31 | chain: "Ethereum" 32 | notes: "Notes about where the tokens from." 33 | 34 | Output example 2 for task `swap 200 USDC for ETH`: 35 | steps: 36 | - id: 1 37 | action: "Swap 200 USDC for ETH" 38 | protocol: 39 | name: "Uniswap" 40 | description: "..." 41 | chain: "Ethereum" 42 | tokens: 43 | - name: "USDC" 44 | chain: "Ethereum" 45 | - name: "ETH" 46 | chain: "Ethereum" 47 | notes: "The source of USDC can be the user balance" 48 | 49 | OUTPUT: -------------------------------------------------------------------------------- /copilot/task_interpreter/task_interpreter.py: -------------------------------------------------------------------------------- 1 | import os 2 | from pathlib import Path 3 | 4 | import jinja2 5 | from langchain.callbacks.base import CallbackManager 6 | from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler 7 | from langchain.schema import HumanMessage, SystemMessage 8 | 9 | from copilot.config import ChatOpenAI 10 | from copilot.data.loader import get_protocols 11 | 12 | protocols = get_protocols() 13 | 14 | 15 | def task_interpreter(user_requirement: str): 16 | p = Path(__file__).with_name('./interpreter-input-template.txt') 17 | with p.open('r') as f: 18 | user_content_template_content = f.read() 19 | 20 | user_template = jinja2.Template(user_content_template_content) 21 | output = user_template.render(protocols=protocols) 22 | 23 | chat_args = {'streaming': True, 'callback_manager': CallbackManager([StreamingStdOutCallbackHandler()]), 'verbose': True, 'temperature': 0} 24 | 25 | if os.getenv('PROMPTLAYER_API_KEY') is not None: 26 | chat_args['pl_tags'] = ['task_interpreter'] 27 | 28 | chat = ChatOpenAI(**chat_args) 29 | 30 | system_instruction = ( 31 | f"Please provide a step-by-step plan that satisfies the following user requirement: {user_requirement}" 32 | "Consider the provided protocol descriptions and choose the most suitable protocols and subcontracts to use in each step. " 33 | "Include the necessary ERC20/ERC721 token information if needed. " 34 | "The source of assets for each step of operation should also be clearly explained, " 35 | "such as the result from a specific step or from user\'s balance.\n\n" 36 | "Requirements:\n" 37 | " 1. As few steps as possible. \n" 38 | " 2. There is no need to list delegate or approve authorization as a separate step;" 39 | " simply add requirement of `delegate` or `approve` operation if needed to the notes." 40 | " Specify whether it is necessary to check beforehand, such as the need to verify" 41 | " the allowance before using many tokens. For example, a swap only need output one step." 42 | ) 43 | messages = [ 44 | SystemMessage( 45 | content=system_instruction), 46 | HumanMessage( 47 | content=output 48 | ) 49 | ] 50 | resp = chat(messages) 51 | 52 | return resp 53 | -------------------------------------------------------------------------------- /copilot/task_interpreter/task_interpreter.test.py: -------------------------------------------------------------------------------- 1 | from copilot.task_interpreter.task_interpreter import task_interpreter 2 | 3 | user_requirement = 'Swap 1000 USDC for ETH in Ethereum, then send half to 0x123, and deposit the rest to Aave' 4 | 5 | task_interpreter(user_requirement) -------------------------------------------------------------------------------- /docs/aave-docs-v2/README.md: -------------------------------------------------------------------------------- 1 | # Introduction 2 | 3 | {% hint style="info" %} 4 | See the major changes between [Aave v1 and v2 here](change-from-v1-to-v2.md). 5 | {% endhint %} 6 | 7 | ## What is Aave? 8 | 9 | Aave is a decentralised non-custodial liquidity protocol where users can participate as depositors or borrowers. Depositors provide liquidity to the market to earn a passive income, while borrowers are able to borrow in an over-collateralised (perpetually) or under-collateralised (one-block liquidity) fashion. 10 | 11 | The following documentation describes the fundamentals of the protocol and how to interact with it. Please join the #development room in the [Aave community Discord server](https://discord.gg/fVaDMqT); our team and members of the community look forward to helping you build on top of Aave. 12 | 13 | ![](<.gitbook/assets/Artboard – 7@2x.jpg>) 14 | 15 | The protocol is implemented as a set of **smart contracts** on top of the Ethereum blockchain. Smart contracts guarantee safety and do not require a middleman. 16 | 17 | {% hint style="info" %} 18 | A detailed and technical description can be found in the [whitepaper](https://github.com/aave/protocol-v2/blob/master/aave-v2-whitepaper.pdf). 19 | {% endhint %} 20 | -------------------------------------------------------------------------------- /docs/aave-docs-v2/deployed-contracts/permission-ed-markets.md: -------------------------------------------------------------------------------- 1 | # Permission-ed Markets 2 | 3 | For permission-ed markets' deployed contract details refer [Aave Permission-ed Markets Docs](https://aave-arc.gitbook.io/docs/deployed-contracts) 4 | -------------------------------------------------------------------------------- /docs/aave-docs-v2/getting-started/gas-limits.md: -------------------------------------------------------------------------------- 1 | # Gas Limits 2 | 3 | The following table shows the recommended gas limit to set when calling the functions. Note that this is the _safe_ gas limit to set to ensure that the transaction completes, however the transaction may use significantly less than these gas limits. 4 | 5 | | Function | Recommended Gas Limit | 6 | | ------------------------------------------------------------------------------------------------ | --------------------- | 7 | | [setUserUseReserveAsCollateral](../the-core-protocol/lendingpool/#setuserusereserveascollateral) | 90000 | 8 | | [swapBorrowRateMode](../the-core-protocol/lendingpool/#swapborrowratemode) | 600000 | 9 | | [deposit](../the-core-protocol/lendingpool/#deposit) | 400000 | 10 | | [withdraw](../the-core-protocol/lendingpool/#withdraw) | 500000 | 11 | | [borrow](../the-core-protocol/lendingpool/#borrow) | 550000 | 12 | | [repay](../the-core-protocol/lendingpool/#repay) | 400000 | 13 | | [stake](../protocol-governance/staking-aave.md#stake) | 600000 | 14 | | [claimRewards](../protocol-governance/staking-aave.md#claimrewards) | 450000 | 15 | | [redeem](../protocol-governance/staking-aave.md#redeem) | 300000 | 16 | | [cooldown](../protocol-governance/staking-aave.md#cooldown) | 100000 | 17 | -------------------------------------------------------------------------------- /docs/aave-docs-v2/guides/ampl-asset-listing.md: -------------------------------------------------------------------------------- 1 | # AMPL on Aave Caveats 2 | 3 | The AMPL token supply automatically rebases in response to the demand. When price is high, wallet balances increase. When price is low, wallet balances decrease. These rebases effects the user's AMPL balance in the Aave markets. 4 | 5 | {% hint style="info" %} 6 | On every rebase the available liquidity of the pool changes but the borrowed liquidity remains same. 7 | {% endhint %} 8 | 9 | ## Depositing AMPL 10 | 11 | On depositing `AMPL` in Aave [LendingPool ](../the-core-protocol/lendingpool/)the user gets `aAMPL`. The available liquidity balance of the pool (ie. `suppliedLiquidity - borrowedLiquidity`) changes when the underlying asset gets rebased. Hence, the aToken balance of the depositors is affected on the AMPL rebase depending on the utilisation rate of the pool. 12 | 13 | ## Borrowing AMPL 14 | 15 | AMPL borrow amount remains fixed ie. debt token balance does not change on underlying asset rebase. Hence, the debt denominated in AMPL remains fixed, while the value of that debt expressed in terms of purchasing power tends toward price-stability. 16 | -------------------------------------------------------------------------------- /docs/aave-docs-v2/protocol-governance/governance/propose-your-token-as-new-aave-asset.md: -------------------------------------------------------------------------------- 1 | # Creating an asset listing proposal 2 | 3 | The following guide will walk you through the process of adding a new token as a whitelisted currency to be deposited/borrowed in the Aave protocol. 4 | 5 | ## 1. Complete the the off-chain process 6 | 7 | Details of the off-chain process, including completing the ARC and starting the AIP, can be found in the [Governance Docs](https://docs.aave.com/governance/guides/new-asset-listing). 8 | 9 | ## 2. Prepare for the on-chain process 10 | 11 | ### 1. Create a Pull Request with your token parameters 12 | 13 | * fork from the [protocol-v2 repository@aave-v2-asset-listing](https://github.com/aave/protocol-v2/tree/aave-v2-asset-listing) 14 | * add your token addresses to `markets/aave/index.ts` 15 | * create your reserve parameters inside `markets/aave/reservesConfigs.ts` 16 | * update the types to include your token in `/helpers/types` 17 | * add the current price in the `MOCK_CHAINLINK_AGGREGATORS_PRICES` object in `markets/aave/commons.ts` 18 | * create a PR with your changes 19 | 20 | An example PR can be found [here](https://github.com/aave/protocol-v2/pull/11/commits/ba5d325ccb0316253720ac9afd972d436491c55c) 21 | 22 | ### 2. Run the asset deployment script 23 | 24 | From the [protocol-v2 repository](https://github.com/aave/protocol-v2), 25 | 26 | `$ npm install` 27 | 28 | `$ SYMBOL="Your Symbol" npm run external:deploy-assets-kovan` to deploy on kovan 29 | 30 | `$ SYMBOL="Your Symbol" npm run external:deploy-assets-main` to deploy on mainnet 31 | 32 | This will deploy the following contracts and display the addresses: 33 | 34 | * AToken 35 | * variableDebt 36 | * stableDebt 37 | * InterestRateStrategy 38 | 39 | You will need them for the last step. 40 | 41 | ## 3. Make a proposal to the Aave Governance to initialize your assets 42 | 43 | * Get your AIP IPFS hash [here](https://github.com/aave/aip/blob/master/content/ipfs-aips/all-aips.json) 44 | 45 | Deploy the on-chain proposal following the instruction from the [asset listing repository](https://github.com/aave/aave-asset-listing) 46 | 47 | ## 4. Follow up 48 | 49 | You will need to connect with Aave Genesis team, to add your token price oracle as a source. 50 | 51 | -------------------------------------------------------------------------------- /docs/aave-docs-v2/the-core-protocol/addresses-provider-registry/ilendingpooladdressesproviderregistry.md: -------------------------------------------------------------------------------- 1 | # ILendingPoolAddressesProviderRegistry 2 | 3 | Also available on [Github](https://github.com/aave/protocol-v2/blob/ice/mainnet-deployment-03-12-2020/contracts/interfaces/ILendingPoolAddressesProviderRegistry.sol). 4 | 5 | {% tabs %} 6 | {% tab title="ILendingPoolAddressesProviderRegistry.sol" %} 7 | ```javascript 8 | // SPDX-License-Identifier: agpl-3.0 9 | pragma solidity 0.6.12; 10 | 11 | /** 12 | * @title LendingPoolAddressesProviderRegistry contract 13 | * @dev Main registry of LendingPoolAddressesProvider of multiple Aave protocol's markets 14 | * - Used for indexing purposes of Aave protocol's markets 15 | * - The id assigned to a LendingPoolAddressesProvider refers to the market it is connected with, 16 | * for example with `0` for the Aave main market and `1` for the next created 17 | * @author Aave 18 | **/ 19 | interface ILendingPoolAddressesProviderRegistry { 20 | event AddressesProviderRegistered(address indexed newAddress); 21 | event AddressesProviderUnregistered(address indexed newAddress); 22 | 23 | function getAddressesProvidersList() external view returns (address[] memory); 24 | 25 | function getAddressesProviderIdByAddress(address addressesProvider) 26 | external 27 | view 28 | returns (uint256); 29 | 30 | function registerAddressesProvider(address provider, uint256 id) external; 31 | 32 | function unregisterAddressesProvider(address provider) external; 33 | } 34 | 35 | ``` 36 | {% endtab %} 37 | {% endtabs %} 38 | -------------------------------------------------------------------------------- /docs/aave-docs-v2/the-core-protocol/addresses-provider/ilendingpooladdressesprovider.md: -------------------------------------------------------------------------------- 1 | # ILendingPoolAddressesProvider 2 | 3 | Also available on [Github](https://github.com/aave/protocol-v2/blob/ice/mainnet-deployment-03-12-2020/contracts/interfaces/ILendingPoolAddressesProvider.sol). 4 | 5 | {% tabs %} 6 | {% tab title="ILendingPoolAddressesProvider.sol" %} 7 | ```javascript 8 | // SPDX-License-Identifier: agpl-3.0 9 | pragma solidity 0.6.12; 10 | 11 | /** 12 | * @title LendingPoolAddressesProvider contract 13 | * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles 14 | * - Acting also as factory of proxies and admin of those, so with right to change its implementations 15 | * - Owned by the Aave Governance 16 | * @author Aave 17 | **/ 18 | interface ILendingPoolAddressesProvider { 19 | event MarketIdSet(string newMarketId); 20 | event LendingPoolUpdated(address indexed newAddress); 21 | event ConfigurationAdminUpdated(address indexed newAddress); 22 | event EmergencyAdminUpdated(address indexed newAddress); 23 | event LendingPoolConfiguratorUpdated(address indexed newAddress); 24 | event LendingPoolCollateralManagerUpdated(address indexed newAddress); 25 | event PriceOracleUpdated(address indexed newAddress); 26 | event LendingRateOracleUpdated(address indexed newAddress); 27 | event ProxyCreated(bytes32 id, address indexed newAddress); 28 | event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy); 29 | 30 | function getMarketId() external view returns (string memory); 31 | 32 | function setMarketId(string calldata marketId) external; 33 | 34 | function setAddress(bytes32 id, address newAddress) external; 35 | 36 | function setAddressAsProxy(bytes32 id, address impl) external; 37 | 38 | function getAddress(bytes32 id) external view returns (address); 39 | 40 | function getLendingPool() external view returns (address); 41 | 42 | function setLendingPoolImpl(address pool) external; 43 | 44 | function getLendingPoolConfigurator() external view returns (address); 45 | 46 | function setLendingPoolConfiguratorImpl(address configurator) external; 47 | 48 | function getLendingPoolCollateralManager() external view returns (address); 49 | 50 | function setLendingPoolCollateralManager(address manager) external; 51 | 52 | function getPoolAdmin() external view returns (address); 53 | 54 | function setPoolAdmin(address admin) external; 55 | 56 | function getEmergencyAdmin() external view returns (address); 57 | 58 | function setEmergencyAdmin(address admin) external; 59 | 60 | function getPriceOracle() external view returns (address); 61 | 62 | function setPriceOracle(address priceOracle) external; 63 | 64 | function getLendingRateOracle() external view returns (address); 65 | 66 | function setLendingRateOracle(address lendingRateOracle) external; 67 | } 68 | 69 | ``` 70 | {% endtab %} 71 | {% endtabs %} 72 | 73 | -------------------------------------------------------------------------------- /docs/aave-docs-v2/the-core-protocol/protocol-data-provider/iprotocoldataprovider.md: -------------------------------------------------------------------------------- 1 | # IProtocolDataProvider 2 | 3 | {% tabs %} 4 | {% tab title="IProtocolDataProvider" %} 5 | ```javascript 6 | // SPDX-License-Identifier: agpl-3.0 7 | pragma solidity 0.6.12; 8 | pragma experimental ABIEncoderV2; 9 | 10 | import {ILendingPoolAddressesProvider} from './ILendingPoolAddressesProvider.sol'; 11 | 12 | interface IProtocolDataProvider { 13 | struct TokenData { 14 | string symbol; 15 | address tokenAddress; 16 | } 17 | 18 | function ADDRESSES_PROVIDER() external view returns (ILendingPoolAddressesProvider); 19 | function getAllReservesTokens() external view returns (TokenData[] memory); 20 | function getAllATokens() external view returns (TokenData[] memory); 21 | function getReserveConfigurationData(address asset) external view returns (uint256 decimals, uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, uint256 reserveFactor, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive, bool isFrozen); 22 | function getReserveData(address asset) external view returns (uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp); 23 | function getUserReserveData(address asset, address user) external view returns (uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled); 24 | function getReserveTokensAddresses(address asset) external view returns (address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress); 25 | } 26 | ``` 27 | {% endtab %} 28 | {% endtabs %} 29 | -------------------------------------------------------------------------------- /docs/aave-docs-v2/the-core-protocol/weth-gateway/iwethgateway.md: -------------------------------------------------------------------------------- 1 | # IWETHGateway 2 | 3 | Also available on [Github](https://github.com/aave/protocol-v2/blob/master/contracts/misc/interfaces/IWETHGateway.sol). 4 | 5 | {% tabs %} 6 | {% tab title="IWETHGateway.sol" %} 7 | ```javascript 8 | 9 | // SPDX-License-Identifier: agpl-3.0 10 | pragma solidity 0.6.12; 11 | 12 | interface IWETHGateway { 13 | function depositETH( 14 | address lendingPool, 15 | address onBehalfOf, 16 | uint16 referralCode 17 | ) external payable; 18 | 19 | function withdrawETH( 20 | address lendingPool, 21 | uint256 amount, 22 | address onBehalfOf 23 | ) external; 24 | 25 | function repayETH( 26 | address lendingPool, 27 | uint256 amount, 28 | uint256 rateMode, 29 | address onBehalfOf 30 | ) external payable; 31 | 32 | function borrowETH( 33 | address lendingPool, 34 | uint256 amount, 35 | uint256 interesRateMode, 36 | uint16 referralCode 37 | ) external; 38 | 39 | } 40 | 41 | ``` 42 | {% endtab %} 43 | {% endtabs %} 44 | -------------------------------------------------------------------------------- /docs/aave-docs-v3/deployed-contracts/deployed-contracts.md: -------------------------------------------------------------------------------- 1 | # Deployed Contracts 2 | 3 |
4 | 5 | Aave V1 6 | 7 | * [Aave V1 Market](https://docs.aave.com/developers/v/1.0/deployed-contracts/deployed-contract-instances) (ETH mainnet, ETH Ropsten testnet, ETH Kovan testnet) 8 | * [Uniswap V1 Market](https://docs.aave.com/developers/v/1.0/deployed-contracts/uniswap-market) (ETH mainnet, ETH Ropsten testmet) 9 | 10 |
11 | 12 |
13 | 14 | Aave V2 15 | 16 | * [Aave V2 Market](https://docs.aave.com/developers/v/2.0/deployed-contracts/deployed-contracts) (ETH mainnet, ETH Kovan testnet) 17 | * [Aave V2 Polygon Market](https://docs.aave.com/developers/v/2.0/deployed-contracts/matic-polygon-market) (Polygon, Mumbai testnet) 18 | * [Aave V2 Avalanche Market](https://docs.aave.com/developers/v/2.0/deployed-contracts/avalanche-market) (Avalanche mainnet, Fuji testnet) 19 | * [Aave V2 AMM Market](https://docs.aave.com/developers/v/2.0/deployed-contracts/amm-market) (ETH mainnet, ETH Kovan testnet) 20 | * Permissioned Markets 21 | * [Aave ARC Market](https://aave-arc.gitbook.io/docs/deployed-contracts/arc) (ETH mainnet) 22 | * [Aave RWA Market](https://aave-arc.gitbook.io/docs/deployed-contracts/rwa) (ETH mainnet) 23 | 24 |
25 | 26 |
27 | 28 | Aave V3 29 | 30 | * [Aave V3 Testnet Markets](v3-testnet-addresses.md) (ETH Görli, Optimism Kovan, Optimism Görli, Arbitrum Rinkeby, Arbitrum Görli, Polygon Mumbai, Avalanche Fuji, Fantom Testnet, Harmony Testnet) 31 | * [Aave V3 Mainnet Markets](https://docs.aave.com/developers/deployed-contracts/v3-mainnet) (Optimism, Arbitrum, Polygon, Avalanche, Fantom, Harmony) 32 | 33 |
34 | 35 |
36 | 37 | Other 38 | 39 | * [Governance](https://docs.aave.com/developers/v/2.0/protocol-governance/governance#deployed-contracts) 40 | * [Staking](https://docs.aave.com/developers/v/2.0/protocol-governance/staking-aave) 41 | 42 |
43 | -------------------------------------------------------------------------------- /docs/aave-docs-v3/deployed-contracts/security-and-audits.md: -------------------------------------------------------------------------------- 1 | # Security & Audits 2 | 3 | Aave has been implemented with security as priority. The system has been designed to be safe and secure, and we have spent all the necessary resources in order to ensure that the protocol matches the highest security standards. 4 | 5 | Below are the links to all audit reports and formal verification for Aave V3 6 | 7 | ## Audit Round 1 8 | 9 | | Auditor | Date | Report | 10 | | ------------- | ---------- | -------------------------------------------------------------------------------------------------------------------- | 11 | | ABDK | 27-01-2022 | [ABDK\_AaveV3](https://github.com/aave/aave-v3-core/blob/master/audits/27-01-2022\_ABDK\_AaveV3.pdf) | 12 | | OpenZeppelin | 01-11-2021 | [OpenZeppelin\_AaveV3](https://github.com/aave/aave-v3-core/blob/master/audits/01-11-2021\_OpenZeppelin\_AaveV3.pdf) | 13 | | Trail of Bits | 07-01-2022 | [TrailOfBits\_AaveV3](https://github.com/aave/aave-v3-core/blob/master/audits/07-01-2022\_TrailOfBits\_AaveV3.pdf) | 14 | | Peckshield | 14-01-2022 | [PeckShield\_AaveV3](https://github.com/aave/aave-v3-core/blob/master/audits/07-01-2022\_TrailOfBits\_AaveV3.pdf) | 15 | 16 | 17 | 18 | ## Audit Round 2 19 | 20 | | Auditor | Date | Report | 21 | | ---------- | ---------- | ---------------------------------------------------------------------------------------------------------------- | 22 | | SigmaPrime | 27-01-2022 | [SigmaPrime\_AaveV3](https://github.com/aave/aave-v3-core/blob/master/audits/27-01-2022\_SigmaPrime\_AaveV3.pdf) | 23 | 24 | 25 | 26 | ## Formal Verification 27 | 28 | Formal verification by [Certora](https://github.com/aave/aave-v3-core/blob/master/Certora/certora/Verification\_Report.pdf) 29 | -------------------------------------------------------------------------------- /docs/aave-docs-v3/deployed-contracts/v3-mainnet/README.md: -------------------------------------------------------------------------------- 1 | --- 2 | description: Addresses 3 | --- 4 | 5 | # V3 Mainnet 6 | 7 | {% content-ref url="optimism.md" %} 8 | [optimism.md](optimism.md) 9 | {% endcontent-ref %} 10 | 11 | {% content-ref url="arbitrum.md" %} 12 | [arbitrum.md](arbitrum.md) 13 | {% endcontent-ref %} 14 | 15 | {% content-ref url="harmony.md" %} 16 | [harmony.md](harmony.md) 17 | {% endcontent-ref %} 18 | 19 | {% content-ref url="polygon.md" %} 20 | [polygon.md](polygon.md) 21 | {% endcontent-ref %} 22 | 23 | {% content-ref url="fantom.md" %} 24 | [fantom.md](fantom.md) 25 | {% endcontent-ref %} 26 | 27 | {% content-ref url="avalanche.md" %} 28 | [avalanche.md](avalanche.md) 29 | {% endcontent-ref %} 30 | -------------------------------------------------------------------------------- /docs/aave-docs-v3/getting-started/l2-optimization/README.md: -------------------------------------------------------------------------------- 1 | # L2 Optimization 2 | 3 | The main transaction cost on L2 comes from calldata. To minimize this cost, Aave V3 uses slightly different L2 Contracts, on Arbitrum and Optimism, that compress the info passed to Pool methods. 4 | 5 | Below are the contracts introduced for L2 optimization: 6 | 7 | * ****[**L2Pool**](l2pool.md): Contract for L2 optimized user facing methods that takes byte encoded input arguments. 8 | * **CalldataLogic**: Library contract used to decode the byte32 arguments passed to the L2Pool. 9 | * ****[**L2Encoder**](l2encoder.md): Helper contract which has view methods to encode data to be passed to L2Pool. 10 | 11 | {% hint style="info" %} 12 | Pool methods not exposed in L2Pool.sol (such as flashLoan, setUserEMode etc.) are same on L2 as on other versions of protocol. Refer [Pool](../../core-contracts/pool.md) docs for rest of the methods. 13 | {% endhint %} 14 | -------------------------------------------------------------------------------- /docs/aave-docs-v3/guides/credit-delegation.md: -------------------------------------------------------------------------------- 1 | # Credit Delegation 2 | 3 | Credit delegation allows a depositor to deposit funds in the protocol to earn interest, and delegate borrowing power (i.e. their credit) to other users. The enforcement of the loan and its terms are agreed upon between the depositor and borrowers, which can be either off-chain via legal agreements or on-chain via smart contracts. 4 | 5 | This enables: 6 | 7 | * The supplier (aka delegator) to earn extra yield on top of the yield they already earn from the protocol, 8 | * The borrowers (aka delegatees) to access an uncollateralized loan. 9 | 10 | {% hint style="warning" %} 11 | Borrow by _delegatee_ must be consistent with _delegator_ [eMode](../whats-new/efficiency-mode-emode.md) category. \ 12 | For eg. if a delegator eMode category is `STABLECOINS`, then 13 | 14 | * delegator can only borrow `STABLECOINS` eMode category asset. 15 | * in case _delegator_ approve credit to _delegatee_ for non `STABLECOINS`category (for eg. weth), then borrow would revert. 16 | {% endhint %} 17 | 18 | {% hint style="danger" %} 19 | The _delegatee_ cannot abuse credit approval to liquidate _delegator_ i.e. if the borrow puts _delegator's_ position in HF < `HEALTH_FACTOR_LIQUIDATION_THRESHOLD`, then borrow will fail. 20 | {% endhint %} 21 | 22 | ## Approving the delegation 23 | 24 | The [`approveDelegation()`](../tokens/debttoken.md#approvedelegation) or [`delegationWithSig()`](../tokens/debttoken.md#delegationwithsig) must be called by the supplier (delegator), approving the borrower (delegatee) a certain amount. 25 | 26 | This is done for each debt token that needs to be delegated. 27 | 28 | {% hint style="info" %} 29 | The delegator does not need to already have supplied funds in the protocol to `approveDelegation()`. However, **before** the delegatee executes `borrow()`, there must be sufficient collateral supplied by delegator in the protocol. 30 | {% endhint %} 31 | 32 | ## Borrowing the credit 33 | 34 | The borrower (delegatee) calls the [`borrow()`](broken-reference) method on the `Pool`, using the supplier's (delegator's) address in final parameter `onBehalfOf`. 35 | 36 | The borrower's available credit is reduced by the borrowed amount. 37 | 38 | ## Repaying the credit 39 | 40 | Anyone can repay the debt _OnBehalf_ of the user, by calling one of the methods - [repay()](../core-contracts/pool.md#repay) or [repayWithPermit()](../core-contracts/pool.md#repaywithpermit). The supplier (aka creditor) can also use [repayWithATokens()](../core-contracts/pool.md#repaywithatokens) method to repay debt with their _aTokens_ of the underlying debt asset in the same pool. 41 | -------------------------------------------------------------------------------- /docs/aave-docs-v3/guides/governance-guide/parametertuning.md: -------------------------------------------------------------------------------- 1 | # Parameter Tuning 2 | 3 | The Aave Pool in V3 has a variety of parameters which can be adjusted: 4 | 5 | * Asset Parameters 6 | * Bridge Parameters 7 | 8 | This guide details the process of executing a proposal for parameter adjustments: 9 | 10 | * [ARC](https://www.notion.so/Asset-Listing-0ef43bf40ac845b7b94b66dfa4c4b3d6) 11 | * [AIP](https://www.notion.so/Asset-Listing-0ef43bf40ac845b7b94b66dfa4c4b3d6) 12 | * [Creating the proposal](https://www.notion.so/Asset-Listing-0ef43bf40ac845b7b94b66dfa4c4b3d6) 13 | 14 | ## ARC 15 | 16 | The ARC (Aave Request for Comment) is the first step in the proposal process. This is where the idea is proposed and the community can discuss. All ARCs should follow these standard [requirements](https://docs.aave.com/governance/arcs). In addition, parameter adjustments should include [asset risk analysis](https://docs.aave.com/risk/asset-risk/introduction) and rationale for changes. Here is a template which you can reference: 17 | 18 | * [Sample ARC from Gauntlet](https://governance.aave.com/t/arc-risk-parameter-updates-2022-01-14/6942) 19 | 20 | ## AIP 21 | 22 | The AIP is a document containing the proposal details which is uploaded to IPFS. The hash of this documented is passed as a parameter when the on-chain proposal is submitted. To create an AIP for a new asset listing follow the steps from the AIP [repo](https://aave.github.io/aip/). 23 | 24 | Once the AIP has been reviewed and merged to generate an ipfs hash, and the payload has been created, the proposal can now be submitted on-chain. 25 | -------------------------------------------------------------------------------- /docs/aave-docs-v3/guides/governance-guide/permissions.md: -------------------------------------------------------------------------------- 1 | # Permissions 2 | 3 | The `ACLManager` (Asset Control List Manager) contract manages the permissions of an Aave market. The Aave Governance serves as the `ROLE_ADMIN` and can approve any of the defined roles: `RISK_ADMIN`, `POOL_ADMIN`, `ASSET_LISTING_ADMIN`, `BRIDGE`, `FLASH_BORROWER`. 4 | 5 | More details on roles can be found [here](../../core-contracts/aclmanager.md/#roles). 6 | 7 | This guide details the steps for enabling or disabling permissions on the `ACLManager`: 8 | 9 | - [ARC]() 10 | - [AIP]() 11 | - [Creating the proposal]() 12 | 13 | ## ARC 14 | 15 | The ARC (Aave Request for Comment) is the first step in the proposal process. This is where the idea is proposed, and the community can discuss the proposal. All ARCs should follow these standard [requirements](https://docs.aave.com/governance/arcs). Permissions proposals should provide extensive background on the qualifications and reputability of the requesting entity. 16 | 17 | ## AIP 18 | 19 | The AIP is a document containing the proposal details which is uploaded to IPFS. The hash of this documented is passed as a parameter when the on-chain proposal is submitted. To create an AIP for adjusting address permissions, follow the steps from the AIP [repo](https://aave.github.io/aip/). 20 | 21 | Once the AIP has been reviewed and merged to generate an ipfs hash, and the payload has been created, the proposal can now be submitted on-chain. -------------------------------------------------------------------------------- /docs/aave-docs-v3/guides/governance-guide/rewards.md: -------------------------------------------------------------------------------- 1 | # Rewards 2 | 3 | In Aave V3, the rewards system has been updated. Now aToken, variableDebtToken and stableDebtToken has an attached array which can accumulate any number of rewards. Each Aave market contains a [RewardsController](../../periphery-contracts/rewardscontroller.md) contract which registers the reward emissions for each aToken and debtToken. 4 | 5 | This guide details the steps for registering a new reward on the `RewardsController`. 6 | 7 | - [ARC] 8 | - [AIP] 9 | - [Creating Proposal] 10 | - [Add to Aave Ui] 11 | 12 | ## ARC 13 | 14 | The ARC (Aave Request for Comment) is the first step in the proposal process. This is where the idea is proposed, and the community can discuss the proposal. All ARCs should follow these standard [requirements](https://docs.aave.com/governance/arcs). In addition, new incentive proposals should specify: 15 | 16 | - Assets receiving rewards 17 | - Duration of rewards program 18 | - Total emission amount 19 | 20 | ## AIP 21 | 22 | The AIP is a document containing the proposal details which is uploaded to IPFS. The hash of this documented is passed as a parameter when the on-chain proposal is submitted. To create an AIP for a reward emission, follow the steps from the AIP [repo](https://aave.github.io/aip/). 23 | 24 | Sample AIPs: 25 | 26 | - https://github.com/aave/aip/pull/93 27 | 28 | Once the AIP has been reviewed and merged to generate an ipfs hash, and the payload has been created, the proposal can now be submitted on-chain. 29 | 30 | ## Create Proposal 31 | `EMISSION_ADMIN` set by owner of the EmissionManager contract can configure rewards by calling `configureAssets`. 32 | 33 | ## Add To Aave Ui 34 | 35 | In order for your reward token name and symbol to appear on the Aave frontend, you will need to add your asset to the [Aave Interface repo](https://github.com/aave/interface/blob/main/CONTRIBUTING.md#token-addition). -------------------------------------------------------------------------------- /docs/aave-docs-v3/tokens/delegationawareatoken.md: -------------------------------------------------------------------------------- 1 | # DelegationAwareAToken 2 | 3 | The special type of aToken that are minted and burned upon supply and withdraw of assets that has voting power associated _(which can be delegated)_ with them. These _aTokens_ are enabled to delegate voting power of the underlying asset to a different address. 4 | 5 | _DelegationAwareAToken_ enables/implements all the methods available for aTokens with additional [`delegateUnderlyingTo`](delegationawareatoken.md#delegateunderlyingto) method. 6 | 7 | Refer [_aToken_](atoken.md) docs for full list of contract api 8 | 9 | ### delegateUnderlyingTo 10 | 11 | `function delegateUnderlyingTo(address delegatee)` 12 | 13 | Delegates voting power of the underlying asset to a `delegatee` address. 14 | 15 | {% hint style="danger" %} 16 | This method can only be called by `POOL_ADMIN.` 17 | {% endhint %} 18 | -------------------------------------------------------------------------------- /docs/aave-docs-v3/whats-new/efficiency-mode-emode.md: -------------------------------------------------------------------------------- 1 | # Efficiency Mode (eMode) 2 | 3 | ## Efficiency Mode (eMode) 4 | 5 | The High Efficiency mode feature (or "eMode") is designed to maximise capital efficiency when collateral and borrowed assets are correlated in price. 6 | 7 | The `RISK_ADMINS` and `POOL_ADMIN`, set by Aave Governance, can configure a maximum of 255 eMode categories, with each `EModeCategory` having following _risk management parameters_: 8 | 9 | * LTV (Loan to value) 10 | * Liquidation threshold 11 | * Liquidation bonus 12 | * A custom price oracle (optional) 13 | 14 | {% hint style="info" %} 15 | 💡 Category 0 is reserved as the default non-eMode category. All the assets listed on Aave V3, by default have category 0 (which indicates the standard operational mode). 16 | {% endhint %} 17 | 18 | All Assets listed on Aave V3 can be set to any of the pre-configured `eModeCategory` by the `RISK_ADMINS` or `POOL_ADMIN`. 19 | 20 | {% hint style="info" %} 21 | The correct categorisation is not enforced on-chain and needs to be maintained by the `RISK_ADMINS` and `POOL_ADMINS` selected via the Aave Governance vote. 22 | {% endhint %} 23 | 24 | eMode also offers the possibility of introducing a specific price oracle for a certain category. 25 | 26 | ## How it works? 27 | 28 | If the user has supplied liquidity to the protocol, the user `eMode` category is set to 0 by default. 29 | 30 | The protocol allows user to set the user eMode category to any of the `eModeCategories` configured by the `PoolConfigurator` given the following conditions holds true: 31 | 32 | * all the borrowed assets of the user are in the chosen category. 33 | * changing eMode doesn’t leave user position under-collateralised 34 | -------------------------------------------------------------------------------- /docs/aave-docs-v3/whats-new/isolation-mode.md: -------------------------------------------------------------------------------- 1 | # Isolation Mode 2 | 3 | Isolation mode allows to list new assets as _**Isolated**_ which has a specific debt ceiling and can be only used to borrow stablecoins that have been permitted, by Aave Governance, to be borrowable in isolation mode. 4 | 5 | {% hint style="info" %} 6 | Debt Ceiling for an \*Isolated Asset\* is represented as the maximum amount in USD that can be borrowed against the collateral with two decimals of precision. 7 | {% endhint %} 8 | 9 | ## Supply Isolated Asset 10 | 11 | A user can supply an _Isolated Asset_ just like any other asset using `supply()` method in pool.sol, though, the default behaviour while supplying an _Isolated Asset_ may vary based on below conditions 12 | 13 | | Use as Collateral | Condition | 14 | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | 15 | | Enabled |

- if Isolated Asset is the first asset supplied by the user
OR
- no other supplied asset is enabled as collateral by the user

| 16 | | Disabled | if any other asset is currently enabled as collateral | 17 | 18 | {% hint style="info" %} 19 | In case the user has other assets enabled as collateral, they can still supply _Isolated Asset_ to capture the yield but won’t be able to use it as collateral 20 | {% endhint %} 21 | 22 | ## Borrow in Isolated Mode 23 | 24 | Borrowers using an _Isolated Asset_ as collateral can only use that particular asset as collateral and can only borrow assets that are _borrowable in isolation mode,_ i.e. have `BORROWABLE_IN_ISOLATION_MASK` bit set in reserve configuration. 25 | 26 | {% hint style="info" %} 27 | Borrower in Isolation Mode cannot enable any other assets including the other isolated assets as collateral. 28 | {% endhint %} 29 | 30 | ## Exit Isolation Mode 31 | 32 | Users can turn off isolation mode by disabling the isolated asset as collateral. This can be done only if the user has no outstanding debt. A user must use `repay()` method in Pool.sol to pay off all of their debt before exiting Isolation Mode 33 | -------------------------------------------------------------------------------- /docs/aave-docs-v3/whats-new/repay-with-atokens.md: -------------------------------------------------------------------------------- 1 | # Repay With aTokens 2 | 3 | Allows user to repay with _aTokens_ in case the underlying borrowed asset is locked in the Aave liquidity pool. 4 | 5 | _Example:_ **User have stable DAI debt and also holds aDAI token** 6 | 7 | The user in this case can use aDAI to repay DAI debt in single transaction without any approvals or having to withdraw their supplied liquidity to the pool using `repayWithATokens` feature. 8 | 9 | ```tsx 10 | import { Contract, utils } from "ethers"; 11 | const poolAbi = require("./abis/pool.json"); 12 | const pool = new Contract(POOL_ADDRESS, poolAbi, signer); 13 | 14 | // repay amount of DAI debt using aDAI tokens 15 | pool.repayWithATokens(DAI.address, amount, 2); 16 | 17 | // User must hold aDAI >= amount being repaid 18 | ``` 19 | -------------------------------------------------------------------------------- /docs/aave-docs-v3/whats-new/siloed-borrowing.md: -------------------------------------------------------------------------------- 1 | # Siloed Borrowing 2 | 3 | This feature allow assets with potentially manipulatable oracles (for example illiquid Uni V3 pairs) to be listed on Aave as single borrow asset i.e. if user borrows siloed asset, they cannot borrow any other asset. This helps mitigating the risk associated with such assets from impacting the overall solvency of the protocol. 4 | 5 | {% hint style="info" %} 6 | [Risk or Pool admin](../core-contracts/aclmanager.md#roles), selected by Aave Governace, can call [`setSiloedBorrowing`](../core-contracts/poolconfigurator.md#setsiloedborrowing) to set an asset in _Siloed Borrowing_ mode. 7 | {% endhint %} 8 | 9 | ## Supply Siloed Assets 10 | 11 | A user can supply S_iloed Asset_ just like any other asset using [`supply()`](../core-contracts/pool.md#supply) method in `pool.sol`, though, the asset will not be enabled to use as collateral i.e. supplied amount will not add to total collateral balance of the user. 12 | 13 | ### Borrow Siloed Assets 14 | 15 | {% hint style="danger" %} 16 | User borrowing a _siloed asset_ will _ **not**_ be allowed to __ borrow __ any other asset_._ 17 | {% endhint %} 18 | 19 | User can borrow _Siloed Assets_ using [`borrow()`](../core-contracts/pool.md#borrow) method in `pool.sol` , only if: 20 | 21 | * It is first borrow onBehalf of the address 22 | 23 | OR 24 | 25 | * Existing user debt is of the same _siloed asset._ 26 | 27 | To check if user is in Siloed Borrowing state, you can see if underlying asset borrowed by user is s_iloed_ using [`getSiloedBorrowing()`](../core-contracts/aaveprotocoldataprovider.md#getsiloedborrowing) method on AaveProtocolDataProvider.sol. 28 | 29 | ### Check if Reserved for Siloed Borrowing 30 | 31 | ```solidity 32 | import {AaveProtocolDataProvider} from '@aave/core-v3/contracts/misc/AaveProtocolDataProvider.sol'; 33 | AaveProtocolDataProvider poolDataProvider = AaveProtocolDataProvider(provider.getPoolDataProvider()); 34 | // address of the underlying asset 35 | address asset = "0x..."; 36 | 37 | protocolDataProvider.getSiloedBorrowing(asset); 38 | ``` 39 | 40 | 41 | 42 | ### FAQ 43 | 44 | #### How can user enter siloed borrowing state? 45 | 46 | User automatically enters siloed borrowing state on their first successful borrow of siloed asset. 47 | 48 | #### How does user exit siloed borrowing state? 49 | 50 | User must repay all their debt to exist siloed borrowing state. 51 | 52 | #### Is any asset currently siloed in Aave V3 market? 53 | 54 | Currently there is no asset marked siloed in any of the V3 markets. Risk or Pool admins can set already listed assets as siloed if needed as per market conditions. This feature can be used for new asset listing which may have higher risk. 55 | -------------------------------------------------------------------------------- /docs/aave-docs-v3/whats-new/supply-borrow-caps.md: -------------------------------------------------------------------------------- 1 | # Supply Borrow Caps 2 | 3 | ## Supply/Borrow Caps 4 | 5 | Aave Governance can appoint `RISK_ADMIN` and `POOL_ADMIN` who have the ability to configure Borrow and Supply Caps of the individual reserves. 6 | 7 | ## **Borrow Caps** 8 | 9 | Allow modulation of how much of each asset can be borrowed, which reduces insolvency risk. 10 | 11 | By default borrow cap of an asset is 0, which signifies no cap. Anyone who has been granted `RISK_ADMIN` or `POOL_ADMIN` role via the ACLManager can call [`setBorrowCap` method in PoolConfigurator](../core-contracts/poolconfigurator.md#write-methods) to update the max total borrow (stable + variable) for the given reserve. 12 | 13 | {% hint style="info" %} 14 | In case \*Borrow Cap\* of the reserve is set lower than the current \*totalDebt\* the existing borrowers are not effected but no more borrows (stable or variable) can be initiated for that reserve. 15 | {% endhint %} 16 | 17 | ## **Supply Caps** 18 | 19 | Allow limiting how much of a certain asset is supplied to the Aave protocol. This helps reducing exposure to a certain asset and mitigate attacks like infinite minting or price oracle manipulation. 20 | 21 | By default supply cap of an asset is 0, which signifies no cap. Anyone who has been granted `RISK_ADMIN` or `POOL_ADMIN` role via the ACLManager can call [`setSupplyCap` method in PoolConfigurator](../core-contracts/poolconfigurator.md#write-methods) to update the liquidity supply for the given reserve. 22 | 23 | {% hint style="info" %} 24 | In case _Supply Cap_ of the reserve is set lower than the current liquidity of the reserve, the existing suppliers are not effected but no more liquidity can be supplied to that reserve. 25 | {% endhint %} 26 | -------------------------------------------------------------------------------- /docs/curve-docs/dao-overview.rst: -------------------------------------------------------------------------------- 1 | .. _dao-overview: 2 | 3 | ============= 4 | The Curve DAO 5 | ============= 6 | 7 | Curve DAO consists of multiple smart contracts connected by `Aragon `_. Interaction with Aragon occurs through a `modified implementation `_ of the `Aragon Voting App `_. Aragon's standard one token, one vote method is replaced with a weighting system based on locking tokens. 8 | 9 | Curve DAO has a token (`CRV `_) which is used for both governance and value accrual. 10 | 11 | Source code for the Curve DAO can be found on `Github `_. 12 | -------------------------------------------------------------------------------- /docs/curve-docs/exchange-overview.rst: -------------------------------------------------------------------------------- 1 | .. _exchange-overview: 2 | 3 | =================================== 4 | Curve StableSwap Exchange: Overview 5 | =================================== 6 | 7 | Curve achieves extremely efficient stablecoin trades by implementing the StableSwap invariant, which has significantly lower slippage for stablecoin trades than many other prominent invariants (e.g., constant-product). Note that in this context *stablecoins* refers to tokens that are stable representations of one another. This includes, for example, USD-pegged stablecoins (like DAI and USDC), but also ETH and sETH (synthetic ETH) or different versions of wrapped BTC. For a detailed overview of the StableSwap invariant design, please read the official `StableSwap whitepaper `_. 8 | 9 | A Curve pool is essentially a smart contract that implements the StableSwap invariant and therefore contains the logic for exchanging stable tokens. However, while all Curve pools implement the StableSwap invariant, they may come in different pool flavors. 10 | 11 | In its simplest form, a Curve pool is an implementation of the StableSwap invariant with 2 or more tokens, which can be referred to as a *plain pool*. Alternative and more complex pool flavors include pools with lending functionality, so-called *lending pools*, as well as *metapools*, which are pools that allow for the exchange of one or more tokens with the tokens of one or more underlying base pools. 12 | 13 | Curve also integrates with Synthetix to offer cross-asset swaps. 14 | 15 | All exchange functionality that Curve supports, as well as noteworthy implementation details, are explained in technical depth in this section. 16 | -------------------------------------------------------------------------------- /docs/curve-docs/factory-migrator.rst: -------------------------------------------------------------------------------- 1 | .. _factory-migrator: 2 | 3 | ==================================== 4 | Metapool Factory: Liquidity Migrator 5 | ==================================== 6 | 7 | The ``PoolMigrator`` contract is used for migrating liquidity between Curve factory pools. It is deployed to the mainnet at the following address: 8 | 9 | `0xd6930b7f661257DA36F93160149b031735237594 `_ 10 | 11 | Source code for this contract is may be viewed on `Github `_. 12 | 13 | Migrating Liquidity between Pools 14 | ================================= 15 | 16 | .. py:function:: Factory.migrate_to_new_pool(_old_pool: address, _new_pool: address, _amount: uint256) -> uint256: 17 | 18 | Migrate liquidity between two pools. 19 | 20 | Each pool must be deployed by the curve factory (v1 or v2) and contain identical assets. Depending on the imbalance of each pool, the migration may incur slippage or provide a bonus. 21 | 22 | Prior to calling this method, the caller must have given approval for the migrator to transfer up to ``_amount`` LP tokens from ``_old_pool``. 23 | 24 | 25 | * ``_old_pool``: Address of the pool to migrate from 26 | * ``_new_pool``: Address of the pool to migrate into 27 | * ``_amount``: Number of ``_old_pool`` LP tokens to migrate 28 | 29 | Returns the number of ``_new_pool`` LP tokens received in the migration. 30 | 31 | .. code-block:: python 32 | 33 | >>> migrator = Contract('0xd6930b7f661257DA36F93160149b031735237594') 34 | >>> old_pool = Contract('0x36F3FD68E7325a35EB768F1AedaAe9EA0689d723') 35 | >>> new_pool = Contract('0x83D2944d5fC10A064451Dc5852f4F47759F249B6') 36 | 37 | >>> balance = old_pool.balanceOf(alice) 38 | 39 | >>> old_pool.approve(migrator, balance, {'from': alice}) 40 | Transaction sent: 0x8fc0dc0844ccbbed63d9cb7f2820087db5f70b320efea7ef4ce6b4a678e3cd45 41 | Gas price: 20 gwei Gas limit: 1100000 Nonce: 9 42 | 43 | >>> migrator.migrate_to_new_pool(old_pool, new_pool, balance, {'from': alice}) 44 | Transaction sent: 0xd65182491c13b2620f84fe2d501ace5c8ab1cda1b9ea54d40f4f2351cccd52b6 45 | Gas price: 20 gwei Gas limit: 1100000 Nonce: 10 46 | -------------------------------------------------------------------------------- /docs/curve-docs/factory-oracles.rst: -------------------------------------------------------------------------------- 1 | .. _factory-oracles: 2 | 3 | =================================== 4 | Metapool Factory: Oracles 5 | =================================== 6 | 7 | Factory contracts include Time-Weighted Average Price oracles. To understand these a bit better, you need to understand how Curve calculates price. 8 | 9 | A curve pool is an array of ``balances`` of the tokens it holds. To provide a price, it calculates how much of ``x`` you can receive given amount ``y``. 10 | 11 | 12 | Time-Weighted Average Price oracles 13 | =================================== 14 | 15 | .. py:function:: MetaPool.get_price_cumulative_last() -> uint256[N_COINS]: 16 | 17 | Returns the current time-weighted average price (TWAP). This will represent the underlying balances of the pool. 18 | 19 | The value returned is the cumulative pool shifting balances over time 20 | 21 | .. py:function:: MetaPool.block_timestamp_last() -> uint256: 22 | 23 | Returns the last timestamp that a TWAP reading was taken in unix time. 24 | 25 | .. py:function:: MetaPool.get_twap_balances(_first_balances: uint256[N_COINS], _last_balances: uint256[N_COINS], _time_elapsed: uint256) -> uint256[N_COINS]: 26 | 27 | Calculate the current effective TWAP balances given two snapshots over time, and the time elapsed between the two snapshots. 28 | 29 | * ``_first_balances``: First ``price_cumulative_last`` array that was snapshot via ``get_price_cumulative_last`` 30 | * ``_last_balances``: Second ``price_cumulative_last`` array that was snapshot via ``get_price_cumulative_last`` 31 | * ``_time_elapsed``: The elapsed time in seconds between ``_first_balances`` and ``_last_balances`` 32 | 33 | Returns the ``balances`` of the TWAP value. 34 | 35 | .. py:function:: MetaPool.get_dy(i: int128, j: int128, dx: uint256, _balances: uint256[N_COINS] = [0,0]) -> uint256: 36 | 37 | Calculate the price for exchanging a token with index ``i`` to token with index ``j`` and amount ``dx`` given the ``_balances`` provided. 38 | 39 | * ``i``: The index of the coin being sent to the pool, as it related to the metapool 40 | * ``j``: The index of the coin being received from the pool, as it relates to the metapool 41 | * ``dx``: The amount of ``i`` being sent to the pool 42 | * ``_balances``: The array of balances to be used for purposes of calculating the output amount / exchange rate, this is the value returned in :func:`get_twap_balances ` 43 | 44 | Returns the quote / price as ``dy`` given ``dx``. 45 | 46 | Security 47 | ======== 48 | 49 | The Curve TWAP is greatly inspired by `Uniswap TWAP architecture `_, in that the price is a cumulative value over time, which reduces balance shifts due to flash loans, but also records the balances based on the previous block, to avoid recording flashloan data. 50 | -------------------------------------------------------------------------------- /docs/curve-docs/factory-overview.rst: -------------------------------------------------------------------------------- 1 | .. _factory-overview: 2 | 3 | ================ 4 | MetaPool Factory 5 | ================ 6 | 7 | The metapool factory allows for permissionless deployment of Curve metapools. 8 | 9 | Source code for factory contracts may be viewed on `Github `_. 10 | 11 | Organization 12 | ============ 13 | 14 | The metapool factory has several core components: 15 | 16 | * The :ref:`factory` is the main contract used to deploy new metapools. It also acts a registry for finding the deployed pools and querying information about them. 17 | * :ref:`Pools` are deployed via a proxy contract. The implementation contract targetted by the proxy is determined according to the base pool. This is the same technique used to create pools in Uniswap V1. 18 | * :ref:`Deposit contracts` ("zaps") are used for wrapping and unwrapping underlying assets when depositing into or withdrawing from pools. 19 | -------------------------------------------------------------------------------- /docs/curve-docs/guide-overview.rst: -------------------------------------------------------------------------------- 1 | .. _guide-overview: 2 | 3 | ================= 4 | Contributor Guide 5 | ================= 6 | 7 | Curve is open-source and consists of a number of repositories `on Github `_. Contributions are welcome! 8 | 9 | On-chain contracts are spread across different Curve repositories as such: 10 | 11 | * `curve-contract `_: contracts for Curve stable swap pools 12 | * `curve-dao-contracts `_: contracts owned by DAO (e.g., liquidity gauges, burners and fee distributor) 13 | * `curve-pool-registry `_: contracts for on-chain information on pools and swaps 14 | 15 | In order to make contributing to Curve as seamless as possible, please read thoroughly through these contribution guidelines. -------------------------------------------------------------------------------- /docs/curve-docs/index.rst: -------------------------------------------------------------------------------- 1 | .. image:: logo.svg 2 | :width: 480px 3 | :alt: Curve 4 | :align: center 5 | 6 | | 7 | 8 | `Curve `_ is an exchange liquidity pool on Ethereum. Curve is designed for extremely efficient stablecoin trading and low risk, supplemental fee income for liquidity providers, without an opportunity cost. 9 | 10 | This documentation outlines the technical implementation of the core Curve protocol and related smart contracts. It may be useful for contributors to the Curve codebase, third party integrators, or technically proficient users of the protocol. 11 | 12 | Non-technical users may prefer the `Resources `_ section of the main Curve website. 13 | 14 | .. note:: 15 | 16 | All code starting with ``$`` is meant to be run on your terminal. Code starting with ``>>>`` is meant to run inside the Brownie console. 17 | 18 | .. note:: 19 | 20 | This project relies heavily upon ``brownie`` and the documentation assumes a basic familiarity with it. You may wish to view the `Brownie documentation `_ if you have not used it previously. 21 | 22 | Procotol Overview 23 | ================= 24 | 25 | Curve can be broadly separated into the following categories: 26 | 27 | * :ref:`StableSwap`: Exchange contracts and core functionality of the protocol 28 | * The :ref:`DAO`: Protocol governance and value accrual 29 | * The :ref:`Factory`: Permissionless deployment of Curve metapools 30 | * The :ref:`Registry`: Standardized API and on-chain resources to aid 3rd party integrations 31 | -------------------------------------------------------------------------------- /docs/curve-docs/ref-glossary.rst: -------------------------------------------------------------------------------- 1 | .. _glossary: 2 | 3 | ================= 4 | Glossary of Terms 5 | ================= 6 | 7 | This glossary of terms contains definitions of commonly used terms within the Curve documentation. 8 | 9 | This section is a work in progress - if a term is missing, feel free to `open a pull request `_ to add it. 10 | 11 | .. _glossary-amm: 12 | 13 | Automated Market Maker (AMM) 14 | A decentralized asset trading pool that allows participants to buy or sell cryptocurrencies. 15 | 16 | Base Pool 17 | The pool issuing the LP token that is used by a metapool. 18 | 19 | Burning 20 | The process of withdrawing admin fees from the excahange contracts and distributing them to veCRV holders. 21 | 22 | ERC20 23 | A technical standard for implementing tokens within Ethereum. Often used interchangeably with the term token. The standard is viewable `here `_. 24 | 25 | LP Token 26 | Short for Liquidity Provider token. An ER20 token which represents a deposit into a Curve exchange contract, or other :ref:`AMM`. 27 | 28 | .. _glossary-metapool: 29 | 30 | Metapool 31 | A Curve pool where one of the tradeable assets is the :ref:`LP token` for another pool (base pool). Metapools are used to prevent liquidity fragmentation. 32 | 33 | .. _glossary-underlying-coin: 34 | 35 | Pool 36 | See :ref:`automated market maker`. 37 | 38 | Synth 39 | Short for "synthetic asset" - a derivative which tracks the price of another asset, offering exposure to price movements without requiring the user to hold the actual asset. 40 | 41 | Underlying Coin 42 | An ERC20 token that has been deposited into a protocol and where the deposit is represented by another token. The other token (the ":ref:`wrapped coin`") may be used to claim back this original token. 43 | 44 | veCRV 45 | Short for "vote-escrowed CRV". CRV that has been locked in the :ref:`voting contract`. 46 | 47 | .. _glossary-wrapped-coin: 48 | 49 | Wrapped Coin 50 | An ERC20 token used to represent the deposit of another token within a protocol. The original token has been "wrapped" in this new token. The originial token is referred to as the ":ref:`underlying coin`". 51 | -------------------------------------------------------------------------------- /docs/curve-docs/registry-overview.rst: -------------------------------------------------------------------------------- 1 | .. _overview: 2 | 3 | 4 | ======== 5 | Registry 6 | ======== 7 | 8 | The Curve registry contracts are open source and may be `found on Github `_. 9 | 10 | The registry is comprised of the following contracts: 11 | 12 | * ``AddressProvider``: Address provider for registry contracts. This contract is immutable and it's address will never change. On-chain integrators should always use this contract to fetch the current address of other registry components. 13 | * ``Registry``: The main registry contract. Used to locate pools and query information about them as well as registered coins. 14 | * ``PoolInfo``: Aggregate getter methods for querying large data sets about a single pool. Designed for off-chain use. 15 | * ``Swaps``: The registry exchange contract. Used to find pools and query exchange rates for token swaps. Also provides a unified exchange API that can be useful for on-chain integrators. 16 | -------------------------------------------------------------------------------- /docs/curve-docs/toctree.rst: -------------------------------------------------------------------------------- 1 | ===== 2 | Curve 3 | ===== 4 | 5 | .. toctree:: 6 | :titlesonly: 7 | 8 | Protocol Overview 9 | 10 | .. toctree:: 11 | :maxdepth: 2 12 | :caption: StableSwap Exchange 13 | 14 | Overview 15 | Pools 16 | LP Tokens 17 | Deposit Contracts 18 | Cross-Asset Swaps 19 | 20 | .. toctree:: 21 | :maxdepth: 2 22 | :caption: Curve DAO 23 | 24 | Overview 25 | Vote-Escrowed CRV 26 | Liquidity Gauges and Minting CRV 27 | Gauges for EVM Sidechains 28 | Fee Collection and Distribution 29 | Governance and Voting 30 | Ownership Proxies 31 | 32 | .. toctree:: 33 | :maxdepth: 2 34 | :caption: Registry 35 | 36 | Overview 37 | The Address Provider 38 | The Main Registry 39 | Pool Info: Aggregated Getters 40 | Exchanges 41 | 42 | .. toctree:: 43 | :maxdepth: 2 44 | :caption: Metapool Factory 45 | 46 | Overview 47 | Deployer and Registry 48 | Pools 49 | Oracles 50 | Deposit Contracts 51 | Liquidity Migrator 52 | 53 | .. toctree:: 54 | :maxdepth: 2 55 | :caption: Contributor Guide 56 | 57 | Overview 58 | General 59 | Testing 60 | Code Style 61 | 62 | .. toctree:: 63 | :maxdepth: 2 64 | :caption: Reference 65 | 66 | Deployment Addresses 67 | Glossary of Terms 68 | -------------------------------------------------------------------------------- /docs/move_to_trash.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Create a trash directory under the script's current directory 4 | script_dir=$(dirname "$(readlink -f "$0")") 5 | trash_dir="${script_dir}/trash" 6 | 7 | if [ ! -d "${trash_dir}" ]; then 8 | mkdir "${trash_dir}" 9 | fi 10 | 11 | # Pattern for directories named "images" 12 | dir_pattern="images" 13 | 14 | # Find and move matching directories to the trash directory with unique names 15 | find "${script_dir}" -type d -name "${dir_pattern}" -exec bash -c 'mv "$0" "${1}/$(uuidgen)_$(basename "$0")"' {} "${trash_dir}" \; 16 | 17 | # Pattern for files with the ".json" extension 18 | file_pattern="*.json" 19 | 20 | # Find and move matching files to the trash directory with unique names 21 | find "${script_dir}" -type f -name "${file_pattern}" -exec bash -c 'mv "$0" "${1}/$(uuidgen)_$(basename "$0")"' {} "${trash_dir}" \; 22 | -------------------------------------------------------------------------------- /docs/uniswap-contracts/permit2/overview.md: -------------------------------------------------------------------------------- 1 | --- 2 | id: overview 3 | title: Overview 4 | sidebar_position: 1 5 | --- 6 | 7 | [`Permit2`](https://github.com/Uniswap/permit2) is a unification of 2 contracts, [`SignatureTransfer`](./reference/signature-transfer.md) and [`AllowanceTransfer`](./reference/allowance-transfer.md). The `SignatureTransfer` contract handles all signature-based transfers, meaning that an allowance on the token is bypassed and permissions to the spender only last for the duration of the transaction that the one-time signature is spent. The `AllowanceTransfer` contract handles setting allowances on tokens, giving permissions to spenders on a specified amount for a specified duration of time. Any transfers that then happen through the `AllowanceTransfer` contract will only succeed if the proper permissions have been set. 8 | 9 | ## Resources 10 | 11 | A great [explanation](https://github.com/dragonfly-xyz/useful-solidity-patterns/tree/main/patterns/permit2) of the Permit2 contract and example usage. 12 | 13 | ## Approving Permit2 14 | 15 | Before integrating contracts can request users’ tokens through Permit2, users must approve the Permit2 contract through the specific token contract by calling something like: 16 | 17 | ```solidity 18 | USDC.approve(permit2Address, totalAmount); 19 | ``` 20 | 21 | To get the maximal benefits from Permit2, users should do a max approval on the contract where: 22 | ```solidity 23 | totalAmount = type(uint256).max; 24 | ``` 25 | 26 | 27 | -------------------------------------------------------------------------------- /docs/uniswap-contracts/universal-router/01-overview.md: -------------------------------------------------------------------------------- 1 | --- 2 | id: overview 3 | title: Overview 4 | sidebar_position: 1 5 | --- 6 | 7 | The `UniversalRouter` is an ETH, ERC20, and NFT swap router, that can aggregate trades across protocols to give users access highly-flexible and personalised transactions. The contract is unowned, and is not upgradeable. 8 | 9 | The flexible command style allows us to provide users with: 10 | 11 | - Splitting and interleaving of Uniswap trades 12 | - Purchases of NFTs across 8 marketplaces 13 | - Partial fills of trades 14 | - Wrapping and Unwrapping of ETH 15 | - Time-bound, signature controlled token approvals using [Permit2](../permit2/overview.md) 16 | 17 | Transactions are encoded using a string of commands, allowing users to have maximum flexibility over what they want to perform. With all of these features available in a single transaction, the possibilities available to users are endless. 18 | 19 | *Note: The `UniversalRouter` uses `Permit2` to remove the need for token approvals being provided directly to the `UniversalRouter`. The `Permit2` documentation can be found [here](../permit2/overview.md).* 20 | -------------------------------------------------------------------------------- /docs/uniswap-contracts/v1/guides/05-iframe-integration.md: -------------------------------------------------------------------------------- 1 | --- 2 | id: iframe-integration 3 | title: Iframe Integration 4 | --- 5 | 6 | Uniswap can be used within other sites as an iframe. An iframe shows an exact version of the app.uniswap.org site and can have custom prefilled settings. 7 | 8 | # Why You May Want This 9 | 10 | Integrating the Uniswap site directly into your web application can be useful for a variety of reasons. 11 | 12 | v1.app.uniswap.org allows users to buy, sell, send, or provide liquidity for ERC20 tokens. An iframe integration may be useful if your application provides services around these ERC20 tokens. \(For example, users can buy DAI through a Uniswap iframe on your site, then allow users to lend that DAI on your site\). 13 | 14 | It can also be useful if your application requires users to acquire some token in order to use some service \(For example, allow users to buy "REP" token so they can engage in prediction markets on the Augur Dapp\). 15 | 16 | # iframe vs. custom UI 17 | 18 | One benefit of an iframe integration is that the your site will automatically keep up with any improvements/additions to the v1.app.uniswap.org site. After the initital integration is setup no further work is needed to pull in updates as the exchange site is updated over time. 19 | 20 | # Live Example 21 | 22 | An example of an Iframe integration can be found on the FOAM site [https://map.foam.space/](https://map.foam.space/#/at/?lng=-74.0045300&lat=40.6771800&zoom=5.00) 23 | 24 | To see the Iframe click the dropdown in the top right and click "get foam". 25 | 26 | # Add To Your Site 27 | 28 | To include a Uniswap iframe within your site just add an iframe element within your website code and link to the Uniswap exchange. 29 | 30 | Linking to a ETH <-> DAI swap page would look something like this. To link to a token of your choice replace the address after "outputCurrency" with the token address of the token you want to link to. 31 | 32 | ```text 33 |