diff --git a/docs/concepts/protocol/architecture.md b/docs/concepts/protocol/architecture.md new file mode 100644 index 000000000..6a8e58486 --- /dev/null +++ b/docs/concepts/protocol/architecture.md @@ -0,0 +1,49 @@ +--- +id: architecture +title: Architecture +sidebar_position: 4 +--- + +t1 is a TEE-enabled cross-chain application infrastructure that leverages defense-in-depth to achieve real-time proving. In the short-term (v1), we achieve RTP with TEE proofs. Longer term, t1 will become a permissionless and decentralized network that will complement TEE proofs with crypto-economic security and bespoke zero-knowledge proofs. You can read more about our long term architecture in our litepaper. + +### Network Architecture v1 + +![](./images//network-architecture-v1.png) + +1. A user, Alice, deposits funds to a t1 bridge contract on Ethereum or on a _Partner Rollup_. Once the deposit is confirmed on the source chain, it gets processed by t1 and Alice gets her funds credited towards her aggregate t1 balance. + +2. Alice creates a t1-native transaction either to interact with applications on t1 or to trigger transactions (including withdrawals) on Ethereum or a _Partner Rollup_. + +3. A TEE enabled sequencer (node) receives the transactions, sequences and executes the block. As a part of execution, when required, the sequencer reads from (xChain Read) and writes (xChain Write) to Partner Rollups, both enabled within the TEE. + +4. The TEE-enabled sequencer generates new trie roots _r_ and a TEE proof. These are submitted to the t1 Canonical Bridge contract on Ethereum and the full compressed transaction data is submitted to Ethereum blob DA. + +5. t1’s _Canonical Bridge_ contract on Ethereum checks the newly submitted t1 trie root _r_ and TEE proof and transaction data availability for consistency. If successful, the trie root _r_ is accepted. This facilitates withdrawals to L1 with a single L1 slot delay (6s on average). + +_Note: Suppose, Alice had desired to withdraw funds, in step 2. She may now submit to the Canonical Bridge an Ethereum claim transaction with an inclusion proof of her withdrawal transaction in t1 (as contained within the withdrawal trie committed to in r). The contract then releases the funds to Alice on Ethereum._ + +### Network Architecture v2 + +![](./images//network-architecture-v2.png) + +1. A user, Alice, deposits funds to a t1 bridge contract on Ethereum or on a _Partner Rollup_. Once the deposit is confirmed on the source chain, it gets processed by t1 and Alice gets her funds credited towards her aggregate t1 balance. + +2. Alice changes her wallet’s network to t1, creates a t1-native transaction (with [some fields encrypted](https://www.notion.so/Litepaper-9a2cc4d321ce4a08a4905aa809fb436e?pvs=21) to the shared rotating TEE pubkey), uses her wallet to sign it, and submits it to the network (i.e. the t1 mempool); this may or may not be a specially-treated withdrawal transaction (to Ethereum or a _Partner Rollup_). +3. A t1 _Sequencer_ receives and gossips such a partially-blind transaction to other _Sequencers_ in the t1 _Sequencing AVS_ network. + +4. After collecting transactions for one t1 slot (currently set to one second), the slot-leading _Sequencer_ proposes an ordering (a blind non-executed bundle). The rest of _Sequencers_ vote on it using Espresso HotShot, to form _Sequencing Consensus_. This bundle and a proof of _Sequencing Consensus_ is then passed on to the _Execution AVS_ network. + +5. t1 _Executors_ validate the proof of _Sequencing Consensus_, decrypt the encrypted parts of the received bundle (if needed and due) using their TEE-derived shared rotating private key, and execute its now fully plaintext ordered transactions against the current state of the t1 blockchain. The slot-leading _Executor_ proposes a new trie root tuple _r_ of state trie root, withdrawals trie root, and proof-of-read trie root—and the rest of the _Executors_ vote on such new trie tuple _r_ to form _Execution Consensus_. + + - Note: _Executors_ use follower nodes also running in TEEs to read from and write to _Partner Rollups_ (whenever required by a t1 tx). + +6. The _Execution_ AVS posts t1’s new trie roots _r_ and all the corresponding consensus proofs to the Ethereum t1 _Canonical Bridge_ contract and the full compressed transactions to Ethereum blob DA. + + - In addition, t1 progressively incentivizes the generation and posting of _periodic ZKPs_ to the _Canonical Bridge_ on Ethereum to create _ZKP checkpoints_ resetting the value-at-risk counters and also speeding up the potential _on-demand ZKP_ creation when required. t1 dynamic gas pricing considers how much AVS security budget is still available, to reach an equilibrium. + - In the rare event that new t1 transactions’ (as per all new trie root tuples) cumulative value since the last _ZKP checkpoint,_ despite the mechanisms above, would exceed the crypto-economic security budget provided by _Execution AVS_, also an _on-demand ZKP_ is required by the _Canonical Bridge_, pausing finalization until then; this would increase the withdrawal delay to hours under such extreme conditions. + +7. t1’s _Canonical Bridge_ contract on Ethereum checks the new submitted t1 trie root tuple _r_, _Sequencing Consensus,_ _Execution Consensus_ and transaction data availability for consistency. If successful, such _r_ is accepted. This then generally facilitates withdrawals from t1 to Ethereum with a single-Ethereum-block delay only (i.e. 6 seconds on average). + + - Suppose, Alice had desired to withdraw funds, in step 2. She may now submit to the _Canonical Bridge_ an Ethereum claim transaction with an inclusion proof of her withdrawal transaction in t1 (as contained within the withdrawal trie committed to in _r_). The contract then releases the funds to Alice on Ethereum. + +8. If Alice wishes to withdraw funds to her account on a _Partner Rollup_ rather than on Ethereum, the same trie root tuple _r_ update in the _Canonical Bridge_ (i.e. on Ethereum) is required as in 7. However, she submits the claim transaction with an inclusion proof of the withdrawal to the (non-canonical) t1 bridge contract on _Partner Rollup_ instead. The _Partner Rollup_ bridge contract verifies the inclusion proof with respect to _r_ as accepted by the _Canonical Bridge_ on Ethereum (using _Partner Rollup_’s Ethereum read abilities, usually via _Partner Rollup_’s own L1 canonical bridge) and then releases the funds to Alice on _Partner Rollup_. diff --git a/docs/concepts/protocol/tee.md b/docs/concepts/protocol/tee.md index 9441bce55..51b588b94 100644 --- a/docs/concepts/protocol/tee.md +++ b/docs/concepts/protocol/tee.md @@ -9,49 +9,3 @@ Trusted Execution Environments (TEEs) are specialized hardware-based environment Two key requirements for achieving full unification of Ethereum and the rollup ecosystem, without reorg risks and asynchrony at all, are shared sequencing across all chains and real-time proving (RTP). At t1, we are working on RTP by employing TEEs. However, TEEs also help with cross-chain composability by enabling lightclients in t1 to reliably read data from and write data to partner rollups. This setup allows t1 to effectively aggregate the state of Ethereum and partner rollups. Our current design, which does not rely on shared sequencing, enables t1 to have as low as a single-block asynchrony window (12 seconds) with Ethereum—a substantial improvement over the current seven-day window in Optimistic Rollups and hours-long window in Zero-Knowledge Rollups. In addition to RTP and cross-chain communication, TEEs allow t1 to offer an encrypted mempool. An encrypted mempool prevents adversarial reordering, such as sandwich attacks, where an attacker observes a pending transaction and places trades before (front-running) and after (back-running) it, profiting at the expense of regular users. Sandwich attacks cost Ethereum users over [$100mn every year](https://eigenphi.io/mev/ethereum/sandwich). An encrypted mempool also facilitates use cases like sealed-bid auctions and information-incomplete games. - -## Architecture - -t1 is a TEE-enabled cross-chain application infrastructure that leverages defense-in-depth to achieve real-time proving. In the short-term (v1), we achieve RTP with TEE proofs. Longer term, t1 will become a permissionless and decentralized network that will complement TEE proofs with crypto-economic security and bespoke zero-knowledge proofs. You can read more about our long term architecture in our litepaper. - -### Network Architecture v1 - -![](./images//network-architecture-v1.png) - -1. A user, Alice, deposits funds to a t1 bridge contract on Ethereum or on a _Partner Rollup_. Once the deposit is confirmed on the source chain, it gets processed by t1 and Alice gets her funds credited towards her aggregate t1 balance. - -2. Alice creates a t1-native transaction either to interact with applications on t1 or to trigger transactions (including withdrawals) on Ethereum or a _Partner Rollup_. - -3. A TEE enabled sequencer (node) receives the transactions, sequences and executes the block. As a part of execution, when required, the sequencer reads from (xChain Read) and writes (xChain Write) to Partner Rollups, both enabled within the TEE. - -4. The TEE-enabled sequencer generates new trie roots _r_ and a TEE proof. These are submitted to the t1 Canonical Bridge contract on Ethereum and the full compressed transaction data is submitted to Ethereum blob DA. - -5. t1’s _Canonical Bridge_ contract on Ethereum checks the newly submitted t1 trie root _r_ and TEE proof and transaction data availability for consistency. If successful, the trie root _r_ is accepted. This facilitates withdrawals to L1 with a single L1 slot delay (6s on average). - -_Note: Suppose, Alice had desired to withdraw funds, in step 2. She may now submit to the Canonical Bridge an Ethereum claim transaction with an inclusion proof of her withdrawal transaction in t1 (as contained within the withdrawal trie committed to in r). The contract then releases the funds to Alice on Ethereum._ - -### Network Architecture v2 - -![](./images//network-architecture-v2.png) - -1. A user, Alice, deposits funds to a t1 bridge contract on Ethereum or on a _Partner Rollup_. Once the deposit is confirmed on the source chain, it gets processed by t1 and Alice gets her funds credited towards her aggregate t1 balance. - -2. Alice changes her wallet’s network to t1, creates a t1-native transaction (with [some fields encrypted](https://www.notion.so/Litepaper-9a2cc4d321ce4a08a4905aa809fb436e?pvs=21) to the shared rotating TEE pubkey), uses her wallet to sign it, and submits it to the network (i.e. the t1 mempool); this may or may not be a specially-treated withdrawal transaction (to Ethereum or a _Partner Rollup_). -3. A t1 _Sequencer_ receives and gossips such a partially-blind transaction to other _Sequencers_ in the t1 _Sequencing AVS_ network. - -4. After collecting transactions for one t1 slot (currently set to one second), the slot-leading _Sequencer_ proposes an ordering (a blind non-executed bundle). The rest of _Sequencers_ vote on it using Espresso HotShot, to form _Sequencing Consensus_. This bundle and a proof of _Sequencing Consensus_ is then passed on to the _Execution AVS_ network. - -5. t1 _Executors_ validate the proof of _Sequencing Consensus_, decrypt the encrypted parts of the received bundle (if needed and due) using their TEE-derived shared rotating private key, and execute its now fully plaintext ordered transactions against the current state of the t1 blockchain. The slot-leading _Executor_ proposes a new trie root tuple _r_ of state trie root, withdrawals trie root, and proof-of-read trie root—and the rest of the _Executors_ vote on such new trie tuple _r_ to form _Execution Consensus_. - - - Note: _Executors_ use follower nodes also running in TEEs to read from and write to _Partner Rollups_ (whenever required by a t1 tx). - -6. The _Execution_ AVS posts t1’s new trie roots _r_ and all the corresponding consensus proofs to the Ethereum t1 _Canonical Bridge_ contract and the full compressed transactions to Ethereum blob DA. - - - In addition, t1 progressively incentivizes the generation and posting of _periodic ZKPs_ to the _Canonical Bridge_ on Ethereum to create _ZKP checkpoints_ resetting the value-at-risk counters and also speeding up the potential _on-demand ZKP_ creation when required. t1 dynamic gas pricing considers how much AVS security budget is still available, to reach an equilibrium. - - In the rare event that new t1 transactions’ (as per all new trie root tuples) cumulative value since the last _ZKP checkpoint,_ despite the mechanisms above, would exceed the crypto-economic security budget provided by _Execution AVS_, also an _on-demand ZKP_ is required by the _Canonical Bridge_, pausing finalization until then; this would increase the withdrawal delay to hours under such extreme conditions. - -7. t1’s _Canonical Bridge_ contract on Ethereum checks the new submitted t1 trie root tuple _r_, _Sequencing Consensus,_ _Execution Consensus_ and transaction data availability for consistency. If successful, such _r_ is accepted. This then generally facilitates withdrawals from t1 to Ethereum with a single-Ethereum-block delay only (i.e. 6 seconds on average). - - - Suppose, Alice had desired to withdraw funds, in step 2. She may now submit to the _Canonical Bridge_ an Ethereum claim transaction with an inclusion proof of her withdrawal transaction in t1 (as contained within the withdrawal trie committed to in _r_). The contract then releases the funds to Alice on Ethereum. - -8. If Alice wishes to withdraw funds to her account on a _Partner Rollup_ rather than on Ethereum, the same trie root tuple _r_ update in the _Canonical Bridge_ (i.e. on Ethereum) is required as in 7. However, she submits the claim transaction with an inclusion proof of the withdrawal to the (non-canonical) t1 bridge contract on _Partner Rollup_ instead. The _Partner Rollup_ bridge contract verifies the inclusion proof with respect to _r_ as accepted by the _Canonical Bridge_ on Ethereum (using _Partner Rollup_’s Ethereum read abilities, usually via _Partner Rollup_’s own L1 canonical bridge) and then releases the funds to Alice on _Partner Rollup_. diff --git a/docs/contracts/permit2/_category_.json b/docs/contracts/permit2/_category_.json deleted file mode 100644 index 54a6ea7d5..000000000 --- a/docs/contracts/permit2/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "label": "Permit2", - "position": 4, - "collapsed": true - } diff --git a/docs/contracts/permit2/overview.md b/docs/contracts/permit2/overview.md deleted file mode 100644 index 20b3ed61d..000000000 --- a/docs/contracts/permit2/overview.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -id: overview -title: Overview -sidebar_position: 1 ---- - -[`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. - -## Resources - -A great [explanation](https://github.com/dragonfly-xyz/useful-solidity-patterns/tree/main/patterns/permit2) of the Permit2 contract and example usage. - -## Approving Permit2 - -Before integrating contracts can request users’ tokens through Permit2, users must approve the Permit2 contract through the specific token contract by calling something like: - -```solidity -USDC.approve(permit2Address, totalAmount); -``` - -To get the maximal benefits from Permit2, users should do a max approval on the contract where: -```solidity -totalAmount = type(uint256).max; -``` - - diff --git a/docs/contracts/permit2/reference/_category_.json b/docs/contracts/permit2/reference/_category_.json deleted file mode 100644 index 2710b6a63..000000000 --- a/docs/contracts/permit2/reference/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Technical Reference", - "position": 2, - "collapsed": false - } - \ No newline at end of file diff --git a/docs/contracts/permit2/reference/allowance-transfer.md b/docs/contracts/permit2/reference/allowance-transfer.md deleted file mode 100644 index 4b20fe217..000000000 --- a/docs/contracts/permit2/reference/allowance-transfer.md +++ /dev/null @@ -1,171 +0,0 @@ ---- -id: allowance-transfer -title: AllowanceTransfer -sidebar_position: 2 ---- - -> [**Source Code**](https://github.com/Uniswap/permit2/blob/main/src/AllowanceTransfer.sol) - -## Overview - -The main entry points on this contract are: - -- `approve` - - Use approve when you do not want to set token permissions through signature validation. -- `permit` - - Use permit when you do want to set token permissions through signature validation. -- `transferFrom` - - Use transferFrom when you want to transfer a token and have the necessary permissions to do so. - -## Functions - -### `approve` - -**Function Signature** - -```solidity -function approve(address token, address spender, uint160 amount, uint48 expiration) external -``` - -**Parameters** - -- token - the token address to approve -- spender - the spender address to approve -- amount - the approved amount of the token, `type(uint160).max` is treated as an unlimited allowance -- expiration - the timestamp at which the approval is no longer valid, passing in `0` will expire the permissions at `block.timestamp` - -### Single `permit` - -**Function Signature** - -```solidity -function permit(address owner, PermitSingle memory permitSingle, bytes calldata signature) external; -``` - -**Parameters** - -- owner - the address of the token’s owner -- permitSingle - constructed with the following: - -```solidity -struct PermitSingle { - // the permit data for a single token allowance - PermitDetails details; - // address permissioned on the allowed tokens - address spender; - // deadline on the permit signature - uint256 sigDeadline; - } - -struct PermitDetails { - // ERC20 token address - address token; - // the maximum amount allowed to spend - uint160 amount; - // timestamp at which a spender's token allowances become invalid - uint48 expiration; - // an incrementing value indexed per owner,token,and spender for each signature - uint48 nonce; - } -``` - -- signature - the signature over the permit data. Supports EOA signatures, compact signatures defined by [EIP-2098](https://eips.ethereum.org/EIPS/eip-2098), and contract signatures defined by [EIP-1271](https://eips.ethereum.org/EIPS/eip-1271) - -### Batched `permit` - -**Function Signature** - -```solidity -function permit(address owner, PermitBatch memory permitBatch, bytes calldata signature) external; -``` - -**Parameters** - -- owner - the address of the token’s owner -- permitBatch - constructed with the following: - -```solidity -struct PermitBatch { - // the permit data for multiple token allowances - PermitDetails[] details; - // address permissioned on the allowed tokens - address spender; - // deadline on the permit signature - uint256 sigDeadline; - } -struct PermitDetails { - // ERC20 token address - address token; - // the maximum amount allowed to spend - uint160 amount; - // timestamp at which a spender's token allowances become invalid - uint48 expiration; - // an incrementing value indexed per owner,token,and spender for each signature - uint48 nonce; - } -``` - -- signature - the signature over the permit data. Supports EOA signatures, compact signatures defined by [EIP-2098](https://eips.ethereum.org/EIPS/eip-2098), and contract signatures defined by [EIP-1271](https://eips.ethereum.org/EIPS/eip-1271) - -### Single `transferFrom` - -**Function Signature** - -```solidity -function transferFrom(address from, address to, uint160 amount, address token) external; -``` - -**Parameters** - -- from - the address to transfer the token from -- to - the address of the recipient -- amount - the amount of the token to transfer, the maximum amount is `type(uint160).max` -- token - the address of the token to be transferred - -### Batched `transferFrom` - -**Function Signature** - -```solidity -function transferFrom(AllowanceTransferDetails[] calldata transferDetails) external; -``` - -**Parameters** - -- transferDetails - constructed with the following - -```solidity -struct AllowanceTransferDetails { - // the owner of the token - address from; - // the recipient of the token - address to; - // the amount of the token - uint160 amount; - // the token to be transferred - address token; - } -``` - -## Nonce Schema - -The nonces used to protect against replay attacks of signatures are similar to standard incrementing nonces. However, we pack nonces with an allowed amount, and an allowed duration. This means that nonces are incremented *per owner*, *per token*, and *per spender.* Which further implies that you could sign two different permits at the same time with the same nonces and they *won’t* cancel each other out so long as the token or spender differ. - -The mapping nonces are packed in is defined as follows: - -```solidity -mapping(address => mapping(address => mapping(address => PackedAllowance))) public allowance; -``` - -and indexed as follows: - -```solidity -PackedAllowance allowanceInformation = allowance[ownerAddress][tokenAddress][spenderAddress]; -uint48 nonce = allowanceInformation.nonce; -``` - -## Security Considerations - -Similar to the security considerations outlined in SignatureTransfer, integrating contracts need to perform valid safety checks on the caller and pass in correct addresses for the `from` argument in any transfer calls. - -All amounts on the `AllowanceTransfer` contract are of type `uint160` so make sure integrating contracts safely downcast if they have to. See how Permit2Lib downcasts safely. \ No newline at end of file diff --git a/docs/contracts/permit2/reference/signature-transfer.md b/docs/contracts/permit2/reference/signature-transfer.md deleted file mode 100644 index 76ebfe844..000000000 --- a/docs/contracts/permit2/reference/signature-transfer.md +++ /dev/null @@ -1,241 +0,0 @@ ---- -id: signature-transfer -title: SignatureTransfer -sidebar_position: 1 ---- - -> [**Source Code**](https://github.com/Uniswap/permit2/blob/main/src/SignatureTransfer.sol) - -## Overview - -The main entry points on this contract are: - -- `permitTransferFrom` - - Use permitTransferFrom when you want to transfer a token from an owner through signature validation. -- `permitWitnessTransferFrom` - - Use permitWitnessTransferFrom when you want to transfer a token from an owner through signature validation, but you would also like to validate other data. Any other data you wish to be validated can be passed through with the `witness` param. - -Each of these functions is overloaded with a batched version that allows users to transfer multiple tokens with 1 transaction. - -## Functions - -### Single `permitTransferFrom` - -Use the `permitTransferFrom` to transfer just one token. - -**Function signature** - -```solidity -function permitTransferFrom( - PermitTransferFrom memory permit, - SignatureTransferDetails calldata transferDetails, - address owner, - bytes calldata signature - ) external -``` - -**Parameters** - -- permit - Construct `PermitTransferFrom` struct with the following: - -```solidity -struct PermitTransferFrom { - TokenPermissions permitted; - // a unique value for every token owner's signature to prevent signature replays - uint256 nonce; - // deadline on the permit signature - uint256 deadline; - } - -struct TokenPermissions { - // ERC20 token address - address token; - // the maximum amount that can be spent - uint256 amount; - } -``` - -- transferDetails - information about recipient and amount - -```solidity -struct SignatureTransferDetails { - // recipient address - address to; - // spender requested amount - uint256 requestedAmount; - } -``` - -- owner - the signer of the permit message and owner of the tokens -- signature - the signature over the permit data. Supports EOA signatures, compact signatures defined by [EIP-2098](https://eips.ethereum.org/EIPS/eip-2098), and contract signatures defined by [EIP-1271](https://eips.ethereum.org/EIPS/eip-1271) - -### Batched `permitTransferFrom` - -Use `permitTransferFrom` with the batched parameters when you want to transfer multiple tokens from an owner. - -**Function Signature** - -```solidity -function permitTransferFrom( - PermitBatchTransferFrom memory permit, - SignatureTransferDetails[] calldata transferDetails, - address owner, - bytes calldata signature - ) external -``` - -**Parameters** - -- permit - Construct `PermitBatchTransferFrom` with the following: - -```solidity -struct PermitBatchTransferFrom { - // the tokens and corresponding amounts permitted for a transfer - TokenPermissions[] permitted; - // a unique value for every token owner's signature to prevent signature replays - uint256 nonce; - // deadline on the permit signature - uint256 deadline; - } - -struct TokenPermissions { - // ERC20 token address - address token; - // the maximum amount that can be spent - uint256 amount; - } -``` - -- transferDetails - parameterized by the spender with information about the token transfer. - - The length of the `SignatureTransferDetails` array must equal the length of the `TokenPermissions` array passed in with `PermitBatchTransferFrom` struct. The token to be transferred specified in the `TokenPermissions` array should match the index of the `SignatureTransferDetails` array. - - Note that if a spender is permitted to a token but does not need to transfer that token, they can specify that the `requestedAmount` is 0 so that the transfer is skipped. -- owner - the signer of the permit message and owner of the tokens - -```solidity -struct SignatureTransferDetails { - // recipient address - address to; - // spender requested amount - uint256 requestedAmount; - } -``` - -- signature - the signature over the permit data. Supports EOA signatures, compact signatures defined by [EIP-2098](https://eips.ethereum.org/EIPS/eip-2098), and contract signatures defined by [EIP-1271](https://eips.ethereum.org/EIPS/eip-1271) - -### Single `permitWitnessTransferFrom` - -**Function Signature** - -```solidity -function permitWitnessTransferFrom( - PermitTransferFrom memory permit, - SignatureTransferDetails calldata transferDetails, - address owner, - bytes32 witness, - string calldata witnessTypeString, - bytes calldata signature - ) external -``` - -**Parameters** - -- permit - constructed with the same type as defined above in the single permitTransferFrom case -- transferDetails constructed with same type as defined above in the single permitTransferFrom case -- owner - the signer of the permit message and owner of the tokens -- witness - arbitrary data passed through that was signed by the user. Is used to reconstruct the signature. Pass through this data if you want the permit signature recovery also to validate other data. -- witnessTypeString - a string that defines the typed data that the witness was hashed from. It must also include the `TokenPermissions` struct and comply with [EIP-712](https://eips.ethereum.org/EIPS/eip-712) struct ordering. See an example below. -- signature - the signature over the permit data. Supports EOA signatures, compact signatures defined by [EIP-2098](https://eips.ethereum.org/EIPS/eip-2098), and contract signatures defined by [EIP-1271](https://eips.ethereum.org/EIPS/eip-1271) - -### Batch `permitWitnessTransferFrom` - -**Function Signature** - -```solidity -function permitWitnessTransferFrom( - PermitBatchTransferFrom memory permit, - SignatureTransferDetails[] calldata transferDetails, - address owner, - bytes32 witness, - string calldata witnessTypeString, - bytes calldata signature - ) external -``` - -**Parameters** - -- permit - constructed with the same type in the batched case of `permitTransferFrom` -- transferDetails - constructed with the same type in the batched case of `permitTransferFrom` -- owner - the signer of the permit message and owner of the tokens -- witness - arbitrary data passed through that was signed by the user. Is used to reconstruct the signature. Pass through this data if you want the permit signature recovery to also validate other data. -- witnessTypeString - a string that defines the typed data that the witness was hashed from. It must also include the `TokenPermissions` struct and comply with [EIP-712](https://eips.ethereum.org/EIPS/eip-712) struct ordering. See an example below. -- signature - the signature over the permit data. Supports EOA signatures, compact signatures defined by [EIP-2098](https://eips.ethereum.org/EIPS/eip-2098), and contract signatures defined by [EIP-1271](https://eips.ethereum.org/EIPS/eip-1271) - -**Example `permitWitnessTransferFrom` parameters** - -If an integrating contract would also like the signer to verify information about a trade, an integrating contract may ask the signer to also sign an `ExampleTrade` object that we define below: - -```solidity -struct ExampleTrade { - address exampleTokenAddress; - uint256 exampleMinimumAmountOut; -} -``` - -Following EIP-721, the typehash for the data would be defined by: - -```solidity -bytes32 _EXAMPLE_TRADE_TYPEHASH = keccak256('ExampleTrade(address exampleTokenAddress,uint256 exampleMinimumAmountOut)'); -``` - -The `witness` that should be passed along with the permit message should be: - -```solidity - bytes32 witness = keccak256( - abi.encode(_EXAMPLE_TRADE_TYPEHASH, exampleTrade.exampleTokenAddress, exampleTrade.exampleMinimumAmountOut)); -``` - -And the `witnessTypeString` to be passed in should be: - -```solidity -string constant witnessTypeString = "ExampleTrade witness)ExampleTrade(address exampleTokenAddress,uint256 exampleMinimumAmountOut)TokenPermissions(address token,uint256 amount)" -``` - -It’s important to note that when hashing multiple typed structs, the ordering of the structs in the type string matters. Referencing EIP-721: - -> If the struct type references other struct types (and these in turn reference even more struct types), then the set of referenced struct types is collected, sorted by name and appended to the encoding. An example encoding is `Transaction(Person from,Person to,Asset tx)Asset(address token,uint256 amount)Person(address wallet,string name)` -> - -## Nonce Schema - -Instead of using incrementing nonces, we introduce non-monotonic, or unordered nonces with a `nonceBitmap`. - -The `nonceBitmap` maps an owner's address to a uint248 value, which we will call `wordPos` which is the index of the desired bitmap. There are 2248 possible indices thus 2248 possible bitmaps where each bitmap holds 256 bits. A bit must be flipped on to prevent replays of users’ signatures. Bits that are dirtied may not be used again. - -```solidity -// nonceBitmap[ownerAddress][wordPosition] retrieves a uint256 bitmap -mapping(address => mapping(uint248 => uint256)) public nonceBitmap; -``` - -Users will sign a `uint256 nonce` value where the first 248 bits correspond to the word position of the bitmap to dirty and the last 8 bits correspond to the actual bit position being flipped on. - -```solidity -uint248 wordPos = uint248(nonce >> 8); -uint8 bitPos = uint8(nonce); -``` - -```solidity -uint256 bitmap = nonceBitmap[wordPos][bitPos] -``` - -## Security Considerations - -An integrating contract must check that tokens are released by a triggering call from the signer, or that the signer meant for their signature to be released by someone else. - - - -Universal Router protects against this by checking that the `msg.sender` from inside the routing contract is the supposed spender by passing `msg.sender` in as the `owner` param in any permit calls and by passing in `msg.sender` as the `from` param in any transfer calls. diff --git a/docs/contracts/uniswapx/01-overview.md b/docs/contracts/uniswapx/01-overview.md deleted file mode 100644 index ac2e93acc..000000000 --- a/docs/contracts/uniswapx/01-overview.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -id: overview -title: Overview -sidebar_position: 1 ---- - -# t1X - -UniswapX is a new permissionless, open source (GPL), auction-based routing protocol for trading across AMMs and other liquidity sources. - -UniswapX improves swapping in several ways: - -- Better prices by aggregating liquidity sources -- Gas-free swapping -- Protection against MEV (Maximal Extractable Value) -- No cost for failed transactions -- And in the coming months, t1X will expand to gas-free cross-chain swaps. - -Swappers generate signed orders which specify the intents of their swap, and fillers compete using arbitrary filling strategies to satisfy these orders. - -# Trading on t1X -To trade using t1X, swappers create a new type of order called an Exclusive Dutch Order which specifies the maximum and minimum outputs they are willing to receive in a trade over a certain time period. - - - -They then sign a message that uses Permit2 to allow the transfer of tokens to complete the trade as long as the the number of tokens sent and received matched what is specified in the decay curve. These Signed Order messages are broadcast publicly and available to be executed by anyone who wants to be a “filler”. - -## Fillers on t1X -UniswapX introduces a new participant in the t1 ecosystem, the _Filler_. These agents pickup signed orders from swappers and compete to execute them using any source of liquidity they have access to. - -Anyone can fill orders on t1X, get started by reading our [Filler Integration Guide](/contracts/uniswapx/guides/createfiller). - -## Parametizing t1X Orders on Mainnet -The t1X protocol on Mainnet does not explicitly parameterize the pricing of orders like the Exclusive Dutch Order, rather order parameterization is left to be configured by the order constructor. - -In the current t1 Labs interface implementation of t1X, some fillers may choose to help parameterize orders on Mainnet by participating as quoters. These fillers can *only* win a quote if they guarantee improved swapper execution over t1 v3 or v2 liquidity pools. Fillers who win a quote will receive execution priority for a limited period of time to fill orders they submitted wining quotes for. - -To ensure a smooth swapping experience for traders, the set of Quoters will be vetted by t1 Labs following t1X’s launch, with plans to make the quoting system fully permissionless in the near future. - -If you are interested in participating as a Quoter, please reach out [here](mailto:quoters@uniswap.org). - -# t1X Protocol Architecture - - -UniswapX - -### Reactors - -Order Reactors _settle_ t1X orders. They are responsible for validating orders of a specific type, resolving them into inputs and outputs, and executing them against the filler's strategy, and verifying that the order was successfully fulfilled. - -Reactors process orders using the following steps: -- Validate the order -- Resolve the order into inputs and outputs -- Pull input tokens from the swapper to the fillContract using permit2 `permitWitnessTransferFrom` with the order as witness -- Call `reactorCallback` on the fillContract -- Verify that the output tokens were received by the output recipients - -Reactors implement the [IReactor](https://github.com/Uniswap/UniswapX/blob/main/src/interfaces/IReactor.sol) interface which abstracts the specifics of the order specification. This allows for different reactor implementations with different order formats to be used with the same interface, allowing for shared infrastructure and easy extension by fillers. - -Current reactor implementations: -- [V2DutchOrderReactor](https://github.com/Uniswap/UniswapX/blob/main/src/reactors/V2DutchOrderReactor.sol): The latest version of the Dutch Order Reactor, that settle v2 linear decay dutch orders. -- [LimitOrderReactor](https://github.com/Uniswap/UniswapX/blob/main/src/reactors/LimitOrderReactor.sol): A reactor that settles simple static limit orders -- [DutchOrderReactor](https://github.com/Uniswap/UniswapX/blob/main/src/reactors/DutchOrderReactor.sol): A reactor that settles linear-decay dutch orders -- [ExclusiveDutchOrderReactor](https://github.com/Uniswap/UniswapX/blob/main/src/reactors/ExclusiveDutchOrderReactor.sol): A reactor that settles linear-decay dutch orders with a period of exclusivity before decay begins -- [PriorityOrderReactor.sol](https://github.com/Uniswap/UniswapX/blob/main/src/reactors/PriorityOrderReactor.sol): A reactor that settles orders which implement priority taxes - -### Fill Contracts - -Order fillContracts _fill_ t1X orders. They specify the filler's strategy for fulfilling orders and are called by the reactor with `reactorCallback`. - -Some sample fillContract implementations are provided in this repository: -- [SwapRouter02Executor](https://github.com/Uniswap/UniswapX/blob/main/src/sample-executors/SwapRouter02Executor.sol): A fillContract that uses t1V2 and t1V3 via the SwapRouter02 router - -### Direct Fill - -If a filler wants to fill orders using funds on-hand rather than a fillContract, they can do so gas efficiently using the `directFill` macro by specifying `address(1)` as the fillContract. This will pull tokens from the filler using `msg.sender` to satisfy the order outputs. - -# Whitepaper -More details on the t1X protocol are available in the [UniswapX Whitepaper](https://uniswap.org/whitepaper-uniswapx.pdf). - -# Deployment Addresses - -| Contract | Address | Source | -| --- | --- | --- | -| V2 Dutch Order Reactor | [0x00000011f84b9aa48e5f8aa8b9897600006289be](https://etherscan.io/address/0x00000011f84b9aa48e5f8aa8b9897600006289be) | [V2DutchOrderReactor](https://github.com/Uniswap/UniswapX/blob/main/src/reactors/V2DutchOrderReactor.sol) | -| V1 Exclusive Dutch Order Reactor | [0x6000da47483062A0D734Ba3dc7576Ce6A0B645C4](https://etherscan.io/address/0x6000da47483062A0D734Ba3dc7576Ce6A0B645C4) | [ExclusiveDutchOrderReactor](https://github.com/Uniswap/UniswapX/blob/v1.0.0/src/reactors/ExclusiveDutchOrderReactor.sol) | -| OrderQuoter | [0x54539967a06Fc0E3C3ED0ee320Eb67362D13C5fF](https://etherscan.io/address/0x54539967a06Fc0E3C3ED0ee320Eb67362D13C5fF) | [OrderQuoter](https://github.com/Uniswap/UniswapX/blob/v1.0.0/src/OrderQuoter.sol) | -| Permit2 | [0x000000000022D473030F116dDEE9F6B43aC78BA3](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3) | [Permit2](https://github.com/Uniswap/permit2) | diff --git a/docs/contracts/uniswapx/_category_.json b/docs/contracts/uniswapx/_category_.json deleted file mode 100644 index b21c97a10..000000000 --- a/docs/contracts/uniswapx/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "label": "UniswapX", - "position": 3, - "collapsed": true - } diff --git a/docs/contracts/uniswapx/guides/_category_.json b/docs/contracts/uniswapx/guides/_category_.json deleted file mode 100644 index 980866705..000000000 --- a/docs/contracts/uniswapx/guides/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Guides", - "position": 3, - "collapsed": false - } - \ No newline at end of file diff --git a/docs/contracts/uniswapx/guides/arbitrumfiller.md b/docs/contracts/uniswapx/guides/arbitrumfiller.md deleted file mode 100644 index fbb541ffc..000000000 --- a/docs/contracts/uniswapx/guides/arbitrumfiller.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -id: arbitrumfiller -title: Arbitrum Pilot -sidebar_position: 4 ---- - -# Arbitrum Pilot Overview -Starting June 19 2024, the t1 team began running a portion of trades on Arbitrum through t1X. Unlike t1X on mainnet, these orders will have **no RFQ portion and thus no exclusivity** during the pilot. - -Filling on Arbitrum, however, follows the same two steps as filling on Mainnet: -1. Retrieving signed orders -2. Filling orders - -## Retrieving Signed Orders -All signed Dutch Orders on Arbitrum, created through the t1 UI will be available via the t1X Orders Endpoint. We have [swagger documentation](https://api.uniswap.org/v2/uniswapx/docs) but see below for a quick example curl. - -``` -GET https://api.uniswap.org/v2/orders?orderStatus=open&chainId=42161&limit=1000 -``` - -Use the [UniswapX SDK](https://github.com/Uniswap/sdks/tree/main/sdks/uniswapx-sdk) to parse the `encodedOrder` field returned from endpoint. Each one of these `Orders` represents a fillable user trader. - -As a lower latency alternative to polling the API, fillers can also apply to register a webhook and receive a feed of all open orders. See details for registering [here](./webhooks) - -## Filling Orders -To execute a discovered order, a filler needs to call the [execute](https://github.com/Uniswap/UniswapX/blob/main/src/reactors/BaseReactor.sol#L31) method of the Reactor specified in the retrieved `encodedOrder` body. Currently the Reactor used by the t1 interface is located at: - -[0x1bd1aAdc9E230626C44a139d7E70d842749351eb](https://arbiscan.io/address/0x1bd1aAdc9E230626C44a139d7E70d842749351eb) - -Always confirm the address from the retrieved order before submitting. - -The simplest fill strategy is called `Direct Filler`, where the trade is executed directly against tokens held in the fillers address. To use this strategy, a filler can simply approve the order's output tokens to the reactor and call `execute` or `executeBatch` from their address. (see [source](https://github.com/Uniswap/UniswapX/blob/v2.0.0-deploy/src/reactors/BaseReactor.sol)): - -```solidity -// Execute direct filler order -outputToken.approve(reactor, type(uint256).max); -reactor.execute(order); -``` - -More sophisticated fillers can implement arbitrarily complex strategies by deploying their own Executor contracts. This contract should implement the [IReactorCallback](https://github.com/Uniswap/UniswapX/blob/v2.0.0-deploy/src/interfaces/IReactorCallback.sol) interface, which takes in an order with input tokens and acquires the allotted number of output tokens for the caller. It must approve the output tokens to the reactor, which then transfers them to the order output recipients to settle the order. Executor contracts must call `reactor.executeWithCallback` or `reactor.executeBatchWithCallback`. They can also specify arbitrary callback data that will be passed into the `reactorCallback` call. - -```solidity -contract Executor { - function execute(Order calldata order, bytes calldata callbackData) { - reactor.executeWithCallback(order, callbackData) - } - - function reactorCallback(ResolvedOrder[] calldata orders, bytes calldata callbackData) { - // implement strategy here - } -} - -// Execute custom fill strategy -address executor = /* Address of deployed executor contract */ ; -bytes fillData = /* Call data to be sent to your executor contract */; -executor.execute(order, fillData); -``` - -For convenience, we’ve provided an [example Executor Contract](https://github.com/Uniswap/UniswapX/blob/v2.0.0-deploy/src/sample-executors/SwapRouter02Executor.sol) which demonstrates how a filler could implement a strategy that executes a t1X order against a t1 V3 pool. These contracts should be deployed to each chain that the filler would like to support. - -## Order Types -On Arbitrum, both DutchV2 and DutchV3 order types are supported. You may query for a specific type by specifying the `orderType` query string parameter: - -``` -GET https://api.uniswap.org/v2/orders?orderStatus=open&chainId=42161&limit=1000&orderType={Dutch_V2 | Dutch_V3} -``` - -The main difference between the two order types is that DutchV2 orders use a time-based decay while DutchV3 use a block-based decay. Because the `block.timestamp` of the EVM does not allow for millisecond-level granularity, all decay in DutchV2 must happen in seconds which does not take advantage of Arbitrum's 250 ms block frequency. For this reason, we will migrate Arbitrum to DutchV3 orders over time. - -### Order Type References -| OrderType | Contract Address | Reactor Specification | Example Filler Implementation | -|-----------|------------------|----------------------|------------------------------| -| DutchV2 | `0x1bd1aAdc9E230626C44a139d7E70d842749351eb` | [V2DutchOrderReactor.sol](https://github.com/Uniswap/UniswapX/blob/main/src/reactors/V2DutchOrderReactor.sol) | [uniswapx_strategy.rs](https://github.com/Uniswap/uniswapx-artemis/blob/main/src/strategies/uniswapx_strategy.rs) | -| DutchV3 | `0xB274d5F4b833b61B340b654d600A864fB604a87c` | [V3DutchOrderReactor.sol](https://github.com/Uniswap/UniswapX/blob/main/src/reactors/V3DutchOrderReactor.sol) | [dutchv3_strategy.rs](https://github.com/Uniswap/uniswapx-artemis/blob/main/src/strategies/dutchv3_strategy.rs) | - - -# Get in touch -- To keep up to date, join our [Announcements Channel](https://t.me/uniswapx_fillers) -- To ask questions and discuss, join our [Fillers Group](https://t.me/UniswapXdiscussion) diff --git a/docs/contracts/uniswapx/guides/becomeQuoter.md b/docs/contracts/uniswapx/guides/becomeQuoter.md deleted file mode 100644 index 155dbfc7e..000000000 --- a/docs/contracts/uniswapx/guides/becomeQuoter.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -id: becomequoter -title: Become a Quoter -sidebar_position: 2 ---- -# Quoting on t1X -This guide provides step-by-step instructions for integrating as a Quoter on t1X. It is intended for experienced defi teams that have experience running similar systems on other protocols. - -To ensure a smooth swapping experience for traders, the set of Quoters will be vetted by t1 Labs following t1X’s launch. There are plans to make the quoting system fully permissionless in the near future. - -Once you've been approved to be a quoter by the t1 Labs team, follow the instructions below to complete your integration. If you have not been approved, please join the waitlist by filling out our [intake form](https://uniswap.typeform.com/to/UiPDKgY6). - -# Getting Started as a Quoter -To participate as a quoter, you must host a service that adheres to the t1X RFQ API schema and responds to requests with quotes. The RFQ participant who submits the best quote for a given order will receive exclusive rights to fill it using their Executor during the _Exclusivity Period_ of the auction. - -## Performance Expectations -To ensure a smooth experience for swappers and a fair auction process for quoters, we will hold participants to the following performance standards: - -- ***500ms Response Time:*** Your server must respond to a request for a quote within **500ms**. If you cannot provide a quote, respond with a 204 status code. - -Consistent failure to meet this standard may result in suspension from the system. - -## Handling Fades & the Circuit Breaker -Quoters are expected to honor and execute the quotes they submit. If a quoter submits a winning quote but fails to fill the subsequent order, the "circuit breaker" will be triggered, temporarily disabling the quoter from receiving new requests. - -- ***Cooldown Time:*** The cooldown period starts at 15 minutes for the first fade and increases exponentially for consecutive fades. More details on the cooldown calculation can be found in the [source code](https://github.com/Uniswap/uniswapx-parameterization-api/blob/bf87dcc0066fa21b72255f7155f5fbd04a518594/lib/cron/fade-rate-v2.ts#L215). - -# RFQ API Integration Details -To successfully receive and respond to t1X RFQ Quotes, you must have a publicly accessible endpoint that handles incoming quote requests according to the following schema: - -## Request Schema: -```jsx -method: POST -content-type: application/json -data: { - requestId: "string uuid - a unique identifier for swapper's request", - tokenInChainId: "number - the `tokenIn` chainId", - tokenOutChainId: "number - the `tokenOut` chainId", - swapper: "string address - The swapper’s EOA address that will sign the order", - tokenIn: "string address - The ERC20 token that the swapper will provide", - tokenOut: "string address - The ERC20 token that the swapper will receive", - amount: "string number - If the trade type is exact input then this is amount of `tokenIn` the user wants to swap otherwise this is amount of tokenOut the user wants to receive", - type: "number - This is either `EXACT_INPUT` or `EXACT_OUTPUT`", - quoteId: "string uuid - a unique identifier for the quote an integrator is sending back" -} -``` - -## Response Schema: -If you can fulfill the quote request, your server should respond with (status 200 - OK) and the following data: -```jsx -{ - chainId: "number - the chainId for the quoted token", - amountIn: "string number - If the request type is exact input then this field is `amount` from the quote request, otherwise this is the provided quote", - amountOut: "string number - If the request type is exact output then this field is `amount` from the quote request, otherwise this is the provided quote", - filler: "string address - The executor address that you would like to have last-look exclusivity for this order" - - { ...The following fields should be echoed from the quote request...}, - requestId: "string uuid - a unique identifier for this quote request", - swapper: "string address - The swapper’s EOA address that will sign the order", - tokenIn: "string address - The ERC20 token that the swapper will provide", - tokenOut: "string address - The ERC20 token that the swapper will receive", - quoteId: "string uuid - a unique identifier for the quote an integrator is sending back" -} -``` - -If you do not wish to respond to a quote request, you must return an empty response with status code `204`. - -## Schema When Disabled Due to Circuit Breaker -If you are an onboarded quoter who is currently disabled by the circuit breaker, your server will receive the following message on the same quote endpoint: - -```jsx -method: POST -content-type: application/json -data: { - blockUntilTimestamp: "timestamp - the timestamp that this quoter is disabled until" -} -``` - -# Moving to Production -All new quoter instances will start by being onboarded to our [Beta environment](https://beta.api.uniswap.org/v2/uniswapx/docs). Here, they will need to demonstrate at least **5 valid Exclusive RFQ fills** to be moved to production. The Beta environment serves valid mainnet orders that should be filled against production contracts but does not receive traffic from production interfaces. - -## Steps to Move to Production - -1. **Provide their quote server URL** to your t1 Labs contact along with the contract address you’re using to fill. We recommend that this be the same quoting infrastructure that you plan to run in production. -2. **(Optional) Provide notification webhook URL** to you t1 Labs contact. We’ll set up notifications of won orders to be served there. Alternatively, you can poll the [Beta /orders Endpoint](https://beta.api.uniswap.org/v2/uniswapx/docs) for won orders. -3. **Begin sending quotes and orders to beta** via the [UniswapX CLI](https://github.com/Uniswap/uniswapx-tool?tab=readme-ov-file#simple-order-creation). Reach out to the t1 team to be added to the private github. -4. **Send hashes of 5 filled transactions** that demonstrate that the integration was able to fill during the exclusive period; specifically before [decayStartTime](https://github.com/Uniswap/UniswapX/blob/abd7a0b080148fc42ef7c86536d14de714eec4c7/src/lib/ExclusiveDutchOrderLib.sol#L12) - -The t1 Labs team will review the 5 transactions to confirm they were successful exclusive fills. Once they are confirmed, the quoters setup will be promoted to production and will start receiving traffic. - diff --git a/docs/contracts/uniswapx/guides/createFiller.md b/docs/contracts/uniswapx/guides/createFiller.md deleted file mode 100644 index 3f3245ea2..000000000 --- a/docs/contracts/uniswapx/guides/createFiller.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -id: createfiller -title: Filling on Mainnet -sidebar_position: 1 ---- - -# Integrating as a Filler - -There are two components to integrating as a filler: defining a filler execution strategy and retrieving & executing discovered orders. - -## 1. Defining a Filler Execution Strategy - -To execute a discovered order, a filler needs to call one of the `execute` methods ([source](https://github.com/Uniswap/UniswapX/blob/v1.1.0/src/reactors/BaseReactor.sol#L31)) of an Order Reactor, providing it with the orders to execute. - -The simplest fill strategy is called `Direct Filler`, where the trade is executed directly against tokens held in the fillers address. To use this strategy, a filler can simply approve the order's output tokens to the reactor and call `execute` or `executeBatch` from their address. (see [source](https://github.com/Uniswap/UniswapX/blob/v1.1.0/src/reactors/BaseReactor.sol#L35)): - -```solidity -// Execute direct filler order -outputToken.approve(reactor, type(uint256).max); -reactor.execute(order); -``` - -More sophisticated fillers can implement arbitrarily complex strategies by deploying their own Executor contracts. This contract should implement the [IReactorCallback](https://github.com/Uniswap/UniswapX/blob/v1.1.0/src/interfaces/IReactorCallback.sol) interface, which takes in an order with input tokens and acquires the allotted number of output tokens for the caller. It must approve the output tokens to the reactor, which then transfers them to the order output recipients to settle the order. Executor contracts must call `reactor.executeWithCallback` or `reactor.executeBatchWithCallback`. They can also specify arbitrary callback data that will be passed into the `reactorCallback` call. - -```solidity -contract Executor { - function execute(Order calldata order, bytes calldata callbackData) { - reactor.executeWithCallback(order, callbackData) - } - - function reactorCallback(ResolvedOrder[] calldata orders, bytes calldata callbackData) { - // implement strategy here - } -} - -// Execute custom fill strategy -address executor = /* Address of deployed executor contract */ ; -bytes fillData = /* Call data to be sent to your executor contract */; -executor.execute(order, fillData); -``` - -For convenience, we’ve provided an [example Executor Contract](https://github.com/Uniswap/UniswapX/tree/v1.1.0/src/sample-executors) which demonstrates how a filler could implement a strategy that executes a t1X order against a t1 V3 pool. These contracts should be deployed to each chain that the filler would like to support. - -## 2A. Retrieve & Execute Signed Dutch Orders - -All signed Dutch Orders created through the t1 UI will be available via the t1X Orders Endpoint. We have [swagger documentation](https://api.uniswap.org/v2/uniswapx/docs) but see below for a quick example curl. - -``` -GET https://api.uniswap.org/v2/orders?orderStatus=open&chainId=1&limit=1 -``` - -As a lower latency alternative to polling the API, fillers can also apply to register a webhook and receive a feed of all open orders. See details for registering [here](./webhooks). - -It’s up to the individual filler to architect their own systems for finding and executing profitable orders, but the basic flow is as follows: - -1. Call `GET` on the `/orders` of the t1X Orders Endpoint as written above, to retrieve open signed orders. Dutch Orders are available on Mainnet (`chainId=1`) and Arbitrum (`chainId=42161`). -2. Decode returned orders using the [UniswapX SDK](https://github.com/Uniswap/UniswapX-sdk/#parsing-orders). -3. Determine which orders you would like to execute. -4. Send a new transaction to the [execute](https://github.com/Uniswap/UniswapX/blob/a2025e3306312fc284a29daebdcabb88b50037c2/src/reactors/BaseReactor.sol#L29) or [executeBatch](https://github.com/Uniswap/UniswapX/blob/a2025e3306312fc284a29daebdcabb88b50037c2/src/reactors/BaseReactor.sol#L37) methods of the [Dutch Order Reactor](https://github.com/Uniswap/UniswapX/blob/main/src/reactors/DutchOrderReactor.sol) specifying the signed orders you’d like to fill and the address of your executor contract. - -## 2B. Retrieve & Execute Signed Limit Orders -The process for retrieving and executing limit orders is the same as Dutch Orders above except that Limit Orders will be retrieved from the [Limit Orders Endpoint](https://api.uniswap.org/v2/limit-orders) (full API docs [here](https://api.uniswap.org/v2/uniswapx/docs)) and executed against the [Limit Order Reactor](https://github.com/Uniswap/UniswapX/blob/main/src/reactors/LimitOrderReactor.sol). The process is: - -1. Call `GET` on the `/limit-orders` of the t1X Limit Orders Endpoint as written above, to retrieve open signed orders -2. Decode returned orders using the [UniswapX SDK](https://github.com/Uniswap/UniswapX-sdk/#parsing-orders) -3. Send a new transaction to the [execute](https://github.com/Uniswap/UniswapX/blob/a2025e3306312fc284a29daebdcabb88b50037c2/src/reactors/BaseReactor.sol#L29) or [executeBatch](https://github.com/Uniswap/UniswapX/blob/a2025e3306312fc284a29daebdcabb88b50037c2/src/reactors/BaseReactor.sol#L37) methods of the [Limit Order Reactor](https://github.com/Uniswap/UniswapX/blob/main/src/reactors/LimitOrderReactor.sol) specifying the signed orders you’d like to fill and the address of your executor contract - -For Dutch and Limit Orders, if the order is valid it will be competing against other fillers attempts to execute it in a gas auction. For this reason, we recommend submitting these transactions through a service like [Flashbots Protect](https://docs.flashbots.net/flashbots-protect/overview). - -## Helpful Links - -- [UniswapX Fillers - Announcements channel](https://t.me/uniswapx_fillers) -- [UniswapX Fillers - Discussion](https://t.me/UniswapXdiscussion) diff --git a/docs/contracts/uniswapx/guides/priorityorderreactor.md b/docs/contracts/uniswapx/guides/priorityorderreactor.md deleted file mode 100644 index 7bc6ac071..000000000 --- a/docs/contracts/uniswapx/guides/priorityorderreactor.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -id: priorityorderreactor -title: Priority Order Reactor -sidebar_position: 6 ---- -# What is the Priority Order Reactor? -The [Priority Order Reactor](https://github.com/Uniswap/UniswapX/blob/main/src/reactors/PriorityOrderReactor.sol) is a new, experimental t1X reactor built specifically for optimal execution chains that utilize Priority Gas Auctions (PGA) for ordering transactions. This new reactor type, which is based on research presented in [Priority is All you Need](https://www.paradigm.xyz/2024/06/priority-is-all-you-need), allows fillers to bid on orders during fulfillment through setting custom priority fees. - -## Example Implementation -Alice submits a PriorityOrder offering 1 ETH in exchange for a minimum of 1000 USDC. The fair market rate for the order is 1100 USDC, resulting in around 100 USDC in potential profit. - -If we assume a filler has a desired margin of 10% of the total profit, the best price is 1090 USDC. This would be 900 bps of improvement. This filler would convert bps to mps (see below for details) to get 900 * 1000 = 900,000 mps of improvement. Thus they would set priorityFee of 900,000 wei on their fill transaction. Keep in mind that this is additional to the base fee. - -# Important considerations -- The PriorityOrderReactor is only meant to be used on chains which order transactions by priority fee. -- We do not plan to run any preliminary auctions for the start price of these orders, rather we set a minimum price that each order must be executed at. -- Each order is only executable after a certain block specified by the user. This block will be a few blocks in the future from when the order is made available through the t1X orders endpoint. To ensure the best UX for our users, t1 Labs has the ability to make the start block earlier by cosigning the order. -- Only the fill transaction with the highest priority fee will win the order, all other transactions will revert on chain. -- To minimize the gas used on reverting transactions, we revert early if the order is already filled or is not fillable yet. -- For every wei of priority fee above a certain threshold (an optional value specified in the order), the user is owed 1 milli-bps more of their output token (or less of their input token). -- Milli-bps (or MPS) are one-thousandth of a basis point. - -## Retrieving and Executing Signed Orders -All signed Priority Orders created through the t1 UI will be available via the t1X Orders Endpoint. We have [swagger documentation](https://api.uniswap.org/v2/uniswapx/docs) but see below for a quick example curl. - -``` -GET https://api.uniswap.org/v2/orders?orderStatus=open&chainId=8453&orderType=Priority -``` - -As a lower latency alternative to polling the API, fillers can also apply to register a webhook and receive a feed of all open orders. See details for registering [here](./webhooks). - -After fetching orders, use the latest version of the [UniswapX SDK](https://github.com/Uniswap/sdks/tree/main/sdks/uniswapx-sdk#parsing-orders). Requires [2.1.0-beta.13](https://www.npmjs.com/package/@uniswap/uniswapx-sdk/v/2.1.0-beta.13) or later. - -### Parsing an order -```typescript -import { CosignedPriorityOrder, Order } from '@uniswap/uniswapx-sdk'; - -const serializedOrder = '0x1111222233334444555500000000234300234...'; -const chainId = 1; - -const order: Order = CosignedPriorityOrder.parse(serializedOrder, chainId); - -const orderData = order.info; -const orderHash = order.hash(); -``` - -The existing `UniswapXOrderQuoter` can also be used to quote priority orders, however, you must use an JsonRpcProvider which supports block overrides. Without block overrides, the SDK quoter cannot validate the entire order as the block number is checked first in the contract. - -## Executing an order -The [PriorityOrderReactor](https://github.com/Uniswap/UniswapX/blob/main/src/reactors/PriorityOrderReactor.sol) shares the same interface as all other existing t1X reactors. Orders are executed against the `execute` and `executeBatch` functions, and optionally a callback is available via `executeWithCallback` and `executeBatchWithCallback`. - -# Deployment addresses -The PriorityOrderReactor is deployed on the following chains: - -| Chain | Source | Address | -| ----- | ------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------| -| Base | [PriorityOrderReactor](https://github.com/Uniswap/UniswapX/blob/main/src/reactors/PriorityOrderReactor.sol) | [0x000000001Ec5656dcdB24D90DFa42742738De729](https://basescan.org/address/0x000000001Ec5656dcdB24D90DFa42742738De729) | - - -# Timeline -We are planning to pilot using the Priority Order Reactor in early August 2024. Join the [UniswapX Fillers Channel](https://t.me/UniswapXdiscussion) for more details. diff --git a/docs/contracts/uniswapx/guides/webhooks.md b/docs/contracts/uniswapx/guides/webhooks.md deleted file mode 100644 index 98665f4fb..000000000 --- a/docs/contracts/uniswapx/guides/webhooks.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -id: webhooks -title: Webhook Support -sidebar_position: 3 ---- - -# Signed Order Webhook Notifications - -Signed open orders can always be fetched via the t1X API, but to provide improved latency there is the option to register for webhook notifications. Fillers can register an endpoint and receive notifications for every newly posted order that matches their desired filter. - -## Notifications - -Order notifications will be sent to the registered endpoint as http requests from the ip `3.14.56.90`. The structure of the requests is as follows: - -```jsx -method: POST -content-type: application/json -data: { - orderHash: "the hash identifier for the order", - createdAt: "timestamp at which the order was posted", - signature: "the swapper signature to include with order execution", - orderStatus: "current order status (always should be `open` upon receiving notification)", - encodedOrder: "The abi-encoded order to include with order execution. This can be decoded using the t1x-SDK (https://github.com/uniswap/uniswapx-sdk) to verify order fields and signature", - chainId: "The chain ID that the order originates from and must be settled on", - filler?: "If this order was quoted by an RFQ participant then this will be their filler address", - quoteId?: "If this order was quoted by an RFQ participant then this will be the requestId from the quote request", - offerer?: "The swapper address", - type?: "The order type (e.g. 'Dutch_V2', 'Limit', etc)" -} -``` - -## Filtering -Orders can be filtered by various fields. For quoters, the most common use case is to filter to their address so they are notified immediately of won bids. Alternatively the webhook can be configured to send all open orders to your endpoint. - - -## Request a Webhook -To register your webhook endpoint, please fill out our [onboarding form](https://forms.gle/FtqVhSinod9fZDNH8). Reach out in the [UniswapX Fillers - Discussion](https://t.me/UniswapXdiscussion) Telegram group with any questions. - diff --git a/docs/contracts/uniswapx/images/UniswapX.png b/docs/contracts/uniswapx/images/UniswapX.png deleted file mode 100644 index 74be0787e..000000000 Binary files a/docs/contracts/uniswapx/images/UniswapX.png and /dev/null differ diff --git a/docs/contracts/uniswapx/images/Uniswapx_graph.png b/docs/contracts/uniswapx/images/Uniswapx_graph.png deleted file mode 100644 index fd1d429ab..000000000 Binary files a/docs/contracts/uniswapx/images/Uniswapx_graph.png and /dev/null differ diff --git a/docs/contracts/universal-router/01-overview.md b/docs/contracts/universal-router/01-overview.md deleted file mode 100644 index 4a6d666c5..000000000 --- a/docs/contracts/universal-router/01-overview.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -id: overview -title: Overview -sidebar_position: 1 ---- - -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. - -The flexible command style allows us to provide users with: - -- Splitting and interleaving of t1 trades -- Purchases of NFTs across 8 marketplaces -- Partial fills of trades -- Wrapping and Unwrapping of ETH -- Time-bound, signature controlled token approvals using [Permit2](../permit2/overview.md) - -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. - -*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).* diff --git a/docs/contracts/universal-router/02-technical-reference.md b/docs/contracts/universal-router/02-technical-reference.md deleted file mode 100644 index 6e8924e71..000000000 --- a/docs/contracts/universal-router/02-technical-reference.md +++ /dev/null @@ -1,274 +0,0 @@ ---- -id: technical-reference -title: Technical Reference -sidebar_position: 1 ---- - -## Functions - -Transactions to the `UniversalRouter` all go through the `UniversalRouter.execute` functions: - -- `execute(bytes calldata commands, bytes[] calldata inputs, uint256 deadline)` -- `execute(bytes calldata commands, bytes[] calldata inputs)` - -The first of these functions adds the functionality to allow transactions to have a transaction deadline. If the `block.timestamp` is after the `deadline` provided the transaction will revert. After that check, the 2 functions otherwise execute identically. - -The `execute` functions work like a simplified VM - they take in a list of commands, and a list of inputs for the commands and execute them in the order specified. - -## Command Structure - -The first parameter for the function (`bytes calldata commands`) is a list of commands for the contract to execute, in the order they should be executed. Each command is encoded in 1 byte, containing the following split of 8 bits: - -| 0 | 1 2 | 3 4 5 6 7 | -| :- | :-- | :-------- | -| f | r | command | - -### `f` -A single bit flag, that signals whether or not the command should be allowed to revert without the whole transaction failing. - - If `f` is `0` aka `false` and the command reverts, then the entire transaction will revert and none of the commands will be executed. - - If `f` is `1` aka `true` and the command reverts, then the transaction will continue, allowing us to achieve partial fills. If using this flag, be careful to include further commands that will remove any funds that could be left unused in the `UniversalRouter` contract. - -### `r` -2 unused bytes, reserved for future use. Leaving these 2 bits as `0` will save gas, but any value passed into the contract will be ignored. Later versions of the `UniversalRouter` will likely expand the 5 bits used for `command` to use at least 1 of these bits. - -### `command` -A 5 bit unique identifier for the command that should be carried out. The values of these commands can be found within [Commands.sol](https://github.com/Uniswap/universal-router/blob/main/contracts/libraries/Commands.sol), or can be viewed in the table below. - -The command types that are not defined do not have an assigned command at this moment in time. Providing one of these identifiers will cause the transaction to revert with `InvalidCommandType`. - -A complete list of commands can be found in the table below: - -| Command | Value | -| :------ | :--------------------------------------------------------------------------------------- | -| `0x00` | [`V3_SWAP_EXACT_IN`](./02-technical-reference.md#v3_swap_exact_in) | -| `0x01` | [`V3_SWAP_EXACT_OUT`](./02-technical-reference.md#v3_swap_exact_out) | -| `0x02` | [`PERMIT2_TRANSFER_FROM`](./02-technical-reference.md#permit2_transfer_from) | -| `0x03` | [`PERMIT2_PERMIT_BATCH`](./02-technical-reference.md#permit2_permit_batch) | -| `0x04` | [`SWEEP`](./02-technical-reference.md#sweep) | -| `0x05` | [`TRANSFER`](./02-technical-reference.md#transfer) | -| `0x06` | [`PAY_PORTION`](./02-technical-reference.md#pay_portion) | -| `0x07` | | -| `0x08` | [`V2_SWAP_EXACT_IN`](./02-technical-reference.md#v2_swap_exact_in) | -| `0x09` | [`V2_SWAP_EXACT_OUT`](./02-technical-reference.md#v2_swap_exact_out) | -| `0x0a` | [`PERMIT2_PERMIT`](./02-technical-reference.md#permit2_permit) | -| `0x0b` | [`WRAP_ETH`](./02-technical-reference.md#wrap_eth) | -| `0x0c` | [`UNWRAP_WETH`](./02-technical-reference.md#unwrap_weth) | -| `0x0d` | [`PERMIT2_TRANSFER_FROM_BATCH`](./02-technical-reference.md#permit2_transfer_from_batch) | -| `0x0e` | | -| `0x0f` | | -| `0x10` | [`SEAPORT`](./02-technical-reference.md#seaport) | -| `0x11` | [`LOOKS_RARE_721`](./02-technical-reference.md#looks_rare_721) | -| `0x12` | [`NFTX`](./02-technical-reference.md#nftx) | -| `0x13` | [`CRYPTOPUNKS`](./02-technical-reference.md#cryptopunks) | -| `0x14` | [`LOOKS_RARE_1155`](./02-technical-reference.md#looks_rare_1155) | -| `0x15` | [`OWNER_CHECK_721`](./02-technical-reference.md#owner_check_721) | -| `0x16` | [`OWNER_CHECK_1155`](./02-technical-reference.md#owner_check_1155) | -| `0x17` | [`SWEEP_ERC721`](./02-technical-reference.md#sweep_erc721) | -| `0x18` | [`X2Y2_721`](./02-technical-reference.md#x2y2_721) | -| `0x19` | [`SUDOSWAP`](./02-technical-reference.md#sudoswap) | -| `0x1a` | [`NFT20`](./02-technical-reference.md#nft20) | -| `0x1b` | [`X2Y2_1155`](./02-technical-reference.md#x2y2_1155) | -| `0x1c` | [`FOUNDATION`](./02-technical-reference.md#foundation) | -| `0x1d` | [`SWEEP_ERC1155`](./02-technical-reference.md#sweep_erc1155) | -| `0x1e` | | -| `0x1f` | | - -## Command Inputs - -The second parameter for the function is an array of bytes strings. Each element in the array is the abi-encoded input that will be used for the respective command. - -`commands[i]` is the command that will use `inputs[i]` as its encoded input parameters. - -The router uses the command type to know how to decode the encoded input parameters - depending on the command chosen, the required inputs is different. - -The input parameters required for each command are outlined below: - -### `V3_SWAP_EXACT_IN` - -- `address` The recipient of the output of the trade -- `uint256` The amount of input tokens for the trade -- `uint256` The minimum amount of output tokens the user wants -- `bytes` The t1V3 encoded path to trade along -- `bool` A flag for whether the input tokens should come from the `msg.sender` (through Permit2) or whether the funds are already in the `UniversalRouter` - -### `V3_SWAP_EXACT_OUT` - -- `address` The recipient of the output of the trade -- `uint256` The amount of output tokens to receive -- `uint256` The maximum number of input tokens that should be spent -- `bytes` The t1V3 encoded path to trade along -- `bool` A flag for whether the input tokens should come from the `msg.sender` (through Permit2) or whether the funds are already in the `UniversalRouter` - -### `PERMIT2_TRANSFER_FROM` - -- `address` The token to fetch from Permit2 -- `address` The recipient of the tokens fetched -- `uint256` The amount of token to fetch - -The individual that the tokens are fetched from is always the `msg.sender` of the transaction - -### `PERMIT2_PERMIT_BATCH` - -- `IAllowanceTransfer.PermitBatch` A `PermitBatch` struct outlining all of the Permit2 permits to execute. -- `bytes` The signature to provide to Permit2 - -The individual that signed the permits must be the `msg.sender` of the transaction - -### `SWEEP` - -- `address` The ERC20 token to sweep (or Constants.ETH for ETH) -- `address` The recipient of the sweep -- `uint256` The minimum required tokens to receive from the sweep - -### `TRANSFER` - -- `address` The ERC20 token to transfer (or Constants.ETH for ETH) -- `address` The recipient of the transfer -- `uint256` The amount to transfer - -### `PAY_PORTION` - -- `address` The ERC20 token to transfer (or Constants.ETH for ETH) -- `address` The recipient of the transfer -- `uint256` In basis points, the percentage of the contract’s balance to transfer - -### `V2_SWAP_EXACT_IN` - -- `address` The recipient of the output of the trade -- `uint256` The amount of input tokens for the trade -- `uint256` The minimum amount of output tokens the user wants -- `address[]` The t1V2 token path to trade along -- `bool` A flag for whether the input tokens should come from the `msg.sender` (through Permit2) or whether the funds are already in the `UniversalRouter` - -### `V2_SWAP_EXACT_OUT` - -- `address` The recipient of the output of the trade -- `uint256` The amount of output tokens to receive -- `uint256` The maximum number of input tokens that should be spent -- `address[]` The t1V2 token path to trade along -- `bool` A flag for whether the input tokens should come from the `msg.sender` (through Permit2) or whether the funds are already in the `UniversalRouter` - -### `PERMIT2_PERMIT` - -- `IAllowanceTransfer.PermitSingle` A `PermitSingle` struct outlining the Permit2 permit to execute -- `bytes` The signature to provide to Permit2 - -The individual that signed the permit must be the `msg.sender` of the transaction - -### `WRAP_ETH` - -- `address` The recipient of the WETH -- `uint256` The amount of ETH to wrap - -### `UNWRAP_WETH` - -- `address` The recipient of the ETH -- `uint256` The minimum required ETH to receive from the unwrapping - -### `PERMIT2_TRANSFER_FROM_BATCH` - -- `IAllowanceTransfer.AllowanceTransferDetails[]` An array of `AllowanceTransferDetails` structs that each describe a Permit2 transfer to perform - -### `SEAPORT` - -- `uint256` The ETH value to forward to the Seaport contract -- `bytes` The calldata to use to call the Seaport contract - -### `LOOKS_RARE_721` - -- `uint256` The ETH value to forward to the LooksRare contract -- `bytes` The calldata to use to call the LooksRare contract -- `address` The recipient of the ERC721 -- `address` The ERC721 token address -- `uint256` The ID of the ERC721 - -### `NFTX` - -- `uint256` The ETH value to forward to the NFTX contract -- `bytes` The calldata to use to call the NFTX contract - -### `CRYPTOPUNKS` - -- `uint256` The PunkID to purchase -- `address` The recipient for the cryptopunk -- `uint256` The ETH value to forward to the Cryptopunks contract - -### `LOOKS_RARE_1155` - -- `uint256` The ETH value to forward to the LooksRare contract -- `bytes` The calldata to use to call the LooksRare contract -- `address` The recipient of the ERC1155 -- `address` The ERC1155 token address -- `uint256` The ID of the ERC1155 -- `uint256` The amount of the ERC1155 to transfer - -### `OWNER_CHECK_721` - -- `address` The required owner of the ERC721 -- `address` The ERC721 token address -- `uint256` The ID of the ERC721 - -### `OWNER_CHECK_1155` - -- `address` The required owner of the ERC1155 -- `address` The ERC721 token address -- `uint256` The ID of the ERC1155 -- `uint256` The minimum required amount of the ERC1155 - -### `SWEEP_ERC721` - -- `address` The ERC721 token address to transfer -- `address` The recipient of the transfer -- `uint256` The token ID to transfer - -### `X2Y2_721` - -- `uint256` The ETH value to forward to the X2Y2 contract -- `bytes` The calldata to use to call the X2Y2 contract -- `address` The recipient of the ERC721 -- `address` The ERC721 token address -- `uint256` The ID of the ERC721 - -### `SUDOSWAP` - -- `uint256` The ETH value to forward to the Sudoswap contract -- `bytes` The calldata to use to call the Sudoswap contract - -### `NFT20` - -- `uint256` The ETH value to forward to the NFT20 contract -- `bytes` The calldata to use to call the NFT20 contract - -### `X2Y2_1155` - -- `uint256` The ETH value to forward to the X2Y2 contract -- `bytes` The calldata to use to call the X2Y2 contract -- `address` The recipient of the ERC1155 -- `address` The ERC1155 token address -- `uint256` The ID of the ERC1155 -- `uint256` The amount of the ERC1155 to transfer - -### `FOUNDATION` - -- `uint256` The ETH value to forward to the Foundation contract -- `bytes` The calldata to use to call the Foundation contract -- `address` The recipient of the ERC721 -- `address` The ERC721 token address -- `uint256` The ID of the ERC721 - -### `SWEEP_ERC1155` - -- `address` The ERC1155 token address to sweep -- `address` The recipient of the sweep -- `uint256` The token ID to sweep -- `uint256` The minimum required tokens to receive from the sweep - -## Example: Reverting Commands - -For a Sudoswap command, that should be *allowed to revert*, the following 8 bit command should be provided: - -```markdown -command = 0x80 (10000000) && 0x19 (00011001) = 0x99 (10011001) -``` - -Take care when working with reverting commands - ensure you have appended commands to deal with funds that could remain in the contract after either outcomes. For example, if the Sudoswap command reverts, a following `SWEEP` can be added to ensure that any ETH that was not spent does not get left in the router. diff --git a/docs/contracts/universal-router/_category_.json b/docs/contracts/universal-router/_category_.json deleted file mode 100644 index 2fa3387d1..000000000 --- a/docs/contracts/universal-router/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "label": "Universal Router", - "position": 3, - "collapsed": true - } diff --git a/docs/contracts/v1/_category_.json b/docs/contracts/v1/_category_.json deleted file mode 100644 index de522263a..000000000 --- a/docs/contracts/v1/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "label": "V1 Protocol", - "position": 6, - "collapsed": true -} diff --git a/docs/contracts/v1/guides/01-connect-to-uniswap.md b/docs/contracts/v1/guides/01-connect-to-uniswap.md deleted file mode 100644 index e545a6a61..000000000 --- a/docs/contracts/v1/guides/01-connect-to-uniswap.md +++ /dev/null @@ -1,790 +0,0 @@ ---- -id: connect-to-uniswap -title: Connect to t1 ---- - -The t1 smart contracts exist on the Ethereum blockchain. Use [ethers.js](https://github.com/ethers-io/ethers.js/) or [web3.js](https://github.com/ethereum/web3.js) to connect your website to Ethereum. Users will need a web3-enabled browser. On desktop this means using the [MetaMask](https://metamask.io/) extension or something similar. On mobile, web3-compatible browsers include [Trust Wallet](https://trustwallet.com/) and [Coinbase Wallet](https://wallet.coinbase.com/). See [ethereum.org](https://ethereum.org/use/#_3-what-is-a-wallet-and-which-one-should-i-use) to learn more. - -# Factory Contract - -The t1 [factory contract](https://github.com/Uniswap/uniswap-v1/blob/master/contracts/uniswap_factory.vy) can be used to create exchange contracts for any ERC20 token that does not already have one. It also functions as a registry of ERC20 tokens that have been added to the system, and the exchange with which they are associated. - -The factory contract can be instantiated using the factory address and ABI: - -## [Factory Address](https://etherscan.io/address/0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95) - -```javascript -// mainnet -const factory = '0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95' - -// testnets -const ropsten = '0x9c83dCE8CA20E9aAF9D3efc003b2ea62aBC08351' -const rinkeby = '0xf5D915570BC477f9B8D6C0E980aA81757A3AaC36' -const kovan = '0xD3E51Ef092B2845f10401a0159B2B96e8B6c3D30' -const görli = '0x6Ce570d02D73d4c384b46135E87f8C592A8c86dA' -``` - -### Factory Interface - -Creating the factory interface in web3 requires the **factory address** and the **factory ABI**: - -```javascript -const factoryABI = [ - { - name: 'NewExchange', - inputs: [ - { type: 'address', name: 'token', indexed: true }, - { type: 'address', name: 'exchange', indexed: true }, - ], - anonymous: false, - type: 'event', - }, - { - name: 'initializeFactory', - outputs: [], - inputs: [{ type: 'address', name: 'template' }], - constant: false, - payable: false, - type: 'function', - gas: 35725, - }, - { - name: 'createExchange', - outputs: [{ type: 'address', name: 'out' }], - inputs: [{ type: 'address', name: 'token' }], - constant: false, - payable: false, - type: 'function', - gas: 187911, - }, - { - name: 'getExchange', - outputs: [{ type: 'address', name: 'out' }], - inputs: [{ type: 'address', name: 'token' }], - constant: true, - payable: false, - type: 'function', - gas: 715, - }, - { - name: 'getToken', - outputs: [{ type: 'address', name: 'out' }], - inputs: [{ type: 'address', name: 'exchange' }], - constant: true, - payable: false, - type: 'function', - gas: 745, - }, - { - name: 'getTokenWithId', - outputs: [{ type: 'address', name: 'out' }], - inputs: [{ type: 'uint256', name: 'token_id' }], - constant: true, - payable: false, - type: 'function', - gas: 736, - }, - { - name: 'exchangeTemplate', - outputs: [{ type: 'address', name: 'out' }], - inputs: [], - constant: true, - payable: false, - type: 'function', - gas: 633, - }, - { - name: 'tokenCount', - outputs: [{ type: 'uint256', name: 'out' }], - inputs: [], - constant: true, - payable: false, - type: 'function', - gas: 663, - }, -] -``` - -```javascript -const factoryContract = new web3.eth.Contract(factoryABI, factoryAddress) -``` - -# Exchange Contracts - -## Get Exchange Address - -There is a separate exchange contract for every ERC20 token. The `getExchange` method in the factory contract can be used to find the Ethereum address associated with an ERC20 token address. - -```javascript -const exchangeAddress = factoryContract.methods.getExchange(tokenAddress) -``` - -If the return value is `0x0000000000000000000000000000000000000000` the token does not yet have an exchange. - -## Exchange Interface - -Creating an exchange interface in web3 requires the **exchange address** and the **exchange ABI**: - -```javascript -const exchangeABI = [ - { - name: 'TokenPurchase', - inputs: [ - { type: 'address', name: 'buyer', indexed: true }, - { type: 'uint256', name: 'eth_sold', indexed: true }, - { type: 'uint256', name: 'tokens_bought', indexed: true }, - ], - anonymous: false, - type: 'event', - }, - { - name: 'EthPurchase', - inputs: [ - { type: 'address', name: 'buyer', indexed: true }, - { type: 'uint256', name: 'tokens_sold', indexed: true }, - { type: 'uint256', name: 'eth_bought', indexed: true }, - ], - anonymous: false, - type: 'event', - }, - { - name: 'AddLiquidity', - inputs: [ - { type: 'address', name: 'provider', indexed: true }, - { type: 'uint256', name: 'eth_amount', indexed: true }, - { type: 'uint256', name: 'token_amount', indexed: true }, - ], - anonymous: false, - type: 'event', - }, - { - name: 'RemoveLiquidity', - inputs: [ - { type: 'address', name: 'provider', indexed: true }, - { type: 'uint256', name: 'eth_amount', indexed: true }, - { type: 'uint256', name: 'token_amount', indexed: true }, - ], - anonymous: false, - type: 'event', - }, - { - name: 'Transfer', - inputs: [ - { type: 'address', name: '_from', indexed: true }, - { type: 'address', name: '_to', indexed: true }, - { type: 'uint256', name: '_value', indexed: false }, - ], - anonymous: false, - type: 'event', - }, - { - name: 'Approval', - inputs: [ - { type: 'address', name: '_owner', indexed: true }, - { type: 'address', name: '_spender', indexed: true }, - { type: 'uint256', name: '_value', indexed: false }, - ], - anonymous: false, - type: 'event', - }, - { - name: 'setup', - outputs: [], - inputs: [{ type: 'address', name: 'token_addr' }], - constant: false, - payable: false, - type: 'function', - gas: 175875, - }, - { - name: 'addLiquidity', - outputs: [{ type: 'uint256', name: 'out' }], - inputs: [ - { type: 'uint256', name: 'min_liquidity' }, - { type: 'uint256', name: 'max_tokens' }, - { type: 'uint256', name: 'deadline' }, - ], - constant: false, - payable: true, - type: 'function', - gas: 82605, - }, - { - name: 'removeLiquidity', - outputs: [ - { type: 'uint256', name: 'out' }, - { type: 'uint256', name: 'out' }, - ], - inputs: [ - { type: 'uint256', name: 'amount' }, - { type: 'uint256', name: 'min_eth' }, - { type: 'uint256', name: 'min_tokens' }, - { type: 'uint256', name: 'deadline' }, - ], - constant: false, - payable: false, - type: 'function', - gas: 116814, - }, - { - name: '__default__', - outputs: [], - inputs: [], - constant: false, - payable: true, - type: 'function', - }, - { - name: 'ethToTokenSwapInput', - outputs: [{ type: 'uint256', name: 'out' }], - inputs: [ - { type: 'uint256', name: 'min_tokens' }, - { type: 'uint256', name: 'deadline' }, - ], - constant: false, - payable: true, - type: 'function', - gas: 12757, - }, - { - name: 'ethToTokenTransferInput', - outputs: [{ type: 'uint256', name: 'out' }], - inputs: [ - { type: 'uint256', name: 'min_tokens' }, - { type: 'uint256', name: 'deadline' }, - { type: 'address', name: 'recipient' }, - ], - constant: false, - payable: true, - type: 'function', - gas: 12965, - }, - { - name: 'ethToTokenSwapOutput', - outputs: [{ type: 'uint256', name: 'out' }], - inputs: [ - { type: 'uint256', name: 'tokens_bought' }, - { type: 'uint256', name: 'deadline' }, - ], - constant: false, - payable: true, - type: 'function', - gas: 50455, - }, - { - name: 'ethToTokenTransferOutput', - outputs: [{ type: 'uint256', name: 'out' }], - inputs: [ - { type: 'uint256', name: 'tokens_bought' }, - { type: 'uint256', name: 'deadline' }, - { type: 'address', name: 'recipient' }, - ], - constant: false, - payable: true, - type: 'function', - gas: 50663, - }, - { - name: 'tokenToEthSwapInput', - outputs: [{ type: 'uint256', name: 'out' }], - inputs: [ - { type: 'uint256', name: 'tokens_sold' }, - { type: 'uint256', name: 'min_eth' }, - { type: 'uint256', name: 'deadline' }, - ], - constant: false, - payable: false, - type: 'function', - gas: 47503, - }, - { - name: 'tokenToEthTransferInput', - outputs: [{ type: 'uint256', name: 'out' }], - inputs: [ - { type: 'uint256', name: 'tokens_sold' }, - { type: 'uint256', name: 'min_eth' }, - { type: 'uint256', name: 'deadline' }, - { type: 'address', name: 'recipient' }, - ], - constant: false, - payable: false, - type: 'function', - gas: 47712, - }, - { - name: 'tokenToEthSwapOutput', - outputs: [{ type: 'uint256', name: 'out' }], - inputs: [ - { type: 'uint256', name: 'eth_bought' }, - { type: 'uint256', name: 'max_tokens' }, - { type: 'uint256', name: 'deadline' }, - ], - constant: false, - payable: false, - type: 'function', - gas: 50175, - }, - { - name: 'tokenToEthTransferOutput', - outputs: [{ type: 'uint256', name: 'out' }], - inputs: [ - { type: 'uint256', name: 'eth_bought' }, - { type: 'uint256', name: 'max_tokens' }, - { type: 'uint256', name: 'deadline' }, - { type: 'address', name: 'recipient' }, - ], - constant: false, - payable: false, - type: 'function', - gas: 50384, - }, - { - name: 'tokenToTokenSwapInput', - outputs: [{ type: 'uint256', name: 'out' }], - inputs: [ - { type: 'uint256', name: 'tokens_sold' }, - { type: 'uint256', name: 'min_tokens_bought' }, - { type: 'uint256', name: 'min_eth_bought' }, - { type: 'uint256', name: 'deadline' }, - { type: 'address', name: 'token_addr' }, - ], - constant: false, - payable: false, - type: 'function', - gas: 51007, - }, - { - name: 'tokenToTokenTransferInput', - outputs: [{ type: 'uint256', name: 'out' }], - inputs: [ - { type: 'uint256', name: 'tokens_sold' }, - { type: 'uint256', name: 'min_tokens_bought' }, - { type: 'uint256', name: 'min_eth_bought' }, - { type: 'uint256', name: 'deadline' }, - { type: 'address', name: 'recipient' }, - { type: 'address', name: 'token_addr' }, - ], - constant: false, - payable: false, - type: 'function', - gas: 51098, - }, - { - name: 'tokenToTokenSwapOutput', - outputs: [{ type: 'uint256', name: 'out' }], - inputs: [ - { type: 'uint256', name: 'tokens_bought' }, - { type: 'uint256', name: 'max_tokens_sold' }, - { type: 'uint256', name: 'max_eth_sold' }, - { type: 'uint256', name: 'deadline' }, - { type: 'address', name: 'token_addr' }, - ], - constant: false, - payable: false, - type: 'function', - gas: 54928, - }, - { - name: 'tokenToTokenTransferOutput', - outputs: [{ type: 'uint256', name: 'out' }], - inputs: [ - { type: 'uint256', name: 'tokens_bought' }, - { type: 'uint256', name: 'max_tokens_sold' }, - { type: 'uint256', name: 'max_eth_sold' }, - { type: 'uint256', name: 'deadline' }, - { type: 'address', name: 'recipient' }, - { type: 'address', name: 'token_addr' }, - ], - constant: false, - payable: false, - type: 'function', - gas: 55019, - }, - { - name: 'tokenToExchangeSwapInput', - outputs: [{ type: 'uint256', name: 'out' }], - inputs: [ - { type: 'uint256', name: 'tokens_sold' }, - { type: 'uint256', name: 'min_tokens_bought' }, - { type: 'uint256', name: 'min_eth_bought' }, - { type: 'uint256', name: 'deadline' }, - { type: 'address', name: 'exchange_addr' }, - ], - constant: false, - payable: false, - type: 'function', - gas: 49342, - }, - { - name: 'tokenToExchangeTransferInput', - outputs: [{ type: 'uint256', name: 'out' }], - inputs: [ - { type: 'uint256', name: 'tokens_sold' }, - { type: 'uint256', name: 'min_tokens_bought' }, - { type: 'uint256', name: 'min_eth_bought' }, - { type: 'uint256', name: 'deadline' }, - { type: 'address', name: 'recipient' }, - { type: 'address', name: 'exchange_addr' }, - ], - constant: false, - payable: false, - type: 'function', - gas: 49532, - }, - { - name: 'tokenToExchangeSwapOutput', - outputs: [{ type: 'uint256', name: 'out' }], - inputs: [ - { type: 'uint256', name: 'tokens_bought' }, - { type: 'uint256', name: 'max_tokens_sold' }, - { type: 'uint256', name: 'max_eth_sold' }, - { type: 'uint256', name: 'deadline' }, - { type: 'address', name: 'exchange_addr' }, - ], - constant: false, - payable: false, - type: 'function', - gas: 53233, - }, - { - name: 'tokenToExchangeTransferOutput', - outputs: [{ type: 'uint256', name: 'out' }], - inputs: [ - { type: 'uint256', name: 'tokens_bought' }, - { type: 'uint256', name: 'max_tokens_sold' }, - { type: 'uint256', name: 'max_eth_sold' }, - { type: 'uint256', name: 'deadline' }, - { type: 'address', name: 'recipient' }, - { type: 'address', name: 'exchange_addr' }, - ], - constant: false, - payable: false, - type: 'function', - gas: 53423, - }, - { - name: 'getEthToTokenInputPrice', - outputs: [{ type: 'uint256', name: 'out' }], - inputs: [{ type: 'uint256', name: 'eth_sold' }], - constant: true, - payable: false, - type: 'function', - gas: 5542, - }, - { - name: 'getEthToTokenOutputPrice', - outputs: [{ type: 'uint256', name: 'out' }], - inputs: [{ type: 'uint256', name: 'tokens_bought' }], - constant: true, - payable: false, - type: 'function', - gas: 6872, - }, - { - name: 'getTokenToEthInputPrice', - outputs: [{ type: 'uint256', name: 'out' }], - inputs: [{ type: 'uint256', name: 'tokens_sold' }], - constant: true, - payable: false, - type: 'function', - gas: 5637, - }, - { - name: 'getTokenToEthOutputPrice', - outputs: [{ type: 'uint256', name: 'out' }], - inputs: [{ type: 'uint256', name: 'eth_bought' }], - constant: true, - payable: false, - type: 'function', - gas: 6897, - }, - { - name: 'tokenAddress', - outputs: [{ type: 'address', name: 'out' }], - inputs: [], - constant: true, - payable: false, - type: 'function', - gas: 1413, - }, - { - name: 'factoryAddress', - outputs: [{ type: 'address', name: 'out' }], - inputs: [], - constant: true, - payable: false, - type: 'function', - gas: 1443, - }, - { - name: 'balanceOf', - outputs: [{ type: 'uint256', name: 'out' }], - inputs: [{ type: 'address', name: '_owner' }], - constant: true, - payable: false, - type: 'function', - gas: 1645, - }, - { - name: 'transfer', - outputs: [{ type: 'bool', name: 'out' }], - inputs: [ - { type: 'address', name: '_to' }, - { type: 'uint256', name: '_value' }, - ], - constant: false, - payable: false, - type: 'function', - gas: 75034, - }, - { - name: 'transferFrom', - outputs: [{ type: 'bool', name: 'out' }], - inputs: [ - { type: 'address', name: '_from' }, - { type: 'address', name: '_to' }, - { type: 'uint256', name: '_value' }, - ], - constant: false, - payable: false, - type: 'function', - gas: 110907, - }, - { - name: 'approve', - outputs: [{ type: 'bool', name: 'out' }], - inputs: [ - { type: 'address', name: '_spender' }, - { type: 'uint256', name: '_value' }, - ], - constant: false, - payable: false, - type: 'function', - gas: 38769, - }, - { - name: 'allowance', - outputs: [{ type: 'uint256', name: 'out' }], - inputs: [ - { type: 'address', name: '_owner' }, - { type: 'address', name: '_spender' }, - ], - constant: true, - payable: false, - type: 'function', - gas: 1925, - }, - { - name: 'name', - outputs: [{ type: 'bytes32', name: 'out' }], - inputs: [], - constant: true, - payable: false, - type: 'function', - gas: 1623, - }, - { - name: 'symbol', - outputs: [{ type: 'bytes32', name: 'out' }], - inputs: [], - constant: true, - payable: false, - type: 'function', - gas: 1653, - }, - { - name: 'decimals', - outputs: [{ type: 'uint256', name: 'out' }], - inputs: [], - constant: true, - payable: false, - type: 'function', - gas: 1683, - }, - { - name: 'totalSupply', - outputs: [{ type: 'uint256', name: 'out' }], - inputs: [], - constant: true, - payable: false, - type: 'function', - gas: 1713, - }, -] -``` - -```javascript -const exchangeContract = new web3.eth.Contract(exchangeABI, exchangeAddress) -``` - -# Token Contracts - -Some t1 interactions require making calls directly to ERC20 token contracts rather than the exchanges with which they are associated. - -## Get Token Address - -The `getToken` method in the factory contract can be used to find the ERC20 token address associated with an exchange contract. There is no barrier of entry for adding an ERC20 token to t1 or checks on the validity of the token contracts. Frontend interfaces should maintain a list of valid ERC20 tokens that users can safely trade or allow users to paste in arbitrary addresses. - -```javascript -const tokenAddress = factoryContract.methods.getToken(exchangeAddress) -``` - -If the return value is `0x0000000000000000000000000000000000000000` the input address is not a t1 exchange. - -## Token Interface - -Creating a token interface in web3 requires the **token address** and the **token ABI**: - -```javascript -const tokenABI = [ - { - name: 'Transfer', - inputs: [ - { type: 'address', name: '_from', indexed: true }, - { type: 'address', name: '_to', indexed: true }, - { type: 'uint256', name: '_value', indexed: false }, - ], - anonymous: false, - type: 'event', - }, - { - name: 'Approval', - inputs: [ - { type: 'address', name: '_owner', indexed: true }, - { type: 'address', name: '_spender', indexed: true }, - { type: 'uint256', name: '_value', indexed: false }, - ], - anonymous: false, - type: 'event', - }, - { - name: '__init__', - outputs: [], - inputs: [ - { type: 'bytes32', name: '_name' }, - { type: 'bytes32', name: '_symbol' }, - { type: 'uint256', name: '_decimals' }, - { type: 'uint256', name: '_supply' }, - ], - constant: false, - payable: false, - type: 'constructor', - }, - { - name: 'deposit', - outputs: [], - inputs: [], - constant: false, - payable: true, - type: 'function', - gas: 74279, - }, - { - name: 'withdraw', - outputs: [{ type: 'bool', name: 'out' }], - inputs: [{ type: 'uint256', name: '_value' }], - constant: false, - payable: false, - type: 'function', - gas: 108706, - }, - { - name: 'totalSupply', - outputs: [{ type: 'uint256', name: 'out' }], - inputs: [], - constant: true, - payable: false, - type: 'function', - gas: 543, - }, - { - name: 'balanceOf', - outputs: [{ type: 'uint256', name: 'out' }], - inputs: [{ type: 'address', name: '_owner' }], - constant: true, - payable: false, - type: 'function', - gas: 745, - }, - { - name: 'transfer', - outputs: [{ type: 'bool', name: 'out' }], - inputs: [ - { type: 'address', name: '_to' }, - { type: 'uint256', name: '_value' }, - ], - constant: false, - payable: false, - type: 'function', - gas: 74698, - }, - { - name: 'transferFrom', - outputs: [{ type: 'bool', name: 'out' }], - inputs: [ - { type: 'address', name: '_from' }, - { type: 'address', name: '_to' }, - { type: 'uint256', name: '_value' }, - ], - constant: false, - payable: false, - type: 'function', - gas: 110600, - }, - { - name: 'approve', - outputs: [{ type: 'bool', name: 'out' }], - inputs: [ - { type: 'address', name: '_spender' }, - { type: 'uint256', name: '_value' }, - ], - constant: false, - payable: false, - type: 'function', - gas: 37888, - }, - { - name: 'allowance', - outputs: [{ type: 'uint256', name: 'out' }], - inputs: [ - { type: 'address', name: '_owner' }, - { type: 'address', name: '_spender' }, - ], - constant: true, - payable: false, - type: 'function', - gas: 1025, - }, - { - name: 'name', - outputs: [{ type: 'bytes32', name: 'out' }], - inputs: [], - constant: true, - payable: false, - type: 'function', - gas: 723, - }, - { - name: 'symbol', - outputs: [{ type: 'bytes32', name: 'out' }], - inputs: [], - constant: true, - payable: false, - type: 'function', - gas: 753, - }, - { - name: 'decimals', - outputs: [{ type: 'uint256', name: 'out' }], - inputs: [], - constant: true, - payable: false, - type: 'function', - gas: 783, - }, -] -``` - -```javascript -const tokenContract = new web3.eth.Contract(tokenABI, tokenAddress) -``` diff --git a/docs/contracts/v1/guides/02-pool-liquidity.md b/docs/contracts/v1/guides/02-pool-liquidity.md deleted file mode 100644 index a81b573be..000000000 --- a/docs/contracts/v1/guides/02-pool-liquidity.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -id: pool-liquidity -title: Pool Liquidity ---- - -# Formalized Model - -Uniswap liquidity pools are autonomous and use the Constant Product Market Maker \(`x * y = k`\). This model was formalized and the smart contract implementation passed a lightweight formal verification. - -- [Formalized Specification](https://github.com/runtimeverification/verified-smart-contracts/blob/uniswap/uniswap/x-y-k.pdf) -- [Lightweight Verification](https://github.com/runtimeverification/verified-smart-contracts/tree/uniswap/uniswap/results) - -## Create Exchange - -The `createExchange` function is used to deploy exchange contracts for ERC20 tokens that do not yet have one. - -```javascript -factory.methods.createExchange(tokenAddress).send() -``` - -Once an exchange is created the address can be retrieved with [`getExchange`](connect-to-uniswap/#get-exchange-address). - -## Exchange Reserves - -Each exchange contract holds a liquidity reserve of ETH and its associated ERC20 token. - -### ETH Reserve - -The ETH reserve associated with an ERC20 token exchange is the ETH balance of the exchange smart contract. - -```javascript -const ethReserve = web3.eth.getBalance(exchangeAddress) -``` - -### ERC20 Reserve - -The ERC20 reserve associated with an ERC20 token exchange is the ERC20 balance of the exchange smart contract. - -```javascript -const tokenReserve = tokenContract.methods.balanceOf(exchangeAddress) -``` - -## Add Liquidity - -Anyone who wants can join a t1 liquidity pool by calling the `addLiquidity` function. - -```javascript -exchange.methods.addLiquidity(min_liquidity, max_tokens, deadline).send({ value: ethAmount }) -``` - -Adding liquidity requires depositing an equivalent **value** of ETH and ERC20 tokens into the ERC20 token's associated exchange contract. - -The first liquidity provider to join a pool sets the initial exchange rate by depositing what they believe to be an equivalent value of ETH and ERC20 tokens. If this ratio is off, arbitrage traders will bring the prices to equilibrium at the expense of the initial liquidity provider. - -All future liquidity providers deposit ETH and ERC20's using the exchange rate at the moment of their deposit. If the exchange rate is bad there is a profitable arbitrage opportunity that will correct the price. - -### Parameters - -The `ethAmount` sent to `addLiquidity` is the exact amount of ETH that will be deposited into the liquidity reserves. It should be 50% of the total value a liquidity provider wishes to deposit into the reserves. - -Since liquidity providers must deposit at the current exchange rate, the t1 smart contracts use `ethAmount` to determine the amount of ERC20 tokens that must be deposited. This token amount is the remaining 50% of total value a liquidity provider wishes to deposit. Since exchange rate can change between when a transaction is signed and when it is executed on Ethereum, `max_tokens` is used to bound the amount this rate can fluctuate. For the first liquidity provider, `max_tokens` is the exact amount of tokens deposited. - -Liquidity tokens are minted to track the relative proportion of total reserves that each liquidity provider has contributed. `min_liquidity` is used in combination with `max_tokens` and `ethAmount` to bound the rate at which liquidity tokens are minted. For the first liquidity provider, `min_liquidity` does not do anything and can be set to 0. - -Transaction `deadline` is used to set a time after which a transaction can no longer be executed. This limits the "free option" problem, where Ethereum miners can hold signed transactions and execute them based off market movements. - -## Remove Liquidity - -Liquidity providers use the `removeLiquidity` function to withdraw their portion of the reserves. - -```javascript -exchange.methods.removeLiquidity(amount, min_eth, min_tokens, deadline).send() -``` - -Liquidity is withdrawn at the same ratio as the reserves at the time of withdrawal. If the exchange rate is bad there is a profitable arbitrage opportunity that will correct the price. - -### Parameters - -`amount` specifies the number of liquidity tokens that will be burned. Dividing this amount by the total liquidity token supply gives the percentage of both the ETH and ER20 reserves the provider is withdrawing. - -Since exchange rate can change between when a transaction is signed and when it is executed on Ethereum, `min_eth` and `min_tokens` are used to bound the amount this rate can fluctuate. - -Same as in `addLiquidity`, `deadline` is used to set a time after which a transaction can no longer be executed. diff --git a/docs/contracts/v1/guides/03-trade-tokens.md b/docs/contracts/v1/guides/03-trade-tokens.md deleted file mode 100644 index 22040b92b..000000000 --- a/docs/contracts/v1/guides/03-trade-tokens.md +++ /dev/null @@ -1,185 +0,0 @@ ---- -id: trade-tokens -title: Trade Tokens ---- - -In t1, there is a separate exchange contract for each ERC20 token. These exchanges hold reserves of both ETH and their associated ERC20. Instead of waiting to be matched in an order-book, users can make trades against the reserves at any time. Reserves are pooled between a decentralized network of liquidity providers who collect fees on every trade. - -Pricing is automatic, based on the `x * y = k` market making formula which automatically adjusts prices based off the relative sizes of the two reserves and the size of the incoming trade. Since all tokens share ETH as a common pair, it is used as an intermediary asset for direct trading between any ERC20 ⇄ ERC20 pair. - -## ETH ⇄ ERC20 Calculations - -The variables needed to determine price when trading between ETH and ERC20 tokens is: - -- ETH reserve size of the ERC20 exchange -- ERC20 reserve size of the ERC20 exchange -- Amount sold \(input\) or amount bought \(output\) - -### Amount Bought \(sell order\) - -For sell orders \(exact input\), the amount bought \(output\) is calculated: - -```javascript -// Sell ETH for ERC20 -const inputAmount = userInputEthValue -const inputReserve = web3.eth.getBalance(exchangeAddress) -const outputReserve = tokenContract.methods.balanceOf(exchangeAddress).call() - -// Sell ERC20 for ETH -const inputAmount = userInputTokenValue -const inputReserve = tokenContract.methods.balanceOf(exchangeAddress).call() -const outputReserve = web3.eth.getBalance(exchangeAddress) - -// Output amount bought -const numerator = inputAmount * outputReserve * 997 -const denominator = inputReserve * 1000 + inputAmount * 997 -const outputAmount = numerator / denominator -``` - -### Amount Sold \(buy order\) - -For buy orders \(exact output\), the cost \(input\) is calculated: - -```javascript -// Buy ERC20 with ETH -const outputAmount = userInputTokenValue -const inputReserve = web3.eth.getBalance(exchangeAddress) -const outputReserve = tokenContract.methods.balanceOf(exchangeAddress).call() - -// Buy ETH with ERC20 -const outputAmount = userInputEthValue -const inputReserve = tokenContract.methods.balanceOf(exchangeAddress).call() -const outputReserve = web3.eth.getBalance(exchangeAddress) - -// Cost -const numerator = outputAmount * inputReserve * 1000 -const denominator = (outputReserve - outputAmount) * 997 -const inputAmount = numerator / denominator + 1 -``` - -### Liquidity Provider Fee - -There is a 0.3% liquidity provider fee built into the price formula. This can be calculated: - -```javascript -fee = inputAmount * 0.003 -``` - -### Exchange Rate - -The exchange rate is simply the output amount divided by the input amount. - -```javascript -const rate = outputAmount / inputAmount -``` - -## ERC20 ⇄ ERC20 Calculations - -The variables needed to determine price when trading between two ERC20 tokens is: - -- ETH reserve size of the input ERC20 exchange -- ERC20 reserve size of the input ERC20 exchange -- ETH reserve size of the output ERC20 exchange -- ERC20 reserve size of the output ERC20 exchange -- Amount sold \(input\) or amount bought \(output\) - -### Amount Bought \(sell order\) - -For sell orders \(exact input\), the amount bought \(output\) is calculated: - -```javascript -// TokenA (ERC20) to ETH conversion -const inputAmountA = userInputTokenAValue -const inputReserveA = tokenContractA.methods.balanceOf(exchangeAddressA).call() -const outputReserveA = web3.eth.getBalance(exchangeAddressA) - -const numeratorA = inputAmountA * outputReserveA * 997 -const denominatorA = inputReserveA * 1000 + inputAmountA * 997 -const outputAmountA = numeratorA / denominatorA - -// ETH to TokenB conversion -const inputAmountB = outputAmountA -const inputReserveB = web3.eth.getBalance(exchangeAddressB) -const outputReserveB = tokenContract.methods.balanceOf(exchangeAddressB).call() - -const numeratorB = inputAmountB * outputReserveB * 997 -const denominatorB = inputReserveB * 1000 + inputAmountB * 997 -const outputAmountB = numeratorB / denominatorB -``` - -### Amount Sold \(buy order\) - -For buy orders \(exact output\), the cost \(input\) is calculated: - -```javascript -// Buy TokenB with ETH -const outputAmountB = userInputTokenBValue -const inputReserveB = web3.eth.getBalance(exchangeAddressB) -const outputReserveB = tokenContractB.methods.balanceOf(exchangeAddressB).call() - -// Cost -const numeratorB = outputAmountB * inputReserveB * 1000 -const denominatorB = (outputReserveB - outputAmountB) * 997 -const inputAmountB = numeratorB / denominatorB + 1 - -// Buy ETH with TokenA -const outputAmountA = userInputEthValue -const inputReserveA = tokenContractA.methods.balanceOf(exchangeAddressA).call() -const outputReserveA = web3.eth.getBalance(exchangeAddressA) - -// Cost -const numeratorA = outputAmountA * inputReserveA * 1000 -const denominatorA = (outputReserveA - outputAmountA) * 997 -const inputAmountA = numeratorA / denominatorA + 1 -``` - -### Liquidity Provider Fee - -There is a 0.30% liquidity provider fee to swap from TokenA to ETH on the input exchange. There is another 0.3% liquidity provider fee to swap the remaining ETH to TokenB. - -```javascript -const exchangeAFee = inputAmountA * 0.003 -const exchangeBFee = inputAmountB * 0.003 -``` - -Since users only inputs Token A, it can be represented to them as: - -```javascript -const combinedFee = inputAmountA * 0.00591 -``` - -### Exchange Rate - -The exchange rate is simply the output amount divided by the input amount. - -```javascript -const rate = outputAmountB / inputAmountA -``` - -## Deadlines - -Many t1 functions include a transaction `deadline` that sets a time after which a transaction can no longer be executed. This limits miners holding signed transactions for extended durations and executing them based off market movements. It also reduces uncertainty around transactions that take a long time to execute due to issues with gas price. - -Deadlines are calculated by adding the desired amount of time \(in seconds\) to the latest Ethereum block timestamp. - -```javascript -web3.eth.getBlock('latest', (error, block) => { - deadline = block.timestamp + 300 // transaction expires in 300 seconds (5 minutes) -}) -``` - -## Recipients - -Uniswap allows traders to swap tokens and transfer the output to a new `recipient` address. This allows for a type of payment where the payer sends one token and the payee receives another. - -## ETH ⇄ ERC20 Trades - -Coming soon... - -## ERC20 ⇄ ERC20 Trades - -Coming soon... - -## Custom Pools - -Coming soon... diff --git a/docs/contracts/v1/guides/04-custom-linking.md b/docs/contracts/v1/guides/04-custom-linking.md deleted file mode 100644 index f5d0b7a32..000000000 --- a/docs/contracts/v1/guides/04-custom-linking.md +++ /dev/null @@ -1,111 +0,0 @@ ---- -id: custom-linking -title: Custom Linking ---- - -# Query Parameters - -The t1 front-end supports URL query parameters to allow for custom linking to the t1 exchange. Users and developers can use these query parameters to link to the t1 exchange with custom prefilled settings. - -Each Page has specific available URL parameters that can be set. Global parameters can be used on all pages. - -A parameter used on an incorrect page will have no effect on exchange settings. Parameters not set with a URL parameter will be set to standard exchange defaults. - -## Global - -| Parameter | Type | Description | -| :-------- | :------- | :------------------------------- | -| theme | `String` | Sets them to dark or light mode. | - -### Theme Options - -Theme can be set as `light` or `dark`. - -### Example Usage - -`https://app.uniswap.org/#/swap?theme=dark&use=v1` - -## Swap Page - -| Parameter | Type | Description | -| :------------- | :--------------- | :--------------------------------------------------------------------- | -| inputCurrency | `address` | Input currency that will be swapped for output currency. | -| outputCurrency | `address or ETH` | Output currency that input currency will be swapped for. | -| slippage | `number` | Max slippage to be used during transaction \(in bips\) | -| exactAmount | `number` | The custom token amount to buy or sell. | -| exactField | `string` | The field to set custom token amount for. Must be `input` or `output`. | - -### Defaults - -ETH defaults as the input currency. When a different token is selected for either input or output ETH will default as the opposite selected currency. - -### Constraints - -Addresses must be valid ERC20 addresses. Slippage and amount values must be valid numbers accepted by the exchange \(or error will prevent from swapping\). Slippage can 0, or within the range 10->9999 bips \(which converts to 0%, 0.01%->99%\) - -When selecting ETH as the output currency a user must also choose an inputCurrency that is not ETH \(to prevent ETH being populated in both fields\) - -### Setting Amounts - -Two parameters, exactField and exactAmount can be used to set specific token amounts to be sold or bought. Both fields must be set in the URL or there will be no effect on the settings. - -### Example Usage - -`https://app.uniswap.org/#/swap?exactField=input&exactAmount=10&inputCurrency=0x0F5D2fB29fb7d3CFeE444a200298f468908cC942?use=v1` - -## Send Page - -The send page has the same options available as the Swap page, plus one additional paramter, `recipient`. - -| Parameter | Type | Description | -| :-------- | :-------- | :---------------------------------------------- | -| recipient | `address` | Address of the recipient of a send transaction. | - -### Example Usage - -`https://app.uniswap.org/#/send?recipient=0x74Aa01d162E6dC6A657caC857418C403D48E2D77?use=v1` - -## Pool Page - -The Pool page is made up of 3 subroutes: `add-liquidity`, `remove-liquidity`, `create-exchange`. - -### Add Liquidity - -| Parameter | Type | Description | -| :---------- | :-------- | :----------------------------------------------------- | -| ethAmount | `number` | Amount of ETH to deposit into the pool. | -| token | `address` | ERC20 address of the pool to add liquidity to. | -| tokenAmount | `number` | Amount of the selected token to deposit into the pool. | - -### Example Usage - -`https://app.uniswap.org/#/add-liquidity?ethAmount=2.34&token=0x42456D7084eacF4083f1140d3229471bbA2949A8&tokenAmount=300?use=v1` - -## Remove Liquidity - -| Parameter | Type | Description | -| :--------------- | :-------- | :-------------------------------------------------------------------------------------- | -| poolTokenAddress | `address` | Pool to withdraw liquidity from. \(Must be an ERC20 address with an existing exchange\) | -| poolTokenAmount | `number` | Amount of pool token to be withdrawn from liquidity pool. | - -### Example Usage - -`https://app.uniswap.org/#/remove-liquidity?poolTokenAmount=1.23&use=v1` - -## Create Exchange - -| Parameter | Type | Description | -| :----------- | :-------- | :--------------------------------------------------------------------------------------------------------- | -| tokenAddress | `address` | ERC20 token to create the exchange for. Must be valid ERC20 token for which there is no existing exchange. | - -### Example Usage - -`https://app.uniswap.org/#/swap?use=v1&create-exchange?tokenAddress=0x0F5D2fB29fb7d3CFeE444a200298f468908cC942` - -## Custom Routes - -Custom token routes can still be used in combination with URL paramters. URL paramters are higher in the settings hierarchy than custom routes. - -An example using custom token route and URL paramters. - -`https://app.uniswap.org/#/swap/0x0F5D2fB29fb7d3CFeE444a200298f468908cC942?exactField=input&exactAmount=10&use=v1` diff --git a/docs/contracts/v1/guides/05-iframe-integration.md b/docs/contracts/v1/guides/05-iframe-integration.md deleted file mode 100644 index 30ab8dce4..000000000 --- a/docs/contracts/v1/guides/05-iframe-integration.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -id: iframe-integration -title: Iframe Integration ---- - -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. - -# Why You May Want This - -Integrating the t1 site directly into your web application can be useful for a variety of reasons. - -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 t1 iframe on your site, then allow users to lend that DAI on your site\). - -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\). - -# iframe vs. custom UI - -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. - -# Live Example - -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) - -To see the Iframe click the dropdown in the top right and click "get foam". - -# Add To Your Site - -To include a t1 iframe within your site just add an iframe element within your website code and link to the t1 exchange. - -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. - -```text - - -Example use cases include: - -- Building a custom frontend for the Uniswap Protocol -- Swapping assets in a DeFi application -- Acquiring a token to participate in your web3 community (e.g. FWB or a gaming token) -- Converting to the required currency for an NFT purchase (e.g. WETH) - -You can make the widget feel like a native part of your app by customizing the colors, font, and token list to match your app theme. This guide will teach you how. - -## Installing the Widgets Library {#installing-library} - -To get started, install the widgets library using npm or Yarn. If you don’t already use it, you’ll need to install `react-redux` as well. - -```bash npm2yarn -npm install --save @uniswap/widgets react-redux -``` - -## Adding the Swap Widget to Your App {#adding-the-widget} - -Next, embed the React component in your application. - -```jsx -import { SwapWidget } from '@uniswap/widgets' -import '@uniswap/widgets/fonts.css' - -function App() { -
- -
-} -``` - -That’s it! You should now see a fully functional swap widget on your site. The widget is self-contained and gracefully handles all interactions with the Uniswap Protocol. It leverages the [Auto Router](/sdk/v3/guides/swaps/routing) to compute the best price across all Uniswap v2 and v3 pools. - -See a full implementation of the swap widget in the `/cra` and `/nextjs` branches of the [widgets-demo](https://github.com/Uniswap/widgets-demo) repo. - -:::note Create React App V4 -All code snippets will work seamlessly if you use [Next.js](https://nextjs.org/) or [Create React App](https://create-react-app.dev/) V5. However, if you’re using Create React App V4, you’ll need to use the following `import` statements instead: - -```jsx -import { SwapWidget } from '@uniswap/widgets/dist/index.js' -import '@uniswap/widgets/dist/fonts.css' -``` - -::: - -# Recommended Parameters {#recommended-parameters} - -The swap widget is a React component that can be easily imported into any React project. It's designed to work out-of-the-box, with no required parameters or web3 integration necessary. Trading is supported on all networks where the Uniswap Protocol is deployed. - -Although the widget will work out-of-the-box with no parameters, we highly recommend integrators provide [JSON-RPC endpoints](#json-rpc-endpoint), like from [Chainnodes](https://www.chainnodes.org), Infura or Alchemy. Existing dApps can also provide their existing [web3 provider](#web3-provider) to integrate the widget seamlessly into their dApp. - -Additional [optional parameters](/sdk/swap-widget/reference/v2#optional-parameters) are available to customize the appearance and performance of the swap widget to fit your unique use case. - -## Web3 Provider {#web3-provider} - -The swap widget uses a web3 `provider` prop to allow users to connect their wallets, fetch balances, and submit transactions through the user’s connected wallet. - -If your app does not maintain its own web3 provider, you can omit the `provider` prop. The widget will use built-in wallet connection functionality (for [WalletConnect](https://walletconnect.com/) and [MetaMask](https://metamask.io/)), making it easy for you to integrate web3 in your app! - -If you already have a web3 provider, you can pass your provider object directly into the `provider` prop. Both [ethers](https://docs.ethers.io/v5/api/providers/provider/) and [web3.js](https://web3js.readthedocs.io/en/v1.5.2/index.html) provider objects are compatible with the widget, as is any [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193) provider. -You can directly use the providers returned from [web3-react](https://github.com/Uniswap/web3-react) or [wagmi](https://wagmi.sh/) (both are [ethers](https://docs.ethers.io/v5/api/providers/provider/) providers). If it is not connected to a wallet, it will still be used to read data from the chain, but the widget will still prompt the user to "Connect wallet". - -:::note Be sure to use the wallet-connected provider -When using [wagmi@v0.11](https://wagmi.sh/), `useProvider()` will return the fallback provider, *not* the wallet-connected provider. You should instead pass `useSigner().data?.provider` to reflect the user's connected wallet. -::: - -If you maintain a web3 provider on your app, you should also consider intercepting the swap widget's wallet connection flow. Do so by passing a handler returning `false` to the [`onConnectWalletClick`](/sdk/swap-widget/reference/v2#onConnectWalletClick) prop, which is triggered when the widget's "Connect wallet" button is clicked. Check out libraries such as [web3-react](https://github.com/Uniswap/web3-react), BlockNative’s [Onboard](https://www.blocknative.com/onboard), or Aragon’s [useWallet()](https://github.com/aragon/use-wallet) to build your own flow. To hide the swap widget's wallet connection flow entirely, pass `true` to the `hideConnectionUI` prop. - -The widget will match the network currently selected by the passed provider. If the user switches networks in your app or in their connected wallet, that change will propagate to the widget as well. If the user connects to a network that is not supported by the swap widget, the widget will gracefully disable itself. - -```tsx -import { SwapWidget } from '@uniswap/widgets' -import '@uniswap/widgets/fonts.css' - -// We recommend you pass a web3 provider. -import { provider } from './your/provider' - -// We recommend you pass your own JSON-RPC endpoints. -const jsonRpcUrlMap = { - 1: ['https://mainnet.infura.io/v3/'], - 3: ['https://ropsten.infura.io/v3/'] -} - -function App() { -
- -
-} -``` - -## JSON-RPC Endpoints {#json-rpc-endpoint} - -JSON-RPC endpoints are used to read data when no `provider` is connected. We strongly recommend you pass either a Web3 Provider to the `provider` prop, or JSON-RPC endpoint URLs to the `jsonRpcUrlMap` prop. - -The widget will use these endpoints to fetch on-chain data and submit transactions for signature. If the user connects a MetaMask wallet, the widget will use the JSON-RPC provided by MetaMask when possible. [(See a list of all chains supported on widget.)](https://github.com/Uniswap/widgets/blob/main/src/constants/chains.ts#L4) - -If you don’t yet have JSON-RPC endpoints, you can easily create them with services like [Chainnodes](https://www.chainnodes.org), [Infura](https://infura.io/product/ethereum) or [Alchemy](https://www.alchemy.com/supernode). - -If you choose not to provide a `jsonRpcUrlMap` prop or are missing endpoints for some chains, the widget uses free public JSON-RPC endpoints to still allow users to interact with the widget and fetch price quotes. However, these public endpoints are NOT recommended for production environment usage, are severely rate-limited, and aren't necessarily as reliable. When possible, we'd recommend providing your own endpoints! - -# Customizing the Swap Widget {#customizing-widget} - -You can set [optional parameters](/sdk/swap-widget/reference/v2#optional-parameters) to tailor the appearance and functionality of the swap widget to fit your dApp. - -## Customizing the Width {#customizing-width} - -The swap widget has a fixed height of 360px and a default width of 360px. You cannot modify the height of the widget. You can modify the width up to a minimum width of 300px. - -You can customize the width by passing a number (of pixels) or a valid CSS width to the `width` prop of the widget. - -```tsx -import { SwapWidget } from '@uniswap/widgets' -import '@uniswap/widgets/fonts.css' - -function App() { -
- -
-} -``` - -For example: - -- `width={360}` sets the width to 360 pixels -- `width="100%"` sets the width to dynamically fill 100% of the parent container -- `width="20em"` sets the width to 20 * 16 = 320 pixels because 16px is the base font-size of the widget - -The recommended and default width is 360 pixels. - -## Customizing the Theme {#customizing-theme} - -You can customize the colors, font, and border radius of the swap widget to match the look and feel of your dApp. You can also toggle between light and dark modes. This section explains how to customize each attribute of the widget with your own `theme`. - -All attributes below are color codes, except `fontFamily` (string), `borderRadius` (number between 0 and 1), and `tokenColorExtraction`(boolean). The next two sections show code examples using these attributes. - -Check out [examples](/sdk/swap-widget/guides/examples) of the swap widget, and the [Figma file](https://www.figma.com/file/m0pVMlgAgSoaIrXlM3VRUG/Widgets-(External)?node-id=4302%3A18261) if you want to mock it up first! - - - - - -### Overriding Attributes {#overriding-attributes} - -You can override specific attributes of the widget by creating a `Theme` object and defining the properties you wish to override. Any properties left undefined will fallback to the default theme. For example, here is a simple `Theme` that removes the border radius and sets a custom font family. - -```tsx -import { Theme, SwapWidget } from '@uniswap/widgets' - -// Define a custom theme to override default attributes -const theme: Theme = { - borderRadius: 0, - fontFamily: '"Helvetica"', -} - -function App() { -
- -
-} -``` - -Please note that the `borderRadius` attribute is a multiplier from 0 to 1 of how much radius to apply. Since the widget uses different values of border radius (e.g. internal edges have tighter radii than external edges), `borderRadius` will apply your multiplier value on all instances so that the border radii still look proportionally correct. - -:::note Importing Fonts -The swap widget fonts must be imported explicitly with `import '@uniswap/widgets/fonts.css'`. However, if you’re overriding the swap widget fonts with your own, or with a default font such as Helvetica in the example above, you can remove this `import` statement. -::: - -### Enabling Token Color Extraction {#enabling-color-extraction} - -By default, the background color of the output module will be set by the `module` attribute. You can optionally enable color extraction to flood the output module with the color of the selected output token. In the above example, DAI is the output token so the output module is flooded with DAI yellow. - -To enable color extraction, set the `tokenColorExtraction` property to `true` in your `Theme` object. - -```tsx -import { Theme, SwapWidget } from '@uniswap/widgets' -import '@uniswap/widgets/fonts.css' - -const enableColorExtractionTheme: Theme = { - tokenColorExtraction: true, // Enable color extraction of the output token -} - -function App() { -
- -
-} -``` - -### Toggling Light and Dark Mode {#toggling-light-dark-mode} - -The swap widget provides a default light theme and dark theme as a starting point. You can import each one and extend it to create your own theme. If your app can toggle between light and dark mode, you can propagate that state down to the widget by following the example below. - -```tsx -import { darkTheme, lightTheme, Theme, SwapWidget } from '@uniswap/widgets' -import '@uniswap/widgets/fonts.css' - -let darkMode = true // Dynamically toggle dark mode on and off -function App() { -
- -
-} -``` - -### Matching System Preference for Light and Dark Mode {#matching-system-light-dark-mode} - -You can match the user’s system preference for light/dark mode by using the `useSystemTheme` hook. This will return the default widget light or dark theme according to the user’s system configuration. You can extend this base theme with further customizations, as you will see in the next section. - -```tsx -import { SwapWidget } from '@uniswap/widgets' -import '@uniswap/widgets/fonts.css' - -function useSystemTheme() { - // Access -} - -function App() { - const theme = useSystemTheme() // Get a theme that matches the user system preference -
- -
-} -``` - -### Extending Themes {#extending-themes} - -You can extend any theme with custom attributes. The below example extends the base light and dark themes with custom colors. - -```tsx -import { darkTheme, lightTheme, Theme, SwapWidget } from '@uniswap/widgets' -import '@uniswap/widgets/fonts.css' - -const myLightTheme: Theme = { - ...lightTheme, // Extend the lightTheme - accent: '#FF007A', - primary: '#000000', - secondary: '#565A69', -} - -const myDarkTheme: Theme = { - ...darkTheme, // Extend the darkTheme - accent: '#2172E5', - primary: '#FFFFFF', - secondary: '#888D9B', -} - -let darkMode = true -function App() { -
- -
-} -``` - -## Customizing the Token Lists {#customizing-token-lists} - -By default, the widget will use the [Uniswap Labs default token list](https://tokenlists.org/token-list?url=https://gateway.ipfs.io/ipns/tokens.uniswap.org) in the selector. - -### Customizing the Default Token List {#customizing-default-token-list} - -If you want to offer a different set of tokens in the widget, you can provide a custom `tokenList` parameter. You can [browse popular token lists](https://tokenlists.org/) to find one that suits your needs and then pass the URL as a parameter. - -```jsx -import { SwapWidget } from '@uniswap/widgets' -import '@uniswap/widgets/fonts.css' - -const CMC_TOKEN_LIST = 'https://api.coinmarketcap.com/data-api/v3/uniswap/all.json' - -function App() { -
- -
-} -``` - -Alternatively, you can create your own token list. There are two ways to provide your own token list for the widget. - -The first option is to [create a full token list](https://github.com/Uniswap/token-lists#authoring-token-lists), host it at your own URI, and pass the URI as a parameter as in the above example. This option is recommended if you want to use the same token list in multiple places throughout your application or community. - -The second and easiest option is to construct a custom token list inline as an array of tokens. The schema is equivalent to the `tokens` array from the [tokenlist JSON schema](https://github.com/Uniswap/token-lists/blob/main/src/tokenlist.schema.json). This option lets you skip deployment, hosting, and versioning of a full URI token list. Here is an example of an inline token list containing only the DAI, USDT, and USDC tokens (in addition to ETH which is always available, regardless of token list). - -```jsx -import { SwapWidget } from '@uniswap/widgets' -import '@uniswap/widgets/fonts.css' - -// You can also pass a token list as JSON, as long as it matches the schema -const MY_TOKEN_LIST = [ - { - "name": "Dai Stablecoin", - "address": "0x6B175474E89094C44Da98b954EedeAC495271d0F", - "symbol": "DAI", - "decimals": 18, - "chainId": 1, - "logoURI": "https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/ethereum/assets/0x6B175474E89094C44Da98b954EedeAC495271d0F/logo.png" - }, - { - "name": "Tether USD", - "address": "0xdAC17F958D2ee523a2206206994597C13D831ec7", - "symbol": "USDT", - "decimals": 6, - "chainId": 1, - "logoURI": "https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/ethereum/assets/0xdAC17F958D2ee523a2206206994597C13D831ec7/logo.png" - }, - { - "name": "USD Coin", - "address": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", - "symbol": "USDC", - "decimals": 6, - "chainId": 1, - "logoURI": "https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/ethereum/assets/0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48/logo.png" - }, -] - -function App() { -
- -
-} -``` - -Please note that the swap widget only enforces metadata validation on remotely hosted token lists, not on token list data passed as a literal value to the widget like in this example. - -If you want to add Layer 2 tokens to the token list, you can add an extension field. See this [GitHub issue](https://github.com/Uniswap/token-lists/issues/51#issuecomment-952268629) for details. - -## Customizing the Default Input and Output Tokens {#customizing-default-input-output-tokens} - -You can set the `defaultInputTokenAddress`, `defaultInputAmount`, `defaultOutputTokenAddress`, and `defaultOutputAmount` to pre-populate the input and output token fields respectively. This is useful when the widget appears in a context where you know which tokens the user is evaluating to trade. For example, if the widget appears on a page that displays the WBTC price chart, it would be helpful to pre-select WBTC as the output token in the widget. - -If your page does not need any particular defaults, then the recommended default input token is the native asset of the active network (e.g. ETH) and no default output token is recommended. Since ETH does not have an address, you can pass `'NATIVE'` as the parameter to set it as the default input or output token. - -The following example sets the default input to 2 ETH and the default output token to WBTC. - -```tsx -import { SwapWidget } from '@uniswap/widgets' -import '@uniswap/widgets/fonts.css' - -// Default token list from Uniswap -const UNISWAP_TOKEN_LIST = 'https://gateway.ipfs.io/ipns/tokens.uniswap.org' - -// Use the native token of the connected chain as the default input token -const NATIVE = 'NATIVE' // Special address for native token - -// WBTC as the default output token -const WBTC = '0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599' - -function App() { -
- -
-} -``` - -## Understanding the Swap Widget States {#understanding-widget-states} - -The widget has two main connectivity states depending on if the user has connected a wallet. - - - -1. **Before wallet connection**, the widget will use the JSON-RPC endpoint to fetch token price data and provide trade quotes, but submitting transactions will be disabled. -2. **After wallet connection**, the widget will be fully functional. The user will be able to fetch trade quotes and submit swap transactions using the JSON-RPC endpoint and web3 provider from their connected wallet. - -:::note Questions? -Join the [Discord channel](https://discord.com/channels/597638925346930701/941447445844463676) to ask questions and get support from the Uniswap community. -::: diff --git a/docs/sdk/swap-widget/overview.md b/docs/sdk/swap-widget/overview.md deleted file mode 100644 index 742ec6175..000000000 --- a/docs/sdk/swap-widget/overview.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -id: overview -sidebar_position: 1 -title: Overview ---- - -# The t1 Swap Widget - -Welcome to the t1 Swap Widget. To begin, we recommend looking at the [**Guides**](./guides/swap-widget.mdx) and for deeper reference see the [**Swap Widget Github**](https://github.com/Uniswap/widgets) repo. - -# Alpha software - -The latest version of the Swap Widget is in production in the t1 Interface, -but it is considered Alpha software and may contain bugs or change significantly between patch versions. -If you have questions about how to use the SDK, please reach out in the `#dev-chat` channel of our Discord. -Pull requests are welcome! - -# t1 Swap Widget - -- [**Swap Widget Github Repo**](https://github.com/Uniswap/widgets) -- [**Swap Widget NPM Package**](https://www.npmjs.com/package/@uniswap/widgets) - -[![Unit Tests](https://github.com/Uniswap/widgets/workflows/Unit%20Tests/badge.svg)](https://github.com/Uniswap/uniswap-v3-sdk/actions?query=workflow%3A%22Unit+Tests%22) -[![Lint](https://github.com/Uniswap/widgets/workflows/Lint/badge.svg)](https://github.com/Uniswap/uniswap-v3-sdk/actions?query=workflow%3ALint) -[![npm version](https://img.shields.io/npm/v/@uniswap/widgets/latest.svg)](https://www.npmjs.com/package/@uniswap/v3-sdk/v/latest) -[![npm bundle size (scoped version)](https://img.shields.io/bundlephobia/minzip/@uniswap/widgets/latest.svg)](https://bundlephobia.com/result?p=@uniswap/v3-sdk@latest) diff --git a/docs/sdk/swap-widget/reference/_category_.json b/docs/sdk/swap-widget/reference/_category_.json deleted file mode 100644 index 19b021994..000000000 --- a/docs/sdk/swap-widget/reference/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "label": "Technical Reference", - "position": 3, - "collapsed": true -} diff --git a/docs/sdk/swap-widget/reference/v1.md b/docs/sdk/swap-widget/reference/v1.md deleted file mode 100644 index 140bd3546..000000000 --- a/docs/sdk/swap-widget/reference/v1.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -id: v1 -title: API V1 Reference (Deprecated) -sidebar_position: 2 ---- - -# Swap Widget API V1 Reference (Deprecated) - -
- -## Required Parameters {#required-parameters} - -| Prop Name | Prop Type | Default Value | Description | -| ----------------- | --------- | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `jsonRpcEndpoint` | `string` | `undefined` | URI of your JSON-RPC endpoint. Strongly recommended in order to provide trade quotes prior to the user connecting a wallet. If none is provided, the widget will be completely disabled until the user connects a wallet. Once a wallet is connected, the widget will use the wallet’s JSON-RPC. See [Understanding the Swap Widget States](/sdk/swap-widget/guides/getting-started#understanding-widget-states). | -| `provider` | `any` | `undefined` | An [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193) provider. This is required to swap. | - -## Optional Parameters {#optional-parameters} - -| Prop Name | Prop Type | Default Value | Description | -| --------------------------- | ----------------------------- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `convenienceFee` | `number` | `undefined` | Optionally, you may charge a convenience fee on top of swaps executed through your web app. The allowed range is 1 to 100 basis points (inclusive of 100) consistent with the t1 v3 Periphery contract. | -| `convenienceFeeRecipient` | `{[chainId: number]: string}` | `undefined` | The address to receive the convenience fee on each network. Required if `convenienceFee` is provided. | -| `defaultInputTokenAddress` | `{[chainId: number]: string}` | `string` or `'NATIVE'` | Address of the token to be selected by default in the input field (e.g. USDC) for each network chain ID. If left empty the widget will use the native token of the connected chain as default. This can be explicitly defined by the special string `'NATIVE'`. For convenience you may pass a single string instead of a `chainId` mapping. In this case, the widget will assume that string corresponds to an L1 Ethereum address with `chaindId=1`. Any addresses provided in this parameter must be included in the `tokenList`. | -| `defaultInputAmount` | `number` | `0` | Default amount for the input field (e.g. 1 ETH). This value will respect the decimals of the `defaultInputTokenAddress`. This parameter is valid only if `defaultInputTokenAddress` is also set. This parameter is mutually exclusive with `defaultOutputAmount`, so you may set only one of `defaultInputAmount` and `defaultOutputAmount`. | -| `defaultOutputTokenAddress` | `{[chainId: number]: string}` | `string` or `undefined` | Address of the token to be selected by default in the input field (e.g. USDC) for each network chain ID. None if left empty. Any addresses provided in this parameter must be included in the `tokenList`. | -| `defaultOutputAmount` | `number` | `0` | Default amount for the input field (e.g. 100 USDC). This value will respect the decimals of the `defaultOutputTokenAddress`. This parameter is mutually exclusive with `defaultInputAmount`, so you may set only one of `defaultInputAmount` and `defaultOutputAmount`. | -| `locale` | `SupportedLocale` | `en-US` | Specifies an explicit locale to use for the widget interface. This can be set to one of the values exported by the library in [`SUPPORTED_LOCALES`](https://github.com/Uniswap/widgets/blob/main/src/constants/locales.ts). | -| `onConnectWallet` | `() => void` | `undefined` | If passed, the “Connect your wallet” message will be clickable, and clicking it will trigger this handler function. This can be used to trigger your own wallet connection flow from the widget. | -| `onError` | `ErrorHandler` | `undefined` | An error handler which receives any errors that occur in the widget. This can be used for collecting error metrics. | -| `theme` | `Theme` | `lightTheme` | Specifies a custom theme (colors, font, and border radii). See [Customizing the Theme](/sdk/swap-widget/guides/getting-started#customizing-theme). | -| `tokenList` | `string` | `TokenInfo[]` | Specifies the set of tokens that appear by default in the token selector list. Accepts either a URI of a token list as defined by the Token Lists standard, or an inline array of tokens. If none is provided, the t1 Labs default token list will be used. See [Customizing the Default Token List](/sdk/swap-widget/guides/getting-started#customizing-default-token-list). | -| `width` | `number` or `string` | `360` | Specifies the width of the widget. If specified as a number, this is in pixels; otherwise, it is interpreted as a CSS `` data type. Recommended width is 360px. Minimum width is 270px. See [Customizing the Width](/sdk/swap-widget/guides/getting-started#customizing-width). | - -## Subscribing to Events - -During the lifecycle of the swap widget, most of the events you will need are available on the web3 provider. For example, the below snippet shows how to listen for events when the wallet account changes or a new wallet connects. You can see more event examples in the [MetaMask](https://docs.metamask.io/guide/ethereum-provider.html) docs. - -```js -// Subscribe to messages -interface ProviderMessage { - type: string; - data: unknown; -} - -ethereum.on( - 'message', - handler: (message: ProviderMessage) => void -); -``` - -
- -:::note Questions? -Join the [Discord channel](https://discord.com/channels/597638925346930701/941447445844463676) to ask questions and get support from the t1 community. -::: diff --git a/docs/sdk/swap-widget/reference/v2.md b/docs/sdk/swap-widget/reference/v2.md deleted file mode 100644 index 90fab824b..000000000 --- a/docs/sdk/swap-widget/reference/v2.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -id: v2 -title: API V2 Reference -sidebar_position: 1 ---- - -# Swap Widget API V2 Reference - -
- -## Recommended Parameters {#recommended-parameters} - -| Prop Name | Prop Type | Default Value | Description | -| --------------- | -------------------------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `provider` | `JsonRpcProvider` or `Eip1193Provider` | `undefined` | An [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193) provider. See [Web3 provider](../guides/swap-widget.mdx#web3-provider). | -| `jsonRpcUrlMap` | `{ [chainId: number]: string[] }` | `JSON_RPC_FALLBACK_ENDPOINTS` | Mapping of your JSON-RPC endpoint URLs indexed by chainId, used to provide trade quotes prior to the user connecting a wallet. If none are provided for a chain, the widget will fallback to public JSON-RPC endpoints, which are unreliable and rate-limited. See [JSON-RPC Endpoints](../guides/swap-widget.mdx#json-rpc-endpoint). | - -## Optional Parameters {#optional-parameters} - -| Prop Name | Prop Type | Default Value | Description | -| --------------------------- | -------------------------------------------------------------- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `convenienceFee` | `number` | `undefined` | Optionally, you may charge a convenience fee on top of swaps executed through your web app. The allowed range is 1 to 100 basis points paid in the output token of a swap, consistent with the t1 v3 Periphery contract. | -| `convenienceFeeRecipient` | `{[chainId: number]: string}` | `undefined` | The address to receive the convenience fee on each network. Required if `convenienceFee` is provided. | -| `defaultChainId` | `number` | `1` | You may specify which chainId you want to prompt a user to connect their wallet to. [See a list of all chains supported on widget.](https://github.com/Uniswap/widgets/blob/main/src/constants/chains.ts#L4) | -| `defaultInputTokenAddress` | `{[chainId: number]: string}` | `string` or `'NATIVE'` | Address of the token to be selected by default in the input field (e.g. USDC) for each network chain ID. If left empty the widget will use the native token of the connected chain as default. This can be explicitly defined by the special string `'NATIVE'`. For convenience you may pass a single string instead of a `chainId` mapping. In this case, the widget will assume that string corresponds to an L1 Ethereum address with `chaindId=1`. Any addresses provided in this parameter must be included in the `tokenList`. | -| `defaultInputAmount` | `number` | `0` | Default amount for the input field (e.g. 1 ETH). This value will respect the decimals of the `defaultInputTokenAddress`. This parameter is valid only if `defaultInputTokenAddress` is also set. This parameter is mutually exclusive with `defaultOutputTokenAmount`, so you may set only one of `defaultInputTokenAmount` and `defaultOutputTokenAmount`. | -| `defaultOutputTokenAddress` | `{[chainId: number]: string}` | `string` or `undefined` | Address of the token to be selected by default in the input field (e.g. USDC) for each network chain ID. None if left empty. Any addresses provided in this parameter must be included in the `tokenList`. | -| `defaultOutputAmount` | `number` | `0` | Default amount for the input field (e.g. 100 USDC). This value will respect the decimals of the `defaultOutputTokenAddress`. This parameter is mutually exclusive with `defaultInputTokenAmount`, so you may set only one `of defaultInputTokenAmount and` `defaultOutputTokenAmount`. | -| `hideConnectionUI` | `boolean` | `false` | Hide the widget's built-in wallet connection UI, including the connected account chip & 'Connect wallet to swap' button. | -| `locale` | `SupportedLocale` | `en-US` | Specifies an explicit locale to use for the widget interface. This can be set to one of the values exported by the library in [`SUPPORTED_LOCALES`](https://github.com/Uniswap/widgets/blob/main/src/constants/locales.ts). | -| `onConnectWalletClick` | `() => void` or `() => Promise` | `undefined` | If passed, allows you to add custom behavior when the user clicks on the 'Connect your wallet to swap' button. To manage displaying the widget's built-in wallet connection modal, return a resolved promise with `resolve(true/false)`. | -| `onSwitchChain` | `(addChainParameter: AddEthereumChainParameter) => void` or `Promise` | `undefined` | An integration hook called when the user tries to switch chains. If the hook returns a Promise, it is assumed the integrator is attempting to switch the chain, and no further attempts will be made. If that Promise rejects, the error will be ignored so as not to crash the widget. | -| `onError` | `ErrorHandler` | `undefined` | An error handler which receives any Javascript errors that occur in the widget. This can be used for collecting error metrics. | -| `onReviewSwapClick` | `() => void` or `() => Promise` | `undefined` | If passed, allows you to add custom behavior when the user clicks on the 'review swap' button. To manage progression to the review screen (i.e. to add a pre-swap warning speedbump), return a resolved promise with `resolve(true/false)`. | -| `onTokenSelectorClick` | `(f: Field) => void \| (f: Field) => Promise` | `undefined` | A click handler fired with the selected `Field` (`'INPUT'\|'OUTPUT'`) when the user clicks on a token selector dropdown. To manage progression to the native token selector view (i.e. to utilize your own external token selector UI), return a resolved promise with resolve(true/false). | -| `onTxFail` | `(error: Error, data: any) => void` | `undefined` | An error handler which receives error data for on-chain transaction failures. Does not include when user cancels a transaction or if a transaction isn't able to be submitted. | -| `onTxSubmit` | `(txHash: string, data: any) => void` | `undefined` | A handler that receives the transaction hash and related data when a user submits a transaction. | -| `onTxSuccess` | `(txHash: string, data: any) => void` | `undefined` | A handler that receives the transaction hash and related data when a transaction succeeds on-chain. | -| `routerUrl` | `string` | `undefined` | Optionally provide a base URL to your own hosted instance of the t1 Router API. If none is provided, the optimal trade route is computed by running the @uniswap/smart-order-router package locally in the browser; this can take a few seconds to load & is slower. You also may be able to find more optimal routes using the Router API! See more about [deploying the Router API](https://github.com/Uniswap/routing-api#deploying-the-api). | -| `theme` | `Theme` | `lightTheme` | Specifies a custom theme (colors, font, and border radii). See [Customizing the Theme](../guides/swap-widget.mdx#customizing-theme). | -| `tokenList` | `string` | `TokenInfo[]` | Specifies the set of tokens that appear by default in the token selector list. Accepts either a URI of a token list as defined by the Token Lists standard, or an inline array of tokens. If none is provided, the t1 Labs default token list will be used. See [Customizing the Default Token List](../guides/swap-widget.mdx#customizing-default-token-list). | -| `width` | `number` or `string` | `360` | Specifies the width of the widget. If specified as a number, this is in pixels; otherwise, it is interpreted as a CSS `` data type. Recommended width is 360px. Minimum width is 300px. See [Customizing the Width](../guides/swap-widget.mdx#customizing-width). | -| `brandedFooter` | `boolean` | `true` | Enables the "Powered by t1" footer at the bottom of the widget. | -| `dialog` | `HTMLDivElement` | `undefined` | Specifies the element to portal widget dialogs (e.g. Summary, Transaction dialogs) into. | -| `dialogOptions` | `DialogOptions` | `undefined` | Specifies more custom dialog behavior, like transition animations. | - - -## Subscribing to Events - -During the lifecycle of the swap widget, most of the events you will need are available on the web3 provider. For example, the below snippet shows how to listen for events when the wallet account changes or a new wallet connects. You can see more event examples in the [MetaMask](https://docs.metamask.io/guide/ethereum-provider.html) docs. - -```js -// Subscribe to messages -interface ProviderMessage { - type: string; - data: unknown; -} - -ethereum.on( - 'message', - handler: (message: ProviderMessage) => void -); -``` - -
- -:::note Questions? -Join the [Discord channel](https://discord.com/channels/597638925346930701/941447445844463676) to ask questions and get support from the t1 community. -::: diff --git a/docs/sdk/v1/_category_.json b/docs/sdk/v1/_category_.json deleted file mode 100644 index 754ace793..000000000 --- a/docs/sdk/v1/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "label": "V1 SDK", - "position": 6, - "collapsed": true -} diff --git a/docs/sdk/v1/guides/_category_.json b/docs/sdk/v1/guides/_category_.json deleted file mode 100644 index c694eb5b2..000000000 --- a/docs/sdk/v1/guides/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "label": "Guides", - "position": 2, - "collapsed": false -} diff --git a/docs/sdk/v1/guides/getting-started.md b/docs/sdk/v1/guides/getting-started.md deleted file mode 100644 index a49761680..000000000 --- a/docs/sdk/v1/guides/getting-started.md +++ /dev/null @@ -1,40 +0,0 @@ ---- -id: getting-started -title: Getting Started -sidebar_position: 1 ---- - -The [Uniswap SDK](https://github.com/Uniswap/uniswap-sdk/tree/v1) is meant to simplify every aspect of integrating t1 into your project. It's written in [TypeScript](https://www.typescriptlang.org), has a [robust test suite](https://github.com/Uniswap/uniswap-sdk/tree/v1/src/__tests__), uses [bignumber.js](https://github.com/MikeMcl/bignumber.js) for math, and includes an optional data-fetching module which relies on [ethers.js](https://github.com/ethers-io/ethers.js/). - -The SDK was built to be extremely easy to use, but also feature-rich. It offers various levels of abstraction that make it suitable for use nearly anywhere, from hackathon projects to production applications. - -# Overview - -The SDK is divided into several modular components that perform tightly scoped tasks: - -- [Data](/sdk/1.0.0/reference/data) - Fetches t1 data from the blockchain -- [Computation](/sdk/1.0.0/reference/computation) - Computes market- and trade-specific statistics using blockchain data -- [Format](/sdk/1.0.0/reference/format) - Formats data for display -- [Orchestration](/sdk/1.0.0/reference/orchestration) - Offers named abstraction functions that seamlessly combine lower-level data- and computation-related functions -- [Transact](/sdk/1.0.0/reference/transact) - Prepares computed trades for execution against t1 smart contracts -- [Constants](/sdk/1.0.0/reference/constants) - Exports various helpful constants for use throughout the SDK - -Additionally, it exports a number of custom types: - -- [Types](/sdk/1.0.0/reference/types) - Exports all types used by the SDK - -# Installation - -To start using the SDK, simply install it into your project... - -```bash -yarn add @uniswap/sdk -``` - -...import some functions... - -```javascript -import { ... } from '@uniswap/sdk' -``` - -...and dive into the rest of the documentation to learn more! diff --git a/docs/sdk/v1/overview.md b/docs/sdk/v1/overview.md deleted file mode 100644 index fbb3ef863..000000000 --- a/docs/sdk/v1/overview.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -id: overview -sidebar_position: 1 -title: Overview ---- - -# The t1 V1 SDK - -This is the original documentation for the t1 V1 SDK, released in 2019. -The t1 V1 SDK is no longer under development, for the most recent implementation of the SDK, see the [V3 SDK](../v3/overview.md). \ No newline at end of file diff --git a/docs/sdk/v1/reference/02-data.md b/docs/sdk/v1/reference/02-data.md deleted file mode 100644 index 5f70e9158..000000000 --- a/docs/sdk/v1/reference/02-data.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -id: data -title: Data ---- - -# getTokenReserves - -This function fetches t1 reserve data for a given token address on a given network. - -- If only a chain id is specified, the Ethereum node used to fulfill data requests is determined by [`ethers.getDefaultProvider`](https://docs.ethers.io/ethers.js/html/api-providers.html#connecting-to-ethereum), else it is the one specified by the passed provider. -- This function throws an error if the provided tokenAddress is not a token with a t1 exchange. - -## Function Signature - -```typescript -export async function getTokenReserves( - tokenAddress: string, - chainIdOrProvider: ChainIdOrProvider = 1 -): Promise -``` - -## Input Parameters - -| Parameter | Type | Description | -| :---------------- | :------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| tokenAddress | `string` | The checksummed address of a token with a t1 exchange. | -| chainIdOrProvider | `ChainIdOrProvider` | A supported chain id \(`1`, `3`, `4`, or `42`\), or an [underlying web3 provider](https://docs.ethers.io/ethers.js/html/api-providers.html#web3provider-inherits-from-jsonrpcprovider) connected to a chain with a supported chain id. | - -## Example Usage - -```typescript -const tokenAddress = '0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359' // DAI Mainnet -const chainIdOrProvider: ChainIdOrProvider = 1 // could be e.g. window.ethereum instead - -const tokenReserves: TokenReservesNormalized = await getTokenReserves(tokenAddress, chainIdOrProvider) - -/* -{ - // details for the passed token - token: { - chainId: 1, - address: '0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359', - decimals: 18 - }, - - // details for the t1 exchange of the passed token - exchange: { - chainId: 1, - address: '0x09cabEC1eAd1c0Ba254B09efb3EE13841712bE14', - decimals: 18 - }, - - // details for the ETH portion of the reserves of the passed token - ethReserve: { - token: { - chainId: 1, - address: 'ETH', - decimals: 18 - }, - amount: - }, - - // details for the token portion of the reserves of the passed token - tokenReserve: { - token: { - chainId: 1, - address: '0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359', - decimals: 18 - }, - amount: - } -} -*/ -``` diff --git a/docs/sdk/v1/reference/03-computation.md b/docs/sdk/v1/reference/03-computation.md deleted file mode 100644 index 009076785..000000000 --- a/docs/sdk/v1/reference/03-computation.md +++ /dev/null @@ -1,133 +0,0 @@ ---- -id: computation -title: Computation ---- - -# getMarketDetails - -This function computes market details for the passed reserves data. Markets are defined as ETH<>ERC20, ERC20<>ETH, or ERC20<>ERC20 pairs, where the first currency is the input and the second is the output. Reserves must be specified for both the input and output currency. - -- In the case of ETH, `undefined` should be passed as the reserves data. [`getTokenReserves`](/sdk/1.0.0/reference/data/#getttokenreserves) formatted ERC20 reserves, or the requisite data can be fetched manually and passed in. - -- Rates are calculated to 18 decimal places of precision. - -## Function Signature - -```typescript -export function getMarketDetails( - optionalReservesInput: OptionalReserves, - optionalReservesOutput: OptionalReserves -): MarketDetails -``` - -## Input Parameters - -| Parameter | Type | Description | -| :--------------------- | :----------------- | :------------------------------------- | -| optionalReservesInput | `OptionalReserves` | Reserves data for the input currency. | -| optionalReservesOutput | `OptionalReserves` | Reserves data for the output currency. | - -## Example Usage - -```typescript -const reserves: ChainIdOrProvider = await getTokenReserves(tokenAddress) - -const marketDetails: MarketDetails = getMarketDetails(undefined, reserves) // ETH<>ERC20 - -/* -{ - // market type - tradeType: 'ETH_TO_TOKEN', - - // dummy ETH reserves - inputReserves: { - token: { - chainId: 1, - address: 'ETH', - decimals: 18 - } - }, - - // normalized token reserves - outputReserves: , - - // market rate calculated to 18 decimals of precision - marketRate: { - rate: , // x output / 1 input - rateInverted: // x input / 1 output - } -} -*/ -``` - -# getTradeDetails - -This function computes trade details for the passed market data. - --This function throws an error if the passed \_tradeAmount is greater than the amount of ETH/tokens in the relevant t1 exchange. - -- Trade amounts must be passed in non-decimal form \(where e.g. 1 ETH is represented as 1000000000000000000 wei\). - -## Function Signature - -```typescript -export function getTradeDetails( - tradeExact: TRADE_EXACT, - _tradeAmount: BigNumberish, - marketDetails: MarketDetails -): TradeDetails -``` - -## Input Parameters - -| Parameter | Type | Description | -| :------------ | :-------------- | :------------------------------------------------------------------------------- | -| tradeExact | `TRADE_EXACT` | Whether either the input or the output currency is the exact amount. | -| \_tradeAmount | `BigNumberish` | The amount to buy/sell \(of the output/input currency, depending on tradeExact\) | -| marketDetails | `MarketDetails` | Market details. | - -## Example Usage - -```typescript -const _purchaseAmount: BigNumber = new BigNumber('2.5') -const _decimals: number = 18 -const tradeAmount: BigNumber = _purchaseAmount.multipliedBy(10 ** _decimals) -const marketDetails: MarketDetails = getMarketDetails(undefined, reserves) // ETH<>ERC20 - -// buy exactly 2.5 of an 18 decimal ERC20 with ETH -const tradeDetails: TradeDetails = getTradeDetails(TRADE_EXACT.OUTPUT, tradeAmount, marketDetails) - -/* -{ - marketDetailsPre: , - - marketDetailsPost: , - - tradeType: 'ETH_TO_TOKEN', - - tradeExact: 'OUTPUT', - - inputAmount: { - token: , - amount: - }, - - outputAmount: { - token: , - amount: - }, - - // execution rate calculated to 18 decimals of precision - executionRate: { - rate: // x output / 1 input - rateInverted: // x input / 1 output - }, - - // slippage between the pre- and post-trade market rates, in basis points, calculated to 18 decimals of precision - marketRateSlippage: , - - // slippage between the execution and pre-trade market rate, in basis points, calculated to 18 decimals of precision - executionRateSlippage: -} -*/ -``` diff --git a/docs/sdk/v1/reference/04-format.md b/docs/sdk/v1/reference/04-format.md deleted file mode 100644 index 3a40ea31a..000000000 --- a/docs/sdk/v1/reference/04-format.md +++ /dev/null @@ -1,106 +0,0 @@ ---- -id: format -title: Format ---- - -# formatSignificant - -This function formats values to a specified number of significant digits. - -## Function Signature - -```typescript -export function formatSignificant(bigNumberish: BigNumberish, options?: FormatSignificantOptions): string -``` - -## Input Parameters - -| Parameter | Type | Description | -| :----------- | :------------------------- | :------------------------- | -| bigNumberish | `BigNumberish` | The value to be formatted. | -| options? | `FormatSignificantOptions` | Formatting options. | - -## Example Usage - -```typescript -const formatted: string = formatSignificant('123456', { significantDigits: 3 }) // 1.23 -``` - -# formatSignificantDecimals - -This function formats token and ethereum values to a specified number of significant digits. - -## Function Signature - -```typescript -export function formatSignificantDecimals( - bigNumberish: BigNumberish, - decimals: number, - options?: FormatSignificantOptions -): string -``` - -## Input Parameters - -| Parameter | Type | Description | -| :----------- | :------------------------- | :-------------------------------- | -| bigNumberish | `BigNumberish` | The value to be formatted. | -| decimals | `number` | The decimals of the passed value. | -| options? | `FormatSignificantOptions` | Formatting options. | - -## Example Usage - -```typescript -const formatted: string = formatSignificantDecimals('1234560000000000000', 18, { - significantDigits: 3, -}) // 1.23 -``` - -# formatFixed - -This function formats values to a specified number of decimal places. - -## Function Signature - -```typescript -export function formatFixed(bigNumberish: BigNumberish, options?: FormatFixedOptions): string -``` - -## Input Parameters - -| Parameter | Type | Description | -| :----------- | :------------------- | :------------------------- | -| bigNumberish | `BigNumberish` | The value to be formatted. | -| options? | `FormatFixedOptions` | Formatting options. | - -## Example Usage - -```typescript -const formatted: string = formatFixed('1.2345', { decimalPlaces: 2 }) // 1.23 -``` - -# formatFixedDecimals - -This function formats token and ethereum values to a specified number of decimal places. - -## Function Signature - -```typescript -export function formatFixedDecimals(bigNumberish: BigNumberish, decimals: number, options?: FormatFixedOptions): string -``` - -## Input Parameters - -| Parameter | Type | Description | -| :----------- | :------------------- | :-------------------------------- | -| bigNumberish | `BigNumberish` | The value to be formatted. | -| decimals | `number` | The decimals of the passed value. | -| options? | `FormatFixedOptions` | Formatting options. | - -## Example Usage - -```typescript -const formatted: string = formatFixedDecimals('1234560000000000000', 18, { - decimalPlaces: 2, -}) // 1.23 -``` diff --git a/docs/sdk/v1/reference/05-orchestration.md b/docs/sdk/v1/reference/05-orchestration.md deleted file mode 100644 index af1f21754..000000000 --- a/docs/sdk/v1/reference/05-orchestration.md +++ /dev/null @@ -1,344 +0,0 @@ ---- -id: orchestration -title: Orchestration ---- - -Orchestration functions are plain-english wrappers for the function defined in [/sdk/1.0.0/reference/data](Data) and [Computation](/sdk/1.0.0/reference/computation). - -Functions suffixed with `WithData` are synchronous, and require token reserves to be passed in as arguments. Functions without the suffix are asychronous, and require token addresses to be passed in as arguments. - -# tradeExactEthForTokensWithData - -The function facilitates trading an exact amount of ETH for a specified token. - -## Function Signature - -```typescript -export function tradeExactEthForTokensWithData(reserves: OptionalReserves, ethAmount: BigNumberish): TradeDetails -``` - -## Input Parameters - -| Parameter | Type | Description | -| :-------- | :----------------- | :---------------------------------- | -| reserves | `OptionalReserves` | Reserves data for the output token. | -| ethAmount | `BigNumberish` | The input amount of ETH. | - -## Example Usage - -```typescript -const tradeDetails: TradeDetails = tradeExactEthForTokensWithData(reserves, '1000000000000000000') -``` - -# tradeExactEthForTokens - -The function facilitates trading an exact amount of ETH for a specified token. - -## Function Signature - -```typescript -export async function tradeExactEthForTokens( - tokenAddress: string, - ethAmount: BigNumberish, - chainIdOrProvider?: ChainIdOrProvider -): Promise -``` - -## Input Parameters - -| Parameter | Type | Description | -| :----------------- | :------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| tokenAddress | `string` | Address of output token. | -| ethAmount | `BigNumberish` | The input amount of ETH. | -| chainIdOrProvider? | `ChainIdOrProvider` | A supported chain id \(`1`, `3`, `4`, or `42`\), or an [underlying web3 provider](https://docs.ethers.io/ethers.js/html/api-providers.html#web3provider-inherits-from-jsonrpcprovider) connected to a chain with a supported chain id. | - -## Example Usage - -```typescript -const tradeDetails: TradeDetails = await tradeExactEthForTokens(tokenAddress, '1000000000000000000') -``` - -# tradeEthForExactTokensWithData - -The function facilitates trading ETH for an exact amount of a specified token. - -## Function Signature - -```typescript -export function tradeEthForExactTokensWithData(reserves: OptionalReserves, tokenAmount: BigNumberish): TradeDetails -``` - -## Input Parameters - -| Parameter | Type | Description | -| :---------- | :----------------- | :---------------------------------- | -| reserves | `OptionalReserves` | Reserves data for the output token. | -| tokenAmount | `BigNumberish` | The output amount of tokens. | - -## Example Usage - -```typescript -const tradeDetails: TradeDetails = tradeEthForExactTokensWithData(reserves, '1000000000000000000') -``` - -# tradeEthForExactTokens - -The function facilitates trading ETH for an exact amount of a specified token. - -## Function Signature - -```typescript -export async function tradeEthForExactTokens( - tokenAddress: string, - tokenAmount: BigNumberish, - chainIdOrProvider?: ChainIdOrProvider -): Promise -``` - -## Input Parameters - -| Parameter | Type | Description | -| :----------------- | :------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| tokenAddress | `string` | Address of output token. | -| tokenAmount | `BigNumberish` | The output amount of tokens. | -| chainIdOrProvider? | `ChainIdOrProvider` | A supported chain id \(`1`, `3`, `4`, or `42`\), or an [underlying web3 provider](https://docs.ethers.io/ethers.js/html/api-providers.html#web3provider-inherits-from-jsonrpcprovider) connected to a chain with a supported chain id. | - -## Example Usage - -```typescript -const tradeDetails: TradeDetails = await tradeEthForExactTokens(tokenAddress, '1000000000000000000') -``` - -# tradeExactTokensForEthWithData - -The function facilitates trading an exact amount of a specified token for ETH. - -## Function Signature - -```typescript -export function tradeExactTokensForEthWithData(reserves: OptionalReserves, tokenAmount: BigNumberish): TradeDetails -``` - -## Input Parameters - -| Parameter | Type | Description | -| :---------- | :----------------- | :--------------------------------- | -| reserves | `OptionalReserves` | Reserves data for the input token. | -| tokenAmount | `BigNumberish` | The input amount of tokens. | - -## Example Usage - -```typescript -const tradeDetails: TradeDetails = tradeExactTokensForEthWithData(reserves, '1000000000000000000') -``` - -# tradeExactTokensForEth - -The function facilitates trading an exact amount of a specified token for ETH. - -## Function Signature - -```typescript -export async function tradeExactTokensForEth( - tokenAddress: string, - tokenAmount: BigNumberish, - chainIdOrProvider?: ChainIdOrProvider -): Promise -``` - -## Input Parameters - -| Parameter | Type | Description | -| :----------------- | :------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| tokenAddress | `string` | Address of input token. | -| tokenAmount | `BigNumberish` | The input amount of tokens. | -| chainIdOrProvider? | `ChainIdOrProvider` | A supported chain id \(`1`, `3`, `4`, or `42`\), or an [underlying web3 provider](https://docs.ethers.io/ethers.js/html/api-providers.html#web3provider-inherits-from-jsonrpcprovider) connected to a chain with a supported chain id. | - -## Example Usage - -```typescript -const tradeDetails: TradeDetails = await tradeExactTokensForEth(tokenAddress, '1000000000000000000') -``` - -# tradeTokensForExactEthWithData - -The function facilitates trading a specified token for an exact amount of ETH. - -## Function Signature - -```typescript -export function tradeTokensForExactEthWithData(reserves: OptionalReserves, ethAmount: BigNumberish): TradeDetails -``` - -## Input Parameters - -| Parameter | Type | Description | -| :-------- | :----------------- | :--------------------------------- | -| reserves | `OptionalReserves` | Reserves data for the input token. | -| ethAmount | `BigNumberish` | The outpute amount of ETH. | - -## Example Usage - -```typescript -const tradeDetails: TradeDetails = tradeTokensForExactEthWithData(reserves, '1000000000000000000') -``` - -# tradeTokensForExactEth - -The function facilitates trading a specified token for an exact amount of ETH. - -## Function Signature - -```typescript -export async function tradeTokensForExactEth( - tokenAddress: string, - ethAmount: BigNumberish, - chainIdOrProvider?: ChainIdOrProvider -): Promise -``` - -## Input Parameters - -| Parameter | Type | Description | -| :----------------- | :------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| tokenAddress | `string` | Address of input token. | -| ethAmount | `BigNumberish` | The output amount of ETH. | -| chainIdOrProvider? | `ChainIdOrProvider` | A supported chain id \(`1`, `3`, `4`, or `42`\), or an [underlying web3 provider](https://docs.ethers.io/ethers.js/html/api-providers.html#web3provider-inherits-from-jsonrpcprovider) connected to a chain with a supported chain id. | - -## Example Usage - -```typescript -const tradeDetails: TradeDetails = await tradeTokensForExactEth(tokenAddress, '1000000000000000000') -``` - -# tradeExactTokensForTokensWithData - -The function facilitates trading an exact amount of a specified token for another token. - -## Function Signature - -```typescript -export function tradeExactTokensForTokensWithData( - reservesInput: OptionalReserves, - reservesOutput: OptionalReserves, - tokenAmount: BigNumberish -): TradeDetails -``` - -## Input Parameters - -| Parameter | Type | Description | -| :------------- | :----------------- | :---------------------------------- | -| reservesInput | `OptionalReserves` | Reserves data for the input token. | -| reservesOutput | `OptionalReserves` | Reserves data for the output token. | -| tokenAmount | `BigNumberish` | The input amount of tokens. | - -## Example Usage - -```typescript -const tradeDetails: TradeDetails = tradeExactTokensForTokensWithData( - reservesInput, - reservesOutput, - '1000000000000000000' -) -``` - -# tradeExactTokensForTokens - -The function facilitates trading an exact amount of a specified token for another token. - -## Function Signature - -```typescript -export async function tradeExactTokensForTokens( - tokenAddressInput: string, - tokenAddressOutput: string, - tokenAmount: BigNumberish, - chainIdOrProvider?: ChainIdOrProvider -): Promise -``` - -## Input Parameters - -| Parameter | Type | Description | -| :----------------- | :------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| tokenAddressInput | `string` | Address of input token. | -| tokenAddressOutput | `string` | Address of output token. | -| tokenAmount | `BigNumberish` | The input amount of tokens. | -| chainIdOrProvider? | `ChainIdOrProvider` | A supported chain id \(`1`, `3`, `4`, or `42`\), or an [underlying web3 provider](https://docs.ethers.io/ethers.js/html/api-providers.html#web3provider-inherits-from-jsonrpcprovider) connected to a chain with a supported chain id. | - -## Example Usage - -```typescript -const tradeDetails: TradeDetails = await tradeExactTokensForTokens( - tokenAddressInput, - tokenAddressOutput, - '1000000000000000000' -) -``` - -# tradeTokensForExactTokensWithData - -The function facilitates trading a specified token for an exact amount of another token. - -## Function Signature - -```typescript -export function tradeTokensForExactTokensWithData( - reservesInput: OptionalReserves, - reservesOutput: OptionalReserves, - tokenAmount: BigNumberish -): TradeDetails -``` - -## Input Parameters - -| Parameter | Type | Description | -| :------------- | :----------------- | :---------------------------------- | -| reservesInput | `OptionalReserves` | Reserves data for the input token. | -| reservesOutput | `OptionalReserves` | Reserves data for the output token. | -| tokenAmount | `BigNumberish` | The output amount of tokens. | - -## Example Usage - -```typescript -const tradeDetails: TradeDetails = tradeTokensForExactTokensWithData( - reservesInput, - reservesOutput, - '1000000000000000000' -) -``` - -# tradeTokensForExactTokens - -The function facilitates trading an exact amount of a specified token for another token. - -## Function Signature - -```typescript -export async function tradeTokensForExactTokens( - tokenAddressInput: string, - tokenAddressOutput: string, - tokenAmount: BigNumberish, - chainIdOrProvider?: ChainIdOrProvider -): Promise -``` - -## Input Parameters - -| Parameter | Type | Description | -| :----------------- | :------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| tokenAddressInput | `string` | Address of input token. | -| tokenAddressOutput | `string` | Address of output token. | -| tokenAmount | `BigNumberish` | The output amount of tokens. | -| chainIdOrProvider? | `ChainIdOrProvider` | A supported chain id \(`1`, `3`, `4`, or `42`\), or an [underlying web3 provider](https://docs.ethers.io/ethers.js/html/api-providers.html#web3provider-inherits-from-jsonrpcprovider) connected to a chain with a supported chain id. | - -## Example Usage - -```typescript -const tradeDetails: TradeDetails = await tradeTokensForExactTokens( - tokenAddressInput, - tokenAddressOutput, - '1000000000000000000' -) -``` diff --git a/docs/sdk/v1/reference/06-transact.md b/docs/sdk/v1/reference/06-transact.md deleted file mode 100644 index b7750b2f2..000000000 --- a/docs/sdk/v1/reference/06-transact.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -id: transact -title: Transact ---- - -# getExecutionDetails - -The function formats trade data for execution against the relevant t1 exchange. - -## Function Signature - -```typescript -export function getExecutionDetails( - trade: TradeDetails, - maxSlippage?: number, - deadline?: number, - recipient?: string -): ExecutionDetails -``` - -## Input Parameters - -| Parameter | Type | Description | -| :----------- | :------------- | :---------------------------------------------------------------------- | -| trade | `TradeDetails` | The trade to execute. | -| maxSlippage? | `number` | The maximum slippage to allow, in basis points. Defaults to 200 \(2%\). | -| deadline? | `number` | When the transaction will expire. Defaults to 10 minutes in the future. | -| recipient? | `number` | An optional recipient address. Defaults to the `msg.sender` | - -## Example Usage - -Method arguments are returned as one of: `BigNumber`, `number`, or `string`. `BigNumber`s are large number objects, `numbers` are small numbers in base 10, and `string`s are addresses. - -```typescript -const tradeDetails: TradeDetails = tradeExactEthForTokensWithData(reserves, '1000000000000000000') - -const executionDetails: ExecutionDetails = await getExecutionDetails(tradeDetails) - -/* -{ - // the address of the relevant exchange - exchangeAddress: 0x09cabEC1eAd1c0Ba254B09efb3EE13841712bE14, - - // the name of the method that must be called - methodName: "ethToTokenSwapInput", - - // the id of the method name - methodId: "0xf39b5b9b", - - // the ether value that must be sent with the transaction - value: , - - // method arguments as an array - methodArguments: MethodArgument[] -} -*/ -``` diff --git a/docs/sdk/v1/reference/07-constants.md b/docs/sdk/v1/reference/07-constants.md deleted file mode 100644 index 7e74eb35e..000000000 --- a/docs/sdk/v1/reference/07-constants.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -id: constants -title: Constants ---- - -Below is an exhaustive list of all external constants used in the SDK. - -```typescript -import BigNumber from 'bignumber.js' - -import ERC20 from './abis/ERC20.json' -import FACTORY from './abis/FACTORY.json' -import EXCHANGE from './abis/EXCHANGE.json' - -export const ETH = 'ETH' - -export enum SUPPORTED_CHAIN_ID { - Mainnet = 1, - Ropsten = 3, - Rinkeby = 4, - Kovan = 42, -} - -export const FACTORY_ADDRESS: { [key: number]: string } = {} - -export const FACTORY_ABI: string = JSON.stringify(FACTORY) -export const EXCHANGE_ABI: string = JSON.stringify(EXCHANGE) - -export enum TRADE_TYPE { - ETH_TO_TOKEN = 'ETH_TO_TOKEN', - TOKEN_TO_ETH = 'TOKEN_TO_ETH', - TOKEN_TO_TOKEN = 'TOKEN_TO_TOKEN', -} - -export enum TRADE_EXACT { - INPUT = 'INPUT', - OUTPUT = 'OUTPUT', -} - -export enum TRADE_METHODS { - ethToTokenSwapInput = 'ethToTokenSwapInput', - ethToTokenTransferInput = 'ethToTokenTransferInput', - ethToTokenSwapOutput = 'ethToTokenSwapOutput', - ethToTokenTransferOutput = 'ethToTokenTransferOutput', - tokenToEthSwapInput = 'tokenToEthSwapInput', - tokenToEthTransferInput = 'tokenToEthTransferInput', - tokenToEthSwapOutput = 'tokenToEthSwapOutput', - tokenToEthTransferOutput = 'tokenToEthTransferOutput', - tokenToTokenSwapInput = 'tokenToTokenSwapInput', - tokenToTokenTransferInput = 'tokenToTokenTransferInput', - tokenToTokenSwapOutput = 'tokenToTokenSwapOutput', - tokenToTokenTransferOutput = 'tokenToTokenTransferOutput', -} - -export const TRADE_METHOD_IDS: { [key: string]: string } = {} - -export enum FIXED_UNDERFLOW_BEHAVIOR { - ZERO = 'ZERO', - LESS_THAN = 'LESS_THAN', - ONE_DIGIT = 'ONE_DIGIT', -} -``` diff --git a/docs/sdk/v1/reference/08-types.md b/docs/sdk/v1/reference/08-types.md deleted file mode 100644 index 15af25d9e..000000000 --- a/docs/sdk/v1/reference/08-types.md +++ /dev/null @@ -1,156 +0,0 @@ ---- -id: types -title: Types ---- - -Below is an exhaustive list of all the external types used in the SDK. - -```typescript -import BigNumber from 'bignumber.js' -import { ethers } from 'ethers' - -import { SUPPORTED_CHAIN_ID, TRADE_TYPE, TRADE_EXACT, FIXED_UNDERFLOW_BEHAVIOR } from './constants' - -export type BigNumberish = BigNumber | ethers.utils.BigNumber | string | number - -//// types for on-chain, submitted, and normalized data -export type ChainIdOrProvider = SUPPORTED_CHAIN_ID | ethers.providers.AsyncSendable | ethers.providers.Provider - -// type guard for ChainIdOrProvider -export function isChainId(chainIdOrProvider: ChainIdOrProvider): chainIdOrProvider is SUPPORTED_CHAIN_ID { - const chainId: SUPPORTED_CHAIN_ID = chainIdOrProvider as SUPPORTED_CHAIN_ID - return typeof chainId === 'number' -} - -// type guard for ChainIdOrProvider -export function isLowLevelProvider( - chainIdOrProvider: ChainIdOrProvider -): chainIdOrProvider is ethers.providers.AsyncSendable { - if (isChainId(chainIdOrProvider)) { - return false - } else { - const provider: ethers.providers.AsyncSendable = chainIdOrProvider as ethers.providers.AsyncSendable - return 'send' in provider || 'sendAsync' in provider - } -} - -export interface Token { - chainId?: SUPPORTED_CHAIN_ID - address?: string - decimals: number -} - -export interface TokenAmount { - token: Token - amount: BigNumberish -} - -export interface TokenAmountNormalized { - token: Token - amount: BigNumber -} - -export interface TokenReserves { - token: Token - exchange?: Token - ethReserve: TokenAmount - tokenReserve: TokenAmount -} - -export interface TokenReservesNormalized { - token: Token - exchange?: Token - ethReserve: TokenAmountNormalized - tokenReserve: TokenAmountNormalized -} - -export interface EthReserves { - token: Token -} - -// type for input data -export type OptionalReserves = TokenReserves | EthReserves | undefined - -// type guard for OptionalReserves -export function areTokenReserves(reserves: OptionalReserves): reserves is TokenReserves { - const tokenReserves: TokenReserves = reserves as TokenReserves - return ( - tokenReserves !== undefined && tokenReserves.ethReserve !== undefined && tokenReserves.tokenReserve !== undefined - ) -} - -// type guard for OptionalReserves -export function areETHReserves(reserves: OptionalReserves): reserves is EthReserves { - const tokenReserves: TokenReserves = reserves as TokenReserves - return ( - tokenReserves !== undefined && tokenReserves.ethReserve === undefined && tokenReserves.tokenReserve === undefined - ) -} - -// type for output data -export type NormalizedReserves = TokenReservesNormalized | EthReserves - -// type guard for NormalizedReserves -export function areTokenReservesNormalized(reserves: NormalizedReserves): reserves is TokenReservesNormalized { - const tokenReservesNormalized: TokenReservesNormalized = reserves as TokenReservesNormalized - return tokenReservesNormalized.ethReserve !== undefined && tokenReservesNormalized.tokenReserve !== undefined -} - -//// types for computed data -export interface Rate { - rate: BigNumber - rateInverted: BigNumber -} -export interface MarketDetails { - tradeType: TRADE_TYPE - inputReserves: NormalizedReserves - outputReserves: NormalizedReserves - marketRate: Rate -} - -export interface TradeDetails { - marketDetailsPre: MarketDetails - marketDetailsPost: MarketDetails - tradeType: TRADE_TYPE - tradeExact: TRADE_EXACT - inputAmount: TokenAmountNormalized - outputAmount: TokenAmountNormalized - executionRate: Rate - marketRateSlippage: BigNumber - executionRateSlippage: BigNumber -} - -export type MethodArgument = BigNumber | number | string - -export interface ExecutionDetails { - exchangeAddress: string - methodName: string - methodId: string - value: BigNumber - methodArguments: MethodArgument[] -} - -//// types for formatting data -export type FlexibleFormat = BigNumber.Format | boolean - -// type guard for FlexibleFormat -export function isFormat(flexibleFormat: FlexibleFormat): flexibleFormat is BigNumber.Format { - const format: BigNumber.Format = flexibleFormat as BigNumber.Format - return typeof format !== 'boolean' -} - -export interface FormatSignificantOptions { - significantDigits: number - roundingMode: BigNumber.RoundingMode - forceIntegerSignificance: boolean - format: FlexibleFormat -} - -export interface FormatFixedOptions { - decimalPlaces: number - roundingMode: BigNumber.RoundingMode - dropTrailingZeros: boolean - underflowBehavior: FIXED_UNDERFLOW_BEHAVIOR - format: FlexibleFormat -} -``` diff --git a/docs/sdk/v1/reference/_category_.json b/docs/sdk/v1/reference/_category_.json deleted file mode 100644 index f98f581c3..000000000 --- a/docs/sdk/v1/reference/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "label": "Technical Reference", - "position": 2, - "collapsed": false -} diff --git a/docs/sdk/v2/_category_.json b/docs/sdk/v2/_category_.json deleted file mode 100644 index 3d94bdc77..000000000 --- a/docs/sdk/v2/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "label": "V2 SDK", - "position": 5, - "collapsed": true -} diff --git a/docs/sdk/v2/guides/01-quick-start.md b/docs/sdk/v2/guides/01-quick-start.md deleted file mode 100644 index a7ac66b85..000000000 --- a/docs/sdk/v2/guides/01-quick-start.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -id: quick-start -title: SDK Quick start ---- - -The t1 SDK exists to help developers build on top of t1. It's designed to run in any environment that can execute JavaScript (think websites, node scripts, etc.). While simple enough to use in a hackathon project, it's also robust enough to power production applications. - -# Installation - -The easiest way to consume the SDK is via [npm](https://github.com/Uniswap/uniswap-v2-sdk). To install it in your project, simply run `yarn add @uniswap/v2-sdk` (or `npm install @uniswap/v2-sdk`). This also installs the sdk-core package that is used by both the V2 and V3 SDK and ethers as dependencies. - -# Usage - -To run code from the SDK in your application, use an `import` or `require` statement, depending on which your environment supports. Note that the guides following this page will use ES6 syntax. - -## ES6 (import) - -```typescript -import { ChainId } from '@uniswap/sdk-core' -import {Pair} from '@uniswap/v2-sdk' -console.log(`The chainId of mainnet is ${ChainId.MAINNET}.`) -``` - -## CommonJS (require) - -```typescript -const CORE = require('@uniswap/sdk-core') -const V2_SDK = require('@uniswap/v2-sdk') -console.log(`The chainId of mainnet is ${CORE.ChainId.MAINNET}.`) -``` - -# Reference - -Comprehensive reference material for the SDK is publicly available on the [Uniswap Labs Github](https://github.com/Uniswap). diff --git a/docs/sdk/v2/guides/02-fetching-data.md b/docs/sdk/v2/guides/02-fetching-data.md deleted file mode 100644 index c5eb3c58e..000000000 --- a/docs/sdk/v2/guides/02-fetching-data.md +++ /dev/null @@ -1,103 +0,0 @@ ---- -id: fetching-data -title: Fetching Data ---- - -> Looking for a [quickstart](quick-start)? - -While the SDK is fully self-contained, there are two cases where it needs _on-chain data_ to function. -This guide will detail both of these cases, and offer a sample that you can use to fetch this data. - -# Case 1: Tokens - -Unsurprisingly, the SDK needs some notion of an ERC-20 token to be able to function. This immediately raises the question of _where data about tokens comes from_. - -As an example, let's try to represent DAI in a format the SDK can work with. To do so, we need at least 3 pieces of data: a **chainId**, a **token address**, and how many **decimals** the token has. We also may be interested in the **symbol** and/or **name** of the token. - -## Identifying Data - -The first two pieces of data — **chainId** and **token address** — must be provided by us. Thinking about it, this makes sense, as there's really no other way to unambiguously identify a token. - -So, in the case of DAI, we know that the **chainId** is `1` (we're on mainnet), and the **token address** is `0x6B175474E89094C44Da98b954EedeAC495271d0F`. Note that it's very important to externally verify token addresses. Don't use addresses from sources you don't trust! - -## Required Data - -The next piece of data we need is **decimals**. - -### Provided by the User - -One option here is to simply pass in the correct value, which we may know is `18`. At this point, we're ready to represent DAI as a [Token](../../core/reference/classes/Token.md): - -```typescript -import { ChainId, Token } from '@uniswap/sdk-core' - -const chainId = ChainId.MAINNET -const tokenAddress = '0x6B175474E89094C44Da98b954EedeAC495271d0F' // must be checksummed -const decimals = 18 - -const DAI = new Token(chainId, tokenAddress, decimals) -``` - -If we don't know or don't want to hardcode the value, we could look it up ourselves via any method of retrieving on-chain data in a function that looks something like: - -```typescript -import { ChainId } from '@uniswap/sdk-core' - -async function getDecimals(chainId: ChainId, tokenAddress: string): Promise { - // Setup provider, import necessary ABI ... - const tokenContract = new ethers.Contract(tokenAddress, erc20abi, provider) - return tokenContract["decimals"]() -} -``` - -## Optional Data - -Finally, we can talk about **symbol** and **name**. Because these fields aren't used anywhere in the SDK itself, they're optional, and can be provided if you want to use them in your application. However, the SDK will not fetch them for you, so you'll have to provide them: - -```typescript -import { ChainId, Token } from '@uniswap/sdk-core' - -const DAI = new Token(ChainId.MAINNET, '0x6B175474E89094C44Da98b954EedeAC495271d0F', 18, 'DAI', 'Dai Stablecoin') -``` - -# Case 2: Pairs - -Now that we've explored how to define a token, let's talk about pairs. To read more about what t1 pairs are, see [Pair](../../../contracts/v2/reference/smart-contracts/pair) - -As an example, let's try to represent the DAI-WETH pair. - -## Identifying Data - -Each pair consists of two tokens (see previous section). Note that WETH used by the router is [exported by the SDK Core as WETH9](../../core/reference/overview.md). - -## Required Data - -The data we need is the _reserves_ of the pair. To read more about reserves, see [getReserves](../../../contracts/v2/reference/smart-contracts/pair#getreserves). - -### Provided by the User - -One option here is to simply pass in values which we've fetched ourselves to create a [Pair](../reference/pair). In this example we use ethers to fetch the data directly from the blockchain: - -```typescript -import { ChainId, Token, WETH9, CurrencyAmount } from '@uniswap/sdk-core' -import { Pair } from '@uniswap/v2-sdk' - -const DAI = new Token(ChainId.MAINNET, '0x6B175474E89094C44Da98b954EedeAC495271d0F', 18) - -async function createPair(): Promise { - const pairAddress = Pair.getAddress(DAI, WETH9[DAI.chainId]) - - // Setup provider, import necessary ABI ... - const pairContract = new ethers.Contract(pairAddress, uniswapV2poolABI, provider) - const reserves = await pairContract["getReserves"]() - const [reserve0, reserve1] = reserves - - const tokens = [DAI, WETH9[DAI.chainId]] - const [token0, token1] = tokens[0].sortsBefore(tokens[1]) ? tokens : [tokens[1], tokens[0]] - - const pair = new Pair(CurrencyAmount.fromRawAmount(token0, reserve0), CurrencyAmount.fromRawAmount(token1, reserve1)) - return pair -} -``` - -Note that these values can change as frequently as every block, and should be kept up-to-date. diff --git a/docs/sdk/v2/guides/03-pricing.md b/docs/sdk/v2/guides/03-pricing.md deleted file mode 100644 index bec115028..000000000 --- a/docs/sdk/v2/guides/03-pricing.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -id: pricing -title: Pricing ---- - -> Looking for a [quickstart](quick-start)? - -Let's talk pricing. This guide will focus on the two most important t1 prices: the **mid price** and the **execution price**. - -# Mid Price - -The mid price, in the context of t1, is the price that reflects the _ratio of reserves in one or more pairs_. There are three ways we can think about this price. Perhaps most simply, it defines the relative value of one token in terms of the other. It also represents the price at which you could theoretically trade an infinitesimal amount (ε) of one token for the other. Finally, it can be interpreted as the current _market-clearing or fair value price_ of the assets. - -Let's consider the mid price for DAI-WETH (that is, the amount of DAI per 1 WETH). - -## Direct - -The simplest way to get the DAI-WETH mid price is to observe the pair directly: - -```typescript -import { ChainId, Token, WETH9 } from '@uniswap/sdk-core' -import { Route } from '@uniswap/v2-sdk' - -const DAI = new Token(ChainId.MAINNET, '0x6B175474E89094C44Da98b954EedeAC495271d0F', 18) - -// To learn how to get Pair data, refer to the previous guide. -const pair = await createPair(DAI, WETH9[ChainId.MAINNET]) - -const route = new Route([pair], WETH9[DAI.chainId], DAI) - -console.log(route.midPrice.toSignificant(6)) // 1901.08 -console.log(route.midPrice.invert().toSignificant(6)) // 0.000526017 -``` - -You may be wondering why we have to construct a _route_ to get the mid price, as opposed to simply getting it from the pair (which, after all, includes all the necessary data). The reason is simple: a route forces us to be opinionated about the _direction_ of trading. Routes consist of one or more pairs, an input token and an output token (which fully defines a trading path). In this case, we passed WETH as the input token and DAI as the output token, meaning we're interested in a WETH -> DAI trade. - -Now we understand that the mid price is going to be defined in terms of DAI/WETH. Not to worry though, if we need the WETH/DAI price, we can easily invert. - -Finally, you may have noticed that we're formatting the price to 6 significant digits. This is because internally, prices are stored as exact-precision fractions, which can be converted to other representations on demand. For a full list of options, see [Price](../../core/reference/classes/Price.md). - -## Indirect - -For the sake of example, let's imagine a direct pair between DAI and WETH _doesn't exist_. In order to get a DAI-WETH mid price we'll need to pick a valid route. Imagine both DAI and WETH have pairs with a third token, USDC. In that case, we can calculate an indirect mid price through the USDC pairs: - -```typescript -import { ChainId, Token, WETH9} from '@uniswap/sdk-core' -import { Route, Pair } from '@uniswap/v2-sdk' - -const USDC = new Token(ChainId.MAINNET, '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', 6) -const DAI = new Token(ChainId.MAINNET, '0x6B175474E89094C44Da98b954EedeAC495271d0F', 18) - -// To learn how to get Pair data, refer to the previous guide. -const USDCWETHPair = await createPair(USDC, WETH9[ChainId.MAINNET]) -const DAIUSDCPair = await createPair(DAI, USDC) - -const route = new Route([USDCWETHPair, DAIUSDCPair], WETH9[ChainId.MAINNET], DAI) - -console.log(route.midPrice.toSignificant(6)) // 1896.34 -console.log(route.midPrice.invert().toSignificant(6)) // 0.000527331 -``` - -# Execution Price - -Mid prices are great representations of the _current_ state of a route, but what about trades? It turns out that it makes sense to define another price, the _execution_ price of a trade, as the ratio of assets sent/received. - -Imagine we're interested in trading 1 WETH for DAI: - -```typescript -import { ChainId, Token, WETH9, CurrencyAmount, TradeType } from '@uniswap/sdk-core' -import { Route, Pair, Trade } from '@uniswap/v2-sdk' - -const DAI = new Token(ChainId.MAINNET, '0x6B175474E89094C44Da98b954EedeAC495271d0F', 18) - -// To learn how to get Pair data, refer to the previous guide. -const pair = await createPair(DAI, WETH9[DAI.chainId]) - -const route = new Route([pair], WETH9[DAI.chainId], DAI) - -const trade = new Trade(route, CurrencyAmount.fromRawAmount(WETH9[DAI.chainId], '1000000000000000000'), TradeType.EXACT_INPUT) - -console.log(trade.executionPrice.toSignificant(6)) // 1894.91 -``` - -Notice that we're constructing a trade of 1 WETH for as much DAI as possible, _given the current reserves of the direct pair_. The execution price represents the average DAI/WETH price for this trade. Of course, the reserves of any pair can change every block, which would affect the execution price. diff --git a/docs/sdk/v2/guides/04-trading.md b/docs/sdk/v2/guides/04-trading.md deleted file mode 100644 index 014cfb32c..000000000 --- a/docs/sdk/v2/guides/04-trading.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -id: trading -title: Trading ---- - -> Looking for a [quickstart](quick-start)? - -The SDK _cannot execute trades or send transactions on your behalf_. Rather, it offers utility classes and functions which make it easy to calculate the data required to safely interact with t1. Nearly everything you need to safely transact with t1 is provided by the [Trade](../reference/trade) entity. However, it is your responsibility to use this data to send transactions in whatever context makes sense for your application. - -This guide will focus exclusively on sending a transaction to the [latest t1 V2 router](../../../contracts/v2/reference/smart-contracts/router-02) - -# Sending a Transaction to the Router - -Let's say we want to trade 1 WETH for as much DAI as possible: - -```typescript -import { ChainId, Token, WETH9, CurrencyAmount, TradeType } from '@uniswap/sdk-core' -import {Trade, Route} from '@uniswap/v2-sdk' - -const DAI = new Token(ChainId.MAINNET, '0x6B175474E89094C44Da98b954EedeAC495271d0F', 18) - -// See the Fetching Data guide to learn how to get Pair data -const pair = await createPair(DAI, WETH9[DAI.chainId]) - -const route = new Route([pair], WETH9[DAI.chainId], DAI) - -const amountIn = '1000000000000000000' // 1 WETH - -const trade = new Trade(route, CurrencyAmount.fromRawAmount(WETH9[DAI.chainId], amountIn), TradeType.EXACT_INPUT) -``` - -So, we've constructed a trade entity, but how do we use it to actually send a transaction? There are still a few pieces we need to put in place. - -Before going on, we should explore how ETH works in the context of trading. Internally, the SDK uses WETH, as all t1 V2 pairs use WETH under the hood. However, it's perfectly possible for you as an end user to use ETH, and rely on the router to handle converting to/from WETH. So, let's use ETH. - -The first step is selecting the appropriate router function. The names of router functions are intended to be self-explanatory; in this case we want [swapExactETHForTokens](../../../contracts/v2/reference/smart-contracts/router-02#swapexactethfortokens), because we're swapping an exact amount of ETH for tokens. - -That Solidity interface for this function is: - -```solidity -function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) - external - payable - returns (uint[] memory amounts); -``` - -Jumping back to our trading code, we can construct all the necessary parameters: - -```typescript -import {Percent} from '@uniswap/sdk-core' - -const slippageTolerance = new Percent('50', '10000') // 50 bips, or 0.50% - -const amountOutMin = trade.minimumAmountOut(slippageTolerance).toExact() // needs to be converted to e.g. decimal string -const path = [WETH9[DAI.chainId].address, DAI.address] -const to = '' // should be a checksummed recipient address -const deadline = Math.floor(Date.now() / 1000) + 60 * 20 // 20 minutes from the current Unix time -const value = trade.inputAmount.toExact() // // needs to be converted to e.g. decimal string -``` - -The slippage tolerance encodes _how large of a price movement we're willing to tolerate before our trade will fail to execute_. Since Ethereum transactions are broadcast and confirmed in an adversarial environment, this tolerance is the best we can do to protect ourselves against price movements. We use this slippage tolerance to calculate the _minumum_ amount of DAI we must receive before our trade reverts, thanks to [minimumAmountOut](../reference/trade#minimumamountout-since-204). Note that this code calculates this worst-case outcome _assuming that the current price, i.e the route's mid price,_ is fair (usually a good assumption because of arbitrage). - -The path is simply the ordered list of token addresses we're trading through, in our case WETH and DAI (note that we use the WETH address, even though we're using ETH). - -The to address is the address that will receive the DAI. - -The deadline is the Unix timestamp after which the transaction will fail, to protect us in the case that our transaction takes a long time to confirm and we wish to rescind our trade. - -The value is the amount of ETH that must be included as the `msg.value` in our transaction. diff --git a/docs/sdk/v2/guides/05-getting-pair-addresses.md b/docs/sdk/v2/guides/05-getting-pair-addresses.md deleted file mode 100644 index 89cf73269..000000000 --- a/docs/sdk/v2/guides/05-getting-pair-addresses.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -id: getting-pair-addresses -title: Pair Addresses ---- - -# getPair - -The most obvious way to get the address for a pair is to call [getPair](../../../contracts/v2/reference/smart-contracts/factory#getpair) on the factory. If the pair exists, this function will return its address, else `address(0)` (`0x0000000000000000000000000000000000000000`). - -- The "canonical" way to determine whether or not a pair exists. -- Requires an on-chain lookup. - -# CREATE2 - -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: - -| | | -| :--------------------- | :----------------------------------------------------------------------------- | -| `address` | The [factory address](../../../contracts/v2/reference/smart-contracts/factory) | -| `salt` | `keccak256(abi.encodePacked(token0, token1))` | -| `keccak256(init_code)` | `0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f` | - -- `token0` must be strictly less than `token1` by sort order. - -* Can be computed offline. -* Requires the ability to perform `keccak256`. - -## Examples - -### TypeScript - -This example makes use of the [Uniswap V2 SDK](../reference/getting-started). In reality, the SDK computes pair addresses behind the scenes, obviating the need to compute them manually like this. - -```typescript -import { FACTORY_ADDRESS, INIT_CODE_HASH } from '@uniswap/v2-sdk' -import { pack, keccak256 } from '@ethersproject/solidity' -import { getCreate2Address } from '@ethersproject/address' - -const token0 = '0xCAFE000000000000000000000000000000000000' // change me! -const token1 = '0xF00D000000000000000000000000000000000000' // change me! - -const pair = getCreate2Address( - FACTORY_ADDRESS, - keccak256(['bytes'], [pack(['address', 'address'], [token0, token1])]), - INIT_CODE_HASH -) -``` diff --git a/docs/sdk/v2/guides/_category_.json b/docs/sdk/v2/guides/_category_.json deleted file mode 100644 index c694eb5b2..000000000 --- a/docs/sdk/v2/guides/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "label": "Guides", - "position": 2, - "collapsed": false -} diff --git a/docs/sdk/v2/overview.md b/docs/sdk/v2/overview.md deleted file mode 100644 index 01f0dee92..000000000 --- a/docs/sdk/v2/overview.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -id: overview -sidebar_position: 1 -title: Overview ---- - -# The t1 V2 SDK - -Welcome to the t1 Protocol V2 SDK. To begin, we recommend looking at the [**Guides**](./guides/01-quick-start.md) and for deeper reference see the [**V2 SDK Github**](https://github.com/Uniswap/v2-sdk) repo. - - -# t1 V2 SDK - -- [**V2 SDK Github**](https://github.com/Uniswap/v2-sdk) -- [**SDK Core Github**](https://github.com/Uniswap/sdk-core) -- [**SDK NPM Package**](https://www.npmjs.com/package/@uniswap/v2-sdk) - -[![Unit Tests](https://github.com/Uniswap/v2-sdk/workflows/Unit%20Tests/badge.svg)](https://github.com/Uniswap/v2-sdk/actions?query=workflow%3A%22Unit+Tests%22) -[![Lint](https://github.com/Uniswap/v2-sdk/workflows/Lint/badge.svg)](https://github.com/Uniswap/v2-sdk/actions?query=workflow%3ALint) -[![npm version](https://img.shields.io/npm/v/@uniswap/v2-sdk/latest.svg)](https://www.npmjs.com/package/@uniswap/v2-sdk/v/latest) -[![npm bundle size (scoped version)](https://img.shields.io/bundlephobia/minzip/@uniswap/v2-sdk/latest.svg)](https://bundlephobia.com/result?p=@uniswap/v2-sdk@latest) \ No newline at end of file diff --git a/docs/sdk/v2/reference/01-getting-started.md b/docs/sdk/v2/reference/01-getting-started.md deleted file mode 100644 index ec51ae923..000000000 --- a/docs/sdk/v2/reference/01-getting-started.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -id: getting-started -title: Getting Started ---- - -The pages that follow contain technical reference information on the t1 SDK. -Looking for a [quick start](../guides/quick-start) instead? -You may also want to jump into a [guide](../guides/fetching-data), -which offers a friendlier introduction to the SDK! - -The SDK is written in TypeScript, has a robust test suite, performs arbitrary precision arithmetic, -and supports rounding to significant digits or fixed decimal places. -The principal exports of the SDK are _entities_: classes that contain initialization and validation checks, -necessary data fields, and helper functions. - -An important concept in the SDK is _fractions_. Because Solidity performs integer math, care must be taken in -non-EVM environments to faithfully replicate the actual computation carried out on-chain. -The first concern here is to ensure that an overflow-safe integer implementation is used. -Ideally, the SDK would be able to use native [BigInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt)s. -However, until support becomes more widespread, [JSBI](https://github.com/GoogleChromeLabs/jsbi) objects are used instead, -with the idea that once BigInts proliferate, this dependency can be compiled away. -The second concern is precision loss due to, for example, chained price ratio calculations. -To address this issue, all math operations are performed as fraction operations, ensuring arbitrary precision up -until the point that values are rounded for display purposes, or truncated to fit inside a fixed bit width. - -The Fractions class, among others that the V2 SDK depends on, are exported from the SDK Core to allow interoperability with the V3 SDK. -Refer to the [Core SDK section of the docs](../../core/overview.md) to learn more about these classes. - -The SDK works for all chains on which the [factory](../../../contracts/v2/reference/smart-contracts/factory#address) is deployed. - -## Code - -The [source code is available on GitHub](https://github.com/Uniswap/uniswap-sdk). - -## Dependencies - -The SDK installs a small number of dependencies(https://github.com/Uniswap/v2-sdk/blob/main/package.json#L24). -The most important dependency of the V2 SDK is the SDK core, which was previously part of the V2 SDK itself, but later released as its own package to avoid duplicate code between the V2 and V3 SDK. diff --git a/docs/sdk/v2/reference/02-pair.md b/docs/sdk/v2/reference/02-pair.md deleted file mode 100644 index bdf093842..000000000 --- a/docs/sdk/v2/reference/02-pair.md +++ /dev/null @@ -1,129 +0,0 @@ ---- -id: pair -title: Pair ---- - -```typescript -constructor(tokenAmountA: CurrencyAmount, tokenAmountB: CurrencyAmount) -``` - -The Pair entity represents a t1 pair with a balance of each of its pair tokens. - -# Example - -```typescript -import { Pair } from '@uniswap/sdk-core' -import {ChainId, Token, CurrencyAmount } from '@uniswap/v2-sdk' - -const HOT = new Token(ChainId.MAINNET, '0xc0FFee0000000000000000000000000000000000', 18, 'HOT', 'Caffeine') -const NOT = new Token(ChainId.MAINNET, '0xDeCAf00000000000000000000000000000000000', 18, 'NOT', 'Caffeine') - -const pair = new Pair(CurrencyAmount.fromRawAmount(HOT, '2000000000000000000'), CurrencyAmount.fromRawAmount(NOT, '1000000000000000000')) -``` - -# Static Methods - -## getAddress - -```typescript -getAddress(tokenA: Token, tokenB: Token): string -``` - -Computes the pair address for the passed [Tokens](token). See [Pair Addresses](../../../contracts/v2/guides/smart-contract-integration/getting-pair-addresses). - -# Properties - -## liquidityToken - -```typescript -liquidityToken: Token -``` - -A Token representing the liquidity token for the pair. See [Pair (ERC-20)](../../../contracts/v2/reference/smart-contracts/pair-erc-20). - -## token0 - -```typescript -token0: Token -``` - -See [Token0](../../../contracts/v2/reference/smart-contracts/pair#token0). - -## token1 - -```typescript -token1: Token -``` - -See [Token1](../../../contracts/v2/reference/smart-contracts/pair#token1). - -## reserve0 - -```typescript -reserve0: CurrencyAmount -``` - -The reserve of token0. - -## reserve1 - -```typescript -reserve1: CurrencyAmount -``` - -The reserve of token1. - -# Methods - -## reserveOf - -```typescript -reserveOf(token: Token): CurrencyAmount -``` - -Returns reserve0 or reserve1, depending on whether token0 or token1 is passed in. - -## getOutputAmount - -```typescript -getOutputAmount(inputAmount: CurrencyAmount): [CurrencyAmount, Pair] -``` - -Pricing function for exact input amounts. Returns maximum output amount based on current reserves and the new Pair that would exist if the trade were executed. - -## getInputAmount - -```typescript -getInputAmount(outputAmount: CurrencyAmount): [CurrencyAmount, Pair] -``` - -Pricing function for exact output amounts. Returns minimum input amount based on current reserves and the new Pair that would exist if the trade were executed. - -## getLiquidityMinted - -```typescript -getLiquidityMinted(totalSupply: CurrencyAmount, tokenAmountA: CurrencyAmount, tokenAmountB: CurrencyAmount): CurrencyAmount -``` - -Calculates the exact amount of liquidity tokens minted from a given amount of token0 and token1. - -- totalSupply must be looked up on-chain. -- The value returned from this function _cannot_ be used as an input to getLiquidityValue. - -## getLiquidityValue - -```typescript -getLiquidityValue( - token: Token, - totalSupply: CurrencyAmount, - liquidity: CurrencyAmount, - feeOn: boolean = false, - kLast?: BigintIsh -): CurrencyAmount -``` - -Calculates the exact amount of token0 or token1 that the given amount of liquidity tokens represent. - -- totalSupply must be looked up on-chain. -- If the protocol charge is on, feeOn must be set to true, and kLast must be provided from an on-chain lookup. -- Values returned from this function _cannot_ be used as inputs to getLiquidityMinted. diff --git a/docs/sdk/v2/reference/03-route.md b/docs/sdk/v2/reference/03-route.md deleted file mode 100644 index 8b989f012..000000000 --- a/docs/sdk/v2/reference/03-route.md +++ /dev/null @@ -1,65 +0,0 @@ ---- -id: route -title: Route ---- - -```typescript -constructor(pairs: Pair[], input: Token, output: Token) -``` - -The Route entity represents one or more ordered t1 pairs with a fully specified path from input token to output token. - -# Example - -```typescript -import { ChainId, Token, CurrencyAmount } from '@uniswap/sdk-core' -import { Pair, Route } from '@uniswap/v2-sdk' - -const HOT = new Token(ChainId.MAINNET, '0xc0FFee0000000000000000000000000000000000', 18, 'HOT', 'Caffeine') -const NOT = new Token(ChainId.MAINNET, '0xDeCAf00000000000000000000000000000000000', 18, 'NOT', 'Caffeine') -const HOT_NOT = new Pair(CurrencyAmount.fromRawAmount(HOT, '2000000000000000000'), CurrencyAmount.fromRawAmount(NOT, '1000000000000000000')) - -const route = new Route([HOT_NOT], NOT, HOT) -``` - -# Properties - -## pairs - -```typescript -pairs: Pair[] -``` - -The ordered pairs that the route is comprised of. - -## path - -```typescript -path: Token[] -``` - -The full path from input token to output token. - -## input - -```typescript -input: Token -``` - -The input token. - -## output - -```typescript -output: Token -``` - -The output token. - -## midPrice - -```typescript -midPrice: Price -``` - -Returns the current mid price along the route. diff --git a/docs/sdk/v2/reference/04-trade.md b/docs/sdk/v2/reference/04-trade.md deleted file mode 100644 index bf59be2fd..000000000 --- a/docs/sdk/v2/reference/04-trade.md +++ /dev/null @@ -1,159 +0,0 @@ ---- -id: trade -title: Trade ---- - -```typescript -constructor(route: Route, amount: CurrencyAmount, tradeType: TradeType) -``` - -The Trade entity represents a fully specified trade along a route. This entity supplies all the information necessary to craft a router transaction. - -# Example - -```typescript -import { ChainId, Token, CurrencyAmount, TradeType } from '@uniswap/sdk-core' -import { Pair, Trade, Route } - -const HOT = new Token(ChainId.MAINNET, '0xc0FFee0000000000000000000000000000000000', 18, 'HOT', 'Caffeine') -const NOT = new Token(ChainId.MAINNET, '0xDeCAf00000000000000000000000000000000000', 18, 'NOT', 'Caffeine') -const HOT_NOT = new Pair(CurrencyAmount.fromRawAmount(HOT, '2000000000000000000'), CurrencyAmount.fromRawAmount(NOT, '1000000000000000000')) -const NOT_TO_HOT = new Route([HOT_NOT], NOT, HOT) - -const trade = new Trade(NOT_TO_HOT, CurrencyAmount.fromRawAmount(NOT, '1000000000000000'), TradeType.EXACT_INPUT) -``` - -# Properties - -## route - -```typescript -route: Route -``` - -The [path](route#path) property of the route should be passed as the path parameter to router functions. - -## tradeType - -```typescript -tradeType: TradeType -``` - -`TradeType.EXACT_INPUT` corresponds to `swapExact*For*` router functions. `TradeType.EXACT_OUTPUT` corresponds to `swap*ForExact*` router functions. - -## inputAmount - -```typescript -inputAmount: CurrencyAmount -``` - -For exact input trades, this value should be passed as amountIn to router functions. For exact output trades, this value should be multiplied by a factor >1, representing slippage tolerance, and passed as amountInMax to router functions. - -## outputAmount - -```typescript -outputAmount: CurrencyAmount -``` - -For exact output trades, this value should be passed as amountOut to router functions. For exact input trades, this value should be multiplied by a factor <1, representing slippage tolerance, and passed as amountOutMin to router functions. - -## executionPrice - -```typescript -executionPrice: Price -``` - -The average price that the trade would execute at. - -## priceImpact - -```typescript -priceImpact: Percent -``` - -The percent difference between the mid price before the trade and the trade execution price. - -# Methods - -In the context of the following two methods, slippage refers to the percent difference between the actual price and the trade `executionPrice`. - -## minimumAmountOut (since 2.0.4) - -```typescript -minimumAmountOut(slippageTolerance: Percent): CurrencyAmount -``` - -Returns the minimum amount of the output token that should be received from a trade, given the slippage tolerance. - -Useful when constructing a transaction for a trade of type `EXACT_INPUT`. - -## maximumAmountIn (since 2.0.4) - -```typescript -maximumAmountIn(slippageTolerance: Percent): CurrencyAmount -``` - -Returns the maximum amount of the input token that should be spent on the trade, given the slippage tolerance. - -Useful when constructing a transaction for a trade of type `EXACT_OUTPUT`. - -## worstExecutionPrice - -Return the execution price after accounting for slippage tolerance - -```typescript -worstExecutionPrice(slippageTolerance: Percent): Price -``` - -# Static methods - -These static methods provide ways to construct ideal trades from lists of pairs. -Note these methods do not perform any aggregation across routes, as routes are linear. -It's possible that a better price can be had by combining multiple trades across -different routes. - -## exactIn - -Constructs an exact in trade with the given amount in and route. - -```typescript -Trade.exactIn(route: Route, amountIn: CurrencyAmount): Trade -``` - -## exactOut - -Constructs an exact out trade with the given amount out and route - -```typescript -Trade.exactOut(route: Route, amountOut: CurrencyAmount): Trade -``` - -## bestTradeExactIn - -Given a list of pairs, and a fixed amount in, returns the top `maxNumResults` trades that go from an input token -amount to an output token, making at most `maxHops` hops. -Note this does not consider aggregation, as routes are linear. It's possible a better route exists by splitting -the amount in among multiple routes. - -```typescript -Trade.bestTradeExactIn( - pairs: Pair[], - nextAmountIn: CurrencyAmount, - currencyOut: Token, - { maxNumResults = 3, maxHops = 3 }: BestTradeOptions = {}): Trade[] -``` - -## bestTradeExactOut - -Similar to the above method but instead targets a fixed output amount given a list of pairs, -and a fixed amount out, returns the top `maxNumResults` trades that go from an input token to an output token amount, -making at most `maxHops` hops. Note this does not consider aggregation, as routes are linear. -It is possible a better route exists by splitting the amountIn among multiple routes. - -```typescript -Trade.bestTradeExactOut( - pairs: Pair[], - currencyIn: Token, - nextAmountOut: CurrencyAmount, - { maxNumResults = 3, maxHops = 3 }: BestTradeOptions = {}): Trade[] -``` diff --git a/docs/sdk/v2/reference/05-other-exports.md b/docs/sdk/v2/reference/05-other-exports.md deleted file mode 100644 index 65391dcb5..000000000 --- a/docs/sdk/v2/reference/05-other-exports.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -id: other-exports -title: Other Exports ---- - -A enum denominating supported rounding options. - -# FACTORY_ADDRESS - -```typescript -import { FACTORY_ADDRESS } from '@uniswap/v2-sdk' -``` - -The [factory address](../../../contracts/v2/reference/smart-contracts/factory#address). - -# INIT_CODE_HASH - -```typescript -import { INIT_CODE_HASH } from '@uniswap/v2-sdk' -``` - -See [pair addresses](../../../contracts/v2/guides/smart-contract-integration/getting-pair-addresses). - -# MINIMUM_LIQUIDITY - -```typescript -import { MINIMUM_LIQUIDITY } from '@uniswap/v2-sdk' -``` - -See [minimum liquidity](../../../contracts/v2/reference/smart-contracts/pair#minimum-liquidity). - -# InsufficientReservesError - -```typescript -import { InsufficientReservesError } from '@uniswap/v2-sdk' -``` - -# InsufficientInputAmountError - -```typescript -import { InsufficientInputAmountError } from '@uniswap/v2-sdk' -``` diff --git a/docs/sdk/v2/reference/_category_.json b/docs/sdk/v2/reference/_category_.json deleted file mode 100644 index 0e72ac2e5..000000000 --- a/docs/sdk/v2/reference/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "label": "Technical Reference", - "position": 3, - "collapsed": false -} diff --git a/docs/sdk/v3/_category_.json b/docs/sdk/v3/_category_.json deleted file mode 100644 index cf72316e0..000000000 --- a/docs/sdk/v3/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "label": "V3 SDK", - "position": 1, - "collapsed": false -} diff --git a/docs/sdk/v3/guides/01-background.md b/docs/sdk/v3/guides/01-background.md deleted file mode 100644 index 08dc4ade9..000000000 --- a/docs/sdk/v3/guides/01-background.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -id: background -title: Background -position: 1 ---- - -Before integrating with t1, it may be helpful for newcomers to review the following background information on some important developer web3 concepts, the structure of our examples, and SDK concepts. - -:::info -Already familiar with web3 development and/or the basics of our SDK and want to get right to the code? Start with our first guide, [Getting a Quote](./swaps/01-quoting.md)! -::: - -## Providers - -Communication with the blockchain is typically done through a provider and local models of smart contracts and their [ABIs](./01-background.md#abis). - -To achieve this, our examples use the [ethers.js](https://docs.ethers.io/v5/) library. To instantiate a provider you will need a data source. Our examples offer two options: - -- **JSON RPC URL**: If you are working directly with the Ethereum mainnet or a local fork, products such as [Infura](https://infura.io/) offer JSON RPC URLs for a wide variety of chains and testnets. For our examples, we'll only be using the Ethereum mainnet. - -- **Wallet Extension**: If you are connecting to a wallet browser extension, these wallets embed a source directly into the Javascript window object as `window.ethereum`. This object surfaces information about the user's wallets and provides the ability to communicate with the connected chain. Importantly for our examples, it can be used with `ethers.js` to construct a provider. - -## t1's Runnable Examples - -Each guide is accompanied and driven by [runnable examples](https://github.com/Uniswap/examples/tree/main/v3-sdk) using React to provide a basic UI for interacting with the example. Each examples provides relevant options such as running against a local blockchain or connecting to the Ethereum mainnet directly. You also have the option of using a wallet extension which can be connected to either environment. - -Inputs and environment settings are configured in each example's `config.ts` and allows for simple setup and configuration. - -### Developing and Testing - -To test your code, we recommend utilizing a local fork of the Ethereum mainnet. To help facilitate easy testing, each example includes a quickstart for running the local chain with a test wallet. To further test, we also recommend using a wallet extension and connecting to the local chain. Finally, each example can be run against the Ethereum mainnet if desired. Full development instructs can be found in the `README.md` of each code example. - -### Utility Libraries - -Each example is concentrated into a single file within the `libs/` folder of the example, with the entry points noted in each guide and README. - -To allow the guides to focus on the SDK's core functionality, additional basic building blocks can be found in each example's `libs` folder. The exported functionality from these files is intended to be the minimum needed for each example and not a complete library for production usage. These also include storing core constants such as definitions for tokens, ABI's, and blockchain addresses that can distract from the core concepts. Below are summaries of the helping libraries you will encounter. - -#### Provider Utilities - -`provider.ts` wraps the basics of `ethers.js` and connecting to wallet extensions into an abstracted view of a provider, a wallet address, and the ability to send transactions. It also helps abstract the configured environment you wish to run against in your example without making code changes outside of your configuration. - -#### Wallet Utilities - -`wallet.ts` offers the ability to query a wallet (whether connected via an extension or defined in code/config) for its balances and other essential information. - -#### Pool Information - -`pool.ts` contains the basic querying of pool information when not essential / core to the relevant guide - -#### Display Utilities - -`conversion.ts` provides display and light math wrappers to help show human readable prices when dealing with currency amounts (typically stored as raw numbers and the decimal placement separate for precision reasons) in the form of two functions: `fromReadableAmount` and `toReadableAmount` - -## Notable SDK Structures and Concepts - -When working with the SDK it can be helpful to understand some of the design choices and why they are needed. Below you can find a few important concepts. - -### ABI's - -To allow others to interact with a smart contract, each contract exposes an ABI (Application Binary Interface). As these are defined on the blockchain, we must ensure the correct definitions are provided to our Javascript functions. ABI's are provided from various SDK's and imported in as needed. Some examples will define an ABI directly as needed. - -### CurrencyAmount and JSBI - -Cryptocurrency applications often work with very small fractions of tokens. As a result, high precision is very important. To ensure precision is upheld, the `CurrencyAmount` class helps store exact values as fractions and utilizes [JSBI](https://github.com/GoogleChromeLabs/jsbi) for compatibility across the web. To display these amounts nicely to users, additional work is sometimes required. - -### Currency - -The `Currency` class can represent both native currency (ETH) and an ERC20 `Token`. Currencies vary in their relative value, so the `Token` class allows your application to define the number of decimals needed for each currency along with the currency's address, symbol, and name. diff --git a/docs/sdk/v3/guides/02-local-development.md b/docs/sdk/v3/guides/02-local-development.md deleted file mode 100644 index 62b54f91b..000000000 --- a/docs/sdk/v3/guides/02-local-development.md +++ /dev/null @@ -1,136 +0,0 @@ ---- -id: local-development -title: Local Development -position: 2 ---- - -## Introduction - -Developing your dApps or smart contracts requires some tinkering to get a proper setup that is both a good simulation of how Mainnet will behave, -but also customizable enough to suit the needs of a development environment. - -One very common approach is to create your own custom chain offline and develop on top of it. -The issue with this approach is that if you are integrating with protocols like t1 or others that are on Mainnet, it's -difficult to simulate on your local chain as the smart contracts from Mainnet are not there. - -Another approach is to use a testnet like Ethereum Goerli. While most protocols (including t1) have versions of their smart contracts -deployed on common testnets, there are certain behavioural differences. Not all pools that are on Mainnet are on Goerli for example. -Also, it's difficult to get enough testnet ETH to account for real testing. And without lots of testnet ETH it's even more difficult -to swap to other coins on t1, if that's what you need to do in your development environment. - -This guide focuses on yet another approach to local development: Mainnet Forks. - -A Mainnet Fork is a local chain that copies the state of Ethereum Mainnet at a given block number. It then gives you access to cheat codes -like wallets with thousands of ETH and RPC URLs that you can use as drop-in replacements of real Mainnet RPCs. - -This approach combines the best of all other approaches. You have a local chain that you can manipulate to your liking -and you have real deployments of all the protocols you need to test and develop your dApp or smart contracts. - -:::info -This guide focuses on Ethereum Mainnet. But you can easily fork any other chain by simply replacing the RPC URL with -one of the network you want to use. -::: - -For this guide, the following packages are used: - -- [`@uniswap/v3-sdk`](https://www.npmjs.com/package/@uniswap/v3-sdk) -- [`@uniswap/sdk-core`](https://www.npmjs.com/package/@uniswap/sdk-core) -- [`ethers@5`](https://www.npmjs.com/package/ethers) - -Please note that we use ethers version 5, as this is still the most commonly used version of ethers.js. -If you use version 6, you will need to slightly change the syntax in the examples below. - -:::info -Forking a chain requires archival data and trace calls. Infura and normal geth instances are by default not archival. -You can get a free archival RPC that you can use to follow this guide and fork Mainnet you can visit [Chainnodes](https://www.chainnodes.org/). -::: - -## Using Foundry and Anvil - -There are several developer tools to fork Mainnet. -[Anvil](https://github.com/foundry-rs/foundry/blob/master/anvil/README.md) by foundry is a newcomer that's fast and easy to setup. -This guide focuses on Anvil. - -As a first step, follow the [installation guide](https://book.getfoundry.sh/getting-started/installation) in the foundry book. - -Once you have done that, you will be able to fork Mainnet straight away. Run the below command in your terminal: - -Make sure that you: - -- Replace your API Key (get one by heading to [Chainnodes](https://app.chainnodes.org/)) -- Replace the block number with a recent one, check [Etherscan](https://etherscan.io/) for that -- If you fork a non-Ethereum Mainnet chain, check [Chainlist](https://chainlist.org/) for the correct chain id and replace both occurrences in the command below - -```bash -anvil --fork-url https://mainnet.chainnodes.org/api_key --fork-block-number 17480237 --fork-chain-id 1 --chain-id 1 -``` - -Run `anvil --help` to see all available options. - -Once you have done that, you should see something like the below: - -anvil result after calling - -Your local fork of Mainnet is now running! - -And as you can see on the screenshot above, anvil prints a bunch of private keys that are loaded with 10k ETH each. -We will use them going forward to send transactions, including swaps on t1 pools. - -:::warning -Security consideration: This is a fork of Mainnet and the same chain id is used. You have no replay protection to Ethereum Mainnet. So you need to 1: Never use the anvil private keys on a real chain or send funds to it -(they are leaked everywhere) and 2: Not send any transactions to your local fork chain with accounts that you use on Ethereum Mainnet or other real chains. -::: - -If you scroll down in your terminal, near the bottom of the anvil logs you will find your RPC URL. -If you haven't changed any configs, it should be `127.0.0.1:8545`. -This is the RPC URL that you can now use as a drop-in replacement everywhere in your development environment, and interact with it -as if it was real Ethereum Mainnet. You can use the http provider `http://127.0.0.1:8545` as well as the Websocket provider `ws://127.0.0.1:8545`. - -You can now make a sample RPC request to your http provider using [Postman](https://www.postman.com/) using the below: - -POST `http://127.0.0.1:8545` - -Body: - -```JSON -{ - "jsonrpc": "2.0", - "method": "eth_chainId", - "params": [], - "id": 1 -} -``` - -The result should look like the below (see image below as well): - -```JSON -{ - "jsonrpc": "2.0", - "id": 1, - "result": "0x1" -} -``` - -anvil result after calling - -As you can see, the chain id is `1`, just like on Mainnet! - -You can find the above example and more in [this Postman workspace](https://www.postman.com/chainnodes/workspace/uniswap-examples) under "Local Development". - -## Using your Mainnet Fork - -Now that you have a running Mainnet Fork, you will be able to use it everywhere in your development setup. -Using one of the private keys provided by anvil, you have access to enough ETH to do endless swaps and smart contract calls. - -If you need any other token, you now have the flexibility of swapping your ETH to any token that has a pool deployed on Mainnet. -You basically take your fake ETH and swap it to the token you need. - -Check out one of the [guides about swapping](./swaps/02-trading.md) and replace the RPC URL with your local anvil HTTP link as above. - -## Next Steps - -Using the above you are fully equipped to continue following the guides about how to use t1 while testing everything locally before -going on Mainnet. You will also be able to reuse what you have learned when you develop your own protocols or dApps. - -You can also continue tapping into other developer tools that make smart contract development easier like [forge](https://github.com/foundry-rs/foundry/tree/master/forge) from foundry. -To read more about foundry and their developer tooling, visit their [Github](https://github.com/foundry-rs/foundry) or the [foundry book](https://book.getfoundry.sh/). diff --git a/docs/sdk/v3/guides/03-web3-development-basics.md b/docs/sdk/v3/guides/03-web3-development-basics.md deleted file mode 100644 index d2dbe0ab7..000000000 --- a/docs/sdk/v3/guides/03-web3-development-basics.md +++ /dev/null @@ -1,192 +0,0 @@ ---- -id: web3-development-basics -title: Web3 Development Basics -position: 3 ---- - -## Introduction - -Developing dApps and interacting with Smart Contracts is quite different from Web2, and at times challenging due to little information -on this topic compared to other areas of software development. - -This developer guide is a quick overview of the space, including references to libraries and guides that are great starting points. -Reading this guide should help you identify areas that you might need to learn a bit more about and prepare you for the following t1-specific guides. - -It is assumed that you know the basics about Ethereum and the blockchain, including some terminology. -If you already know how to build dApps and interact with ethersJS etc. you can safely skip this guide. - -## RPCs - -The access point to the blockchain are RPC nodes. They are the [standardized interface](https://ethereum.org/en/developers/docs/apis/json-rpc/) -to read data from smart contracts, send transactions and interact with on-chain protocols. - -RPCs are either [full or archival nodes](https://ethereum.org/en/developers/docs/nodes-and-clients/archive-nodes/) -with a ([JSON-RPC](https://www.jsonrpc.org/)) interface. - -To support Ethereum's decentralization, one can host a node themselves, for example by using one of the implementations listed below: - -* [geth](https://github.com/ethereum/go-ethereum) - The original (reference) implementation of the Ethereum protocol -* [erigon](https://github.com/ledgerwatch/erigon) - A very efficient archival node implementation -* [Nethermind](https://github.com/NethermindEth/nethermind) - An Ethereum implementation focused on stability - -As achieving high availability and making sure your node is synced all the time turns out to be quite challenging, -there are nodes as a service (RPC) providers that you can use, especially in production environments. -When choosing an RPC provider, we suggest you look for an RPC service that supports websockets as they provide far superior performance than HTTP connections. -To ensure interoperability, you should also ensure that your RPC provider adheres strictly to the JSON-RPC standard and doesn't require custom requests. - -[Chainnodes](https://www.chainnodes.org/) is a robust RPC provider with generous free tier that you can use in both development and production environments. -For testing purposes you could also use a free public RPC endpoint, for example from [Chainlist](https://chainlist.org/). - -### JSON-RPC Standard - -RPCs communicate over the [JSON-RPC](https://www.jsonrpc.org/) standard. To send requests, you take the RPC URL and -make a POST request with a JSON body. See the below example: - -`POST https://mainnet.chainnodes.org/API_KEY` - -Body: - -```json -{ - "jsonrpc": "2.0", - "method": "eth_blockNumber", - "params": [], - "id": 1 -} -``` - -At the time of writing, this request would respond with the following: - -```json -{ - "id": 1, - "result": "0x11527c0", - "jsonrpc": "2.0" -} -``` - -Examining the result, we see that the result is an encoded hex string. -After decoding it, we see it returns the current blocknumber of our network, `18163648`. - -You can find the above examples, including more, in [this Postman collection](https://www.postman.com/chainnodes/workspace/uniswap-examples). - -To check out all possible RPC requests, head over to the [Chainnodes Docs](https://www.chainnodes.org/docs). - -### Client implementations - -As communicating over HTTP with POST requests directly can be quite difficult, especially if you want to properly -encode and decode responses and handle failures and exponential backoffs, there are client implementations that -can do the heavy lifting for you. These SDKs have developer friendly APIs and internally handle -creating the proper RPC requests, sending them to the endpoint you choose and decoding the response for you. - -Some of the major implementations are listed below: - -* [ethers.js](https://github.com/ethers-io/ethers.js) - Javascript/Typescript SDK for NodeJS and the Browser. Used throughout the t1 Docs. -* [wagmi](https://github.com/wagmi-dev/wagmi) and [viem](https://github.com/wagmi-dev/viem) - Javascript/Typescript, great duo for modern Web3 development in the Browser. -* [web3js](https://github.com/web3/web3.js) - Javascript/Typescript SDK for NodeJS and the Browser by ChainSafe. - -Web3 development is not limited to JS. Web3 libraries for various languages include: - -* [Web3.swift](https://github.com/Boilertalk/Web3.swift) - Swift SDK for iOS apps and Backends. -* [KEthereum](https://github.com/komputing/KEthereum) - Kotlin SDK for Android development. -* [ethers-rs](https://github.com/gakonst/ethers-rs) - Rust SDK. -* [ethclient](https://github.com/ethereum/go-ethereum/tree/master/ethclient) - Go SDK, part of geth, the reference Ethereum node implementation. - -At the moment, t1 only offers Typescript sdks. - -As you can see there are lots of SDKs to make it easier to communicate via RPC with the blockchain. - -### Local Development - -To simulate RPCs and transactions locally, you can check [this guide](./02-local-development). - -## Indexers - -As RPCs are only a slim abstraction of the data stored in the blockchain, there are certain things that are hard -or expensive to access with regular RPC requests. - -A common example are transactions of a specific Wallet address. Imagine you want to get a list of all transactions that originated from (or to) a -specific Wallet. One could think there should be an RPC method called `eth_getTransactionsForWallet` or something similar. -But due to the nature of how the data is stored, this RPC method is not feasible, and hence not implemented. - -Now, instead of accessing those kind of things by iterating through every block in the blockchain, you can use Indexers, that are -designed to index data like that on the go and provide easy access to it. - -### TheGraph - -A well-known, standardized implementation of indexers is [TheGraph](https://thegraph.com/). It is used by most major protocols, -including t1, to index data and make it accessible to users and dashboards. - -Using TheGraph, you can either access open [subgraphs](https://thegraph.com/explorer) via the GraphQL querying language, or [create your own](https://thegraph.com/docs/en/developing/creating-a-subgraph/) and deploy it. - -Throughout the docs you will see how to interact with the t1 subgraph to fetch tick data and more without ever touching RPCs. - -An important note about Indexers though: - -While they can be helpful, you need to be aware that the ultimate source of truth comes from the RPCs. As reorgs happen and -certain issues on indexers arise, there might be certain datapoints that are either not fully up-to-date or even -completely wrong on Indexers. If you have a use-case that requires perfectly correct data all the time, use RPCs directly. -If you are just doing data visualization or dashboards, use Indexers if they fit your use-case. - -Some popular subgraphs that you can try to fetch data from the blockchain easily (click on playground to give it a try): - -* [Uniswap Messari subgraph](https://thegraph.com/explorer/subgraphs/ELUcwgpm14LKPLrBRuVvPvNKHQ9HvwmtKgKSH6123cr7?view=Overview&chain=mainnet) -* [Snapshot Subgraph](https://thegraph.com/explorer/subgraphs/3Q4vnuSqemXnSNHoiLD7wdBbGCXszUYnUbTz191kDMNn?view=Overview&chain=mainnet) -* [Aave V3 Messari subgraph](https://thegraph.com/explorer/subgraphs/HB1Z2EAw4rtPRYVb2Nz8QGFLHCpym6ByBX6vbCViuE9F?view=Overview&chain=mainnet) - -## Smart Contract Development - -Smart contracts are typically developed using the [Solidity language](https://soliditylang.org/). - -There are VSCode plugins that make the development with Solidity easier. One of them is Juan Blanco's "Solidity" that you can find -over [here](https://marketplace.visualstudio.com/items?itemName=JuanBlanco.solidity). - -You would typically also go for a developer suite with testing, compilation and deployment capabilities: - -* [Foundry](https://github.com/foundry-rs/foundry) - Fast and modern developer tools for smart contract engineers. -* [Hardhat](https://github.com/NomicFoundation/hardhat) - Scriptable, easy and battle-tested JS developer suite for smart contracts. - -To read data from smart contracts, or interact with them, use the [client SDKs](#client-implementations) mentioned above. -They help you generate the necessary RPC calls to fetch data from / send transactions to the blockchain and interact with your -smart contracts. -You can read more about it in the [ethers.js docs](https://docs.ethers.org/v5/api/contract/contract/). - -## Blockchain Explorers - -Manually gathering information and inspecting data stored in a blockchain is a tedious task. -Almost all chains have at least one accompanying block explorer to help visualize addresses, transactions, contracts and more. - -For Ethereum mainnet, we suggest using [Etherscan](https://etherscan.io/). -You can use Etherscan to inspect [contracts](https://etherscan.io/address/0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45#code), transactions, blocks, and much more. - -If you are looking to debug a transaction, [Tenderly](https://dashboard.tenderly.co/tx/mainnet/0xa4affe1abfaf28d1763d6c3ccda33e717462a928abca89415fc6e661dd7e0c55) can also be a very helpful tool. -In this example of a failed transaction on the t1 V2 Router you can easily see why the execution failed and where. - -## The t1 development suite - -Uniswap offers several SDKs that work together and enable you to easily interact with the t1 protocol -The most important SDKs are: - -* [sdk-core](https://github.com/Uniswap/sdk-core): The core of the t1 SDKs, defines classes and types shared across all the SDKs -* [v2-sdk](https://github.com/Uniswap/v2-sdk): An SDK to interact with the t1 V2 protocol. -* [v3-sdk](https://github.com/Uniswap/v3-sdk): An SDK to interact with the t1 V3 protocol. -* [router-sdk](https://github.com/Uniswap/router-sdk): Provides abstractions to interact with the (older) SwapRouter contracts. -* [universal-router-sdk](https://github.com/Uniswap/universal-router-sdk): Abstracts interactions with the Universal Router. -* [smart-order-router](https://github.com/Uniswap/smart-order-router): Searches for the most efficient routes for a trade. -* [permit2-sdk](https://github.com/Uniswap/permit2-sdk): Simplifies interactions with Permit2 in JS. -* [uniswapx-sdk](https://github.com/Uniswap/uniswapx-sdk): SDK for the t1X protocol. - -As you know already, all interactions with the blockchain happens through RPCs. So the t1 SDKs, as you will see throughout the guides, -requires you to have access to an RPC endpoint like [Chainnodes](https://www.chainnodes.org). -When reading data, the data is read from the given RPC endpoint. When actually swapping, you will need to sign a transaction -using a private key. - -We are continuously working on improving the t1 development suite, so stay tuned for more updates. - -## Next Steps - -Go through the basic guides first and try to fetch some data and interact with the t1 ecosystem a little bit. You can even -[send your first swap transaction](./swaps/02-trading) on a local fork! - -While some concepts in Web3 require thinking outside of the box, this guide should give you a good overview on where to start. -You should now be fully equipped to follow our other guides. diff --git a/docs/sdk/v3/guides/_category_.json b/docs/sdk/v3/guides/_category_.json deleted file mode 100644 index c694eb5b2..000000000 --- a/docs/sdk/v3/guides/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "label": "Guides", - "position": 2, - "collapsed": false -} diff --git a/docs/sdk/v3/guides/advanced/01-introduction.md b/docs/sdk/v3/guides/advanced/01-introduction.md deleted file mode 100644 index ee84a5a70..000000000 --- a/docs/sdk/v3/guides/advanced/01-introduction.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -id: introduction -title: Introduction ---- - -For some more advanced use cases, it is necessary to use multiple tools in the t1 toolchain. - -:::info -If you need a briefer on the SDK and to learn more about how these guides connect to the examples repository, please visit our [background](../01-background.md) page! -::: - -The following examples use **ethersJS** and the **Uniswap V3 subgraph** hosted on The Graph's hosted service. To learn more about t1's subgraphs, visit the [API](../../../../api/subgraph/overview.md) section. - -We will take a deep dive into the t1 V3 protocol and use practical examples to understand the data stored by the t1 smart contracts. -We will explore how we can compute the available liquidity in a specific price range, visualize **liquidity density** in pools, use t1 as a **price oracle** and swap by creating **Range Orders**. - -These guides are a bit longer than the previous ones and provide more theoretical background. - -## Theoretical background - -Some of the guides presented here require a bit of theoretical and mathematical background. -To get the most out of the advanced guides, we encourage you to take a step back and read a bit about the math and theories behind the t1 protocol. - -The most complete source of information on the t1 protocol is the [Uniswap V3 book](https://uniswapv3book.com/). - -Besides the [concepts](../../../../concepts/uniswap-protocol.md) section of the Docs, the [Uniswap V3 whitepaper](https://uniswap.org/whitepaper-v3.pdf) is a great introduction to the protocol. -If you haven't checked it out yet, it is probably more concise and easier to understand than you would expect. - -### Datatypes in Solidity - -Uniswap V3 pools make use of a number of Datatypes Solidity offers to efficiently store their state. -If you are not familiar with Solidity data types yet, it can help to take a look at the [Solidity language reference](https://docs.soliditylang.org/en/v0.8.7/types.html#). -For the following guides, it is beneficial to take a look at two of them, which we will outline here. - -Ticks are stored as a [mapping(int24 => Tick.Info)](https://github.com/Uniswap/v3-core/blob/main/contracts/UniswapV3Pool.sol#L93). -Solidity [mappings](https://docs.soliditylang.org/en/v0.8.7/types.html#mapping-types) are very similar to hash maps, such that we can access any Value with their key with just one read operation. -The [`Tick.Info`](https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/Tick.sol#L17) stores the values of the Tick that we need to work with the Pool: - -```solidity -struct Info { - // the total position liquidity that references this tick - uint128 liquidityGross; - // amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left), - int128 liquidityNet; - // fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick) - // only has relative meaning, not absolute — the value depends on when the tick is initialized - uint256 feeGrowthOutside0X128; - uint256 feeGrowthOutside1X128; - // the cumulative tick value on the other side of the tick - int56 tickCumulativeOutside; - // the seconds per unit of liquidity on the _other_ side of this tick (relative to the current tick) - // only has relative meaning, not absolute — the value depends on when the tick is initialized - uint160 secondsPerLiquidityOutsideX128; - // the seconds spent on the other side of the tick (relative to the current tick) - // only has relative meaning, not absolute — the value depends on when the tick is initialized - uint32 secondsOutside; - // true iff the tick is initialized, i.e. the value is exactly equivalent to the expression liquidityGross != 0 - // these 8 bits are set to prevent fresh sstores when crossing newly initialized ticks - bool initialized; - } -``` - -We will use most of these values in the following guides. - -In our case, we can access any `Tick.Info` value stored in the pool by its `int24` key. -The key of the Tick is usually called its *index*. -Mappings are not iterable, so if we are trying to fetch all the Ticks stored in a Pool, we can't just iterate over the mapping. -Instead, we have to know the keys (indices) of the mapping, we will explore how to do that in the [Pool data guide](./02-pool-data.md). - -The second Solidity datatype we need to understand are normal unsigned [Integers](https://docs.soliditylang.org/en/v0.8.7/types.html#integers). -Solidity supports unsigned integer sizes between `uint8` and `uint256`, which are 8 and 256 bits long respectively. - -Let's take a look at the `tickBitmap` function of a V3 Pool: - -```solidity - function tickBitmap( - int16 wordPosition - ) external view returns (uint256) -``` - -Similar to the tick mapping, the tickBitmap is a mapping of type [mapping(int16 => uint256)](https://github.com/Uniswap/v3-core/blob/main/contracts/UniswapV3Pool.sol#L95). - -Let's look at the WETH/USDC pool with LOW fee on [Etherscan](https://etherscan.io/address/0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640#readContract). -If we call the `tickBitmap` function with the input `0` we get the following response (at the time of writing): - -TickBitmapEtherscan - -The `uint256` return value is interpreted as the representation of a decimal number by Etherscan. -The actual raw return value are 256 bits, that look something like this: - -```raw -0x0000 ... lots of zeros and ones ... 000000110000000000 -``` - -We interpret this string of zeros and ones not as the representation of a number, but rather as 256 booleans. - -If the value of a position in the value is 1, the Tick at this position is **initialized**, meaning it holds a value. - -With this trick, V3 Pools allow us to fetch the status of **256 ticks** with one call. -We will go into more details on how to calculate the tick indices from the tickBitmaps we fetch in the following guides. - -## History of t1 - -To get a better understanding of the V3 protocol, it can also be beneficial to understand the **history of decentralized exchanges** and the t1 protocol since it was founded in 2018. -You can read more about the older versions of t1 in the [V1](https://hackmd.io/@HaydenAdams/HJ9jLsfTz?type=view#Swaps-vs-Transfers) and [V2](https://uniswap.org/whitepaper.pdf) whitepapers, as well as the [V1](../../../../contracts/v1/overview.md) and [V2](../../../../contracts/v2/overview.md) section in the contract section. diff --git a/docs/sdk/v3/guides/advanced/02-pool-data.md b/docs/sdk/v3/guides/advanced/02-pool-data.md deleted file mode 100644 index 95d2deb26..000000000 --- a/docs/sdk/v3/guides/advanced/02-pool-data.md +++ /dev/null @@ -1,369 +0,0 @@ ---- -id: pool-data -title: Fetching Pool Data ---- - -## Introduction - -This guide will cover how to initialize a Pool with full tick data to allow offchain calculations. It is based on the [Fetching Pool data example](https://github.com/Uniswap/examples/tree/main/v3-sdk/pool-data), found in the t1 code examples [repository](https://github.com/Uniswap/examples). To run this example, check out the guide's [README](https://github.com/Uniswap/examples/blob/main/v3-sdk/pool-data/README.md) and follow the setup instructions. - -:::info -If you need a briefer on the SDK and to learn more about how these guides connect to the examples repository, please visit our [background](./01-background.md) page! -::: - -In this example we will use **ethers JS** and **ethers-multicall** to construct a `Pool` object that we can use in the following guides. - -This guide will **cover**: - -1. Computing the Pool's address -2. Referencing the Pool contract and fetching metadata -3. Fetching the positions of all initialized Ticks with multicall -4. Fetching all ticks by their indices with a multicall -5. Constructing the Pool object - -At the end of the guide, we will have created a `Pool` Object that accurately represents the state of a V3 pool at the time we fetched it. - -For this guide, the following t1 packages are used: - -- [`@uniswap/v3-sdk`](https://www.npmjs.com/package/@uniswap/v3-sdk) -- [`@uniswap/sdk-core`](https://www.npmjs.com/package/@uniswap/sdk-core) - -We will also use the `ethers-multicall` npm package: - -- [`ethers-multicall`](https://www.npmjs.com/package/ethers-multicall) - -The core code of this guide can be found in [`fetcher.ts`](https://github.com/Uniswap/examples/tree/main/v3-sdk/multicall/src/libs/fetcher.ts) - -## Configuration - -The example accompanying this guide can be configured in the [`config.ts`](https://github.com/Uniswap/examples/tree/main/v3-sdk/multicall/src/config.ts) file. -The default configuration defines the rpc endpoint and the pool that is used for this guide: - -```typescript -export const CurrentConfig: ExampleConfig = { - env: Environment.MAINNET, - rpc: { - local: 'http://localhost:8545', - mainnet: 'https://mainnet.infura.io/v3/0ac57a06f2994538829c14745750d721', - }, - ... - pool: { - token0: USDC_TOKEN, - token1: WETH_TOKEN, - fee: FeeAmount.MEDIUM, - }, -} -``` - -FeeAmount.MEDIUM means that the pool has a swap fee of **0.3%**. -The `USDC_TOKEN` and `WETH_TOKEN` are defined in the [`constants.ts`](https://github.com/Uniswap/examples/tree/main/v3-sdk/multicall/src/libs/constants.ts) file: - -```typescript -export const WETH_TOKEN = new Token( - SupportedChainId.MAINNET, - '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', - 18, - 'WETH', - 'Wrapped Ether' -) - -export const USDC_TOKEN = new Token( - SupportedChainId.MAINNET, - '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', - 6, - 'USDC', - 'USD//C' -) -``` - -## Computing the Pool's deployment address - -In this example, we will construct the **USDC - WETH** Pool with **MEDIUM** fees. The SDK provides a method to compute the address: - -```typescript -import { Pool } from '@uniswap/v3-sdk' -import { CurrentConfig } from '../config.ts' - -const poolAddress = Pool.getAddress( - CurrentConfig.pool.token0, - CurrentConfig.pool.token1, - CurrentConfig.pool.fee - ) -``` - -Uniswap V3 allows 4 different Fee tiers when deploying a pool, so multiple pools can exist for each pair of tokens. - -## Creating a Pool Contract instance and fetching metadata - -Now that we have the address of a **USDC - ETH** Pool, we can construct an instance of an **ethers** `Contract` to interact with it. -To construct the Contract we need to provide the address of the contract, its ABI and a provider connected to an [RPC endpoint](https://www.chainnodes.org/docs). We get access to the contract's ABI through the `@uniswap/v3-core` package, which holds the core smart contracts of the t1 V3 protocol: - -```typescript -import { ethers } from 'ethers -import IUniswapV3PoolABI from '@uniswap/v3-core/artifacts/contracts/interfaces/IUniswapV3Pool.sol/IUniswapV3Pool.json' - -const provider = getProvider() -const poolContract = new ethers.Contract( - poolAddress, - IUniswapV3PoolABI.abi, - provider -) -``` - -The `getProvider()` function returns an `ethers.providers.JsonRpcProvider` with either the local or mainnet rpc url that we defined, depending on the Environment that we set in `config.ts`. - -Once we have set up our reference to the contract, we can proceed to access its methods. To construct our offchain representation of the Pool Contract, we need to fetch its liquidity, sqrtPrice, currently active tick and the full Tick data. -We get the **liquidity**, **sqrtPrice** and **tick** directly from the blockchain by calling `liquidity()`and `slot0()` on the Pool contract: - -```typescript -const [liquidity, slot0] = - await Promise.all([ - poolContract.liquidity(), - poolContract.slot0(), - ]) -``` - -The [slot0 function](../../../../contracts/v3/reference/core/interfaces/pool/IUniswapV3PoolState.md#slot0) represents the first (0th) storage slot of the pool and exposes multiple useful values in a single function: - -```solidity - function slot0( - ) external view returns ( - uint160 sqrtPriceX96, - int24 tick, - uint16 observationIndex, - uint16 observationCardinality, - uint16 observationCardinalityNext, - uint8 feeProtocol, - bool unlocked - ) -``` - -For our use case, we only need the `sqrtPriceX96` and the currently active `tick`. - -## Fetching all Ticks - -V3 pools use ticks to [concentrate liquidity](../../../../concepts/protocol/concentrated-liquidity.md) in price ranges and allow for better pricing of trades. -Even though most Pools only have a couple of **initialized ticks**, it is possible that a pools liquidity is defined by thousands of **initialized ticks**. -In that case, it can be very expensive or slow to get all of them with normal RPC calls. - -If you are not familiar with the concept of ticks, check out the [`introduction`](./01-introduction.md). - -To access tick data, we will use the `ticks` function of the V3 Pool contract: - -```solidity - function ticks( - int24 tick - ) external view returns ( - uint128 liquidityGross, - int128 liquidityNet, - uint256 feeGrowthOutside0X128, - uint256 feeGrowthOutside1X128, - int56 tickCumulativeOutside, - uint160 secondsPerLiquidityOutsideX128, - uint32 secondsOutside, - bool initialized - ) -``` - -The `tick` parameter that we provide the function with is the **index** (memory position) of the Tick we are trying to fetch. -To get the indices of all initialized Ticks of the Pool, we can calculate them from the **tickBitmaps**. -To fetch a `tickBitmap` function of the V3 Pool: - -```solidity - function tickBitmap( - int16 wordPosition - ) external view returns (uint256) -``` - -A pool stores lots of bitmaps, each of which contain the status of 256 Ticks. -The parameter `int16 wordPosition` the function accepts is the position of the bitMap we want to fetch. -We can calculate all the position of bitMaps (or words as they are sometimes called) from the `tickSpacing` of the Pool, which is in turn dependant on the Fee tier. - -So to summarise we need 4 steps to fetch all initialized ticks: - -1. Calculate all bitMap positions from the tickSpacing of the Pool. -2. Fetch all bitMaps using their positions. -3. Calculate the memory positions of all Ticks from the bitMaps. -4. Fetch all Ticks by their memory position. - -We will use multicalls for the fetch calls. - -## Multicall - -Multicall contracts **aggregate results** from multiple contract calls and therefore allow sending multiple contract calls in **one RPC request**. -This can improve the **speed** of fetching large amounts of data significantly and ensures that the data fetched is all from the **same block**. - -We will use the Multicall2 contract by MakerDAO. -We use the `ethers-muticall` npm package to easily interact with the Contract. - -## Calculating all bitMap positions - -As mentioned, t1 V3 Pools store **bitmaps**, also called *words*, that represent the state of **256 initializable ticks** at a time. -The value at a bit of a word is 1 if the tick at this index is initialized and 0 if it isn't. -We can calculate the positions of initialized ticks from the **words** of the Pool. - -All ticks of t1 V3 pools are between the indices `-887272` and `887272`. -We can calculate the minimum and maximum word from these indices and the Pool's tickSpacing: - -```typescript -function tickToWord(tick: number): number { - let compressed = Math.floor(tick / tickSpacing) - if (tick < 0 && tick % tickSpacing !== 0) { - compressed -= 1 - } - return tick >> 8 -} - -const minWord = tickToWord(-887272) -const maxWord = tickToWord(887272) -``` - -Ticks can only be initialized at indices that are **divisible by the tickSpacing**. -One word contains 256 ticks, so we can compress the ticks by right shifting 8 bit. - -## Fetching bitMaps from their position - -Knowing the positions of words in the Pool contract, we can now fetch them from the Pool using multicall and the `tickBitmap` read call. - -First we initialize our multicall providers and Pool Contract: - -```typescript -import { ethers } from 'ethers' -import { Contract, Provider } from 'ethers-multicall' - -const ethersProvider = new ethers.providers.JsonRpcProvider("...rpcUrl") -const multicallProvider = new Provider(ethersProvider) -await multicallProvider.init() - -const poolContract = new Contract(poolAddress, IUniswapV3PoolABI.abi) -``` - -The `multicallProvider` creates the multicall request and sends it via the ethers Provider. - -Next we loop through all possible word positions and add a `tickBitmap` call for each: - -```typescript -let calls: any[] = [] -let wordPosIndices: number[] = [] -for (let i = minWord; i <= maxWord; i++) { - wordPosIndices.push(i) - calls.push(poolContract.tickBitmap(i)) -} -``` - -We also keep track of the word position indices to be able to loop through them in the same order we added the calls to the array. - -We use the `multicallProvider.all()` function to send a multicall and map the results: - -```typescript -const results: bigint[] = (await multicallProvider.all(calls)).map( - (ethersResponse) => { - return BigInt(ethersResponse.toString()) - } - ) -``` - -A great visualization of what the bitMaps look like can be found in the [Uniswap V3 development book](https://uniswapv3book.com/docs/milestone_2/tick-bitmap-index/): - -TickBitmap - -We encourage anyone trying to get a deeper understanding of the t1 protocol to read the t1 V3 Book. - -## Calculating the memory positions of all Ticks - -Now that we fetched all **bitMaps**, we check which ticks are initialized and calculate the **tick position** from the **word index** and the **tickSpacing** of the pool. - -We check if a tick is **initialized** inside the word by shifting a bit by the index we are looking at and performing a bitwise AND operation: - -```typescript -const bit = 1n -const initialized = (bitmap & (bit << BigInt(i))) !== 0n -``` - -If the tick is **initialized**, we revert the compression from tick to word we made earlier by multiplying the word index with 256, which is the same as left shifting by 8 bit, adding the position we are currently at, and multiplying with the tickSpacing: - -```typescript -const tickIndex = (ind * 256 + i) * tickSpacing -``` - -The whole loop looks like this: - -```typescript -const tickIndices: number[] = [] - - for (let j = 0; j < wordPosIndices.length; j++) { - const ind = wordPosIndices[j] - const bitmap = results[j] - - if (bitmap !== 0n) { - for (let i = 0; i < 256; i++) { - const bit = 1n - const initialized = (bitmap & (bit << BigInt(i))) !== 0n - if (initialized) { - const tickIndex = (ind * 256 + i) * tickSpacing - tickIndices.push(tickIndex) - } - } - } - } -``` - -We now have an array containing the indices of all initialized Ticks. - -## Fetching all Ticks by their indices - -We use the multicallProvider again to execute an aggregated read call for all tick indices. -We create an array of call Promises again and use `.all()` to make our multicall: - -```typescript -const calls: any[] = [] - -for (const index of tickIndices) { - calls.push(poolContract.ticks(index)) -} - -const results = await multicallProvider.all(calls) -``` - -Again, the order of the results array is the same as the elements in **tickIndices**. - -We are able to combine the **tickIndices** and **results** array to create an array of `Tick` objects: - -```typescript -const allTicks: Tick[] = [] - - for (let i = 0; i < tickIndices.length; i++) { - const index = tickIndices[i] - const ethersResponse = results[i] - const tick = new Tick({ - index, - liquidityGross: JSBI.BigInt(ethersResponse.liquidityGross.toString()), - liquidityNet: JSBI.BigInt(ethersResponse.liquidityNet.toString()), - }) - allTicks.push(tick) - } -``` - -We need to parse the response from our RPC provider to JSBI values that the v3-sdk can work with. - -## Constructing the Pool - -We have everything to construct our `Pool` now: - -```typescript -const usdcWethPool = new Pool( - USDC, - WETH, - feeAmount, - slot0.sqrtPriceX96, - liquidity, - slot0.tick, - allTicks -) -``` - -With this fully initialized Pool, we can make accurate offchain calculations. - -## Next Steps - -Now that you are familiar with fetching Pool data, continue your journey with the [next example](./03-active-liquidity.md) on visualizing the Liquidity density of a pool. diff --git a/docs/sdk/v3/guides/advanced/03-active-liquidity.md b/docs/sdk/v3/guides/advanced/03-active-liquidity.md deleted file mode 100644 index 089431288..000000000 --- a/docs/sdk/v3/guides/advanced/03-active-liquidity.md +++ /dev/null @@ -1,307 +0,0 @@ ---- -id: active-liquidity -title: Active Liquidity ---- - -## Introduction - -This guide will cover how to fetch and compute the active liquidity in the specific Tick ranges of a pool. It is based on the [Liquidity Density example](https://github.com/Uniswap/examples/tree/main/v3-sdk/liquidity-density) and can be seen used in production, albeit in a more sophisticated way, in the [Uniswap Analytics](https://info.uniswap.org/#/pools) website. - -:::info -If you need a briefer on the SDK and to learn more about how these guides connect to the examples repository, please visit our [background](./01-background.md) page! -::: - -In this guide, we will use the V3 subgraph to fetch all ticks from **theGraph** and compute the active liquidity our Pool can use at each Tick. We then use `recharts` to draw a chart that visualizes our Pool's liqudity density. - -This guide will cover: - -1. Getting the tickSpacing and currently active Tick from the Pool -2. Calculating active liquidity from net liquidity -3. Drawing a chart from the Tick data - -This guide will not cover: - -- Specifics of working with the recharts library. You can read more about that [here](https://recharts.org/en-US/). - -At the end of the guide, we should be able to visualize the liquidity of any V3 Pool. - -## Understanding Active Liquidity - -To visualize the distribution of active liquidity in our Pool, we want to draw our Chart around the currently active Tick. For that we have to first understand: - -- What is an initialized Tick? -- What is the current Tick? - -### Initialized Ticks - -When providing liquidity for a pool, the LP decides the **price range** in which the liquidity should be provided, and the amount of liquidity to be provided. -The pool understands the position as **liquidity between the lower and upper Tick**. The Tick Index in this context is a representation of the price between the Pool's assets. - -Looking at this [visualization](https://www.desmos.com/calculator/oduetjzfp4) of multiple positions in a V3 Pool, we can see that the liquidity available for a swap does not change inside a position, but when crossing into the next position. -This is what the **Initialized Ticks** of a Pool represent - they are a representation of the start or end of one or more positions. - -LiquidityNet1 - -When entering or leaving a position, its liquidity is added or removed from the **active liquidity available** for a Swap. -The initialized Ticks store this **change in available liquidity** in the `liquidityNet` field. -The change is always stored in relation to the currently active Tick - the current price. -When the price crosses an initialized Tick, it gets updated and liqudity that was previously added when crossing the Tick would now be removed and vice versa. - -The `liquidityGross` value represents the gross value of liquidity referencing the tick. -This is important for the edge case that one position ends at a Tick and a second position with exactly the same liquidity value would start at the Tick. -In this case `liquidityNet` would be **0** but `liquidityGross` would still have a value, which ensures that the Tick is not deleted from the Pool. - -To visualize liquidity in a graph, we will only need to consider the changes, so it's sufficient to fetch the Ticks with `liquidityNet` not 0. - -### Fetching initialized Ticks - -To fetch all ticks of our Pool, we will use the [Uniswap V3 graph](../../../../api/subgraph/overview.md). -To visualize active liquidity, we need the **tickIdx**, the **liquidityGross** and the **liquidityNet**. - -We define our GraphQL query and [send a POST request](https://axios-http.com/docs/post_example) to the V3 subgraph API endpoint: - -```typescript -axios.post( - "https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v3", - {"query": `{ ticks( - where: {poolAddress: "${poolAddress.toLowerCase()}", liquidityNet_not: "0"} - first: 1000, - skip: ${skip}, - orderBy: tickIdx, - orderDirection: asc - ) { - tickIdx - liquidityGross - liquidityNet - } - }` - }, - { - headers: { - "Content-Type": "application/json" - } - } - ) -``` - -We only fetch the ticks that **have liquidity**, and we convert the poolAddress to **lower case** for the subgraph to work with. To make sure the Ticks are ordered correctly, we also define the **order direction** in the query. - -:::note -GraphQL is only able to fetch 1000 records at a time. If a pool has more than 1000 initialized ticks, multiple calls are necessary to get all of them. -::: - -The ticks we got from **theGraph** have this format: - -```typescript -interface GraphTick { - tickIdx: string - liquidityGross: string - liquidityNet: string -} -``` - -### Current Tick - -The current Tick of the Pool represents the **current Price** after the last swap. -Considering that the initialized Ticks only represent positions, we see that it is not necessarily one of the initialized Ticks but can be at any point in between them. -The active liqudity at the current Price is also stored in the smart contract - we already fetched it with the `liquidity` function in the [previous guide](./02-pool-data.md). - -### Tickspacing - -Only the Ticks with indices that are divisible with 0 remainder by the tickspacing of a Pool are initializable. -This is a convention defined by the protocol to save gas. -The Tickspacing of the Pool is dependent on the Fee Tier. -Pools with lower fees are meant to be used for more stable Token Pairs and allow for more granularity in where LPs position their liquidity. - -We can get the `tickSpacing` from the `TICK_SPACINGS` enum exposed by the `v3-sdk`: - -```typescript -import { TICK_SPACINGS } - -const tickSpacing = TICK_SPACINGS[fee] -``` - -Alternatively, if we have already constructed a `Pool` object, we could just call `Pool.tickSpacing()`. - -### Putting it all together - -For the purpose of visualizing the liquidity density of the Pool, it rarely makes sense to display the full Tick Range of the Pool, as the vast majority of liquidity will be focused in a narrow price range. - -Instead, we will display a sensible number of Ticks around the current price. - -## Calculating active liquidity - -We know the spacing between Ticks and the Initialized Ticks where active liquidity changes. -All we have to do is start calculating from the current Tick and iterate outwards. - -The code mentioned in the following snippets can be found in [`active-liquidity.ts`](https://github.com/Uniswap/examples/tree/main/v3-sdk/pool-data/src/libs/active-liquidity.ts). - -To draw our chart we want a data structure that looks something like this: - -```typescript -interface TickProcessed { - tickIdx: number, - liquidityActive: JSBI, - liquidityNet: JSBI, - price0: string, - price1: string, - isCurrent: boolean -} -``` - -To access the initialized Ticks directly from their Tick Index, we store them in a [Record](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type): - -```typescript -const tickIdxToTickDictionary: Record = Object.fromEntries( - ticks.map((graphTick) => [graphTick.tickIdx, graphTick]) - ) -``` - -The `ticks` variable in this code snippet is the result we got from the V3 Subgraph earlier. - -We want to mark the Tick closest to the current Price and we want to be able to display the prices at a Tick to the user. -We calculate the **initializable Tick** closest to the current price and create the active Tick that we start from: - -```typescript -import { tickToPrice } from '@uniswap/v3-sdk' - -const activeTickIdx = Math.floor(pool.tickCurrent / tickSpacing) * tickSpacing - -const activeTickProcessed: TickProcessed = { - tickIdx: activeTickIdx, - liquidityActive: pool.liquidity, - liquidityNet: JSBI.BigInt(0), - price0: tickToPrice(tokenA, tokenB, activeTickIdx).toFixed(6), - price1: tickToPrice(tokenB, tokenA, activeTickIdx).toFixed(6), - isCurrent: true -} -``` - -Here we also calculate the price of the tokens from the tickIdx, the `v3-sdk` exports a handy utility function for that, `tickToPrice`. -We store the Price as a string as we won't make any further calculations in this example. We will instead use it to display prices in the tooltip of our chart. -Notice how the `price0` is the Price of tokenA in terms of tokenB and the `price1` is the Price of tokenB in terms of tokenA **at the specified Tick**. - -If the **current Tick is initialized**, we also need to set the **liquidityNet** to correctly handle moving out of the position: - -```typescript -const currentTickInitialized = tickIdxToTickDictionary[activeTickIdx] -if (currentTickInitialized !== undefined) { - activeTickProcessed.liquidityNet = JSBI.BigInt(currentTickInitialized.liquidityNet) -} -``` - -We now start iterating outwards from the active Tick and compute the active liquidity for each Tick we want to display. The processed Tick is then saved in an Array of `TickProcessed`. -We choose an arbitrary number of Ticks we want to display, for this example we calculate 100 Ticks in each direction. - -```typescript -import { TickMath, tickToPrice } from '@uniswap/v3-sdk' - -let previousTickProcessed = { - ...activeTickProcessed -} - -processedTicks: TickProcessed[] = [] - -for (let i = 0; i < 100; i++) { - const currentTickIdx = previousTickProcessed.tickIdx + tickSpacing - - if (currentTickIdx > TickMath.MAX_TICK) { - break - } - - const currentTickProcessed = { - liquidityActive: previousTickProcessed.liquidityActive, - tickIdx: currentTickIdx, - liquidityNet: JSBI.BigInt(0), - price0: tickToPrice(token0, token1, currentTickIdx), - price1: tickToPrice(token1, token0, currentTickIdx), - isActive: false - } - - ... -} -``` - -We calculate one Tick at a time, and we need to make sure our Tick stays inside the possible price range by checking against `TickMath.MAX_TICK`. -Again, we check if our current Tick is initialized and if so, recalculate the active liquidity: - -```typescript -for (let i = 0; i < 100; i++) { - - ... - - const currentTickInitialized = tickIdxToTickDictionary[currentTickIdx] - - if (currentTickInitialized !== undefined) { - currentTickProcessed.liquidityNet = JSBI.BigInt(currentTickInitialized.liquidityNet) - currentTickProcessed.liquidityActive = JSBI.add( - previousTickProcessed.liquidityActive, - JSBI.BigInt(currentTickInitialized.liquidityNet) - ) - } - - processedTicks.push(currentTickProcessed) - previousTickProcessed = currentTickProcessed -} -``` - -After we are done calculating the next 100 Ticks after the current Tick, we iterate in the opposite direction for the previous Ticks. Iterating downwards, we need to subtract the net liquidity where we added it when iterating upwards. -You can find a full code example in the [Uniswap Example repository](https://github.com/Uniswap/examples/tree/main/v3-sdk/active-liquidity). - -We are finally able to combine the previous, active and subsequent Ticks: - -```typescript -const allProcessedTicks = previousTicks.concat(activeTickProcessed).concat(subsequentTicks) -``` - -## Drawing the Chart - -We are done with our calculations and move on to displaying the data. **Recharts** is not able to handle JSBI, so we need to convert the Array we created to a format it can handle: - -```typescript -const chartTicks: TicksChart[] = allProcessedTicks.map((tickProcessed) => { - return {...processedTick, liquidityActiveChart: parseFloat(tickProcessed.liquidityActive.toString())} -}) -``` - -The loss of precision will not be visually noticeable in the chart and we are still able to display the exact number in a Tooltip if we wish to. -Liquidity is stored in a `uint128` format onchain, so the maximum loss of precision will be far smaller than the number of decimals of almost any ERC20 Token. - -Finally, we draw the Chart: - -```jsx - - - - - - {chartTicks.map((entry, index) => { - return ( - - ) - })} - - - -``` - -In a real application, you will probably want to format the chart properly and display additional information for users. -Check out the full [code example](https://github.com/Uniswap/examples/tree/main/v3-sdk/active-liquidity) to this guide and the official recharts [documentation](https://recharts.org/). - -You can also take a look at the [Uniswap Info](https://github.com/Uniswap/v3-info) repository to see a similar chart used in production. - -## Locked Liquidity - -If you run the example, you will notice that the chart also displays a custom tooltip with additional information that we didn't touch on in this example. -The total locked liqudity in the tooltip represents the sum of positions in the currency locked at the selected Tick. -It is calculated as the maximum token output of a swap when crossing to the next Tick. -The V3 pool here is initialized with only the liquidity of the current Tick. - -Depending on your use case, it may make sense to display this value. You can find the full code in the [code example](https://github.com/Uniswap/examples/tree/main/v3-sdk/active-liquidity). - -## Next Steps - -Now that you are familiar with liquidity data, consider checking out our [next guide](./04-price-oracle.md) on using t1 as a Price Oracle. diff --git a/docs/sdk/v3/guides/advanced/04-price-oracle.md b/docs/sdk/v3/guides/advanced/04-price-oracle.md deleted file mode 100644 index 8471e1997..000000000 --- a/docs/sdk/v3/guides/advanced/04-price-oracle.md +++ /dev/null @@ -1,287 +0,0 @@ ---- -id: price-oracle -title: t1 as a Price Oracle ---- - -## Introduction - -This guide will cover how to fetch price observations from a V3 pool to get onchain asset prices. -It is based on the [Price Oracle example](https://github.com/Uniswap/examples/tree/main/v3-sdk/oracle), found in the t1 code examples [repository](https://github.com/Uniswap/example). -To run this example, check out the guide's [README](https://github.com/Uniswap/examples/blob/main/v3-sdk/oracle/README.md) and follow the setup instructions. - -:::info -If you need a briefer on the SDK and to learn more about how these guides connect to the examples repository, please visit our [background](./01-background.md) page! -::: - -In this example we will use **ethers JS** to observe the development of a Pool's current tick over several blocks. -We will then calculate the time weighted average price - **TWAP**, and time weighted average liquidity - **TWAL** over the observed time interval. - -This guide will **cover**: - -1. Understanding observations -2. Fetching observations -3. Computing TWAP -4. Computing TWAL -5. Why prefer observe over observations - -Before diving into this guide, consider reading the theory behind using t1 V3 as an [Onchain Oracle](../../../../concepts/protocol/oracle.md). - -For this guide, the following t1 packages are used: - -- [`@uniswap/v3-sdk`](https://www.npmjs.com/package/@uniswap/v3-sdk) - -The core code of this guide can be found in [`oracle.ts`](https://github.com/Uniswap/examples/tree/main/v3-sdk/oracle/src/libs/oracle.ts) - -## Understanding Observations - -First, we need to create a Pool contract to fetch data from the blockchain. Check out the [Pool data guide](./02-pool-data.md) to learn how to compute the address and create an **ethers Contract** to interact with. - -```typescript -const poolContract = new ethers.Contract( - poolAddress, - IUniswapV3PoolABI.abi, - provider -) -``` - -All V3 pools store observations of the current tick and the block timestamp. -To minimize pool deployment costs, only one Observation is stored in the contract when the Pool is created. -Anyone who is willing to pay the gas costs can [increase](../../../../contracts/v3/reference/core/UniswapV3Pool.md#increaseobservationcardinalitynext) the number of stored observations to up to `65535`. -If the Pool cannot store an additional Observation, it overwrites the oldest one. - -We create an interface to map our data to: - -```typescript -interface Observation { - secondsAgo: number - tickCumulative: bigint - secondsPerLiquidityCumulativeX128: bigint -} -``` - -To fetch the `Observations` from our pool contract, we will use the [`observe`](../../../../contracts/v3/reference/core/UniswapV3Pool.md#observe) function: - -```solidity -function observe( - uint32[] secondsAgos -) external view override noDelegateCall returns ( - int56[] tickCumulatives, - uint160[] secondsPerLiquidityCumulativeX128s -) -``` - -We first check how many observations are stored in the Pool by calling the `slot0` function. - -```typescript -const slot0 = await poolContract.slot0() - -const observationCount = slot0.observationCardinality -const maxObservationCount = slot0.observationCardinalityNext -``` - -The `observationCardinalityNext` is the maximum number of Observations the Pool **can store** at the moment. -The `observationCardinality` is the actual number of Observations the Pool **has currently stored**. - -Observations are only stored when the `swap()` function is called on the Pool or when a **Position is modified**, so it can take some time to write the Observations after the `observationCardinalityNext` was increased. -If the number of Observations on the Pool is not sufficient, we need to call the `increaseObservationCardinalityNext()` function and set it to the value we desire. - -This is a write function as the contract needs to store more data on the blockchain. -We will need a **wallet** or **signer** to pay the corresponding gas fee. - -In this example, we want to fetch 10 observations. - -```typescript -import { ethers } from 'ethers' - -let provider = new ethers.providers.WebSocketProvider('rpcUrl...') -let wallet = new ethers.Wallet('private_key', provider) - -const poolContract = new ethers.Contract( - poolAddress, - IUniswapV3PoolABI.abi, - wallet -) - -const txRes = await poolContract.increaseObservationCardinalityNext(10) -``` - -The Pool will now fill the open Observation Slots. -As someone has to pay for the gas to write the observations, writing to the array of observations is part of the `swap()` and the `modifyPosition()` function of the Pool. - -:::note -Saving an Observation is a write operation on the blockchain and therefore costs gas. -This means that the pool will only be able to save observations for blocks where write calls are executed on the Pool contract. -If no Observation is stored for a block, it is calculated as the time weighted arithmetic mean between the two closest Observations. -Because of this, we can be sure the oldest Observation is **at least** 10 blocks old. -It is very likely that the number of blocks covered is bigger than 10. -::: - -## Fetching Observations - -We are now sure that at least 10 observations exist, and can safely fetch observations for the last 10 blocks. -We call the `observe` function with an array of numbers, representing the timestamps of the Observations in seconds ago from now. - -In this example, we calculate averages over the last ten blocks so we fetch 2 observations with 9 times the blocktime in between. -Fetching an Observation `0s` ago will return the **most recent Observation** interpolated to the current timestamp as observations are written at most once a block. - -```typescript -const timestamps = [ - 0, 108 -] - -const [tickCumulatives, secondsPerLiquidityCumulatives] = await poolContract.observe(timestamps) - -const observations: Observation[] = timestamps.map((time, i) => { - return { - secondsAgo: time - tickCumulative: BigInt(tickCumulatives[i]) - secondsPerLiquidityCumulativeX128: BigInt(secondsPerLiquidityCumulatives[i]) - } -}) -``` - -We map the response from the RPC provider to match our Observations interface. - -## Calculating the average Price - -To calculate the time weighted average price (TWAP) in the period we fetched, we first need to understand what the values we fetched mean. - -The `tickCumulative` value is a snapshot of the `tick accumulator` at the timestamp we fetched. The Tick Accumulator stores the sum of all current ticks at every second since the Pool was initialised. Its value is therefore increasing with every second. - -We cannot directly use the value of a single Observation for anything meaningful. Instead we need to compare the **difference** between two Observations and calculate the **time weighted arithmetic mean**. - -```typescript -const diffTickCumulative = observations[0].tickCumulative - observations[1].tickCumulative -const secondsBetween = 108 - -const averageTick = diffTickCumulative / secondsBetween -``` - -Now that we know the average active Tick over the last 10 blocks, we can calculate the price with the `tickToPrice` function, which returns a [`Price`](../../../core/reference/classes/Price.md) Object. Check out the [Pool data](./02-pool-data.md) guide to understand how to construct a Pool Object and access its properties. We don't need the full Tick Data for this guide. - -```typescript -import { tickToPrice, Pool } from '@uniswap/v3-sdk' - -const pool = new Pool(...) - -const TWAP = tickToPrice(pool.token0, pool.token1, averageTick) -``` - -We have now calculated the **time weighted average price** over the last 108 seconds. - -Let's continue with the average liquidity. - -## Calculating the average Liquidity - -To understand the term **active Liquidity**, check out the [previous guide](./03-active-liquidity.md). -Similar to the `tick accumulator`, the `liquidity accumulator` stores a sum of values for every second since the Pool was initialized and increases with every second. -Because of the size of the active liquidity value, it is impractical to just add up the active liquidity. Instead the **seconds per liquidity** are summed up. - -The `secondsPerLiquidityX128` value is calculated by shifting the seconds since the last Observation by 128 bits and dividing that value by the active liquidity. It is then added to the accumulator. - -```solidity -uint32 delta = blockTimestamp - last.blockTimestamp; - -uint128 secondsPerLiquidityX128 = (uint160(delta) << 128) / liquidity -uint160 secondsPerLiquidityCumulativeX128 = last.secondsPerLiquidityCumulativeX128 + secondsPerLiquidityX128 -``` - -`last` is the most recent Observation in this illustrative code snippet. Consider taking a look at the [Solidity Oracle library](https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/Oracle.sol) to see the actual implementation. - -Let's invert this calculation and find the average active liquidity over our observed time period. - -```typescript -const diffSecondsPerLiquidityX128 = observations[0].secondsPerLiquidityCumulativeX128 - - observations[1].secondsPerLiquidityCumulativeX128 -const secondsBetweenX128 = BigInt(108) << 128 - -const TWAL = secondsBetweenX128 / diffSecondsPerLiquidityX128 -``` - -This **time weighted average liquidity** is the harmonic mean over the time period observed. - -:::note -The costs associated with manipulating/ changing the liquidity of a Pool are **orders of magnitude smaller** than with manipulating the price of the assets, as **prices** will be arbitraged for assets **with more than one market**. -Adding massive amounts of liquidity to a Pool and withdrawing them after a block has passed more or less only costs gas fees. - -Use the **TWAP** with care and consider handling outliers. -::: - -## Why prefer observe over observations? - -As touched on previously, the `observe` function calculates Observations for the timestamps requested from the nearest observations stored in the Pool. -It is also possible to directly fetch the stored observations by calling the `observations` function with the index of the Observation that we are interested in. - -Let's fetch all observations stored in our Pool. We already made sure the observationCardinality is 10. -The solidity struct `Observation` looks like this: - -```solidity -struct Observation { - // the block timestamp of the observation - uint32 blockTimestamp; - // the tick accumulator, i.e. tick * time elapsed since the pool was first initialized - int56 tickCumulative; - // the seconds per liquidity, i.e. seconds elapsed / max(1, liquidity) since the pool was first initialized - uint160 secondsPerLiquidityCumulativeX128; - // whether or not the observation is initialized - bool initialized; -} -``` - -It is possible to request any Observation up to (excluding) index `65535`, but indices equal to or greater than the `observationCardinality` will return uninitialized Observations. - -The full code to the following code snippets can be found in [`oracle.ts`](https://github.com/uniswap/examples/blob/main/v3-sdk/oracle/src/libs/oracle.ts) - -```typescript -let requests = [] -for (let i = 0; i < 10; i++) { - requests.push(poolContract.observations(i)) -} - -const results = await Promise.all(requests) -``` - -We can only request one Observation at a time, so we create an Array of Promises to get an Array of Observations. - -We already see one difference, to using the `observe` function here. -While `observe` creates an array onchain in the smart contract and returns it, calling `observations` requires us to make multiple RPC calls. - -:::note -Depending on our setup and the Node we are using, either option can be faster, but making multiple RPC calls always has the danger of the blockchain state changing between our calls. -While it is extremely unlikely, it is still possible that our Node updates with a new block and new Observation in between our calls. -Because we access indices of an array, this would give us an unexpected result that we need to handle as an edge case in our implementation. -::: - -One way to handle this behaviour is deploying or [using](https://github.com/mds1/multicall) a Contract with a [multicall](https://solidity-by-example.org/app/multi-call/) functionality to get all observations with one request. -You can also find an example of a JS multicall in the [Pool data guide](./02-pool-data.md). - -We map the RPC result to the Typescript interface that we created: - -```typescript -const utcNow = Math.floor(Date.now() / 1000) -const observations = results.map((result) => { - const secondsAgo = utcNow - Number(result.blockTimeStamp) - return { - secondsAgo, - tickCumulative: BigInt(result.tickCumulative), - secondsPerLiquidityCumulativeX128: BigInt(result.secondsPerLiquidityCumulativeX128) - } -}).sort((a, b) => a.secondsAgo - b.secondsAgo) -``` - -We now have an Array of observations in the same format that we are used to. - -:::note -Because Observations are stored in a **fixed size array** with always the oldest Observation overwritten if a new one is stored, they are **not sorted**. -We need to sort the result by the timestamp. -::: - -The timestamps of the Observations we got are correspondent to blocks where **Swaps or Position changes** happened on the Pool. -Because of this, we would need to calculate Observations for specific intervals manually from the **surrounding Observations**. - -In conclusion, it is much harder to work with `observations` than with `observe`, and we need to consider multiple edge cases. -For this reason, it is recommended to use the `observe` function. - -## Next Steps - -Now that you are familiar with the Oracle feature of t1, consider checking out the [next guide](./05-range-orders.md) on **Range Orders**. diff --git a/docs/sdk/v3/guides/advanced/05-range-orders.md b/docs/sdk/v3/guides/advanced/05-range-orders.md deleted file mode 100644 index 1beaea832..000000000 --- a/docs/sdk/v3/guides/advanced/05-range-orders.md +++ /dev/null @@ -1,430 +0,0 @@ ---- -id: range-orders -title: Range Orders ---- - -## Introduction - -This guide will cover how single-side liquidity provisioning can be used to execute **Limit Orders** on t1 V3 Pools. -An example to showcase this concept can be found in the [Range Order example](https://github.com/Uniswap/examples/tree/main/v3-sdk/range-order), in the t1 code examples [repository](https://github.com/Uniswap/example). -To run this example, check out the guide's [README](https://github.com/Uniswap/examples/blob/main/v3-sdk/price-oracle/README.md) and follow the setup instructions. - -:::info -This guide builds on top of the [Pooling Liquidity guides](../liquidity/01-position-data.md). -We recommend going through this section of the docs before imnplementing Range Orders. -::: - -In this example we will create a single-side liquidity position with the [NonfungiblePositionManager](../../../../contracts/v3/reference/periphery/NonfungiblePositionManager.md) contract. -We will then use **ethers JS** to observe the price of the Pool on new blocks and withdraw the liquidity when our target is reached. - -This guide will **cover**: - -1. Understanding Range Orders -2. Calculating our Tick Range -3. Creating a single-side liquidity position -4. Observing the price of the Pool -5. Closing the Limit Order - -Before working through this guide, consider checking out the Range Orders [concept page](../../../../concepts/protocol/range-orders.md) to understand how Limit orders can be executed with t1 V3. - -For this guide, the following t1 packages are used: - -- [`@uniswap/v3-sdk`](https://www.npmjs.com/package/@uniswap/v3-sdk) -- [`@uniswap/sdk-core`](https://www.npmjs.com/package/@uniswap/sdk-core) - -The core code of this guide can be found in [`range-order.ts`](https://github.com/Uniswap/examples/tree/main/v3-sdk/range-order/src/libs/range-order.ts). - -## Understanding Range Orders - -If you have read the [Range Order Concept page](../../../../concepts/protocol/range-orders.md), you can skip this section. - -Positions on a V3 Pool are always created with a Tick range in which their liquidity is accessible to swaps on the Pool. -Lets look at the return value of the NonfungiblePositionManager contract when calling the `positions` function with a Position `tokenId`. - -```solidity -function positions( - uint256 tokenId - ) external view returns ( - uint96 nonce, - address operator, - address token0, - address token1, - uint24 fee, - int24 tickLower, // Lower Boundary of Position - int24 tickUpper, // Upper Boundary of Position - uint128 liquidity, // Liquidity - uint256 feeGrowthInside0LastX128, - uint256 feeGrowthInside1LastX128, - uint128 tokensOwed0, - uint128 tokensOwed1 - ) -``` - -We see that a position only stores a single `liquidity` value, and a `tickLower` and `tickUpper` value that define the range in which the liquidity of the Position can be utilised for Swaps. -The actual **amount** of `token0` and `token1` that a Pool owes the Position owner is calculated from the parts of the liquidity position that are to the left and right of the current Tick. -Liquidity left of the current Tick is denominated in `token0` and liquidity right of the current Tick is denominated in `token1`. - -If a new Position is created and the Tick Range of the position does not include the current Tick of the Pool, only one of the two Tokens in the Pool can be provided. - -We will call this a **Single Side Liquidity Position**. - -RangeOrder - -When the current Tick of the Pool moves across the Position, the ratio of `token0` and `token1` will change, and ultimately inverse if the current Tick moves out of the position on the other side. - -We will utilise this behaviour to provide liquidity with `token1` and withdraw the position when it has been converted to `token0`. - -## Calculating the Tick Range - -Our goal for this guide is to create a [Take Profit Order](../../../../concepts/protocol/range-orders.md#take-profit-orders) that trades `token0` for `token1` when the Price of `token0` increases by 5%. -To create our Position, we need to first decide the Tick Range that we want to provide liquidity in. - -### Upper Tick - -We [create a Pool](./02-pool-data.md) that represents the V3 Pool we are interacting with and get the `token0Price`. -We won't need full tick data in this example. - -```typescript -import { Pool } from '@uniswap/v3-sdk' - -... -const pool = new Pool(token0, token1, fee, sqrtPriceX96, liquidity, tickCurrent) - -const currentPrice = pool.token0Price -``` - -Next we increase the `Price` by 5%. We create a new Price with a numerator 5% higher than our current Price: - -```typescript -import { Price, Fraction } from '@uniswap/sdk-core' - -const targetFraction = Price.asFraction.multiply(new Fraction(100 + 5, 100)) - -const targetPrice = new Price( - currentPrice.baseCurrency, - currentPrice.quoteCurrency, - targetFraction.denominator, - targetFraction.numerator -) -``` - -Be aware that the `numerator` and `denominator` parameters are ordered differently in the `Fraction` and `Price` constructor. - -We have calculated our target Price but we still need to find the **nearest usable tick** to create our Position. - -:::info -As Positions can only start and end at initializable Ticks of the Pool, so we can only create a Range Order to a Price that exactly matches an initializable Tick. -::: - -We use the `priceToClosestTick` function to find the closest tick to our targetPrice. -We then use the `nearestUsableTick` function to find the closest initializable Tick for the `tickSpacing` of the `Pool`. - -```typescript -import {priceToClosestTick, nearestUsableTick} from '@uniswap/v3-sdk' - -let targetTick = nearestUsableTick( - priceToClosestTick(targetPrice), - pool.tickSpacing -) -``` - -This nearest Tick will most likely not **exactly** match our Price target. - -Depending on our personal preferences we can either err on the higher or lower side of our target by adding or subtracting the `tickSpacing` if the initializable Tick is lower or higher than the theoretically closest Tick. - -### Lower Tick - -We now find the lower Tick by subtracting the tickSpacing from the upper Tick: - -```typescript -let lowerTick = targetTick - pool.tickSpacing -``` - -If the price difference is too low, the lower tick may be left of the current Tick of the Pool. -In that case we would not be able to provide single side liquidity. -We can either throw an Error or increase our Position by one Tick. - -```typescript -if (tickLower <= pool.tickCurrent) { - tickLower += pool.tickSpacing - targetTick += pool.tickSpacing -} -``` - -We now have a lower and upper Tick for our Position, next we need to construct and mint it. - -## Creating the Single Side Liquidity Position - -We will use the `NonfungiblePositionManager` and `Position` classes from the `v3-sdk` to construct our position. We then use an **etherJS** wallet to mint our Position on-chain. - -If you are not familiar with liquidity Positions, check out the [liquidity position guides](../liquidity/01-position-data.md). - -### Minting the Position - -We create a `Position` object with our ticks and the amount of tokens we want to deposit: - -```typescript -import { Position } from '@uniswap/v3-sdk' - -const position = Position.fromAmount0({ - pool: pool, - tickLower: tickLower, - tickUpper: targetTick, - amount0: amount, - useFullPrecision: true -}) -``` - -Before we mint our position, we need to give the `NonfungiblePositionManager` Contract an approval to transfer our tokens. -We can find the Contract address on the official [Uniswap Github](https://github.com/Uniswap/v3-periphery/blob/main/deploys.md). -For local development, the contract address is the same as the network we are forking from. -So if we are using a local fork of mainnet like described in the [Local development guide](../02-local-development.md), the contract address would be the same as on mainnet. - -```typescript -import ethers from 'ethers' - -const provider = new ethers.providers.JsonRpcProvider(rpcUrl) -const wallet = new ethers.Wallet(privateKey, provider) - -const tokenContract = new ethers.Contract( - pool.token0.address, - ERC20_ABI, - wallet -) - -await tokenContract['approve']( - NONFUNGIBLE_POSITION_MANAGER_CONTRACT_ADDRESS, - ethers.BigNumber.from(amount) - ) -``` - -Once we have our approval, we create the calldata for the **Mint** call using the `NonfungiblePositionManager`: - -```typescript -import {MintOptions, NonfungiblePositionManager} -import { Percent } from '@uniswap/sdk-core' - -const mintOptions: MintOptions = { - recipient: wallet.address, - deadline: Math.floor(Date.now() / 1000) + 60 * 20, - slippageTolerance: new Percent(50, 10_000), -} - -const { calldata, value } = NonfungiblePositionManager.addCallParameters( - order.position, - mintOptions -) -``` - -We can populate our mint transaction and send it with our wallet: - -```typescript - const transaction = { - data: calldata, - to: NONFUNGIBLE_POSITION_MANAGER_CONTRACT_ADDRESS, - value: ethers.BigNumber.from(value), - from: address, - maxFeePerGas: MAX_FEE_PER_GAS, - maxPriorityFeePerGas: MAX_PRIORITY_FEE_PER_GAS, - } - -const txRes = await wallet.sendTransaction(transaction) -``` - -You can find full code examples for these code snippets in [`range-order.ts`](https://github.com/uniswap/examples/blob/main/v3-sdk/range-order/src/libs/range-order.ts). - -### Getting the tokenId - -We want to read the response to our `Mint` function call to get **the position id**. -We will need the positionId to fetch the Position Info from the NFTPositionManager contract. -We wait for the transaction receipt and fetch the result using `trace_transaction`: - -```typescript -let receipt = null -let mintCallOutput - -while (receipt === null) { - try { - receipt = await provider.getTransactionReceipt(txRes.hash) - - if (receipt === null) { - continue - } else { - const callTraces = await provider.send('trace_transaction', [ - txRes.hash - ]) - mintCallOutput = callTraces[0].result.output - } - } catch (e) { - break - } -} -``` - -Your Node provider may not support this call. In that case you can also call the NonfungiblePositionManager Contract with the wallet address and identify the Range Order Position manually: - -```typescript -const mintCallOutput = await wallet.call(transaction) -``` - -We get a raw byte string as a return value from this function and have to parse it ourselves. -We decode the result with the **ethers AbiCoder**. The solidity function has this signature: - -```solidity -function mint( - struct INonfungiblePositionManager.MintParams params -) external returns (uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1) -``` - -So we need the first parameter to get the `tokenId`: - -```typescript -const decodedOutput = ethers.utils.defaultAbiCoder.decode( - ['tuple(uint256, uint128, uint256, uint256)'], - mintCallOutput - )[0] - -const tokenId = decodedOutput.toString() -``` - -Ethers handles the string decoding of the byte string we got and parses it to its internal datatypes. -The decodedOutput we get from the AbiCoder is a `ethers.Bignumber` so we need to cast it to a string to use it with the SDK. - -We have created our Range Order Position, now we need to monitor it. - -In the [code example](https://github.com/uniswap/examples/blob/main/v3-sdk/range-order/src/libs/range-order.ts#L180) we use `wallet.call` to get the position id. -`call` and `trace_call` both simulate a transaction on the connected node and return the expected output, `trace_call` gives us a much more detailed output though. -Depending on the use case, either can be the better choice. -In a production environment you would prefer to wait for the `transactionReceipt` like described earlier to ensure the transaction was actaully included in the blockchain. - -## Observing the Price - -We need to observe the price of the Pool and withdraw our Position once the `tickCurrent` has moved across our Position. - -We use **ethers JS** to watch for new blocks and fetch the latest Pool data: - -```typescript - -provider.on('block', refreshPool()) - -function refreshPool() { - - ... // construct Pool contract - - const slot0 = await poolContract.slot0() - const tickCurrent = slot0.tick -} -``` - -It is not necessary to calculate the Price from the tick we fetched, as executing the limit order is dependent on the tick range we defined and not the Price from which we calculated it. - -```typescript - -if (tickCurrent > targetTick) { - // Withdraw position -} -``` - -We check if the tick has crossed our position, and if so we withdraw the Position. - -## Closing the Limit Order - -We call the NonfungiblePositionManager Contract with the `tokenId` to get all info of our position as we may have gotten fees from trades on the Pool: - -```typescript -import INON_FUNGIBLE_POSITION_MANAGER from '@uniswap/v3-periphery/artifacts/contracts/NonfungiblePositionManager.sol/NonfungiblePositionManager.json' - -const positionManagerContract = new ethers.Contract( - NONFUNGIBLE_POSITION_MANAGER_CONTRACT_ADDRESS, - INONFUNGIBLE_POSITION_MANAGER.abi, - provider -) - -const positionInfo = await positionManagerContract.positions(tokenId) -``` - -We use the `NonfungiblePositionManager`, the `pool`, `positionInfo` and `tokenId` to create call parameter for a `decreaseLiquidity` call. - -We start with creating `CollectOptions`: - -```typescript -import { Percent, CurrencyAmount } from '@uniswap/sdk-core' -import { CollectOptions, RemoveLiquidityOptions } from '@uniswap/v3-sdk' -import JSBI from 'jsbi' - -const collectOptions: Omit = { - expectedCurrencyOwed0: CurrencyAmount.fromRawAmount( - pool.token0, - JSBI.BigInt(positionInfo.tokensOwed0.toString()) - ), - expectedCurrencyOwed1: CurrencyAmount.fromRawAmount( - pool.token1, - JSBI.BigInt(positionInfo.tokensOwed1.toString()) - ), - recipient: wallet.address, -} -``` - -Next we create `RemoveLiquidityOptions`. We remove all our liquidity so we set liquidityPercentage to `1`: - -```typescript -const removeLiquidityOptions: RemoveLiquidityOptions = { - deadline: Math.floor(Date.now() / 1000) + 60 * 20, - slippageTolerance: new Percent(50, 10_000), - tokenId, - // percentage of liquidity to remove - liquidityPercentage: new Percent(1), - collectOptions, - } -``` - -We create a new `Position` object from the updated `positionInfo` info we fetched: - -```typescript - -const updatedPosition = new Position{ - pool, - liquidity: JSBI.BigInt(currentPositionInfo.liquidity.toString()), - tickLower: currentPositionInfo.tickLower, - tickUpper: currentPositionInfo.tickUpper, -} -``` - -We have everything to create our calldata now and are ready to make our Contract call: - -```typescript - -const { calldata, value } = NonfungiblePositionManager.removeCallParameters( - updatedPosition, - removeLiquidityOptions - ) -const transaction = { - data: calldata, - to: NONFUNGIBLE_POSITION_MANAGER_CONTRACT_ADDRESS, - value: value, - from: address, - maxFeePerGas: MAX_FEE_PER_GAS, - maxPriorityFeePerGas: MAX_PRIORITY_FEE_PER_GAS, -} - -const result = await wallet.sendTransaction(transaction) -``` - -Our liquidity position is removed and we receive `token1` at the Price we have specified. -We have successfully executed a range order. - -## Caveats - -Executing a range order has certain limitations that may have become obvious during the course of this guide. - -- If the price of the Pool drops below `tickUpper` while we already decided to withdraw our liquidity our order may fail and we either receive `token0`, `token0` and `token1` or our transaction fails depending on our exact implementation. -- Range Orders can only be created between initializable ticks and may not exactly represent our limit order Price-Target. -- Depending on the price ratio of the tokens in the Pool the minimum price difference to the current price may be significant. -- The tokens received are the average between the Price of `tickUpper` and `tickLower` of the Range order. This can be a significant difference for Pools with a tickCurrent far from 0, for example tokens with different decimals (WETH/ USDT, WETH/USDC). The example showcases this behaviour well with the default configuration. - -## Next Steps - -This guide showcases everything you need to implement Range Orders on your own, but only demonstrates creating a Take Profit order in `token0` to `token1` direction. -Consider implementing Buy Limit orders as described in the [Range Orders concept page](../../../../concepts/protocol/range-orders.md#buy-limit-orders). - -This is currently the last guide in the `v3-sdk` series. Consider joining the [Uniswap Discord](https://discord.com/invite/uniswap) or checkout the official [Github](https://github.com/Uniswap) to learn more about the t1 Protocol. diff --git a/docs/sdk/v3/guides/advanced/_category_.json b/docs/sdk/v3/guides/advanced/_category_.json deleted file mode 100644 index 65c1e3161..000000000 --- a/docs/sdk/v3/guides/advanced/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "label": "Advanced", - "position": 6, - "collapsed": true -} diff --git a/docs/sdk/v3/guides/advanced/images/liquidityNetComparison.png b/docs/sdk/v3/guides/advanced/images/liquidityNetComparison.png deleted file mode 100644 index 1c480ffda..000000000 Binary files a/docs/sdk/v3/guides/advanced/images/liquidityNetComparison.png and /dev/null differ diff --git a/docs/sdk/v3/guides/advanced/images/range-order.png b/docs/sdk/v3/guides/advanced/images/range-order.png deleted file mode 100644 index 9e2091d48..000000000 Binary files a/docs/sdk/v3/guides/advanced/images/range-order.png and /dev/null differ diff --git a/docs/sdk/v3/guides/advanced/images/tickBitmap-etherscan.png b/docs/sdk/v3/guides/advanced/images/tickBitmap-etherscan.png deleted file mode 100644 index 208d2db12..000000000 Binary files a/docs/sdk/v3/guides/advanced/images/tickBitmap-etherscan.png and /dev/null differ diff --git a/docs/sdk/v3/guides/advanced/images/tickBitmap_cut.png b/docs/sdk/v3/guides/advanced/images/tickBitmap_cut.png deleted file mode 100644 index 1729004e4..000000000 Binary files a/docs/sdk/v3/guides/advanced/images/tickBitmap_cut.png and /dev/null differ diff --git a/docs/sdk/v3/guides/images/anvil-result.png b/docs/sdk/v3/guides/images/anvil-result.png deleted file mode 100644 index 669539bbd..000000000 Binary files a/docs/sdk/v3/guides/images/anvil-result.png and /dev/null differ diff --git a/docs/sdk/v3/guides/images/postman-chainid-result.png b/docs/sdk/v3/guides/images/postman-chainid-result.png deleted file mode 100644 index b0940f5f6..000000000 Binary files a/docs/sdk/v3/guides/images/postman-chainid-result.png and /dev/null differ diff --git a/docs/sdk/v3/guides/liquidity/01-position-data.md b/docs/sdk/v3/guides/liquidity/01-position-data.md deleted file mode 100644 index 478bb0632..000000000 --- a/docs/sdk/v3/guides/liquidity/01-position-data.md +++ /dev/null @@ -1,206 +0,0 @@ ---- -id: position-data -title: Liquidity Positions ---- - -## Introduction - -This guide will introduce us to **liquidity positions** in t1 V3 and present the `v3-sdk` classes and Contracts used to interact with the protocol. -The concepts and code snippets showcased here can be found across the **Pooling Liquidity** examples in the t1 code examples [repository](https://github.com/Uniswap/examples). - -In this guide, we will take a look at the [Position](../../reference/classes/Position.md) and [NonfungiblePositionManager](../../reference/classes/NonfungiblePositionManager.md) classes, as well as the [NonfungiblePositionManager Contract](../../../../contracts/v3/reference/periphery/NonfungiblePositionManager.md). - -At the end of the guide, we should be familiar with the most important classes used to interact with liquidity positions. -We should also understand how to fetch positions from the **NonfungiblePositionManager Contract**. - -For this guide, the following t1 packages are used: - -- [`@uniswap/v3-sdk`](https://www.npmjs.com/package/@uniswap/v3-sdk) -- [`@uniswap/sdk-core`](https://www.npmjs.com/package/@uniswap/sdk-core) -- [`@uniswap/v3-periphery`](https://www.npmjs.com/package/@uniswap/v3-periphery) - -The code mentioned in this guide can be found across the [minting Position](https://github.com/Uniswap/examples/blob/main/v3-sdk/minting-position/src), [collecting Fees](https://github.com/Uniswap/examples/blob/main/v3-sdk/collecting-fees/src), [modifying positions](https://github.com/Uniswap/examples/blob/d34a53412dbf905802da2249391788a225719bb8/v3-sdk/modifying-position/src) and [swap and add liquidity](https://github.com/Uniswap/examples/blob/main/v3-sdk/swap-and-add-liquidity/src) examples. - -## Prerequisites - -To understand what Positions are, we need to understand some underlying concepts of the t1 protocol. - -Consider checking out the [Concepts section](../../../../concepts/protocol/concentrated-liquidity.md) as well as the [Uniswap Book](https://uniswapv3book.com/docs/introduction/uniswap-v3/). - -### Concentrated liquidity - -Uniswap V3 Pools use concentrated liquidity to allow a denser concentration of liquidity at specific prices. -Compared to the full range liquidity model t1 V2 uses, this allows traders to make larger trades with less price impact. -Liquidity providers can choose a specific price range in which they want their liquidity to be used by trades. - -To achieve this, t1 V3 Pools discriminate the price range with **Ticks**. - -### Ticks - -Ticks are the boundaries between discrete price ranges. -A change of 1 Tick always represents a price change of 0.01% from the current price. -Uniswap V3 Pools can have different `tickSpacings`, a constant that describes which ticks can be used by the Pool. -Only ticks at indices that are divisible by the tickSpacing can be initialized. -This value is dependant on the fee of the Pool, Pools with higher fees have higher tickSpacing. - -For example, a Pool with **HIGH** fee (1%) has a tickSpacing of 200, meaning the price difference between initializable Ticks is: - -$$1.0001^{200} = 1.0202$$ or $$2.02$$% - -### Liquidity Positions - -When someone provides liquidity to a Pool, they create a **Liquidity Position**. -This position is defined by the amount of liquidity provided and the start tick and the end tick, or price range, of the Position. - -Because V3 Pools allow users to choose any price range in which they want to provide liquidity, it is possible to create positions that do not contain the current Price of the Pool. -In this case, the liquidity provider will pay only one type of Token into the Pool, creating a **single side liquidity position**. - -To learn more about how Ticks and Liquidity positions work, consider reading the [whitepaper](https://uniswap.org/whitepaper-v3.pdf) or the other resources mentioned above. - -Now that we have a rough understanding of liquidity positions in t1 V3, let's look at the correspondent classes the SDK offers us. - -## Position class - -The **sdk** provides a [`Position`](https://github.com/Uniswap/v3-sdk/blob/main/src/entities/position.ts) class used to create local representations of an onchain position. -It is used to create the calldata for onchain calls to mint or modify an onchain position. - -There are four ways to construct a position. - -Directly with the [constructor](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/position.ts#L40): - -```typescript -import { Pool, Position } from '@uniswap/v3-sdk' -import JSBI from 'jsbi' - -const pool = new Pool(...) -const tickLower: number = -100 -const tickUpper: number = 200 -const liquidity: JSBI = JSBI.BigInt('1000000000000000000') - -const position = new Position({ - pool, - liquidity, - tickLower, - tickUpper -}) -``` - -Using the [`fromAmounts()`](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/position.ts#L312) function: - -```typescript -import { BigIntish } from '@uniswap/sdk-core' - -const pool = new Pool(...) -const tickLower: number = -100 -const tickUpper: number = 200 -const amount0: BigIntish = '1000000000000000000' -const amount1: BigIntish = JSBI.BigInt('1000000000000000000') -const useFullPrecision: boolean = true - -const position = Position.fromAmounts({ - pool, - tickLower, - tickUpper, - amount0, - amount1, - useFullPrecision -}) -``` - -Or using the [`fromAmount0()`](https://github.com/Uniswap/v3-sdk/blob/08a7c050cba00377843497030f502c05982b1c43/src/entities/position.ts#L354) or [`fromAmount1()`](https://github.com/Uniswap/v3-sdk/blob/08a7c050cba00377843497030f502c05982b1c43/src/entities/position.ts#L378) functions: - -```typescript -import { BigIntish } from '@uniswap/sdk-core' -... - -const pool = new Pool(...) -const tickLower: number = -200 -const tickUpper: number = 100 -const amount0: BigIntish = '1000000000000000000' -const useFullPrecision: boolean = true - -const singleSidePositionToken0 = Position.fromAmount0({ - pool, - tickLower, - tickUpper, - amount0, - useFullPrecision -}) - -const amount1: BigIntish = 100000000 - -const singleSidePositionToken1 = Position.fromAmount1({ - pool, - tickLower, - tickUpper, - amount1, - useFullPrecision -}) -``` - -These last two functions calculate a position at the given tick range given the amount of `token0` or `token1`. The amount of the second token is calculated from the ratio of the tokens inside the tick range and the amount of token one. - -A create transaction would then fail if the wallet doesn't hold enough `token1` or the Contract is not given the necessary **Transfer Approval**. - -All of these functions take an Object with **named values** as a call parameter. The amount and liquidity values are of type `BigIntish` which accepts `number`, `string` and `JSBI`. - -The values of `tickLower` and `tickUpper` must match **initializable ticks** of the Pool. - -## NonfungiblePositionManager - -The `NonfungiblePositionManager` class is mainly used to create calldata for functions on the **NonfungiblePositionManager Contract**. - -We will look at the **sdk** class and write functions on the Contract in this section. - -### Creating a Position - -To create a position on a Pool, the [`mint`](../../../../contracts/v3/reference/periphery/NonfungiblePositionManager.md#mint) function is called on the Contract. -The **sdk** class provides the `addCallParameters` function to create the calldata for the transaction: - -```typescript -import { MintOptions, NonfungiblePositionManager } from '@uniswap/v3-sdk' - -const mintOptions: MintOptions = { - recipient: address, - deadline: Math.floor(Date.now() / 1000) + 60 * 20, - slippageTolerance: new Percent(50, 10_000), -} - -// get calldata for minting a position -const { calldata, value } = NonfungiblePositionManager.addCallParameters( - positionToMint, - mintOptions -) -``` - -This call creates a position if it doesn't exist, but can also be used to increase an existing position. -Take a look at the [Mint Position guide](./02-minting-position.md) and [Modify Position guide](./04-modifying-position.md) to learn more. - -### Decreasing and Increasing a Position - -To decrease or increase the liquidity of a Position, the `decreaseLiquidity` or `increaseLiquidity` functions are called on the Contract. -To increase, `addCallParameters` is used as mentioned above, to decrease we use `removeCallParameters`: - -```typescript -const { calldata, value } = NonfungiblePositionManager.removeCallParameters( - currentPosition, - removeLiquidityOptions -) -``` - -Take a look at the [Modify Positions guide](04-modifying-position.md) to learn how to create the `currentPosition` and `removeLiquidityOptions` parameters. - -### Collecting Fees - -To collect fees accrued, the `collect` function is called on the Contract. -The **sdk class** provides the `collectCallParameters` function to create the calldata for that: - -```typescript -const { calldata, value } = - NonfungiblePositionManager.collectCallParameters(collectOptions) -``` - - -## Next steps - -Now that you are familiar with the most important classes and Contract to interact with Liquidity Positions, continue with the next guide on [Minting Positions](./02-minting-position.md). diff --git a/docs/sdk/v3/guides/liquidity/02-minting-position.md b/docs/sdk/v3/guides/liquidity/02-minting-position.md deleted file mode 100644 index de1ee573d..000000000 --- a/docs/sdk/v3/guides/liquidity/02-minting-position.md +++ /dev/null @@ -1,234 +0,0 @@ ---- -id: minting -title: Minting a Position ---- - -## Introduction - -This guide will cover how to create (or mint) a liquidity position on the t1 V3 protocol. -It is based on the [minting a position code example](https://github.com/Uniswap/examples/tree/main/v3-sdk/minting-position), found in the t1 code examples [repository](https://github.com/Uniswap/examples). -To run this example, check out the examples's [README](https://github.com/Uniswap/examples/blob/main/v3-sdk/minting-position/README.md) and follow the setup instructions. - -:::info -If you need a briefer on the SDK and to learn more about how these guides connect to the examples repository, please visit our [background](../01-background.md) page! -::: - -In the t1 V3 protocol, liquidity positions are represented using non-fungible tokens. In this guide we will use the `NonfungiblePositionManager` class to help us mint a liquidity position for the **USDC - DAI** pair. The inputs to our guide are the **two tokens** that we are pooling for, the **amount** of each token we are pooling for and the Pool **fee**. - -The guide will **cover**: - -1. Giving approval to transfer our tokens -2. Creating an instance of a `Pool` -3. Calculating our `Position` from our input tokens -4. Configuring and executing our minting transaction - -At the end of the guide, given the inputs above, we should be able to mint a liquidity position with the press of a button and view the position on the UI of the web application. - -For this guide, the following t1 packages are used: - -- [`@uniswap/v3-sdk`](https://www.npmjs.com/package/@uniswap/v3-sdk) -- [`@uniswap/sdk-core`](https://www.npmjs.com/package/@uniswap/sdk-core) -- [`@uniswap/smart-order-router`](https://www.npmjs.com/package/@uniswap/smart-order-router) - -The core code of this guide can be found in [`mintPosition()`](https://github.com/Uniswap/examples/blob/main/v3-sdk/minting-position/src/libs/positions.ts#L37) - -## Giving approval to transfer our tokens - -We want to use the `NonfungiblePositionManager` contract to create our liqudity position. -In situations where a smart contract is transfering tokens on our behalf, we need to give it approval to do so. -This is done by interacting with the Contract of the contract, considering ERC20 Tokens are smart contracts of their own. - -Considering this, the first step to create our position is to give approval to the protocol's `NonfungiblePositionManager` to transfer our tokens: - -```typescript -const token0Approval = await getTokenTransferApproval( - token0Address, - amount0 -) -const token1Approval = await getTokenTransferApproval( - token1Address, - amount1 -) -``` - -The logic to achieve that is wrapped in the `getTokenTransferApprovals` function. In short, since both **USDC** and **DAI** are ERC20 tokens, we setup a reference to their smart contracts and call the `approve` function: - -```typescript -import { ethers, BigNumber } from 'ethers' - -async function getTokenTransferApproval(address: string, amount: BigNumber) { - const provider = new ethers.providers.JsonRpcProvider(rpcUrl) - - const tokenContract = new ethers.Contract( - token.address, - ERC20_ABI, - provider - ) - - return tokenContract.approve( - NONFUNGIBLE_POSITION_MANAGER_CONTRACT_ADDRESS, - amount - ) -} -``` - -We can get the Contract address for the NonfungiblePositionManager from [Github](https://github.com/Uniswap/v3-periphery/blob/main/deploys.md). -For Ethereum mainnet or a local fork of mainnet, we see that the contract address is `0xC36442b4a4522E871399CD717aBDD847Ab11FE88`. -In our example, this is defined in the [`constants.ts`](https://github.com/Uniswap/examples/blob/main/v3-sdk/minting-position/src/libs/constants.ts) file. - -## Creating an instance of a `Pool` - -Having approved the transfer of our tokens, we now need to get data about the pool for which we will provide liquidity, in order to instantiate a Pool class. - -To start, we compute our Pool's address by using a helper function and passing in the unique identifiers of a Pool - the **two tokens** and the Pool **fee**. -The **fee** input parameter represents the swap fee that is distributed to all in range liquidity at the time of the swap. - -```typescript -import { computePoolAddress, FeeAmount } from '@uniswap/v3-sdk' -import { Token } from '@uniswap/sdk-core' - -const token0: Token = ... -const token1: Token = ... -const fee: FeeAmount = ... -const POOL_FACTORY_CONTRACT_ADDRESS: string = ... - -const currentPoolAddress = computePoolAddress({ - factoryAddress: POOL_FACTORY_CONTRACT_ADDRESS, - tokenA: token0, - tokenB: token1, - fee: poolFee, -}) -``` - -Again, we can get the factory contract address from [Github](https://github.com/Uniswap/v3-periphery/blob/main/deploys.md). -For Ethereum mainnet, or a local fork of mainnet, it is `0x1F98431c8aD98523631AE4a59f267346ea31F984`. -In our example, it is defined in [`constants.ts`](https://github.com/Uniswap/examples/blob/main/v3-sdk/minting-position/src/libs/constants.ts) - -Then, we get the Pool's data by creating a reference to the Pool's smart contract and accessing its methods, very similar to what we did in the [Quoting guide](../swaps/01-quoting.md#referencing-the-pool-contract-and-fetching-metadata): - -```typescript -import IUniswapV3PoolABI from '@uniswap/v3-core/artifacts/contracts/interfaces/IUniswapV3Pool.sol/IUniswapV3Pool.json' - -const poolContract = new ethers.Contract( - currentPoolAddress, - IUniswapV3PoolABI.abi, - provider -) - -const [liquidity, slot0] = - await Promise.all([ - poolContract.liquidity(), - poolContract.slot0(), - ]) -``` - -Having collected the required data, we can now create an instance of the `Pool` class: - -```typescript -import { Pool } from '@uniswap/v3-sdk' - -const configuredPool = new Pool( - token0, - token1, - poolFee, - slot0.sqrtPriceX96.toString(), - liquidity.toString(), - slot0.tick -) -``` - -We need a Pool instance to create our Position as various parameters of liquidity positions depend on the state of the Pool where they are created. -An example is the current price (named *sqrtPriceX96* after the way it is encoded) to know the ratio of the two Tokens we need to send to the Pool. - -Liquidity provided below the current Price will be provided in the first Token of the Pool, while liquidity provided above the current Price is made up by the second Token. - -## Calculating our `Position` from our input tokens - -Having created the instance of the `Pool` class, we can now use that to create an instance of a `Position` class, which represents the price range for a specific pool that LPs choose to provide in: - -```typescript -import { Position } from '@uniswap/v3-sdk' -import { BigIntish } from '@uniswap/sdk-core' - -// The maximum token amounts we want to provide. BigIntish accepts number, string or JSBI -const amount0: BigIntish = ... -const amount1: BigIntish = ... - -const position = Position.fromAmounts({ - pool: configuredPool, - tickLower: - nearestUsableTick(configuredPool.tickCurrent, configuredPool.tickSpacing) - - configuredPool.tickSpacing * 2, - tickUpper: - nearestUsableTick(configuredPool.tick, configuredPool.tickSpacing) + - configuredPool.tickSpacing * 2, - amount0: amount0, - amount1: amount1, - useFullPrecision: true, -}) -``` - -We use the `fromAmounts` static function of the `Position` class to create an instance of it, which uses the following parameters: - -- The **tickLower** and **tickUpper** parameters specify the price range at which to provide liquidity. This example calls **nearestUsableTick** to get the current useable tick and adjust the lower parameter to be below it by two **tickSpacing** and the upper to be above it by two tickSpacing. This guarantees that the provided liquidity is "in range", meaning it will be earning fees upon minting this position -- **amount0** and **amount1** define the maximum amount of currency the liquidity position can use. In this example, we supply these from our configuration parameters. - -Given those parameters, `fromAmounts` will attempt to calculate the maximum amount of liquidity we can supply. - -## Configuring and executing our minting transaction - -The Position instance is then passed as input to the `NonfungiblePositionManager`'s `addCallParameters` function. The function also requires an [`AddLiquidityOptions`](https://github.com/Uniswap/v3-sdk/blob/08a7c050cba00377843497030f502c05982b1c43/src/nonfungiblePositionManager.ts#L77) object as its second parameter. This is either of type [`MintOptions`](https://github.com/Uniswap/v3-sdk/blob/08a7c050cba00377843497030f502c05982b1c43/src/nonfungiblePositionManager.ts#L74) for minting a new position or [`IncreaseOptions`](https://github.com/Uniswap/v3-sdk/blob/08a7c050cba00377843497030f502c05982b1c43/src/nonfungiblePositionManager.ts#L75) for adding liquidity to an existing position. For this example, we're using a `MintOptions` to create our position. - -```typescript -import { MintOptions, NonfungiblePositionManager } from '@uniswap/v3-sdk' -import { Percent } from '@uniswap/sdk-core' - -const mintOptions: MintOptions = { - recipient: address, - deadline: Math.floor(Date.now() / 1000) + 60 * 20, - slippageTolerance: new Percent(50, 10_000), -} - -// get calldata for minting a position -const { calldata, value } = NonfungiblePositionManager.addCallParameters( - position, - mintOptions -) -``` - -The `MintOptions` interface requires three keys: - -- `recipient` defines the address of the Position owner, so in our case the address of our wallet. -- `deadline` defines the latest point in time at which we want our transaction to be included in the blockchain. -- `slippageTolerance` defines the maximum amount of **change of the ratio** of the Tokens we provide. The ratio can change if for example **trades** that change the price of the Pool are included before our transaction. - -The `addCallParameters` function returns the calldata as well as the value required to execute the transaction: - -```typescript -const transaction = { - data: calldata, - to: NONFUNGIBLE_POSITION_MANAGER_CONTRACT_ADDRESS, - value: value, - from: address, - maxFeePerGas: MAX_FEE_PER_GAS, - maxPriorityFeePerGas: MAX_PRIORITY_FEE_PER_GAS, -} -``` - -We use our wallet to send the transaction. As it is a write call, we need to sign the transaction with a valid private key. - -```typescript -const wallet = new ethers.Wallet(privateKey, provider) - -const txRes = await wallet.sendTransaction(transaction) -``` - -Write calls do not return the result of the transaction. If we want to read the result we would need to use for example `trace_transaction`. -You can find an example of that in the [Range Order guide](../advanced/05-range-orders.md). -In this example, we don't need the result of the transaction. - -The effect of the transaction is to mint a new Position NFT. We should see a new position with liquidity in our list of positions. - -## Next Steps - -Once you have minted a position, our next guide [Adding and Removing Liquidity](./04-modifying-position.md) will demonstrate how you can add and remove liquidity from that minted position! diff --git a/docs/sdk/v3/guides/liquidity/03-fetching-positions.md b/docs/sdk/v3/guides/liquidity/03-fetching-positions.md deleted file mode 100644 index 6e087f5cb..000000000 --- a/docs/sdk/v3/guides/liquidity/03-fetching-positions.md +++ /dev/null @@ -1,141 +0,0 @@ ---- -id: fetching-positions -title: Fetching Positions ---- - -## Introduction - -This guide will cover how to create (or mint) a liquidity position on the t1 V3 protocol. -Like the [Liquidity Position guide](./01-position-data.md) it doesn't have an accompanying example, nevertheless the concepts and functions used here can be found among the various examples that interact with liquidity positions. - -:::info -If you need an introduction to liquidity positions, check out the [Liquidity Position guide](./01-position-data.md) -::: - -The [NonfungiblePositionManager Contract](../../../../contracts/v3/reference/periphery/NonfungiblePositionManager.md) can be used to create Positions, as well as get information on **existing Positions**. -In this guide, we will fetch **all Positions** an address has and fetch the **detailed Position Data** for those positions. - -The guide will **cover**: - -1. Creating an ethersJS contract to interact with the NonfungiblePositionManager. -2. Fetching all positions for an address. -3. Fetching the position info for the positions. - -At the end of the guide, given the inputs above, we should be able to mint a liquidity position with the press of a button and view the position on the UI of the web application. - -For this guide, we do not need to use the t1 SDKs, we will only import the contract ABI for the NonfungiblePositionManager Contract from [`@uniswap/v3-periphery`](https://www.npmjs.com/package/@uniswap/v3-periphery). - -## Connecting to the NFTPositionManager Contract - -We use **ethersJS** to interact with the NonfungiblePositionManager Contract. Let's create an ethers Contract: - -```typescript -import { ethers } from 'ethers' -import INONFUNGIBLE_POSITION_MANAGER from '@uniswap/v3-periphery/artifacts/contracts/NonfungiblePositionManager.sol/NonfungiblePositionManager.json' - -const provider = new ethers.providers.JsonRpcProvider(rpcUrl) - -const nfpmContract = new ethers.Contract( - NONFUNGIBLE_POSITION_MANAGER_CONTRACT_ADDRESS, - INONFUNGIBLE_POSITION_MANAGER.abi, - provider -) -``` - -We get the Contract ABI from the 'v3-periphery` package and the contract address from [Github](https://github.com/Uniswap/v3-periphery/blob/main/deploys.md) - -## Fetching the Position Ids - -We want to fetch all Position Ids for our address. We first fetch the number of positions and then the ids by their indices. - -We fetch the number of positions using the `balanceOf` read call: - -```typescript - -const numPositions = await nfpmContract.balanceOf(address) -``` - -Next we iterate over the number of positions and fetch the ids: - -```typescript -const calls = [] - -for (let i = 0; i < numPositions; i++) { - calls.push( - nfpmContract.tokenOfOwnerByIndex(address, i) - ) -} - -const positionIds = await Promise.all(calls) -``` - -## Fetching the Position Info - -Now that we have the ids of the Positions associated with our address, we can fetch the position info using the `positions` function. - -The solidity function returns a lot of values describing the Position: - -```solidity -function positions( - uint256 tokenId - ) external view returns ( - uint96 nonce, - address operator, - address token0, - address token1, - uint24 fee, - int24 tickLower, - int24 tickUpper, - uint128 liquidity, - uint256 feeGrowthInside0LastX128, - uint256 feeGrowthInside1LastX128, - uint128 tokensOwed0, - uint128 tokensOwed1 - ) -``` - -In this example we only care about values needed to interact with positions, so we create an Interface `PositionInfo`: - -```typescript -interface PositionInfo { - tickLower: number - tickUpper: number - liquidity: JSBI - feeGrowthInside0LastX128: JSBI - feeGrowthInside1LastX128: JSBI - tokensOwed0: JSBI - tokensOwed1: JSBI -} -``` - -We fetch the Position data with `positions`: - -```typescript -const positionCalls = [] - -for (let id of positionIds) { - positionCalls.push( - nfpmContract.positions(id) - ) -} - -const callResponses = await Promise.all(positionCalls) -``` - -Finally, we map the RPC response to our interface: - -```typescript -const positionInfos = callResponses.map((position) => { - return { - tickLower: position.tickLower, - tickUpper: position.tickUpper, - liquidity: JSBI.BigInt(position.liquidity), - feeGrowthInside0LastX128: JSBI.BigInt(position.feeGrowthInside0LastX128), - feeGrowthInside1LastX128: JSBI.BigInt(position.feeGrowthInside1LastX128), - tokensOwed0: JSBI.BigInt(position.tokensOwed0), - tokensOwed1: JSBI.BigInt(position.tokensOwed1), - } -}) -``` - -We now have an array containing PositionInfo for all positions that our address holds. diff --git a/docs/sdk/v3/guides/liquidity/04-modifying-position.md b/docs/sdk/v3/guides/liquidity/04-modifying-position.md deleted file mode 100644 index 2ef1c2184..000000000 --- a/docs/sdk/v3/guides/liquidity/04-modifying-position.md +++ /dev/null @@ -1,269 +0,0 @@ ---- -id: modifying-position -title: Adding & Removing Liquidity ---- - -## Introduction - -This guide will cover how to modify a liquidity position by adding or removing liquidity on the t1 V3 protocol. It is based on the [modifying a position code example](https://github.com/Uniswap/examples/tree/main/v3-sdk/modifying-position), found in the t1 code examples [repository](https://github.com/Uniswap/examples). To run this example, check out the examples's [README](https://github.com/Uniswap/examples/blob/main/v3-sdk/modifying-position/README.md) and follow the setup instructions. - -:::info -If you need a briefer on the SDK and to learn more about how these guides connect to the examples repository, please visit our [background](../01-background.md) page! -::: - -In the t1 V3 protocol, liquidity positions are represented using non-fungible tokens. In this guide we will use the `NonfungiblePositionManager` class to help us mint a liquidity position and then modify the provided liquidity for the **USDC - DAI** pair. The inputs to our guide are the **two tokens** that we are pooling for, the **amount** of each token we are pooling for, the Pool **fee** and the **fraction** by which to **add and remove** from our position. - -The guide will **cover**: - -1. Adding liquidity to our position -2. Removing liquidity from our position - -At the end of the guide, given the inputs above, we should be able to add or remove liquidity from a minted position with the press of a button and see the change reflected in our position and the balance of our tokens. - -For this guide, the following t1 packages are used: - -- [`@uniswap/v3-sdk`](https://www.npmjs.com/package/@uniswap/v3-sdk) -- [`@uniswap/sdk-core`](https://www.npmjs.com/package/@uniswap/sdk-core) - -The core code of this guide can be found in [`addLiquidity()`](https://github.com/Uniswap/examples/blob/d34a53412dbf905802da2249391788a225719bb8/v3-sdk/modifying-position/src/example/Example.tsx#L33) and [`removeLiquidity()`](https://github.com/Uniswap/examples/blob/733d586070afe2c8cceb35d557a77eac7a19a656/v3-sdk/modifying-position/src/example/Example.tsx#L83) - -:::note -This guide assumes you are familiar with our [Minting a Position](./02-minting-position.md) guide. A minted position is required to add or remove liquidity from, so the buttons will be disabled until a position is minted. - -Also note that we do not need to give approval to the `NonfungiblePositionManager` to transfer our tokens as we will have already done that when minting our position. -::: - -## Configuration and utils - -The example can be configured in the [`config.ts`](https://github.com/Uniswap/examples/blob/d34a53412dbf905802da2249391788a225719bb8/v3-sdk/modifying-position/src/config.ts) file. -The `CurrentConfig` object has this structure: - -```typescript -export const CurrentConfig: ExampleConfig = { - env: Environment.LOCAL, - rpc: { - local: 'http://localhost:8545', - mainnet: 'https://mainnet.infura.io/v3/0ac57a06f2994538829c14745750d721', - }, - wallet: { - address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', - privateKey: - '0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80', - }, - tokens: { - token0: USDC_TOKEN, - token0Amount: 1000, - token1: DAI_TOKEN, - token1Amount: 1000, - poolFee: FeeAmount.LOW, - fractionToRemove: 1, - fractionToAdd: 0.5, - }, -} -``` - -You should already be familiar with the `rpc`, `wallet` and token parameters, they are used in the same way as in the guides earlier in our v3-sdk series. -The `fractionToAdd` variable is the multiplicator by which we will increase the Position. A fraction of **0.5** means we increase the liquidity by **50%**. -The `fractionToRemove` variable is the fraction of the Position that we want to remove later in the guide. A fraction of **1** means we remove **100%** of the liquidity. - -## Adding liquidity to our position - -Assuming we have already minted a position, our first step is to construct the modified position using our original position to calculate the amount by which we want to increase our current position: - -```typescript -const fractionToAdd: number = ... - -const amount0Increased: JSBI = fromReadableAmount( - readableAmount0 * fractionToAdd, - token0.decimals -) -const amount1Increase: JSBI = fromReadableAmount( - readableAmount1 * fractionToAdd, - token1.decimals -) - -const positionToIncreaseBy = constructPosition( - amount0Increased, - amount1Increase - ) -) -``` - -The `fromReadableAmount()` function calculates the amount of tokens in their smallest unit, so for example 1 ETH would be `1000000000000000000` Wei as ETH has 18 decimals. - -A better way to get the amounts might be to fetch them with the positionId directly from the blockchain. -We demonstrated how to do that in the [first guide](./01-position-data.md#fetching-positions) of this series. - -```typescript -import { Pool, Position } from '@uniswap/v3-sdk' -import JSBI from 'jsbi' - -function constructPosition( - amount0: JSBI, - amount1: JSBI -): Position { - // create Pool same as in the previous guide - const pool = new Pool(...) - - // create position using the maximum liquidity from input amounts - return Position.fromAmounts({ - pool, - tickLower: - nearestUsableTick(pool.tickCurrent, pool.tickSpacing) - - pool.tickSpacing * 2, - tickUpper: - nearestUsableTick(pool.tickCurrent, pool.tickSpacing) + - pool.tickSpacing * 2, - amount0, - amount1, - useFullPrecision: true, - }) -} -``` - -The function receives two arguments, which are the amounts that are used to construct the Position instance. In this example, both of the arguments follow the same logic: we multiply the parameterized `tokenAmount` by the parameterized `fractionToAdd` since the new liquidity position will be added on top of the already minted liquidity position. - -We then need to construct an options object of type [`AddLiquidityOptions`](https://github.com/Uniswap/v3-sdk/blob/08a7c050cba00377843497030f502c05982b1c43/src/nonfungiblePositionManager.ts#L77) similar to how we did in the minting case. In this case, we will use [`IncreaseOptions`](https://github.com/Uniswap/v3-sdk/blob/08a7c050cba00377843497030f502c05982b1c43/src/nonfungiblePositionManager.ts#L75): - -```typescript -import { AddLiquidityOptions } from '@uniswap/v3-sdk' - -const addLiquidityOptions: AddLiquidityOptions = { - deadline: Math.floor(Date.now() / 1000) + 60 * 20, - slippageTolerance: new Percent(50, 10_000), - tokenId, -} -``` - -Compared to minting, we have omitted the `recipient` parameter and instead passed in the `tokenId` of the position we previously minted. -As the Position already exists, the recipient doesn't change, instead the NonfungiblePositionManager contract can modify the existing Position by accessing it with its id. - -The tokenId can be fetched with the tokenOfOwnerByIndex function of the NonfungiblePositionManager Contract as described [here](./01-position-data.md#fetching-positions). - -The newly created position along with the options object are then passed to the `NonfungiblePositionManager`'s `addCallParameters`: - -```typescript -import { NonfungiblePositionManager } from '@uniswap/v3-sdk' - -const positionToIncreaseBy = constructPosition(CurrentConfig.tokens.amount0, CurrentConfig.tokens.amount1) - -const { calldata, value } = NonfungiblePositionManager.addCallParameters( - positionToIncreaseBy, - addLiquidityOptions -) -``` - -The return values of `addCallParameters` are the calldata and value of the transaction we need to submit to increase our position's liquidity. We can now build and execute the transaction: - -```typescript -import { ethers } from 'ethers' - -const transaction = { - data: calldata, - to: NONFUNGIBLE_POSITION_MANAGER_CONTRACT_ADDRESS, - value: value, - from: address, - maxFeePerGas: MAX_FEE_PER_GAS, - maxPriorityFeePerGas: MAX_PRIORITY_FEE_PER_GAS, -} - -const wallet = new ethers.Wallet(privateKey, provider) - -const txRes = await wallet.sendTransaction(transaction) -``` - -We can get the Contract address for the NonfungiblePositionManager from [Github](https://github.com/Uniswap/v3-periphery/blob/main/deploys.md). - -After pressing the button, note how the balance of USDC and DAI drops and our position's liquidity increases. - -## Removing liquidity from our position - -The `removeLiquidity` function is the mirror action of adding liquidity and will be somewhat similar as a result, requiring a position to already be minted. - -To start, we create a position identical to the one we minted: - -```typescript -const amount0: JSBI = fromReadableAmount( - readableAmount0 * fractionToAdd, - token0.decimals -) -const amount1: JSBI = fromReadableAmount( - readableAmount1 * fractionToAdd, - token1.decimals -) - -const currentPosition = constructPosition( - amount0, - amount1 -) -``` - -We then need to construct an options object of type [`RemoveLiquidityOptions`](https://github.com/Uniswap/v3-sdk/blob/08a7c050cba00377843497030f502c05982b1c43/src/nonfungiblePositionManager.ts#L138): - -```typescript -import { RemoveLiquidityOptions } from '@uniswap/v3-sdk' -import { Percent } from '@uniswap/sdk-core' - -const removeLiquidityOptions: RemoveLiquidityOptions = { - deadline: Math.floor(Date.now() / 1000) + 60 * 20, - slippageTolerance: new Percent(50, 10_000), - tokenId: positionId, - // percentage of liquidity to remove - liquidityPercentage: new Percent(0.5), - collectOptions, -} -``` - -Just as with adding liquidity, we have we have omitted the `recipient` parameter and instead passed in the `tokenId` of the position we previously minted. - -We have also provide two additional parameters: - -- `liquidityPercentage` determines how much liquidity is removed from our initial position (as a `Percentage`), and transfers the removed liquidity back to our address. We set this percentage from our guide configuration ranging from 0 (0%) to 1 (100%). In this example we would remove 50% of the liquidity. -- [`collectOptions`](https://github.com/Uniswap/v3-sdk/blob/08a7c050cba00377843497030f502c05982b1c43/src/nonfungiblePositionManager.ts#L105) gives us the option to collect the fees, if any, that we have accrued for this position. In this example, we won't collect any fees, so we provide zero values. If you'd like to see how to collect fees without modifying your position, check out our [collecting fees](./03-collecting-fees.md) guide! - -```typescript -import { CurrencyAmount } from '@uniswap/sdk-core' -import { CollectOptions } from '@uniswap/v3-sdk' - -const collectOptions: Omit = { - expectedCurrencyOwed0: CurrencyAmount.fromRawAmount( - token0, - 0 - ), - expectedCurrencyOwed1: CurrencyAmount.fromRawAmount( - token1, - 0 - ), - recipient: address, -} -``` - -The position object along with the options object is passed to the `NonfungiblePositionManager`'s `removeCallParameters`, similar to how we did in the adding liquidity case: - -```typescript -const { calldata, value } = NonfungiblePositionManager.removeCallParameters( - currentPosition, - removeLiquidityOptions -) -``` - -The return values `removeCallParameters` are the calldata and value that are needed to construct the transaction to remove liquidity from our position. We can build the transaction and send it for execution: - -```typescript -const transaction = { - data: calldata, - to: NONFUNGIBLE_POSITION_MANAGER_CONTRACT_ADDRESS, - value: value, - from: address, - maxFeePerGas: MAX_FEE_PER_GAS, - maxPriorityFeePerGas: MAX_PRIORITY_FEE_PER_GAS, -} - -const txRes = await wallet.sendTransaction(transaction) -``` - -After pressing the button, note how the balance of USDC and DAI increases and our position's liquidity drops. - -## Next Steps - -Now that you can mint and modify a position, check out how to [collect fees](./04-collecting-fees.md) from the position! diff --git a/docs/sdk/v3/guides/liquidity/05-collecting-fees.md b/docs/sdk/v3/guides/liquidity/05-collecting-fees.md deleted file mode 100644 index e2ee6c2af..000000000 --- a/docs/sdk/v3/guides/liquidity/05-collecting-fees.md +++ /dev/null @@ -1,125 +0,0 @@ ---- -id: liquidity-fees -title: Collecting Fees ---- - -## Introduction - -This guide will cover how to collect fees from a liquidity position on the t1 V3 protocol. It is based on the [collecting fees code example](https://github.com/Uniswap/examples/tree/main/v3-sdk/collecting-fees), found in the t1 code examples [repository](https://github.com/Uniswap/examples). To run this example, check out the examples's [README](https://github.com/Uniswap/examples/blob/main/v3-sdk/collecting-fees/README.md) and follow the setup instructions. - -:::info -If you need a briefer on the SDK and to learn more about how these guides connect to the examples repository, please visit our [background](../01-background.md) page! -::: - -In the t1 V3 protocol, liquidity positions are represented using non-fungible tokens. In this guide we will use the `NonfungiblePositionManager` class to help us mint a liquidity position for the **USDC - DAI** pair. We will then attempt to collect any fees that the position has accrued from those trading against our provisioned liquidity. The inputs to our guide are the **two tokens** that we are pooling for, the **amount** of each token we are pooling for, the Pool **fee** and the **max amount of accrued fees** we want to collect for each token. - -The guide will **cover**: - -1. Setting up our fee collection -2. Submitting our fee collection transaction - -At the end of the guide, given the inputs above, we should be able to collect the accrued fees (if any) of a minted position with the press of a button and see the change reflected in our position and the balance of our tokens. - -For this guide, the following t1 packages are used: - -- [`@uniswap/v3-sdk`](https://www.npmjs.com/package/@uniswap/v3-sdk) -- [`@uniswap/sdk-core`](https://www.npmjs.com/package/@uniswap/sdk-core) - -The core code of this guide can be found in [`collectFees()`](https://github.com/Uniswap/examples/blob/main/v3-sdk/collecting-fees/src/libs/liquidity.ts#L35). - -:::note -This guide assumes you are familiar with our [Minting a Position](./01-minting-position.md) guide. A minted position is required to add or remove liquidity from, so the buttons will be disabled until a position is minted. - -Also note that we do not need to give approval to the `NonfungiblePositionManager` to transfer our tokens as we will have already done that when minting our position. -::: - -## Setting up our fee collection - -All of the fee collecting logic can be found in the [`collectFees`](https://github.com/Uniswap/examples/blob/be67e7df220b0a270c9d18bbaab529e017213adf/v3-sdk/collecting-fees/src/example/Example.tsx#L24) function. Notice how the **Collect Fees** button is disabled until a position is minted. This happens because there will be no fees to collect unless there is a position whose liquidity has been traded against. - -To start, we fetch the position from the NonfungiblePositionManager Contract to get the fees we are owed: - -```typescript -import { ethers } from 'ethers' -import JSBI from 'jsbi' -... - -const nfpmContract = new ethers.Contract(NONFUNGIBLE_POSITION_MANAGER_ADDRESS, provider) -const position = nfpmContract.positions(positionId) -``` - -Next, we construct an options object of type [`CollectOptions`](https://github.com/Uniswap/v3-sdk/blob/08a7c050cba00377843497030f502c05982b1c43/src/nonfungiblePositionManager.ts#L105) that holds the data about the fees we want to collect: - -```typescript -import { CurrencyAmount } from '@uniswap/sdk-core' - -const collectOptions: CollectOptions = { - tokenId: positionId, - expectedCurrencyOwed0: CurrencyAmount.fromRawAmount( - CurrentConfig.tokens.token0, - JSBI.BigInt(position.tokensOwed0) - ), - expectedCurrencyOwed1: CurrencyAmount.fromRawAmount( - CurrentConfig.tokens.token1, - JSBI.BigInt(position.tokensOwed1) - ), - recipient: address, -} -``` - -Read more about fetching position info [here](./01-position-data.md#fetching-positions). - -Similar to the other functions exposed by the `NonfungiblePositionManager`, we pass the `tokenId` and the `recipient` of the fees, which in this case is our function's input position id and our wallet's address. - -The other two `CurrencyAmount` parameters (`expectedCurrencyOwed0` and `expectedCurrencyOwed1`) define the **maximum** amount of currency we expect to get collect through accrued fees of each token in the pool. We set these through our guide's configuration. - -In a real world scenario, we can fetch the amount of fees that are owed to the Position through the `positions()` function of the NonfungiblePositionManager Contract. -We fetch the position info like in this code snippet taken from the [Fetching Positions guide](./03-fetching-positions.md): - -```typescript -const positionInfos = callResponses.map((position) => { - return { - tickLower: position.tickLower, - tickUpper: position.tickUpper, - liquidity: JSBI.BigInt(position.liquidity), - feeGrowthInside0LastX128: JSBI.BigInt(position.feeGrowthInside0LastX128), - feeGrowthInside1LastX128: JSBI.BigInt(position.feeGrowthInside1LastX128), - tokensOwed0: JSBI.BigInt(position.tokensOwed0), - tokensOwed1: JSBI.BigInt(position.tokensOwed1), - } -}) -``` - -The `tokensOwed0` and `tokensOwed1` values are the fees owed. - -In this example, we have the values hardcoded in the [`config.ts`](https://github.com/Uniswap/examples/blob/main/v3-sdk/collecting-fees/src/config.ts) file. - -## Submitting our fee collection transaction - -Next, we get the call parameters for collecting our fees from our `NonfungiblePositionManager` using the constructed `CollectOptions`: - -```typescript -const { calldata, value } = - NonfungiblePositionManager.collectCallParameters(collectOptions) -``` - -The function above returns the calldata and value required to construct the transaction for collecting accrued fees. Now that we have both the calldata and value we needed for the transaction, we can build and execute the it: - -```typescript -const transaction = { - data: calldata, - to: NONFUNGIBLE_POSITION_MANAGER_CONTRACT_ADDRESS, - value: value, - from: address, - maxFeePerGas: MAX_FEE_PER_GAS, - maxPriorityFeePerGas: MAX_PRIORITY_FEE_PER_GAS, -} - -const txRes = await wallet.sendTransaction(transaction) -``` - -After pressing the button, if someone has traded against our position, we should be able to note how the balance of USDC and DAI increases as we collect fees. - -## Next Steps - -The previous guides detail all the atomic steps needed to create and manage positions. However, these approaches may not use all of your desired currency. To ensure you are using your full funds while minimizing gas prices, check out our guide on [Swapping and Adding Liquidity](./05-swap-and-add-liquidity.md) in a single transaction! diff --git a/docs/sdk/v3/guides/liquidity/06-swap-and-add-liquidity.md b/docs/sdk/v3/guides/liquidity/06-swap-and-add-liquidity.md deleted file mode 100644 index 9c53cf3f2..000000000 --- a/docs/sdk/v3/guides/liquidity/06-swap-and-add-liquidity.md +++ /dev/null @@ -1,200 +0,0 @@ ---- -id: swap-and-add -title: Swapping and Adding Liquidity ---- - -## Introduction - -This guide will cover how to execute a swap-and-add operation in a single atomic transaction. It is based on the [swap-and-add example](https://github.com/Uniswap/examples/tree/main/v3-sdk/swap-and-add-liquidity), found in the t1 code examples [repository](https://github.com/Uniswap/examples). To run this example, check out the examples's [README](https://github.com/Uniswap/examples/tree/main/v3-sdk/swap-and-add-liquidity) and follow the setup instructions. - -:::info -If you need a briefer on the SDK and to learn more about how these guides connect to the examples repository, please visit our [background](../01-background.md) page! -::: - -When adding liquidity to a t1 v3 pool, you must provide two assets in a particular ratio. In many cases, your contract or the user's wallet hold a different ratio of those two assets. In order to deposit 100% of your assets, you must first swap your assets to the optimal ratio and then add liquidity. - -However, the swap may shift the balance of the pool and thus change the optimal ratio. To avoid that, we can execute this swap-and-add liquidity operation in an atomic fashion, using a router. The inputs to our guide are the **two tokens** that we are pooling for, the **amount** of each token we are pooling for, the **amount** of each token to swap-and-add, and the Pool **fee**. - -The guide will **cover**: - -1. Setup a router instance -2. Configuring our ratio calculation -3. Calculating our currency ratio -4. Constructing and executing our swap-and-add transaction - -At the end of the guide, given the inputs above, we should be able swap-and-add liquidity using 100% of the input assets with the press of a button and see the change reflected in our position and the balance of our tokens. - -For this guide, the following t1 packages are used: - -- [`@uniswap/v3-sdk`](https://www.npmjs.com/package/@uniswap/v3-sdk) -- [`@uniswap/sdk-core`](https://www.npmjs.com/package/@uniswap/sdk-core) -- [`@uniswap/smart-order-router`](https://www.npmjs.com/package/@uniswap/smart-order-router) - -The core code of this guide can be found in [`swapAndAddLiquidity()`](https://github.com/Uniswap/examples/blob/main/v3-sdk/swap-and-add-liquidity/src/libs/liquidity.ts#L48). - -:::note -This guide assumes you are familiar with our [Minting a Position](./01-minting-position.md) guide. A minted position is required to add or remove liquidity from, so the buttons will be disabled until a position is minted. - -Also note that we do not need to give approval to the `NonfungiblePositionManager` to transfer our tokens as we will have already done that when minting our position. -::: - -## Setup a router instance - -The first step is to approve the `SwapRouter` smart contract to spend our tokens for us in order for us to add liquidity to our position: - -```typescript -const tokenInApproval = await getTokenTransferApproval( - token0, - V3_SWAP_ROUTER_ADDRESS -) - -const tokenOutApproval = await getTokenTransferApproval( - token1, - V3_SWAP_ROUTER_ADDRESS -) -``` - -We described the `getTokenTransferApproval` function [here](./02-minting-position.md#giving-approval-to-transfer-our-tokens). - -Then we can setup our router, the [`AlphaRouter`](https://github.com/Uniswap/smart-order-router/blob/97c1bb7cb64b22ebf3509acda8de60c0445cf250/src/routers/alpha-router/alpha-router.ts#L333), which is part of the [smart-order-router package](https://www.npmjs.com/package/@uniswap/smart-order-router). The router requires a `chainId` and a `provider` to be initialized. Note that routing is not supported for local forks, so we will use a mainnet provider even when swapping on a local fork: - -```typescript -import { ethers } from 'ethers' -import { AlphaRouter } from '@uniswap/smart-order-router' - -const provider = new ethers.providers.JsonRpcProvider(rpcUrl) - -const router = new AlphaRouter({ chainId: 1, provider }) -``` - -For a more detailed example, check out our [routing guide](../trading/03-routing.md). - -## Configuring our ratio calculation - -Having created the router, we now need to construct the parameters required to make a call to its `routeToRatio` function, which will ensure the ratio of currency used matches the pool's required ratio to add our total liquidity. This will require the following parameters: - -The first two parameters are the currency amounts we use as input to the `routeToRatio` algorithm: - -```typescript -import { CurrencyAmount } from '@uniswap/sdk-core' - -const token0CurrencyAmount = CurrencyAmount.fromRawAmount( - token0, - fromReadableAmount( - token0AmountToAdd, - token0.decimals - ) -) - -const token1CurrencyAmount = CurrencyAmount.fromRawAmount( - token1, - fromReadableAmount( - token1AmountToAdd, - token1.decimals - ) -) -``` - -Next, we will create a placeholder position with a liquidity of `1` since liquidity is still unknown and will be set inside the call to `routeToRatio`: - -```typescript -import { Pool, Position, nearestUsableTick } from '@uniswap/v3-sdk' - -const placeholderPosition = new Position{ - pool, - liquidity: 1, - tickLower: - nearestUsableTick(pool.tickCurrent, pool.tickSpacing) - - pool.tickSpacing * 2, - tickUpper: - nearestUsableTick(pool.tickCurrent, pool.tickSpacing) + - poolInfo.tickSpacing * 2 -} -``` - -We then need to create an instance of `SwapAndAddConfig` which will set additional configuration parameters for the `routeToRatio` algorithm: - -- `ratioErrorTolerance` determines the margin of error the resulting ratio can have from the optimal ratio. -- `maxIterations` determines the maximum times the algorithm will iterate to find a ratio within error tolerance. If max iterations is exceeded, an error is returned. The benefit of running the algorithm more times is that we have more chances to find a route, but more iterations will longer to execute. We've used a default of 6 in our example. - -```typescript -import { Fraction } from '@uniswap/sdk-core' -import { SwapAndAddConfig } from '@uniswap/smart-order-router' - -const swapAndAddConfig: SwapAndAddConfig = { - ratioErrorTolerance: new Fraction(1, 100), - maxIterations: 6, -} -``` - -Finally, we will create an instance of `SwapAndAddOptions` to configure which position we are adding liquidity to and our defined swapping parameters in two different objects: - -- **`swapConfig`** configures the `recipient` of leftover dust from swap, `slippageTolerance` and a `deadline` for the swap. -- **`addLiquidityOptions`** must contain a `tokenId` to add to an existing position - -```typescript -import { SwapAndAddOptions } from '@uniswap/smart-order-router' - -const swapAndAddOptions: SwapAndAddOptions = { - swapOptions: { - type: SwapType.SWAP_ROUTER_02, - recipient: address, - slippageTolerance: new Percent(50, 10_000), - deadline: Math.floor(Date.now() / 1000) + 60 * 20, - }, - addLiquidityOptions: { - tokenId: positionId, - }, -} -``` - -## Calculating our currency ratio - -Having constructed all the parameters we need to call `routeToRatio`, we can now make the call to the function: - -```typescript -import { SwapToRatioResponse } from '@uniswap/smart-order-router' - -const routeToRatioResponse: SwapToRatioResponse = await router.routeToRatio( - token0CurrencyAmount, - token1CurrencyAmount, - currentPosition, - swapAndAddConfig, - swapAndAddOptions -) -``` - -The return type of the function call is [SwapToRatioResponse](https://github.com/Uniswap/smart-order-router/blob/97c1bb7cb64b22ebf3509acda8de60c0445cf250/src/routers/router.ts#L121). If a route was found successfully, this object will have two fields: the status (success) and the `SwapToRatioRoute` object. We check to make sure that both of those conditions hold true before we construct and submit the transaction: - -```typescript -import { SwapToRatioStatus } from '@uniswap/smart-order-router' - -if ( - !routeToRatioResponse || - routeToRatioResponse.status !== SwapToRatioStatus.SUCCESS -) { - // Handle Failed Transaction -} -``` - -In case a route was not found, we return from the function a `Failed` state for the transaction. - -## Constructing and executing our swap-and-add transaction - -After making sure that a route was successfully found, we can now construct and send the transaction. The response (`SwapToRatioRoute`) will have the properties we need to construct our transaction object: - -```typescript -import { SwapToRatioRoute } from '@uniswap/smart-order-router' - -const route: SwapToRatioRoute = routeToRatioResponse.result -const transaction = { - data: route.methodParameters?.calldata, - to: V3_SWAP_ROUTER_ADDRESS, - value: route.methodParameters?.value, - from: address, -} - -const txRes = await wallet.sendTransaction(transaction) -``` - -If the transaction was successful, our swap-and-add will be completed! We should see our input token balances decrease and our position balance should be increased accordingly. diff --git a/docs/sdk/v3/guides/liquidity/_category_.json b/docs/sdk/v3/guides/liquidity/_category_.json deleted file mode 100644 index 1a66cbbe2..000000000 --- a/docs/sdk/v3/guides/liquidity/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "label": "Pooling Liquidity", - "position": 5, - "collapsed": true -} diff --git a/docs/sdk/v3/guides/swaps/01-quoting.md b/docs/sdk/v3/guides/swaps/01-quoting.md deleted file mode 100644 index f0e48b449..000000000 --- a/docs/sdk/v3/guides/swaps/01-quoting.md +++ /dev/null @@ -1,229 +0,0 @@ ---- -id: quoting -title: Getting a Quote ---- - -## Introduction - -This guide will cover how to get the current quotes for any token pair on the t1 protocol. It is based on the [Quoting code example](https://github.com/Uniswap/examples/tree/main/v3-sdk/quoting), found in the t1 code examples [repository](https://github.com/Uniswap/examples). To run this example, check out the examples's [README](https://github.com/Uniswap/examples/blob/main/v3-sdk/quoting/README.md) and follow the setup instructions. - -:::info -If you need a briefer on the SDK and to learn more about how these guides connect to the examples repository, please visit our [background](../01-background.md) page! -::: - -In this example we will use `quoteExactInputSingle` to get a quote for the pair **USDC - WETH**. -The inputs are the **token in**, the **token out**, the **amount in** and the **fee**. - -The **fee** input parameters represents the swap fee that distributed to all in range liquidity at the time of the swap. It is one of the identifiers of a Pool, the others being **tokenIn** and **tokenOut**. - -The guide will **cover**: - -1. Computing the Pool's deployment address -2. Referencing the Pool contract and fetching metadata -3. Referencing the Quoter contract and getting a quote - -At the end of the guide, we should be able to fetch a quote for the given input token pair and the input token amount with the press of a button on the web application. - -For this guide, the following t1 packages are used: - -- [`@uniswap/v3-sdk`](https://www.npmjs.com/package/@uniswap/v3-sdk) -- [`@uniswap/sdk-core`](https://www.npmjs.com/package/@uniswap/sdk-core) - -The core code of this guide can be found in [`quote.ts`](https://github.com/Uniswap/examples/blob/main/v3-sdk/quoting/src/libs/quote.ts) - -## Example configuration - -We will use the example configuration `CurrentConfig` in most code snippets of this guide. It has the format: - -```typescript -import { Token } from '@uniswap/sdk-core' - -interface ExampleConfig { - rpc: { - local: string - mainnet: string - } - tokens: { - in: Token - amountIn: number - out: Token - poolFee: number - } -} - -export const CurrentConfig: ExampleConfig = {...} -``` - -The default config of the example uses a local fork of mainnet. If you haven't already, check out our [local development guide](../02-local-development.md). -To change the rpc endpoint or the Pool used, edit the [`Currentconfig`](https://github.com/Uniswap/examples/blob/main/v3-sdk/quoting/src/config.ts#L21). -To connect to mainnet directly, set the `mainnet` field in the config: - -```typescript -export const CurrentConfig: ExampleConfig = { - rpc: { - local: 'http://localhost:8545', - mainnet: 'https://mainnet.infura.io/v3/0ac57a06f2994538829c14745750d721', - }, - tokens: { - in: USDC_TOKEN, - amountIn: 1000, - out: WETH_TOKEN, - poolFee: FeeAmount.MEDIUM, - }, -} -``` - -The pool used is defined by a pair of tokens in [`constants.ts`](https://github.com/Uniswap/examples/blob/main/v3-sdk/quoting/src/libs/constants.ts#L14). -You can also change these two tokens and the fee of the pool in the config, just make sure a Pool actually exists for your configuration. -Check out the top pools on [Uniswap info](https://info.uniswap.org/#/pools). - -## Computing the Pool's deployment address - -To interact with the **USDC - WETH** Pool contract, we first need to compute its deployment address. -If you haven't worked directly with smart contracts yet, check out this [guide](https://docs.alchemy.com/docs/smart-contract-basics) from Alchemy. -The SDK provides a utility method for that: - -```typescript -import { computePoolAddress } from '@uniswap/v3-sdk' - -const currentPoolAddress = computePoolAddress({ - factoryAddress: POOL_FACTORY_CONTRACT_ADDRESS, - tokenA: CurrentConfig.tokens.in, - tokenB: CurrentConfig.tokens.out, - fee: CurrentConfig.tokens.poolFee, -}) -``` - -Since each *Uniswap V3 Pool* is uniquely identified by 3 characteristics (token in, token out, fee), we use those -in combination with the address of the *PoolFactory* contract to compute the address of the **USDC - ETH** Pool. -These parameters have already been defined in our [constants.ts](https://github.com/Uniswap/examples/blob/main/v3-sdk/quoting/src/libs/constants.ts#L14) file: - -```typescript -const WETH_TOKEN = new Token( - 1, - '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', - 18, - 'WETH', - 'Wrapped Ether' -) - -const USDC_TOKEN = new Token( - 1, - '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', - 6, - 'USDC', - 'USD//C' -) -``` - -These constants are used in the `config.ts` file, as mentioned in the Introduction. - -We can find the Pool Factory Contract address for our chain [here](../../../../contracts/v3/reference/Deployments.md). - -## Referencing the Pool contract and fetching metadata - -Now that we have the deployment address of the **USDC - ETH** Pool, we can construct an instance of an **ethers** `Contract` to interact with it: - -```typescript -import { ethers } from 'ethers' - -const provider = new ethers.providers.JsonRpcProvider(rpcUrl) -const poolContract = new ethers.Contract( - currentPoolAddress, - IUniswapV3PoolABI.abi, - provider -) -``` - -To construct the *Contract* we need to provide the address of the contract, its ABI and the provider that will carry out the RPC call for us. -We get access to the contract's ABI through the [@uniswap/v3-core](https://www.npmjs.com/package/@uniswap/v3-core) package, which holds the core smart contracts of the t1 V3 protocol: - -```typescript -import IUniswapV3PoolABI from '@uniswap/v3-core/artifacts/contracts/interfaces/IUniswapV3Pool.sol/IUniswapV3Pool.json' -``` - -Having constructed our reference to the contract, we can now access its methods through our provider. -We use a batch `Promise` call. This approach queries state data concurrently, rather than sequentially, to minimize the chance of fetching out of sync data that may be returned if sequential queries are executed over the span of two blocks: - -```typescript -const [token0, token1, fee, liquidity, slot0] = await Promise.all([ - poolContract.token0(), - poolContract.token1(), - poolContract.fee(), - poolContract.liquidity(), - poolContract.slot0(), -]) -``` - -The return values of these methods will become inputs to the quote fetching function. -The `token0` and `token1` variables are the addresses of the tokens in the Pool and should not be mistaken for `Token` objects from the sdk. -For the full code, check out [`getPoolConstants()`](https://github.com/Uniswap/examples/blob/main/v3-sdk/quoting/src/libs/quote.ts#L35) in `quote.ts`. - -:::note -In this example, the metadata we fetch is already present in our inputs. This guide fetches this information first in order to show how to fetch any metadata, which will be expanded on in future guides. -::: - -## Referencing the Quoter contract and getting a quote - -To get quotes for trades, t1 has deployed a **Quoter Contract**. We will use this contract to fetch the output amount we can expect for our trade, without actually executing the trade. -Check out the full code for the following snippets in [quote.ts](https://github.com/Uniswap/examples/blob/main/v3-sdk/quoting/src/libs/quote.ts) - -Like we did for the Pool contract, we need to construct an instance of an **ethers** `Contract` for our Quoter contract in order to interact with it: - -```typescript -const quoterContract = new ethers.Contract( - QUOTER_CONTRACT_ADDRESS, - Quoter.abi, - getProvider() -) -``` - -We get access to the contract's ABI through the [@uniswap/v3-periphery](https://www.npmjs.com/package/@uniswap/v3-periphery) package, which holds the periphery smart contracts of the t1 V3 protocol: - -```typescript -import Quoter from '@uniswap/v3-periphery/artifacts/contracts/lens/Quoter.sol/Quoter.json' -``` - -We get the QUOTE_CONTRACT_ADDRESS for our chain from [Github](https://github.com/Uniswap/v3-periphery/blob/main/deploys.md). - -We can now use our Quoter contract to obtain the quote. - -In an ideal world, the quoter functions would be `view` functions, which would make them very easy to query on-chain with minimal gas costs. However, the t1 V3 Quoter contracts rely on state-changing calls designed to be reverted to return the desired data. This means calling the quoter will be very expensive and should not be called on-chain. - -To get around this difficulty, we can use the `callStatic` method provided by the **ethers.js** `Contract` instances. -This is a useful method that submits a state-changing transaction to an Ethereum node, but asks the node to simulate the state change, rather than to execute it. Our script can then return the result of the simulated state change: - -```typescript -const quotedAmountOut = await quoterContract.callStatic.quoteExactInputSingle( - token0, - token1, - fee, - fromReadableAmount( - CurrentConfig.tokens.amountIn, - CurrentConfig.tokens.in.decimals - ).toString(), - 0 -) -``` - -The `fromReadableAmount()` function creates the amount of the smallest unit of a token from the full unit amount and the decimals. - -The result of the call is the number of output tokens you'd receive for the quoted swap. - -It should be noted that `quoteExactInputSingle` is only 1 of 4 different methods that the quoter offers: - -1. `quoteExactInputSingle` - given the amount you want to swap, produces a quote for the amount out for a swap of a single pool -2. `quoteExactInput` - given the amount you want to swap, produces a quote for the amount out for a swap over multiple pools -3. `quoteExactOutputSingle` - given the amount you want to get out, produces a quote for the amount in for a swap over a single pool -4. `quoteExactOutput` - given the amount you want to get out, produces a quote for the amount in for a swap over multiple pools - -If we want to trade two tokens that do not share a pool with each other, we will need to make swaps over multiple pools. -This is where the `quoteExactInput` and `quoteExactOutput` methods come in. -We will dive deeper into routing in the [routing guide](03-routing.md). - -For the `exactOutput` and `exactOutputSingle` methods, we need to keep in mind that a pool can not give us more than the amount of Tokens it holds. -If we try to get a quote on an output of 100 WETH from a Pool that only holds 50 WETH, the function call will fail. - -## Next Steps - -Now that you're able to make a quote, check out our next guide on [trading](./02-trading.md) using this quote! diff --git a/docs/sdk/v3/guides/swaps/02-trading.md b/docs/sdk/v3/guides/swaps/02-trading.md deleted file mode 100644 index f3a268197..000000000 --- a/docs/sdk/v3/guides/swaps/02-trading.md +++ /dev/null @@ -1,312 +0,0 @@ ---- -id: trading -title: Executing a Trade ---- - -## Introduction - -This guide will build off our [quoting guide](./01-quoting.md) and show how to use a quote to construct and execute a trade on the t1 V3 protocol. It is based on the [Trading code example](https://github.com/Uniswap/examples/tree/main/v3-sdk/trading), found in the t1 code examples [repository](https://github.com/Uniswap/examples). To run this example, check out the guide's [README](https://github.com/Uniswap/examples/blob/main/v3-sdk/trading/README.md) and follow the setup instructions. - -:::info -If you need a briefer on the SDK and to learn more about how these guides connect to the examples repository, please visit our [background](../01-background.md) page! - -To get started with local development, also check out the [local development guide](../02-local-development.md). -::: - -In this example we will trade between two ERC20 tokens: **WETH and USDC**. The tokens, amount of input token, and the fee level can be configured as inputs. - -The guide will **cover**: - -1. Constructing a route from pool information -2. Constructing an unchecked trade -3. Executing a trade - -At the end of the guide, we should be able to create and execute a trade between any two ERC20 tokens using the example's included UI. - -:::note -Included in the example application is functionality to wrap/unwrap ETH as needed to fund the example `WETH` to `USDC` swap directly from an `ETH` balance. -::: - -For this guide, the following t1 packages are used: - -- [`@uniswap/v3-sdk`](https://www.npmjs.com/package/@uniswap/v3-sdk) -- [`@uniswap/sdk-core`](https://www.npmjs.com/package/@uniswap/sdk-core) - -The core code of this guide can be found in [`trading.ts`](https://github.com/Uniswap/examples/blob/main/v3-sdk/trading/src/libs/trading.ts) - -## Using a wallet extension - -Like in the previous guide, our [example](https://github.com/Uniswap/examples/blob/main/v3-sdk/trading) uses a [config file ](https://github.com/Uniswap/examples/blob/main/v3-sdk/trading/src/config.ts) to configurate the inputs used. -The strucuture is similar to the quoting config, but we also have the option to select an environment: - -```typescript -export interface ExampleConfig { - env: Environment - rpc: { - local: string - mainnet: string - } - wallet: { - address: string - privateKey: string - } - tokens: { - in: Token - amountIn: number - out: Token - poolFee: number - } -} -``` - -Per default, the env field is set to `Environment.LOCAL`: - -```typescript -export const CurrentConfig: ExampleConfig = { - env: Environment.LOCAL, - rpc: { - local: 'http://localhost:8545', - mainnet: '', - }, - wallet: { - address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', - privateKey: - '0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80', - }, - tokens: { - in: WETH_TOKEN, - amountIn: 1, - out: USDC_TOKEN, - poolFee: FeeAmount.MEDIUM, - }, -} -``` - -In this example, we have the option to use a Wallet Extension like Metamask to sign the transactions we are sending. To do so, let's change the Environment to `Environment.WALLET_EXTENSION`: - -```typescript -export const CurrentConfig: ExampleConfig = { - env: Environment.WALLET_EXTENSION, - rpc: { - local: 'http://localhost:8545', - }, - wallet: { - ... - }, - tokens: { - ... - }, -} -``` - -Run the example and then add the local network to your wallet browser extension, if you are using Metamask for example, follow [this guide](https://support.metamask.io/hc/en-us/articles/360043227612-How-to-add-a-custom-network-RPC). -You should also import a private key to use on your local network, for example `0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80` from Foundry's example wallets. - -Consider checking out the [README](https://github.com/Uniswap/examples/blob/main/v3-sdk/trading/README.md) of the example. - -If you cannot see the Tokens traded in your wallet, you possibly have to [import them](https://support.metamask.io/hc/en-us/articles/360015489031-How-to-display-tokens-in-MetaMask). - -## Constructing a route from pool information - -To construct our trade, we will first create an model instance of a `Pool`. We create an **ethers** contract like in the [previous guide](./01-quoting.md#referencing-the-pool-contract-and-fetching-metadata). -We will first extract the needed metadata from the relevant pool contract. Metadata includes both constant information about the pool as well as information about its current state stored in its first slot: - -```typescript -async function getPoolInfo() { - const [token0, token1, fee, liquidity, slot0] = - await Promise.all([ - poolContract.fee(), - poolContract.liquidity(), - poolContract.slot0(), - ]) - - return { - fee, - liquidity, - sqrtPriceX96: slot0[0], - tick: slot0[1], - } -} -``` - -Before continuing, let's talk about the values we fetched here and what they represent: - -- `fee` is the fee that is taken from every swap that is executed on the pool in 1 per million - if the `fee` value of a pool is 500, ```500/ 1000000``` (or 0.05%) of the trade amount is taken as a fee. This fee goes to the liquidity providers of the Pool. -- `liquidity` is the amount of liquidity the Pool can use for trades at the current price. -- `sqrtPriceX96` is the current Price of the pool, encoded as a ratio between `token0` and `token1`. -- `tick` is the tick at the current price of the pool. - -Check out the [whitepaper](https://uniswap.org/whitepaper-v3.pdf) to learn more on how liquidity and ticks work in t1 V3. - -You can find the full code in [`pool.ts`](https://github.com/Uniswap/examples/blob/main/v3-sdk/trading/src/libs/pool.ts). - -Using this metadata along with our inputs, we will then construct a `Pool`: - -```typescript -const poolInfo = await getPoolInfo() - -const pool = new Pool( - CurrentConfig.tokens.in, - CurrentConfig.tokens.out, - CurrentConfig.tokens.poolFee, - poolInfo.sqrtPriceX96.toString(), - poolInfo.liquidity.toString(), - poolInfo.tick -) -``` - -## Creating a Route - -With this `Pool`, we can now construct a route to use in our trade. Routes represent a route over one or more pools from one Token to another. Let's imagine we have three pools: - -``` -- PoolA: USDC/ WETH -- PoolB: USDT/ WETH -- PoolC: USDT/ DAI -``` - -We would like to trade from USDC to DAI, so we create a route through our 3 pools: - -``` -PoolA -> PoolB -> PoolC -``` - -The `Route` object can find this route from an array of given pools and an input and output Token. - -To keep it simple for this guide, we only swap over one Pool: - -```typescript -import { Route } from '@uniswap/v3-sdk' - -const swapRoute = new Route( - [pool], - CurrentConfig.tokens.in, - CurrentConfig.tokens.out -) -``` - -Our `Route` understands that `CurrentConfig.tokens.in` should be traded for `CurrentConfig.tokens.out` over the Array of pools `[pool]`. - - -## Constructing an unchecked trade - -Once we have constructed the route object, we now need to obtain a quote for the given `inputAmount` of the example: - -```typescript -const amountOut = await getOutputQuote(swapRoute) -``` - -As shown below, the quote is obtained using the `v3-sdk`'s `SwapQuoter`, in contrast to the [previous quoting guide](./01-quoting.md), where we directly accessed the smart contact: - -```typescript -import { SwapQuoter } from '@uniswap/v3-sdk' -import { CurrencyAmount, TradeType } from '@uniswap/sdk-core' - -const { calldata } = await SwapQuoter.quoteCallParameters( - swapRoute, - CurrencyAmount.fromRawAmount( - CurrentConfig.tokens.in, - fromReadableAmount( - CurrentConfig.tokens.amountIn, - CurrentConfig.tokens.in.decimals - ) - ), - TradeType.EXACT_INPUT, - { - useQuoterV2: true, - } -) -``` - -The `SwapQuoter`'s `quoteCallParameters` function, gives us the calldata needed to make the call to the `Quoter`, and we then decode the returned quote: - -```typescript -const quoteCallReturnData = await provider.call({ - to: QUOTER_CONTRACT_ADDRESS, - data: calldata, -}) - -return ethers.utils.defaultAbiCoder.decode(['uint256'], quoteCallReturnData) -``` - -With the quote and the route, we can now construct a trade using the route in addition to the output amount from a quote based on our input. -Because we already know the expected output of our Trade, we do not have to check it again. We can use the `uncheckedTrade` function to create our Trade: - -```typescript -import { Trade } from 'uniswap/v3-sdk' -import { CurrencyAmount, TradeType } from '@uniswap/sdk-core' -import JSBI from 'jsbi' - -const uncheckedTrade = Trade.createUncheckedTrade({ - route: swapRoute, - inputAmount: CurrencyAmount.fromRawAmount( - CurrentConfig.tokens.in, - fromReadableAmount( - CurrentConfig.tokens.amountIn, - CurrentConfig.tokens.in.decimals - ) - ), - outputAmount: CurrencyAmount.fromRawAmount( - CurrentConfig.tokens.out, - JSBI.BigInt(amountOut) - ), - tradeType: TradeType.EXACT_INPUT, -}) -``` - -This example uses an exact input trade, but we can also construct a trade using exact output assuming we adapt our quoting code accordingly. - -## Executing a trade - -Once we have created a trade, we can now execute this trade with our provider. First, we must give the `SwapRouter` approval to spend our tokens for us: - -```typescript -const tokenApproval = await getTokenTransferApproval(CurrentConfig.tokens.in) -``` - -You can find the approval function [here](https://github.com/Uniswap/examples/blob/main/v3-sdk/trading/src/libs/trading.ts#L151). -We will use this function or similar implementations in most guides. - -Then, we set our options that define how much time and slippage can occur in our execution as well as the address to use for our wallet: - -```typescript -import { SwapOptions } from '@uniswap/v3-sdk' -import { Percent } from '@uniswap/sdk-core' - -const options: SwapOptions = { - slippageTolerance: new Percent(50, 10_000), // 50 bips, or 0.50% - deadline: Math.floor(Date.now() / 1000) + 60 * 20, // 20 minutes from the current Unix time - recipient: walletAddress, -} -``` - -The slippage of our trade is the maximum decrease from our calculated output amount that we are willing to accept for this trade. -The deadline is the latest point in time when we want the transaction to go through. -If we set this value too high, the transaction could be left waiting for days and we would need to pay gas fees to cancel it. - -Next, we use the `SwapRouter` class, a representation of the t1 [SwapRouter Contract](https://github.com/Uniswap/v3-periphery/blob/v1.0.0/contracts/SwapRouter.sol), to get the associated call parameters for our trade and options: - -```typescript -import { SwapRouter } from '@uniswap/v3-sdk' - -const methodParameters = SwapRouter.swapCallParameters([uncheckedTrade], options) -``` - -Finally, we can construct a transaction from the method parameters and send the transaction: - -```typescript -const tx = { - data: methodParameters.calldata, - to: SWAP_ROUTER_ADDRESS, - value: methodParameters.value, - from: walletAddress, - maxFeePerGas: MAX_FEE_PER_GAS, - maxPriorityFeePerGas: MAX_PRIORITY_FEE_PER_GAS, -} - -const res = await wallet.sendTransaction(tx) -``` - -## Next Steps - -The resulting example allows for trading between any two ERC20 tokens, but this can be suboptimal for the best pricing and fees. To achieve the best possible price, we use the t1 auto router to route through pools to get an optimal cost. Our [routing](./03-routing.md) guide will show you how to use this router and execute optimal swaps. diff --git a/docs/sdk/v3/guides/swaps/03-routing.md b/docs/sdk/v3/guides/swaps/03-routing.md deleted file mode 100644 index 41d6bef9b..000000000 --- a/docs/sdk/v3/guides/swaps/03-routing.md +++ /dev/null @@ -1,187 +0,0 @@ ---- -id: routing -title: Routing a Swap ---- - -## Introduction - -This guide will cover how to use t1's smart order router to compute optimal routes and execute swaps. Rather than trading between a single pool, smart routing may use multiple hops (as many as needed) to ensure that the end result of the swap is the optimal price. It is based on the [routing code example](https://github.com/Uniswap/examples/tree/main/v3-sdk/routing), found in the t1 code examples [repository](https://github.com/Uniswap/examples). To run this example, check out the guide's [README](https://github.com/Uniswap/examples/blob/main/v3-sdk/routing/README.md) and follow the setup instructions. - -:::info -If you need a briefer on the SDK and to learn more about how these guides connect to the examples repository, please visit our [background](./01-background.md) page! -::: - -In this example we will trade between **WETH and USDC**, but you can configure your example to use any two currencies and amount of input currency. - -The guide will **cover**: - -1. Creating a router instance -2. Creating a route -3. Swapping using a route - -At the end of the guide, we should be able to create a route and and execute a swap between any two currencies tokens using the example's included UI. - -For this guide, the following t1 packages are used: - -- [`@uniswap/v3-sdk`](https://www.npmjs.com/package/@uniswap/v3-sdk) -- [`@uniswap/sdk-core`](https://www.npmjs.com/package/@uniswap/sdk-core) -- [`@uniswap/smart-order-router`](https://www.npmjs.com/package/@uniswap/smart-order-router) - -The core code of this guide can be found in [`routing.ts`](https://github.com/Uniswap/examples/blob/main/v3-sdk/routing/src/libs/routing.ts) - -The config, which we will use in some code snippets in this guides has this structure: - -```typescript -import { Token } from '@uniswap/sdk-core' - -interface ExampleConfig { - env: Environment - rpc: { - local: string - mainnet: string - } - wallet: { - address: string - privateKey: string - } - tokens: { - in: Token - amountIn: number - out: Token - } -} - -export const CurrentConfig: ExampleConfig = {...} -``` - -## Creating a router instance - -To compute our route, we will use the `@uniswap/smart-order-router` package, specifically the `AlphaRouter` class which requires a `chainId` and a `provider`. Note that routing is not supported for local forks, so we will use a mainnet provider even when swapping on a local fork: - -```typescript -import { AlphaRouter, ChainId } from '@uniswap/smart-order-router' - -const provider = new ethers.providers.JsonRpcProvider(rpcUrl) - -const router = new AlphaRouter({ - chainId: ChainId.MAINNET, - provider, -}) -``` - -## Creating a route - -We will use the [SwapRouter02](https://github.com/Uniswap/v3-periphery/blob/v1.0.0/contracts/SwapRouter.sol) for our trade. -The `smart-order-router` package provides us with a `SwapOptionsSwapRouter02` interface, defining the wallet to use, slippage tolerance, and deadline for the transaction that we need to interact with the contract: - -```typescript -import { SwapOptionsSwapRouter02, SwapType } from '@uniswap/smart-order-router' -import { Percent } from '@uniswap/sdk-core' - -const options: SwapOptionsSwapRouter02 = { - recipient: CurrentConfig.wallet.address, - slippageTolerance: new Percent(50, 10_000), - deadline: Math.floor(Date.now() / 1000 + 1800), - type: SwapType.SWAP_ROUTER_02, -} -``` - -Like explained in the [previous guide](./02-trading.md#executing-a-trade), it is important to set the parameters to sensible values. - -Using these options, we can now create a trade (`TradeType.EXACT_INPUT` or `TradeType.EXACT_OUTPUT`) with the currency and the input amount to use to get a quote. For this example, we'll use an `EXACT_INPUT` trade to get a quote outputted in the quote currency. - -```typescript -import { CurrencyAmount, TradeType } from '@uniswap/sdk-core' - -const rawTokenAmountIn: JSBI = fromReadableAmount( - CurrentConfig.currencies.amountIn, - CurrentConfig.currencies.in.decimals - ) - -const route = await router.route( - CurrencyAmount.fromRawAmount( - CurrentConfig.currencies.in, - rawTokenAmountIn - ), - CurrentConfig.currencies.out, - TradeType.EXACT_INPUT, - options -) -``` - -The `fromReadableAmount` function calculates the amount of tokens in the Token's smallest unit from the full unit and the Token's decimals: - -```typescript title="src/libs/conversion.ts" -export function fromReadableAmount(amount: number, decimals: number): JSBI { - const extraDigits = Math.pow(10, countDecimals(amount)) - const adjustedAmount = amount * extraDigits - return JSBI.divide( - JSBI.multiply( - JSBI.BigInt(adjustedAmount), - JSBI.exponentiate(JSBI.BigInt(10), JSBI.BigInt(decimals)) - ), - JSBI.BigInt(extraDigits) - ) -} -``` - -`route` and `route.methodParameters` are *optional* as the request can fail, for example if **no route exists** between the two Tokens or because of networking issues. -We check if the call was succesful: - -```typescript -if (!route || !route.methodParameters) { - // Handle failed request -} -``` - -Depending on our preferences and reason for the issue we could retry the request or throw an Error. - -## Swapping using a route - -First, we need to give approval to the `SwapRouter` smart contract to spend our tokens for us: - -```typescript -import { ethers } from 'ethers' -... - -const wallet = new ethers.Wallet(privateKey, provider) -const tokenContract = new ethers.Contract( - CurrentConfig.tokens.in.address, - ERC20ABI, - wallet -) -const tokenApproval = await tokenContract.approve( - V3_SWAP_ROUTER_ADDRESS, - ethers.BigNumber.from(rawTokenAmountIn.toString()) -) -``` - -To be able to spend the tokens of a wallet, a smart contract first needs to get an approval from that wallet. -ERC20 tokens have an `approve` function that accepts the address of the smart contract that we want to allow spending our tokens and the amount the smart contract should be allowed to spend. - -We can get the **V3_SWAP_ROUTER_ADDRESS** for our chain from [Github](https://github.com/Uniswap/v3-periphery/blob/main/deploys.md). -Keep in mind that different chains might have **different deployment addresses** for the same contracts. -The deployment address for local forks of a network are the same as in the network you forked, so for a **fork of mainnet** it would be the address for **Mainnet**. - -We need to wait one block for the approval transaction to be included by the blockchain. - -Once the approval has been granted, we can now execute the trade using the route's computed calldata, values, and gas values: - -```typescript -const txRes = await wallet.sendTransaction({ - data: route.methodParameters.calldata, - to: V3_SWAP_ROUTER_ADDRESS, - value: route.methodParameters.value, - from: wallet.address, - maxFeePerGas: MAX_FEE_PER_GAS, - maxPriorityFeePerGas: MAX_PRIORITY_FEE_PER_GAS, -}) -``` - -After swapping, you should see the currency balances update in the UI shortly after the block is confirmed. - -You can find the full code in [`routing.ts`](https://github.com/Uniswap/examples/blob/main/v3-sdk/routing/src/libs/routing.ts). - -## Next Steps - -Now that you're familiar with trading, consider checking out our next guides on [pooling liquidity](../liquidity/01-position-data.md) to t1! diff --git a/docs/sdk/v3/guides/swaps/_category_.json b/docs/sdk/v3/guides/swaps/_category_.json deleted file mode 100644 index 145573eb1..000000000 --- a/docs/sdk/v3/guides/swaps/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "label": "Swaps", - "position": 4, - "collapsed": true -} diff --git a/docs/sdk/v3/overview.md b/docs/sdk/v3/overview.md deleted file mode 100644 index 7ebb9a707..000000000 --- a/docs/sdk/v3/overview.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -id: overview -sidebar_position: 1 -title: Overview ---- -# The t1 V3 SDK - -> **Welcome to the V3 t1 SDK!** - -The t1 V3 SDK provides abstractions to assist you with interacting with the t1 V3 smart contracts in a Typescript/Javascript environment (e.g. websites, node scripts). It makes uses of the [**Core SDK**](../core/overview.md) to gain access to abstractions that are common amongst the t1 SDKs. With the SDK, you can manipulate data that has been queried from the [EVM](https://ethereum.org/en/developers/docs/evm/) using libraries that assist with needs such as data modeling, protection from rounding errors, and compile time enforced typing. - -To begin, we recommend looking at our [**Guides**](./guides/01-background.md) which include [runnable examples](https://github.com/Uniswap/examples/tree/main/v3-sdk) and walkthroughs of core usages. These guides will help you better understand how to use the SDK and integrate it into your application. - -For complete documentation of the SDK's offerings, see the [**Technical Reference**](./reference/overview.md). - -## Installation - -To interact with the V3 SDK we recommend installing though npm: - -```bash -npm i --save @uniswap/v3-sdk -npm i --save @uniswap/sdk-core -``` - -## Developer Links - -- [**V3 SDK Github Repo**](https://github.com/Uniswap/v3-sdk) -- [**Core SDK Github Repo**](https://github.com/Uniswap/sdk-core) -- [**V3 SDK NPM Package**](https://www.npmjs.com/package/@uniswap/v3-sdk) - -[![Unit Tests](https://github.com/Uniswap/uniswap-v3-sdk/workflows/Unit%20Tests/badge.svg)](https://github.com/Uniswap/uniswap-v3-sdk/actions?query=workflow%3A%22Unit+Tests%22) -[![Lint](https://github.com/Uniswap/uniswap-v3-sdk/workflows/Lint/badge.svg)](https://github.com/Uniswap/uniswap-v3-sdk/actions?query=workflow%3ALint) -[![npm version](https://img.shields.io/npm/v/@uniswap/v3-sdk/latest.svg)](https://www.npmjs.com/package/@uniswap/v3-sdk/v/latest) -[![npm bundle size (scoped version)](https://img.shields.io/bundlephobia/minzip/@uniswap/v3-sdk/latest.svg)](https://bundlephobia.com/result?p=@uniswap/v3-sdk@latest) -[![Discord](https://img.shields.io/badge/discord-join%20chat-blue.svg)](https://discord.com/channels/597638925346930701/607978109089611786) diff --git a/docs/sdk/v3/reference/_category_.json b/docs/sdk/v3/reference/_category_.json deleted file mode 100644 index 19b021994..000000000 --- a/docs/sdk/v3/reference/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "label": "Technical Reference", - "position": 3, - "collapsed": true -} diff --git a/docs/sdk/v3/reference/classes/FullMath.md b/docs/sdk/v3/reference/classes/FullMath.md deleted file mode 100644 index 2d8adca90..000000000 --- a/docs/sdk/v3/reference/classes/FullMath.md +++ /dev/null @@ -1,47 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / FullMath - -# Class: FullMath - -## Table of contents - -### Constructors - -- [constructor](FullMath.md#constructor) - -### Methods - -- [mulDivRoundingUp](FullMath.md#muldivroundingup) - -## Constructors - -### constructor - -• `Private` **new FullMath**() - -Cannot be constructed. - -#### Defined in - -[utils/fullMath.ts:8](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/fullMath.ts#L8) - -## Methods - -### mulDivRoundingUp - -▸ `Static` **mulDivRoundingUp**(`a`, `b`, `denominator`): `default` - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `a` | `default` | -| `b` | `default` | -| `denominator` | `default` | - -#### Returns - -`default` - -#### Defined in - -[utils/fullMath.ts:10](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/fullMath.ts#L10) diff --git a/docs/sdk/v3/reference/classes/LiquidityMath.md b/docs/sdk/v3/reference/classes/LiquidityMath.md deleted file mode 100644 index 62e4ed5fa..000000000 --- a/docs/sdk/v3/reference/classes/LiquidityMath.md +++ /dev/null @@ -1,46 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / LiquidityMath - -# Class: LiquidityMath - -## Table of contents - -### Constructors - -- [constructor](LiquidityMath.md#constructor) - -### Methods - -- [addDelta](LiquidityMath.md#adddelta) - -## Constructors - -### constructor - -• `Private` **new LiquidityMath**() - -Cannot be constructed. - -#### Defined in - -[utils/liquidityMath.ts:8](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/liquidityMath.ts#L8) - -## Methods - -### addDelta - -▸ `Static` **addDelta**(`x`, `y`): `default` - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `x` | `default` | -| `y` | `default` | - -#### Returns - -`default` - -#### Defined in - -[utils/liquidityMath.ts:10](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/liquidityMath.ts#L10) diff --git a/docs/sdk/v3/reference/classes/Multicall.md b/docs/sdk/v3/reference/classes/Multicall.md deleted file mode 100644 index 7c73e792d..000000000 --- a/docs/sdk/v3/reference/classes/Multicall.md +++ /dev/null @@ -1,59 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / Multicall - -# Class: Multicall - -## Table of contents - -### Constructors - -- [constructor](Multicall.md#constructor) - -### Properties - -- [INTERFACE](Multicall.md#interface) - -### Methods - -- [encodeMulticall](Multicall.md#encodemulticall) - -## Constructors - -### constructor - -• `Private` **new Multicall**() - -Cannot be constructed. - -#### Defined in - -[multicall.ts:10](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/multicall.ts#L10) - -## Properties - -### INTERFACE - -▪ `Static` **INTERFACE**: `Interface` - -#### Defined in - -[multicall.ts:5](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/multicall.ts#L5) - -## Methods - -### encodeMulticall - -▸ `Static` **encodeMulticall**(`calldatas`): `string` - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `calldatas` | `string` \| `string`[] | - -#### Returns - -`string` - -#### Defined in - -[multicall.ts:12](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/multicall.ts#L12) diff --git a/docs/sdk/v3/reference/classes/NoTickDataProvider.md b/docs/sdk/v3/reference/classes/NoTickDataProvider.md deleted file mode 100644 index 8e6a71bd7..000000000 --- a/docs/sdk/v3/reference/classes/NoTickDataProvider.md +++ /dev/null @@ -1,95 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / NoTickDataProvider - -# Class: NoTickDataProvider - -This tick data provider does not know how to fetch any tick data. It throws whenever it is required. Useful if you -do not need to load tick data for your use case. - -## Implements - -- [`TickDataProvider`](../interfaces/TickDataProvider.md) - -## Table of contents - -### Constructors - -- [constructor](NoTickDataProvider.md#constructor) - -### Properties - -- [ERROR\_MESSAGE](NoTickDataProvider.md#error_message) - -### Methods - -- [getTick](NoTickDataProvider.md#gettick) -- [nextInitializedTickWithinOneWord](NoTickDataProvider.md#nextinitializedtickwithinoneword) - -## Constructors - -### constructor - -• **new NoTickDataProvider**() - -## Properties - -### ERROR\_MESSAGE - -▪ `Static` `Private` **ERROR\_MESSAGE**: `string` = `'No tick data provider was given'` - -#### Defined in - -[entities/tickDataProvider.ts:27](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/tickDataProvider.ts#L27) - -## Methods - -### getTick - -▸ **getTick**(`_tick`): `Promise`<{ `liquidityNet`: `BigintIsh` }\> - -Return information corresponding to a specific tick - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `_tick` | `number` | the tick to load | - -#### Returns - -`Promise`<{ `liquidityNet`: `BigintIsh` }\> - -#### Implementation of - -[TickDataProvider](../interfaces/TickDataProvider.md).[getTick](../interfaces/TickDataProvider.md#gettick) - -#### Defined in - -[entities/tickDataProvider.ts:28](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/tickDataProvider.ts#L28) - -___ - -### nextInitializedTickWithinOneWord - -▸ **nextInitializedTickWithinOneWord**(`_tick`, `_lte`, `_tickSpacing`): `Promise`<[`number`, `boolean`]\> - -Return the next tick that is initialized within a single word - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `_tick` | `number` | The current tick | -| `_lte` | `boolean` | Whether the next tick should be lte the current tick | -| `_tickSpacing` | `number` | The tick spacing of the pool | - -#### Returns - -`Promise`<[`number`, `boolean`]\> - -#### Implementation of - -[TickDataProvider](../interfaces/TickDataProvider.md).[nextInitializedTickWithinOneWord](../interfaces/TickDataProvider.md#nextinitializedtickwithinoneword) - -#### Defined in - -[entities/tickDataProvider.ts:32](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/tickDataProvider.ts#L32) diff --git a/docs/sdk/v3/reference/classes/NonfungiblePositionManager.md b/docs/sdk/v3/reference/classes/NonfungiblePositionManager.md deleted file mode 100644 index 98647689d..000000000 --- a/docs/sdk/v3/reference/classes/NonfungiblePositionManager.md +++ /dev/null @@ -1,191 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / NonfungiblePositionManager - -# Class: NonfungiblePositionManager - -## Table of contents - -### Constructors - -- [constructor](NonfungiblePositionManager.md#constructor) - -### Properties - -- [INTERFACE](NonfungiblePositionManager.md#interface) - -### Methods - -- [addCallParameters](NonfungiblePositionManager.md#addcallparameters) -- [collectCallParameters](NonfungiblePositionManager.md#collectcallparameters) -- [createCallParameters](NonfungiblePositionManager.md#createcallparameters) -- [encodeCollect](NonfungiblePositionManager.md#encodecollect) -- [encodeCreate](NonfungiblePositionManager.md#encodecreate) -- [removeCallParameters](NonfungiblePositionManager.md#removecallparameters) -- [safeTransferFromParameters](NonfungiblePositionManager.md#safetransferfromparameters) - -## Constructors - -### constructor - -• `Private` **new NonfungiblePositionManager**() - -Cannot be constructed. - -#### Defined in - -[nonfungiblePositionManager.ts:181](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L181) - -## Properties - -### INTERFACE - -▪ `Static` **INTERFACE**: `Interface` - -#### Defined in - -[nonfungiblePositionManager.ts:176](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L176) - -## Methods - -### addCallParameters - -▸ `Static` **addCallParameters**(`position`, `options`): [`MethodParameters`](../interfaces/MethodParameters.md) - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `position` | [`Position`](Position.md) | -| `options` | [`AddLiquidityOptions`](../modules.md#addliquidityoptions) | - -#### Returns - -[`MethodParameters`](../interfaces/MethodParameters.md) - -#### Defined in - -[nonfungiblePositionManager.ts:199](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L199) - -___ - -### collectCallParameters - -▸ `Static` **collectCallParameters**(`options`): [`MethodParameters`](../interfaces/MethodParameters.md) - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `options` | [`CollectOptions`](../interfaces/CollectOptions.md) | - -#### Returns - -[`MethodParameters`](../interfaces/MethodParameters.md) - -#### Defined in - -[nonfungiblePositionManager.ts:326](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L326) - -___ - -### createCallParameters - -▸ `Static` **createCallParameters**(`pool`): [`MethodParameters`](../interfaces/MethodParameters.md) - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `pool` | [`Pool`](Pool.md) | - -#### Returns - -[`MethodParameters`](../interfaces/MethodParameters.md) - -#### Defined in - -[nonfungiblePositionManager.ts:192](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L192) - -___ - -### encodeCollect - -▸ `Static` `Private` **encodeCollect**(`options`): `string`[] - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `options` | [`CollectOptions`](../interfaces/CollectOptions.md) | - -#### Returns - -`string`[] - -#### Defined in - -[nonfungiblePositionManager.ts:286](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L286) - -___ - -### encodeCreate - -▸ `Static` `Private` **encodeCreate**(`pool`): `string` - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `pool` | [`Pool`](Pool.md) | - -#### Returns - -`string` - -#### Defined in - -[nonfungiblePositionManager.ts:183](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L183) - -___ - -### removeCallParameters - -▸ `Static` **removeCallParameters**(`position`, `options`): [`MethodParameters`](../interfaces/MethodParameters.md) - -Produces the calldata for completely or partially exiting a position - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `position` | [`Position`](Position.md) | The position to exit | -| `options` | [`RemoveLiquidityOptions`](../interfaces/RemoveLiquidityOptions.md) | Additional information necessary for generating the calldata | - -#### Returns - -[`MethodParameters`](../interfaces/MethodParameters.md) - -The call parameters - -#### Defined in - -[nonfungiblePositionManager.ts:341](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L341) - -___ - -### safeTransferFromParameters - -▸ `Static` **safeTransferFromParameters**(`options`): [`MethodParameters`](../interfaces/MethodParameters.md) - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `options` | [`SafeTransferOptions`](../interfaces/SafeTransferOptions.md) | - -#### Returns - -[`MethodParameters`](../interfaces/MethodParameters.md) - -#### Defined in - -[nonfungiblePositionManager.ts:416](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L416) diff --git a/docs/sdk/v3/reference/classes/Payments.md b/docs/sdk/v3/reference/classes/Payments.md deleted file mode 100644 index b91ee96b6..000000000 --- a/docs/sdk/v3/reference/classes/Payments.md +++ /dev/null @@ -1,121 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / Payments - -# Class: Payments - -## Table of contents - -### Constructors - -- [constructor](Payments.md#constructor) - -### Properties - -- [INTERFACE](Payments.md#interface) - -### Methods - -- [encodeFeeBips](Payments.md#encodefeebips) -- [encodeRefundETH](Payments.md#encoderefundeth) -- [encodeSweepToken](Payments.md#encodesweeptoken) -- [encodeUnwrapWETH9](Payments.md#encodeunwrapweth9) - -## Constructors - -### constructor - -• `Private` **new Payments**() - -Cannot be constructed. - -#### Defined in - -[payments.ts:25](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/payments.ts#L25) - -## Properties - -### INTERFACE - -▪ `Static` **INTERFACE**: `Interface` - -#### Defined in - -[payments.ts:20](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/payments.ts#L20) - -## Methods - -### encodeFeeBips - -▸ `Static` `Private` **encodeFeeBips**(`fee`): `string` - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `fee` | `Percent` | - -#### Returns - -`string` - -#### Defined in - -[payments.ts:27](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/payments.ts#L27) - -___ - -### encodeRefundETH - -▸ `Static` **encodeRefundETH**(): `string` - -#### Returns - -`string` - -#### Defined in - -[payments.ts:73](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/payments.ts#L73) - -___ - -### encodeSweepToken - -▸ `Static` **encodeSweepToken**(`token`, `amountMinimum`, `recipient`, `feeOptions?`): `string` - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `token` | `Token` | -| `amountMinimum` | `default` | -| `recipient` | `string` | -| `feeOptions?` | [`FeeOptions`](../interfaces/FeeOptions.md) | - -#### Returns - -`string` - -#### Defined in - -[payments.ts:49](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/payments.ts#L49) - -___ - -### encodeUnwrapWETH9 - -▸ `Static` **encodeUnwrapWETH9**(`amountMinimum`, `recipient`, `feeOptions?`): `string` - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `amountMinimum` | `default` | -| `recipient` | `string` | -| `feeOptions?` | [`FeeOptions`](../interfaces/FeeOptions.md) | - -#### Returns - -`string` - -#### Defined in - -[payments.ts:31](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/payments.ts#L31) diff --git a/docs/sdk/v3/reference/classes/Pool.md b/docs/sdk/v3/reference/classes/Pool.md deleted file mode 100644 index f14b00d8a..000000000 --- a/docs/sdk/v3/reference/classes/Pool.md +++ /dev/null @@ -1,369 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / Pool - -# Class: Pool - -Represents a V3 pool - -## Table of contents - -### Constructors - -- [constructor](Pool.md#constructor) - -### Properties - -- [\_token0Price](Pool.md#_token0price) -- [\_token1Price](Pool.md#_token1price) -- [fee](Pool.md#fee) -- [liquidity](Pool.md#liquidity) -- [sqrtRatioX96](Pool.md#sqrtratiox96) -- [tickCurrent](Pool.md#tickcurrent) -- [tickDataProvider](Pool.md#tickdataprovider) -- [token0](Pool.md#token0) -- [token1](Pool.md#token1) - -### Accessors - -- [chainId](Pool.md#chainid) -- [tickSpacing](Pool.md#tickspacing) -- [token0Price](Pool.md#token0price) -- [token1Price](Pool.md#token1price) - -### Methods - -- [getInputAmount](Pool.md#getinputamount) -- [getOutputAmount](Pool.md#getoutputamount) -- [involvesToken](Pool.md#involvestoken) -- [priceOf](Pool.md#priceof) -- [swap](Pool.md#swap) -- [getAddress](Pool.md#getaddress) - -## Constructors - -### constructor - -• **new Pool**(`tokenA`, `tokenB`, `fee`, `sqrtRatioX96`, `liquidity`, `tickCurrent`, `ticks?`) - -Construct a pool - -#### Parameters - -| Name | Type | Default value | Description | -| :------ | :------ | :------ | :------ | -| `tokenA` | `Token` | `undefined` | One of the tokens in the pool | -| `tokenB` | `Token` | `undefined` | The other token in the pool | -| `fee` | [`FeeAmount`](../enums/FeeAmount.md) | `undefined` | The fee in hundredths of a bips of the input amount of every swap that is collected by the pool | -| `sqrtRatioX96` | `BigintIsh` | `undefined` | The sqrt of the current ratio of amounts of token1 to token0 | -| `liquidity` | `BigintIsh` | `undefined` | The current value of in range liquidity | -| `tickCurrent` | `number` | `undefined` | The current tick of the pool | -| `ticks` | [`TickDataProvider`](../interfaces/TickDataProvider.md) \| ([`Tick`](Tick.md) \| [`TickConstructorArgs`](../interfaces/TickConstructorArgs.md))[] | `NO_TICK_DATA_PROVIDER_DEFAULT` | The current state of the pool ticks or a data provider that can return tick data | - -#### Defined in - -[entities/pool.ts:70](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/pool.ts#L70) - -## Properties - -### \_token0Price - -• `Private` `Optional` **\_token0Price**: `Price`<`Token`, `Token`\> - -#### Defined in - -[entities/pool.ts:41](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/pool.ts#L41) - -___ - -### \_token1Price - -• `Private` `Optional` **\_token1Price**: `Price`<`Token`, `Token`\> - -#### Defined in - -[entities/pool.ts:42](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/pool.ts#L42) - -___ - -### fee - -• `Readonly` **fee**: [`FeeAmount`](../enums/FeeAmount.md) - -#### Defined in - -[entities/pool.ts:35](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/pool.ts#L35) - -___ - -### liquidity - -• `Readonly` **liquidity**: `default` - -#### Defined in - -[entities/pool.ts:37](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/pool.ts#L37) - -___ - -### sqrtRatioX96 - -• `Readonly` **sqrtRatioX96**: `default` - -#### Defined in - -[entities/pool.ts:36](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/pool.ts#L36) - -___ - -### tickCurrent - -• `Readonly` **tickCurrent**: `number` - -#### Defined in - -[entities/pool.ts:38](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/pool.ts#L38) - -___ - -### tickDataProvider - -• `Readonly` **tickDataProvider**: [`TickDataProvider`](../interfaces/TickDataProvider.md) - -#### Defined in - -[entities/pool.ts:39](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/pool.ts#L39) - -___ - -### token0 - -• `Readonly` **token0**: `Token` - -#### Defined in - -[entities/pool.ts:33](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/pool.ts#L33) - -___ - -### token1 - -• `Readonly` **token1**: `Token` - -#### Defined in - -[entities/pool.ts:34](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/pool.ts#L34) - -## Accessors - -### chainId - -• `get` **chainId**(): `number` - -Returns the chain ID of the tokens in the pool. - -#### Returns - -`number` - -#### Defined in - -[entities/pool.ts:149](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/pool.ts#L149) - -___ - -### tickSpacing - -• `get` **tickSpacing**(): `number` - -#### Returns - -`number` - -#### Defined in - -[entities/pool.ts:317](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/pool.ts#L317) - -___ - -### token0Price - -• `get` **token0Price**(): `Price`<`Token`, `Token`\> - -Returns the current mid price of the pool in terms of token0, i.e. the ratio of token1 over token0 - -#### Returns - -`Price`<`Token`, `Token`\> - -#### Defined in - -[entities/pool.ts:109](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/pool.ts#L109) - -___ - -### token1Price - -• `get` **token1Price**(): `Price`<`Token`, `Token`\> - -Returns the current mid price of the pool in terms of token1, i.e. the ratio of token0 over token1 - -#### Returns - -`Price`<`Token`, `Token`\> - -#### Defined in - -[entities/pool.ts:124](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/pool.ts#L124) - -## Methods - -### getInputAmount - -▸ **getInputAmount**(`outputAmount`, `sqrtPriceLimitX96?`): `Promise`<[`CurrencyAmount`<`Token`\>, [`Pool`](Pool.md)]\> - -Given a desired output amount of a token, return the computed input amount and a pool with state updated after the trade - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `outputAmount` | `CurrencyAmount`<`Token`\> | the output amount for which to quote the input amount | -| `sqrtPriceLimitX96?` | `default` | The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this value after the swap. If one for zero, the price cannot be greater than this value after the swap | - -#### Returns - -`Promise`<[`CurrencyAmount`<`Token`\>, [`Pool`](Pool.md)]\> - -The input amount and the pool with updated state - -#### Defined in - -[entities/pool.ts:185](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/pool.ts#L185) - -___ - -### getOutputAmount - -▸ **getOutputAmount**(`inputAmount`, `sqrtPriceLimitX96?`): `Promise`<[`CurrencyAmount`<`Token`\>, [`Pool`](Pool.md)]\> - -Given an input amount of a token, return the computed output amount, and a pool with state updated after the trade - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `inputAmount` | `CurrencyAmount`<`Token`\> | The input amount for which to quote the output amount | -| `sqrtPriceLimitX96?` | `default` | The Q64.96 sqrt price limit | - -#### Returns - -`Promise`<[`CurrencyAmount`<`Token`\>, [`Pool`](Pool.md)]\> - -The output amount and the pool with updated state - -#### Defined in - -[entities/pool.ts:159](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/pool.ts#L159) - -___ - -### involvesToken - -▸ **involvesToken**(`token`): `boolean` - -Returns true if the token is either token0 or token1 - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `token` | `Token` | The token to check | - -#### Returns - -`boolean` - -True if token is either token0 or token - -#### Defined in - -[entities/pool.ts:102](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/pool.ts#L102) - -___ - -### priceOf - -▸ **priceOf**(`token`): `Price`<`Token`, `Token`\> - -Return the price of the given token in terms of the other token in the pool. - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `token` | `Token` | The token to return price of | - -#### Returns - -`Price`<`Token`, `Token`\> - -The price of the given token, in terms of the other. - -#### Defined in - -[entities/pool.ts:141](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/pool.ts#L141) - -___ - -### swap - -▸ `Private` **swap**(`zeroForOne`, `amountSpecified`, `sqrtPriceLimitX96?`): `Promise`<{ `amountCalculated`: `default` ; `liquidity`: `default` ; `sqrtRatioX96`: `default` ; `tickCurrent`: `number` }\> - -Executes a swap - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `zeroForOne` | `boolean` | Whether the amount in is token0 or token1 | -| `amountSpecified` | `default` | The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) | -| `sqrtPriceLimitX96?` | `default` | The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this value after the swap. If one for zero, the price cannot be greater than this value after the swap | - -#### Returns - -`Promise`<{ `amountCalculated`: `default` ; `liquidity`: `default` ; `sqrtRatioX96`: `default` ; `tickCurrent`: `number` }\> - -amountCalculated - -sqrtRatioX96 - -liquidity - -tickCurrent - -#### Defined in - -[entities/pool.ts:215](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/pool.ts#L215) - -___ - -### getAddress - -▸ `Static` **getAddress**(`tokenA`, `tokenB`, `fee`, `initCodeHashManualOverride?`, `factoryAddressOverride?`): `string` - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `tokenA` | `Token` | -| `tokenB` | `Token` | -| `fee` | [`FeeAmount`](../enums/FeeAmount.md) | -| `initCodeHashManualOverride?` | `string` | -| `factoryAddressOverride?` | `string` | - -#### Returns - -`string` - -#### Defined in - -[entities/pool.ts:44](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/pool.ts#L44) diff --git a/docs/sdk/v3/reference/classes/Position.md b/docs/sdk/v3/reference/classes/Position.md deleted file mode 100644 index b50c3c84f..000000000 --- a/docs/sdk/v3/reference/classes/Position.md +++ /dev/null @@ -1,374 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / Position - -# Class: Position - -Represents a position on a t1 V3 Pool - -## Table of contents - -### Constructors - -- [constructor](Position.md#constructor) - -### Properties - -- [\_mintAmounts](Position.md#_mintamounts) -- [\_token0Amount](Position.md#_token0amount) -- [\_token1Amount](Position.md#_token1amount) -- [liquidity](Position.md#liquidity) -- [pool](Position.md#pool) -- [tickLower](Position.md#ticklower) -- [tickUpper](Position.md#tickupper) - -### Accessors - -- [amount0](Position.md#amount0) -- [amount1](Position.md#amount1) -- [mintAmounts](Position.md#mintamounts) -- [token0PriceLower](Position.md#token0pricelower) -- [token0PriceUpper](Position.md#token0priceupper) - -### Methods - -- [burnAmountsWithSlippage](Position.md#burnamountswithslippage) -- [mintAmountsWithSlippage](Position.md#mintamountswithslippage) -- [ratiosAfterSlippage](Position.md#ratiosafterslippage) -- [fromAmount0](Position.md#fromamount0) -- [fromAmount1](Position.md#fromamount1) -- [fromAmounts](Position.md#fromamounts) - -## Constructors - -### constructor - -• **new Position**(`__namedParameters`) - -Constructs a position for a given pool with the given liquidity - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `__namedParameters` | `PositionConstructorArgs` | - -#### Defined in - -[entities/position.ts:40](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/position.ts#L40) - -## Properties - -### \_mintAmounts - -• `Private` **\_mintAmounts**: ``null`` \| `Readonly`<{ `amount0`: `default` ; `amount1`: `default` }\> = `null` - -#### Defined in - -[entities/position.ts:31](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/position.ts#L31) - -___ - -### \_token0Amount - -• `Private` **\_token0Amount**: ``null`` \| `CurrencyAmount`<`Token`\> = `null` - -#### Defined in - -[entities/position.ts:29](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/position.ts#L29) - -___ - -### \_token1Amount - -• `Private` **\_token1Amount**: ``null`` \| `CurrencyAmount`<`Token`\> = `null` - -#### Defined in - -[entities/position.ts:30](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/position.ts#L30) - -___ - -### liquidity - -• `Readonly` **liquidity**: `default` - -#### Defined in - -[entities/position.ts:26](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/position.ts#L26) - -___ - -### pool - -• `Readonly` **pool**: [`Pool`](Pool.md) - -#### Defined in - -[entities/position.ts:23](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/position.ts#L23) - -___ - -### tickLower - -• `Readonly` **tickLower**: `number` - -#### Defined in - -[entities/position.ts:24](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/position.ts#L24) - -___ - -### tickUpper - -• `Readonly` **tickUpper**: `number` - -#### Defined in - -[entities/position.ts:25](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/position.ts#L25) - -## Accessors - -### amount0 - -• `get` **amount0**(): `CurrencyAmount`<`Token`\> - -Returns the amount of token0 that this position's liquidity could be burned for at the current pool price - -#### Returns - -`CurrencyAmount`<`Token`\> - -#### Defined in - -[entities/position.ts:68](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/position.ts#L68) - -___ - -### amount1 - -• `get` **amount1**(): `CurrencyAmount`<`Token`\> - -Returns the amount of token1 that this position's liquidity could be burned for at the current pool price - -#### Returns - -`CurrencyAmount`<`Token`\> - -#### Defined in - -[entities/position.ts:100](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/position.ts#L100) - -___ - -### mintAmounts - -• `get` **mintAmounts**(): `Readonly`<{ `amount0`: `default` ; `amount1`: `default` }\> - -Returns the minimum amounts that must be sent in order to mint the amount of liquidity held by the position at -the current price for the pool - -#### Returns - -`Readonly`<{ `amount0`: `default` ; `amount1`: `default` }\> - -#### Defined in - -[entities/position.ts:258](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/position.ts#L258) - -___ - -### token0PriceLower - -• `get` **token0PriceLower**(): `Price`<`Token`, `Token`\> - -Returns the price of token0 at the lower tick - -#### Returns - -`Price`<`Token`, `Token`\> - -#### Defined in - -[entities/position.ts:54](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/position.ts#L54) - -___ - -### token0PriceUpper - -• `get` **token0PriceUpper**(): `Price`<`Token`, `Token`\> - -Returns the price of token0 at the upper tick - -#### Returns - -`Price`<`Token`, `Token`\> - -#### Defined in - -[entities/position.ts:61](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/position.ts#L61) - -## Methods - -### burnAmountsWithSlippage - -▸ **burnAmountsWithSlippage**(`slippageTolerance`): `Readonly`<{ `amount0`: `default` ; `amount1`: `default` }\> - -Returns the minimum amounts that should be requested in order to safely burn the amount of liquidity held by the -position with the given slippage tolerance - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `slippageTolerance` | `Percent` | tolerance of unfavorable slippage from the current price | - -#### Returns - -`Readonly`<{ `amount0`: `default` ; `amount1`: `default` }\> - -The amounts, with slippage - -#### Defined in - -[entities/position.ts:213](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/position.ts#L213) - -___ - -### mintAmountsWithSlippage - -▸ **mintAmountsWithSlippage**(`slippageTolerance`): `Readonly`<{ `amount0`: `default` ; `amount1`: `default` }\> - -Returns the minimum amounts that must be sent in order to safely mint the amount of liquidity held by the position -with the given slippage tolerance - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `slippageTolerance` | `Percent` | Tolerance of unfavorable slippage from the current price | - -#### Returns - -`Readonly`<{ `amount0`: `default` ; `amount1`: `default` }\> - -The amounts, with slippage - -#### Defined in - -[entities/position.ts:157](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/position.ts#L157) - -___ - -### ratiosAfterSlippage - -▸ `Private` **ratiosAfterSlippage**(`slippageTolerance`): `Object` - -Returns the lower and upper sqrt ratios if the price 'slips' up to slippage tolerance percentage - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `slippageTolerance` | `Percent` | The amount by which the price can 'slip' before the transaction will revert | - -#### Returns - -`Object` - -The sqrt ratios after slippage - -| Name | Type | -| :------ | :------ | -| `sqrtRatioX96Lower` | `default` | -| `sqrtRatioX96Upper` | `default` | - -#### Defined in - -[entities/position.ts:134](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/position.ts#L134) - -___ - -### fromAmount0 - -▸ `Static` **fromAmount0**(`__namedParameters`): [`Position`](Position.md) - -Computes a position with the maximum amount of liquidity received for a given amount of token0, assuming an unlimited amount of token1 - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `__namedParameters` | `Object` | -| `__namedParameters.amount0` | `BigintIsh` | -| `__namedParameters.pool` | [`Pool`](Pool.md) | -| `__namedParameters.tickLower` | `number` | -| `__namedParameters.tickUpper` | `number` | -| `__namedParameters.useFullPrecision` | `boolean` | - -#### Returns - -[`Position`](Position.md) - -The position - -#### Defined in - -[entities/position.ts:354](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/position.ts#L354) - -___ - -### fromAmount1 - -▸ `Static` **fromAmount1**(`__namedParameters`): [`Position`](Position.md) - -Computes a position with the maximum amount of liquidity received for a given amount of token1, assuming an unlimited amount of token0 - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `__namedParameters` | `Object` | -| `__namedParameters.amount1` | `BigintIsh` | -| `__namedParameters.pool` | [`Pool`](Pool.md) | -| `__namedParameters.tickLower` | `number` | -| `__namedParameters.tickUpper` | `number` | - -#### Returns - -[`Position`](Position.md) - -The position - -#### Defined in - -[entities/position.ts:378](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/position.ts#L378) - -___ - -### fromAmounts - -▸ `Static` **fromAmounts**(`__namedParameters`): [`Position`](Position.md) - -Computes the maximum amount of liquidity received for a given amount of token0, token1, -and the prices at the tick boundaries. - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `__namedParameters` | `Object` | -| `__namedParameters.amount0` | `BigintIsh` | -| `__namedParameters.amount1` | `BigintIsh` | -| `__namedParameters.pool` | [`Pool`](Pool.md) | -| `__namedParameters.tickLower` | `number` | -| `__namedParameters.tickUpper` | `number` | -| `__namedParameters.useFullPrecision` | `boolean` | - -#### Returns - -[`Position`](Position.md) - -The amount of liquidity for the position - -#### Defined in - -[entities/position.ts:312](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/position.ts#L312) diff --git a/docs/sdk/v3/reference/classes/PositionLibrary.md b/docs/sdk/v3/reference/classes/PositionLibrary.md deleted file mode 100644 index 0bf2239e3..000000000 --- a/docs/sdk/v3/reference/classes/PositionLibrary.md +++ /dev/null @@ -1,49 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / PositionLibrary - -# Class: PositionLibrary - -## Table of contents - -### Constructors - -- [constructor](PositionLibrary.md#constructor) - -### Methods - -- [getTokensOwed](PositionLibrary.md#gettokensowed) - -## Constructors - -### constructor - -• `Private` **new PositionLibrary**() - -Cannot be constructed. - -#### Defined in - -[utils/position.ts:10](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/position.ts#L10) - -## Methods - -### getTokensOwed - -▸ `Static` **getTokensOwed**(`feeGrowthInside0LastX128`, `feeGrowthInside1LastX128`, `liquidity`, `feeGrowthInside0X128`, `feeGrowthInside1X128`): `default`[] - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `feeGrowthInside0LastX128` | `default` | -| `feeGrowthInside1LastX128` | `default` | -| `liquidity` | `default` | -| `feeGrowthInside0X128` | `default` | -| `feeGrowthInside1X128` | `default` | - -#### Returns - -`default`[] - -#### Defined in - -[utils/position.ts:13](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/position.ts#L13) diff --git a/docs/sdk/v3/reference/classes/Route.md b/docs/sdk/v3/reference/classes/Route.md deleted file mode 100644 index f5d007b79..000000000 --- a/docs/sdk/v3/reference/classes/Route.md +++ /dev/null @@ -1,138 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / Route - -# Class: Route - -Represents a list of pools through which a swap can occur - -## Type parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `TInput` | extends `Currency` | The input token | -| `TOutput` | extends `Currency` | The output token | - -## Table of contents - -### Constructors - -- [constructor](Route.md#constructor) - -### Properties - -- [\_midPrice](Route.md#_midprice) -- [input](Route.md#input) -- [output](Route.md#output) -- [pools](Route.md#pools) -- [tokenPath](Route.md#tokenpath) - -### Accessors - -- [chainId](Route.md#chainid) -- [midPrice](Route.md#midprice) - -## Constructors - -### constructor - -• **new Route**<`TInput`, `TOutput`\>(`pools`, `input`, `output`) - -Creates an instance of route. - -#### Type parameters - -| Name | Type | -| :------ | :------ | -| `TInput` | extends `Currency` | -| `TOutput` | extends `Currency` | - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `pools` | [`Pool`](Pool.md)[] | An array of `Pool` objects, ordered by the route the swap will take | -| `input` | `TInput` | The input token | -| `output` | `TOutput` | The output token | - -#### Defined in - -[entities/route.ts:25](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/route.ts#L25) - -## Properties - -### \_midPrice - -• `Private` **\_midPrice**: ``null`` \| `Price`<`TInput`, `TOutput`\> = `null` - -#### Defined in - -[entities/route.ts:17](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/route.ts#L17) - -___ - -### input - -• `Readonly` **input**: `TInput` - -#### Defined in - -[entities/route.ts:14](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/route.ts#L14) - -___ - -### output - -• `Readonly` **output**: `TOutput` - -#### Defined in - -[entities/route.ts:15](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/route.ts#L15) - -___ - -### pools - -• `Readonly` **pools**: [`Pool`](Pool.md)[] - -#### Defined in - -[entities/route.ts:12](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/route.ts#L12) - -___ - -### tokenPath - -• `Readonly` **tokenPath**: `Token`[] - -#### Defined in - -[entities/route.ts:13](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/route.ts#L13) - -## Accessors - -### chainId - -• `get` **chainId**(): `number` - -#### Returns - -`number` - -#### Defined in - -[entities/route.ts:54](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/route.ts#L54) - -___ - -### midPrice - -• `get` **midPrice**(): `Price`<`TInput`, `TOutput`\> - -Returns the mid price of the route - -#### Returns - -`Price`<`TInput`, `TOutput`\> - -#### Defined in - -[entities/route.ts:61](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/route.ts#L61) diff --git a/docs/sdk/v3/reference/classes/SelfPermit.md b/docs/sdk/v3/reference/classes/SelfPermit.md deleted file mode 100644 index 651e908de..000000000 --- a/docs/sdk/v3/reference/classes/SelfPermit.md +++ /dev/null @@ -1,60 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / SelfPermit - -# Class: SelfPermit - -## Table of contents - -### Constructors - -- [constructor](SelfPermit.md#constructor) - -### Properties - -- [INTERFACE](SelfPermit.md#interface) - -### Methods - -- [encodePermit](SelfPermit.md#encodepermit) - -## Constructors - -### constructor - -• `Private` **new SelfPermit**() - -Cannot be constructed. - -#### Defined in - -[selfPermit.ts:34](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/selfPermit.ts#L34) - -## Properties - -### INTERFACE - -▪ `Static` **INTERFACE**: `Interface` - -#### Defined in - -[selfPermit.ts:29](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/selfPermit.ts#L29) - -## Methods - -### encodePermit - -▸ `Static` **encodePermit**(`token`, `options`): `string` - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `token` | `Token` | -| `options` | [`PermitOptions`](../modules.md#permitoptions) | - -#### Returns - -`string` - -#### Defined in - -[selfPermit.ts:36](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/selfPermit.ts#L36) diff --git a/docs/sdk/v3/reference/classes/SqrtPriceMath.md b/docs/sdk/v3/reference/classes/SqrtPriceMath.md deleted file mode 100644 index 35924ddd6..000000000 --- a/docs/sdk/v3/reference/classes/SqrtPriceMath.md +++ /dev/null @@ -1,168 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / SqrtPriceMath - -# Class: SqrtPriceMath - -## Table of contents - -### Constructors - -- [constructor](SqrtPriceMath.md#constructor) - -### Methods - -- [getAmount0Delta](SqrtPriceMath.md#getamount0delta) -- [getAmount1Delta](SqrtPriceMath.md#getamount1delta) -- [getNextSqrtPriceFromAmount0RoundingUp](SqrtPriceMath.md#getnextsqrtpricefromamount0roundingup) -- [getNextSqrtPriceFromAmount1RoundingDown](SqrtPriceMath.md#getnextsqrtpricefromamount1roundingdown) -- [getNextSqrtPriceFromInput](SqrtPriceMath.md#getnextsqrtpricefrominput) -- [getNextSqrtPriceFromOutput](SqrtPriceMath.md#getnextsqrtpricefromoutput) - -## Constructors - -### constructor - -• `Private` **new SqrtPriceMath**() - -Cannot be constructed. - -#### Defined in - -[utils/sqrtPriceMath.ts:23](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/sqrtPriceMath.ts#L23) - -## Methods - -### getAmount0Delta - -▸ `Static` **getAmount0Delta**(`sqrtRatioAX96`, `sqrtRatioBX96`, `liquidity`, `roundUp`): `default` - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `sqrtRatioAX96` | `default` | -| `sqrtRatioBX96` | `default` | -| `liquidity` | `default` | -| `roundUp` | `boolean` | - -#### Returns - -`default` - -#### Defined in - -[utils/sqrtPriceMath.ts:25](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/sqrtPriceMath.ts#L25) - -___ - -### getAmount1Delta - -▸ `Static` **getAmount1Delta**(`sqrtRatioAX96`, `sqrtRatioBX96`, `liquidity`, `roundUp`): `default` - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `sqrtRatioAX96` | `default` | -| `sqrtRatioBX96` | `default` | -| `liquidity` | `default` | -| `roundUp` | `boolean` | - -#### Returns - -`default` - -#### Defined in - -[utils/sqrtPriceMath.ts:38](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/sqrtPriceMath.ts#L38) - -___ - -### getNextSqrtPriceFromAmount0RoundingUp - -▸ `Static` `Private` **getNextSqrtPriceFromAmount0RoundingUp**(`sqrtPX96`, `liquidity`, `amount`, `add`): `default` - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `sqrtPX96` | `default` | -| `liquidity` | `default` | -| `amount` | `default` | -| `add` | `boolean` | - -#### Returns - -`default` - -#### Defined in - -[utils/sqrtPriceMath.ts:71](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/sqrtPriceMath.ts#L71) - -___ - -### getNextSqrtPriceFromAmount1RoundingDown - -▸ `Static` `Private` **getNextSqrtPriceFromAmount1RoundingDown**(`sqrtPX96`, `liquidity`, `amount`, `add`): `default` - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `sqrtPX96` | `default` | -| `liquidity` | `default` | -| `amount` | `default` | -| `add` | `boolean` | - -#### Returns - -`default` - -#### Defined in - -[utils/sqrtPriceMath.ts:100](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/sqrtPriceMath.ts#L100) - -___ - -### getNextSqrtPriceFromInput - -▸ `Static` **getNextSqrtPriceFromInput**(`sqrtPX96`, `liquidity`, `amountIn`, `zeroForOne`): `default` - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `sqrtPX96` | `default` | -| `liquidity` | `default` | -| `amountIn` | `default` | -| `zeroForOne` | `boolean` | - -#### Returns - -`default` - -#### Defined in - -[utils/sqrtPriceMath.ts:48](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/sqrtPriceMath.ts#L48) - -___ - -### getNextSqrtPriceFromOutput - -▸ `Static` **getNextSqrtPriceFromOutput**(`sqrtPX96`, `liquidity`, `amountOut`, `zeroForOne`): `default` - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `sqrtPX96` | `default` | -| `liquidity` | `default` | -| `amountOut` | `default` | -| `zeroForOne` | `boolean` | - -#### Returns - -`default` - -#### Defined in - -[utils/sqrtPriceMath.ts:57](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/sqrtPriceMath.ts#L57) diff --git a/docs/sdk/v3/reference/classes/Staker.md b/docs/sdk/v3/reference/classes/Staker.md deleted file mode 100644 index f275c0485..000000000 --- a/docs/sdk/v3/reference/classes/Staker.md +++ /dev/null @@ -1,167 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / Staker - -# Class: Staker - -## Table of contents - -### Constructors - -- [constructor](Staker.md#constructor) - -### Properties - -- [INCENTIVE\_KEY\_ABI](Staker.md#incentive_key_abi) -- [INTERFACE](Staker.md#interface) - -### Methods - -- [\_encodeIncentiveKey](Staker.md#_encodeincentivekey) -- [collectRewards](Staker.md#collectrewards) -- [encodeClaim](Staker.md#encodeclaim) -- [encodeDeposit](Staker.md#encodedeposit) -- [withdrawToken](Staker.md#withdrawtoken) - -## Constructors - -### constructor - -• `Protected` **new Staker**() - -#### Defined in - -[staker.ts:72](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/staker.ts#L72) - -## Properties - -### INCENTIVE\_KEY\_ABI - -▪ `Static` `Private` **INCENTIVE\_KEY\_ABI**: `string` = `'tuple(address rewardToken, address pool, uint256 startTime, uint256 endTime, address refundee)'` - -#### Defined in - -[staker.ts:73](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/staker.ts#L73) - -___ - -### INTERFACE - -▪ `Static` **INTERFACE**: `Interface` - -#### Defined in - -[staker.ts:70](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/staker.ts#L70) - -## Methods - -### \_encodeIncentiveKey - -▸ `Static` `Private` **_encodeIncentiveKey**(`incentiveKey`): `Object` - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `incentiveKey` | [`IncentiveKey`](../interfaces/IncentiveKey.md) | An `IncentiveKey` which represents a unique staking program. | - -#### Returns - -`Object` - -An encoded IncentiveKey to be read by ethers - -#### Defined in - -[staker.ts:194](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/staker.ts#L194) - -___ - -### collectRewards - -▸ `Static` **collectRewards**(`incentiveKeys`, `options`): [`MethodParameters`](../interfaces/MethodParameters.md) - -Note: A `tokenId` can be staked in many programs but to claim rewards and continue the program you must unstake, claim, and then restake. - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `incentiveKeys` | [`IncentiveKey`](../interfaces/IncentiveKey.md) \| [`IncentiveKey`](../interfaces/IncentiveKey.md)[] | An IncentiveKey or array of IncentiveKeys that `tokenId` is staked in. Input an array of IncentiveKeys to claim rewards for each program. | -| `options` | [`ClaimOptions`](../interfaces/ClaimOptions.md) | ClaimOptions to specify tokenId, recipient, and amount wanting to collect. Note that you can only specify one amount and one recipient across the various programs if you are collecting from multiple programs at once. | - -#### Returns - -[`MethodParameters`](../interfaces/MethodParameters.md) - -#### Defined in - -[staker.ts:107](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/staker.ts#L107) - -___ - -### encodeClaim - -▸ `Static` `Private` **encodeClaim**(`incentiveKey`, `options`): `string`[] - -To claim rewards, must unstake and then claim. - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `incentiveKey` | [`IncentiveKey`](../interfaces/IncentiveKey.md) | The unique identifier of a staking program. | -| `options` | [`ClaimOptions`](../interfaces/ClaimOptions.md) | Options for producing the calldata to claim. Can't claim unless you unstake. | - -#### Returns - -`string`[] - -The calldatas for 'unstakeToken' and 'claimReward'. - -#### Defined in - -[staker.ts:82](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/staker.ts#L82) - -___ - -### encodeDeposit - -▸ `Static` **encodeDeposit**(`incentiveKeys`): `string` - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `incentiveKeys` | [`IncentiveKey`](../interfaces/IncentiveKey.md) \| [`IncentiveKey`](../interfaces/IncentiveKey.md)[] | A single IncentiveKey or array of IncentiveKeys to be encoded and used in the data parameter in `safeTransferFrom` | - -#### Returns - -`string` - -An IncentiveKey as a string - -#### Defined in - -[staker.ts:173](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/staker.ts#L173) - -___ - -### withdrawToken - -▸ `Static` **withdrawToken**(`incentiveKeys`, `withdrawOptions`): [`MethodParameters`](../interfaces/MethodParameters.md) - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `incentiveKeys` | [`IncentiveKey`](../interfaces/IncentiveKey.md) \| [`IncentiveKey`](../interfaces/IncentiveKey.md)[] | A list of incentiveKeys to unstake from. Should include all incentiveKeys (unique staking programs) that `options.tokenId` is staked in. | -| `withdrawOptions` | [`FullWithdrawOptions`](../modules.md#fullwithdrawoptions) | Options for producing claim calldata and withdraw calldata. Can't withdraw without unstaking all programs for `tokenId`. | - -#### Returns - -[`MethodParameters`](../interfaces/MethodParameters.md) - -Calldata for unstaking, claiming, and withdrawing. - -#### Defined in - -[staker.ts:136](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/staker.ts#L136) diff --git a/docs/sdk/v3/reference/classes/SwapMath.md b/docs/sdk/v3/reference/classes/SwapMath.md deleted file mode 100644 index bbf32fb84..000000000 --- a/docs/sdk/v3/reference/classes/SwapMath.md +++ /dev/null @@ -1,49 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / SwapMath - -# Class: SwapMath - -## Table of contents - -### Constructors - -- [constructor](SwapMath.md#constructor) - -### Methods - -- [computeSwapStep](SwapMath.md#computeswapstep) - -## Constructors - -### constructor - -• `Private` **new SwapMath**() - -Cannot be constructed. - -#### Defined in - -[utils/swapMath.ts:13](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/swapMath.ts#L13) - -## Methods - -### computeSwapStep - -▸ `Static` **computeSwapStep**(`sqrtRatioCurrentX96`, `sqrtRatioTargetX96`, `liquidity`, `amountRemaining`, `feePips`): [`default`, `default`, `default`, `default`] - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `sqrtRatioCurrentX96` | `default` | -| `sqrtRatioTargetX96` | `default` | -| `liquidity` | `default` | -| `amountRemaining` | `default` | -| `feePips` | [`FeeAmount`](../enums/FeeAmount.md) | - -#### Returns - -[`default`, `default`, `default`, `default`] - -#### Defined in - -[utils/swapMath.ts:15](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/swapMath.ts#L15) diff --git a/docs/sdk/v3/reference/classes/SwapQuoter.md b/docs/sdk/v3/reference/classes/SwapQuoter.md deleted file mode 100644 index 49c559e71..000000000 --- a/docs/sdk/v3/reference/classes/SwapQuoter.md +++ /dev/null @@ -1,82 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / SwapQuoter - -# Class: SwapQuoter - -Represents the t1 V3 QuoterV1 contract with a method for returning the formatted -calldata needed to call the quoter contract. - -## Table of contents - -### Constructors - -- [constructor](SwapQuoter.md#constructor) - -### Properties - -- [V1INTERFACE](SwapQuoter.md#v1interface) -- [V2INTERFACE](SwapQuoter.md#v2interface) - -### Methods - -- [quoteCallParameters](SwapQuoter.md#quotecallparameters) - -## Constructors - -### constructor - -• **new SwapQuoter**() - -## Properties - -### V1INTERFACE - -▪ `Static` **V1INTERFACE**: `Interface` - -#### Defined in - -[quoter.ts:37](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/quoter.ts#L37) - -___ - -### V2INTERFACE - -▪ `Static` **V2INTERFACE**: `Interface` - -#### Defined in - -[quoter.ts:38](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/quoter.ts#L38) - -## Methods - -### quoteCallParameters - -▸ `Static` **quoteCallParameters**<`TInput`, `TOutput`\>(`route`, `amount`, `tradeType`, `options?`): [`MethodParameters`](../interfaces/MethodParameters.md) - -Produces the on-chain method name of the appropriate function within QuoterV2, -and the relevant hex encoded parameters. - -#### Type parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `TInput` | extends `Currency` | The input token, either Ether or an ERC-20 | -| `TOutput` | extends `Currency` | The output token, either Ether or an ERC-20 | - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `route` | [`Route`](Route.md)<`TInput`, `TOutput`\> | The swap route, a list of pools through which a swap can occur | -| `amount` | `CurrencyAmount`<`TInput` \| `TOutput`\> | The amount of the quote, either an amount in, or an amount out | -| `tradeType` | `TradeType` | The trade type, either exact input or exact output | -| `options` | [`QuoteOptions`](../interfaces/QuoteOptions.md) | The optional params including price limit and Quoter contract switch | - -#### Returns - -[`MethodParameters`](../interfaces/MethodParameters.md) - -The formatted calldata - -#### Defined in - -[quoter.ts:51](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/quoter.ts#L51) diff --git a/docs/sdk/v3/reference/classes/SwapRouter.md b/docs/sdk/v3/reference/classes/SwapRouter.md deleted file mode 100644 index 68787b17f..000000000 --- a/docs/sdk/v3/reference/classes/SwapRouter.md +++ /dev/null @@ -1,64 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / SwapRouter - -# Class: SwapRouter - -Represents the t1 V3 SwapRouter, and has static methods for helping execute trades. - -## Table of contents - -### Constructors - -- [constructor](SwapRouter.md#constructor) - -### Properties - -- [INTERFACE](SwapRouter.md#interface) - -### Methods - -- [swapCallParameters](SwapRouter.md#swapcallparameters) - -## Constructors - -### constructor - -• `Private` **new SwapRouter**() - -Cannot be constructed. - -#### Defined in - -[swapRouter.ts:57](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/swapRouter.ts#L57) - -## Properties - -### INTERFACE - -▪ `Static` **INTERFACE**: `Interface` - -#### Defined in - -[swapRouter.ts:52](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/swapRouter.ts#L52) - -## Methods - -### swapCallParameters - -▸ `Static` **swapCallParameters**(`trades`, `options`): [`MethodParameters`](../interfaces/MethodParameters.md) - -Produces the on-chain method name to call and the hex encoded parameters to pass as arguments for a given trade. - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `trades` | [`Trade`](Trade.md)<`Currency`, `Currency`, `TradeType`\> \| [`Trade`](Trade.md)<`Currency`, `Currency`, `TradeType`\>[] | - | -| `options` | [`SwapOptions`](../interfaces/SwapOptions.md) | options for the call parameters | - -#### Returns - -[`MethodParameters`](../interfaces/MethodParameters.md) - -#### Defined in - -[swapRouter.ts:64](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/swapRouter.ts#L64) diff --git a/docs/sdk/v3/reference/classes/Tick.md b/docs/sdk/v3/reference/classes/Tick.md deleted file mode 100644 index befa90a8f..000000000 --- a/docs/sdk/v3/reference/classes/Tick.md +++ /dev/null @@ -1,61 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / Tick - -# Class: Tick - -## Table of contents - -### Constructors - -- [constructor](Tick.md#constructor) - -### Properties - -- [index](Tick.md#index) -- [liquidityGross](Tick.md#liquiditygross) -- [liquidityNet](Tick.md#liquiditynet) - -## Constructors - -### constructor - -• **new Tick**(`__namedParameters`) - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `__namedParameters` | [`TickConstructorArgs`](../interfaces/TickConstructorArgs.md) | - -#### Defined in - -[entities/tick.ts:17](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/tick.ts#L17) - -## Properties - -### index - -• `Readonly` **index**: `number` - -#### Defined in - -[entities/tick.ts:13](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/tick.ts#L13) - -___ - -### liquidityGross - -• `Readonly` **liquidityGross**: `default` - -#### Defined in - -[entities/tick.ts:14](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/tick.ts#L14) - -___ - -### liquidityNet - -• `Readonly` **liquidityNet**: `default` - -#### Defined in - -[entities/tick.ts:15](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/tick.ts#L15) diff --git a/docs/sdk/v3/reference/classes/TickLibrary.md b/docs/sdk/v3/reference/classes/TickLibrary.md deleted file mode 100644 index 40fe49bec..000000000 --- a/docs/sdk/v3/reference/classes/TickLibrary.md +++ /dev/null @@ -1,51 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / TickLibrary - -# Class: TickLibrary - -## Table of contents - -### Constructors - -- [constructor](TickLibrary.md#constructor) - -### Methods - -- [getFeeGrowthInside](TickLibrary.md#getfeegrowthinside) - -## Constructors - -### constructor - -• `Private` **new TickLibrary**() - -Cannot be constructed. - -#### Defined in - -[utils/tickLibrary.ts:25](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/tickLibrary.ts#L25) - -## Methods - -### getFeeGrowthInside - -▸ `Static` **getFeeGrowthInside**(`feeGrowthOutsideLower`, `feeGrowthOutsideUpper`, `tickLower`, `tickUpper`, `tickCurrent`, `feeGrowthGlobal0X128`, `feeGrowthGlobal1X128`): `default`[] - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `feeGrowthOutsideLower` | `FeeGrowthOutside` | -| `feeGrowthOutsideUpper` | `FeeGrowthOutside` | -| `tickLower` | `number` | -| `tickUpper` | `number` | -| `tickCurrent` | `number` | -| `feeGrowthGlobal0X128` | `default` | -| `feeGrowthGlobal1X128` | `default` | - -#### Returns - -`default`[] - -#### Defined in - -[utils/tickLibrary.ts:27](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/tickLibrary.ts#L27) diff --git a/docs/sdk/v3/reference/classes/TickList.md b/docs/sdk/v3/reference/classes/TickList.md deleted file mode 100644 index aa5b5c557..000000000 --- a/docs/sdk/v3/reference/classes/TickList.md +++ /dev/null @@ -1,185 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / TickList - -# Class: TickList - -Utility methods for interacting with sorted lists of ticks - -## Table of contents - -### Constructors - -- [constructor](TickList.md#constructor) - -### Methods - -- [binarySearch](TickList.md#binarysearch) -- [getTick](TickList.md#gettick) -- [isAtOrAboveLargest](TickList.md#isatorabovelargest) -- [isBelowSmallest](TickList.md#isbelowsmallest) -- [nextInitializedTick](TickList.md#nextinitializedtick) -- [nextInitializedTickWithinOneWord](TickList.md#nextinitializedtickwithinoneword) -- [validateList](TickList.md#validatelist) - -## Constructors - -### constructor - -• `Private` **new TickList**() - -Cannot be constructed - -#### Defined in - -[utils/tickList.ts:18](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/tickList.ts#L18) - -## Methods - -### binarySearch - -▸ `Static` `Private` **binarySearch**(`ticks`, `tick`): `number` - -Finds the largest tick in the list of ticks that is less than or equal to tick - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `ticks` | readonly [`Tick`](Tick.md)[] | list of ticks | -| `tick` | `number` | tick to find the largest tick that is less than or equal to tick | - -#### Returns - -`number` - -#### Defined in - -[utils/tickList.ts:62](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/tickList.ts#L62) - -___ - -### getTick - -▸ `Static` **getTick**(`ticks`, `index`): [`Tick`](Tick.md) - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `ticks` | readonly [`Tick`](Tick.md)[] | -| `index` | `number` | - -#### Returns - -[`Tick`](Tick.md) - -#### Defined in - -[utils/tickList.ts:50](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/tickList.ts#L50) - -___ - -### isAtOrAboveLargest - -▸ `Static` **isAtOrAboveLargest**(`ticks`, `tick`): `boolean` - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `ticks` | readonly [`Tick`](Tick.md)[] | -| `tick` | `number` | - -#### Returns - -`boolean` - -#### Defined in - -[utils/tickList.ts:45](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/tickList.ts#L45) - -___ - -### isBelowSmallest - -▸ `Static` **isBelowSmallest**(`ticks`, `tick`): `boolean` - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `ticks` | readonly [`Tick`](Tick.md)[] | -| `tick` | `number` | - -#### Returns - -`boolean` - -#### Defined in - -[utils/tickList.ts:40](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/tickList.ts#L40) - -___ - -### nextInitializedTick - -▸ `Static` **nextInitializedTick**(`ticks`, `tick`, `lte`): [`Tick`](Tick.md) - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `ticks` | readonly [`Tick`](Tick.md)[] | -| `tick` | `number` | -| `lte` | `boolean` | - -#### Returns - -[`Tick`](Tick.md) - -#### Defined in - -[utils/tickList.ts:83](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/tickList.ts#L83) - -___ - -### nextInitializedTickWithinOneWord - -▸ `Static` **nextInitializedTickWithinOneWord**(`ticks`, `tick`, `lte`, `tickSpacing`): [`number`, `boolean`] - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `ticks` | readonly [`Tick`](Tick.md)[] | -| `tick` | `number` | -| `lte` | `boolean` | -| `tickSpacing` | `number` | - -#### Returns - -[`number`, `boolean`] - -#### Defined in - -[utils/tickList.ts:101](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/tickList.ts#L101) - -___ - -### validateList - -▸ `Static` **validateList**(`ticks`, `tickSpacing`): `void` - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `ticks` | [`Tick`](Tick.md)[] | -| `tickSpacing` | `number` | - -#### Returns - -`void` - -#### Defined in - -[utils/tickList.ts:20](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/tickList.ts#L20) diff --git a/docs/sdk/v3/reference/classes/TickListDataProvider.md b/docs/sdk/v3/reference/classes/TickListDataProvider.md deleted file mode 100644 index c27c686c0..000000000 --- a/docs/sdk/v3/reference/classes/TickListDataProvider.md +++ /dev/null @@ -1,105 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / TickListDataProvider - -# Class: TickListDataProvider - -A data provider for ticks that is backed by an in-memory array of ticks. - -## Implements - -- [`TickDataProvider`](../interfaces/TickDataProvider.md) - -## Table of contents - -### Constructors - -- [constructor](TickListDataProvider.md#constructor) - -### Properties - -- [ticks](TickListDataProvider.md#ticks) - -### Methods - -- [getTick](TickListDataProvider.md#gettick) -- [nextInitializedTickWithinOneWord](TickListDataProvider.md#nextinitializedtickwithinoneword) - -## Constructors - -### constructor - -• **new TickListDataProvider**(`ticks`, `tickSpacing`) - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `ticks` | ([`Tick`](Tick.md) \| [`TickConstructorArgs`](../interfaces/TickConstructorArgs.md))[] | -| `tickSpacing` | `number` | - -#### Defined in - -[entities/tickListDataProvider.ts:12](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/tickListDataProvider.ts#L12) - -## Properties - -### ticks - -• `Private` **ticks**: readonly [`Tick`](Tick.md)[] - -#### Defined in - -[entities/tickListDataProvider.ts:10](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/tickListDataProvider.ts#L10) - -## Methods - -### getTick - -▸ **getTick**(`tick`): `Promise`<{ `liquidityGross`: `BigintIsh` ; `liquidityNet`: `BigintIsh` }\> - -Return information corresponding to a specific tick - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `tick` | `number` | the tick to load | - -#### Returns - -`Promise`<{ `liquidityGross`: `BigintIsh` ; `liquidityNet`: `BigintIsh` }\> - -#### Implementation of - -[TickDataProvider](../interfaces/TickDataProvider.md).[getTick](../interfaces/TickDataProvider.md#gettick) - -#### Defined in - -[entities/tickListDataProvider.ts:18](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/tickListDataProvider.ts#L18) - -___ - -### nextInitializedTickWithinOneWord - -▸ **nextInitializedTickWithinOneWord**(`tick`, `lte`, `tickSpacing`): `Promise`<[`number`, `boolean`]\> - -Return the next tick that is initialized within a single word - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `tick` | `number` | The current tick | -| `lte` | `boolean` | Whether the next tick should be lte the current tick | -| `tickSpacing` | `number` | The tick spacing of the pool | - -#### Returns - -`Promise`<[`number`, `boolean`]\> - -#### Implementation of - -[TickDataProvider](../interfaces/TickDataProvider.md).[nextInitializedTickWithinOneWord](../interfaces/TickDataProvider.md#nextinitializedtickwithinoneword) - -#### Defined in - -[entities/tickListDataProvider.ts:22](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/tickListDataProvider.ts#L22) diff --git a/docs/sdk/v3/reference/classes/TickMath.md b/docs/sdk/v3/reference/classes/TickMath.md deleted file mode 100644 index fefbc18a7..000000000 --- a/docs/sdk/v3/reference/classes/TickMath.md +++ /dev/null @@ -1,126 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / TickMath - -# Class: TickMath - -## Table of contents - -### Constructors - -- [constructor](TickMath.md#constructor) - -### Properties - -- [MAX\_SQRT\_RATIO](TickMath.md#max_sqrt_ratio) -- [MAX\_TICK](TickMath.md#max_tick) -- [MIN\_SQRT\_RATIO](TickMath.md#min_sqrt_ratio) -- [MIN\_TICK](TickMath.md#min_tick) - -### Methods - -- [getSqrtRatioAtTick](TickMath.md#getsqrtratioattick) -- [getTickAtSqrtRatio](TickMath.md#gettickatsqrtratio) - -## Constructors - -### constructor - -• `Private` **new TickMath**() - -Cannot be constructed. - -#### Defined in - -[utils/tickMath.ts:17](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/tickMath.ts#L17) - -## Properties - -### MAX\_SQRT\_RATIO - -▪ `Static` **MAX\_SQRT\_RATIO**: `default` - -The sqrt ratio corresponding to the maximum tick that could be used on any pool. - -#### Defined in - -[utils/tickMath.ts:35](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/tickMath.ts#L35) - -___ - -### MAX\_TICK - -▪ `Static` **MAX\_TICK**: `number` = `-TickMath.MIN_TICK` - -The maximum tick that can be used on any pool. - -#### Defined in - -[utils/tickMath.ts:26](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/tickMath.ts#L26) - -___ - -### MIN\_SQRT\_RATIO - -▪ `Static` **MIN\_SQRT\_RATIO**: `default` - -The sqrt ratio corresponding to the minimum tick that could be used on any pool. - -#### Defined in - -[utils/tickMath.ts:31](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/tickMath.ts#L31) - -___ - -### MIN\_TICK - -▪ `Static` **MIN\_TICK**: `number` = `-887272` - -The minimum tick that can be used on any pool. - -#### Defined in - -[utils/tickMath.ts:22](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/tickMath.ts#L22) - -## Methods - -### getSqrtRatioAtTick - -▸ `Static` **getSqrtRatioAtTick**(`tick`): `default` - -Returns the sqrt ratio as a Q64.96 for the given tick. The sqrt ratio is computed as sqrt(1.0001)^tick - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `tick` | `number` | the tick for which to compute the sqrt ratio | - -#### Returns - -`default` - -#### Defined in - -[utils/tickMath.ts:41](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/tickMath.ts#L41) - -___ - -### getTickAtSqrtRatio - -▸ `Static` **getTickAtSqrtRatio**(`sqrtRatioX96`): `number` - -Returns the tick corresponding to a given sqrt ratio, s.t. #getSqrtRatioAtTick(tick) <= sqrtRatioX96 -and #getSqrtRatioAtTick(tick + 1) > sqrtRatioX96 - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `sqrtRatioX96` | `default` | the sqrt ratio as a Q64.96 for which to compute the tick | - -#### Returns - -`number` - -#### Defined in - -[utils/tickMath.ts:82](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/tickMath.ts#L82) diff --git a/docs/sdk/v3/reference/classes/Trade.md b/docs/sdk/v3/reference/classes/Trade.md deleted file mode 100644 index 05db852da..000000000 --- a/docs/sdk/v3/reference/classes/Trade.md +++ /dev/null @@ -1,601 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / Trade - -# Class: Trade - -Represents a trade executed against a set of routes where some percentage of the input is -split across each route. - -Each route has its own set of pools. Pools can not be re-used across routes. - -Does not account for slippage, i.e., changes in price environment that can occur between -the time the trade is submitted and when it is executed. - -## Type parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `TInput` | extends `Currency` | The input token, either Ether or an ERC-20 | -| `TOutput` | extends `Currency` | The output token, either Ether or an ERC-20 | -| `TTradeType` | extends `TradeType` | The trade type, either exact input or exact output | - -## Table of contents - -### Constructors - -- [constructor](Trade.md#constructor) - -### Properties - -- [\_executionPrice](Trade.md#_executionprice) -- [\_inputAmount](Trade.md#_inputamount) -- [\_outputAmount](Trade.md#_outputamount) -- [\_priceImpact](Trade.md#_priceimpact) -- [swaps](Trade.md#swaps) -- [tradeType](Trade.md#tradetype) - -### Accessors - -- [executionPrice](Trade.md#executionprice) -- [inputAmount](Trade.md#inputamount) -- [outputAmount](Trade.md#outputamount) -- [priceImpact](Trade.md#priceimpact) -- [route](Trade.md#route) - -### Methods - -- [maximumAmountIn](Trade.md#maximumamountin) -- [minimumAmountOut](Trade.md#minimumamountout) -- [worstExecutionPrice](Trade.md#worstexecutionprice) -- [bestTradeExactIn](Trade.md#besttradeexactin) -- [bestTradeExactOut](Trade.md#besttradeexactout) -- [createUncheckedTrade](Trade.md#createuncheckedtrade) -- [createUncheckedTradeWithMultipleRoutes](Trade.md#createuncheckedtradewithmultipleroutes) -- [exactIn](Trade.md#exactin) -- [exactOut](Trade.md#exactout) -- [fromRoute](Trade.md#fromroute) -- [fromRoutes](Trade.md#fromroutes) - -## Constructors - -### constructor - -• `Private` **new Trade**<`TInput`, `TOutput`, `TTradeType`\>(`__namedParameters`) - -Construct a trade by passing in the pre-computed property values - -#### Type parameters - -| Name | Type | -| :------ | :------ | -| `TInput` | extends `Currency` | -| `TOutput` | extends `Currency` | -| `TTradeType` | extends `TradeType` | - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `__namedParameters` | `Object` | -| `__namedParameters.routes` | { `inputAmount`: `CurrencyAmount`<`TInput`\> ; `outputAmount`: `CurrencyAmount`<`TOutput`\> ; `route`: [`Route`](Route.md)<`TInput`, `TOutput`\> }[] | -| `__namedParameters.tradeType` | `TTradeType` | - -#### Defined in - -[entities/trade.ts:397](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/trade.ts#L397) - -## Properties - -### \_executionPrice - -• `Private` **\_executionPrice**: `undefined` \| `Price`<`TInput`, `TOutput`\> - -The cached result of the computed execution price - -#### Defined in - -[entities/trade.ts:143](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/trade.ts#L143) - -___ - -### \_inputAmount - -• `Private` **\_inputAmount**: `undefined` \| `CurrencyAmount`<`TInput`\> - -The cached result of the input amount computation - -#### Defined in - -[entities/trade.ts:97](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/trade.ts#L97) - -___ - -### \_outputAmount - -• `Private` **\_outputAmount**: `undefined` \| `CurrencyAmount`<`TOutput`\> - -The cached result of the output amount computation - -#### Defined in - -[entities/trade.ts:120](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/trade.ts#L120) - -___ - -### \_priceImpact - -• `Private` **\_priceImpact**: `undefined` \| `Percent` - -The cached result of the price impact computation - -#### Defined in - -[entities/trade.ts:164](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/trade.ts#L164) - -___ - -### swaps - -• `Readonly` **swaps**: { `inputAmount`: `CurrencyAmount`<`TInput`\> ; `outputAmount`: `CurrencyAmount`<`TOutput`\> ; `route`: [`Route`](Route.md)<`TInput`, `TOutput`\> }[] - -The swaps of the trade, i.e. which routes and how much is swapped in each that -make up the trade. - -#### Defined in - -[entities/trade.ts:82](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/trade.ts#L82) - -___ - -### tradeType - -• `Readonly` **tradeType**: `TTradeType` - -The type of the trade, either exact in or exact out. - -#### Defined in - -[entities/trade.ts:91](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/trade.ts#L91) - -## Accessors - -### executionPrice - -• `get` **executionPrice**(): `Price`<`TInput`, `TOutput`\> - -The price expressed in terms of output amount/input amount. - -#### Returns - -`Price`<`TInput`, `TOutput`\> - -#### Defined in - -[entities/trade.ts:148](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/trade.ts#L148) - -___ - -### inputAmount - -• `get` **inputAmount**(): `CurrencyAmount`<`TInput`\> - -The input amount for the trade assuming no slippage. - -#### Returns - -`CurrencyAmount`<`TInput`\> - -#### Defined in - -[entities/trade.ts:102](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/trade.ts#L102) - -___ - -### outputAmount - -• `get` **outputAmount**(): `CurrencyAmount`<`TOutput`\> - -The output amount for the trade assuming no slippage. - -#### Returns - -`CurrencyAmount`<`TOutput`\> - -#### Defined in - -[entities/trade.ts:125](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/trade.ts#L125) - -___ - -### priceImpact - -• `get` **priceImpact**(): `Percent` - -Returns the percent difference between the route's mid price and the price impact - -#### Returns - -`Percent` - -#### Defined in - -[entities/trade.ts:169](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/trade.ts#L169) - -___ - -### route - -• `get` **route**(): [`Route`](Route.md)<`TInput`, `TOutput`\> - -**`Deprecated`** - -Deprecated in favor of 'swaps' property. If the trade consists of multiple routes -this will return an error. - -When the trade consists of just a single route, this returns the route of the trade, -i.e. which pools the trade goes through. - -#### Returns - -[`Route`](Route.md)<`TInput`, `TOutput`\> - -#### Defined in - -[entities/trade.ts:73](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/trade.ts#L73) - -## Methods - -### maximumAmountIn - -▸ **maximumAmountIn**(`slippageTolerance`, `amountIn?`): `CurrencyAmount`<`TInput`\> - -Get the maximum amount in that can be spent via this trade for the given slippage tolerance - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `slippageTolerance` | `Percent` | The tolerance of unfavorable slippage from the execution price of this trade | -| `amountIn` | `CurrencyAmount`<`TInput`\> | - | - -#### Returns - -`CurrencyAmount`<`TInput`\> - -The amount in - -#### Defined in - -[entities/trade.ts:456](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/trade.ts#L456) - -___ - -### minimumAmountOut - -▸ **minimumAmountOut**(`slippageTolerance`, `amountOut?`): `CurrencyAmount`<`TOutput`\> - -Get the minimum amount that must be received from this trade for the given slippage tolerance - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `slippageTolerance` | `Percent` | The tolerance of unfavorable slippage from the execution price of this trade | -| `amountOut` | `CurrencyAmount`<`TOutput`\> | - | - -#### Returns - -`CurrencyAmount`<`TOutput`\> - -The amount out - -#### Defined in - -[entities/trade.ts:438](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/trade.ts#L438) - -___ - -### worstExecutionPrice - -▸ **worstExecutionPrice**(`slippageTolerance`): `Price`<`TInput`, `TOutput`\> - -Return the execution price after accounting for slippage tolerance - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `slippageTolerance` | `Percent` | the allowed tolerated slippage | - -#### Returns - -`Price`<`TInput`, `TOutput`\> - -The execution price - -#### Defined in - -[entities/trade.ts:471](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/trade.ts#L471) - -___ - -### bestTradeExactIn - -▸ `Static` **bestTradeExactIn**<`TInput`, `TOutput`\>(`pools`, `currencyAmountIn`, `currencyOut`, `__namedParameters?`, `currentPools?`, `nextAmountIn?`, `bestTrades?`): `Promise`<[`Trade`](Trade.md)<`TInput`, `TOutput`, `EXACT_INPUT`\>[]\> - -Given a list of pools, and a fixed amount in, returns the top `maxNumResults` trades that go from an input token -amount to an output token, making at most `maxHops` hops. -Note this does not consider aggregation, as routes are linear. It's possible a better route exists by splitting -the amount in among multiple routes. - -#### Type parameters - -| Name | Type | -| :------ | :------ | -| `TInput` | extends `Currency` | -| `TOutput` | extends `Currency` | - -#### Parameters - -| Name | Type | Default value | Description | -| :------ | :------ | :------ | :------ | -| `pools` | [`Pool`](Pool.md)[] | `undefined` | the pools to consider in finding the best trade | -| `currencyAmountIn` | `CurrencyAmount`<`TInput`\> | `undefined` | used in recursion; the original value of the currencyAmountIn parameter | -| `currencyOut` | `TOutput` | `undefined` | the desired currency out | -| `__namedParameters` | [`BestTradeOptions`](../interfaces/BestTradeOptions.md) | `{}` | - | -| `currentPools` | [`Pool`](Pool.md)[] | `[]` | used in recursion; the current list of pools | -| `nextAmountIn` | `CurrencyAmount`<`Currency`\> | `currencyAmountIn` | exact amount of input currency to spend | -| `bestTrades` | [`Trade`](Trade.md)<`TInput`, `TOutput`, `EXACT_INPUT`\>[] | `[]` | used in recursion; the current list of best trades | - -#### Returns - -`Promise`<[`Trade`](Trade.md)<`TInput`, `TOutput`, `EXACT_INPUT`\>[]\> - -The exact in trade - -#### Defined in - -[entities/trade.ts:495](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/trade.ts#L495) - -___ - -### bestTradeExactOut - -▸ `Static` **bestTradeExactOut**<`TInput`, `TOutput`\>(`pools`, `currencyIn`, `currencyAmountOut`, `__namedParameters?`, `currentPools?`, `nextAmountOut?`, `bestTrades?`): `Promise`<[`Trade`](Trade.md)<`TInput`, `TOutput`, `EXACT_OUTPUT`\>[]\> - -similar to the above method but instead targets a fixed output amount -given a list of pools, and a fixed amount out, returns the top `maxNumResults` trades that go from an input token -to an output token amount, making at most `maxHops` hops -note this does not consider aggregation, as routes are linear. it's possible a better route exists by splitting -the amount in among multiple routes. - -#### Type parameters - -| Name | Type | -| :------ | :------ | -| `TInput` | extends `Currency` | -| `TOutput` | extends `Currency` | - -#### Parameters - -| Name | Type | Default value | Description | -| :------ | :------ | :------ | :------ | -| `pools` | [`Pool`](Pool.md)[] | `undefined` | the pools to consider in finding the best trade | -| `currencyIn` | `TInput` | `undefined` | the currency to spend | -| `currencyAmountOut` | `CurrencyAmount`<`TOutput`\> | `undefined` | the desired currency amount out | -| `__namedParameters` | [`BestTradeOptions`](../interfaces/BestTradeOptions.md) | `{}` | - | -| `currentPools` | [`Pool`](Pool.md)[] | `[]` | used in recursion; the current list of pools | -| `nextAmountOut` | `CurrencyAmount`<`Currency`\> | `currencyAmountOut` | the exact amount of currency out | -| `bestTrades` | [`Trade`](Trade.md)<`TInput`, `TOutput`, `EXACT_OUTPUT`\>[] | `[]` | used in recursion; the current list of best trades | - -#### Returns - -`Promise`<[`Trade`](Trade.md)<`TInput`, `TOutput`, `EXACT_OUTPUT`\>[]\> - -The exact out trade - -#### Defined in - -[entities/trade.ts:576](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/trade.ts#L576) - -___ - -### createUncheckedTrade - -▸ `Static` **createUncheckedTrade**<`TInput`, `TOutput`, `TTradeType`\>(`constructorArguments`): [`Trade`](Trade.md)<`TInput`, `TOutput`, `TTradeType`\> - -Creates a trade without computing the result of swapping through the route. Useful when you have simulated the trade -elsewhere and do not have any tick data - -#### Type parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `TInput` | extends `Currency` | The input token, either Ether or an ERC-20 | -| `TOutput` | extends `Currency` | The output token, either Ether or an ERC-20 | -| `TTradeType` | extends `TradeType` | The type of the trade, either exact in or exact out | - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `constructorArguments` | `Object` | The arguments passed to the trade constructor | -| `constructorArguments.inputAmount` | `CurrencyAmount`<`TInput`\> | - | -| `constructorArguments.outputAmount` | `CurrencyAmount`<`TOutput`\> | - | -| `constructorArguments.route` | [`Route`](Route.md)<`TInput`, `TOutput`\> | - | -| `constructorArguments.tradeType` | `TTradeType` | - | - -#### Returns - -[`Trade`](Trade.md)<`TInput`, `TOutput`, `TTradeType`\> - -The unchecked trade - -#### Defined in - -[entities/trade.ts:346](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/trade.ts#L346) - -___ - -### createUncheckedTradeWithMultipleRoutes - -▸ `Static` **createUncheckedTradeWithMultipleRoutes**<`TInput`, `TOutput`, `TTradeType`\>(`constructorArguments`): [`Trade`](Trade.md)<`TInput`, `TOutput`, `TTradeType`\> - -Creates a trade without computing the result of swapping through the routes. Useful when you have simulated the trade -elsewhere and do not have any tick data - -#### Type parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `TInput` | extends `Currency` | The input token, either Ether or an ERC-20 | -| `TOutput` | extends `Currency` | The output token, either Ether or an ERC-20 | -| `TTradeType` | extends `TradeType` | The type of the trade, either exact in or exact out | - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `constructorArguments` | `Object` | The arguments passed to the trade constructor | -| `constructorArguments.routes` | { `inputAmount`: `CurrencyAmount`<`TInput`\> ; `outputAmount`: `CurrencyAmount`<`TOutput`\> ; `route`: [`Route`](Route.md)<`TInput`, `TOutput`\> }[] | - | -| `constructorArguments.tradeType` | `TTradeType` | - | - -#### Returns - -[`Trade`](Trade.md)<`TInput`, `TOutput`, `TTradeType`\> - -The unchecked trade - -#### Defined in - -[entities/trade.ts:377](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/trade.ts#L377) - -___ - -### exactIn - -▸ `Static` **exactIn**<`TInput`, `TOutput`\>(`route`, `amountIn`): `Promise`<[`Trade`](Trade.md)<`TInput`, `TOutput`, `EXACT_INPUT`\>\> - -Constructs an exact in trade with the given amount in and route - -#### Type parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `TInput` | extends `Currency` | The input token, either Ether or an ERC-20 | -| `TOutput` | extends `Currency` | The output token, either Ether or an ERC-20 | - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `route` | [`Route`](Route.md)<`TInput`, `TOutput`\> | The route of the exact in trade | -| `amountIn` | `CurrencyAmount`<`TInput`\> | The amount being passed in | - -#### Returns - -`Promise`<[`Trade`](Trade.md)<`TInput`, `TOutput`, `EXACT_INPUT`\>\> - -The exact in trade - -#### Defined in - -[entities/trade.ts:194](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/trade.ts#L194) - -___ - -### exactOut - -▸ `Static` **exactOut**<`TInput`, `TOutput`\>(`route`, `amountOut`): `Promise`<[`Trade`](Trade.md)<`TInput`, `TOutput`, `EXACT_OUTPUT`\>\> - -Constructs an exact out trade with the given amount out and route - -#### Type parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `TInput` | extends `Currency` | The input token, either Ether or an ERC-20 | -| `TOutput` | extends `Currency` | The output token, either Ether or an ERC-20 | - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `route` | [`Route`](Route.md)<`TInput`, `TOutput`\> | The route of the exact out trade | -| `amountOut` | `CurrencyAmount`<`TOutput`\> | The amount returned by the trade | - -#### Returns - -`Promise`<[`Trade`](Trade.md)<`TInput`, `TOutput`, `EXACT_OUTPUT`\>\> - -The exact out trade - -#### Defined in - -[entities/trade.ts:209](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/trade.ts#L209) - -___ - -### fromRoute - -▸ `Static` **fromRoute**<`TInput`, `TOutput`, `TTradeType`\>(`route`, `amount`, `tradeType`): `Promise`<[`Trade`](Trade.md)<`TInput`, `TOutput`, `TTradeType`\>\> - -Constructs a trade by simulating swaps through the given route - -#### Type parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `TInput` | extends `Currency` | The input token, either Ether or an ERC-20. | -| `TOutput` | extends `Currency` | The output token, either Ether or an ERC-20. | -| `TTradeType` | extends `TradeType` | The type of the trade, either exact in or exact out. | - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `route` | [`Route`](Route.md)<`TInput`, `TOutput`\> | route to swap through | -| `amount` | `TTradeType` extends `EXACT_INPUT` ? `CurrencyAmount`<`TInput`\> : `CurrencyAmount`<`TOutput`\> | the amount specified, either input or output, depending on tradeType | -| `tradeType` | `TTradeType` | whether the trade is an exact input or exact output swap | - -#### Returns - -`Promise`<[`Trade`](Trade.md)<`TInput`, `TOutput`, `TTradeType`\>\> - -The route - -#### Defined in - -[entities/trade.ts:226](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/trade.ts#L226) - -___ - -### fromRoutes - -▸ `Static` **fromRoutes**<`TInput`, `TOutput`, `TTradeType`\>(`routes`, `tradeType`): `Promise`<[`Trade`](Trade.md)<`TInput`, `TOutput`, `TTradeType`\>\> - -Constructs a trade from routes by simulating swaps - -#### Type parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `TInput` | extends `Currency` | The input token, either Ether or an ERC-20. | -| `TOutput` | extends `Currency` | The output token, either Ether or an ERC-20. | -| `TTradeType` | extends `TradeType` | The type of the trade, either exact in or exact out. | - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `routes` | { `amount`: `TTradeType` extends `EXACT_INPUT` ? `CurrencyAmount`<`TInput`\> : `CurrencyAmount`<`TOutput`\> ; `route`: [`Route`](Route.md)<`TInput`, `TOutput`\> }[] | the routes to swap through and how much of the amount should be routed through each | -| `tradeType` | `TTradeType` | whether the trade is an exact input or exact output swap | - -#### Returns - -`Promise`<[`Trade`](Trade.md)<`TInput`, `TOutput`, `TTradeType`\>\> - -The trade - -#### Defined in - -[entities/trade.ts:276](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/trade.ts#L276) diff --git a/docs/sdk/v3/reference/enums/FeeAmount.md b/docs/sdk/v3/reference/enums/FeeAmount.md deleted file mode 100644 index 77cb5ed2c..000000000 --- a/docs/sdk/v3/reference/enums/FeeAmount.md +++ /dev/null @@ -1,54 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / FeeAmount - -# Enumeration: FeeAmount - -The default factory enabled fee amounts, denominated in hundredths of bips. - -## Table of contents - -### Enumeration Members - -- [HIGH](FeeAmount.md#high) -- [LOW](FeeAmount.md#low) -- [LOWEST](FeeAmount.md#lowest) -- [MEDIUM](FeeAmount.md#medium) - -## Enumeration Members - -### HIGH - -• **HIGH** = ``10000`` - -#### Defined in - -[constants.ts:14](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/constants.ts#L14) - -___ - -### LOW - -• **LOW** = ``500`` - -#### Defined in - -[constants.ts:12](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/constants.ts#L12) - -___ - -### LOWEST - -• **LOWEST** = ``100`` - -#### Defined in - -[constants.ts:11](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/constants.ts#L11) - -___ - -### MEDIUM - -• **MEDIUM** = ``3000`` - -#### Defined in - -[constants.ts:13](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/constants.ts#L13) diff --git a/docs/sdk/v3/reference/interfaces/AllowedPermitArguments.md b/docs/sdk/v3/reference/interfaces/AllowedPermitArguments.md deleted file mode 100644 index f9856cebf..000000000 --- a/docs/sdk/v3/reference/interfaces/AllowedPermitArguments.md +++ /dev/null @@ -1,63 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / AllowedPermitArguments - -# Interface: AllowedPermitArguments - -## Table of contents - -### Properties - -- [expiry](AllowedPermitArguments.md#expiry) -- [nonce](AllowedPermitArguments.md#nonce) -- [r](AllowedPermitArguments.md#r) -- [s](AllowedPermitArguments.md#s) -- [v](AllowedPermitArguments.md#v) - -## Properties - -### expiry - -• **expiry**: `BigintIsh` - -#### Defined in - -[selfPermit.ts:19](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/selfPermit.ts#L19) - -___ - -### nonce - -• **nonce**: `BigintIsh` - -#### Defined in - -[selfPermit.ts:18](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/selfPermit.ts#L18) - -___ - -### r - -• **r**: `string` - -#### Defined in - -[selfPermit.ts:16](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/selfPermit.ts#L16) - -___ - -### s - -• **s**: `string` - -#### Defined in - -[selfPermit.ts:17](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/selfPermit.ts#L17) - -___ - -### v - -• **v**: ``0`` \| ``1`` \| ``27`` \| ``28`` - -#### Defined in - -[selfPermit.ts:15](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/selfPermit.ts#L15) diff --git a/docs/sdk/v3/reference/interfaces/BestTradeOptions.md b/docs/sdk/v3/reference/interfaces/BestTradeOptions.md deleted file mode 100644 index 37ad44878..000000000 --- a/docs/sdk/v3/reference/interfaces/BestTradeOptions.md +++ /dev/null @@ -1,30 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / BestTradeOptions - -# Interface: BestTradeOptions - -## Table of contents - -### Properties - -- [maxHops](BestTradeOptions.md#maxhops) -- [maxNumResults](BestTradeOptions.md#maxnumresults) - -## Properties - -### maxHops - -• `Optional` **maxHops**: `number` - -#### Defined in - -[entities/trade.ts:50](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/trade.ts#L50) - -___ - -### maxNumResults - -• `Optional` **maxNumResults**: `number` - -#### Defined in - -[entities/trade.ts:48](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/trade.ts#L48) diff --git a/docs/sdk/v3/reference/interfaces/ClaimOptions.md b/docs/sdk/v3/reference/interfaces/ClaimOptions.md deleted file mode 100644 index 7415cba3a..000000000 --- a/docs/sdk/v3/reference/interfaces/ClaimOptions.md +++ /dev/null @@ -1,49 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / ClaimOptions - -# Interface: ClaimOptions - -Options to specify when claiming rewards. - -## Table of contents - -### Properties - -- [amount](ClaimOptions.md#amount) -- [recipient](ClaimOptions.md#recipient) -- [tokenId](ClaimOptions.md#tokenid) - -## Properties - -### amount - -• `Optional` **amount**: `BigintIsh` - -The amount of `rewardToken` to claim. 0 claims all. - -#### Defined in - -[staker.ts:52](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/staker.ts#L52) - -___ - -### recipient - -• **recipient**: `string` - -Address to send rewards to. - -#### Defined in - -[staker.ts:47](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/staker.ts#L47) - -___ - -### tokenId - -• **tokenId**: `BigintIsh` - -The id of the NFT - -#### Defined in - -[staker.ts:42](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/staker.ts#L42) diff --git a/docs/sdk/v3/reference/interfaces/CollectOptions.md b/docs/sdk/v3/reference/interfaces/CollectOptions.md deleted file mode 100644 index 2bcabeb10..000000000 --- a/docs/sdk/v3/reference/interfaces/CollectOptions.md +++ /dev/null @@ -1,60 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / CollectOptions - -# Interface: CollectOptions - -## Table of contents - -### Properties - -- [expectedCurrencyOwed0](CollectOptions.md#expectedcurrencyowed0) -- [expectedCurrencyOwed1](CollectOptions.md#expectedcurrencyowed1) -- [recipient](CollectOptions.md#recipient) -- [tokenId](CollectOptions.md#tokenid) - -## Properties - -### expectedCurrencyOwed0 - -• **expectedCurrencyOwed0**: `CurrencyAmount`<`Currency`\> - -Expected value of tokensOwed0, including as-of-yet-unaccounted-for fees/liquidity value to be burned - -#### Defined in - -[nonfungiblePositionManager.ts:114](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L114) - -___ - -### expectedCurrencyOwed1 - -• **expectedCurrencyOwed1**: `CurrencyAmount`<`Currency`\> - -Expected value of tokensOwed1, including as-of-yet-unaccounted-for fees/liquidity value to be burned - -#### Defined in - -[nonfungiblePositionManager.ts:119](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L119) - -___ - -### recipient - -• **recipient**: `string` - -The account that should receive the tokens. - -#### Defined in - -[nonfungiblePositionManager.ts:124](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L124) - -___ - -### tokenId - -• **tokenId**: `BigintIsh` - -Indicates the ID of the position to collect for. - -#### Defined in - -[nonfungiblePositionManager.ts:109](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L109) diff --git a/docs/sdk/v3/reference/interfaces/CommonAddLiquidityOptions.md b/docs/sdk/v3/reference/interfaces/CommonAddLiquidityOptions.md deleted file mode 100644 index db9f9d0b1..000000000 --- a/docs/sdk/v3/reference/interfaces/CommonAddLiquidityOptions.md +++ /dev/null @@ -1,75 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / CommonAddLiquidityOptions - -# Interface: CommonAddLiquidityOptions - -Options for producing the calldata to add liquidity. - -## Table of contents - -### Properties - -- [deadline](CommonAddLiquidityOptions.md#deadline) -- [slippageTolerance](CommonAddLiquidityOptions.md#slippagetolerance) -- [token0Permit](CommonAddLiquidityOptions.md#token0permit) -- [token1Permit](CommonAddLiquidityOptions.md#token1permit) -- [useNative](CommonAddLiquidityOptions.md#usenative) - -## Properties - -### deadline - -• **deadline**: `BigintIsh` - -When the transaction expires, in epoch seconds. - -#### Defined in - -[nonfungiblePositionManager.ts:56](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L56) - -___ - -### slippageTolerance - -• **slippageTolerance**: `Percent` - -How much the pool price is allowed to move. - -#### Defined in - -[nonfungiblePositionManager.ts:51](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L51) - -___ - -### token0Permit - -• `Optional` **token0Permit**: [`PermitOptions`](../modules.md#permitoptions) - -The optional permit parameters for spending token0 - -#### Defined in - -[nonfungiblePositionManager.ts:66](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L66) - -___ - -### token1Permit - -• `Optional` **token1Permit**: [`PermitOptions`](../modules.md#permitoptions) - -The optional permit parameters for spending token1 - -#### Defined in - -[nonfungiblePositionManager.ts:71](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L71) - -___ - -### useNative - -• `Optional` **useNative**: `NativeCurrency` - -Whether to spend ether. If true, one of the pool tokens must be WETH, by default false - -#### Defined in - -[nonfungiblePositionManager.ts:61](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L61) diff --git a/docs/sdk/v3/reference/interfaces/FeeOptions.md b/docs/sdk/v3/reference/interfaces/FeeOptions.md deleted file mode 100644 index 3ca35a9a0..000000000 --- a/docs/sdk/v3/reference/interfaces/FeeOptions.md +++ /dev/null @@ -1,34 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / FeeOptions - -# Interface: FeeOptions - -## Table of contents - -### Properties - -- [fee](FeeOptions.md#fee) -- [recipient](FeeOptions.md#recipient) - -## Properties - -### fee - -• **fee**: `Percent` - -The percent of the output that will be taken as a fee. - -#### Defined in - -[payments.ts:11](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/payments.ts#L11) - -___ - -### recipient - -• **recipient**: `string` - -The recipient of the fee. - -#### Defined in - -[payments.ts:16](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/payments.ts#L16) diff --git a/docs/sdk/v3/reference/interfaces/IncentiveKey.md b/docs/sdk/v3/reference/interfaces/IncentiveKey.md deleted file mode 100644 index ce57f8795..000000000 --- a/docs/sdk/v3/reference/interfaces/IncentiveKey.md +++ /dev/null @@ -1,75 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / IncentiveKey - -# Interface: IncentiveKey - -Represents a unique staking program. - -## Table of contents - -### Properties - -- [endTime](IncentiveKey.md#endtime) -- [pool](IncentiveKey.md#pool) -- [refundee](IncentiveKey.md#refundee) -- [rewardToken](IncentiveKey.md#rewardtoken) -- [startTime](IncentiveKey.md#starttime) - -## Properties - -### endTime - -• **endTime**: `BigintIsh` - -The time that the incentive program ends. - -#### Defined in - -[staker.ts:28](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/staker.ts#L28) - -___ - -### pool - -• **pool**: [`Pool`](../classes/Pool.md) - -The pool that the staked positions must provide in. - -#### Defined in - -[staker.ts:20](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/staker.ts#L20) - -___ - -### refundee - -• **refundee**: `string` - -The address which receives any remaining reward tokens at `endTime`. - -#### Defined in - -[staker.ts:32](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/staker.ts#L32) - -___ - -### rewardToken - -• **rewardToken**: `Token` - -The token rewarded for participating in the staking program. - -#### Defined in - -[staker.ts:16](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/staker.ts#L16) - -___ - -### startTime - -• **startTime**: `BigintIsh` - -The time when the incentive program begins. - -#### Defined in - -[staker.ts:24](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/staker.ts#L24) diff --git a/docs/sdk/v3/reference/interfaces/IncreaseSpecificOptions.md b/docs/sdk/v3/reference/interfaces/IncreaseSpecificOptions.md deleted file mode 100644 index afb55e57f..000000000 --- a/docs/sdk/v3/reference/interfaces/IncreaseSpecificOptions.md +++ /dev/null @@ -1,21 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / IncreaseSpecificOptions - -# Interface: IncreaseSpecificOptions - -## Table of contents - -### Properties - -- [tokenId](IncreaseSpecificOptions.md#tokenid) - -## Properties - -### tokenId - -• **tokenId**: `BigintIsh` - -Indicates the ID of the position to increase liquidity for. - -#### Defined in - -[nonfungiblePositionManager.ts:41](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L41) diff --git a/docs/sdk/v3/reference/interfaces/MethodParameters.md b/docs/sdk/v3/reference/interfaces/MethodParameters.md deleted file mode 100644 index 303a07b12..000000000 --- a/docs/sdk/v3/reference/interfaces/MethodParameters.md +++ /dev/null @@ -1,36 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / MethodParameters - -# Interface: MethodParameters - -Generated method parameters for executing a call. - -## Table of contents - -### Properties - -- [calldata](MethodParameters.md#calldata) -- [value](MethodParameters.md#value) - -## Properties - -### calldata - -• **calldata**: `string` - -The hex encoded calldata to perform the given operation - -#### Defined in - -[utils/calldata.ts:11](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/calldata.ts#L11) - -___ - -### value - -• **value**: `string` - -The amount of ether (wei) to send in hex. - -#### Defined in - -[utils/calldata.ts:15](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/calldata.ts#L15) diff --git a/docs/sdk/v3/reference/interfaces/MintSpecificOptions.md b/docs/sdk/v3/reference/interfaces/MintSpecificOptions.md deleted file mode 100644 index a11e98ca2..000000000 --- a/docs/sdk/v3/reference/interfaces/MintSpecificOptions.md +++ /dev/null @@ -1,34 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / MintSpecificOptions - -# Interface: MintSpecificOptions - -## Table of contents - -### Properties - -- [createPool](MintSpecificOptions.md#createpool) -- [recipient](MintSpecificOptions.md#recipient) - -## Properties - -### createPool - -• `Optional` **createPool**: `boolean` - -Creates pool if not initialized before mint. - -#### Defined in - -[nonfungiblePositionManager.ts:34](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L34) - -___ - -### recipient - -• **recipient**: `string` - -The account that should receive the minted NFT. - -#### Defined in - -[nonfungiblePositionManager.ts:29](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L29) diff --git a/docs/sdk/v3/reference/interfaces/NFTPermitOptions.md b/docs/sdk/v3/reference/interfaces/NFTPermitOptions.md deleted file mode 100644 index 253979f4a..000000000 --- a/docs/sdk/v3/reference/interfaces/NFTPermitOptions.md +++ /dev/null @@ -1,63 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / NFTPermitOptions - -# Interface: NFTPermitOptions - -## Table of contents - -### Properties - -- [deadline](NFTPermitOptions.md#deadline) -- [r](NFTPermitOptions.md#r) -- [s](NFTPermitOptions.md#s) -- [spender](NFTPermitOptions.md#spender) -- [v](NFTPermitOptions.md#v) - -## Properties - -### deadline - -• **deadline**: `BigintIsh` - -#### Defined in - -[nonfungiblePositionManager.ts:131](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L131) - -___ - -### r - -• **r**: `string` - -#### Defined in - -[nonfungiblePositionManager.ts:129](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L129) - -___ - -### s - -• **s**: `string` - -#### Defined in - -[nonfungiblePositionManager.ts:130](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L130) - -___ - -### spender - -• **spender**: `string` - -#### Defined in - -[nonfungiblePositionManager.ts:132](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L132) - -___ - -### v - -• **v**: ``0`` \| ``1`` \| ``27`` \| ``28`` - -#### Defined in - -[nonfungiblePositionManager.ts:128](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L128) diff --git a/docs/sdk/v3/reference/interfaces/QuoteOptions.md b/docs/sdk/v3/reference/interfaces/QuoteOptions.md deleted file mode 100644 index 16414828b..000000000 --- a/docs/sdk/v3/reference/interfaces/QuoteOptions.md +++ /dev/null @@ -1,36 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / QuoteOptions - -# Interface: QuoteOptions - -Optional arguments to send to the quoter. - -## Table of contents - -### Properties - -- [sqrtPriceLimitX96](QuoteOptions.md#sqrtpricelimitx96) -- [useQuoterV2](QuoteOptions.md#usequoterv2) - -## Properties - -### sqrtPriceLimitX96 - -• `Optional` **sqrtPriceLimitX96**: `BigintIsh` - -The optional price limit for the trade. - -#### Defined in - -[quoter.ts:17](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/quoter.ts#L17) - -___ - -### useQuoterV2 - -• `Optional` **useQuoterV2**: `boolean` - -The optional quoter interface to use - -#### Defined in - -[quoter.ts:22](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/quoter.ts#L22) diff --git a/docs/sdk/v3/reference/interfaces/RemoveLiquidityOptions.md b/docs/sdk/v3/reference/interfaces/RemoveLiquidityOptions.md deleted file mode 100644 index e775fc21c..000000000 --- a/docs/sdk/v3/reference/interfaces/RemoveLiquidityOptions.md +++ /dev/null @@ -1,101 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / RemoveLiquidityOptions - -# Interface: RemoveLiquidityOptions - -Options for producing the calldata to exit a position. - -## Table of contents - -### Properties - -- [burnToken](RemoveLiquidityOptions.md#burntoken) -- [collectOptions](RemoveLiquidityOptions.md#collectoptions) -- [deadline](RemoveLiquidityOptions.md#deadline) -- [liquidityPercentage](RemoveLiquidityOptions.md#liquiditypercentage) -- [permit](RemoveLiquidityOptions.md#permit) -- [slippageTolerance](RemoveLiquidityOptions.md#slippagetolerance) -- [tokenId](RemoveLiquidityOptions.md#tokenid) - -## Properties - -### burnToken - -• `Optional` **burnToken**: `boolean` - -Whether the NFT should be burned if the entire position is being exited, by default false. - -#### Defined in - -[nonfungiblePositionManager.ts:162](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L162) - -___ - -### collectOptions - -• **collectOptions**: `Omit`<[`CollectOptions`](CollectOptions.md), ``"tokenId"``\> - -Parameters to be passed on to collect - -#### Defined in - -[nonfungiblePositionManager.ts:172](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L172) - -___ - -### deadline - -• **deadline**: `BigintIsh` - -When the transaction expires, in epoch seconds. - -#### Defined in - -[nonfungiblePositionManager.ts:157](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L157) - -___ - -### liquidityPercentage - -• **liquidityPercentage**: `Percent` - -The percentage of position liquidity to exit. - -#### Defined in - -[nonfungiblePositionManager.ts:147](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L147) - -___ - -### permit - -• `Optional` **permit**: [`NFTPermitOptions`](NFTPermitOptions.md) - -The optional permit of the token ID being exited, in case the exit transaction is being sent by an account that does not own the NFT - -#### Defined in - -[nonfungiblePositionManager.ts:167](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L167) - -___ - -### slippageTolerance - -• **slippageTolerance**: `Percent` - -How much the pool price is allowed to move. - -#### Defined in - -[nonfungiblePositionManager.ts:152](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L152) - -___ - -### tokenId - -• **tokenId**: `BigintIsh` - -The ID of the token to exit - -#### Defined in - -[nonfungiblePositionManager.ts:142](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L142) diff --git a/docs/sdk/v3/reference/interfaces/SafeTransferOptions.md b/docs/sdk/v3/reference/interfaces/SafeTransferOptions.md deleted file mode 100644 index f6d085f9f..000000000 --- a/docs/sdk/v3/reference/interfaces/SafeTransferOptions.md +++ /dev/null @@ -1,60 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / SafeTransferOptions - -# Interface: SafeTransferOptions - -## Table of contents - -### Properties - -- [data](SafeTransferOptions.md#data) -- [recipient](SafeTransferOptions.md#recipient) -- [sender](SafeTransferOptions.md#sender) -- [tokenId](SafeTransferOptions.md#tokenid) - -## Properties - -### data - -• `Optional` **data**: `string` - -The optional parameter that passes data to the `onERC721Received` call for the staker - -#### Defined in - -[nonfungiblePositionManager.ts:97](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L97) - -___ - -### recipient - -• **recipient**: `string` - -The account that should receive the NFT. - -#### Defined in - -[nonfungiblePositionManager.ts:88](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L88) - -___ - -### sender - -• **sender**: `string` - -The account sending the NFT. - -#### Defined in - -[nonfungiblePositionManager.ts:83](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L83) - -___ - -### tokenId - -• **tokenId**: `BigintIsh` - -The id of the token being sent. - -#### Defined in - -[nonfungiblePositionManager.ts:93](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L93) diff --git a/docs/sdk/v3/reference/interfaces/StandardPermitArguments.md b/docs/sdk/v3/reference/interfaces/StandardPermitArguments.md deleted file mode 100644 index d468bf69d..000000000 --- a/docs/sdk/v3/reference/interfaces/StandardPermitArguments.md +++ /dev/null @@ -1,63 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / StandardPermitArguments - -# Interface: StandardPermitArguments - -## Table of contents - -### Properties - -- [amount](StandardPermitArguments.md#amount) -- [deadline](StandardPermitArguments.md#deadline) -- [r](StandardPermitArguments.md#r) -- [s](StandardPermitArguments.md#s) -- [v](StandardPermitArguments.md#v) - -## Properties - -### amount - -• **amount**: `BigintIsh` - -#### Defined in - -[selfPermit.ts:10](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/selfPermit.ts#L10) - -___ - -### deadline - -• **deadline**: `BigintIsh` - -#### Defined in - -[selfPermit.ts:11](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/selfPermit.ts#L11) - -___ - -### r - -• **r**: `string` - -#### Defined in - -[selfPermit.ts:8](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/selfPermit.ts#L8) - -___ - -### s - -• **s**: `string` - -#### Defined in - -[selfPermit.ts:9](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/selfPermit.ts#L9) - -___ - -### v - -• **v**: ``0`` \| ``1`` \| ``27`` \| ``28`` - -#### Defined in - -[selfPermit.ts:7](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/selfPermit.ts#L7) diff --git a/docs/sdk/v3/reference/interfaces/SwapOptions.md b/docs/sdk/v3/reference/interfaces/SwapOptions.md deleted file mode 100644 index e77958be9..000000000 --- a/docs/sdk/v3/reference/interfaces/SwapOptions.md +++ /dev/null @@ -1,88 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / SwapOptions - -# Interface: SwapOptions - -Options for producing the arguments to send calls to the router. - -## Table of contents - -### Properties - -- [deadline](SwapOptions.md#deadline) -- [fee](SwapOptions.md#fee) -- [inputTokenPermit](SwapOptions.md#inputtokenpermit) -- [recipient](SwapOptions.md#recipient) -- [slippageTolerance](SwapOptions.md#slippagetolerance) -- [sqrtPriceLimitX96](SwapOptions.md#sqrtpricelimitx96) - -## Properties - -### deadline - -• **deadline**: `BigintIsh` - -When the transaction expires, in epoch seconds. - -#### Defined in - -[swapRouter.ts:30](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/swapRouter.ts#L30) - -___ - -### fee - -• `Optional` **fee**: [`FeeOptions`](FeeOptions.md) - -Optional information for taking a fee on output. - -#### Defined in - -[swapRouter.ts:45](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/swapRouter.ts#L45) - -___ - -### inputTokenPermit - -• `Optional` **inputTokenPermit**: [`PermitOptions`](../modules.md#permitoptions) - -The optional permit parameters for spending the input. - -#### Defined in - -[swapRouter.ts:35](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/swapRouter.ts#L35) - -___ - -### recipient - -• **recipient**: `string` - -The account that should receive the output. - -#### Defined in - -[swapRouter.ts:25](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/swapRouter.ts#L25) - -___ - -### slippageTolerance - -• **slippageTolerance**: `Percent` - -How much the execution price is allowed to move unfavorably from the trade execution price. - -#### Defined in - -[swapRouter.ts:20](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/swapRouter.ts#L20) - -___ - -### sqrtPriceLimitX96 - -• `Optional` **sqrtPriceLimitX96**: `BigintIsh` - -The optional price limit for the trade. - -#### Defined in - -[swapRouter.ts:40](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/swapRouter.ts#L40) diff --git a/docs/sdk/v3/reference/interfaces/TickConstructorArgs.md b/docs/sdk/v3/reference/interfaces/TickConstructorArgs.md deleted file mode 100644 index 6ce3179ed..000000000 --- a/docs/sdk/v3/reference/interfaces/TickConstructorArgs.md +++ /dev/null @@ -1,41 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / TickConstructorArgs - -# Interface: TickConstructorArgs - -## Table of contents - -### Properties - -- [index](TickConstructorArgs.md#index) -- [liquidityGross](TickConstructorArgs.md#liquiditygross) -- [liquidityNet](TickConstructorArgs.md#liquiditynet) - -## Properties - -### index - -• **index**: `number` - -#### Defined in - -[entities/tick.ts:7](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/tick.ts#L7) - -___ - -### liquidityGross - -• **liquidityGross**: `BigintIsh` - -#### Defined in - -[entities/tick.ts:8](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/tick.ts#L8) - -___ - -### liquidityNet - -• **liquidityNet**: `BigintIsh` - -#### Defined in - -[entities/tick.ts:9](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/tick.ts#L9) diff --git a/docs/sdk/v3/reference/interfaces/TickDataProvider.md b/docs/sdk/v3/reference/interfaces/TickDataProvider.md deleted file mode 100644 index 01e5b43ac..000000000 --- a/docs/sdk/v3/reference/interfaces/TickDataProvider.md +++ /dev/null @@ -1,63 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / TickDataProvider - -# Interface: TickDataProvider - -Provides information about ticks - -## Implemented by - -- [`NoTickDataProvider`](../classes/NoTickDataProvider.md) -- [`TickListDataProvider`](../classes/TickListDataProvider.md) - -## Table of contents - -### Methods - -- [getTick](TickDataProvider.md#gettick) -- [nextInitializedTickWithinOneWord](TickDataProvider.md#nextinitializedtickwithinoneword) - -## Methods - -### getTick - -▸ **getTick**(`tick`): `Promise`<{ `liquidityNet`: `BigintIsh` }\> - -Return information corresponding to a specific tick - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `tick` | `number` | the tick to load | - -#### Returns - -`Promise`<{ `liquidityNet`: `BigintIsh` }\> - -#### Defined in - -[entities/tickDataProvider.ts:11](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/tickDataProvider.ts#L11) - -___ - -### nextInitializedTickWithinOneWord - -▸ **nextInitializedTickWithinOneWord**(`tick`, `lte`, `tickSpacing`): `Promise`<[`number`, `boolean`]\> - -Return the next tick that is initialized within a single word - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `tick` | `number` | The current tick | -| `lte` | `boolean` | Whether the next tick should be lte the current tick | -| `tickSpacing` | `number` | The tick spacing of the pool | - -#### Returns - -`Promise`<[`number`, `boolean`]\> - -#### Defined in - -[entities/tickDataProvider.ts:19](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/tickDataProvider.ts#L19) diff --git a/docs/sdk/v3/reference/interfaces/WithdrawOptions.md b/docs/sdk/v3/reference/interfaces/WithdrawOptions.md deleted file mode 100644 index d1fdf62e7..000000000 --- a/docs/sdk/v3/reference/interfaces/WithdrawOptions.md +++ /dev/null @@ -1,36 +0,0 @@ -[@uniswap/v3-sdk](../README.md) / [Exports](../modules.md) / WithdrawOptions - -# Interface: WithdrawOptions - -Options to specify when withdrawing a position. - -## Table of contents - -### Properties - -- [data](WithdrawOptions.md#data) -- [owner](WithdrawOptions.md#owner) - -## Properties - -### data - -• `Optional` **data**: `string` - -Set when withdrawing. `data` is passed to `safeTransferFrom` when transferring the position from contract back to owner. - -#### Defined in - -[staker.ts:66](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/staker.ts#L66) - -___ - -### owner - -• **owner**: `string` - -Set when withdrawing. The position will be sent to `owner` on withdraw. - -#### Defined in - -[staker.ts:61](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/staker.ts#L61) diff --git a/docs/sdk/v3/reference/overview.md b/docs/sdk/v3/reference/overview.md deleted file mode 100644 index dfe5a7779..000000000 --- a/docs/sdk/v3/reference/overview.md +++ /dev/null @@ -1,484 +0,0 @@ ---- -id: overview -sidebar_position: 1 -title: Overview ---- - -## Table of contents - -### Enumerations - -- [FeeAmount](enums/FeeAmount.md) - -### Classes - -- [FullMath](classes/FullMath.md) -- [LiquidityMath](classes/LiquidityMath.md) -- [Multicall](classes/Multicall.md) -- [NoTickDataProvider](classes/NoTickDataProvider.md) -- [NonfungiblePositionManager](classes/NonfungiblePositionManager.md) -- [Payments](classes/Payments.md) -- [Pool](classes/Pool.md) -- [Position](classes/Position.md) -- [PositionLibrary](classes/PositionLibrary.md) -- [Route](classes/Route.md) -- [SelfPermit](classes/SelfPermit.md) -- [SqrtPriceMath](classes/SqrtPriceMath.md) -- [Staker](classes/Staker.md) -- [SwapMath](classes/SwapMath.md) -- [SwapQuoter](classes/SwapQuoter.md) -- [SwapRouter](classes/SwapRouter.md) -- [Tick](classes/Tick.md) -- [TickLibrary](classes/TickLibrary.md) -- [TickList](classes/TickList.md) -- [TickListDataProvider](classes/TickListDataProvider.md) -- [TickMath](classes/TickMath.md) -- [Trade](classes/Trade.md) - -### Interfaces - -- [AllowedPermitArguments](interfaces/AllowedPermitArguments.md) -- [BestTradeOptions](interfaces/BestTradeOptions.md) -- [ClaimOptions](interfaces/ClaimOptions.md) -- [CollectOptions](interfaces/CollectOptions.md) -- [CommonAddLiquidityOptions](interfaces/CommonAddLiquidityOptions.md) -- [FeeOptions](interfaces/FeeOptions.md) -- [IncentiveKey](interfaces/IncentiveKey.md) -- [IncreaseSpecificOptions](interfaces/IncreaseSpecificOptions.md) -- [MethodParameters](interfaces/MethodParameters.md) -- [MintSpecificOptions](interfaces/MintSpecificOptions.md) -- [NFTPermitOptions](interfaces/NFTPermitOptions.md) -- [QuoteOptions](interfaces/QuoteOptions.md) -- [RemoveLiquidityOptions](interfaces/RemoveLiquidityOptions.md) -- [SafeTransferOptions](interfaces/SafeTransferOptions.md) -- [StandardPermitArguments](interfaces/StandardPermitArguments.md) -- [SwapOptions](interfaces/SwapOptions.md) -- [TickConstructorArgs](interfaces/TickConstructorArgs.md) -- [TickDataProvider](interfaces/TickDataProvider.md) -- [WithdrawOptions](interfaces/WithdrawOptions.md) - -### Type Aliases - -- [AddLiquidityOptions](modules.md#addliquidityoptions) -- [FullWithdrawOptions](modules.md#fullwithdrawoptions) -- [IncreaseOptions](modules.md#increaseoptions) -- [MintOptions](modules.md#mintoptions) -- [PermitOptions](modules.md#permitoptions) - -### Variables - -- [ADDRESS\_ZERO](modules.md#address_zero) -- [FACTORY\_ADDRESS](modules.md#factory_address) -- [POOL\_INIT\_CODE\_HASH](modules.md#pool_init_code_hash) -- [TICK\_SPACINGS](modules.md#tick_spacings) - -### Functions - -- [computePoolAddress](modules.md#computepooladdress) -- [encodeRouteToPath](modules.md#encoderoutetopath) -- [encodeSqrtRatioX96](modules.md#encodesqrtratiox96) -- [isSorted](modules.md#issorted) -- [maxLiquidityForAmounts](modules.md#maxliquidityforamounts) -- [mostSignificantBit](modules.md#mostsignificantbit) -- [nearestUsableTick](modules.md#nearestusabletick) -- [priceToClosestTick](modules.md#pricetoclosesttick) -- [subIn256](modules.md#subin256) -- [tickToPrice](modules.md#ticktoprice) -- [toHex](modules.md#tohex) -- [tradeComparator](modules.md#tradecomparator) - -## Type Aliases - -### AddLiquidityOptions - -Ƭ **AddLiquidityOptions**: [`MintOptions`](modules.md#mintoptions) \| [`IncreaseOptions`](modules.md#increaseoptions) - -#### Defined in - -[nonfungiblePositionManager.ts:77](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L77) - -___ - -### FullWithdrawOptions - -Ƭ **FullWithdrawOptions**: [`ClaimOptions`](interfaces/ClaimOptions.md) & [`WithdrawOptions`](interfaces/WithdrawOptions.md) - -#### Defined in - -[staker.ts:8](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/staker.ts#L8) - -___ - -### IncreaseOptions - -Ƭ **IncreaseOptions**: [`CommonAddLiquidityOptions`](interfaces/CommonAddLiquidityOptions.md) & [`IncreaseSpecificOptions`](interfaces/IncreaseSpecificOptions.md) - -#### Defined in - -[nonfungiblePositionManager.ts:75](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L75) - -___ - -### MintOptions - -Ƭ **MintOptions**: [`CommonAddLiquidityOptions`](interfaces/CommonAddLiquidityOptions.md) & [`MintSpecificOptions`](interfaces/MintSpecificOptions.md) - -#### Defined in - -[nonfungiblePositionManager.ts:74](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/nonfungiblePositionManager.ts#L74) - -___ - -### PermitOptions - -Ƭ **PermitOptions**: [`StandardPermitArguments`](interfaces/StandardPermitArguments.md) \| [`AllowedPermitArguments`](interfaces/AllowedPermitArguments.md) - -#### Defined in - -[selfPermit.ts:22](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/selfPermit.ts#L22) - -## Variables - -### ADDRESS\_ZERO - -• `Const` **ADDRESS\_ZERO**: ``"0x0000000000000000000000000000000000000000"`` - -#### Defined in - -[constants.ts:3](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/constants.ts#L3) - -___ - -### FACTORY\_ADDRESS - -• `Const` **FACTORY\_ADDRESS**: ``"0x1F98431c8aD98523631AE4a59f267346ea31F984"`` - -#### Defined in - -[constants.ts:1](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/constants.ts#L1) - -___ - -### POOL\_INIT\_CODE\_HASH - -• `Const` **POOL\_INIT\_CODE\_HASH**: ``"0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54"`` - -#### Defined in - -[constants.ts:5](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/constants.ts#L5) - -___ - -### TICK\_SPACINGS - -• `Const` **TICK\_SPACINGS**: { [amount in FeeAmount]: number } - -The default factory tick spacings by fee amount. - -#### Defined in - -[constants.ts:20](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/constants.ts#L20) - -## Functions - -### computePoolAddress - -▸ **computePoolAddress**(`__namedParameters`): `string` - -Computes a pool address - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `__namedParameters` | `Object` | -| `__namedParameters.factoryAddress` | `string` | -| `__namedParameters.fee` | [`FeeAmount`](enums/FeeAmount.md) | -| `__namedParameters.initCodeHashManualOverride?` | `string` | -| `__namedParameters.tokenA` | `Token` | -| `__namedParameters.tokenB` | `Token` | - -#### Returns - -`string` - -The pool address - -#### Defined in - -[utils/computePoolAddress.ts:16](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/computePoolAddress.ts#L16) - -___ - -### encodeRouteToPath - -▸ **encodeRouteToPath**(`route`, `exactOutput`): `string` - -Converts a route to a hex encoded path - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `route` | [`Route`](classes/Route.md)<`Currency`, `Currency`\> | the v3 path to convert to an encoded path | -| `exactOutput` | `boolean` | whether the route should be encoded in reverse, for making exact output swaps | - -#### Returns - -`string` - -#### Defined in - -[utils/encodeRouteToPath.ts:11](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/encodeRouteToPath.ts#L11) - -___ - -### encodeSqrtRatioX96 - -▸ **encodeSqrtRatioX96**(`amount1`, `amount0`): `JSBI` - -Returns the sqrt ratio as a Q64.96 corresponding to a given ratio of amount1 and amount0 - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `amount1` | `BigintIsh` | The numerator amount i.e., the amount of token1 | -| `amount0` | `BigintIsh` | The denominator amount i.e., the amount of token0 | - -#### Returns - -`JSBI` - -The sqrt ratio - -#### Defined in - -[utils/encodeSqrtRatioX96.ts:11](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/encodeSqrtRatioX96.ts#L11) - -___ - -### isSorted - -▸ **isSorted**<`T`\>(`list`, `comparator`): `boolean` - -Determines if a tick list is sorted - -#### Type parameters - -| Name | -| :------ | -| `T` | - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `list` | `T`[] | The tick list | -| `comparator` | (`a`: `T`, `b`: `T`) => `number` | The comparator | - -#### Returns - -`boolean` - -true if sorted - -#### Defined in - -[utils/isSorted.ts:7](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/isSorted.ts#L7) - -___ - -### maxLiquidityForAmounts - -▸ **maxLiquidityForAmounts**(`sqrtRatioCurrentX96`, `sqrtRatioAX96`, `sqrtRatioBX96`, `amount0`, `amount1`, `useFullPrecision`): `JSBI` - -Computes the maximum amount of liquidity received for a given amount of token0, token1, -and the prices at the tick boundaries. - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `sqrtRatioCurrentX96` | `default` | the current price | -| `sqrtRatioAX96` | `default` | price at lower boundary | -| `sqrtRatioBX96` | `default` | price at upper boundary | -| `amount0` | `BigintIsh` | token0 amount | -| `amount1` | `BigintIsh` | token1 amount | -| `useFullPrecision` | `boolean` | if false, liquidity will be maximized according to what the router can calculate, not what core can theoretically support | - -#### Returns - -`JSBI` - -#### Defined in - -[utils/maxLiquidityForAmounts.ts:68](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/maxLiquidityForAmounts.ts#L68) - -___ - -### mostSignificantBit - -▸ **mostSignificantBit**(`x`): `number` - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `x` | `default` | - -#### Returns - -`number` - -#### Defined in - -[utils/mostSignificantBit.ts:12](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/mostSignificantBit.ts#L12) - -___ - -### nearestUsableTick - -▸ **nearestUsableTick**(`tick`, `tickSpacing`): `number` - -Returns the closest tick that is nearest a given tick and usable for the given tick spacing - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `tick` | `number` | the target tick | -| `tickSpacing` | `number` | the spacing of the pool | - -#### Returns - -`number` - -#### Defined in - -[utils/nearestUsableTick.ts:9](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/nearestUsableTick.ts#L9) - -___ - -### priceToClosestTick - -▸ **priceToClosestTick**(`price`): `number` - -Returns the first tick for which the given price is greater than or equal to the tick price - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `price` | `Price`<`Token`, `Token`\> | for which to return the closest tick that represents a price less than or equal to the input price, i.e. the price of the returned tick is less than or equal to the input price | - -#### Returns - -`number` - -#### Defined in - -[utils/priceTickConversions.ts:29](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/priceTickConversions.ts#L29) - -___ - -### subIn256 - -▸ **subIn256**(`x`, `y`): `JSBI` - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `x` | `default` | -| `y` | `default` | - -#### Returns - -`JSBI` - -#### Defined in - -[utils/tickLibrary.ts:11](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/tickLibrary.ts#L11) - -___ - -### tickToPrice - -▸ **tickToPrice**(`baseToken`, `quoteToken`, `tick`): `Price`<`Token`, `Token`\> - -Returns a price object corresponding to the input tick and the base/quote token -Inputs must be tokens because the address order is used to interpret the price represented by the tick - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `baseToken` | `Token` | the base token of the price | -| `quoteToken` | `Token` | the quote token of the price | -| `tick` | `number` | the tick for which to return the price | - -#### Returns - -`Price`<`Token`, `Token`\> - -#### Defined in - -[utils/priceTickConversions.ts:14](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/priceTickConversions.ts#L14) - -___ - -### toHex - -▸ **toHex**(`bigintIsh`): `string` - -Converts a big int to a hex string - -#### Parameters - -| Name | Type | -| :------ | :------ | -| `bigintIsh` | `BigintIsh` | - -#### Returns - -`string` - -The hex encoded calldata - -#### Defined in - -[utils/calldata.ts:23](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/utils/calldata.ts#L23) - -___ - -### tradeComparator - -▸ **tradeComparator**<`TInput`, `TOutput`, `TTradeType`\>(`a`, `b`): `number` - -Trades comparator, an extension of the input output comparator that also considers other dimensions of the trade in ranking them - -#### Type parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `TInput` | extends `Currency` | The input token, either Ether or an ERC-20 | -| `TOutput` | extends `Currency` | The output token, either Ether or an ERC-20 | -| `TTradeType` | extends `TradeType` | The trade type, either exact input or exact output | - -#### Parameters - -| Name | Type | Description | -| :------ | :------ | :------ | -| `a` | [`Trade`](classes/Trade.md)<`TInput`, `TOutput`, `TTradeType`\> | The first trade to compare | -| `b` | [`Trade`](classes/Trade.md)<`TInput`, `TOutput`, `TTradeType`\> | The second trade to compare | - -#### Returns - -`number` - -A sorted ordering for two neighboring elements in a trade array - -#### Defined in - -[entities/trade.ts:16](https://github.com/Uniswap/v3-sdk/blob/08a7c05/src/entities/trade.ts#L16) diff --git a/docs/sdk/web3-react/_category_.json b/docs/sdk/web3-react/_category_.json deleted file mode 100644 index 3b42f2a86..000000000 --- a/docs/sdk/web3-react/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "label": "web3-react", - "position": 3, - "collapsed": true -} diff --git a/docs/sdk/web3-react/guides/01-connect-wallet.md b/docs/sdk/web3-react/guides/01-connect-wallet.md deleted file mode 100644 index ff355646e..000000000 --- a/docs/sdk/web3-react/guides/01-connect-wallet.md +++ /dev/null @@ -1,165 +0,0 @@ ---- -id: connect-wallet -title: Connecting to Wallets ---- - -## Introduction - -This guide will cover how to connect wallets with `web3-react`. It is based on the [`web3-react` example](https://github.com/Uniswap/examples/tree/main/web3-react) found in the t1 code examples [repository](https://github.com/Uniswap/examples). To run this example, check out the examples's [README](https://github.com/Uniswap/examples/blob/main/web3-react/README.md) and follow the setup instructions. - - -In this example we will walk through setting up `web3-react` and connecting the most popular browser-injected connector, [MetaMask](https://metamask.io/), using [@web3-react/metamask](https://www.npmjs.com/package/@web3-react/metamask). - - -The input parameters to this guide are the chains that we want our app to be able to connect to and their RPC URLs. - -The guide will **cover**: - -1. Creating a `web3-react` `Web3ReactProvider` -2. Building a `web3-react` `InjectedConnector` -3. Connecting and disconnecting the application to the connector - -At the end of the guide, we should be able to connect and disconnect your dApp to a MetaMask connector. - -For this guide, the following `web3-react` packages are used: - -- [`@web3-react/core`](https://www.npmjs.com/package/@web3-react/core) -- [`@web3-react/types`](https://www.npmjs.com/package/@web3-react/types) -- [`@web3-react/metamask`](https://www.npmjs.com/package/@web3-react/metamask) - -:::info -This guide uses `web3-react` version 8, which is a beta version. -::: - -These will be automatically installed by following the example's [README](https://github.com/Uniswap/examples/blob/main/web3-react/README.md). - -The core code of this guide can be found in [Web3ContextProvider](https://github.com/Uniswap/examples/blob/main/web3-react/src/libs/components/Web3ContextProvider.tsx) and [InjectedConnector](https://github.com/Uniswap/examples/blob/main/web3-react/src/libs/injected.ts). - -## Creating a `Web3ReactProvider` - -To be able to interact with the methods that `web3-react` offers, we first need to setup a `Web3ReactProvider` and wrap our application in it. `web3-react` uses a [React `Context`](https://reactjs.org/docs/context.html) to allow us to use the exposed hooks without additional configuration. - -To start, we create a React component called `Web3ContextProvider` in order to wrap the logic of configuring the `Web3ReactProvider`. In this component, we first import `Web3ReactProvider` from [@web3-react/core](https://www.npmjs.com/package/@web3-react/core). - -The component receives just one prop which is the `children` to which it will be providing the `Context`: - -```typescript reference title="Defining the Web3React component" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/81ec93e97b0afded621e177fe5f34fc9f98f80b0/web3-react/src/libs/components/Web3ContextProvider.tsx#L24 -``` - -We then implement the component by rendering the imported `Web3ReactProvider` with the `children` within that: - - -```typescript reference title="Implementing the component" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/81ec93e97b0afded621e177fe5f34fc9f98f80b0/web3-react/src/libs/components/Web3ContextProvider.tsx#L30-L34 -``` - -Note that we map our list of [`Connections`](https://github.com/Uniswap/examples/blob/856dbb002e7f38120554ef226f4309c96ce6ea79/web3-react/src/libs/connections.ts#L10) to a *tuple* of the `connector` and `hooks` of the connection. The third element of a `Connection` refers to the [type](https://github.com/Uniswap/examples/blob/06980acc8f6d484b719d2c60f5bfe9d766cb95d6/web3-react/src/libs/connections.ts#L16) of `Connection` being established, which we will later use to keep track of the actively connected wallet. - -Finally, having created the `Web3ContextProvider` component, we can navigate to our [index file](https://github.com/Uniswap/examples/blob/feat/web3-react/web3-react/src/index.tsx) and wrap the whole application with it: - -```typescript reference title="Wrapping our app with the web3 context" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/7ac3853bc465aecc428a32be584bbeb833b0a63c/web3-react/src/index.tsx#L16-L22 -``` - -## Building an Injected Connector - -The only parameter that we provided to the `Web3ReactProvider` component is a list of prioritized connectors, declared as `PRIORITIZED_CONNECTORS`. The prioritization ordering is with regards to which connector we want to be active when more than one connector is connected to our application. The list is defined inside our connectors module: -```typescript reference title="Creating the prioritized Connectors list" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/8c0e36ca8d2ba4718af944094191f39da62a9c5c/web3-react/src/libs/connections.ts#L33-L39 -``` - -Each one of those connectors lives within its own file, and they all follow a similar setup pattern. - -An example of a connector in the list is the `InjectedConnector`, which supports wallets that inject an *Ethereum Provider* into the browser window. The most popular example of an injected connector is the *MetaMask* browser extension. To set it up, we import `initializeConnector` function from [core]((https://www.npmjs.com/package/@web3-react/core)) and the `MetaMask` type from [metamask]((https://www.npmjs.com/package/@web3-react/core)): - -```typescript reference title="Importing Connector dependencies" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/856dbb002e7f38120554ef226f4309c96ce6ea79/web3-react/src/libs/injected.ts#L1-L2 -``` - -We then utilize the templated `initializeConnector` function with `MetaMask` as the type argument: - -```typescript reference title="Initializing the MetaMask connector" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/81ec93e97b0afded621e177fe5f34fc9f98f80b0/web3-react/src/libs/injected.ts#L7-L9 -``` - -By passing in `MetaMask` as the type argument, we define the function's required input parameters. In this case, the only parameter we need to pass is an instance of `Metamask`, which receives the `actions` and `onError` parameters. The first parameter defines the actions that `web3-react` performs on its local store for the connector (this usually can be passed through without modification), while the second parameter is the callback invoked when an error occurs. - -The return type of the function is a tuple of the initialized `Connector` and the `Hooks` that we can use on it. Using this tuple, we create an instance of a [`Connection`](https://github.com/Uniswap/examples/blob/856dbb002e7f38120554ef226f4309c96ce6ea79/web3-react/src/libs/connections.ts#L10) type, by setting the `type` property to `INJECTED`: - - -```typescript reference title="Creating a connection instance" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/856dbb002e7f38120554ef226f4309c96ce6ea79/web3-react/src/libs/injected.ts#L16-L20 -``` - -Finally, we return the instance of `Connection` we created, which is added to the list of prioritized connectors. - -:::info -For help on creating the rest of the supported connectors of this examples, please visit our [connectors](./connectors.md) page! -::: - - -## Connecting and disconnecting the application to the connector - -Having built our `InjectedConnector`, we can now use it in the Context that allows our application to use that connector: - -```typescript reference title="Creating the Option component" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/81ec93e97b0afded621e177fe5f34fc9f98f80b0/web3-react/src/libs/components/Option.tsx#L5-L11 -``` - -The component receives 5 parameters: -- `isEnabled` determines whether the connector is eligible to be activated -- `isConnected` determines whether the connector is currently active -- `connectionType` determines the `ConnectionType` -- `onActivate` is called once the component has established a connection -- `onDeactivate` is called once the component has disconnected - -In the case of *MetaMask*, when declaring the `InjectedConnector` we pass the connector-specific arguments: - -```typescript reference title="Creating an injected connector" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/81ec93e97b0afded621e177fe5f34fc9f98f80b0/web3-react/src/libs/components/ConnectionOptions.tsx#L26-L32 -``` - -Then, in the `html` portion of the `Option`, we can figure out whether we want the current `Option`'s action button to be disabled, and whether clicking the button would result in the connector being connected or disconnected: - -```typescript reference title="The component user interface" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/81ec93e97b0afded621e177fe5f34fc9f98f80b0/web3-react/src/libs/components/Option.tsx#L38-L42 -``` - -Finally, we also have enough information to figure out what action to take when the button is clicked. In the case that the click triggers a connection: - -```typescript reference title="On connecting to a Connector" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/8c0e36ca8d2ba4718af944094191f39da62a9c5c/web3-react/src/libs/components/Option.tsx#L38-L42 -``` - -To connect our wallet, all we need to do is to call the `tryActivateConnector` function and pass it the `InjectedConnector`. We then call the `onActivate` callback, which makes the `InjectedConnector` the active connector in our application's state. - - -`tryActivateConnector` takes as its argument the connector that we want to activate, and attempts to call `activate` on it. If this activation succeeds, it returns the new `ConnectionType`: - - -```typescript reference title="The implementation of tryActivateConnector" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/8c0e36ca8d2ba4718af944094191f39da62a9c5c/web3-react/src/libs/connections.ts#L90-L92 -``` - - -In the case that the click triggers a disconnection: - -```typescript reference title="On disconnecting from a Connector" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/8c0e36ca8d2ba4718af944094191f39da62a9c5c/web3-react/src/libs/components/Option.tsx#L29-L36 -``` - - -To disconnect, all we need to do is to call `tryDeactivateConnector` and pass in it the `InjectedConnector` we created before. We then call the `onDeactivate` callback, which removes the `InjectedConnector` as the currently active connector from our application's state. - -`tryDeactivateConnector` takes as its argument the connector that we want to deactivate, and attempts to call `deactivate` on it. If this deactivation succeeds, it resets the connector's state by calling `resetState` and returns `null`: - -```typescript reference title="The implementation of tryDeactivateConnector" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/81ec93e97b0afded621e177fe5f34fc9f98f80b0/web3-react/src/libs/connections.ts#L98-L100 -``` - -## Next Steps - -Now that we have gone through connecting and disconnecting from an `InjectedConnector`, we will learn how to [connect and disconnect](./02-connectors.md) from all the different types of connectors that `web3-react` supports. - - diff --git a/docs/sdk/web3-react/guides/02-connectors.md b/docs/sdk/web3-react/guides/02-connectors.md deleted file mode 100644 index e157a26c1..000000000 --- a/docs/sdk/web3-react/guides/02-connectors.md +++ /dev/null @@ -1,164 +0,0 @@ ---- -id: connectors -title: Supported Connectors ---- - -## Introduction - -This guide will cover how to connect our dApp to all the different connectors that `web3-react` supports. It is based on the [`web3-react` example](https://github.com/Uniswap/examples/tree/main/web3-react), found in the t1 code examples [repository](https://github.com/Uniswap/examples). To run this example, check out the examples's [README](https://github.com/Uniswap/examples/blob/main/web3-react/README.md) and follow the setup instructions. - - -In this example we will cover connecting our dApp to the following connectors: -- Coinbase wallet -- WalletConnect wallet -- Network -- Gnosis safe - - -:::info -For help on setting up `web3-react` and interacting with a MetaMask wallet, please visit our [connecting to wallets](./01-connect-wallet.md) page! -::: - - -The input parameters to this guide are the chains that we want our dApp to be able to connect to and their RPC URLs. - -The guide will **cover**: - -1. Building a Coinbase Wallet connector -2. Building a WalletConnect Wallet connector -3. Building a Network connector -4. Building a Gnosis Safe connector - - -At the end of the guide, we should be able to connect and disconnect the application to the different connectors listed above. - -For this guide, the following `web3-react` packages are used: - -- [`@web3-react/core`](https://www.npmjs.com/package/@web3-react/core) -- [`@web3-react/types`](https://www.npmjs.com/package/@web3-react/types) -- [`@web3-react/coinbase-wallet`](https://www.npmjs.com/package/@web3-react/coinbase-wallet) -- [`@web3-react/walletconnect`](https://www.npmjs.com/package/@web3-react/walletconnect) -- [`@web3-react/network`](https://www.npmjs.com/package/@web3-react/network) -- [`@web3-react/gnosis-safe`](https://www.npmjs.com/package/@web3-react/gnosis-safe) - -:::info -This guide uses `web3-react` version 8, which is a beta version. -::: - -The core code of this guide can be found in the top level of our [examples repository](https://github.com/Uniswap/examples/tree/main/web3-react), under each connectors' name. For example, the code for the Coinbase Wallet connector can be found in the the [coinbase file](https://github.com/Uniswap/examples/blob/main/web3-react/src/libs/coinbase.ts). - -## Building a Coinbase Wallet connector - -The second connector in the list of prioritized connectors that [we provided](./01-connect-wallet.md/#building-an-injected-connector) as a parameter to [`Web3ReactProvider`](https://github.com/Uniswap/examples/blob/feat/web3-react/web3-react/src/libs/components/Web3ContextProvider.tsx) is the *Coinbase Wallet* connector: - -```typescript reference title="Creating the prioritized Connectors list" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/8c0e36ca8d2ba4718af944094191f39da62a9c5c/web3-react/src/libs/connections.ts#L33-L39 -``` - -To connect to a *Coinbase Wallet* connector, we first need to install [`@web3-react/coinbase-wallet`](https://www.npmjs.com/package/@web3-react/coinbase-wallet), as well as [`@coinbase/wallet-sdk`](https://github.com/coinbase/coinbase-wallet-sdk). Having installed the packages, we can import the `CoinbaseWallet` class from `@web3-react/coinbase-wallet`, as well as the `initializeConnector` function from the `@web3-react/core` package: - -```typescript reference title="Importing the Coinbase Wallet connector" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/8c0e36ca8d2ba4718af944094191f39da62a9c5c/web3-react/src/libs/coinbase.ts#L1-L2 -``` -We can now build our connector, supplying the required arguments: - -```typescript reference title="Initializing the Coinbase Wallet Connector" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/8c0e36ca8d2ba4718af944094191f39da62a9c5c/web3-react/src/libs/coinbase.ts#L8-L19 -``` - -We pass `CoinbaseWallet` as the type argument to `initializeConnector`'s templated parameter. Similar to the case of the `InjectedConnector`, the `CoinbaseWallet` class is a class that extends the `AbstractConnector` class, which is part of the `@web3-react/core` package. The parameter provided to `initializeConnector` is a function that receives an `actions` object, and expects an instance of `CoinbaseWallet` (to match the type argument) to be returned. - -We build the new `CoinbaseWallet` instance by passing the `actions` object, an `options` object, and an `onError` callback. `onError` handles errors that occur during interaction with the connector, and `options` is used to configure the connector. In our case, we pass the `url`, `appName` and `reloadOnDisconnect` options: `url` is the *RPC URL* to connect to that was provided as an argument to the example application, `appName` is the name of our application, and `reloadOnDisconnect` is a `boolean` that indicates whether the application should reload when the user disconnects from the wallet. - -After building the connector, we use its two return types, the `Connector` and it's respective hooks, and build a `Connection` object by setting the connection's type as the Coinbase wallet: - -```typescript reference title="Building the Coinbase Wallet Connection" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/8c0e36ca8d2ba4718af944094191f39da62a9c5c/web3-react/src/libs/coinbase.ts#L20-L24 -``` - -Having built the connector, all that remains is to build the user interface and supply it to our [`ConnectionOptions`](https://github.com/Uniswap/examples/blob/feat/web3-react/web3-react/src/libs/components/ConnectionOptions.tsx) component, just as we did with the `InjectedConnector`: - -```typescript reference title="Building the Coinbase Wallet component" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/81ec93e97b0afded621e177fe5f34fc9f98f80b0/web3-react/src/libs/components/ConnectionOptions.tsx#L39-L46 -``` -## Building a WalletConnect Wallet connector - -The third connector in the list of prioritized connectors that we provided to [`Web3ReactProvider`](https://github.com/Uniswap/examples/blob/feat/web3-react/web3-react/src/libs/components/Web3ContextProvider.tsx) is the WalletConnect Wallet connector. - -To connect to a WalletConnect Wallet connector, we first need to install [`@web3-react/walletconnect`](https://www.npmjs.com/package/@web3-react/walletconnect), as well as [`@walletconnect/ethereum-provider`](https://www.npmjs.com/package/@walletconnect/ethereum-provider). Having installed the packages, we can import the `WalletConnect` class from `@web3-react/walletconnect`, as well as the `initializeConnector` function from`@web3-react/core` package: - -```typescript reference title="Importing the WalletConnect Wallet Connector" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/8c0e36ca8d2ba4718af944094191f39da62a9c5c/web3-react/src/libs/wallet-connect.ts#L1-L2 -``` -We can now build our connector, supplying the required arguments: - -```typescript reference title="Initializing the WalletConnect Wallet Connector" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/8c0e36ca8d2ba4718af944094191f39da62a9c5c/web3-react/src/libs/wallet-connect.ts#L8-L17 -``` - -The main difference from the Coinbase Wallet connector lies in the arguments that the `WalletConnect` class requires to be instantiated. `web3-react` knows about this difference, as we passed the type argument `WalletConnect` to `initializeConnector`, thus specializing the type of `AbstractConnector`. In this case, the class receives three arguments, including `actions` and `onError`, identical to those supplied in the Coinbase Wallet connector case. - -The difference lies in the second argument, which is an `options` object. In this case, we are passing the `rpc` parameter, which is an object that maps the chain ID to the RPC URL to connect to. We have already created this [map](https://github.com/Uniswap/examples/blob/8c0e36ca8d2ba4718af944094191f39da62a9c5c/web3-react/src/libs/constants.ts#L11) in our [`constants`](https://github.com/Uniswap/examples/blob/feat/web3-react/web3-react/src/libs/constants.ts) file using our example's parameters. The other option that we are passing is the `qrcode`, which is a `boolean` that indicates whether the QR code should be displayed in the browser. In our case, we are passing `true` as we want to show the QR code. - -Having built the connector, we just need to build the user interface to enable user interaction with the connector, and supply it to our `ConnectionOptions`: - -```typescript reference title="Building the WalletConnect Wallet component" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/81ec93e97b0afded621e177fe5f34fc9f98f80b0/web3-react/src/libs/components/ConnectionOptions.tsx#L49-L56 -``` -## Building a Network connector - -The *Network connector*, alongside the *Gnosis Safe connector*, are two of the connectors that we do not surface through our user interface, but instead we connect to them programmatically. In contrast to the previous *Connectors*, these do not come with any pre-built user interface for the user to interact with. We attempt to connect to them **eagerly** in our [`Web3ContextProvider`](https://github.com/Uniswap/examples/blob/feat/web3-react/web3-react/src/libs/components/Web3ContextProvider.tsx) component through a hook: - -```typescript reference title="Hook to connect eagerly" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/81ec93e97b0afded621e177fe5f34fc9f98f80b0/web3-react/src/libs/components/Web3ContextProvider.tsx#L9-L13 -``` - -The `useEagerlyConnect` hook is called in the `Web3ContextProvider` component and attempts to connect to the Network Connector and the Gnosis Safe Connector. The hook is named **eagerly** as it is called in the component's body as [React effect](https://reactjs.org/docs/hooks-effect.html) when the component is first rendered. In the hook implementation we attempt to call `web3-react`'s `connectEagerly` function if it exists on the connector, otherwise we call `activate` otherwise. The `connectEagerly` function attempts to connect our application to the connector, and **fails silently** if it does not succeed: - -```typescript reference title="Connecting eagerly" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/8c0e36ca8d2ba4718af944094191f39da62a9c5c/web3-react/src/libs/hooks.ts#L15-L19 -``` - -Before eagerly connecting, we first need to initialize the connectors. We start by building the Network connector, and we first need to install [`@web3-react/network`](https://www.npmjs.com/package/@web3-react/network), and import the `Network` class from it. Note how this Connect does not require any package besides its `web3-react` package to function. We also need to import the `initializeConnector` function from `@web3-react/core`: - -```typescript reference title="Importing the Network Connector" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/8c0e36ca8d2ba4718af944094191f39da62a9c5c/web3-react/src/libs/network.ts#L1-L2 -``` -We can now build our connector, supplying the required arguments: - -```typescript reference title="Initializing the Network Connector" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/8c0e36ca8d2ba4718af944094191f39da62a9c5c/web3-react/src/libs/network.ts#L8-L15 -``` - -The main difference from the other connectors lies in the arguments that the `Network` class requires to be instantiated. `web3-react` knows about this difference, as we passed the type argument `Network` to `initializeConnector`, thus specializing the type of `AbstractConnector`. In this case, the class receives `actions`, which is identical to that supplied in the rest of the connectors; `urlMap`, which is an object that maps the chain ID to the RPC URL to connect to, which we have already created in our [`constants`](https://github.com/Uniswap/examples/blob/feat/web3-react/web3-react/src/libs/constants.ts) file; and `defaultChainId` which is the chain ID to connect to by default. - -After building, the connector, we can create a `Connection` instance by supplying it the return value of the `initializeConnector` function, and the `Network` class: - -```typescript reference title="Creating a Network connection" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/8c0e36ca8d2ba4718af944094191f39da62a9c5c/web3-react/src/libs/network.ts#L16-L20 -``` -All that remains is to return the constructed `Connection` instance. - -## Building a Gnosis Safe connector - -Similar to the Network connector, we build the Gnosis Safe connector. We start by first installing [`@web3-react/gnosis-safe`](https://www.npmjs.com/package/@web3-react/gnosis-safe), and import the `GnosisSafe` class from it. We also need to import the `initializeConnector` function from `@web3-react/core`: - -```typescript reference title="Importing the Gnosis Safe connector" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/8c0e36ca8d2ba4718af944094191f39da62a9c5c/web3-react/src/libs/gnosis.tsx#L1-L2 -``` - -The Gnosis Safe connector is the simplest of them all, as it does not require any additional parameterization other than `actions`: - -```typescript reference title="Initializing a Gnosis Safe Connector" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/8c0e36ca8d2ba4718af944094191f39da62a9c5c/web3-react/src/libs/gnosis.tsx#L6-L9 -``` - -Having initialized the connector, we can now build the `Connection` instance and return it: - -```typescript reference title="Creating a Gnosis Safe Connection" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/8c0e36ca8d2ba4718af944094191f39da62a9c5c/web3-react/src/libs/gnosis.tsx#L10-L14 -``` - -## Next steps - -Now that we have gone through building all of the different types of supported connectors, we will learn how to [switch chains](03-switch-chains.md). \ No newline at end of file diff --git a/docs/sdk/web3-react/guides/03-switch-chains.md b/docs/sdk/web3-react/guides/03-switch-chains.md deleted file mode 100644 index 531a70078..000000000 --- a/docs/sdk/web3-react/guides/03-switch-chains.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -id: switch-chains -title: Switching Chains ---- - -## Introduction - -This guide will cover how to prompt a wallet that has connected to our dApp to switch chains using `web3-react`. It is based on the [`web3-react` example](https://github.com/Uniswap/examples/tree/main/web3-react), found in the t1 code examples [repository](https://github.com/Uniswap/examples). To run this example, check out the examples's [README](https://github.com/Uniswap/examples/blob/main/web3-react/README.md) and follow the setup instructions. - - -:::info -For help on setting up `web3-react` and interacting with a MetaMask wallet, please visit our [connecting to wallets](./01-connect-wallet.md) page! -::: - - -The input parameters to this guide are the chains that we want our dApp to be able to connect to and their RPC URLs. - -At the end of the guide, we should be able to switch chains on the connected wallet. - -For this guide, the following `web3-react` packages are used: - -- [`@web3-react/core`](https://www.npmjs.com/package/@web3-react/core) - -:::info -This guide uses `web3-react` version 8, which is a beta version. -::: - -The core code of this guide can be found in [connections](https://github.com/Uniswap/examples/blob/feat/web3-react/web3-react/src/libs/connections.ts). - -## Switching Chains - -Having [setup our application](./01-connect-wallet.md) to use `web3-react` and having built out the ability to [connect and disconnect wallets](./02-connectors.md), we can now move on to switching chains. - -Switching chains requires two parameters, the `chainId` we want to switch to, and the current `connectionType`: - -```typescript reference title="Defining the function" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/8c0e36ca8d2ba4718af944094191f39da62a9c5c/web3-react/src/libs/connections.ts#L64 -``` - -Given the `ConnectionType`, we can retrieve the actual connector: - -```typescript reference title="Retrieving the connector" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/8c0e36ca8d2ba4718af944094191f39da62a9c5c/web3-react/src/libs/connections.ts#L69 -``` - -Then, depending on the `ConnectionType`, we determine how to switch chains. For the `Network` or `WalletConnect` cases, we call `web3-react`'s `activate` function with the supplied `chainId`: - -```typescript reference title="Switching chains for Network and WalletConnect" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/8c0e36ca8d2ba4718af944094191f39da62a9c5c/web3-react/src/libs/connections.ts#L71-L74 -``` - -The rest of the connectors require us to build an `AddEthereumChainParameter` object and pass it to the `web3-react`'s `activate` function: - -```typescript reference title="Switching chains the other Connectors" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/8c0e36ca8d2ba4718af944094191f39da62a9c5c/web3-react/src/libs/connections.ts#L77-L84 -``` - -The metadata required to build `AddEthereumChainParameter` are defined in our constants file: - -```typescript reference title="Defining the chain parameters" referenceLinkText="View on Github" customStyling -https://github.com/Uniswap/examples/blob/8c0e36ca8d2ba4718af944094191f39da62a9c5c/web3-react/src/libs/constants.ts#L27-L40 -``` - -## Next steps - -Know you know how to support `web3-react`'s most common use cases! Stay tuned for follow up guides. diff --git a/docs/sdk/web3-react/guides/_category_.json b/docs/sdk/web3-react/guides/_category_.json deleted file mode 100644 index c694eb5b2..000000000 --- a/docs/sdk/web3-react/guides/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "label": "Guides", - "position": 2, - "collapsed": false -} diff --git a/docs/sdk/web3-react/overview.md b/docs/sdk/web3-react/overview.md deleted file mode 100644 index 46fdadf73..000000000 --- a/docs/sdk/web3-react/overview.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -id: overview -sidebar_position: 1 -title: Overview ---- -# `web3-react` - -> **Welcome to `web3-react`!** - -`web3-react` provides abstractions to assist you with connecting your dApp to web3 connectors and exposes methods to interact with those connections. It currently supports connecting to the following wallets: -- Network -- Injected wallets (eg MetaMask) -- Gnosis safe -- Coinbase wallet -- WalletConnect wallet - -To begin, we recommend looking at our [guides](./guides/01-setting-up.md) which include [runnable examples](https://github.com/Uniswap/examples/tree/main/web3-react) and walkthroughs of core usages. These guides will help you better understand how to use `web3-react` and integrate it into your application. - -:::info -This guide uses `web3-react` version 8, which is a beta version. -::: - -## Installation - -`web3-react` consists of many packages, each providing different functionalities. The [core](https://www.npmjs.com/package/@web3-react/core) package exposes the methods used to interact with web3 connectors, the [types](https://www.npmjs.com/package/@web3-react/types) package declares useful types, while the others are installed to enable interactions with different connectors. - -To interact with `web3-react` we recommend installing though npm: - -```bash -npm install --save @web3-react/core -``` - -or yarn: - -```bash -yarn add @web3-react/core -``` - -## Developer Links - -- [**`web3-react` on Github**](https://github.com/Uniswap/web3-react) - -[![npm version](https://img.shields.io/npm/v/@web3-react/core/latest.svg)](https://www.npmjs.com/package/@web3-react/core/v/latest) -[![npm bundle size (scoped version)](https://img.shields.io/bundlephobia/minzip/@web3-react/core/latest.svg)](https://bundlephobia.com/result?p=@web3-react/core@latest) -[![Discord](https://img.shields.io/badge/discord-join%20chat-blue.svg)](https://discord.com/channels/597638925346930701/607978109089611786) diff --git a/docusaurus.config.js b/docusaurus.config.js index 14cd31019..225e021b1 100644 --- a/docusaurus.config.js +++ b/docusaurus.config.js @@ -107,13 +107,6 @@ module.exports = { editUrl: 'https://github.com/t1protocol/docs/tree/main/', includeCurrentVersion: true, }, - blog: { - remarkPlugins: [math], - rehypePlugins: [katex], - path: 'blog/', - blogTitle: 'Engineering Blog', - blogSidebarCount: 0, - }, theme: { customCss: require.resolve('./src/css/custom.css'), customCss2: require.resolve('./src/css/colors.css'), @@ -129,78 +122,5 @@ module.exports = { crossorigin: 'anonymous', }, ], - plugins: [ - ['@saucelabs/theme-github-codeblock', {}], - [ - '@docusaurus/plugin-client-redirects', - { - redirects: [ - // 1/9/23 V3 SDK Guide Redirects - { - to: '/sdk/v3/guides/background', - from: '/sdk/v3/guides/quick-start', - }, - { - to: '/sdk/v3/guides/swaps/quoting', - from: ['/sdk/v3/guides/creating-a-pool', '/sdk/v3/guides/fetching-prices'], - }, - { - to: '/sdk/v3/guides/swaps/trading', - from: '/sdk/v3/guides/creating-a-trade', - }, - { - to: '/sdk/v3/guides/swaps/routing', - from: '/sdk/v3/guides/auto-router', - }, - { - to: '/sdk/v3/guides/liquidity/modifying-position', - from: ['/sdk/v3/guides/liquidity/adding', '/sdk/v3/guides/liquidity/removing'], - }, - ], - createRedirects(existingPath) { - // V3 Redirects - if (existingPath.includes('/concepts/overview')) { - return [existingPath.replace('/concepts/overview', '/protocol/introduction')] - } - if (existingPath.includes('/contracts/v3/reference')) { - return [existingPath.replace('/contracts/v3/reference', '/protocol/reference')] - } - if (existingPath.includes('/contracts/v3/guides')) { - return [existingPath.replace('/contracts/v3/guides', '/protocol/guides')] - } - // V2 Redirects - if (existingPath.includes('/contracts/v2/reference')) { - return [existingPath.replace('/contracts/v2/reference', '/protocol/V2/reference')] - } - if (existingPath.includes('/contracts/v2/guides')) { - return [existingPath.replace('/contracts/v2/guides', '/protocol/V2/guides')] - } - // Permit2 Redirects - if (existingPath.includes('/contracts/permit2')) { - return [existingPath.replace('/contracts/permit2', '/protocol/permit2')] - } - // v3-sdk Redirects - if (existingPath.includes('/sdk/v3/overview')) { - return [existingPath.replace('/sdk/v3/overview', '/sdk/introduction')] - } - if (existingPath.includes('/sdk/v3/guides')) { - return [existingPath.replace('/sdk/v3/guides', '/sdk/guides')] - } - // swap-widgets Redirects - if (existingPath.includes('/sdk/swap-widget/overview')) { - return [existingPath.replace('/sdk/swap-widget/overview', '/sdk/widgets/swap-widget')] - } - if (existingPath.includes('/sdk/swap-widget/reference/v2')) { - return [existingPath.replace('/sdk/swap-widget/reference/v2', '/sdk/widgets/swap-widget/api')] - } - if (existingPath.includes('/concepts')) { - return [existingPath.replace('/concepts', '/protocol/concepts')] - } - - // Return a falsy value: no redirect created - return undefined - }, - }, - ], - ], + plugins: [['@saucelabs/theme-github-codeblock', {}]], } diff --git a/examples/sdk/AddAndRemoveLiquidity.tsx b/examples/sdk/AddAndRemoveLiquidity.tsx deleted file mode 100644 index de0c4636b..000000000 --- a/examples/sdk/AddAndRemoveLiquidity.tsx +++ /dev/null @@ -1,126 +0,0 @@ -import { Pool, Position, NonfungiblePositionManager, nearestUsableTick } from '@uniswap/v3-sdk' - -import { ethers } from 'ethers' -import { Percent, Token, CurrencyAmount } from '@uniswap/sdk-core' -import { abi as IUniswapV3PoolABI } from '@uniswap/v3-core/artifacts/contracts/interfaces/IUniswapV3Pool.sol/IUniswapV3Pool.json' - -// default uses “http://localhost:8545” -// can also input your own connection with "https://mainnet.infura.io/v3/" as an input -const provider = new ethers.providers.JsonRpcProvider() - -// pool address for DAI/USDC 0.05% -const poolAddress = '0x6c6bc977e13df9b0de53b251522280bb72383700' - -const poolContract = new ethers.Contract(poolAddress, IUniswapV3PoolABI, provider) - -interface Immutables { - factory: string - token0: string - token1: string - fee: number - tickSpacing: number - maxLiquidityPerTick: ethers.BigNumber -} - -interface State { - liquidity: ethers.BigNumber - sqrtPriceX96: ethers.BigNumber - tick: number - observationIndex: number - observationCardinality: number - observationCardinalityNext: number - feeProtocol: number - unlocked: boolean -} - -async function getPoolImmutables() { - const immutables: Immutables = { - factory: await poolContract.factory(), - token0: await poolContract.token0(), - token1: await poolContract.token1(), - fee: await poolContract.fee(), - tickSpacing: await poolContract.tickSpacing(), - maxLiquidityPerTick: await poolContract.maxLiquidityPerTick(), - } - return immutables -} - -async function getPoolState() { - const slot = await poolContract.slot0() - const PoolState: State = { - liquidity: await poolContract.liquidity(), - sqrtPriceX96: slot[0], - tick: slot[1], - observationIndex: slot[2], - observationCardinality: slot[3], - observationCardinalityNext: slot[4], - feeProtocol: slot[5], - unlocked: slot[6], - } - return PoolState -} - -async function liquidityExamples(sender: string, exampleType: number) { - const immutables = await getPoolImmutables() - const state = await getPoolState() - const DAI = new Token(1, immutables.token0, 18, 'DAI', 'Stablecoin') - const USDC = new Token(1, immutables.token1, 18, 'USDC', 'USD Coin') - const block = await provider.getBlock(provider.getBlockNumber()) - const deadline = block.timestamp + 200 - - //create a pool - const DAI_USDC_POOL = new Pool( - DAI, - USDC, - immutables.fee, - state.sqrtPriceX96.toString(), - state.liquidity.toString(), - state.tick - ) - - // create a position with the pool - // the position is in-range, specified by the lower and upper tick - // in this example, we will set the liquidity parameter to a small percentage of the current liquidity - const position = new Position({ - pool: DAI_USDC_POOL, - liquidity: state.liquidity.div(5000).toString(), - tickLower: nearestUsableTick(state.tick, immutables.tickSpacing) - immutables.tickSpacing * 2, - tickUpper: nearestUsableTick(state.tick, immutables.tickSpacing) + immutables.tickSpacing * 2, - }) - - // Example 0: Setting up calldata for minting a Position - if (exampleType == 0) { - const { calldata, value } = NonfungiblePositionManager.addCallParameters(position, { - slippageTolerance: new Percent(50, 10_000), - recipient: sender, - deadline: deadline, - }) - } - - // Example 1: Setting up calldata for adding liquidity to Position - if (exampleType == 1) { - const { calldata, value } = NonfungiblePositionManager.addCallParameters(position, { - slippageTolerance: new Percent(50, 10_000), - deadline: deadline, - tokenId: 1, - }) - } - - // Example 2: Setting up calldata for removing liquidity from Position - if (exampleType == 2) { - const { calldata, value } = NonfungiblePositionManager.removeCallParameters(position, { - tokenId: 1, - liquidityPercentage: new Percent(1), - slippageTolerance: new Percent(50, 10_000), - deadline: deadline, - collectOptions: { - expectedCurrencyOwed0: CurrencyAmount.fromRawAmount(DAI, 0), - expectedCurrencyOwed1: CurrencyAmount.fromRawAmount(USDC, 0), - recipient: sender, - }, - }) - } -} - -// call the example function by passing the sender, e.g.: -// liquidityExamples("0xDA9dfA130Df4dE4673b89022EE50ff26f6EA73Cf", 0) diff --git a/examples/sdk/fetchAndVerifyProofOfRead.ts b/examples/sdk/fetchAndVerifyProofOfRead.ts deleted file mode 100644 index a560f6aa0..000000000 --- a/examples/sdk/fetchAndVerifyProofOfRead.ts +++ /dev/null @@ -1,174 +0,0 @@ -/** - * t1 Protocol - Proof of Read Verification Example Script - * - * This script demonstrates how to fetch and verify cross-chain read proofs using the t1 Protocol. - * It retrieves Merkle proofs for cross-chain read operations from t1's API and verifies them on-chain via t1 XChainReader contract. - * - * Before running this script, ensure you have: - * 1. Node.js and npm installed - * 2. Installed dependencies (ethers.js) - * 3. A valid Ethereum address that has performed cross-chain reads through t1 Protocol - * - * Usage: node fetchAndVerifyProofOfRead - * - requester_address: The Ethereum address that initiated cross-chain reads - * - direction: Either "ARB_TO_BASE" or "BASE_TO_ARB" for the cross-chain direction - * - * Example: node fetchAndVerifyProofOfRead 0x1234567890123456789012345678901234567890 ARB_TO_BASE - */ - -import { ethers } from 'ethers'; - -enum Direction { - ARB_TO_BASE = 'ARB_TO_BASE', - BASE_TO_ARB = 'BASE_TO_ARB', -} - -interface ClaimInfo { - from: string; - to: string; - value: string; - nonce: string; - message: string; - x_chain_read_result: string; - request_id: string; - handle_read_result_with_proof_calldata: string; - proof: { - batch_index: string; - merkle_proof: string; - }; -} - -interface Result { - source_tx_hash: string; - message_type: number; - block_number: number; - message_hash: string; - tx_sender: string; - direction: Direction; - claim_info: ClaimInfo; -} - -interface ReadProofsResponse { - results: Result[]; - page: number; - page_size: number; - total: number; -} - -interface VerifiedProofReturn { - requestId: string; - result: string; -} - -const XCHAINREADER_ABI = [ - 'function verifyProofOfRead(bytes encodedProofOfRead) external view returns (bytes32, bytes)', -]; -const API_BASE_URL = 'https://api.v06.t1protocol.com/api'; -const ARB_RPC_URL = 'https://arbitrum-sepolia-rpc.publicnode.com'; -const BASE_RPC_URL = 'https://base-sepolia-rpc.publicnode.com'; -const ARB_XCHAINREADER_ADDRESS = '0x42d389A9007e446b92C0ce7bd8F42Ea10292881B'; -const BASE_XCHAINREADER_ADDRESS = '0x3821b214B4c9D053fa744dc2B355E2039696dFb7'; - -async function getMerkleProofs( - address: string, - direction: Direction, - page: number = 1, - pageSize: number = 100, -): Promise { - const url = `${API_BASE_URL}/read-proofs?address=${address}&direction=${direction}&page=${page}&page_size=${pageSize}`; - - console.log(`Fetching Merkle proofs from: ${url}`); - - const response = await fetch(url); - - if (!response.ok) { - throw new Error( - `Failed to fetch proofs: ${response.status} ${response.statusText}`, - ); - } - - const { data } = await response.json(); - return data; -} - -async function verifyProofOfRead( - direction: Direction, - proofCalldata: string, -): Promise { - const provider = new ethers.JsonRpcProvider( - direction === Direction.ARB_TO_BASE ? ARB_RPC_URL : BASE_RPC_URL, - ); - const contract = new ethers.Contract( - direction === Direction.ARB_TO_BASE - ? ARB_XCHAINREADER_ADDRESS - : BASE_XCHAINREADER_ADDRESS, - XCHAINREADER_ABI, - provider, - ); - - try { - const response = await contract.verifyProofOfRead(proofCalldata); - return { requestId: response[0], result: response[1] }; - } catch (error) { - console.error('Error verifying proof:', error); - return undefined; - } -} - -async function main() { - const address = process.argv[2]; - const direction = process.argv[3]; - - if ( - !address || - (direction !== 'ARB_TO_BASE' && direction !== 'BASE_TO_ARB') - ) { - console.error( - 'Usage: npm run dev ', - ); - process.exit(1); - } - - const parsedDirection = - direction === 'ARB_TO_BASE' ? Direction.ARB_TO_BASE : Direction.BASE_TO_ARB; - - try { - console.log(`Getting Merkle proofs for address: ${address}`); - - const response = await getMerkleProofs(address, parsedDirection); - - if (response.results.length === 0) { - console.log('No proofs found for this address.'); - return; - } - - console.log(`Found ${response.results.length} proof(s)`); - - for (let i = 0; i < response.results.length; i++) { - const item = response.results[i]; - - console.log(`\nVerifying proof ${i + 1}/${response.results.length}:`); - console.log(`- Request ID: ${item.claim_info.request_id}`); - console.log(`- Source TX Hash: ${item.source_tx_hash}`); - console.log(`- Batch Index: ${item.claim_info.proof.batch_index}`); - - const res = await verifyProofOfRead( - parsedDirection, - item.claim_info.handle_read_result_with_proof_calldata, - ); - - if (!res) { - console.log('Proof verification FAILED'); - } else { - console.log('Proof verification SUCCESSFUL'); - } - } - - console.log('\nProof verifications completed'); - } catch (error) { - console.error('Error:', error); - process.exit(1); - } -} - -main().catch(console.error); diff --git a/examples/smart-contracts/LiquidityExamples.sol b/examples/smart-contracts/LiquidityExamples.sol deleted file mode 100644 index a722e3396..000000000 --- a/examples/smart-contracts/LiquidityExamples.sol +++ /dev/null @@ -1,243 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-or-later -pragma solidity =0.7.6; -pragma abicoder v2; - -import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol'; -import '@uniswap/v3-core/contracts/libraries/TickMath.sol'; -import '../libraries/TransferHelper.sol'; -import '../interfaces/INonfungiblePositionManager.sol'; - -contract LiquidityExamples is IERC721Receiver { - address public constant nonfungiblePositionManager = 0xC36442b4a4522E871399CD717aBDD847Ab11FE88; - address public constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; - address public constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; - uint24 public constant poolFee = 3000; - - /// @notice Represents the deposit of an NFT - struct Deposit { - address owner; - uint128 liquidity; - address token0; - address token1; - } - - /// @dev deposits[tokenId] => Deposit - mapping(uint256 => Deposit) public deposits; - - // Implementing `onERC721Received` so this contract can receive custody of erc721 tokens - // Note that the operator is recorded as the owner of the deposited NFT - function onERC721Received( - address operator, - address, - uint256 tokenId, - bytes calldata - ) external override returns (bytes4) { - require(msg.sender == address(nonfungiblePositionManager), 'not a univ3 nft'); - _createDeposit(operator, tokenId); - return this.onERC721Received.selector; - } - - function _createDeposit(address owner, uint256 tokenId) internal { - (, , address token0, address token1, , , , uint128 liquidity, , , , ) = - nonfungiblePositionManager.positions(tokenId); - // set the owner and data for position - deposits[tokenId] = Deposit({owner: owner, liquidity: liquidity, token0: token0, token1: token1}); - } - - /// @notice Calls the mint function defined in periphery, mints the same amount of each token. - /// For this example we are providing 1000 DAI and 1000 USDC in liquidity - /// @return tokenId The id of the newly minted ERC721 - /// @return liquidity The amount of liquidity for the position - /// @return amount0 The amount of token0 - /// @return amount1 The amount of token1 - function mintNewPosition() - external - returns ( - uint256 tokenId, - uint128 liquidity, - uint256 amount0, - uint256 amount1 - ) - { - // For this example, we will provide equal amounts of liquidity in both assets. - // Providing liquidity in both assets means liquidity will be earning fees and is considered in-range. - uint256 amount0ToMint = 1000; - uint256 amount1ToMint = 1000; - - // transfer tokens to contract - TransferHelper.safeTransferFrom(DAI, msg.sender, address(this), amount0ToMint); - TransferHelper.safeTransferFrom(USDC, msg.sender, address(this), amount1ToMint); - - // Approve the position manager - TransferHelper.safeApprove(DAI, address(nonfungiblePositionManager), amount0ToMint); - TransferHelper.safeApprove(USDC, address(nonfungiblePositionManager), amount1ToMint); - - // The values for tickLower and tickUpper may not work for all tick spacings. - // Setting amount0Min and amount1Min to 0 is unsafe. - INonfungiblePositionManager.MintParams memory params = - INonfungiblePositionManager.MintParams({ - token0: DAI, - token1: USDC, - fee: poolFee, - tickLower: TickMath.MIN_TICK, - tickUpper: TickMath.MAX_TICK, - amount0Desired: amount0ToMint, - amount1Desired: amount1ToMint, - amount0Min: 0, - amount1Min: 0, - recipient: address(this), - deadline: block.timestamp - }); - - // Note that the pool defined by DAI/USDC and fee tier 0.3% must already be created and initialized in order to mint - (tokenId, liquidity, amount0, amount1) = nonfungiblePositionManager.mint(params); - - // Create a deposit - _createDeposit(msg.sender, tokenId); - - // Remove allowance and refund in both assets. - if (amount0 < amount0ToMint) { - TransferHelper.safeApprove(DAI, address(nonfungiblePositionManager), 0); - uint256 refund0 = amount0ToMint - amount0; - TransferHelper.safeTransfer(DAI, msg.sender, refund0); - } - - if (amount1 < amount1ToMint) { - TransferHelper.safeApprove(USDC, address(nonfungiblePositionManager), 0); - uint256 refund1 = amount1ToMint - amount1; - TransferHelper.safeTransfer(USDC, msg.sender, refund1); - } - } - - /// @notice Collects the fees associated with provided liquidity - /// @dev The contract must hold the erc721 token before it can collect fees - /// @param tokenId The id of the erc721 token - /// @return amount0 The amount of fees collected in token0 - /// @return amount1 The amount of fees collected in token1 - function collectAllFees(uint256 tokenId) external returns (uint256 amount0, uint256 amount1) { - // Caller must own the ERC721 position, meaning it must be a deposit - // set amount0Max and amount1Max to type(uint128).max to collect all fees - // alternatively can set recipient to msg.sender and avoid another transaction in `sendToOwner` - INonfungiblePositionManager.CollectParams memory params = - INonfungiblePositionManager.CollectParams({ - tokenId: tokenId, - recipient: address(this), - amount0Max: type(uint128).max, - amount1Max: type(uint128).max - }); - - (amount0, amount1) = nonfungiblePositionManager.collect(params); - - // send collected fees back to owner - _sendToOwner(tokenId, amount0, amount1); - } - - /// @notice A function that decreases the current liquidity by half. An example to show how to call the `decreaseLiquidity` function defined in periphery. - /// @param tokenId The id of the erc721 token - /// @return amount0 The amount received back in token0 - /// @return amount1 The amount returned back in token1 - function decreaseLiquidityInHalf(uint256 tokenId) external returns (uint256 amount0, uint256 amount1) { - // caller must be the owner of the NFT - require(msg.sender == deposits[tokenId].owner, 'Not the owner'); - // get liquidity data for tokenId - uint128 liquidity = deposits[tokenId].liquidity; - uint128 halfLiquidity = liquidity / 2; - - // amount0Min and amount1Min are price slippage checks - // if the amount received after burning is not greater than these minimums, transaction will fail - INonfungiblePositionManager.DecreaseLiquidityParams memory params = - INonfungiblePositionManager.DecreaseLiquidityParams({ - tokenId: tokenId, - liquidity: halfLiquidity, - amount0Min: 0, - amount1Min: 0, - deadline: block.timestamp - }); - - (amount0, amount1) = nonfungiblePositionManager.decreaseLiquidity(params); - - // send liquidity back to owner - _sendToOwner(tokenId, amount0, amount1); - } - - /// @notice Increases liquidity in the current range - /// @dev Pool must be initialized already to add liquidity - /// @param tokenId The id of the erc721 token - /// @param amount0 The amount to add of token0 - /// @param amount1 The amount to add of token1 - function increaseLiquidityCurrentRange( - uint256 tokenId, - uint256 amountAdd0, - uint256 amountAdd1 - ) - external - returns ( - uint128 liquidity, - uint256 amount0, - uint256 amount1 - ) - { - uint256 token0 = deposits[tokenId].token0; - uint256 token1 = deposits[tokenId].token1; - TransferHelper.safeTransferFrom(token0, msg.sender, address(this), amountAdd0); - TransferHelper.safeTransferFrom(token1, msg.sender, address(this), amountAdd1); - - TransferHelper.safeApprove(token0, address(nonfungiblePositionManager), amountAdd0); - TransferHelper.safeApprove(token1, address(nonfungiblePositionManager), amountAdd1); - - INonfungiblePositionManager.IncreaseLiquidityParams memory params = - INonfungiblePositionManager.IncreaseLiquidityParams({ - tokenId: tokenId, - amount0Desired: amountAdd0, - amount1Desired: amountAdd1, - amount0Min: 0, - amount1Min: 0, - deadline: block.timestamp - }); - - (liquidity, amount0, amount1) = nonfungiblePositionManager.increaseLiquidity(params); - - // Remove allowance and refund in both assets. - if (amount0 < amountAdd0) { - TransferHelper.safeApprove(token0, address(nonfungiblePositionManager), 0); - uint256 refund0 = amountAdd0 - amount0; - TransferHelper.safeTransfer(token0, msg.sender, refund0); - } - - if (amount1 < amount1ToMint) { - TransferHelper.safeApprove(token1, address(nonfungiblePositionManager), 0); - uint256 refund1 = amount1ToMint - amount1; - TransferHelper.safeTransfer(token1, msg.sender, refund1); - } - } - - /// @notice Transfers funds to owner of NFT - /// @param tokenId The id of the erc721 - /// @param amount0 The amount of token0 - /// @param amount1 The amount of token1 - function _sendToOwner( - uint256 tokenId, - uint256 amount0, - uint256 amount1 - ) private { - // get owner of contract - address owner = deposits[tokenId].owner; - - address token0 = deposits[tokenId].token0; - address token1 = deposits[tokenId].token1; - // send collected fees to owner - TransferHelper.safeTransfer(token0, owner, amount0); - TransferHelper.safeTransfer(token1, owner, amount1); - } - - /// @notice Transfers the NFT to the owner - /// @param tokenId The id of the erc721 - function retrieveNFT(uint256 tokenId) external { - // must be the owner of the NFT - require(msg.sender == deposits[tokenId].owner, 'Not the owner'); - // remove information related to tokenId - delete deposits[tokenId]; - // transfer ownership to original owner - nonfungiblePositionManager.safeTransferFrom(address(this), msg.sender, tokenId); - } -} \ No newline at end of file diff --git a/examples/smart-contracts/SwapExamples.sol b/examples/smart-contracts/SwapExamples.sol deleted file mode 100644 index c8e7cdd9f..000000000 --- a/examples/smart-contracts/SwapExamples.sol +++ /dev/null @@ -1,163 +0,0 @@ -// SPDX-License-Identifier: GPL-2.0-or-later -pragma solidity =0.7.6; -pragma abicoder v2; - -import '../libraries/TransferHelper.sol'; -import '../interfaces/ISwapRouter.sol'; - -contract SwapExamples { - // For the scope of these swap examples, - // we will detail the design considerations when using - // `exactInput`, `exactInputSingle`, `exactOutput`, and `exactOutputSingle`. - - // It should be noted that for the sake of simplicity, we purposefully pass in the swap router instead of inheriting the swap router in these examples. - // More advanced example contracts will detail how to inherit the swap router safely. - - ISwapRouter public immutable swapRouter; - - // This example swaps DAI/WETH9 for single path swaps and DAI/USDC/WETH9 for multipath swaps. - - address public constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; - address public constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; - address public constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; - - // For this example, we will set the pool fee to 0.3%. - uint24 public constant poolFee = 3000; - - constructor(ISwapRouter _swapRouter) { - swapRouter = _swapRouter; - } - - /// @notice swapExactInputSingle swaps a fixed amount of DAI for a maximum possible amount of WETH9 - /// using the DAI/WETH9 0.3% pool by calling `exactInputSingle` in the swap router. - /// @dev The calling address must approve this contract to spend at least `amountIn` worth of its DAI for this function to succeed. - /// @param amountIn The exact amount of DAI that will be swapped for WETH9. - /// @return amountOut The amount of WETH9 received. - function swapExactInputSingle(uint256 amountIn) external returns (uint256 amountOut) { - // msg.sender must approve this contract - - // Transfer the specified amount of DAI to this contract. - TransferHelper.safeTransferFrom(DAI, msg.sender, address(this), amountIn); - - // Approve the router to spend DAI. - TransferHelper.safeApprove(DAI, address(swapRouter), amountIn); - - // Naively set amountOutMinimum to 0. In production, use an oracle or other data source to choose a safer value for amountOutMinimum. - // We also set the sqrtPriceLimitx96 to be 0 to ensure we swap our exact input amount. - ISwapRouter.ExactInputSingleParams memory params = - ISwapRouter.ExactInputSingleParams({ - tokenIn: DAI, - tokenOut: WETH9, - fee: poolFee, - recipient: msg.sender, - deadline: block.timestamp, - amountIn: amountIn, - amountOutMinimum: 0, - sqrtPriceLimitX96: 0 - }); - - // The call to `exactInputSingle` executes the swap. - amountOut = swapRouter.exactInputSingle(params); - } - - /// @notice swapExactOutputSingle swaps a minimum possible amount of DAI for a fixed amount of WETH. - /// @dev The calling address must approve this contract to spend its DAI for this function to succeed. As the amount of input DAI is variable, - /// the calling address will need to approve for a slightly higher amount, anticipating some variance. - /// @param amountOut The exact amount of WETH9 to receive from the swap. - /// @param amountInMaximum The amount of DAI we are willing to spend to receive the specified amount of WETH9. - /// @return amountIn The amount of DAI actually spent in the swap. - function swapExactOutputSingle(uint256 amountOut, uint256 amountInMaximum) external returns (uint256 amountIn) { - // Transfer the specified amount of DAI to this contract. - TransferHelper.safeTransferFrom(DAI, msg.sender, address(this), amountInMaximum); - - // Approve the router to spend the specified `amountInMaximum` of DAI. - // In production, you should choose the maximum amount to spend based on oracles or other data sources to achieve a better swap. - TransferHelper.safeApprove(DAI, address(swapRouter), amountInMaximum); - - ISwapRouter.ExactOutputSingleParams memory params = - ISwapRouter.ExactOutputSingleParams({ - tokenIn: DAI, - tokenOut: WETH9, - fee: poolFee, - recipient: msg.sender, - deadline: block.timestamp, - amountOut: amountOut, - amountInMaximum: amountInMaximum, - sqrtPriceLimitX96: 0 - }); - - // Executes the swap returning the amountIn needed to spend to receive the desired amountOut. - amountIn = swapRouter.exactOutputSingle(params); - - // For exact output swaps, the amountInMaximum may not have all been spent. - // If the actual amount spent (amountIn) is less than the specified maximum amount, we must refund the msg.sender and approve the swapRouter to spend 0. - if (amountIn < amountInMaximum) { - TransferHelper.safeApprove(DAI, address(swapRouter), 0); - TransferHelper.safeTransfer(DAI, msg.sender, amountInMaximum - amountIn); - } - } - - /// @notice swapInputMultiplePools swaps a fixed amount of DAI for a maximum possible amount of WETH9 through an intermediary pool. - /// For this example, we will swap DAI to USDC, then USDC to WETH9 to achieve our desired output. - /// @dev The calling address must approve this contract to spend at least `amountIn` worth of its DAI for this function to succeed. - /// @param amountIn The amount of DAI to be swapped. - /// @return amountOut The amount of WETH9 received after the swap. - function swapExactInputMultihop(uint256 amountIn) external returns (uint256 amountOut) { - // Transfer `amountIn` of DAI to this contract. - TransferHelper.safeTransferFrom(DAI, msg.sender, address(this), amountIn); - - // Approve the router to spend DAI. - TransferHelper.safeApprove(DAI, address(swapRouter), amountIn); - - // Multiple pool swaps are encoded through bytes called a `path`. A path is a sequence of token addresses and poolFees that define the pools used in the swaps. - // The format for pool encoding is (tokenIn, fee, tokenOut/tokenIn, fee, tokenOut) where tokenIn/tokenOut parameter is the shared token across the pools. - // Since we are swapping DAI to USDC and then USDC to WETH9 the path encoding is (DAI, 0.3%, USDC, 0.3%, WETH9). - ISwapRouter.ExactInputParams memory params = - ISwapRouter.ExactInputParams({ - path: abi.encodePacked(DAI, poolFee, USDC, poolFee, WETH9), - recipient: msg.sender, - deadline: block.timestamp, - amountIn: amountIn, - amountOutMinimum: 0 - }); - - // Executes the swap. - amountOut = swapRouter.exactInput(params); - } - - /// @notice swapExactOutputMultihop swaps a minimum possible amount of DAI for a fixed amount of WETH through an intermediary pool. - /// For this example, we want to swap DAI for WETH9 through a USDC pool but we specify the desired amountOut of WETH9. Notice how the path encoding is slightly different for exact output swaps. - /// @dev The calling address must approve this contract to spend its DAI for this function to succeed. As the amount of input DAI is variable, - /// the calling address will need to approve for a slightly higher amount, anticipating some variance. - /// @param amountOut The desired amount of WETH9. - /// @param amountInMaximum The maximum amount of DAI willing to be swapped for the specified amountOut of WETH9. - /// @return amountIn The amountIn of DAI actually spent to receive the desired amountOut. - function swapExactOutputMultihop(uint256 amountOut, uint256 amountInMaximum) external returns (uint256 amountIn) { - // Transfer the specified `amountInMaximum` to this contract. - TransferHelper.safeTransferFrom(DAI, msg.sender, address(this), amountInMaximum); - // Approve the router to spend `amountInMaximum`. - TransferHelper.safeApprove(DAI, address(swapRouter), amountInMaximum); - - // The parameter path is encoded as (tokenOut, fee, tokenIn/tokenOut, fee, tokenIn) - // The tokenIn/tokenOut field is the shared token between the two pools used in the multiple pool swap. In this case, USDC is the "shared" token. - // For an exactOutput swap, the first swap that occurs is the swap that returns the eventually desired token. - // In this case, our desired output token is WETH9 so that swap happens first, and is encoded in the path accordingly. - ISwapRouter.ExactOutputParams memory params = - ISwapRouter.ExactOutputParams({ - path: abi.encodePacked(WETH9, poolFee, USDC, poolFee, DAI), - recipient: msg.sender, - deadline: block.timestamp, - amountOut: amountOut, - amountInMaximum: amountInMaximum - }); - - // Executes the swap, returning the amountIn actually spent. - amountIn = swapRouter.exactOutput(params); - - // If the swap did not require the full amountInMaximum to achieve the exact amountOut then we refund msg.sender and approve the router to spend 0. - if (amountIn < amountInMaximum) { - TransferHelper.safeApprove(DAI, address(swapRouter), 0); - TransferHelper.safeTransferFrom(DAI, address(this), msg.sender, amountInMaximum - amountIn); - } - } -} diff --git a/sidebars.js b/sidebars.js index 3f4d8b9da..d51202570 100644 --- a/sidebars.js +++ b/sidebars.js @@ -1,10 +1,19 @@ /** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ const sidebars = { // By default, Docusaurus generates a sidebar from the docs folder structure - integrationSidebar: [{ type: 'autogenerated', dirName: 'integration' }], conceptsSidebar: [{ type: 'autogenerated', dirName: 'concepts' }], - contractsSidebar: [{ type: 'autogenerated', dirName: 'contracts' }], - sdkSidebar: [{ type: 'autogenerated', dirName: 'sdk' }], + integrationSidebar: [ + { + type: 'category', + label: 'xChainRead', + items: ['integration/xChainRead/overview', 'integration/xChainRead/api-reference'], + }, + { + type: 'category', + label: '7683', + items: ['integration/7683/solver-integration', 'integration/7683/frontend-integration'], + }, + ], } module.exports = sidebars diff --git a/src/pages/index.tsx b/src/pages/index.tsx index 15a1511e6..1c54d0404 100644 --- a/src/pages/index.tsx +++ b/src/pages/index.tsx @@ -62,7 +62,7 @@ export const dAppGuides = [ ] export const smartContractGuides = [ { - title: 'Cross Chain Intents', + title: 'Cross-chain Reads', text: 'Read data from other chains and prove the results back to your contract. This primitive is useful in ERC7683 enabled cross-chain intents and swaps.', to: '/integration/xChainRead/overview', },