├── .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 | 
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 |
47 | ```
48 |
49 | You can customize the selected page, selected custom tokens and more using URL query parameters. See [Custom Linking](custom-linking).
50 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v1/guides/06-token-listing.md:
--------------------------------------------------------------------------------
1 | ---
2 | id: token-listing
3 | title: Token Listing
4 | ---
5 |
6 | It is possible that a token you are interested in is not included in the token dropdown on [https://app.uniswap.org/#/swap?use=v1](https://app.uniswap.org/#/swap?use=v1), however, all tokens that have a deployed uniswap exchange are supported on the front-end.
7 |
8 | There are three ways to interact with tokens that are not yet included on the default list.
9 |
10 | ## 1. Paste the token address into the search box.
11 |
12 | If a token is not included in the list, try pasting the token address into the search box. It will populate the dropdown with the token you are looking for.
13 |
14 | ## 2. Custom Linking
15 |
16 | [https://app.uniswap.org/#/swap?use=v1](https://app.uniswap.org/#/swap?use=v1) supports custom linking to all tokens that have a Uniswap exchange. See [Custom Linking](custom-linking) for details on how to link.
17 |
18 | For example, to populate the output token field with an unlisted token, we can specify the outputCurrency in the URL and pass in the token's address like this:
19 |
20 | `https://app.uniswap.org/#/swap?use=v1?outputCurrency=0xfA3E941D1F6B7b10eD84A0C211bfA8aeE907965e`
21 |
22 | ## Token Details and Assets
23 |
24 | Token information (including decimals, symbol, name, etc.) is pulled from token contracts directly. Logo images are pulled from TrustWallet. If you'd like your token logo updated make a pull request into the TrustWallet assets repo [https://github.com/trustwallet/assets](https://github.com/trustwallet/assets).
25 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v2/concepts/01-protocol-overview/01-how-uniswap-works.md:
--------------------------------------------------------------------------------
1 | ---
2 | id: how-uniswap-works
3 | title: How Uniswap works
4 | ---
5 |
6 | 
7 |
8 | Uniswap is an _automated liquidity protocol_ powered by a [constant product formula](../protocol-overview/glossary#constant-product-formula)
9 | and implemented in a system of non-upgradeable smart contracts on the [Ethereum](https://ethereum.org/) blockchain.
10 | It obviates the need for trusted intermediaries, prioritizing **decentralization**, **censorship resistance**,
11 | and **security**. Uniswap is **open-source software** licensed under the
12 | [GPL](https://en.wikipedia.org/wiki/GNU_General_Public_License).
13 |
14 | Each Uniswap smart contract, or pair, manages a liquidity pool made up of reserves of two [ERC-20](https://eips.ethereum.org/EIPS/eip-20) tokens.
15 |
16 | Anyone can become a liquidity provider (LP) for a pool by depositing an equivalent value of each underlying token in return for pool tokens. These tokens track pro-rata LP shares of the total reserves, and can be redeemed for the underlying assets at any time.
17 |
18 | 
19 |
20 | Pairs act as automated market makers, standing ready to accept one token for the other as long as the “constant product” formula is preserved. This formula, most simply expressed as `x * y = k`, states that trades must not change the product (`k`) of a pair’s reserve balances (`x` and `y`). Because `k` remains unchanged from the reference frame of a trade, it is often referred to as the invariant. This formula has the desirable property that larger trades (relative to reserves) execute at exponentially worse rates than smaller ones.
21 |
22 | In practice, Uniswap applies a 0.30% fee to trades, which is added to reserves. As a result, each trade actually increases `k`. This functions as a payout to LPs, which is realized when they burn their pool tokens to withdraw their portion of total reserves. In the future, this fee may be reduced to 0.25%, with the remaining 0.05% withheld as a protocol-wide charge.
23 |
24 | 
25 |
26 | Because the relative price of the two pair assets can only be changed through trading, divergences between the Uniswap price and external prices create arbitrage opportunities. This mechanism ensures that Uniswap prices always trend toward the market-clearing price.
27 |
28 | # Further reading
29 |
30 | To see how token swaps work in practice, and to walk through the lifecycle of a swap, check out [Swaps](../core-concepts/swaps). Or, to see how liquidity pools work, see [Pools](../core-concepts/pools).
31 |
32 | Ultimately, of course, the Uniswap protocol is just smart contract code running on Ethereum. To understand how they work, head over to [Smart Contracts](../../reference/smart-contracts/factory).
33 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v2/concepts/01-protocol-overview/04-glossary.md:
--------------------------------------------------------------------------------
1 | ---
2 | id: glossary
3 | title: Glossary
4 | ---
5 |
6 | ### Automated market maker
7 |
8 | An automated market maker is a smart contract on Ethereum that holds on-chain liquidity reserves. Users can trade against these reserves at prices set by an automated market making formula.
9 |
10 | ### Constant product formula
11 |
12 | The automated market making algorithm used by Uniswap.
13 | See [x\*y=k](#x--y--k).
14 |
15 | ### ERC20
16 |
17 | ERC20 tokens are fungible tokens on Ethereum. Uniswap supports all standard ERC20 implementations.
18 |
19 | ### Factory
20 |
21 | A smart contract that deploys a unique smart contract for any ERC20/ERC20 trading pair.
22 |
23 | ### Pair
24 |
25 | A smart contract deployed from the Uniswap V2 Factory that enables trading between two ERC20 tokens.
26 |
27 | ### Pool
28 |
29 | Liquidity within a pair is pooled across all liquidity providers.
30 |
31 | ### Liquidity provider / LP
32 |
33 | A liquidity provider is someone who deposits an equivalent value of two ERC20 tokens into the liquidity pool within a pair. Liquidity providers take on price risk and are compensated with fees.
34 |
35 | ### Mid price
36 |
37 | The price between what users can buy and sell tokens at a given moment. In Uniswap this is the ratio of the two ERC20 token reserves.
38 |
39 | ### Price impact
40 |
41 | The difference between the mid-price and the execution price of a trade.
42 |
43 | ### Slippage
44 |
45 | The amount the price moves in a trading pair between when a transaction is submitted and when it is executed.
46 |
47 | ### Core
48 |
49 | Smart contracts that are essential for Uniswap to exist. Upgrading to a new version of core would require a liquidity migration.
50 |
51 | ### Periphery
52 |
53 | External smart contracts that are useful, but not required for Uniswap to exist. New periphery contracts can always be deployed without migrating liquidity.
54 |
55 | ### Flash swap
56 |
57 | A trade that uses the tokens being purchased before paying for them.
58 |
59 | ### `x * y = k`
60 |
61 | The constant product formula.
62 |
63 | ### Invariant
64 |
65 | The "k" value in the constant product formula
66 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v2/concepts/03-advanced-topics/01-fees.md:
--------------------------------------------------------------------------------
1 | ---
2 | id: fees
3 | title: Fees
4 | ---
5 |
6 | ## Liquidity provider fees
7 |
8 | There is a **0.3%** fee for swapping tokens. **This fee is split by liquidity providers proportional to their contribution to liquidity reserves.**
9 |
10 | Swapping fees are immediately deposited into liquidity reserves. This increases the value of liquidity tokens, functioning as a payout to all liquidity providers proportional to their share of the pool. Fees are collected by burning liquidity tokens to remove a proportional share of the underlying reserves.
11 |
12 | Since fees are added to liquidity pools, the invariant increases at the end of every trade. Within a single transaction, the invariant represents `token0_pool / token1_pool` at the end of the previous transaction.
13 |
14 | There are many community-developed tools to determine returns. You can also read more in the docs about how to think about [LP returns](../advanced-topics/understanding-returns).
15 |
16 | ## Protocol Fees
17 |
18 | At the moment there are no protocol fees. However, it is possible for a 0.05% fee to be turned on in the future.
19 |
20 | More information about a potential future protocol fee can be found [here](https://uniswap.org/blog/uniswap-v2/#path-to-sustainability).
21 |
22 | ## Protocol Charge Calculation
23 |
24 | In the future, it is possible that a protocol-wide charge of 0.05% per trade will take effect. This represents ⅙th (16.6̅%) of the 0.30% fee. The fee is in effect if [feeTo](../../reference/smart-contracts/factory/#feeto) is not `address(0)` (`0x0000000000000000000000000000000000000000`), indicating that feeTo is the recipient of the charge.
25 |
26 | This amount would not affect the fee paid by traders, but would affect the amount received by liquidity providers.
27 |
28 | Rather than calculating this charge on swaps, which would significantly increase gas costs for all users, the charge is instead calculated when liquidity is added or removed. See the whitepaper for more details.
29 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v2/concepts/03-advanced-topics/05-math.md:
--------------------------------------------------------------------------------
1 | ---
2 | id: math
3 | title: Math
4 | ---
5 |
6 | This section will be expanded in the future. In the mean time, the [Uniswap V2 whitepaper](https://uniswap.org/whitepaper.pdf) has most relevant math for Uniswap V2.
7 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v2/guides/smart-contract-integration/06-getting-pair-addresses.md:
--------------------------------------------------------------------------------
1 | ---
2 | id: getting-pair-addresses
3 | title: Pair Addresses
4 | ---
5 |
6 | # getPair
7 |
8 | The most obvious way to get the address for a pair is to call [getPair](../../reference/smart-contracts/factory#getpair) on the factory. If the pair exists, this function will return its address, else `address(0)` (`0x0000000000000000000000000000000000000000`).
9 |
10 | - The "canonical" way to determine whether or not a pair exists.
11 | - Requires an on-chain lookup.
12 |
13 | # CREATE2
14 |
15 | Thanks to some [fancy footwork in the factory](https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2Factory.sol#L32), we can also compute pair addresses _without any on-chain lookups_ because of [CREATE2](https://eips.ethereum.org/EIPS/eip-1014). The following values are required for this technique:
16 |
17 | | | |
18 | | :--------------------- | :--------------------------------------------------------------------- |
19 | | `address` | The [factory address](../../reference/smart-contracts/factory#address) |
20 | | `salt` | `keccak256(abi.encodePacked(token0, token1))` |
21 | | `keccak256(init_code)` | `0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f` |
22 |
23 | - `token0` must be strictly less than `token1` by sort order.
24 |
25 | * Can be computed offline.
26 | * Requires the ability to perform `keccak256`.
27 |
28 | ## Examples
29 |
30 | ### Solidity
31 |
32 | ```solidity
33 | address factory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
34 | address token0 = 0xCAFE000000000000000000000000000000000000; // change me!
35 | address token1 = 0xF00D000000000000000000000000000000000000; // change me!
36 |
37 | address pair = address(uint(keccak256(abi.encodePacked(
38 | hex'ff',
39 | factory,
40 | keccak256(abi.encodePacked(token0, token1)),
41 | hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'
42 | ))));
43 | ```
44 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v2/guides/smart-contract-integration/07-supporting-meta-transactions.md:
--------------------------------------------------------------------------------
1 | ---
2 | id: supporting-meta-transactions
3 | title: Supporting meta transactions
4 | ---
5 |
6 | All Uniswap V2 pool tokens support meta-transaction approvals via the [permit](../../reference/smart-contracts/pair-erc-20#permit) function. This obviates the need for a blocking approve transaction before programmatic interactions with pool tokens can occur.
7 |
8 | # ERC-712
9 |
10 | In vanilla ERC-20 token contracts, owners may only register approvals by directly calling a function which uses `msg.sender` to permission itself. With meta-approvals, ownership and permissioning are derived from a signature passed into the function by the caller (sometimes referred to as the relayer). Because signing data with Ethereum private keys can be a tricky endeavor, Uniswap V2 relies on [ERC-712](https://eips.ethereum.org/EIPS/eip-712), a signature standard with widespread community support, to ensure user safety and wallet compatibility.
11 |
12 | ## Domain Separator
13 |
14 | ```solidity
15 | keccak256(
16 | abi.encode(
17 | keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
18 | keccak256(bytes(name)),
19 | keccak256(bytes('1')),
20 | chainId,
21 | address(this)
22 | )
23 | );
24 | ```
25 |
26 | - `name` is always `Uniswap V2`, see [name](../../reference/smart-contracts/pair-erc-20#name).
27 | - `chainId` is determined from the [ERC-1344](https://ethereum-magicians.org/t/eip-1344-add-chain-id-opcode/1131) `chainid` opcode.
28 | - `address(this)` is the address of the pair, see [Pair Addresses](../../../../sdk/v2/guides/getting-pair-addresses).
29 |
30 | ## Permit Typehash
31 |
32 | ```solidity
33 | keccak256('Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)');`
34 | ```
35 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v2/overview.md:
--------------------------------------------------------------------------------
1 | ---
2 | id: overview
3 | title: Overview
4 | sidebar_position: 1
5 | ---
6 |
7 | # The Uniswap V2 Smart Contracts
8 |
9 | Welcome to the Uniswap protocol V2 docs.
10 |
11 | The pages here contain conceptual and technical documentation of the Uniswap V2 protocol.
12 |
13 | If you are new to Uniswap, you might want to check out the [Protocol overview](../V2/concepts/protocol-overview/how-uniswap-works) first.
14 |
15 | You can also take a look at the V2 Protocol Whitepaper.
16 |
17 | # Developer links
18 |
19 | The V2 Uniswap protocol is separated across two repositories
20 |
21 | - [`uniswap-v2-core`](https://github.com/Uniswap/uniswap-v2-core)
22 | - [`uniswap-v2-periphery`](https://github.com/Uniswap/uniswap-v2-periphery)
23 |
24 | The V2 SDK, which can assist developers when interacting with the Uniswap V2 Protocol can be found here.
25 |
26 | - [`uniswap-sdk`](https://github.com/Uniswap/uniswap-v2-sdk)
27 | - [`uniswap-sdk-core`](https://github.com/Uniswap/uniswap-sdk-core)
28 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v2/reference/API/01-overview.md:
--------------------------------------------------------------------------------
1 | ---
2 | id: overview
3 | title: API Overview
4 | ---
5 |
6 | This section explains the Uniswap Subgraph and how to interact with it. The Uniswap subgraph indexes data from the Uniswap contracts over time. It organizes data about pairs, tokens, Uniswap as a whole, and more. The subgraph updates any time a transaction is made on Uniswap. The subgraph runs on [The Graph](https://thegraph.com/) protocol's hosted service and can be openly queried.
7 |
8 | ## Resources
9 |
10 | [Subgraph Explorer](https://thegraph.com/explorer/subgraph/uniswap/uniswap-v2) - sandbox for querying data and endpoints for developers.
11 |
12 | [Uniswap V2 Subgraph](https://github.com/Uniswap/uniswap-v2-subgraph) - source code for deployed subgraph.
13 |
14 | ## Usage
15 |
16 | The subgraph provides a snapshot of the current state of Uniswap and also tracks historical data. It is currently used to power [uniswap.info](https://uniswap.info/). **It is not intended to be used as a data source for structuring transactions (contracts should be referenced directly for the most reliable live data).**
17 |
18 | ## Making Queries
19 |
20 | To learn more about querying a subgraph refer to [The Graph's documentation](https://thegraph.com/docs/about/introduction).
21 |
22 | ## Versions
23 |
24 | The [Uniswap V2 Subgraph](https://thegraph.com/explorer/subgraph/uniswap/uniswap-v2) only tracks data on Uniswap V2. For Uniswap V1 information see the [V1 Subgraph](https://thegraph.com/explorer/subgraph/graphprotocol/uniswap).
25 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/guides/providing-liquidity/increase-liquidity.md:
--------------------------------------------------------------------------------
1 | ---
2 | id: increase-liquidity
3 | title: Increase Liquidity
4 | sidebar_position: 5
5 | ---
6 |
7 | ## Increase Liquidity Within The Current Range
8 |
9 | Make sure to go through the [first guide](./setting-up-your-contract.md) before continuing to this section
10 |
11 | - This example assumes the contract already has custody of the NFT.
12 |
13 | - We cannot change the boundaries of a given liquidity position using the Uniswap v3 protocol; `increaseLiquidity` can only increase the liquidity of a position.
14 | - In production, `amount0Min` and `amount1Min` should be adjusted to create slippage protections.
15 |
16 | ```solidity
17 | /// @notice Increases liquidity in the current range
18 | /// @dev Pool must be initialized already to add liquidity
19 | /// @param tokenId The id of the erc721 token
20 | /// @param amount0 The amount to add of token0
21 | /// @param amount1 The amount to add of token1
22 | function increaseLiquidityCurrentRange(
23 | uint256 tokenId,
24 | uint256 amountAdd0,
25 | uint256 amountAdd1
26 | )
27 | external
28 | returns (
29 | uint128 liquidity,
30 | uint256 amount0,
31 | uint256 amount1
32 | )
33 | {
34 | INonfungiblePositionManager.IncreaseLiquidityParams memory params =
35 | INonfungiblePositionManager.IncreaseLiquidityParams({
36 | tokenId: tokenId,
37 | amount0Desired: amountAdd0,
38 | amount1Desired: amountAdd1,
39 | amount0Min: 0,
40 | amount1Min: 0,
41 | deadline: block.timestamp
42 | });
43 |
44 | (liquidity, amount0, amount1) = nonfungiblePositionManager.increaseLiquidity(params);
45 | }
46 | ```
47 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/overview.md:
--------------------------------------------------------------------------------
1 | ---
2 | id: overview
3 | title: Overview
4 | sidebar_position: 1
5 | ---
6 |
7 | # The Uniswap V3 Smart Contracts
8 |
9 | Welcome to the Uniswap V3 smart contracts documentation.
10 |
11 | The pages here contain guides and technical documentation for the Uniswap V3 Smart Contracts.
12 | You can use these docs to learn about the V3 Protocol Smart Contracts and develop on-chain integrations.
13 |
14 | # Guides
15 |
16 | If you are new to the Uniswap Protocol, we recommend you start with the [basic concepts](../../concepts/uniswap-protocol) first.
17 |
18 | You can then setup your [local environment](./guides/local-environment) and execute your [first swap](./guides/swaps/single-swaps).
19 |
20 | # Reference
21 |
22 | For a deeper dive, read through the [technical reference](./reference/overview) docs.
23 |
24 | # Resources
25 |
26 | - [**V3 Core**](https://github.com/Uniswap/v3-core)
27 | - [**V3 Periphery**](https://github.com/Uniswap/v3-periphery)
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/core/UniswapV3Factory.md:
--------------------------------------------------------------------------------
1 | Deploys Uniswap V3 pools and manages ownership and control over pool protocol fees
2 |
3 | ## Functions
4 |
5 | ### createPool
6 |
7 | ```solidity
8 | function createPool(
9 | address tokenA,
10 | address tokenB,
11 | uint24 fee
12 | ) external returns (address pool)
13 | ```
14 |
15 | Creates a pool for the given two tokens and fee
16 |
17 | tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved
18 | from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments
19 | are invalid.
20 |
21 | #### Parameters:
22 |
23 | | Name | Type | Description |
24 | | :------- | :------ | :---------------------------------------------- |
25 | | `tokenA` | address | One of the two tokens in the desired pool |
26 | | `tokenB` | address | The other of the two tokens in the desired pool |
27 | | `fee` | uint24 | The desired fee for the pool |
28 |
29 | #### Return Values:
30 |
31 | | Name | Type | Description |
32 | | :----- | :------ | :------------------------------------ |
33 | | `pool` | address | The address of the newly created pool |
34 |
35 | ### setOwner
36 |
37 | ```solidity
38 | function setOwner(
39 | address _owner
40 | ) external
41 | ```
42 |
43 | Updates the owner of the factory
44 |
45 | Must be called by the current owner
46 |
47 | #### Parameters:
48 |
49 | | Name | Type | Description |
50 | | :------- | :------ | :--------------------------- |
51 | | `_owner` | address | The new owner of the factory |
52 |
53 | ### enableFeeAmount
54 |
55 | ```solidity
56 | function enableFeeAmount(
57 | uint24 fee,
58 | int24 tickSpacing
59 | ) public
60 | ```
61 |
62 | Enables a fee amount with the given tickSpacing
63 |
64 | Fee amounts may never be removed once enabled
65 |
66 | #### Parameters:
67 |
68 | | Name | Type | Description |
69 | | :------------ | :----- | :--------------------------------------------------------------------------------------- |
70 | | `fee` | uint24 | The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6) |
71 | | `tickSpacing` | int24 | The spacing between ticks to be enforced for all pools created with the given fee amount |
72 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/core/UniswapV3PoolDeployer.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### deploy
4 |
5 | ```solidity
6 | function deploy(
7 | address factory,
8 | address token0,
9 | address token1,
10 | uint24 fee,
11 | int24 tickSpacing
12 | ) internal returns (address pool)
13 | ```
14 |
15 | Deploys a pool with the given parameters by transiently setting the parameters storage slot and then
16 | clearing it after deploying the pool.
17 |
18 | #### Parameters:
19 |
20 | | Name | Type | Description |
21 | | :------------ | :------ | :-------------------------------------------------------------------------------- |
22 | | `factory` | address | The contract address of the Uniswap V3 factory |
23 | | `token0` | address | The first token of the pool by address sort order |
24 | | `token1` | address | The second token of the pool by address sort order |
25 | | `fee` | uint24 | The fee collected upon every swap in the pool, denominated in hundredths of a bip |
26 | | `tickSpacing` | int24 | The spacing between usable ticks |
27 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/core/interfaces/IUniswapV3Pool.md:
--------------------------------------------------------------------------------
1 | A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
2 | to the ERC20 specification
3 |
4 | The pool interface is broken up into many smaller pieces
5 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/core/interfaces/IUniswapV3PoolDeployer.md:
--------------------------------------------------------------------------------
1 | A contract that constructs a pool must implement this to pass arguments to the pool
2 |
3 | This is used to avoid having constructor arguments in the pool contract, which results in the init code hash
4 | of the pool being constant allowing the CREATE2 address of the pool to be cheaply computed on-chain
5 |
6 | ## Functions
7 |
8 | ### parameters
9 |
10 | ```solidity
11 | function parameters(
12 | ) external view returns (address factory, address token0, address token1, uint24 fee, int24 tickSpacing)
13 | ```
14 |
15 | Get the parameters to be used in constructing the pool, set transiently during pool creation.
16 |
17 | #### Return Values :
18 |
19 | | Name | Type | Description |
20 | | :------------ | :------ | :-------------------------------------------------------------------------------- |
21 | | `factory ` | address | The factory address |
22 | | `token0` | address | The first token of the pool by address sort order |
23 | | `token1` | address | The second token of the pool by address sort order |
24 | | `fee ` | uint24 | The fee collected upon every swap in the pool, denominated in hundredths of a bip |
25 | | `tickSpacing` | int24 | The minimum number of ticks between initialized ticks |
26 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/core/interfaces/callback/IUniswapV3FlashCallback.md:
--------------------------------------------------------------------------------
1 | Any contract that calls IUniswapV3PoolActions#flash must implement this interface
2 |
3 | ## Functions
4 |
5 | ### uniswapV3FlashCallback
6 |
7 | ```solidity
8 | function uniswapV3FlashCallback(
9 | uint256 fee0,
10 | uint256 fee1,
11 | bytes data
12 | ) external
13 | ```
14 |
15 | Called to `msg.sender` after transferring to the recipient from IUniswapV3Pool#flash.
16 |
17 | In the implementation you must repay the pool the tokens sent by flash plus the computed fee amounts.
18 | The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
19 |
20 | #### Parameters:
21 |
22 | | Name | Type | Description |
23 | | :----- | :------ | :----------------------------------------------------------------------------- |
24 | | `fee0` | uint256 | The fee amount in token0 due to the pool by the end of the flash |
25 | | `fee1` | uint256 | The fee amount in token1 due to the pool by the end of the flash |
26 | | `data` | bytes | Any data passed through by the caller via the IUniswapV3PoolActions#flash call |
27 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/core/interfaces/callback/IUniswapV3MintCallback.md:
--------------------------------------------------------------------------------
1 | Any contract that calls IUniswapV3PoolActions#mint must implement this interface
2 |
3 | ## Functions
4 |
5 | ### uniswapV3MintCallback
6 |
7 | ```solidity
8 | function uniswapV3MintCallback(
9 | uint256 amount0Owed,
10 | uint256 amount1Owed,
11 | bytes data
12 | ) external
13 | ```
14 |
15 | Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.
16 |
17 | In the implementation you must pay the pool tokens owed for the minted liquidity.
18 | The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
19 |
20 | #### Parameters:
21 |
22 | | Name | Type | Description |
23 | | :------------ | :------ | :---------------------------------------------------------------------------- |
24 | | `amount0Owed` | uint256 | The amount of token0 due to the pool for the minted liquidity |
25 | | `amount1Owed` | uint256 | The amount of token1 due to the pool for the minted liquidity |
26 | | `data` | bytes | Any data passed through by the caller via the IUniswapV3PoolActions#mint call |
27 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/core/interfaces/callback/IUniswapV3SwapCallback.md:
--------------------------------------------------------------------------------
1 | Any contract that calls IUniswapV3PoolActions#swap must implement this interface
2 |
3 | ## Functions
4 |
5 | ### uniswapV3SwapCallback
6 |
7 | ```solidity
8 | function uniswapV3SwapCallback(
9 | int256 amount0Delta,
10 | int256 amount1Delta,
11 | bytes data
12 | ) external
13 | ```
14 |
15 | Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
16 |
17 | In the implementation you must pay the pool tokens owed for the swap.
18 | The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
19 | amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
20 |
21 | #### Parameters:
22 |
23 | | Name | Type | Description |
24 | | :------------- | :----- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
25 | | `amount0Delta` | int256 | The amount of token0 that was sent (negative) or must be received (positive) by the pool by the end of the swap. If positive, the callback must send that amount of token0 to the pool. |
26 | | `amount1Delta` | int256 | The amount of token1 that was sent (negative) or must be received (positive) by the pool by the end of the swap. If positive, the callback must send that amount of token1 to the pool. |
27 | | `data` | bytes | Any data passed through by the caller via the IUniswapV3PoolActions#swap call. |
28 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/core/interfaces/pool/IUniswapV3PoolImmutables.md:
--------------------------------------------------------------------------------
1 | These parameters are fixed for a pool forever, i.e., the methods will always return the same values
2 |
3 | ## Functions
4 |
5 | ### factory
6 |
7 | ```solidity
8 | function factory(
9 | ) external view returns (address)
10 | ```
11 |
12 | The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
13 |
14 | #### Return Values:
15 |
16 | | Type | Description |
17 | | :------ | :--------------- |
18 | | address | contract address |
19 |
20 | ### token0
21 |
22 | ```solidity
23 | function token0(
24 | ) external view returns (address)
25 | ```
26 |
27 | The first of the two tokens of the pool, sorted by address
28 |
29 | #### Return Values:
30 |
31 | | Type | Description |
32 | | :------ | :--------------------- |
33 | | address | token contract address |
34 |
35 | ### token1
36 |
37 | ```solidity
38 | function token1(
39 | ) external view returns (address)
40 | ```
41 |
42 | The second of the two tokens of the pool, sorted by address
43 |
44 | #### Return Values:
45 |
46 | | Type | Description |
47 | | :------ | :--------------------- |
48 | | address | token contract address |
49 |
50 | ### fee
51 |
52 | ```solidity
53 | function fee(
54 | ) external view returns (uint24)
55 | ```
56 |
57 | The pool's fee in hundredths of a bip, i.e. 1e-6
58 |
59 | #### Return Values:
60 |
61 | | Type | Description |
62 | | :----- | :---------- |
63 | | uint24 | fee |
64 |
65 | ### tickSpacing
66 |
67 | ```solidity
68 | function tickSpacing(
69 | ) external view returns (int24)
70 | ```
71 |
72 | The pool tick spacing
73 |
74 | Ticks can only be used at multiples of this value, minimum of 1 and always positive
75 | e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
76 | This value is an int24 to avoid casting even though it is always positive.
77 |
78 | #### Return Values:
79 |
80 | | Type | Description |
81 | | :---- | :----------- |
82 | | int24 | tick spacing |
83 |
84 | ### maxLiquidityPerTick
85 |
86 | ```solidity
87 | function maxLiquidityPerTick(
88 | ) external view returns (uint128)
89 | ```
90 |
91 | The maximum amount of position liquidity that can use any tick in the range
92 |
93 | This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
94 | also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
95 |
96 | #### Return Values:
97 |
98 | | Type | Description |
99 | | :------ | :------------------------------- |
100 | | uint128 | max amount of liquidity per tick |
101 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/core/interfaces/pool/IUniswapV3PoolOwnerActions.md:
--------------------------------------------------------------------------------
1 | Contains pool methods that may only be called by the factory owner
2 |
3 | ## Functions
4 |
5 | ### setFeeProtocol
6 |
7 | ```solidity
8 | function setFeeProtocol(
9 | uint8 feeProtocol0,
10 | uint8 feeProtocol1
11 | ) external
12 | ```
13 |
14 | Set the denominator of the protocol's % share of the fees
15 |
16 | #### Parameters:
17 |
18 | | Name | Type | Description |
19 | | :------------- | :---- | :-------------------------------------- |
20 | | `feeProtocol0` | uint8 | new protocol fee for token0 of the pool |
21 | | `feeProtocol1` | uint8 | new protocol fee for token1 of the pool |
22 |
23 | ### collectProtocol
24 |
25 | ```solidity
26 | function collectProtocol(
27 | address recipient,
28 | uint128 amount0Requested,
29 | uint128 amount1Requested
30 | ) external returns (uint128 amount0, uint128 amount1)
31 | ```
32 |
33 | Collect the protocol fee accrued to the pool
34 |
35 | #### Parameters:
36 |
37 | | Name | Type | Description |
38 | | :----------------- | :------ | :---------------------------------------------------------------------------- |
39 | | `recipient` | address | The address to which collected protocol fees should be sent |
40 | | `amount0Requested` | uint128 | The maximum amount of token0 to send, can be 0 to collect fees in only token1 |
41 | | `amount1Requested` | uint128 | The maximum amount of token1 to send, can be 0 to collect fees in only token0 |
42 |
43 | #### Return Values:
44 |
45 | | Name | Type | Description |
46 | | :-------- | :------ | :----------------------------------- |
47 | | `amount0` | uint128 | The protocol fee collected in token0 |
48 | | `amount1` | uint128 | The protocol fee collected in token1 |
49 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/core/libraries/BitMath.md:
--------------------------------------------------------------------------------
1 | This library provides functionality for computing bit properties of an unsigned integer
2 |
3 | ## Functions
4 |
5 | ### mostSignificantBit
6 |
7 | ```solidity
8 | function mostSignificantBit(
9 | uint256 x
10 | ) internal pure returns (uint8 r)
11 | ```
12 |
13 | Returns the index of the most significant bit of the number,
14 | where the least significant bit is at index 0 and the most significant bit is at index 255
15 |
16 | The function satisfies the property:
17 | x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1)
18 |
19 | #### Parameters:
20 |
21 | | Name | Type | Description |
22 | | :--- | :------ | :------------------------------------------------------------------------------ |
23 | | `x` | uint256 | the value for which to compute the most significant bit, must be greater than 0 |
24 |
25 | #### Return Values:
26 |
27 | | Name | Type | Description |
28 | | :--- | :---- | :------------------------------------ |
29 | | `r` | unit8 | the index of the most significant bit |
30 |
31 | ### leastSignificantBit
32 |
33 | ```solidity
34 | function leastSignificantBit(
35 | uint256 x
36 | ) internal pure returns (uint8 r)
37 | ```
38 |
39 | Returns the index of the least significant bit of the number,
40 | where the least significant bit is at index 0 and the most significant bit is at index 255
41 |
42 | The function satisfies the property:
43 | (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0)
44 |
45 | #### Parameters:
46 |
47 | | Name | Type | Description |
48 | | :--- | :------ | :------------------------------------------------------------------------------- |
49 | | `x` | uint256 | the value for which to compute the least significant bit, must be greater than 0 |
50 |
51 | #### Return Values:
52 |
53 | | Name | Type | Description |
54 | | :--- | :---- | :------------------------------------- |
55 | | `r` | unit8 | the index of the least significant bit |
56 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/core/libraries/FixedPoint128.md:
--------------------------------------------------------------------------------
1 | A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
2 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/core/libraries/FixedPoint96.md:
--------------------------------------------------------------------------------
1 | A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
2 |
3 | Used in SqrtPriceMath.sol
4 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/core/libraries/FullMath.md:
--------------------------------------------------------------------------------
1 | Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
2 |
3 | Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
4 |
5 | ## Functions
6 |
7 | ### mulDiv
8 |
9 | ```solidity
10 | function mulDiv(
11 | uint256 a,
12 | uint256 b,
13 | uint256 denominator
14 | ) internal pure returns (uint256 result)
15 | ```
16 |
17 | Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
18 |
19 | Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
20 |
21 | #### Parameters:
22 |
23 | | Name | Type | Description |
24 | | :------------ | :------ | :--------------- |
25 | | `a` | uint256 | The multiplicand |
26 | | `b` | uint256 | The multiplier |
27 | | `denominator` | uint256 | The divisor |
28 |
29 | #### Return Values:
30 |
31 | | Name | Type | Description |
32 | | :------- | :------ | :----------------- |
33 | | `result` | uint256 | The 256-bit result |
34 |
35 | ### mulDivRoundingUp
36 |
37 | ```solidity
38 | function mulDivRoundingUp(
39 | uint256 a,
40 | uint256 b,
41 | uint256 denominator
42 | ) internal pure returns (uint256 result)
43 | ```
44 |
45 | Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
46 |
47 | #### Parameters:
48 |
49 | | Name | Type | Description |
50 | | :------------ | :------ | :--------------- |
51 | | `a` | uint256 | The multiplicand |
52 | | `b` | uint256 | The multiplier |
53 | | `denominator` | uint256 | The divisor |
54 |
55 | #### Return Values:
56 |
57 | | Name | Type | Description |
58 | | :------- | :------ | :----------------- |
59 | | `result` | uint256 | The 256-bit result |
60 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/core/libraries/LiquidityMath.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### addDelta
4 |
5 | ```solidity
6 | function addDelta(
7 | uint128 x,
8 | int128 y
9 | ) internal pure returns (uint128 z)
10 | ```
11 |
12 | Add a signed liquidity delta to liquidity and revert if it overflows or underflows
13 |
14 | #### Parameters:
15 |
16 | | Name | Type | Description |
17 | | :--- | :------ | :--------------------------------------------- |
18 | | `x` | uint128 | The liquidity before change |
19 | | `y` | int128 | The delta by which liquidity should be changed |
20 |
21 | #### Return Values:
22 |
23 | | Name | Type | Description |
24 | | :--- | :------ | :------------------ |
25 | | `z` | uint128 | The liquidity delta |
26 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/core/libraries/Position.md:
--------------------------------------------------------------------------------
1 | Positions represent an owner address' liquidity between a lower and upper tick boundary
2 |
3 | Positions store additional state for tracking fees owed to the position
4 |
5 | ## Functions
6 |
7 | ### get
8 |
9 | ```solidity
10 | function get(
11 | mapping(bytes32 => struct Position.Info) self,
12 | address owner,
13 | int24 tickLower,
14 | int24 tickUpper
15 | ) internal view returns (struct Position.Info position)
16 | ```
17 |
18 | Returns the Info struct of a position, given an owner and position boundaries
19 |
20 | #### Parameters:
21 |
22 | | Name | Type | Description |
23 | | :---------- | :--------------------------------------- | :---------------------------------------- |
24 | | `self` | mapping(bytes32 => struct Position.Info) | The mapping containing all user positions |
25 | | `owner` | address | The address of the position owner |
26 | | `tickLower` | int24 | The lower tick boundary of the position |
27 | | `tickUpper` | int24 | The upper tick boundary of the position |
28 |
29 | #### Return Values:
30 |
31 | | Name | Type | Description |
32 | | :--------- | :------------------- | :----------------------------------------------------- |
33 | | `position` | struct Position.Info | The position info struct of the given owners' position |
34 |
35 | ### update
36 |
37 | ```solidity
38 | function update(
39 | struct Position.Info self,
40 | int128 liquidityDelta,
41 | uint256 feeGrowthInside0X128,
42 | uint256 feeGrowthInside1X128
43 | ) internal
44 | ```
45 |
46 | Credits accumulated fees to a user's position
47 |
48 | #### Parameters:
49 |
50 | | Name | Type | Description |
51 | | :--------------------- | :------------------- | :---------------------------------------------------------------------------------------------- |
52 | | `self` | struct Position.Info | The mapping containing all user positions |
53 | | `liquidityDelta` | int128 | The change in pool liquidity as a result of the position update |
54 | | `feeGrowthInside0X128` | uint256 | The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries |
55 | | `feeGrowthInside1X128` | uint256 | The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries |
56 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/core/libraries/SafeCast.md:
--------------------------------------------------------------------------------
1 | Contains methods for safely casting between types
2 |
3 | ## Functions
4 |
5 | ### toUint160
6 |
7 | ```solidity
8 | function toUint160(
9 | uint256 y
10 | ) internal pure returns (uint160 z)
11 | ```
12 |
13 | Cast a uint256 to a uint160, revert on overflow
14 |
15 | #### Parameters:
16 |
17 | | Name | Type | Description |
18 | | :--- | :------ | :--------------------------- |
19 | | `y` | uint256 | The uint256 to be downcasted |
20 |
21 | #### Return Values:
22 |
23 | | Name | Type | Description |
24 | | :--- | :------ | :--------------------------------------- |
25 | | `z` | uint160 | The downcasted integer, now type uint160 |
26 |
27 | ### toInt128
28 |
29 | ```solidity
30 | function toInt128(
31 | int256 y
32 | ) internal pure returns (int128 z)
33 | ```
34 |
35 | Cast a int256 to a int128, revert on overflow or underflow
36 |
37 | #### Parameters:
38 |
39 | | Name | Type | Description |
40 | | :--- | :----- | :-------------------------- |
41 | | `y` | int256 | The int256 to be downcasted |
42 |
43 | #### Return Values:
44 |
45 | | Name | Type | Description |
46 | | :--- | :----- | :-------------------------------------- |
47 | | `z` | int128 | The downcasted integer, now type int128 |
48 |
49 | ### toInt256
50 |
51 | ```solidity
52 | function toInt256(
53 | uint256 y
54 | ) internal pure returns (int256 z)
55 | ```
56 |
57 | Cast a uint256 to a int256, revert on overflow
58 |
59 | #### Parameters:
60 |
61 | | Name | Type | Description |
62 | | :--- | :------ | :----------------------- |
63 | | `y` | uint256 | The uint256 to be casted |
64 |
65 | #### Return Values:
66 |
67 | | Name | Type | Description |
68 | | :--- | :----- | :---------------------------------- |
69 | | `z` | int256 | The casted integer, now type int256 |
70 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/core/libraries/SwapMath.md:
--------------------------------------------------------------------------------
1 | Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick.
2 |
3 | ## Functions
4 |
5 | ### computeSwapStep
6 |
7 | ```solidity
8 | function computeSwapStep(
9 | uint160 sqrtRatioCurrentX96,
10 | uint160 sqrtRatioTargetX96,
11 | uint128 liquidity,
12 | int256 amountRemaining,
13 | uint24 feePips
14 | ) internal pure returns (uint160 sqrtRatioNextX96, uint256 amountIn, uint256 amountOut, uint256 feeAmount)
15 | ```
16 |
17 | Computes the result of swapping some amount in, or amount out, given the parameters of the swap
18 |
19 | The fee, plus the amount in, will never exceed the amount remaining if the swap's `amountSpecified` is positive
20 |
21 | #### Parameters:
22 |
23 | | Name | Type | Description |
24 | | :-------------------- | :------ | :---------------------------------------------------------------------------------- |
25 | | `sqrtRatioCurrentX96` | uint160 | The current sqrt price of the pool |
26 | | `sqrtRatioTargetX96` | uint160 | The price that cannot be exceeded, from which the direction of the swap is inferred |
27 | | `liquidity` | uint128 | The usable liquidity |
28 | | `amountRemaining` | int256 | How much input or output amount is remaining to be swapped in/out |
29 | | `feePips` | uint24 | The fee taken from the input amount, expressed in hundredths of a bip |
30 |
31 | #### Return Values:
32 |
33 | | Name | Type | Description |
34 | | :----------------- | :------ | :------------------------------------------------------------------------------------------ |
35 | | `sqrtRatioNextX96` | uint160 | The price after swapping the amount in/out, not to exceed the price target |
36 | | `amountIn` | uint256 | The amount to be swapped in, of either token0 or token1, based on the direction of the swap |
37 | | `amountOut` | uint256 | The amount to be received, of either token0 or token1, based on the direction of the swap |
38 | | `feeAmount` | uint256 | The amount of input that will be taken as a fee |
39 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/core/libraries/TickMath.md:
--------------------------------------------------------------------------------
1 | Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
2 | prices between 2**-128 and 2**128
3 |
4 | ## Functions
5 |
6 | ### getSqrtRatioAtTick
7 |
8 | ```solidity
9 | function getSqrtRatioAtTick(
10 | int24 tick
11 | ) internal pure returns (uint160 sqrtPriceX96)
12 | ```
13 |
14 | Calculates sqrt(1.0001^tick) \* 2^96
15 |
16 | Throws if |tick| > max tick
17 |
18 | #### Parameters:
19 |
20 | | Name | Type | Description |
21 | | :----- | :---- | :----------------------------------- |
22 | | `tick` | int24 | The input tick for the above formula |
23 |
24 | #### Return Values:
25 |
26 | | Name | Type | Description |
27 | | :------------- | :------ | :----------------------------------------------------------------------------------------------- |
28 | | `sqrtPriceX96` | uint160 | A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) |
29 |
30 | at the given tick
31 |
32 | ### getTickAtSqrtRatio
33 |
34 | ```solidity
35 | function getTickAtSqrtRatio(
36 | uint160 sqrtPriceX96
37 | ) internal pure returns (int24 tick)
38 | ```
39 |
40 | Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
41 |
42 | Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
43 | ever return.
44 |
45 | #### Parameters:
46 |
47 | | Name | Type | Description |
48 | | :------------- | :------ | :------------------------------------------------------- |
49 | | `sqrtPriceX96` | uint160 | The sqrt ratio for which to compute the tick as a Q64.96 |
50 |
51 | #### Return Values:
52 |
53 | | Name | Type | Description |
54 | | :----- | :---- | :----------------------------------------------------------------------------- |
55 | | `tick` | int24 | The greatest tick for which the ratio is less than or equal to the input ratio |
56 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/core/libraries/TransferHelper.md:
--------------------------------------------------------------------------------
1 | Contains helper methods for interacting with ERC20 tokens that do not consistently return true/false
2 |
3 | ## Functions
4 |
5 | ### safeTransfer
6 |
7 | ```solidity
8 | function safeTransfer(
9 | address token,
10 | address to,
11 | uint256 value
12 | ) internal
13 | ```
14 |
15 | Transfers tokens from msg.sender to a recipient
16 |
17 | Calls transfer on token contract, errors with TF if transfer fails
18 |
19 | #### Parameters:
20 |
21 | | Name | Type | Description |
22 | | :------ | :------ | :---------------------------------------------------------- |
23 | | `token` | address | The contract address of the token which will be transferred |
24 | | `to` | address | The recipient of the transfer |
25 | | `value` | uint256 | The value of the transfer |
26 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/core/libraries/UnsafeMath.md:
--------------------------------------------------------------------------------
1 | Contains methods that perform common math functions but do not do any overflow or underflow checks
2 |
3 | ## Functions
4 |
5 | ### divRoundingUp
6 |
7 | ```solidity
8 | function divRoundingUp(
9 | uint256 x,
10 | uint256 y
11 | ) internal pure returns (uint256 z)
12 | ```
13 |
14 | Returns ceil(x / y)
15 |
16 | panics if y == 0
17 |
18 | #### Parameters:
19 |
20 | | Name | Type | Description |
21 | | :--- | :------ | :----------- |
22 | | `x` | uint256 | The dividend |
23 | | `y` | uint256 | The divisor |
24 |
25 | #### Return Values:
26 |
27 | | Name | Type | Description |
28 | | :--- | :------ | :------------------------ |
29 | | `z` | uint256 | The quotient, ceil(x / y) |
30 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/error-codes.md:
--------------------------------------------------------------------------------
1 | ---
2 | id: error-codes
3 | title: Error Codes
4 | ---
5 |
6 | LiquidityMath.sol
7 |
8 | - `LS`: Liquidity Sub
9 | - `LA`: Liquidity Add
10 |
11 | Oracle.sol
12 |
13 | - `OLD`: The target must be chronologically after the oldest observation
14 |
15 | - `I`: The pool has not been initialized
16 |
17 | Position.sol
18 |
19 | - `NP`: Burn cannot be called for a position with 0 liquidity
20 |
21 | Tick.sol
22 |
23 | - `LO`: LiquidityGrossAfter must be less than MaxLiquidity
24 |
25 | TickMath.sol
26 |
27 | - `T`: The given tick must be less than, or equal to, the maximum tick
28 | - `R`: second inequality must be < because the price can never reach the price at the max tick
29 |
30 | TransferHelper.sol
31 |
32 | - `TF`: Transfer Failed : errors with TF if transfer fails
33 |
34 | UniswapV3Pool.sol
35 |
36 | - `LOK`: The reentrancy guard. A transaction cannot re-enter the pool mid-swap
37 |
38 | - `TLU`: The lower tick must be below the upper tick
39 | - `TLM`: The lower tick must be greater, or equal to, the minimum tick
40 | - `TUM`: The upper tick must be lesser than, or equal to, the maximum tick
41 | - `AI`: The pool is already initialized
42 | - `M0`: Mint 0, The balance of token0 in the given pool before minting must be less than, or equal to, the balance after minting
43 | - `M1`: Mint 1, The balance of token1 in the given pool before minting must be less than, or equal to, the balance after minting
44 | - `AS`: `amountSpecified` cannot be zero
45 | - `SPL`: Square root price limit
46 | - `IIA`: Insufficient input amount, an insufficient amount of input token was sent during the callback
47 | - `L`: Liquidity in the pool must be greater than zero for a flash to be executed
48 | - `F0`: The balance of token0 in the given pool before the flash transaction must be less than, or equal to, the balance of token0 after the flash plus the fee
49 | - `F1`: The balance of token1 in the given pool before the flash transaction must be less than, or equal to, the balance of token1 after the flash plus the fee
50 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/NonfungibleTokenPositionDescriptor.md:
--------------------------------------------------------------------------------
1 | Produces a string containing the data URI for a JSON metadata string
2 |
3 | ## Functions
4 |
5 | ### constructor
6 |
7 | ```solidity
8 | function constructor(
9 | ) public
10 | ```
11 |
12 | ### tokenURI
13 |
14 | ```solidity
15 | function tokenURI(
16 | contract INonfungiblePositionManager positionManager,
17 | uint256 tokenId
18 | ) external returns (string)
19 | ```
20 |
21 | Produces the URI describing a particular token ID for a position manager
22 |
23 | Note this URI may be a data: URI with the JSON contents directly inlined
24 |
25 | #### Parameters:
26 |
27 | | Name | Type | Description |
28 | | :---------------- | :----------------------------------- | :----------------------------------------------------------------------------- |
29 | | `positionManager` | contract INonfungiblePositionManager | The position manager for which to describe the token |
30 | | `tokenId` | uint256 | The ID of the token for which to produce a description, which may not be valid |
31 |
32 | #### Return Values:
33 |
34 | | Name | Type | Description |
35 | | :---- | :----------------------------------- | :----------------------------------- |
36 | | `The` | contract INonfungiblePositionManager | URI of the ERC721-compliant metadata |
37 |
38 | ### flipRatio
39 |
40 | ```solidity
41 | function flipRatio(
42 | ) public returns (bool)
43 | ```
44 |
45 | ### tokenRatioPriority
46 |
47 | ```solidity
48 | function tokenRatioPriority(
49 | ) public returns (int256)
50 | ```
51 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/V3Migrator.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### constructor
4 |
5 | ```solidity
6 | function constructor(
7 | ) public
8 | ```
9 |
10 | ### receive
11 |
12 | ```solidity
13 | function receive(
14 | ) external
15 | ```
16 |
17 | ### migrate
18 |
19 | ```solidity
20 | function migrate(
21 | ) external
22 | ```
23 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/base/BlockTimestamp.md:
--------------------------------------------------------------------------------
1 | Base contract that is overridden for tests
2 |
3 | ## Functions
4 |
5 | ### \_blockTimestamp
6 |
7 | ```solidity
8 | function _blockTimestamp(
9 | ) internal view returns (uint256)
10 | ```
11 |
12 | Method that exists purely to be overridden for tests
13 |
14 | #### Return Values:
15 |
16 | | Type | Description |
17 | | :------ | :---------------------- |
18 | | uint256 | current block timestamp |
19 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/base/ERC721Permit.md:
--------------------------------------------------------------------------------
1 | Nonfungible tokens that support an approve via signature, i.e. permit
2 |
3 | ## Functions
4 |
5 | ### \_getAndIncrementNonce
6 |
7 | ```solidity
8 | function _getAndIncrementNonce(
9 | uint256 tokenId
10 | ) internal virtual returns (uint256)
11 | ```
12 |
13 | Gets the current nonce for a token ID and then increments it, returning the original value
14 |
15 | ### constructor
16 |
17 | ```solidity
18 | function constructor(
19 | string memory name_,
20 | string memory symbol_,
21 | string memory version_
22 | ) internal
23 | ```
24 |
25 | Computes the nameHash and versionHash
26 |
27 | ### DOMAIN_SEPARATOR
28 |
29 | ```solidity
30 | function DOMAIN_SEPARATOR(
31 | ) public view override returns (bytes32)
32 | ```
33 |
34 | The domain separator used in the permit signature
35 |
36 | #### Return Values:
37 |
38 | | Type | Description |
39 | | :------ | :---------------------------------------------------- |
40 | | bytes32 | domain seperator used in encoding of permit signature |
41 |
42 | ### permit
43 |
44 | ```solidity
45 | function permit(
46 | address spender,
47 | uint256 tokenId,
48 | uint256 deadline,
49 | uint8 v,
50 | bytes32 r,
51 | bytes32 s
52 | ) external
53 | ```
54 |
55 | Approve of a specific token ID for spending by spender via signature
56 |
57 | #### Parameters:
58 |
59 | | Name | Type | Description |
60 | | :--------- | :------ | :----------------------------------------------------------------------------- |
61 | | `spender` | address | The account that is being approved |
62 | | `tokenId` | uint256 | The ID of the token that is being approved for spending |
63 | | `deadline` | uint256 | The deadline timestamp by which the call must be mined for the approve to work |
64 | | `v` | uint8 | Must produce valid secp256k1 signature from the holder along with `r` and `s` |
65 | | `r` | bytes32 | Must produce valid secp256k1 signature from the holder along with `v` and `s` |
66 | | `s` | bytes32 | Must produce valid secp256k1 signature from the holder along with `r` and `v` |
67 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/base/LiquidityManagement.md:
--------------------------------------------------------------------------------
1 | Internal functions for safely managing liquidity in Uniswap V3
2 |
3 | ## Parameter Structs
4 |
5 | ### AddLiquidityParams
6 |
7 | ```solidity
8 | struct AddLiquidityParams {
9 | address token0;
10 | address token1;
11 | uint24 fee;
12 | address recipient;
13 | int24 tickLower;
14 | int24 tickUpper;
15 | uint256 amount0Desired;
16 | uint256 amount1Desired;
17 | uint256 amount0Min;
18 | uint256 amount1Min;
19 | }
20 | ```
21 |
22 | ## Functions
23 |
24 | ### uniswapV3MintCallback
25 |
26 | ```solidity
27 | function uniswapV3MintCallback(
28 | uint256 amount0Owed,
29 | uint256 amount1Owed,
30 | bytes data
31 | ) external
32 | ```
33 |
34 | Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.
35 |
36 | In the implementation you must pay the pool tokens owed for the minted liquidity.
37 | The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
38 |
39 | #### Parameters:
40 |
41 | | Name | Type | Description |
42 | | :------------ | :------ | :---------------------------------------------------------------------------- |
43 | | `amount0Owed` | uint256 | The amount of token0 due to the pool for the minted liquidity |
44 | | `amount1Owed` | uint256 | The amount of token1 due to the pool for the minted liquidity |
45 | | `data` | bytes | Any data passed through by the caller via the IUniswapV3PoolActions#mint call |
46 |
47 | ### addLiquidity
48 |
49 | ```solidity
50 | function addLiquidity(
51 | AddLiquidityParams memory params
52 | ) internal returns (uint128 liquidity, uint256 amount0, uint256 amount1, contract IUniswapV3Pool pool)
53 | ```
54 |
55 | Add liquidity to an initialized pool
56 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/base/Multicall.md:
--------------------------------------------------------------------------------
1 | Enables calling multiple methods in a single call to the contract
2 |
3 | ## Functions
4 |
5 | ### multicall
6 |
7 | ```solidity
8 | function multicall(
9 | bytes[] data
10 | ) external payable override returns (bytes[] results)
11 | ```
12 |
13 | Call multiple functions in the current contract and return the data from all of them if they all succeed
14 |
15 | The `msg.value` should not be trusted for any method callable from multicall.
16 |
17 | #### Parameters:
18 |
19 | | Name | Type | Description |
20 | | :----- | :------ | :----------------------------------------------------------------------- |
21 | | `data` | bytes[] | The encoded function data for each of the calls to make to this contract |
22 |
23 | #### Return Values:
24 |
25 | | Name | Type | Description |
26 | | :-------- | :------ | :---------------------------------------------------- |
27 | | `results` | bytes[] | The results from each of the calls passed in via data |
28 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/base/PeripheryImmutableState.md:
--------------------------------------------------------------------------------
1 | Immutable state used by periphery contracts
2 |
3 | ## Functions
4 |
5 | ### constructor
6 |
7 | ```solidity
8 | function constructor(
9 | address _factory, address _WETH9
10 | ) internal
11 | ```
12 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/base/PeripheryPayments.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### receive
4 |
5 | ```solidity
6 | function receive(
7 | ) external
8 | ```
9 |
10 | ### unwrapWETH9
11 |
12 | ```solidity
13 | function unwrapWETH9(
14 | uint256 amountMinimum,
15 | address recipient
16 | ) external
17 | ```
18 |
19 | Unwraps the contract's WETH9 balance and sends it to recipient as ETH.
20 |
21 | The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.
22 |
23 | #### Parameters:
24 |
25 | | Name | Type | Description |
26 | | :-------------- | :------ | :------------------------------------ |
27 | | `amountMinimum` | uint256 | The minimum amount of WETH9 to unwrap |
28 | | `recipient` | address | The address receiving ETH |
29 |
30 | ### sweepToken
31 |
32 | ```solidity
33 | function sweepToken(
34 | address token,
35 | uint256 amountMinimum,
36 | address recipient
37 | ) external
38 | ```
39 |
40 | Transfers the full amount of a token held by this contract to recipient
41 |
42 | The amountMinimum parameter prevents malicious contracts from stealing the token from users
43 |
44 | #### Parameters:
45 |
46 | | Name | Type | Description |
47 | | :-------------- | :------ | :------------------------------------------------------------------------- |
48 | | `token` | address | The contract address of the token which will be transferred to `recipient` |
49 | | `amountMinimum` | uint256 | The minimum amount of token required for a transfer |
50 | | `recipient` | address | The destination address of the token |
51 |
52 | ### refundETH
53 |
54 | ```solidity
55 | function refundETH(
56 | ) external
57 | ```
58 |
59 | Refunds any ETH balance held by this contract to the `msg.sender`
60 |
61 | Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
62 | that use ether for the input amount
63 |
64 | ### pay
65 |
66 | ```solidity
67 | function pay(
68 | address token,
69 | address payer,
70 | address recipient,
71 | uint256 value
72 | ) internal
73 | ```
74 |
75 | #### Parameters:
76 |
77 | | Name | Type | Description |
78 | | :---------- | :------ | :----------------------------------- |
79 | | `token` | address | The token to pay |
80 | | `payer` | address | The entity that must pay |
81 | | `recipient` | address | The entity that will receive payment |
82 | | `value` | uint256 | The amount to pay |
83 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/base/PeripheryPaymentsWithFee.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### unwrapWETH9WithFee
4 |
5 | ```solidity
6 | function unwrapWETH9WithFee(
7 | uint256 amountMinimum,
8 | address recipient,
9 | uint256 feeBips,
10 | address feeRecipient
11 | ) public
12 | ```
13 |
14 | Unwraps the contract's WETH9 balance and sends it to recipient as ETH, with a percentage between
15 | 0 (exclusive), and 1 (inclusive) going to feeRecipient
16 |
17 | The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.
18 |
19 | ### sweepTokenWithFee
20 |
21 | ```solidity
22 | function sweepTokenWithFee(
23 | address token,
24 | uint256 amountMinimum,
25 | address recipient,
26 | uint256 feeBips,
27 | address feeRecipient
28 | ) public
29 | ```
30 |
31 | Transfers the full amount of a token held by this contract to recipient, with a percentage between
32 | 0 (exclusive) and 1 (inclusive) going to feeRecipient
33 |
34 | The amountMinimum parameter prevents malicious contracts from stealing the token from users
35 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/base/PoolInitializer.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### createAndInitializePoolIfNecessary
4 |
5 | ```solidity
6 | function createAndInitializePoolIfNecessary(
7 | address token0,
8 | address token1,
9 | uint24 fee,
10 | uint160 sqrtPriceX96
11 | ) external returns (address pool)
12 | ```
13 |
14 | Creates a new pool if it does not exist, then initializes if not initialized
15 |
16 | This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool
17 |
18 | #### Parameters:
19 |
20 | | Name | Type | Description |
21 | | :------------- | :------ | :---------------------------------------------------------- |
22 | | `token0` | address | The contract address of token0 of the pool |
23 | | `token1` | address | The contract address of token1 of the pool |
24 | | `fee` | uint24 | The fee amount of the v3 pool for the specified token pair |
25 | | `sqrtPriceX96` | uint160 | The initial square root price of the pool as a Q64.96 value |
26 |
27 | #### Return Values:
28 |
29 | | Name | Type | Description |
30 | | :----- | :------ | :-------------------------------------------------------------------------------------------------------------------- |
31 | | `pool` | address | Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary |
32 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/interfaces/IERC20Metadata.md:
--------------------------------------------------------------------------------
1 | Extension to IERC20 that includes token metadata
2 |
3 | ## Functions
4 |
5 | ### name
6 |
7 | ```solidity
8 | function name(
9 | ) external returns (string)
10 | ```
11 |
12 | #### Return Values:
13 |
14 | | Type | Description |
15 | | :----- | :---------------- |
16 | | string | name of the token |
17 |
18 | ### symbol
19 |
20 | ```solidity
21 | function symbol(
22 | ) external returns (string)
23 | ```
24 |
25 | #### Return Values:
26 |
27 | | Type | Description |
28 | | :----- | :------------------ |
29 | | string | symbol of the token |
30 |
31 | ### decimals
32 |
33 | ```solidity
34 | function decimals(
35 | ) external returns (uint8)
36 | ```
37 |
38 | #### Return Values:
39 |
40 | | Type | Description |
41 | | :---- | :------------------------------------- |
42 | | uint8 | number of decimal places the token has |
43 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/interfaces/IERC721Permit.md:
--------------------------------------------------------------------------------
1 | Extension to ERC721 that includes a permit function for signature based approvals
2 |
3 | ## Functions
4 |
5 | ### PERMIT_TYPEHASH
6 |
7 | ```solidity
8 | function PERMIT_TYPEHASH(
9 | ) external returns (bytes32)
10 | ```
11 |
12 | The permit typehash used in the permit signature
13 |
14 | #### Return Values:
15 |
16 | | Type | Description |
17 | | :------ | :---------------------- |
18 | | bytes32 | typehash for the permit |
19 |
20 | ### DOMAIN_SEPARATOR
21 |
22 | ```solidity
23 | function DOMAIN_SEPARATOR(
24 | ) external returns (bytes32)
25 | ```
26 |
27 | The domain separator used in the permit signature
28 |
29 | #### Return Values:
30 |
31 | | Name | Type | Description |
32 | | :---- | :--- | :---------------------------------------------------- |
33 | | `The` | | domain seperator used in encoding of permit signature |
34 |
35 | ### permit
36 |
37 | ```solidity
38 | function permit(
39 | address spender,
40 | uint256 tokenId,
41 | uint256 deadline,
42 | uint8 v,
43 | bytes32 r,
44 | bytes32 s
45 | ) external
46 | ```
47 |
48 | Approve of a specific token ID for spending by spender via signature
49 |
50 | #### Parameters:
51 |
52 | | Name | Type | Description |
53 | | :--------- | :------ | :----------------------------------------------------------------------------- |
54 | | `spender` | address | The account that is being approved |
55 | | `tokenId` | uint256 | The ID of the token that is being approved for spending |
56 | | `deadline` | uint256 | The deadline timestamp by which the call must be mined for the approve to work |
57 | | `v` | uint8 | Must produce valid secp256k1 signature from the holder along with `r` and `s` |
58 | | `r` | bytes32 | Must produce valid secp256k1 signature from the holder along with `v` and `s` |
59 | | `s` | bytes32 | Must produce valid secp256k1 signature from the holder along with `r` and `v` |
60 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/interfaces/IMulticall.md:
--------------------------------------------------------------------------------
1 | Enables calling multiple methods in a single call to the contract
2 |
3 | ## Functions
4 |
5 | ### multicall
6 |
7 | ```solidity
8 | function multicall(
9 | bytes[] data
10 | ) external returns (bytes[] results)
11 | ```
12 |
13 | Call multiple functions in the current contract and return the data from all of them if they all succeed
14 |
15 | The `msg.value` should not be trusted for any method callable from multicall.
16 |
17 | #### Parameters:
18 |
19 | | Name | Type | Description |
20 | | :----- | :------ | :----------------------------------------------------------------------- |
21 | | `data` | bytes[] | The encoded function data for each of the calls to make to this contract |
22 |
23 | #### Return Values:
24 |
25 | | Name | Type | Description |
26 | | :-------- | :------ | :---------------------------------------------------- |
27 | | `results` | bytes[] | The results from each of the calls passed in via data |
28 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/interfaces/INonfungibleTokenPositionDescriptor.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### tokenURI
4 |
5 | ```solidity
6 | function tokenURI(
7 | contract INonfungiblePositionManager positionManager,
8 | uint256 tokenId
9 | ) external returns (string)
10 | ```
11 |
12 | Produces the URI describing a particular token ID for a position manager
13 |
14 | Note this URI may be a data: URI with the JSON contents directly inlined
15 |
16 | #### Parameters:
17 |
18 | | Name | Type | Description |
19 | | :---------------- | :----------------------------------- | :----------------------------------------------------------------------------- |
20 | | `positionManager` | contract INonfungiblePositionManager | The position manager for which to describe the token |
21 | | `tokenId` | uint256 | The ID of the token for which to produce a description, which may not be valid |
22 |
23 | #### Return Values:
24 |
25 | | Type | Description |
26 | | :----- | :----------------------------------- |
27 | | string | URI of the ERC721-compliant metadata |
28 |
29 | ## Events
30 |
31 | ### UpdateTokenRatioPriority
32 |
33 | ```solidity
34 | event UpdateTokenRatioPriority(
35 | address token,
36 | int256 priority
37 | )
38 | ```
39 |
40 | Emitted when a token is given a new priority order in the displayed price ratio
41 |
42 | #### Parameters:
43 |
44 | | Name | Type | Description |
45 | | :--------- | :------ | :-------------------------------------------------------------------- |
46 | | `token` | address | The token being given priority order |
47 | | `priority` | int256 | Represents priority in ratio - higher integers get numerator priority |
48 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/interfaces/IPeripheryImmutableState.md:
--------------------------------------------------------------------------------
1 | Functions that return immutable state of the router
2 |
3 | ## Functions
4 |
5 | ### factory
6 |
7 | ```solidity
8 | function factory(
9 | ) external returns (address)
10 | ```
11 |
12 | #### Return Values:
13 |
14 | | Type | Description |
15 | | :------ | :------------------------------------ |
16 | | address | the address of the Uniswap V3 factory |
17 |
18 | ### WETH9
19 |
20 | ```solidity
21 | function WETH9(
22 | ) external returns (address)
23 | ```
24 |
25 | #### Return Values:
26 |
27 | | Type | Description |
28 | | :------ | :------------------- |
29 | | address | the address of WETH9 |
30 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/interfaces/IPeripheryPayments.md:
--------------------------------------------------------------------------------
1 | Functions to ease deposits and withdrawals of ETH
2 |
3 | ## Functions
4 |
5 | ### unwrapWETH9
6 |
7 | ```solidity
8 | function unwrapWETH9(
9 | uint256 amountMinimum,
10 | address recipient
11 | ) external
12 | ```
13 |
14 | Unwraps the contract's WETH9 balance and sends it to recipient as ETH.
15 |
16 | The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.
17 |
18 | #### Parameters:
19 |
20 | | Name | Type | Description |
21 | | :-------------- | :------ | :------------------------------------ |
22 | | `amountMinimum` | uint256 | The minimum amount of WETH9 to unwrap |
23 | | `recipient` | address | The address receiving ETH |
24 |
25 | ### refundETH
26 |
27 | ```solidity
28 | function refundETH(
29 | ) external
30 | ```
31 |
32 | Refunds any ETH balance held by this contract to the `msg.sender`
33 |
34 | Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
35 | that use ether for the input amount
36 |
37 | ### sweepToken
38 |
39 | ```solidity
40 | function sweepToken(
41 | address token,
42 | uint256 amountMinimum,
43 | address recipient
44 | ) external
45 | ```
46 |
47 | Transfers the full amount of a token held by this contract to recipient
48 |
49 | The amountMinimum parameter prevents malicious contracts from stealing the token from users
50 |
51 | #### Parameters:
52 |
53 | | Name | Type | Description |
54 | | :-------------- | :------ | :------------------------------------------------------------------------- |
55 | | `token` | address | The contract address of the token which will be transferred to `recipient` |
56 | | `amountMinimum` | uint256 | The minimum amount of token required for a transfer |
57 | | `recipient` | address | The destination address of the token |
58 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/interfaces/IPeripheryPaymentsWithFee.md:
--------------------------------------------------------------------------------
1 | Functions to ease deposits and withdrawals of ETH
2 |
3 | ## Functions
4 |
5 | ### unwrapWETH9WithFee
6 |
7 | ```solidity
8 | function unwrapWETH9WithFee(
9 | ) external
10 | ```
11 |
12 | Unwraps the contract's WETH9 balance and sends it to recipient as ETH, with a percentage between
13 | 0 (exclusive), and 1 (inclusive) going to feeRecipient
14 |
15 | The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.
16 |
17 | ### sweepTokenWithFee
18 |
19 | ```solidity
20 | function sweepTokenWithFee(
21 | ) external
22 | ```
23 |
24 | Transfers the full amount of a token held by this contract to recipient, with a percentage between
25 | 0 (exclusive) and 1 (inclusive) going to feeRecipient
26 |
27 | The amountMinimum parameter prevents malicious contracts from stealing the token from users
28 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/interfaces/IPoolInitializer.md:
--------------------------------------------------------------------------------
1 | Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that
2 | require the pool to exist.
3 |
4 | ## Functions
5 |
6 | ### createAndInitializePoolIfNecessary
7 |
8 | ```solidity
9 | function createAndInitializePoolIfNecessary(
10 | address token0,
11 | address token1,
12 | uint24 fee,
13 | uint160 sqrtPriceX96
14 | ) external returns (address pool)
15 | ```
16 |
17 | Creates a new pool if it does not exist, then initializes if not initialized
18 |
19 | This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool
20 |
21 | #### Parameters:
22 |
23 | | Name | Type | Description |
24 | | :------------- | :------ | :---------------------------------------------------------- |
25 | | `token0` | address | The contract address of token0 of the pool |
26 | | `token1` | address | The contract address of token1 of the pool |
27 | | `fee` | uint24 | The fee amount of the v3 pool for the specified token pair |
28 | | `sqrtPriceX96` | uint160 | The initial square root price of the pool as a Q64.96 value |
29 |
30 | #### Return Values:
31 |
32 | | Name | Type | Description |
33 | | :----- | :------ | :-------------------------------------------------------------------------------------------------------------------- |
34 | | `pool` | address | Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary |
35 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/interfaces/ITickLens.md:
--------------------------------------------------------------------------------
1 | Provides functions for fetching chunks of tick data for a pool
2 |
3 | This avoids the waterfall of fetching the tick bitmap, parsing the bitmap to know which ticks to fetch, and
4 | then sending additional multicalls to fetch the tick data
5 |
6 | ## Functions
7 |
8 | ### getPopulatedTicksInWord
9 |
10 | ```solidity
11 | function getPopulatedTicksInWord(
12 | address pool,
13 | int16 tickBitmapIndex
14 | ) external returns (struct ITickLens.PopulatedTick[] populatedTicks)
15 | ```
16 |
17 | Get all the tick data for the populated ticks from a word of the tick bitmap of a pool
18 |
19 | #### Parameters:
20 |
21 | | Name | Type | Description |
22 | | :---------------- | :------ | :------------------------------------------------------------------------------------------------------- |
23 | | `pool` | address | The address of the pool for which to fetch populated tick data |
24 | | `tickBitmapIndex` | int16 | The index of the word in the tick bitmap for which to parse the bitmap and fetch all the populated ticks |
25 |
26 | #### Return Values:
27 |
28 | | Name | Type | Description |
29 | | :--------------- | :------------------------ | :---------------------------------------------------------- |
30 | | `populatedTicks` | ITickLens.PopulatedTick[] | An array of tick data for the given word in the tick bitmap |
31 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/interfaces/IV3Migrator.md:
--------------------------------------------------------------------------------
1 | Enables migration of liqudity from Uniswap v2-compatible pairs into Uniswap v3 pools
2 |
3 | ## Functions
4 |
5 | ### migrate
6 |
7 | ```solidity
8 | function migrate(
9 | struct IV3Migrator.MigrateParams params
10 | ) external
11 | ```
12 |
13 | Migrates liquidity to v3 by burning v2 liquidity and minting a new position for v3
14 |
15 | Slippage protection is enforced via `amount{0,1}Min`, which should be a discount of the expected values of
16 | the maximum amount of v3 liquidity that the v2 liquidity can get. For the special case of migrating to an
17 | out-of-range position, `amount{0,1}Min` may be set to 0, enforcing that the position remains out of range
18 |
19 | #### Parameters:
20 |
21 | | Name | Type | Description |
22 | | :------- | :------------------------------- | :----------------------------------------------------------------------------------- |
23 | | `params` | struct IV3Migrator.MigrateParams | The params necessary to migrate v2 liquidity, encoded as `MigrateParams` in calldata |
24 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/interfaces/external/IERC1271.md:
--------------------------------------------------------------------------------
1 | Interface that verifies provided signature for the data
2 |
3 | Interface defined by EIP-1271
4 |
5 | ## Functions
6 |
7 | ### isValidSignature
8 |
9 | ```solidity
10 | function isValidSignature(
11 | bytes32 hash,
12 | bytes signature
13 | ) external returns (bytes4 magicValue)
14 | ```
15 |
16 | Returns whether the provided signature is valid for the provided data
17 |
18 | MUST return the bytes4 magic value 0x1626ba7e when function passes.
19 | MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5).
20 | MUST allow external calls.
21 |
22 | #### Parameters:
23 |
24 | | Name | Type | Description |
25 | | :---------- | :------ | :------------------------------------------ |
26 | | `hash` | bytes32 | Hash of the data to be signed |
27 | | `signature` | bytes | Signature byte array associated with \_data |
28 |
29 | #### Return Values:
30 |
31 | | Name | Type | Description |
32 | | :----------- | :------ | :-------------------------------- |
33 | | `magicValue` | bytes32 | The bytes4 magic value 0x1626ba7e |
34 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/interfaces/external/IERC20PermitAllowed.md:
--------------------------------------------------------------------------------
1 | Interface used by DAI/CHAI for permit
2 |
3 | ## Functions
4 |
5 | ### permit
6 |
7 | ```solidity
8 | function permit(
9 | address holder,
10 | address spender,
11 | uint256 nonce,
12 | uint256 expiry,
13 | bool allowed,
14 | uint8 v,
15 | bytes32 r,
16 | bytes32 s
17 | ) external
18 | ```
19 |
20 | Approve the spender to spend some tokens via the holder signature
21 |
22 | This is the permit interface used by DAI and CHAI
23 |
24 | #### Parameters:
25 |
26 | | Name | Type | Description |
27 | | :-------- | :------ | :---------------------------------------------------------------------------- |
28 | | `holder` | address | The address of the token holder, the token owner |
29 | | `spender` | address | The address of the token spender |
30 | | `nonce` | uint256 | The holder's nonce, increases at each call to permit |
31 | | `expiry` | uint256 | The timestamp at which the permit is no longer valid |
32 | | `allowed` | bool | Boolean that sets approval amount, true for type(uint256).max and false for 0 |
33 | | `v` | uint8 | Must produce valid secp256k1 signature from the holder along with `r` and `s` |
34 | | `r` | bytes32 | Must produce valid secp256k1 signature from the holder along with `v` and `s` |
35 | | `s` | bytes32 | Must produce valid secp256k1 signature from the holder along with `r` and `v` |
36 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/interfaces/external/IWETH9.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### deposit
4 |
5 | ```solidity
6 | function deposit(
7 | ) external
8 | ```
9 |
10 | Deposit ether to get wrapped ether
11 |
12 | ### withdraw
13 |
14 | ```solidity
15 | function withdraw(
16 | ) external
17 | ```
18 |
19 | Withdraw wrapped ether to get ether
20 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/lens/QuoterV2.md:
--------------------------------------------------------------------------------
1 | Allows getting the expected amount out or amount in for a given swap without executing the swap
2 |
3 | These functions are not gas efficient and should _not_ be called on chain. Instead, optimistically execute
4 | the swap and check the amounts in the callback.
5 |
6 | ## Functions
7 |
8 | ### constructor
9 |
10 | ```solidity
11 | function constructor(
12 | ) public
13 | ```
14 |
15 | ### uniswapV3SwapCallback
16 |
17 | ```solidity
18 | function uniswapV3SwapCallback(
19 | int256 amount0Delta,
20 | int256 amount1Delta,
21 | bytes data
22 | ) external view override
23 | ```
24 |
25 | Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
26 |
27 | In the implementation you must pay the pool tokens owed for the swap.
28 | The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
29 | amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
30 |
31 | #### Parameters:
32 |
33 | | Name | Type | Description |
34 | | :------------- | :----- | :------------------------------------------------------------------------------------------ |
35 | | `amount0Delta` | int256 | The amount of token0 that was sent (negative) or must be received (positive) by the pool by |
36 |
37 | the end of the swap. If positive, the callback must send that amount of token0 to the pool.
38 | |`amount1Delta` | int256 | The amount of token1 that was sent (negative) or must be received (positive) by the pool by
39 | the end of the swap. If positive, the callback must send that amount of token1 to the pool.
40 | |`data` | bytes | Any data passed through by the caller via the IUniswapV3PoolActions#swap call
41 |
42 | ### quoteExactInputSingle
43 |
44 | ```solidity
45 | function quoteExactInputSingle(
46 | ) public override returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)
47 | ```
48 |
49 | ### quoteExactInput
50 |
51 | ```solidity
52 | function quoteExactInput(
53 | ) public override returns (uint256 amountOut, uint160[] sqrtPriceX96AfterList, uint32[] initializedTicksCrossedList, uint256 gasEstimate)
54 | ```
55 |
56 | ### quoteExactOutputSingle
57 |
58 | ```solidity
59 | function quoteExactOutputSingle(
60 | ) public override returns (uint256 amountIn, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)
61 | ```
62 |
63 | ### quoteExactOutput
64 |
65 | ```solidity
66 | function quoteExactOutput(
67 | ) public override returns (uint256 amountIn, uint160[] sqrtPriceX96AfterList, uint32[] initializedTicksCrossedList, uint256 gasEstimate)
68 | ```
69 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/lens/TickLens.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### getPopulatedTicksInWord
4 |
5 | ```solidity
6 | function getPopulatedTicksInWord(
7 | address pool,
8 | int16 tickBitmapIndex
9 | ) public returns (struct ITickLens.PopulatedTick[] populatedTicks)
10 | ```
11 |
12 | Get all the tick data for the populated ticks from a word of the tick bitmap of a pool
13 |
14 | #### Parameters:
15 |
16 | | Name | Type | Description |
17 | | :---------------- | :------ | :------------------------------------------------------------------------------------------------------- |
18 | | `pool` | address | The address of the pool for which to fetch populated tick data |
19 | | `tickBitmapIndex` | int16 | The index of the word in the tick bitmap for which to parse the bitmap and fetch all the populated ticks |
20 |
21 | #### Return Values:
22 |
23 | | Name | Type | Description |
24 | | :--------------- | :------------------------ | :---------------------------------------------------------- |
25 | | `populatedTicks` | ITickLens.PopulatedTick[] | An array of tick data for the given word in the tick bitmap |
26 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/libraries/Base64.md:
--------------------------------------------------------------------------------
1 | Provides a function for encoding some bytes in base64
2 |
3 | ## Functions
4 |
5 | ### encode
6 |
7 | ```solidity
8 | function encode(
9 | ) internal returns (string)
10 | ```
11 |
12 | Encodes some bytes to the base64 representation
13 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/libraries/BytesLib.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### slice
4 |
5 | ```solidity
6 | function slice(
7 | ) internal returns (bytes)
8 | ```
9 |
10 | ### toAddress
11 |
12 | ```solidity
13 | function toAddress(
14 | ) internal returns (address)
15 | ```
16 |
17 | ### toUint24
18 |
19 | ```solidity
20 | function toUint24(
21 | ) internal returns (uint24)
22 | ```
23 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/libraries/CallbackValidation.md:
--------------------------------------------------------------------------------
1 | Provides validation for callbacks from Uniswap V3 Pools
2 |
3 | ## Functions
4 |
5 | ### verifyCallback
6 |
7 | ```solidity
8 | function verifyCallback(
9 | address factory,
10 | address tokenA,
11 | address tokenB,
12 | uint24 fee
13 | ) internal returns (contract IUniswapV3Pool pool)
14 | ```
15 |
16 | Returns the address of a valid Uniswap V3 Pool
17 |
18 | #### Parameters:
19 |
20 | | Name | Type | Description |
21 | | :-------- | :------ | :-------------------------------------------------------------------------------- |
22 | | `factory` | address | The contract address of the Uniswap V3 factory |
23 | | `tokenA` | address | The contract address of either token0 or token1 |
24 | | `tokenB` | address | The contract address of the other token |
25 | | `fee` | uint24 | The fee collected upon every swap in the pool, denominated in hundredths of a bip |
26 |
27 | #### Return Values:
28 |
29 | | Name | Type | Description |
30 | | :----- | :------------- | :--------------------------- |
31 | | `pool` | IUniswapV3Pool | The V3 pool contract address |
32 |
33 | ### verifyCallback
34 |
35 | ```solidity
36 | function verifyCallback(
37 | address factory,
38 | struct PoolAddress.PoolKey poolKey
39 | ) internal returns (contract IUniswapV3Pool pool)
40 | ```
41 |
42 | Returns the address of a valid Uniswap V3 Pool
43 |
44 | #### Parameters:
45 |
46 | | Name | Type | Description |
47 | | :-------- | :------------------------- | :--------------------------------------------- |
48 | | `factory` | address | The contract address of the Uniswap V3 factory |
49 | | `poolKey` | struct PoolAddress.PoolKey | The identifying key of the V3 pool |
50 |
51 | #### Return Values:
52 |
53 | | Name | Type | Description |
54 | | :----- | :------------- | :--------------------------- |
55 | | `pool` | IUniswapV3Pool | The V3 pool contract address |
56 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/libraries/ChainId.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### get
4 |
5 | ```solidity
6 | function get(
7 | ) internal returns (uint256 chainId)
8 | ```
9 |
10 | Gets the current chain ID
11 |
12 | #### Return Values:
13 |
14 | | Name | Type | Description |
15 | | :-------- | :------ | :------------------- |
16 | | `chainId` | uint256 | The current chain ID |
17 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/libraries/HexStrings.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### toHexString
4 |
5 | ```solidity
6 | function toHexString(
7 | ) internal returns (string)
8 | ```
9 |
10 | Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
11 |
12 | Credit to Open Zeppelin under MIT license https://github.com/OpenZeppelin/openzeppelin-contracts/blob/243adff49ce1700e0ecb99fe522fb16cff1d1ddc/contracts/utils/Strings.sol#L55
13 |
14 | ### toHexStringNoPrefix
15 |
16 | ```solidity
17 | function toHexStringNoPrefix(
18 | ) internal returns (string)
19 | ```
20 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/libraries/NFTDescriptor.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### constructTokenURI
4 |
5 | ```solidity
6 | function constructTokenURI(
7 | ) public returns (string)
8 | ```
9 |
10 | ### escapeQuotes
11 |
12 | ```solidity
13 | function escapeQuotes(
14 | ) internal returns (string)
15 | ```
16 |
17 | ### tickToDecimalString
18 |
19 | ```solidity
20 | function tickToDecimalString(
21 | ) internal returns (string)
22 | ```
23 |
24 | ### fixedPointToDecimalString
25 |
26 | ```solidity
27 | function fixedPointToDecimalString(
28 | ) internal returns (string)
29 | ```
30 |
31 | ### feeToPercentString
32 |
33 | ```solidity
34 | function feeToPercentString(
35 | ) internal returns (string)
36 | ```
37 |
38 | ### addressToString
39 |
40 | ```solidity
41 | function addressToString(
42 | ) internal returns (string)
43 | ```
44 |
45 | ### generateSVGImage
46 |
47 | ```solidity
48 | function generateSVGImage(
49 | ) internal returns (string svg)
50 | ```
51 |
52 | ### tokenToColorHex
53 |
54 | ```solidity
55 | function tokenToColorHex(
56 | ) internal returns (string str)
57 | ```
58 |
59 | ### getCircleCoord
60 |
61 | ```solidity
62 | function getCircleCoord(
63 | ) internal returns (uint256)
64 | ```
65 |
66 | ### sliceTokenHex
67 |
68 | ```solidity
69 | function sliceTokenHex(
70 | ) internal returns (uint256)
71 | ```
72 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/libraries/NFTSVG.md:
--------------------------------------------------------------------------------
1 | Provides a function for generating an SVG associated with a Uniswap NFT
2 |
3 | ## Functions
4 |
5 | ### generateSVG
6 |
7 | ```solidity
8 | function generateSVG(
9 | ) internal returns (string svg)
10 | ```
11 |
12 | ### getCurve
13 |
14 | ```solidity
15 | function getCurve(
16 | ) internal returns (string curve)
17 | ```
18 |
19 | ### generateSVGCurveCircle
20 |
21 | ```solidity
22 | function generateSVGCurveCircle(
23 | ) internal returns (string svg)
24 | ```
25 |
26 | ### rangeLocation
27 |
28 | ```solidity
29 | function rangeLocation(
30 | ) internal returns (string, string)
31 | ```
32 |
33 | ### isRare
34 |
35 | ```solidity
36 | function isRare(
37 | ) internal returns (bool)
38 | ```
39 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/libraries/OracleLibrary.md:
--------------------------------------------------------------------------------
1 | Provides functions to integrate with V3 pool oracle
2 |
3 | ## Functions
4 |
5 | ### consult
6 |
7 | ```solidity
8 | function consult(
9 | address pool,
10 | uint32 period
11 | ) internal view returns (int24 arithmeticMeanTick, uint128 harmonicMeanLiquidity)
12 | ```
13 |
14 | Calculates time-weighted means of tick and liquidity for a given Uniswap V3 pool
15 |
16 | #### Parameters:
17 |
18 | | Name | Type | Description |
19 | | :------- | :------ | :----------------------------------------------------------------------- |
20 | | `pool` | address | Address of Uniswap V3 pool that we want to observe |
21 | | `period` | uint32 | Number of seconds in the past to start calculating time-weighted average |
22 |
23 | #### Return Values:
24 |
25 | | Name | Type | Description |
26 | | :------------------------ | :------ | :--------------------------------------------------------------------------------- |
27 | | `arithmeticMeanTick` | int24 | The arithmetic mean tick from (block.timestamp - secondsAgo) to block.timestamp |
28 | | `harmonicMeanLiquidity` | uint128 | The harmonic mean liquidity from (block.timestamp - secondsAgo) to block.timestamp |
29 |
30 |
31 | ### getQuoteAtTick
32 |
33 | ```solidity
34 | function getQuoteAtTick(
35 | int24 tick,
36 | uint128 baseAmount,
37 | address baseToken,
38 | address quoteToken
39 | ) internal pure returns (uint256 quoteAmount)
40 | ```
41 |
42 | Given a tick and a token amount, calculates the amount of token received in exchange
43 |
44 | #### Parameters:
45 |
46 | | Name | Type | Description |
47 | | :----------- | :------ | :---------------------------------------------------------------------- |
48 | | `tick` | int24 | Tick value used to calculate the quote |
49 | | `baseAmount` | uint128 | Amount of token to be converted |
50 | | `baseToken` | address | Address of an ERC20 token contract used as the baseAmount denomination |
51 | | `quoteToken` | address | Address of an ERC20 token contract used as the quoteAmount denomination |
52 |
53 | #### Return Values:
54 |
55 | | Name | Type | Description |
56 | | :------------ | :------ | :-------------------------------------------------------- |
57 | | `quoteAmount` | uint256 | Amount of quoteToken received for baseAmount of baseToken |
58 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/libraries/Path.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### hasMultiplePools
4 |
5 | ```solidity
6 | function hasMultiplePools(
7 | bytes path
8 | ) internal returns (bool)
9 | ```
10 |
11 | Returns true iff the path contains two or more pools
12 |
13 | #### Parameters:
14 |
15 | | Name | Type | Description |
16 | | :----- | :---- | :-------------------- |
17 | | `path` | bytes | The encoded swap path |
18 |
19 | #### Return Values:
20 |
21 | | Type | Description |
22 | | :--- | :-------------------------------------------------- |
23 | | bool | if path contains two or more pools, otherwise false |
24 |
25 | ### decodeFirstPool
26 |
27 | ```solidity
28 | function decodeFirstPool(
29 | bytes path
30 | ) internal returns (address tokenA, address tokenB, uint24 fee)
31 | ```
32 |
33 | Decodes the first pool in path
34 |
35 | #### Parameters:
36 |
37 | | Name | Type | Description |
38 | | :----- | :---- | :-------------------------- |
39 | | `path` | bytes | The bytes encoded swap path |
40 |
41 | #### Return Values:
42 |
43 | | Name | Type | Description |
44 | | :------- | :------ | :--------------------------------- |
45 | | `tokenA` | address | The first token of the given pool |
46 | | `tokenB` | address | The second token of the given pool |
47 | | `fee` | uint24 | The fee level of the pool |
48 |
49 | ### getFirstPool
50 |
51 | ```solidity
52 | function getFirstPool(
53 | bytes path
54 | ) internal returns (bytes)
55 | ```
56 |
57 | Gets the segment corresponding to the first pool in the path
58 |
59 | #### Parameters:
60 |
61 | | Name | Type | Description |
62 | | :----- | :---- | :-------------------------- |
63 | | `path` | bytes | The bytes encoded swap path |
64 |
65 | #### Return Values:
66 |
67 | | Type | Description |
68 | | :---- | :------------------------------------------------------------------------- |
69 | | bytes | segment containing all data necessary to target the first pool in the path |
70 |
71 | ### skipToken
72 |
73 | ```solidity
74 | function skipToken(
75 | bytes path
76 | ) internal returns (bytes)
77 | ```
78 |
79 | Skips a token + fee element from the buffer and returns the remainder
80 |
81 | #### Parameters:
82 |
83 | | Name | Type | Description |
84 | | :----- | :---- | :------------ |
85 | | `path` | bytes | The swap path |
86 |
87 | #### Return Values:
88 |
89 | | Type | Description |
90 | | :---- | :----------------------------------------- |
91 | | bytes | remaining token + fee elements in the path |
92 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/libraries/PoolAddress.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### getPoolKey
4 |
5 | ```solidity
6 | function getPoolKey(
7 | address tokenA,
8 | address tokenB,
9 | uint24 fee
10 | ) internal returns (struct PoolAddress.PoolKey)
11 | ```
12 |
13 | Returns PoolKey: the ordered tokens with the matched fee levels
14 |
15 | #### Parameters:
16 |
17 | | Name | Type | Description |
18 | | :------- | :------ | :----------------------------------- |
19 | | `tokenA` | address | The first token of a pool, unsorted |
20 | | `tokenB` | address | The second token of a pool, unsorted |
21 | | `fee` | uint24 | The fee level of the pool |
22 |
23 | #### Return Values:
24 |
25 | | Name | Type | Description |
26 | | :-------- | :------------------ | :---------------------------------------------------------- |
27 | | `Poolkey` | PoolAddress.PoolKey | The pool details with ordered token0 and token1 assignments |
28 |
29 | ### computeAddress
30 |
31 | ```solidity
32 | function computeAddress(
33 | address factory,
34 | struct PoolAddress.PoolKey key
35 | ) internal returns (address pool)
36 | ```
37 |
38 | Deterministically computes the pool address given the factory and PoolKey
39 |
40 | #### Parameters:
41 |
42 | | Name | Type | Description |
43 | | :-------- | :------------------------- | :-------------------------------------- |
44 | | `factory` | address | The Uniswap V3 factory contract address |
45 | | `key` | struct PoolAddress.PoolKey | The PoolKey |
46 |
47 | #### Return Values:
48 |
49 | | Name | Type | Description |
50 | | :----- | :------ | :---------------------------------- |
51 | | `pool` | address | The contract address of the V3 pool |
52 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/libraries/PoolTicksCounter.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### countInitializedTicksCrossed
4 |
5 | ```solidity
6 | function countInitializedTicksCrossed(
7 | ) internal view returns (uint32 initializedTicksCrossed)
8 | ```
9 |
10 | This function counts the number of initialized ticks that would incur a gas cost between tickBefore and tickAfter.
11 | When tickBefore and/or tickAfter themselves are initialized, the logic over whether we should count them depends on the
12 | direction of the swap. If we are swapping upwards (tickAfter > tickBefore) we don't want to count tickBefore but we do
13 | want to count tickAfter. The opposite is true if we are swapping downwards.
14 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/libraries/PositionKey.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### compute
4 |
5 | ```solidity
6 | function compute(
7 | ) internal returns (bytes32)
8 | ```
9 |
10 | Returns the key of the position in the core library
11 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/libraries/TokenRatioSortOrder.md:
--------------------------------------------------------------------------------
1 | # TokenRatioSortOrder
2 |
3 | ```solidity
4 | library TokenRatioSortOrder {
5 | int256 constant NUMERATOR_MOST = 300;
6 | int256 constant NUMERATOR_MORE = 200;
7 | int256 constant NUMERATOR = 100;
8 | int256 constant DENOMINATOR_MOST = -300;
9 | int256 constant DENOMINATOR_MORE = -200;
10 | int256 constant DENOMINATOR = -100;
11 | }
12 | ```
13 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/staker/libraries/IncentiveId.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### compute
4 |
5 | ```solidity
6 | function compute(
7 | struct IUniswapV3Staker.IncentiveKey key
8 | ) internal pure returns (bytes32 incentiveId)
9 | ```
10 |
11 | Calculate the key for a staking incentive
12 |
13 | #### Parameters:
14 |
15 | | Name | Type | Description |
16 | | :---- | :----------------------------------- | :------------------------------------------------------ |
17 | | `key` | struct IUniswapV3Staker.IncentiveKey | The components used to compute the incentive identifier |
18 |
19 | #### Return Values:
20 |
21 | | Name | Type | Description |
22 | | :------------ | :------ | :------------------------------- |
23 | | `incentiveId` | bytes32 | The identifier for the incentive |
24 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/staker/libraries/NFTPositionInfo.md:
--------------------------------------------------------------------------------
1 | Encapsulates the logic for getting info about a NFT token ID
2 |
3 | ## Functions
4 |
5 | ### getPositionInfo
6 |
7 | ```solidity
8 | function getPositionInfo(
9 | contract IUniswapV3Factory factory,
10 | contract INonfungiblePositionManager nonfungiblePositionManager,
11 | uint256 tokenId
12 | ) internal view returns (contract IUniswapV3Pool pool, int24 tickLower, int24 tickUpper, uint128 liquidity)
13 | ```
14 |
15 | #### Parameters:
16 |
17 | | Name | Type | Description |
18 | | :--------------------------- | :----------------------------------- | :----------------------------------------------------------------------- |
19 | | `factory` | contract IUniswapV3Factory | The address of the Uniswap V3 Factory used in computing the pool address |
20 | | `nonfungiblePositionManager` | contract INonfungiblePositionManager | The address of the nonfungible position manager to query |
21 | | `tokenId` | uint256 | The unique identifier of an Uniswap V3 LP token |
22 |
23 | #### Return Values:
24 |
25 | | Name | Type | Description |
26 | | :---------- | :------------- | :---------------------------------------- |
27 | | `pool` | IUniswapV3Pool | The address of the Uniswap V3 pool |
28 | | `tickLower` | int24 | The lower tick of the Uniswap V3 position |
29 | | `tickUpper` | int24 | The upper tick of the Uniswap V3 position |
30 | | `liquidity` | uint128 | The amount of liquidity staked |
31 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/staker/libraries/RewardMath.md:
--------------------------------------------------------------------------------
1 | Allows computing rewards given some parameters of stakes and incentives
2 |
3 | ## Functions
4 |
5 | ### computeRewardAmount
6 |
7 | ```solidity
8 | function computeRewardAmount(
9 | uint256 totalRewardUnclaimed,
10 | uint160 totalSecondsClaimedX128,
11 | uint256 startTime,
12 | uint256 endTime,
13 | uint128 liquidity,
14 | uint160 secondsPerLiquidityInsideInitialX128,
15 | uint160 secondsPerLiquidityInsideX128,
16 | uint256 currentTime
17 | ) internal pure returns (uint256 reward, uint160 secondsInsideX128)
18 | ```
19 |
20 | Compute the amount of rewards owed given parameters of the incentive and stake
21 |
22 | #### Parameters:
23 |
24 | | Name | Type | Description |
25 | | :------------------------------------- | :------ | :---------------------------------------------------------------------------------------------------- |
26 | | `totalRewardUnclaimed` | uint256 | The total amount of unclaimed rewards left for an incentive |
27 | | `totalSecondsClaimedX128` | uint160 | How many full liquidity-seconds have been already claimed for the incentive |
28 | | `startTime` | uint256 | When the incentive rewards began in epoch seconds |
29 | | `endTime` | uint256 | When rewards are no longer being dripped out in epoch seconds |
30 | | `liquidity` | uint128 | The amount of liquidity, assumed to be constant over the period over which the snapshots are measured |
31 | | `secondsPerLiquidityInsideInitialX128` | uint160 | The seconds per liquidity of the liquidity tick range as of the beginning of the period |
32 | | `secondsPerLiquidityInsideX128` | uint160 | The seconds per liquidity of the liquidity tick range as of the current block timestamp |
33 | | `currentTime` | uint256 | The current block timestamp, which must be greater than or equal to the start time |
34 |
35 | #### Return Values:
36 |
37 | | Name | Type | Description |
38 | | :------------------ | :------ | :------------------------------------------------------------------------------------ |
39 | | `reward` | uint256 | The amount of rewards owed |
40 | | `secondsInsideX128` | uint160 | The total liquidity seconds inside the position's range for the duration of the stake |
41 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/test/Base64Test.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### encode
4 |
5 | ```solidity
6 | function encode(
7 | ) external returns (string)
8 | ```
9 |
10 | ### getGasCostOfEncode
11 |
12 | ```solidity
13 | function getGasCostOfEncode(
14 | ) external returns (uint256)
15 | ```
16 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/test/LiquidityAmountsTest.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### getLiquidityForAmount0
4 |
5 | ```solidity
6 | function getLiquidityForAmount0(
7 | ) external returns (uint128 liquidity)
8 | ```
9 |
10 | ### getGasCostOfGetLiquidityForAmount0
11 |
12 | ```solidity
13 | function getGasCostOfGetLiquidityForAmount0(
14 | ) external returns (uint256)
15 | ```
16 |
17 | ### getLiquidityForAmount1
18 |
19 | ```solidity
20 | function getLiquidityForAmount1(
21 | ) external returns (uint128 liquidity)
22 | ```
23 |
24 | ### getGasCostOfGetLiquidityForAmount1
25 |
26 | ```solidity
27 | function getGasCostOfGetLiquidityForAmount1(
28 | ) external returns (uint256)
29 | ```
30 |
31 | ### getLiquidityForAmounts
32 |
33 | ```solidity
34 | function getLiquidityForAmounts(
35 | ) external returns (uint128 liquidity)
36 | ```
37 |
38 | ### getGasCostOfGetLiquidityForAmounts
39 |
40 | ```solidity
41 | function getGasCostOfGetLiquidityForAmounts(
42 | ) external returns (uint256)
43 | ```
44 |
45 | ### getAmount0ForLiquidity
46 |
47 | ```solidity
48 | function getAmount0ForLiquidity(
49 | ) external returns (uint256 amount0)
50 | ```
51 |
52 | ### getGasCostOfGetAmount0ForLiquidity
53 |
54 | ```solidity
55 | function getGasCostOfGetAmount0ForLiquidity(
56 | ) external returns (uint256)
57 | ```
58 |
59 | ### getAmount1ForLiquidity
60 |
61 | ```solidity
62 | function getAmount1ForLiquidity(
63 | ) external returns (uint256 amount1)
64 | ```
65 |
66 | ### getGasCostOfGetAmount1ForLiquidity
67 |
68 | ```solidity
69 | function getGasCostOfGetAmount1ForLiquidity(
70 | ) external returns (uint256)
71 | ```
72 |
73 | ### getAmountsForLiquidity
74 |
75 | ```solidity
76 | function getAmountsForLiquidity(
77 | ) external returns (uint256 amount0, uint256 amount1)
78 | ```
79 |
80 | ### getGasCostOfGetAmountsForLiquidity
81 |
82 | ```solidity
83 | function getGasCostOfGetAmountsForLiquidity(
84 | ) external returns (uint256)
85 | ```
86 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/test/MockTimeNonfungiblePositionManager.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### constructor
4 |
5 | ```solidity
6 | function constructor(
7 | ) public
8 | ```
9 |
10 | ### \_blockTimestamp
11 |
12 | ```solidity
13 | function _blockTimestamp(
14 | ) internal returns (uint256)
15 | ```
16 |
17 | ### setTime
18 |
19 | ```solidity
20 | function setTime(
21 | ) external
22 | ```
23 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/test/MockTimeSwapRouter.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### constructor
4 |
5 | ```solidity
6 | function constructor(
7 | ) public
8 | ```
9 |
10 | ### \_blockTimestamp
11 |
12 | ```solidity
13 | function _blockTimestamp(
14 | ) internal returns (uint256)
15 | ```
16 |
17 | ### setTime
18 |
19 | ```solidity
20 | function setTime(
21 | ) external
22 | ```
23 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/test/NFTDescriptorTest.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### constructTokenURI
4 |
5 | ```solidity
6 | function constructTokenURI(
7 | ) public returns (string)
8 | ```
9 |
10 | ### getGasCostOfConstructTokenURI
11 |
12 | ```solidity
13 | function getGasCostOfConstructTokenURI(
14 | ) public returns (uint256)
15 | ```
16 |
17 | ### tickToDecimalString
18 |
19 | ```solidity
20 | function tickToDecimalString(
21 | ) public returns (string)
22 | ```
23 |
24 | ### fixedPointToDecimalString
25 |
26 | ```solidity
27 | function fixedPointToDecimalString(
28 | ) public returns (string)
29 | ```
30 |
31 | ### feeToPercentString
32 |
33 | ```solidity
34 | function feeToPercentString(
35 | ) public returns (string)
36 | ```
37 |
38 | ### addressToString
39 |
40 | ```solidity
41 | function addressToString(
42 | ) public returns (string)
43 | ```
44 |
45 | ### generateSVGImage
46 |
47 | ```solidity
48 | function generateSVGImage(
49 | ) public returns (string)
50 | ```
51 |
52 | ### tokenToColorHex
53 |
54 | ```solidity
55 | function tokenToColorHex(
56 | ) public returns (string)
57 | ```
58 |
59 | ### sliceTokenHex
60 |
61 | ```solidity
62 | function sliceTokenHex(
63 | ) public returns (uint256)
64 | ```
65 |
66 | ### rangeLocation
67 |
68 | ```solidity
69 | function rangeLocation(
70 | ) public returns (string, string)
71 | ```
72 |
73 | ### isRare
74 |
75 | ```solidity
76 | function isRare(
77 | ) public returns (bool)
78 | ```
79 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/test/PathTest.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### hasMultiplePools
4 |
5 | ```solidity
6 | function hasMultiplePools(
7 | ) public returns (bool)
8 | ```
9 |
10 | ### decodeFirstPool
11 |
12 | ```solidity
13 | function decodeFirstPool(
14 | ) public returns (address tokenA, address tokenB, uint24 fee)
15 | ```
16 |
17 | ### getFirstPool
18 |
19 | ```solidity
20 | function getFirstPool(
21 | ) public returns (bytes)
22 | ```
23 |
24 | ### skipToken
25 |
26 | ```solidity
27 | function skipToken(
28 | ) public returns (bytes)
29 | ```
30 |
31 | ### getGasCostOfDecodeFirstPool
32 |
33 | ```solidity
34 | function getGasCostOfDecodeFirstPool(
35 | ) public returns (uint256)
36 | ```
37 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/test/PeripheryImmutableStateTest.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### constructor
4 |
5 | ```solidity
6 | function constructor(
7 | ) public
8 | ```
9 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/test/PoolAddressTest.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### POOL_INIT_CODE_HASH
4 |
5 | ```solidity
6 | function POOL_INIT_CODE_HASH(
7 | ) external returns (bytes32)
8 | ```
9 |
10 | ### computeAddress
11 |
12 | ```solidity
13 | function computeAddress(
14 | ) external returns (address)
15 | ```
16 |
17 | ### getGasCostOfComputeAddress
18 |
19 | ```solidity
20 | function getGasCostOfComputeAddress(
21 | ) external returns (uint256)
22 | ```
23 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/test/SelfPermitTest.md:
--------------------------------------------------------------------------------
1 | Same as SelfPermit but not abstract
2 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/test/TestCallbackValidation.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### verifyCallback
4 |
5 | ```solidity
6 | function verifyCallback(
7 | ) external returns (contract IUniswapV3Pool pool)
8 | ```
9 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/test/TestERC20.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### constructor
4 |
5 | ```solidity
6 | function constructor(
7 | ) public
8 | ```
9 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/test/TestERC20Metadata.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### constructor
4 |
5 | ```solidity
6 | function constructor(
7 | ) public
8 | ```
9 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/test/TestERC20PermitAllowed.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### constructor
4 |
5 | ```solidity
6 | function constructor(
7 | ) public
8 | ```
9 |
10 | ### permit
11 |
12 | ```solidity
13 | function permit(
14 | ) external
15 | ```
16 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/test/TestMulticall.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### functionThatRevertsWithError
4 |
5 | ```solidity
6 | function functionThatRevertsWithError(
7 | ) external
8 | ```
9 |
10 | ### functionThatReturnsTuple
11 |
12 | ```solidity
13 | function functionThatReturnsTuple(
14 | ) external returns (struct TestMulticall.Tuple tuple)
15 | ```
16 |
17 | ### pays
18 |
19 | ```solidity
20 | function pays(
21 | ) external
22 | ```
23 |
24 | ### returnSender
25 |
26 | ```solidity
27 | function returnSender(
28 | ) external returns (address)
29 | ```
30 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/test/TestPositionNFTOwner.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### setOwner
4 |
5 | ```solidity
6 | function setOwner(
7 | ) external
8 | ```
9 |
10 | ### isValidSignature
11 |
12 | ```solidity
13 | function isValidSignature(
14 | ) external returns (bytes4 magicValue)
15 | ```
16 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/test/TestUniswapV3Callee.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### swapExact0For1
4 |
5 | ```solidity
6 | function swapExact0For1(
7 | ) external
8 | ```
9 |
10 | ### swap0ForExact1
11 |
12 | ```solidity
13 | function swap0ForExact1(
14 | ) external
15 | ```
16 |
17 | ### swapExact1For0
18 |
19 | ```solidity
20 | function swapExact1For0(
21 | ) external
22 | ```
23 |
24 | ### swap1ForExact0
25 |
26 | ```solidity
27 | function swap1ForExact0(
28 | ) external
29 | ```
30 |
31 | ### uniswapV3SwapCallback
32 |
33 | ```solidity
34 | function uniswapV3SwapCallback(
35 | ) external
36 | ```
37 |
--------------------------------------------------------------------------------
/docs/uniswap-contracts/v3/reference/periphery/test/TickLensTest.md:
--------------------------------------------------------------------------------
1 | ## Functions
2 |
3 | ### getGasCostOfGetPopulatedTicksInWord
4 |
5 | ```solidity
6 | function getGasCostOfGetPopulatedTicksInWord(
7 | ) external returns (uint256)
8 | ```
9 |
--------------------------------------------------------------------------------
/docs/web3-py-docs/constants.rst:
--------------------------------------------------------------------------------
1 | .. _constants:
2 |
3 | Constants
4 | =========
5 |
6 | The web3.contants module contains commonly used values.
7 |
8 | Strings
9 | *******
10 |
11 | .. code-block:: python
12 |
13 | #The Address Zero, which is 20 bytes (40 nibbles) of zero.
14 | web3.constants.ADDRESS_ZERO
15 |
16 | #The hexadecimal version of Max uint256.
17 | web3.constants.MAX_INT
18 |
19 | #The Hash Zero, which is 32 bytes (64 nibbles) of zero.
20 | web3.constants.HASH_ZERO
21 |
22 | Int
23 | ***
24 |
25 | .. code-block:: python
26 |
27 | #The amount of Wei in one Ether
28 | web3.constants.WEI_PER_ETHER
29 |
30 |
31 |
--------------------------------------------------------------------------------
/docs/web3-py-docs/ens.rst:
--------------------------------------------------------------------------------
1 | .. py:module:: ens
2 |
3 | ENS API
4 | ===========
5 |
6 | :doc:`ens_overview` has a friendly overview.
7 |
8 | Continue below for the detailed specs on each method and class in the ens module.
9 |
10 | ens\.ens module
11 | ----------------
12 |
13 | .. automodule:: ens.ens
14 | :members:
15 |
16 | ens\.async_ens module
17 | ---------------------
18 |
19 | .. automodule:: ens.async_ens
20 | :members:
21 |
22 | ens\.exceptions module
23 | ----------------------
24 |
25 | .. automodule:: ens.exceptions
26 | :members:
27 | :show-inheritance:
28 |
--------------------------------------------------------------------------------
/docs/web3-py-docs/index.rst:
--------------------------------------------------------------------------------
1 | .. meta::
2 | :description: Python Web3 SDK for Ethereum and EVM blockchains
3 |
4 |
5 | gm
6 | ==
7 |
8 | **web3.py** is a Python library for interacting with Ethereum.
9 |
10 | It's commonly found in `decentralized apps (dapps)`_ to help with
11 | sending transactions, interacting with smart contracts, reading
12 | block data, and a variety of other use cases.
13 |
14 | The original API was derived from the `Web3.js`_ Javascript API,
15 | but has since evolved toward the needs and creature comforts of
16 | Python developers.
17 |
18 |
19 | Getting Started
20 | ---------------
21 |
22 | .. NOTE::
23 | 👋 Brand new to Ethereum?
24 |
25 | 0. Don't travel alone! Join the Ethereum Python Community `Discord`_.
26 | 1. Read this `blog post series`_ for a gentle introduction to Ethereum blockchain concepts.
27 | 2. The :ref:`Overview` page will give you a quick idea of what else web3.py can do.
28 | 3. Try building a little something!
29 |
30 | - Ready to code? → :ref:`quickstart`
31 | - Interested in a quick tour? → :ref:`overview`
32 | - Need help debugging? → `StackExchange`_
33 | - Found a bug? → :ref:`Contribute `
34 | - Want to chat? → `Discord`_
35 | - Read the source? → `Github`_
36 |
37 | .. include:: toc.rst
38 |
39 |
40 | .. _decentralized apps (dapps): https://ethereum.org/dapps/
41 | .. _Web3.js: https://web3js.readthedocs.io/
42 | .. _blog post series: https://snakecharmers.ethereum.org/a-developers-guide-to-ethereum-pt-1
43 | .. _StackExchange: https://ethereum.stackexchange.com/questions/tagged/web3.py
44 | .. _Discord: https://discord.gg/GHryRvPB84
45 | .. _Github: https://github.com/ethereum/web3.py
46 |
--------------------------------------------------------------------------------
/docs/web3-py-docs/web3.net.rst:
--------------------------------------------------------------------------------
1 | Net API
2 | =======
3 |
4 | .. py:module:: web3.net
5 |
6 | The ``web3.net`` object exposes methods to interact with the RPC APIs under
7 | the ``net_`` namespace.
8 |
9 |
10 | Properties
11 | ----------
12 |
13 | The following properties are available on the ``web3.net`` namespace.
14 |
15 | .. py:method:: listening
16 | ..py:property::
17 |
18 | * Delegates to ``net_listening`` RPC method
19 |
20 | Returns true if client is actively listening for network connections.
21 |
22 | .. code-block:: python
23 |
24 | >>> web3.net.listening
25 | True
26 |
27 | .. py:method:: peer_count
28 | ..py:property::
29 |
30 | * Delegates to ``net_peerCount`` RPC method
31 |
32 | Returns number of peers currently connected to the client.
33 |
34 | .. code-block:: python
35 |
36 | >>> web3.net.peer_count
37 | 1
38 |
39 | .. py:method:: version
40 | ..py:property::
41 |
42 | * Delegates to ``net_version`` RPC Method
43 |
44 | Returns the current network id.
45 |
46 | .. code-block:: python
47 |
48 | >>> web3.net.version
49 | '8996'
50 |
--------------------------------------------------------------------------------
/docs/web3-py-docs/web3.pm.rst:
--------------------------------------------------------------------------------
1 | Package Manager API
2 | ===================
3 |
4 |
5 | The ``web3.pm`` object exposes methods to interact with Packages as defined by `ERC 1123 `_.
6 |
7 | - To learn more about the EthPM spec, visit the `spec `__ or the `documentation `__.
8 |
9 |
10 | .. WARNING::
11 |
12 | The ``web3.pm`` API is still under development and likely to change quickly.
13 |
14 | Now is a great time to get familiar with the API, and test out writing
15 | code that uses some of the great upcoming features.
16 |
17 | By default, access to this module has been turned off in the stable version of web3.py:
18 |
19 | .. code-block:: python
20 |
21 | >>> from web3 import Web3, IPCProvider
22 | >>> w3 = Web3(IPCProvider(...))
23 | >>> w3.pm
24 | ...
25 | AttributeError: The Package Management feature is disabled by default ...
26 |
27 | In order to access these features, you can turn it on with...
28 |
29 | .. code-block:: python
30 |
31 | >>> w3.enable_unstable_package_management_api()
32 | >>> w3.pm
33 |
34 |
35 |
36 | Methods
37 | -------
38 | The following methods are available on the ``web3.pm`` namespace.
39 |
40 | .. autoclass:: web3.pm.PM
41 | :members:
42 |
43 | .. autoclass:: web3.pm.ERC1319Registry
44 | :members: __init__, _release, _get_package_name, _get_all_package_ids, _get_release_id, _get_all_release_ids, _get_release_data, _generate_release_id, _num_package_ids, _num_release_ids
45 |
46 |
47 | Creating your own Registry class
48 | --------------------------------
49 | If you want to implement your own registry and use it with ``web3.pm``, you must create a subclass that inherits from ``ERC1319Registry``, and implements all the `ERC 1319 standard methods `_ prefixed with an underscore in ``ERC1319Registry``. Then, you have to manually set it as the ``registry`` attribute on ``web3.pm``.
50 |
51 | .. code-block:: python
52 |
53 | custom_registry = CustomRegistryClass(address, w3)
54 | w3.pm.registry = custom_registry
55 |
56 | One reason a user might want to create their own Registry class is if they build a custom Package Registry smart contract that has features beyond those specified in `ERC 1319 `_. For example, the ability to delete a release or some micropayment feature. Rather than accessing those functions directly on the contract instance, they can create a custom ``ERC1319Registry`` subclass to easily call both the standard & custom methods.
57 |
--------------------------------------------------------------------------------
/docs/web3-py-docs/web3.utils.rst:
--------------------------------------------------------------------------------
1 | Utils
2 | =====
3 |
4 | .. py:module:: web3.utils
5 |
6 | The ``utils`` module houses public utility functions and classes.
7 |
8 | ABI
9 | ---
10 |
11 | .. py:method:: utils.get_abi_input_names(abi)
12 |
13 | Return the ``input`` names for an ABI function or event.
14 |
15 |
16 | .. py:method:: utils.get_abi_output_names(abi)
17 |
18 | Return the ``output`` names an ABI function or event.
19 |
20 | Address
21 | -------
22 |
23 | .. py:method:: utils.get_create_address(sender, nonce)
24 |
25 | Return the checksummed contract address generated by using the ``CREATE`` opcode by
26 | a sender address with a given nonce.
27 |
28 |
29 | .. py:method:: utils.get_create2_address(sender, salt, init_code)
30 |
31 | Return the checksummed contract address generated by using the ``CREATE2`` opcode by
32 | a sender address with a given salt and contract bytecode. See
33 | `EIP-1014 `_.
34 |
35 |
36 | Caching
37 | -------
38 |
39 | .. py:class:: utils.SimpleCache
40 |
41 | The main cache class being used internally by web3.py. In some cases, it may prove
42 | useful to set your own cache size and pass in your own instance of this class where
43 | supported.
44 |
45 |
46 | Exception Handling
47 | ------------------
48 |
49 | .. py:method:: utils.handle_offchain_lookup(offchain_lookup_payload, transaction)
50 |
51 | Handle ``OffchainLookup`` reverts on contract function calls manually. For an example, see :ref:`ccip-read-example`
52 | within the examples section.
53 |
54 |
55 | .. py:method:: utils.async_handle_offchain_lookup(offchain_lookup_payload, transaction)
56 |
57 | The async version of the ``handle_offchain_lookup()`` utility method described above.
58 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [tool.poetry]
2 | name = "auto3-copilot"
3 | version = "0.1.0"
4 | description = ""
5 | authors = ["Your Name "]
6 | readme = "README.md"
7 | packages = [{include = "copilot"}]
8 |
9 | [tool.poetry.scripts]
10 | copilot = "copilot.greet:run"
11 |
12 | [tool.poetry.dependencies]
13 | python = "^3.10"
14 | llama-index = "^0.5.9"
15 | arrow = "^1.2.3"
16 | click = "^8.1.3"
17 | pyyaml = "^6.0"
18 | promptlayer = "^0.1.80"
19 | jinja2 = "^3.1.2"
20 | pandas = "^2.0.0"
21 | langchain = "^0.0.136"
22 | nest-asyncio = "^1.5.6"
23 | web3 = "^6.1.0"
24 | python-dotenv = "^1.0.0"
25 |
26 |
27 | [tool.poetry.group.dev.dependencies]
28 | autopep8 = "^2.0.2"
29 | unidiff = "^0.7.5"
30 | ipdb = "^0.13.13"
31 |
32 | [build-system]
33 | requires = ["poetry-core"]
34 | build-backend = "poetry.core.masonry.api"
35 |
--------------------------------------------------------------------------------
/scripts/get_address_abi.py:
--------------------------------------------------------------------------------
1 | import time
2 | import requests
3 | import csv
4 | import os
5 |
6 | os.environ["HTTP_PROXY"] = "http://127.0.0.1:10809"
7 | os.environ["HTTPS_PROXY"] = "http://127.0.0.1:10809"
8 |
9 | def get_contract_abi(address):
10 | url = f"http://api.etherscan.io/api?module=contract&action=getabi&address={address}&format=raw"
11 | response = requests.get(url)
12 |
13 | if response.status_code == 200:
14 | return response.text
15 | else:
16 | return f"Error: Unable to fetch ABI for {address}, status code {response.status_code}"
17 |
18 | input_csv_file = r'D:\1.csv' # Replace with the path to your input CSV file
19 | output_csv_file = r'D:\contract_abis.csv' # Replace with the path to your output CSV file
20 |
21 | with open(input_csv_file, newline='') as infile, open(output_csv_file, 'w', newline='', encoding='utf-8') as outfile:
22 | reader = csv.reader(infile)
23 | writer = csv.writer(outfile)
24 | writer.writerow(['Address', 'ABI'])
25 |
26 | for row in reader:
27 | address = row[0] # Assuming contract address is in the first column
28 | abi = get_contract_abi(address)
29 | time.sleep(15)
30 | writer.writerow([address, abi])
31 | print(f"Retrieved ABI for {address}")
32 |
33 | print("Done!")
34 |
--------------------------------------------------------------------------------
/scripts/proxy_check.py:
--------------------------------------------------------------------------------
1 | import csv
2 | import time
3 | from web3 import Web3
4 |
5 | # 连接到以太坊节点
6 | web3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/d65cbc952b854854b6a2a08708057072'))
7 |
8 | # 检查是否为代理合约的代码前缀
9 | proxy_code_prefix = '73b4'
10 | i=1
11 | # 读取合约地址列表
12 | with open('D:/constrac_accresses.csv', newline='') as csvfile:
13 | reader = csv.DictReader(csvfile)
14 | for row in reader:
15 | contract_address = row['contract_address']
16 | print(f'Checking {contract_address}...')
17 |
18 | # 将地址转换为checksum地址
19 | checksum_address = web3.to_checksum_address(contract_address)
20 |
21 | # 获取合约的代码
22 | code = web3.eth.get_code(checksum_address)
23 |
24 |
25 | # 检查代码是否为代理合约
26 | if proxy_code_prefix in code.hex():
27 | print(f'{i} 1.')
28 | else:
29 | print(f'{i} 0.')
30 | i=i+1
31 | time.sleep(1)
--------------------------------------------------------------------------------